libmysql.c 136 KB
Newer Older
Sergei Golubchik's avatar
Sergei Golubchik committed
1 2
/* Copyright (c) 2000, 2014, Oracle and/or its affiliates.
   Copyright (c) 2009, 2014, SkySQL Ab.
unknown's avatar
unknown committed
3 4 5

   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
6 7 8 9
   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
10
   EXCEPTIONS-CLIENT in the directory of this software distribution.
unknown's avatar
unknown committed
11 12

   This program is distributed in the hope that it will be useful,
unknown's avatar
unknown committed
13
   but WITHOUT ANY WARRANTY; without even the implied warranty of
unknown's avatar
unknown committed
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
Kent Boortz's avatar
Kent Boortz committed
19
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
unknown's avatar
unknown committed
20

unknown's avatar
unknown committed
21
#include <my_global.h>
unknown's avatar
unknown committed
22
#include <my_sys.h>
23
#include <my_time.h>
unknown's avatar
unknown committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37
#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
38
#if !defined(__WIN__)
unknown's avatar
unknown committed
39 40 41 42 43
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#ifdef HAVE_SELECT_H
44
#include <select.h>
unknown's avatar
unknown committed
45 46 47 48
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
49
#endif /* !defined(__WIN__) */
50 51 52
#if defined(HAVE_POLL_H)
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
53
#include <sys/poll.h>
54
#endif /* defined(HAVE_POLL_H) */
unknown's avatar
unknown committed
55
#ifdef HAVE_SYS_UN_H
56
#include <sys/un.h>
unknown's avatar
unknown committed
57
#endif
58
#if !defined(__WIN__)
unknown's avatar
unknown committed
59 60 61 62 63 64
#include <my_pthread.h>				/* because of signal()	*/
#endif
#ifndef INADDR_NONE
#define INADDR_NONE	-1
#endif

unknown's avatar
SCRUM:  
unknown committed
65
#include <sql_common.h>
unknown's avatar
SCRUM  
unknown committed
66
#include "client_settings.h"
unknown's avatar
SCRUM:  
unknown committed
67

68 69
#undef net_buffer_length
#undef max_allowed_packet
70

unknown's avatar
unknown committed
71
ulong 		net_buffer_length=8192;
72
ulong		max_allowed_packet= 1024L*1024L*1024L;
unknown's avatar
unknown committed
73

unknown's avatar
unknown committed
74

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

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

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

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

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

101 102 103 104 105
typedef struct st_mysql_stmt_extension
{
  MEM_ROOT fields_mem_root;
} MYSQL_STMT_EXT;

unknown's avatar
unknown committed
106 107

/*
unknown's avatar
merge  
unknown committed
108
  Initialize the MySQL client library
unknown's avatar
unknown committed
109 110

  SYNOPSIS
unknown's avatar
merge  
unknown committed
111
    mysql_server_init()
unknown's avatar
unknown committed
112 113

  NOTES
unknown's avatar
merge  
unknown committed
114 115 116 117 118
    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
119 120 121 122 123 124

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

unknown's avatar
unknown committed
125 126 127
int STDCALL mysql_server_init(int argc __attribute__((unused)),
			      char **argv __attribute__((unused)),
			      char **groups __attribute__((unused)))
128
{
129
  int result= 0;
130 131 132 133
  if (!mysql_client_init)
  {
    mysql_client_init=1;
    org_my_init_done=my_init_done;
unknown's avatar
unknown committed
134 135
    if (my_init())				/* Will init threads */
      return 1;
136
    init_client_errs();
137 138
    if (mysql_client_plugin_init())
      return 1;
139 140
    if (!mysql_port)
    {
141 142 143
      char *env;
      struct servent *serv_ptr __attribute__((unused));

144
      mysql_port = MYSQL_PORT;
145

146 147 148 149 150 151 152 153 154
      /*
        if builder specifically requested a default port, use that
        (even if it coincides with our factory default).
        only if they didn't do we check /etc/services (and, failing
        on that, fall back to the factory default of 3306).
        either default can be overridden by the environment variable
        MYSQL_TCP_PORT, which in turn can be overridden with command
        line options.
      */
155 156

#if MYSQL_PORT_DEFAULT == 0
157 158
      if ((serv_ptr= getservbyname("mysql", "tcp")))
        mysql_port= (uint) ntohs((ushort) serv_ptr->s_port);
159
#endif
160 161
      if ((env= getenv("MYSQL_TCP_PORT")))
        mysql_port=(uint) atoi(env);
162
    }
163

164 165 166 167 168 169 170 171 172 173 174 175
    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);
176
#if defined(SIGPIPE) && !defined(__WIN__)
unknown's avatar
unknown committed
177
    (void) signal(SIGPIPE, SIG_IGN);
178
#endif
unknown's avatar
unknown committed
179
#ifdef EMBEDDED_LIBRARY
180
    if (argc > -1)
181
       result= init_embedded_server(argc, argv, groups);
unknown's avatar
unknown committed
182
#endif
183 184
  }
  else
unknown's avatar
unknown committed
185
    result= (int)my_thread_init();         /* Init if new thread */
186
  return result;
unknown's avatar
unknown committed
187
}
unknown's avatar
unknown committed
188

189

190 191 192 193 194 195 196 197 198 199 200 201
/*
  Free all memory and resources used by the client library

  NOTES
    When calling this there should not be any other threads using
    the library.

    To make things simpler when used with windows dll's (which calls this
    function automaticly), it's safe to call this function multiple times.
*/


202
void STDCALL mysql_server_end()
203
{
204 205 206
  if (!mysql_client_init)
    return;

207 208
  mysql_client_plugin_deinit();

209
  finish_client_errs();
210 211
  if (mariadb_deinitialize_ssl)
    vio_end();
unknown's avatar
unknown committed
212
#ifdef EMBEDDED_LIBRARY
213
  end_embedded_server();
unknown's avatar
unknown committed
214
#endif
unknown's avatar
unknown committed
215

216 217
  /* If library called my_init(), free memory allocated by it */
  if (!org_my_init_done)
218
  {
219
    my_end(0);
220
  }
221 222 223 224 225 226 227
#ifdef NOT_NEEDED
  /*
    The following is not needed as if the program explicitely called
    my_init() then we can assume it will also call my_end().
    The reason to not also do it here is in that case we can't get
    statistics from my_end() to debug log.
  */
unknown's avatar
unknown committed
228
  else
unknown's avatar
unknown committed
229
  {
230
    free_charsets();
unknown's avatar
unknown committed
231
    mysql_thread_end();
unknown's avatar
unknown committed
232
  }
233
#endif
unknown's avatar
unknown committed
234

235
  mysql_client_init= org_my_init_done= 0;
236
}
unknown's avatar
unknown committed
237

238
static MYSQL_PARAMETERS mysql_internal_parameters=
239
{&max_allowed_packet, &net_buffer_length, 0};
240

unknown's avatar
unknown committed
241
MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void)
242 243 244 245
{
  return &mysql_internal_parameters;
}

246
my_bool STDCALL mysql_thread_init()
unknown's avatar
unknown committed
247
{
248
  return my_thread_init();
unknown's avatar
unknown committed
249 250
}

251
void STDCALL mysql_thread_end()
unknown's avatar
unknown committed
252
{
253
  my_thread_end();
unknown's avatar
unknown committed
254 255
}

unknown's avatar
unknown committed
256 257

/*
258
  Expand wildcard to a sql string
unknown's avatar
unknown committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
*/

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


/**************************************************************************
283
  Init debugging if MYSQL_DEBUG environment variable is found
unknown's avatar
unknown committed
284 285 286
**************************************************************************/

void STDCALL
unknown's avatar
unknown committed
287
mysql_debug(const char *debug __attribute__((unused)))
unknown's avatar
unknown committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
{
#ifndef DBUG_OFF
  char	*env;
  if (debug)
  {
    DBUG_PUSH(debug);
  }
  else if ((env = getenv("MYSQL_DEBUG")))
  {
    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];
306 307
      buff[sizeof(buff)-1]= 0;
      strxnmov(buff,sizeof(buff)-1,"libmysql: ", env, NullS);
unknown's avatar
unknown committed
308 309 310 311 312 313 314 315 316
      MessageBox((HWND) 0,"Debugging variable MYSQL_DEBUG used",buff,MB_OK);
    }
#endif
  }
#endif
}


/**************************************************************************
Konstantin Osipov's avatar
Konstantin Osipov committed
317
  Ignore SIGPIPE handler
unknown's avatar
unknown committed
318 319 320
   ARGSUSED
**************************************************************************/

unknown's avatar
SCRUM:  
unknown committed
321
sig_handler
322
my_pipe_sig_handler(int sig __attribute__((unused)))
unknown's avatar
unknown committed
323 324
{
  DBUG_PRINT("info",("Hit by signal %d",sig));
325
#ifdef SIGNAL_HANDLER_RESET_ON_DELIVERY
326
  (void) signal(SIGPIPE, my_pipe_sig_handler);
unknown's avatar
unknown committed
327 328 329 330
#endif
}


unknown's avatar
SCRUM  
unknown committed
331 332 333 334
/**************************************************************************
  Connect to sql server
  If host == 0 then use localhost
**************************************************************************/
335

unknown's avatar
SCRUM  
unknown committed
336 337 338 339
#ifdef USE_OLD_FUNCTIONS
MYSQL * STDCALL
mysql_connect(MYSQL *mysql,const char *host,
	      const char *user, const char *passwd)
unknown's avatar
unknown committed
340
{
unknown's avatar
SCRUM  
unknown committed
341 342
  MYSQL *res;
  mysql=mysql_init(mysql);			/* Make it thread safe */
unknown's avatar
unknown committed
343
  {
unknown's avatar
SCRUM  
unknown committed
344 345 346 347
    DBUG_ENTER("mysql_connect");
    if (!(res=mysql_real_connect(mysql,host,user,passwd,NullS,0,NullS,0)))
    {
      if (mysql->free_me)
348
	my_free(mysql);
unknown's avatar
SCRUM  
unknown committed
349
    }
350
    mysql->reconnect= 1;
unknown's avatar
SCRUM  
unknown committed
351
    DBUG_RETURN(res);
unknown's avatar
unknown committed
352
  }
unknown's avatar
unknown committed
353
}
unknown's avatar
SCRUM  
unknown committed
354
#endif
unknown's avatar
unknown committed
355

356

unknown's avatar
unknown committed
357
/**************************************************************************
unknown's avatar
unknown committed
358
  Change user and database
unknown's avatar
unknown committed
359
**************************************************************************/
360

unknown's avatar
unknown committed
361
my_bool	STDCALL mysql_change_user(MYSQL *mysql, const char *user,
unknown's avatar
unknown committed
362 363
				  const char *passwd, const char *db)
{
364
  int rc;
365
  CHARSET_INFO *saved_cs= mysql->charset;
366 367 368
  char *saved_user= mysql->user;
  char *saved_passwd= mysql->passwd;
  char *saved_db= mysql->db;
369

unknown's avatar
unknown committed
370 371
  DBUG_ENTER("mysql_change_user");

372 373 374 375 376 377 378 379 380 381
  /* Get the connection-default character set. */

  if (mysql_init_character_set(mysql))
  {
    mysql->charset= saved_cs;
    DBUG_RETURN(TRUE);
  }

  /* Use an empty string instead of NULL. */

382 383 384
  mysql->user= (char*)(user ? user : "");
  mysql->passwd= (char*)(passwd ? passwd : "");
  mysql->db= 0;
unknown's avatar
unknown committed
385

386
  rc= run_plugin_auth(mysql, 0, 0, 0, db);
387 388 389 390 391

  /*
    The server will close all statements no matter was the attempt
    to change user successful or not.
  */
392
  mysql_detach_stmt_list(&mysql->stmts, "mysql_change_user");
393 394 395
  if (rc == 0)
  {
    /* Free old connect information */
Sergei Golubchik's avatar
Sergei Golubchik committed
396 397 398
    my_free(saved_user);
    my_free(saved_passwd);
    my_free(saved_db);
399 400

    /* alloc new connect information */
401 402 403
    mysql->user= my_strdup(mysql->user, MYF(MY_WME));
    mysql->passwd= my_strdup(mysql->passwd, MYF(MY_WME));
    mysql->db= db ? my_strdup(db, MYF(MY_WME)) : 0;
404
  }
405 406 407
  else
  {
    mysql->charset= saved_cs;
408 409 410
    mysql->user= saved_user;
    mysql->passwd= saved_passwd;
    mysql->db= saved_db;
411 412
  }

413
  DBUG_RETURN(rc);
unknown's avatar
unknown committed
414 415
}

unknown's avatar
SCRUM:  
unknown committed
416 417 418 419 420
#if defined(HAVE_GETPWUID) && defined(NO_GETPWUID_DECL)
struct passwd *getpwuid(uid_t);
char* getlogin(void);
#endif

421
#if !defined(__WIN__)
unknown's avatar
SCRUM:  
unknown committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

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

451
#else /* If Windows */
unknown's avatar
SCRUM:  
unknown committed
452 453 454 455 456 457 458 459 460

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

#endif

461
my_bool handle_local_infile(MYSQL *mysql, const char *net_filename)
unknown's avatar
SCRUM:  
unknown committed
462 463 464 465
{
  my_bool result= 1;
  uint packet_length=MY_ALIGN(mysql->net.max_packet-16,IO_SIZE);
  NET *net= &mysql->net;
466 467
  int readcount;
  void *li_ptr;          /* pass state to local_infile functions */
unknown's avatar
unknown committed
468
  char *buf;		/* buffer to be filled by local_infile_read */
unknown's avatar
unknown committed
469
  struct st_mysql_options *options= &mysql->options;
470 471 472
  DBUG_ENTER("handle_local_infile");

  /* check that we've got valid callback functions */
unknown's avatar
unknown committed
473 474 475 476
  if (!(options->local_infile_init &&
	options->local_infile_read &&
	options->local_infile_end &&
	options->local_infile_error))
unknown's avatar
SCRUM:  
unknown committed
477
  {
478
    /* if any of the functions is invalid, set the default */
unknown's avatar
unknown committed
479
    mysql_set_local_infile_default(mysql);
unknown's avatar
SCRUM:  
unknown committed
480 481
  }

482
  /* copy filename into local memory and allocate read buffer */
unknown's avatar
unknown committed
483 484
  if (!(buf=my_malloc(packet_length, MYF(0))))
  {
485
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
unknown's avatar
unknown committed
486 487
    DBUG_RETURN(1);
  }
488 489

  /* initialize local infile (open file, usually) */
490 491
  if ((*options->local_infile_init)(&li_ptr, net_filename,
    options->local_infile_userdata))
unknown's avatar
SCRUM:  
unknown committed
492
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
493
    (void) my_net_write(net,(const uchar*) "",0); /* Server needs one packet */
unknown's avatar
SCRUM:  
unknown committed
494 495
    net_flush(net);
    strmov(net->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
496
    net->last_errno=
497
      (*options->local_infile_error)(li_ptr,
unknown's avatar
unknown committed
498 499
                                     net->last_error,
                                     sizeof(net->last_error)-1);
unknown's avatar
SCRUM:  
unknown committed
500 501 502
    goto err;
  }

503
  /* read blocks of data from local infile callback */
unknown's avatar
unknown committed
504 505 506
  while ((readcount =
	  (*options->local_infile_read)(li_ptr, buf,
					packet_length)) > 0)
unknown's avatar
SCRUM:  
unknown committed
507
  {
508
    if (my_net_write(net, (uchar*) buf, readcount))
unknown's avatar
SCRUM:  
unknown committed
509
    {
unknown's avatar
unknown committed
510 511
      DBUG_PRINT("error",
		 ("Lost connection to MySQL server during LOAD DATA of local file"));
512
      set_mysql_error(mysql, CR_SERVER_LOST, unknown_sqlstate);
unknown's avatar
SCRUM:  
unknown committed
513 514 515
      goto err;
    }
  }
516

unknown's avatar
SCRUM:  
unknown committed
517
  /* Send empty packet to mark end of file */
518
  if (my_net_write(net, (const uchar*) "", 0) || net_flush(net))
unknown's avatar
SCRUM:  
unknown committed
519
  {
520
    set_mysql_error(mysql, CR_SERVER_LOST, unknown_sqlstate);
unknown's avatar
SCRUM:  
unknown committed
521 522
    goto err;
  }
523

unknown's avatar
SCRUM:  
unknown committed
524 525
  if (readcount < 0)
  {
unknown's avatar
unknown committed
526
    net->last_errno=
527
      (*options->local_infile_error)(li_ptr,
unknown's avatar
unknown committed
528 529
                                     net->last_error,
                                     sizeof(net->last_error)-1);
unknown's avatar
SCRUM:  
unknown committed
530 531
    goto err;
  }
532

unknown's avatar
SCRUM:  
unknown committed
533 534 535
  result=0;					/* Ok */

err:
536
  /* free up memory allocated with _init, usually */
unknown's avatar
unknown committed
537
  (*options->local_infile_end)(li_ptr);
538
  my_free(buf);
unknown's avatar
SCRUM:  
unknown committed
539
  DBUG_RETURN(result);
540 541 542
}


unknown's avatar
unknown committed
543 544 545 546 547 548
/****************************************************************************
  Default handlers for LOAD LOCAL INFILE
****************************************************************************/

typedef struct st_default_local_infile
{
549 550
  int fd;
  int error_num;
unknown's avatar
unknown committed
551
  const char *filename;
552 553 554 555
  char error_msg[LOCAL_INFILE_ERROR_LEN];
} default_local_infile_data;


unknown's avatar
unknown committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
/*
  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
*/

574 575
static int default_local_infile_init(void **ptr, const char *filename,
             void *userdata __attribute__ ((unused)))
576 577
{
  default_local_infile_data *data;
unknown's avatar
unknown committed
578
  char tmp_name[FN_REFLEN];
579 580

  if (!(*ptr= data= ((default_local_infile_data *)
unknown's avatar
unknown committed
581 582
		     my_malloc(sizeof(default_local_infile_data),  MYF(0)))))
    return 1; /* out of memory */
583 584 585

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

unknown's avatar
unknown committed
588 589
  fn_format(tmp_name, filename, "", "", MY_UNPACK_FILENAME);
  if ((data->fd = my_open(tmp_name, O_RDONLY, MYF(0))) < 0)
590
  {
unknown's avatar
unknown committed
591
    data->error_num= my_errno;
592
    my_snprintf(data->error_msg, sizeof(data->error_msg)-1,
unknown's avatar
unknown committed
593 594
                EE(EE_FILENOTFOUND), tmp_name, data->error_num);
    return 1;
595 596 597 598 599
  }
  return 0; /* ok */
}


