sql_prepare.cc 28.8 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 42
    previously prepared query. If there is any param markers; then client
    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:
unknown's avatar
unknown committed
60
    [COM_LONG_DATA:1][STMT_ID:4][parameter_number:2][type:2][data]
unknown's avatar
unknown committed
61 62
  - Checks if the type is specified by client, and if yes reads the type, 
    and stores the data in that format.
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()
unknown's avatar
unknown committed
74

unknown's avatar
unknown committed
75
#define IS_PARAM_NULL(pos, param_no) pos[param_no/8] & (1 << param_no & 7)
76

77 78
#define STMT_QUERY_LOG_LENGTH 8192

79
extern int yyparse(void *thd);
80
static String null_string("NULL", 4, default_charset_info);
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

/*
  Find prepared statement in thd

  SYNOPSIS
    find_prepared_statement()
    thd		Thread handler
    stmt_id	Statement id server specified to the client on prepare

  RETURN VALUES
    0		error.  In this case the error is sent with my_error()
    ptr 	Pointer to statement
*/

static PREP_STMT *find_prepared_statement(THD *thd, ulong stmt_id,
					  const char *when)
{
  PREP_STMT *stmt;
  DBUG_ENTER("find_prepared_statement");
  DBUG_PRINT("enter",("stmt_id: %d", stmt_id));

  if (thd->last_prepared_stmt && thd->last_prepared_stmt->stmt_id == stmt_id)
    DBUG_RETURN(thd->last_prepared_stmt);
  if ((stmt= (PREP_STMT*) tree_search(&thd->prepared_statements, &stmt_id,
				      (void*) 0)))
    DBUG_RETURN (thd->last_prepared_stmt= stmt);
  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), stmt_id, when);
  DBUG_RETURN(0);
}

/*
  Compare two prepared statements;  Used to find a prepared statement
*/

unknown's avatar
unknown committed
115
int compare_prep_stmt(void *not_used, PREP_STMT *stmt, ulong *key)
116
{
unknown's avatar
unknown committed
117
  return (stmt->stmt_id == *key) ? 0 : (stmt->stmt_id < *key) ? -1 : 1;
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
}


/*
  Free prepared statement.

  SYNOPSIS
    standard tree_element_free function.

  DESCRIPTION
    We don't have to free the stmt itself as this was stored in the tree
    and will be freed when the node is deleted
*/

void free_prep_stmt(PREP_STMT *stmt, TREE_FREE mode, void *not_used)
133 134
{     
  my_free((char *)stmt->param, MYF(MY_ALLOW_ZERO_PTR));
135 136
  if (stmt->query)
    stmt->query->free();
137
  free_items(stmt->free_list);
unknown's avatar
unknown committed
138
  free_root(&stmt->mem_root, MYF(0));
139 140 141 142 143 144
}

/*
  Send prepared stmt info to client after prepare
*/

unknown's avatar
unknown committed
145
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
146
static bool send_prep_stmt(PREP_STMT *stmt, uint columns)
147
{
unknown's avatar
unknown committed
148
  NET  *net=&stmt->thd->net;
149 150 151 152 153
  char buff[9];
  buff[0]= 0;
  int4store(buff+1, stmt->stmt_id);
  int2store(buff+5, columns);
  int2store(buff+7, stmt->param_count);
unknown's avatar
SCRUM  
unknown committed
154 155
  /* This should be fixed to work with prepared statements
   */
unknown's avatar
unknown committed
156
  return (my_net_write(net, buff, sizeof(buff)) || net_flush(net));
unknown's avatar
unknown committed
157
}
158
#else
unknown's avatar
unknown committed
159 160 161 162 163 164 165
static bool send_prep_stmt(PREP_STMT *stmt, uint columns)
{
  MYSQL_STMT *client_stmt= stmt->thd->client_stmt;

  client_stmt->stmt_id= stmt->stmt_id;
  client_stmt->field_count= columns;
  client_stmt->param_count= stmt->param_count;
166
}
unknown's avatar
unknown committed
167
#endif /*!EMBEDDED_LIBRAYR*/
168 169 170 171 172 173 174

/*
  Send information about all item parameters

  TODO: Not yet ready
*/

unknown's avatar
unknown committed
175
static bool send_item_params(PREP_STMT *stmt)
176
{
unknown's avatar
unknown committed
177
#if 0
178 179
  char buff[1];
  buff[0]=0;
unknown's avatar
unknown committed
180
  if (my_net_write(&stmt->thd->net, buff, sizeof(buff))) 
unknown's avatar
unknown committed
181
    return 1;
unknown's avatar
unknown committed
182 183
  send_eof(stmt->thd);
#endif
unknown's avatar
unknown committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  return 0;
}

