sql_prepare.cc 54.4 KB
Newer Older
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 */
16 17 18 19 20 21

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

Prepare:

22 23 24
  - Server gets the query from client with command 'COM_PREPARE'; 
    in the following format:
    [COM_PREPARE:1] [query]
25
  - Parse the query and recognize any parameter markers '?' and 
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.
29 30
  - Without executing the query, return back to client the total 
    number of parameters along with result-set metadata information
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)
37 38 39 40
     
Prepare-execute:

  - Server gets the command 'COM_EXECUTE' to execute the 
venu@myvenu.com's avatar
venu@myvenu.com committed
41
    previously prepared query. If there is any param markers; then client
42
    will send the data in the following format:
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)
venu@myvenu.com's avatar
venu@myvenu.com 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.
53 54 55 56
  - Execute the query without re-parsing and send back the results 
    to client

Long data handling:
57

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
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

68 69 70 71
***********************************************************************/

#include "mysql_priv.h"
#include "sql_acl.h"
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
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);
hf@deer.(none)'s avatar
hf@deer.(none) committed
94
#else
95
  bool (*set_params_data)(Prepared_statement *st, String *expanded_query);
hf@deer.(none)'s avatar
hf@deer.(none) committed
96
#endif
sergefp@mysql.com's avatar
sergefp@mysql.com 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
};
hf@deer.(none)'s avatar
hf@deer.(none) 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);

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
*/

hf@deer.(none)'s avatar
hf@deer.(none) 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;
hf@deer.(none)'s avatar
hf@deer.(none) committed
170
}
171
#else
172 173
static bool send_prep_stmt(Prepared_statement *stmt,
                           uint columns __attribute__((unused)))
hf@deer.(none)'s avatar
hf@deer.(none) committed
174
{
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
175 176
  THD *thd= stmt->thd;

177
  thd->client_stmt_id= stmt->id;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
178
  thd->client_param_count= stmt->param_count;
hf@deer.(none)'s avatar
hf@deer.(none) committed
179
  thd->net.last_errno= 0;
hf@deer.(none)'s avatar
hf@deer.(none) committed
180

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
181
  return 0;
182
}
183
#endif /*!EMBEDDED_LIBRARY*/
184

185 186

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

hf@deer.(none)'s avatar
hf@deer.(none) committed
191
#ifndef EMBEDDED_LIBRARY
192
static ulong get_param_length(uchar **packet, ulong len)
193 194
{
  reg1 uchar *pos= *packet;
195 196
  if (len < 1)
    return 0;
197 198 199 200 201
  if (*pos < 251)
  {
    (*packet)++;
    return (ulong) *pos;
  }
202 203
  if (len < 3)
    return 0;
204 205 206 207 208
  if (*pos == 252)
  {
    (*packet)+=3;
    return (ulong) uint2korr(pos+1);
  }
209 210
  if (len < 4)
    return 0;
211 212 213 214 215
  if (*pos == 253)
  {
    (*packet)+=4;
    return (ulong) uint3korr(pos+1);
  }
216 217
  if (len < 5)
    return 0;
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.
  */
226 227
  return (ulong) uint4korr(pos+1);
}
hf@deer.(none)'s avatar
hf@deer.(none) committed
228
#else
229
#define get_param_length(packet, len) len
hf@deer.(none)'s avatar
hf@deer.(none) committed
230 231
#endif /*!EMBEDDED_LIBRARY*/

venu@myvenu.com's avatar
venu@myvenu.com 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
venu@myvenu.com's avatar
venu@myvenu.com 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.
venu@myvenu.com's avatar
venu@myvenu.com 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
249 250
*/

251
static void set_param_tiny(Item_param *param, uchar **pos, ulong len)
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);
venu@myvenu.com's avatar
venu@myvenu.com committed
260 261 262
  *pos+= 1;
}

263
static void set_param_short(Item_param *param, uchar **pos, ulong len)
venu@myvenu.com's avatar
venu@myvenu.com 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);
venu@myvenu.com's avatar
venu@myvenu.com committed
275 276 277
  *pos+= 2;
}

278
static void set_param_int32(Item_param *param, uchar **pos, ulong len)
venu@myvenu.com's avatar
venu@myvenu.com 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);
venu@myvenu.com's avatar
venu@myvenu.com committed
290 291 292
  *pos+= 4;
}

293
static void set_param_int64(Item_param *param, uchar **pos, ulong len)
venu@myvenu.com's avatar
venu@myvenu.com 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;
venu@myvenu.com's avatar
venu@myvenu.com committed
305 306
}

307
static void set_param_float(Item_param *param, uchar **pos, ulong len)
venu@myvenu.com's avatar
venu@myvenu.com committed
308
{
309 310 311 312
#ifndef EMBEDDED_LIBRARY
  if (len < 4)
    return;
#endif
venu@myvenu.com's avatar
venu@myvenu.com 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)
venu@myvenu.com's avatar
venu@myvenu.com committed
320
{
321 322 323 324
#ifndef EMBEDDED_LIBRARY
  if (len < 8)
    return;
#endif
venu@myvenu.com's avatar
venu@myvenu.com committed
325 326 327 328 329 330
  double data;
  float8get(data,*pos);
  param->set_double((double) data);
  *pos+= 8;
}