unknown's avatar
unknown committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
/*
  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)
616
{
unknown's avatar
unknown committed
617 618
  int count;
  default_local_infile_data*data = (default_local_infile_data *) ptr;
619

620
  if ((count= (int) my_read(data->fd, (uchar *) buf, buf_len, MYF(0))) < 0)
unknown's avatar
unknown committed
621 622 623 624 625 626 627
  {
    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;
628 629 630
}


unknown's avatar
unknown committed
631 632 633 634 635 636 637 638 639 640 641 642
/*
  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)
643
{
unknown's avatar
unknown committed
644 645
  default_local_infile_data *data= (default_local_infile_data *) ptr;
  if (data)					/* If not error on open */
646
  {
unknown's avatar
unknown committed
647 648
    if (data->fd >= 0)
      my_close(data->fd, MYF(MY_WME));
649
    my_free(ptr);
650 651 652 653
  }
}


unknown's avatar
unknown committed
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
/*
  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
669 670
default_local_infile_error(void *ptr, char *error_msg, uint error_msg_len)
{
unknown's avatar
unknown committed
671 672 673
  default_local_infile_data *data = (default_local_infile_data *) ptr;
  if (data)					/* If not error on open */
  {
674 675 676
    strmake(error_msg, data->error_msg, error_msg_len);
    return data->error_num;
  }
unknown's avatar
unknown committed
677 678 679
  /* 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;
680 681 682
}


unknown's avatar
unknown committed
683
void
684
mysql_set_local_infile_handler(MYSQL *mysql,
685 686
                               int (*local_infile_init)(void **, const char *,
                               void *),
687
                               int (*local_infile_read)(void *, char *, uint),
unknown's avatar
unknown committed
688
                               void (*local_infile_end)(void *),
689 690
                               int (*local_infile_error)(void *, char *, uint),
                               void *userdata)
691
{
unknown's avatar
unknown committed
692 693 694 695
  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;
696
  mysql->options.local_infile_userdata = userdata;
697 698 699
}


unknown's avatar
unknown committed
700
void mysql_set_local_infile_default(MYSQL *mysql)
701 702 703 704 705
{
  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
706 707 708
}


unknown's avatar
unknown committed
709
/**************************************************************************
710 711
  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
712 713 714 715 716 717 718 719
**************************************************************************/

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

unknown's avatar
SCRUM:  
unknown committed
720

unknown's avatar
unknown committed
721
/**************************************************************************
722
  Return next field of the query results
unknown's avatar
unknown committed
723 724 725 726 727 728 729 730 731 732
**************************************************************************/

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

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

/**************************************************************************
  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
750
/*************************************************************************
751 752 753
  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
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
*************************************************************************/

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

774

unknown's avatar
unknown committed
775
/*****************************************************************************
776
  List all databases
unknown's avatar
unknown committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
*****************************************************************************/

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


/*****************************************************************************
793 794
  List all tables in a database
  If wild is given then only the tables matching wild is returned
unknown's avatar
unknown committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808
*****************************************************************************/

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

809

unknown's avatar
unknown committed
810
MYSQL_FIELD *cli_list_fields(MYSQL *mysql)
unknown's avatar
SCRUM  
unknown committed
811 812 813 814 815 816
{
  MYSQL_DATA *query;
  if (!(query= cli_read_rows(mysql,(MYSQL_FIELD*) 0, 
			     protocol_41(mysql) ? 8 : 6)))
    return NULL;

unknown's avatar
unknown committed
817
  mysql->field_count= (uint) query->rows;
818
  return unpack_fields(mysql, query,&mysql->field_alloc,
unknown's avatar
unknown committed
819
		       mysql->field_count, 1, mysql->server_capabilities);
unknown's avatar
SCRUM  
unknown committed
820 821 822
}


unknown's avatar
unknown committed
823
/**************************************************************************
824 825 826 827
  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
828 829 830
**************************************************************************/

MYSQL_RES * STDCALL
unknown's avatar
SCRUM  
unknown committed
831
mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
unknown's avatar
unknown committed
832
{
unknown's avatar
SCRUM  
unknown committed
833 834
  MYSQL_RES   *result;
  MYSQL_FIELD *fields;
835
  char	     buff[258],*end;
unknown's avatar
unknown committed
836 837 838 839
  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
840
  free_old_query(mysql);
841 842
  if (simple_command(mysql, COM_FIELD_LIST, (uchar*) buff,
                     (ulong) (end-buff), 1) ||
unknown's avatar
SCRUM  
unknown committed
843
      !(fields= (*mysql->methods->list_fields)(mysql)))
unknown's avatar
unknown committed
844 845 846 847 848
    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
849

850
  result->methods= mysql->methods;
unknown's avatar
unknown committed
851 852
  result->field_alloc=mysql->field_alloc;
  mysql->fields=0;
unknown's avatar
SCRUM  
unknown committed
853 854
  result->field_count = mysql->field_count;
  result->fields= fields;
unknown's avatar
unknown committed
855 856 857 858 859 860 861 862 863
  result->eof=1;
  DBUG_RETURN(result);
}

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

MYSQL_RES * STDCALL
mysql_list_processes(MYSQL *mysql)
{
864
  MYSQL_DATA *UNINIT_VAR(fields);
unknown's avatar
unknown committed
865 866 867 868 869 870 871 872 873
  uint field_count;
  uchar *pos;
  DBUG_ENTER("mysql_list_processes");

  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
874 875
  if (!(fields = (*mysql->methods->read_rows)(mysql,(MYSQL_FIELD*) 0,
					      protocol_41(mysql) ? 7 : 5)))
unknown's avatar
unknown committed
876
    DBUG_RETURN(NULL);
877
  if (!(mysql->fields=unpack_fields(mysql, fields,&mysql->field_alloc,field_count,0,
878
				    mysql->server_capabilities)))
unknown's avatar
unknown committed
879 880 881 882 883 884
    DBUG_RETURN(0);
  mysql->status=MYSQL_STATUS_GET_RESULT;
  mysql->field_count=field_count;
  DBUG_RETURN(mysql_store_result(mysql));
}

885

886
#ifdef USE_OLD_FUNCTIONS
unknown's avatar
unknown committed
887 888 889 890 891
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
892
  DBUG_RETURN(simple_command(mysql,COM_CREATE_DB,db, (ulong) strlen(db),0));
unknown's avatar
unknown committed
893 894 895 896 897 898 899 900
}


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
901
  DBUG_RETURN(simple_command(mysql,COM_DROP_DB,db,(ulong) strlen(db),0));
unknown's avatar
unknown committed
902
}
903
#endif
unknown's avatar
unknown committed
904 905 906


int STDCALL
907
mysql_shutdown(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level)
unknown's avatar
unknown committed
908
{
909
  uchar level[1];
unknown's avatar
unknown committed
910
  DBUG_ENTER("mysql_shutdown");
unknown's avatar
unknown committed
911
  level[0]= (uchar) shutdown_level;
912
  DBUG_RETURN(simple_command(mysql, COM_SHUTDOWN, level, 1, 0));
unknown's avatar
unknown committed
913 914 915 916 917 918 919 920 921
}


int STDCALL
mysql_refresh(MYSQL *mysql,uint options)
{
  uchar bits[1];
  DBUG_ENTER("mysql_refresh");
  bits[0]= (uchar) options;
922
  DBUG_RETURN(simple_command(mysql, COM_REFRESH, bits, 1, 0));
unknown's avatar
unknown committed
923 924
}

925

unknown's avatar
unknown committed
926 927 928
int STDCALL
mysql_kill(MYSQL *mysql,ulong pid)
{
929
  uchar buff[4];
unknown's avatar
unknown committed
930 931
  DBUG_ENTER("mysql_kill");
  int4store(buff,pid);
932 933 934 935 936 937 938
  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)
{
939
  uchar buff[2];
940 941 942
  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
943 944 945 946 947 948 949 950 951 952
}


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

953

unknown's avatar
Rename:  
unknown committed
954
const char *cli_read_statistics(MYSQL *mysql)
unknown's avatar
unknown committed
955 956 957 958
{
  mysql->net.read_pos[mysql->packet_length]=0;	/* End of stat string */
  if (!mysql->net.read_pos[0])
  {
959
    set_mysql_error(mysql, CR_WRONG_HOST_INFO, unknown_sqlstate);
unknown's avatar
unknown committed
960
    return mysql->net.last_error;
unknown's avatar
unknown committed
961
  }
unknown's avatar
unknown committed
962 963 964
  return (char*) mysql->net.read_pos;
}

965

unknown's avatar
unknown committed
966 967 968 969 970
const char * STDCALL
mysql_stat(MYSQL *mysql)
{
  DBUG_ENTER("mysql_stat");
  if (simple_command(mysql,COM_STATISTICS,0,0,0))
unknown's avatar
unknown committed
971
    DBUG_RETURN(mysql->net.last_error);
unknown's avatar
Rename:  
unknown committed
972
  DBUG_RETURN((*mysql->methods->read_statistics)(mysql));
unknown's avatar
unknown committed
973 974 975 976 977 978
}


int STDCALL
mysql_ping(MYSQL *mysql)
{
979
  int res;
unknown's avatar
unknown committed
980
  DBUG_ENTER("mysql_ping");
981 982 983 984
  res= simple_command(mysql,COM_PING,0,0,0);
  if (res == CR_SERVER_LOST && mysql->reconnect)
    res= simple_command(mysql,COM_PING,0,0,0);
  DBUG_RETURN(res);
unknown's avatar
unknown committed
985 986 987
}


unknown's avatar
unknown committed
988
const char * STDCALL
unknown's avatar
unknown committed
989 990 991 992 993 994
mysql_get_server_info(MYSQL *mysql)
{
  return((char*) mysql->server_version);
}


Michael Widenius's avatar
Michael Widenius committed
995 996
my_bool STDCALL mariadb_connection(MYSQL *mysql)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
997 998
  return (strstr(mysql->server_version, "MariaDB") ||
          strstr(mysql->server_version, "-maria-"));
Michael Widenius's avatar
Michael Widenius committed
999 1000 1001 1002 1003 1004 1005 1006 1007
}

const char * STDCALL
mysql_get_server_name(MYSQL *mysql)
{
  return mariadb_connection(mysql) ? "MariaDB" : "MySQL";
}


unknown's avatar
unknown committed
1008
const char * STDCALL
unknown's avatar
unknown committed
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
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
1021
const char * STDCALL
unknown's avatar
unknown committed
1022 1023 1024 1025 1026
mysql_get_client_info(void)
{
  return (char*) MYSQL_SERVER_VERSION;
}

unknown's avatar
unknown committed
1027 1028 1029 1030 1031
ulong STDCALL mysql_get_client_version(void)
{
  return MYSQL_VERSION_ID;
}

unknown's avatar
unknown committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
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
1047
MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res)
unknown's avatar
unknown committed
1048 1049 1050 1051
{
  return res->data_cursor;
}

unknown's avatar
unknown committed
1052
MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res)
unknown's avatar
unknown committed
1053 1054 1055 1056 1057 1058 1059 1060
{
  return (res)->current_field;
}

/* MYSQL */

unsigned int STDCALL mysql_field_count(MYSQL *mysql)
{
Konstantin Osipov's avatar
Konstantin Osipov committed
1061
  return mysql->field_count;
unknown's avatar
unknown committed
1062 1063 1064 1065
}

my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql)
{
Konstantin Osipov's avatar
Konstantin Osipov committed
1066
  return mysql->affected_rows;
unknown's avatar
unknown committed
1067 1068 1069 1070
}

my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql)
{
Konstantin Osipov's avatar
Konstantin Osipov committed
1071
  return mysql->insert_id;
unknown's avatar
unknown committed
1072 1073
}

1074 1075
const char *STDCALL mysql_sqlstate(MYSQL *mysql)
{
1076
  return mysql ? mysql->net.sqlstate : cant_connect_sqlstate;
1077 1078
}

1079 1080 1081 1082 1083
uint STDCALL mysql_warning_count(MYSQL *mysql)
{
  return mysql->warning_count;
}

unknown's avatar
unknown committed
1084
const char *STDCALL mysql_info(MYSQL *mysql)
unknown's avatar
unknown committed
1085
{
1086
  return mysql->info;
unknown's avatar
unknown committed
1087 1088 1089 1090 1091 1092 1093 1094 1095
}

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

const char * STDCALL mysql_character_set_name(MYSQL *mysql)
{
unknown's avatar
unknown committed
1096
  return mysql->charset->csname;
unknown's avatar
unknown committed
1097 1098
}

1099
void STDCALL mysql_get_character_set_info(MYSQL *mysql, MY_CHARSET_INFO *csinfo)
unknown's avatar
unknown committed
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
{
  csinfo->number   = mysql->charset->number;
  csinfo->state    = mysql->charset->state;
  csinfo->csname   = mysql->charset->csname;
  csinfo->name     = mysql->charset->name;
  csinfo->comment  = mysql->charset->comment;
  csinfo->mbminlen = mysql->charset->mbminlen;
  csinfo->mbmaxlen = mysql->charset->mbmaxlen;

  if (mysql->options.charset_dir)
    csinfo->dir = mysql->options.charset_dir;
  else
    csinfo->dir = charsets_dir;
}
unknown's avatar
unknown committed
1114

unknown's avatar
unknown committed
1115 1116 1117 1118 1119
uint STDCALL mysql_thread_safe(void)
{
  return 1;
}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

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

unknown's avatar
unknown committed
1130
/****************************************************************************
1131
  Some support functions
unknown's avatar
unknown committed
1132 1133
****************************************************************************/

unknown's avatar
unknown committed
1134 1135 1136 1137 1138 1139 1140
/*
  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;
1141 1142
  my_net_set_read_timeout(net, CLIENT_NET_READ_TIMEOUT);
  my_net_set_write_timeout(net, CLIENT_NET_WRITE_TIMEOUT);
1143
  net->retry_count=  1;
1144
  net->max_packet_size= MY_MAX(net_buffer_length, max_allowed_packet);
unknown's avatar
unknown committed
1145 1146
}

unknown's avatar
unknown committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
/*
  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
1167 1168
ulong STDCALL
mysql_hex_string(char *to, const char *from, ulong length)
unknown's avatar
unknown committed
1169 1170 1171 1172 1173 1174
{
  char *to0= to;
  const char *end;
            
  for (end= from + length; from < end; from++)
  {
unknown's avatar
unknown committed
1175 1176
    *to++= _dig_vec_upper[((unsigned char) *from) >> 4];
    *to++= _dig_vec_upper[((unsigned char) *from) & 0x0F];
unknown's avatar
unknown committed
1177 1178 1179 1180 1181
  }
  *to= '\0';
  return (ulong) (to-to0);
}

unknown's avatar
unknown committed
1182
/*
1183 1184 1185
  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
1186 1187 1188 1189 1190
*/

ulong STDCALL
mysql_escape_string(char *to,const char *from,ulong length)
{
1191
  return (uint) escape_string_for_mysql(default_charset_info, to, 0, from, length);
unknown's avatar
unknown committed
1192 1193 1194 1195 1196 1197
}

ulong STDCALL
mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
			 ulong length)
{
1198
  if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
1199 1200
    return (uint) escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
  return (uint) escape_string_for_mysql(mysql->charset, to, 0, from, length);
unknown's avatar
unknown committed
1201 1202 1203 1204 1205 1206 1207 1208
}

void STDCALL
myodbc_remove_escape(MYSQL *mysql,char *name)
{
  char *to;
#ifdef USE_MB
  my_bool use_mb_flag=use_mb(mysql->charset);
1209
  char *UNINIT_VAR(end);
unknown's avatar
unknown committed
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
  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;
}
1232 1233

/********************************************************************
1234
 Implementation of new client API for 4.1 version.
1235

1236
 mysql_stmt_* are real prototypes used by applications.
1237

1238 1239 1240 1241 1242
 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.
1243 1244
*********************************************************************/

1245
/******************* Declarations ***********************************/
1246

1247
/* Default number of rows fetched per one COM_STMT_FETCH command. */
1248

unknown's avatar
unknown committed
1249
#define DEFAULT_PREFETCH_ROWS (ulong) 1
1250

1251
/*
1252 1253 1254 1255 1256
  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)
1257 1258
*/

1259 1260
static int stmt_read_row_unbuffered(MYSQL_STMT *stmt, unsigned char **row);
static int stmt_read_row_buffered(MYSQL_STMT *stmt, unsigned char **row);
1261
static int stmt_read_row_from_cursor(MYSQL_STMT *stmt, unsigned char **row);
1262
static int stmt_read_row_no_data(MYSQL_STMT *stmt, unsigned char **row);
unknown's avatar
unknown committed
1263
static int stmt_read_row_no_result_set(MYSQL_STMT *stmt, unsigned char **row);
1264

1265 1266 1267 1268 1269
/*
  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);
1270
static my_bool setup_one_fetch_function(MYSQL_BIND *, MYSQL_FIELD *field);
1271

1272 1273 1274 1275
/* Auxilary function used to reset statement handle. */

#define RESET_SERVER_SIDE 1
#define RESET_LONG_DATA 2
1276
#define RESET_STORE_RESULT 4
1277
#define RESET_CLEAR_ERROR 8
1278
#define RESET_ALL_BUFFERS 16
1279 1280 1281

static my_bool reset_stmt_handle(MYSQL_STMT *stmt, uint flags);

1282 1283 1284 1285 1286 1287
/*
  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) */
1288
#define MAX_DATE_REP_LENGTH 5
1289 1290 1291 1292 1293

/*
  1 (length) + 1 (is negative) + 4 (day count) + 1 (hour)
  + 1 (minute) + 1 (seconds) + 4 (microseconds)
*/
1294
#define MAX_TIME_REP_LENGTH 13
1295 1296 1297 1298 1299

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

1302
#define MAX_DOUBLE_STRING_REP_LENGTH 331
1303

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
/* A macro to check truncation errors */

#define IS_TRUNCATED(value, is_unsigned, min, max, umax) \
        ((is_unsigned) ? (((value) > (umax) || (value) < 0) ? 1 : 0) : \
                         (((value) > (max)  || (value) < (min)) ? 1 : 0))

#define BIND_RESULT_DONE 1
/*
  We report truncations only if at least one of MYSQL_BIND::error
  pointers is set. In this case stmt->bind_result_done |-ed with
  this flag.
*/
#define REPORT_DATA_TRUNCATION 2

1318
/**************** Misc utility functions ****************************/
1319 1320

/*
1321
  Reallocate the NET package to have at least length bytes available.
1322

1323
  SYNPOSIS
1324 1325 1326 1327
    my_realloc_str()
    net                 The NET structure to modify.
    length              Ensure that net->buff has space for at least
                        this number of bytes.
1328

1329
  RETURN VALUES
1330 1331 1332
    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.
1333 1334
*/

1335
static my_bool my_realloc_str(NET *net, ulong length)
1336
{
1337 1338 1339 1340
  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)
