libmysql.c 125 KB
Newer Older
1
/* Copyright (C) 2000-2004 MySQL AB
unknown's avatar
unknown committed
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
5 6 7 8
   the Free Software Foundation.

   There are special exceptions to the terms and conditions of the GPL as it
   is applied to this software. View the full text of the exception in file
9
   EXCEPTIONS-CLIENT in the directory of this software distribution.
unknown's avatar
unknown committed
10 11

   This program is distributed in the hope that it will be useful,
unknown's avatar
unknown committed
12
   but WITHOUT ANY WARRANTY; without even the implied warranty of
unknown's avatar
unknown committed
13 14 15 16 17 18
   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 */
unknown's avatar
unknown committed
19

unknown's avatar
unknown committed
20
#include <my_global.h>
unknown's avatar
unknown committed
21
#include <my_sys.h>
22
#include <my_time.h>
unknown's avatar
unknown committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <mysys_err.h>
#include <m_string.h>
#include <m_ctype.h>
#include "mysql.h"
#include "mysql_version.h"
#include "mysqld_error.h"
#include "errmsg.h"
#include <violite.h>
#include <sys/stat.h>
#include <signal.h>
#include <time.h>
#ifdef	 HAVE_PWD_H
#include <pwd.h>
#endif
#if !defined(MSDOS) && !defined(__WIN__)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#ifdef HAVE_SELECT_H
43
#include <select.h>
unknown's avatar
unknown committed
44 45 46 47
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
unknown's avatar
unknown committed
48
#endif /* !defined(MSDOS) && !defined(__WIN__) */
49 50
#ifdef HAVE_POLL
#include <sys/poll.h>
unknown's avatar
unknown committed
51 52
#endif
#ifdef HAVE_SYS_UN_H
53
#include <sys/un.h>
unknown's avatar
unknown committed
54 55 56 57 58 59 60 61
#endif
#if defined(THREAD) && !defined(__WIN__)
#include <my_pthread.h>				/* because of signal()	*/
#endif
#ifndef INADDR_NONE
#define INADDR_NONE	-1
#endif

unknown's avatar
SCRUM:  
unknown committed
62
#include <sql_common.h>
unknown's avatar
SCRUM  
unknown committed
63
#include "client_settings.h"
unknown's avatar
SCRUM:  
unknown committed
64

65 66
#undef net_buffer_length
#undef max_allowed_packet
67

unknown's avatar
unknown committed
68
ulong 		net_buffer_length=8192;
69
ulong		max_allowed_packet= 1024L*1024L*1024L;
70 71
ulong		net_read_timeout=  CLIENT_NET_READ_TIMEOUT;
ulong		net_write_timeout= CLIENT_NET_WRITE_TIMEOUT;
unknown's avatar
unknown committed
72

unknown's avatar
unknown committed
73

unknown's avatar
SCRUM  
unknown committed
74 75 76 77 78
#ifdef EMBEDDED_LIBRARY
#undef net_flush
my_bool	net_flush(NET *net);
#endif

unknown's avatar
unknown committed
79
#if defined(MSDOS) || defined(__WIN__)
unknown's avatar
unknown committed
80
/* socket_errno is defined in my_global.h for all platforms */
unknown's avatar
unknown committed
81 82 83 84
#define perror(A)
#else
#include <errno.h>
#define SOCKET_ERROR -1
unknown's avatar
unknown committed
85
#endif /* __WIN__ */
unknown's avatar
unknown committed
86

87 88 89 90 91
/*
  If allowed through some configuration, then this needs to
  be changed
*/
#define MAX_LONG_DATA_LENGTH 8192
92 93
#define unsigned_field(A) ((A)->flags & UNSIGNED_FLAG)

unknown's avatar
unknown committed
94
static void append_wild(char *to,char *end,const char *wild);
unknown's avatar
SCRUM:  
unknown committed
95
sig_handler pipe_sig_handler(int sig);
96 97 98 99

static my_bool mysql_client_init= 0;
static my_bool org_my_init_done= 0;

unknown's avatar
unknown committed
100 101

/*
unknown's avatar
merge  
unknown committed
102
  Initialize the MySQL client library
unknown's avatar
unknown committed
103 104

  SYNOPSIS
unknown's avatar
merge  
unknown committed
105
    mysql_server_init()
unknown's avatar
unknown committed
106 107

  NOTES
unknown's avatar
merge  
unknown committed
108 109 110 111 112
    Should be called before doing any other calls to the MySQL
    client library to initialize thread specific variables etc.
    It's called by mysql_init() to ensure that things will work for
    old not threaded applications that doesn't call mysql_server_init()
    directly.
unknown's avatar
unknown committed
113 114 115 116 117 118

  RETURN
    0  ok
    1  could not initialize environment (out of memory or thread keys)
*/

unknown's avatar
unknown committed
119 120 121
int STDCALL mysql_server_init(int argc __attribute__((unused)),
			      char **argv __attribute__((unused)),
			      char **groups __attribute__((unused)))
122
{
123
  int result= 0;
124 125 126 127
  if (!mysql_client_init)
  {
    mysql_client_init=1;
    org_my_init_done=my_init_done;
unknown's avatar
unknown committed
128 129
    if (my_init())				/* Will init threads */
      return 1;
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
    init_client_errs();
    if (!mysql_port)
    {
      mysql_port = MYSQL_PORT;
#ifndef MSDOS
      {
	struct servent *serv_ptr;
	char	*env;
	if ((serv_ptr = getservbyname("mysql", "tcp")))
	  mysql_port = (uint) ntohs((ushort) serv_ptr->s_port);
	if ((env = getenv("MYSQL_TCP_PORT")))
	  mysql_port =(uint) atoi(env);
      }
#endif
    }
    if (!mysql_unix_port)
    {
      char *env;
#ifdef __WIN__
      mysql_unix_port = (char*) MYSQL_NAMEDPIPE;
#else
      mysql_unix_port = (char*) MYSQL_UNIX_ADDR;
#endif
      if ((env = getenv("MYSQL_UNIX_PORT")))
	mysql_unix_port = env;
    }
    mysql_debug(NullS);
157
#if defined(SIGPIPE) && !defined(__WIN__) && !defined(__NETWARE__)
unknown's avatar
unknown committed
158
    (void) signal(SIGPIPE, SIG_IGN);
159
#endif
unknown's avatar
unknown committed
160
#ifdef EMBEDDED_LIBRARY
161
    result= init_embedded_server(argc, argv, groups);
unknown's avatar
unknown committed
162
#endif
163 164 165
  }
#ifdef THREAD
  else
unknown's avatar
unknown committed
166
    result= (int)my_thread_init();         /* Init if new thread */
167
#endif
168
  return result;
unknown's avatar
unknown committed
169
}
unknown's avatar
unknown committed
170

171

172
void STDCALL mysql_server_end()
173
{
unknown's avatar
unknown committed
174
#ifdef EMBEDDED_LIBRARY
175
  end_embedded_server();
unknown's avatar
unknown committed
176
#endif
177 178
  /* If library called my_init(), free memory allocated by it */
  if (!org_my_init_done)
179
  {
180
    my_end(0);
181 182 183 184 185
#ifndef THREAD
  /* Remove TRACING, if enabled by mysql_debug() */
    DBUG_POP();
#endif
  }
unknown's avatar
unknown committed
186 187
  else
    mysql_thread_end();
188
  mysql_client_init= org_my_init_done= 0;
189
}
unknown's avatar
unknown committed
190

191 192 193
static MYSQL_PARAMETERS mysql_internal_parameters=
{&max_allowed_packet, &net_buffer_length};

unknown's avatar
unknown committed
194
MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void)
195 196 197 198
{
  return &mysql_internal_parameters;
}

199
my_bool STDCALL mysql_thread_init()
unknown's avatar
unknown committed
200 201
{
#ifdef THREAD
202
  return my_thread_init();
unknown's avatar
unknown committed
203
#else
204
  return 0;
unknown's avatar
unknown committed
205 206 207
#endif
}

208
void STDCALL mysql_thread_end()
unknown's avatar
unknown committed
209 210
{
#ifdef THREAD
211
  my_thread_end();
unknown's avatar
unknown committed
212 213 214
#endif
}

unknown's avatar
unknown committed
215 216 217 218
/*
  Let the user specify that we don't want SIGPIPE;  This doesn't however work
  with threaded applications as we can have multiple read in progress.
*/
219 220 221 222 223
static MYSQL* spawn_init(MYSQL* parent, const char* host,
			 unsigned int port,
			 const char* user,
			 const char* passwd);

224

unknown's avatar
unknown committed
225 226

/*
227
  Expand wildcard to a sql string
unknown's avatar
unknown committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
*/

static void
append_wild(char *to, char *end, const char *wild)
{
  end-=5;					/* Some extra */
  if (wild && wild[0])
  {
    to=strmov(to," like '");
    while (*wild && to < end)
    {
      if (*wild == '\\' || *wild == '\'')
	*to++='\\';
      *to++= *wild++;
    }
    if (*wild)					/* Too small buffer */
      *to++='%';				/* Nicer this way */
    to[0]='\'';
    to[1]=0;
  }
}


/**************************************************************************
252
  Init debugging if MYSQL_DEBUG environment variable is found
unknown's avatar
unknown committed
253 254 255
**************************************************************************/

void STDCALL
unknown's avatar
unknown committed
256
mysql_debug(const char *debug __attribute__((unused)))
unknown's avatar
unknown committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
{
#ifndef DBUG_OFF
  char	*env;
  if (_db_on_)
    return;					/* Already using debugging */
  if (debug)
  {
    DEBUGGER_ON;
    DBUG_PUSH(debug);
  }
  else if ((env = getenv("MYSQL_DEBUG")))
  {
    DEBUGGER_ON;
    DBUG_PUSH(env);
#if !defined(_WINVER) && !defined(WINVER)
    puts("\n-------------------------------------------------------");
    puts("MYSQL_DEBUG found. libmysql started with the following:");
    puts(env);
    puts("-------------------------------------------------------\n");
#else
    {
      char buff[80];
279 280
      buff[sizeof(buff)-1]= 0;
      strxnmov(buff,sizeof(buff)-1,"libmysql: ", env, NullS);
unknown's avatar
unknown committed
281 282 283 284 285 286 287 288 289
      MessageBox((HWND) 0,"Debugging variable MYSQL_DEBUG used",buff,MB_OK);
    }
#endif
  }
#endif
}


/**************************************************************************
290
  Close the server connection if we get a SIGPIPE
unknown's avatar
unknown committed
291 292 293
   ARGSUSED
**************************************************************************/

unknown's avatar
SCRUM:  
unknown committed
294
sig_handler
unknown's avatar
unknown committed
295 296 297 298 299 300 301 302
pipe_sig_handler(int sig __attribute__((unused)))
{
  DBUG_PRINT("info",("Hit by signal %d",sig));
#ifdef DONT_REMEMBER_SIGNAL
  (void) signal(SIGPIPE,pipe_sig_handler);
#endif
}

unknown's avatar
SCRUM  
unknown committed
303 304
/* perform query on master */
my_bool STDCALL mysql_master_query(MYSQL *mysql, const char *q,
unknown's avatar
unknown committed
305
				   unsigned long length)
unknown's avatar
SCRUM  
unknown committed
306 307 308 309
{
  DBUG_ENTER("mysql_master_query");
  if (mysql_master_send_query(mysql, q, length))
    DBUG_RETURN(1);
unknown's avatar
SCRUM:  
unknown committed
310
  DBUG_RETURN((*mysql->methods->read_query_result)(mysql));
unknown's avatar
SCRUM  
unknown committed
311
}
unknown's avatar
unknown committed
312

unknown's avatar
SCRUM  
unknown committed
313 314
my_bool STDCALL mysql_master_send_query(MYSQL *mysql, const char *q,
					unsigned long length)
unknown's avatar
unknown committed
315
{
unknown's avatar
SCRUM  
unknown committed
316 317 318 319 320 321
  MYSQL *master = mysql->master;
  DBUG_ENTER("mysql_master_send_query");
  if (!master->net.vio && !mysql_real_connect(master,0,0,0,0,0,0,0))
    DBUG_RETURN(1);
  mysql->last_used_con = master;
  DBUG_RETURN(simple_command(master, COM_QUERY, q, length, 1));
unknown's avatar
unknown committed
322 323 324
}


unknown's avatar
SCRUM  
unknown committed
325 326 327
/* perform query on slave */
my_bool STDCALL mysql_slave_query(MYSQL *mysql, const char *q,
				  unsigned long length)
unknown's avatar
unknown committed
328
{
unknown's avatar
SCRUM  
unknown committed
329 330 331
  DBUG_ENTER("mysql_slave_query");
  if (mysql_slave_send_query(mysql, q, length))
    DBUG_RETURN(1);
unknown's avatar
SCRUM:  
unknown committed
332
  DBUG_RETURN((*mysql->methods->read_query_result)(mysql));
unknown's avatar
unknown committed
333 334 335
}


unknown's avatar
SCRUM  
unknown committed
336 337
my_bool STDCALL mysql_slave_send_query(MYSQL *mysql, const char *q,
				   unsigned long length)
unknown's avatar
unknown committed
338
{
unknown's avatar
SCRUM  
unknown committed
339 340
  MYSQL* last_used_slave, *slave_to_use = 0;
  DBUG_ENTER("mysql_slave_send_query");
unknown's avatar
unknown committed
341

unknown's avatar
SCRUM  
unknown committed
342 343 344 345 346 347 348 349 350 351
  if ((last_used_slave = mysql->last_used_slave))
    slave_to_use = last_used_slave->next_slave;
  else
    slave_to_use = mysql->next_slave;
  /*
    Next_slave is always safe to use - we have a circular list of slaves
    if there are no slaves, mysql->next_slave == mysql
  */
  mysql->last_used_con = mysql->last_used_slave = slave_to_use;
  if (!slave_to_use->net.vio && !mysql_real_connect(slave_to_use, 0,0,0,
unknown's avatar
unknown committed
352
						    0,0,0,0))
unknown's avatar
SCRUM  
unknown committed
353 354 355
    DBUG_RETURN(1);
  DBUG_RETURN(simple_command(slave_to_use, COM_QUERY, q, length, 1));
}
unknown's avatar
unknown committed
356 357


unknown's avatar
SCRUM  
unknown committed
358 359 360
/* enable/disable parsing of all queries to decide
   if they go on master or slave */
void STDCALL mysql_enable_rpl_parse(MYSQL* mysql)
unknown's avatar
unknown committed
361
{
unknown's avatar
SCRUM  
unknown committed
362
  mysql->options.rpl_parse = 1;
unknown's avatar
unknown committed
363 364
}

unknown's avatar
SCRUM  
unknown committed
365
void STDCALL mysql_disable_rpl_parse(MYSQL* mysql)
unknown's avatar
unknown committed
366
{
unknown's avatar
SCRUM  
unknown committed
367
  mysql->options.rpl_parse = 0;
unknown's avatar
unknown committed
368 369
}

unknown's avatar
SCRUM  
unknown committed
370 371
/* get the value of the parse flag */
int STDCALL mysql_rpl_parse_enabled(MYSQL* mysql)
unknown's avatar
unknown committed
372
{
unknown's avatar
SCRUM  
unknown committed
373
  return mysql->options.rpl_parse;
unknown's avatar
unknown committed
374 375
}

unknown's avatar
SCRUM  
unknown committed
376 377
/*  enable/disable reads from master */
void STDCALL mysql_enable_reads_from_master(MYSQL* mysql)
unknown's avatar
unknown committed
378
{
unknown's avatar
SCRUM  
unknown committed
379 380
  mysql->options.no_master_reads = 0;
}
unknown's avatar
unknown committed
381

unknown's avatar
SCRUM  
unknown committed
382
void STDCALL mysql_disable_reads_from_master(MYSQL* mysql)
383 384 385 386
{
  mysql->options.no_master_reads = 1;
}

unknown's avatar
unknown committed
387
/* get the value of the master read flag */
388
my_bool STDCALL mysql_reads_from_master_enabled(MYSQL* mysql)
389 390 391 392
{
  return !(mysql->options.no_master_reads);
}

393 394 395 396 397

/*
  We may get an error while doing replication internals.
  In this case, we add a special explanation to the original
  error
398
*/
399 400

static void expand_error(MYSQL* mysql, int error)
401 402
{
  char tmp[MYSQL_ERRMSG_SIZE];
403 404 405 406 407 408
  char *p;
  uint err_length;
  strmake(tmp, mysql->net.last_error, MYSQL_ERRMSG_SIZE-1);
  p = strmake(mysql->net.last_error, ER(error), MYSQL_ERRMSG_SIZE-1);
  err_length= (uint) (p - mysql->net.last_error);
  strmake(p, tmp, MYSQL_ERRMSG_SIZE-1 - err_length);
409 410 411
  mysql->net.last_errno = error;
}

412 413 414
/*
  This function assumes we have just called SHOW SLAVE STATUS and have
  read the given result and row
415
*/
416

417
static my_bool get_master(MYSQL* mysql, MYSQL_RES* res, MYSQL_ROW row)
418 419
{
  MYSQL* master;
unknown's avatar
unknown committed
420
  DBUG_ENTER("get_master");
unknown's avatar
unknown committed
421
  if (mysql_num_fields(res) < 3)
unknown's avatar
unknown committed
422
    DBUG_RETURN(1); /* safety */
unknown's avatar
unknown committed
423

424
  /* use the same username and password as the original connection */
unknown's avatar
unknown committed
425
  if (!(master = spawn_init(mysql, row[0], atoi(row[2]), 0, 0)))
unknown's avatar
unknown committed
426
    DBUG_RETURN(1);
427
  mysql->master = master;
unknown's avatar
unknown committed
428
  DBUG_RETURN(0);
429 430
}

431 432 433 434

/*
  Assuming we already know that mysql points to a master connection,
  retrieve all the slaves
435
*/
436

437
static my_bool get_slaves_from_master(MYSQL* mysql)
438
{
439 440
  MYSQL_RES* res = 0;
  MYSQL_ROW row;
441
  my_bool error = 1;
442
  int has_auth_info;
unknown's avatar
cleanup  
unknown committed
443
  int port_ind;
unknown's avatar
unknown committed
444
  DBUG_ENTER("get_slaves_from_master");
unknown's avatar
unknown committed
445

446 447 448
  if (!mysql->net.vio && !mysql_real_connect(mysql,0,0,0,0,0,0,0))
  {
    expand_error(mysql, CR_PROBE_MASTER_CONNECT);
unknown's avatar
unknown committed
449
    DBUG_RETURN(1);
450 451 452
  }

  if (mysql_query(mysql, "SHOW SLAVE HOSTS") ||
453
      !(res = mysql_store_result(mysql)))
454 455
  {
    expand_error(mysql, CR_PROBE_SLAVE_HOSTS);
unknown's avatar
unknown committed
456
    DBUG_RETURN(1);
457 458
  }

459
  switch (mysql_num_fields(res)) {
unknown's avatar
cleanup  
unknown committed
460 461 462 463 464 465 466 467
  case 5:
    has_auth_info = 0;
    port_ind=2;
    break;
  case 7:
    has_auth_info = 1;
    port_ind=4;
    break;
468 469 470 471 472 473 474 475 476 477 478
  default:
    goto err;
  }

  while ((row = mysql_fetch_row(res)))
  {
    MYSQL* slave;
    const char* tmp_user, *tmp_pass;

    if (has_auth_info)
    {
unknown's avatar
cleanup  
unknown committed
479 480
      tmp_user = row[2];
      tmp_pass = row[3];
481 482 483 484 485 486 487
    }
    else
    {
      tmp_user = mysql->user;
      tmp_pass = mysql->passwd;
    }

unknown's avatar
cleanup  
unknown committed
488
    if (!(slave = spawn_init(mysql, row[1], atoi(row[port_ind]),
unknown's avatar
unknown committed
489
			     tmp_user, tmp_pass)))
490
      goto err;
unknown's avatar
unknown committed
491

492 493 494 495 496 497
    /* Now add slave into the circular linked list */
    slave->next_slave = mysql->next_slave;
    mysql->next_slave = slave;
  }
  error = 0;
err:
unknown's avatar
unknown committed
498
  if (res)
unknown's avatar
unknown committed
499
    mysql_free_result(res);
unknown's avatar
unknown committed
500
  DBUG_RETURN(error);
501 502
}

503

504
my_bool STDCALL mysql_rpl_probe(MYSQL* mysql)
505
{
unknown's avatar
unknown committed
506
  MYSQL_RES *res= 0;
507
  MYSQL_ROW row;
508
  my_bool error= 1;
unknown's avatar
unknown committed
509 510
  DBUG_ENTER("mysql_rpl_probe");

511 512 513 514 515
  /*
    First determine the replication role of the server we connected to
    the most reliable way to do this is to run SHOW SLAVE STATUS and see
    if we have a non-empty master host. This is still not fool-proof -
    it is not a sin to have a master that has a dormant slave thread with
unknown's avatar
unknown committed
516
    a non-empty master host. However, it is more reliable to check
517
    for empty master than whether the slave thread is actually running
518
  */
519
  if (mysql_query(mysql, "SHOW SLAVE STATUS") ||
520
      !(res = mysql_store_result(mysql)))
521 522
  {
    expand_error(mysql, CR_PROBE_SLAVE_STATUS);
unknown's avatar
unknown committed
523
    DBUG_RETURN(1);
524
  }
unknown's avatar
unknown committed
525

526 527 528 529 530 531
  row= mysql_fetch_row(res);
  /*
    Check master host for emptiness/NULL
    For MySQL 4.0 it's enough to check for row[0]
  */
  if (row && row[0] && *(row[0]))
532 533
  {
    /* this is a slave, ask it for the master */
534
    if (get_master(mysql, res, row) || get_slaves_from_master(mysql))
535 536 537 538 539
      goto err;
  }
  else
  {
    mysql->master = mysql;
540
    if (get_slaves_from_master(mysql))
541 542 543 544 545
      goto err;
  }

  error = 0;
err:
unknown's avatar
unknown committed
546
  if (res)
547
    mysql_free_result(res);
unknown's avatar
unknown committed
548
  DBUG_RETURN(error);
549 550 551
}


