sql_prepare.cc 55.3 KB
Newer Older
unknown's avatar
unknown committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (C) 1995-2002 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
15
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA */
unknown's avatar
unknown committed
16 17 18 19 20 21

/**********************************************************************
This file contains the implementation of prepare and executes. 

Prepare:

unknown's avatar
unknown committed
22 23 24
  - Server gets the query from client with command 'COM_PREPARE'; 
    in the following format:
    [COM_PREPARE:1] [query]
unknown's avatar
unknown committed
25
  - Parse the query and recognize any parameter markers '?' and 
unknown's avatar
unknown committed
26 27 28
    store its information list in lex->param_list
  - Allocate a new statement for this prepare; and keep this in 
    'thd->prepared_statements' pool.
unknown's avatar
unknown committed
29 30
  - Without executing the query, return back to client the total 
    number of parameters along with result-set metadata information
unknown's avatar
unknown committed
31
    (if any) in the following format:
32 33 34 35 36
    [STMT_ID:4]
    [Column_count:2]
    [Param_count:2]
    [Columns meta info] (if Column_count > 0)
    [Params meta info]  (if Param_count > 0 ) (TODO : 4.1.1)
unknown's avatar
unknown committed
37 38 39 40
     
Prepare-execute:

  - Server gets the command 'COM_EXECUTE' to execute the 
unknown's avatar
unknown committed
41
    previously prepared query. If there is any param markers; then client
42
    will send the data in the following format:
unknown's avatar
unknown committed
43 44 45 46 47 48 49 50
    [COM_EXECUTE:1]
    [STMT_ID:4]
    [NULL_BITS:(param_count+7)/8)]
    [TYPES_SUPPLIED_BY_CLIENT(0/1):1]
    [[length]data]
    [[length]data] .. [[length]data]. 
    (Note: Except for string/binary types; all other types will not be 
    supplied with length field)
unknown's avatar
unknown committed
51 52
  - Replace the param items with this new data. If it is a first execute 
    or types altered by client; then setup the conversion routines.
unknown's avatar
unknown committed
53 54 55 56
  - Execute the query without re-parsing and send back the results 
    to client

Long data handling:
unknown's avatar
unknown committed
57

unknown's avatar
unknown committed
58 59
  - Server gets the long data in pieces with command type 'COM_LONG_DATA'.
  - The packet recieved will have the format as:
60 61 62
    [COM_LONG_DATA:1][STMT_ID:4][parameter_number:2][data]
  - data from the packet is appended to long data value buffer for this
    placeholder.
63
  - It's up to the client to check for read data ended. The server doesn't
unknown's avatar
unknown committed
64 65 66
    care; and also server doesn't notify to the client that it got the 
    data or not; if there is any error; then during execute; the error 
    will be returned
67

unknown's avatar
unknown committed
68 69 70 71
***********************************************************************/

#include "mysql_priv.h"
#include "sql_acl.h"
unknown's avatar
unknown committed
72
#include "sql_select.h" // for JOIN
73
#include <m_ctype.h>  // for isspace()
74 75 76 77
#ifdef EMBEDDED_LIBRARY
/* include MYSQL_BIND headers */
#include <mysql.h>
#endif
unknown's avatar
unknown committed
78

79 80 81
/******************************************************************************
  Prepared_statement: statement which can contain placeholders
******************************************************************************/
82

83 84 85 86
class Prepared_statement: public Statement
{
public:
  THD *thd;
87
  Item_param **param_array;
88 89 90 91
  uint param_count;
  uint last_errno;
  char last_error[MYSQL_ERRMSG_SIZE];
#ifndef EMBEDDED_LIBRARY
92
  bool (*set_params)(Prepared_statement *st, uchar *data, uchar *data_end,
93
                     uchar *read_pos, String *expanded_query);
unknown's avatar
unknown committed
94
#else
95
  bool (*set_params_data)(Prepared_statement *st, String *expanded_query);
unknown's avatar
unknown committed
96
#endif
unknown's avatar
unknown committed
97
  bool (*set_params_from_vars)(Prepared_statement *stmt, 
98 99
                               List<LEX_STRING>& varnames,
                               String *expanded_query);
100 101 102
public:
  Prepared_statement(THD *thd_arg);
  virtual ~Prepared_statement();
103
  void setup_set_params();
104
  virtual Item_arena::Type type() const;
105
};
unknown's avatar
unknown committed
106

107 108
static void execute_stmt(THD *thd, Prepared_statement *stmt,
                         String *expanded_query, bool set_context);
109

110 111 112
/******************************************************************************
  Implementation
******************************************************************************/
113 114


115
inline bool is_param_null(const uchar *pos, ulong param_no)
116
{
117
  return pos[param_no/8] & (1 << (param_no & 7));
118 119
}

120
enum { STMT_QUERY_LOG_LENGTH= 8192 };
121

122
enum enum_send_error { DONT_SEND_ERROR= 0, SEND_ERROR };
123 124

/*
125 126
  Seek prepared statement in statement map by id: returns zero if statement
  was not found, pointer otherwise.
127 128
*/

129
static Prepared_statement *
130 131
find_prepared_statement(THD *thd, ulong id, const char *where,
                        enum enum_send_error se)
132 133 134
{
  Statement *stmt= thd->stmt_map.find(id);

unknown's avatar
unknown committed
135
  if (stmt == 0 || stmt->type() != Item_arena::PREPARED_STATEMENT)
136
  {
137 138
    char llbuf[22];
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), 22, llstr(id, llbuf), where);
139 140
    if (se == SEND_ERROR)
      send_error(thd);
141 142 143
    return 0;
  }
  return (Prepared_statement *) stmt;
144 145
}

146

147 148 149 150
/*
  Send prepared stmt info to client after prepare
*/

unknown's avatar
unknown committed
151
#ifndef EMBEDDED_LIBRARY
152
static bool send_prep_stmt(Prepared_statement *stmt, uint columns)
153
{
154
  NET *net= &stmt->thd->net;
155
  char buff[9];
156
  buff[0]= 0;                                   /* OK packet indicator */
157
  int4store(buff+1, stmt->id);
158 159
  int2store(buff+5, columns);
  int2store(buff+7, stmt->param_count);
160 161 162 163 164 165 166 167 168 169
  /*
    Send types and names of placeholders to the client
    XXX: fix this nasty upcast from List<Item_param> to List<Item>
  */
  return my_net_write(net, buff, sizeof(buff)) || 
         (stmt->param_count &&
          stmt->thd->protocol_simple.send_fields((List<Item> *)
                                                 &stmt->lex->param_list, 0)) ||
         net_flush(net);
  return 0;
unknown's avatar
unknown committed
170
}
171
#else
172 173
static bool send_prep_stmt(Prepared_statement *stmt,
                           uint columns __attribute__((unused)))
unknown's avatar
unknown committed
174
{
unknown's avatar
SCRUM  
unknown committed
175 176
  THD *thd= stmt->thd;

177
  thd->client_stmt_id= stmt->id;
unknown's avatar
SCRUM  
unknown committed
178
  thd->client_param_count= stmt->param_count;
unknown's avatar
unknown committed
179
  thd->net.last_errno= 0;
unknown's avatar
unknown committed
180

unknown's avatar
SCRUM  
unknown committed
181
  return 0;
182
}
183
#endif /*!EMBEDDED_LIBRARY*/
184

unknown's avatar
unknown committed
185 186

/*
187 188
  Read the length of the parameter data and return back to
  caller by positing the pointer to param data.
unknown's avatar
unknown committed
189 190
*/

unknown's avatar
unknown committed
191
#ifndef EMBEDDED_LIBRARY
192
static ulong get_param_length(uchar **packet, ulong len)
unknown's avatar
unknown committed
193 194
{
  reg1 uchar *pos= *packet;
195 196
  if (len < 1)
    return 0;
unknown's avatar
unknown committed
197 198 199 200 201
  if (*pos < 251)
  {
    (*packet)++;
    return (ulong) *pos;
  }
202 203
  if (len < 3)
    return 0;
unknown's avatar
unknown committed
204 205 206 207 208
  if (*pos == 252)
  {
    (*packet)+=3;
    return (ulong) uint2korr(pos+1);
  }
209 210
  if (len < 4)
    return 0;
unknown's avatar
unknown committed
211 212 213 214 215
  if (*pos == 253)
  {
    (*packet)+=4;
    return (ulong) uint3korr(pos+1);
  }
216 217
  if (len < 5)
    return 0;
unknown's avatar
unknown committed
218
  (*packet)+=9; // Must be 254 when here 
219 220 221 222 223 224 225
  /*
    In our client-server protocol all numbers bigger than 2^24
    stored as 8 bytes with uint8korr. Here we always know that
    parameter length is less than 2^4 so don't look at the second
    4 bytes. But still we need to obey the protocol hence 9 in the
    assignment above.
  */
unknown's avatar
unknown committed
226 227
  return (ulong) uint4korr(pos+1);
}
unknown's avatar
unknown committed
228
#else
229
#define get_param_length(packet, len) len
unknown's avatar
unknown committed
230 231
#endif /*!EMBEDDED_LIBRARY*/

unknown's avatar
unknown committed
232
 /*
233 234 235 236 237 238
   Data conversion routines
   SYNOPSIS
   set_param_xx()
    param   parameter item
    pos     input data buffer
    len     length of data in the buffer
unknown's avatar
unknown committed
239

240 241
  All these functions read the data from pos, convert it to requested type 
  and assign to param; pos is advanced to predefined length.
unknown's avatar
unknown committed
242 243 244 245 246

  Make a note that the NULL handling is examined at first execution
  (i.e. when input types altered) and for all subsequent executions
  we don't read any values for this.

247 248
  RETURN VALUE
    none
unknown's avatar
unknown committed
249 250
*/