1341
  {
1342
    res= net_realloc(net, buf_length + length);
1343 1344
    if (res)
    {
1345 1346 1347 1348
      if (net->last_errno == ER_OUT_OF_RESOURCES)
        net->last_errno= CR_OUT_OF_MEMORY;
      else if (net->last_errno == ER_NET_PACKET_TOO_LARGE)
        net->last_errno= CR_NET_PACKET_TOO_LARGE;
1349
      strmov(net->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
1350
      strmov(net->last_error, ER(net->last_errno));
1351
    }
1352
    net->write_pos= net->buff+ buf_length;
1353
  }
1354
  DBUG_RETURN(res);
1355 1356 1357
}


1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
static void stmt_clear_error(MYSQL_STMT *stmt)
{
  if (stmt->last_errno)
  {
    stmt->last_errno= 0;
    stmt->last_error[0]= '\0';
    strmov(stmt->sqlstate, not_error_sqlstate);
  }
}

1368
/**
1369 1370 1371 1372
  Set statement error code, sqlstate, and error message
  from given errcode and sqlstate.
*/

1373 1374
void set_stmt_error(MYSQL_STMT * stmt, int errcode,
                    const char *sqlstate, const char *err)
1375 1376 1377 1378 1379
{
  DBUG_ENTER("set_stmt_error");
  DBUG_PRINT("enter", ("error: %d '%s'", errcode, ER(errcode)));
  DBUG_ASSERT(stmt != 0);

1380 1381 1382
  if (err == 0)
    err= ER(errcode);

1383 1384 1385 1386 1387 1388 1389 1390
  stmt->last_errno= errcode;
  strmov(stmt->last_error, ER(errcode));
  strmov(stmt->sqlstate, sqlstate);

  DBUG_VOID_RETURN;
}


1391 1392 1393 1394 1395
/**
  Set statement error code, sqlstate, and error message from NET.

  @param stmt  a statement handle. Copy the error here.
  @param net   mysql->net. Source of the error.
1396 1397
*/

1398
void set_stmt_errmsg(MYSQL_STMT *stmt, NET *net)
1399 1400
{
  DBUG_ENTER("set_stmt_errmsg");
1401
  DBUG_PRINT("enter", ("error: %d/%s '%s'",
unknown's avatar
unknown committed
1402
                       net->last_errno,
1403
                       net->sqlstate,
unknown's avatar
unknown committed
1404
                       net->last_error));
1405 1406
  DBUG_ASSERT(stmt != 0);

unknown's avatar
unknown committed
1407 1408 1409
  stmt->last_errno= net->last_errno;
  if (net->last_error && net->last_error[0])
    strmov(stmt->last_error, net->last_error);
1410
  strmov(stmt->sqlstate, net->sqlstate);
1411 1412 1413

  DBUG_VOID_RETURN;
}
1414

1415
/*
1416
  Read and unpack server reply to COM_STMT_PREPARE command (sent from
1417
  mysql_stmt_prepare).
1418

1419 1420 1421 1422
  SYNOPSIS
    cli_read_prepare_result()
    mysql   connection handle
    stmt    statement handle
1423 1424 1425 1426

  RETURN VALUES
    0	ok
    1	error
1427 1428
*/

unknown's avatar
unknown committed
1429
my_bool cli_read_prepare_result(MYSQL *mysql, MYSQL_STMT *stmt)
1430 1431
{
  uchar *pos;
1432 1433
  uint field_count, param_count;
  ulong packet_length;
1434
  MYSQL_DATA *fields_data;
1435
  DBUG_ENTER("cli_read_prepare_result");
1436

1437
  if ((packet_length= cli_safe_read(mysql)) == packet_error)
1438
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1439
  mysql->warning_count= 0;
1440

1441
  pos= (uchar*) mysql->net.read_pos;
1442
  stmt->stmt_id= uint4korr(pos+1); pos+= 5;
1443
  /* Number of columns in result set */
1444
  field_count=   uint2korr(pos);   pos+= 2;
1445
  /* Number of placeholders in the statement */
1446
  param_count=   uint2korr(pos);   pos+= 2;
unknown's avatar
unknown committed
1447 1448
  if (packet_length >= 12)
    mysql->warning_count= uint2korr(pos+1);
1449

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
  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);
  }

1460 1461 1462 1463
  if (field_count != 0)
  {
    if (!(mysql->server_status & SERVER_STATUS_AUTOCOMMIT))
      mysql->server_status|= SERVER_STATUS_IN_TRANS;
1464

unknown's avatar
SCRUM  
unknown committed
1465
    if (!(fields_data= (*mysql->methods->read_rows)(mysql,(MYSQL_FIELD*)0,7)))
1466
      DBUG_RETURN(1);
1467
    if (!(stmt->fields= unpack_fields(mysql, fields_data,&stmt->mem_root,
1468 1469 1470 1471
				      field_count,0,
				      mysql->server_capabilities)))
      DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
1472
  stmt->field_count=  field_count;
1473
  stmt->param_count=  (ulong) param_count;
unknown's avatar
unknown committed
1474 1475
  DBUG_PRINT("exit",("field_count: %u  param_count: %u  warning_count: %u",
                     field_count, param_count, (uint) mysql->warning_count));
unknown's avatar
SCRUM  
unknown committed
1476

1477 1478 1479 1480 1481
  DBUG_RETURN(0);
}


/*
1482 1483
  Allocate memory and init prepared statement structure.

1484 1485
  SYNOPSIS
    mysql_stmt_init()
1486 1487 1488 1489 1490 1491 1492
    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
1493
    handle provided to this call: its lifetime is limited by lifetime
1494 1495 1496 1497 1498 1499
    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
1500
    - close statement handle and free its memory (mysql_stmt_close()),
1501 1502 1503 1504 1505
    - 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).
1506

1507 1508 1509 1510 1511
  RETURN VALUE
    statement structure upon success and NULL if out of
    memory
*/

1512
#ifdef EMBEDDED_LIBRARY
1513 1514
#undef MY_THREAD_SPECIFIC
#define MY_THREAD_SPECIFIC 0
1515 1516
#endif /*EMBEDDED_LIBRARY*/

1517 1518 1519 1520 1521 1522
MYSQL_STMT * STDCALL
mysql_stmt_init(MYSQL *mysql)
{
  MYSQL_STMT *stmt;
  DBUG_ENTER("mysql_stmt_init");

1523 1524 1525 1526 1527
  if (!(stmt=
          (MYSQL_STMT *) my_malloc(sizeof (MYSQL_STMT),
                                   MYF(MY_WME | MY_ZEROFILL))) ||
      !(stmt->extension=
          (MYSQL_STMT_EXT *) my_malloc(sizeof (MYSQL_STMT_EXT),
1528 1529 1530
                                       MYF(MY_WME | MY_ZEROFILL))))
  {
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
1531 1532
    my_free(stmt);
    DBUG_RETURN(NULL);
1533 1534
  }

1535 1536
  init_alloc_root(&stmt->mem_root, 2048,2048, MYF(MY_THREAD_SPECIFIC));
  init_alloc_root(&stmt->result.alloc, 4096, 4096, MYF(MY_THREAD_SPECIFIC));
1537
  stmt->result.alloc.min_malloc= sizeof(MYSQL_ROWS);
1538 1539
  mysql->stmts= list_add(mysql->stmts, &stmt->list);
  stmt->list.data= stmt;
1540
  stmt->state= MYSQL_STMT_INIT_DONE;
1541
  stmt->mysql= mysql;
unknown's avatar
unknown committed
1542
  stmt->read_row_func= stmt_read_row_no_result_set;
1543
  stmt->prefetch_rows= DEFAULT_PREFETCH_ROWS;
1544
  strmov(stmt->sqlstate, not_error_sqlstate);
1545
  /* The rest of statement members was bzeroed inside malloc */
1546

1547 1548
  init_alloc_root(&stmt->extension->fields_mem_root, 2048, 0,
                  MYF(MY_THREAD_SPECIFIC));
1549

1550 1551 1552
  DBUG_RETURN(stmt);
}

1553

1554
/*
1555 1556
  Prepare server side statement with query.

1557 1558
  SYNOPSIS
    mysql_stmt_prepare()
1559 1560 1561
    stmt    statement handle
    query   statement to prepare
    length  statement length
1562 1563

  DESCRIPTION
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    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
1577
    structure on the server and free old statement data
1578
  - then send the query to server and get back number of placeholders,
1579
    number of columns in result set (if any), and result set metadata.
1580
    At the same time allocate memory for input and output parameters
1581
    to have less checks in mysql_stmt_bind_{param, result}.
1582

1583 1584
  RETURN VALUES
    0  success
1585
   !0  error
1586 1587
*/

1588 1589
int STDCALL
mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, ulong length)
1590
{
1591 1592 1593
  MYSQL *mysql= stmt->mysql;
  DBUG_ENTER("mysql_stmt_prepare");

1594
  if (!mysql)
1595
  {
1596
    /* mysql can be reset in mysql_close called from mysql_reconnect */
1597
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate, NULL);
1598
    DBUG_RETURN(1);
1599
  }
1600

1601 1602 1603 1604 1605 1606 1607
  /*
    Reset the last error in any case: that would clear the statement
    if the previous prepare failed.
  */
  stmt->last_errno= 0;
  stmt->last_error[0]= '\0';

1608 1609 1610
  if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
  {
    /* This is second prepare with another statement */
1611
    uchar buff[MYSQL_STMT_HEADER];               /* 4 bytes - stmt id */
1612

1613
    if (reset_stmt_handle(stmt, RESET_LONG_DATA | RESET_STORE_RESULT))
1614
      DBUG_RETURN(1);
1615
    /*
1616
      These members must be reset for API to
1617 1618 1619 1620 1621
      function in case of error or misuse.
    */
    stmt->bind_param_done= stmt->bind_result_done= FALSE;
    stmt->param_count= stmt->field_count= 0;
    free_root(&stmt->mem_root, MYF(MY_KEEP_PREALLOC));
1622
    free_root(&stmt->extension->fields_mem_root, MYF(0));
1623 1624

    int4store(buff, stmt->stmt_id);
1625

1626
    /*
1627 1628
      Close statement in server

1629 1630 1631 1632
      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.
    */
1633
    stmt->state= MYSQL_STMT_INIT_DONE;
1634
    if (stmt_command(mysql, COM_STMT_CLOSE, buff, 4, stmt))
1635
    {
1636
      set_stmt_errmsg(stmt, &mysql->net);
1637 1638 1639 1640
      DBUG_RETURN(1);
    }
  }

1641
  if (stmt_command(mysql, COM_STMT_PREPARE, (const uchar*) query, length, stmt))
1642
  {
1643
    set_stmt_errmsg(stmt, &mysql->net);
1644
    DBUG_RETURN(1);
1645 1646
  }

unknown's avatar
SCRUM  
unknown committed
1647
  if ((*mysql->methods->read_prepare_result)(mysql, stmt))
1648
  {
1649
    set_stmt_errmsg(stmt, &mysql->net);
1650
    DBUG_RETURN(1);
1651
  }
unknown's avatar
SCRUM:  
unknown committed
1652

1653
  /*
1654
    alloc_root will return valid address even in case when param_count
1655 1656 1657 1658
    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
1659 1660
  if (!(stmt->params= (MYSQL_BIND *) alloc_root(&stmt->mem_root,
						sizeof(MYSQL_BIND)*
1661
                                                (stmt->param_count +
unknown's avatar
SCRUM:  
unknown committed
1662 1663
                                                 stmt->field_count))))
  {
1664
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate, NULL);
1665
    DBUG_RETURN(1);
unknown's avatar
SCRUM:  
unknown committed
1666 1667
  }
  stmt->bind= stmt->params + stmt->param_count;
1668
  stmt->state= MYSQL_STMT_PREPARE_DONE;
unknown's avatar
unknown committed
1669
  DBUG_PRINT("info", ("Parameter count: %u", stmt->param_count));
1670
  DBUG_RETURN(0);
1671 1672
}

1673
/*
1674 1675 1676 1677
  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.
1678 1679
*/

1680
static void alloc_stmt_fields(MYSQL_STMT *stmt)
1681
{
1682
  MYSQL_FIELD *fields, *field, *end;
1683
  MEM_ROOT *fields_mem_root= &stmt->extension->fields_mem_root;
Konstantin Osipov's avatar
Konstantin Osipov committed
1684
  MYSQL *mysql= stmt->mysql;
1685

1686
  DBUG_ASSERT(stmt->field_count);
1687

1688
  free_root(fields_mem_root, MYF(0));
1689

1690
  /*
1691
    Get the field information for non-select statements
1692 1693
    like SHOW and DESCRIBE commands
  */
1694
  if (!(stmt->fields= (MYSQL_FIELD *) alloc_root(fields_mem_root,
1695
						 sizeof(MYSQL_FIELD) *
1696
						 stmt->field_count)) ||
1697
      !(stmt->bind= (MYSQL_BIND *) alloc_root(fields_mem_root,
1698 1699
					      sizeof(MYSQL_BIND) *
					      stmt->field_count)))
1700 1701 1702 1703
  {
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate, NULL);
    return;
  }
1704 1705

  for (fields= mysql->fields, end= fields+stmt->field_count,
1706
	 field= stmt->fields;
1707 1708
       field && fields < end; fields++, field++)
  {
1709
    *field= *fields; /* To copy all numeric parts. */
1710 1711
    field->catalog=   strmake_root(fields_mem_root,
                                   fields->catalog,
1712
                                   fields->catalog_length);
1713 1714 1715 1716 1717 1718 1719 1720
    field->db=        strmake_root(fields_mem_root,
                                   fields->db,
                                   fields->db_length);
    field->table=     strmake_root(fields_mem_root,
                                   fields->table,
                                   fields->table_length);
    field->org_table= strmake_root(fields_mem_root,
                                   fields->org_table,
1721
                                   fields->org_table_length);
1722 1723 1724 1725 1726
    field->name=      strmake_root(fields_mem_root,
                                   fields->name,
                                   fields->name_length);
    field->org_name=  strmake_root(fields_mem_root,
                                   fields->org_name,
1727
                                   fields->org_name_length);
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
    if (fields->def)
    {
      field->def= strmake_root(fields_mem_root,
                               fields->def,
                               fields->def_length);
      field->def_length= fields->def_length;
    }
    else
    {
      field->def= NULL;
      field->def_length= 0;
    }
1740 1741
    field->extension= 0; /* Avoid dangling links. */
    field->max_length= 0; /* max_length is set in mysql_stmt_store_result() */
1742
  }
1743
}
1744

1745

1746
/**
1747
  Update result set columns metadata if it was sent again in
1748
  reply to COM_STMT_EXECUTE.
1749 1750 1751

  @note If the new field count is different from the original one,
        an error is set and no update is performed.
1752 1753 1754 1755 1756 1757 1758
*/

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;
1759
  MYSQL_BIND *my_bind= stmt->bind_result_done ? stmt->bind : 0;
1760

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
  if (stmt->field_count != stmt->mysql->field_count)
  {
    /*
      The tables used in the statement were altered,
      and the query now returns a different number of columns.
      There is no way to continue without reallocating the bind
      array:
      - if the number of columns increased, mysql_stmt_fetch()
      will write beyond allocated memory
      - if the number of columns decreased, some user-bound
      buffers will be left unassigned without user knowing
      that.
    */
    set_stmt_error(stmt, CR_NEW_STMT_METADATA, unknown_sqlstate, NULL);
    return;
  }
1777 1778 1779 1780 1781 1782 1783 1784

  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;
1785
    if (my_bind)
1786 1787
    {
      /* Ignore return value: it should be 0 if bind_result succeeded. */
1788
      (void) setup_one_fetch_function(my_bind++, stmt_field);
1789
    }
1790 1791 1792
  }
}

1793
/*
1794 1795 1796 1797 1798 1799 1800 1801 1802
  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
1803
    mysql_stmt_field_count(): if number of fields is not zero, you can call
1804 1805 1806 1807
    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
1808
      mysql_stmt_field_count())
1809 1810 1811 1812
    - 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.
1813 1814 1815 1816 1817 1818

  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
1819 1820 1821
*/

MYSQL_RES * STDCALL
1822
mysql_stmt_result_metadata(MYSQL_STMT *stmt)
1823 1824
{
  MYSQL_RES *result;
1825
  DBUG_ENTER("mysql_stmt_result_metadata");
1826

1827 1828 1829 1830 1831 1832 1833 1834 1835
  /*
    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))))
1836
  {
1837
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate, NULL);
1838 1839
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
1840

1841 1842
  result->methods=	stmt->mysql->methods;
  result->eof=		1;                      /* Marker for buffered */
1843 1844
  result->fields=	stmt->fields;
  result->field_count=	stmt->field_count;
1845
  /* The rest of members of 'result' was bzeroed inside malloc */
1846
  DBUG_RETURN(result);
1847 1848
}

1849

1850
/*
1851 1852
  Returns parameter columns meta information in the form of
  result set.
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865

  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.
1866 1867 1868
*/

MYSQL_RES * STDCALL
1869
mysql_stmt_param_metadata(MYSQL_STMT *stmt)
1870
{
1871
  DBUG_ENTER("mysql_stmt_param_metadata");
1872

1873 1874 1875 1876
  if (!stmt->param_count)
    DBUG_RETURN(0);

  /*
1877 1878
    TODO: Fix this when server sends the information.
    Till then keep a dummy prototype.
1879 1880 1881 1882 1883
  */
  DBUG_RETURN(0); 
}


1884 1885
/* Store type of parameter in network buffer. */

1886
static void store_param_type(unsigned char **pos, MYSQL_BIND *param)
1887 1888 1889 1890 1891 1892 1893
{
  uint typecode= param->buffer_type | (param->is_unsigned ? 32768 : 0);
  int2store(*pos, typecode);
  *pos+= 2;
}


1894 1895
/*
  Functions to store parameter data in network packet.
1896

1897 1898 1899 1900 1901
  SYNOPSIS
    store_param_xxx()
    net			MySQL NET connection
    param		MySQL bind param

1902
  DESCRIPTION
1903 1904 1905 1906 1907
    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).
1908
*/
1909 1910 1911

static void store_param_tinyint(NET *net, MYSQL_BIND *param)
{
1912
  *(net->write_pos++)= *(uchar *) param->buffer;
1913 1914
}

1915 1916 1917 1918 1919 1920
static void store_param_short(NET *net, MYSQL_BIND *param)
{
  short value= *(short*) param->buffer;
  int2store(net->write_pos,value);
  net->write_pos+=2;
}
1921

1922
static void store_param_int32(NET *net, MYSQL_BIND *param)
1923
{
1924 1925 1926 1927
  int32 value= *(int32*) param->buffer;
  int4store(net->write_pos,value);
  net->write_pos+=4;
}
1928

1929 1930 1931 1932 1933 1934
static void store_param_int64(NET *net, MYSQL_BIND *param)
{
  longlong value= *(longlong*) param->buffer;
  int8store(net->write_pos,value);
  net->write_pos+= 8;
}
1935

