protocol.cc 29.8 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2003 MySQL AB
2 3 4

   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
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

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

/*
  Low level functions for storing data to be send to the MySQL client
  The actual communction is handled by the net_xxx functions in net_serv.cc
*/

21
#ifdef USE_PRAGMA_IMPLEMENTATION
22 23 24 25
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
26
#include "sp_rcontext.h"
27 28
#include <stdarg.h>

29
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024;
30
void net_send_error_packet(THD *thd, uint sql_errno, const char *err);
31 32 33
#ifndef EMBEDDED_LIBRARY
static void write_eof_packet(THD *thd, NET *net);
#endif
34

unknown's avatar
SCRUM  
unknown committed
35
#ifndef EMBEDDED_LIBRARY
36
bool Protocol::net_store_data(const uchar *from, size_t length)
unknown's avatar
SCRUM  
unknown committed
37
#else
38
bool Protocol_binary::net_store_data(const uchar *from, size_t length)
unknown's avatar
SCRUM  
unknown committed
39
#endif
unknown's avatar
SCRUM  
unknown committed
40 41
{
  ulong packet_length=packet->length();
unknown's avatar
unknown committed
42 43 44 45 46 47
  /* 
     The +9 comes from that strings of length longer than 16M require
     9 bytes to be stored (see net_store_length).
  */
  if (packet_length+9+length > packet->alloced_length() &&
      packet->realloc(packet_length+9+length))
unknown's avatar
SCRUM  
unknown committed
48
    return 1;
49
  uchar *to= net_store_length((uchar*) packet->ptr()+packet_length, length);
unknown's avatar
SCRUM  
unknown committed
50
  memcpy(to,from,length);
51
  packet->length((uint) (to+length-(uchar*) packet->ptr()));
unknown's avatar
SCRUM  
unknown committed
52 53 54 55
  return 0;
}


56 57 58 59
/*
   Send a error string to client

   Design note:
60

61
   net_send_error is a low-level functions
62 63 64 65 66 67
   that shall be used only when a new connection is being
   established or at server startup.
   For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
   critical that every error that can be intercepted is issued in one
   place only, my_message_sql.
*/
68
void net_send_error(THD *thd, uint sql_errno, const char *err)
69 70
{
  NET *net= &thd->net;
unknown's avatar
unknown committed
71
  bool generate_warning= thd->killed != THD::KILL_CONNECTION;
72
  DBUG_ENTER("net_send_error");
73 74 75 76
  DBUG_PRINT("enter",("sql_errno: %d  err: %s", sql_errno,
		      err ? err : net->last_error[0] ?
		      net->last_error : "NULL"));

77 78
  DBUG_ASSERT(!thd->spcont);

79 80 81 82 83 84
  if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
  {
    thd->killed= THD::NOT_KILLED;
    thd->mysys_var->abort= 0;
  }

85 86 87
  if (net && net->no_send_error)
  {
    thd->clear_error();
88
    thd->is_fatal_error= 0;			// Error message is given
89 90 91
    DBUG_PRINT("info", ("sending error messages prohibited"));
    DBUG_VOID_RETURN;
  }
92

93
  thd->is_slave_error=  1; // needed to catch query errors during replication
94 95 96 97 98 99 100
  if (!err)
  {
    if (sql_errno)
      err=ER(sql_errno);
    else
    {
      if ((err=net->last_error)[0])
101
      {
102
	sql_errno=net->last_errno;
103 104
        generate_warning= 0;            // This warning has already been given
      }
105 106 107 108 109 110
      else
      {
	sql_errno=ER_UNKNOWN_ERROR;
	err=ER(sql_errno);	 /* purecov: inspected */
      }
    }
111 112 113 114 115 116
  }

  if (generate_warning)
  {
    /* Error that we have not got with my_error() */
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, sql_errno, err);
117
  }
unknown's avatar
unknown committed
118

119
  net_send_error_packet(thd, sql_errno, err);
120

121
  thd->is_fatal_error= 0;			// Error message is given
122
  thd->net.report_error= 0;
123 124

  /* Abort multi-result sets */
125
  thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
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
  DBUG_VOID_RETURN;
}


/*
  Return ok to the client.

  SYNOPSIS
    send_ok()
    thd			Thread handler
    affected_rows	Number of rows changed by statement
    id			Auto_increment id for first row (if used)
    message		Message to send to the client (Used by mysql_status)

  DESCRIPTION
    The ok packet has the following structure

    0			Marker (1 byte)
    affected_rows	Stored in 1-9 bytes
    id			Stored in 1-9 bytes
    server_status	Copy of thd->server_status;  Can be used by client
			to check if we are inside an transaction
			New in 4.0 protocol
    warning_count	Stored in 2 bytes; New in 4.1 protocol
    message		Stored as packed length (1-9 bytes) + message
			Is not stored if no message

   If net->no_send_ok return without sending packet
*/    