251
static void set_param_tiny(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
252
{
253 254 255 256
#ifndef EMBEDDED_LIBRARY
  if (len < 1)
    return;
#endif
257 258
  int8 value= (int8) **pos;
  param->set_int(param->unsigned_flag ? (longlong) ((uint8) value) : 
259
                                        (longlong) value, 4);
unknown's avatar
unknown committed
260 261 262
  *pos+= 1;
}

263
static void set_param_short(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
264
{
265
  int16 value;
266 267 268
#ifndef EMBEDDED_LIBRARY
  if (len < 2)
    return;
269
  value= sint2korr(*pos);
270 271 272
#else
  shortget(value, *pos);
#endif
273
  param->set_int(param->unsigned_flag ? (longlong) ((uint16) value) :
274
                                        (longlong) value, 6);
unknown's avatar
unknown committed
275 276 277
  *pos+= 2;
}

278
static void set_param_int32(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
279
{
280
  int32 value;
281 282 283
#ifndef EMBEDDED_LIBRARY
  if (len < 4)
    return;
284
  value= sint4korr(*pos);
285 286 287
#else
  longget(value, *pos);
#endif
288
  param->set_int(param->unsigned_flag ? (longlong) ((uint32) value) :
289
                                        (longlong) value, 11);
unknown's avatar
unknown committed
290 291 292
  *pos+= 4;
}

293
static void set_param_int64(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
294
{
295
  longlong value;
296 297 298
#ifndef EMBEDDED_LIBRARY
  if (len < 8)
    return;
299
  value= (longlong) sint8korr(*pos);
300 301 302
#else
  longlongget(value, *pos);
#endif
303 304
  param->set_int(value, 21);
  *pos+= 8;
unknown's avatar
unknown committed
305 306
}

307
static void set_param_float(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
308
{
309 310 311 312
#ifndef EMBEDDED_LIBRARY
  if (len < 4)
    return;
#endif
unknown's avatar
unknown committed
313 314 315 316 317 318
  float data;
  float4get(data,*pos);
  param->set_double((double) data);
  *pos+= 4;
}

319
static void set_param_double(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
320
{
321 322 323 324
#ifndef EMBEDDED_LIBRARY
  if (len < 8)
    return;
#endif
unknown's avatar
unknown committed
325 326 327 328 329 330
  double data;
  float8get(data,*pos);
  param->set_double((double) data);
  *pos+= 8;
}

331
#ifndef EMBEDDED_LIBRARY
332 333 334 335 336 337 338

/*
  Read date/time/datetime parameter values from network (binary
  protocol). See writing counterparts of these functions in
  libmysql.c (store_param_{time,date,datetime}).
*/

339
static void set_param_time(Item_param *param, uchar **pos, ulong len)
340
{
341 342
  MYSQL_TIME tm;
  ulong length= get_param_length(pos, len);
343

344
  if (length >= 8)
345 346
  {
    uchar *to= *pos;
347
    uint day;
348

349 350
    tm.neg= (bool) to[0];
    day= (uint) sint4korr(to+1);
351 352 353 354 355 356 357
    /*
      Note, that though ranges of hour, minute and second are not checked
      here we rely on them being < 256: otherwise
      we'll get buffer overflow in make_{date,time} functions,
      which are called when time value is converted to string.
    */
    tm.hour=   (uint) to[5] + day * 24;
358 359
    tm.minute= (uint) to[6];
    tm.second= (uint) to[7];
360
    tm.second_part= (length > 8) ? (ulong) sint4korr(to+8) : 0;
361 362 363 364 365 366 367 368
    if (tm.hour > 838)
    {
      /* TODO: add warning 'Data truncated' here */
      tm.hour= 838;
      tm.minute= 59;
      tm.second= 59;
    }
    tm.day= tm.year= tm.month= 0;
369
  }
370 371 372 373
  else
    set_zero_time(&tm);
  param->set_time(&tm, MYSQL_TIMESTAMP_TIME,
                  MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
374 375 376
  *pos+= length;
}

377
static void set_param_datetime(Item_param *param, uchar **pos, ulong len)
378
{
379 380
  MYSQL_TIME tm;
  ulong length= get_param_length(pos, len);
381

382
  if (length >= 4)
383 384
  {
    uchar *to= *pos;
385 386 387 388 389

    tm.neg=    0;
    tm.year=   (uint) sint2korr(to);
    tm.month=  (uint) to[2];
    tm.day=    (uint) to[3];
390 391 392 393 394
    /*
      Note, that though ranges of hour, minute and second are not checked
      here we rely on them being < 256: otherwise
      we'll get buffer overflow in make_{date,time} functions.
    */
395 396 397 398 399 400 401 402
    if (length > 4)
    {
      tm.hour=   (uint) to[4];
      tm.minute= (uint) to[5];
      tm.second= (uint) to[6];
    }
    else
      tm.hour= tm.minute= tm.second= 0;
403 404

    tm.second_part= (length > 7) ? (ulong) sint4korr(to+7) : 0;
405
  }
406 407 408 409
  else
    set_zero_time(&tm);
  param->set_time(&tm, MYSQL_TIMESTAMP_DATETIME,
                  MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
410 411 412
  *pos+= length;
}

413
static void set_param_date(Item_param *param, uchar **pos, ulong len)
414
{
415 416 417 418
  MYSQL_TIME tm;
  ulong length= get_param_length(pos, len);

  if (length >= 4)
419 420
  {
    uchar *to= *pos;
421 422 423 424 425
    /*
      Note, that though ranges of hour, minute and second are not checked
      here we rely on them being < 256: otherwise
      we'll get buffer overflow in make_{date,time} functions.
    */
426
    tm.year=  (uint) sint2korr(to);
427 428 429 430 431 432 433
    tm.month=  (uint) to[2];
    tm.day= (uint) to[3];

    tm.hour= tm.minute= tm.second= 0;
    tm.second_part= 0;
    tm.neg= 0;
  }
434 435 436 437
  else
    set_zero_time(&tm);
  param->set_time(&tm, MYSQL_TIMESTAMP_DATE,
                  MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
438 439 440
  *pos+= length;
}

441 442 443 444
#else/*!EMBEDDED_LIBRARY*/
void set_param_time(Item_param *param, uchar **pos, ulong len)
{
  MYSQL_TIME *to= (MYSQL_TIME*)*pos;
445
  param->set_time(to, MYSQL_TIMESTAMP_TIME,
446
                  MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
447 448 449 450 451 452 453

}

void set_param_datetime(Item_param *param, uchar **pos, ulong len)
{
  MYSQL_TIME *to= (MYSQL_TIME*)*pos;

454
  param->set_time(to, MYSQL_TIMESTAMP_DATETIME,
455
                  MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
456 457 458 459 460
}

void set_param_date(Item_param *param, uchar **pos, ulong len)
{
  MYSQL_TIME *to= (MYSQL_TIME*)*pos;
461 462

  param->set_time(to, MYSQL_TIMESTAMP_DATE,
463
                  MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
464 465 466
}
#endif /*!EMBEDDED_LIBRARY*/

467 468

static void set_param_str(Item_param *param, uchar **pos, ulong len)
unknown's avatar
unknown committed
469
{
470
  ulong length= get_param_length(pos, len);
471
  param->set_str((const char *)*pos, length);
472
  *pos+= length;
unknown's avatar
unknown committed
473 474
}

475 476 477 478 479

#undef get_param_length 

static void setup_one_conversion_function(THD *thd, Item_param *param,
                                          uchar param_type)
unknown's avatar
unknown committed
480
{
unknown's avatar
unknown committed
481
  switch (param_type) {
482
  case MYSQL_TYPE_TINY:
483
    param->set_param_func= set_param_tiny;
484
    param->item_type= Item::INT_ITEM;
485
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
486
    break;
487
  case MYSQL_TYPE_SHORT:
488
    param->set_param_func= set_param_short;
489
    param->item_type= Item::INT_ITEM;
490
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
491
    break;
492
  case MYSQL_TYPE_LONG:
493
    param->set_param_func= set_param_int32;
494
    param->item_type= Item::INT_ITEM;
495
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
496
    break;
497
  case MYSQL_TYPE_LONGLONG:
498
    param->set_param_func= set_param_int64;
499
    param->item_type= Item::INT_ITEM;
500
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
501
    break;
502
  case MYSQL_TYPE_FLOAT:
503
    param->set_param_func= set_param_float;
504
    param->item_type= Item::REAL_ITEM;
505
    param->item_result_type= REAL_RESULT;
unknown's avatar
unknown committed
506
    break;
507
  case MYSQL_TYPE_DOUBLE:
508
    param->set_param_func= set_param_double;
509
    param->item_type= Item::REAL_ITEM;
510
    param->item_result_type= REAL_RESULT;
unknown's avatar
unknown committed
511
    break;
512
  case MYSQL_TYPE_TIME:
513
    param->set_param_func= set_param_time;
514
    param->item_type= Item::STRING_ITEM;
515
    param->item_result_type= STRING_RESULT;
516
    break;
517
  case MYSQL_TYPE_DATE:
518
    param->set_param_func= set_param_date;
519
    param->item_type= Item::STRING_ITEM;
520
    param->item_result_type= STRING_RESULT;
521
    break;
522 523
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
524
    param->set_param_func= set_param_datetime;
525
    param->item_type= Item::STRING_ITEM;
526
    param->item_result_type= STRING_RESULT;
527
    break;
528 529 530 531
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
532
    param->set_param_func= set_param_str;
533 534 535
    param->value.cs_info.character_set_client= &my_charset_bin;
    param->value.cs_info.final_character_set_of_str_value= &my_charset_bin;
    param->item_type= Item::STRING_ITEM;
536
    param->item_result_type= STRING_RESULT;
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    break;
  default:
    /*
      The client library ensures that we won't get any other typecodes
      except typecodes above and typecodes for string types. Marking
      label as 'default' lets us to handle malformed packets as well.
    */
    {
      CHARSET_INFO *fromcs= thd->variables.character_set_client;
      CHARSET_INFO *tocs= thd->variables.collation_connection;
      uint32 dummy_offset;

      param->value.cs_info.character_set_client= fromcs;

      /*
        Setup source and destination character sets so that they
        are different only if conversion is necessary: this will
        make later checks easier.
      */
      param->value.cs_info.final_character_set_of_str_value=
        String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
        tocs : fromcs;
      param->set_param_func= set_param_str;
      /*
        Exact value of max_length is not known unless data is converted to
        charset of connection, so we have to set it later.
      */
      param->item_type= Item::STRING_ITEM;
      param->item_result_type= STRING_RESULT;
    }
unknown's avatar
unknown committed
567
  }
568
  param->param_type= (enum enum_field_types) param_type;
unknown's avatar
unknown committed
569 570
}

unknown's avatar
unknown committed
571
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
572
/*
573 574
  Update the parameter markers by reading data from client packet 
  and if binary/update log is set, generate the valid query.
unknown's avatar
unknown committed
575 576
*/

577
static bool insert_params_withlog(Prepared_statement *stmt, uchar *null_array,
578 579
                                  uchar *read_pos, uchar *data_end, 
                                  String *query)
580
{
581 582 583 584 585
  THD  *thd= stmt->thd;
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
  uint32 length= 0;

586
  String str; 
587 588 589
  const String *res;

  DBUG_ENTER("insert_params_withlog"); 
590

591
  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
592
    DBUG_RETURN(1);
593
  
594
  for (Item_param **it= begin; it < end; ++it)
595
  {
596
    Item_param *param= *it;
597
    if (param->state != Item_param::LONG_DATA_VALUE)
598
    {
599
      if (is_param_null(null_array, it - begin))
600
        param->set_null();
601 602
      else
      {
603 604 605
        if (read_pos >= data_end)
          DBUG_RETURN(1);
        param->set_param_func(param, &read_pos, data_end - read_pos);
606 607
      }
    }
608 609 610 611
    res= param->query_val_str(&str);
    if (param->convert_str_value(thd))
      DBUG_RETURN(1);                           /* out of memory */

612
    if (query->replace(param->pos_in_query+length, 1, *res))
613 614 615 616 617 618 619
      DBUG_RETURN(1);
    
    length+= res->length()-1;
  }
  DBUG_RETURN(0);
}

620

621
static bool insert_params(Prepared_statement *stmt, uchar *null_array,
622 623
                          uchar *read_pos, uchar *data_end, 
                          String *expanded_query)
624
{
625 626
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
627 628 629

  DBUG_ENTER("insert_params"); 

630
  for (Item_param **it= begin; it < end; ++it)
631
  {
632
    Item_param *param= *it;
633
    if (param->state != Item_param::LONG_DATA_VALUE)
634
    {
635
      if (is_param_null(null_array, it - begin))
636
        param->set_null();
637 638
      else
      {
639 640 641
        if (read_pos >= data_end)
          DBUG_RETURN(1);
        param->set_param_func(param, &read_pos, data_end - read_pos);
642 643
      }
    }
644 645
    if (param->convert_str_value(stmt->thd))
      DBUG_RETURN(1);                           /* out of memory */
646 647 648 649
  }
  DBUG_RETURN(0);
}

650

651
static bool setup_conversion_functions(Prepared_statement *stmt,
652
                                       uchar **data, uchar *data_end)
653 654 655
{
  /* skip null bits */
  uchar *read_pos= *data + (stmt->param_count+7) / 8;
unknown's avatar
unknown committed
656

657
  DBUG_ENTER("setup_conversion_functions");
658

unknown's avatar
unknown committed
659
  if (*read_pos++) //types supplied / first execute
660
  {
unknown's avatar
unknown committed
661 662 663 664
    /*
      First execute or types altered by the client, setup the 
      conversion routines for all parameters (one time)
    */
665 666
    Item_param **it= stmt->param_array;
    Item_param **end= it + stmt->param_count;
667
    THD *thd= stmt->thd;
668 669
    for (; it < end; ++it)
    {
670 671 672
      ushort typecode;
      const uint signed_bit= 1 << 15;

673 674
      if (read_pos >= data_end)
        DBUG_RETURN(1);
675 676

      typecode= sint2korr(read_pos);
unknown's avatar
unknown committed
677
      read_pos+= 2;
678
      (**it).unsigned_flag= test(typecode & signed_bit);
679
      setup_one_conversion_function(thd, *it, (uchar) (typecode & ~signed_bit));
unknown's avatar
unknown committed
680
    }
681 682
  }
  *data= read_pos;
unknown's avatar
unknown committed
683 684 685
  DBUG_RETURN(0);
}

686 687
#else

688
static bool emb_insert_params(Prepared_statement *stmt, String *expanded_query)
689
{
690
  THD *thd= stmt->thd;
691 692
  Item_param **it= stmt->param_array;
  Item_param **end= it + stmt->param_count;
693 694
  MYSQL_BIND *client_param= stmt->thd->client_params;

695
  DBUG_ENTER("emb_insert_params");
696

697 698 699
  for (; it < end; ++it, ++client_param)
  {
    Item_param *param= *it;
700 701
    setup_one_conversion_function(thd, param, client_param->buffer_type);
    if (param->state != Item_param::LONG_DATA_VALUE)
702 703
    {
      if (*client_param->is_null)
704
        param->set_null();
705 706
      else
      {
707
        uchar *buff= (uchar*) client_param->buffer;
unknown's avatar
unknown committed
708
        param->unsigned_flag= client_param->is_unsigned;
709 710 711 712
        param->set_param_func(param, &buff,
                              client_param->length ? 
                              *client_param->length : 
                              client_param->buffer_length);
713 714
      }
    }
715 716
    if (param->convert_str_value(thd))
      DBUG_RETURN(1);                           /* out of memory */
717 718 719 720
  }
  DBUG_RETURN(0);
}

721

722
static bool emb_insert_params_withlog(Prepared_statement *stmt, String *query)
723
{
724
  THD *thd= stmt->thd;
725 726
  Item_param **it= stmt->param_array;
  Item_param **end= it + stmt->param_count;
727 728
  MYSQL_BIND *client_param= thd->client_params;

729
  String str;
730
  const String *res;
731
  uint32 length= 0;
732

733
  DBUG_ENTER("emb_insert_params_withlog");
734

735
  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
736 737
    DBUG_RETURN(1);
  
738 739 740
  for (; it < end; ++it, ++client_param)
  {
    Item_param *param= *it;
741 742
    setup_one_conversion_function(thd, param, client_param->buffer_type);
    if (param->state != Item_param::LONG_DATA_VALUE)
743 744
    {
      if (*client_param->is_null)
745
        param->set_null();
746 747
      else
      {
748
        uchar *buff= (uchar*)client_param->buffer;
749
	param->unsigned_flag= client_param->is_unsigned;
750 751 752 753
        param->set_param_func(param, &buff,
                              client_param->length ? 
                              *client_param->length : 
                              client_param->buffer_length);
754 755
      }
    }
756 757 758 759
    res= param->query_val_str(&str);
    if (param->convert_str_value(thd))
      DBUG_RETURN(1);                           /* out of memory */

760
    if (query->replace(param->pos_in_query+length, 1, *res))
761
      DBUG_RETURN(1);
762

763 764 765 766 767
    length+= res->length()-1;
  }
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
768 769
#endif /*!EMBEDDED_LIBRARY*/

unknown's avatar
unknown committed
770

771
/*
unknown's avatar
unknown committed
772 773 774 775 776 777
  Set prepared statement parameters from user variables.
  SYNOPSIS
    insert_params_from_vars()
      stmt      Statement
      varnames  List of variables. Caller must ensure that number of variables
                in the list is equal to number of statement parameters
778
      query     Ignored
unknown's avatar
unknown committed
779 780
*/

781 782
static bool insert_params_from_vars(Prepared_statement *stmt,
                                    List<LEX_STRING>& varnames,
783
                                    String *query __attribute__((unused)))
unknown's avatar
unknown committed
784 785 786 787 788 789
{
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
  user_var_entry *entry;
  LEX_STRING *varname;
  List_iterator<LEX_STRING> var_it(varnames);
790 791
  DBUG_ENTER("insert_params_from_vars");

unknown's avatar
unknown committed
792 793 794 795
  for (Item_param **it= begin; it < end; ++it)
  {
    Item_param *param= *it;
    varname= var_it++;
796 797 798 799 800 801
    entry= (user_var_entry*)hash_search(&stmt->thd->user_vars,
                                        (byte*) varname->str,
                                         varname->length);
    if (param->set_from_user_var(stmt->thd, entry) ||
        param->convert_str_value(stmt->thd))
      DBUG_RETURN(1);
unknown's avatar
unknown committed
802 803 804 805
  }
  DBUG_RETURN(0);
}

806

807
/*
808 809 810 811 812 813 814 815 816 817
  Do the same as insert_params_from_vars but also construct query text for
  binary log.
  SYNOPSIS
    insert_params_from_vars()
      stmt      Statement
      varnames  List of variables. Caller must ensure that number of variables
                in the list is equal to number of statement parameters
      query     The query with parameter markers replaced with their values
*/

unknown's avatar
unknown committed
818
static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
819
                                             List<LEX_STRING>& varnames,
820
                                             String *query)
unknown's avatar
unknown committed
821 822 823 824 825
{
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
  user_var_entry *entry;
  LEX_STRING *varname;
826
  DBUG_ENTER("insert_params_from_vars");
unknown's avatar
unknown committed
827 828

  List_iterator<LEX_STRING> var_it(varnames);
829
  String str;
unknown's avatar
unknown committed
830
  uint32 length= 0;
831
  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
832
    DBUG_RETURN(1);
unknown's avatar
unknown committed
833 834 835 836 837

  for (Item_param **it= begin; it < end; ++it)
  {
    Item_param *param= *it;
    varname= var_it++;
838 839 840
    if (get_var_with_binlog(stmt->thd, *varname, &entry))
        DBUG_RETURN(1);
    DBUG_ASSERT(entry);
unknown's avatar
unknown committed
841

842 843 844
    if (param->set_from_user_var(stmt->thd, entry))
      DBUG_RETURN(1);
    /* Insert @'escaped-varname' instead of parameter in the query */
845 846 847
    char *buf, *ptr;
    str.length(0);
    if (str.reserve(entry->name.length*2+3))
unknown's avatar
unknown committed
848
      DBUG_RETURN(1);
849 850 851 852 853

    buf= str.c_ptr_quick();
    ptr= buf;
    *ptr++= '@';
    *ptr++= '\'';
854 855
    ptr+=
      escape_string_for_mysql(&my_charset_utf8_general_ci,
856 857 858 859 860 861
                              ptr, entry->name.str, entry->name.length);
    *ptr++= '\'';
    str.length(ptr - buf);

    if (param->convert_str_value(stmt->thd))
      DBUG_RETURN(1);                           /* out of memory */
862

863 864 865
    if (query->replace(param->pos_in_query+length, 1, str))
      DBUG_RETURN(1);
    length+= str.length()-1;
unknown's avatar
unknown committed
866 867 868 869
  }
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
870
/*
unknown's avatar
unknown committed
871 872
  Validate INSERT statement: 

873
  SYNOPSIS
unknown's avatar
unknown committed
874 875 876 877
    mysql_test_insert()
    stmt	prepared statemen handler
    tables	list of tables queries  

878 879 880 881
  RETURN VALUE
    0   ok
    1   error, sent to the client
   -1   error, not sent to client
unknown's avatar
unknown committed
882
*/
unknown's avatar
unknown committed
883 884 885 886 887 888 889
static int mysql_test_insert(Prepared_statement *stmt,
			     TABLE_LIST *table_list,
			     List<Item> &fields, 
			     List<List_item> &values_list,
			     List<Item> &update_fields,
			     List<Item> &update_values,
			     enum_duplicates duplic)
unknown's avatar
unknown committed
890
{
891
  THD *thd= stmt->thd;
892
  LEX *lex= stmt->lex;
unknown's avatar
unknown committed
893 894
  List_iterator_fast<List_item> its(values_list);
  List_item *values;
unknown's avatar
unknown committed
895
  int res= -1;
896 897
  TABLE_LIST *insert_table_list=
    (TABLE_LIST*) lex->select_lex.table_list.first;
898
  DBUG_ENTER("mysql_test_insert");
unknown's avatar
unknown committed
899

900
  if ((res= insert_precheck(thd, table_list)))
unknown's avatar
unknown committed
901
    DBUG_RETURN(res);
unknown's avatar
unknown committed
902

903
  /*
unknown's avatar
unknown committed
904 905 906
     open temporary memory pool for temporary data allocated by derived
     tables & preparation procedure
  */
unknown's avatar
unknown committed
907
  if (open_and_lock_tables(thd, table_list))
908
  {
909
    DBUG_RETURN(-1);
910 911
  }

unknown's avatar
unknown committed
912 913 914
  if ((values= its++))
  {
    uint value_count;
915
    ulong counter= 0;
unknown's avatar
unknown committed
916

unknown's avatar
unknown committed
917 918 919 920 921
    if ((res= mysql_prepare_insert(thd, table_list, insert_table_list,
				   table_list->table, fields, values,
				   update_fields, update_values, duplic)))
      goto error;
    
unknown's avatar
unknown committed
922 923 924
    value_count= values->elements;
    its.rewind();
   
925
    while ((values= its++))
unknown's avatar
unknown committed
926 927 928 929 930 931
    {
      counter++;
      if (values->elements != value_count)
      {
        my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
			ER(ER_WRONG_VALUE_COUNT_ON_ROW),
932
			MYF(0), counter);
933
        goto error;
unknown's avatar
unknown committed
934
      }
935 936
      if (setup_fields(thd, 0, insert_table_list, *values, 0, 0, 0))
	goto error;
unknown's avatar
unknown committed
937 938
    }
  }
939

unknown's avatar
unknown committed
940
  res= 0;
941 942
error:
  lex->unit.cleanup();
unknown's avatar
unknown committed
943
  DBUG_RETURN(res);
unknown's avatar
unknown committed
944 945 946 947
}


/*
unknown's avatar
unknown committed
948 949
  Validate UPDATE statement

950
  SYNOPSIS
951
    mysql_test_update()
unknown's avatar
unknown committed
952 953 954
    stmt	prepared statemen handler
    tables	list of tables queries

955 956 957 958
  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
unknown's avatar
unknown committed
959
*/
unknown's avatar
unknown committed
960 961
static int mysql_test_update(Prepared_statement *stmt,
			     TABLE_LIST *table_list)
unknown's avatar
unknown committed
962
{
unknown's avatar
unknown committed
963
  int res;
964
  THD *thd= stmt->thd;
unknown's avatar
unknown committed
965 966 967 968 969
  SELECT_LEX *select= &stmt->lex->select_lex;
  DBUG_ENTER("mysql_test_update");

  if ((res= update_precheck(thd, table_list)))
    DBUG_RETURN(res);
unknown's avatar
unknown committed
970

unknown's avatar
unknown committed
971
  if (open_and_lock_tables(thd, table_list))
unknown's avatar
unknown committed
972 973
    res= -1;
  else
974
  {
unknown's avatar
unknown committed
975 976 977 978 979 980 981 982 983 984 985 986 987
    TABLE_LIST *update_table_list= (TABLE_LIST *)select->table_list.first;
    if (!(res= mysql_prepare_update(thd, table_list,
				    update_table_list,
				    &select->where,
				    select->order_list.elements,
				    (ORDER *) select->order_list.first)))
    {
      if (setup_fields(thd, 0, update_table_list,
		       select->item_list, 1, 0, 0) ||
	  setup_fields(thd, 0, update_table_list,
		       stmt->lex->value_list, 0, 0, 0))
	res= -1;
    }
988 989
    stmt->lex->unit.cleanup();
  }
unknown's avatar
unknown committed
990 991 992
  /* TODO: here we should send types of placeholders to the client. */ 
  DBUG_RETURN(res);
}
unknown's avatar
unknown committed
993

unknown's avatar
unknown committed
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

/*
  Validate DELETE statement

  SYNOPSIS
    mysql_test_delete()
    stmt	prepared statemen handler
    tables	list of tables queries

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/
static int mysql_test_delete(Prepared_statement *stmt,
			     TABLE_LIST *table_list)
{
  int res;
  THD *thd= stmt->thd;
  LEX *lex= stmt->lex;
  DBUG_ENTER("mysql_test_delete");

  if ((res= delete_precheck(thd, table_list)))
    DBUG_RETURN(res);

  if (open_and_lock_tables(thd, table_list))
    res= -1;
  else
  {
    res= mysql_prepare_delete(thd, table_list, &lex->select_lex.where);
    lex->unit.cleanup();
  }
  /* TODO: here we should send types of placeholders to the client. */ 
  DBUG_RETURN(res);
unknown's avatar
unknown committed
1028 1029
}

unknown's avatar
unknown committed
1030

unknown's avatar
unknown committed
1031
/*
unknown's avatar
unknown committed
1032
  Validate SELECT statement.
1033 1034
  In case of success, if this query is not EXPLAIN, send column list info
  back to client. 
unknown's avatar
unknown committed
1035

1036
  SYNOPSIS
unknown's avatar
unknown committed
1037 1038 1039 1040
    mysql_test_select()
    stmt	prepared statemen handler
    tables	list of tables queries

1041 1042 1043 1044
  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
unknown's avatar
unknown committed
1045
*/
1046

unknown's avatar
unknown committed
1047
static int mysql_test_select(Prepared_statement *stmt,
unknown's avatar
unknown committed
1048
			     TABLE_LIST *tables, bool text_protocol)
unknown's avatar
unknown committed
1049
{
1050
  THD *thd= stmt->thd;
1051
  LEX *lex= stmt->lex;
1052
  SELECT_LEX_UNIT *unit= &lex->unit;
1053
  int result= 1;
unknown's avatar
unknown committed
1054
  DBUG_ENTER("mysql_test_select");
unknown's avatar
unknown committed
1055

unknown's avatar
unknown committed
1056
#ifndef NO_EMBEDDED_ACCESS_CHECKS
1057 1058 1059
  ulong privilege= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL;
  if (tables)
  {
unknown's avatar
unknown committed
1060
    if (check_table_access(thd, privilege, tables,0))
1061 1062
      DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
1063
  else if (check_access(thd, privilege, any_db,0,0,0))
1064
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1065
#endif
unknown's avatar
unknown committed
1066

1067 1068 1069 1070 1071 1072
  if (!lex->result && !(lex->result= new (&stmt->mem_root) select_send))
  {
    send_error(thd);
    goto err;
  }

unknown's avatar
unknown committed
1073
  if (open_and_lock_tables(thd, tables))
1074 1075
  {
    send_error(thd);
unknown's avatar
unknown committed
1076
    goto err;
1077
  }
unknown's avatar
unknown committed
1078

1079 1080 1081 1082 1083 1084 1085 1086
  thd->used_tables= 0;                        // Updated by setup_fields

  // JOIN::prepare calls
  if (unit->prepare(thd, 0, 0))
  {
    send_error(thd);
    goto err_prep;
  }
1087
  if (!text_protocol)
1088
  {
1089 1090 1091 1092 1093 1094
    if (lex->describe)
    {
      if (send_prep_stmt(stmt, 0))
        goto err_prep;
    }
    else
unknown's avatar
unknown committed
1095
    {
1096 1097 1098 1099 1100 1101 1102
      List<Item> &fields= lex->select_lex.item_list;
      /*
        We can use lex->result as it should've been
        prepared in unit->prepare call above.
      */
      if (send_prep_stmt(stmt, lex->result->field_count(fields)) ||
          lex->result->send_fields(fields, 0)
unknown's avatar
SCRUM  
unknown committed
1103
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1104
          || net_flush(&thd->net)
unknown's avatar
SCRUM  
unknown committed
1105
#endif
unknown's avatar
unknown committed
1106 1107 1108
         )
        goto err_prep;
    }
1109
  }
1110
  result= 0;                                    // ok
1111 1112 1113 1114

err_prep:
  unit->cleanup();
err:
1115
  DBUG_RETURN(result);
unknown's avatar
unknown committed
1116 1117
}

1118

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
/*
  Validate and prepare for execution DO statement expressions

  SYNOPSIS
    mysql_test_do_fields()
    stmt	prepared statemen handler
    tables	list of tables queries
    values	list of expressions

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/

static int mysql_test_do_fields(Prepared_statement *stmt,
				TABLE_LIST *tables,
				List<Item> *values)
{
  DBUG_ENTER("mysql_test_do_fields");
  THD *thd= stmt->thd;
  int res= 0;
  if (tables && (res= check_table_access(thd, SELECT_ACL, tables, 0)))
    DBUG_RETURN(res);
1143

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
  if (tables && (res= open_and_lock_tables(thd, tables)))
  {
    DBUG_RETURN(res);
  }
  res= setup_fields(thd, 0, 0, *values, 0, 0, 0);
  stmt->lex->unit.cleanup();
  if (res)
    DBUG_RETURN(-1);
  DBUG_RETURN(0);
}


/*
  Validate and prepare for execution SET statement expressions

  SYNOPSIS
    mysql_test_set_fields()
    stmt	prepared statemen handler
    tables	list of tables queries
    values	list of expressions

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/
static int mysql_test_set_fields(Prepared_statement *stmt,
				TABLE_LIST *tables,
				List<set_var_base> *var_list)
{
  DBUG_ENTER("mysql_test_set_fields");
  List_iterator_fast<set_var_base> it(*var_list);
  THD *thd= stmt->thd;
  set_var_base *var;
  int res= 0;

  if (tables && (res= check_table_access(thd, SELECT_ACL, tables, 0)))
    DBUG_RETURN(res);
1182

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
  if (tables && (res= open_and_lock_tables(thd, tables)))
    goto error;
  while ((var= it++))
  {
    if (var->light_check(thd))
    {
      stmt->lex->unit.cleanup();
      res= -1;
      goto error;
    }
  }
error:
unknown's avatar
unknown committed
1195
  stmt->lex->unit.cleanup();
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
  DBUG_RETURN(res);
}


/*
  Check internal SELECT of the prepared command

  SYNOPSIS
    select_like_statement_test()
      stmt	- prepared table handler
      tables	- global list of tables

unknown's avatar
unknown committed
1208
  RETURN VALUE
1209 1210
    0   success
    1   error, sent to client
unknown's avatar
unknown committed
1211
   -1   error, not sent to client
1212 1213 1214 1215 1216 1217 1218 1219
*/
static int select_like_statement_test(Prepared_statement *stmt,
				      TABLE_LIST *tables)
{
  DBUG_ENTER("select_like_statement_test");
  THD *thd= stmt->thd;
  LEX *lex= stmt->lex;
  int res= 0;
1220

1221 1222 1223 1224 1225
  if (tables && (res= open_and_lock_tables(thd, tables)))
    goto end;

  thd->used_tables= 0;                        // Updated by setup_fields

unknown's avatar
unknown committed
1226
  // JOIN::prepare calls
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  if (lex->unit.prepare(thd, 0, 0))
  {
    res= thd->net.report_error ? -1 : 1;
  }
end:
  lex->unit.cleanup();
  DBUG_RETURN(res);
}


/*
1238
  Validate and prepare for execution CREATE TABLE statement
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

  SYNOPSIS
    mysql_test_create_table()
    stmt	prepared statemen handler
    tables	list of tables queries

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/
static int mysql_test_create_table(Prepared_statement *stmt,
				   TABLE_LIST *tables)
{
  DBUG_ENTER("mysql_test_create_table");
  THD *thd= stmt->thd;
  LEX *lex= stmt->lex;
1256
  SELECT_LEX *select_lex= &lex->select_lex;
1257 1258 1259 1260 1261
  int res= 0;

  /* Skip first table, which is the table we are creating */
  TABLE_LIST *create_table, *create_table_local;
  tables= lex->unlink_first_table(tables, &create_table,
unknown's avatar
unknown committed
1262
				  &create_table_local);
1263

unknown's avatar
unknown committed
1264
  if (!(res= create_table_precheck(thd, tables, create_table)) &&
1265 1266 1267
      select_lex->item_list.elements)
  {
    select_lex->resolve_mode= SELECT_LEX::SELECT_MODE;
1268
    res= select_like_statement_test(stmt, tables);
1269 1270
    select_lex->resolve_mode= SELECT_LEX::NOMATTER_MODE;
  }
1271

unknown's avatar
unknown committed
1272
  /* put tables back for PS rexecuting */
1273 1274 1275 1276 1277
  tables= lex->link_first_table_back(tables, create_table,
				     create_table_local);
  DBUG_RETURN(res);
}

unknown's avatar
unknown committed
1278

1279
/*
1280
  Validate and prepare for execution multi update statement
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302

  SYNOPSIS
    mysql_test_multiupdate()
    stmt	prepared statemen handler
    tables	list of tables queries

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/
static int mysql_test_multiupdate(Prepared_statement *stmt,
				  TABLE_LIST *tables)
{
  int res;
  if ((res= multi_update_precheck(stmt->thd, tables)))
    return res;
  return select_like_statement_test(stmt, tables);
}


/*
1303
  Validate and prepare for execution multi delete statement
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

  SYNOPSIS
    mysql_test_multidelete()
    stmt	prepared statemen handler
    tables	list of tables queries

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/
static int mysql_test_multidelete(Prepared_statement *stmt,
				  TABLE_LIST *tables)
{
  int res;
  stmt->thd->lex->current_select= &stmt->thd->lex->select_lex;
  if (add_item_to_list(stmt->thd, new Item_null()))
    return -1;

unknown's avatar
unknown committed
1323
  uint fake_counter;
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
  if ((res= multi_delete_precheck(stmt->thd, tables, &fake_counter)))
    return res;
  return select_like_statement_test(stmt, tables);
}


/*
  Validate and prepare for execution INSERT ... SELECT statement

  SYNOPSIS
    mysql_test_insert_select()
    stmt	prepared statemen handler
    tables	list of tables queries

  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
*/
static int mysql_test_insert_select(Prepared_statement *stmt,
				    TABLE_LIST *tables)
{
  int res;
  LEX *lex= stmt->lex;
  if ((res= insert_select_precheck(stmt->thd, tables)))
    return res;
  TABLE_LIST *first_local_table=
    (TABLE_LIST *)lex->select_lex.table_list.first;
  /* Skip first table, which is the table we are inserting in */
unknown's avatar
unknown committed
1353
  lex->select_lex.table_list.first= (byte*) first_local_table->next;
1354 1355 1356 1357 1358
  /*
    insert/replace from SELECT give its SELECT_LEX for SELECT,
    and item_list belong to SELECT
  */
  lex->select_lex.resolve_mode= SELECT_LEX::SELECT_MODE;
1359 1360
  res= select_like_statement_test(stmt, tables);
  /* revert changes*/
unknown's avatar
unknown committed
1361
  lex->select_lex.table_list.first= (byte*) first_local_table;
1362 1363 1364 1365 1366
  lex->select_lex.resolve_mode= SELECT_LEX::INSERT_MODE;
  return res;
}


unknown's avatar
unknown committed
1367
/*
1368 1369 1370 1371 1372 1373 1374
  Send the prepare query results back to client
  SYNOPSIS
  send_prepare_results()
    stmt prepared statement
  RETURN VALUE
    0   success
    1   error, sent to client
unknown's avatar
unknown committed
1375
*/
unknown's avatar
unknown committed
1376
static int send_prepare_results(Prepared_statement *stmt, bool text_protocol)
unknown's avatar
unknown committed
1377
{   
1378
  THD *thd= stmt->thd;
1379
  LEX *lex= stmt->lex;
1380 1381
  SELECT_LEX *select_lex= &lex->select_lex;
  TABLE_LIST *tables=(TABLE_LIST*) select_lex->table_list.first;
1382
  enum enum_sql_command sql_command= lex->sql_command;
unknown's avatar
unknown committed
1383 1384 1385
  int res= 0;
  DBUG_ENTER("send_prepare_results");

1386
  DBUG_PRINT("enter",("command: %d, param_count: %ld",
1387
                      sql_command, stmt->param_count));
1388

1389 1390
  if ((&lex->select_lex != lex->all_selects_list ||
       lex->time_zone_tables_used) &&
1391 1392 1393
      lex->unit.create_total_list(thd, lex, &tables))
    DBUG_RETURN(1);

unknown's avatar
unknown committed
1394
  
1395
  switch (sql_command) {
1396
  case SQLCOM_REPLACE:
unknown's avatar
unknown committed
1397
  case SQLCOM_INSERT:
unknown's avatar
unknown committed
1398 1399 1400
    res= mysql_test_insert(stmt, tables, lex->field_list,
			   lex->many_values,
			   select_lex->item_list, lex->value_list,
1401
			   lex->duplicates);
unknown's avatar
unknown committed
1402 1403 1404
    break;

  case SQLCOM_UPDATE:
unknown's avatar
unknown committed
1405 1406 1407
    res= mysql_test_update(stmt, tables);
    break;

unknown's avatar
unknown committed
1408
  case SQLCOM_DELETE:
unknown's avatar
unknown committed
1409
    res= mysql_test_delete(stmt, tables);
unknown's avatar
unknown committed
1410 1411 1412
    break;

  case SQLCOM_SELECT:
unknown's avatar
unknown committed
1413
    if ((res= mysql_test_select(stmt, tables, text_protocol)))
1414 1415 1416
      goto error;
    /* Statement and field info has already been sent */
    DBUG_RETURN(0);
unknown's avatar
unknown committed
1417

1418
  case SQLCOM_CREATE_TABLE:
unknown's avatar
unknown committed
1419
    res= mysql_test_create_table(stmt, tables);
1420 1421 1422
    break;
  
  case SQLCOM_DO:
unknown's avatar
unknown committed
1423 1424
    res= mysql_test_do_fields(stmt, tables, lex->insert_list);
    break;
1425 1426

  case SQLCOM_SET_OPTION:
unknown's avatar
unknown committed
1427
    res= mysql_test_set_fields(stmt, tables, &lex->var_list);
1428 1429 1430
    break;

  case SQLCOM_DELETE_MULTI:
unknown's avatar
unknown committed
1431
    res= mysql_test_multidelete(stmt, tables);
1432 1433 1434
    break;
  
  case SQLCOM_UPDATE_MULTI:
unknown's avatar
unknown committed
1435
    res= mysql_test_multiupdate(stmt, tables);
1436 1437 1438
    break;

  case SQLCOM_INSERT_SELECT:
unknown's avatar
unknown committed
1439
    res= mysql_test_insert_select(stmt, tables);
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    break;

  case SQLCOM_SHOW_DATABASES:
  case SQLCOM_SHOW_PROCESSLIST:
  case SQLCOM_SHOW_STORAGE_ENGINES:
  case SQLCOM_SHOW_PRIVILEGES:
  case SQLCOM_SHOW_COLUMN_TYPES:
  case SQLCOM_SHOW_STATUS:
  case SQLCOM_SHOW_VARIABLES:
  case SQLCOM_SHOW_LOGS:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_OPEN_TABLES:
  case SQLCOM_SHOW_CHARSETS:
  case SQLCOM_SHOW_COLLATIONS:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_SHOW_KEYS:
  case SQLCOM_SHOW_CREATE_DB:
  case SQLCOM_SHOW_GRANTS:
  case SQLCOM_DROP_TABLE:
  case SQLCOM_RENAME_TABLE:
    break;

unknown's avatar
unknown committed
1462
  default:
1463 1464
    /*
      All other is not supported yet
1465
    */
1466 1467 1468
    res= -1;
    my_error(ER_UNSUPPORTED_PS, MYF(0));
    goto error;
unknown's avatar
unknown committed
1469
  }
unknown's avatar
unknown committed
1470
  if (res == 0)
1471
    DBUG_RETURN(text_protocol? 0 : send_prep_stmt(stmt, 0));
1472 1473 1474
error:
  if (res < 0)
    send_error(thd, thd->killed ? ER_SERVER_SHUTDOWN : 0);
1475
  DBUG_RETURN(1);
unknown's avatar
unknown committed
1476 1477
}

unknown's avatar
unknown committed
1478
/*
1479 1480
  Initialize array of parameters in statement from LEX.
  (We need to have quick access to items by number in mysql_stmt_get_longdata).
1481
  This is to avoid using malloc/realloc in the parser.
unknown's avatar
unknown committed
1482
*/
unknown's avatar
unknown committed
1483

1484
static bool init_param_array(Prepared_statement *stmt)
unknown's avatar
unknown committed
1485
{
1486
  LEX *lex= stmt->lex;
1487
  THD *thd= stmt->thd;
1488 1489
  if ((stmt->param_count= lex->param_list.elements))
  {
1490 1491 1492 1493 1494 1495 1496
    if (stmt->param_count > (uint) UINT_MAX16)
    {
      /* Error code to be defined in 5.0 */
      send_error(thd, ER_UNKNOWN_ERROR,
                 "Prepared statement contains too many placeholders.");
      return 1;
    }
1497 1498 1499 1500 1501 1502 1503 1504
    Item_param **to;
    List_iterator<Item_param> param_iterator(lex->param_list);
    /* Use thd->mem_root as it points at statement mem_root */
    stmt->param_array= (Item_param **)
                       alloc_root(&stmt->thd->mem_root,
                                  sizeof(Item_param*) * stmt->param_count);
    if (!stmt->param_array)
    {
1505
      send_error(thd, ER_OUT_OF_RESOURCES);
1506
      return 1;
1507 1508 1509 1510 1511 1512 1513 1514
    }
    for (to= stmt->param_array;
         to < stmt->param_array + stmt->param_count;
         ++to)
    {
      *to= param_iterator++;
    }
  }
unknown's avatar
unknown committed
1515
  return 0;
unknown's avatar
unknown committed
1516
}
1517

1518

unknown's avatar
unknown committed
1519
/*
1520 1521 1522
  Given a query string with parameter markers, create a Prepared Statement
  from it and send PS info back to the client.
  
1523 1524
  SYNOPSIS
    mysql_stmt_prepare()
1525 1526 1527
      packet         query to be prepared 
      packet_length  query string length, including ignored trailing NULL or 
                     quote char.
1528
      name           NULL or statement name. For unnamed statements binary PS
1529
                     protocol is used, for named statements text protocol is 
1530
                     used.
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
  RETURN 
    0      OK, statement prepared successfully
    other  Error
  
  NOTES
    This function parses the query and sends the total number of parameters 
    and resultset metadata information back to client (if any), without 
    executing the query i.e. without any log/disk writes. This allows the 
    queries to be re-executed without re-parsing during execute. 

    If parameter markers are found in the query, then store the information
    using Item_param along with maintaining a list in lex->param_array, so 
    that a fast and direct retrieval can be made without going through all 
    field items.
1545
   
unknown's avatar
unknown committed
1546 1547
*/

1548 1549
int mysql_stmt_prepare(THD *thd, char *packet, uint packet_length,
                       LEX_STRING *name)
unknown's avatar
unknown committed
1550
{
1551 1552
  LEX *lex;
  Prepared_statement *stmt= new Prepared_statement(thd);
1553
  int error;
1554
  DBUG_ENTER("mysql_stmt_prepare");
unknown's avatar
unknown committed
1555

unknown's avatar
unknown committed
1556
  DBUG_PRINT("prep_query", ("%s", packet));
unknown's avatar
unknown committed
1557

1558
  if (stmt == 0)
1559 1560
  {
    send_error(thd, ER_OUT_OF_RESOURCES);
1561 1562 1563 1564 1565 1566
    DBUG_RETURN(1);
  }

  if (name)
  {
    stmt->name.length= name->length;
1567
    if (!(stmt->name.str= memdup_root(&stmt->mem_root, (char*)name->str,
1568
                                      name->length)))
1569 1570 1571 1572 1573
    {
      delete stmt;
      send_error(thd, ER_OUT_OF_RESOURCES);
      DBUG_RETURN(1);
    }
1574
  }
1575 1576

  if (thd->stmt_map.insert(stmt))
1577 1578 1579
  {
    delete stmt;
    send_error(thd, ER_OUT_OF_RESOURCES);
1580
    DBUG_RETURN(1);
1581
  }
1582

1583 1584
  thd->set_n_backup_statement(stmt, &thd->stmt_backup);
  thd->set_n_backup_item_arena(stmt, &thd->stmt_backup);
unknown's avatar
unknown committed
1585

1586
  if (alloc_query(thd, packet, packet_length))
1587
  {
1588 1589
    thd->restore_backup_statement(stmt, &thd->stmt_backup);
    thd->restore_backup_item_arena(stmt, &thd->stmt_backup);
1590 1591 1592
    /* Statement map deletes statement on erase */
    thd->stmt_map.erase(stmt);
    send_error(thd, ER_OUT_OF_RESOURCES);
1593
    DBUG_RETURN(1);
1594
  }
1595

1596
  mysql_log.write(thd, COM_PREPARE, "%s", packet);
1597

1598
  thd->current_arena= stmt;
unknown's avatar
unknown committed
1599 1600
  mysql_init_query(thd, (uchar *) thd->query, thd->query_length);
  lex= thd->lex;
1601 1602
  lex->safe_to_cache_query= 0;

1603
  error= yyparse((void *)thd) || thd->is_fatal_error ||
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
         init_param_array(stmt);
  /*
    While doing context analysis of the query (in send_prepare_results) we
    allocate a lot of additional memory: for open tables, JOINs, derived
    tables, etc.  Let's save a snapshot of current parse tree to the
    statement and restore original THD. In cases when some tree
    transformation can be reused on execute, we set again thd->mem_root from
    stmt->mem_root (see setup_wild for one place where we do that).
  */
  thd->restore_backup_item_arena(stmt, &thd->stmt_backup);

  if (!error)
    error= send_prepare_results(stmt, test(name));
unknown's avatar
unknown committed
1617

1618
  /* restore to WAIT_PRIOR: QUERY_PRIOR is set inside alloc_query */
unknown's avatar
unknown committed
1619
  if (!(specialflag & SPECIAL_NO_PRIOR))
unknown's avatar
unknown committed
1620
    my_pthread_setprio(pthread_self(),WAIT_PRIOR);
1621
  lex_end(lex);
1622 1623 1624 1625
  thd->restore_backup_statement(stmt, &thd->stmt_backup);
  cleanup_items(stmt->free_list);
  close_thread_tables(thd);
  free_items(thd->free_list);
1626
  thd->rollback_item_tree_changes();
1627 1628
  thd->free_list= 0;
  thd->current_arena= thd;
unknown's avatar
unknown committed
1629

1630
  if (error)
1631
  {
1632 1633
    /* Statement map deletes statement on erase */
    thd->stmt_map.erase(stmt);
unknown's avatar
unknown committed
1634
    stmt= NULL;
1635
    /* error is sent inside yyparse/send_prepare_results */
1636
  }
1637 1638
  else
  {
1639
    stmt->setup_set_params();
1640 1641 1642 1643 1644 1645 1646 1647 1648
    SELECT_LEX *sl= stmt->lex->all_selects_list;
    /*
      Save WHERE clause pointers, because they may be changed during query
      optimisation.
    */
    for (; sl; sl= sl->next_select_in_list())
    {
      sl->prep_where= sl->where;
    }
unknown's avatar
unknown committed
1649
    stmt->state= Item_arena::PREPARED;
1650
  }
1651

1652
  DBUG_RETURN(!stmt);
1653
}
1654

1655
/* Reinit statement before execution */
1656

1657 1658 1659
static void reset_stmt_for_execute(Prepared_statement *stmt)
{
  THD *thd= stmt->thd;
1660 1661
  LEX *lex= stmt->lex;
  SELECT_LEX *sl= lex->all_selects_list;
1662

1663
  for (; sl; sl= sl->next_select_in_list())
1664
  {
1665 1666
    /* remove option which was put by mysql_explain_union() */
    sl->options&= ~SELECT_DESCRIBE;
unknown's avatar
unknown committed
1667 1668 1669
    /*
      Copy WHERE clause pointers to avoid damaging they by optimisation
    */
1670
    if (sl->prep_where)
1671
    {
1672
      sl->where= sl->prep_where->copy_andor_structure(thd);
1673 1674
      sl->where->cleanup();
    }
1675
    DBUG_ASSERT(sl->join == 0);
unknown's avatar
unknown committed
1676
    ORDER *order;
unknown's avatar
unknown committed
1677
    /* Fix GROUP list */
unknown's avatar
unknown committed
1678 1679
    for (order= (ORDER *)sl->group_list.first; order; order= order->next)
      order->item= &order->item_ptr;
unknown's avatar
unknown committed
1680
    /* Fix ORDER list */
unknown's avatar
unknown committed
1681 1682
    for (order= (ORDER *)sl->order_list.first; order; order= order->next)
      order->item= &order->item_ptr;
unknown's avatar
unknown committed
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

    /*
      TODO: When the new table structure is ready, then have a status bit 
      to indicate the table is altered, and re-do the setup_* 
      and open the tables back.
    */
    for (TABLE_LIST *tables= (TABLE_LIST*) sl->table_list.first;
	 tables;
	 tables= tables->next)
    {
unknown's avatar
unknown committed
1693 1694 1695 1696 1697
      /*
        Reset old pointers to TABLEs: they are not valid since the tables
        were closed in the end of previous prepare or execute call.
      */
      tables->table= 0;
unknown's avatar
unknown committed
1698 1699
      tables->table_list= 0;
    }
1700 1701 1702 1703 1704
    
    {
      SELECT_LEX_UNIT *unit= sl->master_unit();
      unit->unclean();
      unit->types.empty();
1705
      /* for derived tables & PS (which can't be reset by Item_subquery) */
1706 1707
      unit->reinit_exec_mechanism();
    }
1708
  }
1709 1710 1711
  lex->current_select= &lex->select_lex;
  if (lex->result)
    lex->result->cleanup();
1712 1713
}

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

/* 
    Clears parameters from data left from previous execution or long data
    
  SYNOPSIS
    reset_stmt_params()
      stmt - prepared statement for which parameters should be reset
*/

static void reset_stmt_params(Prepared_statement *stmt)
{
  Item_param **item= stmt->param_array;
  Item_param **end= item + stmt->param_count;
  for (;item < end ; ++item)
    (**item).reset();
}


1732 1733 1734 1735
/*
  Executes previously prepared query.
  If there is any parameters, then replace markers with the data supplied
  from client, and then execute the query.
1736
  SYNOPSIS
1737
    mysql_stmt_execute()
1738 1739 1740
      thd            Current thread
      packet         Query string
      packet_length  Query string length, including terminator character.
1741 1742
*/

1743
void mysql_stmt_execute(THD *thd, char *packet, uint packet_length)
1744 1745
{
  ulong stmt_id= uint4korr(packet);
1746 1747 1748 1749 1750
  /*
    Query text for binary log, or empty string if the query is not put into
    binary log.
  */
  String expanded_query;
unknown's avatar
unknown committed
1751
#ifndef EMBEDDED_LIBRARY
1752
  uchar *packet_end= (uchar *) packet + packet_length - 1;
unknown's avatar
unknown committed
1753
#endif
1754 1755
  Prepared_statement *stmt;
  DBUG_ENTER("mysql_stmt_execute");
1756 1757

  packet+= 9;                               /* stmt_id + 5 bytes of flags */
1758

1759 1760
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_execute",
                                      SEND_ERROR)))
1761 1762
    DBUG_VOID_RETURN;

unknown's avatar
unknown committed
1763
  DBUG_PRINT("exec_query:", ("%s", stmt->query));
unknown's avatar
unknown committed
1764

1765
  /* Check if we got an error when sending long data */
unknown's avatar
unknown committed
1766
  if (stmt->state == Item_arena::ERROR)
1767 1768 1769 1770 1771
  {
    send_error(thd, stmt->last_errno, stmt->last_error);
    DBUG_VOID_RETURN;
  }

1772 1773
  DBUG_ASSERT(thd->free_list == NULL);
  mysql_reset_thd_for_next_command(thd);
unknown's avatar
unknown committed
1774
#ifndef EMBEDDED_LIBRARY
1775 1776 1777
  if (stmt->param_count)
  {
    uchar *null_array= (uchar *) packet;
1778
    if (setup_conversion_functions(stmt, (uchar **) &packet, packet_end) ||
1779
        stmt->set_params(stmt, null_array, (uchar *) packet, packet_end,
1780
                         &expanded_query))
1781 1782
      goto set_params_data_err;
  }
unknown's avatar
unknown committed
1783
#else
1784 1785 1786 1787 1788
  /*
    In embedded library we re-install conversion routines each time 
    we set params, and also we don't need to parse packet. 
    So we do it in one function.
  */
1789
  if (stmt->param_count && stmt->set_params_data(stmt, &expanded_query))
1790
    goto set_params_data_err;
unknown's avatar
unknown committed
1791
#endif
1792
  thd->protocol= &thd->protocol_prep;           // Switch to binary protocol
unknown's avatar
unknown committed
1793
  execute_stmt(thd, stmt, &expanded_query, TRUE);
1794 1795
  thd->protocol= &thd->protocol_simple;         // Use normal protocol
  DBUG_VOID_RETURN;
1796

1797
set_params_data_err:
1798
  reset_stmt_params(stmt);
1799
  my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_execute");
1800
  send_error(thd);
unknown's avatar
unknown committed
1801 1802 1803
  DBUG_VOID_RETURN;
}

1804

unknown's avatar
unknown committed
1805
/*
1806
  Execute prepared statement using parameter values from
unknown's avatar
unknown committed
1807 1808 1809
  lex->prepared_stmt_params and send result to the client using text protocol.
*/

1810
void mysql_sql_stmt_execute(THD *thd, LEX_STRING *stmt_name)
unknown's avatar
unknown committed
1811
{
1812
  Prepared_statement *stmt;
1813
  /*
1814 1815
    Query text for binary log, or empty string if the query is not put into
    binary log.
1816
  */
1817
  String expanded_query;
1818
  DBUG_ENTER("mysql_sql_stmt_execute");
1819

1820 1821
  if (!(stmt= (Prepared_statement*)thd->stmt_map.find_by_name(stmt_name)))
  {
1822 1823 1824 1825
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), stmt_name->length,
             stmt_name->str, "EXECUTE");
    send_error(thd);
    DBUG_VOID_RETURN;
1826 1827
  }

unknown's avatar
unknown committed
1828 1829
  if (stmt->param_count != thd->lex->prepared_stmt_params.elements)
  {
1830
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
unknown's avatar
unknown committed
1831 1832 1833 1834
    send_error(thd);
    DBUG_VOID_RETURN;
  }

1835
  DBUG_ASSERT(thd->free_list == NULL);
1836 1837
  /* Must go before setting variables, as it clears thd->user_var_events */
  mysql_reset_thd_for_next_command(thd);
1838
  thd->set_n_backup_statement(stmt, &thd->stmt_backup);
1839 1840
  if (stmt->set_params_from_vars(stmt,
                                 thd->stmt_backup.lex->prepared_stmt_params,
1841
                                 &expanded_query))
unknown's avatar
unknown committed
1842
  {
1843
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
unknown's avatar
unknown committed
1844 1845
    send_error(thd);
  }
unknown's avatar
unknown committed
1846
  execute_stmt(thd, stmt, &expanded_query, FALSE);
1847 1848 1849
  DBUG_VOID_RETURN;
}

1850

1851 1852
/*
  Execute prepared statement.
1853 1854 1855 1856
  SYNOPSIS
    execute_stmt()
      thd            Current thread
      stmt           Statement to execute
1857
      expanded_query If binary log is enabled, query string with parameter
1858 1859 1860
                     placeholders replaced with actual values. Otherwise empty
                     string.
  NOTES
1861
  Caller must set parameter values and thd::protocol.
unknown's avatar
unknown committed
1862
  thd->free_list is assumed to be garbage.
1863
*/
1864

1865
static void execute_stmt(THD *thd, Prepared_statement *stmt,
1866
                         String *expanded_query, bool set_context)
1867 1868
{
  DBUG_ENTER("execute_stmt");
1869
  if (set_context)
1870
    thd->set_n_backup_statement(stmt, &thd->stmt_backup);
1871
  reset_stmt_for_execute(stmt);
1872 1873 1874

  if (expanded_query->length() &&
      alloc_query(thd, (char *)expanded_query->ptr(),
1875 1876 1877 1878 1879
                  expanded_query->length()+1))
  {
    my_error(ER_OUTOFMEMORY, 0, expanded_query->length());
    DBUG_VOID_RETURN;
  }
1880 1881 1882 1883 1884
  /*
    At first execution of prepared statement we will perform logical
    transformations of the query tree (i.e. negations elimination).
    This should be done permanently on the parse tree of this statement.
  */
1885
  thd->current_arena= stmt;
1886

unknown's avatar
unknown committed
1887
  if (!(specialflag & SPECIAL_NO_PRIOR))
1888
    my_pthread_setprio(pthread_self(),QUERY_PRIOR);
1889
  mysql_execute_command(thd);
1890
  thd->lex->unit.cleanup();
unknown's avatar
unknown committed
1891
  if (!(specialflag & SPECIAL_NO_PRIOR))
1892
    my_pthread_setprio(pthread_self(), WAIT_PRIOR);
unknown's avatar
unknown committed
1893

1894 1895
  /* Free Items that were created during this execution of the PS. */
  free_items(thd->free_list);
1896
  thd->free_list= 0;
unknown's avatar
unknown committed
1897 1898
  if (stmt->state == Item_arena::PREPARED)
    stmt->state= Item_arena::EXECUTED;
1899
  thd->current_arena= thd;
unknown's avatar
unknown committed
1900
  cleanup_items(stmt->free_list);
1901
  thd->rollback_item_tree_changes();
1902
  reset_stmt_params(stmt);
1903
  close_thread_tables(thd);                    // to close derived tables
1904
  thd->set_statement(&thd->stmt_backup);
unknown's avatar
unknown committed
1905 1906 1907
  DBUG_VOID_RETURN;
}

1908

unknown's avatar
unknown committed
1909
/*
1910
  Reset a prepared statement in case there was a recoverable error.
1911 1912
  SYNOPSIS
    mysql_stmt_reset()
1913 1914
      thd       Thread handle
      packet	Packet with stmt id 
1915 1916

  DESCRIPTION
1917 1918 1919 1920 1921 1922 1923
    This function resets statement to the state it was right after prepare.
    It can be used to:
     - clear an error happened during mysql_stmt_send_long_data
     - cancel long data stream for all placeholders without
       having to call mysql_stmt_execute.
    Sends 'OK' packet in case of success (statement was reset)
    or 'ERROR' packet (unrecoverable error/statement not found/etc).
unknown's avatar
unknown committed
1924 1925
*/

1926
void mysql_stmt_reset(THD *thd, char *packet)
unknown's avatar
unknown committed
1927
{
1928
  /* There is always space for 4 bytes in buffer */
1929
  ulong stmt_id= uint4korr(packet);
1930 1931
  Prepared_statement *stmt;
  
1932
  DBUG_ENTER("mysql_stmt_reset");
unknown's avatar
unknown committed
1933

1934 1935
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_reset",
                                      SEND_ERROR)))
1936 1937
    DBUG_VOID_RETURN;

unknown's avatar
unknown committed
1938
  stmt->state= Item_arena::PREPARED;
1939

1940 1941 1942 1943 1944
  /* 
    Clear parameters from data which could be set by 
    mysql_stmt_send_long_data() call.
  */
  reset_stmt_params(stmt);
1945

1946
  mysql_reset_thd_for_next_command(thd);
1947
  send_ok(thd);
1948
  
1949 1950 1951 1952 1953
  DBUG_VOID_RETURN;
}


/*
1954 1955
  Delete a prepared statement from memory.
  Note: we don't send any reply to that command. 
1956 1957
*/

unknown's avatar
unknown committed
1958
void mysql_stmt_free(THD *thd, char *packet)
1959
{
1960
  /* There is always space for 4 bytes in packet buffer */
1961
  ulong stmt_id= uint4korr(packet);
1962 1963
  Prepared_statement *stmt;

unknown's avatar
unknown committed
1964
  DBUG_ENTER("mysql_stmt_free");
1965

1966 1967
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_close",
                                      DONT_SEND_ERROR)))
1968
    DBUG_VOID_RETURN;
1969 1970 1971

  /* Statement map deletes statement on erase */
  thd->stmt_map.erase(stmt);
unknown's avatar
unknown committed
1972 1973 1974
  DBUG_VOID_RETURN;
}