552 553 554 555 556 557 558 559 560 561
/*
  Make a not so fool-proof decision on where the query should go, to
  the master or the slave. Ideally the user should always make this
  decision himself with mysql_master_query() or mysql_slave_query().
  However, to be able to more easily port the old code, we support the
  option of an educated guess - this should work for most applications,
  however, it may make the wrong decision in some particular cases. If
  that happens, the user would have to change the code to call
  mysql_master_query() or mysql_slave_query() explicitly in the place
  where we have made the wrong decision
562
*/
563

564 565
enum mysql_rpl_type
STDCALL mysql_rpl_query_type(const char* q, int len)
566
{
unknown's avatar
unknown committed
567
  const char *q_end= q + len;
568
  for (; q < q_end; ++q)
569 570
  {
    char c;
571
    if (my_isalpha(&my_charset_latin1, (c= *q)))
572
    {
573
      switch (my_tolower(&my_charset_latin1,c)) {
574 575 576 577 578 579 580
      case 'i':  /* insert */
      case 'u':  /* update or unlock tables */
      case 'l':  /* lock tables or load data infile */
      case 'd':  /* drop or delete */
      case 'a':  /* alter */
	return MYSQL_RPL_MASTER;
      case 'c':  /* create or check */
581
	return my_tolower(&my_charset_latin1,q[1]) == 'h' ? MYSQL_RPL_ADMIN :
unknown's avatar
unknown committed
582
	  MYSQL_RPL_MASTER;
583
      case 's': /* select or show */
584
	return my_tolower(&my_charset_latin1,q[1]) == 'h' ? MYSQL_RPL_ADMIN :
unknown's avatar
unknown committed
585
	  MYSQL_RPL_SLAVE;
586 587 588
      case 'f': /* flush */
      case 'r': /* repair */
      case 'g': /* grant */
unknown's avatar
SCRUM  
unknown committed
589 590 591 592 593
	return MYSQL_RPL_ADMIN;
      default:
	return MYSQL_RPL_SLAVE;
      }
    }
unknown's avatar
unknown committed
594
  }
unknown's avatar
SCRUM  
unknown committed
595
  return MYSQL_RPL_MASTER;		/* By default, send to master */
unknown's avatar
unknown committed
596 597 598
}


unknown's avatar
SCRUM  
unknown committed
599 600 601 602
/**************************************************************************
  Connect to sql server
  If host == 0 then use localhost
**************************************************************************/
603

unknown's avatar
SCRUM  
unknown committed
604 605 606 607
#ifdef USE_OLD_FUNCTIONS
MYSQL * STDCALL
mysql_connect(MYSQL *mysql,const char *host,
	      const char *user, const char *passwd)
unknown's avatar
unknown committed
608
{
unknown's avatar
SCRUM  
unknown committed
609 610
  MYSQL *res;
  mysql=mysql_init(mysql);			/* Make it thread safe */
unknown's avatar
unknown committed
611
  {
unknown's avatar
SCRUM  
unknown committed
612 613 614 615 616 617 618
    DBUG_ENTER("mysql_connect");
    if (!(res=mysql_real_connect(mysql,host,user,passwd,NullS,0,NullS,0)))
    {
      if (mysql->free_me)
	my_free((gptr) mysql,MYF(0));
    }
    DBUG_RETURN(res);
unknown's avatar
unknown committed
619
  }
unknown's avatar
unknown committed
620
}
unknown's avatar
SCRUM  
unknown committed
621
#endif
unknown's avatar
unknown committed
622

623

unknown's avatar
unknown committed
624
/**************************************************************************
unknown's avatar
unknown committed
625
  Change user and database
unknown's avatar
unknown committed
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
int cli_read_change_user_result(MYSQL *mysql, char *buff, const char *passwd)
{
  NET *net= &mysql->net;
  ulong pkt_length;

  pkt_length= net_safe_read(mysql);
  
  if (pkt_length == packet_error)
    return 1;

  if (pkt_length == 1 && net->read_pos[0] == 254 &&
      mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
  {
    /*
      By sending this very specific reply server asks us to send scrambled
      password in old format. The reply contains scramble_323.
    */
    scramble_323(buff, mysql->scramble, passwd);
    if (my_net_write(net, buff, SCRAMBLE_LENGTH_323 + 1) || net_flush(net))
    {
      net->last_errno= CR_SERVER_LOST;
      strmov(net->sqlstate, unknown_sqlstate);
      strmov(net->last_error,ER(net->last_errno));
      return 1;
    }
    /* Read what server thinks about out new auth message report */
    if (net_safe_read(mysql) == packet_error)
      return 1;
  }
  return 0;
}
unknown's avatar
unknown committed
659

660

unknown's avatar
unknown committed
661
my_bool	STDCALL mysql_change_user(MYSQL *mysql, const char *user,
unknown's avatar
unknown committed
662 663
				  const char *passwd, const char *db)
{
unknown's avatar
unknown committed
664
  char buff[512],*end=buff;
665
  int rc;
unknown's avatar
unknown committed
666 667 668 669 670 671
  DBUG_ENTER("mysql_change_user");

  if (!user)
    user="";
  if (!passwd)
    passwd="";
unknown's avatar
unknown committed
672

673
  /* Store user into the buffer */
unknown's avatar
unknown committed
674
  end=strmov(end,user)+1;
unknown's avatar
unknown committed
675

676 677
  /* write scrambled password according to server capabilities */
  if (passwd[0])
unknown's avatar
unknown committed
678
  {
unknown's avatar
unknown committed
679
    if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
unknown's avatar
unknown committed
680
    {
unknown's avatar
unknown committed
681 682 683
      *end++= SCRAMBLE_LENGTH;
      scramble(end, mysql->scramble, passwd);
      end+= SCRAMBLE_LENGTH;
unknown's avatar
unknown committed
684
    }
unknown's avatar
unknown committed
685
    else
686 687 688
    {
      scramble_323(end, mysql->scramble, passwd);
      end+= SCRAMBLE_LENGTH_323 + 1;
unknown's avatar
unknown committed
689
    }
unknown's avatar
unknown committed
690 691
  }
  else
692
    *end++= '\0';                               /* empty password */
unknown's avatar
unknown committed
693
  /* Add database if needed */
unknown's avatar
unknown committed
694
  end= strmov(end, db ? db : "") + 1;
unknown's avatar
unknown committed
695 696

  /* Write authentication package */
unknown's avatar
unknown committed
697
  simple_command(mysql,COM_CHANGE_USER, buff,(ulong) (end-buff),1);
unknown's avatar
unknown committed
698

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
  rc= (*mysql->methods->read_change_user_result)(mysql, buff, passwd);

  /*
    The server will close all statements no matter was the attempt
    to change user successful or not.
  */
  mysql_detach_stmt_list(&mysql->stmts);
  if (rc == 0)
  {
    /* Free old connect information */
    my_free(mysql->user,MYF(MY_ALLOW_ZERO_PTR));
    my_free(mysql->passwd,MYF(MY_ALLOW_ZERO_PTR));
    my_free(mysql->db,MYF(MY_ALLOW_ZERO_PTR));

    /* alloc new connect information */
    mysql->user=  my_strdup(user,MYF(MY_WME));
    mysql->passwd=my_strdup(passwd,MYF(MY_WME));
    mysql->db=    db ? my_strdup(db,MYF(MY_WME)) : 0;
  }
  DBUG_RETURN(rc);
unknown's avatar
unknown committed
719 720
}

unknown's avatar
SCRUM:  
unknown committed
721 722 723 724 725 726
#if defined(HAVE_GETPWUID) && defined(NO_GETPWUID_DECL)
struct passwd *getpwuid(uid_t);
char* getlogin(void);
#endif

#if defined(__NETWARE__)
727
/* Default to value of USER on NetWare, if unset use "UNKNOWN_USER" */
unknown's avatar
SCRUM:  
unknown committed
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
void read_user_name(char *name)
{
  char *str=getenv("USER");
  strmake(name, str ? str : "UNKNOWN_USER", USERNAME_LENGTH);
}

#elif !defined(MSDOS) && ! defined(VMS) && !defined(__WIN__) && !defined(OS2)

void read_user_name(char *name)
{
  DBUG_ENTER("read_user_name");
  if (geteuid() == 0)
    (void) strmov(name,"root");		/* allow use of surun */
  else
  {
#ifdef HAVE_GETPWUID
    struct passwd *skr;
    const char *str;
    if ((str=getlogin()) == NULL)
    {
      if ((skr=getpwuid(geteuid())) != NULL)
	str=skr->pw_name;
      else if (!(str=getenv("USER")) && !(str=getenv("LOGNAME")) &&
	       !(str=getenv("LOGIN")))
	str="UNKNOWN_USER";
    }
    (void) strmake(name,str,USERNAME_LENGTH);
#elif HAVE_CUSERID
    (void) cuserid(name);
#else
    strmov(name,"UNKNOWN_USER");
#endif
  }
  DBUG_VOID_RETURN;
}

#else /* If MSDOS || VMS */

void read_user_name(char *name)
{
  char *str=getenv("USER");		/* ODBC will send user variable */
  strmake(name,str ? str : "ODBC", USERNAME_LENGTH);
}

#endif

774
my_bool handle_local_infile(MYSQL *mysql, const char *net_filename)
unknown's avatar
SCRUM:  
unknown committed
775 776 777 778
{
  my_bool result= 1;
  uint packet_length=MY_ALIGN(mysql->net.max_packet-16,IO_SIZE);
  NET *net= &mysql->net;
779 780
  int readcount;
  void *li_ptr;          /* pass state to local_infile functions */
unknown's avatar
unknown committed
781
  char *buf;		/* buffer to be filled by local_infile_read */
unknown's avatar
unknown committed
782
  struct st_mysql_options *options= &mysql->options;
783 784 785
  DBUG_ENTER("handle_local_infile");

  /* check that we've got valid callback functions */
unknown's avatar
unknown committed
786 787 788 789
  if (!(options->local_infile_init &&
	options->local_infile_read &&
	options->local_infile_end &&
	options->local_infile_error))
unknown's avatar
SCRUM:  
unknown committed
790
  {
791
    /* if any of the functions is invalid, set the default */
unknown's avatar
unknown committed
792
    mysql_set_local_infile_default(mysql);
unknown's avatar
SCRUM:  
unknown committed
793 794
  }

795
  /* copy filename into local memory and allocate read buffer */
unknown's avatar
unknown committed
796 797 798 799 800 801
  if (!(buf=my_malloc(packet_length, MYF(0))))
  {
    strmov(net->sqlstate, unknown_sqlstate);
    strmov(net->last_error, ER(net->last_errno=CR_OUT_OF_MEMORY));
    DBUG_RETURN(1);
  }
802 803

  /* initialize local infile (open file, usually) */
804 805
  if ((*options->local_infile_init)(&li_ptr, net_filename,
    options->local_infile_userdata))
unknown's avatar
SCRUM:  
unknown committed
806 807 808 809
  {
    my_net_write(net,"",0);		/* Server needs one packet */
    net_flush(net);
    strmov(net->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
810 811 812
    net->last_errno= (*options->local_infile_error)(li_ptr,
						    net->last_error,
						    sizeof(net->last_error)-1);
unknown's avatar
SCRUM:  
unknown committed
813 814 815
    goto err;
  }

816
  /* read blocks of data from local infile callback */
unknown's avatar
unknown committed
817 818 819
  while ((readcount =
	  (*options->local_infile_read)(li_ptr, buf,
					packet_length)) > 0)
unknown's avatar
SCRUM:  
unknown committed
820 821 822
  {
    if (my_net_write(net,buf,readcount))
    {
unknown's avatar
unknown committed
823 824
      DBUG_PRINT("error",
		 ("Lost connection to MySQL server during LOAD DATA of local file"));
unknown's avatar
SCRUM:  
unknown committed
825 826 827 828 829 830
      strmov(net->sqlstate, unknown_sqlstate);
      net->last_errno=CR_SERVER_LOST;
      strmov(net->last_error,ER(net->last_errno));
      goto err;
    }
  }
831

unknown's avatar
SCRUM:  
unknown committed
832 833 834 835 836 837 838 839
  /* Send empty packet to mark end of file */
  if (my_net_write(net,"",0) || net_flush(net))
  {
    strmov(net->sqlstate, unknown_sqlstate);
    net->last_errno=CR_SERVER_LOST;
    sprintf(net->last_error,ER(net->last_errno),errno);
    goto err;
  }
840

unknown's avatar
SCRUM:  
unknown committed
841 842
  if (readcount < 0)
  {
unknown's avatar
unknown committed
843 844 845
    net->last_errno= (*options->local_infile_error)(li_ptr,
						    net->last_error,
						    sizeof(net->last_error)-1);
unknown's avatar
SCRUM:  
unknown committed
846 847
    goto err;
  }
848

unknown's avatar
SCRUM:  
unknown committed
849 850 851
  result=0;					/* Ok */

err:
852
  /* free up memory allocated with _init, usually */
unknown's avatar
unknown committed
853
  (*options->local_infile_end)(li_ptr);
unknown's avatar
SCRUM:  
unknown committed
854
  DBUG_RETURN(result);
855 856 857
}


unknown's avatar
unknown committed
858 859 860 861 862 863
/****************************************************************************
  Default handlers for LOAD LOCAL INFILE
****************************************************************************/

typedef struct st_default_local_infile
{
864 865
  int fd;
  int error_num;
unknown's avatar
unknown committed
866
  const char *filename;
867 868 869 870
  char error_msg[LOCAL_INFILE_ERROR_LEN];
} default_local_infile_data;


unknown's avatar
unknown committed
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
/*
  Open file for LOAD LOCAL INFILE

  SYNOPSIS
    default_local_infile_init()
    ptr			Store pointer to internal data here
    filename		File name to open. This may be in unix format !


  NOTES
    Even if this function returns an error, the load data interface
    guarantees that default_local_infile_end() is called.

  RETURN
    0	ok
    1	error
*/

889 890
static int default_local_infile_init(void **ptr, const char *filename,
             void *userdata __attribute__ ((unused)))
891 892
{
  default_local_infile_data *data;
unknown's avatar
unknown committed
893
  char tmp_name[FN_REFLEN];
894 895

  if (!(*ptr= data= ((default_local_infile_data *)
unknown's avatar
unknown committed
896 897
		     my_malloc(sizeof(default_local_infile_data),  MYF(0)))))
    return 1; /* out of memory */
898 899 900

  data->error_msg[0]= 0;
  data->error_num=    0;
unknown's avatar
unknown committed
901
  data->filename= filename;
902

unknown's avatar
unknown committed
903 904
  fn_format(tmp_name, filename, "", "", MY_UNPACK_FILENAME);
  if ((data->fd = my_open(tmp_name, O_RDONLY, MYF(0))) < 0)
905
  {
unknown's avatar
unknown committed
906
    data->error_num= my_errno;
907
    my_snprintf(data->error_msg, sizeof(data->error_msg)-1,
unknown's avatar
unknown committed
908 909
                EE(EE_FILENOTFOUND), tmp_name, data->error_num);
    return 1;
910 911 912 913 914
  }
  return 0; /* ok */
}


unknown's avatar
unknown committed
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
/*
  Read data for LOAD LOCAL INFILE

  SYNOPSIS
    default_local_infile_read()
    ptr			Points to handle allocated by _init
    buf			Read data here
    buf_len		Ammount of data to read

  RETURN
    > 0		number of bytes read
    == 0	End of data
    < 0		Error
*/

static int default_local_infile_read(void *ptr, char *buf, uint buf_len)
931
{
unknown's avatar
unknown committed
932 933
  int count;
  default_local_infile_data*data = (default_local_infile_data *) ptr;
934

unknown's avatar
unknown committed
935 936 937 938 939 940 941 942
  if ((count= (int) my_read(data->fd, (byte *) buf, buf_len, MYF(0))) < 0)
  {
    data->error_num= EE_READ; /* the errmsg for not entire file read */
    my_snprintf(data->error_msg, sizeof(data->error_msg)-1,
		EE(EE_READ),
		data->filename, my_errno);
  }
  return count;
943 944 945
}


unknown's avatar
unknown committed
946 947 948 949 950 951 952 953 954 955 956 957
/*
  Read data for LOAD LOCAL INFILE

  SYNOPSIS
    default_local_infile_end()
    ptr			Points to handle allocated by _init
			May be NULL if _init failed!

  RETURN
*/

static void default_local_infile_end(void *ptr)
958
{
unknown's avatar
unknown committed
959 960
  default_local_infile_data *data= (default_local_infile_data *) ptr;
  if (data)					/* If not error on open */
961
  {
unknown's avatar
unknown committed
962 963 964
    if (data->fd >= 0)
      my_close(data->fd, MYF(MY_WME));
    my_free(ptr, MYF(MY_WME));
965 966 967 968
  }
}


unknown's avatar
unknown committed
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
/*
  Return error from LOAD LOCAL INFILE

  SYNOPSIS
    default_local_infile_end()
    ptr			Points to handle allocated by _init
			May be NULL if _init failed!
    error_msg		Store error text here
    error_msg_len	Max lenght of error_msg

  RETURN
    error message number
*/

static int
984 985
default_local_infile_error(void *ptr, char *error_msg, uint error_msg_len)
{
unknown's avatar
unknown committed
986 987 988
  default_local_infile_data *data = (default_local_infile_data *) ptr;
  if (data)					/* If not error on open */
  {
989 990 991
    strmake(error_msg, data->error_msg, error_msg_len);
    return data->error_num;
  }
unknown's avatar
unknown committed
992 993 994
  /* This can only happen if we got error on malloc of handle */
  strmov(error_msg, ER(CR_OUT_OF_MEMORY));
  return CR_OUT_OF_MEMORY;
995 996 997
}


unknown's avatar
unknown committed
998
void
999
mysql_set_local_infile_handler(MYSQL *mysql,
1000 1001
                               int (*local_infile_init)(void **, const char *,
                               void *),
1002
                               int (*local_infile_read)(void *, char *, uint),
unknown's avatar
unknown committed
1003
                               void (*local_infile_end)(void *),
1004 1005
                               int (*local_infile_error)(void *, char *, uint),
                               void *userdata)
1006
{
unknown's avatar
unknown committed
1007 1008 1009 1010
  mysql->options.local_infile_init=  local_infile_init;
  mysql->options.local_infile_read=  local_infile_read;
  mysql->options.local_infile_end=   local_infile_end;
  mysql->options.local_infile_error= local_infile_error;
1011
  mysql->options.local_infile_userdata = userdata;
1012 1013 1014
}


unknown's avatar
unknown committed
1015
void mysql_set_local_infile_default(MYSQL *mysql)
1016 1017 1018 1019 1020
{
  mysql->options.local_infile_init=  default_local_infile_init;
  mysql->options.local_infile_read=  default_local_infile_read;
  mysql->options.local_infile_end=   default_local_infile_end;
  mysql->options.local_infile_error= default_local_infile_error;
unknown's avatar
SCRUM:  
unknown committed
1021 1022 1023
}


unknown's avatar
unknown committed
1024
/**************************************************************************
1025 1026
  Do a query. If query returned rows, free old rows.
  Read data by mysql_store_result or by repeat call of mysql_fetch_row
unknown's avatar
unknown committed
1027 1028 1029 1030 1031 1032 1033 1034
**************************************************************************/

int STDCALL
mysql_query(MYSQL *mysql, const char *query)
{
  return mysql_real_query(mysql,query, (uint) strlen(query));
}

unknown's avatar
SCRUM:  
unknown committed
1035

1036
static MYSQL* spawn_init(MYSQL* parent, const char* host,
unknown's avatar
unknown committed
1037 1038
			 unsigned int port, const char* user,
			 const char* passwd)
1039 1040
{
  MYSQL* child;
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
  DBUG_ENTER("spawn_init");
  if (!(child= mysql_init(0)))
    DBUG_RETURN(0);

  child->options.user= my_strdup((user) ? user :
				 (parent->user ? parent->user :
				  parent->options.user), MYF(0));
  child->options.password= my_strdup((passwd) ? passwd :
				     (parent->passwd ?
				      parent->passwd :
				      parent->options.password), MYF(0));
  child->options.port= port;
  child->options.host= my_strdup((host) ? host :
				 (parent->host ?
				  parent->host :
				  parent->options.host), MYF(0));
unknown's avatar
unknown committed
1057
  if (parent->db)
1058
    child->options.db= my_strdup(parent->db, MYF(0));
unknown's avatar
unknown committed
1059
  else if (parent->options.db)
1060
    child->options.db= my_strdup(parent->options.db, MYF(0));
1061

1062 1063 1064 1065 1066 1067
  /*
    rpl_pivot is set to 1 in mysql_init();  Reset it as we are not doing
    replication here
  */
  child->rpl_pivot= 0;
  DBUG_RETURN(child);
1068 1069 1070 1071 1072
}


int
STDCALL mysql_set_master(MYSQL* mysql, const char* host,
unknown's avatar
unknown committed
1073 1074
			 unsigned int port, const char* user,
			 const char* passwd)
1075 1076 1077
{
  if (mysql->master != mysql && !mysql->master->rpl_pivot)
    mysql_close(mysql->master);
unknown's avatar
unknown committed
1078
  if (!(mysql->master = spawn_init(mysql, host, port, user, passwd)))
1079 1080 1081 1082
    return 1;
  return 0;
}

1083

1084 1085
int
STDCALL mysql_add_slave(MYSQL* mysql, const char* host,
unknown's avatar
unknown committed
1086 1087 1088
			unsigned int port,
			const char* user,
			const char* passwd)
1089 1090
{
  MYSQL* slave;
unknown's avatar
unknown committed
1091
  if (!(slave = spawn_init(mysql, host, port, user, passwd)))
1092 1093 1094 1095 1096 1097
    return 1;
  slave->next_slave = mysql->next_slave;
  mysql->next_slave = slave;
  return 0;
}

unknown's avatar
unknown committed
1098
/**************************************************************************
1099
  Return next field of the query results
unknown's avatar
unknown committed
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
**************************************************************************/

MYSQL_FIELD * STDCALL
mysql_fetch_field(MYSQL_RES *result)
{
  if (result->current_field >= result->field_count)
    return(NULL);
  return &result->fields[result->current_field++];
}

1110 1111 1112 1113 1114 1115 1116

/**************************************************************************
  Get column lengths of the current row
  If one uses mysql_use_result, res->lengths contains the length information,
  else the lengths are calculated from the offset between pointers.
**************************************************************************/

unknown's avatar
unknown committed
1117 1118 1119
ulong * STDCALL
mysql_fetch_lengths(MYSQL_RES *res)
{
1120
  MYSQL_ROW column;
unknown's avatar
unknown committed
1121 1122 1123 1124

  if (!(column=res->current_row))
    return 0;					/* Something is wrong */
  if (res->data)
1125
    (*res->methods->fetch_lengths)(res->lengths, column, res->field_count);
unknown's avatar
unknown committed
1126 1127 1128
  return res->lengths;
}

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145

/**************************************************************************
  Move to a specific row and column
**************************************************************************/

void STDCALL
mysql_data_seek(MYSQL_RES *result, my_ulonglong row)
{
  MYSQL_ROWS	*tmp=0;
  DBUG_PRINT("info",("mysql_data_seek(%ld)",(long) row));
  if (result->data)
    for (tmp=result->data->data; row-- && tmp ; tmp = tmp->next) ;
  result->current_row=0;
  result->data_cursor = tmp;
}


unknown's avatar
unknown committed
1146
/*************************************************************************
1147 1148 1149
  put the row or field cursor one a position one got from mysql_row_tell()
  This doesn't restore any data. The next mysql_fetch_row or
  mysql_fetch_field will return the next row or field after the last used
unknown's avatar
unknown committed
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
*************************************************************************/

MYSQL_ROW_OFFSET STDCALL
mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET row)
{
  MYSQL_ROW_OFFSET return_value=result->data_cursor;
  result->current_row= 0;
  result->data_cursor= row;
  return return_value;
}