156
#ifndef EMBEDDED_LIBRARY
157 158 159 160
void
send_ok(THD *thd, ha_rows affected_rows, ulonglong id, const char *message)
{
  NET *net= &thd->net;
161
  uchar buff[MYSQL_ERRMSG_SIZE+10],*pos;
162
  DBUG_ENTER("send_ok");
163 164

  if (net->no_send_ok || !net->vio)	// hack for re-parsing queries
165 166 167 168
  {
    DBUG_PRINT("info", ("no send ok: %s, vio present: %s",
                        (net->no_send_ok ? "YES" : "NO"),
                        (net->vio ? "YES" : "NO")));
169
    DBUG_VOID_RETURN;
170
  }
171

172
  buff[0]=0;					// No fields
173 174
  pos=net_store_length(buff+1,affected_rows);
  pos=net_store_length(pos, id);
175 176
  if (thd->client_capabilities & CLIENT_PROTOCOL_41)
  {
177 178 179 180 181 182
    DBUG_PRINT("info",
	       ("affected_rows: %lu  id: %lu  status: %u  warning_count: %u",
		(ulong) affected_rows,		
		(ulong) id,
		(uint) (thd->server_status & 0xffff),
		(uint) thd->total_warn_count));
183 184 185 186 187 188 189 190 191 192 193 194 195 196
    int2store(pos,thd->server_status);
    pos+=2;

    /* We can only return up to 65535 warnings in two bytes */
    uint tmp= min(thd->total_warn_count, 65535);
    int2store(pos, tmp);
    pos+= 2;
  }
  else if (net->return_status)			// For 4.0 protocol
  {
    int2store(pos,thd->server_status);
    pos+=2;
  }
  if (message)
197 198
    pos= net_store_data(pos, (uchar*) message, strlen(message));
  VOID(my_net_write(net, buff, (size_t) (pos-buff)));
199
  VOID(net_flush(net));
unknown's avatar
unknown committed
200 201
  /* We can't anymore send an error to the client */
  thd->net.report_error= 0;
202
  thd->net.no_send_error= 1;
203
  DBUG_PRINT("info", ("OK sent, so no more error sending allowed"));
204

205 206 207
  DBUG_VOID_RETURN;
}

208
static uchar eof_buff[1]= { (uchar) 254 };      /* Marker for end of fields */
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

/*
  Send eof (= end of result set) to the client

  SYNOPSIS
    send_eof()
    thd			Thread handler
    no_flush		Set to 1 if there will be more data to the client,
			like in send_fields().

  DESCRIPTION
    The eof packet has the following structure

    254			Marker (1 byte)
    warning_count	Stored in 2 bytes; New in 4.1 protocol
    status_flag		Stored in 2 bytes;
225
			For flags like SERVER_MORE_RESULTS_EXISTS
226 227 228 229 230 231 232

    Note that the warning count will not be sent if 'no_flush' is set as
    we don't want to report the warning count until all data is sent to the
    client.
*/    

void
233
send_eof(THD *thd)
234 235 236
{
  NET *net= &thd->net;
  DBUG_ENTER("send_eof");
237
  if (net->vio != 0)
238
  {
239 240
    write_eof_packet(thd, net);
    VOID(net_flush(net));
241
    thd->net.no_send_error= 1;
242
    DBUG_PRINT("info", ("EOF sent, so no more error sending allowed"));
243 244 245
  }
  DBUG_VOID_RETURN;
}
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

/*
  Format EOF packet according to the current protocol and
  write it to the network output buffer.
*/