1975 1976

/*
1977
  Long data in pieces from client
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994

  SYNOPSIS
    mysql_stmt_get_longdata()
    thd			Thread handle
    pos			String to append
    packet_length	Length of string

  DESCRIPTION
    Get a part of a long data.
    To make the protocol efficient, we are not sending any return packages
    here.
    If something goes wrong, then we will send the error on 'execute'

    We assume that the client takes care of checking that all parts are sent
    to the server. (No checking that we get a 'end of column' in the server)
*/

1995
void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
1996
{
1997 1998
  ulong stmt_id;
  uint param_number;
1999
  Prepared_statement *stmt;
2000 2001
  Item_param *param;
  char *packet_end= packet + packet_length - 1;
2002
  
2003 2004
  DBUG_ENTER("mysql_stmt_get_longdata");

unknown's avatar
unknown committed
2005
#ifndef EMBEDDED_LIBRARY
2006 2007
  /* Minimal size of long data packet is 6 bytes */
  if ((ulong) (packet_end - packet) < MYSQL_LONG_DATA_HEADER)
2008
  {
2009
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_send_long_data");
2010 2011
    DBUG_VOID_RETURN;
  }
unknown's avatar
unknown committed
2012
#endif
2013

2014 2015
  stmt_id= uint4korr(packet);
  packet+= 4;
2016

2017
  if (!(stmt=find_prepared_statement(thd, stmt_id, "mysql_stmt_send_long_data",
2018
                                     DONT_SEND_ERROR)))
2019 2020
    DBUG_VOID_RETURN;

2021 2022
  param_number= uint2korr(packet);
  packet+= 2;
unknown's avatar
unknown committed
2023
#ifndef EMBEDDED_LIBRARY
2024 2025
  if (param_number >= stmt->param_count)
  {
unknown's avatar
unknown committed
2026
    /* Error will be sent in execute call */
unknown's avatar
unknown committed
2027
    stmt->state= Item_arena::ERROR;
unknown's avatar
unknown committed
2028
    stmt->last_errno= ER_WRONG_ARGUMENTS;
2029 2030
    sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS),
            "mysql_stmt_send_long_data");