331
#ifndef EMBEDDED_LIBRARY
332
static void set_param_time(Item_param *param, uchar **pos, ulong len)
333 334
{
  ulong length;
335
  uint day;
336

337
  if ((length= get_param_length(pos, len)) >= 8)
338 339
  {
    uchar *to= *pos;
340
    TIME  tm;
341

342 343
    tm.neg= (bool) to[0];
    day= (uint) sint4korr(to+1);
344 345 346 347 348 349 350
    /*
      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;
351 352
    tm.minute= (uint) to[6];
    tm.second= (uint) to[7];
353
    tm.second_part= (length > 8) ? (ulong) sint4korr(to+8) : 0;
354 355 356 357 358 359 360 361
    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;
362

363
    param->set_time(&tm, MYSQL_TIMESTAMP_TIME,
364
                    MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
365 366 367 368
  }
  *pos+= length;
}

369
static void set_param_datetime(Item_param *param, uchar **pos, ulong len)
370
{
371
  uint length;
372

373
  if ((length= get_param_length(pos, len)) >= 4)
374 375 376
  {
    uchar *to= *pos;
    TIME  tm;
377 378 379 380 381

    tm.neg=    0;
    tm.year=   (uint) sint2korr(to);
    tm.month=  (uint) to[2];
    tm.day=    (uint) to[3];
382 383 384 385 386
    /*
      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.
    */
387 388 389 390 391 392 393 394
    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;
395 396

    tm.second_part= (length > 7) ? (ulong) sint4korr(to+7) : 0;
397

398
    param->set_time(&tm, MYSQL_TIMESTAMP_DATETIME, 
399
                    MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
400 401 402 403
  }
  *pos+= length;
}

404
static void set_param_date(Item_param *param, uchar **pos, ulong len)
405 406 407
{
  ulong length;
 
408
  if ((length= get_param_length(pos, len)) >= 4)
409 410 411
  {
    uchar *to= *pos;
    TIME tm;
412 413 414 415 416
    /*
      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.
    */
417
    tm.year=  (uint) sint2korr(to);
418 419 420 421 422 423 424
    tm.month=  (uint) to[2];
    tm.day= (uint) to[3];

    tm.hour= tm.minute= tm.second= 0;
    tm.second_part= 0;
    tm.neg= 0;

425
    param->set_time(&tm, MYSQL_TIMESTAMP_DATE,
426
                    MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
427 428 429 430
  }
  *pos+= length;
}

431 432 433 434
#else/*!EMBEDDED_LIBRARY*/
void set_param_time(Item_param *param, uchar **pos, ulong len)
{
  MYSQL_TIME *to= (MYSQL_TIME*)*pos;
435
  param->set_time(to, MYSQL_TIMESTAMP_TIME,
436
                  MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
437 438 439 440 441 442 443

}

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

444
  param->set_time(to, MYSQL_TIMESTAMP_DATETIME,
445
                  MAX_DATETIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
446 447 448 449 450
}

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

  param->set_time(to, MYSQL_TIMESTAMP_DATE,
453
                  MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN);
454 455 456
}
#endif /*!EMBEDDED_LIBRARY*/

457 458

static void set_param_str(Item_param *param, uchar **pos, ulong len)
venu@myvenu.com's avatar
venu@myvenu.com committed
459
{
460
  ulong length= get_param_length(pos, len);
461
  param->set_str((const char *)*pos, length);
462
  *pos+= length;
venu@myvenu.com's avatar
venu@myvenu.com committed
463 464
}

465 466 467 468 469

#undef get_param_length 

static void setup_one_conversion_function(THD *thd, Item_param *param,
                                          uchar param_type)
venu@myvenu.com's avatar
venu@myvenu.com committed
470
{
471
  switch (param_type) {
472
  case MYSQL_TYPE_TINY:
473
    param->set_param_func= set_param_tiny;
474
    param->item_type= Item::INT_ITEM;
475
    param->item_result_type= INT_RESULT;
476
    break;
477
  case MYSQL_TYPE_SHORT:
478
    param->set_param_func= set_param_short;
479
    param->item_type= Item::INT_ITEM;
480
    param->item_result_type= INT_RESULT;
481
    break;
482
  case MYSQL_TYPE_LONG:
483
    param->set_param_func= set_param_int32;
484
    param->item_type= Item::INT_ITEM;
485
    param->item_result_type= INT_RESULT;
486
    break;
487
  case MYSQL_TYPE_LONGLONG:
488
    param->set_param_func= set_param_int64;
489
    param->item_type= Item::INT_ITEM;
490
    param->item_result_type= INT_RESULT;
491
    break;
492
  case MYSQL_TYPE_FLOAT:
493
    param->set_param_func= set_param_float;
494
    param->item_type= Item::REAL_ITEM;
495
    param->item_result_type= REAL_RESULT;
496
    break;
497
  case MYSQL_TYPE_DOUBLE:
498
    param->set_param_func= set_param_double;
499
    param->item_type= Item::REAL_ITEM;
500
    param->item_result_type= REAL_RESULT;
501
    break;
502
  case MYSQL_TYPE_TIME:
503
    param->set_param_func= set_param_time;
504
    param->item_type= Item::STRING_ITEM;
505
    param->item_result_type= STRING_RESULT;
506
    break;
507
  case MYSQL_TYPE_DATE:
508
    param->set_param_func= set_param_date;
509
    param->item_type= Item::STRING_ITEM;
510
    param->item_result_type= STRING_RESULT;
511
    break;
512 513
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
514
    param->set_param_func= set_param_datetime;
515
    param->item_type= Item::STRING_ITEM;
516
    param->item_result_type= STRING_RESULT;
517
    break;
518 519 520 521
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
522
    param->set_param_func= set_param_str;
523 524 525
    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;
526
    param->item_result_type= STRING_RESULT;
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    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;
    }
557
  }
558
  param->param_type= (enum enum_field_types) param_type;
559 560
}

hf@deer.(none)'s avatar
hf@deer.(none) committed
561
#ifndef EMBEDDED_LIBRARY
562
/*
563 564
  Update the parameter markers by reading data from client packet 
  and if binary/update log is set, generate the valid query.
565 566
*/

567
static bool insert_params_withlog(Prepared_statement *stmt, uchar *null_array,
568 569
                                  uchar *read_pos, uchar *data_end, 
                                  String *query)
570
{
571 572 573 574 575
  THD  *thd= stmt->thd;
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
  uint32 length= 0;

576
  String str; 
577 578 579
  const String *res;

  DBUG_ENTER("insert_params_withlog"); 
580

581
  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
582
    DBUG_RETURN(1);
583
  
584
  for (Item_param **it= begin; it < end; ++it)
585
  {
586
    Item_param *param= *it;
587
    if (param->state != Item_param::LONG_DATA_VALUE)
588
    {
589
      if (is_param_null(null_array, it - begin))
590
        param->set_null();
591 592
      else
      {
593 594 595
        if (read_pos >= data_end)
          DBUG_RETURN(1);
        param->set_param_func(param, &read_pos, data_end - read_pos);
596 597
      }
    }
598 599 600 601
    res= param->query_val_str(&str);
    if (param->convert_str_value(thd))
      DBUG_RETURN(1);                           /* out of memory */

602
    if (query->replace(param->pos_in_query+length, 1, *res))
603 604 605 606 607 608 609
      DBUG_RETURN(1);
    
    length+= res->length()-1;
  }
  DBUG_RETURN(0);
}

610

611
static bool insert_params(Prepared_statement *stmt, uchar *null_array,
612 613
                          uchar *read_pos, uchar *data_end, 
                          String *expanded_query)
614
{
615 616
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
617 618 619

  DBUG_ENTER("insert_params"); 

620
  for (Item_param **it= begin; it < end; ++it)
621
  {
622
    Item_param *param= *it;
623
    if (param->state != Item_param::LONG_DATA_VALUE)
624
    {
625
      if (is_param_null(null_array, it - begin))
626
        param->set_null();
627 628
      else
      {
629 630 631
        if (read_pos >= data_end)
          DBUG_RETURN(1);
        param->set_param_func(param, &read_pos, data_end - read_pos);
632 633
      }
    }
634 635
    if (param->convert_str_value(stmt->thd))
      DBUG_RETURN(1);                           /* out of memory */
636 637 638 639
  }
  DBUG_RETURN(0);
}

640

641
static bool setup_conversion_functions(Prepared_statement *stmt,
642
                                       uchar **data, uchar *data_end)
643 644 645
{
  /* skip null bits */
  uchar *read_pos= *data + (stmt->param_count+7) / 8;
646

647
  DBUG_ENTER("setup_conversion_functions");
648

venu@myvenu.com's avatar
venu@myvenu.com committed
649
  if (*read_pos++) //types supplied / first execute
650
  {
venu@myvenu.com's avatar
venu@myvenu.com committed
651 652 653 654
    /*
      First execute or types altered by the client, setup the 
      conversion routines for all parameters (one time)
    */
655 656
    Item_param **it= stmt->param_array;
    Item_param **end= it + stmt->param_count;
657
    THD *thd= stmt->thd;
658 659
    for (; it < end; ++it)
    {
660 661 662
      ushort typecode;
      const uint signed_bit= 1 << 15;

663 664
      if (read_pos >= data_end)
        DBUG_RETURN(1);
665 666

      typecode= sint2korr(read_pos);
venu@myvenu.com's avatar
venu@myvenu.com committed
667
      read_pos+= 2;
668
      (**it).unsigned_flag= test(typecode & signed_bit);
669
      setup_one_conversion_function(thd, *it, (uchar) (typecode & ~signed_bit));
670
    }
671 672
  }
  *data= read_pos;
673 674 675
  DBUG_RETURN(0);
}

676 677
#else

678
static bool emb_insert_params(Prepared_statement *stmt, String *expanded_query)
679
{
680
  THD *thd= stmt->thd;
681 682
  Item_param **it= stmt->param_array;
  Item_param **end= it + stmt->param_count;
683 684
  MYSQL_BIND *client_param= stmt->thd->client_params;

685
  DBUG_ENTER("emb_insert_params");
686

687 688 689
  for (; it < end; ++it, ++client_param)
  {
    Item_param *param= *it;
690 691
    setup_one_conversion_function(thd, param, client_param->buffer_type);
    if (param->state != Item_param::LONG_DATA_VALUE)
692 693
    {
      if (*client_param->is_null)
694
        param->set_null();
695 696
      else
      {
697
        uchar *buff= (uchar*) client_param->buffer;
hf@deer.(none)'s avatar
hf@deer.(none) committed
698
        param->unsigned_flag= client_param->is_unsigned;
699 700 701 702
        param->set_param_func(param, &buff,
                              client_param->length ? 
                              *client_param->length : 
                              client_param->buffer_length);
703 704
      }
    }
705 706
    if (param->convert_str_value(thd))
      DBUG_RETURN(1);                           /* out of memory */
707 708 709 710
  }
  DBUG_RETURN(0);
}

711

712
static bool emb_insert_params_withlog(Prepared_statement *stmt, String *query)
713
{
714
  THD *thd= stmt->thd;
715 716
  Item_param **it= stmt->param_array;
  Item_param **end= it + stmt->param_count;
717 718
  MYSQL_BIND *client_param= thd->client_params;

719
  String str;
720
  const String *res;
721
  uint32 length= 0;
722

723
  DBUG_ENTER("emb_insert_params_withlog");
724

725
  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
726 727
    DBUG_RETURN(1);
  
728 729 730
  for (; it < end; ++it, ++client_param)
  {
    Item_param *param= *it;
731 732
    setup_one_conversion_function(thd, param, client_param->buffer_type);
    if (param->state != Item_param::LONG_DATA_VALUE)
733 734
    {
      if (*client_param->is_null)
735
        param->set_null();
736 737
      else
      {
738
        uchar *buff= (uchar*)client_param->buffer;
739
	param->unsigned_flag= client_param->is_unsigned;
740 741 742 743
        param->set_param_func(param, &buff,
                              client_param->length ? 
                              *client_param->length : 
                              client_param->buffer_length);
744 745
      }
    }
746 747 748 749
    res= param->query_val_str(&str);
    if (param->convert_str_value(thd))
      DBUG_RETURN(1);                           /* out of memory */

750
    if (query->replace(param->pos_in_query+length, 1, *res))
751
      DBUG_RETURN(1);
752

753 754 755 756 757
    length+= res->length()-1;
  }
  DBUG_RETURN(0);
}

hf@deer.(none)'s avatar
hf@deer.(none) committed
758 759
#endif /*!EMBEDDED_LIBRARY*/

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
760

761
/*
sergefp@mysql.com's avatar
sergefp@mysql.com committed
762 763 764 765 766 767
  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
768
      query     Ignored
sergefp@mysql.com's avatar
sergefp@mysql.com committed
769 770
*/

771 772
static bool insert_params_from_vars(Prepared_statement *stmt,
                                    List<LEX_STRING>& varnames,
773
                                    String *query __attribute__((unused)))
sergefp@mysql.com's avatar
sergefp@mysql.com committed
774 775 776 777 778 779
{
  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);
780 781
  DBUG_ENTER("insert_params_from_vars");

sergefp@mysql.com's avatar
sergefp@mysql.com committed
782 783 784 785
  for (Item_param **it= begin; it < end; ++it)
  {
    Item_param *param= *it;
    varname= var_it++;
786 787 788 789 790 791
    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);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
792 793 794 795
  }
  DBUG_RETURN(0);
}