MYSQL_FIELD_OFFSET STDCALL
mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET field_offset)
{
  MYSQL_FIELD_OFFSET return_value=result->current_field;
  result->current_field=field_offset;
  return return_value;
}

1170

unknown's avatar
unknown committed
1171
/*****************************************************************************
1172
  List all databases
unknown's avatar
unknown committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
*****************************************************************************/

MYSQL_RES * STDCALL
mysql_list_dbs(MYSQL *mysql, const char *wild)
{
  char buff[255];
  DBUG_ENTER("mysql_list_dbs");

  append_wild(strmov(buff,"show databases"),buff+sizeof(buff),wild);
  if (mysql_query(mysql,buff))
    DBUG_RETURN(0);
  DBUG_RETURN (mysql_store_result(mysql));
}


/*****************************************************************************
1189 1190
  List all tables in a database
  If wild is given then only the tables matching wild is returned
unknown's avatar
unknown committed
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
*****************************************************************************/

MYSQL_RES * STDCALL
mysql_list_tables(MYSQL *mysql, const char *wild)
{
  char buff[255];
  DBUG_ENTER("mysql_list_tables");

  append_wild(strmov(buff,"show tables"),buff+sizeof(buff),wild);
  if (mysql_query(mysql,buff))
    DBUG_RETURN(0);
  DBUG_RETURN (mysql_store_result(mysql));
}

1205

unknown's avatar
unknown committed
1206
MYSQL_FIELD *cli_list_fields(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
1207 1208 1209 1210 1211 1212
{
  MYSQL_DATA *query;
  if (!(query= cli_read_rows(mysql,(MYSQL_FIELD*) 0, 
			     protocol_41(mysql) ? 8 : 6)))
    return NULL;

unknown's avatar
unknown committed
1213
  mysql->field_count= (uint) query->rows;
unknown's avatar
SCRUM  
unknown committed
1214
  return unpack_fields(query,&mysql->field_alloc,
unknown's avatar
unknown committed
1215
		       mysql->field_count, 1, mysql->server_capabilities);
unknown's avatar
SCRUM  
unknown committed
1216 1217 1218
}


unknown's avatar
unknown committed
1219
/**************************************************************************
1220 1221 1222 1223
  List all fields in a table
  If wild is given then only the fields matching wild is returned
  Instead of this use query:
  show fields in 'table' like "wild"
unknown's avatar
unknown committed
1224 1225 1226
**************************************************************************/

MYSQL_RES * STDCALL
unknown's avatar
SCRUM  
unknown committed
1227
mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
unknown's avatar
unknown committed
1228
{
unknown's avatar
SCRUM  
unknown committed
1229 1230
  MYSQL_RES   *result;
  MYSQL_FIELD *fields;
unknown's avatar
unknown committed
1231 1232 1233 1234 1235
  char	     buff[257],*end;
  DBUG_ENTER("mysql_list_fields");
  DBUG_PRINT("enter",("table: '%s'  wild: '%s'",table,wild ? wild : ""));

  end=strmake(strmake(buff, table,128)+1,wild ? wild : "",128);
unknown's avatar
SCRUM  
unknown committed
1236
  free_old_query(mysql);
unknown's avatar
unknown committed
1237
  if (simple_command(mysql,COM_FIELD_LIST,buff,(ulong) (end-buff),1) ||
unknown's avatar
SCRUM  
unknown committed
1238
      !(fields= (*mysql->methods->list_fields)(mysql)))
unknown's avatar
unknown committed
1239 1240 1241 1242 1243
    DBUG_RETURN(NULL);

  if (!(result = (MYSQL_RES *) my_malloc(sizeof(MYSQL_RES),
					 MYF(MY_WME | MY_ZEROFILL))))
    DBUG_RETURN(NULL);
unknown's avatar
SCRUM  
unknown committed
1244

1245
  result->methods= mysql->methods;
unknown's avatar
unknown committed
1246 1247
  result->field_alloc=mysql->field_alloc;
  mysql->fields=0;
unknown's avatar
SCRUM  
unknown committed
1248 1249
  result->field_count = mysql->field_count;
  result->fields= fields;
unknown's avatar
unknown committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
  result->eof=1;
  DBUG_RETURN(result);
}

/* List all running processes (threads) in server */

MYSQL_RES * STDCALL
mysql_list_processes(MYSQL *mysql)
{
  MYSQL_DATA *fields;
  uint field_count;
  uchar *pos;
  DBUG_ENTER("mysql_list_processes");

  LINT_INIT(fields);
  if (simple_command(mysql,COM_PROCESS_INFO,0,0,0))
    DBUG_RETURN(0);
  free_old_query(mysql);
  pos=(uchar*) mysql->net.read_pos;
  field_count=(uint) net_field_length(&pos);
unknown's avatar
SCRUM  
unknown committed
1270 1271
  if (!(fields = (*mysql->methods->read_rows)(mysql,(MYSQL_FIELD*) 0,
					      protocol_41(mysql) ? 7 : 5)))
unknown's avatar
unknown committed
1272 1273
    DBUG_RETURN(NULL);
  if (!(mysql->fields=unpack_fields(fields,&mysql->field_alloc,field_count,0,
1274
				    mysql->server_capabilities)))
unknown's avatar
unknown committed
1275 1276 1277 1278 1279 1280
    DBUG_RETURN(0);
  mysql->status=MYSQL_STATUS_GET_RESULT;
  mysql->field_count=field_count;
  DBUG_RETURN(mysql_store_result(mysql));
}

1281

1282
#ifdef USE_OLD_FUNCTIONS
unknown's avatar
unknown committed
1283 1284 1285 1286 1287
int  STDCALL
mysql_create_db(MYSQL *mysql, const char *db)
{
  DBUG_ENTER("mysql_createdb");
  DBUG_PRINT("enter",("db: %s",db));
unknown's avatar
unknown committed
1288
  DBUG_RETURN(simple_command(mysql,COM_CREATE_DB,db, (ulong) strlen(db),0));
unknown's avatar
unknown committed
1289 1290 1291 1292 1293 1294 1295 1296
}


int  STDCALL
mysql_drop_db(MYSQL *mysql, const char *db)
{
  DBUG_ENTER("mysql_drop_db");
  DBUG_PRINT("enter",("db: %s",db));
unknown's avatar
unknown committed
1297
  DBUG_RETURN(simple_command(mysql,COM_DROP_DB,db,(ulong) strlen(db),0));
unknown's avatar
unknown committed
1298
}
1299
#endif
unknown's avatar
unknown committed
1300 1301 1302


int STDCALL
1303
mysql_shutdown(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level)
unknown's avatar
unknown committed
1304
{
1305
  uchar level[1];
unknown's avatar
unknown committed
1306
  DBUG_ENTER("mysql_shutdown");
unknown's avatar
unknown committed
1307
  level[0]= (uchar) shutdown_level;
1308
  DBUG_RETURN(simple_command(mysql, COM_SHUTDOWN, (char *)level, 1, 0));
unknown's avatar
unknown committed
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
}


int STDCALL
mysql_refresh(MYSQL *mysql,uint options)
{
  uchar bits[1];
  DBUG_ENTER("mysql_refresh");
  bits[0]= (uchar) options;
  DBUG_RETURN(simple_command(mysql,COM_REFRESH,(char*) bits,1,0));
}

1321

unknown's avatar
unknown committed
1322 1323 1324
int STDCALL
mysql_kill(MYSQL *mysql,ulong pid)
{
1325
  char buff[4];
unknown's avatar
unknown committed
1326 1327
  DBUG_ENTER("mysql_kill");
  int4store(buff,pid);
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
  DBUG_RETURN(simple_command(mysql,COM_PROCESS_KILL,buff,sizeof(buff),0));
}


int STDCALL
mysql_set_server_option(MYSQL *mysql, enum enum_mysql_set_option option)
{
  char buff[2];
  DBUG_ENTER("mysql_set_server_option");
  int2store(buff, (uint) option);
  DBUG_RETURN(simple_command(mysql, COM_SET_OPTION, buff, sizeof(buff), 0));
unknown's avatar
unknown committed
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
}


int STDCALL
mysql_dump_debug_info(MYSQL *mysql)
{
  DBUG_ENTER("mysql_dump_debug_info");
  DBUG_RETURN(simple_command(mysql,COM_DEBUG,0,0,0));
}

1349

unknown's avatar
Rename:  
unknown committed
1350
const char *cli_read_statistics(MYSQL *mysql)
unknown's avatar
unknown committed
1351 1352 1353 1354
{
  mysql->net.read_pos[mysql->packet_length]=0;	/* End of stat string */
  if (!mysql->net.read_pos[0])
  {
1355
    strmov(mysql->net.sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
1356 1357 1358 1359
    mysql->net.last_errno=CR_WRONG_HOST_INFO;
    strmov(mysql->net.last_error, ER(mysql->net.last_errno));
    return mysql->net.last_error;
  }
unknown's avatar
unknown committed
1360 1361 1362
  return (char*) mysql->net.read_pos;
}

1363

unknown's avatar
unknown committed
1364 1365 1366 1367 1368 1369
const char * STDCALL
mysql_stat(MYSQL *mysql)
{
  DBUG_ENTER("mysql_stat");
  if (simple_command(mysql,COM_STATISTICS,0,0,0))
    return mysql->net.last_error;
unknown's avatar
Rename:  
unknown committed
1370
  DBUG_RETURN((*mysql->methods->read_statistics)(mysql));
unknown's avatar
unknown committed
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
}


int STDCALL
mysql_ping(MYSQL *mysql)
{
  DBUG_ENTER("mysql_ping");
  DBUG_RETURN(simple_command(mysql,COM_PING,0,0,0));
}


unknown's avatar
unknown committed
1382
const char * STDCALL
unknown's avatar
unknown committed
1383 1384 1385 1386 1387 1388
mysql_get_server_info(MYSQL *mysql)
{
  return((char*) mysql->server_version);
}


1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
/*
  Get version number for server in a form easy to test on

  SYNOPSIS
    mysql_get_server_version()
    mysql		Connection

  EXAMPLE
    4.1.0-alfa ->  40100
  
  NOTES
    We will ensure that a newer server always has a bigger number.

  RETURN
   Signed number > 323000
*/

ulong STDCALL
mysql_get_server_version(MYSQL *mysql)
{
  uint major, minor, version;
  char *pos= mysql->server_version, *end_pos;
  major=   (uint) strtoul(pos, &end_pos, 10);	pos=end_pos+1;
  minor=   (uint) strtoul(pos, &end_pos, 10);	pos=end_pos+1;
  version= (uint) strtoul(pos, &end_pos, 10);
  return (ulong) major*10000L+(ulong) (minor*100+version);
}


unknown's avatar
unknown committed
1418
const char * STDCALL
unknown's avatar
unknown committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
mysql_get_host_info(MYSQL *mysql)
{
  return(mysql->host_info);
}


uint STDCALL
mysql_get_proto_info(MYSQL *mysql)
{
  return (mysql->protocol_version);
}

unknown's avatar
unknown committed
1431
const char * STDCALL
unknown's avatar
unknown committed
1432 1433 1434 1435 1436
mysql_get_client_info(void)
{
  return (char*) MYSQL_SERVER_VERSION;
}

unknown's avatar
unknown committed
1437 1438 1439 1440 1441
ulong STDCALL mysql_get_client_version(void)
{
  return MYSQL_VERSION_ID;
}

unknown's avatar
unknown committed
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
my_bool STDCALL mysql_eof(MYSQL_RES *res)
{
  return res->eof;
}

MYSQL_FIELD * STDCALL mysql_fetch_field_direct(MYSQL_RES *res,uint fieldnr)
{
  return &(res)->fields[fieldnr];
}

MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res)
{
  return (res)->fields;
}

unknown's avatar
unknown committed
1457
MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res)
unknown's avatar
unknown committed
1458 1459 1460 1461
{
  return res->data_cursor;
}

unknown's avatar
unknown committed
1462
MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res)
unknown's avatar
unknown committed
1463 1464 1465 1466 1467 1468 1469 1470
{
  return (res)->current_field;
}

/* MYSQL */

unsigned int STDCALL mysql_field_count(MYSQL *mysql)
{
1471
  return mysql->last_used_con->field_count;
unknown's avatar
unknown committed
1472 1473 1474 1475
}

my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql)
{
1476
  return mysql->last_used_con->affected_rows;
unknown's avatar
unknown committed
1477 1478 1479 1480
}

my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql)
{
1481
  return mysql->last_used_con->insert_id;
unknown's avatar
unknown committed
1482 1483
}

1484 1485 1486 1487 1488
const char *STDCALL mysql_sqlstate(MYSQL *mysql)
{
  return mysql->net.sqlstate;
}

1489 1490 1491 1492 1493
uint STDCALL mysql_warning_count(MYSQL *mysql)
{
  return mysql->warning_count;
}

unknown's avatar
unknown committed
1494
const char *STDCALL mysql_info(MYSQL *mysql)
unknown's avatar
unknown committed
1495
{
1496
  return mysql->info;
unknown's avatar
unknown committed
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
}

ulong STDCALL mysql_thread_id(MYSQL *mysql)
{
  return (mysql)->thread_id;
}

const char * STDCALL mysql_character_set_name(MYSQL *mysql)
{
  return mysql->charset->name;
}


uint STDCALL mysql_thread_safe(void)
{
#ifdef THREAD
  return 1;
#else
  return 0;
#endif
}

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528

my_bool STDCALL mysql_embedded(void)
{
#ifdef EMBEDDED_LIBRARY
  return 1;
#else
  return 0;
#endif
}

unknown's avatar
unknown committed
1529
/****************************************************************************
1530
  Some support functions
unknown's avatar
unknown committed
1531 1532
****************************************************************************/

unknown's avatar
unknown committed
1533 1534 1535 1536 1537 1538 1539 1540 1541
/*
  Functions called my my_net_init() to set some application specific variables
*/

void my_net_local_init(NET *net)
{
  net->max_packet=   (uint) net_buffer_length;
  net->read_timeout= (uint) net_read_timeout;
  net->write_timeout=(uint) net_write_timeout;
1542
  net->retry_count=  1;
unknown's avatar
unknown committed
1543 1544 1545
  net->max_packet_size= max(net_buffer_length, max_allowed_packet);
}

unknown's avatar
unknown committed
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
/*
  This function is used to create HEX string that you
  can use in a SQL statement in of the either ways:
    INSERT INTO blob_column VALUES (0xAABBCC);  (any MySQL version)
    INSERT INTO blob_column VALUES (X'AABBCC'); (4.1 and higher)
  
  The string in "from" is encoded to a HEX string.
  The result is placed in "to" and a terminating null byte is appended.
  
  The string pointed to by "from" must be "length" bytes long.
  You must allocate the "to" buffer to be at least length*2+1 bytes long.
  Each character needs two bytes, and you need room for the terminating
  null byte. When mysql_hex_string() returns, the contents of "to" will
  be a null-terminated string. The return value is the length of the
  encoded string, not including the terminating null character.

  The return value does not contain any leading 0x or a leading X' and
  trailing '. The caller must supply whichever of those is desired.
*/

unknown's avatar
unknown committed
1566 1567
ulong STDCALL
mysql_hex_string(char *to, const char *from, ulong length)
unknown's avatar
unknown committed
1568 1569 1570 1571 1572 1573
{
  char *to0= to;
  const char *end;
            
  for (end= from + length; from < end; from++)
  {
unknown's avatar
unknown committed
1574 1575
    *to++= _dig_vec_upper[((unsigned char) *from) >> 4];
    *to++= _dig_vec_upper[((unsigned char) *from) & 0x0F];
unknown's avatar
unknown committed
1576 1577 1578 1579 1580
  }
  *to= '\0';
  return (ulong) (to-to0);
}

unknown's avatar
unknown committed
1581
/*
1582 1583 1584
  Add escape characters to a string (blob?) to make it suitable for a insert
  to should at least have place for length*2+1 chars
  Returns the length of the to string
unknown's avatar
unknown committed
1585 1586 1587 1588 1589
*/

ulong STDCALL
mysql_escape_string(char *to,const char *from,ulong length)
{
1590
  return escape_string_for_mysql(default_charset_info, to, from, length);
unknown's avatar
unknown committed
1591 1592 1593 1594 1595 1596
}

ulong STDCALL
mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
			 ulong length)
{
1597
  return escape_string_for_mysql(mysql->charset, to, from, length);
unknown's avatar
unknown committed
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
}


char * STDCALL
mysql_odbc_escape_string(MYSQL *mysql,
			 char *to, ulong to_length,
			 const char *from, ulong from_length,
			 void *param,
			 char * (*extend_buffer)
			 (void *, char *, ulong *))
{
  char *to_end=to+to_length-5;
  const char *end;
#ifdef USE_MB
  my_bool use_mb_flag=use_mb(mysql->charset);
#endif

  for (end=from+from_length; from != end ; from++)
  {
    if (to >= to_end)
    {
      to_length = (ulong) (end-from)+512;	/* We want this much more */
      if (!(to=(*extend_buffer)(param, to, &to_length)))
	return to;
      to_end=to+to_length-5;
    }
#ifdef USE_MB
    {
      int l;
      if (use_mb_flag && (l = my_ismbchar(mysql->charset, from, end)))
      {
	while (l--)
	  *to++ = *from++;
	from--;
	continue;
      }
    }
#endif
    switch (*from) {
    case 0:				/* Must be escaped for 'mysql' */
      *to++= '\\';
      *to++= '0';
      break;
    case '\n':				/* Must be escaped for logs */
      *to++= '\\';
      *to++= 'n';
      break;
    case '\r':
      *to++= '\\';
      *to++= 'r';
      break;
    case '\\':
      *to++= '\\';
      *to++= '\\';
      break;
    case '\'':
      *to++= '\\';
      *to++= '\'';
      break;
    case '"':				/* Better safe than sorry */
      *to++= '\\';
      *to++= '"';
      break;
    case '\032':			/* This gives problems on Win32 */
      *to++= '\\';
      *to++= 'Z';
      break;
    default:
      *to++= *from;
    }
  }
  return to;
}

void STDCALL
myodbc_remove_escape(MYSQL *mysql,char *name)
{
  char *to;
#ifdef USE_MB
  my_bool use_mb_flag=use_mb(mysql->charset);
  char *end;
  LINT_INIT(end);
  if (use_mb_flag)
    for (end=name; *end ; end++) ;
#endif

  for (to=name ; *name ; name++)
  {
#ifdef USE_MB
    int l;
    if (use_mb_flag && (l = my_ismbchar( mysql->charset, name , end ) ) )
    {
      while (l--)
	*to++ = *name++;
      name--;
      continue;
    }
#endif
    if (*name == '\\' && name[1])
      name++;
    *to++= *name;
  }
  *to=0;
}
1702 1703

/********************************************************************
1704
 Implementation of new client API for 4.1 version.
1705

1706
 mysql_stmt_* are real prototypes used by applications.
1707

1708 1709 1710 1711 1712
 To make API work in embedded library all functions performing
 real I/O are prefixed with 'cli_' (abbreviated from 'Call Level
 Interface'). This functions are invoked via pointers set in
 MYSQL::methods structure. Embedded counterparts, prefixed with
 'emb_' reside in libmysqld/lib_sql.cc.
1713 1714
*********************************************************************/

1715
/******************* Declarations ***********************************/
1716

1717

1718
/*
1719 1720 1721 1722 1723
  These functions are called by function pointer MYSQL_STMT::read_row_func.
  Each function corresponds to one of the read methods:
  - mysql_stmt_fetch without prior mysql_stmt_store_result,
  - mysql_stmt_fetch when result is stored,
  - mysql_stmt_fetch when there are no rows (always returns MYSQL_NO_DATA)
1724 1725
*/

1726 1727 1728
static int stmt_read_row_unbuffered(MYSQL_STMT *stmt, unsigned char **row);
static int stmt_read_row_buffered(MYSQL_STMT *stmt, unsigned char **row);
static int stmt_read_row_no_data(MYSQL_STMT *stmt, unsigned char **row);
1729

1730 1731 1732 1733 1734
/*
  This function is used in mysql_stmt_store_result if
  STMT_ATTR_UPDATE_MAX_LENGTH attribute is set.
*/
static void stmt_update_metadata(MYSQL_STMT *stmt, MYSQL_ROWS *data);
1735

1736 1737 1738 1739 1740 1741
/*
  Maximum sizes of MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME
  values stored in network buffer.
*/

/* 1 (length) + 2 (year) + 1 (month) + 1 (day) */
1742
#define MAX_DATE_REP_LENGTH 5
1743 1744 1745 1746 1747

/*
  1 (length) + 1 (is negative) + 4 (day count) + 1 (hour)
  + 1 (minute) + 1 (seconds) + 4 (microseconds)
*/
1748
#define MAX_TIME_REP_LENGTH 13
1749 1750 1751 1752 1753

/*
  1 (length) + 2 (year) + 1 (month) + 1 (day) +
  1 (hour) + 1 (minute) + 1 (second) + 4 (microseconds)
*/
1754
#define MAX_DATETIME_REP_LENGTH 12
1755