2031 2032
    DBUG_VOID_RETURN;
  }
unknown's avatar
unknown committed
2033 2034
#endif

2035 2036
  param= stmt->param_array[param_number];

unknown's avatar
unknown committed
2037
#ifndef EMBEDDED_LIBRARY
2038
  if (param->set_longdata(packet, (ulong) (packet_end - packet)))
unknown's avatar
unknown committed
2039
#else
2040
  if (param->set_longdata(thd->extra_data, thd->extra_length))
unknown's avatar
unknown committed
2041
#endif
2042
  {
unknown's avatar
unknown committed
2043
    stmt->state= Item_arena::ERROR;
2044 2045 2046
    stmt->last_errno= ER_OUTOFMEMORY;
    sprintf(stmt->last_error, ER(ER_OUTOFMEMORY), 0);
  }
2047 2048
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
2049

2050 2051 2052 2053

Prepared_statement::Prepared_statement(THD *thd_arg)
  :Statement(thd_arg),
  thd(thd_arg),
2054
  param_array(0),
2055
  param_count(0),
2056
  last_errno(0)
2057 2058 2059 2060
{
  *last_error= '\0';
}

2061 2062 2063 2064
void Prepared_statement::setup_set_params()
{
  /* Setup binary logging */
  if (mysql_bin_log.is_open() && is_update_query(lex->sql_command))
2065
  {
2066
    set_params_from_vars= insert_params_from_vars_with_log;
2067
#ifndef EMBEDDED_LIBRARY
2068
    set_params= insert_params_withlog;
2069
#else
2070
    set_params_data= emb_insert_params_withlog;
2071 2072 2073
#endif
  }
  else
2074 2075
  {
    set_params_from_vars= insert_params_from_vars;
2076
#ifndef EMBEDDED_LIBRARY
2077
    set_params= insert_params;
2078
#else
2079
    set_params_data= emb_insert_params;
2080
#endif
2081
  }
2082 2083 2084 2085 2086
}

Prepared_statement::~Prepared_statement()
{
  free_items(free_list);
2087
  delete lex->result;
2088 2089 2090
}


2091
Item_arena::Type Prepared_statement::type() const
2092 2093 2094 2095
{
  return PREPARED_STATEMENT;
}