static void write_eof_packet(THD *thd, NET *net)
{
  if (thd->client_capabilities & CLIENT_PROTOCOL_41)
  {
    uchar buff[5];
    /*
      Don't send warn count during SP execution, as the warn_list
      is cleared between substatements, and mysqltest gets confused
    */
    uint tmp= (thd->spcont ? 0 : min(thd->total_warn_count, 65535));
    buff[0]= 254;
    int2store(buff+1, tmp);
    /*
      The following test should never be true, but it's better to do it
      because if 'is_fatal_error' is set the server is not going to execute
      other queries (see the if test in dispatch_command / COM_QUERY)
    */
    if (thd->is_fatal_error)
      thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
    int2store(buff+3, thd->server_status);
273
    VOID(my_net_write(net, buff, 5));
274 275 276 277 278
  }
  else
    VOID(my_net_write(net, eof_buff, 1));
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292
/*
    Please client to send scrambled_password in old format.
  SYNOPSYS
    send_old_password_request()
    thd thread handle
     
  RETURN VALUE
    0  ok
   !0  error
*/

bool send_old_password_request(THD *thd)
{
  NET *net= &thd->net;
293
  return my_net_write(net, eof_buff, 1) || net_flush(net);
294 295
}

296 297 298 299 300

void net_send_error_packet(THD *thd, uint sql_errno, const char *err)
{
  NET *net= &thd->net;
  uint length;
301
  uchar buff[MYSQL_ERRMSG_SIZE+2], *pos;
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

  DBUG_ENTER("send_error_packet");

  if (net->vio == 0)
  {
    if (thd->bootstrap)
    {
      /* In bootstrap it's ok to print on stderr */
      fprintf(stderr,"ERROR: %d  %s\n",sql_errno,err);
    }
    DBUG_VOID_RETURN;
  }

  if (net->return_errno)
  {				// new client code; Add errno before message
    int2store(buff,sql_errno);
    pos= buff+2;
    if (thd->client_capabilities & CLIENT_PROTOCOL_41)
    {
      /* The first # is to make the protocol backward compatible */
      buff[2]= '#';
323
      pos= (uchar*) strmov((char*) buff+3, mysql_errno_to_sqlstate(sql_errno));
324
    }
325 326 327
    length= (uint) (strmake((char*) pos, err, MYSQL_ERRMSG_SIZE-1) -
                    (char*) buff);
    err= (char*) buff;
328 329 330 331 332 333
  }
  else
  {
    length=(uint) strlen(err);
    set_if_smaller(length,MYSQL_ERRMSG_SIZE-1);
  }
334 335
  VOID(net_write_command(net,(uchar) 255, (uchar*) "", 0, (uchar*) err,
                         length));
336 337 338
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
339
#endif /* EMBEDDED_LIBRARY */
340 341

/*
342 343 344 345 346 347 348
  Faster net_store_length when we know that length is less than 65536.
  We keep a separate version for that range because it's widely used in
  libmysql.
  uint is used as agrument type because of MySQL type conventions:
  uint for 0..65536
  ulong for 0..4294967296
  ulonglong for bigger numbers.
349 350
*/

351
static uchar *net_store_length_fast(uchar *packet, uint length)
352 353 354 355
{
  if (length < 251)
  {
    *packet=(uchar) length;
356
    return packet+1;
357 358 359
  }
  *packet++=252;
  int2store(packet,(uint) length);
360
  return packet+2;
361 362 363 364 365 366 367 368 369 370
}


/****************************************************************************
  Functions used by the protocol functions (like send_ok) to store strings
  and numbers in the header result packet.
****************************************************************************/

/* The following will only be used for short strings < 65K */

371
uchar *net_store_data(uchar *to, const uchar *from, size_t length)
372
{
373
  to=net_store_length_fast(to,length);
374 375 376 377
  memcpy(to,from,length);
  return to+length;
}

378
uchar *net_store_data(uchar *to,int32 from)
379 380 381
{
  char buff[20];
  uint length=(uint) (int10_to_str(from,buff,10)-buff);
382
  to=net_store_length_fast(to,length);
383 384 385 386
  memcpy(to,buff,length);
  return to+length;
}

387
uchar *net_store_data(uchar *to,longlong from)
388 389 390
{
  char buff[22];
  uint length=(uint) (longlong10_to_str(from,buff,10)-buff);
391
  to=net_store_length_fast(to,length);
392 393 394 395 396 397 398 399 400 401 402 403 404
  memcpy(to,buff,length);
  return to+length;
}


/*****************************************************************************
  Default Protocol functions
*****************************************************************************/

void Protocol::init(THD *thd_arg)
{
  thd=thd_arg;
  packet= &thd->packet;
405
  convert= &thd->convert_buffer;
406
#ifndef DBUG_OFF
407 408 409 410
  field_types= 0;
#endif
}

411

412 413 414 415 416 417 418 419 420
bool Protocol::flush()
{
#ifndef EMBEDDED_LIBRARY
  return net_flush(&thd->net);
#else
  return 0;
#endif
}

421 422 423 424 425 426 427 428 429 430
/*
  Send name and type of result to client.

  SYNOPSIS
    send_fields()
    THD		Thread data object
    list	List of items to send to client
    flag	Bit mask with the following functions:
		1 send number of rows
		2 send default values
431
                4 don't write eof packet
432 433 434 435 436 437 438 439 440

  DESCRIPTION
    Sum fields has table name empty and field_name.

  RETURN VALUES
    0	ok
    1	Error  (Note that in this case the error is not sent to the client)
*/

unknown's avatar
unknown committed
441
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
442
bool Protocol::send_fields(List<Item> *list, uint flags)
443 444 445
{
  List_iterator_fast<Item> it(*list);
  Item *item;
446
  uchar buff[80];
unknown's avatar
unknown committed
447
  String tmp((char*) buff,sizeof(buff),&my_charset_bin);
unknown's avatar
unknown committed
448
  Protocol_text prot(thd);
449
  String *local_packet= prot.storage_packet();
450
  CHARSET_INFO *thd_charset= thd->variables.character_set_results;
451 452
  DBUG_ENTER("send_fields");

453
  if (flags & SEND_NUM_ROWS)
454
  {				// Packet with number of elements
455 456
    uchar *pos= net_store_length(buff, list->elements);
    (void) my_net_write(&thd->net, buff, (size_t) (pos-buff));
457 458
  }

459
#ifndef DBUG_OFF
460 461 462 463 464 465 466 467
  field_types= (enum_field_types*) thd->alloc(sizeof(field_types) *
					      list->elements);
  uint count= 0;
#endif

  while ((item=it++))
  {
    char *pos;
468
    CHARSET_INFO *cs= system_charset_info;
469 470
    Send_field field;
    item->make_field(&field);
471 472 473 474 475

    /* Keep things compatible for old clients */
    if (field.type == MYSQL_TYPE_VARCHAR)
      field.type= MYSQL_TYPE_VAR_STRING;

476 477 478 479
    prot.prepare_for_resend();

    if (thd->client_capabilities & CLIENT_PROTOCOL_41)
    {
480
      if (prot.store(STRING_WITH_LEN("def"), cs, thd_charset) ||
481 482
	  prot.store(field.db_name, (uint) strlen(field.db_name),
		     cs, thd_charset) ||
483
	  prot.store(field.table_name, (uint) strlen(field.table_name),
484
		     cs, thd_charset) ||
485
	  prot.store(field.org_table_name, (uint) strlen(field.org_table_name),
486
		     cs, thd_charset) ||
487
	  prot.store(field.col_name, (uint) strlen(field.col_name),
488
		     cs, thd_charset) ||
489
	  prot.store(field.org_col_name, (uint) strlen(field.org_col_name),
490
		     cs, thd_charset) ||
491
	  local_packet->realloc(local_packet->length()+12))
492
	goto err;
493
      /* Store fixed length fields */
494
      pos= (char*) local_packet->ptr()+local_packet->length();
495
      *pos++= 12;				// Length of packed fields
unknown's avatar
unknown committed
496
      if (item->collation.collation == &my_charset_bin || thd_charset == NULL)
497 498
      {
        /* No conversion */
unknown's avatar
unknown committed
499
        int2store(pos, field.charsetnr);
500 501
        int4store(pos+2, field.length);
      }
unknown's avatar
unknown committed
502
      else
503 504
      {
        /* With conversion */
505
        uint max_char_len;
506
        int2store(pos, thd_charset->number);
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        /*
          For TEXT/BLOB columns, field_length describes the maximum data
          length in bytes. There is no limit to the number of characters
          that a TEXT column can store, as long as the data fits into
          the designated space.
          For the rest of textual columns, field_length is evaluated as
          char_count * mbmaxlen, where character count is taken from the
          definition of the column. In other words, the maximum number
          of characters here is limited by the column definition.
        */
        max_char_len= (field.type >= (int) MYSQL_TYPE_TINY_BLOB &&
                      field.type <= (int) MYSQL_TYPE_BLOB) ?
                      field.length / item->collation.collation->mbminlen :
                      field.length / item->collation.collation->mbmaxlen;
        int4store(pos+2, max_char_len * thd_charset->mbmaxlen);
522
      }
523 524 525
      pos[6]= field.type;
      int2store(pos+7,field.flags);
      pos[9]= (char) field.decimals;
526
      pos[10]= 0;				// For the future
527 528
      pos[11]= 0;				// For the future
      pos+= 12;
529 530 531
    }
    else
    {
532
      if (prot.store(field.table_name, (uint) strlen(field.table_name),
533
		     cs, thd_charset) ||
534
	  prot.store(field.col_name, (uint) strlen(field.col_name),
535
		     cs, thd_charset) ||
536
	  local_packet->realloc(local_packet->length()+10))
537
	goto err;
538
      pos= (char*) local_packet->ptr()+local_packet->length();
539 540

#ifdef TO_BE_DELETED_IN_6
541 542 543 544 545 546 547 548 549 550 551 552
      if (!(thd->client_capabilities & CLIENT_LONG_FLAG))
      {
	pos[0]=3;
	int3store(pos+1,field.length);
	pos[4]=1;
	pos[5]=field.type;
	pos[6]=2;
	pos[7]= (char) field.flags;
	pos[8]= (char) field.decimals;
	pos+= 9;
      }
      else
553
#endif
554 555 556 557 558 559 560 561 562 563
      {
	pos[0]=3;
	int3store(pos+1,field.length);
	pos[4]=1;
	pos[5]=field.type;
	pos[6]=3;
	int2store(pos+7,field.flags);
	pos[9]= (char) field.decimals;
	pos+= 10;
      }
564
    }
565
    local_packet->length((uint) (pos - local_packet->ptr()));
566
    if (flags & SEND_DEFAULTS)
567 568 569
      item->send(&prot, &tmp);			// Send default value
    if (prot.write())
      break;					/* purecov: inspected */
570
#ifndef DBUG_OFF
571 572 573 574
    field_types[count++]= field.type;
#endif
  }

575
  if (flags & SEND_EOF)
576
    write_eof_packet(thd, &thd->net);
577 578 579
  DBUG_RETURN(prepare_for_send(list));

err:
unknown's avatar
unknown committed
580 581
  my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES),
             MYF(0));	/* purecov: inspected */
582 583 584
  DBUG_RETURN(1);				/* purecov: inspected */
}