796

797
/*
798 799 800 801 802 803 804 805 806 807
  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
*/

sergefp@mysql.com's avatar
sergefp@mysql.com committed
808
static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
809
                                             List<LEX_STRING>& varnames,
810
                                             String *query)
sergefp@mysql.com's avatar
sergefp@mysql.com committed
811 812 813 814 815
{
  Item_param **begin= stmt->param_array;
  Item_param **end= begin + stmt->param_count;
  user_var_entry *entry;
  LEX_STRING *varname;
816
  DBUG_ENTER("insert_params_from_vars");
sergefp@mysql.com's avatar
sergefp@mysql.com committed
817 818

  List_iterator<LEX_STRING> var_it(varnames);
819
  String str;
sergefp@mysql.com's avatar
sergefp@mysql.com committed
820
  uint32 length= 0;
821
  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
822
    DBUG_RETURN(1);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
823 824 825 826 827

  for (Item_param **it= begin; it < end; ++it)
  {
    Item_param *param= *it;
    varname= var_it++;
828 829 830
    if (get_var_with_binlog(stmt->thd, *varname, &entry))
        DBUG_RETURN(1);
    DBUG_ASSERT(entry);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
831

832 833 834
    if (param->set_from_user_var(stmt->thd, entry))
      DBUG_RETURN(1);
    /* Insert @'escaped-varname' instead of parameter in the query */
835 836 837
    char *buf, *ptr;
    str.length(0);
    if (str.reserve(entry->name.length*2+3))
sergefp@mysql.com's avatar
sergefp@mysql.com committed
838
      DBUG_RETURN(1);
839 840 841 842 843

    buf= str.c_ptr_quick();
    ptr= buf;
    *ptr++= '@';
    *ptr++= '\'';
844 845
    ptr+=
      escape_string_for_mysql(&my_charset_utf8_general_ci,
846 847 848 849 850 851
                              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 */
852

853 854 855
    if (query->replace(param->pos_in_query+length, 1, str))
      DBUG_RETURN(1);
    length+= str.length()-1;
sergefp@mysql.com's avatar
sergefp@mysql.com committed
856 857 858 859
  }
  DBUG_RETURN(0);
}

860
/*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
861 862
  Validate INSERT statement: 

863
  SYNOPSIS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
864 865 866 867
    mysql_test_insert()
    stmt	prepared statemen handler
    tables	list of tables queries  

868 869 870 871
  RETURN VALUE
    0   ok
    1   error, sent to the client
   -1   error, not sent to client
872
*/
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
873 874 875 876 877 878 879
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)
880
{
881
  THD *thd= stmt->thd;
882
  LEX *lex= stmt->lex;
883 884
  List_iterator_fast<List_item> its(values_list);
  List_item *values;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
885
  int res= -1;
886 887
  TABLE_LIST *insert_table_list=
    (TABLE_LIST*) lex->select_lex.table_list.first;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
888
  my_bool update= (lex->value_list.elements ? UPDATE_ACL : 0);
889
  DBUG_ENTER("mysql_test_insert");
890

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
891 892
  if ((res= insert_precheck(thd, table_list, update)))
    DBUG_RETURN(res);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
893

894
  /*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
895 896 897
     open temporary memory pool for temporary data allocated by derived
     tables & preparation procedure
  */
hf@deer.(none)'s avatar
hf@deer.(none) committed
898
  if (open_and_lock_tables(thd, table_list))
899
  {
900
    DBUG_RETURN(-1);
901 902
  }

903 904 905
  if ((values= its++))
  {
    uint value_count;
906
    ulong counter= 0;
907

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
908 909 910 911 912
    if ((res= mysql_prepare_insert(thd, table_list, insert_table_list,
				   table_list->table, fields, values,
				   update_fields, update_values, duplic)))
      goto error;
    
913 914 915
    value_count= values->elements;
    its.rewind();
   
916
    while ((values= its++))
917 918 919 920 921 922
    {
      counter++;
      if (values->elements != value_count)
      {
        my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
			ER(ER_WRONG_VALUE_COUNT_ON_ROW),
923
			MYF(0), counter);
924
        goto error;
925
      }
926 927
      if (setup_fields(thd, 0, insert_table_list, *values, 0, 0, 0))
	goto error;
928 929
    }
  }
