1 /* Copyright (c) 2002, 2015, Oracle and/or its affiliates.
2    Copyright (c) 2008, 2021, MariaDB
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; version 2 of the License.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software
15    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1335  USA */
16 
17 /**
18   @file
19 
20 This file contains the implementation of prepared statements.
21 
22 When one prepares a statement:
23 
24   - Server gets the query from client with command 'COM_STMT_PREPARE';
25     in the following format:
26     [COM_STMT_PREPARE:1] [query]
27   - Parse the query and recognize any parameter markers '?' and
28     store its information list in lex->param_list
29   - Allocate a new statement for this prepare; and keep this in
30     'thd->stmt_map'.
31   - Without executing the query, return back to client the total
32     number of parameters along with result-set metadata information
33     (if any) in the following format:
34     @verbatim
35     [STMT_ID:4]
36     [Column_count:2]
37     [Param_count:2]
38     [Params meta info (stubs only for now)]  (if Param_count > 0)
39     [Columns meta info] (if Column_count > 0)
40     @endverbatim
41 
42   During prepare the tables used in a statement are opened, but no
43   locks are acquired.  Table opening will block any DDL during the
44   operation, and we do not need any locks as we neither read nor
45   modify any data during prepare.  Tables are closed after prepare
46   finishes.
47 
48 When one executes a statement:
49 
50   - Server gets the command 'COM_STMT_EXECUTE' to execute the
51     previously prepared query. If there are any parameter markers, then the
52     client will send the data in the following format:
53     @verbatim
54     [COM_STMT_EXECUTE:1]
55     [STMT_ID:4]
56     [NULL_BITS:(param_count+7)/8)]
57     [TYPES_SUPPLIED_BY_CLIENT(0/1):1]
58     [[length]data]
59     [[length]data] .. [[length]data].
60     @endverbatim
61     (Note: Except for string/binary types; all other types will not be
62     supplied with length field)
63   - If it is a first execute or types of parameters were altered by client,
64     then setup the conversion routines.
65   - Assign parameter items from the supplied data.
66   - Execute the query without re-parsing and send back the results
67     to client
68 
69   During execution of prepared statement tables are opened and locked
70   the same way they would for normal (non-prepared) statement
71   execution.  Tables are unlocked and closed after the execution.
72 
73 When one supplies long data for a placeholder:
74 
75   - Server gets the long data in pieces with command type
76     'COM_STMT_SEND_LONG_DATA'.
77   - The packet received will have the format as:
78     [COM_STMT_SEND_LONG_DATA:1][STMT_ID:4][parameter_number:2][data]
79   - data from the packet is appended to the long data value buffer for this
80     placeholder.
81   - It's up to the client to stop supplying data chunks at any point. The
82     server doesn't care; also, the server doesn't notify the client whether
83     it got the data or not; if there is any error, then it will be returned
84     at statement execute.
85 */
86 
87 #include "mariadb.h"                          /* NO_EMBEDDED_ACCESS_CHECKS */
88 #include "sql_priv.h"
89 #include "unireg.h"
90 #include "sql_class.h"                          // set_var.h: THD
91 #include "set_var.h"
92 #include "sql_prepare.h"
93 #include "sql_parse.h" // insert_precheck, update_precheck, delete_precheck
94 #include "sql_base.h"  // open_normal_and_derived_tables
95 #include "sql_cache.h"                          // query_cache_*
96 #include "sql_view.h"                          // create_view_precheck
97 #include "sql_delete.h"                        // mysql_prepare_delete
98 #include "sql_select.h" // for JOIN
99 #include "sql_insert.h" // upgrade_lock_type_for_insert, mysql_prepare_insert
100 #include "sql_update.h" // mysql_prepare_update
101 #include "sql_db.h"     // mysql_opt_change_db, mysql_change_db
102 #include "sql_acl.h"    // *_ACL
103 #include "sql_derived.h" // mysql_derived_prepare,
104                          // mysql_handle_derived
105 #include "sql_cte.h"
106 #include "sql_cursor.h"
107 #include "sql_show.h"
108 #include "sql_repl.h"
109 #include "slave.h"
110 #include "sp_head.h"
111 #include "sp.h"
112 #include "sp_cache.h"
113 #include "sql_handler.h"  // mysql_ha_rm_tables
114 #include "probes_mysql.h"
115 #ifdef EMBEDDED_LIBRARY
116 /* include MYSQL_BIND headers */
117 #include <mysql.h>
118 #else
119 #include <mysql_com.h>
120 /* Constants defining bits in parameter type flags. Flags are read from high byte of short value */
121 static const uint PARAMETER_FLAG_UNSIGNED= 128U << 8;
122 #endif
123 #include "lock.h"                               // MYSQL_OPEN_FORCE_SHARED_MDL
124 #include "log_event.h"                          // class Log_event
125 #include "sql_handler.h"
126 #include "transaction.h"                        // trans_rollback_implicit
127 #include "wsrep_mysqld.h"
128 
129 /**
130   A result class used to send cursor rows using the binary protocol.
131 */
132 
133 class Select_fetch_protocol_binary: public select_send
134 {
135   Protocol_binary protocol;
136 public:
137   Select_fetch_protocol_binary(THD *thd);
138   virtual bool send_result_set_metadata(List<Item> &list, uint flags);
139   virtual int send_data(List<Item> &items);
140   virtual bool send_eof();
141 #ifdef EMBEDDED_LIBRARY
142   void begin_dataset()
143   {
144     protocol.begin_dataset();
145   }
146 #endif
147 };
148 
149 /****************************************************************************/
150 
151 /**
152   Prepared_statement: a statement that can contain placeholders.
153 */
154 
155 class Prepared_statement: public Statement
156 {
157 public:
158   enum flag_values
159   {
160     IS_IN_USE= 1,
161     IS_SQL_PREPARE= 2
162   };
163 
164   THD *thd;
165   Select_fetch_protocol_binary result;
166   Item_param **param_array;
167   Server_side_cursor *cursor;
168   uchar *packet;
169   uchar *packet_end;
170   uint param_count;
171   uint last_errno;
172   uint flags;
173   char last_error[MYSQL_ERRMSG_SIZE];
174   my_bool iterations;
175   my_bool start_param;
176   my_bool read_types;
177 #ifndef EMBEDDED_LIBRARY
178   bool (*set_params)(Prepared_statement *st, uchar *data, uchar *data_end,
179                      uchar *read_pos, String *expanded_query);
180   bool (*set_bulk_params)(Prepared_statement *st,
181                           uchar **read_pos, uchar *data_end, bool reset);
182 #else
183   bool (*set_params_data)(Prepared_statement *st, String *expanded_query);
184   /*TODO: add bulk support for builtin server */
185 #endif
186   bool (*set_params_from_actual_params)(Prepared_statement *stmt,
187                                         List<Item> &list,
188                                         String *expanded_query);
189 public:
190   Prepared_statement(THD *thd_arg);
191   virtual ~Prepared_statement();
192   void setup_set_params();
193   virtual Query_arena::Type type() const;
194   virtual void cleanup_stmt();
195   bool set_name(LEX_CSTRING *name);
196   inline void close_cursor() { delete cursor; cursor= 0; }
197   inline bool is_in_use() { return flags & (uint) IS_IN_USE; }
198   inline bool is_sql_prepare() const { return flags & (uint) IS_SQL_PREPARE; }
199   void set_sql_prepare() { flags|= (uint) IS_SQL_PREPARE; }
200   bool prepare(const char *packet, uint packet_length);
201   bool execute_loop(String *expanded_query,
202                     bool open_cursor,
203                     uchar *packet_arg, uchar *packet_end_arg);
204   bool execute_bulk_loop(String *expanded_query,
205                          bool open_cursor,
206                          uchar *packet_arg, uchar *packet_end_arg);
207   bool execute_server_runnable(Server_runnable *server_runnable);
208   my_bool set_bulk_parameters(bool reset);
209   bool bulk_iterations() { return iterations; };
210   /* Destroy this statement */
211   void deallocate();
212   bool execute_immediate(const char *query, uint query_length);
213 private:
214   /**
215     The memory root to allocate parsed tree elements (instances of Item,
216     SELECT_LEX and other classes).
217   */
218   MEM_ROOT main_mem_root;
219   sql_mode_t m_sql_mode;
220 private:
221   bool set_db(const LEX_CSTRING *db);
222   bool set_parameters(String *expanded_query,
223                       uchar *packet, uchar *packet_end);
224   bool execute(String *expanded_query, bool open_cursor);
225   void deallocate_immediate();
226   bool reprepare();
227   bool validate_metadata(Prepared_statement  *copy);
228   void swap_prepared_statement(Prepared_statement *copy);
229 };
230 
231 /**
232   Execute one SQL statement in an isolated context.
233 */
234 
235 class Execute_sql_statement: public Server_runnable
236 {
237 public:
238   Execute_sql_statement(LEX_STRING sql_text);
239   virtual bool execute_server_code(THD *thd);
240 private:
241   LEX_STRING m_sql_text;
242 };
243 
244 
245 class Ed_connection;
246 
247 /**
248   Protocol_local: a helper class to intercept the result
249   of the data written to the network.
250 */
251 
252 class Protocol_local :public Protocol
253 {
254 public:
255   Protocol_local(THD *thd, Ed_connection *ed_connection);
256   ~Protocol_local() { free_root(&m_rset_root, MYF(0)); }
257 protected:
258   virtual void prepare_for_resend();
259   virtual bool write();
260   virtual bool store_null();
261   virtual bool store_tiny(longlong from);
262   virtual bool store_short(longlong from);
263   virtual bool store_long(longlong from);
264   virtual bool store_longlong(longlong from, bool unsigned_flag);
265   virtual bool store_decimal(const my_decimal *);
266   virtual bool store(const char *from, size_t length, CHARSET_INFO *cs);
267   virtual bool store(const char *from, size_t length,
268                      CHARSET_INFO *fromcs, CHARSET_INFO *tocs);
269   virtual bool store(MYSQL_TIME *time, int decimals);
270   virtual bool store_date(MYSQL_TIME *time);
271   virtual bool store_time(MYSQL_TIME *time, int decimals);
272   virtual bool store(float value, uint32 decimals, String *buffer);
273   virtual bool store(double value, uint32 decimals, String *buffer);
274   virtual bool store(Field *field);
275 
276   virtual bool send_result_set_metadata(List<Item> *list, uint flags);
277   virtual bool send_out_parameters(List<Item_param> *sp_params);
278 #ifdef EMBEDDED_LIBRARY
279   void remove_last_row();
280 #endif
281   virtual enum enum_protocol_type type() { return PROTOCOL_LOCAL; };
282 
283   virtual bool send_ok(uint server_status, uint statement_warn_count,
284                        ulonglong affected_rows, ulonglong last_insert_id,
285                        const char *message, bool skip_flush);
286 
287   virtual bool send_eof(uint server_status, uint statement_warn_count);
288   virtual bool send_error(uint sql_errno, const char *err_msg, const char* sqlstate);
289 private:
290   bool store_string(const char *str, size_t length,
291                     CHARSET_INFO *src_cs, CHARSET_INFO *dst_cs);
292 
293   bool store_column(const void *data, size_t length);
294   void opt_add_row_to_rset();
295 private:
296   Ed_connection *m_connection;
297   MEM_ROOT m_rset_root;
298   List<Ed_row> *m_rset;
299   size_t m_column_count;
300   Ed_column *m_current_row;
301   Ed_column *m_current_column;
302 };
303 
304 /******************************************************************************
305   Implementation
306 ******************************************************************************/
307 
308 
309 inline bool is_param_null(const uchar *pos, ulong param_no)
310 {
311   return pos[param_no/8] & (1 << (param_no & 7));
312 }
313 
314 /**
315   Find a prepared statement in the statement map by id.
316 
317     Try to find a prepared statement and set THD error if it's not found.
318 
319   @param thd                thread handle
320   @param id                 statement id
321   @param where              the place from which this function is called (for
322                             error reporting).
323 
324   @return
325     0 if the statement was not found, a pointer otherwise.
326 */
327 
328 static Prepared_statement *
329 find_prepared_statement(THD *thd, ulong id)
330 {
331   /*
332     To strictly separate namespaces of SQL prepared statements and C API
333     prepared statements find() will return 0 if there is a named prepared
334     statement with such id.
335 
336     LAST_STMT_ID is special value which mean last prepared statement ID
337     (it was made for COM_MULTI to allow prepare and execute a statement
338     in the same command but usage is not limited by COM_MULTI only).
339   */
340   Statement *stmt= ((id == LAST_STMT_ID) ?
341                     thd->last_stmt :
342                     thd->stmt_map.find(id));
343 
344   if (stmt == 0 || stmt->type() != Query_arena::PREPARED_STATEMENT)
345     return NULL;
346 
347   return (Prepared_statement *) stmt;
348 }
349 
350 
351 /**
352   Send prepared statement id and metadata to the client after prepare.
353 
354   @todo
355     Fix this nasty upcast from List<Item_param> to List<Item>
356 
357   @return
358     0 in case of success, 1 otherwise
359 */
360 
361 #ifndef EMBEDDED_LIBRARY
362 static bool send_prep_stmt(Prepared_statement *stmt, uint columns)
363 {
364   NET *net= &stmt->thd->net;
365   uchar buff[12];
366   uint tmp;
367   int error;
368   THD *thd= stmt->thd;
369   DBUG_ENTER("send_prep_stmt");
370   DBUG_PRINT("enter",("stmt->id: %lu  columns: %d  param_count: %d",
371                       stmt->id, columns, stmt->param_count));
372 
373   buff[0]= 0;                                   /* OK packet indicator */
374   int4store(buff+1, stmt->id);
375   int2store(buff+5, columns);
376   int2store(buff+7, stmt->param_count);
377   buff[9]= 0;                                   // Guard against a 4.1 client
378   tmp= MY_MIN(stmt->thd->get_stmt_da()->current_statement_warn_count(), 65535);
379   int2store(buff+10, tmp);
380 
381   /*
382     Send types and names of placeholders to the client
383     XXX: fix this nasty upcast from List<Item_param> to List<Item>
384   */
385   error= my_net_write(net, buff, sizeof(buff));
386   if (stmt->param_count && likely(!error))
387   {
388     error= thd->protocol_text.send_result_set_metadata((List<Item> *)
389                                           &stmt->lex->param_list,
390                                           Protocol::SEND_EOF);
391   }
392 
393   if (likely(!error))
394   {
395     /* Flag that a response has already been sent */
396     thd->get_stmt_da()->disable_status();
397   }
398 
399   DBUG_RETURN(error);
400 }
401 #else
402 static bool send_prep_stmt(Prepared_statement *stmt,
403                            uint columns __attribute__((unused)))
404 {
405   THD *thd= stmt->thd;
406 
407   thd->client_stmt_id= stmt->id;
408   thd->client_param_count= stmt->param_count;
409   thd->clear_error();
410   thd->get_stmt_da()->disable_status();
411 
412   return 0;
413 }
414 #endif /*!EMBEDDED_LIBRARY*/
415 
416 
417 #ifndef EMBEDDED_LIBRARY
418 
419 /**
420   Read the length of the parameter data and return it back to
421   the caller.
422 
423     Read data length, position the packet to the first byte after it,
424     and return the length to the caller.
425 
426   @param packet             a pointer to the data
427   @param len                remaining packet length
428 
429   @return
430     Length of data piece.
431 */
432 
433 static ulong get_param_length(uchar **packet, ulong len)
434 {
435   uchar *pos= *packet;
436   if (len < 1)
437     return 0;
438   if (*pos < 251)
439   {
440     (*packet)++;
441     return (ulong) *pos;
442   }
443   if (len < 3)
444     return 0;
445   if (*pos == 252)
446   {
447     (*packet)+=3;
448     return (ulong) uint2korr(pos+1);
449   }
450   if (len < 4)
451     return 0;
452   if (*pos == 253)
453   {
454     (*packet)+=4;
455     return (ulong) uint3korr(pos+1);
456   }
457   if (len < 5)
458     return 0;
459   (*packet)+=9; // Must be 254 when here
460   /*
461     In our client-server protocol all numbers bigger than 2^24
462     stored as 8 bytes with uint8korr. Here we always know that
463     parameter length is less than 2^4 so don't look at the second
464     4 bytes. But still we need to obey the protocol hence 9 in the
465     assignment above.
466   */
467   return (ulong) uint4korr(pos+1);
468 }
469 #else
470 #define get_param_length(packet, len) len
471 #endif /*!EMBEDDED_LIBRARY*/
472 
473 /**
474   Data conversion routines.
475 
476     All these functions read the data from pos, convert it to requested
477     type and assign to param; pos is advanced to predefined length.
478 
479     Make a note that the NULL handling is examined at first execution
480     (i.e. when input types altered) and for all subsequent executions
481     we don't read any values for this.
482 
483   @param  pos               input data buffer
484   @param  len               length of data in the buffer
485 */
486 
487 void Item_param::set_param_tiny(uchar **pos, ulong len)
488 {
489 #ifndef EMBEDDED_LIBRARY
490   if (len < 1)
491     return;
492 #endif
493   int8 value= (int8) **pos;
494   set_int(unsigned_flag ? (longlong) ((uint8) value) :
495                           (longlong) value, 4);
496   *pos+= 1;
497 }
498 
499 void Item_param::set_param_short(uchar **pos, ulong len)
500 {
501   int16 value;
502 #ifndef EMBEDDED_LIBRARY
503   if (len < 2)
504     return;
505   value= sint2korr(*pos);
506 #else
507   shortget(value, *pos);
508 #endif
509   set_int(unsigned_flag ? (longlong) ((uint16) value) :
510                           (longlong) value, 6);
511   *pos+= 2;
512 }
513 
514 void Item_param::set_param_int32(uchar **pos, ulong len)
515 {
516   int32 value;
517 #ifndef EMBEDDED_LIBRARY
518   if (len < 4)
519     return;
520   value= sint4korr(*pos);
521 #else
522   longget(value, *pos);
523 #endif
524   set_int(unsigned_flag ? (longlong) ((uint32) value) :
525                           (longlong) value, 11);
526   *pos+= 4;
527 }
528 
529 void Item_param::set_param_int64(uchar **pos, ulong len)
530 {
531   longlong value;
532 #ifndef EMBEDDED_LIBRARY
533   if (len < 8)
534     return;
535   value= (longlong) sint8korr(*pos);
536 #else
537   longlongget(value, *pos);
538 #endif
539   set_int(value, 21);
540   *pos+= 8;
541 }
542 
543 void Item_param::set_param_float(uchar **pos, ulong len)
544 {
545   float data;
546 #ifndef EMBEDDED_LIBRARY
547   if (len < 4)
548     return;
549   float4get(data,*pos);
550 #else
551   floatget(data, *pos);
552 #endif
553   set_double((double) data);
554   *pos+= 4;
555 }
556 
557 void Item_param::set_param_double(uchar **pos, ulong len)
558 {
559   double data;
560 #ifndef EMBEDDED_LIBRARY
561   if (len < 8)
562     return;
563   float8get(data,*pos);
564 #else
565   doubleget(data, *pos);
566 #endif
567   set_double((double) data);
568   *pos+= 8;
569 }
570 
571 void Item_param::set_param_decimal(uchar **pos, ulong len)
572 {
573   ulong length= get_param_length(pos, len);
574   set_decimal((char*)*pos, length);
575   *pos+= length;
576 }
577 
578 #ifndef EMBEDDED_LIBRARY
579 
580 /*
581   Read date/time/datetime parameter values from network (binary
582   protocol). See writing counterparts of these functions in
583   libmysql.c (store_param_{time,date,datetime}).
584 */
585 
586 /**
587   @todo
588     Add warning 'Data truncated' here
589 */
590 void Item_param::set_param_time(uchar **pos, ulong len)
591 {
592   MYSQL_TIME tm;
593   ulong length= get_param_length(pos, len);
594 
595   if (length >= 8)
596   {
597     uchar *to= *pos;
598     uint day;
599 
600     tm.neg= (bool) to[0];
601     day= (uint) sint4korr(to+1);
602     tm.hour=   (uint) to[5] + day * 24;
603     tm.minute= (uint) to[6];
604     tm.second= (uint) to[7];
605     tm.second_part= (length > 8) ? (ulong) sint4korr(to+8) : 0;
606     if (tm.hour > 838)
607     {
608       /* TODO: add warning 'Data truncated' here */
609       tm.hour= 838;
610       tm.minute= 59;
611       tm.second= 59;
612     }
613     tm.day= tm.year= tm.month= 0;
614   }
615   else
616     set_zero_time(&tm, MYSQL_TIMESTAMP_TIME);
617   set_time(&tm, MYSQL_TIMESTAMP_TIME, MAX_TIME_FULL_WIDTH);
618   *pos+= length;
619 }
620 
621 void Item_param::set_param_datetime(uchar **pos, ulong len)
622 {
623   MYSQL_TIME tm;
624   ulong length= get_param_length(pos, len);
625 
626   if (length >= 4)
627   {
628     uchar *to= *pos;
629 
630     tm.neg=    0;
631     tm.year=   (uint) sint2korr(to);
632     tm.month=  (uint) to[2];
633     tm.day=    (uint) to[3];
634     if (length > 4)
635     {
636       tm.hour=   (uint) to[4];
637       tm.minute= (uint) to[5];
638       tm.second= (uint) to[6];
639     }
640     else
641       tm.hour= tm.minute= tm.second= 0;
642 
643     tm.second_part= (length > 7) ? (ulong) sint4korr(to+7) : 0;
644   }
645   else
646     set_zero_time(&tm, MYSQL_TIMESTAMP_DATETIME);
647   set_time(&tm, MYSQL_TIMESTAMP_DATETIME, MAX_DATETIME_WIDTH);
648   *pos+= length;
649 }
650 
651 
652 void Item_param::set_param_date(uchar **pos, ulong len)
653 {
654   MYSQL_TIME tm;
655   ulong length= get_param_length(pos, len);
656 
657   if (length >= 4)
658   {
659     uchar *to= *pos;
660 
661     tm.year=  (uint) sint2korr(to);
662     tm.month=  (uint) to[2];
663     tm.day= (uint) to[3];
664 
665     tm.hour= tm.minute= tm.second= 0;
666     tm.second_part= 0;
667     tm.neg= 0;
668   }
669   else
670     set_zero_time(&tm, MYSQL_TIMESTAMP_DATE);
671   set_time(&tm, MYSQL_TIMESTAMP_DATE, MAX_DATE_WIDTH);
672   *pos+= length;
673 }
674 
675 #else/*!EMBEDDED_LIBRARY*/
676 /**
677   @todo
678     Add warning 'Data truncated' here
679 */
680 void Item_param::set_param_time(uchar **pos, ulong len)
681 {
682   MYSQL_TIME tm= *((MYSQL_TIME*)*pos);
683   tm.hour+= tm.day * 24;
684   tm.day= tm.year= tm.month= 0;
685   if (tm.hour > 838)
686   {
687     /* TODO: add warning 'Data truncated' here */
688     tm.hour= 838;
689     tm.minute= 59;
690     tm.second= 59;
691   }
692   set_time(&tm, MYSQL_TIMESTAMP_TIME, MAX_TIME_WIDTH);
693 }
694 
695 void Item_param::set_param_datetime(uchar **pos, ulong len)
696 {
697   MYSQL_TIME tm= *((MYSQL_TIME*)*pos);
698   tm.neg= 0;
699   set_time(&tm, MYSQL_TIMESTAMP_DATETIME, MAX_DATETIME_WIDTH);
700 }
701 
702 void Item_param::set_param_date(uchar **pos, ulong len)
703 {
704   MYSQL_TIME *to= (MYSQL_TIME*)*pos;
705   set_time(to, MYSQL_TIMESTAMP_DATE, MAX_DATE_WIDTH);
706 }
707 #endif /*!EMBEDDED_LIBRARY*/
708 
709 
710 void Item_param::set_param_str(uchar **pos, ulong len)
711 {
712   ulong length= get_param_length(pos, len);
713   if (length == 0 && m_empty_string_is_null)
714     set_null();
715   else
716   {
717     if (length > len)
718       length= len;
719     /*
720       We use &my_charset_bin here. Conversion and setting real character
721       sets will be done in Item_param::convert_str_value(), after the
722       original value is appended to the query used for logging.
723     */
724     set_str((const char *) *pos, length, &my_charset_bin, &my_charset_bin);
725     *pos+= length;
726   }
727 }
728 
729 
730 #undef get_param_length
731 
732 
733 void Item_param::setup_conversion(THD *thd, uchar param_type)
734 {
735   const Type_handler *h=
736     Type_handler::get_handler_by_field_type((enum_field_types) param_type);
737   /*
738     The client library ensures that we won't get any unexpected typecodes
739     in the bound parameter. Translating unknown typecodes to
740     &type_handler_string lets us to handle malformed packets as well.
741   */
742   if (!h)
743     h= &type_handler_string;
744   set_handler(h);
745   h->Item_param_setup_conversion(thd, this);
746 }
747 
748 
749 void Item_param::setup_conversion_blob(THD *thd)
750 {
751   value.cs_info.character_set_of_placeholder= &my_charset_bin;
752   value.cs_info.character_set_client= thd->variables.character_set_client;
753   DBUG_ASSERT(thd->variables.character_set_client);
754   value.cs_info.final_character_set_of_str_value= &my_charset_bin;
755   m_empty_string_is_null= thd->variables.sql_mode & MODE_EMPTY_STRING_IS_NULL;
756 }
757 
758 
759 void Item_param::setup_conversion_string(THD *thd, CHARSET_INFO *fromcs)
760 {
761   value.cs_info.set(thd, fromcs);
762   m_empty_string_is_null= thd->variables.sql_mode & MODE_EMPTY_STRING_IS_NULL;
763   /*
764     Exact value of max_length is not known unless data is converted to
765     charset of connection, so we have to set it later.
766   */
767 }
768 
769 #ifndef EMBEDDED_LIBRARY
770 
771 /**
772   Routines to assign parameters from data supplied by the client.
773 
774     Update the parameter markers by reading data from the packet and
775     and generate a valid query for logging.
776 
777   @note
778     This function, along with other _with_log functions is called when one of
779     binary, slow or general logs is open. Logging of prepared statements in
780     all cases is performed by means of conventional queries: if parameter
781     data was supplied from C API, each placeholder in the query is
782     replaced with its actual value; if we're logging a [Dynamic] SQL
783     prepared statement, parameter markers are replaced with variable names.
784     Example:
785     @verbatim
786      mysqld_stmt_prepare("UPDATE t1 SET a=a*1.25 WHERE a=?")
787        --> general logs gets [Prepare] UPDATE t1 SET a*1.25 WHERE a=?"
788      mysqld_stmt_execute(stmt);
789        --> general and binary logs get
790                              [Execute] UPDATE t1 SET a*1.25 WHERE a=1"
791     @endverbatim
792 
793     If a statement has been prepared using SQL syntax:
794     @verbatim
795      PREPARE stmt FROM "UPDATE t1 SET a=a*1.25 WHERE a=?"
796        --> general log gets
797                                  [Query]   PREPARE stmt FROM "UPDATE ..."
798      EXECUTE stmt USING @a
799        --> general log gets
800                              [Query]   EXECUTE stmt USING @a;
801     @endverbatim
802 
803   @retval
804     0  if success
805   @retval
806     1  otherwise
807 */
808 
809 static bool insert_params_with_log(Prepared_statement *stmt, uchar *null_array,
810                                    uchar *read_pos, uchar *data_end,
811                                    String *query)
812 {
813   THD  *thd= stmt->thd;
814   Item_param **begin= stmt->param_array;
815   Item_param **end= begin + stmt->param_count;
816   Copy_query_with_rewrite acc(thd, stmt->query(), stmt->query_length(), query);
817   DBUG_ENTER("insert_params_with_log");
818 
819   for (Item_param **it= begin; it < end; ++it)
820   {
821     Item_param *param= *it;
822     if (!param->has_long_data_value())
823     {
824       if (is_param_null(null_array, (uint) (it - begin)))
825         param->set_null();
826       else
827       {
828         if (read_pos >= data_end)
829           DBUG_RETURN(1);
830         param->set_param_func(&read_pos, (uint) (data_end - read_pos));
831         if (param->has_no_value())
832           DBUG_RETURN(1);
833 
834         if (param->limit_clause_param && !param->has_int_value())
835         {
836           if (param->set_limit_clause_param(param->val_int()))
837             DBUG_RETURN(1);
838         }
839       }
840     }
841     /*
842       A long data stream was supplied for this parameter marker.
843       This was done after prepare, prior to providing a placeholder
844       type (the types are supplied at execute). Check that the
845       supplied type of placeholder can accept a data stream.
846     */
847     else if (!param->type_handler()->is_param_long_data_type())
848       DBUG_RETURN(1);
849 
850     if (acc.append(param))
851       DBUG_RETURN(1);
852 
853     if (param->convert_str_value(thd))
854       DBUG_RETURN(1);                           /* out of memory */
855 
856     param->sync_clones();
857   }
858   if (acc.finalize())
859     DBUG_RETURN(1);
860 
861   DBUG_RETURN(0);
862 }
863 
864 
865 static bool insert_params(Prepared_statement *stmt, uchar *null_array,
866                           uchar *read_pos, uchar *data_end,
867                           String *expanded_query)
868 {
869   Item_param **begin= stmt->param_array;
870   Item_param **end= begin + stmt->param_count;
871 
872   DBUG_ENTER("insert_params");
873 
874   for (Item_param **it= begin; it < end; ++it)
875   {
876     Item_param *param= *it;
877     param->indicator= STMT_INDICATOR_NONE; // only for bulk parameters
878     if (!param->has_long_data_value())
879     {
880       if (is_param_null(null_array, (uint) (it - begin)))
881         param->set_null();
882       else
883       {
884         if (read_pos >= data_end)
885           DBUG_RETURN(1);
886         param->set_param_func(&read_pos, (uint) (data_end - read_pos));
887         if (param->has_no_value())
888           DBUG_RETURN(1);
889       }
890     }
891     /*
892       A long data stream was supplied for this parameter marker.
893       This was done after prepare, prior to providing a placeholder
894       type (the types are supplied at execute). Check that the
895       supplied type of placeholder can accept a data stream.
896     */
897     else if (!param->type_handler()->is_param_long_data_type())
898       DBUG_RETURN(1);
899     if (param->convert_str_value(stmt->thd))
900       DBUG_RETURN(1);                           /* out of memory */
901     param->sync_clones();
902   }
903   DBUG_RETURN(0);
904 }
905 
906 
907 static bool insert_bulk_params(Prepared_statement *stmt,
908                                uchar **read_pos, uchar *data_end,
909                                bool reset)
910 {
911   Item_param **begin= stmt->param_array;
912   Item_param **end= begin + stmt->param_count;
913 
914   DBUG_ENTER("insert_params");
915 
916   for (Item_param **it= begin; it < end; ++it)
917   {
918     Item_param *param= *it;
919     if (reset)
920       param->reset();
921     if (!param->has_long_data_value())
922     {
923       param->indicator= (enum_indicator_type) *((*read_pos)++);
924       if ((*read_pos) > data_end)
925         DBUG_RETURN(1);
926       switch (param->indicator)
927       {
928       case STMT_INDICATOR_NONE:
929         if ((*read_pos) >= data_end)
930           DBUG_RETURN(1);
931         param->set_param_func(read_pos, (uint) (data_end - (*read_pos)));
932         if (param->has_no_value())
933           DBUG_RETURN(1);
934         if (param->convert_str_value(stmt->thd))
935           DBUG_RETURN(1);                           /* out of memory */
936         break;
937       case STMT_INDICATOR_NULL:
938         param->set_null();
939         break;
940       case STMT_INDICATOR_DEFAULT:
941         param->set_default();
942         break;
943       case STMT_INDICATOR_IGNORE:
944         param->set_ignore();
945         break;
946       }
947     }
948     else
949       DBUG_RETURN(1); // long is not supported here
950     param->sync_clones();
951   }
952   DBUG_RETURN(0);
953 }
954 
955 
956 /**
957   Checking if parameter type and flags are valid
958 
959   @param typecode  ushort value with type in low byte, and flags in high byte
960 
961   @retval true  this parameter is wrong
962   @retval false this parameter is OK
963 */
964 
965 static bool
966 parameter_type_sanity_check(ushort typecode)
967 {
968   /* Checking if type in lower byte is valid */
969   switch (typecode & 0xff) {
970   case MYSQL_TYPE_DECIMAL:
971   case MYSQL_TYPE_NEWDECIMAL:
972   case MYSQL_TYPE_TINY:
973   case MYSQL_TYPE_SHORT:
974   case MYSQL_TYPE_LONG:
975   case MYSQL_TYPE_LONGLONG:
976   case MYSQL_TYPE_INT24:
977   case MYSQL_TYPE_YEAR:
978   case MYSQL_TYPE_BIT:
979   case MYSQL_TYPE_FLOAT:
980   case MYSQL_TYPE_DOUBLE:
981   case MYSQL_TYPE_NULL:
982   case MYSQL_TYPE_VARCHAR:
983   case MYSQL_TYPE_TINY_BLOB:
984   case MYSQL_TYPE_MEDIUM_BLOB:
985   case MYSQL_TYPE_LONG_BLOB:
986   case MYSQL_TYPE_BLOB:
987   case MYSQL_TYPE_VAR_STRING:
988   case MYSQL_TYPE_STRING:
989   case MYSQL_TYPE_ENUM:
990   case MYSQL_TYPE_SET:
991   case MYSQL_TYPE_GEOMETRY:
992   case MYSQL_TYPE_TIMESTAMP:
993   case MYSQL_TYPE_DATE:
994   case MYSQL_TYPE_TIME:
995   case MYSQL_TYPE_DATETIME:
996   case MYSQL_TYPE_NEWDATE:
997   break;
998   /*
999     This types normally cannot be sent by client, so maybe it'd be
1000     better to treat them like an error here.
1001   */
1002   case MYSQL_TYPE_TIMESTAMP2:
1003   case MYSQL_TYPE_TIME2:
1004   case MYSQL_TYPE_DATETIME2:
1005   default:
1006     return true;
1007   };
1008 
1009   // In Flags in high byte only unsigned bit may be set
1010   if (typecode & ((~PARAMETER_FLAG_UNSIGNED) & 0x0000ff00))
1011   {
1012     return true;
1013   }
1014   return false;
1015 }
1016 
1017 static bool
1018 set_conversion_functions(Prepared_statement *stmt, uchar **data)
1019 {
1020   uchar *read_pos= *data;
1021 
1022   DBUG_ENTER("set_conversion_functions");
1023   /*
1024      First execute or types altered by the client, setup the
1025      conversion routines for all parameters (one time)
1026    */
1027   Item_param **it= stmt->param_array;
1028   Item_param **end= it + stmt->param_count;
1029   THD *thd= stmt->thd;
1030   for (; it < end; ++it)
1031   {
1032     ushort typecode;
1033 
1034     /*
1035       stmt_execute_packet_sanity_check has already verified, that there
1036       are enough data in the packet for data types
1037     */
1038     typecode= sint2korr(read_pos);
1039     read_pos+= 2;
1040     if (parameter_type_sanity_check(typecode))
1041     {
1042       DBUG_RETURN(1);
1043     }
1044     (**it).unsigned_flag= MY_TEST(typecode & PARAMETER_FLAG_UNSIGNED);
1045     (*it)->setup_conversion(thd, (uchar) (typecode & 0xff));
1046     (*it)->sync_clones();
1047   }
1048   *data= read_pos;
1049   DBUG_RETURN(0);
1050 }
1051 
1052 
1053 static bool setup_conversion_functions(Prepared_statement *stmt,
1054                                        uchar **data,
1055                                        bool bulk_protocol= 0)
1056 {
1057   /* skip null bits */
1058   uchar *read_pos= *data;
1059   if (!bulk_protocol)
1060     read_pos+= (stmt->param_count+7) / 8;
1061 
1062   DBUG_ENTER("setup_conversion_functions");
1063 
1064   if (*read_pos++) //types supplied / first execute
1065   {
1066     *data= read_pos;
1067     bool res= set_conversion_functions(stmt, data);
1068     DBUG_RETURN(res);
1069   }
1070   *data= read_pos;
1071   DBUG_RETURN(0);
1072 }
1073 
1074 #else
1075 
1076 //TODO: support bulk parameters
1077 
1078 /**
1079   Embedded counterparts of parameter assignment routines.
1080 
1081     The main difference between the embedded library and the server is
1082     that in embedded case we don't serialize/deserialize parameters data.
1083 
1084     Additionally, for unknown reason, the client-side flag raised for
1085     changed types of placeholders is ignored and we simply setup conversion
1086     functions at each execute (TODO: fix).
1087 */
1088 
1089 static bool emb_insert_params(Prepared_statement *stmt, String *expanded_query)
1090 {
1091   THD *thd= stmt->thd;
1092   Item_param **it= stmt->param_array;
1093   Item_param **end= it + stmt->param_count;
1094   MYSQL_BIND *client_param= stmt->thd->client_params;
1095 
1096   DBUG_ENTER("emb_insert_params");
1097 
1098   for (; it < end; ++it, ++client_param)
1099   {
1100     Item_param *param= *it;
1101     param->setup_conversion(thd, client_param->buffer_type);
1102     if (!param->has_long_data_value())
1103     {
1104       if (*client_param->is_null)
1105         param->set_null();
1106       else
1107       {
1108         uchar *buff= (uchar*) client_param->buffer;
1109         param->unsigned_flag= client_param->is_unsigned;
1110         param->set_param_func(&buff,
1111                               client_param->length ?
1112                               *client_param->length :
1113                               client_param->buffer_length);
1114         if (param->has_no_value())
1115           DBUG_RETURN(1);
1116       }
1117       param->sync_clones();
1118     }
1119     if (param->convert_str_value(thd))
1120       DBUG_RETURN(1);                           /* out of memory */
1121   }
1122   DBUG_RETURN(0);
1123 }
1124 
1125 
1126 static bool emb_insert_params_with_log(Prepared_statement *stmt, String *query)
1127 {
1128   THD *thd= stmt->thd;
1129   Item_param **it= stmt->param_array;
1130   Item_param **end= it + stmt->param_count;
1131   MYSQL_BIND *client_param= thd->client_params;
1132   Copy_query_with_rewrite acc(thd, stmt->query(), stmt->query_length(), query);
1133   DBUG_ENTER("emb_insert_params_with_log");
1134 
1135   for (; it < end; ++it, ++client_param)
1136   {
1137     Item_param *param= *it;
1138     param->setup_conversion(thd, client_param->buffer_type);
1139     if (!param->has_long_data_value())
1140     {
1141       if (*client_param->is_null)
1142         param->set_null();
1143       else
1144       {
1145         uchar *buff= (uchar*)client_param->buffer;
1146         param->unsigned_flag= client_param->is_unsigned;
1147         param->set_param_func(&buff,
1148                               client_param->length ?
1149                               *client_param->length :
1150                               client_param->buffer_length);
1151         if (param->has_no_value())
1152           DBUG_RETURN(1);
1153       }
1154     }
1155     if (acc.append(param))
1156       DBUG_RETURN(1);
1157 
1158     if (param->convert_str_value(thd))
1159       DBUG_RETURN(1);                           /* out of memory */
1160     param->sync_clones();
1161   }
1162   if (acc.finalize())
1163     DBUG_RETURN(1);
1164 
1165   DBUG_RETURN(0);
1166 }
1167 
1168 #endif /*!EMBEDDED_LIBRARY*/
1169 
1170 /**
1171   Setup data conversion routines using an array of parameter
1172   markers from the original prepared statement.
1173   Swap the parameter data of the original prepared
1174   statement to the new one.
1175 
1176   Used only when we re-prepare a prepared statement.
1177   There are two reasons for this function to exist:
1178 
1179   1) In the binary client/server protocol, parameter metadata
1180   is sent only at first execute. Consequently, if we need to
1181   reprepare a prepared statement at a subsequent execution,
1182   we may not have metadata information in the packet.
1183   In that case we use the parameter array of the original
1184   prepared statement to setup parameter types of the new
1185   prepared statement.
1186 
1187   2) In the binary client/server protocol, we may supply
1188   long data in pieces. When the last piece is supplied,
1189   we assemble the pieces and convert them from client
1190   character set to the connection character set. After
1191   that the parameter value is only available inside
1192   the parameter, the original pieces are lost, and thus
1193   we can only assign the corresponding parameter of the
1194   reprepared statement from the original value.
1195 
1196   @param[out]  param_array_dst  parameter markers of the new statement
1197   @param[in]   param_array_src  parameter markers of the original
1198                                 statement
1199   @param[in]   param_count      total number of parameters. Is the
1200                                 same in src and dst arrays, since
1201                                 the statement query is the same
1202 
1203   @return this function never fails
1204 */
1205 
1206 static void
1207 swap_parameter_array(Item_param **param_array_dst,
1208                      Item_param **param_array_src,
1209                      uint param_count)
1210 {
1211   Item_param **dst= param_array_dst;
1212   Item_param **src= param_array_src;
1213   Item_param **end= param_array_dst + param_count;
1214 
1215   for (; dst < end; ++src, ++dst)
1216   {
1217     (*dst)->set_param_type_and_swap_value(*src);
1218     (*dst)->sync_clones();
1219     (*src)->sync_clones();
1220   }
1221 }
1222 
1223 
1224 /**
1225   Assign prepared statement parameters from user variables.
1226 
1227   @param stmt      Statement
1228   @param params    A list of parameters. Caller must ensure that number
1229                    of parameters in the list is equal to number of statement
1230                    parameters
1231   @param query     Ignored
1232 */
1233 
1234 static bool
1235 insert_params_from_actual_params(Prepared_statement *stmt,
1236                                  List<Item> &params,
1237                                  String *query __attribute__((unused)))
1238 {
1239   Item_param **begin= stmt->param_array;
1240   Item_param **end= begin + stmt->param_count;
1241   List_iterator<Item> param_it(params);
1242   DBUG_ENTER("insert_params_from_actual_params");
1243 
1244   for (Item_param **it= begin; it < end; ++it)
1245   {
1246     Item_param *param= *it;
1247     Item *ps_param= param_it++;
1248     if (ps_param->save_in_param(stmt->thd, param) ||
1249         param->convert_str_value(stmt->thd))
1250       DBUG_RETURN(1);
1251     param->sync_clones();
1252   }
1253   DBUG_RETURN(0);
1254 }
1255 
1256 
1257 /**
1258   Do the same as insert_params_from_actual_params
1259   but also construct query text for binary log.
1260 
1261   @param stmt      Prepared statement
1262   @param params    A list of parameters. Caller must ensure that number of
1263                    parameters in the list is equal to number of statement
1264                    parameters
1265   @param query     The query with parameter markers replaced with corresponding
1266                    user variables that were used to execute the query.
1267 */
1268 
1269 static bool
1270 insert_params_from_actual_params_with_log(Prepared_statement *stmt,
1271                                           List<Item> &params,
1272                                           String *query)
1273 {
1274   Item_param **begin= stmt->param_array;
1275   Item_param **end= begin + stmt->param_count;
1276   List_iterator<Item> param_it(params);
1277   THD *thd= stmt->thd;
1278   Copy_query_with_rewrite acc(thd, stmt->query(), stmt->query_length(), query);
1279 
1280   DBUG_ENTER("insert_params_from_actual_params_with_log");
1281 
1282   for (Item_param **it= begin; it < end; ++it)
1283   {
1284     Item_param *param= *it;
1285     Item *ps_param= param_it++;
1286     if (ps_param->save_in_param(thd, param))
1287       DBUG_RETURN(1);
1288 
1289     if (acc.append(param))
1290       DBUG_RETURN(1);
1291 
1292     if (param->convert_str_value(thd))
1293       DBUG_RETURN(1);
1294 
1295     param->sync_clones();
1296   }
1297   if (acc.finalize())
1298     DBUG_RETURN(1);
1299 
1300   DBUG_RETURN(0);
1301 }
1302 
1303 /**
1304   Validate INSERT statement.
1305 
1306   @param stmt               prepared statement
1307   @param tables             global/local table list
1308 
1309   @retval
1310     FALSE             success
1311   @retval
1312     TRUE              error, error message is set in THD
1313 */
1314 
1315 static bool mysql_test_insert(Prepared_statement *stmt,
1316                               TABLE_LIST *table_list,
1317                               List<Item> &fields,
1318                               List<List_item> &values_list,
1319                               List<Item> &update_fields,
1320                               List<Item> &update_values,
1321                               enum_duplicates duplic)
1322 {
1323   THD *thd= stmt->thd;
1324   List_iterator_fast<List_item> its(values_list);
1325   List_item *values;
1326   DBUG_ENTER("mysql_test_insert");
1327 
1328   /*
1329     Since INSERT DELAYED doesn't support temporary tables, we could
1330     not pre-open temporary tables for SQLCOM_INSERT / SQLCOM_REPLACE.
1331     Open them here instead.
1332   */
1333   if (table_list->lock_type != TL_WRITE_DELAYED)
1334   {
1335     if (thd->open_temporary_tables(table_list))
1336       goto error;
1337   }
1338 
1339   if (insert_precheck(thd, table_list))
1340     goto error;
1341 
1342   //upgrade_lock_type_for_insert(thd, &table_list->lock_type, duplic,
1343   //                             values_list.elements > 1);
1344   /*
1345     open temporary memory pool for temporary data allocated by derived
1346     tables & preparation procedure
1347     Note that this is done without locks (should not be needed as we will not
1348     access any data here)
1349     If we would use locks, then we have to ensure we are not using
1350     TL_WRITE_DELAYED as having two such locks can cause table corruption.
1351   */
1352   if (open_normal_and_derived_tables(thd, table_list,
1353                                      MYSQL_OPEN_FORCE_SHARED_MDL, DT_INIT))
1354     goto error;
1355 
1356   if ((values= its++))
1357   {
1358     uint value_count;
1359     ulong counter= 0;
1360     Item *unused_conds= 0;
1361 
1362     if (table_list->table)
1363     {
1364       // don't allocate insert_values
1365       table_list->table->insert_values=(uchar *)1;
1366     }
1367 
1368     if (mysql_prepare_insert(thd, table_list, table_list->table,
1369                              fields, values, update_fields, update_values,
1370                              duplic, &unused_conds, FALSE))
1371       goto error;
1372 
1373     value_count= values->elements;
1374     its.rewind();
1375 
1376     if (table_list->lock_type == TL_WRITE_DELAYED &&
1377         !(table_list->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED))
1378     {
1379       my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), (table_list->view ?
1380                                                   table_list->view_name.str :
1381                                                   table_list->table_name.str));
1382       goto error;
1383     }
1384     while ((values= its++))
1385     {
1386       counter++;
1387       if (values->elements != value_count)
1388       {
1389         my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
1390         goto error;
1391       }
1392       if (setup_fields(thd, Ref_ptr_array(),
1393                        *values, COLUMNS_READ, 0, NULL, 0))
1394         goto error;
1395     }
1396   }
1397   DBUG_RETURN(FALSE);
1398 
1399 error:
1400   /* insert_values is cleared in open_table */
1401   DBUG_RETURN(TRUE);
1402 }
1403 
1404 
1405 /**
1406   Validate UPDATE statement.
1407 
1408   @param stmt               prepared statement
1409   @param tables             list of tables used in this query
1410 
1411   @todo
1412     - here we should send types of placeholders to the client.
1413 
1414   @retval
1415     0                 success
1416   @retval
1417     1                 error, error message is set in THD
1418   @retval
1419     2                 convert to multi_update
1420 */
1421 
1422 static int mysql_test_update(Prepared_statement *stmt,
1423                               TABLE_LIST *table_list)
1424 {
1425   int res;
1426   THD *thd= stmt->thd;
1427   uint table_count= 0;
1428   TABLE_LIST *update_source_table;
1429   SELECT_LEX *select= &stmt->lex->select_lex;
1430 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1431   uint          want_privilege;
1432 #endif
1433   DBUG_ENTER("mysql_test_update");
1434 
1435   if (update_precheck(thd, table_list) ||
1436       open_tables(thd, &table_list, &table_count, MYSQL_OPEN_FORCE_SHARED_MDL))
1437     goto error;
1438 
1439   if (mysql_handle_derived(thd->lex, DT_INIT))
1440     goto error;
1441 
1442   if (((update_source_table= unique_table(thd, table_list,
1443                                           table_list->next_global, 0)) ||
1444         table_list->is_multitable()))
1445   {
1446     DBUG_ASSERT(update_source_table || table_list->view != 0);
1447     DBUG_PRINT("info", ("Switch to multi-update"));
1448     /* pass counter value */
1449     thd->lex->table_count= table_count;
1450     /* convert to multiupdate */
1451     DBUG_RETURN(2);
1452   }
1453 
1454   /*
1455     thd->fill_derived_tables() is false here for sure (because it is
1456     preparation of PS, so we even do not check it).
1457   */
1458   if (table_list->handle_derived(thd->lex, DT_MERGE_FOR_INSERT))
1459     goto error;
1460   if (table_list->handle_derived(thd->lex, DT_PREPARE))
1461     goto error;
1462 
1463   if (!table_list->single_table_updatable())
1464   {
1465     my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias.str, "UPDATE");
1466     goto error;
1467   }
1468 
1469 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1470   /* Force privilege re-checking for views after they have been opened. */
1471   want_privilege= (table_list->view ? UPDATE_ACL :
1472                    table_list->grant.want_privilege);
1473 #endif
1474 
1475   if (mysql_prepare_update(thd, table_list, &select->where,
1476                            select->order_list.elements,
1477                            select->order_list.first))
1478     goto error;
1479 
1480 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1481   table_list->grant.want_privilege= want_privilege;
1482   table_list->table->grant.want_privilege= want_privilege;
1483   table_list->register_want_access(want_privilege);
1484 #endif
1485   thd->lex->select_lex.no_wrap_view_item= TRUE;
1486   res= setup_fields(thd, Ref_ptr_array(),
1487                     select->item_list, MARK_COLUMNS_READ, 0, NULL, 0);
1488   thd->lex->select_lex.no_wrap_view_item= FALSE;
1489   if (res)
1490     goto error;
1491 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1492   /* Check values */
1493   table_list->grant.want_privilege=
1494   table_list->table->grant.want_privilege=
1495     (SELECT_ACL & ~table_list->table->grant.privilege);
1496   table_list->register_want_access(SELECT_ACL);
1497 #endif
1498   if (setup_fields(thd, Ref_ptr_array(),
1499                    stmt->lex->value_list, COLUMNS_READ, 0, NULL, 0) ||
1500       check_unique_table(thd, table_list))
1501     goto error;
1502   /* TODO: here we should send types of placeholders to the client. */
1503   DBUG_RETURN(0);
1504 error:
1505   DBUG_RETURN(1);
1506 }
1507 
1508 
1509 /**
1510   Validate DELETE statement.
1511 
1512   @param stmt               prepared statement
1513   @param tables             list of tables used in this query
1514 
1515   @retval
1516     FALSE             success
1517   @retval
1518     TRUE              error, error message is set in THD
1519 */
1520 
1521 static bool mysql_test_delete(Prepared_statement *stmt,
1522                               TABLE_LIST *table_list)
1523 {
1524   uint table_count= 0;
1525   THD *thd= stmt->thd;
1526   LEX *lex= stmt->lex;
1527   bool delete_while_scanning;
1528   DBUG_ENTER("mysql_test_delete");
1529 
1530   if (delete_precheck(thd, table_list) ||
1531       open_tables(thd, &table_list, &table_count, MYSQL_OPEN_FORCE_SHARED_MDL))
1532     goto error;
1533 
1534   if (mysql_handle_derived(thd->lex, DT_INIT))
1535     goto error;
1536   if (mysql_handle_derived(thd->lex, DT_MERGE_FOR_INSERT))
1537     goto error;
1538   if (mysql_handle_derived(thd->lex, DT_PREPARE))
1539     goto error;
1540 
1541   if (!table_list->single_table_updatable())
1542   {
1543     my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias.str, "DELETE");
1544     goto error;
1545   }
1546   if (!table_list->table || !table_list->table->is_created())
1547   {
1548     my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
1549              table_list->view_db.str, table_list->view_name.str);
1550     goto error;
1551   }
1552 
1553   DBUG_RETURN(mysql_prepare_delete(thd, table_list,
1554                                    lex->select_lex.with_wild,
1555                                    lex->select_lex.item_list,
1556                                    &lex->select_lex.where,
1557                                    &delete_while_scanning));
1558 error:
1559   DBUG_RETURN(TRUE);
1560 }
1561 
1562 
1563 /**
1564   Validate SELECT statement.
1565 
1566     In case of success, if this query is not EXPLAIN, send column list info
1567     back to the client.
1568 
1569   @param stmt               prepared statement
1570   @param tables             list of tables used in the query
1571 
1572   @retval
1573     0                 success
1574   @retval
1575     1                 error, error message is set in THD
1576   @retval
1577     2                 success, and statement metadata has been sent
1578 */
1579 
1580 static int mysql_test_select(Prepared_statement *stmt,
1581                              TABLE_LIST *tables)
1582 {
1583   THD *thd= stmt->thd;
1584   LEX *lex= stmt->lex;
1585   SELECT_LEX_UNIT *unit= &lex->unit;
1586   DBUG_ENTER("mysql_test_select");
1587 
1588   lex->select_lex.context.resolve_in_select_list= TRUE;
1589 
1590   ulong privilege= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL;
1591   if (tables)
1592   {
1593     if (check_table_access(thd, privilege, tables, FALSE, UINT_MAX, FALSE))
1594       goto error;
1595   }
1596   else if (check_access(thd, privilege, any_db, NULL, NULL, 0, 0))
1597     goto error;
1598 
1599   if (!lex->result && !(lex->result= new (stmt->mem_root) select_send(thd)))
1600   {
1601     my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR),
1602              static_cast<int>(sizeof(select_send)));
1603     goto error;
1604   }
1605 
1606   if (open_normal_and_derived_tables(thd, tables,  MYSQL_OPEN_FORCE_SHARED_MDL,
1607                                      DT_INIT | DT_PREPARE))
1608     goto error;
1609 
1610   thd->lex->used_tables= 0;                        // Updated by setup_fields
1611 
1612   /*
1613     JOIN::prepare calls
1614     It is not SELECT COMMAND for sure, so setup_tables will be called as
1615     usual, and we pass 0 as setup_tables_done_option
1616   */
1617   if (unit->prepare(unit->derived, 0, 0))
1618     goto error;
1619   if (!lex->describe && !thd->lex->analyze_stmt && !stmt->is_sql_prepare())
1620   {
1621     /* Make copy of item list, as change_columns may change it */
1622     SELECT_LEX_UNIT* master_unit= unit->first_select()->master_unit();
1623     bool is_union_op=
1624       master_unit->is_unit_op() || master_unit->fake_select_lex;
1625 
1626     List<Item> fields(is_union_op ? unit->item_list :
1627                                     lex->select_lex.item_list);
1628 
1629     /* Change columns if a procedure like analyse() */
1630     if (unit->last_procedure && unit->last_procedure->change_columns(thd, fields))
1631       goto error;
1632 
1633     /*
1634       We can use lex->result as it should've been prepared in
1635       unit->prepare call above.
1636     */
1637     if (send_prep_stmt(stmt, lex->result->field_count(fields)) ||
1638         lex->result->send_result_set_metadata(fields, Protocol::SEND_EOF) ||
1639         thd->protocol->flush())
1640       goto error;
1641     DBUG_RETURN(2);
1642   }
1643   DBUG_RETURN(0);
1644 error:
1645   DBUG_RETURN(1);
1646 }
1647 
1648 
1649 /**
1650   Validate and prepare for execution DO statement expressions.
1651 
1652   @param stmt               prepared statement
1653   @param tables             list of tables used in this query
1654   @param values             list of expressions
1655 
1656   @retval
1657     FALSE             success
1658   @retval
1659     TRUE              error, error message is set in THD
1660 */
1661 
1662 static bool mysql_test_do_fields(Prepared_statement *stmt,
1663                                 TABLE_LIST *tables,
1664                                 List<Item> *values)
1665 {
1666   THD *thd= stmt->thd;
1667 
1668   DBUG_ENTER("mysql_test_do_fields");
1669   if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
1670                                    UINT_MAX, FALSE))
1671     DBUG_RETURN(TRUE);
1672 
1673   if (open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL,
1674                                      DT_INIT | DT_PREPARE))
1675     DBUG_RETURN(TRUE);
1676   DBUG_RETURN(setup_fields(thd, Ref_ptr_array(),
1677                            *values, COLUMNS_READ, 0, NULL, 0));
1678 }
1679 
1680 
1681 /**
1682   Validate and prepare for execution SET statement expressions.
1683 
1684   @param stmt               prepared statement
1685   @param tables             list of tables used in this query
1686   @param values             list of expressions
1687 
1688   @retval
1689     FALSE             success
1690   @retval
1691     TRUE              error, error message is set in THD
1692 */
1693 
1694 static bool mysql_test_set_fields(Prepared_statement *stmt,
1695                                   TABLE_LIST *tables,
1696                                   List<set_var_base> *var_list)
1697 {
1698   DBUG_ENTER("mysql_test_set_fields");
1699   List_iterator_fast<set_var_base> it(*var_list);
1700   THD *thd= stmt->thd;
1701   set_var_base *var;
1702 
1703   if ((tables &&
1704        check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE)) ||
1705       open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL,
1706                                      DT_INIT | DT_PREPARE))
1707     goto error;
1708 
1709   while ((var= it++))
1710   {
1711     if (var->light_check(thd))
1712       goto error;
1713   }
1714   DBUG_RETURN(FALSE);
1715 error:
1716   DBUG_RETURN(TRUE);
1717 }
1718 
1719 
1720 /**
1721   Validate and prepare for execution CALL statement expressions.
1722 
1723   @param stmt               prepared statement
1724   @param tables             list of tables used in this query
1725   @param value_list         list of expressions
1726 
1727   @retval FALSE             success
1728   @retval TRUE              error, error message is set in THD
1729 */
1730 
1731 static bool mysql_test_call_fields(Prepared_statement *stmt,
1732                                    TABLE_LIST *tables,
1733                                    List<Item> *value_list)
1734 {
1735   DBUG_ENTER("mysql_test_call_fields");
1736 
1737   List_iterator<Item> it(*value_list);
1738   THD *thd= stmt->thd;
1739   Item *item;
1740 
1741   if ((tables &&
1742        check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE)) ||
1743       open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL,
1744                                      DT_INIT | DT_PREPARE))
1745     goto err;
1746 
1747   while ((item= it++))
1748   {
1749     if (item->fix_fields_if_needed(thd, it.ref()))
1750       goto err;
1751   }
1752   DBUG_RETURN(FALSE);
1753 err:
1754   DBUG_RETURN(TRUE);
1755 }
1756 
1757 
1758 /**
1759   Check internal SELECT of the prepared command.
1760 
1761   @param stmt                      prepared statement
1762   @param specific_prepare          function of command specific prepare
1763   @param setup_tables_done_option  options to be passed to LEX::unit.prepare()
1764 
1765   @note
1766     This function won't directly open tables used in select. They should
1767     be opened either by calling function (and in this case you probably
1768     should use select_like_stmt_test_with_open()) or by
1769     "specific_prepare" call (like this happens in case of multi-update).
1770 
1771   @retval
1772     FALSE                success
1773   @retval
1774     TRUE                 error, error message is set in THD
1775 */
1776 
1777 static bool select_like_stmt_test(Prepared_statement *stmt,
1778                                   int (*specific_prepare)(THD *thd),
1779                                   ulong setup_tables_done_option)
1780 {
1781   DBUG_ENTER("select_like_stmt_test");
1782   THD *thd= stmt->thd;
1783   LEX *lex= stmt->lex;
1784 
1785   lex->select_lex.context.resolve_in_select_list= TRUE;
1786 
1787   if (specific_prepare && (*specific_prepare)(thd))
1788     DBUG_RETURN(TRUE);
1789 
1790   thd->lex->used_tables= 0;                        // Updated by setup_fields
1791 
1792   /* Calls JOIN::prepare */
1793   DBUG_RETURN(lex->unit.prepare(lex->unit.derived, 0, setup_tables_done_option));
1794 }
1795 
1796 /**
1797   Check internal SELECT of the prepared command (with opening of used
1798   tables).
1799 
1800   @param stmt                      prepared statement
1801   @param tables                    list of tables to be opened
1802                                    before calling specific_prepare function
1803   @param specific_prepare          function of command specific prepare
1804   @param setup_tables_done_option  options to be passed to LEX::unit.prepare()
1805 
1806   @retval
1807     FALSE                success
1808   @retval
1809     TRUE                 error
1810 */
1811 
1812 static bool
1813 select_like_stmt_test_with_open(Prepared_statement *stmt,
1814                                 TABLE_LIST *tables,
1815                                 int (*specific_prepare)(THD *thd),
1816                                 ulong setup_tables_done_option)
1817 {
1818   uint table_count= 0;
1819   DBUG_ENTER("select_like_stmt_test_with_open");
1820 
1821   /*
1822     We should not call LEX::unit.cleanup() after this
1823     open_normal_and_derived_tables() call because we don't allow
1824     prepared EXPLAIN yet so derived tables will clean up after
1825     themself.
1826   */
1827   THD *thd= stmt->thd;
1828   if (open_tables(thd, &tables, &table_count, MYSQL_OPEN_FORCE_SHARED_MDL))
1829     DBUG_RETURN(TRUE);
1830 
1831   DBUG_RETURN(select_like_stmt_test(stmt, specific_prepare,
1832                                     setup_tables_done_option));
1833 }
1834 
1835 
1836 /**
1837   Validate and prepare for execution CREATE TABLE statement.
1838 
1839   @param stmt               prepared statement
1840   @param tables             list of tables used in this query
1841 
1842   @retval
1843     FALSE             success
1844   @retval
1845     TRUE              error, error message is set in THD
1846 */
1847 
1848 static bool mysql_test_create_table(Prepared_statement *stmt)
1849 {
1850   DBUG_ENTER("mysql_test_create_table");
1851   THD *thd= stmt->thd;
1852   LEX *lex= stmt->lex;
1853   SELECT_LEX *select_lex= &lex->select_lex;
1854   bool res= FALSE;
1855   bool link_to_local;
1856   TABLE_LIST *create_table= lex->query_tables;
1857   TABLE_LIST *tables= lex->create_last_non_select_table->next_global;
1858 
1859   if (create_table_precheck(thd, tables, create_table))
1860     DBUG_RETURN(TRUE);
1861 
1862   if (select_lex->item_list.elements)
1863   {
1864     /* Base table and temporary table are not in the same name space. */
1865     if (!lex->create_info.tmp_table())
1866       create_table->open_type= OT_BASE_ONLY;
1867 
1868     if (open_normal_and_derived_tables(stmt->thd, lex->query_tables,
1869                                        MYSQL_OPEN_FORCE_SHARED_MDL,
1870                                        DT_INIT | DT_PREPARE))
1871       DBUG_RETURN(TRUE);
1872 
1873     select_lex->context.resolve_in_select_list= TRUE;
1874 
1875     lex->unlink_first_table(&link_to_local);
1876 
1877     res= select_like_stmt_test(stmt, 0, 0);
1878 
1879     lex->link_first_table_back(create_table, link_to_local);
1880   }
1881   else
1882   {
1883     /*
1884       Check that the source table exist, and also record
1885       its metadata version. Even though not strictly necessary,
1886       we validate metadata of all CREATE TABLE statements,
1887       which keeps metadata validation code simple.
1888     */
1889     if (open_normal_and_derived_tables(stmt->thd, lex->query_tables,
1890                                        MYSQL_OPEN_FORCE_SHARED_MDL,
1891                                        DT_INIT | DT_PREPARE))
1892       DBUG_RETURN(TRUE);
1893   }
1894 
1895   DBUG_RETURN(res);
1896 }
1897 
1898 
1899 static int send_stmt_metadata(THD *thd, Prepared_statement *stmt, List<Item> *fields)
1900 {
1901   if (stmt->is_sql_prepare())
1902     return 0;
1903 
1904   if (send_prep_stmt(stmt, fields->elements) ||
1905       thd->protocol->send_result_set_metadata(fields, Protocol::SEND_EOF) ||
1906       thd->protocol->flush())
1907     return 1;
1908 
1909   return 2;
1910 }
1911 
1912 
1913 /**
1914   Validate and prepare for execution SHOW CREATE TABLE statement.
1915 
1916   @param stmt               prepared statement
1917   @param tables             list of tables used in this query
1918 
1919   @retval
1920     FALSE             success
1921   @retval
1922     TRUE              error, error message is set in THD
1923 */
1924 
1925 static int mysql_test_show_create_table(Prepared_statement *stmt,
1926                                         TABLE_LIST *tables)
1927 {
1928   DBUG_ENTER("mysql_test_show_create_table");
1929   THD *thd= stmt->thd;
1930   List<Item> fields;
1931   char buff[2048];
1932   String buffer(buff, sizeof(buff), system_charset_info);
1933 
1934   if (mysqld_show_create_get_fields(thd, tables, &fields, &buffer))
1935     DBUG_RETURN(1);
1936 
1937   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
1938 }
1939 
1940 
1941 /**
1942   Validate and prepare for execution SHOW CREATE DATABASE statement.
1943 
1944   @param stmt               prepared statement
1945 
1946   @retval
1947     FALSE             success
1948   @retval
1949     TRUE              error, error message is set in THD
1950 */
1951 
1952 static int mysql_test_show_create_db(Prepared_statement *stmt)
1953 {
1954   DBUG_ENTER("mysql_test_show_create_db");
1955   THD *thd= stmt->thd;
1956   List<Item> fields;
1957 
1958   mysqld_show_create_db_get_fields(thd, &fields);
1959 
1960   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
1961 }
1962 
1963 
1964 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1965 /**
1966   Validate and prepare for execution SHOW GRANTS statement.
1967 
1968   @param stmt               prepared statement
1969 
1970   @retval
1971     FALSE             success
1972   @retval
1973     TRUE              error, error message is set in THD
1974 */
1975 
1976 static int mysql_test_show_grants(Prepared_statement *stmt)
1977 {
1978   DBUG_ENTER("mysql_test_show_grants");
1979   THD *thd= stmt->thd;
1980   List<Item> fields;
1981   char buff[1024];
1982   const char *username= NULL, *hostname= NULL, *rolename= NULL, *end;
1983 
1984   if (get_show_user(thd, thd->lex->grant_user, &username, &hostname, &rolename))
1985     DBUG_RETURN(1);
1986 
1987   if (username)
1988     end= strxmov(buff,"Grants for ",username,"@",hostname, NullS);
1989   else if (rolename)
1990     end= strxmov(buff,"Grants for ",rolename, NullS);
1991   else
1992     DBUG_RETURN(1);
1993 
1994   mysql_show_grants_get_fields(thd, &fields, buff, (uint)(end - buff));
1995   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
1996 }
1997 #endif /*NO_EMBEDDED_ACCESS_CHECKS*/
1998 
1999 
2000 #ifndef EMBEDDED_LIBRARY
2001 /**
2002   Validate and prepare for execution SHOW SLAVE STATUS statement.
2003 
2004   @param stmt               prepared statement
2005 
2006   @retval
2007     FALSE             success
2008   @retval
2009     TRUE              error, error message is set in THD
2010 */
2011 
2012 static int mysql_test_show_slave_status(Prepared_statement *stmt)
2013 {
2014   DBUG_ENTER("mysql_test_show_slave_status");
2015   THD *thd= stmt->thd;
2016   List<Item> fields;
2017 
2018   show_master_info_get_fields(thd, &fields, thd->lex->verbose, 0);
2019 
2020   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
2021 }
2022 
2023 
2024 /**
2025   Validate and prepare for execution SHOW MASTER STATUS statement.
2026 
2027   @param stmt               prepared statement
2028 
2029   @retval
2030     FALSE             success
2031   @retval
2032     TRUE              error, error message is set in THD
2033 */
2034 
2035 static int mysql_test_show_master_status(Prepared_statement *stmt)
2036 {
2037   DBUG_ENTER("mysql_test_show_master_status");
2038   THD *thd= stmt->thd;
2039   List<Item> fields;
2040 
2041   show_binlog_info_get_fields(thd, &fields);
2042 
2043   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
2044 }
2045 
2046 
2047 /**
2048   Validate and prepare for execution SHOW BINLOGS statement.
2049 
2050   @param stmt               prepared statement
2051 
2052   @retval
2053     FALSE             success
2054   @retval
2055     TRUE              error, error message is set in THD
2056 */
2057 
2058 static int mysql_test_show_binlogs(Prepared_statement *stmt)
2059 {
2060   DBUG_ENTER("mysql_test_show_binlogs");
2061   THD *thd= stmt->thd;
2062   List<Item> fields;
2063 
2064   show_binlogs_get_fields(thd, &fields);
2065 
2066   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
2067 }
2068 
2069 #endif /* EMBEDDED_LIBRARY */
2070 
2071 
2072 /**
2073   Validate and prepare for execution SHOW CREATE PROC/FUNC statement.
2074 
2075   @param stmt               prepared statement
2076 
2077   @retval
2078     FALSE             success
2079   @retval
2080     TRUE              error, error message is set in THD
2081 */
2082 
2083 static int mysql_test_show_create_routine(Prepared_statement *stmt,
2084                                           const Sp_handler *sph)
2085 {
2086   DBUG_ENTER("mysql_test_show_binlogs");
2087   THD *thd= stmt->thd;
2088   List<Item> fields;
2089 
2090   sp_head::show_create_routine_get_fields(thd, sph, &fields);
2091 
2092   DBUG_RETURN(send_stmt_metadata(thd, stmt, &fields));
2093 }
2094 
2095 
2096 /**
2097   @brief Validate and prepare for execution CREATE VIEW statement
2098 
2099   @param stmt prepared statement
2100 
2101   @note This function handles create view commands.
2102 
2103   @retval FALSE Operation was a success.
2104   @retval TRUE An error occurred.
2105 */
2106 
2107 static bool mysql_test_create_view(Prepared_statement *stmt)
2108 {
2109   DBUG_ENTER("mysql_test_create_view");
2110   THD *thd= stmt->thd;
2111   LEX *lex= stmt->lex;
2112   bool res= TRUE;
2113   /* Skip first table, which is the view we are creating */
2114   bool link_to_local;
2115   TABLE_LIST *view= lex->unlink_first_table(&link_to_local);
2116   TABLE_LIST *tables= lex->query_tables;
2117 
2118   if (create_view_precheck(thd, tables, view, lex->create_view->mode))
2119     goto err;
2120 
2121   /*
2122     Since we can't pre-open temporary tables for SQLCOM_CREATE_VIEW,
2123     (see mysql_create_view) we have to do it here instead.
2124   */
2125   if (thd->open_temporary_tables(tables))
2126     goto err;
2127 
2128   lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW;
2129   if (open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL,
2130                                      DT_INIT | DT_PREPARE))
2131     goto err;
2132 
2133   res= select_like_stmt_test(stmt, 0, 0);
2134 
2135 err:
2136   /* put view back for PS rexecuting */
2137   lex->link_first_table_back(view, link_to_local);
2138   DBUG_RETURN(res);
2139 }
2140 
2141 
2142 /*
2143   Validate and prepare for execution a multi update statement.
2144 
2145   @param stmt               prepared statement
2146   @param tables             list of tables used in this query
2147   @param converted          converted to multi-update from usual update
2148 
2149   @retval
2150     FALSE             success
2151   @retval
2152     TRUE              error, error message is set in THD
2153 */
2154 
2155 static bool mysql_test_multiupdate(Prepared_statement *stmt,
2156                                   TABLE_LIST *tables,
2157                                   bool converted)
2158 {
2159   /* if we switched from normal update, rights are checked */
2160   if (!converted && multi_update_precheck(stmt->thd, tables))
2161     return TRUE;
2162 
2163   return select_like_stmt_test(stmt, &mysql_multi_update_prepare,
2164                                OPTION_SETUP_TABLES_DONE);
2165 }
2166 
2167 
2168 /**
2169   Validate and prepare for execution a multi delete statement.
2170 
2171   @param stmt               prepared statement
2172   @param tables             list of tables used in this query
2173 
2174   @retval
2175     FALSE             success
2176   @retval
2177     TRUE              error, error message in THD is set.
2178 */
2179 
2180 static bool mysql_test_multidelete(Prepared_statement *stmt,
2181                                   TABLE_LIST *tables)
2182 {
2183   THD *thd= stmt->thd;
2184 
2185   thd->lex->current_select= &thd->lex->select_lex;
2186   if (add_item_to_list(thd, new (thd->mem_root)
2187                        Item_null(thd)))
2188   {
2189     my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR), 0);
2190     goto error;
2191   }
2192 
2193   if (multi_delete_precheck(thd, tables) ||
2194       select_like_stmt_test_with_open(stmt, tables,
2195                                       &mysql_multi_delete_prepare,
2196                                       OPTION_SETUP_TABLES_DONE))
2197     goto error;
2198   if (!tables->table)
2199   {
2200     my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
2201              tables->view_db.str, tables->view_name.str);
2202     goto error;
2203   }
2204   return FALSE;
2205 error:
2206   return TRUE;
2207 }
2208 
2209 
2210 /**
2211   Wrapper for mysql_insert_select_prepare, to make change of local tables
2212   after open_normal_and_derived_tables() call.
2213 
2214   @param thd                thread handle
2215 
2216   @note
2217     We need to remove the first local table after
2218     open_normal_and_derived_tables(), because mysql_handle_derived
2219     uses local tables lists.
2220 */
2221 
2222 static int mysql_insert_select_prepare_tester(THD *thd)
2223 {
2224   SELECT_LEX *first_select= &thd->lex->select_lex;
2225   TABLE_LIST *second_table= first_select->table_list.first->next_local;
2226 
2227   /* Skip first table, which is the table we are inserting in */
2228   first_select->table_list.first= second_table;
2229   thd->lex->select_lex.context.table_list=
2230     thd->lex->select_lex.context.first_name_resolution_table= second_table;
2231 
2232   return mysql_insert_select_prepare(thd);
2233 }
2234 
2235 
2236 /**
2237   Validate and prepare for execution INSERT ... SELECT statement.
2238 
2239   @param stmt               prepared statement
2240   @param tables             list of tables used in this query
2241 
2242   @retval
2243     FALSE             success
2244   @retval
2245     TRUE              error, error message is set in THD
2246 */
2247 
2248 static bool mysql_test_insert_select(Prepared_statement *stmt,
2249                                      TABLE_LIST *tables)
2250 {
2251   int res;
2252   LEX *lex= stmt->lex;
2253   TABLE_LIST *first_local_table;
2254 
2255   if (tables->table)
2256   {
2257     // don't allocate insert_values
2258     tables->table->insert_values=(uchar *)1;
2259   }
2260 
2261   if (insert_precheck(stmt->thd, tables))
2262     return 1;
2263 
2264   /* store it, because mysql_insert_select_prepare_tester change it */
2265   first_local_table= lex->select_lex.table_list.first;
2266   DBUG_ASSERT(first_local_table != 0);
2267 
2268   res=
2269     select_like_stmt_test_with_open(stmt, tables,
2270                                     &mysql_insert_select_prepare_tester,
2271                                     OPTION_SETUP_TABLES_DONE);
2272   /* revert changes  made by mysql_insert_select_prepare_tester */
2273   lex->select_lex.table_list.first= first_local_table;
2274   return res;
2275 }
2276 
2277 /**
2278   Validate SELECT statement.
2279 
2280     In case of success, if this query is not EXPLAIN, send column list info
2281     back to the client.
2282 
2283   @param stmt               prepared statement
2284   @param tables             list of tables used in the query
2285 
2286   @retval 0 success
2287   @retval 1 error, error message is set in THD
2288   @retval 2 success, and statement metadata has been sent
2289 */
2290 
2291 static int mysql_test_handler_read(Prepared_statement *stmt,
2292                                    TABLE_LIST *tables)
2293 {
2294   THD *thd= stmt->thd;
2295   LEX *lex= stmt->lex;
2296   SQL_HANDLER *ha_table;
2297   DBUG_ENTER("mysql_test_handler_read");
2298 
2299   lex->select_lex.context.resolve_in_select_list= TRUE;
2300 
2301   /*
2302     We don't have to test for permissions as this is already done during
2303     HANDLER OPEN
2304   */
2305   if (!(ha_table= mysql_ha_read_prepare(thd, tables, lex->ha_read_mode,
2306                                         lex->ident.str,
2307                                         lex->insert_list,
2308                                         lex->ha_rkey_mode,
2309                                         lex->select_lex.where)))
2310     DBUG_RETURN(1);
2311 
2312   if (!stmt->is_sql_prepare())
2313   {
2314     if (!lex->result && !(lex->result= new (stmt->mem_root) select_send(thd)))
2315       DBUG_RETURN(1);
2316 
2317     if (send_prep_stmt(stmt, ha_table->fields.elements) ||
2318         lex->result->send_result_set_metadata(ha_table->fields, Protocol::SEND_EOF) ||
2319         thd->protocol->flush())
2320       DBUG_RETURN(1);
2321     DBUG_RETURN(2);
2322   }
2323   DBUG_RETURN(0);
2324 }
2325 
2326 
2327 /**
2328   Perform semantic analysis of the parsed tree and send a response packet
2329   to the client.
2330 
2331     This function
2332     - opens all tables and checks access rights
2333     - validates semantics of statement columns and SQL functions
2334       by calling fix_fields.
2335 
2336   @param stmt               prepared statement
2337 
2338   @retval
2339     FALSE             success, statement metadata is sent to client
2340   @retval
2341     TRUE              error, error message is set in THD (but not sent)
2342 */
2343 
2344 static bool check_prepared_statement(Prepared_statement *stmt)
2345 {
2346   THD *thd= stmt->thd;
2347   LEX *lex= stmt->lex;
2348   SELECT_LEX *select_lex= &lex->select_lex;
2349   TABLE_LIST *tables;
2350   enum enum_sql_command sql_command= lex->sql_command;
2351   int res= 0;
2352   DBUG_ENTER("check_prepared_statement");
2353   DBUG_PRINT("enter",("command: %d  param_count: %u",
2354                       sql_command, stmt->param_count));
2355 
2356   lex->first_lists_tables_same();
2357   tables= lex->query_tables;
2358 
2359   /* set context for commands which do not use setup_tables */
2360   lex->select_lex.context.resolve_in_table_list_only(select_lex->
2361                                                      get_table_list());
2362 
2363   /* Reset warning count for each query that uses tables */
2364   if (tables)
2365     thd->get_stmt_da()->opt_clear_warning_info(thd->query_id);
2366 
2367   if (sql_command_flags[sql_command] & CF_HA_CLOSE)
2368     mysql_ha_rm_tables(thd, tables);
2369 
2370   /*
2371     Open temporary tables that are known now. Temporary tables added by
2372     prelocking will be opened afterwards (during open_tables()).
2373   */
2374   if (sql_command_flags[sql_command] & CF_PREOPEN_TMP_TABLES)
2375   {
2376     if (thd->open_temporary_tables(tables))
2377       goto error;
2378   }
2379 
2380   switch (sql_command) {
2381   case SQLCOM_REPLACE:
2382   case SQLCOM_INSERT:
2383     res= mysql_test_insert(stmt, tables, lex->field_list,
2384                            lex->many_values,
2385                            lex->update_list, lex->value_list,
2386                            lex->duplicates);
2387     break;
2388 
2389   case SQLCOM_UPDATE:
2390     res= mysql_test_update(stmt, tables);
2391     /* mysql_test_update returns 2 if we need to switch to multi-update */
2392     if (res != 2)
2393       break;
2394     /* fall through */
2395   case SQLCOM_UPDATE_MULTI:
2396     res= mysql_test_multiupdate(stmt, tables, res == 2);
2397     break;
2398 
2399   case SQLCOM_DELETE:
2400     res= mysql_test_delete(stmt, tables);
2401     break;
2402   /* The following allow WHERE clause, so they must be tested like SELECT */
2403   case SQLCOM_SHOW_DATABASES:
2404   case SQLCOM_SHOW_TABLES:
2405   case SQLCOM_SHOW_TRIGGERS:
2406   case SQLCOM_SHOW_EVENTS:
2407   case SQLCOM_SHOW_OPEN_TABLES:
2408   case SQLCOM_SHOW_FIELDS:
2409   case SQLCOM_SHOW_KEYS:
2410   case SQLCOM_SHOW_COLLATIONS:
2411   case SQLCOM_SHOW_CHARSETS:
2412   case SQLCOM_SHOW_VARIABLES:
2413   case SQLCOM_SHOW_STATUS:
2414   case SQLCOM_SHOW_TABLE_STATUS:
2415   case SQLCOM_SHOW_STATUS_PROC:
2416   case SQLCOM_SHOW_STATUS_FUNC:
2417   case SQLCOM_SHOW_STATUS_PACKAGE:
2418   case SQLCOM_SHOW_STATUS_PACKAGE_BODY:
2419   case SQLCOM_SELECT:
2420     res= mysql_test_select(stmt, tables);
2421     if (res == 2)
2422     {
2423       /* Statement and field info has already been sent */
2424       DBUG_RETURN(FALSE);
2425     }
2426     break;
2427   case SQLCOM_CREATE_TABLE:
2428   case SQLCOM_CREATE_SEQUENCE:
2429     res= mysql_test_create_table(stmt);
2430     break;
2431   case SQLCOM_SHOW_CREATE:
2432     if ((res= mysql_test_show_create_table(stmt, tables)) == 2)
2433     {
2434       /* Statement and field info has already been sent */
2435       DBUG_RETURN(FALSE);
2436     }
2437     break;
2438   case SQLCOM_SHOW_CREATE_DB:
2439     if ((res= mysql_test_show_create_db(stmt)) == 2)
2440     {
2441       /* Statement and field info has already been sent */
2442       DBUG_RETURN(FALSE);
2443     }
2444     break;
2445 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2446   case SQLCOM_SHOW_GRANTS:
2447     if ((res= mysql_test_show_grants(stmt)) == 2)
2448     {
2449       /* Statement and field info has already been sent */
2450       DBUG_RETURN(FALSE);
2451     }
2452     break;
2453 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
2454 #ifndef EMBEDDED_LIBRARY
2455   case SQLCOM_SHOW_SLAVE_STAT:
2456     if ((res= mysql_test_show_slave_status(stmt)) == 2)
2457     {
2458       /* Statement and field info has already been sent */
2459       DBUG_RETURN(FALSE);
2460     }
2461     break;
2462   case SQLCOM_SHOW_MASTER_STAT:
2463     if ((res= mysql_test_show_master_status(stmt)) == 2)
2464     {
2465       /* Statement and field info has already been sent */
2466       DBUG_RETURN(FALSE);
2467     }
2468     break;
2469   case SQLCOM_SHOW_BINLOGS:
2470     if ((res= mysql_test_show_binlogs(stmt)) == 2)
2471     {
2472       /* Statement and field info has already been sent */
2473       DBUG_RETURN(FALSE);
2474     }
2475     break;
2476   case SQLCOM_SHOW_BINLOG_EVENTS:
2477   case SQLCOM_SHOW_RELAYLOG_EVENTS:
2478     {
2479       List<Item> field_list;
2480       Log_event::init_show_field_list(thd, &field_list);
2481 
2482       if ((res= send_stmt_metadata(thd, stmt, &field_list)) == 2)
2483         DBUG_RETURN(FALSE);
2484     }
2485   break;
2486 #endif /* EMBEDDED_LIBRARY */
2487   case SQLCOM_SHOW_CREATE_PROC:
2488     if ((res= mysql_test_show_create_routine(stmt, &sp_handler_procedure)) == 2)
2489     {
2490       /* Statement and field info has already been sent */
2491       DBUG_RETURN(FALSE);
2492     }
2493     break;
2494   case SQLCOM_SHOW_CREATE_FUNC:
2495     if ((res= mysql_test_show_create_routine(stmt, &sp_handler_function)) == 2)
2496     {
2497       /* Statement and field info has already been sent */
2498       DBUG_RETURN(FALSE);
2499     }
2500     break;
2501   case SQLCOM_SHOW_CREATE_PACKAGE:
2502     if ((res= mysql_test_show_create_routine(stmt, &sp_handler_package_spec)) == 2)
2503     {
2504       /* Statement and field info has already been sent */
2505       DBUG_RETURN(FALSE);
2506     }
2507     break;
2508   case SQLCOM_SHOW_CREATE_PACKAGE_BODY:
2509     if ((res= mysql_test_show_create_routine(stmt,
2510                                              &sp_handler_package_body)) == 2)
2511     {
2512       /* Statement and field info has already been sent */
2513       DBUG_RETURN(FALSE);
2514     }
2515     break;
2516   case SQLCOM_CREATE_VIEW:
2517     if (lex->create_view->mode == VIEW_ALTER)
2518     {
2519       my_message(ER_UNSUPPORTED_PS, ER_THD(thd, ER_UNSUPPORTED_PS), MYF(0));
2520       goto error;
2521     }
2522     res= mysql_test_create_view(stmt);
2523     break;
2524   case SQLCOM_DO:
2525     res= mysql_test_do_fields(stmt, tables, lex->insert_list);
2526     break;
2527 
2528   case SQLCOM_CALL:
2529     res= mysql_test_call_fields(stmt, tables, &lex->value_list);
2530     break;
2531   case SQLCOM_SET_OPTION:
2532     res= mysql_test_set_fields(stmt, tables, &lex->var_list);
2533     break;
2534 
2535   case SQLCOM_DELETE_MULTI:
2536     res= mysql_test_multidelete(stmt, tables);
2537     break;
2538 
2539   case SQLCOM_INSERT_SELECT:
2540   case SQLCOM_REPLACE_SELECT:
2541     res= mysql_test_insert_select(stmt, tables);
2542     break;
2543 
2544   case SQLCOM_HA_READ:
2545     res= mysql_test_handler_read(stmt, tables);
2546     /* Statement and field info has already been sent */
2547     DBUG_RETURN(res == 1 ? TRUE : FALSE);
2548 
2549     /*
2550       Note that we don't need to have cases in this list if they are
2551       marked with CF_STATUS_COMMAND in sql_command_flags
2552     */
2553   case SQLCOM_SHOW_EXPLAIN:
2554   case SQLCOM_DROP_TABLE:
2555   case SQLCOM_DROP_SEQUENCE:
2556   case SQLCOM_RENAME_TABLE:
2557   case SQLCOM_ALTER_TABLE:
2558   case SQLCOM_ALTER_SEQUENCE:
2559   case SQLCOM_COMMIT:
2560   case SQLCOM_CREATE_INDEX:
2561   case SQLCOM_DROP_INDEX:
2562   case SQLCOM_ROLLBACK:
2563   case SQLCOM_ROLLBACK_TO_SAVEPOINT:
2564   case SQLCOM_TRUNCATE:
2565   case SQLCOM_DROP_VIEW:
2566   case SQLCOM_REPAIR:
2567   case SQLCOM_ANALYZE:
2568   case SQLCOM_OPTIMIZE:
2569   case SQLCOM_CHANGE_MASTER:
2570   case SQLCOM_RESET:
2571   case SQLCOM_FLUSH:
2572   case SQLCOM_SLAVE_START:
2573   case SQLCOM_SLAVE_STOP:
2574   case SQLCOM_SLAVE_ALL_START:
2575   case SQLCOM_SLAVE_ALL_STOP:
2576   case SQLCOM_INSTALL_PLUGIN:
2577   case SQLCOM_UNINSTALL_PLUGIN:
2578   case SQLCOM_CREATE_DB:
2579   case SQLCOM_DROP_DB:
2580   case SQLCOM_ALTER_DB_UPGRADE:
2581   case SQLCOM_CHECKSUM:
2582   case SQLCOM_CREATE_USER:
2583   case SQLCOM_ALTER_USER:
2584   case SQLCOM_RENAME_USER:
2585   case SQLCOM_DROP_USER:
2586   case SQLCOM_CREATE_ROLE:
2587   case SQLCOM_DROP_ROLE:
2588   case SQLCOM_ASSIGN_TO_KEYCACHE:
2589   case SQLCOM_PRELOAD_KEYS:
2590   case SQLCOM_GRANT:
2591   case SQLCOM_GRANT_ROLE:
2592   case SQLCOM_REVOKE:
2593   case SQLCOM_REVOKE_ALL:
2594   case SQLCOM_REVOKE_ROLE:
2595   case SQLCOM_KILL:
2596   case SQLCOM_COMPOUND:
2597   case SQLCOM_SHUTDOWN:
2598     break;
2599 
2600   case SQLCOM_PREPARE:
2601   case SQLCOM_EXECUTE:
2602   case SQLCOM_DEALLOCATE_PREPARE:
2603   default:
2604     /*
2605       Trivial check of all status commands. This is easier than having
2606       things in the above case list, as it's less chance for mistakes.
2607     */
2608     if (!(sql_command_flags[sql_command] & CF_STATUS_COMMAND))
2609     {
2610       /* All other statements are not supported yet. */
2611       my_message(ER_UNSUPPORTED_PS, ER_THD(thd, ER_UNSUPPORTED_PS), MYF(0));
2612       goto error;
2613     }
2614     break;
2615   }
2616   if (res == 0)
2617   {
2618     if (!stmt->is_sql_prepare())
2619     {
2620        if (lex->describe || lex->analyze_stmt)
2621        {
2622          select_send result(thd);
2623          List<Item> field_list;
2624          res= thd->prepare_explain_fields(&result, &field_list,
2625                                           lex->describe, lex->analyze_stmt) ||
2626               send_prep_stmt(stmt, result.field_count(field_list)) ||
2627               result.send_result_set_metadata(field_list,
2628                                                     Protocol::SEND_EOF);
2629        }
2630        else
2631          res= send_prep_stmt(stmt, 0);
2632        if (!res)
2633          thd->protocol->flush();
2634     }
2635     DBUG_RETURN(FALSE);
2636   }
2637 error:
2638   DBUG_RETURN(TRUE);
2639 }
2640 
2641 /**
2642   Initialize array of parameters in statement from LEX.
2643   (We need to have quick access to items by number in mysql_stmt_get_longdata).
2644   This is to avoid using malloc/realloc in the parser.
2645 */
2646 
2647 static bool init_param_array(Prepared_statement *stmt)
2648 {
2649   LEX *lex= stmt->lex;
2650   if ((stmt->param_count= lex->param_list.elements))
2651   {
2652     if (stmt->param_count > (uint) UINT_MAX16)
2653     {
2654       /* Error code to be defined in 5.0 */
2655       my_message(ER_PS_MANY_PARAM, ER_THD(stmt->thd, ER_PS_MANY_PARAM),
2656                  MYF(0));
2657       return TRUE;
2658     }
2659     Item_param **to;
2660     List_iterator<Item_param> param_iterator(lex->param_list);
2661     /* Use thd->mem_root as it points at statement mem_root */
2662     stmt->param_array= (Item_param **)
2663                        alloc_root(stmt->thd->mem_root,
2664                                   sizeof(Item_param*) * stmt->param_count);
2665     if (!stmt->param_array)
2666       return TRUE;
2667     for (to= stmt->param_array;
2668          to < stmt->param_array + stmt->param_count;
2669          ++to)
2670     {
2671       *to= param_iterator++;
2672     }
2673   }
2674   return FALSE;
2675 }
2676 
2677 
2678 /**
2679   COM_STMT_PREPARE handler.
2680 
2681     Given a query string with parameter markers, create a prepared
2682     statement from it and send PS info back to the client.
2683 
2684     If parameter markers are found in the query, then store the information
2685     using Item_param along with maintaining a list in lex->param_array, so
2686     that a fast and direct retrieval can be made without going through all
2687     field items.
2688 
2689   @param packet             query to be prepared
2690   @param packet_length      query string length, including ignored
2691                             trailing NULL or quote char.
2692 
2693   @note
2694     This function parses the query and sends the total number of parameters
2695     and resultset metadata information back to client (if any), without
2696     executing the query i.e. without any log/disk writes. This allows the
2697     queries to be re-executed without re-parsing during execute.
2698 
2699   @return
2700     none: in case of success a new statement id and metadata is sent
2701     to the client, otherwise an error message is set in THD.
2702 */
2703 
2704 void mysqld_stmt_prepare(THD *thd, const char *packet, uint packet_length)
2705 {
2706   Protocol *save_protocol= thd->protocol;
2707   Prepared_statement *stmt;
2708   DBUG_ENTER("mysqld_stmt_prepare");
2709   DBUG_PRINT("prep_query", ("%s", packet));
2710 
2711   /* First of all clear possible warnings from the previous command */
2712   thd->reset_for_next_command();
2713 
2714   if (! (stmt= new Prepared_statement(thd)))
2715     goto end;           /* out of memory: error is set in Sql_alloc */
2716 
2717   if (thd->stmt_map.insert(thd, stmt))
2718   {
2719     /*
2720       The error is set in the insert. The statement itself
2721       will be also deleted there (this is how the hash works).
2722     */
2723     goto end;
2724   }
2725 
2726   thd->protocol= &thd->protocol_binary;
2727 
2728   if (stmt->prepare(packet, packet_length))
2729   {
2730     /* Statement map deletes statement on erase */
2731     thd->stmt_map.erase(stmt);
2732     thd->clear_last_stmt();
2733   }
2734   else
2735     thd->set_last_stmt(stmt);
2736 
2737   thd->protocol= save_protocol;
2738 
2739   sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
2740   sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
2741   sp_cache_enforce_limit(thd->sp_package_spec_cache, stored_program_cache_size);
2742   sp_cache_enforce_limit(thd->sp_package_body_cache, stored_program_cache_size);
2743 
2744   /* check_prepared_statemnt sends the metadata packet in case of success */
2745 end:
2746   DBUG_VOID_RETURN;
2747 }
2748 
2749 /**
2750   Get an SQL statement from an item in lex->prepared_stmt_code.
2751 
2752   This function can return pointers to very different memory classes:
2753   - a static string "NULL", if the item returned NULL
2754   - the result of prepare_stmt_code->val_str(), if no conversion was needed
2755   - a thd->mem_root allocated string with the result of
2756     prepare_stmt_code->val_str() converted to @@collation_connection,
2757     if conversion was needed
2758 
2759   The caller must dispose the result before the life cycle of "buffer" ends.
2760   As soon as buffer's destructor is called, the value is not valid any more!
2761 
2762   mysql_sql_stmt_prepare() and mysql_sql_stmt_execute_immediate()
2763   call get_dynamic_sql_string() and then call respectively
2764   Prepare_statement::prepare() and Prepare_statment::execute_immediate(),
2765   who store the returned result into its permanent location using
2766   alloc_query(). "buffer" is still not destructed at that time.
2767 
2768   @param[out]   dst        the result is stored here
2769   @param[inout] buffer
2770 
2771   @retval       false on success
2772   @retval       true on error (out of memory)
2773 */
2774 
2775 bool LEX::get_dynamic_sql_string(LEX_CSTRING *dst, String *buffer)
2776 {
2777   if (prepared_stmt_code->fix_fields_if_needed_for_scalar(thd, NULL))
2778     return true;
2779 
2780   const String *str= prepared_stmt_code->val_str(buffer);
2781   if (prepared_stmt_code->null_value)
2782   {
2783     /*
2784       Prepare source was NULL, so we need to set "str" to
2785       something reasonable to get a readable error message during parsing
2786     */
2787     dst->str= "NULL";
2788     dst->length= 4;
2789     return false;
2790   }
2791 
2792   /*
2793     Character set conversion notes:
2794 
2795     1) When PREPARE or EXECUTE IMMEDIATE are used with string literals:
2796           PREPARE stmt FROM 'SELECT ''str''';
2797           EXECUTE IMMEDIATE 'SELECT ''str''';
2798        it's very unlikely that any conversion will happen below, because
2799        @@character_set_client and @@collation_connection are normally
2800        set to the same CHARSET_INFO pointer.
2801 
2802        In tricky environments when @@collation_connection is set to something
2803        different from @@character_set_client, double conversion may happen:
2804        - When the parser scans the string literal
2805          (sql_yacc.yy rules "prepare_src" -> "expr" -> ... -> "text_literal")
2806          it will convert 'str' from @@character_set_client to
2807          @@collation_connection.
2808        - Then in the code below will convert 'str' from @@collation_connection
2809          back to @@character_set_client.
2810 
2811     2) When PREPARE or EXECUTE IMMEDIATE is used with a user variable,
2812         it should work about the same way, because user variables are usually
2813         assigned like this:
2814           SET @str='str';
2815         and thus have the same character set with string literals.
2816 
2817     3) When PREPARE or EXECUTE IMMEDIATE is used with some
2818        more complex expression, conversion will depend on this expression.
2819        For example, a concatenation of string literals:
2820          EXECUTE IMMEDIATE 'SELECT * FROM'||'t1';
2821        should work the same way with just a single literal,
2822        so no conversion normally.
2823   */
2824   CHARSET_INFO *to_cs= thd->variables.character_set_client;
2825 
2826   uint32 unused;
2827   if (String::needs_conversion(str->length(), str->charset(), to_cs, &unused))
2828   {
2829     if (!(dst->str= sql_strmake_with_convert(thd, str->ptr(), str->length(),
2830                                              str->charset(), UINT_MAX32,
2831                                              to_cs, &dst->length)))
2832     {
2833       dst->length= 0;
2834       return true;
2835     }
2836     DBUG_ASSERT(dst->length <= UINT_MAX32);
2837     return false;
2838   }
2839   dst->str= str->ptr();
2840   dst->length= str->length();
2841   return false;
2842 }
2843 
2844 
2845 /**
2846   SQLCOM_PREPARE implementation.
2847 
2848     Prepare an SQL prepared statement. This is called from
2849     mysql_execute_command and should therefore behave like an
2850     ordinary query (e.g. should not reset any global THD data).
2851 
2852   @param thd     thread handle
2853 
2854   @return
2855     none: in case of success, OK packet is sent to the client,
2856     otherwise an error message is set in THD
2857 */
2858 
2859 void mysql_sql_stmt_prepare(THD *thd)
2860 {
2861   LEX *lex= thd->lex;
2862   LEX_CSTRING *name= &lex->prepared_stmt_name;
2863   Prepared_statement *stmt;
2864   LEX_CSTRING query;
2865   DBUG_ENTER("mysql_sql_stmt_prepare");
2866 
2867   if ((stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
2868   {
2869     /*
2870       If there is a statement with the same name, remove it. It is ok to
2871       remove old and fail to insert a new one at the same time.
2872     */
2873     if (stmt->is_in_use())
2874     {
2875       my_error(ER_PS_NO_RECURSION, MYF(0));
2876       DBUG_VOID_RETURN;
2877     }
2878 
2879     stmt->deallocate();
2880   }
2881 
2882   /*
2883     It's important for "buffer" not to be destructed before stmt->prepare()!
2884     See comments in get_dynamic_sql_string().
2885   */
2886   StringBuffer<256> buffer;
2887   if (lex->get_dynamic_sql_string(&query, &buffer) ||
2888       ! (stmt= new Prepared_statement(thd)))
2889   {
2890     DBUG_VOID_RETURN;                           /* out of memory */
2891   }
2892 
2893   stmt->set_sql_prepare();
2894 
2895   /* Set the name first, insert should know that this statement has a name */
2896   if (stmt->set_name(name))
2897   {
2898     delete stmt;
2899     DBUG_VOID_RETURN;
2900   }
2901 
2902   if (thd->stmt_map.insert(thd, stmt))
2903   {
2904     /* The statement is deleted and an error is set if insert fails */
2905     DBUG_VOID_RETURN;
2906   }
2907 
2908   /*
2909     Make sure we call Prepared_statement::prepare() with an empty
2910     THD::change_list. It can be non-empty as LEX::get_dynamic_sql_string()
2911     calls fix_fields() for the Item containing the PS source,
2912     e.g. on character set conversion:
2913 
2914     SET NAMES utf8;
2915     DELIMITER $$
2916     CREATE PROCEDURE p1()
2917     BEGIN
2918       PREPARE stmt FROM CONCAT('SELECT ',CONVERT(RAND() USING latin1));
2919       EXECUTE stmt;
2920     END;
2921     $$
2922     DELIMITER ;
2923     CALL p1();
2924   */
2925   Item_change_list_savepoint change_list_savepoint(thd);
2926 
2927   if (stmt->prepare(query.str, (uint) query.length))
2928   {
2929     /* Statement map deletes the statement on erase */
2930     thd->stmt_map.erase(stmt);
2931   }
2932   else
2933   {
2934     SESSION_TRACKER_CHANGED(thd, SESSION_STATE_CHANGE_TRACKER, NULL);
2935     my_ok(thd, 0L, 0L, "Statement prepared");
2936   }
2937   change_list_savepoint.rollback(thd);
2938 
2939   DBUG_VOID_RETURN;
2940 }
2941 
2942 
2943 void mysql_sql_stmt_execute_immediate(THD *thd)
2944 {
2945   LEX *lex= thd->lex;
2946   Prepared_statement *stmt;
2947   LEX_CSTRING query;
2948   DBUG_ENTER("mysql_sql_stmt_execute_immediate");
2949 
2950   if (lex->prepared_stmt_params_fix_fields(thd))
2951     DBUG_VOID_RETURN;
2952 
2953   /*
2954     Prepared_statement is quite large,
2955     let's allocate it on the heap rather than on the stack.
2956 
2957     It's important for "buffer" not to be destructed
2958     before stmt->execute_immediate().
2959     See comments in get_dynamic_sql_string().
2960   */
2961   StringBuffer<256> buffer;
2962   if (lex->get_dynamic_sql_string(&query, &buffer) ||
2963       !(stmt= new Prepared_statement(thd)))
2964     DBUG_VOID_RETURN;                           // out of memory
2965 
2966   // See comments on thd->free_list in mysql_sql_stmt_execute()
2967   Item *free_list_backup= thd->free_list;
2968   thd->free_list= NULL;
2969   /*
2970     Make sure we call Prepared_statement::execute_immediate()
2971     with an empty THD::change_list. It can be non empty as the above
2972     LEX::prepared_stmt_params_fix_fields() and LEX::get_dynamic_str_string()
2973     call fix_fields() for the PS source and PS parameter Items and
2974     can do Item tree changes, e.g. on character set conversion:
2975 
2976     - Example #1: Item tree changes in get_dynamic_str_string()
2977     SET NAMES utf8;
2978     CREATE PROCEDURE p1()
2979       EXECUTE IMMEDIATE CONCAT('SELECT ',CONVERT(RAND() USING latin1));
2980     CALL p1();
2981 
2982     - Example #2: Item tree changes in prepared_stmt_param_fix_fields():
2983     SET NAMES utf8;
2984     CREATE PROCEDURE p1(a VARCHAR(10) CHARACTER SET utf8)
2985       EXECUTE IMMEDIATE 'SELECT ?' USING CONCAT(a, CONVERT(RAND() USING latin1));
2986     CALL p1('x');
2987   */
2988   Item_change_list_savepoint change_list_savepoint(thd);
2989   (void) stmt->execute_immediate(query.str, (uint) query.length);
2990   change_list_savepoint.rollback(thd);
2991   thd->free_items();
2992   thd->free_list= free_list_backup;
2993 
2994   stmt->lex->restore_set_statement_var();
2995   delete stmt;
2996   DBUG_VOID_RETURN;
2997 }
2998 
2999 
3000 /**
3001   Reinit prepared statement/stored procedure before execution.
3002 
3003   @todo
3004     When the new table structure is ready, then have a status bit
3005     to indicate the table is altered, and re-do the setup_*
3006     and open the tables back.
3007 */
3008 
3009 void reinit_stmt_before_use(THD *thd, LEX *lex)
3010 {
3011   SELECT_LEX *sl= lex->all_selects_list;
3012   DBUG_ENTER("reinit_stmt_before_use");
3013   Window_spec *win_spec;
3014 
3015   /*
3016     We have to update "thd" pointer in LEX, all its units and in LEX::result,
3017     since statements which belong to trigger body are associated with TABLE
3018     object and because of this can be used in different threads.
3019   */
3020   lex->thd= thd;
3021   DBUG_ASSERT(!lex->explain);
3022 
3023   if (lex->empty_field_list_on_rset)
3024   {
3025     lex->empty_field_list_on_rset= 0;
3026     lex->field_list.empty();
3027   }
3028   for (; sl; sl= sl->next_select_in_list())
3029   {
3030     if (sl->changed_elements & TOUCHED_SEL_COND)
3031     {
3032       /* remove option which was put by mysql_explain_union() */
3033       sl->options&= ~SELECT_DESCRIBE;
3034 
3035       /* see unique_table() */
3036       sl->exclude_from_table_unique_test= FALSE;
3037 
3038       /*
3039         Copy WHERE, HAVING clause pointers to avoid damaging them
3040         by optimisation
3041       */
3042       if (sl->prep_where)
3043       {
3044         /*
3045           We need this rollback because memory allocated in
3046           copy_andor_structure() will be freed
3047         */
3048         thd->change_item_tree((Item**)&sl->where,
3049                               sl->prep_where->copy_andor_structure(thd));
3050         sl->where->cleanup();
3051       }
3052       else
3053         sl->where= NULL;
3054       if (sl->prep_having)
3055       {
3056         /*
3057           We need this rollback because memory allocated in
3058           copy_andor_structure() will be freed
3059         */
3060         thd->change_item_tree((Item**)&sl->having,
3061                               sl->prep_having->copy_andor_structure(thd));
3062         sl->having->cleanup();
3063       }
3064       else
3065         sl->having= NULL;
3066       DBUG_ASSERT(sl->join == 0);
3067       ORDER *order;
3068       /* Fix GROUP list */
3069       if (sl->group_list_ptrs && sl->group_list_ptrs->size() > 0)
3070       {
3071         for (uint ix= 0; ix < sl->group_list_ptrs->size() - 1; ++ix)
3072         {
3073           order= sl->group_list_ptrs->at(ix);
3074           order->next= sl->group_list_ptrs->at(ix+1);
3075         }
3076       }
3077     }
3078     { // no harm to do it (item_ptr set on parsing)
3079       ORDER *order;
3080       for (order= sl->group_list.first; order; order= order->next)
3081       {
3082         order->item= &order->item_ptr;
3083       }
3084       /* Fix ORDER list */
3085       for (order= sl->order_list.first; order; order= order->next)
3086         order->item= &order->item_ptr;
3087       /* Fix window functions too */
3088       List_iterator<Window_spec> it(sl->window_specs);
3089 
3090       while ((win_spec= it++))
3091       {
3092         for (order= win_spec->partition_list->first; order; order= order->next)
3093           order->item= &order->item_ptr;
3094         for (order= win_spec->order_list->first; order; order= order->next)
3095           order->item= &order->item_ptr;
3096       }
3097     }
3098     if (sl->changed_elements & TOUCHED_SEL_DERIVED)
3099     {
3100 #ifdef DBUG_ASSERT_EXISTS
3101       bool res=
3102 #endif
3103         sl->handle_derived(lex, DT_REINIT);
3104       DBUG_ASSERT(res == 0);
3105     }
3106 
3107     {
3108       SELECT_LEX_UNIT *unit= sl->master_unit();
3109       unit->unclean();
3110       unit->types.empty();
3111       /* for derived tables & PS (which can't be reset by Item_subselect) */
3112       unit->reinit_exec_mechanism();
3113       unit->set_thd(thd);
3114     }
3115   }
3116 
3117   /*
3118     TODO: When the new table structure is ready, then have a status bit
3119     to indicate the table is altered, and re-do the setup_*
3120     and open the tables back.
3121   */
3122   /*
3123     NOTE: We should reset whole table list here including all tables added
3124     by prelocking algorithm (it is not a problem for substatements since
3125     they have their own table list).
3126   */
3127   for (TABLE_LIST *tables= lex->query_tables;
3128        tables;
3129        tables= tables->next_global)
3130   {
3131     tables->reinit_before_use(thd);
3132   }
3133 
3134   /* Reset MDL tickets for procedures/functions */
3135   for (Sroutine_hash_entry *rt=
3136          (Sroutine_hash_entry*)thd->lex->sroutines_list.first;
3137        rt; rt= rt->next)
3138     rt->mdl_request.ticket= NULL;
3139 
3140   /*
3141     Cleanup of the special case of DELETE t1, t2 FROM t1, t2, t3 ...
3142     (multi-delete).  We do a full clean up, although at the moment all we
3143     need to clean in the tables of MULTI-DELETE list is 'table' member.
3144   */
3145   for (TABLE_LIST *tables= lex->auxiliary_table_list.first;
3146        tables;
3147        tables= tables->next_global)
3148   {
3149     tables->reinit_before_use(thd);
3150   }
3151   lex->current_select= &lex->select_lex;
3152 
3153 
3154   if (lex->result)
3155   {
3156     lex->result->cleanup();
3157     lex->result->set_thd(thd);
3158   }
3159   lex->allow_sum_func.clear_all();
3160   lex->in_sum_func= NULL;
3161   DBUG_VOID_RETURN;
3162 }
3163 
3164 
3165 /**
3166   Clears parameters from data left from previous execution or long data.
3167 
3168   @param stmt               prepared statement for which parameters should
3169                             be reset
3170 */
3171 
3172 static void reset_stmt_params(Prepared_statement *stmt)
3173 {
3174   Item_param **item= stmt->param_array;
3175   Item_param **end= item + stmt->param_count;
3176   for (;item < end ; ++item)
3177   {
3178     (**item).reset();
3179     (**item).sync_clones();
3180   }
3181 }
3182 
3183 
3184 static void mysql_stmt_execute_common(THD *thd,
3185                                       ulong stmt_id,
3186                                       uchar *packet,
3187                                       uchar *packet_end,
3188                                       ulong cursor_flags,
3189                                       bool iteration,
3190                                       bool types);
3191 
3192 /**
3193   COM_STMT_EXECUTE handler: execute a previously prepared statement.
3194 
3195     If there are any parameters, then replace parameter markers with the
3196     data supplied from the client, and then execute the statement.
3197     This function uses binary protocol to send a possible result set
3198     to the client.
3199 
3200   @param thd                current thread
3201   @param packet_arg         parameter types and data, if any
3202   @param packet_length      packet length, including the terminator character.
3203 
3204   @return
3205     none: in case of success OK packet or a result set is sent to the
3206     client, otherwise an error message is set in THD.
3207 */
3208 
3209 void mysqld_stmt_execute(THD *thd, char *packet_arg, uint packet_length)
3210 {
3211   const uint packet_min_lenght= 9;
3212   uchar *packet= (uchar*)packet_arg; // GCC 4.0.1 workaround
3213 
3214   DBUG_ENTER("mysqld_stmt_execute");
3215 
3216   if (packet_length < packet_min_lenght)
3217   {
3218     my_error(ER_MALFORMED_PACKET, MYF(0));
3219     DBUG_VOID_RETURN;
3220   }
3221   ulong stmt_id= uint4korr(packet);
3222   ulong flags= (ulong) packet[4];
3223   uchar *packet_end= packet + packet_length;
3224 
3225   packet+= 9;                               /* stmt_id + 5 bytes of flags */
3226 
3227   mysql_stmt_execute_common(thd, stmt_id, packet, packet_end, flags, FALSE,
3228   FALSE);
3229   DBUG_VOID_RETURN;
3230 }
3231 
3232 
3233 /**
3234   COM_STMT_BULK_EXECUTE handler: execute a previously prepared statement.
3235 
3236     If there are any parameters, then replace parameter markers with the
3237     data supplied from the client, and then execute the statement.
3238     This function uses binary protocol to send a possible result set
3239     to the client.
3240 
3241   @param thd                current thread
3242   @param packet_arg         parameter types and data, if any
3243   @param packet_length      packet length, including the terminator character.
3244 
3245   @return
3246     none: in case of success OK packet or a result set is sent to the
3247     client, otherwise an error message is set in THD.
3248 */
3249 
3250 void mysqld_stmt_bulk_execute(THD *thd, char *packet_arg, uint packet_length)
3251 {
3252   uchar *packet= (uchar*)packet_arg; // GCC 4.0.1 workaround
3253   DBUG_ENTER("mysqld_stmt_execute_bulk");
3254 
3255   const uint packet_header_lenght= 4 + 2; //ID & 2 bytes of flags
3256 
3257   if (packet_length < packet_header_lenght)
3258   {
3259     my_error(ER_MALFORMED_PACKET, MYF(0));
3260     DBUG_VOID_RETURN;
3261   }
3262 
3263   ulong stmt_id= uint4korr(packet);
3264   uint flags= (uint) uint2korr(packet + 4);
3265   uchar *packet_end= packet + packet_length;
3266 
3267   if (!(thd->client_capabilities &
3268         MARIADB_CLIENT_STMT_BULK_OPERATIONS))
3269   {
3270     DBUG_PRINT("error",
3271                ("An attempt to execute bulk operation without support"));
3272     my_error(ER_UNSUPPORTED_PS, MYF(0));
3273     DBUG_VOID_RETURN;
3274   }
3275   /* Check for implemented parameters */
3276   if (flags & (~STMT_BULK_FLAG_CLIENT_SEND_TYPES))
3277   {
3278     DBUG_PRINT("error", ("unsupported bulk execute flags %x", flags));
3279     my_error(ER_UNSUPPORTED_PS, MYF(0));
3280     DBUG_VOID_RETURN;
3281   }
3282 
3283   /* stmt id and two bytes of flags */
3284   packet+= packet_header_lenght;
3285   mysql_stmt_execute_common(thd, stmt_id, packet, packet_end, 0, TRUE,
3286                             (flags & STMT_BULK_FLAG_CLIENT_SEND_TYPES));
3287   DBUG_VOID_RETURN;
3288 }
3289 
3290 /**
3291   Additional packet checks for direct execution
3292 
3293   @param thd             THD handle
3294   @param stmt            prepared statement being directly executed
3295   @param paket           packet with parameters to bind
3296   @param packet_end      pointer to the byte after parameters end
3297   @param bulk_op         is it bulk operation
3298   @param direct_exec     is it direct execution
3299   @param read_bytes      need to read types (only with bulk_op)
3300 
3301   @retval true  this parameter is wrong
3302   @retval false this parameter is OK
3303 */
3304 
3305 static bool
3306 stmt_execute_packet_sanity_check(Prepared_statement *stmt,
3307                                  uchar *packet, uchar *packet_end,
3308                                  bool bulk_op, bool direct_exec,
3309                                  bool read_types)
3310 {
3311 
3312   DBUG_ASSERT((!read_types) || (read_types && bulk_op));
3313   if (stmt->param_count > 0)
3314   {
3315     uint packet_length= static_cast<uint>(packet_end - packet);
3316     uint null_bitmap_bytes= (bulk_op ? 0 : (stmt->param_count + 7)/8);
3317     uint min_len_for_param_count = null_bitmap_bytes
3318                                  + (bulk_op ? 0 : 1); /* sent types byte */
3319 
3320     if (!bulk_op && packet_length >= min_len_for_param_count)
3321     {
3322       if ((read_types= packet[null_bitmap_bytes]))
3323       {
3324         /*
3325           Should be 0 or 1. If the byte is not 1, that could mean,
3326           e.g. that we read incorrect byte due to incorrect number
3327           of sent parameters for direct execution (i.e. null bitmap
3328           is shorter or longer, than it should be)
3329         */
3330         if (packet[null_bitmap_bytes] != '\1')
3331         {
3332           return true;
3333         }
3334       }
3335     }
3336 
3337     if (read_types)
3338     {
3339       /* 2 bytes per parameter of the type and flags */
3340       min_len_for_param_count+= 2*stmt->param_count;
3341     }
3342     else
3343     {
3344       /*
3345         If types are not sent, there is nothing to do here.
3346         But for direct execution types should always be sent
3347       */
3348       return direct_exec;
3349     }
3350 
3351     /*
3352       If true, the packet is guaranteed too short for the number of
3353       parameters in the PS
3354     */
3355     return (packet_length < min_len_for_param_count);
3356   }
3357   else
3358   {
3359     /*
3360       If there is no parameters, this should be normally already end
3361       of the packet, but it is not a problem if something left (popular
3362       mistake in protocol implementation) because we will not read anymore
3363       from the buffer.
3364     */
3365     return false;
3366   }
3367   return false;
3368 }
3369 
3370 
3371 /**
3372   Common part of prepared statement execution
3373 
3374   @param thd             THD handle
3375   @param stmt_id         id of the prepared statement
3376   @param paket           packet with parameters to bind
3377   @param packet_end      pointer to the byte after parameters end
3378   @param cursor_flags    cursor flags
3379   @param bulk_op         id it bulk operation
3380   @param read_types      flag say that types muast been read
3381 */
3382 
3383 static void mysql_stmt_execute_common(THD *thd,
3384                                       ulong stmt_id,
3385                                       uchar *packet,
3386                                       uchar *packet_end,
3387                                       ulong cursor_flags,
3388                                       bool bulk_op,
3389                                       bool read_types)
3390 {
3391   /* Query text for binary, general or slow log, if any of them is open */
3392   String expanded_query;
3393   Prepared_statement *stmt;
3394   Protocol *save_protocol= thd->protocol;
3395   bool open_cursor;
3396   DBUG_ENTER("mysqld_stmt_execute_common");
3397   DBUG_ASSERT((!read_types) || (read_types && bulk_op));
3398 
3399   /* First of all clear possible warnings from the previous command */
3400   thd->reset_for_next_command();
3401 
3402   if (!(stmt= find_prepared_statement(thd, stmt_id)))
3403   {
3404     char llbuf[22];
3405     my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
3406              llstr(stmt_id, llbuf), "mysqld_stmt_execute");
3407     DBUG_VOID_RETURN;
3408   }
3409 
3410   /*
3411     In case of direct execution application decides how many parameters
3412     to send.
3413 
3414     Thus extra checks are required to prevent crashes caused by incorrect
3415     interpretation of the packet data. Plus there can be always a broken
3416     evil client.
3417   */
3418   if (stmt_execute_packet_sanity_check(stmt, packet, packet_end, bulk_op,
3419                                        stmt_id == LAST_STMT_ID, read_types))
3420   {
3421     my_error(ER_MALFORMED_PACKET, MYF(0));
3422     DBUG_VOID_RETURN;
3423   }
3424 
3425   stmt->read_types= read_types;
3426 
3427 #if defined(ENABLED_PROFILING)
3428   thd->profiling.set_query_source(stmt->query(), stmt->query_length());
3429 #endif
3430   DBUG_PRINT("exec_query", ("%s", stmt->query()));
3431   DBUG_PRINT("info",("stmt: %p bulk_op %d", stmt, bulk_op));
3432 
3433   open_cursor= MY_TEST(cursor_flags & (ulong) CURSOR_TYPE_READ_ONLY);
3434 
3435   thd->protocol= &thd->protocol_binary;
3436   if (!bulk_op)
3437     stmt->execute_loop(&expanded_query, open_cursor, packet, packet_end);
3438   else
3439     stmt->execute_bulk_loop(&expanded_query, open_cursor, packet, packet_end);
3440   thd->protocol= save_protocol;
3441 
3442   sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
3443   sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
3444   sp_cache_enforce_limit(thd->sp_package_spec_cache, stored_program_cache_size);
3445   sp_cache_enforce_limit(thd->sp_package_body_cache, stored_program_cache_size);
3446 
3447   /* Close connection socket; for use with client testing (Bug#43560). */
3448   DBUG_EXECUTE_IF("close_conn_after_stmt_execute", vio_shutdown(thd->net.vio,SHUT_RD););
3449 
3450   DBUG_VOID_RETURN;
3451 }
3452 
3453 
3454 /**
3455   SQLCOM_EXECUTE implementation.
3456 
3457     Execute prepared statement using parameter values from
3458     lex->prepared_stmt_params and send result to the client using
3459     text protocol. This is called from mysql_execute_command and
3460     therefore should behave like an ordinary query (e.g. not change
3461     global THD data, such as warning count, server status, etc).
3462     This function uses text protocol to send a possible result set.
3463 
3464   @param thd                thread handle
3465 
3466   @return
3467     none: in case of success, OK (or result set) packet is sent to the
3468     client, otherwise an error is set in THD
3469 */
3470 
3471 void mysql_sql_stmt_execute(THD *thd)
3472 {
3473   LEX *lex= thd->lex;
3474   Prepared_statement *stmt;
3475   LEX_CSTRING *name= &lex->prepared_stmt_name;
3476   /* Query text for binary, general or slow log, if any of them is open */
3477   String expanded_query;
3478   DBUG_ENTER("mysql_sql_stmt_execute");
3479   DBUG_PRINT("info", ("EXECUTE: %.*s", (int) name->length, name->str));
3480 
3481   if (!(stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
3482   {
3483     my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
3484              static_cast<int>(name->length), name->str, "EXECUTE");
3485     DBUG_VOID_RETURN;
3486   }
3487 
3488   if (stmt->param_count != lex->prepared_stmt_params.elements)
3489   {
3490     my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
3491     DBUG_VOID_RETURN;
3492   }
3493 
3494   DBUG_PRINT("info",("stmt: %p", stmt));
3495 
3496   if (lex->prepared_stmt_params_fix_fields(thd))
3497     DBUG_VOID_RETURN;
3498 
3499   /*
3500     thd->free_list can already have some Items.
3501 
3502     Example queries:
3503       - SET STATEMENT var=expr FOR EXECUTE stmt;
3504       - EXECUTE stmt USING expr;
3505 
3506     E.g. for a query like this:
3507       PREPARE stmt FROM 'INSERT INTO t1 VALUES (@@max_sort_length)';
3508       SET STATEMENT max_sort_length=2048 FOR EXECUTE stmt;
3509     thd->free_list contains a pointer to Item_int corresponding to 2048.
3510 
3511     If Prepared_statement::execute() notices that the table metadata for "t1"
3512     has changed since PREPARE, it returns an error asking the calling
3513     Prepared_statement::execute_loop() to re-prepare the statement.
3514     Before returning the error, Prepared_statement::execute()
3515     calls Prepared_statement::cleanup_stmt(),
3516     which calls thd->cleanup_after_query(),
3517     which calls Query_arena::free_items().
3518 
3519     We hide "external" Items, e.g. those created while parsing the
3520     "SET STATEMENT" or "USING" parts of the query,
3521     so they don't get freed in case of re-prepare.
3522     See MDEV-10702 Crash in SET STATEMENT FOR EXECUTE
3523   */
3524   Item *free_list_backup= thd->free_list;
3525   thd->free_list= NULL; // Hide the external (e.g. "SET STATEMENT") Items
3526   /*
3527     Make sure we call Prepared_statement::execute_loop() with an empty
3528     THD::change_list. It can be non-empty because the above
3529     LEX::prepared_stmt_params_fix_fields() calls fix_fields() for
3530     the PS parameter Items and can do some Item tree changes,
3531     e.g. on character set conversion:
3532 
3533     SET NAMES utf8;
3534     DELIMITER $$
3535     CREATE PROCEDURE p1(a VARCHAR(10) CHARACTER SET utf8)
3536     BEGIN
3537       PREPARE stmt FROM 'SELECT ?';
3538       EXECUTE stmt USING CONCAT(a, CONVERT(RAND() USING latin1));
3539     END;
3540     $$
3541     DELIMITER ;
3542     CALL p1('x');
3543   */
3544   Item_change_list_savepoint change_list_savepoint(thd);
3545   (void) stmt->execute_loop(&expanded_query, FALSE, NULL, NULL);
3546   change_list_savepoint.rollback(thd);
3547   thd->free_items();    // Free items created by execute_loop()
3548   /*
3549     Now restore the "external" (e.g. "SET STATEMENT") Item list.
3550     It will be freed normaly in THD::cleanup_after_query().
3551   */
3552   thd->free_list= free_list_backup;
3553 
3554   stmt->lex->restore_set_statement_var();
3555   DBUG_VOID_RETURN;
3556 }
3557 
3558 
3559 /**
3560   COM_STMT_FETCH handler: fetches requested amount of rows from cursor.
3561 
3562   @param thd                Thread handle
3563   @param packet             Packet from client (with stmt_id & num_rows)
3564   @param packet_length      Length of packet
3565 */
3566 
3567 void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length)
3568 {
3569   /* assume there is always place for 8-16 bytes */
3570   ulong stmt_id= uint4korr(packet);
3571   ulong num_rows= uint4korr(packet+4);
3572   Prepared_statement *stmt;
3573   Statement stmt_backup;
3574   Server_side_cursor *cursor;
3575   DBUG_ENTER("mysqld_stmt_fetch");
3576 
3577   /* First of all clear possible warnings from the previous command */
3578   thd->reset_for_next_command();
3579 
3580   status_var_increment(thd->status_var.com_stmt_fetch);
3581   if (!(stmt= find_prepared_statement(thd, stmt_id)))
3582   {
3583     char llbuf[22];
3584     my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
3585              llstr(stmt_id, llbuf), "mysqld_stmt_fetch");
3586     DBUG_VOID_RETURN;
3587   }
3588 
3589   cursor= stmt->cursor;
3590   if (!cursor)
3591   {
3592     my_error(ER_STMT_HAS_NO_OPEN_CURSOR, MYF(0), stmt_id);
3593     DBUG_VOID_RETURN;
3594   }
3595 
3596   thd->stmt_arena= stmt;
3597   thd->set_n_backup_statement(stmt, &stmt_backup);
3598 
3599   cursor->fetch(num_rows);
3600 
3601   if (!cursor->is_open())
3602   {
3603     stmt->close_cursor();
3604     reset_stmt_params(stmt);
3605   }
3606 
3607   thd->restore_backup_statement(stmt, &stmt_backup);
3608   thd->stmt_arena= thd;
3609 
3610   DBUG_VOID_RETURN;
3611 }
3612 
3613 
3614 /**
3615   Reset a prepared statement in case there was a recoverable error.
3616 
3617     This function resets statement to the state it was right after prepare.
3618     It can be used to:
3619     - clear an error happened during mysqld_stmt_send_long_data
3620     - cancel long data stream for all placeholders without
3621       having to call mysqld_stmt_execute.
3622     - close an open cursor
3623     Sends 'OK' packet in case of success (statement was reset)
3624     or 'ERROR' packet (unrecoverable error/statement not found/etc).
3625 
3626   @param thd                Thread handle
3627   @param packet             Packet with stmt id
3628 */
3629 
3630 void mysqld_stmt_reset(THD *thd, char *packet)
3631 {
3632   /* There is always space for 4 bytes in buffer */
3633   ulong stmt_id= uint4korr(packet);
3634   Prepared_statement *stmt;
3635   DBUG_ENTER("mysqld_stmt_reset");
3636 
3637   /* First of all clear possible warnings from the previous command */
3638   thd->reset_for_next_command();
3639 
3640   status_var_increment(thd->status_var.com_stmt_reset);
3641   if (!(stmt= find_prepared_statement(thd, stmt_id)))
3642   {
3643     char llbuf[22];
3644     my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
3645              llstr(stmt_id, llbuf), "mysqld_stmt_reset");
3646     DBUG_VOID_RETURN;
3647   }
3648 
3649   stmt->close_cursor();
3650 
3651   /*
3652     Clear parameters from data which could be set by
3653     mysqld_stmt_send_long_data() call.
3654   */
3655   reset_stmt_params(stmt);
3656 
3657   stmt->state= Query_arena::STMT_PREPARED;
3658 
3659   general_log_print(thd, thd->get_command(), NullS);
3660 
3661   my_ok(thd);
3662 
3663   DBUG_VOID_RETURN;
3664 }
3665 
3666 
3667 /**
3668   Delete a prepared statement from memory.
3669 
3670   @note
3671     we don't send any reply to this command.
3672 */
3673 
3674 void mysqld_stmt_close(THD *thd, char *packet)
3675 {
3676   /* There is always space for 4 bytes in packet buffer */
3677   ulong stmt_id= uint4korr(packet);
3678   Prepared_statement *stmt;
3679   DBUG_ENTER("mysqld_stmt_close");
3680 
3681   thd->get_stmt_da()->disable_status();
3682 
3683   if (!(stmt= find_prepared_statement(thd, stmt_id)))
3684     DBUG_VOID_RETURN;
3685 
3686   /*
3687     The only way currently a statement can be deallocated when it's
3688     in use is from within Dynamic SQL.
3689   */
3690   DBUG_ASSERT(! stmt->is_in_use());
3691   stmt->deallocate();
3692   general_log_print(thd, thd->get_command(), NullS);
3693 
3694   if (thd->last_stmt == stmt)
3695     thd->clear_last_stmt();
3696 
3697   DBUG_VOID_RETURN;
3698 }
3699 
3700 
3701 /**
3702   SQLCOM_DEALLOCATE implementation.
3703 
3704     Close an SQL prepared statement. As this can be called from Dynamic
3705     SQL, we should be careful to not close a statement that is currently
3706     being executed.
3707 
3708   @return
3709     none: OK packet is sent in case of success, otherwise an error
3710     message is set in THD
3711 */
3712 
3713 void mysql_sql_stmt_close(THD *thd)
3714 {
3715   Prepared_statement* stmt;
3716   LEX_CSTRING *name= &thd->lex->prepared_stmt_name;
3717   DBUG_PRINT("info", ("DEALLOCATE PREPARE: %.*s", (int) name->length,
3718                       name->str));
3719 
3720   if (! (stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
3721     my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
3722              static_cast<int>(name->length), name->str, "DEALLOCATE PREPARE");
3723   else if (stmt->is_in_use())
3724     my_error(ER_PS_NO_RECURSION, MYF(0));
3725   else
3726   {
3727     stmt->deallocate();
3728     SESSION_TRACKER_CHANGED(thd, SESSION_STATE_CHANGE_TRACKER, NULL);
3729     my_ok(thd);
3730   }
3731 }
3732 
3733 
3734 /**
3735   Handle long data in pieces from client.
3736 
3737     Get a part of a long data. To make the protocol efficient, we are
3738     not sending any return packets here. If something goes wrong, then
3739     we will send the error on 'execute' We assume that the client takes
3740     care of checking that all parts are sent to the server. (No checking
3741     that we get a 'end of column' in the server is performed).
3742 
3743   @param thd                Thread handle
3744   @param packet             String to append
3745   @param packet_length      Length of string (including end \\0)
3746 */
3747 
3748 void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
3749 {
3750   ulong stmt_id;
3751   uint param_number;
3752   Prepared_statement *stmt;
3753   Item_param *param;
3754 #ifndef EMBEDDED_LIBRARY
3755   char *packet_end= packet + packet_length;
3756 #endif
3757   DBUG_ENTER("mysql_stmt_get_longdata");
3758 
3759   status_var_increment(thd->status_var.com_stmt_send_long_data);
3760 
3761   thd->get_stmt_da()->disable_status();
3762 #ifndef EMBEDDED_LIBRARY
3763   /* Minimal size of long data packet is 6 bytes */
3764   if (packet_length < MYSQL_LONG_DATA_HEADER)
3765     DBUG_VOID_RETURN;
3766 #endif
3767 
3768   stmt_id= uint4korr(packet);
3769   packet+= 4;
3770 
3771   if (!(stmt=find_prepared_statement(thd, stmt_id)))
3772     DBUG_VOID_RETURN;
3773 
3774   param_number= uint2korr(packet);
3775   packet+= 2;
3776 #ifndef EMBEDDED_LIBRARY
3777   if (param_number >= stmt->param_count)
3778   {
3779     /* Error will be sent in execute call */
3780     stmt->state= Query_arena::STMT_ERROR;
3781     stmt->last_errno= ER_WRONG_ARGUMENTS;
3782     sprintf(stmt->last_error, ER_THD(thd, ER_WRONG_ARGUMENTS),
3783             "mysqld_stmt_send_long_data");
3784     DBUG_VOID_RETURN;
3785   }
3786 #endif
3787 
3788   param= stmt->param_array[param_number];
3789 
3790   Diagnostics_area new_stmt_da(thd->query_id, false, true);
3791   Diagnostics_area *save_stmt_da= thd->get_stmt_da();
3792 
3793   thd->set_stmt_da(&new_stmt_da);
3794 
3795 #ifndef EMBEDDED_LIBRARY
3796   param->set_longdata(packet, (ulong) (packet_end - packet));
3797 #else
3798   param->set_longdata(thd->extra_data, thd->extra_length);
3799 #endif
3800   if (unlikely(thd->get_stmt_da()->is_error()))
3801   {
3802     stmt->state= Query_arena::STMT_ERROR;
3803     stmt->last_errno= thd->get_stmt_da()->sql_errno();
3804     strmake_buf(stmt->last_error, thd->get_stmt_da()->message());
3805   }
3806   thd->set_stmt_da(save_stmt_da);
3807 
3808   general_log_print(thd, thd->get_command(), NullS);
3809 
3810   DBUG_VOID_RETURN;
3811 }
3812 
3813 
3814 /***************************************************************************
3815  Select_fetch_protocol_binary
3816 ****************************************************************************/
3817 
3818 Select_fetch_protocol_binary::Select_fetch_protocol_binary(THD *thd_arg):
3819   select_send(thd_arg), protocol(thd_arg)
3820 {}
3821 
3822 bool Select_fetch_protocol_binary::send_result_set_metadata(List<Item> &list, uint flags)
3823 {
3824   bool rc;
3825   Protocol *save_protocol= thd->protocol;
3826 
3827   /*
3828     Protocol::send_result_set_metadata caches the information about column types:
3829     this information is later used to send data. Therefore, the same
3830     dedicated Protocol object must be used for all operations with
3831     a cursor.
3832   */
3833   thd->protocol= &protocol;
3834   rc= select_send::send_result_set_metadata(list, flags);
3835   thd->protocol= save_protocol;
3836 
3837   return rc;
3838 }
3839 
3840 bool Select_fetch_protocol_binary::send_eof()
3841 {
3842   /*
3843     Don't send EOF if we're in error condition (which implies we've already
3844     sent or are sending an error)
3845   */
3846   if (unlikely(thd->is_error()))
3847     return true;
3848 
3849   ::my_eof(thd);
3850   return false;
3851 }
3852 
3853 
3854 int
3855 Select_fetch_protocol_binary::send_data(List<Item> &fields)
3856 {
3857   Protocol *save_protocol= thd->protocol;
3858   int rc;
3859 
3860   thd->protocol= &protocol;
3861   rc= select_send::send_data(fields);
3862   thd->protocol= save_protocol;
3863   return rc;
3864 }
3865 
3866 /*******************************************************************
3867 * Reprepare_observer
3868 *******************************************************************/
3869 /** Push an error to the error stack and return TRUE for now. */
3870 
3871 bool
3872 Reprepare_observer::report_error(THD *thd)
3873 {
3874   /*
3875     This 'error' is purely internal to the server:
3876     - No exception handler is invoked,
3877     - No condition is added in the condition area (warn_list).
3878     The diagnostics area is set to an error status to enforce
3879     that this thread execution stops and returns to the caller,
3880     backtracking all the way to Prepared_statement::execute_loop().
3881   */
3882   thd->get_stmt_da()->set_error_status(ER_NEED_REPREPARE);
3883   m_invalidated= TRUE;
3884 
3885   return TRUE;
3886 }
3887 
3888 
3889 /*******************************************************************
3890 * Server_runnable
3891 *******************************************************************/
3892 
3893 Server_runnable::~Server_runnable()
3894 {
3895 }
3896 
3897 ///////////////////////////////////////////////////////////////////////////
3898 
3899 Execute_sql_statement::
3900 Execute_sql_statement(LEX_STRING sql_text)
3901   :m_sql_text(sql_text)
3902 {}
3903 
3904 
3905 /**
3906   Parse and execute a statement. Does not prepare the query.
3907 
3908   Allows to execute a statement from within another statement.
3909   The main property of the implementation is that it does not
3910   affect the environment -- i.e. you  can run many
3911   executions without having to cleanup/reset THD in between.
3912 */
3913 
3914 bool
3915 Execute_sql_statement::execute_server_code(THD *thd)
3916 {
3917   PSI_statement_locker *parent_locker;
3918   bool error;
3919 
3920   if (alloc_query(thd, m_sql_text.str, m_sql_text.length))
3921     return TRUE;
3922 
3923   Parser_state parser_state;
3924   if (parser_state.init(thd, thd->query(), thd->query_length()))
3925     return TRUE;
3926 
3927   parser_state.m_lip.multi_statements= FALSE;
3928   lex_start(thd);
3929 
3930   error= parse_sql(thd, &parser_state, NULL) || thd->is_error();
3931 
3932   if (unlikely(error))
3933     goto end;
3934 
3935   thd->lex->set_trg_event_type_for_tables();
3936 
3937   parent_locker= thd->m_statement_psi;
3938   thd->m_statement_psi= NULL;
3939   error= mysql_execute_command(thd);
3940   thd->m_statement_psi= parent_locker;
3941 
3942   /* report error issued during command execution */
3943   if (likely(error == 0) && thd->spcont == NULL)
3944     general_log_write(thd, COM_STMT_EXECUTE,
3945                       thd->query(), thd->query_length());
3946 
3947 end:
3948   thd->lex->restore_set_statement_var();
3949   lex_end(thd->lex);
3950 
3951   return error;
3952 }
3953 
3954 /***************************************************************************
3955  Prepared_statement
3956 ****************************************************************************/
3957 
3958 Prepared_statement::Prepared_statement(THD *thd_arg)
3959   :Statement(NULL, &main_mem_root,
3960              STMT_INITIALIZED,
3961              ((++thd_arg->statement_id_counter) & STMT_ID_MASK)),
3962   thd(thd_arg),
3963   result(thd_arg),
3964   param_array(0),
3965   cursor(0),
3966   packet(0),
3967   packet_end(0),
3968   param_count(0),
3969   last_errno(0),
3970   flags((uint) IS_IN_USE),
3971   iterations(0),
3972   start_param(0),
3973   read_types(0),
3974   m_sql_mode(thd->variables.sql_mode)
3975 {
3976   init_sql_alloc(&main_mem_root, "Prepared_statement",
3977                  thd_arg->variables.query_alloc_block_size,
3978                  thd_arg->variables.query_prealloc_size,
3979                  MYF(MY_THREAD_SPECIFIC));
3980   *last_error= '\0';
3981 }
3982 
3983 
3984 void Prepared_statement::setup_set_params()
3985 {
3986   /*
3987     Note: BUG#25843 applies here too (query cache lookup uses thd->db, not
3988     db from "prepare" time).
3989   */
3990   if (query_cache_maybe_disabled(thd)) // we won't expand the query
3991     lex->safe_to_cache_query= FALSE;   // so don't cache it at Execution
3992 
3993   /*
3994     Decide if we have to expand the query (because we must write it to logs or
3995     because we want to look it up in the query cache) or not.
3996   */
3997   bool replace_params_with_values= false;
3998   // binlog
3999   replace_params_with_values|= mysql_bin_log.is_open() && is_update_query(lex->sql_command);
4000   // general or slow log
4001   replace_params_with_values|= opt_log || thd->variables.sql_log_slow;
4002   // query cache
4003   replace_params_with_values|= query_cache_is_cacheable_query(lex);
4004   // but never for compound statements
4005   replace_params_with_values&= lex->sql_command != SQLCOM_COMPOUND;
4006 
4007   if (replace_params_with_values)
4008   {
4009     set_params_from_actual_params= insert_params_from_actual_params_with_log;
4010 #ifndef EMBEDDED_LIBRARY
4011     set_params= insert_params_with_log;
4012     set_bulk_params= insert_bulk_params; // RBR is on for bulk operation
4013 #else
4014     //TODO: add bulk support for bulk parameters
4015     set_params_data= emb_insert_params_with_log;
4016 #endif
4017   }
4018   else
4019   {
4020     set_params_from_actual_params= insert_params_from_actual_params;
4021 #ifndef EMBEDDED_LIBRARY
4022     set_params= insert_params;
4023     set_bulk_params= insert_bulk_params;
4024 #else
4025     //TODO: add bulk support for bulk parameters
4026     set_params_data= emb_insert_params;
4027 #endif
4028   }
4029 }
4030 
4031 
4032 /**
4033   Destroy this prepared statement, cleaning up all used memory
4034   and resources.
4035 
4036   This is called from ::deallocate() to handle COM_STMT_CLOSE and
4037   DEALLOCATE PREPARE or when THD ends and all prepared statements are freed.
4038 */
4039 
4040 Prepared_statement::~Prepared_statement()
4041 {
4042   DBUG_ENTER("Prepared_statement::~Prepared_statement");
4043   DBUG_PRINT("enter",("stmt: %p  cursor: %p",
4044                       this, cursor));
4045   delete cursor;
4046   /*
4047     We have to call free on the items even if cleanup is called as some items,
4048     like Item_param, don't free everything until free_items()
4049   */
4050   free_items();
4051   if (lex)
4052   {
4053     sp_head::destroy(lex->sphead);
4054     delete lex->result;
4055     delete (st_lex_local *) lex;
4056   }
4057   free_root(&main_mem_root, MYF(0));
4058   DBUG_VOID_RETURN;
4059 }
4060 
4061 
4062 Query_arena::Type Prepared_statement::type() const
4063 {
4064   return PREPARED_STATEMENT;
4065 }
4066 
4067 
4068 void Prepared_statement::cleanup_stmt()
4069 {
4070   DBUG_ENTER("Prepared_statement::cleanup_stmt");
4071   DBUG_PRINT("enter",("stmt: %p", this));
4072   lex->restore_set_statement_var();
4073   thd->rollback_item_tree_changes();
4074   cleanup_items(free_list);
4075   thd->cleanup_after_query();
4076 
4077   DBUG_VOID_RETURN;
4078 }
4079 
4080 
4081 bool Prepared_statement::set_name(LEX_CSTRING *name_arg)
4082 {
4083   name.length= name_arg->length;
4084   name.str= (char*) memdup_root(mem_root, name_arg->str, name_arg->length);
4085   return name.str == 0;
4086 }
4087 
4088 
4089 /**
4090   Remember the current database.
4091 
4092   We must reset/restore the current database during execution of
4093   a prepared statement since it affects execution environment:
4094   privileges, @@character_set_database, and other.
4095 
4096   @return 1 if out of memory.
4097 */
4098 
4099 bool
4100 Prepared_statement::set_db(const LEX_CSTRING *db_arg)
4101 {
4102   /* Remember the current database. */
4103   if (db_arg->length)
4104   {
4105     if (!(db.str= this->strmake(db_arg->str, db_arg->length)))
4106       return 1;
4107     db.length= db_arg->length;
4108   }
4109   else
4110     db= null_clex_str;
4111   return 0;
4112 }
4113 
4114 /**************************************************************************
4115   Common parts of mysql_[sql]_stmt_prepare, mysql_[sql]_stmt_execute.
4116   Essentially, these functions do all the magic of preparing/executing
4117   a statement, leaving network communication, input data handling and
4118   global THD state management to the caller.
4119 ***************************************************************************/
4120 
4121 /**
4122   Parse statement text, validate the statement, and prepare it for execution.
4123 
4124     You should not change global THD state in this function, if at all
4125     possible: it may be called from any context, e.g. when executing
4126     a COM_* command, and SQLCOM_* command, or a stored procedure.
4127 
4128   @param packet             statement text
4129   @param packet_len
4130 
4131   @note
4132     Precondition:
4133     The caller must ensure that thd->change_list and thd->free_list
4134     is empty: this function will not back them up but will free
4135     in the end of its execution.
4136 
4137   @note
4138     Postcondition:
4139     thd->mem_root contains unused memory allocated during validation.
4140 */
4141 
4142 bool Prepared_statement::prepare(const char *packet, uint packet_len)
4143 {
4144   bool error;
4145   Statement stmt_backup;
4146   Query_arena *old_stmt_arena;
4147   DBUG_ENTER("Prepared_statement::prepare");
4148   DBUG_ASSERT(m_sql_mode == thd->variables.sql_mode);
4149   /*
4150     If this is an SQLCOM_PREPARE, we also increase Com_prepare_sql.
4151     However, it seems handy if com_stmt_prepare is increased always,
4152     no matter what kind of prepare is processed.
4153   */
4154   status_var_increment(thd->status_var.com_stmt_prepare);
4155 
4156   if (! (lex= new (mem_root) st_lex_local))
4157     DBUG_RETURN(TRUE);
4158   lex->stmt_lex= lex;
4159 
4160   if (set_db(&thd->db))
4161     DBUG_RETURN(TRUE);
4162 
4163   /*
4164     alloc_query() uses thd->mem_root && thd->query, so we should call
4165     both of backup_statement() and backup_query_arena() here.
4166   */
4167   thd->set_n_backup_statement(this, &stmt_backup);
4168   thd->set_n_backup_active_arena(this, &stmt_backup);
4169 
4170   if (alloc_query(thd, packet, packet_len))
4171   {
4172     thd->restore_backup_statement(this, &stmt_backup);
4173     thd->restore_active_arena(this, &stmt_backup);
4174     DBUG_RETURN(TRUE);
4175   }
4176 
4177   old_stmt_arena= thd->stmt_arena;
4178   thd->stmt_arena= this;
4179 
4180   Parser_state parser_state;
4181   if (parser_state.init(thd, thd->query(), thd->query_length()))
4182   {
4183     thd->restore_backup_statement(this, &stmt_backup);
4184     thd->restore_active_arena(this, &stmt_backup);
4185     thd->stmt_arena= old_stmt_arena;
4186     DBUG_RETURN(TRUE);
4187   }
4188 
4189   parser_state.m_lip.stmt_prepare_mode= TRUE;
4190   parser_state.m_lip.multi_statements= FALSE;
4191 
4192   lex_start(thd);
4193   lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_PREPARE;
4194 
4195   error= (parse_sql(thd, & parser_state, NULL) ||
4196           thd->is_error() ||
4197           init_param_array(this));
4198 
4199   lex->set_trg_event_type_for_tables();
4200 
4201   /*
4202     While doing context analysis of the query (in check_prepared_statement)
4203     we allocate a lot of additional memory: for open tables, JOINs, derived
4204     tables, etc.  Let's save a snapshot of current parse tree to the
4205     statement and restore original THD. In cases when some tree
4206     transformation can be reused on execute, we set again thd->mem_root from
4207     stmt->mem_root (see setup_wild for one place where we do that).
4208   */
4209   thd->restore_active_arena(this, &stmt_backup);
4210 
4211   /*
4212     If called from a stored procedure, ensure that we won't rollback
4213     external changes when cleaning up after validation.
4214   */
4215   DBUG_ASSERT(thd->Item_change_list::is_empty());
4216 
4217   /*
4218     Marker used to release metadata locks acquired while the prepared
4219     statement is being checked.
4220   */
4221   MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
4222 
4223   /*
4224     Set variables specified by
4225       SET STATEMENT var1=value1 [, var2=value2, ...] FOR <statement>
4226     clause for duration of prepare phase. Original values of variable
4227     listed in the SET STATEMENT clause is restored right after return
4228     from the function check_prepared_statement()
4229   */
4230   if (likely(error == 0))
4231     error= run_set_statement_if_requested(thd, lex);
4232 
4233   /*
4234    The only case where we should have items in the thd->free_list is
4235    after stmt->set_params_from_vars(), which may in some cases create
4236    Item_null objects.
4237   */
4238 
4239   if (likely(error == 0))
4240     error= check_prepared_statement(this);
4241 
4242   if (unlikely(error))
4243   {
4244     /*
4245       let the following code know we're not in PS anymore,
4246       the won't be any EXECUTE, so we need a full cleanup
4247     */
4248     lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_PREPARE;
4249   }
4250 
4251   /*
4252     Restore original values of variables modified on handling
4253     SET STATEMENT clause.
4254   */
4255   error|= thd->lex->restore_set_statement_var();
4256 
4257   /* The order is important */
4258   lex->unit.cleanup();
4259 
4260   /* No need to commit statement transaction, it's not started. */
4261   DBUG_ASSERT(thd->transaction.stmt.is_empty());
4262 
4263   close_thread_tables(thd);
4264   thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
4265 
4266   /*
4267     Transaction rollback was requested since MDL deadlock was discovered
4268     while trying to open tables. Rollback transaction in all storage
4269     engines including binary log and release all locks.
4270 
4271     Once dynamic SQL is allowed as substatements the below if-statement
4272     has to be adjusted to not do rollback in substatement.
4273   */
4274   DBUG_ASSERT(! thd->in_sub_stmt);
4275   if (thd->transaction_rollback_request)
4276   {
4277     trans_rollback_implicit(thd);
4278     thd->release_transactional_locks();
4279   }
4280 
4281   /* Preserve locked plugins for SET */
4282   if (lex->sql_command != SQLCOM_SET_OPTION)
4283     lex_unlock_plugins(lex);
4284 
4285   cleanup_stmt();
4286   thd->restore_backup_statement(this, &stmt_backup);
4287   thd->stmt_arena= old_stmt_arena;
4288 
4289   if (likely(error == 0))
4290   {
4291     setup_set_params();
4292     lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_PREPARE;
4293     state= Query_arena::STMT_PREPARED;
4294     flags&= ~ (uint) IS_IN_USE;
4295 
4296     /*
4297       Log COM_EXECUTE to the general log. Note, that in case of SQL
4298       prepared statements this causes two records to be output:
4299 
4300       Query       PREPARE stmt from @user_variable
4301       Prepare     <statement SQL text>
4302 
4303       This is considered user-friendly, since in the
4304       second log entry we output the actual statement text.
4305 
4306       Do not print anything if this is an SQL prepared statement and
4307       we're inside a stored procedure (also called Dynamic SQL) --
4308       sub-statements inside stored procedures are not logged into
4309       the general log.
4310     */
4311     if (thd->spcont == NULL)
4312       general_log_write(thd, COM_STMT_PREPARE, query(), query_length());
4313   }
4314   DBUG_RETURN(error);
4315 }
4316 
4317 
4318 /**
4319   Assign parameter values either from variables, in case of SQL PS
4320   or from the execute packet.
4321 
4322   @param expanded_query  a container with the original SQL statement.
4323                          '?' placeholders will be replaced with
4324                          their values in case of success.
4325                          The result is used for logging and replication
4326   @param packet          pointer to execute packet.
4327                          NULL in case of SQL PS
4328   @param packet_end      end of the packet. NULL in case of SQL PS
4329 
4330   @todo Use a paremeter source class family instead of 'if's, and
4331   support stored procedure variables.
4332 
4333   @retval TRUE an error occurred when assigning a parameter (likely
4334           a conversion error or out of memory, or malformed packet)
4335   @retval FALSE success
4336 */
4337 
4338 bool
4339 Prepared_statement::set_parameters(String *expanded_query,
4340                                    uchar *packet, uchar *packet_end)
4341 {
4342   bool is_sql_ps= packet == NULL;
4343   bool res= FALSE;
4344 
4345   if (is_sql_ps)
4346   {
4347     /* SQL prepared statement */
4348     res= set_params_from_actual_params(this, thd->lex->prepared_stmt_params,
4349                                        expanded_query);
4350   }
4351   else if (param_count)
4352   {
4353 #ifndef EMBEDDED_LIBRARY
4354     uchar *null_array= packet;
4355     res= (setup_conversion_functions(this, &packet) ||
4356           set_params(this, null_array, packet, packet_end, expanded_query));
4357 #else
4358     /*
4359       In embedded library we re-install conversion routines each time
4360       we set parameters, and also we don't need to parse packet.
4361       So we do it in one function.
4362     */
4363     res= set_params_data(this, expanded_query);
4364 #endif
4365   }
4366   if (res)
4367   {
4368     my_error(ER_WRONG_ARGUMENTS, MYF(0),
4369              is_sql_ps ? "EXECUTE" : "mysqld_stmt_execute");
4370     reset_stmt_params(this);
4371   }
4372   return res;
4373 }
4374 
4375 
4376 /**
4377   Execute a prepared statement. Re-prepare it a limited number
4378   of times if necessary.
4379 
4380   Try to execute a prepared statement. If there is a metadata
4381   validation error, prepare a new copy of the prepared statement,
4382   swap the old and the new statements, and try again.
4383   If there is a validation error again, repeat the above, but
4384   perform no more than MAX_REPREPARE_ATTEMPTS.
4385 
4386   @note We have to try several times in a loop since we
4387   release metadata locks on tables after prepared statement
4388   prepare. Therefore, a DDL statement may sneak in between prepare
4389   and execute of a new statement. If this happens repeatedly
4390   more than MAX_REPREPARE_ATTEMPTS times, we give up.
4391 
4392   @return TRUE if an error, FALSE if success
4393   @retval  TRUE    either MAX_REPREPARE_ATTEMPTS has been reached,
4394                    or some general error
4395   @retval  FALSE   successfully executed the statement, perhaps
4396                    after having reprepared it a few times.
4397 */
4398 const static int MAX_REPREPARE_ATTEMPTS= 3;
4399 
4400 bool
4401 Prepared_statement::execute_loop(String *expanded_query,
4402                                  bool open_cursor,
4403                                  uchar *packet,
4404                                  uchar *packet_end)
4405 {
4406   Reprepare_observer reprepare_observer;
4407   bool error;
4408   int reprepare_attempt= 0;
4409   iterations= FALSE;
4410 
4411   /*
4412     - In mysql_sql_stmt_execute() we hide all "external" Items
4413       e.g. those created in the "SET STATEMENT" part of the "EXECUTE" query.
4414     - In case of mysqld_stmt_execute() there should not be "external" Items.
4415   */
4416   DBUG_ASSERT(thd->free_list == NULL);
4417 
4418   /* Check if we got an error when sending long data */
4419   if (unlikely(state == Query_arena::STMT_ERROR))
4420   {
4421     my_message(last_errno, last_error, MYF(0));
4422     return TRUE;
4423   }
4424 
4425   if (set_parameters(expanded_query, packet, packet_end))
4426     return TRUE;
4427 
4428 #ifdef NOT_YET_FROM_MYSQL_5_6
4429   if (unlikely(thd->security_ctx->password_expired &&
4430                !lex->is_change_password))
4431   {
4432     my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
4433     return true;
4434   }
4435 #endif
4436 
4437 reexecute:
4438   // Make sure that reprepare() did not create any new Items.
4439   DBUG_ASSERT(thd->free_list == NULL);
4440 
4441   /*
4442     Install the metadata observer. If some metadata version is
4443     different from prepare time and an observer is installed,
4444     the observer method will be invoked to push an error into
4445     the error stack.
4446   */
4447 
4448   if (sql_command_flags[lex->sql_command] & CF_REEXECUTION_FRAGILE)
4449   {
4450     reprepare_observer.reset_reprepare_observer();
4451     DBUG_ASSERT(thd->m_reprepare_observer == NULL);
4452     thd->m_reprepare_observer= &reprepare_observer;
4453   }
4454 
4455   error= execute(expanded_query, open_cursor) || thd->is_error();
4456 
4457   thd->m_reprepare_observer= NULL;
4458 #ifdef WITH_WSREP
4459 
4460   if (WSREP_ON)
4461   {
4462     mysql_mutex_lock(&thd->LOCK_thd_data);
4463     switch (thd->wsrep_conflict_state)
4464     {
4465       case CERT_FAILURE:
4466         WSREP_DEBUG("PS execute fail for CERT_FAILURE: thd: %lld  err: %d",
4467 	            (longlong) thd->thread_id,
4468                     thd->get_stmt_da()->sql_errno() );
4469         thd->wsrep_conflict_state = NO_CONFLICT;
4470         break;
4471 
4472       case MUST_REPLAY:
4473         (void) wsrep_replay_transaction(thd);
4474         break;
4475 
4476       default:
4477         break;
4478     }
4479     mysql_mutex_unlock(&thd->LOCK_thd_data);
4480   }
4481 #endif /* WITH_WSREP */
4482 
4483   if (unlikely(error) &&
4484       (sql_command_flags[lex->sql_command] & CF_REEXECUTION_FRAGILE) &&
4485       !thd->is_fatal_error && !thd->killed &&
4486       reprepare_observer.is_invalidated() &&
4487       reprepare_attempt++ < MAX_REPREPARE_ATTEMPTS)
4488   {
4489     DBUG_ASSERT(thd->get_stmt_da()->sql_errno() == ER_NEED_REPREPARE);
4490     thd->clear_error();
4491 
4492     error= reprepare();
4493 
4494     if (likely(!error))                         /* Success */
4495       goto reexecute;
4496   }
4497   reset_stmt_params(this);
4498 
4499   return error;
4500 }
4501 
4502 my_bool bulk_parameters_set(THD *thd)
4503 {
4504   DBUG_ENTER("bulk_parameters_set");
4505   Prepared_statement *stmt= (Prepared_statement *) thd->bulk_param;
4506 
4507   if (stmt && unlikely(stmt->set_bulk_parameters(FALSE)))
4508     DBUG_RETURN(TRUE);
4509   DBUG_RETURN(FALSE);
4510 }
4511 
4512 my_bool bulk_parameters_iterations(THD *thd)
4513 {
4514   Prepared_statement *stmt= (Prepared_statement *) thd->bulk_param;
4515   if (!stmt)
4516     return FALSE;
4517   return stmt->bulk_iterations();
4518 }
4519 
4520 
4521 my_bool Prepared_statement::set_bulk_parameters(bool reset)
4522 {
4523   DBUG_ENTER("Prepared_statement::set_bulk_parameters");
4524   DBUG_PRINT("info", ("iteration: %d", iterations));
4525 
4526   if (iterations)
4527   {
4528 #ifndef EMBEDDED_LIBRARY
4529     if ((*set_bulk_params)(this, &packet, packet_end, reset))
4530 #else
4531     // bulk parameters are not supported for embedded, so it will an error
4532 #endif
4533     {
4534       my_error(ER_WRONG_ARGUMENTS, MYF(0),
4535                "mysqld_stmt_bulk_execute");
4536       reset_stmt_params(this);
4537       DBUG_RETURN(true);
4538     }
4539     if (packet >= packet_end)
4540       iterations= FALSE;
4541   }
4542   start_param= 0;
4543   DBUG_RETURN(false);
4544 }
4545 
4546 bool
4547 Prepared_statement::execute_bulk_loop(String *expanded_query,
4548                                       bool open_cursor,
4549                                       uchar *packet_arg,
4550                                       uchar *packet_end_arg)
4551 {
4552   Reprepare_observer reprepare_observer;
4553   bool error= 0;
4554   packet= packet_arg;
4555   packet_end= packet_end_arg;
4556   iterations= TRUE;
4557   start_param= true;
4558 #ifdef DBUG_ASSERT_EXISTS
4559   Item *free_list_state= thd->free_list;
4560 #endif
4561   thd->set_bulk_execution((void *)this);
4562   /* Check if we got an error when sending long data */
4563   if (state == Query_arena::STMT_ERROR)
4564   {
4565     my_message(last_errno, last_error, MYF(0));
4566     thd->set_bulk_execution(0);
4567     return TRUE;
4568   }
4569   /* Check for non zero parameter count*/
4570   if (param_count == 0)
4571   {
4572     DBUG_PRINT("error", ("Statement with no parameters for bulk execution."));
4573     my_error(ER_UNSUPPORTED_PS, MYF(0));
4574     thd->set_bulk_execution(0);
4575     return TRUE;
4576   }
4577 
4578   if (!(sql_command_flags[lex->sql_command] & CF_PS_ARRAY_BINDING_SAFE))
4579   {
4580     DBUG_PRINT("error", ("Command is not supported in bulk execution."));
4581     my_error(ER_UNSUPPORTED_PS, MYF(0));
4582     thd->set_bulk_execution(0);
4583     return TRUE;
4584   }
4585 
4586 #ifndef EMBEDDED_LIBRARY
4587   if (read_types &&
4588       set_conversion_functions(this, &packet))
4589 #else
4590   // bulk parameters are not supported for embedded, so it will an error
4591 #endif
4592   {
4593     my_error(ER_WRONG_ARGUMENTS, MYF(0),
4594             "mysqld_stmt_bulk_execute");
4595     reset_stmt_params(this);
4596     thd->set_bulk_execution(0);
4597     return true;
4598   }
4599   read_types= FALSE;
4600 
4601 #ifdef NOT_YET_FROM_MYSQL_5_6
4602   if (unlikely(thd->security_ctx->password_expired &&
4603                !lex->is_change_password))
4604   {
4605     my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
4606     thd->set_bulk_execution(0);
4607     return true;
4608   }
4609 #endif
4610 
4611   // iterations changed by set_bulk_parameters
4612   while ((iterations || start_param) && !error && !thd->is_error())
4613   {
4614     int reprepare_attempt= 0;
4615 
4616     /*
4617       Here we set parameters for not optimized commands,
4618       optimized commands do it inside thier internal loop.
4619     */
4620     if (!(sql_command_flags[lex->sql_command] & CF_PS_ARRAY_BINDING_OPTIMIZED))
4621     {
4622       if (set_bulk_parameters(TRUE))
4623       {
4624         thd->set_bulk_execution(0);
4625         return true;
4626       }
4627     }
4628 
4629 reexecute:
4630     /*
4631       If the free_list is not empty, we'll wrongly free some externally
4632       allocated items when cleaning up after validation of the prepared
4633       statement.
4634     */
4635     DBUG_ASSERT(thd->free_list == free_list_state);
4636 
4637     /*
4638       Install the metadata observer. If some metadata version is
4639       different from prepare time and an observer is installed,
4640       the observer method will be invoked to push an error into
4641       the error stack.
4642     */
4643 
4644     if (sql_command_flags[lex->sql_command] & CF_REEXECUTION_FRAGILE)
4645     {
4646       reprepare_observer.reset_reprepare_observer();
4647       DBUG_ASSERT(thd->m_reprepare_observer == NULL);
4648       thd->m_reprepare_observer= &reprepare_observer;
4649     }
4650 
4651     error= execute(expanded_query, open_cursor) || thd->is_error();
4652 
4653     thd->m_reprepare_observer= NULL;
4654 #ifdef WITH_WSREP
4655 
4656     if (WSREP_ON)
4657     {
4658       mysql_mutex_lock(&thd->LOCK_thd_data);
4659       switch (thd->wsrep_conflict_state)
4660       {
4661       case CERT_FAILURE:
4662         WSREP_DEBUG("PS execute fail for CERT_FAILURE: thd: %lld  err: %d",
4663 	            (longlong) thd->thread_id,
4664                     thd->get_stmt_da()->sql_errno() );
4665         thd->wsrep_conflict_state = NO_CONFLICT;
4666         break;
4667 
4668       case MUST_REPLAY:
4669         (void) wsrep_replay_transaction(thd);
4670         break;
4671 
4672       default:
4673         break;
4674       }
4675       mysql_mutex_unlock(&thd->LOCK_thd_data);
4676     }
4677 #endif /* WITH_WSREP */
4678 
4679     if (unlikely(error) &&
4680         (sql_command_flags[lex->sql_command] & CF_REEXECUTION_FRAGILE) &&
4681         !thd->is_fatal_error && !thd->killed &&
4682         reprepare_observer.is_invalidated() &&
4683         reprepare_attempt++ < MAX_REPREPARE_ATTEMPTS)
4684     {
4685       DBUG_ASSERT(thd->get_stmt_da()->sql_errno() == ER_NEED_REPREPARE);
4686       thd->clear_error();
4687 
4688       error= reprepare();
4689 
4690       if (likely(!error))                                /* Success */
4691         goto reexecute;
4692     }
4693   }
4694   reset_stmt_params(this);
4695   thd->set_bulk_execution(0);
4696 
4697   return error;
4698 }
4699 
4700 
4701 bool
4702 Prepared_statement::execute_server_runnable(Server_runnable *server_runnable)
4703 {
4704   Statement stmt_backup;
4705   bool error;
4706   Query_arena *save_stmt_arena= thd->stmt_arena;
4707   Item_change_list save_change_list;
4708   thd->Item_change_list::move_elements_to(&save_change_list);
4709 
4710   state= STMT_CONVENTIONAL_EXECUTION;
4711 
4712   if (!(lex= new (mem_root) st_lex_local))
4713     return TRUE;
4714 
4715   thd->set_n_backup_statement(this, &stmt_backup);
4716   thd->set_n_backup_active_arena(this, &stmt_backup);
4717   thd->stmt_arena= this;
4718 
4719   error= server_runnable->execute_server_code(thd);
4720 
4721   thd->cleanup_after_query();
4722 
4723   thd->restore_active_arena(this, &stmt_backup);
4724   thd->restore_backup_statement(this, &stmt_backup);
4725   thd->stmt_arena= save_stmt_arena;
4726 
4727   save_change_list.move_elements_to(thd);
4728 
4729   /* Items and memory will freed in destructor */
4730 
4731   return error;
4732 }
4733 
4734 
4735 /**
4736   Reprepare this prepared statement.
4737 
4738   Currently this is implemented by creating a new prepared
4739   statement, preparing it with the original query and then
4740   swapping the new statement and the original one.
4741 
4742   @retval  TRUE   an error occurred. Possible errors include
4743                   incompatibility of new and old result set
4744                   metadata
4745   @retval  FALSE  success, the statement has been reprepared
4746 */
4747 
4748 bool
4749 Prepared_statement::reprepare()
4750 {
4751   char saved_cur_db_name_buf[SAFE_NAME_LEN+1];
4752   LEX_STRING saved_cur_db_name=
4753     { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
4754   LEX_CSTRING stmt_db_name= db;
4755   bool cur_db_changed;
4756   bool error;
4757 
4758   Prepared_statement copy(thd);
4759   copy.m_sql_mode= m_sql_mode;
4760 
4761   copy.set_sql_prepare(); /* To suppress sending metadata to the client. */
4762 
4763   status_var_increment(thd->status_var.com_stmt_reprepare);
4764 
4765   if (unlikely(mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name,
4766                                    TRUE, &cur_db_changed)))
4767     return TRUE;
4768 
4769   sql_mode_t save_sql_mode= thd->variables.sql_mode;
4770   thd->variables.sql_mode= m_sql_mode;
4771   error= ((name.str && copy.set_name(&name)) ||
4772           copy.prepare(query(), query_length()) ||
4773           validate_metadata(&copy));
4774   thd->variables.sql_mode= save_sql_mode;
4775 
4776   if (cur_db_changed)
4777     mysql_change_db(thd, (LEX_CSTRING*) &saved_cur_db_name, TRUE);
4778 
4779   if (likely(!error))
4780   {
4781     swap_prepared_statement(&copy);
4782     swap_parameter_array(param_array, copy.param_array, param_count);
4783 #ifdef DBUG_ASSERT_EXISTS
4784     is_reprepared= TRUE;
4785 #endif
4786     /*
4787       Clear possible warnings during reprepare, it has to be completely
4788       transparent to the user. We use clear_warning_info() since
4789       there were no separate query id issued for re-prepare.
4790       Sic: we can't simply silence warnings during reprepare, because if
4791       it's failed, we need to return all the warnings to the user.
4792     */
4793     thd->get_stmt_da()->clear_warning_info(thd->query_id);
4794   }
4795   return error;
4796 }
4797 
4798 
4799 /**
4800   Validate statement result set metadata (if the statement returns
4801   a result set).
4802 
4803   Currently we only check that the number of columns of the result
4804   set did not change.
4805   This is a helper method used during re-prepare.
4806 
4807   @param[in]  copy  the re-prepared prepared statement to verify
4808                     the metadata of
4809 
4810   @retval TRUE  error, ER_PS_REBIND is reported
4811   @retval FALSE statement return no or compatible metadata
4812 */
4813 
4814 
4815 bool Prepared_statement::validate_metadata(Prepared_statement *copy)
4816 {
4817   /**
4818     If this is an SQL prepared statement or EXPLAIN,
4819     return FALSE -- the metadata of the original SELECT,
4820     if any, has not been sent to the client.
4821   */
4822   if (is_sql_prepare() || lex->describe)
4823     return FALSE;
4824 
4825   if (lex->select_lex.item_list.elements !=
4826       copy->lex->select_lex.item_list.elements)
4827   {
4828     /** Column counts mismatch, update the client */
4829     thd->server_status|= SERVER_STATUS_METADATA_CHANGED;
4830   }
4831 
4832   return FALSE;
4833 }
4834 
4835 
4836 /**
4837   Replace the original prepared statement with a prepared copy.
4838 
4839   This is a private helper that is used as part of statement
4840   reprepare
4841 
4842   @return This function does not return any errors.
4843 */
4844 
4845 void
4846 Prepared_statement::swap_prepared_statement(Prepared_statement *copy)
4847 {
4848   Statement tmp_stmt;
4849 
4850   /* Swap memory roots. */
4851   swap_variables(MEM_ROOT, main_mem_root, copy->main_mem_root);
4852 
4853   /* Swap the arenas */
4854   tmp_stmt.set_query_arena(this);
4855   set_query_arena(copy);
4856   copy->set_query_arena(&tmp_stmt);
4857 
4858   /* Swap the statement parent classes */
4859   tmp_stmt.set_statement(this);
4860   set_statement(copy);
4861   copy->set_statement(&tmp_stmt);
4862 
4863   /* Swap ids back, we need the original id */
4864   swap_variables(ulong, id, copy->id);
4865   /* Swap mem_roots back, they must continue pointing at the main_mem_roots */
4866   swap_variables(MEM_ROOT *, mem_root, copy->mem_root);
4867   /*
4868     Swap the old and the new parameters array. The old array
4869     is allocated in the old arena.
4870   */
4871   swap_variables(Item_param **, param_array, copy->param_array);
4872   /* Don't swap flags: the copy has IS_SQL_PREPARE always set. */
4873   /* swap_variables(uint, flags, copy->flags); */
4874   /* Swap names, the old name is allocated in the wrong memory root */
4875   swap_variables(LEX_CSTRING, name, copy->name);
4876   /* Ditto */
4877   swap_variables(LEX_CSTRING, db, copy->db);
4878 
4879   DBUG_ASSERT(param_count == copy->param_count);
4880   DBUG_ASSERT(thd == copy->thd);
4881   last_error[0]= '\0';
4882   last_errno= 0;
4883 }
4884 
4885 
4886 /**
4887   Execute a prepared statement.
4888 
4889     You should not change global THD state in this function, if at all
4890     possible: it may be called from any context, e.g. when executing
4891     a COM_* command, and SQLCOM_* command, or a stored procedure.
4892 
4893   @param expanded_query     A query for binlogging which has all parameter
4894                             markers ('?') replaced with their actual values.
4895   @param open_cursor        True if an attempt to open a cursor should be made.
4896                             Currenlty used only in the binary protocol.
4897 
4898   @note
4899     Preconditions, postconditions.
4900     - See the comment for Prepared_statement::prepare().
4901 
4902   @retval
4903     FALSE	    ok
4904   @retval
4905     TRUE		Error
4906 */
4907 
4908 bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
4909 {
4910   Statement stmt_backup;
4911   Query_arena *old_stmt_arena;
4912   bool error= TRUE;
4913   bool qc_executed= FALSE;
4914 
4915   char saved_cur_db_name_buf[SAFE_NAME_LEN+1];
4916   LEX_STRING saved_cur_db_name=
4917     { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
4918   bool cur_db_changed;
4919 
4920   LEX_CSTRING stmt_db_name= db;
4921 
4922   status_var_increment(thd->status_var.com_stmt_execute);
4923 
4924   if (flags & (uint) IS_IN_USE)
4925   {
4926     my_error(ER_PS_NO_RECURSION, MYF(0));
4927     return TRUE;
4928   }
4929 
4930   /*
4931     For SHOW VARIABLES lex->result is NULL, as it's a non-SELECT
4932     command. For such queries we don't return an error and don't
4933     open a cursor -- the client library will recognize this case and
4934     materialize the result set.
4935     For SELECT statements lex->result is created in
4936     check_prepared_statement. lex->result->simple_select() is FALSE
4937     in INSERT ... SELECT and similar commands.
4938   */
4939 
4940   if (open_cursor && lex->result && lex->result->check_simple_select())
4941   {
4942     DBUG_PRINT("info",("Cursor asked for not SELECT stmt"));
4943     return TRUE;
4944   }
4945 
4946   /* In case the command has a call to SP which re-uses this statement name */
4947   flags|= IS_IN_USE;
4948 
4949   close_cursor();
4950 
4951   /*
4952     If the free_list is not empty, we'll wrongly free some externally
4953     allocated items when cleaning up after execution of this statement.
4954   */
4955   DBUG_ASSERT(thd->Item_change_list::is_empty());
4956 
4957   /*
4958    The only case where we should have items in the thd->free_list is
4959    after stmt->set_params_from_vars(), which may in some cases create
4960    Item_null objects.
4961   */
4962 
4963   thd->set_n_backup_statement(this, &stmt_backup);
4964 
4965   /*
4966     Change the current database (if needed).
4967 
4968     Force switching, because the database of the prepared statement may be
4969     NULL (prepared statements can be created while no current database
4970     selected).
4971   */
4972 
4973   if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE,
4974                           &cur_db_changed))
4975     goto error;
4976 
4977   /* Allocate query. */
4978 
4979   if (expanded_query->length() &&
4980       alloc_query(thd, (char*) expanded_query->ptr(),
4981                   expanded_query->length()))
4982   {
4983     my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR), expanded_query->length());
4984     goto error;
4985   }
4986   /*
4987     Expanded query is needed for slow logging, so we want thd->query
4988     to point at it even after we restore from backup. This is ok, as
4989     expanded query was allocated in thd->mem_root.
4990   */
4991   stmt_backup.set_query_inner(thd->query_string);
4992 
4993   /*
4994     At first execution of prepared statement we may perform logical
4995     transformations of the query tree. Such changes should be performed
4996     on the parse tree of current prepared statement and new items should
4997     be allocated in its memory root. Set the appropriate pointer in THD
4998     to the arena of the statement.
4999   */
5000   old_stmt_arena= thd->stmt_arena;
5001   thd->stmt_arena= this;
5002   reinit_stmt_before_use(thd, lex);
5003 
5004   /* Go! */
5005 
5006   if (open_cursor)
5007     error= mysql_open_cursor(thd, &result, &cursor);
5008   else
5009   {
5010     /*
5011       Try to find it in the query cache, if not, execute it.
5012       Note that multi-statements cannot exist here (they are not supported in
5013       prepared statements).
5014     */
5015     if (query_cache_send_result_to_client(thd, thd->query(),
5016                                           thd->query_length()) <= 0)
5017     {
5018       PSI_statement_locker *parent_locker;
5019       MYSQL_QUERY_EXEC_START(thd->query(),
5020                              thd->thread_id,
5021                              thd->get_db(),
5022                              &thd->security_ctx->priv_user[0],
5023                              (char *) thd->security_ctx->host_or_ip,
5024                              1);
5025       parent_locker= thd->m_statement_psi;
5026       thd->m_statement_psi= NULL;
5027       error= mysql_execute_command(thd);
5028       thd->m_statement_psi= parent_locker;
5029       MYSQL_QUERY_EXEC_DONE(error);
5030     }
5031     else
5032     {
5033       thd->lex->sql_command= SQLCOM_SELECT;
5034       status_var_increment(thd->status_var.com_stat[SQLCOM_SELECT]);
5035       thd->update_stats();
5036       qc_executed= TRUE;
5037     }
5038   }
5039 
5040   /*
5041     Restore the current database (if changed).
5042 
5043     Force switching back to the saved current database (if changed),
5044     because it may be NULL. In this case, mysql_change_db() would generate
5045     an error.
5046   */
5047 
5048   if (cur_db_changed)
5049     mysql_change_db(thd, (LEX_CSTRING*) &saved_cur_db_name, TRUE);
5050 
5051   /* Assert that if an error, no cursor is open */
5052   DBUG_ASSERT(! (error && cursor));
5053 
5054   if (! cursor)
5055     cleanup_stmt();
5056 
5057   /*
5058     EXECUTE command has its own dummy "explain data". We don't need it,
5059     instead, we want to keep the query plan of the statement that was
5060     executed.
5061   */
5062   if (!stmt_backup.lex->explain ||
5063       !stmt_backup.lex->explain->have_query_plan())
5064   {
5065     delete_explain_query(stmt_backup.lex);
5066     stmt_backup.lex->explain = thd->lex->explain;
5067     thd->lex->explain= NULL;
5068   }
5069   else
5070     delete_explain_query(thd->lex);
5071 
5072   thd->set_statement(&stmt_backup);
5073   thd->stmt_arena= old_stmt_arena;
5074 
5075   if (state == Query_arena::STMT_PREPARED && !qc_executed)
5076     state= Query_arena::STMT_EXECUTED;
5077 
5078   if (likely(error == 0) && this->lex->sql_command == SQLCOM_CALL)
5079   {
5080     if (is_sql_prepare())
5081     {
5082       /*
5083         Here we have the diagnostics area status already set to DA_OK.
5084         sent_out_parameters() can raise errors when assigning OUT parameters:
5085           DECLARE a DATETIME;
5086           EXECUTE IMMEDIATE 'CALL p1(?)' USING a;
5087         when the procedure p1 assigns a DATETIME-incompatible value (e.g. 10)
5088         to the out parameter. Allow to overwrite status (to DA_ERROR).
5089       */
5090       thd->get_stmt_da()->set_overwrite_status(true);
5091       thd->protocol_text.send_out_parameters(&this->lex->param_list);
5092       thd->get_stmt_da()->set_overwrite_status(false);
5093     }
5094     else
5095       thd->protocol->send_out_parameters(&this->lex->param_list);
5096   }
5097 
5098   /*
5099     Log COM_EXECUTE to the general log. Note, that in case of SQL
5100     prepared statements this causes two records to be output:
5101 
5102     Query       EXECUTE <statement name>
5103     Execute     <statement SQL text>
5104 
5105     This is considered user-friendly, since in the
5106     second log entry we output values of parameter markers.
5107 
5108     Do not print anything if this is an SQL prepared statement and
5109     we're inside a stored procedure (also called Dynamic SQL) --
5110     sub-statements inside stored procedures are not logged into
5111     the general log.
5112   */
5113   if (likely(error == 0 && thd->spcont == NULL))
5114     general_log_write(thd, COM_STMT_EXECUTE, thd->query(), thd->query_length());
5115 
5116 error:
5117   thd->lex->restore_set_statement_var();
5118   flags&= ~ (uint) IS_IN_USE;
5119   return error;
5120 }
5121 
5122 
5123 /**
5124   Prepare, execute and clean-up a statement.
5125   @param query  - query text
5126   @param length - query text length
5127   @retval true  - the query was not executed (parse error, wrong parameters)
5128   @retval false - the query was prepared and executed
5129 
5130   Note, if some error happened during execution, it still returns "false".
5131 */
5132 bool Prepared_statement::execute_immediate(const char *query, uint query_len)
5133 {
5134   DBUG_ENTER("Prepared_statement::execute_immediate");
5135   String expanded_query;
5136   static LEX_CSTRING execute_immediate_stmt_name=
5137     {STRING_WITH_LEN("(immediate)") };
5138 
5139   set_sql_prepare();
5140   name= execute_immediate_stmt_name;      // for DBUG_PRINT etc
5141   if (unlikely(prepare(query, query_len)))
5142     DBUG_RETURN(true);
5143 
5144   if (param_count != thd->lex->prepared_stmt_params.elements)
5145   {
5146     my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
5147     deallocate_immediate();
5148     DBUG_RETURN(true);
5149   }
5150 
5151   (void) execute_loop(&expanded_query, FALSE, NULL, NULL);
5152   deallocate_immediate();
5153   DBUG_RETURN(false);
5154 }
5155 
5156 
5157 /**
5158   Common part of DEALLOCATE PREPARE, EXECUTE IMMEDIATE, mysqld_stmt_close.
5159 */
5160 void Prepared_statement::deallocate_immediate()
5161 {
5162   /* We account deallocate in the same manner as mysqld_stmt_close */
5163   status_var_increment(thd->status_var.com_stmt_close);
5164 
5165   /* It should now be safe to reset CHANGE MASTER parameters */
5166   lex_end(lex);
5167 }
5168 
5169 
5170 /** Common part of DEALLOCATE PREPARE and mysqld_stmt_close. */
5171 
5172 void Prepared_statement::deallocate()
5173 {
5174   deallocate_immediate();
5175   /* Statement map calls delete stmt on erase */
5176   thd->stmt_map.erase(this);
5177 }
5178 
5179 
5180 /***************************************************************************
5181 * Ed_result_set
5182 ***************************************************************************/
5183 /**
5184   Use operator delete to free memory of Ed_result_set.
5185   Accessing members of a class after the class has been destroyed
5186   is a violation of the C++ standard but is commonly used in the
5187   server code.
5188 */
5189 
5190 void Ed_result_set::operator delete(void *ptr, size_t size) throw ()
5191 {
5192   if (ptr)
5193   {
5194     /*
5195       Make a stack copy, otherwise free_root() will attempt to
5196       write to freed memory.
5197     */
5198     MEM_ROOT own_root= ((Ed_result_set*) ptr)->m_mem_root;
5199     free_root(&own_root, MYF(0));
5200   }
5201 }
5202 
5203 
5204 /**
5205   Initialize an instance of Ed_result_set.
5206 
5207   Instances of the class, as well as all result set rows, are
5208   always allocated in the memory root passed over as the second
5209   argument. In the constructor, we take over ownership of the
5210   memory root. It will be freed when the class is destroyed.
5211 
5212   sic: Ed_result_est is not designed to be allocated on stack.
5213 */
5214 
5215 Ed_result_set::Ed_result_set(List<Ed_row> *rows_arg,
5216                              size_t column_count_arg,
5217                              MEM_ROOT *mem_root_arg)
5218   :m_mem_root(*mem_root_arg),
5219   m_column_count(column_count_arg),
5220   m_rows(rows_arg),
5221   m_next_rset(NULL)
5222 {
5223   /* Take over responsibility for the memory */
5224   clear_alloc_root(mem_root_arg);
5225 }
5226 
5227 /***************************************************************************
5228 * Ed_result_set
5229 ***************************************************************************/
5230 
5231 /**
5232   Create a new "execute direct" connection.
5233 */
5234 
5235 Ed_connection::Ed_connection(THD *thd)
5236   :m_diagnostics_area(thd->query_id, false, true),
5237   m_thd(thd),
5238   m_rsets(0),
5239   m_current_rset(0)
5240 {
5241 }
5242 
5243 
5244 /**
5245   Free all result sets of the previous statement, if any,
5246   and reset warnings and errors.
5247 
5248   Called before execution of the next query.
5249 */
5250 
5251 void
5252 Ed_connection::free_old_result()
5253 {
5254   while (m_rsets)
5255   {
5256     Ed_result_set *rset= m_rsets->m_next_rset;
5257     delete m_rsets;
5258     m_rsets= rset;
5259   }
5260   m_current_rset= m_rsets;
5261   m_diagnostics_area.reset_diagnostics_area();
5262   m_diagnostics_area.clear_warning_info(m_thd->query_id);
5263 }
5264 
5265 
5266 /**
5267   A simple wrapper that uses a helper class to execute SQL statements.
5268 */
5269 
5270 bool
5271 Ed_connection::execute_direct(LEX_STRING sql_text)
5272 {
5273   Execute_sql_statement execute_sql_statement(sql_text);
5274   DBUG_PRINT("ed_query", ("%s", sql_text.str));
5275 
5276   return execute_direct(&execute_sql_statement);
5277 }
5278 
5279 
5280 /**
5281   Execute a fragment of server functionality without an effect on
5282   thd, and store results in memory.
5283 
5284   Conventions:
5285   - the code fragment must finish with OK, EOF or ERROR.
5286   - the code fragment doesn't have to close thread tables,
5287   free memory, commit statement transaction or do any other
5288   cleanup that is normally done in the end of dispatch_command().
5289 
5290   @param server_runnable A code fragment to execute.
5291 */
5292 
5293 bool Ed_connection::execute_direct(Server_runnable *server_runnable)
5294 {
5295   bool rc= FALSE;
5296   Protocol_local protocol_local(m_thd, this);
5297   Prepared_statement stmt(m_thd);
5298   Protocol *save_protocol= m_thd->protocol;
5299   Diagnostics_area *save_diagnostics_area= m_thd->get_stmt_da();
5300 
5301   DBUG_ENTER("Ed_connection::execute_direct");
5302 
5303   free_old_result(); /* Delete all data from previous execution, if any */
5304 
5305   m_thd->protocol= &protocol_local;
5306   m_thd->set_stmt_da(&m_diagnostics_area);
5307 
5308   rc= stmt.execute_server_runnable(server_runnable);
5309   m_thd->protocol->end_statement();
5310 
5311   m_thd->protocol= save_protocol;
5312   m_thd->set_stmt_da(save_diagnostics_area);
5313   /*
5314     Protocol_local makes use of m_current_rset to keep
5315     track of the last result set, while adding result sets to the end.
5316     Reset it to point to the first result set instead.
5317   */
5318   m_current_rset= m_rsets;
5319 
5320   DBUG_RETURN(rc);
5321 }
5322 
5323 
5324 /**
5325   A helper method that is called only during execution.
5326 
5327   Although Ed_connection doesn't support multi-statements,
5328   a statement may generate many result sets. All subsequent
5329   result sets are appended to the end.
5330 
5331   @pre This is called only by Protocol_local.
5332 */
5333 
5334 void
5335 Ed_connection::add_result_set(Ed_result_set *ed_result_set)
5336 {
5337   if (m_rsets)
5338   {
5339     m_current_rset->m_next_rset= ed_result_set;
5340     /* While appending, use m_current_rset as a pointer to the tail. */
5341     m_current_rset= ed_result_set;
5342   }
5343   else
5344     m_current_rset= m_rsets= ed_result_set;
5345 }
5346 
5347 
5348 /**
5349   Release ownership of the current result set to the client.
5350 
5351   Since we use a simple linked list for result sets,
5352   this method uses a linear search of the previous result
5353   set to exclude the released instance from the list.
5354 
5355   @todo Use double-linked list, when this is really used.
5356 
5357   XXX: This has never been tested with more than one result set!
5358 
5359   @pre There must be a result set.
5360 */
5361 
5362 Ed_result_set *
5363 Ed_connection::store_result_set()
5364 {
5365   Ed_result_set *ed_result_set;
5366 
5367   DBUG_ASSERT(m_current_rset);
5368 
5369   if (m_current_rset == m_rsets)
5370   {
5371     /* Assign the return value */
5372     ed_result_set= m_current_rset;
5373     /* Exclude the return value from the list. */
5374     m_current_rset= m_rsets= m_rsets->m_next_rset;
5375   }
5376   else
5377   {
5378     Ed_result_set *prev_rset= m_rsets;
5379     /* Assign the return value. */
5380     ed_result_set= m_current_rset;
5381 
5382     /* Exclude the return value from the list */
5383     while (prev_rset->m_next_rset != m_current_rset)
5384       prev_rset= ed_result_set->m_next_rset;
5385     m_current_rset= prev_rset->m_next_rset= m_current_rset->m_next_rset;
5386   }
5387   ed_result_set->m_next_rset= NULL; /* safety */
5388 
5389   return ed_result_set;
5390 }
5391 
5392 /*************************************************************************
5393 * Protocol_local
5394 **************************************************************************/
5395 
5396 Protocol_local::Protocol_local(THD *thd, Ed_connection *ed_connection)
5397   :Protocol(thd),
5398   m_connection(ed_connection),
5399   m_rset(NULL),
5400   m_column_count(0),
5401   m_current_row(NULL),
5402   m_current_column(NULL)
5403 {
5404   clear_alloc_root(&m_rset_root);
5405 }
5406 
5407 /**
5408   Called between two result set rows.
5409 
5410   Prepare structures to fill result set rows.
5411   Unfortunately, we can't return an error here. If memory allocation
5412   fails, we'll have to return an error later. And so is done
5413   in methods such as @sa store_column().
5414 */
5415 
5416 void Protocol_local::prepare_for_resend()
5417 {
5418   DBUG_ASSERT(alloc_root_inited(&m_rset_root));
5419 
5420   opt_add_row_to_rset();
5421   /* Start a new row. */
5422   m_current_row= (Ed_column *) alloc_root(&m_rset_root,
5423                                           sizeof(Ed_column) * m_column_count);
5424   m_current_column= m_current_row;
5425 }
5426 
5427 
5428 /**
5429   In "real" protocols this is called to finish a result set row.
5430   Unused in the local implementation.
5431 */
5432 
5433 bool Protocol_local::write()
5434 {
5435   return FALSE;
5436 }
5437 
5438 /**
5439   A helper function to add the current row to the current result
5440   set. Called in @sa prepare_for_resend(), when a new row is started,
5441   and in send_eof(), when the result set is finished.
5442 */
5443 
5444 void Protocol_local::opt_add_row_to_rset()
5445 {
5446   if (m_current_row)
5447   {
5448     /* Add the old row to the result set */
5449     Ed_row *ed_row= new (&m_rset_root) Ed_row(m_current_row, m_column_count);
5450     if (ed_row)
5451       m_rset->push_back(ed_row, &m_rset_root);
5452   }
5453 }
5454 
5455 
5456 /**
5457   Add a NULL column to the current row.
5458 */
5459 
5460 bool Protocol_local::store_null()
5461 {
5462   if (m_current_column == NULL)
5463     return TRUE; /* prepare_for_resend() failed to allocate memory. */
5464 
5465   bzero(m_current_column, sizeof(*m_current_column));
5466   ++m_current_column;
5467   return FALSE;
5468 }
5469 
5470 
5471 /**
5472   A helper method to add any column to the current row
5473   in its binary form.
5474 
5475   Allocates memory for the data in the result set memory root.
5476 */
5477 
5478 bool Protocol_local::store_column(const void *data, size_t length)
5479 {
5480   if (m_current_column == NULL)
5481     return TRUE; /* prepare_for_resend() failed to allocate memory. */
5482   /*
5483     alloc_root() automatically aligns memory, so we don't need to
5484     do any extra alignment if we're pointing to, say, an integer.
5485   */
5486   m_current_column->str= (char*) memdup_root(&m_rset_root,
5487                                              data,
5488                                              length + 1 /* Safety */);
5489   if (! m_current_column->str)
5490     return TRUE;
5491   m_current_column->str[length]= '\0'; /* Safety */
5492   m_current_column->length= length;
5493   ++m_current_column;
5494   return FALSE;
5495 }
5496 
5497 
5498 /**
5499   Store a string value in a result set column, optionally
5500   having converted it to character_set_results.
5501 */
5502 
5503 bool
5504 Protocol_local::store_string(const char *str, size_t length,
5505                              CHARSET_INFO *src_cs, CHARSET_INFO *dst_cs)
5506 {
5507   /* Store with conversion */
5508   uint error_unused;
5509 
5510   if (dst_cs && !my_charset_same(src_cs, dst_cs) &&
5511       src_cs != &my_charset_bin &&
5512       dst_cs != &my_charset_bin)
5513   {
5514     if (unlikely(convert->copy(str, length, src_cs, dst_cs, &error_unused)))
5515       return TRUE;
5516     str= convert->ptr();
5517     length= convert->length();
5518   }
5519   return store_column(str, length);
5520 }
5521 
5522 
5523 /** Store a tiny int as is (1 byte) in a result set column. */
5524 
5525 bool Protocol_local::store_tiny(longlong value)
5526 {
5527   char v= (char) value;
5528   return store_column(&v, 1);
5529 }
5530 
5531 
5532 /** Store a short as is (2 bytes, host order) in a result set column. */
5533 
5534 bool Protocol_local::store_short(longlong value)
5535 {
5536   int16 v= (int16) value;
5537   return store_column(&v, 2);
5538 }
5539 
5540 
5541 /** Store a "long" as is (4 bytes, host order) in a result set column.  */
5542 
5543 bool Protocol_local::store_long(longlong value)
5544 {
5545   int32 v= (int32) value;
5546   return store_column(&v, 4);
5547 }
5548 
5549 
5550 /** Store a "longlong" as is (8 bytes, host order) in a result set column. */
5551 
5552 bool Protocol_local::store_longlong(longlong value, bool unsigned_flag)
5553 {
5554   int64 v= (int64) value;
5555   return store_column(&v, 8);
5556 }
5557 
5558 
5559 /** Store a decimal in string format in a result set column */
5560 
5561 bool Protocol_local::store_decimal(const my_decimal *value)
5562 {
5563   char buf[DECIMAL_MAX_STR_LENGTH];
5564   String str(buf, sizeof (buf), &my_charset_bin);
5565   int rc;
5566 
5567   rc= my_decimal2string(E_DEC_FATAL_ERROR, value, 0, 0, 0, &str);
5568 
5569   if (rc)
5570     return TRUE;
5571 
5572   return store_column(str.ptr(), str.length());
5573 }
5574 
5575 
5576 /** Convert to cs_results and store a string. */
5577 
5578 bool Protocol_local::store(const char *str, size_t length,
5579                            CHARSET_INFO *src_cs)
5580 {
5581   CHARSET_INFO *dst_cs;
5582 
5583   dst_cs= m_connection->m_thd->variables.character_set_results;
5584   return store_string(str, length, src_cs, dst_cs);
5585 }
5586 
5587 
5588 /** Store a string. */
5589 
5590 bool Protocol_local::store(const char *str, size_t length,
5591                            CHARSET_INFO *src_cs, CHARSET_INFO *dst_cs)
5592 {
5593   return store_string(str, length, src_cs, dst_cs);
5594 }
5595 
5596 
5597 /* Store MYSQL_TIME (in binary format) */
5598 
5599 bool Protocol_local::store(MYSQL_TIME *time, int decimals)
5600 {
5601   if (decimals != AUTO_SEC_PART_DIGITS)
5602     my_time_trunc(time, decimals);
5603   return store_column(time, sizeof(MYSQL_TIME));
5604 }
5605 
5606 
5607 /** Store MYSQL_TIME (in binary format) */
5608 
5609 bool Protocol_local::store_date(MYSQL_TIME *time)
5610 {
5611   return store_column(time, sizeof(MYSQL_TIME));
5612 }
5613 
5614 
5615 /** Store MYSQL_TIME (in binary format) */
5616 
5617 bool Protocol_local::store_time(MYSQL_TIME *time, int decimals)
5618 {
5619   if (decimals != AUTO_SEC_PART_DIGITS)
5620     my_time_trunc(time, decimals);
5621   return store_column(time, sizeof(MYSQL_TIME));
5622 }
5623 
5624 
5625 /* Store a floating point number, as is. */
5626 
5627 bool Protocol_local::store(float value, uint32 decimals, String *buffer)
5628 {
5629   return store_column(&value, sizeof(float));
5630 }
5631 
5632 
5633 /* Store a double precision number, as is. */
5634 
5635 bool Protocol_local::store(double value, uint32 decimals, String *buffer)
5636 {
5637   return store_column(&value, sizeof (double));
5638 }
5639 
5640 
5641 /* Store a Field. */
5642 
5643 bool Protocol_local::store(Field *field)
5644 {
5645   if (field->is_null())
5646     return store_null();
5647   return field->send_binary(this);
5648 }
5649 
5650 
5651 /** Called to start a new result set. */
5652 
5653 bool Protocol_local::send_result_set_metadata(List<Item> *columns, uint)
5654 {
5655   DBUG_ASSERT(m_rset == 0 && !alloc_root_inited(&m_rset_root));
5656 
5657   init_sql_alloc(&m_rset_root, "send_result_set_metadata",
5658                  MEM_ROOT_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC));
5659 
5660   if (! (m_rset= new (&m_rset_root) List<Ed_row>))
5661     return TRUE;
5662 
5663   m_column_count= columns->elements;
5664 
5665   return FALSE;
5666 }
5667 
5668 
5669 /**
5670   Normally this is a separate result set with OUT parameters
5671   of stored procedures. Currently unsupported for the local
5672   version.
5673 */
5674 
5675 bool Protocol_local::send_out_parameters(List<Item_param> *sp_params)
5676 {
5677   return FALSE;
5678 }
5679 
5680 
5681 /** Called for statements that don't have a result set, at statement end. */
5682 
5683 bool
5684 Protocol_local::send_ok(uint server_status, uint statement_warn_count,
5685                         ulonglong affected_rows, ulonglong last_insert_id,
5686                         const char *message, bool skip_flush)
5687 {
5688   /*
5689     Just make sure nothing is sent to the client, we have grabbed
5690     the status information in the connection diagnostics area.
5691   */
5692   return FALSE;
5693 }
5694 
5695 
5696 /**
5697   Called at the end of a result set. Append a complete
5698   result set to the list in Ed_connection.
5699 
5700   Don't send anything to the client, but instead finish
5701   building of the result set at hand.
5702 */
5703 
5704 bool Protocol_local::send_eof(uint server_status, uint statement_warn_count)
5705 {
5706   Ed_result_set *ed_result_set;
5707 
5708   DBUG_ASSERT(m_rset);
5709 
5710   opt_add_row_to_rset();
5711   m_current_row= 0;
5712 
5713   ed_result_set= new (&m_rset_root) Ed_result_set(m_rset, m_column_count,
5714                                                   &m_rset_root);
5715 
5716   m_rset= NULL;
5717 
5718   if (! ed_result_set)
5719     return TRUE;
5720 
5721   /* In case of successful allocation memory ownership was transferred. */
5722   DBUG_ASSERT(!alloc_root_inited(&m_rset_root));
5723 
5724   /*
5725     Link the created Ed_result_set instance into the list of connection
5726     result sets. Never fails.
5727   */
5728   m_connection->add_result_set(ed_result_set);
5729   return FALSE;
5730 }
5731 
5732 
5733 /** Called to send an error to the client at the end of a statement. */
5734 
5735 bool
5736 Protocol_local::send_error(uint sql_errno, const char *err_msg, const char*)
5737 {
5738   /*
5739     Just make sure that nothing is sent to the client (default
5740     implementation).
5741   */
5742   return FALSE;
5743 }
5744 
5745 
5746 #ifdef EMBEDDED_LIBRARY
5747 void Protocol_local::remove_last_row()
5748 { }
5749 #endif
5750