585

586 587 588
bool Protocol::write()
{
  DBUG_ENTER("Protocol::write");
589 590
  DBUG_RETURN(my_net_write(&thd->net, (uchar*) packet->ptr(),
                           packet->length()));
591
}
unknown's avatar
SCRUM  
unknown committed
592 593 594
#endif /* EMBEDDED_LIBRARY */


595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
/*
  Send \0 end terminated string

  SYNOPSIS
    store()
    from	NullS or \0 terminated string

  NOTES
    In most cases one should use store(from, length) instead of this function

  RETURN VALUES
    0		ok
    1		error
*/

610
bool Protocol::store(const char *from, CHARSET_INFO *cs)
611 612 613 614
{
  if (!from)
    return store_null();
  uint length= strlen(from);
615
  return store(from, length, cs);
616 617 618 619 620 621 622 623 624 625
}


/*
  Send a set of strings as one long string with ',' in between
*/

bool Protocol::store(I_List<i_string>* str_list)
{
  char buf[256];
unknown's avatar
unknown committed
626
  String tmp(buf, sizeof(buf), &my_charset_bin);
627
  uint32 len;
628 629 630
  I_List_iterator<i_string> it(*str_list);
  i_string* s;

631
  tmp.length(0);
632 633 634
  while ((s=it++))
  {
    tmp.append(s->ptr);
635
    tmp.append(',');
636
  }
637 638
  if ((len= tmp.length()))
    len--;					// Remove last ','
639
  return store((char*) tmp.ptr(), len,  tmp.charset());
640 641 642 643 644 645 646 647 648 649 650
}