930

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
931
  res= 0;
932 933
error:
  lex->unit.cleanup();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
934
  DBUG_RETURN(res);
935 936 937 938
}


/*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
939 940
  Validate UPDATE statement

941
  SYNOPSIS
942
    mysql_test_update()
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
943 944 945
    stmt	prepared statemen handler
    tables	list of tables queries

946 947 948 949
  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
950
*/
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
951 952
static int mysql_test_update(Prepared_statement *stmt,
			     TABLE_LIST *table_list)
953
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
954
  int res;
955
  THD *thd= stmt->thd;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
956 957 958 959 960
  SELECT_LEX *select= &stmt->lex->select_lex;
  DBUG_ENTER("mysql_test_update");

  if ((res= update_precheck(thd, table_list)))
    DBUG_RETURN(res);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
961

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
962
  if (open_and_lock_tables(thd, table_list))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
963 964
    res= -1;
  else
965
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
966 967 968 969 970 971 972 973 974 975 976 977 978
    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;
    }
979 980
    stmt->lex->unit.cleanup();
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
981 982 983
  /* TODO: here we should send types of placeholders to the client. */ 
  DBUG_RETURN(res);
}
984

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
985 986 987 988 989 990 991 992 993 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

/*
  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);
1019 1020
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1021

1022
/*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1023
  Validate SELECT statement.
1024 1025
  In case of success, if this query is not EXPLAIN, send column list info
  back to client. 
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1026

1027
  SYNOPSIS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1028 1029 1030 1031
    mysql_test_select()
    stmt	prepared statemen handler
    tables	list of tables queries

1032 1033 1034 1035
  RETURN VALUE
    0   success
    1   error, sent to client
   -1   error, not sent to client
1036
*/
1037

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1038
static int mysql_test_select(Prepared_statement *stmt,
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1039
			     TABLE_LIST *tables, bool text_protocol)
1040
{
1041
  THD *thd= stmt->thd;
1042
  LEX *lex= stmt->lex;
1043
  SELECT_LEX_UNIT *unit= &lex->unit;
1044

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1045
  DBUG_ENTER("mysql_test_select");
1046

hf@deer.(none)'s avatar
hf@deer.(none) committed
1047
#ifndef NO_EMBEDDED_ACCESS_CHECKS
1048 1049 1050
  ulong privilege= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL;
  if (tables)
  {
hf@deer.(none)'s avatar
hf@deer.(none) committed
1051
    if (check_table_access(thd, privilege, tables,0))
1052 1053
      DBUG_RETURN(1);
  }
1054
  else if (check_access(thd, privilege, any_db,0,0,0))
1055
    DBUG_RETURN(1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1056
#endif
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1057

1058
  if (open_and_lock_tables(thd, tables))
1059 1060
  {
    send_error(thd);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1061
    goto err;
1062
  }
1063

1064 1065 1066 1067 1068 1069 1070 1071
  thd->used_tables= 0;                        // Updated by setup_fields

  // JOIN::prepare calls
  if (unit->prepare(thd, 0, 0))
  {
    send_error(thd);
    goto err_prep;
  }
1072
  if (!text_protocol)
1073
  {
1074 1075 1076 1077 1078 1079
    if (lex->describe)
    {
      if (send_prep_stmt(stmt, 0))
        goto err_prep;
    }
    else
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1080
    {
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1081
      if (send_prep_stmt(stmt, lex->select_lex.item_list.elements) ||
1082
          thd->protocol_simple.send_fields(&lex->select_lex.item_list, 0)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1083
#ifndef EMBEDDED_LIBRARY
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1084
          || net_flush(&thd->net)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1085
#endif
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1086 1087 1088
         )
        goto err_prep;
    }
1089
  }
1090
  unit->cleanup();
1091 1092 1093 1094 1095 1096
  DBUG_RETURN(0);

err_prep:
  unit->cleanup();
err:
  DBUG_RETURN(1);
1097 1098
}

1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
/*
  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);
1124

1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
  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);
1163

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
  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:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1176
  stmt->lex->unit.cleanup();
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  DBUG_RETURN(res);
}


/*
  Check internal SELECT of the prepared command

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

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1189
  RETURN VALUE
1190 1191
    0   success
    1   error, sent to client
miguel@hegel.local's avatar
miguel@hegel.local committed
1192
   -1   error, not sent to client
1193 1194 1195 1196 1197 1198 1199 1200
*/
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;
1201

1202 1203 1204 1205 1206
  if (tables && (res= open_and_lock_tables(thd, tables)))
    goto end;

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

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1207
  // JOIN::prepare calls
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
  if (lex->unit.prepare(thd, 0, 0))
  {
    res= thd->net.report_error ? -1 : 1;
  }
end:
  lex->unit.cleanup();
  DBUG_RETURN(res);
}