1756
#define MAX_DOUBLE_STRING_REP_LENGTH 331
1757

1758
/**************** Misc utility functions ****************************/
1759 1760

/*
1761
  Reallocate the NET package to have at least length bytes available.
1762

1763
  SYNPOSIS
1764 1765 1766 1767
    my_realloc_str()
    net                 The NET structure to modify.
    length              Ensure that net->buff has space for at least
                        this number of bytes.
1768

1769
  RETURN VALUES
1770 1771 1772
    0   Success.
    1   Error, i.e. out of memory or requested packet size is bigger
        than max_allowed_packet. The error code is stored in net->last_errno.
1773 1774
*/

1775
static my_bool my_realloc_str(NET *net, ulong length)
1776
{
1777 1778 1779 1780
  ulong buf_length= (ulong) (net->write_pos - net->buff);
  my_bool res=0;
  DBUG_ENTER("my_realloc_str");
  if (buf_length + length > net->max_packet)
1781
  {
1782 1783
    res= net_realloc(net, buf_length + length);
    net->write_pos= net->buff+ buf_length;
1784
  }
1785
  DBUG_RETURN(res);
1786 1787 1788
}


1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
/*
  Set statement error code, sqlstate, and error message
  from given errcode and sqlstate.
*/

static void set_stmt_error(MYSQL_STMT * stmt, int errcode,
                           const char *sqlstate)
{
  DBUG_ENTER("set_stmt_error");
  DBUG_PRINT("enter", ("error: %d '%s'", errcode, ER(errcode)));
  DBUG_ASSERT(stmt != 0);

  stmt->last_errno= errcode;
  strmov(stmt->last_error, ER(errcode));
  strmov(stmt->sqlstate, sqlstate);

  DBUG_VOID_RETURN;
}


/*
  Set statement error code, sqlstate, and error message.
*/

void set_stmt_errmsg(MYSQL_STMT * stmt, const char *err, int errcode,
                     const char *sqlstate)
{
  DBUG_ENTER("set_stmt_errmsg");
  DBUG_PRINT("enter", ("error: %d/%s '%s'", errcode, sqlstate, err));
  DBUG_ASSERT(stmt != 0);

  stmt->last_errno= errcode;
  if (err && err[0])
    strmov(stmt->last_error, err);
  strmov(stmt->sqlstate, sqlstate);

  DBUG_VOID_RETURN;
}
1827

1828
/*
1829 1830
  Read and unpack server reply to COM_PREPARE command (sent from
  mysql_stmt_prepare).
1831

1832 1833 1834 1835
  SYNOPSIS
    cli_read_prepare_result()
    mysql   connection handle
    stmt    statement handle
1836 1837 1838 1839

  RETURN VALUES
    0	ok
    1	error
1840 1841
*/

unknown's avatar
unknown committed
1842
my_bool cli_read_prepare_result(MYSQL *mysql, MYSQL_STMT *stmt)
1843 1844
{
  uchar *pos;
1845
  uint field_count, param_count;
1846
  MYSQL_DATA *fields_data;
unknown's avatar
SCRUM  
unknown committed
1847
  DBUG_ENTER("read_prepare_result");
1848

1849
  mysql= mysql->last_used_con;
1850
  if (net_safe_read(mysql) == packet_error)
1851
    DBUG_RETURN(1);
1852

1853
  pos= (uchar*) mysql->net.read_pos;
1854
  stmt->stmt_id= uint4korr(pos+1); pos+= 5;
1855
  /* Number of columns in result set */
1856
  field_count=   uint2korr(pos);   pos+= 2;
1857
  /* Number of placeholders in the statement */
1858
  param_count=   uint2korr(pos);   pos+= 2;
1859

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
  if (param_count != 0)
  {
    MYSQL_DATA *param_data;

    /* skip parameters data: we don't support it yet */
    if (!(param_data= (*mysql->methods->read_rows)(mysql, (MYSQL_FIELD*)0, 7)))
      DBUG_RETURN(1);
    free_rows(param_data);
  }

1870 1871 1872 1873
  if (field_count != 0)
  {
    if (!(mysql->server_status & SERVER_STATUS_AUTOCOMMIT))
      mysql->server_status|= SERVER_STATUS_IN_TRANS;
1874

1875
    mysql->extra_info= net_field_length_ll(&pos);
unknown's avatar
SCRUM  
unknown committed
1876
    if (!(fields_data= (*mysql->methods->read_rows)(mysql,(MYSQL_FIELD*)0,7)))
1877 1878 1879 1880 1881 1882
      DBUG_RETURN(1);
    if (!(stmt->fields= unpack_fields(fields_data,&stmt->mem_root,
				      field_count,0,
				      mysql->server_capabilities)))
      DBUG_RETURN(1);
  }
1883 1884
  stmt->field_count=  (uint) field_count;
  stmt->param_count=  (ulong) param_count;
1885
  mysql->warning_count= 0;
unknown's avatar
SCRUM  
unknown committed
1886

1887 1888 1889 1890 1891
  DBUG_RETURN(0);
}


/*
1892 1893
  Allocate memory and init prepared statement structure.

1894 1895
  SYNOPSIS
    mysql_stmt_init()
1896 1897 1898 1899 1900 1901 1902
    mysql   connection handle

  DESCRIPTION
    This is an entry point of the new API. Returned handle stands for
    a server-side prepared statement. Memory for this structure (~700
    bytes) is allocated using 'malloc'. Once created, the handle can be
    reused many times. Created statement handle is bound to connection
unknown's avatar
unknown committed
1903
    handle provided to this call: its lifetime is limited by lifetime
1904 1905 1906 1907 1908 1909
    of connection.
    'mysql_stmt_init()' is a pure local call, server side structure is
    created only in mysql_stmt_prepare.
    Next steps you may want to make:
    - set a statement attribute (mysql_stmt_attr_set()),
    - prepare statement handle with a query (mysql_stmt_prepare()),
unknown's avatar
unknown committed
1910
    - close statement handle and free its memory (mysql_stmt_close()),
1911 1912 1913 1914 1915
    - reset statement with mysql_stmt_reset() (a no-op which will
      just return).
    Behaviour of the rest of API calls on this statement is not defined yet
    (though we're working on making each wrong call sequence return
    error).
1916

1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
  RETURN VALUE
    statement structure upon success and NULL if out of
    memory
*/

MYSQL_STMT * STDCALL
mysql_stmt_init(MYSQL *mysql)
{
  MYSQL_STMT *stmt;
  DBUG_ENTER("mysql_stmt_init");

  if (!(stmt= (MYSQL_STMT *) my_malloc(sizeof(MYSQL_STMT),
                                       MYF(MY_WME | MY_ZEROFILL))))
  {
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
    DBUG_RETURN(0);
  }

1935
  init_alloc_root(&stmt->mem_root, 2048, 2048);
1936 1937
  init_alloc_root(&stmt->result.alloc, 4096, 4096);
  stmt->result.alloc.min_malloc= sizeof(MYSQL_ROWS);
1938 1939
  mysql->stmts= list_add(mysql->stmts, &stmt->list);
  stmt->list.data= stmt;
1940
  stmt->state= MYSQL_STMT_INIT_DONE;
1941
  stmt->mysql= mysql;
1942 1943
  stmt->read_row_func= stmt_read_row_no_data;
  /* The rest of statement members was bzeroed inside malloc */
1944 1945 1946 1947

  DBUG_RETURN(stmt);
}

1948

1949
/*
1950 1951
  Prepare server side statement with query.

1952 1953
  SYNOPSIS
    mysql_stmt_prepare()
1954 1955 1956
    stmt    statement handle
    query   statement to prepare
    length  statement length
1957 1958

  DESCRIPTION
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
    Associate statement with statement handle. This is done both on
    client and server sides. At this point the server parses given query
    and creates an internal structure to represent it.
    Next steps you may want to make:
    - find out if this statement returns a result set by
      calling mysql_stmt_field_count(), and get result set metadata
      with mysql_stmt_result_metadata(),
    - if query contains placeholders, bind input parameters to placeholders
      using mysql_stmt_bind_param(),
    - otherwise proceed directly to mysql_stmt_execute().

  IMPLEMENTATION NOTES
  - if this is a re-prepare of the statement, first close previous data
1972
    structure on the server and free old statement data
1973
  - then send the query to server and get back number of placeholders,
1974
    number of columns in result set (if any), and result set metadata.
1975
    At the same time allocate memory for input and output parameters
1976
    to have less checks in mysql_stmt_bind_{param, result}.
1977

1978 1979
  RETURN VALUES
    0  success
1980
   !0  error
1981 1982
*/

1983 1984
int STDCALL
mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, ulong length)
1985
{
1986 1987 1988
  MYSQL *mysql= stmt->mysql;
  DBUG_ENTER("mysql_stmt_prepare");

1989
  if (!mysql)
1990
  {
1991 1992
    /* mysql can be reset in mysql_close called from mysql_reconnect */
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
1993
    DBUG_RETURN(1);
1994
  }
1995 1996 1997 1998

  if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
  {
    /* This is second prepare with another statement */
1999
    char buff[MYSQL_STMT_HEADER];               /* 4 bytes - stmt id */
2000 2001 2002

    mysql_stmt_free_result(stmt);
    /*
2003
      These members must be reset for API to
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
      function in case of error or misuse.
    */
    stmt->bind_param_done= stmt->bind_result_done= FALSE;
    stmt->param_count= stmt->field_count= 0;
    stmt->last_errno= 0;
    stmt->last_error[0]= '\0';
    free_root(&stmt->mem_root, MYF(MY_KEEP_PREALLOC));

    int4store(buff, stmt->stmt_id);
    /*
      If there was a 'use' result from another statement, or from
      mysql_use_result it won't be freed in mysql_stmt_free_result and
      we should get 'Commands out of sync' here.
    */
    if (simple_command(mysql, COM_CLOSE_STMT, buff, 4, 1))
    {
      set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                      mysql->net.sqlstate);
      DBUG_RETURN(1);
    }
    stmt->state= MYSQL_STMT_INIT_DONE;
  }

2027 2028
  if (simple_command(mysql, COM_PREPARE, query, length, 1))
  {
2029 2030 2031
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                    mysql->net.sqlstate);
    DBUG_RETURN(1);
2032 2033
  }

unknown's avatar
SCRUM  
unknown committed
2034
  if ((*mysql->methods->read_prepare_result)(mysql, stmt))
2035 2036 2037
  {
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                    mysql->net.sqlstate);
2038
    DBUG_RETURN(1);
2039
  }
unknown's avatar
SCRUM:  
unknown committed
2040

2041
  /*
2042
    alloc_root will return valid address even in case when param_count
2043 2044 2045 2046
    and field_count are zero. Thus we should never rely on stmt->bind
    or stmt->params when checking for existence of placeholders or
    result set.
  */
unknown's avatar
SCRUM:  
unknown committed
2047 2048
  if (!(stmt->params= (MYSQL_BIND *) alloc_root(&stmt->mem_root,
						sizeof(MYSQL_BIND)*
2049
                                                (stmt->param_count +
unknown's avatar
SCRUM:  
unknown committed
2050 2051 2052
                                                 stmt->field_count))))
  {
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
2053
    DBUG_RETURN(1);
unknown's avatar
SCRUM:  
unknown committed
2054 2055
  }
  stmt->bind= stmt->params + stmt->param_count;
2056
  stmt->state= MYSQL_STMT_PREPARE_DONE;
2057
  DBUG_PRINT("info", ("Parameter count: %ld", stmt->param_count));
2058
  DBUG_RETURN(0);
2059 2060
}

2061
/*
2062 2063 2064 2065
  Get result set metadata from reply to mysql_stmt_execute.
  This is used mainly for SHOW commands, as metadata for these
  commands is sent only with result set.
  To be removed when all commands will fully support prepared mode.
2066 2067
*/

2068
static unsigned int alloc_stmt_fields(MYSQL_STMT *stmt)
2069
{
2070 2071
  MYSQL_FIELD *fields, *field, *end;
  MEM_ROOT *alloc= &stmt->mem_root;
unknown's avatar
unknown committed
2072
  MYSQL *mysql= stmt->mysql->last_used_con;
2073

unknown's avatar
unknown committed
2074
  stmt->field_count= mysql->field_count;
2075

2076
  /*
2077
    Get the field information for non-select statements
2078 2079
    like SHOW and DESCRIBE commands
  */
2080
  if (!(stmt->fields= (MYSQL_FIELD *) alloc_root(alloc,
2081
						 sizeof(MYSQL_FIELD) *
2082 2083
						 stmt->field_count)) ||
      !(stmt->bind= (MYSQL_BIND *) alloc_root(alloc,
2084 2085
					      sizeof(MYSQL_BIND) *
					      stmt->field_count)))
2086
    return 0;
2087 2088

  for (fields= mysql->fields, end= fields+stmt->field_count,
2089
	 field= stmt->fields;
2090 2091 2092 2093 2094 2095 2096
       field && fields < end; fields++, field++)
  {
    field->db       = strdup_root(alloc,fields->db);
    field->table    = strdup_root(alloc,fields->table);
    field->org_table= strdup_root(alloc,fields->org_table);
    field->name     = strdup_root(alloc,fields->name);
    field->org_name = strdup_root(alloc,fields->org_name);
2097
    field->charsetnr= fields->charsetnr;
2098 2099 2100 2101 2102 2103 2104
    field->length   = fields->length;
    field->type     = fields->type;
    field->flags    = fields->flags;
    field->decimals = fields->decimals;
    field->def      = fields->def ? strdup_root(alloc,fields->def): 0;
    field->max_length= 0;
  }
2105 2106
  return stmt->field_count;
}
2107

2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131

/*
  Update result set columns metadata if it was sent again in
  reply to COM_EXECUTE.
*/

static void update_stmt_fields(MYSQL_STMT *stmt)
{
  MYSQL_FIELD *field= stmt->mysql->fields;
  MYSQL_FIELD *field_end= field + stmt->field_count;
  MYSQL_FIELD *stmt_field= stmt->fields;

  DBUG_ASSERT(stmt->field_count == stmt->mysql->field_count);

  for (; field < field_end; ++field, ++stmt_field)
  {
    stmt_field->charsetnr= field->charsetnr;
    stmt_field->length   = field->length;
    stmt_field->type     = field->type;
    stmt_field->flags    = field->flags;
    stmt_field->decimals = field->decimals;
  }
}

2132
/*
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
  Returns prepared statement metadata in the form of a result set.

  SYNOPSIS
    mysql_stmt_result_metadata()
    stmt  statement handle

  DESCRIPTION
    This function should be used after mysql_stmt_execute().
    You can safely check that prepared statement has a result set by calling
    mysql_stmt_num_fields(): if number of fields is not zero, you can call
    this function to get fields metadata.
    Next steps you may want to make:
    - find out number of columns in result set by calling
      mysql_num_fields(res) (the same value is returned by
      mysql_stmt_num_fields)
    - fetch metadata for any column with mysql_fetch_field,
      mysql_fetch_field_direct, mysql_fetch_fields, mysql_field_seek.
    - free returned MYSQL_RES structure with mysql_free_result.
    - proceed to binding of output parameters.
2152 2153 2154 2155 2156 2157

  RETURN
    NULL  statement contains no result set or out of memory.
          In the latter case you can retreive error message
          with mysql_stmt_error.
    MYSQL_RES  a result set with no rows
2158 2159 2160
*/

