summaryrefslogtreecommitdiff
path: root/sql/sql_prepare.cc
blob: 8e0c031065e80f9a14d9797a7dbd7926b854a6b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
/* 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
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
*/

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

Prepare:

  - Server gets the query from client with command 'COM_PREPARE'; 
    in the following format:
    [COM_PREPARE:1] [query]
  - Parse the query and recognize any parameter markers '?' and 
    store its information list in lex->param_list
  - Allocate a new statement for this prepare; and keep this in 
    'thd->prepared_statements' pool.
  - Without executing the query, return back to client the total 
    number of parameters along with result-set metadata information
    (if any) in the following format:
    [STMT_ID:4][Columns:2][Param_count:2][Columns meta info][Params meta info]
     
Prepare-execute:

  - Server gets the command 'COM_EXECUTE' to execute the 
    previously prepared query. If there is any param markers; then client
    will send the data in the following format:    
    [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)
  - Replace the param items with this new data. If it is a first execute 
    or types altered by client; then setup the conversion routines.
  - Execute the query without re-parsing and send back the results 
    to client

Long data handling:

  - Server gets the long data in pieces with command type 'COM_LONG_DATA'.
  - The packet recieved will have the format as:
    [COM_LONG_DATA:1][STMT_ID:4][parameter_number:2][type:2][data]
  - Checks if the type is specified by client, and if yes reads the type, 
    and stores the data in that format.
  - It's up to the client to check for read data ended. The server doesn't
    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

***********************************************************************/

#include "mysql_priv.h"
#include "sql_acl.h"
#include "sql_select.h" // for JOIN
#include <assert.h> // for DEBUG_ASSERT()
#include <m_ctype.h>  // for isspace()

#define IS_PARAM_NULL(pos, param_no) pos[param_no/8] & (1 << param_no & 7)

extern int yyparse(void *thd);

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

int compare_prep_stmt(void *not_used, PREP_STMT *stmt, ulong *key)
{
  return (stmt->stmt_id == *key) ? 0 : (stmt->stmt_id < *key) ? -1 : 1;
}


/*
  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)
{   
  free_items(stmt->free_list);
  free_root(&stmt->mem_root, MYF(0));
}

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

static bool send_prep_stmt(PREP_STMT *stmt, uint columns)
{
  NET  *net=&stmt->thd->net;
  char buff[8];
  int4store(buff, stmt->stmt_id);
  int2store(buff+4, columns);
  int2store(buff+6, stmt->param_count);
  return (my_net_write(net, buff, sizeof(buff)) || net_flush(net));
}

/*
  Send information about all item parameters

  TODO: Not yet ready
*/

static bool send_item_params(PREP_STMT *stmt)
{
#if 0
  char buff[1];
  buff[0]=0;
  if (my_net_write(&stmt->thd->net, buff, sizeof(buff))) 
    return 1;
  send_eof(stmt->thd);
#endif
  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);
}
 /*
  Setup param conversion routines

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

static void setup_param_tiny(Item_param *param, uchar **pos)
{
  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;
}

static void setup_param_str(Item_param *param, uchar **pos)
{
  ulong len=get_param_length(pos);
  param->set_value((const char *)*pos, len);
  *pos+=len;        
}

static void setup_param_functions(Item_param *param, uchar param_type)
{
  switch (param_type) {
  case FIELD_TYPE_TINY:
    param->setup_param_func= setup_param_tiny;
    param->item_result_type = INT_RESULT;
    break;
  case FIELD_TYPE_SHORT:
    param->setup_param_func= setup_param_short;
    param->item_result_type = INT_RESULT;
    break;
  case FIELD_TYPE_LONG:
    param->setup_param_func= setup_param_int32;
    param->item_result_type = INT_RESULT;
    break;
  case FIELD_TYPE_LONGLONG:
    param->setup_param_func= setup_param_int64;
    param->item_result_type = INT_RESULT;
    break;
  case FIELD_TYPE_FLOAT:
    param->setup_param_func= setup_param_float;
    param->item_result_type = REAL_RESULT;
    break;
  case FIELD_TYPE_DOUBLE:
    param->setup_param_func= setup_param_double;
    param->item_result_type = REAL_RESULT;
    break;
  default:
    param->setup_param_func= setup_param_str;
    param->item_result_type = STRING_RESULT;
  }
}

/*
  Update the parameter markers by reading the data           
  from client ..                                             
*/