/*
1219
  Validate and prepare for execution CREATE TABLE statement
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

  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;
1237
  SELECT_LEX *select_lex= &lex->select_lex;
1238 1239 1240 1241 1242
  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,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1243
				  &create_table_local);
1244

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1245
  if (!(res= create_table_precheck(thd, tables, create_table)) &&
1246 1247 1248
      select_lex->item_list.elements)
  {
    select_lex->resolve_mode= SELECT_LEX::SELECT_MODE;
1249
    res= select_like_statement_test(stmt, tables);
1250 1251
    select_lex->resolve_mode= SELECT_LEX::NOMATTER_MODE;
  }
1252

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1253
  /* put tables back for PS rexecuting */
1254 1255 1256 1257 1258
  tables= lex->link_first_table_back(tables, create_table,
				     create_table_local);
  DBUG_RETURN(res);
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1259

1260
/*
1261
  Validate and prepare for execution multi update statement
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

  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);
}


/*
1284
  Validate and prepare for execution multi delete statement
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303

  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;

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1304
  uint fake_counter;
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
  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 */
miguel@hegel.local's avatar
miguel@hegel.local committed
1334
  lex->select_lex.table_list.first= (byte*) first_local_table->next;
1335 1336 1337 1338 1339
  /*
    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;
1340 1341
  res= select_like_statement_test(stmt, tables);
  /* revert changes*/
miguel@hegel.local's avatar
miguel@hegel.local committed
1342
  lex->select_lex.table_list.first= (byte*) first_local_table;
1343 1344 1345 1346 1347
  lex->select_lex.resolve_mode= SELECT_LEX::INSERT_MODE;
  return res;
}


1348
/*
1349 1350 1351 1352 1353 1354 1355
  Send the prepare query results back to client
  SYNOPSIS
  send_prepare_results()
    stmt prepared statement
  RETURN VALUE
    0   success
    1   error, sent to client
1356
*/
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1357
static int send_prepare_results(Prepared_statement *stmt, bool text_protocol)
1358
{   
1359
  THD *thd= stmt->thd;
1360
  LEX *lex= stmt->lex;
1361 1362
  SELECT_LEX *select_lex= &lex->select_lex;
  TABLE_LIST *tables=(TABLE_LIST*) select_lex->table_list.first;
1363
  enum enum_sql_command sql_command= lex->sql_command;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1364 1365 1366
  int res= 0;
  DBUG_ENTER("send_prepare_results");

1367
  DBUG_PRINT("enter",("command: %d, param_count: %ld",
1368
                      sql_command, stmt->param_count));
1369

1370 1371
  if ((&lex->select_lex != lex->all_selects_list ||
       lex->time_zone_tables_used) &&
1372 1373 1374
      lex->unit.create_total_list(thd, lex, &tables))
    DBUG_RETURN(1);

1375
  
1376
  switch (sql_command) {
1377
  case SQLCOM_REPLACE:
1378
  case SQLCOM_INSERT:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1379 1380 1381 1382 1383
    res= mysql_test_insert(stmt, tables, lex->field_list,
			   lex->many_values,
			   select_lex->item_list, lex->value_list,
			   (lex->value_list.elements ?
			    DUP_UPDATE : lex->duplicates));
1384 1385 1386
    break;

  case SQLCOM_UPDATE:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1387 1388 1389
    res= mysql_test_update(stmt, tables);
    break;

1390
  case SQLCOM_DELETE:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1391
    res= mysql_test_delete(stmt, tables);
1392 1393 1394
    break;

  case SQLCOM_SELECT:
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1395
    if ((res= mysql_test_select(stmt, tables, text_protocol)))
1396 1397 1398
      goto error;
    /* Statement and field info has already been sent */
    DBUG_RETURN(0);
1399

1400
  case SQLCOM_CREATE_TABLE:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1401
    res= mysql_test_create_table(stmt, tables);
1402 1403 1404
    break;
  
  case SQLCOM_DO:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1405 1406
    res= mysql_test_do_fields(stmt, tables, lex->insert_list);
    break;
1407 1408

  case SQLCOM_SET_OPTION:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1409
    res= mysql_test_set_fields(stmt, tables, &lex->var_list);
1410 1411 1412
    break;

  case SQLCOM_DELETE_MULTI:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1413
    res= mysql_test_multidelete(stmt, tables);
1414 1415 1416
    break;
  
  case SQLCOM_UPDATE_MULTI:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1417
    res= mysql_test_multiupdate(stmt, tables);
1418 1419 1420
    break;

  case SQLCOM_INSERT_SELECT:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1421
    res= mysql_test_insert_select(stmt, tables);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
    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;

1444
  default:
1445 1446
    /*
      All other is not supported yet
1447
    */
1448 1449 1450
    res= -1;
    my_error(ER_UNSUPPORTED_PS, MYF(0));
    goto error;
1451
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1452
  if (res == 0)
1453
    DBUG_RETURN(text_protocol? 0 : send_prep_stmt(stmt, 0));
1454 1455 1456
error:
  if (res < 0)
    send_error(thd, thd->killed ? ER_SERVER_SHUTDOWN : 0);
1457
  DBUG_RETURN(1);
1458 1459
}

venu@myvenu.com's avatar
venu@myvenu.com committed
1460
/*
1461 1462
  Initialize array of parameters in statement from LEX.
  (We need to have quick access to items by number in mysql_stmt_get_longdata).
1463
  This is to avoid using malloc/realloc in the parser.
venu@myvenu.com's avatar
venu@myvenu.com committed
1464
*/
1465

1466
static bool init_param_array(Prepared_statement *stmt)
venu@myvenu.com's avatar
venu@myvenu.com committed
1467
{
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
  LEX *lex= stmt->lex;
  if ((stmt->param_count= lex->param_list.elements))
  {
    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)
    {
      send_error(stmt->thd, ER_OUT_OF_RESOURCES);
1480
      return 1;
1481 1482 1483 1484 1485 1486 1487 1488
    }
    for (to= stmt->param_array;
         to < stmt->param_array + stmt->param_count;
         ++to)
    {
      *to= param_iterator++;
    }
  }
1489
  return 0;
venu@myvenu.com's avatar
venu@myvenu.com committed
1490
}
1491