/*
  Read the length of the parameter data and retun back to   
  caller by positing the pointer to param data              
*/

static ulong get_param_length(uchar **packet)
{
  reg1 uchar *pos= *packet;
  if (*pos < 251)
  {
    (*packet)++;
    return (ulong) *pos;
  }
  if (*pos == 252)
  {
    (*packet)+=3;
    return (ulong) uint2korr(pos+1);
  }
  if (*pos == 253)
  {
    (*packet)+=4;
    return (ulong) uint3korr(pos+1);
  }
  (*packet)+=9; // Must be 254 when here 
  return (ulong) uint4korr(pos+1);
}
unknown's avatar
unknown committed
213 214
 /*
  Setup param conversion routines
unknown's avatar
unknown committed
215

unknown's avatar
unknown committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229
  setup_param_xx()
  param   Parameter Item
  pos     Input data buffer

  All these functions reads the data from pos and sets up that data
  through 'param' and advances the buffer position to predifined
  length position.

  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.

  RETURN VALUES
    
unknown's avatar
unknown committed
230 231
*/

unknown's avatar
unknown committed
232
static void setup_param_tiny(Item_param *param, uchar **pos)
unknown's avatar
unknown committed
233
{
unknown's avatar
unknown committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  param->set_int((longlong)(**pos));
  *pos+= 1;
}

static void setup_param_short(Item_param *param, uchar **pos)
{
  param->set_int((longlong)sint2korr(*pos));
  *pos+= 2;
}

static void setup_param_int32(Item_param *param, uchar **pos)
{
  param->set_int((longlong)sint4korr(*pos));
  *pos+= 4;
}

static void setup_param_int64(Item_param *param, uchar **pos)
{
  param->set_int((longlong)sint8korr(*pos));
  *pos+= 8;
}

static void setup_param_float(Item_param *param, uchar **pos)
{
  float data;
  float4get(data,*pos);
  param->set_double((double) data);
  *pos+= 4;
}

static void setup_param_double(Item_param *param, uchar **pos)
{
  double data;
  float8get(data,*pos);
  param->set_double((double) data);
  *pos+= 8;
}

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
static void setup_param_time(Item_param *param, uchar **pos)
{
  ulong length;

  if ((length= get_param_length(pos)))
  {
    uchar *to= *pos;
    TIME  tm;   
    
    tm.second_part= (length > 8 ) ? (ulong) sint4korr(to+7): 0;

    tm.day=    (ulong) sint4korr(to+1);
    tm.hour=   (uint) to[5];
    tm.minute= (uint) to[6];
    tm.second= (uint) to[7];

    tm.year= tm.month= 0;
    tm.neg= (bool)to[0];

    param->set_time(&tm, TIMESTAMP_TIME);
  }
  *pos+= length;
}

static void setup_param_datetime(Item_param *param, uchar **pos)
{
  uint length= get_param_length(pos);
 
  if (length)
  {
    uchar *to= *pos;
    TIME  tm;
    
    tm.second_part= (length > 7 ) ? (ulong) sint4korr(to+7): 0;
    
    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;
    
    tm.year=   (uint) sint2korr(to);
    tm.month=  (uint) to[2];
    tm.day=    (uint) to[3];
    tm.neg=    0;

    param->set_time(&tm, TIMESTAMP_FULL);
  }
  *pos+= length;
}

static void setup_param_date(Item_param *param, uchar **pos)
{
  ulong length;
 
  if ((length= get_param_length(pos)))
  {
    uchar *to= *pos;
    TIME tm;

335
    tm.year=  (uint) sint2korr(to);
336 337 338 339 340 341 342 343 344 345 346 347
    tm.month=  (uint) to[2];
    tm.day= (uint) to[3];

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

    param->set_time(&tm, TIMESTAMP_DATE);
  }
  *pos+= length;
}

unknown's avatar
unknown committed
348 349
static void setup_param_str(Item_param *param, uchar **pos)
{
350
  ulong len= get_param_length(pos);
unknown's avatar
unknown committed
351
  param->set_value((const char *)*pos, len);
352
  *pos+= len;        
unknown's avatar
unknown committed
353 354
}