MYSQL_RES * STDCALL
2161
mysql_stmt_result_metadata(MYSQL_STMT *stmt)
2162 2163
{
  MYSQL_RES *result;
2164
  DBUG_ENTER("mysql_stmt_result_metadata");
2165

2166 2167 2168 2169 2170 2171 2172 2173 2174
  /*
    stmt->fields is only defined if stmt->field_count is not null;
    stmt->field_count is initialized in prepare.
  */
  if (!stmt->field_count)
     DBUG_RETURN(0);

  if (!(result=(MYSQL_RES*) my_malloc(sizeof(*result),
                                      MYF(MY_WME | MY_ZEROFILL))))
2175
  {
2176 2177 2178
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
2179

2180 2181
  result->methods=	stmt->mysql->methods;
  result->eof=		1;                      /* Marker for buffered */
2182 2183
  result->fields=	stmt->fields;
  result->field_count=	stmt->field_count;
2184
  /* The rest of members of 'result' was bzeroed inside malloc */
2185
  DBUG_RETURN(result);
2186 2187
}

2188

2189
/*
2190 2191
  Returns parameter columns meta information in the form of
  result set.
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204

  SYNOPSYS
    mysql_stmt_param_metadata()
    stmt    statement handle

  DESCRIPTION
    This function can be called after you prepared the statement handle
    with mysql_stmt_prepare().
    XXX: not implemented yet.

  RETURN
    MYSQL_RES on success, 0 if there is no metadata.
    Currently this function always returns 0.
2205 2206 2207
*/

MYSQL_RES * STDCALL
2208
mysql_stmt_param_metadata(MYSQL_STMT *stmt)
2209
{
2210
  DBUG_ENTER("mysql_stmt_param_metadata");
2211

2212 2213 2214 2215
  if (!stmt->param_count)
    DBUG_RETURN(0);

  /*
2216 2217
    TODO: Fix this when server sends the information.
    Till then keep a dummy prototype.
2218 2219 2220 2221 2222
  */
  DBUG_RETURN(0); 
}


2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
/* Store type of parameter in network buffer. */

static void store_param_type(char **pos, MYSQL_BIND *param)
{
  uint typecode= param->buffer_type | (param->is_unsigned ? 32768 : 0);
  int2store(*pos, typecode);
  *pos+= 2;
}


2233 2234
/*
  Functions to store parameter data in network packet.
2235

2236 2237 2238 2239 2240
  SYNOPSIS
    store_param_xxx()
    net			MySQL NET connection
    param		MySQL bind param

2241
  DESCRIPTION
2242 2243 2244 2245 2246
    These funtions are invoked from mysql_stmt_execute() by
    MYSQL_BIND::store_param_func pointer. This pointer is set once per
    many executions in mysql_stmt_bind_param(). The caller must ensure
    that network buffer have enough capacity to store parameter
    (MYSQL_BIND::buffer_length contains needed number of bytes).
2247
*/
2248 2249 2250

static void store_param_tinyint(NET *net, MYSQL_BIND *param)
{
2251
  *(net->write_pos++)= *(uchar *) param->buffer;
2252 2253
}

2254 2255 2256 2257 2258 2259
static void store_param_short(NET *net, MYSQL_BIND *param)
{
  short value= *(short*) param->buffer;
  int2store(net->write_pos,value);
  net->write_pos+=2;
}
2260

2261
static void store_param_int32(NET *net, MYSQL_BIND *param)
2262
{
2263 2264 2265 2266
  int32 value= *(int32*) param->buffer;
  int4store(net->write_pos,value);
  net->write_pos+=4;
}
2267

2268 2269 2270 2271 2272 2273
static void store_param_int64(NET *net, MYSQL_BIND *param)
{
  longlong value= *(longlong*) param->buffer;
  int8store(net->write_pos,value);
  net->write_pos+= 8;
}
2274

2275 2276 2277 2278 2279
static void store_param_float(NET *net, MYSQL_BIND *param)
{
  float value= *(float*) param->buffer;
  float4store(net->write_pos, value);
  net->write_pos+= 4;
2280 2281
}

2282 2283 2284 2285 2286 2287
static void store_param_double(NET *net, MYSQL_BIND *param)
{
  double value= *(double*) param->buffer;
  float8store(net->write_pos, value);
  net->write_pos+= 8;
}
2288

unknown's avatar
unknown committed
2289 2290 2291
static void store_param_time(NET *net, MYSQL_BIND *param)
{
  MYSQL_TIME *tm= (MYSQL_TIME *) param->buffer;
2292
  char buff[MAX_TIME_REP_LENGTH], *pos;
unknown's avatar
unknown committed
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
  uint length;

  pos= buff+1;
  pos[0]= tm->neg ? 1: 0;
  int4store(pos+1, tm->day);
  pos[5]= (uchar) tm->hour;
  pos[6]= (uchar) tm->minute;
  pos[7]= (uchar) tm->second;
  int4store(pos+8, tm->second_part);
  if (tm->second_part)
2303
    length= 12;
unknown's avatar
unknown committed
2304 2305 2306 2307
  else if (tm->hour || tm->minute || tm->second || tm->day)
    length= 8;
  else
    length= 0;
2308
  buff[0]= (char) length++;
unknown's avatar
unknown committed
2309 2310 2311 2312 2313 2314
  memcpy((char *)net->write_pos, buff, length);
  net->write_pos+= length;
}

static void net_store_datetime(NET *net, MYSQL_TIME *tm)
{
2315
  char buff[MAX_DATETIME_REP_LENGTH], *pos;
unknown's avatar
unknown committed
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
  uint length;

  pos= buff+1;

  int2store(pos, tm->year);
  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;
  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;
2335
  buff[0]= (char) length++;
unknown's avatar
unknown committed
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
  memcpy((char *)net->write_pos, buff, length);
  net->write_pos+= length;
}

static void store_param_date(NET *net, MYSQL_BIND *param)
{
  MYSQL_TIME *tm= (MYSQL_TIME *) param->buffer;
  tm->hour= tm->minute= tm->second= 0;
  tm->second_part= 0;
  net_store_datetime(net, tm);
}

static void store_param_datetime(NET *net, MYSQL_BIND *param)
{
  MYSQL_TIME *tm= (MYSQL_TIME *) param->buffer;
  net_store_datetime(net, tm);
}
2353

2354
static void store_param_str(NET *net, MYSQL_BIND *param)
2355
{
2356 2357
  /* param->length is always set in mysql_stmt_bind_param */
  ulong length= *param->length;
2358 2359
  char *to= (char *) net_store_length((char *) net->write_pos, length);
  memcpy(to, param->buffer, length);
unknown's avatar
unknown committed
2360
  net->write_pos= (uchar*) to+length;
2361 2362
}

2363

2364
/*
2365 2366 2367 2368 2369 2370 2371 2372 2373
  Mark if the parameter is NULL.

  SYNOPSIS
    store_param_null()
    net			MySQL NET connection
    param		MySQL bind param

  DESCRIPTION
    A data package starts with a string of bits where we set a bit
2374 2375
    if a parameter is NULL. Unlike bit string in result set row, here
    we don't have reserved bits for OK/error packet.
2376 2377
*/

2378
static void store_param_null(NET *net, MYSQL_BIND *param)
2379
{
2380
  uint pos= param->param_number;
unknown's avatar
unknown committed
2381
  net->buff[pos/8]|=  (uchar) (1 << (pos & 7));
2382
}
2383 2384 2385


/*
2386 2387 2388
  Store one parameter in network packet: data is read from
  client buffer and saved in network packet by means of one
  of store_param_xxxx functions.
2389 2390
*/

2391
static my_bool store_param(MYSQL_STMT *stmt, MYSQL_BIND *param)
2392
{
2393
  NET *net= &stmt->mysql->net;
2394
  DBUG_ENTER("store_param");
unknown's avatar
unknown committed
2395 2396 2397 2398 2399 2400
  DBUG_PRINT("enter",("type: %d, buffer:%lx, length: %lu  is_null: %d",
		      param->buffer_type,
		      param->buffer ? param->buffer : "0", *param->length,
		      *param->is_null));

  if (*param->is_null)
2401 2402
    store_param_null(net, param);
  else
unknown's avatar
unknown committed
2403
  {
unknown's avatar
unknown committed
2404 2405
    /*
      Param->length should ALWAYS point to the correct length for the type
2406
      Either to the length pointer given by the user or param->buffer_length
unknown's avatar
unknown committed
2407
    */
2408
    if ((my_realloc_str(net, *param->length)))
unknown's avatar
unknown committed
2409
    {
2410
      set_stmt_error(stmt, net->last_errno, unknown_sqlstate);
unknown's avatar
unknown committed
2411
      DBUG_RETURN(1);
unknown's avatar
unknown committed
2412
    }
2413
    (*param->store_param_func)(net, param);
unknown's avatar
unknown committed
2414 2415
  }
  DBUG_RETURN(0);
2416 2417
}

unknown's avatar
unknown committed
2418

2419
/*
2420 2421
  Auxilary function to send COM_EXECUTE packet to server and read reply.
  Used from cli_stmt_execute, which is in turn used by mysql_stmt_execute.
2422 2423
*/

2424
static my_bool execute(MYSQL_STMT *stmt, char *packet, ulong length)
2425
{
2426 2427
  MYSQL *mysql= stmt->mysql;
  NET	*net= &mysql->net;
2428
  char buff[4 /* size of stmt id */ +
2429
            5 /* execution flags */];
2430
  DBUG_ENTER("execute");
2431 2432
  DBUG_PRINT("enter",("packet: %s, length :%d",packet ? packet :" ", length));

2433 2434
  mysql->last_used_con= mysql;
  int4store(buff, stmt->stmt_id);		/* Send stmt id to server */
2435 2436 2437 2438
  buff[4]= (char) 0;                            /* no flags */
  int4store(buff+5, 1);                         /* iteration count */
  if (cli_advanced_command(mysql, COM_EXECUTE, buff, sizeof(buff),
                           packet, length, 1) ||
unknown's avatar
SCRUM:  
unknown committed
2439
      (*mysql->methods->read_query_result)(mysql))
2440
  {
2441
    set_stmt_errmsg(stmt, net->last_error, net->last_errno, net->sqlstate);
2442
    DBUG_RETURN(1);
2443
  }
2444
  stmt->affected_rows= mysql->affected_rows;
2445
  stmt->insert_id= mysql->insert_id;
2446 2447 2448
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
2449 2450

int cli_stmt_execute(MYSQL_STMT *stmt)
2451
{
unknown's avatar
SCRUM  
unknown committed
2452
  DBUG_ENTER("cli_stmt_execute");
2453 2454 2455

  if (stmt->param_count)
  {
2456 2457
    NET        *net= &stmt->mysql->net;
    MYSQL_BIND *param, *param_end;
2458
    char       *param_data;
unknown's avatar
unknown committed
2459 2460 2461
    ulong length;
    uint null_count;
    my_bool    result;
2462

2463 2464 2465 2466 2467 2468
    if (!stmt->bind_param_done)
    {
      set_stmt_error(stmt, CR_PARAMS_NOT_BOUND, unknown_sqlstate);
      DBUG_RETURN(1);
    }

2469 2470 2471
    net_clear(net);				/* Sets net->write_pos */
    /* Reserve place for null-marker bytes */
    null_count= (stmt->param_count+7) /8;
2472 2473 2474 2475 2476
    if (my_realloc_str(net, null_count + 1))
    {
      set_stmt_error(stmt, net->last_errno, unknown_sqlstate);
      DBUG_RETURN(1);
    }
2477 2478 2479 2480 2481
    bzero((char*) net->write_pos, null_count);
    net->write_pos+= null_count;
    param_end= stmt->params + stmt->param_count;

    /* In case if buffers (type) altered, indicate to server */
unknown's avatar
unknown committed
2482 2483
    *(net->write_pos)++= (uchar) stmt->send_types_to_server;
    if (stmt->send_types_to_server)
2484
    {
2485 2486 2487 2488 2489
      if (my_realloc_str(net, 2 * stmt->param_count))
      {
        set_stmt_error(stmt, net->last_errno, unknown_sqlstate);
        DBUG_RETURN(1);
      }
2490 2491 2492 2493 2494
      /*
	Store types of parameters in first in first package
	that is sent to the server.
      */
      for (param= stmt->params;	param < param_end ; param++)
2495
        store_param_type((char**) &net->write_pos, param);
2496 2497 2498
    }

    for (param= stmt->params; param < param_end; param++)
2499
    {
2500
      /* check if mysql_stmt_send_long_data() was used */
unknown's avatar
unknown committed
2501 2502
      if (param->long_data_used)
	param->long_data_used= 0;	/* Clear for next execute call */
2503
      else if (store_param(stmt, param))
unknown's avatar
unknown committed
2504
	DBUG_RETURN(1);
2505
    }
2506 2507
    length= (ulong) (net->write_pos - net->buff);
    /* TODO: Look into avoding the following memdup */
unknown's avatar
unknown committed
2508
    if (!(param_data= my_memdup((const char*) net->buff, length, MYF(0))))
2509
    {
2510
      set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
2511
      DBUG_RETURN(1);
2512
    }
2513
    result= execute(stmt, param_data, length);
unknown's avatar
unknown committed
2514
    stmt->send_types_to_server=0;
2515
    my_free(param_data, MYF(MY_WME));
2516 2517 2518
    DBUG_RETURN(result);
  }
  DBUG_RETURN((int) execute(stmt,0,0));
2519 2520
}

2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
/*
  Read one row from buffered result set.  Result set is created by prior
  call to mysql_stmt_store_result().
  SYNOPSIS
    stmt_read_row_buffered()

  RETURN VALUE
    0             - success; *row is set to valid row pointer (row data
                    is stored in result set buffer)
    MYSQL_NO_DATA - end of result set. *row is set to NULL
*/

static int stmt_read_row_buffered(MYSQL_STMT *stmt, unsigned char **row)
{
2535
  if (stmt->data_cursor)
2536
  {
2537 2538
    *row= (uchar *) stmt->data_cursor->data;
    stmt->data_cursor= stmt->data_cursor->next;
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
    return 0;
  }
  *row= 0;
  return MYSQL_NO_DATA;
}

/*
  Read one row from network: unbuffered non-cursor fetch.
  If last row was read, or error occured, erase this statement
  from record pointing to object unbuffered fetch is performed from.

  SYNOPSIS
    stmt_read_row_unbuffered()
    stmt  statement handle
    row   pointer to write pointer to row data;

  RETURN VALUE
    0           - success; *row contains valid address of a row;
                  row data is stored in network buffer
    1           - error; error code is written to
2559
                  stmt->last_{errno,error}; *row is not changed
2560
  MYSQL_NO_DATA - end of file was read from network;
2561
                  *row is set to NULL
2562 2563 2564 2565 2566 2567
*/

static int stmt_read_row_unbuffered(MYSQL_STMT *stmt, unsigned char **row)
{
  int rc= 1;
  MYSQL *mysql= stmt->mysql;
2568
  /*
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
    This function won't be called if stmt->field_count is zero
    or execution wasn't done: this is ensured by mysql_stmt_execute.
  */
  if (!mysql)
  {
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
    return 1;
  }
  if (mysql->status != MYSQL_STATUS_GET_RESULT)
  {
    set_stmt_error(stmt, stmt->unbuffered_fetch_cancelled ?
unknown's avatar
unknown committed
2580
                   CR_FETCH_CANCELED : CR_COMMANDS_OUT_OF_SYNC,
2581 2582 2583 2584 2585 2586 2587
                   unknown_sqlstate);
    goto error;
  }
  if ((*mysql->methods->unbuffered_fetch)(mysql, (char**) row))
  {
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                    mysql->net.sqlstate);
2588 2589 2590 2591 2592 2593 2594
    /*
      If there was an error, there are no more pending rows:
      reset statement status to not hang up in following
      mysql_stmt_close (it will try to flush result set before
      closing the statement).
    */
    mysql->status= MYSQL_STATUS_READY;
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
    goto error;
  }
  if (!*row)
  {
    mysql->status= MYSQL_STATUS_READY;
    rc= MYSQL_NO_DATA;
    goto error;
  }
  return 0;
error:
  if (mysql->unbuffered_fetch_owner == &stmt->unbuffered_fetch_cancelled)
    mysql->unbuffered_fetch_owner= 0;
  return rc;
}

/*
  Default read row function to not SIGSEGV in client in
  case of wrong sequence of API calls.
*/

static int
stmt_read_row_no_data(MYSQL_STMT *stmt  __attribute__((unused)),
                      unsigned char **row  __attribute__((unused)))
{
  if ((int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE)
  {
    set_stmt_error(stmt, CR_NO_PREPARE_STMT, unknown_sqlstate);
    return 1;
  }
  return MYSQL_NO_DATA;
}

2627 2628 2629 2630 2631 2632 2633 2634

/*
  Get/set statement attributes

  SYNOPSIS
    mysql_stmt_attr_get()
    mysql_stmt_attr_set()

unknown's avatar
unknown committed
2635
    attr_type  statement attribute
2636 2637 2638 2639 2640 2641
    value      casted to const void * pointer to value.

  RETURN VALUE
    0 success
   !0 wrong attribute type
*/
2642

2643 2644 2645 2646 2647 2648 2649 2650
my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt,
                                    enum enum_stmt_attr_type attr_type,
                                    const void *value)
{
  switch (attr_type) {
  case STMT_ATTR_UPDATE_MAX_LENGTH:
    stmt->update_max_length= value ? *(const my_bool*) value : 0;
    break;
2651
  default:
2652 2653 2654 2655 2656 2657
    return TRUE;
  }
  return FALSE;
}


2658
my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
2659 2660 2661 2662 2663 2664
                                    enum enum_stmt_attr_type attr_type,
                                    void *value)
{
  switch (attr_type) {
  case STMT_ATTR_UPDATE_MAX_LENGTH:
    *(unsigned long *) value= stmt->update_max_length;
2665
    break;
2666
  default:
2667 2668 2669 2670 2671 2672
    return TRUE;
  }
  return FALSE;
}


unknown's avatar
SCRUM  
unknown committed
2673
/*
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
  Send placeholders data to server (if there are placeholders)
  and execute prepared statement.

  SYNOPSIS
    mysql_stmt_execute()
    stmt  statement handle. The handle must be created
          with mysql_stmt_init() and prepared with
          mysql_stmt_prepare(). If there are placeholders
          in the statement they must be bound to local
          variables with mysql_stmt_bind_param().

  DESCRIPTION
    This function will automatically flush pending result
    set (if there is one), send parameters data to the server
    and read result of statement execution.
    If previous result set was cached with mysql_stmt_store_result()
    it will also be freed in the beginning of this call.
    The server can return 3 types of responses to this command:
    - error, can be retrieved with mysql_stmt_error()
    - ok, no result set pending. In this case we just update
      stmt->insert_id and stmt->affected_rows.
    - the query returns a result set: there could be 0 .. N
    rows in it. In this case the server can also send updated
    result set metadata.

    Next steps you may want to make:
    - find out if there is result set with mysql_stmt_field_count().
    If there is one:
    - optionally, cache entire result set on client to unblock
    connection with mysql_stmt_store_result()
    - bind client variables to result set columns and start read rows
    with mysql_stmt_fetch().
    - reset statement with mysql_stmt_reset() or close it with
    mysql_stmt_close()
    Otherwise:
    - find out last insert id and number of affected rows with
    mysql_stmt_insert_id(), mysql_stmt_affected_rows()

  RETURN
    0   success
    1   error, message can be retrieved with mysql_stmt_error().
unknown's avatar
SCRUM  
unknown committed
2715 2716
*/

2717
int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt)
unknown's avatar
SCRUM  
unknown committed
2718
{
2719
  MYSQL *mysql= stmt->mysql;
2720
  DBUG_ENTER("mysql_stmt_execute");
unknown's avatar
SCRUM  
unknown committed
2721

2722 2723 2724
  if (!mysql)
  {
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
unknown's avatar
SCRUM  
unknown committed
2725
    DBUG_RETURN(1);
2726 2727 2728 2729 2730
  }

  mysql_stmt_free_result(stmt);
  /*
    No need to check for stmt->state: if the statement wasn't
unknown's avatar
unknown committed
2731
    prepared we'll get 'unknown statement handler' error from server.
2732 2733 2734
  */
  if (mysql->methods->stmt_execute(stmt))
    DBUG_RETURN(1);
2735
  if (mysql->field_count)
2736
  {
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
    /* Server has sent result set metadata */
    if (stmt->field_count == 0)
    {
      /*
        This is 'SHOW'/'EXPLAIN'-like query. Current implementation of
        prepared statements can't send result set metadata for these queries
        on prepare stage. Read it now.
      */
      alloc_stmt_fields(stmt);
    }
    else
    {
      /*
        Update result set metadata if it for some reason changed between
        prepare and execute, i.e.:
        - in case of 'SELECT ?' we don't know column type unless data was
          supplied to mysql_stmt_execute, so updated column type is sent
          now.
        - if data dictionary changed between prepare and execute, for
          example a table used in the query was altered.
        Note, that now (4.1.3) we always send metadata in reply to
        COM_EXECUTE (even if it is not necessary), so either this or
2759
        previous branch always works.
2760 2761 2762 2763 2764
        TODO: send metadata only when it's really necessary and add a warning
        'Metadata changed' when it's sent twice.
      */
      update_stmt_fields(stmt);
    }
2765 2766 2767 2768 2769 2770 2771 2772
  }
  stmt->state= MYSQL_STMT_EXECUTE_DONE;
  if (stmt->field_count)
  {
    stmt->mysql->unbuffered_fetch_owner= &stmt->unbuffered_fetch_cancelled;
    stmt->unbuffered_fetch_cancelled= FALSE;
    stmt->read_row_func= stmt_read_row_unbuffered;
  }
unknown's avatar
SCRUM  
unknown committed
2773 2774 2775
  DBUG_RETURN(0);
}

2776

2777 2778 2779 2780
/*
  Return total parameters count in the statement
*/

2781
ulong STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt)
2782
{
2783
  DBUG_ENTER("mysql_stmt_param_count");
2784 2785 2786
  DBUG_RETURN(stmt->param_count);
}

2787 2788 2789 2790 2791 2792
/*
  Return total affected rows from the last statement
*/

my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt)
{
2793
  return stmt->affected_rows;
2794
}
2795

unknown's avatar
unknown committed
2796

unknown's avatar
unknown committed
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806
/*
  Returns the number of result columns for the most recent query
  run on this statement.
*/

unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt)
{
  return stmt->field_count;
}

2807
/*
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
  Return last inserted id for auto_increment columns.

  SYNOPSIS
    mysql_stmt_insert_id()
    stmt    statement handle

  DESCRIPTION
    Current implementation of this call has a caveat: stmt->insert_id is
    unconditionally updated from mysql->insert_id in the end of each
    mysql_stmt_execute(). This works OK if mysql->insert_id contains new
    value (sent in reply to mysql_stmt_execute()), otherwise stmt->insert_id
    value gets undefined, as it's updated from some arbitrary value saved in
    connection structure during some other call.
2821 2822 2823 2824 2825 2826 2827
*/

my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt)
{
  return stmt->insert_id;
}

2828

unknown's avatar
unknown committed
2829 2830 2831
static my_bool int_is_null_true= 1;		/* Used for MYSQL_TYPE_NULL */
static my_bool int_is_null_false= 0;

2832

2833
/*
2834
  Set up input data buffers for a statement.
2835 2836 2837 2838 2839 2840

  SYNOPSIS
    mysql_stmt_bind_param()
    stmt    statement handle
            The statement must be prepared with mysql_stmt_prepare().
    bind    Array of mysql_stmt_param_count() bind parameters.
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
            This function doesn't check that size of this argument
            is >= mysql_stmt_field_count(): it's user's responsibility.

  DESCRIPTION
    Use this call after mysql_stmt_prepare() to bind user variables to
    placeholders.
    Each element of bind array stands for a placeholder. Placeholders
    are counted from 0.  For example statement
    'INSERT INTO t (a, b) VALUES (?, ?)'
    contains two placeholders, and for such statement you should supply
    bind array of two elements (MYSQL_BIND bind[2]).

    By properly initializing bind array you can bind virtually any
    C language type to statement's placeholders:
    First, it's strongly recommended to always zero-initialize entire
unknown's avatar
unknown committed
2856
    bind structure before setting its members. This will both shorten
2857 2858
    your application code and make it robust to future extensions of
    MYSQL_BIND structure.
2859
    Then you need to assign typecode of your application buffer to
2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
    MYSQL_BIND::buffer_type. The following typecodes with their
    correspondence to C language types are supported:
    MYSQL_TYPE_TINY       for 8-bit integer variables. Normally it's
                          'signed char' and 'unsigned char';
    MYSQL_TYPE_SHORT      for 16-bit signed and unsigned variables. This
                          is usually 'short' and 'unsigned short';
    MYSQL_TYPE_LONG       for 32-bit signed and unsigned variables. It
                          corresponds to 'int' and 'unsigned int' on
                          vast majority of platforms. On IA-32 and some
                          other 32-bit systems you can also use 'long'
                          here;
    MYSQL_TYPE_LONGLONG   64-bit signed or unsigned integer.  Stands for
                          '[unsigned] long long' on most platforms;
    MYSQL_TYPE_FLOAT      32-bit floating point type, 'float' on most
                          systems;
    MYSQL_TYPE_DOUBLE     64-bit floating point type, 'double' on most
                          systems;
    MYSQL_TYPE_TIME       broken-down time stored in MYSQL_TIME
                          structure
    MYSQL_TYPE_DATE       date stored in MYSQL_TIME structure
    MYSQL_TYPE_DATETIME   datetime stored in MYSQL_TIME structure See
                          more on how to use these types for sending
                          dates and times below;
    MYSQL_TYPE_STRING     character string, assumed to be in
                          character-set-client. If character set of
                          client is not equal to character set of
                          column, value for this placeholder will be
                          converted to destination character set before
                          insert.
    MYSQL_TYPE_BLOB       sequence of bytes. This sequence is assumed to
                          be in binary character set (which is the same
                          as no particular character set), and is never
                          converted to any other character set. See also
                          notes about supplying string/blob length
                          below.
    MYSQL_TYPE_NULL       special typecode for binding nulls.
    These C/C++ types are not supported yet by the API: long double,
    bool.

    As you can see from the list above, it's responsibility of
    application programmer to ensure that chosen typecode properly
    corresponds to host language type. For example on all platforms
    where we build MySQL packages (as of MySQL 4.1.4) int is a 32-bit
    type. So for int you can always assume that proper typecode is
    MYSQL_TYPE_LONG (however queer it sounds, the name is legacy of the
    old MySQL API). In contrary sizeof(long) can be 4 or 8 8-bit bytes,
    depending on platform.

    TODO: provide client typedefs for each integer and floating point
    typecode, i. e. int8, uint8, float32, etc.

    Once typecode was set, it's necessary to assign MYSQL_BIND::buffer
    to point to the buffer of given type. Finally, additional actions
    may be taken for some types or use cases:

      Binding integer types.
    For integer types you might also need to set MYSQL_BIND::is_unsigned
    member. Set it to TRUE when binding unsigned char, unsigned short,
    unsigned int, unsigned long, unsigned long long.

      Binding floating point types.
    For floating point types you just need to set
    MYSQL_BIND::buffer_type and MYSQL_BIND::buffer. The rest of the
    members should be zero-initialized.

      Binding NULLs.
    You might have a column always NULL, never NULL, or sometimes NULL.
    For an always NULL column set MYSQL_BIND::buffer_type to
    MYSQL_TYPE_NULL.  The rest of the members just need to be
    zero-initialized.  For never NULL columns set MYSQL_BIND::is_null to
    0, or this has already been done if you zero-initialized the entire
    structure.  If you set MYSQL_TYPE::is_null to point to an
    application buffer of type 'my_bool', then this buffer will be
    checked on each execution: this way you can set the buffer to TRUE,
    or any non-0 value for NULLs, and to FALSE or 0 for not NULL data.

      Binding text strings and sequences of bytes.
    For strings, in addition to MYSQL_BIND::buffer_type and
    MYSQL_BIND::buffer you need to set MYSQL_BIND::length or
    MYSQL_BIND::buffer_length.
    If 'length' is set, 'buffer_length' is ignored. 'buffer_length'
    member should be used when size of string doesn't change between
    executions. If you want to vary buffer length for each value, set
    'length' to point to an application buffer of type 'unsigned long'
    and set this long to length of the string before each
    mysql_stmt_execute().

      Binding dates and times.
    For binding dates and times prepared statements API provides clients
    with MYSQL_TIME structure. A pointer to instance of this structure
    should be assigned to MYSQL_BIND::buffer whenever MYSQL_TYPE_TIME,
    MYSQL_TYPE_DATE, MYSQL_TYPE_DATETIME typecodes are used.  When
    typecode is MYSQL_TYPE_TIME, only members 'hour', 'minute', 'second'
    and 'neg' (is time offset negative) are used. These members only
    will be sent to the server.
    MYSQL_TYPE_DATE implies use of 'year', 'month', 'day', 'neg'.
    MYSQL_TYPE_DATETIME utilizes both parts of MYSQL_TIME structure.
    You don't have to set MYSQL_TIME::time_type member: it's not used
    when sending data to the server, typecode information is enough.
    'second_part' member can hold microsecond precision of time value,
    but now it's only supported on protocol level: you can't store
    microsecond in a column, or use in temporal calculations. However,
    if you send a time value with microsecond part for 'SELECT ?',
    statement, you'll get it back unchanged from the server.

      Data conversion.
    If conversion from host language type to data representation,
    corresponding to SQL type, is required it's done on the server.
    Data truncation is possible when conversion is lossy. For example,
    if you supply MYSQL_TYPE_DATETIME value out of valid SQL type
    TIMESTAMP range, the same conversion will be applied as if this
    value would have been sent as string in the old protocol.
    TODO: document how the server will behave in case of truncation/data
    loss.

    After variables were bound, you can repeatedly set/change their
    values and mysql_stmt_execute() the statement.

    See also: mysql_stmt_send_long_data() for sending long text/blob
    data in pieces, examples in tests/client_test.c.
    Next steps you might want to make:
    - execute statement with mysql_stmt_execute(),
    - reset statement using mysql_stmt_reset() or reprepare it with
      another query using mysql_stmt_prepare()
    - close statement with mysql_stmt_close().

  IMPLEMENTATION
    The function copies given bind array to internal storage of the
    statement, and sets up typecode-specific handlers to perform
    serialization of bound data. This means that although you don't need
2990 2991
    to call this routine after each assignment to bind buffers, you
    need to call it each time you change parameter typecodes, or other
2992 2993 2994
    members of MYSQL_BIND array.
    This is a pure local call. Data types of client buffers are sent
    along with buffers' data at first execution of the statement.
2995 2996 2997 2998

  RETURN
    0  success
    1  error, can be retrieved with mysql_stmt_error.
2999 3000
*/