1936 1937 1938 1939 1940
static void store_param_float(NET *net, MYSQL_BIND *param)
{
  float value= *(float*) param->buffer;
  float4store(net->write_pos, value);
  net->write_pos+= 4;
1941 1942
}

1943 1944 1945 1946 1947 1948
static void store_param_double(NET *net, MYSQL_BIND *param)
{
  double value= *(double*) param->buffer;
  float8store(net->write_pos, value);
  net->write_pos+= 8;
}
1949

unknown's avatar
unknown committed
1950 1951 1952
static void store_param_time(NET *net, MYSQL_BIND *param)
{
  MYSQL_TIME *tm= (MYSQL_TIME *) param->buffer;
1953
  char buff[MAX_TIME_REP_LENGTH], *pos;
unknown's avatar
unknown committed
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
  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)
1964
    length= 12;
unknown's avatar
unknown committed
1965 1966 1967 1968
  else if (tm->hour || tm->minute || tm->second || tm->day)
    length= 8;
  else
    length= 0;
1969
  buff[0]= (char) length++;
unknown's avatar
unknown committed
1970 1971 1972 1973 1974 1975
  memcpy((char *)net->write_pos, buff, length);
  net->write_pos+= length;
}

static void net_store_datetime(NET *net, MYSQL_TIME *tm)
{
1976
  char buff[MAX_DATETIME_REP_LENGTH], *pos;
unknown's avatar
unknown committed
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
  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;
1996
  buff[0]= (char) length++;
unknown's avatar
unknown committed
1997 1998 1999 2000 2001 2002
  memcpy((char *)net->write_pos, buff, length);
  net->write_pos+= length;
}

static void store_param_date(NET *net, MYSQL_BIND *param)
{
2003 2004 2005
  MYSQL_TIME tm= *((MYSQL_TIME *) param->buffer);
  tm.hour= tm.minute= tm.second= tm.second_part= 0;
  net_store_datetime(net, &tm);
unknown's avatar
unknown committed
2006 2007 2008 2009 2010 2011 2012
}

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

2014
static void store_param_str(NET *net, MYSQL_BIND *param)
2015
{
2016 2017
  /* param->length is always set in mysql_stmt_bind_param */
  ulong length= *param->length;
2018
  uchar *to= net_store_length(net->write_pos, length);
2019
  memcpy(to, param->buffer, length);
2020
  net->write_pos= to+length;
2021 2022
}

2023

2024
/*
2025 2026 2027 2028 2029 2030 2031 2032 2033
  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
2034 2035
    if a parameter is NULL. Unlike bit string in result set row, here
    we don't have reserved bits for OK/error packet.
2036 2037
*/

2038
static void store_param_null(NET *net, MYSQL_BIND *param)
2039
{
2040
  uint pos= param->param_number;
unknown's avatar
unknown committed
2041
  net->buff[pos/8]|=  (uchar) (1 << (pos & 7));
2042
}
2043 2044 2045


/*
2046 2047 2048
  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.
2049 2050
*/

2051
static my_bool store_param(MYSQL_STMT *stmt, MYSQL_BIND *param)
2052
{
2053
  NET *net= &stmt->mysql->net;
2054
  DBUG_ENTER("store_param");
unknown's avatar
unknown committed
2055
  DBUG_PRINT("enter",("type: %d  buffer: 0x%lx  length: %lu  is_null: %d",
unknown's avatar
unknown committed
2056
		      param->buffer_type,
unknown's avatar
unknown committed
2057 2058
		      (long) (param->buffer ? param->buffer : NullS),
                      *param->length, *param->is_null));
unknown's avatar
unknown committed
2059 2060

  if (*param->is_null)
2061 2062
    store_param_null(net, param);
  else
unknown's avatar
unknown committed
2063
  {
unknown's avatar
unknown committed
2064 2065
    /*
      Param->length should ALWAYS point to the correct length for the type
2066
      Either to the length pointer given by the user or param->buffer_length
unknown's avatar
unknown committed
2067
    */
2068
    if ((my_realloc_str(net, *param->length)))
unknown's avatar
unknown committed
2069
    {
2070
      set_stmt_errmsg(stmt, net);
unknown's avatar
unknown committed
2071
      DBUG_RETURN(1);
unknown's avatar
unknown committed
2072
    }
2073
    (*param->store_param_func)(net, param);
unknown's avatar
unknown committed
2074 2075
  }
  DBUG_RETURN(0);
2076 2077
}

unknown's avatar
unknown committed
2078

2079
/*
2080
  Auxilary function to send COM_STMT_EXECUTE packet to server and read reply.
2081
  Used from cli_stmt_execute, which is in turn used by mysql_stmt_execute.
2082 2083
*/

2084
static my_bool execute(MYSQL_STMT *stmt, char *packet, ulong length)
2085
{
2086 2087
  MYSQL *mysql= stmt->mysql;
  NET	*net= &mysql->net;
2088 2089
  uchar buff[4 /* size of stmt id */ +
             5 /* execution flags */];
2090
  my_bool res;
2091
  DBUG_ENTER("execute");
unknown's avatar
unknown committed
2092
  DBUG_DUMP("packet", (uchar *) packet, length);
2093

2094
  int4store(buff, stmt->stmt_id);		/* Send stmt id to server */
2095
  buff[4]= (char) stmt->flags;
2096
  int4store(buff+5, 1);                         /* iteration count */
2097

2098 2099
  res= MY_TEST(cli_advanced_command(mysql, COM_STMT_EXECUTE, buff, sizeof(buff),
                                    (uchar*) packet, length, 1, stmt) ||
2100 2101
            (*mysql->methods->read_query_result)(mysql));
  stmt->affected_rows= mysql->affected_rows;
2102
  stmt->server_status= mysql->server_status;
2103 2104
  stmt->insert_id= mysql->insert_id;
  if (res)
2105
  {
2106 2107 2108 2109 2110 2111
    /* 
      Don't set stmt error if stmt->mysql is NULL, as the error in this case 
      has already been set by mysql_prune_stmt_list(). 
    */
    if (stmt->mysql)
      set_stmt_errmsg(stmt, net);
2112
    DBUG_RETURN(1);
2113
  }
2114 2115
  else if (mysql->status == MYSQL_STATUS_GET_RESULT)
    stmt->mysql->status= MYSQL_STATUS_STATEMENT_GET_RESULT;
2116 2117 2118
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
2119 2120

int cli_stmt_execute(MYSQL_STMT *stmt)
2121
{
unknown's avatar
SCRUM  
unknown committed
2122
  DBUG_ENTER("cli_stmt_execute");
2123 2124 2125

  if (stmt->param_count)
  {
2126 2127
    MYSQL *mysql= stmt->mysql;
    NET        *net= &mysql->net;
2128
    MYSQL_BIND *param, *param_end;
2129
    char       *param_data;
unknown's avatar
unknown committed
2130 2131 2132
    ulong length;
    uint null_count;
    my_bool    result;
2133

2134 2135
    if (!stmt->bind_param_done)
    {
2136
      set_stmt_error(stmt, CR_PARAMS_NOT_BOUND, unknown_sqlstate, NULL);
2137 2138
      DBUG_RETURN(1);
    }
2139 2140
    if (mysql->status != MYSQL_STATUS_READY ||
        mysql->server_status & SERVER_MORE_RESULTS_EXISTS)
2141
    {
2142
      set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate, NULL);
2143 2144
      DBUG_RETURN(1);
    }
2145

2146 2147 2148 2149 2150 2151 2152 2153
    if (net->vio)
      net_clear(net, 1);          /* Sets net->write_pos */
    else
    {
      set_stmt_errmsg(stmt, net);
      DBUG_RETURN(1);             
    }

2154 2155
    /* Reserve place for null-marker bytes */
    null_count= (stmt->param_count+7) /8;
2156 2157
    if (my_realloc_str(net, null_count + 1))
    {
2158
      set_stmt_errmsg(stmt, net);
2159 2160
      DBUG_RETURN(1);
    }
2161 2162 2163 2164 2165
    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
2166 2167
    *(net->write_pos)++= (uchar) stmt->send_types_to_server;
    if (stmt->send_types_to_server)
2168
    {
2169 2170
      if (my_realloc_str(net, 2 * stmt->param_count))
      {
2171
        set_stmt_errmsg(stmt, net);
2172 2173
        DBUG_RETURN(1);
      }
2174 2175 2176 2177 2178
      /*
	Store types of parameters in first in first package
	that is sent to the server.
      */
      for (param= stmt->params;	param < param_end ; param++)
2179
        store_param_type(&net->write_pos, param);
2180 2181 2182
    }

    for (param= stmt->params; param < param_end; param++)
2183
    {
2184
      /* check if mysql_stmt_send_long_data() was used */
unknown's avatar
unknown committed
2185 2186
      if (param->long_data_used)
	param->long_data_used= 0;	/* Clear for next execute call */
2187
      else if (store_param(stmt, param))
unknown's avatar
unknown committed
2188
	DBUG_RETURN(1);
2189
    }
2190 2191
    length= (ulong) (net->write_pos - net->buff);
    /* TODO: Look into avoding the following memdup */
2192
    if (!(param_data= my_memdup(net->buff, length, MYF(0))))
2193
    {
2194
      set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate, NULL);
2195
      DBUG_RETURN(1);
2196
    }
2197
    result= execute(stmt, param_data, length);
unknown's avatar
unknown committed
2198
    stmt->send_types_to_server=0;
2199
    my_free(param_data);
2200 2201 2202
    DBUG_RETURN(result);
  }
  DBUG_RETURN((int) execute(stmt,0,0));
2203 2204
}

2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
/*
  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)
{
2219
  if (stmt->data_cursor)
2220
  {
2221 2222
    *row= (uchar *) stmt->data_cursor->data;
    stmt->data_cursor= stmt->data_cursor->next;
2223 2224 2225 2226 2227 2228 2229 2230
    return 0;
  }
  *row= 0;
  return MYSQL_NO_DATA;
}

/*
  Read one row from network: unbuffered non-cursor fetch.
2231
  If last row was read, or error occurred, erase this statement
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
  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
2243
                  stmt->last_{errno,error}; *row is not changed
2244
  MYSQL_NO_DATA - end of file was read from network;
2245
                  *row is set to NULL
2246 2247 2248 2249 2250 2251
*/

static int stmt_read_row_unbuffered(MYSQL_STMT *stmt, unsigned char **row)
{
  int rc= 1;
  MYSQL *mysql= stmt->mysql;
2252
  /*
2253 2254 2255 2256 2257
    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)
  {
2258
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate, NULL);
2259 2260
    return 1;
  }
2261
  if (mysql->status != MYSQL_STATUS_STATEMENT_GET_RESULT)
2262 2263
  {
    set_stmt_error(stmt, stmt->unbuffered_fetch_cancelled ?
unknown's avatar
unknown committed
2264
                   CR_FETCH_CANCELED : CR_COMMANDS_OUT_OF_SYNC,
2265
                   unknown_sqlstate, NULL);
2266 2267 2268 2269
    goto error;
  }
  if ((*mysql->methods->unbuffered_fetch)(mysql, (char**) row))
  {
2270
    set_stmt_errmsg(stmt, &mysql->net);
2271 2272 2273 2274 2275 2276 2277
    /*
      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;
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
    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;
}

2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317

/*
  Fetch statement row using server side cursor.

  SYNOPSIS
    stmt_read_row_from_cursor()

  RETURN VALUE
    0            success
    1            error
  MYSQL_NO_DATA  end of data
*/

static int
stmt_read_row_from_cursor(MYSQL_STMT *stmt, unsigned char **row)
{
  if (stmt->data_cursor)
    return stmt_read_row_buffered(stmt, row);
  if (stmt->server_status & SERVER_STATUS_LAST_ROW_SENT)
    stmt->server_status &= ~SERVER_STATUS_LAST_ROW_SENT;
  else
  {
    MYSQL *mysql= stmt->mysql;
    NET *net= &mysql->net;
    MYSQL_DATA *result= &stmt->result;
2318 2319
    uchar buff[4 /* statement id */ +
               4 /* number of rows to fetch */];
2320 2321 2322 2323 2324 2325

    free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
    result->data= NULL;
    result->rows= 0;
    /* Send row request to the server */
    int4store(buff, stmt->stmt_id);
2326
    int4store(buff + 4, stmt->prefetch_rows); /* number of rows to fetch */
2327
    if ((*mysql->methods->advanced_command)(mysql, COM_STMT_FETCH,
2328
                                            buff, sizeof(buff), (uchar*) 0, 0,
2329
                                            1, stmt))
2330
    {
2331 2332 2333 2334 2335 2336
      /* 
        Don't set stmt error if stmt->mysql is NULL, as the error in this case 
        has already been set by mysql_prune_stmt_list(). 
      */
      if (stmt->mysql)
        set_stmt_errmsg(stmt, net);
2337 2338
      return 1;
    }
2339
    if ((*mysql->methods->read_rows_from_cursor)(stmt))
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
      return 1;
    stmt->server_status= mysql->server_status;

    stmt->data_cursor= result->data;
    return stmt_read_row_buffered(stmt, row);
  }
  *row= 0;
  return MYSQL_NO_DATA;
}


2351 2352 2353 2354 2355 2356 2357 2358
/*
  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)))
unknown's avatar
unknown committed
2359 2360 2361 2362 2363 2364 2365
{
  return MYSQL_NO_DATA;
}

static int
stmt_read_row_no_result_set(MYSQL_STMT *stmt  __attribute__((unused)),
                      unsigned char **row  __attribute__((unused)))
2366
{
2367
  set_stmt_error(stmt, CR_NO_RESULT_SET, unknown_sqlstate, NULL);
2368
  return 1;
2369 2370
}

2371 2372 2373 2374 2375 2376 2377 2378

/*
  Get/set statement attributes

  SYNOPSIS
    mysql_stmt_attr_get()
    mysql_stmt_attr_set()

unknown's avatar
unknown committed
2379
    attr_type  statement attribute
2380 2381 2382 2383 2384 2385
    value      casted to const void * pointer to value.

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

2387 2388 2389 2390 2391 2392 2393 2394
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;
2395
  case STMT_ATTR_CURSOR_TYPE:
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
  {
    ulong cursor_type;
    cursor_type= value ? *(ulong*) value : 0UL;
    if (cursor_type > (ulong) CURSOR_TYPE_READ_ONLY)
      goto err_not_implemented;
    stmt->flags= cursor_type;
    break;
  }
  case STMT_ATTR_PREFETCH_ROWS:
  {
    ulong prefetch_rows= value ? *(ulong*) value : DEFAULT_PREFETCH_ROWS;
    if (value == 0)
      return TRUE;
    stmt->prefetch_rows= prefetch_rows;
2410
    break;
2411
  }
2412
  default:
2413
    goto err_not_implemented;
2414 2415
  }
  return FALSE;
2416
err_not_implemented:
2417
  set_stmt_error(stmt, CR_NOT_IMPLEMENTED, unknown_sqlstate, NULL);
2418
  return TRUE;
2419 2420 2421
}


2422
my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
2423 2424 2425 2426 2427
                                    enum enum_stmt_attr_type attr_type,
                                    void *value)
{
  switch (attr_type) {
  case STMT_ATTR_UPDATE_MAX_LENGTH:
2428
    *(my_bool*) value= stmt->update_max_length;
2429
    break;
2430
  case STMT_ATTR_CURSOR_TYPE:
2431
    *(ulong*) value= stmt->flags;
2432
    break;
2433 2434 2435
  case STMT_ATTR_PREFETCH_ROWS:
    *(ulong*) value= stmt->prefetch_rows;
    break;
2436
  default:
2437 2438 2439 2440 2441 2442
    return TRUE;
  }
  return FALSE;
}


2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
/**
  Update statement result set metadata from with the new field
  information sent during statement execute.

  @pre mysql->field_count is not zero

  @retval TRUE   if error: out of memory or the new
                 result set has a different number of columns
  @retval FALSE  success
*/

static void reinit_result_set_metadata(MYSQL_STMT *stmt)
{
  /* 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.
    */
2464 2465 2466

    stmt->field_count= stmt->mysql->field_count;

2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
    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_STMT_EXECUTE (even if it is not necessary), so either this or
      previous branch always works.
      TODO: send metadata only when it's really necessary and add a warning
      'Metadata changed' when it's sent twice.
2484
    */
2485 2486 2487 2488 2489
    update_stmt_fields(stmt);
  }
}


2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
static void prepare_to_fetch_result(MYSQL_STMT *stmt)
{
  if (stmt->server_status & SERVER_STATUS_CURSOR_EXISTS)
  {
    stmt->mysql->status= MYSQL_STATUS_READY;
    stmt->read_row_func= stmt_read_row_from_cursor;
  }
  else if (stmt->flags & CURSOR_TYPE_READ_ONLY)
  {
    /*
      This is a single-row result set, a result set with no rows, EXPLAIN,
      SHOW VARIABLES, or some other command which either a) bypasses the
      cursors framework in the server and writes rows directly to the
      network or b) is more efficient if all (few) result set rows are
      precached on client and server's resources are freed.
    */
    mysql_stmt_store_result(stmt);
  }
  else
  {
    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
2517
/*
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
  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
2559 2560
*/

2561
int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt)
unknown's avatar
SCRUM  
unknown committed
2562
{
2563
  MYSQL *mysql= stmt->mysql;
2564
  DBUG_ENTER("mysql_stmt_execute");
unknown's avatar
SCRUM  
unknown committed
2565

2566 2567
  if (!mysql)
  {
2568
    /* Error is already set in mysql_detatch_stmt_list */
unknown's avatar
SCRUM  
unknown committed
2569
    DBUG_RETURN(1);
2570 2571
  }

2572
  if (reset_stmt_handle(stmt, RESET_STORE_RESULT | RESET_CLEAR_ERROR))
2573
    DBUG_RETURN(1);
2574 2575
  /*
    No need to check for stmt->state: if the statement wasn't
unknown's avatar
unknown committed
2576
    prepared we'll get 'unknown statement handler' error from server.
2577 2578 2579 2580
  */
  if (mysql->methods->stmt_execute(stmt))
    DBUG_RETURN(1);
  stmt->state= MYSQL_STMT_EXECUTE_DONE;
2581
  if (mysql->field_count)
2582
  {
2583
    reinit_result_set_metadata(stmt);
2584
    prepare_to_fetch_result(stmt);
2585
  }
2586
  DBUG_RETURN(MY_TEST(stmt->last_errno));
unknown's avatar
SCRUM  
unknown committed
2587 2588
}

2589

2590 2591 2592 2593
/*
  Return total parameters count in the statement
*/

2594
ulong STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt)
2595
{
2596
  DBUG_ENTER("mysql_stmt_param_count");
2597 2598 2599
  DBUG_RETURN(stmt->param_count);
}