1492

1493
/*
1494 1495 1496
  Given a query string with parameter markers, create a Prepared Statement
  from it and send PS info back to the client.
  
1497 1498
  SYNOPSIS
    mysql_stmt_prepare()
1499 1500 1501
      packet         query to be prepared 
      packet_length  query string length, including ignored trailing NULL or 
                     quote char.
1502
      name           NULL or statement name. For unnamed statements binary PS
1503
                     protocol is used, for named statements text protocol is 
1504
                     used.
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
  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.
1519
   
1520 1521
*/

1522 1523
int mysql_stmt_prepare(THD *thd, char *packet, uint packet_length,
                       LEX_STRING *name)
1524
{
1525 1526
  LEX *lex;
  Prepared_statement *stmt= new Prepared_statement(thd);
1527
  int error;
1528
  DBUG_ENTER("mysql_stmt_prepare");
1529

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1530
  DBUG_PRINT("prep_query", ("%s", packet));
1531

1532
  if (stmt == 0)
1533 1534
  {
    send_error(thd, ER_OUT_OF_RESOURCES);
1535 1536 1537 1538 1539 1540
    DBUG_RETURN(1);
  }

  if (name)
  {
    stmt->name.length= name->length;
1541
    if (!(stmt->name.str= memdup_root(&stmt->mem_root, (char*)name->str,
1542
                                      name->length)))
1543 1544 1545 1546 1547
    {
      delete stmt;
      send_error(thd, ER_OUT_OF_RESOURCES);
      DBUG_RETURN(1);
    }
1548
  }
1549 1550

  if (thd->stmt_map.insert(stmt))
1551 1552 1553
  {
    delete stmt;
    send_error(thd, ER_OUT_OF_RESOURCES);
1554
    DBUG_RETURN(1);
1555
  }
1556

1557 1558
  thd->set_n_backup_statement(stmt, &thd->stmt_backup);
  thd->set_n_backup_item_arena(stmt, &thd->stmt_backup);
1559

1560
  if (alloc_query(thd, packet, packet_length))
1561
  {
1562 1563
    thd->restore_backup_statement(stmt, &thd->stmt_backup);
    thd->restore_backup_item_arena(stmt, &thd->stmt_backup);
1564 1565 1566
    /* Statement map deletes statement on erase */
    thd->stmt_map.erase(stmt);
    send_error(thd, ER_OUT_OF_RESOURCES);
1567
    DBUG_RETURN(1);
1568
  }
1569

1570
  mysql_log.write(thd, COM_PREPARE, "%s", packet);
1571

1572
  thd->current_arena= stmt;
1573 1574
  mysql_init_query(thd, (uchar *) thd->query, thd->query_length);
  lex= thd->lex;
1575 1576
  lex->safe_to_cache_query= 0;

1577
  error= yyparse((void *)thd) || thd->is_fatal_error ||
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
         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));
1591

1592
  /* restore to WAIT_PRIOR: QUERY_PRIOR is set inside alloc_query */
1593
  if (!(specialflag & SPECIAL_NO_PRIOR))
venu@myvenu.com's avatar
venu@myvenu.com committed
1594
    my_pthread_setprio(pthread_self(),WAIT_PRIOR);
1595
  lex_end(lex);
1596 1597 1598 1599 1600 1601
  thd->restore_backup_statement(stmt, &thd->stmt_backup);
  cleanup_items(stmt->free_list);
  close_thread_tables(thd);
  free_items(thd->free_list);
  thd->free_list= 0;
  thd->current_arena= thd;
1602

1603
  if (error)
1604
  {
1605 1606
    /* Statement map deletes statement on erase */
    thd->stmt_map.erase(stmt);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1607
    stmt= NULL;
1608
    /* error is sent inside yyparse/send_prepare_results */
1609
  }
1610 1611
  else
  {
1612
    stmt->setup_set_params();
1613 1614 1615 1616 1617 1618 1619 1620 1621
    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;
    }
1622
    stmt->state= Prepared_statement::PREPARED;
1623
  }
1624

1625
  DBUG_RETURN(!stmt);
1626
}
1627

1628
/* Reinit statement before execution */
1629

1630 1631 1632 1633
static void reset_stmt_for_execute(Prepared_statement *stmt)
{
  THD *thd= stmt->thd;
  SELECT_LEX *sl= stmt->lex->all_selects_list;
1634

1635
  for (; sl; sl= sl->next_select_in_list())
1636
  {
1637 1638
    /* remove option which was put by mysql_explain_union() */
    sl->options&= ~SELECT_DESCRIBE;
1639 1640 1641
    /*
      Copy WHERE clause pointers to avoid damaging they by optimisation
    */
1642
    if (sl->prep_where)
1643
    {
1644
      sl->where= sl->prep_where->copy_andor_structure(thd);
1645 1646
      sl->where->cleanup();
    }
1647
    DBUG_ASSERT(sl->join == 0);
hf@deer.(none)'s avatar
hf@deer.(none) committed
1648
    ORDER *order;
1649
    /* Fix GROUP list */
1650 1651
    for (order= (ORDER *)sl->group_list.first; order; order= order->next)
      order->item= &order->item_ptr;
1652
    /* Fix ORDER list */
1653 1654
    for (order= (ORDER *)sl->order_list.first; order; order= order->next)
      order->item= &order->item_ptr;
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

    /*
      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)
    {
konstantin@oak.local's avatar
konstantin@oak.local committed
1665 1666 1667 1668 1669
      /*
        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;
1670 1671
      tables->table_list= 0;
    }
1672 1673 1674 1675 1676
    
    {
      SELECT_LEX_UNIT *unit= sl->master_unit();
      unit->unclean();
      unit->types.empty();
1677
      /* for derived tables & PS (which can't be reset by Item_subquery) */
1678 1679
      unit->reinit_exec_mechanism();
    }
1680
  }