3001
my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind)
3002
{
3003 3004
  uint count=0;
  MYSQL_BIND *param, *end;
3005
  DBUG_ENTER("mysql_stmt_bind_param");
3006

3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
  if (!stmt->param_count)
  {
    if ((int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE)
    {
      set_stmt_error(stmt, CR_NO_PREPARE_STMT, unknown_sqlstate);
      DBUG_RETURN(1);
    }
    DBUG_RETURN(0);
  }

3017 3018 3019 3020 3021 3022 3023
  /* Allocated on prepare */
  memcpy((char*) stmt->params, (char*) bind,
	 sizeof(MYSQL_BIND) * stmt->param_count);

  for (param= stmt->params, end= param+stmt->param_count;
       param < end ;
       param++)
3024
  {
3025
    param->param_number= count++;
3026 3027
    param->long_data_used= 0;

unknown's avatar
unknown committed
3028 3029 3030 3031
    /* If param->is_null is not set, then the value can never be NULL */
    if (!param->is_null)
      param->is_null= &int_is_null_false;

3032 3033
    /* Setup data copy functions for the different supported types */
    switch (param->buffer_type) {
unknown's avatar
unknown committed
3034
    case MYSQL_TYPE_NULL:
unknown's avatar
unknown committed
3035
      param->is_null= &int_is_null_true;
unknown's avatar
unknown committed
3036
      break;
3037
    case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
3038
      /* Force param->length as this is fixed for this type */
3039 3040
      param->length= &param->buffer_length;
      param->buffer_length= 1;
3041 3042 3043
      param->store_param_func= store_param_tinyint;
      break;
    case MYSQL_TYPE_SHORT:
3044 3045
      param->length= &param->buffer_length;
      param->buffer_length= 2;
3046 3047 3048
      param->store_param_func= store_param_short;
      break;
    case MYSQL_TYPE_LONG:
3049 3050
      param->length= &param->buffer_length;
      param->buffer_length= 4;
3051 3052 3053
      param->store_param_func= store_param_int32;
      break;
    case MYSQL_TYPE_LONGLONG:
3054 3055
      param->length= &param->buffer_length;
      param->buffer_length= 8;
3056 3057 3058
      param->store_param_func= store_param_int64;
      break;
    case MYSQL_TYPE_FLOAT:
3059 3060
      param->length= &param->buffer_length;
      param->buffer_length= 4;
3061 3062 3063
      param->store_param_func= store_param_float;
      break;
    case MYSQL_TYPE_DOUBLE:
3064 3065
      param->length= &param->buffer_length;
      param->buffer_length= 8;
3066 3067
      param->store_param_func= store_param_double;
      break;
unknown's avatar
unknown committed
3068 3069
    case MYSQL_TYPE_TIME:
      param->store_param_func= store_param_time;
3070
      param->buffer_length= MAX_TIME_REP_LENGTH;
unknown's avatar
unknown committed
3071 3072 3073
      break;
    case MYSQL_TYPE_DATE:
      param->store_param_func= store_param_date;
3074
      param->buffer_length= MAX_DATE_REP_LENGTH;
unknown's avatar
unknown committed
3075 3076 3077 3078
      break;
    case MYSQL_TYPE_DATETIME:
    case MYSQL_TYPE_TIMESTAMP:
      param->store_param_func= store_param_datetime;
3079
      param->buffer_length= MAX_DATETIME_REP_LENGTH;
unknown's avatar
unknown committed
3080
      break;
3081 3082 3083
    case MYSQL_TYPE_TINY_BLOB:
    case MYSQL_TYPE_MEDIUM_BLOB:
    case MYSQL_TYPE_LONG_BLOB:
unknown's avatar
unknown committed
3084
    case MYSQL_TYPE_BLOB:
3085 3086 3087
    case MYSQL_TYPE_VAR_STRING:
    case MYSQL_TYPE_STRING:
      param->store_param_func= store_param_str;
3088
      /*
3089 3090
        For variable length types user must set either length or
        buffer_length.
3091
      */
3092 3093
      break;
    default:
3094
      strmov(stmt->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
3095 3096
      sprintf(stmt->last_error,
	      ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
3097
	      param->buffer_type, count);
3098
      DBUG_RETURN(1);
3099
    }
3100 3101 3102 3103 3104 3105
    /*
      If param->length is not given, change it to point to buffer_length.
      This way we can always use *param->length to get the length of data
    */
    if (!param->length)
      param->length= &param->buffer_length;
3106
  }
3107
  /* We have to send/resend type information to MySQL */
3108 3109
  stmt->send_types_to_server= TRUE;
  stmt->bind_param_done= TRUE;
3110 3111 3112
  DBUG_RETURN(0);
}

3113

3114 3115 3116 3117 3118
/********************************************************************
 Long data implementation
*********************************************************************/

/*
3119 3120 3121
  Send long data in pieces to the server

  SYNOPSIS
3122
    mysql_stmt_send_long_data()
3123 3124 3125 3126
    stmt			Statement handler
    param_number		Parameter number (0 - N-1)
    data			Data to send to server
    length			Length of data to send (may be 0)
unknown's avatar
unknown committed
3127

3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
  DESCRIPTION
    This call can be used repeatedly to send long data in pieces
    for any string/binary placeholder. Data supplied for
    a placeholder is saved at server side till execute, and then
    used instead of value from MYSQL_BIND object. More precisely,
    if long data for a parameter was supplied, MYSQL_BIND object
    corresponding to this parameter is not sent to server. In the
    end of execution long data states of placeholders are reset,
    so next time values of such placeholders will be taken again
    from MYSQL_BIND array.
    The server does not reply to this call: if there was an error
    in data handling (which now only can happen if server run out
    of memory) it would be returned in reply to
    mysql_stmt_execute().
    You should choose type of long data carefully if you care
    about character set conversions performed by server when the
    statement is executed.  No conversion is performed at all for
    MYSQL_TYPE_BLOB and other binary typecodes. For
    MYSQL_TYPE_STRING and the rest of text placeholders data is
    converted from client character set to character set of
    connection. If these character sets are different, this
    conversion may require additional memory at server, equal to
    total size of supplied pieces.

3152
  RETURN VALUES
unknown's avatar
unknown committed
3153 3154
    0	ok
    1	error
3155 3156
*/

3157
my_bool STDCALL
3158
mysql_stmt_send_long_data(MYSQL_STMT *stmt, uint param_number,
unknown's avatar
unknown committed
3159
		     const char *data, ulong length)
3160 3161
{
  MYSQL_BIND *param;
3162
  DBUG_ENTER("mysql_stmt_send_long_data");
3163
  DBUG_ASSERT(stmt != 0);
3164
  DBUG_PRINT("enter",("param no : %d, data : %lx, length : %ld",
3165
		      param_number, data, length));
3166

3167 3168 3169 3170 3171 3172 3173 3174 3175
  /*
    We only need to check for stmt->param_count, if it's not null
    prepare was done.
  */
  if (param_number >= stmt->param_count)
  {
    set_stmt_error(stmt, CR_INVALID_PARAMETER_NO, unknown_sqlstate);
    DBUG_RETURN(1);
  }
3176

3177
  param= stmt->params+param_number;
unknown's avatar
unknown committed
3178 3179 3180
  if (param->buffer_type < MYSQL_TYPE_TINY_BLOB ||
      param->buffer_type > MYSQL_TYPE_STRING)
  {
3181
    /* Long data handling should be used only for string/binary types */
3182
    strmov(stmt->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
3183 3184 3185 3186
    sprintf(stmt->last_error, ER(stmt->last_errno= CR_INVALID_BUFFER_USE),
	    param->param_number);
    DBUG_RETURN(1);
  }
3187

3188
  /*
3189 3190 3191
    Send long data packet if there is data or we're sending long data
    for the first time.
  */
3192
  if (length || param->long_data_used == 0)
3193
  {
3194
    MYSQL *mysql= stmt->mysql;
3195
    /* Packet header: stmt id (4 bytes), param no (2 bytes) */
3196 3197
    char buff[MYSQL_LONG_DATA_HEADER];

3198 3199
    int4store(buff, stmt->stmt_id);
    int2store(buff + 4, param_number);
3200 3201
    param->long_data_used= 1;

3202 3203 3204 3205
    /*
      Note that we don't get any ok packet from the server in this case
      This is intentional to save bandwidth.
    */
3206 3207
    if ((*mysql->methods->advanced_command)(mysql, COM_LONG_DATA, buff,
					    sizeof(buff), data, length, 1))
3208
    {
3209 3210
      set_stmt_errmsg(stmt, mysql->net.last_error,
		      mysql->net.last_errno, mysql->net.sqlstate);
3211 3212 3213 3214 3215 3216
      DBUG_RETURN(1);
    }
  }
  DBUG_RETURN(0);
}

3217

3218
/********************************************************************
3219
 Fetch and conversion of result set rows (binary protocol).
3220 3221
*********************************************************************/

3222 3223 3224 3225 3226 3227 3228 3229
/*
  Read date, (time, datetime) value from network buffer and store it
  in MYSQL_TIME structure.

  SYNOPSIS
    read_binary_{date,time,datetime}()
    tm    MYSQL_TIME structure to fill
    pos   pointer to current position in network buffer.
unknown's avatar
unknown committed
3230 3231
          These functions increase pos to point to the beginning of the
          next column.
3232 3233 3234 3235 3236 3237

  Auxiliary functions to read time (date, datetime) values from network
  buffer and store in MYSQL_TIME structure. Jointly used by conversion
  and no-conversion fetching.
*/

unknown's avatar
unknown committed
3238
static void read_binary_time(MYSQL_TIME *tm, uchar **pos)
unknown's avatar
unknown committed
3239
{
3240
  /* net_field_length will set pos to the first byte of data */
unknown's avatar
unknown committed
3241 3242 3243
  uint length= net_field_length(pos);

  if (length)
unknown's avatar
unknown committed
3244 3245 3246
  {
    uchar *to= *pos;
    tm->neg= (bool) to[0];
unknown's avatar
unknown committed
3247

unknown's avatar
unknown committed
3248 3249 3250 3251 3252 3253
    tm->day=    (ulong) sint4korr(to+1);
    tm->hour=   (uint) to[5];
    tm->minute= (uint) to[6];
    tm->second= (uint) to[7];
    tm->second_part= (length > 8) ? (ulong) sint4korr(to+8) : 0;
    tm->year= tm->month= 0;
3254 3255 3256 3257 3258 3259
    if (tm->day)
    {
      /* Convert days to hours at once */
      tm->hour+= tm->day*24;
      tm->day= 0;
    }
3260 3261
    tm->time_type= MYSQL_TIMESTAMP_TIME;

unknown's avatar
unknown committed
3262
    *pos+= length;
unknown's avatar
unknown committed
3263
  }
unknown's avatar
unknown committed
3264
  else
3265
    set_zero_time(tm, MYSQL_TIMESTAMP_TIME);
unknown's avatar
unknown committed
3266 3267
}

unknown's avatar
unknown committed
3268
static void read_binary_datetime(MYSQL_TIME *tm, uchar **pos)
unknown's avatar
unknown committed
3269
{
unknown's avatar
unknown committed
3270
  uint length= net_field_length(pos);
3271

unknown's avatar
unknown committed
3272
  if (length)
unknown's avatar
unknown committed
3273 3274
  {
    uchar *to= *pos;
3275

unknown's avatar
unknown committed
3276 3277 3278 3279
    tm->neg=    0;
    tm->year=   (uint) sint2korr(to);
    tm->month=  (uint) to[2];
    tm->day=    (uint) to[3];
3280

unknown's avatar
unknown committed
3281 3282 3283 3284 3285 3286 3287 3288 3289
    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->second_part= (length > 7) ? (ulong) sint4korr(to+7) : 0;
3290
    tm->time_type= MYSQL_TIMESTAMP_DATETIME;
unknown's avatar
unknown committed
3291 3292

    *pos+= length;
unknown's avatar
unknown committed
3293
  }
unknown's avatar
unknown committed
3294
  else
3295
    set_zero_time(tm, MYSQL_TIMESTAMP_DATETIME);
unknown's avatar
unknown committed
3296 3297
}

unknown's avatar
unknown committed
3298
static void read_binary_date(MYSQL_TIME *tm, uchar **pos)
unknown's avatar
unknown committed
3299
{
unknown's avatar
unknown committed
3300
  uint length= net_field_length(pos);
3301

unknown's avatar
unknown committed
3302
  if (length)
unknown's avatar
unknown committed
3303 3304 3305 3306 3307
  {
    uchar *to= *pos;
    tm->year =  (uint) sint2korr(to);
    tm->month=  (uint) to[2];
    tm->day= (uint) to[3];
unknown's avatar
unknown committed
3308

unknown's avatar
unknown committed
3309 3310 3311
    tm->hour= tm->minute= tm->second= 0;
    tm->second_part= 0;
    tm->neg= 0;
3312
    tm->time_type= MYSQL_TIMESTAMP_DATE;
unknown's avatar
unknown committed
3313 3314

    *pos+= length;
unknown's avatar
unknown committed
3315
  }
unknown's avatar
unknown committed
3316
  else
3317
    set_zero_time(tm, MYSQL_TIMESTAMP_DATE);
3318 3319
}

3320

unknown's avatar
unknown committed
3321 3322 3323 3324 3325 3326 3327 3328 3329
/*
  Convert string to supplied buffer of any type.

  SYNOPSIS
    fetch_string_with_conversion()
    param   output buffer descriptor
    value   column data
    length  data length
*/
3330

unknown's avatar
unknown committed
3331 3332
static void fetch_string_with_conversion(MYSQL_BIND *param, char *value,
                                         uint length)
3333
{
3334
  char *buffer= (char *)param->buffer;
unknown's avatar
unknown committed
3335
  int err= 0;
3336

unknown's avatar
unknown committed
3337 3338 3339 3340 3341
  /*
    This function should support all target buffer types: the rest
    of conversion functions can delegate conversion to it.
  */
  switch(param->buffer_type) {
unknown's avatar
unknown committed
3342 3343
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3344
  case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
3345 3346 3347 3348
  {
    uchar data= (uchar) my_strntol(&my_charset_latin1, value, length, 10,
                                   NULL, &err);
    *buffer= data;
3349
    break;
unknown's avatar
unknown committed
3350
  }
3351
  case MYSQL_TYPE_SHORT:
unknown's avatar
unknown committed
3352 3353 3354 3355
  {
    short data= (short) my_strntol(&my_charset_latin1, value, length, 10,
                                   NULL, &err);
    shortstore(buffer, data);
3356
    break;
unknown's avatar
unknown committed
3357
  }
3358
  case MYSQL_TYPE_LONG:
unknown's avatar
unknown committed
3359 3360 3361 3362
  {
    int32 data= (int32)my_strntol(&my_charset_latin1, value, length, 10,
                                  NULL, &err);
    longstore(buffer, data);
3363
    break;
unknown's avatar
unknown committed
3364
  }
3365
  case MYSQL_TYPE_LONGLONG:
unknown's avatar
unknown committed
3366 3367 3368 3369
  {
    longlong data= my_strntoll(&my_charset_latin1, value, length, 10,
                               NULL, &err);
    longlongstore(buffer, data);
3370
    break;
unknown's avatar
unknown committed
3371
  }
3372
  case MYSQL_TYPE_FLOAT:
3373
  {
unknown's avatar
unknown committed
3374 3375
    float data = (float) my_strntod(&my_charset_latin1, value, length,
                                    NULL, &err);
3376
    floatstore(buffer, data);
3377 3378
    break;
  }
3379
  case MYSQL_TYPE_DOUBLE:
3380
  {
unknown's avatar
unknown committed
3381
    double data= my_strntod(&my_charset_latin1, value, length, NULL, &err);
3382
    doublestore(buffer, data);
3383 3384
    break;
  }
unknown's avatar
unknown committed
3385 3386 3387 3388 3389 3390 3391 3392
  case MYSQL_TYPE_TIME:
  {
    MYSQL_TIME *tm= (MYSQL_TIME *)buffer;
    str_to_time(value, length, tm, &err);
    break;
  }
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_DATETIME:
3393
  case MYSQL_TYPE_TIMESTAMP:
unknown's avatar
unknown committed
3394 3395 3396 3397 3398 3399 3400 3401 3402
  {
    MYSQL_TIME *tm= (MYSQL_TIME *)buffer;
    str_to_datetime(value, length, tm, 0, &err);
    break;
  }
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
3403
  default:
3404
  {
unknown's avatar
unknown committed
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
    /*
      Copy column data to the buffer taking into account offset,
      data length and buffer length.
    */
    char *start= value + param->offset;
    char *end= value + length;
    ulong copy_length;
    if (start < end)
    {
      copy_length= end - start;
      /* We've got some data beyond offset: copy up to buffer_length bytes */
      if (param->buffer_length)
        memcpy(buffer, start, min(copy_length, param->buffer_length));
    }
unknown's avatar
unknown committed
3419
    else
unknown's avatar
unknown committed
3420 3421 3422 3423 3424 3425 3426
      copy_length= 0;
    if (copy_length < param->buffer_length)
      buffer[copy_length]= '\0';
    /*
      param->length will always contain length of entire column;
      number of copied bytes may be way different:
    */
3427
    *param->length= length;
unknown's avatar
unknown committed
3428
    break;
3429
  }
3430
  }
3431 3432
}

3433

unknown's avatar
unknown committed
3434 3435 3436 3437 3438 3439 3440 3441 3442
/*
  Convert integer value to client buffer of any type.

  SYNOPSIS
    fetch_long_with_conversion()
    param   output buffer descriptor
    field   column metadata
    value   column data
*/
3443

unknown's avatar
unknown committed
3444 3445
static void fetch_long_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
                                       longlong value)
3446
{
3447
  char *buffer= (char *)param->buffer;
unknown's avatar
unknown committed
3448
  uint field_is_unsigned= field->flags & UNSIGNED_FLAG;
3449

unknown's avatar
unknown committed
3450
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3451 3452
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3453
  case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
3454
    *(uchar *)param->buffer= (uchar) value;
3455 3456
    break;
  case MYSQL_TYPE_SHORT:
unknown's avatar
unknown committed
3457
    shortstore(buffer, value);
3458 3459
    break;
  case MYSQL_TYPE_LONG:
unknown's avatar
unknown committed
3460
    longstore(buffer, value);
3461 3462
    break;
  case MYSQL_TYPE_LONGLONG:
unknown's avatar
unknown committed
3463
    longlongstore(buffer, value);
3464 3465
    break;
  case MYSQL_TYPE_FLOAT:
unknown's avatar
unknown committed
3466
  {
unknown's avatar
unknown committed
3467 3468
    float data= field_is_unsigned ? (float) ulonglong2double(value) :
                                    (float) value;
3469
    floatstore(buffer, data);
unknown's avatar
unknown committed
3470 3471
    break;
  }
3472
  case MYSQL_TYPE_DOUBLE:
unknown's avatar
unknown committed
3473
  {
unknown's avatar
unknown committed
3474 3475 3476
    double data= field_is_unsigned ? ulonglong2double(value) :
                                     (double) value;
    doublestore(buffer, data);
unknown's avatar
unknown committed
3477 3478
    break;
  }
3479
  default:
unknown's avatar
unknown committed
3480
  {
unknown's avatar
unknown committed
3481 3482 3483
    char buff[22];                              /* Enough for longlong */
    char *end= longlong10_to_str(value, buff, field_is_unsigned ? 10: -10);
    /* Resort to string conversion which supports all typecodes */
3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
    uint length= (uint) (end-buff);

    if (field->flags & ZEROFILL_FLAG && length < field->length &&
        field->length < 21)
    {
      bmove_upp((char*) buff+field->length,buff+length, length);
      bfill((char*) buff, field->length - length,'0');
      length= field->length;
    }
    fetch_string_with_conversion(param, buff, length);
unknown's avatar
unknown committed
3494
    break;
unknown's avatar
unknown committed
3495
  }
3496
  }
3497 3498
}

unknown's avatar
unknown committed
3499

unknown's avatar
unknown committed
3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
/*
  Convert double/float column to supplied buffer of any type.

  SYNOPSIS
    fetch_float_with_conversion()
    param   output buffer descriptor
    field   column metadata
    value   column data
    width   default number of significant digits used when converting
            float/double to string
*/
unknown's avatar
unknown committed
3511

unknown's avatar
unknown committed
3512 3513
static void fetch_float_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
                                        double value, int width)