static bool setup_params_data(PREP_STMT *stmt)
{                                       
  THD *thd= stmt->thd;
  List<Item> &params= thd->lex.param_list;
  List_iterator<Item> param_iterator(params);
  Item_param *param;
  DBUG_ENTER("setup_params_data");

  uchar *pos=(uchar*) thd->net.read_pos+1+MYSQL_STMT_HEADER; //skip header
  uchar *read_pos= pos+(stmt->param_count+7) / 8; //skip null bits   

  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++))
    {       
      setup_param_functions(param,*read_pos);
      read_pos+= 2;
    }
    param_iterator.rewind();
  }    
  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);
}

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

static bool mysql_test_insert_fields(PREP_STMT *stmt,
				     TABLE_LIST *table_list,
				     List<Item> &fields, 
				     List<List_item> &values_list)
{
  THD *thd= stmt->thd;
  TABLE *table;
  List_iterator_fast<List_item> its(values_list);
  List_item *values;
  DBUG_ENTER("mysql_test_insert_fields");

  if (!(table = open_ltable(thd,table_list,table_list->lock_type)))
    DBUG_RETURN(1);

  if ((values= its++))
  {
    uint value_count;
    ulong counter= 0;
    
    if (check_insert_fields(thd,table,fields,*values,1))
      DBUG_RETURN(1);

    value_count= values->elements;
    its.rewind();
   
    while ((values= its++))
    {
      counter++;
      if (values->elements != value_count)
      {
        my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
			ER(ER_WRONG_VALUE_COUNT_ON_ROW),
			MYF(0), counter);
        DBUG_RETURN(1);
      }
    }
  }
  if (send_prep_stmt(stmt, 0) || send_item_params(stmt))
    DBUG_RETURN(1);
  DBUG_RETURN(0);
}


/*
  Validate the following information                         
    UPDATE - set and where clause    DELETE - where clause                                             
                                                             
  And send update-set clause column list fields info 
  back to client. For DELETE, just validate where clause 
  and return no fields information back to client.
*/

static bool mysql_test_upd_fields(PREP_STMT *stmt, TABLE_LIST *table_list,
				  List<Item> &fields, List<Item> &values,
				  COND *conds)
{
  THD *thd= stmt->thd;
  DBUG_ENTER("mysql_test_upd_fields");

  if (open_and_lock_tables(thd, table_list))
    DBUG_RETURN(1);

  if (setup_tables(table_list) || setup_fields(thd,table_list,fields,1,0,0) || 
      setup_conds(thd,table_list,&conds) || thd->net.report_error)      
    DBUG_RETURN(1);

  /* 
     Currently return only column list info only, and we are not
     sending any info on where clause.
  */
  if (send_prep_stmt(stmt, 0) || send_item_params(stmt))
    DBUG_RETURN(1);
  DBUG_RETURN(0);
}

/*
  Validate the following information:                         

    SELECT - column list 
           - where clause
           - order clause
           - having clause
           - group by clause
           - if no column spec i.e. '*', then setup all fields
                                                           
  And send column list fields info back to client. 
*/
static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
                                     List<Item> &fields, COND *conds, 
                                     ORDER *order, ORDER *group,
                                     Item *having, ORDER *proc,
                                     ulong select_options, 
                                     SELECT_LEX_UNIT *unit,
                                     SELECT_LEX *select_lex)
{
  THD *thd= stmt->thd;
  LEX *lex= &thd->lex;
  select_result *result= thd->lex.result;
  DBUG_ENTER("mysql_test_select_fields");

  if ((&lex->select_lex != lex->all_selects_list &&
       lex->unit.create_total_list(thd, lex, &tables)))
   DBUG_RETURN(1);
    
  if (open_and_lock_tables(thd, tables))
    DBUG_RETURN(1);
  
  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);
  }

  JOIN *join= new JOIN(thd, fields, select_options, result);
  thd->used_tables= 0;	// Updated by setup_fields  

  if (join->prepare(tables, conds, order, group, having, proc, 
                    select_lex, unit, 0))
    DBUG_RETURN(1);

  /* 
     Currently return only column list info only, and we are not
     sending any info on where clause.
  */
  if (send_prep_stmt(stmt, fields.elements) ||
      thd->protocol_simple.send_fields(&fields, 0) ||
      send_item_params(stmt))
    DBUG_RETURN(1);
  join->cleanup(thd);
  DBUG_RETURN(0);  
}