1681
  stmt->lex->current_select= &stmt->lex->select_lex;
1682 1683
}

1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

/* 
    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();
}


1702 1703 1704 1705
/*
  Executes previously prepared query.
  If there is any parameters, then replace markers with the data supplied
  from client, and then execute the query.
1706
  SYNOPSIS
1707
    mysql_stmt_execute()
1708 1709 1710
      thd            Current thread
      packet         Query string
      packet_length  Query string length, including terminator character.
1711 1712
*/

1713
void mysql_stmt_execute(THD *thd, char *packet, uint packet_length)
1714 1715
{
  ulong stmt_id= uint4korr(packet);
1716 1717 1718 1719 1720
  /*
    Query text for binary log, or empty string if the query is not put into
    binary log.
  */
  String expanded_query;
1721
#ifndef EMBEDDED_LIBRARY
1722
  uchar *packet_end= (uchar *) packet + packet_length - 1;
1723
#endif
1724 1725
  Prepared_statement *stmt;
  DBUG_ENTER("mysql_stmt_execute");
1726 1727

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

1729 1730
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_execute",
                                      SEND_ERROR)))
1731 1732
    DBUG_VOID_RETURN;

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1733
  DBUG_PRINT("exec_query:", ("%s", stmt->query));
1734

1735
  /* Check if we got an error when sending long data */
1736
  if (stmt->state == Item_arena::ERROR)
1737 1738 1739 1740 1741
  {
    send_error(thd, stmt->last_errno, stmt->last_error);
    DBUG_VOID_RETURN;
  }

hf@deer.(none)'s avatar
hf@deer.(none) committed
1742
#ifndef EMBEDDED_LIBRARY
1743 1744 1745
  if (stmt->param_count)
  {
    uchar *null_array= (uchar *) packet;
1746
    if (setup_conversion_functions(stmt, (uchar **) &packet, packet_end) ||
1747
        stmt->set_params(stmt, null_array, (uchar *) packet, packet_end,
1748
                         &expanded_query))
1749 1750
      goto set_params_data_err;
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
1751
#else
1752 1753 1754 1755 1756
  /*
    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.
  */
1757
  if (stmt->param_count && stmt->set_params_data(stmt, &expanded_query))
1758
    goto set_params_data_err;
hf@deer.(none)'s avatar
hf@deer.(none) committed
1759
#endif
1760
  DBUG_ASSERT(thd->free_list == NULL);
1761
  thd->protocol= &thd->protocol_prep;           // Switch to binary protocol
1762
  execute_stmt(thd, stmt, &expanded_query, true);
1763 1764
  thd->protocol= &thd->protocol_simple;         // Use normal protocol
  DBUG_VOID_RETURN;
1765

1766
set_params_data_err:
1767
  reset_stmt_params(stmt);
1768
  my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_execute");
1769
  send_error(thd);
1770 1771 1772
  DBUG_VOID_RETURN;
}

1773

sergefp@mysql.com's avatar
sergefp@mysql.com committed
1774
/*
1775
  Execute prepared statement using parameter values from
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1776 1777 1778
  lex->prepared_stmt_params and send result to the client using text protocol.
*/

1779
void mysql_sql_stmt_execute(THD *thd, LEX_STRING *stmt_name)
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1780
{
1781
  Prepared_statement *stmt;
1782
  /*
1783 1784
    Query text for binary log, or empty string if the query is not put into
    binary log.
1785
  */
1786
  String expanded_query;
1787
  DBUG_ENTER("mysql_sql_stmt_execute");
1788

1789 1790
  if (!(stmt= (Prepared_statement*)thd->stmt_map.find_by_name(stmt_name)))
  {
1791 1792 1793 1794
    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), stmt_name->length,
             stmt_name->str, "EXECUTE");
    send_error(thd);
    DBUG_VOID_RETURN;
1795 1796
  }

sergefp@mysql.com's avatar
sergefp@mysql.com committed
1797 1798
  if (stmt->param_count != thd->lex->prepared_stmt_params.elements)
  {
1799
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1800 1801 1802 1803
    send_error(thd);
    DBUG_VOID_RETURN;
  }

1804 1805 1806
  DBUG_ASSERT(thd->free_list == NULL);

  thd->set_n_backup_statement(stmt, &thd->stmt_backup);
1807 1808
  if (stmt->set_params_from_vars(stmt,
                                 thd->stmt_backup.lex->prepared_stmt_params,
1809
                                 &expanded_query))
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1810
  {
1811
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
sergefp@mysql.com's avatar
sergefp@mysql.com committed
1812 1813
    send_error(thd);
  }
1814
  execute_stmt(thd, stmt, &expanded_query, false);
1815 1816 1817
  DBUG_VOID_RETURN;
}

1818

1819 1820
/*
  Execute prepared statement.
1821 1822 1823 1824
  SYNOPSIS
    execute_stmt()
      thd            Current thread
      stmt           Statement to execute
1825
      expanded_query If binary log is enabled, query string with parameter
1826 1827 1828
                     placeholders replaced with actual values. Otherwise empty
                     string.
  NOTES
1829
  Caller must set parameter values and thd::protocol.
1830
  thd->free_list is assumed to be garbage.
1831
*/
1832

1833
static void execute_stmt(THD *thd, Prepared_statement *stmt,
1834
                         String *expanded_query, bool set_context)