unknown's avatar
unknown committed
355
static void setup_param_functions(Item_param *param, uchar param_type)
unknown's avatar
unknown committed
356
{
unknown's avatar
unknown committed
357
  switch (param_type) {
unknown's avatar
unknown committed
358
  case FIELD_TYPE_TINY:
unknown's avatar
unknown committed
359
    param->setup_param_func= setup_param_tiny;
360
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
361 362
    break;
  case FIELD_TYPE_SHORT:
unknown's avatar
unknown committed
363
    param->setup_param_func= setup_param_short;
364
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
365 366
    break;
  case FIELD_TYPE_LONG:
unknown's avatar
unknown committed
367
    param->setup_param_func= setup_param_int32;
368
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
369 370
    break;
  case FIELD_TYPE_LONGLONG:
unknown's avatar
unknown committed
371
    param->setup_param_func= setup_param_int64;
372
    param->item_result_type= INT_RESULT;
unknown's avatar
unknown committed
373 374
    break;
  case FIELD_TYPE_FLOAT:
unknown's avatar
unknown committed
375
    param->setup_param_func= setup_param_float;
376
    param->item_result_type= REAL_RESULT;
unknown's avatar
unknown committed
377 378
    break;
  case FIELD_TYPE_DOUBLE:
unknown's avatar
unknown committed
379
    param->setup_param_func= setup_param_double;
380
    param->item_result_type= REAL_RESULT;
unknown's avatar
unknown committed
381
    break;
382 383
  case FIELD_TYPE_TIME:
    param->setup_param_func= setup_param_time;
384
    param->item_result_type= STRING_RESULT;
385 386 387
    break;
  case FIELD_TYPE_DATE:
    param->setup_param_func= setup_param_date;
388
    param->item_result_type= STRING_RESULT;
389
    break;
390 391
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
392
    param->setup_param_func= setup_param_datetime;
393
    param->item_result_type= STRING_RESULT;
394
    break;
unknown's avatar
unknown committed
395
  default:
unknown's avatar
unknown committed
396
    param->setup_param_func= setup_param_str;
397
    param->item_result_type= STRING_RESULT;
unknown's avatar
unknown committed
398 399 400 401
  }
}