2600 2601 2602 2603 2604 2605
/*
  Return total affected rows from the last statement
*/

my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt)
{
2606
  return stmt->affected_rows;
2607
}
2608

unknown's avatar
unknown committed
2609

unknown's avatar
unknown committed
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
/*
  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;
}

2620
/*
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
  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.
2634 2635 2636 2637 2638 2639 2640
*/

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

2641

unknown's avatar
unknown committed
2642 2643 2644
static my_bool int_is_null_true= 1;		/* Used for MYSQL_TYPE_NULL */
static my_bool int_is_null_false= 0;

2645

2646
/*
2647
  Set up input data buffers for a statement.
2648 2649 2650 2651 2652

  SYNOPSIS
    mysql_stmt_bind_param()
    stmt    statement handle
            The statement must be prepared with mysql_stmt_prepare().
2653
    my_bind Array of mysql_stmt_param_count() bind parameters.
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
            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
2669
    bind structure before setting its members. This will both shorten
2670 2671
    your application code and make it robust to future extensions of
    MYSQL_BIND structure.
2672
    Then you need to assign typecode of your application buffer to
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 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
    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:

2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
    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.
2788 2789 2790 2791 2792

    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
2793
    data in pieces, examples in tests/mysql_client_test.c.
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
    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
2804 2805
    to call this routine after each assignment to bind buffers, you
    need to call it each time you change parameter typecodes, or other
2806 2807 2808
    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.
2809 2810 2811 2812

  RETURN
    0  success
    1  error, can be retrieved with mysql_stmt_error.
2813 2814
*/

2815
my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *my_bind)
2816
{
2817 2818
  uint count=0;
  MYSQL_BIND *param, *end;
2819
  DBUG_ENTER("mysql_stmt_bind_param");
2820

2821 2822 2823 2824
  if (!stmt->param_count)
  {
    if ((int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE)
    {
2825
      set_stmt_error(stmt, CR_NO_PREPARE_STMT, unknown_sqlstate, NULL);
2826 2827 2828 2829 2830
      DBUG_RETURN(1);
    }
    DBUG_RETURN(0);
  }

2831
  /* Allocated on prepare */
2832
  memcpy((char*) stmt->params, (char*) my_bind,
2833 2834 2835 2836 2837
	 sizeof(MYSQL_BIND) * stmt->param_count);

  for (param= stmt->params, end= param+stmt->param_count;
       param < end ;
       param++)
2838
  {
2839
    param->param_number= count++;
2840 2841
    param->long_data_used= 0;

unknown's avatar
unknown committed
2842 2843 2844 2845
    /* 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;

2846 2847
    /* Setup data copy functions for the different supported types */
    switch (param->buffer_type) {
unknown's avatar
unknown committed
2848
    case MYSQL_TYPE_NULL:
unknown's avatar
unknown committed
2849
      param->is_null= &int_is_null_true;
unknown's avatar
unknown committed
2850
      break;
2851
    case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
2852
      /* Force param->length as this is fixed for this type */
2853 2854
      param->length= &param->buffer_length;
      param->buffer_length= 1;
2855 2856 2857
      param->store_param_func= store_param_tinyint;
      break;
    case MYSQL_TYPE_SHORT:
2858 2859
      param->length= &param->buffer_length;
      param->buffer_length= 2;
2860 2861 2862
      param->store_param_func= store_param_short;
      break;
    case MYSQL_TYPE_LONG:
2863 2864
      param->length= &param->buffer_length;
      param->buffer_length= 4;
2865 2866 2867
      param->store_param_func= store_param_int32;
      break;
    case MYSQL_TYPE_LONGLONG:
2868 2869
      param->length= &param->buffer_length;
      param->buffer_length= 8;
2870 2871 2872
      param->store_param_func= store_param_int64;
      break;
    case MYSQL_TYPE_FLOAT:
2873 2874
      param->length= &param->buffer_length;
      param->buffer_length= 4;
2875 2876 2877
      param->store_param_func= store_param_float;
      break;
    case MYSQL_TYPE_DOUBLE:
2878 2879
      param->length= &param->buffer_length;
      param->buffer_length= 8;
2880 2881
      param->store_param_func= store_param_double;
      break;
unknown's avatar
unknown committed
2882 2883
    case MYSQL_TYPE_TIME:
      param->store_param_func= store_param_time;
2884
      param->buffer_length= MAX_TIME_REP_LENGTH;
unknown's avatar
unknown committed
2885 2886 2887
      break;
    case MYSQL_TYPE_DATE:
      param->store_param_func= store_param_date;
2888
      param->buffer_length= MAX_DATE_REP_LENGTH;
unknown's avatar
unknown committed
2889 2890 2891 2892
      break;
    case MYSQL_TYPE_DATETIME:
    case MYSQL_TYPE_TIMESTAMP:
      param->store_param_func= store_param_datetime;
2893
      param->buffer_length= MAX_DATETIME_REP_LENGTH;
unknown's avatar
unknown committed
2894
      break;
2895 2896 2897
    case MYSQL_TYPE_TINY_BLOB:
    case MYSQL_TYPE_MEDIUM_BLOB:
    case MYSQL_TYPE_LONG_BLOB:
unknown's avatar
unknown committed
2898
    case MYSQL_TYPE_BLOB:
2899
    case MYSQL_TYPE_VARCHAR:
2900 2901
    case MYSQL_TYPE_VAR_STRING:
    case MYSQL_TYPE_STRING:
unknown's avatar
unknown committed
2902 2903
    case MYSQL_TYPE_DECIMAL:
    case MYSQL_TYPE_NEWDECIMAL:
2904
      param->store_param_func= store_param_str;
2905
      /*
2906 2907
        For variable length types user must set either length or
        buffer_length.
2908
      */
2909 2910
      break;
    default:
2911
      strmov(stmt->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
2912 2913
      sprintf(stmt->last_error,
	      ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
2914
	      param->buffer_type, count);
2915
      DBUG_RETURN(1);
2916
    }
2917 2918 2919 2920 2921 2922
    /*
      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;
2923
  }
2924
  /* We have to send/resend type information to MySQL */
2925 2926
  stmt->send_types_to_server= TRUE;
  stmt->bind_param_done= TRUE;
2927 2928 2929
  DBUG_RETURN(0);
}

2930

2931 2932 2933 2934 2935
/********************************************************************
 Long data implementation
*********************************************************************/

/*
2936 2937 2938
  Send long data in pieces to the server

  SYNOPSIS
2939
    mysql_stmt_send_long_data()
2940 2941 2942 2943
    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
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
  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.

2969
  RETURN VALUES
unknown's avatar
unknown committed
2970 2971
    0	ok
    1	error
2972 2973
*/

2974
my_bool STDCALL
2975
mysql_stmt_send_long_data(MYSQL_STMT *stmt, uint param_number,
unknown's avatar
unknown committed
2976
		     const char *data, ulong length)
2977 2978
{
  MYSQL_BIND *param;
2979
  DBUG_ENTER("mysql_stmt_send_long_data");
2980
  DBUG_ASSERT(stmt != 0);
unknown's avatar
unknown committed
2981 2982
  DBUG_PRINT("enter",("param no: %d  data: 0x%lx, length : %ld",
		      param_number, (long) data, length));
2983

2984 2985 2986 2987 2988 2989
  /*
    We only need to check for stmt->param_count, if it's not null
    prepare was done.
  */
  if (param_number >= stmt->param_count)
  {
2990
    set_stmt_error(stmt, CR_INVALID_PARAMETER_NO, unknown_sqlstate, NULL);
2991 2992
    DBUG_RETURN(1);
  }
2993

2994
  param= stmt->params+param_number;
2995
  if (!IS_LONGDATA(param->buffer_type))
unknown's avatar
unknown committed
2996
  {
2997
    /* Long data handling should be used only for string/binary types */
2998
    strmov(stmt->sqlstate, unknown_sqlstate);
unknown's avatar
unknown committed
2999 3000 3001 3002
    sprintf(stmt->last_error, ER(stmt->last_errno= CR_INVALID_BUFFER_USE),
	    param->param_number);
    DBUG_RETURN(1);
  }
3003

3004
  /*
3005 3006 3007
    Send long data packet if there is data or we're sending long data
    for the first time.
  */
3008
  if (length || param->long_data_used == 0)
3009
  {
3010
    MYSQL *mysql= stmt->mysql;
3011
    /* Packet header: stmt id (4 bytes), param no (2 bytes) */
3012
    uchar buff[MYSQL_LONG_DATA_HEADER];
3013

3014 3015
    int4store(buff, stmt->stmt_id);
    int2store(buff + 4, param_number);
3016 3017
    param->long_data_used= 1;

3018 3019 3020 3021
    /*
      Note that we don't get any ok packet from the server in this case
      This is intentional to save bandwidth.
    */
3022
    if ((*mysql->methods->advanced_command)(mysql, COM_STMT_SEND_LONG_DATA,
3023
                                            buff, sizeof(buff), (uchar*) data,
3024
                                            length, 1, stmt))
3025
    {
3026 3027 3028 3029 3030 3031
      /* 
        Don't set stmt error if stmt->mysql is NULL, as the error in this case 
        has already been set by mysql_prune_stmt_list(). 
      */
      if (stmt->mysql)
        set_stmt_errmsg(stmt, &mysql->net);
3032 3033 3034 3035 3036 3037
      DBUG_RETURN(1);
    }
  }
  DBUG_RETURN(0);
}

3038

3039
/********************************************************************
3040
 Fetch and conversion of result set rows (binary protocol).
3041 3042
*********************************************************************/

3043 3044 3045 3046 3047 3048 3049 3050
/*
  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
3051 3052
          These functions increase pos to point to the beginning of the
          next column.
3053 3054 3055 3056 3057 3058

  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
3059
static void read_binary_time(MYSQL_TIME *tm, uchar **pos)
unknown's avatar
unknown committed
3060
{
3061
  /* net_field_length will set pos to the first byte of data */
unknown's avatar
unknown committed
3062 3063 3064
  uint length= net_field_length(pos);

  if (length)
unknown's avatar
unknown committed
3065 3066
  {
    uchar *to= *pos;
3067
    tm->neg=    to[0];
unknown's avatar
unknown committed
3068

unknown's avatar
unknown committed
3069 3070 3071 3072 3073 3074
    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;
3075 3076 3077 3078 3079 3080
    if (tm->day)
    {
      /* Convert days to hours at once */
      tm->hour+= tm->day*24;
      tm->day= 0;
    }
3081 3082
    tm->time_type= MYSQL_TIMESTAMP_TIME;

unknown's avatar
unknown committed
3083
    *pos+= length;
unknown's avatar
unknown committed
3084
  }
unknown's avatar
unknown committed
3085
  else
3086
    set_zero_time(tm, MYSQL_TIMESTAMP_TIME);
unknown's avatar
unknown committed
3087 3088
}

unknown's avatar
unknown committed
3089
static void read_binary_datetime(MYSQL_TIME *tm, uchar **pos)
unknown's avatar
unknown committed
3090
{
unknown's avatar
unknown committed
3091
  uint length= net_field_length(pos);
3092

unknown's avatar
unknown committed
3093
  if (length)
unknown's avatar
unknown committed
3094 3095
  {
    uchar *to= *pos;
3096

unknown's avatar
unknown committed
3097 3098 3099 3100
    tm->neg=    0;
    tm->year=   (uint) sint2korr(to);
    tm->month=  (uint) to[2];
    tm->day=    (uint) to[3];
3101

unknown's avatar
unknown committed
3102 3103 3104 3105 3106 3107 3108 3109 3110
    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;
3111
    tm->time_type= MYSQL_TIMESTAMP_DATETIME;
unknown's avatar
unknown committed
3112 3113

    *pos+= length;
unknown's avatar
unknown committed
3114
  }
unknown's avatar
unknown committed
3115
  else
3116
    set_zero_time(tm, MYSQL_TIMESTAMP_DATETIME);
unknown's avatar
unknown committed
3117 3118
}

unknown's avatar
unknown committed
3119
static void read_binary_date(MYSQL_TIME *tm, uchar **pos)
unknown's avatar
unknown committed
3120
{
unknown's avatar
unknown committed
3121
  uint length= net_field_length(pos);
3122

unknown's avatar
unknown committed
3123
  if (length)
unknown's avatar
unknown committed
3124 3125 3126 3127 3128
  {
    uchar *to= *pos;
    tm->year =  (uint) sint2korr(to);
    tm->month=  (uint) to[2];
    tm->day= (uint) to[3];
unknown's avatar
unknown committed
3129

unknown's avatar
unknown committed
3130 3131 3132
    tm->hour= tm->minute= tm->second= 0;
    tm->second_part= 0;
    tm->neg= 0;
3133
    tm->time_type= MYSQL_TIMESTAMP_DATE;
unknown's avatar
unknown committed
3134 3135

    *pos+= length;
unknown's avatar
unknown committed
3136
  }
unknown's avatar
unknown committed
3137
  else
3138
    set_zero_time(tm, MYSQL_TIMESTAMP_DATE);
3139 3140
}

3141

unknown's avatar
unknown committed
3142 3143 3144 3145 3146 3147 3148 3149 3150
/*
  Convert string to supplied buffer of any type.

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

unknown's avatar
unknown committed
3152 3153
static void fetch_string_with_conversion(MYSQL_BIND *param, char *value,
                                         uint length)
3154
{
3155
  char *buffer= (char *)param->buffer;
unknown's avatar
unknown committed
3156
  int err= 0;
3157
  char *endptr= value + length;
3158

unknown's avatar
unknown committed
3159 3160 3161 3162
  /*
    This function should support all target buffer types: the rest
    of conversion functions can delegate conversion to it.
  */
3163
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3164 3165
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3166
  case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
3167
  {
3168
    longlong data= my_strtoll10(value, &endptr, &err);
3169
    *param->error= (IS_TRUNCATED(data, param->is_unsigned,
3170
                                 INT_MIN8, INT_MAX8, UINT_MAX8) || err > 0);
3171
    *buffer= (uchar) data;
3172
    break;
unknown's avatar
unknown committed
3173
  }
3174
  case MYSQL_TYPE_SHORT:
unknown's avatar
unknown committed
3175
  {
3176
    longlong data= my_strtoll10(value, &endptr, &err);
3177
    *param->error= (IS_TRUNCATED(data, param->is_unsigned,
3178
                                 INT_MIN16, INT_MAX16, UINT_MAX16) || err > 0);
3179
    shortstore(buffer, (short) data);
3180
    break;
unknown's avatar
unknown committed
3181
  }
3182
  case MYSQL_TYPE_LONG:
unknown's avatar
unknown committed
3183
  {
3184
    longlong data= my_strtoll10(value, &endptr, &err);
3185
    *param->error= (IS_TRUNCATED(data, param->is_unsigned,
3186
                                 INT_MIN32, INT_MAX32, UINT_MAX32) || err > 0);
3187
    longstore(buffer, (int32) data);
3188
    break;
unknown's avatar
unknown committed
3189
  }
3190
  case MYSQL_TYPE_LONGLONG:
unknown's avatar
unknown committed
3191
  {
3192 3193 3194
    longlong data= my_strtoll10(value, &endptr, &err);
    *param->error= param->is_unsigned ? err != 0 :
                                       (err > 0 || (err == 0 && data < 0));
unknown's avatar
unknown committed
3195
    longlongstore(buffer, data);
3196
    break;
unknown's avatar
unknown committed
3197
  }
3198
  case MYSQL_TYPE_FLOAT:
3199
  {
3200 3201
    double data= my_strntod(&my_charset_latin1, value, length, &endptr, &err);
    float fdata= (float) data;
3202
    *param->error= (fdata != data) | MY_TEST(err);
3203
    floatstore(buffer, fdata);
3204 3205
    break;
  }
3206
  case MYSQL_TYPE_DOUBLE:
3207
  {
3208
    double data= my_strntod(&my_charset_latin1, value, length, &endptr, &err);
3209
    *param->error= MY_TEST(err);
3210
    doublestore(buffer, data);
3211 3212
    break;
  }
unknown's avatar
unknown committed
3213 3214 3215
  case MYSQL_TYPE_TIME:
  {
    MYSQL_TIME *tm= (MYSQL_TIME *)buffer;
Sergei Golubchik's avatar
Sergei Golubchik committed
3216 3217 3218
    MYSQL_TIME_STATUS status;
    str_to_time(value, length, tm, 0, &status);
    err= status.warnings;
3219
    *param->error= MY_TEST(err);
unknown's avatar
unknown committed
3220 3221 3222 3223
    break;
  }
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_DATETIME:
3224
  case MYSQL_TYPE_TIMESTAMP:
unknown's avatar
unknown committed
3225 3226
  {
    MYSQL_TIME *tm= (MYSQL_TIME *)buffer;
Sergei Golubchik's avatar
Sergei Golubchik committed
3227 3228 3229
    MYSQL_TIME_STATUS status;
    (void) str_to_datetime(value, length, tm, 0, &status);
    err= status.warnings;
3230 3231
    *param->error= MY_TEST(err) && (param->buffer_type == MYSQL_TYPE_DATE &&
                                    tm->time_type != MYSQL_TIMESTAMP_DATE);
unknown's avatar
unknown committed
3232 3233 3234 3235 3236 3237
    break;
  }
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
unknown's avatar
unknown committed
3238 3239
  case MYSQL_TYPE_DECIMAL:
  case MYSQL_TYPE_NEWDECIMAL:
3240
  default:
3241
  {
unknown's avatar
unknown committed
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
    /*
      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)
3254
        memcpy(buffer, start, MY_MIN(copy_length, param->buffer_length));
unknown's avatar
unknown committed
3255
    }
unknown's avatar
unknown committed
3256
    else
unknown's avatar
unknown committed
3257 3258 3259
      copy_length= 0;
    if (copy_length < param->buffer_length)
      buffer[copy_length]= '\0';
3260
    *param->error= copy_length > param->buffer_length;
unknown's avatar
unknown committed
3261 3262 3263 3264
    /*
      param->length will always contain length of entire column;
      number of copied bytes may be way different:
    */
3265
    *param->length= length;
unknown's avatar
unknown committed
3266
    break;
3267
  }
3268
  }
3269 3270
}

3271

unknown's avatar
unknown committed
3272 3273
/*
  Convert integer value to client buffer of any type.
3274

unknown's avatar
unknown committed
3275 3276 3277 3278 3279 3280
  SYNOPSIS
    fetch_long_with_conversion()
    param   output buffer descriptor
    field   column metadata
    value   column data
*/
3281

unknown's avatar
unknown committed
3282
static void fetch_long_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
3283
                                       longlong value, my_bool is_unsigned)