/*
  Send the prepare query results back to client              
*/
                     
static bool send_prepare_results(PREP_STMT *stmt)     
{   
  THD *thd= stmt->thd;
  LEX *lex= &thd->lex;
  enum enum_sql_command sql_command = thd->lex.sql_command;
  DBUG_ENTER("send_prepare_results");
  DBUG_PRINT("enter",("command: %d, param_count: %ld",
                      sql_command, lex->param_count));
  
  /* Setup prepared stmt */
  stmt->param_count= lex->param_count;
  stmt->free_list= thd->free_list;		// Save items used in stmt
  thd->free_list= 0;

  SELECT_LEX *select_lex = &lex->select_lex;
  TABLE_LIST *tables=(TABLE_LIST*) select_lex->table_list.first;
  
  switch (sql_command) {

  case SQLCOM_INSERT:
    if (mysql_test_insert_fields(stmt, tables, lex->field_list,
				 lex->many_values))
      goto abort;    
    break;

  case SQLCOM_UPDATE:
    if (mysql_test_upd_fields(stmt, tables, select_lex->item_list,
			      lex->value_list, select_lex->where))
      goto abort;
    break;

  case SQLCOM_DELETE:
    if (mysql_test_upd_fields(stmt, tables, select_lex->item_list,
			      lex->value_list, select_lex->where))
      goto abort;
    break;

  case SQLCOM_SELECT:
    if (mysql_test_select_fields(stmt, tables, 
                                 select_lex->item_list,
                                 select_lex->where,
                                 (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))
      goto abort;
    break;

  default:
    {
      /* 
         Rest fall through to default category, no parsing 
         for non-DML statements 
      */
      if (send_prep_stmt(stmt, 0))
        goto abort;
    }
  }
  DBUG_RETURN(0);

abort:
  send_error(thd,thd->killed ? ER_SERVER_SHUTDOWN : 0);
  DBUG_RETURN(1);
}

/*
  Parse the prepare query                                    
*/

static bool parse_prepare_query(PREP_STMT *stmt,
		char *packet, uint length)
{
  bool error= 1;
  THD *thd= stmt->thd;
  DBUG_ENTER("parse_prepare_query");

  mysql_log.write(thd,COM_PREPARE,"%s",packet);       
  mysql_init_query(thd);   
  thd->prepare_command=true; 
  thd->lex.param_count= 0;

  LEX *lex=lex_start(thd, (uchar*) packet, length);
  lex->safe_to_cache_query= 0;
  if (!yyparse((void *)thd) && !thd->fatal_error) 
    error= send_prepare_results(stmt);
  lex_end(lex);
  DBUG_RETURN(error);
}

/*
  Initialize parameter items in statement
*/

static bool init_param_items(PREP_STMT *stmt)
{
  List<Item> &params= stmt->thd->lex.param_list;
  Item_param **to;
  
  if (!(stmt->param= to= (Item_param **)
        my_malloc(sizeof(Item_param *)*(stmt->param_count+1), 
                  MYF(MY_WME))))
    return 1;
  List_iterator<Item> param_iterator(params);
  while ((*(to++) = (Item_param *)param_iterator++));
  return 0;
}

/*
  Initialize stmt execution
*/

static void init_stmt_execute(PREP_STMT *stmt)
{
  THD *thd= stmt->thd;
  TABLE_LIST *tables=(TABLE_LIST*) thd->lex.select_lex.table_list.first;
  
  /*
  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.
  */
  if (tables)
    tables->table=0; //safety - nasty init
}

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

bool mysql_stmt_prepare(THD *thd, char *packet, uint packet_length)
{
  MEM_ROOT thd_root = thd->mem_root;
  PREP_STMT stmt;
  DBUG_ENTER("mysql_stmt_prepare");

  bzero((char*) &stmt, sizeof(stmt));
  
  stmt.stmt_id= ++thd->current_stmt_id;
  init_sql_alloc(&stmt.mem_root, 8192, 8192);
  
  stmt.thd= thd;
  stmt.thd->mem_root= stmt.mem_root;

  if (alloc_query(stmt.thd, packet, packet_length))
    goto err;

  if (parse_prepare_query(&stmt, thd->query, thd->query_length))
    goto err;

  if (!(specialflag & SPECIAL_NO_PRIOR))
    my_pthread_setprio(pthread_self(),WAIT_PRIOR);
  
  if (init_param_items(&stmt))
    goto err;
  
  stmt.mem_root= stmt.thd->mem_root;  
  tree_insert(&thd->prepared_statements, (void *)&stmt, 0, (void *)0);
  thd->mem_root= thd_root; // restore main mem_root
  DBUG_RETURN(0);

err:
  stmt.mem_root= stmt.thd->mem_root;  
  free_prep_stmt(&stmt, free_free, (void*) 0);
  thd->mem_root = thd_root;	// restore main mem_root
  DBUG_RETURN(1);
}


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

void mysql_stmt_execute(THD *thd, char *packet)
{
  ulong stmt_id=     uint4korr(packet);
  PREP_STMT	*stmt;
  DBUG_ENTER("mysql_stmt_execute");

  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)
  {
    send_error(thd, stmt->last_errno, stmt->last_error);
    DBUG_VOID_RETURN;
  }

  if (my_pthread_setspecific_ptr(THR_THD, stmt->thd) ||
      my_pthread_setspecific_ptr(THR_MALLOC, &stmt->thd->mem_root))
    DBUG_VOID_RETURN;

  init_stmt_execute(stmt);

  if (stmt->param_count && setup_params_data(stmt))
    DBUG_VOID_RETURN;

  if (!(specialflag & SPECIAL_NO_PRIOR))
    my_pthread_setprio(pthread_self(),QUERY_PRIOR);  
 
  /*
    TODO:
    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 ..
  */  
  THD *cur_thd= stmt->thd;
  cur_thd->protocol= &cur_thd->protocol_prep;		// Switch to binary protocol
  mysql_execute_command(cur_thd);
  cur_thd->protocol= &cur_thd->protocol_simple;	// Use normal protocol

  if (!(specialflag & SPECIAL_NO_PRIOR))
    my_pthread_setprio(pthread_self(), WAIT_PRIOR);

  my_pthread_setspecific_ptr(THR_THD, thd);
  my_pthread_setspecific_ptr(THR_MALLOC, &thd->mem_root);

  DBUG_VOID_RETURN;
}


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