/****************************************************************************
  Functions to handle the simple (default) protocol where everything is
  This protocol is the one that is used by default between the MySQL server
  and client when you are not using prepared statements.

  All data are sent as 'packed-string-length' followed by 'string-data'
****************************************************************************/

unknown's avatar
SCRUM  
unknown committed
651
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
652
void Protocol_text::prepare_for_resend()
653 654
{
  packet->length(0);
655
#ifndef DBUG_OFF
656 657 658 659
  field_pos= 0;
#endif
}

unknown's avatar
unknown committed
660
bool Protocol_text::store_null()
661
{
662
#ifndef DBUG_OFF
663 664 665
  field_pos++;
#endif
  char buff[1];
unknown's avatar
unknown committed
666
  buff[0]= (char)251;
667
  return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
668
}
unknown's avatar
SCRUM  
unknown committed
669
#endif
670

671

672 673 674 675 676
/*
  Auxilary function to convert string to the given character set
  and store in network buffer.
*/

677
bool Protocol::store_string_aux(const char *from, size_t length,
678 679 680 681 682 683 684
                                CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
{
  /* 'tocs' is set 0 when client issues SET character_set_results=NULL */
  if (tocs && !my_charset_same(fromcs, tocs) &&
      fromcs != &my_charset_bin &&
      tocs != &my_charset_bin)
  {
685
    uint dummy_errors;
686 687
    return (convert->copy(from, length, fromcs, tocs, &dummy_errors) ||
            net_store_data((uchar*) convert->ptr(), convert->length()));
688
  }
689
  return net_store_data((uchar*) from, length);
690 691 692
}


693 694
bool Protocol_text::store(const char *from, size_t length,
                          CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
695
{
696
#ifndef DBUG_OFF
697
  DBUG_ASSERT(field_types == 0 ||
698
	      field_types[field_pos] == MYSQL_TYPE_DECIMAL ||
unknown's avatar
unknown committed
699
              field_types[field_pos] == MYSQL_TYPE_BIT ||
unknown's avatar
unknown committed
700
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL ||
701 702
	      (field_types[field_pos] >= MYSQL_TYPE_ENUM &&
	       field_types[field_pos] <= MYSQL_TYPE_GEOMETRY));
703 704
  field_pos++;
#endif
705
  return store_string_aux(from, length, fromcs, tocs);
706 707 708
}


709
bool Protocol_text::store(const char *from, size_t length,
710
                          CHARSET_INFO *fromcs)
711
{
712
  CHARSET_INFO *tocs= this->thd->variables.character_set_results;
713
#ifndef DBUG_OFF
714 715
  DBUG_ASSERT(field_types == 0 ||
	      field_types[field_pos] == MYSQL_TYPE_DECIMAL ||
unknown's avatar
unknown committed
716
              field_types[field_pos] == MYSQL_TYPE_BIT ||
unknown's avatar
unknown committed
717
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL ||
718
              field_types[field_pos] == MYSQL_TYPE_NEWDATE ||
719 720 721 722
	      (field_types[field_pos] >= MYSQL_TYPE_ENUM &&
	       field_types[field_pos] <= MYSQL_TYPE_GEOMETRY));
  field_pos++;
#endif
723
  return store_string_aux(from, length, fromcs, tocs);
724 725 726
}


unknown's avatar
unknown committed
727
bool Protocol_text::store_tiny(longlong from)
728
{
729
#ifndef DBUG_OFF
unknown's avatar
unknown committed
730 731
  DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_TINY);
  field_pos++;
732 733
#endif
  char buff[20];
734 735
  return net_store_data((uchar*) buff,
			(size_t) (int10_to_str((int) from, buff, -10) - buff));
736 737
}

738

unknown's avatar
unknown committed
739
bool Protocol_text::store_short(longlong from)
740
{
741
#ifndef DBUG_OFF
742
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
743
	      field_types[field_pos] == MYSQL_TYPE_YEAR ||
unknown's avatar
unknown committed
744 745
	      field_types[field_pos] == MYSQL_TYPE_SHORT);
  field_pos++;
746 747
#endif
  char buff[20];
748 749 750
  return net_store_data((uchar*) buff,
			(size_t) (int10_to_str((int) from, buff, -10) -
                                  buff));
751 752
}