3284
{
3285
  char *buffer= (char *)param->buffer;
3286

unknown's avatar
unknown committed
3287
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3288 3289
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3290
  case MYSQL_TYPE_TINY:
3291
    *param->error= IS_TRUNCATED(value, param->is_unsigned,
3292
                                INT_MIN8, INT_MAX8, UINT_MAX8);
unknown's avatar
unknown committed
3293
    *(uchar *)param->buffer= (uchar) value;
3294 3295
    break;
  case MYSQL_TYPE_SHORT:
3296
    *param->error= IS_TRUNCATED(value, param->is_unsigned,
3297
                                INT_MIN16, INT_MAX16, UINT_MAX16);
3298
    shortstore(buffer, (short) value);
3299 3300
    break;
  case MYSQL_TYPE_LONG:
3301
    *param->error= IS_TRUNCATED(value, param->is_unsigned,
3302
                                INT_MIN32, INT_MAX32, UINT_MAX32);
3303
    longstore(buffer, (int32) value);
3304 3305
    break;
  case MYSQL_TYPE_LONGLONG:
unknown's avatar
unknown committed
3306
    longlongstore(buffer, value);
3307
    *param->error= param->is_unsigned != is_unsigned && value < 0;
3308 3309
    break;
  case MYSQL_TYPE_FLOAT:
unknown's avatar
unknown committed
3310
  {
3311
    /*
3312
      We need to mark the local variable volatile to
3313 3314 3315
      workaround Intel FPU executive precision feature.
      (See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 for details)
    */
3316
    volatile float data;
3317
    if (is_unsigned)
3318
    {
3319
      data= (float) ulonglong2double(value);
3320 3321
      *param->error= ((ulonglong) value) != ((ulonglong) data);
    }
3322
    else
3323 3324 3325 3326
    {
      data= (float)value;
      *param->error= value != ((longlong) data);
    }
3327
    floatstore(buffer, data);
unknown's avatar
unknown committed
3328 3329
    break;
  }
3330
  case MYSQL_TYPE_DOUBLE:
unknown's avatar
unknown committed
3331
  {
3332
    volatile double data;
3333
    if (is_unsigned)
3334
    {
3335
      data= ulonglong2double(value);
3336 3337
      *param->error= ((ulonglong) value) != ((ulonglong) data);
    }
3338
    else
3339
    {
3340
      data= (double)value;
3341 3342
      *param->error= value != ((longlong) data);
    }
unknown's avatar
unknown committed
3343
    doublestore(buffer, data);
unknown's avatar
unknown committed
3344 3345
    break;
  }
3346 3347 3348 3349 3350 3351
  case MYSQL_TYPE_TIME:
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_TIMESTAMP:
  case MYSQL_TYPE_DATETIME:
  {
    int error;
3352
    value= number_to_datetime(value, 0, (MYSQL_TIME *) buffer, 0, &error);
3353
    *param->error= MY_TEST(error);
3354 3355
    break;
  }
3356
  default:
unknown's avatar
unknown committed
3357
  {
3358 3359 3360
    uchar buff[22];                              /* Enough for longlong */
    uchar *end= (uchar*) longlong10_to_str(value, (char*) buff,
                                           is_unsigned ? 10: -10);
unknown's avatar
unknown committed
3361
    /* Resort to string conversion which supports all typecodes */
3362 3363 3364 3365 3366
    uint length= (uint) (end-buff);

    if (field->flags & ZEROFILL_FLAG && length < field->length &&
        field->length < 21)
    {
3367 3368
      bmove_upp(buff+field->length,buff+length, length);
      bfill(buff, field->length - length,'0');
3369 3370
      length= field->length;
    }
3371
    fetch_string_with_conversion(param, (char*) buff, length);
unknown's avatar
unknown committed
3372
    break;
unknown's avatar
unknown committed
3373
  }
3374
  }
3375 3376
}

unknown's avatar
unknown committed
3377 3378 3379 3380 3381 3382 3383 3384
/*
  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
3385 3386 3387
    type    either MY_GCVT_ARG_FLOAT or MY_GCVT_ARG_DOUBLE.
            Affects the maximum number of significant digits
            returned by my_gcvt().
unknown's avatar
unknown committed
3388
*/
unknown's avatar
unknown committed
3389

unknown's avatar
unknown committed
3390
static void fetch_float_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
3391
                                        double value, my_gcvt_arg_type type)
3392
{
3393
  char *buffer= (char *)param->buffer;
3394
  double val64 = (value < 0 ? -floor(-value) : floor(value));
3395

unknown's avatar
unknown committed
3396
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3397 3398
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3399
  case MYSQL_TYPE_TINY:
3400 3401 3402 3403 3404 3405
    /*
      We need to _store_ data in the buffer before the truncation check to
      workaround Intel FPU executive precision feature.
      (See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 for details)
      Sic: AFAIU it does not guarantee to work.
    */
3406
    if (param->is_unsigned)
3407
      *buffer= (uint8) value;
3408
    else
3409
      *buffer= (int8) value;
3410 3411
    *param->error= val64 != (param->is_unsigned ? (double)((uint8) *buffer) :
                                                  (double)((int8) *buffer));
3412 3413
    break;
  case MYSQL_TYPE_SHORT:
3414 3415 3416 3417 3418 3419 3420 3421 3422 3423
    if (param->is_unsigned)
    {
      ushort data= (ushort) value;
      shortstore(buffer, data);
    }
    else
    {
      short data= (short) value;
      shortstore(buffer, data);
    }
3424
    *param->error= val64 != (param->is_unsigned ? (double) (*(ushort*) buffer):
3425
                                                  (double) (*(short*) buffer));
3426 3427
    break;
  case MYSQL_TYPE_LONG:
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
    if (param->is_unsigned)
    {
      uint32 data= (uint32) value;
      longstore(buffer, data);
    }
    else
    {
      int32 data= (int32) value;
      longstore(buffer, data);
    }
3438
    *param->error= val64 != (param->is_unsigned ? (double) (*(uint32*) buffer):
3439 3440
                                                  (double) (*(int32*) buffer));
      break;
3441
  case MYSQL_TYPE_LONGLONG:
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
    if (param->is_unsigned)
    {
      ulonglong data= (ulonglong) value;
      longlongstore(buffer, data);
    }
    else
    {
      longlong data= (longlong) value;
      longlongstore(buffer, data);
    }
3452
    *param->error= val64 != (param->is_unsigned ?
unknown's avatar
unknown committed
3453
                             ulonglong2double(*(ulonglong*) buffer) :
3454
                             (double) (*(longlong*) buffer));
3455 3456 3457
    break;
  case MYSQL_TYPE_FLOAT:
  {
unknown's avatar
unknown committed
3458
    float data= (float) value;
3459
    floatstore(buffer, data);
3460
    *param->error= (*(float*) buffer) != value;
3461 3462 3463 3464
    break;
  }
  case MYSQL_TYPE_DOUBLE:
  {
unknown's avatar
unknown committed
3465
    doublestore(buffer, value);
3466 3467
    break;
  }
3468
  default:
3469
  {
unknown's avatar
unknown committed
3470 3471 3472 3473 3474
    /*
      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
    */
3475 3476
    char buff[FLOATING_POINT_BUFFER];
    size_t len;
unknown's avatar
unknown committed
3477
    if (field->decimals >= NOT_FIXED_DEC)
3478
      len= my_gcvt(value, type,
3479
                   (int) MY_MIN(sizeof(buff)-1, param->buffer_length),
3480
                   buff, NULL);
unknown's avatar
unknown committed
3481
    else
3482
      len= my_fcvt(value, (int) field->decimals, buff, NULL);
3483

3484 3485
    if (field->flags & ZEROFILL_FLAG && len < field->length &&
        field->length < MAX_DOUBLE_STRING_REP_LENGTH - 1)
3486
    {
3487 3488 3489 3490
      bmove_upp((uchar*) buff + field->length, (uchar*) buff + len,
                len);
      bfill((char*) buff, field->length - len, '0');
      len= field->length;
3491
    }
3492
    fetch_string_with_conversion(param, buff, len);
3493

3494 3495
    break;
  }
unknown's avatar
unknown committed
3496
  }
3497 3498
}

unknown's avatar
unknown committed
3499

unknown's avatar
unknown committed
3500 3501 3502 3503 3504 3505 3506 3507 3508
/*
  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,
3509
                                           MYSQL_FIELD *field,
3510
                                           MYSQL_TIME *my_time)
unknown's avatar
unknown committed
3511 3512
{
  switch (param->buffer_type) {
unknown's avatar
unknown committed
3513 3514
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
unknown's avatar
unknown committed
3515
  case MYSQL_TYPE_DATE:
3516 3517
    *(MYSQL_TIME *)(param->buffer)= *my_time;
    *param->error= my_time->time_type != MYSQL_TIMESTAMP_DATE;
3518
    break;
unknown's avatar
unknown committed
3519
  case MYSQL_TYPE_TIME:
3520 3521
    *(MYSQL_TIME *)(param->buffer)= *my_time;
    *param->error= my_time->time_type != MYSQL_TIMESTAMP_TIME;
3522
    break;
unknown's avatar
unknown committed
3523 3524
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
3525
    *(MYSQL_TIME *)(param->buffer)= *my_time;
3526
    /* No error: time and date are compatible with datetime */
3527
    break;
3528
  case MYSQL_TYPE_YEAR:
3529
    shortstore(param->buffer, my_time->year);
3530 3531 3532 3533 3534
    *param->error= 1;
    break;
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
  {
3535
    ulonglong value= TIME_to_ulonglong(my_time);
3536
    fetch_float_with_conversion(param, field,
3537
                                ulonglong2double(value), MY_GCVT_ARG_DOUBLE);
3538
    break;
3539 3540 3541 3542 3543 3544 3545
  }
  case MYSQL_TYPE_TINY:
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_LONGLONG:
  {
3546
    longlong value= (longlong) TIME_to_ulonglong(my_time);
3547
    fetch_long_with_conversion(param, field, value, TRUE);
3548
    break;
3549
  }
unknown's avatar
unknown committed
3550 3551
  default:
  {
unknown's avatar
unknown committed
3552 3553 3554 3555
    /*
      Convert time value  to string and delegate the rest to
      fetch_string_with_conversion:
    */
3556
    char buff[MAX_DATE_STRING_REP_LENGTH];
3557
    uint length= my_TIME_to_str(my_time, buff, field->decimals);
unknown's avatar
unknown committed
3558 3559 3560
    /* Resort to string conversion */
    fetch_string_with_conversion(param, (char *)buff, length);
    break;
unknown's avatar
unknown committed
3561 3562 3563
  }
  }
}
3564

unknown's avatar
unknown committed
3565

unknown's avatar
unknown committed
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580
/*
  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.
*/
3581

unknown's avatar
unknown committed
3582 3583
static void fetch_result_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
                                         uchar **row)
3584
{
unknown's avatar
unknown committed
3585
  enum enum_field_types field_type= field->type;
unknown's avatar
unknown committed
3586
  uint field_is_unsigned= field->flags & UNSIGNED_FLAG;
unknown's avatar
unknown committed
3587

3588 3589 3590
  switch (field_type) {
  case MYSQL_TYPE_TINY:
  {
3591 3592 3593 3594
    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;
3595
    fetch_long_with_conversion(param, field, data, 0);
unknown's avatar
unknown committed
3596
    *row+= 1;
3597 3598 3599 3600 3601
    break;
  }
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_YEAR:
  {
3602
    short value= sint2korr(*row);
unknown's avatar
unknown committed
3603 3604
    longlong data= field_is_unsigned ? (longlong) (unsigned short) value :
                                       (longlong) value;
3605
    fetch_long_with_conversion(param, field, data, 0);
unknown's avatar
unknown committed
3606
    *row+= 2;
3607 3608
    break;
  }
3609
  case MYSQL_TYPE_INT24: /* mediumint is sent as 4 bytes int */
3610 3611
  case MYSQL_TYPE_LONG:
  {
3612 3613
    int32 value= sint4korr(*row);
    longlong data= field_is_unsigned ? (longlong) (uint32) value :
unknown's avatar
unknown committed
3614
                                       (longlong) value;
3615
    fetch_long_with_conversion(param, field, data, 0);
unknown's avatar
unknown committed
3616
    *row+= 4;
3617 3618 3619 3620 3621
    break;
  }
  case MYSQL_TYPE_LONGLONG:
  {
    longlong value= (longlong)sint8korr(*row);
3622 3623
    fetch_long_with_conversion(param, field, value,
                               field->flags & UNSIGNED_FLAG);
unknown's avatar
unknown committed
3624
    *row+= 8;
3625 3626 3627 3628 3629 3630
    break;
  }
  case MYSQL_TYPE_FLOAT:
  {
    float value;
    float4get(value,*row);
3631
    fetch_float_with_conversion(param, field, value, MY_GCVT_ARG_FLOAT);
unknown's avatar
unknown committed
3632
    *row+= 4;
3633 3634 3635 3636 3637 3638
    break;
  }
  case MYSQL_TYPE_DOUBLE:
  {
    double value;
    float8get(value,*row);
3639
    fetch_float_with_conversion(param, field, value, MY_GCVT_ARG_DOUBLE);
unknown's avatar
unknown committed
3640
    *row+= 8;
3641 3642 3643 3644
    break;
  }
  case MYSQL_TYPE_DATE:
  {
unknown's avatar
unknown committed
3645
    MYSQL_TIME tm;
3646

unknown's avatar
unknown committed
3647
    read_binary_date(&tm, row);
3648
    fetch_datetime_with_conversion(param, field, &tm);
3649 3650 3651 3652
    break;
  }
  case MYSQL_TYPE_TIME:
  {
unknown's avatar
unknown committed
3653
    MYSQL_TIME tm;
3654

unknown's avatar
unknown committed
3655
    read_binary_time(&tm, row);
3656
    fetch_datetime_with_conversion(param, field, &tm);
unknown's avatar
unknown committed
3657 3658 3659 3660 3661 3662
    break;
  }
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
  {
    MYSQL_TIME tm;
3663

unknown's avatar
unknown committed
3664
    read_binary_datetime(&tm, row);
3665
    fetch_datetime_with_conversion(param, field, &tm);
3666 3667
    break;
  }
3668
  default:
unknown's avatar
unknown committed
3669 3670
  {
    ulong length= net_field_length(row);
unknown's avatar
unknown committed
3671
    fetch_string_with_conversion(param, (char*) *row, length);
unknown's avatar
unknown committed
3672
    *row+= length;
3673 3674
    break;
  }
unknown's avatar
unknown committed
3675
  }
3676 3677
}

unknown's avatar
unknown committed
3678

3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
/*
  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
*/

3698 3699
static void fetch_result_tinyint(MYSQL_BIND *param, MYSQL_FIELD *field,
                                 uchar **row)
unknown's avatar
unknown committed
3700
{
3701
  my_bool field_is_unsigned= MY_TEST(field->flags & UNSIGNED_FLAG);
3702 3703
  uchar data= **row;
  *(uchar *)param->buffer= data;
3704
  *param->error= param->is_unsigned != field_is_unsigned && data > INT_MAX8;
3705
  (*row)++;
unknown's avatar
unknown committed
3706 3707
}

3708 3709
static void fetch_result_short(MYSQL_BIND *param, MYSQL_FIELD *field,
                               uchar **row)
unknown's avatar
unknown committed
3710
{
3711
  my_bool field_is_unsigned= MY_TEST(field->flags & UNSIGNED_FLAG);
3712 3713
  ushort data= (ushort) sint2korr(*row);
  shortstore(param->buffer, data);
3714
  *param->error= param->is_unsigned != field_is_unsigned && data > INT_MAX16;
3715
  *row+= 2;
unknown's avatar
unknown committed
3716 3717
}

3718 3719 3720
static void fetch_result_int32(MYSQL_BIND *param,
                               MYSQL_FIELD *field __attribute__((unused)),
                               uchar **row)
unknown's avatar
unknown committed
3721
{
3722
  my_bool field_is_unsigned= MY_TEST(field->flags & UNSIGNED_FLAG);
3723 3724
  uint32 data= (uint32) sint4korr(*row);
  longstore(param->buffer, data);
3725
  *param->error= param->is_unsigned != field_is_unsigned && data > INT_MAX32;
3726
  *row+= 4;
unknown's avatar
unknown committed
3727 3728
}

3729 3730 3731
static void fetch_result_int64(MYSQL_BIND *param,
                               MYSQL_FIELD *field __attribute__((unused)),
                               uchar **row)
3732
{
3733
  my_bool field_is_unsigned= MY_TEST(field->flags & UNSIGNED_FLAG);
3734
  ulonglong data= (ulonglong) sint8korr(*row);
3735
  *param->error= param->is_unsigned != field_is_unsigned && data > LONGLONG_MAX;
3736
  longlongstore(param->buffer, data);
3737
  *row+= 8;
unknown's avatar
unknown committed
3738 3739
}

3740 3741 3742
static void fetch_result_float(MYSQL_BIND *param,
                               MYSQL_FIELD *field __attribute__((unused)),
                               uchar **row)
unknown's avatar
unknown committed
3743 3744 3745
{
  float value;
  float4get(value,*row);
3746
  floatstore(param->buffer, value);
3747
  *row+= 4;
unknown's avatar
unknown committed
3748 3749
}

3750 3751 3752
static void fetch_result_double(MYSQL_BIND *param,
                                MYSQL_FIELD *field __attribute__((unused)),
                                uchar **row)
unknown's avatar
unknown committed
3753 3754 3755
{
  double value;
  float8get(value,*row);
3756
  doublestore(param->buffer, value);
3757
  *row+= 8;
unknown's avatar
unknown committed
3758 3759
}

3760 3761 3762
static void fetch_result_time(MYSQL_BIND *param,
                              MYSQL_FIELD *field __attribute__((unused)),
                              uchar **row)
unknown's avatar
unknown committed
3763 3764
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
unknown's avatar
unknown committed
3765
  read_binary_time(tm, row);
unknown's avatar
unknown committed
3766 3767
}

3768 3769 3770
static void fetch_result_date(MYSQL_BIND *param,
                              MYSQL_FIELD *field __attribute__((unused)),
                              uchar **row)
unknown's avatar
unknown committed
3771 3772
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
unknown's avatar
unknown committed
3773
  read_binary_date(tm, row);
unknown's avatar
unknown committed
3774 3775
}

3776 3777 3778
static void fetch_result_datetime(MYSQL_BIND *param,
                                  MYSQL_FIELD *field __attribute__((unused)),
                                  uchar **row)
unknown's avatar
unknown committed
3779 3780
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
unknown's avatar
unknown committed
3781
  read_binary_datetime(tm, row);
unknown's avatar
unknown committed
3782 3783
}

3784 3785 3786
static void fetch_result_bin(MYSQL_BIND *param,
                             MYSQL_FIELD *field __attribute__((unused)),
                             uchar **row)
3787
{
unknown's avatar
unknown committed
3788
  ulong length= net_field_length(row);
3789
  ulong copy_length= MY_MIN(length, param->buffer_length);
unknown's avatar
unknown committed
3790
  memcpy(param->buffer, (char *)*row, copy_length);
3791
  *param->length= length;
3792
  *param->error= copy_length < length;
unknown's avatar
unknown committed
3793 3794
  *row+= length;
}
3795