/*
402 403
  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
404 405
*/

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
static bool insert_params_withlog(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
{
  THD *thd= stmt->thd;
  List<Item> &params= thd->lex.param_list;
  List_iterator<Item> param_iterator(params);
  Item_param *param;
  DBUG_ENTER("insert_params_withlog"); 
  
  String str, *res, *query= new String(stmt->query->alloced_length());  
  query->copy(*stmt->query);
  
  ulong param_no= 0;  
  uint32 length= 0;
  
  while ((param= (Item_param *)param_iterator++))
  {
    if (param->long_data_supplied)
      res= param->query_val_str(&str);       
    
    else
    {
      if (IS_PARAM_NULL(pos,param_no))
      {
        param->maybe_null= param->null_value= 1;
        res= &null_string;
      }
      else
      {
        param->maybe_null= param->null_value= 0;
        param->setup_param_func(param,&read_pos);
        res= param->query_val_str(&str);
      }
    }
    if (query->replace(param->pos_in_query+length, 1, *res))
      DBUG_RETURN(1);
    
    length+= res->length()-1;
    param_no++;
  }
  if (alloc_query(stmt->thd, (char *)query->ptr(), query->length()+1))
    DBUG_RETURN(1);
  
  query->free();
  DBUG_RETURN(0);
}

static bool insert_params(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
{
  THD *thd= stmt->thd;
  List<Item> &params= thd->lex.param_list;
  List_iterator<Item> param_iterator(params);
  Item_param *param;
  DBUG_ENTER("insert_params"); 
  
  ulong param_no= 0;  
  while ((param= (Item_param *)param_iterator++))
  {
    if (!param->long_data_supplied)   
    {
      if (IS_PARAM_NULL(pos,param_no))
        param->maybe_null= param->null_value= 1;
      else
      {
        param->maybe_null= param->null_value= 0;
        param->setup_param_func(param,&read_pos);
      }
    }
    param_no++;
  }
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
478
static bool setup_params_data(PREP_STMT *stmt)
unknown's avatar
unknown committed
479
{                                       
unknown's avatar
unknown committed
480
  THD *thd= stmt->thd;
unknown's avatar
unknown committed
481 482 483 484
  List<Item> &params= thd->lex.param_list;
  List_iterator<Item> param_iterator(params);
  Item_param *param;
  DBUG_ENTER("setup_params_data");
485

486
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
487
  uchar *pos=(uchar*) thd->net.read_pos+1+MYSQL_STMT_HEADER; //skip header
488 489 490
#else
  uchar *pos= 0; //just to compile TODO code for embedded case
#endif
unknown's avatar
unknown committed
491
  uchar *read_pos= pos+(stmt->param_count+7) / 8; //skip null bits   
unknown's avatar
unknown committed
492

unknown's avatar
unknown committed
493 494 495 496 497 498 499 500
  if (*read_pos++) //types supplied / first execute
  {              
    /*
      First execute or types altered by the client, setup the 
      conversion routines for all parameters (one time)
    */
    while ((param= (Item_param *)param_iterator++))
    {       
unknown's avatar
unknown committed
501 502
      setup_param_functions(param,*read_pos);
      read_pos+= 2;
unknown's avatar
unknown committed
503
    }
unknown's avatar
unknown committed
504 505
    param_iterator.rewind();
  }    
506
  stmt->setup_params(stmt,pos,read_pos);
unknown's avatar
unknown committed
507 508 509 510 511 512 513 514 515
  DBUG_RETURN(0);
}

/*
  Validate the following information for INSERT statement:                         
    - field existance           
    - fields count                          
*/

516 517
static bool mysql_test_insert_fields(PREP_STMT *stmt,
				     TABLE_LIST *table_list,
unknown's avatar
unknown committed
518
				     List<Item> &fields, 
unknown's avatar
unknown committed
519
				     List<List_item> &values_list)
unknown's avatar
unknown committed
520
{
521
  THD *thd= stmt->thd;
unknown's avatar
unknown committed
522 523 524 525 526
  TABLE *table;
  List_iterator_fast<List_item> its(values_list);
  List_item *values;
  DBUG_ENTER("mysql_test_insert_fields");

527 528 529 530 531 532 533 534 535 536 537
  my_bool update=(thd->lex.value_list.elements ? UPDATE_ACL : 0);
  ulong privilege= (thd->lex.duplicates == DUP_REPLACE ?
                    INSERT_ACL | DELETE_ACL : INSERT_ACL | update);

  if (check_access(thd,privilege,table_list->db,
                   &table_list->grant.privilege) || 
      (grant_option && check_grant(thd,privilege,table_list)) || 
      open_and_lock_tables(thd, table_list))
    DBUG_RETURN(1); 
  
  table= table_list->table;
unknown's avatar
unknown committed
538 539 540 541

  if ((values= its++))
  {
    uint value_count;
542
    ulong counter= 0;
unknown's avatar
unknown committed
543 544 545 546 547 548 549
    
    if (check_insert_fields(thd,table,fields,*values,1))
      DBUG_RETURN(1);

    value_count= values->elements;
    its.rewind();
   
550
    while ((values= its++))
unknown's avatar
unknown committed
551 552 553 554 555 556
    {
      counter++;
      if (values->elements != value_count)
      {
        my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
			ER(ER_WRONG_VALUE_COUNT_ON_ROW),
557
			MYF(0), counter);
unknown's avatar
unknown committed
558 559 560 561
        DBUG_RETURN(1);
      }
    }
  }
562 563
  if (send_prep_stmt(stmt, 0) || send_item_params(stmt))
    DBUG_RETURN(1);
unknown's avatar
unknown committed
564 565 566 567 568 569 570 571
  DBUG_RETURN(0);
}


/*
  Validate the following information                         
    UPDATE - set and where clause    DELETE - where clause                                             
                                                             
572 573
  And send update-set clause column list fields info 
  back to client. For DELETE, just validate where clause 
unknown's avatar
unknown committed
574 575 576
  and return no fields information back to client.
*/

577
static bool mysql_test_upd_fields(PREP_STMT *stmt, TABLE_LIST *table_list,
unknown's avatar
unknown committed
578
				  List<Item> &fields, List<Item> &values,
unknown's avatar
unknown committed
579
				  COND *conds)
unknown's avatar
unknown committed
580
{
581
  THD *thd= stmt->thd;
unknown's avatar
unknown committed
582 583
  DBUG_ENTER("mysql_test_upd_fields");

584 585 586 587
  if (check_access(thd,UPDATE_ACL,table_list->db,
                   &table_list->grant.privilege) || 
      (grant_option && check_grant(thd,UPDATE_ACL,table_list)) || 
      open_and_lock_tables(thd, table_list))
unknown's avatar
unknown committed
588 589
    DBUG_RETURN(1);

590 591
  if (setup_tables(table_list) ||
      setup_fields(thd, 0, table_list, fields, 1, 0, 0) || 
unknown's avatar
unknown committed
592
      setup_conds(thd, table_list, &conds) || thd->net.report_error)      
unknown's avatar
unknown committed
593 594 595 596 597 598
    DBUG_RETURN(1);

  /* 
     Currently return only column list info only, and we are not
     sending any info on where clause.
  */
599
  if (send_prep_stmt(stmt, 0) || send_item_params(stmt))
unknown's avatar
unknown committed
600 601 602 603 604 605 606 607 608
    DBUG_RETURN(1);
  DBUG_RETURN(0);
}

/*
  Validate the following information:                         

    SELECT - column list 
           - where clause
609
           - order clause
unknown's avatar
unknown committed
610 611 612 613 614 615
           - having clause
           - group by clause
           - if no column spec i.e. '*', then setup all fields
                                                           
  And send column list fields info back to client. 
*/
616
static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
617
				     uint wild_num,
unknown's avatar
unknown committed
618
                                     List<Item> &fields, COND *conds, 
619
                                     uint og_num, ORDER *order, ORDER *group,
unknown's avatar
unknown committed
620 621 622 623
                                     Item *having, ORDER *proc,
                                     ulong select_options, 
                                     SELECT_LEX_UNIT *unit,
                                     SELECT_LEX *select_lex)
unknown's avatar
unknown committed
624
{
625
  THD *thd= stmt->thd;
unknown's avatar
unknown committed
626 627
  LEX *lex= &thd->lex;
  select_result *result= thd->lex.result;
unknown's avatar
unknown committed
628 629
  DBUG_ENTER("mysql_test_select_fields");

630 631 632 633 634 635 636 637 638
  ulong privilege= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL;
  if (tables)
  {
    if (check_table_access(thd, privilege, tables))
      DBUG_RETURN(1);
  }
  else if (check_access(thd, privilege, "*any*"))
    DBUG_RETURN(1);

unknown's avatar
unknown committed
639
  if ((&lex->select_lex != lex->all_selects_list &&
640
       lex->unit.create_total_list(thd, lex, &tables, 0)))
unknown's avatar
unknown committed
641 642
   DBUG_RETURN(1);
    
unknown's avatar
unknown committed
643
  if (open_and_lock_tables(thd, tables))
unknown's avatar
unknown committed
644 645
    DBUG_RETURN(1);

646
  if (lex->describe)
unknown's avatar
unknown committed
647
  {
648 649 650 651 652 653 654 655 656 657 658 659 660
    if (send_prep_stmt(stmt, 0) ||  send_item_params(stmt))
      DBUG_RETURN(1);      
  }   
  else 
  {
    fix_tables_pointers(thd->lex.all_selects_list);
    if (!result && !(result= new select_send()))
    {
      delete select_lex->having;
      delete select_lex->where;
      send_error(thd, ER_OUT_OF_RESOURCES);
      DBUG_RETURN(1);
    }
unknown's avatar
unknown committed
661

662 663
    JOIN *join= new JOIN(thd, fields, select_options, result);
    thd->used_tables= 0;	// Updated by setup_fields  
unknown's avatar
unknown committed
664

665 666
  if (join->prepare(&select_lex->ref_pointer_array, tables, 
		    wild_num, conds, og_num, order, group, having, proc, 
667
                    select_lex, unit, 0))
unknown's avatar
unknown committed
668
    DBUG_RETURN(1);
669
#ifndef EMBEDDED_LIBRARY
670 671
    if (send_prep_stmt(stmt, fields.elements) ||
        thd->protocol_simple.send_fields(&fields, 0) ||
672
        net_flush(&thd->net) ||
673 674
        send_item_params(stmt))
      DBUG_RETURN(1);
675
#endif
676
    join->cleanup();
677
  }
unknown's avatar
unknown committed
678 679 680
  DBUG_RETURN(0);  
}

681

unknown's avatar
unknown committed
682 683 684 685
/*
  Send the prepare query results back to client              
*/
                     
686
static bool send_prepare_results(PREP_STMT *stmt)     
unknown's avatar
unknown committed
687
{   
688 689
  THD *thd= stmt->thd;
  LEX *lex= &thd->lex;
690
  enum enum_sql_command sql_command= thd->lex.sql_command;
691 692 693
  DBUG_ENTER("send_prepare_results");
  DBUG_PRINT("enter",("command: %d, param_count: %ld",
                      sql_command, lex->param_count));
unknown's avatar
unknown committed
694
  
695 696 697 698 699
  /* Setup prepared stmt */
  stmt->param_count= lex->param_count;
  stmt->free_list= thd->free_list;		// Save items used in stmt
  thd->free_list= 0;

700
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
unknown committed
701 702
  TABLE_LIST *tables=(TABLE_LIST*) select_lex->table_list.first;
  
703
  switch (sql_command) {
unknown's avatar
unknown committed
704 705

  case SQLCOM_INSERT:
706
    if (mysql_test_insert_fields(stmt, tables, lex->field_list,
unknown's avatar
unknown committed
707
				 lex->many_values))
unknown's avatar
unknown committed
708 709 710 711
      goto abort;    
    break;

  case SQLCOM_UPDATE:
712
    if (mysql_test_upd_fields(stmt, tables, select_lex->item_list,
unknown's avatar
unknown committed
713
			      lex->value_list, select_lex->where))
unknown's avatar
unknown committed
714 715 716 717
      goto abort;
    break;

  case SQLCOM_DELETE:
718
    if (mysql_test_upd_fields(stmt, tables, select_lex->item_list,
unknown's avatar
unknown committed
719
			      lex->value_list, select_lex->where))
unknown's avatar
unknown committed
720 721 722 723
      goto abort;
    break;

  case SQLCOM_SELECT:
724
    if (mysql_test_select_fields(stmt, tables, select_lex->with_wild,
unknown's avatar
unknown committed
725 726
                                 select_lex->item_list,
                                 select_lex->where,
727 728
				 select_lex->order_list.elements +
				 select_lex->group_list.elements,
unknown's avatar
unknown committed
729 730 731 732 733 734
                                 (ORDER*) select_lex->order_list.first,
                                 (ORDER*) select_lex->group_list.first, 
                                 select_lex->having,
                                 (ORDER*)lex->proc_list.first,
                                 select_lex->options | thd->options,
                                 &(lex->unit), select_lex))
unknown's avatar
unknown committed
735 736 737 738 739 740 741 742 743
      goto abort;
    break;

  default:
    {
      /* 
         Rest fall through to default category, no parsing 
         for non-DML statements 
      */
unknown's avatar
unknown committed
744 745
      if (send_prep_stmt(stmt, 0))
        goto abort;
unknown's avatar
unknown committed
746 747
    }
  }
748
  DBUG_RETURN(0);
unknown's avatar
unknown committed
749 750

abort:
751 752
  send_error(thd,thd->killed ? ER_SERVER_SHUTDOWN : 0);
  DBUG_RETURN(1);
unknown's avatar
unknown committed
753 754 755 756 757 758
}

/*
  Parse the prepare query                                    
*/

759
static bool parse_prepare_query(PREP_STMT *stmt,
unknown's avatar
unknown committed
760
		char *packet, uint length)
unknown's avatar
unknown committed
761
{
762 763 764
  bool error= 1;
  THD *thd= stmt->thd;
  DBUG_ENTER("parse_prepare_query");
unknown's avatar
unknown committed
765 766 767

  mysql_log.write(thd,COM_PREPARE,"%s",packet);       
  mysql_init_query(thd);   
768
  LEX *lex=lex_start(thd, (uchar*) packet, length);
769
  lex->safe_to_cache_query= 0;
770 771
  thd->prepare_command= TRUE; 
  thd->lex.param_count= 0;
772
  if (!yyparse((void *)thd) && !thd->is_fatal_error) 
773 774 775
    error= send_prepare_results(stmt);
  lex_end(lex);
  DBUG_RETURN(error);
unknown's avatar
unknown committed
776 777
}

unknown's avatar
unknown committed
778 779 780
/*
  Initialize parameter items in statement
*/
unknown's avatar
unknown committed
781

782
static bool init_param_items(PREP_STMT *stmt)
unknown's avatar
unknown committed
783
{
784 785
  THD *thd= stmt->thd;
  List<Item> &params= thd->lex.param_list;
unknown's avatar
unknown committed
786
  Item_param **to;
787
  uint32 length= thd->query_length;
788
 
789 790 791 792 793 794 795 796 797 798
  stmt->lex=  thd->lex;

  if (mysql_bin_log.is_open() || mysql_update_log.is_open())
  {
    stmt->log_full_query= 1;
    stmt->setup_params= insert_params_withlog;
  }
  else
    stmt->setup_params= insert_params; // not fully qualified query
   
799 800 801
  if (!stmt->param_count)
    stmt->param= (Item_param **)0;
  else
802
  {    
803 804 805 806
    if (!(stmt->param= to= (Item_param **)
          my_malloc(sizeof(Item_param *)*(stmt->param_count+1), 
                    MYF(MY_WME))))
      return 1;
807 808 809 810 811 812 813 814

    if (stmt->log_full_query)
    {
      length= thd->query_length+(stmt->param_count*2)+1;
 
      if ( length < STMT_QUERY_LOG_LENGTH ) 
        length= STMT_QUERY_LOG_LENGTH;
    }
815 816
    List_iterator<Item> param_iterator(params);
    while ((*(to++)= (Item_param *)param_iterator++));
817 818 819
  }  
  stmt->query= new String(length);
  stmt->query->copy(thd->query, thd->query_length, default_charset_info);
unknown's avatar
unknown committed
820
  return 0;
unknown's avatar
unknown committed
821
}
822

823 824 825 826 827 828 829
/*
  Initialize stmt execution
*/

static void init_stmt_execute(PREP_STMT *stmt)
{
  THD *thd= stmt->thd;
830
  TABLE_LIST *tables= (TABLE_LIST*) thd->lex.select_lex.table_list.first;
831 832 833 834 835
  
  /*
  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.
836 837
  */  
  for (; tables ; tables= tables->next)
838
    tables->table= 0; //safety - nasty init
839 840 841 842 843 844
  
  if (!(stmt->log_full_query && stmt->param_count))
  {
    thd->query= stmt->query->c_ptr();
    thd->query_length= stmt->query->length();
  }
845 846
}

unknown's avatar
unknown committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860
/*
  Parse the query and send the total number of parameters 
  and resultset metadata information back to client (if any), 
  without executing the query i.e. with out any log/disk 
  writes. This will allow 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_list, so that a fast and direct         
  retrieveal can be made without going through all field     
  items.                                                     
*/

861
bool mysql_stmt_prepare(THD *thd, char *packet, uint packet_length)
unknown's avatar
unknown committed
862
{
863
  MEM_ROOT thd_root= thd->mem_root;
864 865
  PREP_STMT stmt;
  DBUG_ENTER("mysql_stmt_prepare");
unknown's avatar
unknown committed
866

867
  bzero((char*) &stmt, sizeof(stmt));
unknown's avatar
unknown committed
868
  
869 870
  stmt.stmt_id= ++thd->current_stmt_id;
  init_sql_alloc(&stmt.mem_root, 8192, 8192);
unknown's avatar
unknown committed
871 872 873
  
  stmt.thd= thd;
  stmt.thd->mem_root= stmt.mem_root;
874

unknown's avatar
unknown committed
875
  if (alloc_query(stmt.thd, packet, packet_length))
876
    goto err;
unknown's avatar
unknown committed
877

878 879
  if (parse_prepare_query(&stmt, thd->query, thd->query_length))
    goto err;
unknown's avatar
unknown committed
880 881

  if (!(specialflag & SPECIAL_NO_PRIOR))
unknown's avatar
unknown committed
882
    my_pthread_setprio(pthread_self(),WAIT_PRIOR);
883 884 885 886 887 888 889 890 891

  // save WHERE clause pointers to avoid damaging they by optimisation
  for (SELECT_LEX *sl= thd->lex.all_selects_list;
       sl;
       sl= sl->next_select_in_list())
  {
    sl->prep_where= sl->where;
  }

unknown's avatar
unknown committed
892
  
unknown's avatar
unknown committed
893
  if (init_param_items(&stmt))
unknown's avatar
unknown committed
894
    goto err;
895

unknown's avatar
unknown committed
896
  
897
  stmt.mem_root= stmt.thd->mem_root;
unknown's avatar
unknown committed
898
  tree_insert(&thd->prepared_statements, (void *)&stmt, 0, (void *)0);
899 900 901 902
  thd->mem_root= thd_root; // restore main mem_root
  DBUG_RETURN(0);

err:
unknown's avatar
unknown committed
903
  stmt.mem_root= stmt.thd->mem_root;  
904
  free_prep_stmt(&stmt, free_free, (void*) 0);
905
  thd->mem_root= thd_root;	// restore main mem_root
906
  DBUG_RETURN(1);
unknown's avatar
unknown committed
907 908 909 910 911 912 913 914 915 916 917
}


/*
  Executes previously prepared query

  If there is any parameters(thd->param_count), then replace 
  markers with the data supplied from client, and then       
  execute the query                                            
*/

918
void mysql_stmt_execute(THD *thd, char *packet)
unknown's avatar
unknown committed
919
{
920 921 922
  ulong stmt_id=     uint4korr(packet);
  PREP_STMT	*stmt;
  DBUG_ENTER("mysql_stmt_execute");
unknown's avatar
unknown committed
923

924 925 926 927 928 929 930 931 932
  if (!(stmt=find_prepared_statement(thd, stmt_id, "execute")))
  {
    send_error(thd);
    DBUG_VOID_RETURN;
  }

  /* Check if we got an error when sending long data */
  if (stmt->error_in_prepare)
  {
unknown's avatar
unknown committed
933
    send_error(thd, stmt->last_errno, stmt->last_error);
934 935 936
    DBUG_VOID_RETURN;
  }

937 938
  LEX thd_lex= thd->lex;
  thd->lex= stmt->lex;
939 940 941 942 943 944 945 946
  
  for (SELECT_LEX *sl= stmt->lex.all_selects_list;
       sl;
       sl= sl->next_select_in_list())
  {
    // copy WHERE clause pointers to avoid damaging they by optimisation
    if (sl->prep_where)
      sl->where= sl->prep_where->copy_andor_structure(thd);
947
    DBUG_ASSERT(sl->join == 0);
948
  }
949 950
  init_stmt_execute(stmt);

unknown's avatar
unknown committed
951
  if (stmt->param_count && setup_params_data(stmt))
unknown's avatar
unknown committed
952
    DBUG_VOID_RETURN;
953

unknown's avatar
unknown committed
954 955 956
  if (!(specialflag & SPECIAL_NO_PRIOR))
    my_pthread_setprio(pthread_self(),QUERY_PRIOR);  
 
957 958
  /*
    TODO:
unknown's avatar
unknown committed
959 960 961 962
    Also, have checks on basic executions such as mysql_insert(), 
    mysql_delete(), mysql_update() and mysql_select() to not to 
    have re-check on setup_* and other things ..
  */  
963 964 965
  thd->protocol= &thd->protocol_prep;		// Switch to binary protocol
  mysql_execute_command(thd);
  thd->protocol= &thd->protocol_simple;	// Use normal protocol
unknown's avatar
unknown committed
966

unknown's avatar
unknown committed
967
  if (!(specialflag & SPECIAL_NO_PRIOR))
968
    my_pthread_setprio(pthread_self(), WAIT_PRIOR);
unknown's avatar
unknown committed
969

970
  thd->lex= thd_lex;
unknown's avatar
unknown committed
971 972 973
  DBUG_VOID_RETURN;
}

974

unknown's avatar
unknown committed
975
/*
976 977 978 979 980 981 982 983 984 985 986
  Reset a prepared statement
  
  SYNOPSIS
    mysql_stmt_reset()
    thd		Thread handle
    packet	Packet with stmt handle

  DESCRIPTION
    This function is useful when one gets an error after calling
    mysql_stmt_getlongdata() and one wants to reset the handle
    so that one can call execute again.
unknown's avatar
unknown committed
987 988
*/

989
void mysql_stmt_reset(THD *thd, char *packet)
unknown's avatar
unknown committed
990
{
991 992 993
  ulong stmt_id= uint4korr(packet);
  PREP_STMT *stmt;
  DBUG_ENTER("mysql_stmt_reset");
unknown's avatar
unknown committed
994

995
  if (!(stmt= find_prepared_statement(thd, stmt_id, "reset")))
996 997 998 999 1000
  {
    send_error(thd);
    DBUG_VOID_RETURN;
  }

unknown's avatar
unknown committed
1001 1002
  stmt->error_in_prepare= 0;
  Item_param *item= *stmt->param, *end= item + stmt->param_count;
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

  /* Free long data if used */
  if (stmt->long_data_used)
  {
    stmt->long_data_used= 0;
    for (; item < end ; item++)
      item->reset();
  }
  DBUG_VOID_RETURN;
}


/*
  Delete a prepared statement from memory
*/

unknown's avatar
unknown committed
1019
void mysql_stmt_free(THD *thd, char *packet)
1020 1021 1022
{
  ulong stmt_id= uint4korr(packet);
  PREP_STMT *stmt;
unknown's avatar
unknown committed
1023
  DBUG_ENTER("mysql_stmt_free");
1024 1025 1026

  if (!(stmt=find_prepared_statement(thd, stmt_id, "close")))
  {
unknown's avatar
unknown committed
1027
    send_error(thd); // Not seen by the client
1028 1029
    DBUG_VOID_RETURN;
  }
1030 1031
  tree_delete(&thd->prepared_statements, (void*) &stmt_id, (void *)0);
  thd->last_prepared_stmt= (PREP_STMT *)0;
unknown's avatar
unknown committed
1032 1033 1034
  DBUG_VOID_RETURN;
}

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

/*
  Long data in pieces from client                            

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

void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length)
{
  PREP_STMT *stmt;
  DBUG_ENTER("mysql_stmt_get_longdata");

  /* The following should never happen */
unknown's avatar
unknown committed
1061
  if (packet_length < MYSQL_LONG_DATA_HEADER+1)
1062 1063 1064 1065 1066 1067 1068
  {
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "get_longdata");
    DBUG_VOID_RETURN;
  }

  ulong stmt_id=     uint4korr(pos);
  uint param_number= uint2korr(pos+4);
unknown's avatar
unknown committed
1069
  pos+= MYSQL_LONG_DATA_HEADER;	// Point to data
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082

  if (!(stmt=find_prepared_statement(thd, stmt_id, "get_longdata")))
  {
    /*
      There is a chance that the client will never see this as
      it doesn't expect an answer from this call...
    */
    send_error(thd);
    DBUG_VOID_RETURN;
  }

  if (param_number >= stmt->param_count)
  {
unknown's avatar
unknown committed
1083 1084 1085
    /* Error will be sent in execute call */
    stmt->error_in_prepare= 1;
    stmt->last_errno= ER_WRONG_ARGUMENTS;
1086 1087 1088
    sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS), "get_longdata");
    DBUG_VOID_RETURN;
  }
unknown's avatar
unknown committed
1089 1090
  Item_param *param= *(stmt->param+param_number);
  param->set_longdata(pos, packet_length-MYSQL_LONG_DATA_HEADER-1);
1091 1092 1093
  stmt->long_data_used= 1;
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
1094