753

unknown's avatar
unknown committed
754
bool Protocol_text::store_long(longlong from)
755
{
756
#ifndef DBUG_OFF
unknown's avatar
unknown committed
757 758 759 760
  DBUG_ASSERT(field_types == 0 ||
              field_types[field_pos] == MYSQL_TYPE_INT24 ||
              field_types[field_pos] == MYSQL_TYPE_LONG);
  field_pos++;
761 762
#endif
  char buff[20];
763 764 765
  return net_store_data((uchar*) buff,
			(size_t) (int10_to_str((long int)from, buff,
                                               (from <0)?-10:10)-buff));
766 767 768
}


unknown's avatar
unknown committed
769
bool Protocol_text::store_longlong(longlong from, bool unsigned_flag)
770
{
771
#ifndef DBUG_OFF
772
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
773 774
	      field_types[field_pos] == MYSQL_TYPE_LONGLONG);
  field_pos++;
775 776
#endif
  char buff[22];
777 778 779 780
  return net_store_data((uchar*) buff,
			(size_t) (longlong10_to_str(from,buff,
                                                    unsigned_flag ? 10 : -10)-
                                  buff));
781 782 783
}


unknown's avatar
unknown committed
784
bool Protocol_text::store_decimal(const my_decimal *d)
unknown's avatar
unknown committed
785
{
786
#ifndef DBUG_OFF
unknown's avatar
unknown committed
787 788 789 790
  DBUG_ASSERT(field_types == 0 ||
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL);
  field_pos++;
#endif
791 792 793
  char buff[DECIMAL_MAX_STR_LENGTH];
  String str(buff, sizeof(buff), &my_charset_bin);
  (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
794
  return net_store_data((uchar*) str.ptr(), str.length());
unknown's avatar
unknown committed
795 796 797
}


unknown's avatar
unknown committed
798
bool Protocol_text::store(float from, uint32 decimals, String *buffer)
799
{
800
#ifndef DBUG_OFF
801
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
802 803
	      field_types[field_pos] == MYSQL_TYPE_FLOAT);
  field_pos++;
804
#endif
805
  buffer->set_real((double) from, decimals, thd->charset());
806
  return net_store_data((uchar*) buffer->ptr(), buffer->length());
807 808
}

809

unknown's avatar
unknown committed
810
bool Protocol_text::store(double from, uint32 decimals, String *buffer)
811
{
812
#ifndef DBUG_OFF
813
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
814 815
	      field_types[field_pos] == MYSQL_TYPE_DOUBLE);
  field_pos++;
816
#endif
817
  buffer->set_real(from, decimals, thd->charset());
818
  return net_store_data((uchar*) buffer->ptr(), buffer->length());
819 820 821
}


unknown's avatar
unknown committed
822
bool Protocol_text::store(Field *field)
823
{
824 825
  if (field->is_null())
    return store_null();
826
#ifndef DBUG_OFF
827 828 829
  field_pos++;
#endif
  char buff[MAX_FIELD_WIDTH];
830
  String str(buff,sizeof(buff), &my_charset_bin);
831
  CHARSET_INFO *tocs= this->thd->variables.character_set_results;
unknown's avatar
unknown committed
832
#ifndef DBUG_OFF
833 834 835 836 837
  TABLE *table= field->table;
  my_bitmap_map *old_map= 0;
  if (table->file)
    old_map= dbug_tmp_use_all_columns(table, table->read_set);
#endif
838

839
  field->val_str(&str);
unknown's avatar
unknown committed
840
#ifndef DBUG_OFF
841 842 843 844
  if (old_map)
    dbug_tmp_restore_column_map(table->read_set, old_map);
#endif

845
  return store_string_aux(str.ptr(), str.length(), str.charset(), tocs);
846 847 848
}


unknown's avatar
unknown committed
849 850 851 852 853 854 855
/*
   TODO:
        Second_part format ("%06") needs to change when 
        we support 0-6 decimals for time.
*/


856
bool Protocol_text::store(MYSQL_TIME *tm)
857
{
858
#ifndef DBUG_OFF
859
  DBUG_ASSERT(field_types == 0 ||
860 861 862
	      field_types[field_pos] == MYSQL_TYPE_DATETIME ||
	      field_types[field_pos] == MYSQL_TYPE_TIMESTAMP);
  field_pos++;
863 864
#endif
  char buff[40];
865 866 867 868 869 870 871 872 873
  uint length;
  length= my_sprintf(buff,(buff, "%04d-%02d-%02d %02d:%02d:%02d",
			   (int) tm->year,
			   (int) tm->month,
			   (int) tm->day,
			   (int) tm->hour,
			   (int) tm->minute,
			   (int) tm->second));
  if (tm->second_part)
874 875 876
    length+= my_sprintf(buff+length,(buff+length, ".%06d",
                                     (int)tm->second_part));
  return net_store_data((uchar*) buff, length);
877 878 879
}