3796 3797 3798
static void fetch_result_str(MYSQL_BIND *param,
                             MYSQL_FIELD *field __attribute__((unused)),
                             uchar **row)
unknown's avatar
unknown committed
3799 3800
{
  ulong length= net_field_length(row);
3801
  ulong copy_length= MY_MIN(length, param->buffer_length);
3802
  memcpy(param->buffer, (char *)*row, copy_length);
3803 3804
  /* Add an end null if there is room in the buffer */
  if (copy_length != param->buffer_length)
3805
    ((uchar *)param->buffer)[copy_length]= '\0';
3806
  *param->length= length;			/* return total length */
3807
  *param->error= copy_length < length;
3808
  *row+= length;
unknown's avatar
unknown committed
3809 3810
}

unknown's avatar
unknown committed
3811

3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
/*
  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;
}


3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
/*
  Check that two field types are binary compatible i. e.
  have equal representation in the binary protocol and
  require client-side buffers of the same type.

  SYNOPSIS
    is_binary_compatible()
    type1   parameter type supplied by user
    type2   field type, obtained from result set metadata

  RETURN
    TRUE or FALSE
*/

static my_bool is_binary_compatible(enum enum_field_types type1,
                                    enum enum_field_types type2)
{
  static const enum enum_field_types
3866 3867 3868
    range1[]= { MYSQL_TYPE_SHORT, MYSQL_TYPE_YEAR, MYSQL_TYPE_NULL },
    range2[]= { MYSQL_TYPE_INT24, MYSQL_TYPE_LONG, MYSQL_TYPE_NULL },
    range3[]= { MYSQL_TYPE_DATETIME, MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_NULL },
3869 3870 3871
    range4[]= { MYSQL_TYPE_ENUM, MYSQL_TYPE_SET, MYSQL_TYPE_TINY_BLOB,
                MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB,
                MYSQL_TYPE_VAR_STRING, MYSQL_TYPE_STRING, MYSQL_TYPE_GEOMETRY,
3872 3873
                MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NULL };
  static const enum enum_field_types
3874 3875
   *range_list[]= { range1, range2, range3, range4 },
   **range_list_end= range_list + sizeof(range_list)/sizeof(*range_list);
3876
   const enum enum_field_types **range, *type;
3877 3878 3879 3880 3881 3882

  if (type1 == type2)
    return TRUE;
  for (range= range_list; range != range_list_end; ++range)
  {
    /* check that both type1 and type2 are in the same range */
3883
    my_bool type1_found= FALSE, type2_found= FALSE;
3884
    for (type= *range; *type != MYSQL_TYPE_NULL; type++)
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
    {
      type1_found|= type1 == *type;
      type2_found|= type2 == *type;
    }
    if (type1_found || type2_found)
      return type1_found && type2_found;
  }
  return FALSE;
}


/*
  Setup a fetch function for one column of a result set.

  SYNOPSIS
    setup_one_fetch_function()
    param    output buffer descriptor
    field    column descriptor

  DESCRIPTION
    When user binds result set buffers or when result set
    metadata is changed, we need to setup fetch (and possibly
    conversion) functions for all columns of the result set.
    In addition to that here we set up skip_result function, used
    to update result set metadata in case when
    STMT_ATTR_UPDATE_MAX_LENGTH attribute is set.
    Notice that while fetch_result is chosen depending on both
    field->type and param->type, skip_result depends on field->type
    only.

  RETURN
    TRUE   fetch function for this typecode was not found (typecode
          is not supported by the client library)
    FALSE  success
*/

static my_bool setup_one_fetch_function(MYSQL_BIND *param, MYSQL_FIELD *field)
{
3923 3924
  DBUG_ENTER("setup_one_fetch_function");

3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976
  /* Setup data copy functions for the different supported types */
  switch (param->buffer_type) {
  case MYSQL_TYPE_NULL: /* for dummy binds */
    /*
      It's not binary compatible with anything the server can return:
      no need to setup fetch_result, as it'll be reset anyway
    */
    *param->length= 0;
    break;
  case MYSQL_TYPE_TINY:
    param->fetch_result= fetch_result_tinyint;
    *param->length= 1;
    break;
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_YEAR:
    param->fetch_result= fetch_result_short;
    *param->length= 2;
    break;
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_LONG:
    param->fetch_result= fetch_result_int32;
    *param->length= 4;
    break;
  case MYSQL_TYPE_LONGLONG:
    param->fetch_result= fetch_result_int64;
    *param->length= 8;
    break;
  case MYSQL_TYPE_FLOAT:
    param->fetch_result= fetch_result_float;
    *param->length= 4;
    break;
  case MYSQL_TYPE_DOUBLE:
    param->fetch_result= fetch_result_double;
    *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);
    break;
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
unknown's avatar
unknown committed
3977
  case MYSQL_TYPE_BIT:
3978 3979 3980 3981 3982
    DBUG_ASSERT(param->buffer_length != 0);
    param->fetch_result= fetch_result_bin;
    break;
  case MYSQL_TYPE_VAR_STRING:
  case MYSQL_TYPE_STRING:
unknown's avatar
unknown committed
3983 3984
  case MYSQL_TYPE_DECIMAL:
  case MYSQL_TYPE_NEWDECIMAL:
3985
  case MYSQL_TYPE_NEWDATE:
3986 3987 3988 3989
    DBUG_ASSERT(param->buffer_length != 0);
    param->fetch_result= fetch_result_str;
    break;
  default:
3990 3991 3992
    DBUG_PRINT("error", ("Unknown param->buffer_type: %u",
                         (uint) param->buffer_type));
    DBUG_RETURN(TRUE);
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033
  }
  if (! is_binary_compatible(param->buffer_type, field->type))
    param->fetch_result= fetch_result_with_conversion;

  /* 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;
    field->max_length= 0;
    break;
  case MYSQL_TYPE_TINY:
    param->pack_length= 1;
    field->max_length= 4;                     /* as in '-127' */
    break;
  case MYSQL_TYPE_YEAR:
  case MYSQL_TYPE_SHORT:
    param->pack_length= 2;
    field->max_length= 6;                     /* as in '-32767' */
    break;
  case MYSQL_TYPE_INT24:
    field->max_length= 9;  /* as in '16777216' or in '-8388607' */
    param->pack_length= 4;
    break;
  case MYSQL_TYPE_LONG:
    field->max_length= 11;                    /* '-2147483647' */
    param->pack_length= 4;
    break;
  case MYSQL_TYPE_LONGLONG:
    field->max_length= 21;                    /* '18446744073709551616' */
    param->pack_length= 8;
    break;
  case MYSQL_TYPE_FLOAT:
    param->pack_length= 4;
    field->max_length= MAX_DOUBLE_STRING_REP_LENGTH;
    break;
  case MYSQL_TYPE_DOUBLE:
    param->pack_length= 8;
    field->max_length= MAX_DOUBLE_STRING_REP_LENGTH;
    break;
  case MYSQL_TYPE_TIME:
4034
    field->max_length= 17;                    /* -819:23:48.123456 */
4035
    param->skip_result= skip_result_with_length;
4036
    break;
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
  case MYSQL_TYPE_DATE:
    field->max_length= 10;                    /* 2003-11-11 */
    param->skip_result= skip_result_with_length;
    break;
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
    param->skip_result= skip_result_with_length;
    field->max_length= MAX_DATE_STRING_REP_LENGTH;
    break;
  case MYSQL_TYPE_DECIMAL:
unknown's avatar
unknown committed
4047
  case MYSQL_TYPE_NEWDECIMAL:
4048 4049 4050 4051 4052 4053 4054 4055 4056
  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:
unknown's avatar
unknown committed
4057
  case MYSQL_TYPE_BIT:
4058
  case MYSQL_TYPE_NEWDATE:
4059 4060 4061
    param->skip_result= skip_result_string;
    break;
  default:
4062 4063
    DBUG_PRINT("error", ("Unknown field->type: %u", (uint) field->type));
    DBUG_RETURN(TRUE);
4064
  }
4065
  DBUG_RETURN(FALSE);
4066 4067 4068
}


4069
/*
4070
  Setup the bind buffers for resultset processing
4071 4072
*/

4073
my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT *stmt, MYSQL_BIND *my_bind)
4074
{
4075
  MYSQL_BIND *param, *end;
4076
  MYSQL_FIELD *field;
4077
  ulong       bind_count= stmt->field_count;
4078
  uint        param_count= 0;
4079
  DBUG_ENTER("mysql_stmt_bind_result");
unknown's avatar
unknown committed
4080
  DBUG_PRINT("enter",("field_count: %lu", bind_count));
4081

4082
  if (!bind_count)
4083
  {
4084 4085
    int errorcode= (int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE ?
                   CR_NO_PREPARE_STMT : CR_NO_STMT_METADATA;
4086
    set_stmt_error(stmt, errorcode, unknown_sqlstate, NULL);
4087
    DBUG_RETURN(1);
4088 4089 4090 4091 4092
  }

  /*
    We only need to check that stmt->field_count - if it is not null
    stmt->bind was initialized in mysql_stmt_prepare
4093 4094 4095
    stmt->bind overlaps with bind if mysql_stmt_bind_param
    is called from mysql_stmt_store_result.
  */
4096

4097 4098 4099
  if (stmt->bind != my_bind)
    memcpy((char*) stmt->bind, (char*) my_bind,
           sizeof(MYSQL_BIND) * bind_count);
4100

4101 4102 4103
  for (param= stmt->bind, end= param + bind_count, field= stmt->fields ;
       param < end ;
       param++, field++)
4104
  {
4105 4106
    DBUG_PRINT("info",("buffer_type: %u  field_type: %u",
                       (uint) param->buffer_type, (uint) field->type));
unknown's avatar
unknown committed
4107 4108
    /*
      Set param->is_null to point to a dummy variable if it's not set.
unknown's avatar
unknown committed
4109
      This is to make the execute code easier
unknown's avatar
unknown committed
4110 4111
    */
    if (!param->is_null)
4112
      param->is_null= &param->is_null_value;
unknown's avatar
unknown committed
4113

unknown's avatar
unknown committed
4114
    if (!param->length)
4115 4116 4117 4118
      param->length= &param->length_value;

    if (!param->error)
      param->error= &param->error_value;
unknown's avatar
unknown committed
4119

4120
    param->param_number= param_count++;
unknown's avatar
unknown committed
4121 4122
    param->offset= 0;

4123 4124
    if (setup_one_fetch_function(param, field))
    {
4125 4126
      strmov(stmt->sqlstate, unknown_sqlstate);
      sprintf(stmt->last_error,
4127 4128
              ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
              field->type, param_count);
4129 4130
      DBUG_RETURN(1);
    }
4131
  }
4132 4133 4134 4135
  stmt->bind_result_done= BIND_RESULT_DONE;
  if (stmt->mysql->options.report_data_truncation)
    stmt->bind_result_done|= REPORT_DATA_TRUNCATION;

4136 4137 4138
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
4139

4140
/*
4141
  Fetch row data to bind buffers
4142 4143
*/

4144
static int stmt_fetch_row(MYSQL_STMT *stmt, uchar *row)
4145
{
4146
  MYSQL_BIND  *my_bind, *end;
4147
  MYSQL_FIELD *field;
unknown's avatar
unknown committed
4148
  uchar *null_ptr, bit;
4149
  int truncation_count= 0;
4150 4151 4152 4153 4154 4155
  /*
    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);
4156

4157 4158 4159
  if (!stmt->bind_result_done)
  {
    /* If output parameters were not bound we should just return success */
4160
    return 0;
4161
  }
4162 4163

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

unknown's avatar
unknown committed
4167
  /* Copy complete row to application buffers */
4168 4169 4170 4171
  for (my_bind= stmt->bind, end= my_bind + stmt->field_count,
         field= stmt->fields ;
       my_bind < end ;
       my_bind++, field++)
4172
  {
4173
    *my_bind->error= 0;
4174
    if (*null_ptr & bit)
4175 4176
    {
      /*
4177
        We should set both row_ptr and is_null to be able to see
4178 4179 4180 4181 4182
        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.
      */
4183 4184
      my_bind->row_ptr= NULL;
      *my_bind->is_null= 1;
4185
    }
4186
    else
4187
    {
4188 4189 4190 4191
      *my_bind->is_null= 0;
      my_bind->row_ptr= row;
      (*my_bind->fetch_result)(my_bind, field, &row);
      truncation_count+= *my_bind->error;
4192
    }
unknown's avatar
unknown committed
4193
    if (!((bit<<=1) & 255))
4194
    {
4195
      bit= 1;					/* To next uchar */
4196
      null_ptr++;
4197 4198
    }
  }
4199 4200
  if (truncation_count && (stmt->bind_result_done & REPORT_DATA_TRUNCATION))
    return MYSQL_DATA_TRUNCATED;
4201 4202 4203
  return 0;
}

4204

unknown's avatar
unknown committed
4205
int cli_unbuffered_fetch(MYSQL *mysql, char **row)
unknown's avatar
SCRUM  
unknown committed
4206
{
4207
  if (packet_error == cli_safe_read(mysql))
unknown's avatar
SCRUM  
unknown committed
4208 4209
    return 1;

unknown's avatar
unknown committed
4210 4211
  *row= ((mysql->net.read_pos[0] == 254) ? NULL :
	 (char*) (mysql->net.read_pos+1));
unknown's avatar
SCRUM  
unknown committed
4212 4213
  return 0;
}
unknown's avatar
unknown committed
4214

4215

4216
/*
4217
  Fetch and return row data to bound buffers, if any
4218 4219
*/

4220
int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt)
4221
{
4222
  int rc;
4223
  uchar *row;
4224
  DBUG_ENTER("mysql_stmt_fetch");
4225

4226
  if ((rc= (*stmt->read_row_func)(stmt, &row)) ||
4227
      ((rc= stmt_fetch_row(stmt, row)) && rc != MYSQL_DATA_TRUNCATED))
4228
  {
4229
    stmt->state= MYSQL_STMT_PREPARE_DONE;       /* XXX: this is buggy */
unknown's avatar
unknown committed
4230 4231
    stmt->read_row_func= (rc == MYSQL_NO_DATA) ? 
      stmt_read_row_no_data : stmt_read_row_no_result_set;
unknown's avatar
unknown committed
4232
  }
4233
  else
4234
  {
4235 4236
    /* 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
4237
  }
4238
  DBUG_RETURN(rc);
4239 4240
}

unknown's avatar
unknown committed
4241

unknown's avatar
unknown committed
4242
/*
unknown's avatar
unknown committed
4243
  Fetch data for one specified column data
unknown's avatar
unknown committed
4244 4245

  SYNOPSIS
4246
    mysql_stmt_fetch_column()
unknown's avatar
unknown committed
4247
    stmt		Prepared statement handler
4248
    my_bind		Where data should be placed. Should be filled in as
4249
			when calling mysql_stmt_bind_result()
unknown's avatar
unknown committed
4250 4251 4252
    column		Column to fetch (first column is 0)
    ulong offset	Offset in result data (to fetch blob in pieces)
			This is normally 0
4253
  RETURN
unknown's avatar
unknown committed
4254 4255
    0	ok
    1	error
unknown's avatar
unknown committed
4256 4257
*/

4258
int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *my_bind,
4259
                                    uint column, ulong offset)
unknown's avatar
unknown committed
4260
{
4261
  MYSQL_BIND *param= stmt->bind+column;
4262
  DBUG_ENTER("mysql_stmt_fetch_column");
unknown's avatar
unknown committed
4263

4264 4265
  if ((int) stmt->state < (int) MYSQL_STMT_FETCH_DONE)
  {
4266
    set_stmt_error(stmt, CR_NO_DATA, unknown_sqlstate, NULL);
unknown's avatar
unknown committed
4267
    DBUG_RETURN(1);
4268 4269 4270
  }
  if (column >= stmt->field_count)
  {
4271
    set_stmt_error(stmt, CR_INVALID_PARAMETER_NO, unknown_sqlstate, NULL);
4272 4273 4274
    DBUG_RETURN(1);
  }

4275 4276 4277
  if (!my_bind->error)
    my_bind->error= &my_bind->error_value;
  *my_bind->error= 0;
4278
  if (param->row_ptr)
unknown's avatar
unknown committed
4279
  {
4280
    MYSQL_FIELD *field= stmt->fields+column;
4281
    uchar *row= param->row_ptr;
4282 4283 4284 4285 4286
    my_bind->offset= offset;
    if (my_bind->is_null)
      *my_bind->is_null= 0;
    if (my_bind->length) /* Set the length if non char/binary types */
      *my_bind->length= *param->length;
unknown's avatar
unknown committed
4287
    else
4288 4289
      my_bind->length= &param->length_value;       /* Needed for fetch_result() */
    fetch_result_with_conversion(my_bind, field, &row);
unknown's avatar
unknown committed
4290
  }
4291 4292
  else
  {
4293 4294
    if (my_bind->is_null)
      *my_bind->is_null= 1;
4295
  }
unknown's avatar
unknown committed
4296 4297 4298 4299
  DBUG_RETURN(0);
}


4300
/*
4301 4302 4303
  Read all rows of data from server  (binary format)
*/

4304
int cli_read_binary_rows(MYSQL_STMT *stmt)
4305 4306 4307 4308
{
  ulong      pkt_len;
  uchar      *cp;
  MYSQL      *mysql= stmt->mysql;
4309 4310
  MYSQL_DATA *result= &stmt->result;
  MYSQL_ROWS *cur, **prev_ptr= &result->data;
4311 4312
  NET        *net;

unknown's avatar
unknown committed
4313
  DBUG_ENTER("cli_read_binary_rows");
unknown's avatar
unknown committed
4314

4315 4316
  if (!mysql)
  {
4317
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate, NULL);
unknown's avatar
unknown committed
4318
    DBUG_RETURN(1);
4319 4320 4321
  }

  net = &mysql->net;
4322

4323
  while ((pkt_len= cli_safe_read(mysql)) != packet_error)
4324
  {
4325 4326
    cp= net->read_pos;
    if (cp[0] != 254 || pkt_len >= 8)
4327
    {
4328 4329 4330
      if (!(cur= (MYSQL_ROWS*) alloc_root(&result->alloc,
                                          sizeof(MYSQL_ROWS) + pkt_len - 1)))
      {
4331
        set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate, NULL);
4332
        goto err;
4333 4334 4335 4336 4337
      }
      cur->data= (MYSQL_ROW) (cur+1);
      *prev_ptr= cur;
      prev_ptr= &cur->next;
      memcpy((char *) cur->data, (char *) cp+1, pkt_len-1);
4338 4339
      cur->length= pkt_len;		/* To allow us to do sanity checks */
      result->rows++;
4340
    }
4341
    else
4342
    {
4343 4344 4345 4346
      /* end of data */
      *prev_ptr= 0;
      mysql->warning_count= uint2korr(cp+1);
      mysql->server_status= uint2korr(cp+3);
4347 4348
      DBUG_PRINT("info",("status: %u  warning_count: %u",
                         mysql->server_status, mysql->warning_count));
4349 4350 4351
      DBUG_RETURN(0);
    }
  }