1835 1836
{
  DBUG_ENTER("execute_stmt");
1837
  if (set_context)
1838
    thd->set_n_backup_statement(stmt, &thd->stmt_backup);
1839
  reset_stmt_for_execute(stmt);
1840 1841 1842

  if (expanded_query->length() &&
      alloc_query(thd, (char *)expanded_query->ptr(),
1843 1844 1845 1846 1847
                  expanded_query->length()+1))
  {
    my_error(ER_OUTOFMEMORY, 0, expanded_query->length());
    DBUG_VOID_RETURN;
  }
1848 1849 1850 1851 1852 1853 1854
  /*
    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.
  */
  if (stmt->state == Item_arena::PREPARED)
    thd->current_arena= stmt;
1855

1856
  if (!(specialflag & SPECIAL_NO_PRIOR))
1857
    my_pthread_setprio(pthread_self(),QUERY_PRIOR);
1858
  mysql_execute_command(thd);
1859
  thd->lex->unit.cleanup();
1860
  if (!(specialflag & SPECIAL_NO_PRIOR))
1861
    my_pthread_setprio(pthread_self(), WAIT_PRIOR);
1862

1863 1864
  /* Free Items that were created during this execution of the PS. */
  free_items(thd->free_list);
1865 1866 1867 1868 1869 1870
  thd->free_list= 0;
  if (stmt->state == Item_arena::PREPARED)
  {
    thd->current_arena= thd;
    stmt->state= Item_arena::EXECUTED;
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
1871
  cleanup_items(stmt->free_list);
1872
  reset_stmt_params(stmt);
1873
  close_thread_tables(thd);                    // to close derived tables
1874
  thd->set_statement(&thd->stmt_backup);
1875 1876 1877
  DBUG_VOID_RETURN;
}

1878

1879
/*
1880
  Reset a prepared statement in case there was a recoverable error.
1881 1882
  SYNOPSIS
    mysql_stmt_reset()
1883 1884
      thd       Thread handle
      packet	Packet with stmt id 
1885 1886

  DESCRIPTION
1887 1888 1889 1890 1891 1892 1893
    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).
1894 1895
*/

1896
void mysql_stmt_reset(THD *thd, char *packet)
1897
{
1898
  /* There is always space for 4 bytes in buffer */
1899
  ulong stmt_id= uint4korr(packet);
1900 1901
  Prepared_statement *stmt;
  
1902
  DBUG_ENTER("mysql_stmt_reset");
1903

1904 1905
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_reset",
                                      SEND_ERROR)))
1906 1907
    DBUG_VOID_RETURN;

1908
  stmt->state= Item_arena::PREPARED;
1909

1910 1911 1912 1913 1914
  /* 
    Clear parameters from data which could be set by 
    mysql_stmt_send_long_data() call.
  */
  reset_stmt_params(stmt);
1915 1916

  send_ok(thd);
1917
  
1918 1919 1920 1921 1922
  DBUG_VOID_RETURN;
}


/*
1923 1924
  Delete a prepared statement from memory.
  Note: we don't send any reply to that command. 
1925 1926
*/

1927
void mysql_stmt_free(THD *thd, char *packet)
1928
{
1929
  /* There is always space for 4 bytes in packet buffer */
1930
  ulong stmt_id= uint4korr(packet);
1931 1932
  Prepared_statement *stmt;

1933
  DBUG_ENTER("mysql_stmt_free");
1934

1935 1936
  if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_close",
                                      DONT_SEND_ERROR)))
1937
    DBUG_VOID_RETURN;
1938 1939 1940

  /* Statement map deletes statement on erase */
  thd->stmt_map.erase(stmt);
1941 1942 1943
  DBUG_VOID_RETURN;
}

1944 1945

/*
1946
  Long data in pieces from client
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963

  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)
*/

1964
void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
1965
{
1966 1967
  ulong stmt_id;
  uint param_number;
1968
  Prepared_statement *stmt;
1969 1970
  Item_param *param;
  char *packet_end= packet + packet_length - 1;
1971
  
1972 1973
  DBUG_ENTER("mysql_stmt_get_longdata");

hf@deer.(none)'s avatar
hf@deer.(none) committed
1974
#ifndef EMBEDDED_LIBRARY
1975 1976
  /* Minimal size of long data packet is 6 bytes */
  if ((ulong) (packet_end - packet) < MYSQL_LONG_DATA_HEADER)
1977
  {
1978
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_send_long_data");
1979 1980
    DBUG_VOID_RETURN;
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
1981
#endif
1982

1983 1984
  stmt_id= uint4korr(packet);
  packet+= 4;
1985

1986
  if (!(stmt=find_prepared_statement(thd, stmt_id, "mysql_stmt_send_long_data",
1987
                                     DONT_SEND_ERROR)))
1988 1989
    DBUG_VOID_RETURN;

1990 1991
  param_number= uint2korr(packet);
  packet+= 2;
hf@deer.(none)'s avatar
hf@deer.(none) committed
1992
#ifndef EMBEDDED_LIBRARY
1993 1994
  if (param_number >= stmt->param_count)
  {
venu@myvenu.com's avatar
venu@myvenu.com committed
1995
    /* Error will be sent in execute call */
1996
    stmt->state= Item_arena::ERROR;
venu@myvenu.com's avatar
venu@myvenu.com committed
1997
    stmt->last_errno= ER_WRONG_ARGUMENTS;
1998 1999
    sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS),
            "mysql_stmt_send_long_data");
2000 2001
    DBUG_VOID_RETURN;
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
2002 2003
#endif

2004 2005
  param= stmt->param_array[param_number];

hf@deer.(none)'s avatar
hf@deer.(none) committed
2006
#ifndef EMBEDDED_LIBRARY
2007
  if (param->set_longdata(packet, (ulong) (packet_end - packet)))
hf@deer.(none)'s avatar
hf@deer.(none) committed
2008
#else
2009
  if (param->set_longdata(thd->extra_data, thd->extra_length))
hf@deer.(none)'s avatar
hf@deer.(none) committed
2010
#endif
2011 2012 2013 2014 2015
  {
    stmt->state= Item_arena::ERROR;
    stmt->last_errno= ER_OUTOFMEMORY;
    sprintf(stmt->last_error, ER(ER_OUTOFMEMORY), 0);
  }
2016 2017
  DBUG_VOID_RETURN;
}
venu@myvenu.com's avatar
venu@myvenu.com committed
2018

2019 2020 2021 2022

Prepared_statement::Prepared_statement(THD *thd_arg)
  :Statement(thd_arg),
  thd(thd_arg),
2023
  param_array(0),
2024
  param_count(0),
2025
  last_errno(0)
2026 2027 2028 2029
{
  *last_error= '\0';
}

2030 2031 2032 2033
void Prepared_statement::setup_set_params()
{
  /* Setup binary logging */
  if (mysql_bin_log.is_open() && is_update_query(lex->sql_command))
2034
  {
2035
    set_params_from_vars= insert_params_from_vars_with_log;
2036
#ifndef EMBEDDED_LIBRARY
2037
    set_params= insert_params_withlog;
2038
#else
2039
    set_params_data= emb_insert_params_withlog;
2040 2041 2042
#endif
  }
  else
2043 2044
  {
    set_params_from_vars= insert_params_from_vars;
2045
#ifndef EMBEDDED_LIBRARY
2046
    set_params= insert_params;
2047
#else
2048
    set_params_data= emb_insert_params;
2049
#endif
2050
  }
2051 2052 2053 2054 2055 2056 2057 2058
}

Prepared_statement::~Prepared_statement()
{
  free_items(free_list);
}


2059
Item_arena::Type Prepared_statement::type() const
2060 2061 2062 2063
{
  return PREPARED_STATEMENT;
}