880
bool Protocol_text::store_date(MYSQL_TIME *tm)
881
{
882
#ifndef DBUG_OFF
883
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
884 885
	      field_types[field_pos] == MYSQL_TYPE_DATE);
  field_pos++;
886
#endif
887
  char buff[MAX_DATE_STRING_REP_LENGTH];
888 889
  size_t length= my_date_to_str(tm, buff);
  return net_store_data((uchar*) buff, length);
890 891 892
}


unknown's avatar
unknown committed
893 894 895 896 897 898
/*
   TODO:
        Second_part format ("%06") needs to change when 
        we support 0-6 decimals for time.
*/

899
bool Protocol_text::store_time(MYSQL_TIME *tm)
900
{
901
#ifndef DBUG_OFF
902
  DBUG_ASSERT(field_types == 0 ||
unknown's avatar
unknown committed
903 904
	      field_types[field_pos] == MYSQL_TYPE_TIME);
  field_pos++;
905 906
#endif
  char buff[40];
907
  uint length;
908
  uint day= (tm->year || tm->month) ? 0 : tm->day;
909 910 911 912 913 914 915
  length= my_sprintf(buff,(buff, "%s%02ld:%02d:%02d",
			   tm->neg ? "-" : "",
			   (long) day*24L+(long) tm->hour,
			   (int) tm->minute,
			   (int) tm->second));
  if (tm->second_part)
    length+= my_sprintf(buff+length,(buff+length, ".%06d", (int)tm->second_part));
916
  return net_store_data((uchar*) buff, length);
917 918 919 920 921
}


/****************************************************************************
  Functions to handle the binary protocol used with prepared statements
unknown's avatar
unknown committed
922 923 924

  Data format:

925 926 927 928 929 930 931 932 933 934 935 936
   [ok:1]                            reserved ok packet
   [null_field:(field_count+7+2)/8]  reserved to send null data. The size is
                                     calculated using:
                                     bit_fields= (field_count+7+2)/8; 
                                     2 bits are reserved for identifying type
				     of package.
   [[length]data]                    data field (the length applies only for 
                                     string/binary/time/timestamp fields and 
                                     rest of them are not sent as they have 
                                     the default length that client understands
                                     based on the field type
   [..]..[[length]data]              data
937 938
****************************************************************************/

unknown's avatar
unknown committed
939
bool Protocol_binary::prepare_for_send(List<Item> *item_list)
940
{
unknown's avatar
SCRUM  
unknown committed
941
  Protocol::prepare_for_send(item_list);
unknown's avatar
unknown committed
942 943
  bit_fields= (field_count+9)/8;
  if (packet->alloc(bit_fields+1))
944 945 946 947 948 949
    return 1;
  /* prepare_for_resend will be called after this one */
  return 0;
}


unknown's avatar
unknown committed
950
void Protocol_binary::prepare_for_resend()
951
{
unknown's avatar
unknown committed
952
  packet->length(bit_fields+1);
953
  bzero((uchar*) packet->ptr(), 1+bit_fields);
954 955 956 957
  field_pos=0;
}


958
bool Protocol_binary::store(const char *from, size_t length,
959
                            CHARSET_INFO *fromcs)
960
{
961
  CHARSET_INFO *tocs= thd->variables.character_set_results;
962
  field_pos++;
963
  return store_string_aux(from, length, fromcs, tocs);
964 965
}

966
bool Protocol_binary::store(const char *from, size_t length,
967
                            CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
968 969
{
  field_pos++;
970
  return store_string_aux(from, length, fromcs, tocs);
971 972
}

unknown's avatar
unknown committed
973
bool Protocol_binary::store_null()
974
{
unknown's avatar
unknown committed
975
  uint offset= (field_pos+2)/8+1, bit= (1 << ((field_pos+2) & 7));
976 977 978 979 980 981 982 983
  /* Room for this as it's allocated in prepare_for_send */
  char *to= (char*) packet->ptr()+offset;
  *to= (char) ((uchar) *to | (uchar) bit);
  field_pos++;
  return 0;
}


unknown's avatar
unknown committed
984
bool Protocol_binary::store_tiny(longlong from)
985 986 987 988
{
  char buff[1];
  field_pos++;
  buff[0]= (uchar) from;
989
  return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC);
990 991 992
}


unknown's avatar
unknown committed
993
bool Protocol_binary::store_short(longlong from)
994 995
{
  field_pos++;
996
  char *to= packet->prep_append(2, PACKET_BUFFER_EXTRA_ALLOC);
997 998 999 1000 1001 1002 1003
  if (!to)
    return 1;
  int2store(to, (int) from);
  return 0;
}