4352
  set_stmt_errmsg(stmt, net);
4353 4354

err:
4355
  DBUG_RETURN(1);
4356 4357
}

4358

4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372
/*
  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)
{
4373
  MYSQL_BIND  *my_bind, *end;
4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
  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 */

4385
  /* Go through all fields and calculate metadata */
4386 4387 4388
  for (my_bind= stmt->bind, end= my_bind + stmt->field_count, field= stmt->fields ;
       my_bind < end ;
       my_bind++, field++)
4389 4390
  {
    if (!(*null_ptr & bit))
4391
      (*my_bind->skip_result)(my_bind, field, &row);
4392 4393 4394
    DBUG_ASSERT(row <= row_end);
    if (!((bit<<=1) & 255))
    {
4395
      bit= 1;					/* To next uchar */
4396 4397 4398 4399 4400 4401
      null_ptr++;
    }
  }
}


4402 4403 4404 4405 4406 4407 4408
/*
  Store or buffer the binary results to stmt
*/

int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt)
{
  MYSQL *mysql= stmt->mysql;
4409
  MYSQL_DATA *result= &stmt->result;
4410
  DBUG_ENTER("mysql_stmt_store_result");
4411

4412 4413 4414
  if (!mysql)
  {
    /* mysql can be reset in mysql_close called from mysql_reconnect */
unknown's avatar
unknown committed
4415
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate, NULL);
4416 4417 4418
    DBUG_RETURN(1);
  }

4419 4420
  if (!stmt->field_count)
    DBUG_RETURN(0);
4421 4422 4423

  if ((int) stmt->state < (int) MYSQL_STMT_EXECUTE_DONE)
  {
4424
    set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate, NULL);
4425 4426 4427
    DBUG_RETURN(1);
  }

4428 4429 4430 4431 4432 4433
  if (stmt->last_errno)
  {
    /* An attempt to use an invalid statement handle. */
    DBUG_RETURN(1);
  }

4434 4435 4436 4437 4438 4439 4440
  if (mysql->status == MYSQL_STATUS_READY &&
      stmt->server_status & SERVER_STATUS_CURSOR_EXISTS)
  {
    /*
      Server side cursor exist, tell server to start sending the rows
    */
    NET *net= &mysql->net;
4441 4442
    uchar buff[4 /* statement id */ +
               4 /* number of rows to fetch */];
4443 4444 4445 4446 4447

    /* Send row request to the server */
    int4store(buff, stmt->stmt_id);
    int4store(buff + 4, (int)~0); /* number of rows to fetch */
    if (cli_advanced_command(mysql, COM_STMT_FETCH, buff, sizeof(buff),
4448
                             (uchar*) 0, 0, 1, stmt))
4449
    {
4450 4451 4452 4453 4454 4455
      /* 
        Don't set stmt error if stmt->mysql is NULL, as the error in this case 
        has already been set by mysql_prune_stmt_list(). 
      */
      if (stmt->mysql)
        set_stmt_errmsg(stmt, net);
4456 4457 4458
      DBUG_RETURN(1);
    }
  }
4459
  else if (mysql->status != MYSQL_STATUS_STATEMENT_GET_RESULT)
4460
  {
4461
    set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate, NULL);
4462
    DBUG_RETURN(1);
4463
  }
4464

4465 4466 4467 4468 4469 4470
  if (stmt->update_max_length && !stmt->bind_result_done)
  {
    /*
      We must initalize the bind structure to be able to calculate
      max_length
    */
4471
    MYSQL_BIND  *my_bind, *end;
4472 4473 4474
    MYSQL_FIELD *field;
    bzero((char*) stmt->bind, sizeof(*stmt->bind)* stmt->field_count);

4475 4476 4477 4478
    for (my_bind= stmt->bind, end= my_bind + stmt->field_count,
           field= stmt->fields;
	 my_bind < end ;
	 my_bind++, field++)
4479
    {
4480 4481
      my_bind->buffer_type= MYSQL_TYPE_NULL;
      my_bind->buffer_length=1;
4482 4483
    }

4484 4485
    if (mysql_stmt_bind_result(stmt, stmt->bind))
      DBUG_RETURN(1);
4486 4487 4488
    stmt->bind_result_done= 0;			/* No normal bind done */
  }

4489
  if ((*mysql->methods->read_binary_rows)(stmt))
4490
  {
4491 4492 4493
    free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
    result->data= NULL;
    result->rows= 0;
4494
    mysql->status= MYSQL_STATUS_READY;
4495
    DBUG_RETURN(1);
4496
  }
4497

4498 4499 4500 4501
  /* Assert that if there was a cursor, all rows have been fetched */
  DBUG_ASSERT(mysql->status != MYSQL_STATUS_READY ||
              (mysql->server_status & SERVER_STATUS_LAST_ROW_SENT));

4502 4503 4504 4505 4506 4507 4508
  if (stmt->update_max_length)
  {
    MYSQL_ROWS *cur= result->data;
    for(; cur; cur=cur->next)
      stmt_update_metadata(stmt, cur);
  }

4509 4510
  stmt->data_cursor= result->data;
  mysql->affected_rows= stmt->affected_rows= result->rows;
4511 4512 4513
  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 */
4514
  DBUG_RETURN(0); /* Data buffered, must be fetched with mysql_stmt_fetch() */
4515 4516
}

4517

4518 4519 4520 4521 4522 4523 4524
/*
  Seek to desired row in the statement result set
*/

MYSQL_ROW_OFFSET STDCALL
mysql_stmt_row_seek(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET row)
{
4525
  MYSQL_ROW_OFFSET offset= stmt->data_cursor;
4526
  DBUG_ENTER("mysql_stmt_row_seek");
4527

4528 4529
  stmt->data_cursor= row;
  DBUG_RETURN(offset);
4530 4531
}

4532

4533 4534 4535 4536
/*
  Return the current statement row cursor position
*/

4537
MYSQL_ROW_OFFSET STDCALL
4538 4539 4540
mysql_stmt_row_tell(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_row_tell");
4541

4542
  DBUG_RETURN(stmt->data_cursor);
4543 4544
}

unknown's avatar
unknown committed
4545

4546 4547 4548 4549 4550 4551 4552
/*
  Move the stmt result set data cursor to specified row
*/

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

4557 4558 4559
  for (; tmp && row; --row, tmp= tmp->next)
    ;
  stmt->data_cursor= tmp;
unknown's avatar
unknown committed
4560 4561 4562 4563 4564 4565
  if (!row && tmp)
  {
       /*  Rewind the counter */
    stmt->read_row_func= stmt_read_row_buffered;
    stmt->state= MYSQL_STMT_EXECUTE_DONE;
  }
4566
  DBUG_VOID_RETURN;
4567 4568
}

unknown's avatar
unknown committed
4569

4570 4571 4572 4573 4574 4575 4576
/*
  Return total rows the current statement result set
*/

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

4578
  DBUG_RETURN(stmt->result.rows);
4579
}
4580

4581

4582 4583 4584 4585 4586
/*
  Free the client side memory buffers, reset long data state
  on client if necessary, and reset the server side statement if
  this has been requested.
*/
4587

4588 4589 4590
static my_bool reset_stmt_handle(MYSQL_STMT *stmt, uint flags)
{
  /* If statement hasn't been prepared there is nothing to reset */
4591 4592 4593
  if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
  {
    MYSQL *mysql= stmt->mysql;
4594
    MYSQL_DATA *result= &stmt->result;
4595

4596 4597 4598 4599
    /*
      Reset stored result set if so was requested or it's a part
      of cursor fetch.
    */
4600
    if (flags & RESET_STORE_RESULT)
4601 4602
    {
      /* Result buffered */
4603 4604 4605 4606
      free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
      result->data= NULL;
      result->rows= 0;
      stmt->data_cursor= NULL;
4607
    }
4608
    if (flags & RESET_LONG_DATA)
4609
    {
4610 4611 4612 4613 4614
      MYSQL_BIND *param= stmt->params, *param_end= param + stmt->param_count;
      /* Clear long_data_used flags */
      for (; param < param_end; param++)
        param->long_data_used= 0;
    }
unknown's avatar
unknown committed
4615
    stmt->read_row_func= stmt_read_row_no_result_set;
4616 4617 4618
    if (mysql)
    {
      if ((int) stmt->state > (int) MYSQL_STMT_PREPARE_DONE)
4619
      {
4620 4621 4622 4623 4624
        if (mysql->unbuffered_fetch_owner == &stmt->unbuffered_fetch_cancelled)
          mysql->unbuffered_fetch_owner= 0;
        if (stmt->field_count && mysql->status != MYSQL_STATUS_READY)
        {
          /* There is a result set and it belongs to this statement */
4625
          (*mysql->methods->flush_use_result)(mysql, FALSE);
4626 4627 4628 4629
          if (mysql->unbuffered_fetch_owner)
            *mysql->unbuffered_fetch_owner= TRUE;
          mysql->status= MYSQL_STATUS_READY;
        }
4630 4631 4632 4633 4634 4635 4636 4637
        if (flags & RESET_ALL_BUFFERS)
        {
          /* mysql_stmt_next_result will flush all pending
             result sets 
          */
          while (mysql_more_results(mysql) &&
                 mysql_stmt_next_result(stmt) == 0);
        }
4638
      }
4639
      if (flags & RESET_SERVER_SIDE)
4640 4641 4642 4643 4644
      {
        /*
          Reset the server side statement and close the server side
          cursor if it exists.
        */
4645
        uchar buff[MYSQL_STMT_HEADER]; /* packet header: 4 bytes for stmt id */
4646
        int4store(buff, stmt->stmt_id);
4647
        if ((*mysql->methods->advanced_command)(mysql, COM_STMT_RESET, buff,
4648
                                                sizeof(buff), 0, 0, 0, stmt))
4649
        {
4650
          set_stmt_errmsg(stmt, &mysql->net);
4651 4652 4653
          stmt->state= MYSQL_STMT_INIT_DONE;
          return 1;
        }
4654 4655
      }
    }
4656 4657
    if (flags & RESET_CLEAR_ERROR)
      stmt_clear_error(stmt);
4658 4659
    stmt->state= MYSQL_STMT_PREPARE_DONE;
  }
4660 4661 4662 4663 4664 4665 4666 4667
  return 0;
}

my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_free_result");

  /* Free the client side and close the server side cursor if there is one */
4668 4669
  DBUG_RETURN(reset_stmt_handle(stmt, RESET_LONG_DATA | RESET_STORE_RESULT |
                                RESET_CLEAR_ERROR));
4670 4671
}

4672
/********************************************************************
4673
 statement error handling and close
4674
*********************************************************************/
4675

4676
/*
unknown's avatar
unknown committed
4677
  Close the statement handle by freeing all alloced resources
4678

unknown's avatar
unknown committed
4679
  SYNOPSIS
4680
    mysql_stmt_close()
unknown's avatar
unknown committed
4681
    stmt	       Statement handle
4682

unknown's avatar
unknown committed
4683 4684 4685 4686
  RETURN VALUES
    0	ok
    1	error
*/
4687

4688
my_bool STDCALL mysql_stmt_close(MYSQL_STMT *stmt)
4689
{
4690 4691 4692
  MYSQL *mysql= stmt->mysql;
  int rc= 0;
  DBUG_ENTER("mysql_stmt_close");
4693

4694
  free_root(&stmt->result.alloc, MYF(0));
4695
  free_root(&stmt->mem_root, MYF(0));
4696
  free_root(&stmt->extension->fields_mem_root, MYF(0));
4697 4698

  if (mysql)
4699
  {
4700
    mysql->stmts= list_delete(mysql->stmts, &stmt->list);
unknown's avatar
unknown committed
4701
    /*
4702 4703
     Clear NET error state: if the following commands come through
     successfully, connection will still be usable for other commands.
unknown's avatar
unknown committed
4704 4705
    */
    net_clear_error(&mysql->net);
4706

4707
    if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
4708
    {
4709
      uchar buff[MYSQL_STMT_HEADER];             /* 4 bytes - stmt id */
4710

4711 4712 4713
      if ((rc= reset_stmt_handle(stmt, RESET_ALL_BUFFERS | RESET_CLEAR_ERROR)))
        return rc;

4714
      int4store(buff, stmt->stmt_id);
4715
      if ((rc= stmt_command(mysql, COM_STMT_CLOSE, buff, 4, stmt)))
4716
      {
4717
        set_stmt_errmsg(stmt, &mysql->net);
4718
      }
4719
    }
4720
  }
4721

4722
  my_free(stmt->extension);
4723
  my_free(stmt);
unknown's avatar
unknown committed
4724

4725
  DBUG_RETURN(MY_TEST(rc));
unknown's avatar
unknown committed
4726 4727
}

4728 4729 4730 4731 4732 4733 4734 4735
/*
  Reset the statement buffers in server
*/

my_bool STDCALL mysql_stmt_reset(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_reset");
  DBUG_ASSERT(stmt != 0);
4736 4737 4738
  if (!stmt->mysql)
  {
    /* mysql can be reset in mysql_close called from mysql_reconnect */
4739
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate, NULL);
4740 4741
    DBUG_RETURN(1);
  }
4742
  /* Reset the client and server sides of the prepared statement */
4743 4744
  DBUG_RETURN(reset_stmt_handle(stmt,
                                RESET_SERVER_SIDE | RESET_LONG_DATA |
4745
                                RESET_ALL_BUFFERS | RESET_CLEAR_ERROR));
4746 4747
}

4748 4749 4750 4751 4752 4753 4754
/*
  Return statement error code
*/

uint STDCALL mysql_stmt_errno(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_errno");
4755
  DBUG_RETURN(stmt->last_errno);
4756 4757
}

4758 4759 4760 4761 4762 4763
const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_sqlstate");
  DBUG_RETURN(stmt->sqlstate);
}

4764 4765 4766 4767 4768 4769 4770
/*
  Return statement error message
*/

const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_error");
4771
  DBUG_RETURN(stmt->last_error);
4772 4773
}

4774

4775 4776 4777 4778
/********************************************************************
 Transactional APIs
*********************************************************************/

4779 4780 4781 4782
/*
  Commit the current transaction
*/

4783
my_bool STDCALL mysql_commit(MYSQL * mysql)
4784 4785
{
  DBUG_ENTER("mysql_commit");
4786
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "commit", 6));
4787 4788 4789
}

/*
4790
  Rollback the current transaction
4791 4792
*/

4793
my_bool STDCALL mysql_rollback(MYSQL * mysql)
4794 4795
{
  DBUG_ENTER("mysql_rollback");
4796
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "rollback", 8));
4797 4798 4799 4800 4801 4802 4803
}


/*
  Set autocommit to either true or false
*/

4804
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode)
4805 4806 4807 4808
{
  DBUG_ENTER("mysql_autocommit");
  DBUG_PRINT("enter", ("mode : %d", auto_mode));

4809 4810 4811
  DBUG_RETURN((my_bool) mysql_real_query(mysql, auto_mode ?
                                         "set autocommit=1":"set autocommit=0",
                                         16));
4812
}
4813 4814 4815


/********************************************************************
4816
 Multi query execution + SPs APIs
4817 4818 4819
*********************************************************************/

/*
unknown's avatar
unknown committed
4820 4821
  Returns true/false to indicate whether any more query results exist
  to be read using mysql_next_result()
4822 4823 4824 4825
*/

my_bool STDCALL mysql_more_results(MYSQL *mysql)
{
4826
  my_bool res;
4827
  DBUG_ENTER("mysql_more_results");
4828

Konstantin Osipov's avatar
Konstantin Osipov committed
4829
  res= ((mysql->server_status & SERVER_MORE_RESULTS_EXISTS) ? 1: 0);
4830
  DBUG_PRINT("exit",("More results exists ? %d", res));
4831
  DBUG_RETURN(res);
4832 4833
}

4834

4835 4836 4837
/*
  Reads and returns the next query results
*/
4838
int STDCALL mysql_next_result(MYSQL *mysql)
4839
{
4840
  DBUG_ENTER("mysql_next_result");
4841

4842 4843
  if (mysql->status != MYSQL_STATUS_READY)
  {
4844
    set_mysql_error(mysql, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
4845 4846 4847
    DBUG_RETURN(1);
  }

4848
  net_clear_error(&mysql->net);
4849 4850
  mysql->affected_rows= ~(my_ulonglong) 0;

Konstantin Osipov's avatar
Konstantin Osipov committed
4851
  if (mysql->server_status & SERVER_MORE_RESULTS_EXISTS)
unknown's avatar
unknown committed
4852 4853
    DBUG_RETURN((*mysql->methods->next_result)(mysql));

4854
  DBUG_RETURN(-1);				/* No more results */
4855
}
unknown's avatar
SCRUM:  
unknown committed
4856

4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882
int STDCALL mysql_stmt_next_result(MYSQL_STMT *stmt)
{
  MYSQL *mysql= stmt->mysql;
  int rc;
  DBUG_ENTER("mysql_stmt_next_result");

  if (!mysql)
    DBUG_RETURN(1);

  if (stmt->last_errno)
    DBUG_RETURN(stmt->last_errno);

  if (mysql->server_status & SERVER_MORE_RESULTS_EXISTS)
  {
    if (reset_stmt_handle(stmt, RESET_STORE_RESULT))
      DBUG_RETURN(1);
  }

  rc= mysql_next_result(mysql);

  if (rc)
  {
    set_stmt_errmsg(stmt, &mysql->net);
    DBUG_RETURN(rc);
  }

4883 4884 4885
  if (mysql->status == MYSQL_STATUS_GET_RESULT)
    mysql->status= MYSQL_STATUS_STATEMENT_GET_RESULT;

4886 4887
  stmt->state= MYSQL_STMT_EXECUTE_DONE;
  stmt->bind_result_done= FALSE;
4888
  stmt->field_count= mysql->field_count;
4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899

  if (mysql->field_count)
  {
    alloc_stmt_fields(stmt);
    prepare_to_fetch_result(stmt);
  }

  DBUG_RETURN(0);
}


unknown's avatar
SCRUM:  
unknown committed
4900 4901 4902 4903 4904 4905 4906 4907 4908 4909
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);
}

4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
/********************************************************************
  mysql_net_ functions - low-level API to MySQL protocol
*********************************************************************/
ulong STDCALL mysql_net_read_packet(MYSQL *mysql)
{
  return cli_safe_read(mysql);
}

ulong STDCALL mysql_net_field_length(uchar **packet)
{
  return net_field_length(packet);
}