MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_prepare.cc
Go to the documentation of this file.
1 /* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
86 #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
87 #include "sql_priv.h"
88 #include "unireg.h"
89 #include "sql_class.h" // set_var.h: THD
90 #include "set_var.h"
91 #include "sql_prepare.h"
92 #include "sql_parse.h" // insert_precheck, update_precheck, delete_precheck
93 #include "sql_base.h" // open_normal_and_derived_tables
94 #include "sql_cache.h" // query_cache_*
95 #include "sql_view.h" // create_view_precheck
96 #include "sql_delete.h" // mysql_prepare_delete
97 #include "sql_select.h" // for JOIN
98 #include "sql_insert.h" // upgrade_lock_type_for_insert, mysql_prepare_insert
99 #include "sql_update.h" // mysql_prepare_update
100 #include "sql_db.h" // mysql_opt_change_db, mysql_change_db
101 #include "sql_acl.h" // *_ACL
102 #include "sql_cursor.h"
103 #include "sp_head.h"
104 #include "sp.h"
105 #include "sp_cache.h"
106 #include "sql_handler.h" // mysql_ha_rm_tables
107 #include "probes_mysql.h"
108 #ifdef EMBEDDED_LIBRARY
109 /* include MYSQL_BIND headers */
110 #include <mysql.h>
111 #else
112 #include <mysql_com.h>
113 #endif
114 #include "lock.h" // MYSQL_OPEN_FORCE_SHARED_MDL
115 #include "opt_trace.h" // Opt_trace_object
116 #include "sql_analyse.h"
117 #include "sql_rewrite.h"
118 #include "transaction.h" // trans_rollback_implicit
119 
120 #include <algorithm>
121 using std::max;
122 using std::min;
123 
128 class Select_fetch_protocol_binary: public select_send
129 {
130  Protocol_binary protocol;
131 public:
133  virtual bool send_result_set_metadata(List<Item> &list, uint flags);
134  virtual bool send_data(List<Item> &items);
135  virtual bool send_eof();
136 #ifdef EMBEDDED_LIBRARY
137  void begin_dataset()
138  {
139  protocol.begin_dataset();
140  }
141 #endif
142 };
143 
144 /****************************************************************************/
145 
150 class Prepared_statement: public Statement
151 {
152 public:
153  enum flag_values
154  {
155  IS_IN_USE= 1,
156  IS_SQL_PREPARE= 2
157  };
158 
159  THD *thd;
161  Item_param **param_array;
162  Server_side_cursor *cursor;
163  uint param_count;
164  uint last_errno;
165  uint flags;
166  char last_error[MYSQL_ERRMSG_SIZE];
167 #ifndef EMBEDDED_LIBRARY
168  bool (*set_params)(Prepared_statement *st, uchar *data, uchar *data_end,
169  uchar *read_pos, String *expanded_query);
170 #else
171  bool (*set_params_data)(Prepared_statement *st, String *expanded_query);
172 #endif
173  bool (*set_params_from_vars)(Prepared_statement *stmt,
174  List<LEX_STRING>& varnames,
175  String *expanded_query);
176 public:
177  Prepared_statement(THD *thd_arg);
178  virtual ~Prepared_statement();
179  void setup_set_params();
180  virtual Query_arena::Type type() const;
181  virtual void cleanup_stmt();
182  bool set_name(LEX_STRING *name);
183  inline void close_cursor() { delete cursor; cursor= 0; }
184  inline bool is_in_use() { return flags & (uint) IS_IN_USE; }
185  inline bool is_sql_prepare() const { return flags & (uint) IS_SQL_PREPARE; }
186  void set_sql_prepare() { flags|= (uint) IS_SQL_PREPARE; }
187  bool prepare(const char *packet, uint packet_length);
188  bool execute_loop(String *expanded_query,
189  bool open_cursor,
190  uchar *packet_arg, uchar *packet_end_arg);
191  bool execute_server_runnable(Server_runnable *server_runnable);
192  /* Destroy this statement */
193  void deallocate();
194 private:
199  MEM_ROOT main_mem_root;
200 private:
201  bool set_db(const char *db, uint db_length);
202  bool set_parameters(String *expanded_query,
203  uchar *packet, uchar *packet_end);
204  bool execute(String *expanded_query, bool open_cursor);
205  bool reprepare();
206  bool validate_metadata(Prepared_statement *copy);
207  void swap_prepared_statement(Prepared_statement *copy);
208 };
209 
215 {
216 public:
218  virtual bool execute_server_code(THD *thd);
219 private:
220  LEX_STRING m_sql_text;
221 };
222 
223 
224 class Ed_connection;
225 
232 {
233 public:
234  Protocol_local(THD *thd, Ed_connection *ed_connection);
235  ~Protocol_local() { free_root(&m_rset_root, MYF(0)); }
236 protected:
237  virtual void prepare_for_resend();
238  virtual bool write();
239  virtual bool store_null();
240  virtual bool store_tiny(longlong from);
241  virtual bool store_short(longlong from);
242  virtual bool store_long(longlong from);
243  virtual bool store_longlong(longlong from, bool unsigned_flag);
244  virtual bool store_decimal(const my_decimal *);
245  virtual bool store(const char *from, size_t length, const CHARSET_INFO *cs);
246  virtual bool store(const char *from, size_t length,
247  const CHARSET_INFO *fromcs, const CHARSET_INFO *tocs);
248  virtual bool store(MYSQL_TIME *time, uint precision);
249  virtual bool store_date(MYSQL_TIME *time);
250  virtual bool store_time(MYSQL_TIME *time, uint precision);
251  virtual bool store(float value, uint32 decimals, String *buffer);
252  virtual bool store(double value, uint32 decimals, String *buffer);
253  virtual bool store(Field *field);
254 
255  virtual bool send_result_set_metadata(List<Item> *list, uint flags);
256  virtual bool send_out_parameters(List<Item_param> *sp_params);
257 #ifdef EMBEDDED_LIBRARY
258  void remove_last_row();
259 #endif
260  virtual enum enum_protocol_type type() { return PROTOCOL_LOCAL; };
261 
262  virtual bool send_ok(uint server_status, uint statement_warn_count,
263  ulonglong affected_rows, ulonglong last_insert_id,
264  const char *message);
265 
266  virtual bool send_eof(uint server_status, uint statement_warn_count);
267  virtual bool send_error(uint sql_errno, const char *err_msg, const char* sqlstate);
268 private:
269  bool store_string(const char *str, size_t length,
270  const CHARSET_INFO *src_cs, const CHARSET_INFO *dst_cs);
271 
272  bool store_column(const void *data, size_t length);
273  void opt_add_row_to_rset();
274 private:
275  Ed_connection *m_connection;
276  MEM_ROOT m_rset_root;
277  List<Ed_row> *m_rset;
278  size_t m_column_count;
279  Ed_column *m_current_row;
280  Ed_column *m_current_column;
281 };
282 
283 /******************************************************************************
284  Implementation
285 ******************************************************************************/
286 
287 static inline void rewrite_query_if_needed(THD *thd)
288 {
289  bool general= (opt_log &&
290  !(opt_log_raw || thd->slave_thread));
291 
292  if ((thd->sp_runtime_ctx == NULL) &&
293  (general || opt_slow_log || opt_bin_log))
294  mysql_rewrite_query(thd);
295 }
296 
297 static inline void log_execute_line(THD *thd)
298 {
299  /*
300  Do not print anything if this is an SQL prepared statement and
301  we're inside a stored procedure (also called Dynamic SQL) --
302  sub-statements inside stored procedures are not logged into
303  the general log.
304  */
305  if (thd->sp_runtime_ctx != NULL)
306  return;
307 
308  if (thd->rewritten_query.length())
309  logger.general_log_write(thd, COM_STMT_EXECUTE,
310  thd->rewritten_query.c_ptr_safe(),
311  thd->rewritten_query.length());
312  else
313  logger.general_log_write(thd, COM_STMT_EXECUTE,
314  thd->query(), thd->query_length());
315 }
316 
317 
318 inline bool is_param_null(const uchar *pos, ulong param_no)
319 {
320  return pos[param_no/8] & (1 << (param_no & 7));
321 }
322 
337 static Prepared_statement *
338 find_prepared_statement(THD *thd, ulong id)
339 {
340  /*
341  To strictly separate namespaces of SQL prepared statements and C API
342  prepared statements find() will return 0 if there is a named prepared
343  statement with such id.
344  */
345  Statement *stmt= thd->stmt_map.find(id);
346 
347  if (stmt == 0 || stmt->type() != Query_arena::PREPARED_STATEMENT)
348  return NULL;
349 
350  return (Prepared_statement *) stmt;
351 }
352 
353 
364 #ifndef EMBEDDED_LIBRARY
365 static bool send_prep_stmt(Prepared_statement *stmt, uint columns)
366 {
367  NET *net= &stmt->thd->net;
368  uchar buff[12];
369  uint tmp;
370  int error;
371  THD *thd= stmt->thd;
372  DBUG_ENTER("send_prep_stmt");
373 
374  buff[0]= 0; /* OK packet indicator */
375  int4store(buff+1, stmt->id);
376  int2store(buff+5, columns);
377  int2store(buff+7, stmt->param_count);
378  buff[9]= 0; // Guard against a 4.1 client
379  tmp= min(stmt->thd->get_stmt_da()->current_statement_warn_count(), 65535UL);
380  int2store(buff+10, tmp);
381 
382  /*
383  Send types and names of placeholders to the client
384  XXX: fix this nasty upcast from List<Item_param> to List<Item>
385  */
386  error= my_net_write(net, buff, sizeof(buff));
387  if (stmt->param_count && ! error)
388  {
389  error= thd->protocol_text.send_result_set_metadata((List<Item> *)
390  &stmt->lex->param_list,
391  Protocol::SEND_EOF);
392  }
393 
394  if (!error)
395  /* Flag that a response has already been sent */
396  thd->get_stmt_da()->disable_status();
397 
398  DBUG_RETURN(error);
399 }
400 #else
401 static bool send_prep_stmt(Prepared_statement *stmt,
402  uint columns __attribute__((unused)))
403 {
404  THD *thd= stmt->thd;
405 
406  thd->client_stmt_id= stmt->id;
407  thd->client_param_count= stmt->param_count;
408  thd->clear_error();
409  thd->get_stmt_da()->disable_status();
410 
411  return 0;
412 }
413 #endif
416 #ifndef EMBEDDED_LIBRARY
417 
432 static ulong get_param_length(uchar **packet, ulong len)
433 {
434  reg1 uchar *pos= *packet;
435  if (len < 1)
436  return 0;
437  if (*pos < 251)
438  {
439  (*packet)++;
440  return (ulong) *pos;
441  }
442  if (len < 3)
443  return 0;
444  if (*pos == 252)
445  {
446  (*packet)+=3;
447  return (ulong) uint2korr(pos+1);
448  }
449  if (len < 4)
450  return 0;
451  if (*pos == 253)
452  {
453  (*packet)+=4;
454  return (ulong) uint3korr(pos+1);
455  }
456  if (len < 5)
457  return 0;
458  (*packet)+=9; // Must be 254 when here
459  /*
460  In our client-server protocol all numbers bigger than 2^24
461  stored as 8 bytes with uint8korr. Here we always know that
462  parameter length is less than 2^4 so don't look at the second
463  4 bytes. But still we need to obey the protocol hence 9 in the
464  assignment above.
465  */
466  return (ulong) uint4korr(pos+1);
467 }
468 #else
469 #define get_param_length(packet, len) len
470 #endif
487 static void set_param_tiny(Item_param *param, uchar **pos, ulong len)
488 {
489 #ifndef EMBEDDED_LIBRARY
490  if (len < 1)
491  return;
492 #endif
493  int8 value= (int8) **pos;
494  param->set_int(param->unsigned_flag ? (longlong) ((uint8) value) :
495  (longlong) value, 4);
496  *pos+= 1;
497 }
498 
499 static void set_param_short(Item_param *param, 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  param->set_int(param->unsigned_flag ? (longlong) ((uint16) value) :
510  (longlong) value, 6);
511  *pos+= 2;
512 }
513 
514 static void set_param_int32(Item_param *param, 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  param->set_int(param->unsigned_flag ? (longlong) ((uint32) value) :
525  (longlong) value, 11);
526  *pos+= 4;
527 }
528 
529 static void set_param_int64(Item_param *param, 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  param->set_int(value, 21);
540  *pos+= 8;
541 }
542 
543 static void set_param_float(Item_param *param, 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  param->set_double((double) data);
554  *pos+= 4;
555 }
556 
557 static void set_param_double(Item_param *param, 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  param->set_double((double) data);
568  *pos+= 8;
569 }
570 
571 static void set_param_decimal(Item_param *param, uchar **pos, ulong len)
572 {
573  ulong length= get_param_length(pos, len);
574  param->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 
590 static void set_param_time(Item_param *param, 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  param->set_time(&tm, MYSQL_TIMESTAMP_TIME,
618  MAX_TIME_FULL_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
619  *pos+= length;
620 }
621 
622 static void set_param_datetime(Item_param *param, uchar **pos, ulong len)
623 {
624  MYSQL_TIME tm;
625  ulong length= get_param_length(pos, len);
626 
627  if (length >= 4)
628  {
629  uchar *to= *pos;
630 
631  tm.neg= 0;
632  tm.year= (uint) sint2korr(to);
633  tm.month= (uint) to[2];
634  tm.day= (uint) to[3];
635  if (length > 4)
636  {
637  tm.hour= (uint) to[4];
638  tm.minute= (uint) to[5];
639  tm.second= (uint) to[6];
640  }
641  else
642  tm.hour= tm.minute= tm.second= 0;
643 
644  tm.second_part= (length > 7) ? (ulong) sint4korr(to+7) : 0;
645  }
646  else
647  set_zero_time(&tm, MYSQL_TIMESTAMP_DATETIME);
648  param->set_time(&tm, MYSQL_TIMESTAMP_DATETIME,
649  MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
650  *pos+= length;
651 }
652 
653 
654 static void set_param_date(Item_param *param, uchar **pos, ulong len)
655 {
656  MYSQL_TIME tm;
657  ulong length= get_param_length(pos, len);
658 
659  if (length >= 4)
660  {
661  uchar *to= *pos;
662 
663  tm.year= (uint) sint2korr(to);
664  tm.month= (uint) to[2];
665  tm.day= (uint) to[3];
666 
667  tm.hour= tm.minute= tm.second= 0;
668  tm.second_part= 0;
669  tm.neg= 0;
670  }
671  else
672  set_zero_time(&tm, MYSQL_TIMESTAMP_DATE);
673  param->set_time(&tm, MYSQL_TIMESTAMP_DATE,
674  MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
675  *pos+= length;
676 }
677 
678 #else
683 void set_param_time(Item_param *param, uchar **pos, ulong len)
684 {
685  MYSQL_TIME tm= *((MYSQL_TIME*)*pos);
686  tm.hour+= tm.day * 24;
687  tm.day= tm.year= tm.month= 0;
688  if (tm.hour > 838)
689  {
690  /* TODO: add warning 'Data truncated' here */
691  tm.hour= 838;
692  tm.minute= 59;
693  tm.second= 59;
694  }
695  param->set_time(&tm, MYSQL_TIMESTAMP_TIME,
696  MAX_TIME_FULL_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
697 
698 }
699 
700 void set_param_datetime(Item_param *param, uchar **pos, ulong len)
701 {
702  MYSQL_TIME tm= *((MYSQL_TIME*)*pos);
703  tm.neg= 0;
704 
705  param->set_time(&tm, MYSQL_TIMESTAMP_DATETIME,
706  MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
707 }
708 
709 void set_param_date(Item_param *param, uchar **pos, ulong len)
710 {
711  MYSQL_TIME *to= (MYSQL_TIME*)*pos;
712 
713  param->set_time(to, MYSQL_TIMESTAMP_DATE,
714  MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
715 }
716 #endif
719 static void set_param_str(Item_param *param, uchar **pos, ulong len)
720 {
721  ulong length= get_param_length(pos, len);
722  if (length > len)
723  length= len;
724  param->set_str((const char *)*pos, length);
725  *pos+= length;
726 }
727 
728 
729 #undef get_param_length
730 
731 static void setup_one_conversion_function(THD *thd, Item_param *param,
732  uchar param_type)
733 {
734  switch (param_type) {
735  case MYSQL_TYPE_TINY:
736  param->set_param_func= set_param_tiny;
737  param->item_type= Item::INT_ITEM;
738  param->item_result_type= INT_RESULT;
739  break;
740  case MYSQL_TYPE_SHORT:
741  param->set_param_func= set_param_short;
742  param->item_type= Item::INT_ITEM;
743  param->item_result_type= INT_RESULT;
744  break;
745  case MYSQL_TYPE_LONG:
746  param->set_param_func= set_param_int32;
747  param->item_type= Item::INT_ITEM;
748  param->item_result_type= INT_RESULT;
749  break;
750  case MYSQL_TYPE_LONGLONG:
751  param->set_param_func= set_param_int64;
752  param->item_type= Item::INT_ITEM;
753  param->item_result_type= INT_RESULT;
754  break;
755  case MYSQL_TYPE_FLOAT:
756  param->set_param_func= set_param_float;
757  param->item_type= Item::REAL_ITEM;
758  param->item_result_type= REAL_RESULT;
759  break;
760  case MYSQL_TYPE_DOUBLE:
761  param->set_param_func= set_param_double;
762  param->item_type= Item::REAL_ITEM;
763  param->item_result_type= REAL_RESULT;
764  break;
765  case MYSQL_TYPE_DECIMAL:
766  case MYSQL_TYPE_NEWDECIMAL:
767  param->set_param_func= set_param_decimal;
768  param->item_type= Item::DECIMAL_ITEM;
769  param->item_result_type= DECIMAL_RESULT;
770  break;
771  case MYSQL_TYPE_TIME:
772  param->set_param_func= set_param_time;
773  param->item_type= Item::STRING_ITEM;
774  param->item_result_type= STRING_RESULT;
775  break;
776  case MYSQL_TYPE_DATE:
777  param->set_param_func= set_param_date;
778  param->item_type= Item::STRING_ITEM;
779  param->item_result_type= STRING_RESULT;
780  break;
781  case MYSQL_TYPE_DATETIME:
782  case MYSQL_TYPE_TIMESTAMP:
783  param->set_param_func= set_param_datetime;
784  param->item_type= Item::STRING_ITEM;
785  param->item_result_type= STRING_RESULT;
786  break;
787  case MYSQL_TYPE_TINY_BLOB:
788  case MYSQL_TYPE_MEDIUM_BLOB:
789  case MYSQL_TYPE_LONG_BLOB:
790  case MYSQL_TYPE_BLOB:
791  param->set_param_func= set_param_str;
792  param->value.cs_info.character_set_of_placeholder= &my_charset_bin;
793  param->value.cs_info.character_set_client=
794  thd->variables.character_set_client;
795  DBUG_ASSERT(thd->variables.character_set_client);
796  param->value.cs_info.final_character_set_of_str_value= &my_charset_bin;
797  param->item_type= Item::STRING_ITEM;
798  param->item_result_type= STRING_RESULT;
799  break;
800  default:
801  /*
802  The client library ensures that we won't get any other typecodes
803  except typecodes above and typecodes for string types. Marking
804  label as 'default' lets us to handle malformed packets as well.
805  */
806  {
807  const CHARSET_INFO *fromcs= thd->variables.character_set_client;
808  const CHARSET_INFO *tocs= thd->variables.collation_connection;
809  uint32 dummy_offset;
810 
811  param->value.cs_info.character_set_of_placeholder= fromcs;
812  param->value.cs_info.character_set_client= fromcs;
813 
814  /*
815  Setup source and destination character sets so that they
816  are different only if conversion is necessary: this will
817  make later checks easier.
818  */
819  param->value.cs_info.final_character_set_of_str_value=
820  String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
821  tocs : fromcs;
822  param->set_param_func= set_param_str;
823  /*
824  Exact value of max_length is not known unless data is converted to
825  charset of connection, so we have to set it later.
826  */
827  param->item_type= Item::STRING_ITEM;
828  param->item_result_type= STRING_RESULT;
829  }
830  }
831  param->param_type= (enum enum_field_types) param_type;
832 }
833 
834 #ifndef EMBEDDED_LIBRARY
835 
842 {
843  return ((param->param_type >= MYSQL_TYPE_TINY_BLOB) &&
844  (param->param_type <= MYSQL_TYPE_STRING));
845 }
846 
847 
886 static bool insert_params_with_log(Prepared_statement *stmt, uchar *null_array,
887  uchar *read_pos, uchar *data_end,
888  String *query)
889 {
890  THD *thd= stmt->thd;
891  Item_param **begin= stmt->param_array;
892  Item_param **end= begin + stmt->param_count;
893  uint32 length= 0;
894  String str;
895  const String *res;
896  DBUG_ENTER("insert_params_with_log");
897 
898  if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
899  DBUG_RETURN(1);
900 
901  for (Item_param **it= begin; it < end; ++it)
902  {
903  Item_param *param= *it;
904  if (param->state != Item_param::LONG_DATA_VALUE)
905  {
906  if (is_param_null(null_array, (uint) (it - begin)))
907  param->set_null();
908  else
909  {
910  if (read_pos >= data_end)
911  DBUG_RETURN(1);
912  param->set_param_func(param, &read_pos, (uint) (data_end - read_pos));
913  if (param->state == Item_param::NO_VALUE)
914  DBUG_RETURN(1);
915 
916  if (param->limit_clause_param && param->item_type != Item::INT_ITEM)
917  {
918  param->set_int(param->val_int(), MY_INT64_NUM_DECIMAL_DIGITS);
919  param->item_type= Item::INT_ITEM;
920  if (!param->unsigned_flag && param->value.integer < 0)
921  DBUG_RETURN(1);
922  }
923  }
924  }
925  /*
926  A long data stream was supplied for this parameter marker.
927  This was done after prepare, prior to providing a placeholder
928  type (the types are supplied at execute). Check that the
929  supplied type of placeholder can accept a data stream.
930  */
931  else if (! is_param_long_data_type(param))
932  DBUG_RETURN(1);
933  res= param->query_val_str(thd, &str);
934  if (param->convert_str_value(thd))
935  DBUG_RETURN(1); /* out of memory */
936 
937  if (query->replace(param->pos_in_query+length, 1, *res))
938  DBUG_RETURN(1);
939 
940  length+= res->length()-1;
941  }
942  DBUG_RETURN(0);
943 }
944 
945 
946 static bool insert_params(Prepared_statement *stmt, uchar *null_array,
947  uchar *read_pos, uchar *data_end,
948  String *expanded_query)
949 {
950  Item_param **begin= stmt->param_array;
951  Item_param **end= begin + stmt->param_count;
952 
953  DBUG_ENTER("insert_params");
954 
955  for (Item_param **it= begin; it < end; ++it)
956  {
957  Item_param *param= *it;
958  if (param->state != Item_param::LONG_DATA_VALUE)
959  {
960  if (is_param_null(null_array, (uint) (it - begin)))
961  param->set_null();
962  else
963  {
964  if (read_pos >= data_end)
965  DBUG_RETURN(1);
966  param->set_param_func(param, &read_pos, (uint) (data_end - read_pos));
967  if (param->state == Item_param::NO_VALUE)
968  DBUG_RETURN(1);
969  }
970  }
971  /*
972  A long data stream was supplied for this parameter marker.
973  This was done after prepare, prior to providing a placeholder
974  type (the types are supplied at execute). Check that the
975  supplied type of placeholder can accept a data stream.
976  */
977  else if (! is_param_long_data_type(param))
978  DBUG_RETURN(1);
979  if (param->convert_str_value(stmt->thd))
980  DBUG_RETURN(1); /* out of memory */
981  }
982  DBUG_RETURN(0);
983 }
984 
985 
986 static bool setup_conversion_functions(Prepared_statement *stmt,
987  uchar **data, uchar *data_end)
988 {
989  /* skip null bits */
990  uchar *read_pos= *data + (stmt->param_count+7) / 8;
991 
992  DBUG_ENTER("setup_conversion_functions");
993 
994  if (read_pos >= data_end)
995  DBUG_RETURN(1);
996 
997  if (*read_pos++) //types supplied / first execute
998  {
999  /*
1000  First execute or types altered by the client, setup the
1001  conversion routines for all parameters (one time)
1002  */
1003  Item_param **it= stmt->param_array;
1004  Item_param **end= it + stmt->param_count;
1005  THD *thd= stmt->thd;
1006  for (; it < end; ++it)
1007  {
1008  ushort typecode;
1009  const uint signed_bit= 1 << 15;
1010 
1011  if (read_pos >= data_end)
1012  DBUG_RETURN(1);
1013 
1014  typecode= sint2korr(read_pos);
1015  read_pos+= 2;
1016  (**it).unsigned_flag= test(typecode & signed_bit);
1017  setup_one_conversion_function(thd, *it, (uchar) (typecode & ~signed_bit));
1018  }
1019  }
1020  *data= read_pos;
1021  DBUG_RETURN(0);
1022 }
1023 
1024 #else
1025 
1037 static bool emb_insert_params(Prepared_statement *stmt, String *expanded_query)
1038 {
1039  THD *thd= stmt->thd;
1040  Item_param **it= stmt->param_array;
1041  Item_param **end= it + stmt->param_count;
1042  MYSQL_BIND *client_param= stmt->thd->client_params;
1043 
1044  DBUG_ENTER("emb_insert_params");
1045 
1046  for (; it < end; ++it, ++client_param)
1047  {
1048  Item_param *param= *it;
1049  setup_one_conversion_function(thd, param, client_param->buffer_type);
1050  if (param->state != Item_param::LONG_DATA_VALUE)
1051  {
1052  if (*client_param->is_null)
1053  param->set_null();
1054  else
1055  {
1056  uchar *buff= (uchar*) client_param->buffer;
1057  param->unsigned_flag= client_param->is_unsigned;
1058  param->set_param_func(param, &buff,
1059  client_param->length ?
1060  *client_param->length :
1061  client_param->buffer_length);
1062  if (param->state == Item_param::NO_VALUE)
1063  DBUG_RETURN(1);
1064  }
1065  }
1066  if (param->convert_str_value(thd))
1067  DBUG_RETURN(1); /* out of memory */
1068  }
1069  DBUG_RETURN(0);
1070 }
1071 
1072 
1073 static bool emb_insert_params_with_log(Prepared_statement *stmt,
1074  String *query)
1075 {
1076  THD *thd= stmt->thd;
1077  Item_param **it= stmt->param_array;
1078  Item_param **end= it + stmt->param_count;
1079  MYSQL_BIND *client_param= thd->client_params;
1080 
1081  String str;
1082  const String *res;
1083  uint32 length= 0;
1084 
1085  DBUG_ENTER("emb_insert_params_with_log");
1086 
1087  if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
1088  DBUG_RETURN(1);
1089 
1090  for (; it < end; ++it, ++client_param)
1091  {
1092  Item_param *param= *it;
1093  setup_one_conversion_function(thd, param, client_param->buffer_type);
1094  if (param->state != Item_param::LONG_DATA_VALUE)
1095  {
1096  if (*client_param->is_null)
1097  param->set_null();
1098  else
1099  {
1100  uchar *buff= (uchar*)client_param->buffer;
1101  param->unsigned_flag= client_param->is_unsigned;
1102  param->set_param_func(param, &buff,
1103  client_param->length ?
1104  *client_param->length :
1105  client_param->buffer_length);
1106  if (param->state == Item_param::NO_VALUE)
1107  DBUG_RETURN(1);
1108  }
1109  }
1110  res= param->query_val_str(thd, &str);
1111  if (param->convert_str_value(thd))
1112  DBUG_RETURN(1); /* out of memory */
1113 
1114  if (query->replace(param->pos_in_query+length, 1, *res))
1115  DBUG_RETURN(1);
1116 
1117  length+= res->length()-1;
1118  }
1119  DBUG_RETURN(0);
1120 }
1121 
1122 #endif
1160 static void
1161 swap_parameter_array(Item_param **param_array_dst,
1162  Item_param **param_array_src,
1163  uint param_count)
1164 {
1165  Item_param **dst= param_array_dst;
1166  Item_param **src= param_array_src;
1167  Item_param **end= param_array_dst + param_count;
1168 
1169  for (; dst < end; ++src, ++dst)
1170  (*dst)->set_param_type_and_swap_value(*src);
1171 }
1172 
1173 
1184 static bool insert_params_from_vars(Prepared_statement *stmt,
1185  List<LEX_STRING>& varnames,
1186  String *query __attribute__((unused)))
1187 {
1188  Item_param **begin= stmt->param_array;
1189  Item_param **end= begin + stmt->param_count;
1190  user_var_entry *entry;
1191  LEX_STRING *varname;
1192  List_iterator<LEX_STRING> var_it(varnames);
1193  DBUG_ENTER("insert_params_from_vars");
1194 
1195  for (Item_param **it= begin; it < end; ++it)
1196  {
1197  Item_param *param= *it;
1198  varname= var_it++;
1199  entry= (user_var_entry*)my_hash_search(&stmt->thd->user_vars,
1200  (uchar*) varname->str,
1201  varname->length);
1202  if (param->set_from_user_var(stmt->thd, entry) ||
1203  param->convert_str_value(stmt->thd))
1204  DBUG_RETURN(1);
1205  }
1206  DBUG_RETURN(0);
1207 }
1208 
1209 
1222 static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
1223  List<LEX_STRING>& varnames,
1224  String *query)
1225 {
1226  Item_param **begin= stmt->param_array;
1227  Item_param **end= begin + stmt->param_count;
1228  user_var_entry *entry;
1229  LEX_STRING *varname;
1230  List_iterator<LEX_STRING> var_it(varnames);
1231  String buf;
1232  const String *val;
1233  uint32 length= 0;
1234  THD *thd= stmt->thd;
1235 
1236  DBUG_ENTER("insert_params_from_vars_with_log");
1237 
1238  if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
1239  DBUG_RETURN(1);
1240 
1241  for (Item_param **it= begin; it < end; ++it)
1242  {
1243  Item_param *param= *it;
1244  varname= var_it++;
1245 
1246  entry= (user_var_entry *) my_hash_search(&thd->user_vars, (uchar*)
1247  varname->str, varname->length);
1248  /*
1249  We have to call the setup_one_conversion_function() here to set
1250  the parameter's members that might be needed further
1251  (e.g. value.cs_info.character_set_client is used in the query_val_str()).
1252  */
1253  setup_one_conversion_function(thd, param, param->param_type);
1254  if (param->set_from_user_var(thd, entry))
1255  DBUG_RETURN(1);
1256  val= param->query_val_str(thd, &buf);
1257 
1258  if (param->convert_str_value(thd))
1259  DBUG_RETURN(1); /* out of memory */
1260 
1261  if (query->replace(param->pos_in_query+length, 1, *val))
1262  DBUG_RETURN(1);
1263  length+= val->length()-1;
1264  }
1265  DBUG_RETURN(0);
1266 }
1267 
1280 static bool mysql_test_insert(Prepared_statement *stmt,
1281  TABLE_LIST *table_list,
1282  List<Item> &fields,
1283  List<List_item> &values_list,
1284  List<Item> &update_fields,
1285  List<Item> &update_values,
1286  enum_duplicates duplic)
1287 {
1288  THD *thd= stmt->thd;
1289  List_iterator_fast<List_item> its(values_list);
1290  List_item *values;
1291  DBUG_ENTER("mysql_test_insert");
1292  DBUG_ASSERT(stmt->is_stmt_prepare());
1293 
1294  /*
1295  Since INSERT DELAYED doesn't support temporary tables, we could
1296  not pre-open temporary tables for SQLCOM_INSERT / SQLCOM_REPLACE.
1297  Open them here instead.
1298  */
1299  if (table_list->lock_type != TL_WRITE_DELAYED)
1300  {
1301  if (open_temporary_tables(thd, table_list))
1302  goto error;
1303  }
1304 
1305  if (insert_precheck(thd, table_list))
1306  goto error;
1307 
1308  /*
1309  open temporary memory pool for temporary data allocated by derived
1310  tables & preparation procedure
1311  Note that this is done without locks (should not be needed as we will not
1312  access any data here)
1313  If we would use locks, then we have to ensure we are not using
1314  TL_WRITE_DELAYED as having two such locks can cause table corruption.
1315  */
1316  if (open_normal_and_derived_tables(thd, table_list,
1317  MYSQL_OPEN_FORCE_SHARED_MDL))
1318  goto error;
1319 
1320  if ((values= its++))
1321  {
1322  uint value_count;
1323  ulong counter= 0;
1324  Item *unused_conds= 0;
1325 
1326  if (table_list->table)
1327  {
1328  // don't allocate insert_values
1329  table_list->table->insert_values=(uchar *)1;
1330  }
1331 
1332  if (mysql_prepare_insert(thd, table_list, table_list->table,
1333  fields, values, update_fields, update_values,
1334  duplic, &unused_conds, FALSE, FALSE, FALSE))
1335  goto error;
1336 
1337  value_count= values->elements;
1338  its.rewind();
1339 
1340  if (table_list->lock_type == TL_WRITE_DELAYED &&
1341  !(table_list->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED))
1342  {
1343  my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), (table_list->view ?
1344  table_list->view_name.str :
1345  table_list->table_name));
1346  goto error;
1347  }
1348  while ((values= its++))
1349  {
1350  counter++;
1351  if (values->elements != value_count)
1352  {
1353  my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
1354  goto error;
1355  }
1356  if (setup_fields(thd, Ref_ptr_array(), *values, MARK_COLUMNS_NONE, 0, 0))
1357  goto error;
1358  }
1359  }
1360  DBUG_RETURN(FALSE);
1361 
1362 error:
1363  /* insert_values is cleared in open_table */
1364  DBUG_RETURN(TRUE);
1365 }
1366 
1367 
1385 static int mysql_test_update(Prepared_statement *stmt,
1386  TABLE_LIST *table_list)
1387 {
1388  int res;
1389  THD *thd= stmt->thd;
1390  SELECT_LEX *select= &stmt->lex->select_lex;
1391 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1392  uint want_privilege;
1393 #endif
1394  DBUG_ENTER("mysql_test_update");
1395 
1396  if (update_precheck(thd, table_list) ||
1397  open_normal_and_derived_tables(thd, table_list,
1398  MYSQL_OPEN_FORCE_SHARED_MDL))
1399  goto error;
1400 
1401  if (table_list->multitable_view)
1402  {
1403  DBUG_ASSERT(table_list->view != 0);
1404  DBUG_PRINT("info", ("Switch to multi-update"));
1405  /* convert to multiupdate */
1406  DBUG_RETURN(2);
1407  }
1408 
1409  if (!table_list->updatable)
1410  {
1411  my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "UPDATE");
1412  goto error;
1413  }
1414 
1415 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1416  /* Force privilege re-checking for views after they have been opened. */
1417  want_privilege= (table_list->view ? UPDATE_ACL :
1418  table_list->grant.want_privilege);
1419 #endif
1420 
1421  if (mysql_prepare_update(thd, table_list, &select->where,
1422  select->order_list.elements,
1423  select->order_list.first))
1424  goto error;
1425 
1426 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1427  table_list->grant.want_privilege= want_privilege;
1428  table_list->table->grant.want_privilege= want_privilege;
1429  table_list->register_want_access(want_privilege);
1430 #endif
1431  thd->lex->select_lex.no_wrap_view_item= TRUE;
1432  res= setup_fields(thd, Ref_ptr_array(),
1433  select->item_list, MARK_COLUMNS_READ, 0, 0);
1434  thd->lex->select_lex.no_wrap_view_item= FALSE;
1435  if (res)
1436  goto error;
1437 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1438  /* Check values */
1439  table_list->grant.want_privilege=
1440  table_list->table->grant.want_privilege=
1441  (SELECT_ACL & ~table_list->table->grant.privilege);
1442  table_list->register_want_access(SELECT_ACL);
1443 #endif
1444  if (setup_fields(thd, Ref_ptr_array(),
1445  stmt->lex->value_list, MARK_COLUMNS_NONE, 0, 0))
1446  goto error;
1447  /* TODO: here we should send types of placeholders to the client. */
1448  DBUG_RETURN(0);
1449 error:
1450  DBUG_RETURN(1);
1451 }
1452 
1453 
1466 static bool mysql_test_delete(Prepared_statement *stmt,
1467  TABLE_LIST *table_list)
1468 {
1469  THD *thd= stmt->thd;
1470  LEX *lex= stmt->lex;
1471  DBUG_ENTER("mysql_test_delete");
1472  DBUG_ASSERT(stmt->is_stmt_prepare());
1473 
1474  if (delete_precheck(thd, table_list) ||
1475  open_normal_and_derived_tables(thd, table_list,
1476  MYSQL_OPEN_FORCE_SHARED_MDL))
1477  goto error;
1478 
1479  if (!table_list->table)
1480  {
1481  my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
1482  table_list->view_db.str, table_list->view_name.str);
1483  goto error;
1484  }
1485 
1486  DBUG_RETURN(mysql_prepare_delete(thd, table_list, &lex->select_lex.where));
1487 error:
1488  DBUG_RETURN(TRUE);
1489 }
1490 
1491 
1509 static int mysql_test_select(Prepared_statement *stmt,
1510  TABLE_LIST *tables)
1511 {
1512  THD *thd= stmt->thd;
1513  LEX *lex= stmt->lex;
1514  SELECT_LEX_UNIT *unit= &lex->unit;
1515  DBUG_ENTER("mysql_test_select");
1516 
1517  lex->select_lex.context.resolve_in_select_list= TRUE;
1518 
1519  if (select_precheck(thd, lex, tables, lex->select_lex.table_list.first))
1520  goto error;
1521 
1522  if (!lex->result && !(lex->result= new (stmt->mem_root) select_send))
1523  {
1524  my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR),
1525  static_cast<int>(sizeof(select_send)));
1526  goto error;
1527  }
1528 
1529  if (open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL))
1530  goto error;
1531 
1532  thd->lex->used_tables= 0; // Updated by setup_fields
1533 
1534  /*
1535  JOIN::prepare calls
1536  It is not SELECT COMMAND for sure, so setup_tables will be called as
1537  usual, and we pass 0 as setup_tables_done_option
1538  */
1539  if (unit->prepare(thd, 0, 0))
1540  goto error;
1541  if (!lex->describe && !stmt->is_sql_prepare())
1542  {
1543  select_result *result= lex->result;
1544  select_result *analyse_result= NULL;
1545  if (lex->proc_analyse)
1546  {
1547  /*
1548  We need proper output recordset metadata for SELECT ... PROCEDURE ANALUSE()
1549  */
1550  if ((result= analyse_result=
1551  new select_analyse(result, lex->proc_analyse)) == NULL)
1552  goto error; // OOM
1553  }
1554 
1555  /*
1556  We can use "result" as it should've been prepared in
1557  unit->prepare call above.
1558  */
1559  bool rc= (send_prep_stmt(stmt, result->field_count(unit->types)) ||
1560  result->send_result_set_metadata(unit->types,
1561  Protocol::SEND_EOF) ||
1562  thd->protocol->flush());
1563  delete analyse_result;
1564  if (rc)
1565  goto error;
1566  DBUG_RETURN(2);
1567  }
1568  DBUG_RETURN(0);
1569 error:
1570  DBUG_RETURN(1);
1571 }
1572 
1573 
1587 static bool mysql_test_do_fields(Prepared_statement *stmt,
1588  TABLE_LIST *tables,
1589  List<Item> *values)
1590 {
1591  THD *thd= stmt->thd;
1592 
1593  DBUG_ENTER("mysql_test_do_fields");
1594  DBUG_ASSERT(stmt->is_stmt_prepare());
1595  if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
1596  UINT_MAX, FALSE))
1597  DBUG_RETURN(TRUE);
1598 
1599  if (open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL))
1600  DBUG_RETURN(TRUE);
1601  DBUG_RETURN(setup_fields(thd, Ref_ptr_array(),
1602  *values, MARK_COLUMNS_NONE, 0, 0));
1603 }
1604 
1605 
1619 static bool mysql_test_set_fields(Prepared_statement *stmt,
1620  TABLE_LIST *tables,
1621  List<set_var_base> *var_list)
1622 {
1623  List_iterator_fast<set_var_base> it(*var_list);
1624  THD *thd= stmt->thd;
1625  set_var_base *var;
1626  DBUG_ENTER("mysql_test_set_fields");
1627  DBUG_ASSERT(stmt->is_stmt_prepare());
1628 
1629  if ((tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
1630  UINT_MAX, FALSE)) ||
1631  open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL))
1632  goto error;
1633 
1634  while ((var= it++))
1635  {
1636  if (var->light_check(thd))
1637  goto error;
1638  }
1639  DBUG_RETURN(FALSE);
1640 error:
1641  DBUG_RETURN(TRUE);
1642 }
1643 
1644 
1656 static bool mysql_test_call_fields(Prepared_statement *stmt,
1657  TABLE_LIST *tables,
1658  List<Item> *value_list)
1659 {
1660  List_iterator<Item> it(*value_list);
1661  THD *thd= stmt->thd;
1662  Item *item;
1663  DBUG_ENTER("mysql_test_call_fields");
1664  DBUG_ASSERT(stmt->is_stmt_prepare());
1665 
1666  if ((tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
1667  UINT_MAX, FALSE)) ||
1668  open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL))
1669  goto err;
1670 
1671  while ((item= it++))
1672  {
1673  if ((!item->fixed && item->fix_fields(thd, it.ref())) ||
1674  item->check_cols(1))
1675  goto err;
1676  }
1677  DBUG_RETURN(FALSE);
1678 err:
1679  DBUG_RETURN(TRUE);
1680 }
1681 
1682 
1702 static bool select_like_stmt_test(Prepared_statement *stmt,
1703  int (*specific_prepare)(THD *thd),
1704  ulong setup_tables_done_option)
1705 {
1706  DBUG_ENTER("select_like_stmt_test");
1707  THD *thd= stmt->thd;
1708  LEX *lex= stmt->lex;
1709 
1710  lex->select_lex.context.resolve_in_select_list= TRUE;
1711 
1712  if (specific_prepare && (*specific_prepare)(thd))
1713  DBUG_RETURN(TRUE);
1714 
1715  thd->lex->used_tables= 0; // Updated by setup_fields
1716 
1717  /* Calls JOIN::prepare */
1718  DBUG_RETURN(lex->unit.prepare(thd, 0, setup_tables_done_option));
1719 }
1720 
1737 static bool
1738 select_like_stmt_test_with_open(Prepared_statement *stmt,
1739  TABLE_LIST *tables,
1740  int (*specific_prepare)(THD *thd),
1741  ulong setup_tables_done_option)
1742 {
1743  DBUG_ENTER("select_like_stmt_test_with_open");
1744  DBUG_ASSERT(stmt->is_stmt_prepare());
1745 
1746  /*
1747  We should not call LEX::unit.cleanup() after this
1748  open_normal_and_derived_tables() call because we don't allow
1749  prepared EXPLAIN yet so derived tables will clean up after
1750  themself.
1751  */
1752  if (open_normal_and_derived_tables(stmt->thd, tables,
1753  MYSQL_OPEN_FORCE_SHARED_MDL))
1754  DBUG_RETURN(TRUE);
1755 
1756  DBUG_RETURN(select_like_stmt_test(stmt, specific_prepare,
1757  setup_tables_done_option));
1758 }
1759 
1760 
1773 static bool mysql_test_create_table(Prepared_statement *stmt)
1774 {
1775  THD *thd= stmt->thd;
1776  LEX *lex= stmt->lex;
1777  SELECT_LEX *select_lex= &lex->select_lex;
1778  bool res= FALSE;
1779  bool link_to_local;
1780  TABLE_LIST *create_table= lex->query_tables;
1781  TABLE_LIST *tables= lex->create_last_non_select_table->next_global;
1782  DBUG_ENTER("mysql_test_create_table");
1783  DBUG_ASSERT(stmt->is_stmt_prepare());
1784 
1785  if (create_table_precheck(thd, tables, create_table))
1786  DBUG_RETURN(TRUE);
1787 
1788  if (select_lex->item_list.elements)
1789  {
1790  /* Base table and temporary table are not in the same name space. */
1791  if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
1792  create_table->open_type= OT_BASE_ONLY;
1793 
1794  if (open_normal_and_derived_tables(stmt->thd, lex->query_tables,
1795  MYSQL_OPEN_FORCE_SHARED_MDL))
1796  DBUG_RETURN(TRUE);
1797 
1798  select_lex->context.resolve_in_select_list= TRUE;
1799 
1800  lex->unlink_first_table(&link_to_local);
1801 
1802  res= select_like_stmt_test(stmt, 0, 0);
1803 
1804  lex->link_first_table_back(create_table, link_to_local);
1805  }
1806  else
1807  {
1808  /*
1809  Check that the source table exist, and also record
1810  its metadata version. Even though not strictly necessary,
1811  we validate metadata of all CREATE TABLE statements,
1812  which keeps metadata validation code simple.
1813  */
1814  if (open_normal_and_derived_tables(stmt->thd, lex->query_tables,
1815  MYSQL_OPEN_FORCE_SHARED_MDL))
1816  DBUG_RETURN(TRUE);
1817  }
1818 
1819  DBUG_RETURN(res);
1820 }
1821 
1822 
1834 static bool mysql_test_create_view(Prepared_statement *stmt)
1835 {
1836  THD *thd= stmt->thd;
1837  LEX *lex= stmt->lex;
1838  bool res= TRUE;
1839  /* Skip first table, which is the view we are creating */
1840  bool link_to_local;
1841  TABLE_LIST *view= lex->unlink_first_table(&link_to_local);
1842  TABLE_LIST *tables= lex->query_tables;
1843  DBUG_ENTER("mysql_test_create_view");
1844  DBUG_ASSERT(stmt->is_stmt_prepare());
1845 
1846  if (create_view_precheck(thd, tables, view, lex->create_view_mode))
1847  goto err;
1848 
1849  /*
1850  Since we can't pre-open temporary tables for SQLCOM_CREATE_VIEW,
1851  (see mysql_create_view) we have to do it here instead.
1852  */
1853  if (open_temporary_tables(thd, tables))
1854  goto err;
1855 
1856  if (open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL))
1857  goto err;
1858 
1859  lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW;
1860  res= select_like_stmt_test(stmt, 0, 0);
1861 
1862 err:
1863  /* put view back for PS rexecuting */
1864  lex->link_first_table_back(view, link_to_local);
1865  DBUG_RETURN(res);
1866 }
1867 
1868 
1869 /*
1870  Validate and prepare for execution a multi update statement.
1871 
1872  @param stmt prepared statement
1873  @param tables list of tables used in this query
1874  @param converted converted to multi-update from usual update
1875 
1876  @retval
1877  FALSE success
1878  @retval
1879  TRUE error, error message is set in THD
1880 */
1881 
1882 static bool mysql_test_multiupdate(Prepared_statement *stmt,
1883  TABLE_LIST *tables,
1884  bool converted)
1885 {
1886  /* if we switched from normal update, rights are checked */
1887  if (!converted && multi_update_precheck(stmt->thd, tables))
1888  return TRUE;
1889 
1890  return select_like_stmt_test(stmt, &mysql_multi_update_prepare,
1892 }
1893 
1894 
1900 static int mysql_multi_delete_prepare_tester(THD *thd)
1901 {
1902  uint table_count;
1903  return mysql_multi_delete_prepare(thd, &table_count);
1904 }
1905 
1906 
1919 static bool mysql_test_multidelete(Prepared_statement *stmt,
1920  TABLE_LIST *tables)
1921 {
1922  stmt->thd->lex->current_select= &stmt->thd->lex->select_lex;
1923  if (add_item_to_list(stmt->thd, new Item_null()))
1924  {
1925  my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR), 0);
1926  goto error;
1927  }
1928 
1929  if (multi_delete_precheck(stmt->thd, tables) ||
1930  select_like_stmt_test_with_open(stmt, tables,
1931  &mysql_multi_delete_prepare_tester,
1933  goto error;
1934  if (!tables->table)
1935  {
1936  my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
1937  tables->view_db.str, tables->view_name.str);
1938  goto error;
1939  }
1940  return FALSE;
1941 error:
1942  return TRUE;
1943 }
1944 
1945 
1958 static int mysql_insert_select_prepare_tester(THD *thd)
1959 {
1960  SELECT_LEX *first_select= &thd->lex->select_lex;
1961  TABLE_LIST *second_table= first_select->table_list.first->next_local;
1962 
1963  /* Skip first table, which is the table we are inserting in */
1964  first_select->table_list.first= second_table;
1965  thd->lex->select_lex.context.table_list=
1966  thd->lex->select_lex.context.first_name_resolution_table= second_table;
1967 
1968  return mysql_insert_select_prepare(thd);
1969 }
1970 
1971 
1984 static bool mysql_test_insert_select(Prepared_statement *stmt,
1985  TABLE_LIST *tables)
1986 {
1987  int res;
1988  LEX *lex= stmt->lex;
1989  TABLE_LIST *first_local_table;
1990 
1991  if (tables->table)
1992  {
1993  // don't allocate insert_values
1994  tables->table->insert_values=(uchar *)1;
1995  }
1996 
1997  if (insert_precheck(stmt->thd, tables))
1998  return 1;
1999 
2000  /* store it, because mysql_insert_select_prepare_tester change it */
2001  first_local_table= lex->select_lex.table_list.first;
2002  DBUG_ASSERT(first_local_table != 0);
2003 
2004  res=
2005  select_like_stmt_test_with_open(stmt, tables,
2006  &mysql_insert_select_prepare_tester,
2008  /* revert changes made by mysql_insert_select_prepare_tester */
2009  lex->select_lex.table_list.first= first_local_table;
2010  return res;
2011 }
2012 
2013 
2031 static bool check_prepared_statement(Prepared_statement *stmt)
2032 {
2033  THD *thd= stmt->thd;
2034  LEX *lex= stmt->lex;
2035  SELECT_LEX *select_lex= &lex->select_lex;
2036  TABLE_LIST *tables;
2037  enum enum_sql_command sql_command= lex->sql_command;
2038  int res= 0;
2039  DBUG_ENTER("check_prepared_statement");
2040  DBUG_PRINT("enter",("command: %d param_count: %u",
2041  sql_command, stmt->param_count));
2042 
2043  lex->first_lists_tables_same();
2044  tables= lex->query_tables;
2045 
2046  /* set context for commands which do not use setup_tables */
2047  lex->select_lex.context.resolve_in_table_list_only(select_lex->
2048  get_table_list());
2049 
2050  /* Reset warning count for each query that uses tables */
2051  if (tables)
2052  thd->get_stmt_da()->opt_clear_warning_info(thd->query_id);
2053 
2054  /*
2055  For the optimizer trace, this is the symmetric, for statement preparation,
2056  of what is done at statement execution (in mysql_execute_command()).
2057  */
2058  Opt_trace_start ots(thd, tables, sql_command, &lex->var_list,
2059  thd->query(), thd->query_length(), NULL,
2060  thd->variables.character_set_client);
2061 
2062  Opt_trace_object trace_command(&thd->opt_trace);
2063  Opt_trace_array trace_command_steps(&thd->opt_trace, "steps");
2064 
2065  if (sql_command_flags[sql_command] & CF_HA_CLOSE)
2066  mysql_ha_rm_tables(thd, tables);
2067 
2068  /*
2069  Open temporary tables that are known now. Temporary tables added by
2070  prelocking will be opened afterwards (during open_tables()).
2071  */
2072  if (sql_command_flags[sql_command] & CF_PREOPEN_TMP_TABLES)
2073  {
2074  if (open_temporary_tables(thd, tables))
2075  goto error;
2076  }
2077 
2078  switch (sql_command) {
2079  case SQLCOM_REPLACE:
2080  case SQLCOM_INSERT:
2081  res= mysql_test_insert(stmt, tables, lex->field_list,
2082  lex->many_values,
2083  lex->update_list, lex->value_list,
2084  lex->duplicates);
2085  break;
2086 
2087  case SQLCOM_UPDATE:
2088  res= mysql_test_update(stmt, tables);
2089  /* mysql_test_update returns 2 if we need to switch to multi-update */
2090  if (res != 2)
2091  break;
2092 
2093  case SQLCOM_UPDATE_MULTI:
2094  res= mysql_test_multiupdate(stmt, tables, res == 2);
2095  break;
2096 
2097  case SQLCOM_DELETE:
2098  res= mysql_test_delete(stmt, tables);
2099  break;
2100  /* The following allow WHERE clause, so they must be tested like SELECT */
2101  case SQLCOM_SHOW_DATABASES:
2102  case SQLCOM_SHOW_TABLES:
2103  case SQLCOM_SHOW_TRIGGERS:
2104  case SQLCOM_SHOW_EVENTS:
2105  case SQLCOM_SHOW_OPEN_TABLES:
2106  case SQLCOM_SHOW_FIELDS:
2107  case SQLCOM_SHOW_KEYS:
2108  case SQLCOM_SHOW_COLLATIONS:
2109  case SQLCOM_SHOW_CHARSETS:
2110  case SQLCOM_SHOW_VARIABLES:
2111  case SQLCOM_SHOW_STATUS:
2112  case SQLCOM_SHOW_TABLE_STATUS:
2113  case SQLCOM_SHOW_STATUS_PROC:
2114  case SQLCOM_SHOW_STATUS_FUNC:
2115  case SQLCOM_SELECT:
2116  res= mysql_test_select(stmt, tables);
2117  if (res == 2)
2118  {
2119  /* Statement and field info has already been sent */
2120  DBUG_RETURN(FALSE);
2121  }
2122  break;
2123  case SQLCOM_CREATE_TABLE:
2124  res= mysql_test_create_table(stmt);
2125  break;
2126 
2127  case SQLCOM_CREATE_VIEW:
2128  if (lex->create_view_mode == VIEW_ALTER)
2129  {
2130  my_message(ER_UNSUPPORTED_PS, ER(ER_UNSUPPORTED_PS), MYF(0));
2131  goto error;
2132  }
2133  res= mysql_test_create_view(stmt);
2134  break;
2135  case SQLCOM_DO:
2136  res= mysql_test_do_fields(stmt, tables, lex->insert_list);
2137  break;
2138 
2139  case SQLCOM_CALL:
2140  res= mysql_test_call_fields(stmt, tables, &lex->value_list);
2141  break;
2142  case SQLCOM_SET_OPTION:
2143  res= mysql_test_set_fields(stmt, tables, &lex->var_list);
2144  break;
2145 
2146  case SQLCOM_DELETE_MULTI:
2147  res= mysql_test_multidelete(stmt, tables);
2148  break;
2149 
2150  case SQLCOM_INSERT_SELECT:
2151  case SQLCOM_REPLACE_SELECT:
2152  res= mysql_test_insert_select(stmt, tables);
2153  break;
2154 
2155  /*
2156  Note that we don't need to have cases in this list if they are
2157  marked with CF_STATUS_COMMAND in sql_command_flags
2158  */
2159  case SQLCOM_DROP_TABLE:
2160  case SQLCOM_RENAME_TABLE:
2161  case SQLCOM_ALTER_TABLE:
2162  case SQLCOM_COMMIT:
2163  case SQLCOM_CREATE_INDEX:
2164  case SQLCOM_DROP_INDEX:
2165  case SQLCOM_ROLLBACK:
2166  case SQLCOM_TRUNCATE:
2167  case SQLCOM_DROP_VIEW:
2168  case SQLCOM_REPAIR:
2169  case SQLCOM_ANALYZE:
2170  case SQLCOM_OPTIMIZE:
2171  case SQLCOM_CHANGE_MASTER:
2172  case SQLCOM_RESET:
2173  case SQLCOM_FLUSH:
2174  case SQLCOM_SLAVE_START:
2175  case SQLCOM_SLAVE_STOP:
2176  case SQLCOM_INSTALL_PLUGIN:
2177  case SQLCOM_UNINSTALL_PLUGIN:
2178  case SQLCOM_CREATE_DB:
2179  case SQLCOM_DROP_DB:
2180  case SQLCOM_ALTER_DB_UPGRADE:
2181  case SQLCOM_CHECKSUM:
2182  case SQLCOM_CREATE_USER:
2183  case SQLCOM_RENAME_USER:
2184  case SQLCOM_DROP_USER:
2185  case SQLCOM_ALTER_USER:
2186  case SQLCOM_ASSIGN_TO_KEYCACHE:
2187  case SQLCOM_PRELOAD_KEYS:
2188  case SQLCOM_GRANT:
2189  case SQLCOM_REVOKE:
2190  case SQLCOM_KILL:
2191  break;
2192 
2193  case SQLCOM_PREPARE:
2194  case SQLCOM_EXECUTE:
2195  case SQLCOM_DEALLOCATE_PREPARE:
2196  default:
2197  /*
2198  Trivial check of all status commands. This is easier than having
2199  things in the above case list, as it's less chance for mistakes.
2200  */
2201  if (!(sql_command_flags[sql_command] & CF_STATUS_COMMAND))
2202  {
2203  /* All other statements are not supported yet. */
2204  my_message(ER_UNSUPPORTED_PS, ER(ER_UNSUPPORTED_PS), MYF(0));
2205  goto error;
2206  }
2207  break;
2208  }
2209  if (res == 0)
2210  DBUG_RETURN(stmt->is_sql_prepare() ?
2211  FALSE : (send_prep_stmt(stmt, 0) || thd->protocol->flush()));
2212 error:
2213  DBUG_RETURN(TRUE);
2214 }
2215 
2222 static bool init_param_array(Prepared_statement *stmt)
2223 {
2224  LEX *lex= stmt->lex;
2225  if ((stmt->param_count= lex->param_list.elements))
2226  {
2227  if (stmt->param_count > (uint) UINT_MAX16)
2228  {
2229  /* Error code to be defined in 5.0 */
2230  my_message(ER_PS_MANY_PARAM, ER(ER_PS_MANY_PARAM), MYF(0));
2231  return TRUE;
2232  }
2233  Item_param **to;
2234  List_iterator<Item_param> param_iterator(lex->param_list);
2235  /* Use thd->mem_root as it points at statement mem_root */
2236  stmt->param_array= (Item_param **)
2237  alloc_root(stmt->thd->mem_root,
2238  sizeof(Item_param*) * stmt->param_count);
2239  if (!stmt->param_array)
2240  return TRUE;
2241  for (to= stmt->param_array;
2242  to < stmt->param_array + stmt->param_count;
2243  ++to)
2244  {
2245  *to= param_iterator++;
2246  }
2247  }
2248  return FALSE;
2249 }
2250 
2251 
2278 void mysqld_stmt_prepare(THD *thd, const char *packet, uint packet_length)
2279 {
2280  Protocol *save_protocol= thd->protocol;
2281  Prepared_statement *stmt;
2282  DBUG_ENTER("mysqld_stmt_prepare");
2283 
2284  DBUG_PRINT("prep_query", ("%s", packet));
2285 
2286  /* First of all clear possible warnings from the previous command */
2288 
2289  if (! (stmt= new Prepared_statement(thd)))
2290  DBUG_VOID_RETURN; /* out of memory: error is set in Sql_alloc */
2291 
2292  if (thd->stmt_map.insert(thd, stmt))
2293  {
2294  /*
2295  The error is set in the insert. The statement itself
2296  will be also deleted there (this is how the hash works).
2297  */
2298  DBUG_VOID_RETURN;
2299  }
2300 
2301  thd->protocol= &thd->protocol_binary;
2302 
2303  if (stmt->prepare(packet, packet_length))
2304  {
2305  /* Statement map deletes statement on erase */
2306  thd->stmt_map.erase(stmt);
2307  }
2308 
2309  thd->protocol= save_protocol;
2310 
2311  sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
2312  sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
2313 
2314  /* check_prepared_statemnt sends the metadata packet in case of success */
2315  DBUG_VOID_RETURN;
2316 }
2317 
2336 static const char *get_dynamic_sql_string(LEX *lex, uint *query_len)
2337 {
2338  THD *thd= lex->thd;
2339  char *query_str= 0;
2340 
2341  if (lex->prepared_stmt_code_is_varref)
2342  {
2343  /* This is PREPARE stmt FROM or EXECUTE IMMEDIATE @var. */
2344  String str;
2345  const CHARSET_INFO *to_cs= thd->variables.collation_connection;
2346  bool needs_conversion;
2347  user_var_entry *entry;
2348  String *var_value= &str;
2349  uint32 unused, len;
2350  /*
2351  Convert @var contents to string in connection character set. Although
2352  it is known that int/real/NULL value cannot be a valid query we still
2353  convert it for error messages to be uniform.
2354  */
2355  if ((entry=
2356  (user_var_entry*)my_hash_search(&thd->user_vars,
2357  (uchar*)lex->prepared_stmt_code.str,
2358  lex->prepared_stmt_code.length))
2359  && entry->ptr())
2360  {
2361  my_bool is_var_null;
2362  var_value= entry->val_str(&is_var_null, &str, NOT_FIXED_DEC);
2363  /*
2364  NULL value of variable checked early as entry->value so here
2365  we can't get NULL in normal conditions
2366  */
2367  DBUG_ASSERT(!is_var_null);
2368  if (!var_value)
2369  goto end;
2370  }
2371  else
2372  {
2373  /*
2374  variable absent or equal to NULL, so we need to set variable to
2375  something reasonable to get a readable error message during parsing
2376  */
2377  str.set(STRING_WITH_LEN("NULL"), &my_charset_latin1);
2378  }
2379 
2380  needs_conversion= String::needs_conversion(var_value->length(),
2381  var_value->charset(), to_cs,
2382  &unused);
2383 
2384  len= (needs_conversion ? var_value->length() * to_cs->mbmaxlen :
2385  var_value->length());
2386  if (!(query_str= (char*) alloc_root(thd->mem_root, len+1)))
2387  goto end;
2388 
2389  if (needs_conversion)
2390  {
2391  uint dummy_errors;
2392  len= copy_and_convert(query_str, len, to_cs, var_value->ptr(),
2393  var_value->length(), var_value->charset(),
2394  &dummy_errors);
2395  }
2396  else
2397  memcpy(query_str, var_value->ptr(), var_value->length());
2398  query_str[len]= '\0'; // Safety (mostly for debug)
2399  *query_len= len;
2400  }
2401  else
2402  {
2403  query_str= lex->prepared_stmt_code.str;
2404  *query_len= lex->prepared_stmt_code.length;
2405  }
2406 end:
2407  return query_str;
2408 }
2409 
2410 
2426 {
2427  LEX *lex= thd->lex;
2428  LEX_STRING *name= &lex->prepared_stmt_name;
2429  Prepared_statement *stmt;
2430  const char *query;
2431  uint query_len= 0;
2432  DBUG_ENTER("mysql_sql_stmt_prepare");
2433 
2434  if ((stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
2435  {
2436  /*
2437  If there is a statement with the same name, remove it. It is ok to
2438  remove old and fail to insert a new one at the same time.
2439  */
2440  if (stmt->is_in_use())
2441  {
2442  my_error(ER_PS_NO_RECURSION, MYF(0));
2443  DBUG_VOID_RETURN;
2444  }
2445 
2446  stmt->deallocate();
2447  }
2448 
2449  if (! (query= get_dynamic_sql_string(lex, &query_len)) ||
2450  ! (stmt= new Prepared_statement(thd)))
2451  {
2452  DBUG_VOID_RETURN; /* out of memory */
2453  }
2454 
2455  stmt->set_sql_prepare();
2456 
2457  /* Set the name first, insert should know that this statement has a name */
2458  if (stmt->set_name(name))
2459  {
2460  delete stmt;
2461  DBUG_VOID_RETURN;
2462  }
2463 
2464  if (thd->stmt_map.insert(thd, stmt))
2465  {
2466  /* The statement is deleted and an error is set if insert fails */
2467  DBUG_VOID_RETURN;
2468  }
2469 
2470  if (stmt->prepare(query, query_len))
2471  {
2472  /* Statement map deletes the statement on erase */
2473  thd->stmt_map.erase(stmt);
2474  }
2475  else
2476  my_ok(thd, 0L, 0L, "Statement prepared");
2477 
2478  DBUG_VOID_RETURN;
2479 }
2480 
2490 void reinit_stmt_before_use(THD *thd, LEX *lex)
2491 {
2492  SELECT_LEX *sl= lex->all_selects_list;
2493  DBUG_ENTER("reinit_stmt_before_use");
2494 
2495  /*
2496  We have to update "thd" pointer in LEX, all its units and in LEX::result,
2497  since statements which belong to trigger body are associated with TABLE
2498  object and because of this can be used in different threads.
2499  */
2500  lex->thd= thd;
2501 
2502  if (lex->empty_field_list_on_rset)
2503  {
2504  lex->empty_field_list_on_rset= 0;
2505  lex->field_list.empty();
2506  }
2507  for (; sl; sl= sl->next_select_in_list())
2508  {
2509  if (!sl->first_execution)
2510  {
2511  /* remove option which was put by mysql_explain_unit() */
2512  sl->options&= ~SELECT_DESCRIBE;
2513 
2514  /* see unique_table() */
2515  sl->exclude_from_table_unique_test= FALSE;
2516 
2517  /*
2518  Copy WHERE, HAVING clause pointers to avoid damaging them
2519  by optimisation
2520  */
2521  if (sl->prep_where)
2522  {
2523  sl->where= sl->prep_where->copy_andor_structure(thd);
2524  sl->where->cleanup();
2525  }
2526  else
2527  sl->where= NULL;
2528  if (sl->prep_having)
2529  {
2530  sl->having= sl->prep_having->copy_andor_structure(thd);
2531  sl->having->cleanup();
2532  }
2533  else
2534  sl->having= NULL;
2535  DBUG_ASSERT(sl->join == 0);
2536  ORDER *order;
2537  /* Fix GROUP list */
2538  if (sl->group_list_ptrs && sl->group_list_ptrs->size() > 0)
2539  {
2540  for (uint ix= 0; ix < sl->group_list_ptrs->size() - 1; ++ix)
2541  {
2542  order= sl->group_list_ptrs->at(ix);
2543  order->next= sl->group_list_ptrs->at(ix+1);
2544  }
2545  }
2546  for (order= sl->group_list.first; order; order= order->next)
2547  order->item= &order->item_ptr;
2548  /* Fix ORDER list */
2549  if (sl->order_list_ptrs && sl->order_list_ptrs->size() > 0)
2550  {
2551  for (uint ix= 0; ix < sl->order_list_ptrs->size() - 1; ++ix)
2552  {
2553  order= sl->order_list_ptrs->at(ix);
2554  order->next= sl->order_list_ptrs->at(ix+1);
2555  }
2556  }
2557  for (order= sl->order_list.first; order; order= order->next)
2558  order->item= &order->item_ptr;
2559 
2560  /* clear the no_error flag for INSERT/UPDATE IGNORE */
2561  sl->no_error= FALSE;
2562  }
2563  {
2564  SELECT_LEX_UNIT *unit= sl->master_unit();
2565  unit->unclean();
2566  unit->types.empty();
2567  /* for derived tables & PS (which can't be reset by Item_subquery) */
2568  unit->reinit_exec_mechanism();
2569  unit->set_thd(thd);
2570  }
2571  }
2572 
2573  /*
2574  TODO: When the new table structure is ready, then have a status bit
2575  to indicate the table is altered, and re-do the setup_*
2576  and open the tables back.
2577  */
2578  /*
2579  NOTE: We should reset whole table list here including all tables added
2580  by prelocking algorithm (it is not a problem for substatements since
2581  they have their own table list).
2582  */
2583  for (TABLE_LIST *tables= lex->query_tables;
2584  tables;
2585  tables= tables->next_global)
2586  {
2587  tables->reinit_before_use(thd);
2588  }
2589 
2590  /* Reset MDL tickets for procedures/functions */
2591  for (Sroutine_hash_entry *rt=
2592  (Sroutine_hash_entry*)thd->lex->sroutines_list.first;
2593  rt; rt= rt->next)
2594  rt->mdl_request.ticket= NULL;
2595 
2596  /*
2597  Cleanup of the special case of DELETE t1, t2 FROM t1, t2, t3 ...
2598  (multi-delete). We do a full clean up, although at the moment all we
2599  need to clean in the tables of MULTI-DELETE list is 'table' member.
2600  */
2601  for (TABLE_LIST *tables= lex->auxiliary_table_list.first;
2602  tables;
2603  tables= tables->next_global)
2604  {
2605  tables->reinit_before_use(thd);
2606  }
2607  lex->current_select= &lex->select_lex;
2608 
2609  /* restore original list used in INSERT ... SELECT */
2610  if (lex->leaf_tables_insert)
2611  lex->select_lex.leaf_tables= lex->leaf_tables_insert;
2612 
2613  if (lex->result)
2614  {
2615  lex->result->cleanup();
2616  lex->result->set_thd(thd);
2617  }
2618  lex->allow_sum_func= 0;
2619  lex->in_sum_func= NULL;
2620  DBUG_VOID_RETURN;
2621 }
2622 
2623 
2631 static void reset_stmt_params(Prepared_statement *stmt)
2632 {
2633  Item_param **item= stmt->param_array;
2634  Item_param **end= item + stmt->param_count;
2635  for (;item < end ; ++item)
2636  (**item).reset();
2637 }
2638 
2639 
2657 void mysqld_stmt_execute(THD *thd, char *packet_arg, uint packet_length)
2658 {
2659  uchar *packet= (uchar*)packet_arg; // GCC 4.0.1 workaround
2660  ulong stmt_id;
2661  ulong flags;
2662  /* Query text for binary, general or slow log, if any of them is open */
2663  String expanded_query;
2664  uchar *packet_end= packet + packet_length;
2665  Prepared_statement *stmt;
2666  Protocol *save_protocol= thd->protocol;
2667  bool open_cursor;
2668  DBUG_ENTER("mysqld_stmt_execute");
2669 
2670  if (packet + 9 > packet_end)
2671  {
2672  my_error(ER_MALFORMED_PACKET, MYF(0));
2673  DBUG_VOID_RETURN;
2674  }
2675 
2676  stmt_id= uint4korr(packet);
2677  flags= (ulong) packet[4];
2678  packet+= 9; /* stmt_id + 5 bytes of flags */
2679 
2680  /* First of all clear possible warnings from the previous command */
2682 
2683  if (!(stmt= find_prepared_statement(thd, stmt_id)))
2684  {
2685  char llbuf[22];
2686  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
2687  llstr(stmt_id, llbuf), "mysqld_stmt_execute");
2688  DBUG_VOID_RETURN;
2689  }
2690 
2691 #if defined(ENABLED_PROFILING)
2692  thd->profiling.set_query_source(stmt->query(), stmt->query_length());
2693 #endif
2694  DBUG_PRINT("exec_query", ("%s", stmt->query()));
2695  DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
2696 
2697  open_cursor= test(flags & (ulong) CURSOR_TYPE_READ_ONLY);
2698 
2699  thd->protocol= &thd->protocol_binary;
2700  stmt->execute_loop(&expanded_query, open_cursor, packet, packet_end);
2701  thd->protocol= save_protocol;
2702 
2703  sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
2704  sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
2705 
2706  /* Close connection socket; for use with client testing (Bug#43560). */
2707  DBUG_EXECUTE_IF("close_conn_after_stmt_execute", vio_shutdown(thd->net.vio););
2708 
2709  DBUG_VOID_RETURN;
2710 }
2711 
2712 
2731 {
2732  LEX *lex= thd->lex;
2733  Prepared_statement *stmt;
2734  LEX_STRING *name= &lex->prepared_stmt_name;
2735  /* Query text for binary, general or slow log, if any of them is open */
2736  String expanded_query;
2737  DBUG_ENTER("mysql_sql_stmt_execute");
2738  DBUG_PRINT("info", ("EXECUTE: %.*s\n", (int) name->length, name->str));
2739 
2740  if (!(stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
2741  {
2742  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
2743  static_cast<int>(name->length), name->str, "EXECUTE");
2744  DBUG_VOID_RETURN;
2745  }
2746 
2747  if (stmt->param_count != lex->prepared_stmt_params.elements)
2748  {
2749  my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
2750  DBUG_VOID_RETURN;
2751  }
2752 
2753  DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
2754 
2755  (void) stmt->execute_loop(&expanded_query, FALSE, NULL, NULL);
2756 
2757  DBUG_VOID_RETURN;
2758 }
2759 
2760 
2769 void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length)
2770 {
2771  /* assume there is always place for 8-16 bytes */
2772  ulong stmt_id;
2773  ulong num_rows;
2774  Prepared_statement *stmt;
2775  Statement stmt_backup;
2777  DBUG_ENTER("mysqld_stmt_fetch");
2778 
2779  if (packet_length < 8)
2780  {
2781  my_error(ER_MALFORMED_PACKET, MYF(0));
2782  DBUG_VOID_RETURN;
2783  }
2784  stmt_id= uint4korr(packet);
2785  num_rows= uint4korr(packet+4);
2786 
2787  /* First of all clear possible warnings from the previous command */
2789  status_var_increment(thd->status_var.com_stmt_fetch);
2790  if (!(stmt= find_prepared_statement(thd, stmt_id)))
2791  {
2792  char llbuf[22];
2793  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
2794  llstr(stmt_id, llbuf), "mysqld_stmt_fetch");
2795  DBUG_VOID_RETURN;
2796  }
2797 
2798  cursor= stmt->cursor;
2799  if (!cursor)
2800  {
2801  my_error(ER_STMT_HAS_NO_OPEN_CURSOR, MYF(0), stmt_id);
2802  DBUG_VOID_RETURN;
2803  }
2804 
2805  thd->stmt_arena= stmt;
2806  thd->set_n_backup_statement(stmt, &stmt_backup);
2807 
2808  cursor->fetch(num_rows);
2809 
2810  if (!cursor->is_open())
2811  {
2812  stmt->close_cursor();
2813  reset_stmt_params(stmt);
2814  }
2815 
2816  thd->restore_backup_statement(stmt, &stmt_backup);
2817  thd->stmt_arena= thd;
2818 
2819  DBUG_VOID_RETURN;
2820 }
2821 
2822 
2840 void mysqld_stmt_reset(THD *thd, char *packet, uint packet_length)
2841 {
2842  ulong stmt_id;
2843  Prepared_statement *stmt;
2844  DBUG_ENTER("mysqld_stmt_reset");
2845 
2846  if (packet_length < 4)
2847  {
2848  my_error(ER_MALFORMED_PACKET, MYF(0));
2849  DBUG_VOID_RETURN;
2850  }
2851 
2852  stmt_id= uint4korr(packet);
2853 
2854  /* First of all clear possible warnings from the previous command */
2856 
2857  status_var_increment(thd->status_var.com_stmt_reset);
2858  if (!(stmt= find_prepared_statement(thd, stmt_id)))
2859  {
2860  char llbuf[22];
2861  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
2862  llstr(stmt_id, llbuf), "mysqld_stmt_reset");
2863  DBUG_VOID_RETURN;
2864  }
2865 
2866  stmt->close_cursor();
2867 
2868  /*
2869  Clear parameters from data which could be set by
2870  mysqld_stmt_send_long_data() call.
2871  */
2872  reset_stmt_params(stmt);
2873 
2874  stmt->state= Query_arena::STMT_PREPARED;
2875 
2876  general_log_print(thd, thd->get_command(), NullS);
2877 
2878  my_ok(thd);
2879 
2880  DBUG_VOID_RETURN;
2881 }
2882 
2883 
2891 void mysqld_stmt_close(THD *thd, char *packet, uint packet_length)
2892 {
2893  /* There is always space for 4 bytes in packet buffer */
2894  ulong stmt_id;
2895  Prepared_statement *stmt;
2896  DBUG_ENTER("mysqld_stmt_close");
2897 
2898  if (packet_length < 4)
2899  {
2900  my_error(ER_MALFORMED_PACKET, MYF(0));
2901  DBUG_VOID_RETURN;
2902  }
2903 
2904  stmt_id= uint4korr(packet);
2905 
2906  thd->get_stmt_da()->disable_status();
2907 
2908  if (!(stmt= find_prepared_statement(thd, stmt_id)))
2909  DBUG_VOID_RETURN;
2910 
2911  /*
2912  The only way currently a statement can be deallocated when it's
2913  in use is from within Dynamic SQL.
2914  */
2915  DBUG_ASSERT(! stmt->is_in_use());
2916  stmt->deallocate();
2917  general_log_print(thd, thd->get_command(), NullS);
2918 
2919  DBUG_VOID_RETURN;
2920 }
2921 
2922 
2935 void mysql_sql_stmt_close(THD *thd)
2936 {
2937  Prepared_statement* stmt;
2938  LEX_STRING *name= &thd->lex->prepared_stmt_name;
2939  DBUG_PRINT("info", ("DEALLOCATE PREPARE: %.*s\n", (int) name->length,
2940  name->str));
2941 
2942  if (! (stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
2943  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
2944  static_cast<int>(name->length), name->str, "DEALLOCATE PREPARE");
2945  else if (stmt->is_in_use())
2946  my_error(ER_PS_NO_RECURSION, MYF(0));
2947  else
2948  {
2949  stmt->deallocate();
2950  my_ok(thd);
2951  }
2952 }
2953 
2954 
2969 void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
2970 {
2971  ulong stmt_id;
2972  uint param_number;
2973  Prepared_statement *stmt;
2974  Item_param *param;
2975 #ifndef EMBEDDED_LIBRARY
2976  char *packet_end= packet + packet_length;
2977 #endif
2978  DBUG_ENTER("mysql_stmt_get_longdata");
2979 
2980  status_var_increment(thd->status_var.com_stmt_send_long_data);
2981 
2982  thd->get_stmt_da()->disable_status();
2983 #ifndef EMBEDDED_LIBRARY
2984  /* Minimal size of long data packet is 6 bytes */
2985  if (packet_length < MYSQL_LONG_DATA_HEADER)
2986  DBUG_VOID_RETURN;
2987 #endif
2988 
2989  stmt_id= uint4korr(packet);
2990  packet+= 4;
2991 
2992  if (!(stmt=find_prepared_statement(thd, stmt_id)))
2993  DBUG_VOID_RETURN;
2994 
2995  param_number= uint2korr(packet);
2996  packet+= 2;
2997 #ifndef EMBEDDED_LIBRARY
2998  if (param_number >= stmt->param_count)
2999  {
3000  /* Error will be sent in execute call */
3001  stmt->state= Query_arena::STMT_ERROR;
3002  stmt->last_errno= ER_WRONG_ARGUMENTS;
3003  sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS),
3004  "mysqld_stmt_send_long_data");
3005  DBUG_VOID_RETURN;
3006  }
3007 #endif
3008 
3009  param= stmt->param_array[param_number];
3010 
3011  Diagnostics_area new_stmt_da(thd->query_id, false);
3012  Diagnostics_area *save_stmt_da= thd->get_stmt_da();
3013 
3014  thd->set_stmt_da(&new_stmt_da);
3015 
3016 #ifndef EMBEDDED_LIBRARY
3017  param->set_longdata(packet, (ulong) (packet_end - packet));
3018 #else
3019  param->set_longdata(thd->extra_data, thd->extra_length);
3020 #endif
3021  if (thd->get_stmt_da()->is_error())
3022  {
3023  stmt->state= Query_arena::STMT_ERROR;
3024  stmt->last_errno= thd->get_stmt_da()->sql_errno();
3025  strncpy(stmt->last_error, thd->get_stmt_da()->message(), MYSQL_ERRMSG_SIZE);
3026  }
3027  thd->set_stmt_da(save_stmt_da);
3028 
3029  general_log_print(thd, thd->get_command(), NullS);
3030 
3031  DBUG_VOID_RETURN;
3032 }
3033 
3034 
3035 /***************************************************************************
3036  Select_fetch_protocol_binary
3037 ****************************************************************************/
3038 
3039 Select_fetch_protocol_binary::Select_fetch_protocol_binary(THD *thd_arg)
3040  :protocol(thd_arg)
3041 {}
3042 
3043 bool Select_fetch_protocol_binary::send_result_set_metadata(List<Item> &list, uint flags)
3044 {
3045  bool rc;
3046  Protocol *save_protocol= thd->protocol;
3047 
3048  /*
3049  Protocol::send_result_set_metadata caches the information about column types:
3050  this information is later used to send data. Therefore, the same
3051  dedicated Protocol object must be used for all operations with
3052  a cursor.
3053  */
3054  thd->protocol= &protocol;
3055  rc= select_send::send_result_set_metadata(list, flags);
3056  thd->protocol= save_protocol;
3057 
3058  return rc;
3059 }
3060 
3061 bool Select_fetch_protocol_binary::send_eof()
3062 {
3063  /*
3064  Don't send EOF if we're in error condition (which implies we've already
3065  sent or are sending an error)
3066  */
3067  if (thd->is_error())
3068  return true;
3069 
3070  ::my_eof(thd);
3071  return false;
3072 }
3073 
3074 
3075 bool
3076 Select_fetch_protocol_binary::send_data(List<Item> &fields)
3077 {
3078  Protocol *save_protocol= thd->protocol;
3079  bool rc;
3080 
3081  thd->protocol= &protocol;
3082  rc= select_send::send_data(fields);
3083  thd->protocol= save_protocol;
3084  return rc;
3085 }
3086 
3087 /*******************************************************************
3088 * Reprepare_observer
3089 *******************************************************************/
3092 bool
3094 {
3095  /*
3096  This 'error' is purely internal to the server:
3097  - No exception handler is invoked,
3098  - No condition is added in the condition area (warn_list).
3099  The diagnostics area is set to an error status to enforce
3100  that this thread execution stops and returns to the caller,
3101  backtracking all the way to Prepared_statement::execute_loop().
3102  */
3103  thd->get_stmt_da()->set_error_status(ER_NEED_REPREPARE);
3104  m_invalidated= TRUE;
3105 
3106  return TRUE;
3107 }
3108 
3109 
3110 /*******************************************************************
3111 * Server_runnable
3112 *******************************************************************/
3113 
3114 Server_runnable::~Server_runnable()
3115 {
3116 }
3117 
3119 
3120 Execute_sql_statement::
3121 Execute_sql_statement(LEX_STRING sql_text)
3122  :m_sql_text(sql_text)
3123 {}
3124 
3125 
3135 bool
3137 {
3138  PSI_statement_locker *parent_locker;
3139  bool error;
3140 
3141  if (alloc_query(thd, m_sql_text.str, m_sql_text.length))
3142  return TRUE;
3143 
3144  Parser_state parser_state;
3145  if (parser_state.init(thd, thd->query(), thd->query_length()))
3146  return TRUE;
3147 
3148  parser_state.m_lip.multi_statements= FALSE;
3149  lex_start(thd);
3150 
3151  parent_locker= thd->m_statement_psi;
3152  thd->m_statement_psi= NULL;
3153  error= parse_sql(thd, &parser_state, NULL) || thd->is_error();
3154  thd->m_statement_psi= parent_locker;
3155 
3156  if (error)
3157  goto end;
3158 
3159  thd->lex->set_trg_event_type_for_tables();
3160 
3161  parent_locker= thd->m_statement_psi;
3162  thd->m_statement_psi= NULL;
3163  /*
3164  Rewrite first (if needed); execution might replace passwords
3165  with hashes in situ without flagging it, and then we'd make
3166  a hash of that hash.
3167  */
3168  rewrite_query_if_needed(thd);
3169  error= mysql_execute_command(thd) ;
3170  thd->m_statement_psi= parent_locker;
3171 
3172  /* report error issued during command execution */
3173  if (error == 0)
3174  log_execute_line(thd);
3175 
3176 end:
3177  lex_end(thd->lex);
3178 
3179  return error;
3180 }
3181 
3182 /***************************************************************************
3183  Prepared_statement
3184 ****************************************************************************/
3185 
3186 Prepared_statement::Prepared_statement(THD *thd_arg)
3187  :Statement(NULL, &main_mem_root,
3188  STMT_INITIALIZED, ++thd_arg->statement_id_counter),
3189  thd(thd_arg),
3190  result(thd_arg),
3191  param_array(0),
3192  cursor(0),
3193  param_count(0),
3194  last_errno(0),
3195  flags((uint) IS_IN_USE)
3196 {
3197  init_sql_alloc(&main_mem_root, thd_arg->variables.query_alloc_block_size,
3198  thd_arg->variables.query_prealloc_size);
3199  *last_error= '\0';
3200 }
3201 
3202 
3203 void Prepared_statement::setup_set_params()
3204 {
3205  /*
3206  Note: BUG#25843 applies here too (query cache lookup uses thd->db, not
3207  db from "prepare" time).
3208  */
3209  if (query_cache_maybe_disabled(thd)) // we won't expand the query
3210  lex->safe_to_cache_query= FALSE; // so don't cache it at Execution
3211 
3212  /*
3213  Decide if we have to expand the query (because we must write it to logs or
3214  because we want to look it up in the query cache) or not.
3215  */
3216  if ((mysql_bin_log.is_open() && is_update_query(lex->sql_command)) ||
3217  opt_log || opt_slow_log ||
3218  query_cache_is_cacheable_query(lex))
3219  {
3220  set_params_from_vars= insert_params_from_vars_with_log;
3221 #ifndef EMBEDDED_LIBRARY
3222  set_params= insert_params_with_log;
3223 #else
3224  set_params_data= emb_insert_params_with_log;
3225 #endif
3226  }
3227  else
3228  {
3229  set_params_from_vars= insert_params_from_vars;
3230 #ifndef EMBEDDED_LIBRARY
3231  set_params= insert_params;
3232 #else
3233  set_params_data= emb_insert_params;
3234 #endif
3235  }
3236 }
3237 
3238 
3248 {
3249  DBUG_ENTER("Prepared_statement::~Prepared_statement");
3250  DBUG_PRINT("enter",("stmt: 0x%lx cursor: 0x%lx",
3251  (long) this, (long) cursor));
3252  delete cursor;
3253  /*
3254  We have to call free on the items even if cleanup is called as some items,
3255  like Item_param, don't free everything until free_items()
3256  */
3257  free_items();
3258  if (lex)
3259  {
3260  delete lex->result;
3261  delete (st_lex_local *) lex;
3262  }
3263  free_root(&main_mem_root, MYF(0));
3264  DBUG_VOID_RETURN;
3265 }
3266 
3267 
3268 Query_arena::Type Prepared_statement::type() const
3269 {
3270  return PREPARED_STATEMENT;
3271 }
3272 
3273 
3274 void Prepared_statement::cleanup_stmt()
3275 {
3276  DBUG_ENTER("Prepared_statement::cleanup_stmt");
3277  DBUG_PRINT("enter",("stmt: 0x%lx", (long) this));
3278 
3279  cleanup_items(free_list);
3280  thd->cleanup_after_query();
3281  thd->rollback_item_tree_changes();
3282 
3283  DBUG_VOID_RETURN;
3284 }
3285 
3286 
3287 bool Prepared_statement::set_name(LEX_STRING *name_arg)
3288 {
3289  name.length= name_arg->length;
3290  name.str= (char*) memdup_root(mem_root, name_arg->str, name_arg->length);
3291  return name.str == 0;
3292 }
3293 
3294 
3305 bool
3306 Prepared_statement::set_db(const char *db_arg, uint db_length_arg)
3307 {
3308  /* Remember the current database. */
3309  if (db_arg && db_length_arg)
3310  {
3311  db= this->strmake(db_arg, db_length_arg);
3312  db_length= db_length_arg;
3313  }
3314  else
3315  {
3316  db= NULL;
3317  db_length= 0;
3318  }
3319  return db_arg != NULL && db == NULL;
3320 }
3321 
3322 /**************************************************************************
3323  Common parts of mysql_[sql]_stmt_prepare, mysql_[sql]_stmt_execute.
3324  Essentially, these functions do all the magic of preparing/executing
3325  a statement, leaving network communication, input data handling and
3326  global THD state management to the caller.
3327 ***************************************************************************/
3328 
3350 bool Prepared_statement::prepare(const char *packet, uint packet_len)
3351 {
3352  bool error;
3353  Statement stmt_backup;
3354  Query_arena *old_stmt_arena;
3355  PSI_statement_locker *parent_locker= thd->m_statement_psi;
3356  DBUG_ENTER("Prepared_statement::prepare");
3357  /*
3358  If this is an SQLCOM_PREPARE, we also increase Com_prepare_sql.
3359  However, it seems handy if com_stmt_prepare is increased always,
3360  no matter what kind of prepare is processed.
3361  */
3362  status_var_increment(thd->status_var.com_stmt_prepare);
3363 
3364  if (! (lex= new (mem_root) st_lex_local))
3365  DBUG_RETURN(TRUE);
3366 
3367  if (set_db(thd->db, thd->db_length))
3368  DBUG_RETURN(TRUE);
3369 
3370  /*
3371  alloc_query() uses thd->memroot && thd->query, so we should call
3372  both of backup_statement() and backup_query_arena() here.
3373  */
3374  thd->set_n_backup_statement(this, &stmt_backup);
3375  thd->set_n_backup_active_arena(this, &stmt_backup);
3376 
3377  if (alloc_query(thd, packet, packet_len))
3378  {
3379  thd->restore_backup_statement(this, &stmt_backup);
3380  thd->restore_active_arena(this, &stmt_backup);
3381  DBUG_RETURN(TRUE);
3382  }
3383 
3384  old_stmt_arena= thd->stmt_arena;
3385  thd->stmt_arena= this;
3386 
3387  Parser_state parser_state;
3388  if (parser_state.init(thd, thd->query(), thd->query_length()))
3389  {
3390  thd->restore_backup_statement(this, &stmt_backup);
3391  thd->restore_active_arena(this, &stmt_backup);
3392  thd->stmt_arena= old_stmt_arena;
3393  DBUG_RETURN(TRUE);
3394  }
3395 
3396  parser_state.m_lip.stmt_prepare_mode= TRUE;
3397  parser_state.m_lip.multi_statements= FALSE;
3398 
3399  lex_start(thd);
3400  lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_PREPARE;
3401 
3402  thd->m_statement_psi= NULL;
3403  error= parse_sql(thd, & parser_state, NULL) ||
3404  thd->is_error() ||
3405  init_param_array(this);
3406  thd->m_statement_psi= parent_locker;
3407 
3408  lex->set_trg_event_type_for_tables();
3409 
3410  /*
3411  While doing context analysis of the query (in check_prepared_statement)
3412  we allocate a lot of additional memory: for open tables, JOINs, derived
3413  tables, etc. Let's save a snapshot of current parse tree to the
3414  statement and restore original THD. In cases when some tree
3415  transformation can be reused on execute, we set again thd->mem_root from
3416  stmt->mem_root (see setup_wild for one place where we do that).
3417  */
3418  thd->restore_active_arena(this, &stmt_backup);
3419 
3420  /*
3421  If called from a stored procedure, ensure that we won't rollback
3422  external changes when cleaning up after validation.
3423  */
3424  DBUG_ASSERT(thd->change_list.is_empty());
3425 
3426  /*
3427  Marker used to release metadata locks acquired while the prepared
3428  statement is being checked.
3429  */
3430  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
3431 
3432  /*
3433  The only case where we should have items in the thd->free_list is
3434  after stmt->set_params_from_vars(), which may in some cases create
3435  Item_null objects.
3436  */
3437 
3438  if (error == 0)
3439  error= check_prepared_statement(this);
3440 
3441  /*
3442  Currently CREATE PROCEDURE/TRIGGER/EVENT are prohibited in prepared
3443  statements: ensure we have no memory leak here if by someone tries
3444  to PREPARE stmt FROM "CREATE PROCEDURE ..."
3445  */
3446  DBUG_ASSERT(lex->sphead == NULL || error != 0);
3447  /* The order is important */
3448  lex->unit.cleanup();
3449 
3450  /* No need to commit statement transaction, it's not started. */
3451  DBUG_ASSERT(thd->transaction.stmt.is_empty());
3452 
3453  close_thread_tables(thd);
3454  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
3455 
3456  /*
3457  Transaction rollback was requested since MDL deadlock was discovered
3458  while trying to open tables. Rollback transaction in all storage
3459  engines including binary log and release all locks.
3460 
3461  Once dynamic SQL is allowed as substatements the below if-statement
3462  has to be adjusted to not do rollback in substatement.
3463  */
3464  DBUG_ASSERT(! thd->in_sub_stmt);
3465  if (thd->transaction_rollback_request)
3466  {
3467  trans_rollback_implicit(thd);
3468  thd->mdl_context.release_transactional_locks();
3469  }
3470 
3471  lex_end(lex);
3472 
3473  rewrite_query_if_needed(thd);
3474 
3475  cleanup_stmt();
3476  thd->restore_backup_statement(this, &stmt_backup);
3477  thd->stmt_arena= old_stmt_arena;
3478 
3479  if (error == 0)
3480  {
3481  setup_set_params();
3482  lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_PREPARE;
3483  state= Query_arena::STMT_PREPARED;
3484  flags&= ~ (uint) IS_IN_USE;
3485 
3486  /*
3487  Log COM_STMT_PREPARE to the general log. Note, that in case of SQL
3488  prepared statements this causes two records to be output:
3489 
3490  Query PREPARE stmt from @user_variable
3491  Prepare <statement SQL text>
3492 
3493  This is considered user-friendly, since in the second log Entry
3494  we output the actual statement text rather than the variable name.
3495 
3496  Rewriting/password obfuscation:
3497 
3498  - If we're preparing from a string literal rather than from a
3499  variable, the literal is elided in the "Query" log line, as
3500  it may contain a password. (As we've parsed the PREPARE statement,
3501  but not the statement to prepare yet, we don't know at that point.)
3502  Eliding the literal is fine, as we'll print it in the next log line
3503  ("Prepare"), anyway.
3504 
3505  - Any passwords in the "Prepare" line should be substituted with their
3506  hashes, or a notice.
3507 
3508  Do not print anything if this is an SQL prepared statement and
3509  we're inside a stored procedure (also called Dynamic SQL) --
3510  sub-statements inside stored procedures are not logged into
3511  the general log.
3512  */
3513  if (thd->sp_runtime_ctx == NULL)
3514  {
3515  if (thd->rewritten_query.length())
3516  logger.general_log_write(thd, COM_STMT_PREPARE,
3517  thd->rewritten_query.c_ptr_safe(),
3518  thd->rewritten_query.length());
3519  else
3520  logger.general_log_write(thd, COM_STMT_PREPARE,
3521  query(), query_length());
3522  }
3523  }
3524  DBUG_RETURN(error);
3525 }
3526 
3527 
3548 bool
3549 Prepared_statement::set_parameters(String *expanded_query,
3550  uchar *packet, uchar *packet_end)
3551 {
3552  bool is_sql_ps= packet == NULL;
3553  bool res= FALSE;
3554 
3555  if (is_sql_ps)
3556  {
3557  /* SQL prepared statement */
3558  res= set_params_from_vars(this, thd->lex->prepared_stmt_params,
3559  expanded_query);
3560  }
3561  else if (param_count)
3562  {
3563 #ifndef EMBEDDED_LIBRARY
3564  uchar *null_array= packet;
3565  res= (setup_conversion_functions(this, &packet, packet_end) ||
3566  set_params(this, null_array, packet, packet_end, expanded_query));
3567 #else
3568  /*
3569  In embedded library we re-install conversion routines each time
3570  we set parameters, and also we don't need to parse packet.
3571  So we do it in one function.
3572  */
3573  res= set_params_data(this, expanded_query);
3574 #endif
3575  }
3576  if (res)
3577  {
3578  my_error(ER_WRONG_ARGUMENTS, MYF(0),
3579  is_sql_ps ? "EXECUTE" : "mysqld_stmt_execute");
3580  reset_stmt_params(this);
3581  }
3582  return res;
3583 }
3584 
3585 
3609 bool
3611  bool open_cursor,
3612  uchar *packet,
3613  uchar *packet_end)
3614 {
3615  const int MAX_REPREPARE_ATTEMPTS= 3;
3616  Reprepare_observer reprepare_observer;
3617  bool error;
3618  int reprepare_attempt= 0;
3619 
3620  /* Check if we got an error when sending long data */
3621  if (state == Query_arena::STMT_ERROR)
3622  {
3623  my_message(last_errno, last_error, MYF(0));
3624  return TRUE;
3625  }
3626 
3627  if (set_parameters(expanded_query, packet, packet_end))
3628  return TRUE;
3629 
3630  if (unlikely(thd->security_ctx->password_expired &&
3631  !lex->is_change_password))
3632  {
3633  my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
3634  return true;
3635  }
3636 
3637 reexecute:
3638  /*
3639  If the free_list is not empty, we'll wrongly free some externally
3640  allocated items when cleaning up after validation of the prepared
3641  statement.
3642  */
3643  DBUG_ASSERT(thd->free_list == NULL);
3644 
3645  /*
3646  Install the metadata observer. If some metadata version is
3647  different from prepare time and an observer is installed,
3648  the observer method will be invoked to push an error into
3649  the error stack.
3650  */
3651  Reprepare_observer *stmt_reprepare_observer= NULL;
3652 
3653  if (sql_command_flags[lex->sql_command] & CF_REEXECUTION_FRAGILE)
3654  {
3655  reprepare_observer.reset_reprepare_observer();
3656  stmt_reprepare_observer = &reprepare_observer;
3657  }
3658 
3659  thd->push_reprepare_observer(stmt_reprepare_observer);
3660 
3661  error= execute(expanded_query, open_cursor) || thd->is_error();
3662 
3663  thd->pop_reprepare_observer();
3664 
3665  if ((sql_command_flags[lex->sql_command] & CF_REEXECUTION_FRAGILE) &&
3666  error && !thd->is_fatal_error && !thd->killed &&
3667  reprepare_observer.is_invalidated() &&
3668  reprepare_attempt++ < MAX_REPREPARE_ATTEMPTS)
3669  {
3670  DBUG_ASSERT(thd->get_stmt_da()->sql_errno() == ER_NEED_REPREPARE);
3671  thd->clear_error();
3672 
3673  error= reprepare();
3674 
3675  if (! error) /* Success */
3676  goto reexecute;
3677  }
3678  reset_stmt_params(this);
3679 
3680  return error;
3681 }
3682 
3683 
3684 bool
3685 Prepared_statement::execute_server_runnable(Server_runnable *server_runnable)
3686 {
3687  Statement stmt_backup;
3688  bool error;
3689  Query_arena *save_stmt_arena= thd->stmt_arena;
3690  Item_change_list save_change_list;
3691  thd->change_list.move_elements_to(&save_change_list);
3692 
3693  state= STMT_CONVENTIONAL_EXECUTION;
3694 
3695  if (!(lex= new (mem_root) st_lex_local))
3696  return TRUE;
3697 
3698  thd->set_n_backup_statement(this, &stmt_backup);
3699  thd->set_n_backup_active_arena(this, &stmt_backup);
3700  thd->stmt_arena= this;
3701 
3702  error= server_runnable->execute_server_code(thd);
3703 
3704  thd->cleanup_after_query();
3705 
3706  thd->restore_active_arena(this, &stmt_backup);
3707  thd->restore_backup_statement(this, &stmt_backup);
3708  thd->stmt_arena= save_stmt_arena;
3709 
3710  save_change_list.move_elements_to(&thd->change_list);
3711 
3712  /* Items and memory will freed in destructor */
3713 
3714  return error;
3715 }
3716 
3717 
3731 bool
3732 Prepared_statement::reprepare()
3733 {
3734  char saved_cur_db_name_buf[NAME_LEN+1];
3735  LEX_STRING saved_cur_db_name=
3736  { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
3737  LEX_STRING stmt_db_name= { db, db_length };
3738  bool cur_db_changed;
3739  bool error;
3740 
3741  Prepared_statement copy(thd);
3742 
3743  copy.set_sql_prepare(); /* To suppress sending metadata to the client. */
3744 
3745  status_var_increment(thd->status_var.com_stmt_reprepare);
3746 
3747  if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE,
3748  &cur_db_changed))
3749  return TRUE;
3750 
3751  error= ((name.str && copy.set_name(&name)) ||
3752  copy.prepare(query(), query_length()) ||
3753  validate_metadata(&copy));
3754 
3755  if (cur_db_changed)
3756  mysql_change_db(thd, &saved_cur_db_name, TRUE);
3757 
3758  if (! error)
3759  {
3760  swap_prepared_statement(&copy);
3761  swap_parameter_array(param_array, copy.param_array, param_count);
3762 #ifndef DBUG_OFF
3763  is_reprepared= TRUE;
3764 #endif
3765  /*
3766  Clear possible warnings during reprepare, it has to be completely
3767  transparent to the user. We use clear_warning_info() since
3768  there were no separate query id issued for re-prepare.
3769  Sic: we can't simply silence warnings during reprepare, because if
3770  it's failed, we need to return all the warnings to the user.
3771  */
3772  thd->get_stmt_da()->clear_warning_info(thd->query_id);
3773  }
3774  return error;
3775 }
3776 
3777 
3794 bool Prepared_statement::validate_metadata(Prepared_statement *copy)
3795 {
3801  if (is_sql_prepare() || lex->describe)
3802  return FALSE;
3803 
3804  if (lex->select_lex.item_list.elements !=
3805  copy->lex->select_lex.item_list.elements)
3806  {
3808  thd->server_status|= SERVER_STATUS_METADATA_CHANGED;
3809  }
3810 
3811  return FALSE;
3812 }
3813 
3814 
3824 void
3825 Prepared_statement::swap_prepared_statement(Prepared_statement *copy)
3826 {
3827  Statement tmp_stmt;
3828 
3829  /* Swap memory roots. */
3830  swap_variables(MEM_ROOT, main_mem_root, copy->main_mem_root);
3831 
3832  /* Swap the arenas */
3833  tmp_stmt.set_query_arena(this);
3834  set_query_arena(copy);
3835  copy->set_query_arena(&tmp_stmt);
3836 
3837  /* Swap the statement parent classes */
3838  tmp_stmt.set_statement(this);
3839  set_statement(copy);
3840  copy->set_statement(&tmp_stmt);
3841 
3842  /* Swap ids back, we need the original id */
3843  swap_variables(ulong, id, copy->id);
3844  /* Swap mem_roots back, they must continue pointing at the main_mem_roots */
3845  swap_variables(MEM_ROOT *, mem_root, copy->mem_root);
3846  /*
3847  Swap the old and the new parameters array. The old array
3848  is allocated in the old arena.
3849  */
3850  swap_variables(Item_param **, param_array, copy->param_array);
3851  /* Don't swap flags: the copy has IS_SQL_PREPARE always set. */
3852  /* swap_variables(uint, flags, copy->flags); */
3853  /* Swap names, the old name is allocated in the wrong memory root */
3854  swap_variables(LEX_STRING, name, copy->name);
3855  /* Ditto */
3856  swap_variables(char *, db, copy->db);
3857 
3858  DBUG_ASSERT(db_length == copy->db_length);
3859  DBUG_ASSERT(param_count == copy->param_count);
3860  DBUG_ASSERT(thd == copy->thd);
3861  last_error[0]= '\0';
3862  last_errno= 0;
3863 }
3864 
3865 
3888 bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
3889 {
3890  Statement stmt_backup;
3891  Query_arena *old_stmt_arena;
3892  bool error= TRUE;
3893 
3894  char saved_cur_db_name_buf[NAME_LEN+1];
3895  LEX_STRING saved_cur_db_name=
3896  { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
3897  bool cur_db_changed;
3898 
3899  LEX_STRING stmt_db_name= { db, db_length };
3900 
3901  status_var_increment(thd->status_var.com_stmt_execute);
3902 
3903  if (flags & (uint) IS_IN_USE)
3904  {
3905  my_error(ER_PS_NO_RECURSION, MYF(0));
3906  return TRUE;
3907  }
3908 
3909  /*
3910  For SHOW VARIABLES lex->result is NULL, as it's a non-SELECT
3911  command. For such queries we don't return an error and don't
3912  open a cursor -- the client library will recognize this case and
3913  materialize the result set.
3914  For SELECT statements lex->result is created in
3915  check_prepared_statement. lex->result->simple_select() is FALSE
3916  in INSERT ... SELECT and similar commands.
3917  */
3918 
3919  if (open_cursor && lex->result && lex->result->check_simple_select())
3920  {
3921  DBUG_PRINT("info",("Cursor asked for not SELECT stmt"));
3922  return TRUE;
3923  }
3924 
3925  /* In case the command has a call to SP which re-uses this statement name */
3926  flags|= IS_IN_USE;
3927 
3928  close_cursor();
3929 
3930  /*
3931  If the free_list is not empty, we'll wrongly free some externally
3932  allocated items when cleaning up after execution of this statement.
3933  */
3934  DBUG_ASSERT(thd->change_list.is_empty());
3935 
3936  /*
3937  The only case where we should have items in the thd->free_list is
3938  after stmt->set_params_from_vars(), which may in some cases create
3939  Item_null objects.
3940  */
3941 
3942  thd->set_n_backup_statement(this, &stmt_backup);
3943 
3944  /*
3945  Change the current database (if needed).
3946 
3947  Force switching, because the database of the prepared statement may be
3948  NULL (prepared statements can be created while no current database
3949  selected).
3950  */
3951 
3952  if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE,
3953  &cur_db_changed))
3954  goto error;
3955 
3956  /* Allocate query. */
3957 
3958  if (expanded_query->length() &&
3959  alloc_query(thd, (char*) expanded_query->ptr(),
3960  expanded_query->length()))
3961  {
3962  my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR), expanded_query->length());
3963  goto error;
3964  }
3965  /*
3966  Expanded query is needed for slow logging, so we want thd->query
3967  to point at it even after we restore from backup. This is ok, as
3968  expanded query was allocated in thd->mem_root.
3969  */
3970  stmt_backup.set_query_inner(thd->query_string);
3971 
3972  /*
3973  At first execution of prepared statement we may perform logical
3974  transformations of the query tree. Such changes should be performed
3975  on the parse tree of current prepared statement and new items should
3976  be allocated in its memory root. Set the appropriate pointer in THD
3977  to the arena of the statement.
3978  */
3979  old_stmt_arena= thd->stmt_arena;
3980  thd->stmt_arena= this;
3981  reinit_stmt_before_use(thd, lex);
3982 
3983  /* Go! */
3984 
3985  if (open_cursor)
3986  error= mysql_open_cursor(thd, &result, &cursor);
3987  else
3988  {
3989  /*
3990  Try to find it in the query cache, if not, execute it.
3991  Note that multi-statements cannot exist here (they are not supported in
3992  prepared statements).
3993  */
3994  if (query_cache_send_result_to_client(thd, thd->query(),
3995  thd->query_length()) <= 0)
3996  {
3997  PSI_statement_locker *parent_locker;
3998  MYSQL_QUERY_EXEC_START(thd->query(),
3999  thd->thread_id,
4000  (char *) (thd->db ? thd->db : ""),
4001  &thd->security_ctx->priv_user[0],
4002  (char *) thd->security_ctx->host_or_ip,
4003  1);
4004  parent_locker= thd->m_statement_psi;
4005  thd->m_statement_psi= NULL;
4006  /*
4007  Rewrite first (if needed); execution might replace passwords
4008  with hashes in situ without flagging it, and then we'd make
4009  a hash of that hash.
4010  */
4011  rewrite_query_if_needed(thd);
4012 
4013  error= mysql_execute_command(thd);
4014  thd->m_statement_psi= parent_locker;
4015  MYSQL_QUERY_EXEC_DONE(error);
4016  }
4017  }
4018 
4019  /*
4020  Restore the current database (if changed).
4021 
4022  Force switching back to the saved current database (if changed),
4023  because it may be NULL. In this case, mysql_change_db() would generate
4024  an error.
4025  */
4026 
4027  if (cur_db_changed)
4028  mysql_change_db(thd, &saved_cur_db_name, TRUE);
4029 
4030  /* Assert that if an error, no cursor is open */
4031  DBUG_ASSERT(! (error && cursor));
4032 
4033  if (! cursor)
4034  cleanup_stmt();
4035 
4036  thd->set_statement(&stmt_backup);
4037  thd->stmt_arena= old_stmt_arena;
4038 
4039  if (state == Query_arena::STMT_PREPARED)
4040  state= Query_arena::STMT_EXECUTED;
4041 
4042  if (error == 0 && this->lex->sql_command == SQLCOM_CALL)
4043  {
4044  if (is_sql_prepare())
4045  thd->protocol_text.send_out_parameters(&this->lex->param_list);
4046  else
4047  thd->protocol->send_out_parameters(&this->lex->param_list);
4048  }
4049 
4050  /*
4051  Log COM_STMT_EXECUTE to the general log. Note, that in case of SQL
4052  prepared statements this causes two records to be output:
4053 
4054  Query EXECUTE <statement name>
4055  Execute <statement SQL text>
4056 
4057  This is considered user-friendly, since in the
4058  second log entry we output values of parameter markers.
4059 
4060  Rewriting/password obfuscation:
4061 
4062  - Any passwords in the "Execute" line should be substituted with
4063  their hashes, or a notice.
4064 
4065  */
4066  if (error == 0)
4067  log_execute_line(thd);
4068 
4069 error:
4070  flags&= ~ (uint) IS_IN_USE;
4071  return error;
4072 }
4073 
4074 
4078 {
4079  /* We account deallocate in the same manner as mysqld_stmt_close */
4080  status_var_increment(thd->status_var.com_stmt_close);
4081  /* Statement map calls delete stmt on erase */
4082  thd->stmt_map.erase(this);
4083 }
4084 
4085 
4086 /***************************************************************************
4087 * Ed_result_set
4088 ***************************************************************************/
4096 void Ed_result_set::operator delete(void *ptr, size_t size) throw ()
4097 {
4098  if (ptr)
4099  {
4100  /*
4101  Make a stack copy, otherwise free_root() will attempt to
4102  write to freed memory.
4103  */
4104  MEM_ROOT own_root= ((Ed_result_set*) ptr)->m_mem_root;
4105  free_root(&own_root, MYF(0));
4106  }
4107 }
4108 
4109 
4122  size_t column_count_arg,
4123  MEM_ROOT *mem_root_arg)
4124  :m_mem_root(*mem_root_arg),
4125  m_column_count(column_count_arg),
4126  m_rows(rows_arg),
4127  m_next_rset(NULL)
4128 {
4129  /* Take over responsibility for the memory */
4130  clear_alloc_root(mem_root_arg);
4131 }
4132 
4133 /***************************************************************************
4134 * Ed_result_set
4135 ***************************************************************************/
4136 
4142  :m_diagnostics_area(thd->query_id, false),
4143  m_thd(thd),
4144  m_rsets(0),
4145  m_current_rset(0)
4146 {
4147 }
4148 
4149 
4157 void
4158 Ed_connection::free_old_result()
4159 {
4160  while (m_rsets)
4161  {
4162  Ed_result_set *rset= m_rsets->m_next_rset;
4163  delete m_rsets;
4164  m_rsets= rset;
4165  }
4166  m_current_rset= m_rsets;
4167  m_diagnostics_area.reset_diagnostics_area();
4168  m_diagnostics_area.clear_warning_info(m_thd->query_id);
4169 }
4170 
4171 
4176 bool
4178 {
4179  Execute_sql_statement execute_sql_statement(sql_text);
4180  DBUG_PRINT("ed_query", ("%s", sql_text.str));
4181 
4182  return execute_direct(&execute_sql_statement);
4183 }
4184 
4185 
4200 {
4201  bool rc= FALSE;
4202  Protocol_local protocol_local(m_thd, this);
4203  Prepared_statement stmt(m_thd);
4204  Protocol *save_protocol= m_thd->protocol;
4205  Diagnostics_area *save_diagnostics_area= m_thd->get_stmt_da();
4206 
4207  DBUG_ENTER("Ed_connection::execute_direct");
4208 
4209  free_old_result(); /* Delete all data from previous execution, if any */
4210 
4211  m_thd->protocol= &protocol_local;
4212  m_thd->set_stmt_da(&m_diagnostics_area);
4213 
4214  rc= stmt.execute_server_runnable(server_runnable);
4215  m_thd->protocol->end_statement();
4216 
4217  m_thd->protocol= save_protocol;
4218  m_thd->set_stmt_da(save_diagnostics_area);
4219  /*
4220  Protocol_local makes use of m_current_rset to keep
4221  track of the last result set, while adding result sets to the end.
4222  Reset it to point to the first result set instead.
4223  */
4224  m_current_rset= m_rsets;
4225 
4226  DBUG_RETURN(rc);
4227 }
4228 
4229 
4240 void
4241 Ed_connection::add_result_set(Ed_result_set *ed_result_set)
4242 {
4243  if (m_rsets)
4244  {
4245  m_current_rset->m_next_rset= ed_result_set;
4246  /* While appending, use m_current_rset as a pointer to the tail. */
4247  m_current_rset= ed_result_set;
4248  }
4249  else
4250  m_current_rset= m_rsets= ed_result_set;
4251 }
4252 
4253 
4268 Ed_result_set *
4270 {
4271  Ed_result_set *ed_result_set;
4272 
4273  DBUG_ASSERT(m_current_rset);
4274 
4275  if (m_current_rset == m_rsets)
4276  {
4277  /* Assign the return value */
4278  ed_result_set= m_current_rset;
4279  /* Exclude the return value from the list. */
4280  m_current_rset= m_rsets= m_rsets->m_next_rset;
4281  }
4282  else
4283  {
4284  Ed_result_set *prev_rset= m_rsets;
4285  /* Assign the return value. */
4286  ed_result_set= m_current_rset;
4287 
4288  /* Exclude the return value from the list */
4289  while (prev_rset->m_next_rset != m_current_rset)
4290  prev_rset= ed_result_set->m_next_rset;
4291  m_current_rset= prev_rset->m_next_rset= m_current_rset->m_next_rset;
4292  }
4293  ed_result_set->m_next_rset= NULL; /* safety */
4294 
4295  return ed_result_set;
4296 }
4297 
4298 /*************************************************************************
4299 * Protocol_local
4300 **************************************************************************/
4301 
4302 Protocol_local::Protocol_local(THD *thd, Ed_connection *ed_connection)
4303  :Protocol(thd),
4304  m_connection(ed_connection),
4305  m_rset(NULL),
4306  m_column_count(0),
4307  m_current_row(NULL),
4308  m_current_column(NULL)
4309 {
4310  clear_alloc_root(&m_rset_root);
4311 }
4312 
4323 {
4324  DBUG_ASSERT(alloc_root_inited(&m_rset_root));
4325 
4326  opt_add_row_to_rset();
4327  /* Start a new row. */
4328  m_current_row= (Ed_column *) alloc_root(&m_rset_root,
4329  sizeof(Ed_column) * m_column_count);
4330  m_current_column= m_current_row;
4331 }
4332 
4333 
4340 {
4341  return FALSE;
4342 }
4343 
4350 void Protocol_local::opt_add_row_to_rset()
4351 {
4352  if (m_current_row)
4353  {
4354  /* Add the old row to the result set */
4355  Ed_row *ed_row= new (&m_rset_root) Ed_row(m_current_row, m_column_count);
4356  if (ed_row)
4357  m_rset->push_back(ed_row, &m_rset_root);
4358  }
4359 }
4360 
4361 
4367 {
4368  if (m_current_column == NULL)
4369  return TRUE; /* prepare_for_resend() failed to allocate memory. */
4370 
4371  memset(m_current_column, 0, sizeof(*m_current_column));
4372  ++m_current_column;
4373  return FALSE;
4374 }
4375 
4376 
4384 bool Protocol_local::store_column(const void *data, size_t length)
4385 {
4386  if (m_current_column == NULL)
4387  return TRUE; /* prepare_for_resend() failed to allocate memory. */
4388  /*
4389  alloc_root() automatically aligns memory, so we don't need to
4390  do any extra alignment if we're pointing to, say, an integer.
4391  */
4392  m_current_column->str= (char*) memdup_root(&m_rset_root,
4393  data,
4394  length + 1 /* Safety */);
4395  if (! m_current_column->str)
4396  return TRUE;
4397  m_current_column->str[length]= '\0'; /* Safety */
4398  m_current_column->length= length;
4399  ++m_current_column;
4400  return FALSE;
4401 }
4402 
4403 
4409 bool
4410 Protocol_local::store_string(const char *str, size_t length,
4411  const CHARSET_INFO *src_cs,
4412  const CHARSET_INFO *dst_cs)
4413 {
4414  /* Store with conversion */
4415  uint error_unused;
4416 
4417  if (dst_cs && !my_charset_same(src_cs, dst_cs) &&
4418  src_cs != &my_charset_bin &&
4419  dst_cs != &my_charset_bin)
4420  {
4421  if (convert->copy(str, length, src_cs, dst_cs, &error_unused))
4422  return TRUE;
4423  str= convert->ptr();
4424  length= convert->length();
4425  }
4426  return store_column(str, length);
4427 }
4428 
4429 
4432 bool Protocol_local::store_tiny(longlong value)
4433 {
4434  char v= (char) value;
4435  return store_column(&v, 1);
4436 }
4437 
4438 
4441 bool Protocol_local::store_short(longlong value)
4442 {
4443  int16 v= (int16) value;
4444  return store_column(&v, 2);
4445 }
4446 
4447 
4450 bool Protocol_local::store_long(longlong value)
4451 {
4452  int32 v= (int32) value;
4453  return store_column(&v, 4);
4454 }
4455 
4456 
4459 bool Protocol_local::store_longlong(longlong value, bool unsigned_flag)
4460 {
4461  int64 v= (int64) value;
4462  return store_column(&v, 8);
4463 }
4464 
4465 
4469 {
4470  char buf[DECIMAL_MAX_STR_LENGTH];
4471  String str(buf, sizeof (buf), &my_charset_bin);
4472  int rc;
4473 
4474  rc= my_decimal2string(E_DEC_FATAL_ERROR, value, 0, 0, 0, &str);
4475 
4476  if (rc)
4477  return TRUE;
4478 
4479  return store_column(str.ptr(), str.length());
4480 }
4481 
4482 
4485 bool Protocol_local::store(const char *str, size_t length,
4486  const CHARSET_INFO *src_cs)
4487 {
4488  const CHARSET_INFO *dst_cs;
4489 
4490  dst_cs= m_connection->m_thd->variables.character_set_results;
4491  return store_string(str, length, src_cs, dst_cs);
4492 }
4493 
4494 
4497 bool Protocol_local::store(const char *str, size_t length,
4498  const CHARSET_INFO *src_cs,
4499  const CHARSET_INFO *dst_cs)
4500 {
4501  return store_string(str, length, src_cs, dst_cs);
4502 }
4503 
4504 
4505 /* Store MYSQL_TIME (in binary format) */
4506 
4508  uint precision __attribute__((unused)))
4509 {
4510  return store_column(time, sizeof(MYSQL_TIME));
4511 }
4512 
4513 
4517 {
4518  return store_column(time, sizeof(MYSQL_TIME));
4519 }
4520 
4521 
4525  uint precision __attribute__((unused)))
4526 {
4527  return store_column(time, sizeof(MYSQL_TIME));
4528 }
4529 
4530 
4531 /* Store a floating point number, as is. */
4532 
4533 bool Protocol_local::store(float value, uint32 decimals, String *buffer)
4534 {
4535  return store_column(&value, sizeof(float));
4536 }
4537 
4538 
4539 /* Store a double precision number, as is. */
4540 
4541 bool Protocol_local::store(double value, uint32 decimals, String *buffer)
4542 {
4543  return store_column(&value, sizeof (double));
4544 }
4545 
4546 
4547 /* Store a Field. */
4548 
4549 bool Protocol_local::store(Field *field)
4550 {
4551  if (field->is_null())
4552  return store_null();
4553  return field->send_binary(this);
4554 }
4555 
4556 
4560 {
4561  DBUG_ASSERT(m_rset == 0 && !alloc_root_inited(&m_rset_root));
4562 
4563  init_sql_alloc(&m_rset_root, MEM_ROOT_BLOCK_SIZE, 0);
4564 
4565  if (! (m_rset= new (&m_rset_root) List<Ed_row>))
4566  return TRUE;
4567 
4568  m_column_count= columns->elements;
4569 
4570  return FALSE;
4571 }
4572 
4573 
4581 {
4582  return FALSE;
4583 }
4584 
4585 
4588 bool
4589 Protocol_local::send_ok(uint server_status, uint statement_warn_count,
4590  ulonglong affected_rows, ulonglong last_insert_id,
4591  const char *message)
4592 {
4593  /*
4594  Just make sure nothing is sent to the client, we have grabbed
4595  the status information in the connection diagnostics area.
4596  */
4597  return FALSE;
4598 }
4599 
4600 
4609 bool Protocol_local::send_eof(uint server_status, uint statement_warn_count)
4610 {
4611  Ed_result_set *ed_result_set;
4612 
4613  DBUG_ASSERT(m_rset);
4614 
4615  opt_add_row_to_rset();
4616  m_current_row= 0;
4617 
4618  ed_result_set= new (&m_rset_root) Ed_result_set(m_rset, m_column_count,
4619  &m_rset_root);
4620 
4621  m_rset= NULL;
4622 
4623  if (! ed_result_set)
4624  return TRUE;
4625 
4626  /* In case of successful allocation memory ownership was transferred. */
4627  DBUG_ASSERT(!alloc_root_inited(&m_rset_root));
4628 
4629  /*
4630  Link the created Ed_result_set instance into the list of connection
4631  result sets. Never fails.
4632  */
4633  m_connection->add_result_set(ed_result_set);
4634  return FALSE;
4635 }
4636 
4637 
4640 bool
4641 Protocol_local::send_error(uint sql_errno, const char *err_msg, const char*)
4642 {
4643  /*
4644  Just make sure that nothing is sent to the client (default
4645  implementation).
4646  */
4647  return FALSE;
4648 }
4649 
4650 
4651 #ifdef EMBEDDED_LIBRARY
4652 void Protocol_local::remove_last_row()
4653 { }
4654 #endif