3514
{
3515
  char *buffer= (char *)param->buffer;
3516

unknown's avatar
unknown committed
3517
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3518 3519
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3520
  case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
3521
    *buffer= (uchar)value;
3522 3523
    break;
  case MYSQL_TYPE_SHORT:
unknown's avatar
unknown committed
3524
    shortstore(buffer, (short)value);
3525 3526
    break;
  case MYSQL_TYPE_LONG:
unknown's avatar
unknown committed
3527
    longstore(buffer, (long)value);
3528 3529 3530
    break;
  case MYSQL_TYPE_LONGLONG:
  {
unknown's avatar
unknown committed
3531 3532
    longlong val= (longlong) value;
    longlongstore(buffer, val);
3533 3534 3535 3536
    break;
  }
  case MYSQL_TYPE_FLOAT:
  {
unknown's avatar
unknown committed
3537
    float data= (float) value;
3538
    floatstore(buffer, data);
3539 3540 3541 3542
    break;
  }
  case MYSQL_TYPE_DOUBLE:
  {
unknown's avatar
unknown committed
3543
    doublestore(buffer, value);
3544 3545
    break;
  }
3546
  default:
unknown's avatar
unknown committed
3547 3548 3549 3550 3551 3552
  {
    /*
      Resort to fetch_string_with_conversion: this should handle
      floating point -> string conversion nicely, honor all typecodes
      and param->offset possibly set in mysql_stmt_fetch_column
    */
3553
    char buff[MAX_DOUBLE_STRING_REP_LENGTH];
unknown's avatar
unknown committed
3554 3555 3556
    char *end;
    /* TODO: move this to a header shared between client and server. */
#define NOT_FIXED_DEC  31
unknown's avatar
unknown committed
3557
    if (field->decimals >= NOT_FIXED_DEC)
unknown's avatar
unknown committed
3558 3559
#undef NOT_FIXED_DEC
    {
3560 3561 3562 3563 3564 3565 3566 3567
      /*
        The 14 below is to ensure that the server and client has the same
        precisions. This will ensure that on the same machine you get the
        same value as a string independent of the protocol you use.
      */
      sprintf(buff, "%-*.*g", (int) min(sizeof(buff)-1,
                                        param->buffer_length),
	      min(14,width), value);
unknown's avatar
unknown committed
3568 3569 3570
      end= strcend(buff, ' ');
      *end= 0;
    }
unknown's avatar
unknown committed
3571
    else
unknown's avatar
unknown committed
3572
    {
unknown's avatar
unknown committed
3573
      sprintf(buff, "%.*f", (int) field->decimals, value);
unknown's avatar
unknown committed
3574 3575
      end= strend(buff);
    }
unknown's avatar
unknown committed
3576
    fetch_string_with_conversion(param, buff, (uint) (end - buff));
unknown's avatar
unknown committed
3577
    break;
unknown's avatar
unknown committed
3578
  }
unknown's avatar
unknown committed
3579
  }
3580 3581
}

unknown's avatar
unknown committed
3582

unknown's avatar
unknown committed
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
/*
  Fetch time/date/datetime to supplied buffer of any type

  SYNOPSIS
    param   output buffer descriptor
    time    column data
*/

static void fetch_datetime_with_conversion(MYSQL_BIND *param,
                                           MYSQL_TIME *time)
unknown's avatar
unknown committed
3593 3594
{
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3595 3596
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
unknown's avatar
unknown committed
3597 3598 3599 3600
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_TIME:
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
unknown's avatar
unknown committed
3601 3602
    /* XXX: should we copy only relevant members here? */
    *(MYSQL_TIME *)(param->buffer)= *time;
3603
    break;
unknown's avatar
unknown committed
3604 3605
  default:
  {
unknown's avatar
unknown committed
3606 3607 3608 3609
    /*
      Convert time value  to string and delegate the rest to
      fetch_string_with_conversion:
    */
3610 3611
    char buff[MAX_DATE_STRING_REP_LENGTH];
    uint length= my_TIME_to_str(time, buff);
unknown's avatar
unknown committed
3612 3613 3614
    /* Resort to string conversion */
    fetch_string_with_conversion(param, (char *)buff, length);
    break;
unknown's avatar
unknown committed
3615 3616 3617
  }
  }
}
3618

unknown's avatar
unknown committed
3619

unknown's avatar
unknown committed
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
/*
  Fetch and convert result set column to output buffer.

  SYNOPSIS
    fetch_result_with_conversion()
    param   output buffer descriptor
    field   column metadata
    row     points to a column of result set tuple in binary format

  DESCRIPTION
    This is a fallback implementation of column fetch used
    if column and output buffer types do not match.
    Increases tuple pointer to point at the next column within the
    tuple.
*/
3635

unknown's avatar
unknown committed
3636 3637
static void fetch_result_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
                                         uchar **row)
3638
{
unknown's avatar
unknown committed
3639
  enum enum_field_types field_type= field->type;
unknown's avatar
unknown committed
3640
  uint field_is_unsigned= field->flags & UNSIGNED_FLAG;
unknown's avatar
unknown committed
3641

3642 3643 3644
  switch (field_type) {
  case MYSQL_TYPE_TINY:
  {
3645 3646 3647 3648
    uchar value= **row;
    /* sic: we need to cast to 'signed char' as 'char' may be unsigned */
    longlong data= field_is_unsigned ? (longlong) value :
                                       (longlong) (signed char) value;
unknown's avatar
unknown committed
3649
    fetch_long_with_conversion(param, field, data);
unknown's avatar
unknown committed
3650
    *row+= 1;
3651 3652 3653 3654 3655
    break;
  }
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_YEAR:
  {
3656
    short value= sint2korr(*row);
unknown's avatar
unknown committed
3657 3658
    longlong data= field_is_unsigned ? (longlong) (unsigned short) value :
                                       (longlong) value;
unknown's avatar
unknown committed
3659
    fetch_long_with_conversion(param, field, data);
unknown's avatar
unknown committed
3660
    *row+= 2;
3661 3662
    break;
  }
3663
  case MYSQL_TYPE_INT24: /* mediumint is sent as 4 bytes int */
3664 3665
  case MYSQL_TYPE_LONG:
  {
3666 3667
    int32 value= sint4korr(*row);
    longlong data= field_is_unsigned ? (longlong) (uint32) value :
unknown's avatar
unknown committed
3668
                                       (longlong) value;
unknown's avatar
unknown committed
3669
    fetch_long_with_conversion(param, field, data);
unknown's avatar
unknown committed
3670
    *row+= 4;
3671 3672 3673 3674 3675
    break;
  }
  case MYSQL_TYPE_LONGLONG:
  {
    longlong value= (longlong)sint8korr(*row);
unknown's avatar
unknown committed
3676
    fetch_long_with_conversion(param, field, value);
unknown's avatar
unknown committed
3677
    *row+= 8;
3678 3679 3680 3681 3682 3683
    break;
  }
  case MYSQL_TYPE_FLOAT:
  {
    float value;
    float4get(value,*row);
unknown's avatar
unknown committed
3684
    fetch_float_with_conversion(param, field, value, FLT_DIG);
unknown's avatar
unknown committed
3685
    *row+= 4;
3686 3687 3688 3689 3690 3691
    break;
  }
  case MYSQL_TYPE_DOUBLE:
  {
    double value;
    float8get(value,*row);
unknown's avatar
unknown committed
3692
    fetch_float_with_conversion(param, field, value, DBL_DIG);
unknown's avatar
unknown committed
3693
    *row+= 8;
3694 3695 3696 3697
    break;
  }
  case MYSQL_TYPE_DATE:
  {
unknown's avatar
unknown committed
3698
    MYSQL_TIME tm;
3699

unknown's avatar
unknown committed
3700
    read_binary_date(&tm, row);
unknown's avatar
unknown committed
3701
    fetch_datetime_with_conversion(param, &tm);
3702 3703 3704 3705
    break;
  }
  case MYSQL_TYPE_TIME:
  {
unknown's avatar
unknown committed
3706
    MYSQL_TIME tm;
3707

unknown's avatar
unknown committed
3708
    read_binary_time(&tm, row);
unknown's avatar
unknown committed
3709
    fetch_datetime_with_conversion(param, &tm);
unknown's avatar
unknown committed
3710 3711 3712 3713 3714 3715
    break;
  }
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
  {
    MYSQL_TIME tm;
3716

unknown's avatar
unknown committed
3717
    read_binary_datetime(&tm, row);
unknown's avatar
unknown committed
3718
    fetch_datetime_with_conversion(param, &tm);
3719 3720
    break;
  }
3721
  default:
unknown's avatar
unknown committed
3722 3723
  {
    ulong length= net_field_length(row);
unknown's avatar
unknown committed
3724
    fetch_string_with_conversion(param, (char*) *row, length);
unknown's avatar
unknown committed
3725
    *row+= length;
3726 3727
    break;
  }
unknown's avatar
unknown committed
3728
  }
3729 3730
}

unknown's avatar
unknown committed
3731

3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750
/*
  Functions to fetch data to application buffers without conversion.

  All functions have the following characteristics:

  SYNOPSIS
    fetch_result_xxx()
    param   MySQL bind param
    pos     Row value

  DESCRIPTION
    These are no-conversion functions, used in binary protocol to store
    rows in application buffers. A function used only if type of binary data
    is compatible with type of application buffer.

  RETURN
    none
*/

unknown's avatar
unknown committed
3751 3752
static void fetch_result_tinyint(MYSQL_BIND *param, uchar **row)
{
3753
  *(uchar *)param->buffer= **row;
3754
  (*row)++;
unknown's avatar
unknown committed
3755 3756 3757 3758
}

static void fetch_result_short(MYSQL_BIND *param, uchar **row)
{
3759
  short value = (short)sint2korr(*row);
3760
  shortstore(param->buffer, value);
3761
  *row+= 2;
unknown's avatar
unknown committed
3762 3763 3764 3765
}

static void fetch_result_int32(MYSQL_BIND *param, uchar **row)
{
3766
  int32 value= (int32)sint4korr(*row);
3767
  longstore(param->buffer, value);
3768
  *row+= 4;
unknown's avatar
unknown committed
3769 3770 3771
}

static void fetch_result_int64(MYSQL_BIND *param, uchar **row)
3772
{
3773
  longlong value= (longlong)sint8korr(*row);
3774
  longlongstore(param->buffer, value);
3775
  *row+= 8;
unknown's avatar
unknown committed
3776 3777 3778 3779 3780 3781
}

static void fetch_result_float(MYSQL_BIND *param, uchar **row)
{
  float value;
  float4get(value,*row);
3782
  floatstore(param->buffer, value);
3783
  *row+= 4;
unknown's avatar
unknown committed
3784 3785 3786 3787 3788 3789
}

static void fetch_result_double(MYSQL_BIND *param, uchar **row)
{
  double value;
  float8get(value,*row);
3790
  doublestore(param->buffer, value);
3791
  *row+= 8;
unknown's avatar
unknown committed
3792 3793
}

unknown's avatar
unknown committed
3794 3795 3796
static void fetch_result_time(MYSQL_BIND *param, uchar **row)
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
unknown's avatar
unknown committed
3797
  read_binary_time(tm, row);
unknown's avatar
unknown committed
3798 3799 3800 3801 3802
}

static void fetch_result_date(MYSQL_BIND *param, uchar **row)
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
unknown's avatar
unknown committed
3803
  read_binary_date(tm, row);
unknown's avatar
unknown committed
3804 3805 3806 3807 3808
}

static void fetch_result_datetime(MYSQL_BIND *param, uchar **row)
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
unknown's avatar
unknown committed
3809
  read_binary_datetime(tm, row);
unknown's avatar
unknown committed
3810 3811
}

unknown's avatar
unknown committed
3812
static void fetch_result_bin(MYSQL_BIND *param, uchar **row)
3813
{
unknown's avatar
unknown committed
3814 3815 3816
  ulong length= net_field_length(row);
  ulong copy_length= min(length, param->buffer_length);
  memcpy(param->buffer, (char *)*row, copy_length);
3817
  *param->length= length;
unknown's avatar
unknown committed
3818 3819
  *row+= length;
}
3820

unknown's avatar
unknown committed
3821 3822 3823
static void fetch_result_str(MYSQL_BIND *param, uchar **row)
{
  ulong length= net_field_length(row);
3824 3825
  ulong copy_length= min(length, param->buffer_length);
  memcpy(param->buffer, (char *)*row, copy_length);
3826 3827
  /* Add an end null if there is room in the buffer */
  if (copy_length != param->buffer_length)
3828
    ((uchar *)param->buffer)[copy_length]= '\0';
3829
  *param->length= length;			/* return total length */
3830
  *row+= length;
unknown's avatar
unknown committed
3831 3832
}

unknown's avatar
unknown committed
3833

3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
/*
  functions to calculate max lengths for strings during
  mysql_stmt_store_result()
*/

static void skip_result_fixed(MYSQL_BIND *param,
			      MYSQL_FIELD *field __attribute__((unused)),
			      uchar **row)

{
  (*row)+= param->pack_length;
}


static void skip_result_with_length(MYSQL_BIND *param __attribute__((unused)),
				    MYSQL_FIELD *field __attribute__((unused)),
				    uchar **row)

{
  ulong length= net_field_length(row);
  (*row)+= length;
}


static void skip_result_string(MYSQL_BIND *param __attribute__((unused)),
			       MYSQL_FIELD *field,
			       uchar **row)

{
  ulong length= net_field_length(row);
  (*row)+= length;
  if (field->max_length < length)
    field->max_length= length;
}


3870
/*
3871
  Setup the bind buffers for resultset processing
3872 3873
*/