void mysql_stmt_reset(THD *thd, char *packet)
{
  ulong stmt_id= uint4korr(packet);
  PREP_STMT *stmt;
  DBUG_ENTER("mysql_stmt_reset");

  if (!(stmt=find_prepared_statement(thd, stmt_id, "close")))
  {
    send_error(thd);
    DBUG_VOID_RETURN;
  }

  stmt->error_in_prepare= 0;
  Item_param *item= *stmt->param, *end= item + stmt->param_count;

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

void mysql_stmt_free(THD *thd, char *packet)
{
  ulong stmt_id= uint4korr(packet);
  PREP_STMT *stmt;
  DBUG_ENTER("mysql_stmt_free");

  if (!(stmt=find_prepared_statement(thd, stmt_id, "close")))
  {
    send_error(thd); // Not seen by the client
    DBUG_VOID_RETURN;
  }
  my_free((char *)stmt->param, MYF(MY_ALLOW_ZERO_PTR));
  tree_delete(&thd->prepared_statements, (void*) &stmt, (void *)0);
  thd->last_prepared_stmt=0;
  DBUG_VOID_RETURN;
}


/*
  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 */
  if (packet_length < MYSQL_LONG_DATA_HEADER+1)
  {
    my_error(ER_WRONG_ARGUMENTS, MYF(0), "get_longdata");
    DBUG_VOID_RETURN;
  }

  ulong stmt_id=     uint4korr(pos);
  uint param_number= uint2korr(pos+4);
  pos+= MYSQL_LONG_DATA_HEADER;	// Point to data

  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)
  {
    /* Error will be sent in execute call */
    stmt->error_in_prepare= 1;
    stmt->last_errno= ER_WRONG_ARGUMENTS;
    sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS), "get_longdata");
    DBUG_VOID_RETURN;
  }
  Item_param *param= *(stmt->param+param_number);
  param->set_longdata(pos, packet_length-MYSQL_LONG_DATA_HEADER-1);
  stmt->long_data_used= 1;
  DBUG_VOID_RETURN;
}