unknown's avatar
unknown committed
1004
bool Protocol_binary::store_long(longlong from)
1005 1006
{
  field_pos++;
1007
  char *to= packet->prep_append(4, PACKET_BUFFER_EXTRA_ALLOC);
1008 1009 1010 1011 1012 1013 1014
  if (!to)
    return 1;
  int4store(to, from);
  return 0;
}


unknown's avatar
unknown committed
1015
bool Protocol_binary::store_longlong(longlong from, bool unsigned_flag)
1016 1017
{
  field_pos++;
1018
  char *to= packet->prep_append(8, PACKET_BUFFER_EXTRA_ALLOC);
1019 1020 1021 1022 1023 1024
  if (!to)
    return 1;
  int8store(to, from);
  return 0;
}

unknown's avatar
unknown committed
1025
bool Protocol_binary::store_decimal(const my_decimal *d)
unknown's avatar
unknown committed
1026
{
1027
#ifndef DBUG_OFF
unknown's avatar
unknown committed
1028 1029 1030 1031
  DBUG_ASSERT(field_types == 0 ||
              field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL);
  field_pos++;
#endif
1032 1033 1034
  char buff[DECIMAL_MAX_STR_LENGTH];
  String str(buff, sizeof(buff), &my_charset_bin);
  (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
unknown's avatar
unknown committed
1035 1036
  return store(str.ptr(), str.length(), str.charset());
}
1037

unknown's avatar
unknown committed
1038
bool Protocol_binary::store(float from, uint32 decimals, String *buffer)
1039 1040
{
  field_pos++;
1041
  char *to= packet->prep_append(4, PACKET_BUFFER_EXTRA_ALLOC);
1042 1043 1044 1045 1046 1047 1048
  if (!to)
    return 1;
  float4store(to, from);
  return 0;
}


unknown's avatar
unknown committed
1049
bool Protocol_binary::store(double from, uint32 decimals, String *buffer)
1050 1051
{
  field_pos++;
1052
  char *to= packet->prep_append(8, PACKET_BUFFER_EXTRA_ALLOC);
1053 1054 1055 1056 1057 1058 1059
  if (!to)
    return 1;
  float8store(to, from);
  return 0;
}


unknown's avatar
unknown committed
1060
bool Protocol_binary::store(Field *field)
1061 1062
{
  /*
1063
    We should not increment field_pos here as send_binary() will call another
1064 1065 1066 1067 1068 1069 1070 1071
    protocol function to do this for us
  */
  if (field->is_null())
    return store_null();
  return field->send_binary(this);
}


1072
bool Protocol_binary::store(MYSQL_TIME *tm)
1073 1074 1075 1076 1077
{
  char buff[12],*pos;
  uint length;
  field_pos++;
  pos= buff+1;
unknown's avatar
unknown committed
1078

1079
  int2store(pos, tm->year);
1080 1081 1082 1083 1084
  pos[2]= (uchar) tm->month;
  pos[3]= (uchar) tm->day;
  pos[4]= (uchar) tm->hour;
  pos[5]= (uchar) tm->minute;
  pos[6]= (uchar) tm->second;
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
  int4store(pos+7, tm->second_part);
  if (tm->second_part)
    length=11;
  else if (tm->hour || tm->minute || tm->second)
    length=7;
  else if (tm->year || tm->month || tm->day)
    length=4;
  else
    length=0;
  buff[0]=(char) length;			// Length is stored first
1095
  return packet->append(buff, length+1, PACKET_BUFFER_EXTRA_ALLOC);
1096 1097
}

1098
bool Protocol_binary::store_date(MYSQL_TIME *tm)
1099 1100 1101
{
  tm->hour= tm->minute= tm->second=0;
  tm->second_part= 0;
unknown's avatar
unknown committed
1102
  return Protocol_binary::store(tm);
1103 1104 1105
}


1106
bool Protocol_binary::store_time(MYSQL_TIME *tm)
1107
{
1108
  char buff[13], *pos;
1109 1110 1111 1112
  uint length;
  field_pos++;
  pos= buff+1;
  pos[0]= tm->neg ? 1 : 0;
1113 1114 1115 1116 1117 1118 1119
  if (tm->hour >= 24)
  {
    /* Fix if we come from Item::send */
    uint days= tm->hour/24;
    tm->hour-= days*24;
    tm->day+= days;
  }
unknown's avatar
unknown committed
1120
  int4store(pos+1, tm->day);
1121 1122 1123 1124
  pos[5]= (uchar) tm->hour;
  pos[6]= (uchar) tm->minute;
  pos[7]= (uchar) tm->second;
  int4store(pos+8, tm->second_part);
1125
  if (tm->second_part)
1126
    length=12;
1127
  else if (tm->hour || tm->minute || tm->second || tm->day)
1128
    length=8;
1129 1130 1131
  else
    length=0;
  buff[0]=(char) length;			// Length is stored first
1132
  return packet->append(buff, length+1, PACKET_BUFFER_EXTRA_ALLOC);
1133
}