3874
my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT *stmt, MYSQL_BIND *bind)
3875
{
3876
  MYSQL_BIND *param, *end;
3877
  MYSQL_FIELD *field;
3878
  ulong       bind_count= stmt->field_count;
3879
  uint        param_count= 0;
3880
  DBUG_ENTER("mysql_stmt_bind_result");
3881
  DBUG_PRINT("enter",("field_count: %d", bind_count));
3882

3883
  if (!bind_count)
3884 3885 3886 3887 3888
  {
    if ((int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE)
    {
      set_stmt_error(stmt, CR_NO_PREPARE_STMT, unknown_sqlstate);
    }
3889
    DBUG_RETURN(0);
3890 3891 3892 3893 3894 3895
  }

  /*
    We only need to check that stmt->field_count - if it is not null
    stmt->bind was initialized in mysql_stmt_prepare
   */
3896

3897
  memcpy((char*) stmt->bind, (char*) bind, sizeof(MYSQL_BIND) * bind_count);
3898

3899 3900 3901
  for (param= stmt->bind, end= param + bind_count, field= stmt->fields ;
       param < end ;
       param++, field++)
3902
  {
3903 3904
    DBUG_PRINT("info",("buffer_type: %u  field_type: %u",
                       (uint) param->buffer_type, (uint) field->type));
unknown's avatar
unknown committed
3905 3906
    /*
      Set param->is_null to point to a dummy variable if it's not set.
unknown's avatar
unknown committed
3907
      This is to make the execute code easier
unknown's avatar
unknown committed
3908 3909
    */
    if (!param->is_null)
unknown's avatar
unknown committed
3910
      param->is_null= &param->internal_is_null;
unknown's avatar
unknown committed
3911

unknown's avatar
unknown committed
3912
    if (!param->length)
unknown's avatar
unknown committed
3913
      param->length= &param->internal_length;
unknown's avatar
unknown committed
3914

3915
    param->param_number= param_count++;
unknown's avatar
unknown committed
3916 3917
    param->offset= 0;

unknown's avatar
unknown committed
3918 3919
    /* Setup data copy functions for the different supported types */
    switch (param->buffer_type) {
unknown's avatar
unknown committed
3920
    case MYSQL_TYPE_NULL: /* for dummy binds */
3921
      *param->length= 0;
unknown's avatar
unknown committed
3922
      break;
unknown's avatar
unknown committed
3923 3924
    case MYSQL_TYPE_TINY:
      param->fetch_result= fetch_result_tinyint;
unknown's avatar
unknown committed
3925
      *param->length= 1;
unknown's avatar
unknown committed
3926 3927
      break;
    case MYSQL_TYPE_SHORT:
3928
    case MYSQL_TYPE_YEAR:
unknown's avatar
unknown committed
3929
      param->fetch_result= fetch_result_short;
unknown's avatar
unknown committed
3930
      *param->length= 2;
unknown's avatar
unknown committed
3931
      break;
3932
    case MYSQL_TYPE_INT24:
unknown's avatar
unknown committed
3933 3934
    case MYSQL_TYPE_LONG:
      param->fetch_result= fetch_result_int32;
unknown's avatar
unknown committed
3935
      *param->length= 4;
unknown's avatar
unknown committed
3936 3937 3938
      break;
    case MYSQL_TYPE_LONGLONG:
      param->fetch_result= fetch_result_int64;
unknown's avatar
unknown committed
3939
      *param->length= 8;
unknown's avatar
unknown committed
3940 3941 3942
      break;
    case MYSQL_TYPE_FLOAT:
      param->fetch_result= fetch_result_float;
unknown's avatar
unknown committed
3943
      *param->length= 4;
unknown's avatar
unknown committed
3944 3945 3946
      break;
    case MYSQL_TYPE_DOUBLE:
      param->fetch_result= fetch_result_double;
unknown's avatar
unknown committed
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960
      *param->length= 8;
      break;
    case MYSQL_TYPE_TIME:
      param->fetch_result= fetch_result_time;
      *param->length= sizeof(MYSQL_TIME);
      break;
    case MYSQL_TYPE_DATE:
      param->fetch_result= fetch_result_date;
      *param->length= sizeof(MYSQL_TIME);
      break;
    case MYSQL_TYPE_DATETIME:
    case MYSQL_TYPE_TIMESTAMP:
      param->fetch_result= fetch_result_datetime;
      *param->length= sizeof(MYSQL_TIME);
unknown's avatar
unknown committed
3961 3962 3963 3964
      break;
    case MYSQL_TYPE_TINY_BLOB:
    case MYSQL_TYPE_MEDIUM_BLOB:
    case MYSQL_TYPE_LONG_BLOB:
3965
    case MYSQL_TYPE_BLOB:
unknown's avatar
unknown committed
3966 3967 3968
      DBUG_ASSERT(param->buffer_length != 0);
      param->fetch_result= fetch_result_bin;
      break;
unknown's avatar
unknown committed
3969 3970
    case MYSQL_TYPE_VAR_STRING:
    case MYSQL_TYPE_STRING:
unknown's avatar
unknown committed
3971
      DBUG_ASSERT(param->buffer_length != 0);
unknown's avatar
unknown committed
3972 3973 3974
      param->fetch_result= fetch_result_str;
      break;
    default:
3975
      strmov(stmt->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
3976 3977
      sprintf(stmt->last_error,
	      ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
3978
	      param->buffer_type, param_count);
unknown's avatar
unknown committed
3979
      DBUG_RETURN(1);
unknown's avatar
unknown committed
3980
    }
3981 3982 3983 3984 3985 3986

    /* Setup skip_result functions (to calculate max_length) */
    param->skip_result= skip_result_fixed;
    switch (field->type) {
    case MYSQL_TYPE_NULL: /* for dummy binds */
      param->pack_length= 0;
3987
      field->max_length= 0;
3988 3989 3990
      break;
    case MYSQL_TYPE_TINY:
      param->pack_length= 1;
3991
      field->max_length= 4;                     /* as in '-127' */
3992 3993 3994 3995
      break;
    case MYSQL_TYPE_YEAR:
    case MYSQL_TYPE_SHORT:
      param->pack_length= 2;
3996
      field->max_length= 6;                     /* as in '-32767' */
3997 3998
      break;
    case MYSQL_TYPE_INT24:
3999 4000 4001
      field->max_length= 9;  /* as in '16777216' or in '-8388607' */
      param->pack_length= 4;
      break;
4002
    case MYSQL_TYPE_LONG:
4003
      field->max_length= 11;                    /* '-2147483647' */
4004 4005 4006
      param->pack_length= 4;
      break;
    case MYSQL_TYPE_LONGLONG:
4007
      field->max_length= 21;                    /* '18446744073709551616' */
4008 4009 4010 4011
      param->pack_length= 8;
      break;
    case MYSQL_TYPE_FLOAT:
      param->pack_length= 4;
4012
      field->max_length= MAX_DOUBLE_STRING_REP_LENGTH;
4013 4014 4015
      break;
    case MYSQL_TYPE_DOUBLE:
      param->pack_length= 8;
4016
      field->max_length= MAX_DOUBLE_STRING_REP_LENGTH;
4017 4018 4019 4020 4021 4022
      break;
    case MYSQL_TYPE_TIME:
    case MYSQL_TYPE_DATE:
    case MYSQL_TYPE_DATETIME:
    case MYSQL_TYPE_TIMESTAMP:
      param->skip_result= skip_result_with_length;
4023
      field->max_length= MAX_DATE_STRING_REP_LENGTH;
4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
      break;
    case MYSQL_TYPE_DECIMAL:
    case MYSQL_TYPE_ENUM:
    case MYSQL_TYPE_SET:
    case MYSQL_TYPE_GEOMETRY:
    case MYSQL_TYPE_TINY_BLOB:
    case MYSQL_TYPE_MEDIUM_BLOB:
    case MYSQL_TYPE_LONG_BLOB:
    case MYSQL_TYPE_BLOB:
    case MYSQL_TYPE_VAR_STRING:
    case MYSQL_TYPE_STRING:
      param->skip_result= skip_result_string;
      break;
    default:
      strmov(stmt->sqlstate, unknown_sqlstate);
      sprintf(stmt->last_error,
	      ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
	      field->type, param_count);
      DBUG_RETURN(1);
    }
4044
  }
4045
  stmt->bind_result_done= TRUE;
4046 4047 4048
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
4049

4050
/*
4051
  Fetch row data to bind buffers
4052 4053
*/

4054
static int stmt_fetch_row(MYSQL_STMT *stmt, uchar *row)
4055
{
4056
  MYSQL_BIND  *bind, *end;
4057
  MYSQL_FIELD *field;
unknown's avatar
unknown committed
4058
  uchar *null_ptr, bit;
4059 4060 4061 4062 4063 4064
  /*
    Precondition: if stmt->field_count is zero or row is NULL, read_row_*
    function must return no data.
  */
  DBUG_ASSERT(stmt->field_count);
  DBUG_ASSERT(row);
4065

4066 4067 4068
  if (!stmt->bind_result_done)
  {
    /* If output parameters were not bound we should just return success */
4069
    return 0;
4070
  }
4071 4072

  null_ptr= row;
unknown's avatar
unknown committed
4073 4074
  row+= (stmt->field_count+9)/8;		/* skip null bits */
  bit= 4;					/* first 2 bits are reserved */
4075

unknown's avatar
unknown committed
4076
  /* Copy complete row to application buffers */
4077 4078
  for (bind= stmt->bind, end= bind + stmt->field_count, field= stmt->fields ;
       bind < end ;
unknown's avatar
unknown committed
4079
       bind++, field++)
4080
  {
4081
    if (*null_ptr & bit)
4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092
    {
      /*
        We should set both inter_buffer and is_null to be able to see
        nulls in mysql_stmt_fetch_column. This is because is_null may point
        to user data which can be overwritten between mysql_stmt_fetch and
        mysql_stmt_fetch_column, and in this case nullness of column will be
        lost. See mysql_stmt_fetch_column for details.
      */
      bind->inter_buffer= NULL;
      *bind->is_null= 1;
    }
4093
    else
4094
    {
4095
      *bind->is_null= 0;
unknown's avatar
unknown committed
4096
      bind->inter_buffer= row;
4097 4098
      if (field->type == bind->buffer_type)
        (*bind->fetch_result)(bind, &row);
4099
      else
unknown's avatar
unknown committed
4100
        fetch_result_with_conversion(bind, field, &row);
4101
    }
unknown's avatar
unknown committed
4102
    if (!((bit<<=1) & 255))
4103
    {
unknown's avatar
unknown committed
4104
      bit= 1;					/* To next byte */
4105
      null_ptr++;
4106 4107 4108 4109 4110
    }
  }
  return 0;
}

4111

unknown's avatar
unknown committed
4112
int cli_unbuffered_fetch(MYSQL *mysql, char **row)
unknown's avatar
SCRUM  
unknown committed
4113 4114 4115 4116
{
  if (packet_error == net_safe_read(mysql))
    return 1;

unknown's avatar
unknown committed
4117 4118
  *row= ((mysql->net.read_pos[0] == 254) ? NULL :
	 (char*) (mysql->net.read_pos+1));
unknown's avatar
SCRUM  
unknown committed
4119 4120
  return 0;
}
unknown's avatar
unknown committed
4121

4122

4123
/*
4124
  Fetch and return row data to bound buffers, if any
4125 4126
*/

4127
int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt)
4128
{
4129
  int rc;
4130
  uchar *row;
4131
  DBUG_ENTER("mysql_stmt_fetch");
4132

4133 4134
  if ((rc= (*stmt->read_row_func)(stmt, &row)) ||
      (rc= stmt_fetch_row(stmt, row)))
4135
  {
4136 4137
    stmt->state= MYSQL_STMT_PREPARE_DONE;       /* XXX: this is buggy */
    stmt->read_row_func= stmt_read_row_no_data;
unknown's avatar
unknown committed
4138
  }
4139
  else
4140
  {
4141 4142
    /* This is to know in mysql_stmt_fetch_column that data was fetched */
    stmt->state= MYSQL_STMT_FETCH_DONE;
unknown's avatar
SCRUM  
unknown committed
4143
  }
4144
  DBUG_RETURN(rc);
4145 4146
}

unknown's avatar
unknown committed
4147

unknown's avatar
unknown committed
4148
/*
unknown's avatar
unknown committed
4149
  Fetch data for one specified column data
unknown's avatar
unknown committed
4150 4151

  SYNOPSIS
4152
    mysql_stmt_fetch_column()
unknown's avatar
unknown committed
4153
    stmt		Prepared statement handler
unknown's avatar
unknown committed
4154
    bind		Where data should be placed. Should be filled in as
4155
			when calling mysql_stmt_bind_result()
unknown's avatar
unknown committed
4156 4157 4158
    column		Column to fetch (first column is 0)
    ulong offset	Offset in result data (to fetch blob in pieces)
			This is normally 0
4159
  RETURN
unknown's avatar
unknown committed
4160 4161
    0	ok
    1	error
unknown's avatar
unknown committed
4162 4163
*/

4164
int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
4165
                                    uint column, ulong offset)
unknown's avatar
unknown committed
4166
{
4167
  MYSQL_BIND *param= stmt->bind+column;
4168
  DBUG_ENTER("mysql_stmt_fetch_column");
unknown's avatar
unknown committed
4169

4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
  if ((int) stmt->state < (int) MYSQL_STMT_FETCH_DONE)
  {
    set_stmt_error(stmt, CR_NO_DATA, unknown_sqlstate);
    return 1;
  }
  if (column >= stmt->field_count)
  {
    set_stmt_error(stmt, CR_INVALID_PARAMETER_NO, unknown_sqlstate);
    DBUG_RETURN(1);
  }

4181
  if (param->inter_buffer)
unknown's avatar
unknown committed
4182
  {
4183
    MYSQL_FIELD *field= stmt->fields+column;
unknown's avatar
unknown committed
4184
    uchar *row= param->inter_buffer;
unknown's avatar
unknown committed
4185 4186 4187 4188
    bind->offset= offset;
    if (bind->is_null)
      *bind->is_null= 0;
    if (bind->length) /* Set the length if non char/binary types */
unknown's avatar
unknown committed
4189
      *bind->length= *param->length;
unknown's avatar
unknown committed
4190
    else
unknown's avatar
unknown committed
4191
      bind->length= &param->internal_length;	/* Needed for fetch_result() */
unknown's avatar
unknown committed
4192
    fetch_result_with_conversion(bind, field, &row);
unknown's avatar
unknown committed
4193
  }
4194 4195 4196 4197 4198
  else
  {
    if (bind->is_null)
      *bind->is_null= 1;
  }
unknown's avatar
unknown committed
4199 4200 4201 4202
  DBUG_RETURN(0);
}


4203
/*
4204 4205 4206
  Read all rows of data from server  (binary format)
*/

4207
int cli_read_binary_rows(MYSQL_STMT *stmt)
4208 4209 4210 4211
{
  ulong      pkt_len;
  uchar      *cp;
  MYSQL      *mysql= stmt->mysql;
4212 4213
  MYSQL_DATA *result= &stmt->result;
  MYSQL_ROWS *cur, **prev_ptr= &result->data;
4214
  NET        *net = &mysql->net;
4215
  DBUG_ENTER("cli_read_binary_rows");
4216

4217
  mysql= mysql->last_used_con;
4218

4219
  while ((pkt_len= net_safe_read(mysql)) != packet_error)
4220
  {
4221 4222
    cp= net->read_pos;
    if (cp[0] != 254 || pkt_len >= 8)
4223
    {
4224 4225 4226 4227
      if (!(cur= (MYSQL_ROWS*) alloc_root(&result->alloc,
                                          sizeof(MYSQL_ROWS) + pkt_len - 1)))
      {
        set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
4228
        goto err;
4229 4230 4231 4232 4233
      }
      cur->data= (MYSQL_ROW) (cur+1);
      *prev_ptr= cur;
      prev_ptr= &cur->next;
      memcpy((char *) cur->data, (char *) cp+1, pkt_len-1);
4234 4235
      cur->length= pkt_len;		/* To allow us to do sanity checks */
      result->rows++;
4236
    }
4237
    else
4238
    {
4239 4240 4241 4242
      /* end of data */
      *prev_ptr= 0;
      mysql->warning_count= uint2korr(cp+1);
      mysql->server_status= uint2korr(cp+3);
4243 4244
      DBUG_PRINT("info",("status: %u  warning_count: %u",
                         mysql->server_status, mysql->warning_count));
4245 4246 4247
      DBUG_RETURN(0);
    }
  }
4248
  set_stmt_errmsg(stmt, net->last_error, net->last_errno, net->sqlstate);
4249 4250

err:
4251
  DBUG_RETURN(1);
4252 4253
}

4254

4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297
/*
  Update meta data for statement

  SYNOPSIS
    stmt_update_metadata()
    stmt			Statement handler
    row				Binary data

  NOTES
    Only updates MYSQL_FIELD->max_length for strings
*/

static void stmt_update_metadata(MYSQL_STMT *stmt, MYSQL_ROWS *data)
{
  MYSQL_BIND  *bind, *end;
  MYSQL_FIELD *field;
  uchar *null_ptr, bit;
  uchar *row= (uchar*) data->data;
#ifndef DBUG_OFF
  uchar *row_end= row + data->length;
#endif

  null_ptr= row;
  row+= (stmt->field_count+9)/8;		/* skip null bits */
  bit= 4;					/* first 2 bits are reserved */

  /* Go throw all fields and calculate metadata */
  for (bind= stmt->bind, end= bind + stmt->field_count, field= stmt->fields ;
       bind < end ;
       bind++, field++)
  {
    if (!(*null_ptr & bit))
      (*bind->skip_result)(bind, field, &row);
    DBUG_ASSERT(row <= row_end);
    if (!((bit<<=1) & 255))
    {
      bit= 1;					/* To next byte */
      null_ptr++;
    }
  }
}


4298 4299 4300 4301 4302 4303 4304
/*
  Store or buffer the binary results to stmt
*/

int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt)
{
  MYSQL *mysql= stmt->mysql;
4305
  MYSQL_DATA *result= &stmt->result;
4306
  DBUG_ENTER("mysql_stmt_store_result");
4307 4308 4309 4310 4311

  mysql= mysql->last_used_con;

  if (!stmt->field_count)
    DBUG_RETURN(0);
4312 4313
  if ((int) stmt->state < (int) MYSQL_STMT_EXECUTE_DONE ||
      mysql->status != MYSQL_STATUS_GET_RESULT)
4314
  {
4315
    set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
4316
    DBUG_RETURN(1);
4317
  }
4318
  if (result->data)
4319
  {
4320 4321 4322 4323
    free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
    result->data= NULL;
    result->rows= 0;
    stmt->data_cursor= NULL;
4324
  }
4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339

  if (stmt->update_max_length && !stmt->bind_result_done)
  {
    /*
      We must initalize the bind structure to be able to calculate
      max_length
    */
    MYSQL_BIND  *bind, *end;
    MYSQL_FIELD *field;
    bzero((char*) stmt->bind, sizeof(*stmt->bind)* stmt->field_count);

    for (bind= stmt->bind, end= bind + stmt->field_count, field= stmt->fields;
	 bind < end ;
	 bind++, field++)
    {
4340
      bind->buffer_type= MYSQL_TYPE_NULL;
4341 4342 4343
      bind->buffer_length=1;
    }

4344 4345
    if (mysql_stmt_bind_result(stmt, stmt->bind))
      DBUG_RETURN(1);
4346 4347 4348
    stmt->bind_result_done= 0;			/* No normal bind done */
  }

4349
  if ((*mysql->methods->read_binary_rows)(stmt))
4350
  {
4351 4352 4353
    free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
    result->data= NULL;
    result->rows= 0;
4354
    mysql->status= MYSQL_STATUS_READY;
4355
    DBUG_RETURN(1);
4356
  }
4357

4358 4359 4360 4361 4362 4363 4364
  if (stmt->update_max_length)
  {
    MYSQL_ROWS *cur= result->data;
    for(; cur; cur=cur->next)
      stmt_update_metadata(stmt, cur);
  }

4365 4366
  stmt->data_cursor= result->data;
  mysql->affected_rows= stmt->affected_rows= result->rows;
4367 4368 4369
  stmt->read_row_func= stmt_read_row_buffered;
  mysql->unbuffered_fetch_owner= 0;             /* set in stmt_execute */
  mysql->status= MYSQL_STATUS_READY;		/* server is ready */
4370
  DBUG_RETURN(0); /* Data buffered, must be fetched with mysql_stmt_fetch() */
4371 4372
}

4373

4374 4375 4376 4377 4378 4379 4380
/*
  Seek to desired row in the statement result set
*/

MYSQL_ROW_OFFSET STDCALL
mysql_stmt_row_seek(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET row)
{
4381
  MYSQL_ROW_OFFSET offset= stmt->data_cursor;
4382
  DBUG_ENTER("mysql_stmt_row_seek");
4383

4384 4385
  stmt->data_cursor= row;
  DBUG_RETURN(offset);
4386 4387
}

4388

4389 4390 4391 4392
/*
  Return the current statement row cursor position
*/

4393
MYSQL_ROW_OFFSET STDCALL
4394 4395 4396
mysql_stmt_row_tell(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_row_tell");
4397

4398
  DBUG_RETURN(stmt->data_cursor);
4399 4400
}

unknown's avatar
unknown committed
4401

4402 4403 4404 4405 4406 4407 4408
/*
  Move the stmt result set data cursor to specified row
*/

void STDCALL
mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong row)
{
4409
  MYSQL_ROWS *tmp= stmt->result.data;
4410 4411
  DBUG_ENTER("mysql_stmt_data_seek");
  DBUG_PRINT("enter",("row id to seek: %ld",(long) row));
4412

4413 4414 4415
  for (; tmp && row; --row, tmp= tmp->next)
    ;
  stmt->data_cursor= tmp;
unknown's avatar
unknown committed
4416 4417 4418 4419 4420 4421
  if (!row && tmp)
  {
       /*  Rewind the counter */
    stmt->read_row_func= stmt_read_row_buffered;
    stmt->state= MYSQL_STMT_EXECUTE_DONE;
  }
4422
  DBUG_VOID_RETURN;
4423 4424
}

unknown's avatar
unknown committed
4425

4426 4427 4428 4429 4430 4431 4432
/*
  Return total rows the current statement result set
*/

my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_num_rows");
4433

4434
  DBUG_RETURN(stmt->result.rows);
4435
}
4436

4437 4438
my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt)
{
4439
  MYSQL_DATA *result= &stmt->result;
4440 4441 4442
  DBUG_ENTER("mysql_stmt_free_result");

  DBUG_ASSERT(stmt != 0);
4443

4444 4445 4446 4447
  if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
  {
    MYSQL *mysql= stmt->mysql;

4448
    if (result->data)
4449 4450
    {
      /* Result buffered */
4451 4452 4453 4454
      free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
      result->data= NULL;
      result->rows= 0;
      stmt->data_cursor= NULL;
4455
    }
4456 4457 4458

    if (mysql && stmt->field_count &&
        (int) stmt->state > (int) MYSQL_STMT_PREPARE_DONE)
4459 4460 4461 4462 4463 4464
    {
      if (mysql->unbuffered_fetch_owner == &stmt->unbuffered_fetch_cancelled)
        mysql->unbuffered_fetch_owner= 0;
      if (mysql->status != MYSQL_STATUS_READY)
      {
        /* There is a result set and it belongs to this statement */
unknown's avatar
unknown committed
4465
        (*mysql->methods->flush_use_result)(mysql);
4466 4467 4468 4469 4470 4471 4472 4473 4474
        mysql->status= MYSQL_STATUS_READY;
      }
    }
    stmt->state= MYSQL_STMT_PREPARE_DONE;
    stmt->read_row_func= stmt_read_row_no_data;
  }
  DBUG_RETURN(0);
}

4475
/********************************************************************
4476
 statement error handling and close
4477
*********************************************************************/
4478

4479
/*
unknown's avatar
unknown committed
4480
  Close the statement handle by freeing all alloced resources
4481

unknown's avatar
unknown committed
4482
  SYNOPSIS
4483
    mysql_stmt_close()
unknown's avatar
unknown committed
4484
    stmt	       Statement handle
4485

unknown's avatar
unknown committed
4486 4487 4488 4489
  RETURN VALUES
    0	ok
    1	error
*/
4490

4491
my_bool STDCALL mysql_stmt_close(MYSQL_STMT *stmt)
4492
{
4493 4494 4495
  MYSQL *mysql= stmt->mysql;
  int rc= 0;
  DBUG_ENTER("mysql_stmt_close");
4496

4497
  free_root(&stmt->result.alloc, MYF(0));
4498 4499 4500
  free_root(&stmt->mem_root, MYF(0));

  if (mysql)
4501
  {
4502 4503
    mysql->stmts= list_delete(mysql->stmts, &stmt->list);
    if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
4504
    {
4505
      char buff[MYSQL_STMT_HEADER];             /* 4 bytes - stmt id */
4506 4507 4508 4509 4510

      if (mysql->unbuffered_fetch_owner == &stmt->unbuffered_fetch_cancelled)
        mysql->unbuffered_fetch_owner= 0;
      if (mysql->status != MYSQL_STATUS_READY)
      {
4511
        /*
4512 4513 4514
          Flush result set of the connection. If it does not belong
          to this statement, set a warning.
        */
unknown's avatar
unknown committed
4515
        (*mysql->methods->flush_use_result)(mysql);
4516 4517 4518 4519 4520 4521 4522 4523 4524 4525
        if (mysql->unbuffered_fetch_owner)
          *mysql->unbuffered_fetch_owner= TRUE;
        mysql->status= MYSQL_STATUS_READY;
      }
      int4store(buff, stmt->stmt_id);
      if ((rc= simple_command(mysql, COM_CLOSE_STMT, buff, 4, 1)))
      {
        set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                        mysql->net.sqlstate);
      }
4526
    }
4527
  }
4528

4529
  my_free((gptr) stmt, MYF(MY_WME));
unknown's avatar
unknown committed
4530

4531
  DBUG_RETURN(test(rc));
unknown's avatar
unknown committed
4532 4533
}

4534 4535 4536 4537 4538 4539
/*
  Reset the statement buffers in server
*/

my_bool STDCALL mysql_stmt_reset(MYSQL_STMT *stmt)
{
4540
  char buff[MYSQL_STMT_HEADER]; /* packet header: 4 bytes for stmt id */
4541
  MYSQL *mysql;
4542
  MYSQL_BIND *param, *param_end;
4543 4544
  DBUG_ENTER("mysql_stmt_reset");
  DBUG_ASSERT(stmt != 0);
4545 4546 4547 4548

  /* If statement hasnt been prepared there is nothing to reset */
  if ((int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE)
    DBUG_RETURN(0);
4549

4550 4551
  mysql= stmt->mysql->last_used_con;
  int4store(buff, stmt->stmt_id);		/* Send stmt id to server */
4552
  if ((*mysql->methods->advanced_command)(mysql, COM_RESET_STMT, buff,
4553
                                          sizeof(buff), 0, 0, 0))
4554
  {
4555
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
4556 4557 4558
                    mysql->net.sqlstate);
    DBUG_RETURN(1);
  }
4559 4560 4561 4562 4563 4564 4565

  /* Clear long_data_used for next call (as we do in mysql_stmt_execute() */
  for (param= stmt->params, param_end= param + stmt->param_count;
       param < param_end;
       param++)
    param->long_data_used= 0;

4566 4567 4568
  DBUG_RETURN(0);
}

4569 4570 4571 4572 4573 4574 4575
/*
  Return statement error code
*/

uint STDCALL mysql_stmt_errno(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_errno");
4576
  DBUG_RETURN(stmt->last_errno);
4577 4578
}

4579 4580 4581 4582 4583 4584
const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_sqlstate");
  DBUG_RETURN(stmt->sqlstate);
}

4585 4586 4587 4588 4589 4590 4591
/*
  Return statement error message
*/

const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_error");
4592
  DBUG_RETURN(stmt->last_error);
4593 4594
}

4595

4596 4597 4598 4599
/********************************************************************
 Transactional APIs
*********************************************************************/

4600 4601 4602 4603
/*
  Commit the current transaction
*/

4604
my_bool STDCALL mysql_commit(MYSQL * mysql)
4605 4606
{
  DBUG_ENTER("mysql_commit");
4607
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "commit", 6));
4608 4609 4610
}

/*
4611
  Rollback the current transaction
4612 4613
*/

4614
my_bool STDCALL mysql_rollback(MYSQL * mysql)
4615 4616
{
  DBUG_ENTER("mysql_rollback");
4617
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "rollback", 8));
4618 4619 4620 4621 4622 4623 4624
}


/*
  Set autocommit to either true or false
*/

4625
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode)
4626 4627 4628 4629 4630
{
  DBUG_ENTER("mysql_autocommit");
  DBUG_PRINT("enter", ("mode : %d", auto_mode));

  if (auto_mode) /* set to true */
4631 4632
    DBUG_RETURN((my_bool) mysql_real_query(mysql, "set autocommit=1", 16));
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "set autocommit=0", 16));
4633
}
4634 4635 4636


/********************************************************************
4637
 Multi query execution + SPs APIs
4638 4639 4640
*********************************************************************/

/*
unknown's avatar
unknown committed
4641 4642
  Returns true/false to indicate whether any more query results exist
  to be read using mysql_next_result()
4643 4644 4645 4646
*/

my_bool STDCALL mysql_more_results(MYSQL *mysql)
{
4647
  my_bool res;
4648
  DBUG_ENTER("mysql_more_results");
4649 4650

  res= ((mysql->last_used_con->server_status & SERVER_MORE_RESULTS_EXISTS) ?
4651
	1: 0);
4652
  DBUG_PRINT("exit",("More results exists ? %d", res));
4653
  DBUG_RETURN(res);
4654 4655
}

4656

4657 4658 4659
/*
  Reads and returns the next query results
*/
4660
int STDCALL mysql_next_result(MYSQL *mysql)
4661
{
4662
  DBUG_ENTER("mysql_next_result");
4663

4664 4665 4666 4667 4668 4669 4670 4671
  if (mysql->status != MYSQL_STATUS_READY)
  {
    strmov(mysql->net.sqlstate, unknown_sqlstate);
    strmov(mysql->net.last_error,
	   ER(mysql->net.last_errno=CR_COMMANDS_OUT_OF_SYNC));
    DBUG_RETURN(1);
  }

4672 4673
  mysql->net.last_error[0]= 0;
  mysql->net.last_errno= 0;
4674
  strmov(mysql->net.sqlstate, not_error_sqlstate);
4675 4676 4677
  mysql->affected_rows= ~(my_ulonglong) 0;

  if (mysql->last_used_con->server_status & SERVER_MORE_RESULTS_EXISTS)
unknown's avatar
unknown committed
4678 4679
    DBUG_RETURN((*mysql->methods->next_result)(mysql));

4680
  DBUG_RETURN(-1);				/* No more results */
4681
}
unknown's avatar
SCRUM:  
unknown committed
4682

4683

unknown's avatar
SCRUM:  
unknown committed
4684 4685 4686 4687 4688 4689 4690 4691 4692 4693
MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql)
{
  return (*mysql->methods->use_result)(mysql);
}

my_bool STDCALL mysql_read_query_result(MYSQL *mysql)
{
  return (*mysql->methods->read_query_result)(mysql);
}