libmysql.c 142 KB
Newer Older
1
/* Copyright (C) 2000-2004 MySQL AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2 3 4

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
5 6 7 8
   the Free Software Foundation.

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

   This program is distributed in the hope that it will be useful,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
12
   but WITHOUT ANY WARRANTY; without even the implied warranty of
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
13 14 15 16 17 18
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
19

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

hf@deer.(none)'s avatar
hf@deer.(none) committed
62
#include <sql_common.h>
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
63
#include "client_settings.h"
hf@deer.(none)'s avatar
hf@deer.(none) committed
64

65 66
#undef net_buffer_length
#undef max_allowed_packet
67

68
ulong 		net_buffer_length=8192;
69
ulong		max_allowed_packet= 1024L*1024L*1024L;
70 71
ulong		net_read_timeout=  CLIENT_NET_READ_TIMEOUT;
ulong		net_write_timeout= CLIENT_NET_WRITE_TIMEOUT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
72

hf@deer.(none)'s avatar
hf@deer.(none) committed
73

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
74 75 76 77 78
#ifdef EMBEDDED_LIBRARY
#undef net_flush
my_bool	net_flush(NET *net);
#endif

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

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
94
static void append_wild(char *to,char *end,const char *wild);
95
sig_handler my_pipe_sig_handler(int sig);
96 97 98 99

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

monty@mysql.com's avatar
monty@mysql.com committed
100 101

/*
monty@mysql.com's avatar
merge  
monty@mysql.com committed
102
  Initialize the MySQL client library
monty@mysql.com's avatar
monty@mysql.com committed
103 104

  SYNOPSIS
monty@mysql.com's avatar
merge  
monty@mysql.com committed
105
    mysql_server_init()
monty@mysql.com's avatar
monty@mysql.com committed
106 107

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

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

monty@mysql.com's avatar
monty@mysql.com committed
119 120 121
int STDCALL mysql_server_init(int argc __attribute__((unused)),
			      char **argv __attribute__((unused)),
			      char **groups __attribute__((unused)))
122
{
123
  int result= 0;
124 125 126 127
  if (!mysql_client_init)
  {
    mysql_client_init=1;
    org_my_init_done=my_init_done;
monty@mysql.com's avatar
monty@mysql.com committed
128 129
    if (my_init())				/* Will init threads */
      return 1;
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    init_client_errs();
    if (!mysql_port)
    {
      mysql_port = MYSQL_PORT;
#ifndef MSDOS
      {
	struct servent *serv_ptr;
	char	*env;
	if ((serv_ptr = getservbyname("mysql", "tcp")))
	  mysql_port = (uint) ntohs((ushort) serv_ptr->s_port);
	if ((env = getenv("MYSQL_TCP_PORT")))
	  mysql_port =(uint) atoi(env);
      }
#endif
    }
    if (!mysql_unix_port)
    {
      char *env;
#ifdef __WIN__
      mysql_unix_port = (char*) MYSQL_NAMEDPIPE;
#else
      mysql_unix_port = (char*) MYSQL_UNIX_ADDR;
#endif
      if ((env = getenv("MYSQL_UNIX_PORT")))
	mysql_unix_port = env;
    }
    mysql_debug(NullS);
157
#if defined(SIGPIPE) && !defined(__WIN__) && !defined(__NETWARE__)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
158
    (void) signal(SIGPIPE, SIG_IGN);
159
#endif
monty@mysql.com's avatar
monty@mysql.com committed
160
#ifdef EMBEDDED_LIBRARY
161
    if (argc > -1)
162
       result= init_embedded_server(argc, argv, groups);
monty@mysql.com's avatar
monty@mysql.com committed
163
#endif
164 165 166
  }
#ifdef THREAD
  else
hf@deer.(none)'s avatar
hf@deer.(none) committed
167
    result= (int)my_thread_init();         /* Init if new thread */
168
#endif
169
  return result;
170
}
tim@black.box's avatar
tim@black.box committed
171

172

173
void STDCALL mysql_server_end()
174
{
monty@mysql.com's avatar
monty@mysql.com committed
175
#ifdef EMBEDDED_LIBRARY
176
  end_embedded_server();
monty@mysql.com's avatar
monty@mysql.com committed
177
#endif
178 179
  /* If library called my_init(), free memory allocated by it */
  if (!org_my_init_done)
180
  {
181
    my_end(MY_DONT_FREE_DBUG);
182 183 184 185 186
#ifndef THREAD
  /* Remove TRACING, if enabled by mysql_debug() */
    DBUG_POP();
#endif
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
187 188
  else
    mysql_thread_end();
189
  finish_client_errs();
190
  free_charsets();
191
  vio_end();
192
  mysql_client_init= org_my_init_done= 0;
193 194 195 196 197 198 199
#ifdef EMBEDDED_SERVER
  if (stderror_file)
  {
    fclose(stderror_file);
    stderror_file= 0;
  }
#endif
200
}
tim@black.box's avatar
tim@black.box committed
201

202 203 204
static MYSQL_PARAMETERS mysql_internal_parameters=
{&max_allowed_packet, &net_buffer_length};

205
MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void)
206 207 208 209
{
  return &mysql_internal_parameters;
}

210
my_bool STDCALL mysql_thread_init()
tim@black.box's avatar
tim@black.box committed
211 212
{
#ifdef THREAD
213
  return my_thread_init();
tim@black.box's avatar
tim@black.box committed
214
#else
215
  return 0;
tim@black.box's avatar
tim@black.box committed
216 217 218
#endif
}

219
void STDCALL mysql_thread_end()
tim@black.box's avatar
tim@black.box committed
220 221
{
#ifdef THREAD
222
  my_thread_end();
tim@black.box's avatar
tim@black.box committed
223 224 225
#endif
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
226 227 228 229
/*
  Let the user specify that we don't want SIGPIPE;  This doesn't however work
  with threaded applications as we can have multiple read in progress.
*/
230 231 232 233 234
static MYSQL* spawn_init(MYSQL* parent, const char* host,
			 unsigned int port,
			 const char* user,
			 const char* passwd);

235

bk@work.mysql.com's avatar
bk@work.mysql.com committed
236 237

/*
238
  Expand wildcard to a sql string
bk@work.mysql.com's avatar
bk@work.mysql.com committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
*/

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


/**************************************************************************
263
  Init debugging if MYSQL_DEBUG environment variable is found
bk@work.mysql.com's avatar
bk@work.mysql.com committed
264 265 266
**************************************************************************/

void STDCALL
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
267
mysql_debug(const char *debug __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
{
#ifndef DBUG_OFF
  char	*env;
  if (_db_on_)
    return;					/* Already using debugging */
  if (debug)
  {
    DEBUGGER_ON;
    DBUG_PUSH(debug);
  }
  else if ((env = getenv("MYSQL_DEBUG")))
  {
    DEBUGGER_ON;
    DBUG_PUSH(env);
#if !defined(_WINVER) && !defined(WINVER)
    puts("\n-------------------------------------------------------");
    puts("MYSQL_DEBUG found. libmysql started with the following:");
    puts(env);
    puts("-------------------------------------------------------\n");
#else
    {
      char buff[80];
290 291
      buff[sizeof(buff)-1]= 0;
      strxnmov(buff,sizeof(buff)-1,"libmysql: ", env, NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
292 293 294 295 296 297 298 299 300
      MessageBox((HWND) 0,"Debugging variable MYSQL_DEBUG used",buff,MB_OK);
    }
#endif
  }
#endif
}


/**************************************************************************
301
  Close the server connection if we get a SIGPIPE
bk@work.mysql.com's avatar
bk@work.mysql.com committed
302 303 304
   ARGSUSED
**************************************************************************/

hf@deer.(none)'s avatar
hf@deer.(none) committed
305
sig_handler
306
my_pipe_sig_handler(int sig __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
307 308 309
{
  DBUG_PRINT("info",("Hit by signal %d",sig));
#ifdef DONT_REMEMBER_SIGNAL
310
  (void) signal(SIGPIPE, my_pipe_sig_handler);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
311 312 313
#endif
}

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
314 315
/* perform query on master */
my_bool STDCALL mysql_master_query(MYSQL *mysql, const char *q,
316
				   unsigned long length)
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
317 318 319 320
{
  DBUG_ENTER("mysql_master_query");
  if (mysql_master_send_query(mysql, q, length))
    DBUG_RETURN(1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
321
  DBUG_RETURN((*mysql->methods->read_query_result)(mysql));
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
322
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
323

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
324 325
my_bool STDCALL mysql_master_send_query(MYSQL *mysql, const char *q,
					unsigned long length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
326
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
327 328 329 330
  MYSQL *master = mysql->master;
  DBUG_ENTER("mysql_master_send_query");
  if (!master->net.vio && !mysql_real_connect(master,0,0,0,0,0,0,0))
    DBUG_RETURN(1);
331
  master->reconnect= 1;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
332 333
  mysql->last_used_con = master;
  DBUG_RETURN(simple_command(master, COM_QUERY, q, length, 1));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
334 335 336
}


hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
337 338 339
/* perform query on slave */
my_bool STDCALL mysql_slave_query(MYSQL *mysql, const char *q,
				  unsigned long length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
340
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
341 342 343
  DBUG_ENTER("mysql_slave_query");
  if (mysql_slave_send_query(mysql, q, length))
    DBUG_RETURN(1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
344
  DBUG_RETURN((*mysql->methods->read_query_result)(mysql));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
345 346 347
}


hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
348 349
my_bool STDCALL mysql_slave_send_query(MYSQL *mysql, const char *q,
				   unsigned long length)
350
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
351 352
  MYSQL* last_used_slave, *slave_to_use = 0;
  DBUG_ENTER("mysql_slave_send_query");
353

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
354 355 356 357 358 359 360 361 362 363
  if ((last_used_slave = mysql->last_used_slave))
    slave_to_use = last_used_slave->next_slave;
  else
    slave_to_use = mysql->next_slave;
  /*
    Next_slave is always safe to use - we have a circular list of slaves
    if there are no slaves, mysql->next_slave == mysql
  */
  mysql->last_used_con = mysql->last_used_slave = slave_to_use;
  if (!slave_to_use->net.vio && !mysql_real_connect(slave_to_use, 0,0,0,
364
						    0,0,0,0))
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
365
    DBUG_RETURN(1);
366
  slave_to_use->reconnect= 1;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
367 368
  DBUG_RETURN(simple_command(slave_to_use, COM_QUERY, q, length, 1));
}
369 370


hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
371 372 373
/* enable/disable parsing of all queries to decide
   if they go on master or slave */
void STDCALL mysql_enable_rpl_parse(MYSQL* mysql)
374
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
375
  mysql->options.rpl_parse = 1;
376 377
}

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
378
void STDCALL mysql_disable_rpl_parse(MYSQL* mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
379
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
380
  mysql->options.rpl_parse = 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
381 382
}

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
383 384
/* get the value of the parse flag */
int STDCALL mysql_rpl_parse_enabled(MYSQL* mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
385
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
386
  return mysql->options.rpl_parse;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
387 388
}

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
389 390
/*  enable/disable reads from master */
void STDCALL mysql_enable_reads_from_master(MYSQL* mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
391
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
392 393
  mysql->options.no_master_reads = 0;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
394

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
395
void STDCALL mysql_disable_reads_from_master(MYSQL* mysql)
396 397 398 399
{
  mysql->options.no_master_reads = 1;
}

peter@mysql.com's avatar
peter@mysql.com committed
400
/* get the value of the master read flag */
401
my_bool STDCALL mysql_reads_from_master_enabled(MYSQL* mysql)
402 403 404 405
{
  return !(mysql->options.no_master_reads);
}

406 407 408 409 410

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

static void expand_error(MYSQL* mysql, int error)
414 415
{
  char tmp[MYSQL_ERRMSG_SIZE];
416 417 418 419 420 421
  char *p;
  uint err_length;
  strmake(tmp, mysql->net.last_error, MYSQL_ERRMSG_SIZE-1);
  p = strmake(mysql->net.last_error, ER(error), MYSQL_ERRMSG_SIZE-1);
  err_length= (uint) (p - mysql->net.last_error);
  strmake(p, tmp, MYSQL_ERRMSG_SIZE-1 - err_length);
422 423 424
  mysql->net.last_errno = error;
}

425 426 427
/*
  This function assumes we have just called SHOW SLAVE STATUS and have
  read the given result and row
428
*/
429

430
static my_bool get_master(MYSQL* mysql, MYSQL_RES* res, MYSQL_ROW row)
431 432
{
  MYSQL* master;
433
  DBUG_ENTER("get_master");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
434
  if (mysql_num_fields(res) < 3)
435
    DBUG_RETURN(1); /* safety */
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
436

437
  /* use the same username and password as the original connection */
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
438
  if (!(master = spawn_init(mysql, row[0], atoi(row[2]), 0, 0)))
439
    DBUG_RETURN(1);
440
  mysql->master = master;
441
  DBUG_RETURN(0);
442 443
}

444 445 446 447

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

450
static my_bool get_slaves_from_master(MYSQL* mysql)
451
{
452 453
  MYSQL_RES* res = 0;
  MYSQL_ROW row;
454
  my_bool error = 1;
455
  int has_auth_info;
sasha@mysql.sashanet.com's avatar
sasha@mysql.sashanet.com committed
456
  int port_ind;
457
  DBUG_ENTER("get_slaves_from_master");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
458

459 460 461
  if (!mysql->net.vio && !mysql_real_connect(mysql,0,0,0,0,0,0,0))
  {
    expand_error(mysql, CR_PROBE_MASTER_CONNECT);
462
    DBUG_RETURN(1);
463
  }
464
  mysql->reconnect= 1;
465 466

  if (mysql_query(mysql, "SHOW SLAVE HOSTS") ||
467
      !(res = mysql_store_result(mysql)))
468 469
  {
    expand_error(mysql, CR_PROBE_SLAVE_HOSTS);
470
    DBUG_RETURN(1);
471 472
  }

473
  switch (mysql_num_fields(res)) {
sasha@mysql.sashanet.com's avatar
sasha@mysql.sashanet.com committed
474 475 476 477 478 479 480 481
  case 5:
    has_auth_info = 0;
    port_ind=2;
    break;
  case 7:
    has_auth_info = 1;
    port_ind=4;
    break;
482 483 484 485 486 487 488 489 490 491 492
  default:
    goto err;
  }

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

    if (has_auth_info)
    {
sasha@mysql.sashanet.com's avatar
sasha@mysql.sashanet.com committed
493 494
      tmp_user = row[2];
      tmp_pass = row[3];
495 496 497 498 499 500 501
    }
    else
    {
      tmp_user = mysql->user;
      tmp_pass = mysql->passwd;
    }

sasha@mysql.sashanet.com's avatar
sasha@mysql.sashanet.com committed
502
    if (!(slave = spawn_init(mysql, row[1], atoi(row[port_ind]),
503
			     tmp_user, tmp_pass)))
504
      goto err;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
505

506 507 508 509 510 511
    /* Now add slave into the circular linked list */
    slave->next_slave = mysql->next_slave;
    mysql->next_slave = slave;
  }
  error = 0;
err:
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
512
  if (res)
513
    mysql_free_result(res);
514
  DBUG_RETURN(error);
515 516
}

517

518
my_bool STDCALL mysql_rpl_probe(MYSQL* mysql)
519
{
520
  MYSQL_RES *res= 0;
521
  MYSQL_ROW row;
522
  my_bool error= 1;
523 524
  DBUG_ENTER("mysql_rpl_probe");

525 526 527 528 529
  /*
    First determine the replication role of the server we connected to
    the most reliable way to do this is to run SHOW SLAVE STATUS and see
    if we have a non-empty master host. This is still not fool-proof -
    it is not a sin to have a master that has a dormant slave thread with
peter@mysql.com's avatar
peter@mysql.com committed
530
    a non-empty master host. However, it is more reliable to check
531
    for empty master than whether the slave thread is actually running
532
  */
533
  if (mysql_query(mysql, "SHOW SLAVE STATUS") ||
534
      !(res = mysql_store_result(mysql)))
535 536
  {
    expand_error(mysql, CR_PROBE_SLAVE_STATUS);
537
    DBUG_RETURN(1);
538
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
539

540 541 542 543 544 545
  row= mysql_fetch_row(res);
  /*
    Check master host for emptiness/NULL
    For MySQL 4.0 it's enough to check for row[0]
  */
  if (row && row[0] && *(row[0]))
546 547
  {
    /* this is a slave, ask it for the master */
548
    if (get_master(mysql, res, row) || get_slaves_from_master(mysql))
549 550 551 552 553
      goto err;
  }
  else
  {
    mysql->master = mysql;
554
    if (get_slaves_from_master(mysql))
555 556 557 558 559
      goto err;
  }

  error = 0;
err:
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
560
  if (res)
561
    mysql_free_result(res);
562
  DBUG_RETURN(error);
563 564 565
}


566 567 568 569 570 571 572 573 574 575
/*
  Make a not so fool-proof decision on where the query should go, to
  the master or the slave. Ideally the user should always make this
  decision himself with mysql_master_query() or mysql_slave_query().
  However, to be able to more easily port the old code, we support the
  option of an educated guess - this should work for most applications,
  however, it may make the wrong decision in some particular cases. If
  that happens, the user would have to change the code to call
  mysql_master_query() or mysql_slave_query() explicitly in the place
  where we have made the wrong decision
576
*/
577

578 579
enum mysql_rpl_type
STDCALL mysql_rpl_query_type(const char* q, int len)
580
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
581
  const char *q_end= q + len;
582
  for (; q < q_end; ++q)
583 584
  {
    char c;
585
    if (my_isalpha(&my_charset_latin1, (c= *q)))
586
    {
587
      switch (my_tolower(&my_charset_latin1,c)) {
588 589 590 591 592 593 594
      case 'i':  /* insert */
      case 'u':  /* update or unlock tables */
      case 'l':  /* lock tables or load data infile */
      case 'd':  /* drop or delete */
      case 'a':  /* alter */
	return MYSQL_RPL_MASTER;
      case 'c':  /* create or check */
595
	return my_tolower(&my_charset_latin1,q[1]) == 'h' ? MYSQL_RPL_ADMIN :
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
596
	  MYSQL_RPL_MASTER;
597
      case 's': /* select or show */
598
	return my_tolower(&my_charset_latin1,q[1]) == 'h' ? MYSQL_RPL_ADMIN :
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
599
	  MYSQL_RPL_SLAVE;
600 601 602
      case 'f': /* flush */
      case 'r': /* repair */
      case 'g': /* grant */
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
603 604 605 606 607
	return MYSQL_RPL_ADMIN;
      default:
	return MYSQL_RPL_SLAVE;
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
608
  }
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
609
  return MYSQL_RPL_MASTER;		/* By default, send to master */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
610 611 612
}


hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
613 614 615 616
/**************************************************************************
  Connect to sql server
  If host == 0 then use localhost
**************************************************************************/
617

hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
618 619 620 621
#ifdef USE_OLD_FUNCTIONS
MYSQL * STDCALL
mysql_connect(MYSQL *mysql,const char *host,
	      const char *user, const char *passwd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
622
{
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
623 624
  MYSQL *res;
  mysql=mysql_init(mysql);			/* Make it thread safe */
625
  {
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
626 627 628 629 630 631
    DBUG_ENTER("mysql_connect");
    if (!(res=mysql_real_connect(mysql,host,user,passwd,NullS,0,NullS,0)))
    {
      if (mysql->free_me)
	my_free((gptr) mysql,MYF(0));
    }
632
    mysql->reconnect= 1;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
633
    DBUG_RETURN(res);
634
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
635
}
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
636
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
637

638

bk@work.mysql.com's avatar
bk@work.mysql.com committed
639
/**************************************************************************
peter@mysql.com's avatar
peter@mysql.com committed
640
  Change user and database
bk@work.mysql.com's avatar
bk@work.mysql.com committed
641
**************************************************************************/
642

643 644 645 646 647
int cli_read_change_user_result(MYSQL *mysql, char *buff, const char *passwd)
{
  NET *net= &mysql->net;
  ulong pkt_length;

648
  pkt_length= cli_safe_read(mysql);
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
  
  if (pkt_length == packet_error)
    return 1;

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

675

peter@mysql.com's avatar
peter@mysql.com committed
676
my_bool	STDCALL mysql_change_user(MYSQL *mysql, const char *user,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
677 678
				  const char *passwd, const char *db)
{
peter@mysql.com's avatar
peter@mysql.com committed
679
  char buff[512],*end=buff;
680
  int rc;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
681 682 683 684 685 686
  DBUG_ENTER("mysql_change_user");

  if (!user)
    user="";
  if (!passwd)
    passwd="";
peter@mysql.com's avatar
peter@mysql.com committed
687

688
  /* Store user into the buffer */
peter@mysql.com's avatar
peter@mysql.com committed
689
  end=strmov(end,user)+1;
peter@mysql.com's avatar
peter@mysql.com committed
690

691 692
  /* write scrambled password according to server capabilities */
  if (passwd[0])
peter@mysql.com's avatar
peter@mysql.com committed
693
  {
694
    if (mysql->server_capabilities & CLIENT_SECURE_CONNECTION)
peter@mysql.com's avatar
peter@mysql.com committed
695
    {
696 697 698
      *end++= SCRAMBLE_LENGTH;
      scramble(end, mysql->scramble, passwd);
      end+= SCRAMBLE_LENGTH;
peter@mysql.com's avatar
peter@mysql.com committed
699
    }
700
    else
701 702 703
    {
      scramble_323(end, mysql->scramble, passwd);
      end+= SCRAMBLE_LENGTH_323 + 1;
peter@mysql.com's avatar
peter@mysql.com committed
704
    }
peter@mysql.com's avatar
peter@mysql.com committed
705 706
  }
  else
707
    *end++= '\0';                               /* empty password */
peter@mysql.com's avatar
peter@mysql.com committed
708
  /* Add database if needed */
709
  end= strmov(end, db ? db : "") + 1;
peter@mysql.com's avatar
peter@mysql.com committed
710 711

  /* Write authentication package */
peter@mysql.com's avatar
peter@mysql.com committed
712
  simple_command(mysql,COM_CHANGE_USER, buff,(ulong) (end-buff),1);
peter@mysql.com's avatar
peter@mysql.com committed
713

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
  rc= (*mysql->methods->read_change_user_result)(mysql, buff, passwd);

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

    /* alloc new connect information */
    mysql->user=  my_strdup(user,MYF(MY_WME));
    mysql->passwd=my_strdup(passwd,MYF(MY_WME));
    mysql->db=    db ? my_strdup(db,MYF(MY_WME)) : 0;
  }
  DBUG_RETURN(rc);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
734 735
}

hf@deer.(none)'s avatar
hf@deer.(none) committed
736 737 738 739 740 741
#if defined(HAVE_GETPWUID) && defined(NO_GETPWUID_DECL)
struct passwd *getpwuid(uid_t);
char* getlogin(void);
#endif

#if defined(__NETWARE__)
742
/* Default to value of USER on NetWare, if unset use "UNKNOWN_USER" */
hf@deer.(none)'s avatar
hf@deer.(none) committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
void read_user_name(char *name)
{
  char *str=getenv("USER");
  strmake(name, str ? str : "UNKNOWN_USER", USERNAME_LENGTH);
}

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

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

#else /* If MSDOS || VMS */

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

#endif

789
my_bool handle_local_infile(MYSQL *mysql, const char *net_filename)
hf@deer.(none)'s avatar
hf@deer.(none) committed
790 791 792 793
{
  my_bool result= 1;
  uint packet_length=MY_ALIGN(mysql->net.max_packet-16,IO_SIZE);
  NET *net= &mysql->net;
794 795
  int readcount;
  void *li_ptr;          /* pass state to local_infile functions */
serg@serg.mylan's avatar
serg@serg.mylan committed
796
  char *buf;		/* buffer to be filled by local_infile_read */
monty@mysql.com's avatar
monty@mysql.com committed
797
  struct st_mysql_options *options= &mysql->options;
798 799 800
  DBUG_ENTER("handle_local_infile");

  /* check that we've got valid callback functions */
monty@mysql.com's avatar
monty@mysql.com committed
801 802 803 804
  if (!(options->local_infile_init &&
	options->local_infile_read &&
	options->local_infile_end &&
	options->local_infile_error))
hf@deer.(none)'s avatar
hf@deer.(none) committed
805
  {
806
    /* if any of the functions is invalid, set the default */
monty@mysql.com's avatar
monty@mysql.com committed
807
    mysql_set_local_infile_default(mysql);
hf@deer.(none)'s avatar
hf@deer.(none) committed
808 809
  }

810
  /* copy filename into local memory and allocate read buffer */
monty@mysql.com's avatar
monty@mysql.com committed
811 812 813 814 815 816
  if (!(buf=my_malloc(packet_length, MYF(0))))
  {
    strmov(net->sqlstate, unknown_sqlstate);
    strmov(net->last_error, ER(net->last_errno=CR_OUT_OF_MEMORY));
    DBUG_RETURN(1);
  }
817 818

  /* initialize local infile (open file, usually) */
819 820
  if ((*options->local_infile_init)(&li_ptr, net_filename,
    options->local_infile_userdata))
hf@deer.(none)'s avatar
hf@deer.(none) committed
821
  {
822
    VOID(my_net_write(net,"",0));               /* Server needs one packet */
hf@deer.(none)'s avatar
hf@deer.(none) committed
823 824
    net_flush(net);
    strmov(net->sqlstate, unknown_sqlstate);
monty@mysql.com's avatar
monty@mysql.com committed
825 826 827
    net->last_errno= (*options->local_infile_error)(li_ptr,
						    net->last_error,
						    sizeof(net->last_error)-1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
828 829 830
    goto err;
  }

831
  /* read blocks of data from local infile callback */
monty@mysql.com's avatar
monty@mysql.com committed
832 833 834
  while ((readcount =
	  (*options->local_infile_read)(li_ptr, buf,
					packet_length)) > 0)
hf@deer.(none)'s avatar
hf@deer.(none) committed
835 836 837
  {
    if (my_net_write(net,buf,readcount))
    {
monty@mysql.com's avatar
monty@mysql.com committed
838 839
      DBUG_PRINT("error",
		 ("Lost connection to MySQL server during LOAD DATA of local file"));
hf@deer.(none)'s avatar
hf@deer.(none) committed
840 841 842 843 844 845
      strmov(net->sqlstate, unknown_sqlstate);
      net->last_errno=CR_SERVER_LOST;
      strmov(net->last_error,ER(net->last_errno));
      goto err;
    }
  }
846

hf@deer.(none)'s avatar
hf@deer.(none) committed
847 848 849 850 851 852 853 854
  /* Send empty packet to mark end of file */
  if (my_net_write(net,"",0) || net_flush(net))
  {
    strmov(net->sqlstate, unknown_sqlstate);
    net->last_errno=CR_SERVER_LOST;
    sprintf(net->last_error,ER(net->last_errno),errno);
    goto err;
  }
855

hf@deer.(none)'s avatar
hf@deer.(none) committed
856 857
  if (readcount < 0)
  {
monty@mysql.com's avatar
monty@mysql.com committed
858 859 860
    net->last_errno= (*options->local_infile_error)(li_ptr,
						    net->last_error,
						    sizeof(net->last_error)-1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
861 862
    goto err;
  }
863

hf@deer.(none)'s avatar
hf@deer.(none) committed
864 865 866
  result=0;					/* Ok */

err:
867
  /* free up memory allocated with _init, usually */
monty@mysql.com's avatar
monty@mysql.com committed
868
  (*options->local_infile_end)(li_ptr);
869
  my_free(buf, MYF(0));
hf@deer.(none)'s avatar
hf@deer.(none) committed
870
  DBUG_RETURN(result);
871 872 873
}


monty@mysql.com's avatar
monty@mysql.com committed
874 875 876 877 878 879
/****************************************************************************
  Default handlers for LOAD LOCAL INFILE
****************************************************************************/

typedef struct st_default_local_infile
{
880 881
  int fd;
  int error_num;
monty@mysql.com's avatar
monty@mysql.com committed
882
  const char *filename;
883 884 885 886
  char error_msg[LOCAL_INFILE_ERROR_LEN];
} default_local_infile_data;


monty@mysql.com's avatar
monty@mysql.com committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
/*
  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
*/

905 906
static int default_local_infile_init(void **ptr, const char *filename,
             void *userdata __attribute__ ((unused)))
907 908
{
  default_local_infile_data *data;
monty@mysql.com's avatar
monty@mysql.com committed
909
  char tmp_name[FN_REFLEN];
910 911

  if (!(*ptr= data= ((default_local_infile_data *)
monty@mysql.com's avatar
monty@mysql.com committed
912 913
		     my_malloc(sizeof(default_local_infile_data),  MYF(0)))))
    return 1; /* out of memory */
914 915 916

  data->error_msg[0]= 0;
  data->error_num=    0;
monty@mysql.com's avatar
monty@mysql.com committed
917
  data->filename= filename;
918

monty@mysql.com's avatar
monty@mysql.com committed
919 920
  fn_format(tmp_name, filename, "", "", MY_UNPACK_FILENAME);
  if ((data->fd = my_open(tmp_name, O_RDONLY, MYF(0))) < 0)
921
  {
monty@mysql.com's avatar
monty@mysql.com committed
922
    data->error_num= my_errno;
923
    my_snprintf(data->error_msg, sizeof(data->error_msg)-1,
monty@mysql.com's avatar
monty@mysql.com committed
924 925
                EE(EE_FILENOTFOUND), tmp_name, data->error_num);
    return 1;
926 927 928 929 930
  }
  return 0; /* ok */
}


monty@mysql.com's avatar
monty@mysql.com committed
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
/*
  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)
947
{
monty@mysql.com's avatar
monty@mysql.com committed
948 949
  int count;
  default_local_infile_data*data = (default_local_infile_data *) ptr;
950

monty@mysql.com's avatar
monty@mysql.com committed
951 952 953 954 955 956 957 958
  if ((count= (int) my_read(data->fd, (byte *) buf, buf_len, MYF(0))) < 0)
  {
    data->error_num= EE_READ; /* the errmsg for not entire file read */
    my_snprintf(data->error_msg, sizeof(data->error_msg)-1,
		EE(EE_READ),
		data->filename, my_errno);
  }
  return count;
959 960 961
}


monty@mysql.com's avatar
monty@mysql.com committed
962 963 964 965 966 967 968 969 970 971 972 973
/*
  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)
974
{
monty@mysql.com's avatar
monty@mysql.com committed
975 976
  default_local_infile_data *data= (default_local_infile_data *) ptr;
  if (data)					/* If not error on open */
977
  {
monty@mysql.com's avatar
monty@mysql.com committed
978 979 980
    if (data->fd >= 0)
      my_close(data->fd, MYF(MY_WME));
    my_free(ptr, MYF(MY_WME));
981 982 983 984
  }
}


monty@mysql.com's avatar
monty@mysql.com committed
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
/*
  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
1000 1001
default_local_infile_error(void *ptr, char *error_msg, uint error_msg_len)
{
monty@mysql.com's avatar
monty@mysql.com committed
1002 1003 1004
  default_local_infile_data *data = (default_local_infile_data *) ptr;
  if (data)					/* If not error on open */
  {
1005 1006 1007
    strmake(error_msg, data->error_msg, error_msg_len);
    return data->error_num;
  }
monty@mysql.com's avatar
monty@mysql.com committed
1008 1009 1010
  /* 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;
1011 1012 1013
}


monty@mysql.com's avatar
monty@mysql.com committed
1014
void
1015
mysql_set_local_infile_handler(MYSQL *mysql,
1016 1017
                               int (*local_infile_init)(void **, const char *,
                               void *),
1018
                               int (*local_infile_read)(void *, char *, uint),
monty@mysql.com's avatar
monty@mysql.com committed
1019
                               void (*local_infile_end)(void *),
1020 1021
                               int (*local_infile_error)(void *, char *, uint),
                               void *userdata)
1022
{
monty@mysql.com's avatar
monty@mysql.com committed
1023 1024 1025 1026
  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;
1027
  mysql->options.local_infile_userdata = userdata;
1028 1029 1030
}


monty@mysql.com's avatar
monty@mysql.com committed
1031
void mysql_set_local_infile_default(MYSQL *mysql)
1032 1033 1034 1035 1036
{
  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;
hf@deer.(none)'s avatar
hf@deer.(none) committed
1037 1038 1039
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1040
/**************************************************************************
1041 1042
  Do a query. If query returned rows, free old rows.
  Read data by mysql_store_result or by repeat call of mysql_fetch_row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1043 1044 1045 1046 1047 1048 1049 1050
**************************************************************************/

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

hf@deer.(none)'s avatar
hf@deer.(none) committed
1051

1052
static MYSQL* spawn_init(MYSQL* parent, const char* host,
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1053 1054
			 unsigned int port, const char* user,
			 const char* passwd)
1055 1056
{
  MYSQL* child;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
  DBUG_ENTER("spawn_init");
  if (!(child= mysql_init(0)))
    DBUG_RETURN(0);

  child->options.user= my_strdup((user) ? user :
				 (parent->user ? parent->user :
				  parent->options.user), MYF(0));
  child->options.password= my_strdup((passwd) ? passwd :
				     (parent->passwd ?
				      parent->passwd :
				      parent->options.password), MYF(0));
  child->options.port= port;
  child->options.host= my_strdup((host) ? host :
				 (parent->host ?
				  parent->host :
				  parent->options.host), MYF(0));
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1073
  if (parent->db)
1074
    child->options.db= my_strdup(parent->db, MYF(0));
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1075
  else if (parent->options.db)
1076
    child->options.db= my_strdup(parent->options.db, MYF(0));
1077

1078 1079 1080 1081 1082 1083
  /*
    rpl_pivot is set to 1 in mysql_init();  Reset it as we are not doing
    replication here
  */
  child->rpl_pivot= 0;
  DBUG_RETURN(child);
1084 1085 1086 1087 1088
}


int
STDCALL mysql_set_master(MYSQL* mysql, const char* host,
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1089 1090
			 unsigned int port, const char* user,
			 const char* passwd)
1091 1092 1093
{
  if (mysql->master != mysql && !mysql->master->rpl_pivot)
    mysql_close(mysql->master);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1094
  if (!(mysql->master = spawn_init(mysql, host, port, user, passwd)))
1095 1096 1097 1098
    return 1;
  return 0;
}

1099

1100 1101
int
STDCALL mysql_add_slave(MYSQL* mysql, const char* host,
1102 1103 1104
			unsigned int port,
			const char* user,
			const char* passwd)
1105 1106
{
  MYSQL* slave;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1107
  if (!(slave = spawn_init(mysql, host, port, user, passwd)))
1108 1109 1110 1111 1112 1113
    return 1;
  slave->next_slave = mysql->next_slave;
  mysql->next_slave = slave;
  return 0;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1114
/**************************************************************************
1115
  Return next field of the query results
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
**************************************************************************/

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

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1143
/*************************************************************************
1144 1145 1146
  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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
*************************************************************************/

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

1167

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1168
/*****************************************************************************
1169
  List all databases
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
*****************************************************************************/

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


/*****************************************************************************
1186 1187
  List all tables in a database
  If wild is given then only the tables matching wild is returned
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
*****************************************************************************/

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

1202

1203
MYSQL_FIELD *cli_list_fields(MYSQL *mysql)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1204 1205 1206 1207 1208 1209
{
  MYSQL_DATA *query;
  if (!(query= cli_read_rows(mysql,(MYSQL_FIELD*) 0, 
			     protocol_41(mysql) ? 8 : 6)))
    return NULL;

1210
  mysql->field_count= (uint) query->rows;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1211
  return unpack_fields(query,&mysql->field_alloc,
1212
		       mysql->field_count, 1, mysql->server_capabilities);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1213 1214 1215
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1216
/**************************************************************************
1217 1218 1219 1220
  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"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1221 1222 1223
**************************************************************************/

MYSQL_RES * STDCALL
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1224
mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1225
{
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1226 1227
  MYSQL_RES   *result;
  MYSQL_FIELD *fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1228 1229 1230 1231 1232
  char	     buff[257],*end;
  DBUG_ENTER("mysql_list_fields");
  DBUG_PRINT("enter",("table: '%s'  wild: '%s'",table,wild ? wild : ""));

  end=strmake(strmake(buff, table,128)+1,wild ? wild : "",128);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1233
  free_old_query(mysql);
1234
  if (simple_command(mysql,COM_FIELD_LIST,buff,(ulong) (end-buff),1) ||
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1235
      !(fields= (*mysql->methods->list_fields)(mysql)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1236 1237 1238 1239 1240
    DBUG_RETURN(NULL);

  if (!(result = (MYSQL_RES *) my_malloc(sizeof(MYSQL_RES),
					 MYF(MY_WME | MY_ZEROFILL))))
    DBUG_RETURN(NULL);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1241

1242
  result->methods= mysql->methods;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1243 1244
  result->field_alloc=mysql->field_alloc;
  mysql->fields=0;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1245 1246
  result->field_count = mysql->field_count;
  result->fields= fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
  result->eof=1;
  DBUG_RETURN(result);
}

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

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

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

1278

1279
#ifdef USE_OLD_FUNCTIONS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1280 1281 1282 1283 1284
int  STDCALL
mysql_create_db(MYSQL *mysql, const char *db)
{
  DBUG_ENTER("mysql_createdb");
  DBUG_PRINT("enter",("db: %s",db));
1285
  DBUG_RETURN(simple_command(mysql,COM_CREATE_DB,db, (ulong) strlen(db),0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1286 1287 1288 1289 1290 1291 1292 1293
}


int  STDCALL
mysql_drop_db(MYSQL *mysql, const char *db)
{
  DBUG_ENTER("mysql_drop_db");
  DBUG_PRINT("enter",("db: %s",db));
1294
  DBUG_RETURN(simple_command(mysql,COM_DROP_DB,db,(ulong) strlen(db),0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1295
}
1296
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1297 1298 1299


int STDCALL
1300
mysql_shutdown(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1301
{
1302
  uchar level[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1303
  DBUG_ENTER("mysql_shutdown");
1304
  level[0]= (uchar) shutdown_level;
1305
  DBUG_RETURN(simple_command(mysql, COM_SHUTDOWN, (char *)level, 1, 0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
}


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

1318

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1319 1320 1321
int STDCALL
mysql_kill(MYSQL *mysql,ulong pid)
{
1322
  char buff[4];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1323 1324
  DBUG_ENTER("mysql_kill");
  int4store(buff,pid);
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
  DBUG_RETURN(simple_command(mysql,COM_PROCESS_KILL,buff,sizeof(buff),0));
}


int STDCALL
mysql_set_server_option(MYSQL *mysql, enum enum_mysql_set_option option)
{
  char buff[2];
  DBUG_ENTER("mysql_set_server_option");
  int2store(buff, (uint) option);
  DBUG_RETURN(simple_command(mysql, COM_SET_OPTION, buff, sizeof(buff), 0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
}


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

1346

konstantin@oak.local's avatar
konstantin@oak.local committed
1347
const char *cli_read_statistics(MYSQL *mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1348 1349 1350 1351
{
  mysql->net.read_pos[mysql->packet_length]=0;	/* End of stat string */
  if (!mysql->net.read_pos[0])
  {
1352
    strmov(mysql->net.sqlstate, unknown_sqlstate);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1353 1354 1355 1356
    mysql->net.last_errno=CR_WRONG_HOST_INFO;
    strmov(mysql->net.last_error, ER(mysql->net.last_errno));
    return mysql->net.last_error;
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
1357 1358 1359
  return (char*) mysql->net.read_pos;
}

1360

hf@deer.(none)'s avatar
hf@deer.(none) committed
1361 1362 1363 1364 1365 1366
const char * STDCALL
mysql_stat(MYSQL *mysql)
{
  DBUG_ENTER("mysql_stat");
  if (simple_command(mysql,COM_STATISTICS,0,0,0))
    return mysql->net.last_error;
konstantin@oak.local's avatar
konstantin@oak.local committed
1367
  DBUG_RETURN((*mysql->methods->read_statistics)(mysql));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1368 1369 1370 1371 1372 1373
}


int STDCALL
mysql_ping(MYSQL *mysql)
{
1374
  int res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1375
  DBUG_ENTER("mysql_ping");
1376 1377 1378 1379
  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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1380 1381 1382
}


monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1383
const char * STDCALL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1384 1385 1386 1387 1388 1389
mysql_get_server_info(MYSQL *mysql)
{
  return((char*) mysql->server_version);
}


monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1390
const char * STDCALL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
mysql_get_host_info(MYSQL *mysql)
{
  return(mysql->host_info);
}


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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1403
const char * STDCALL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1404 1405 1406 1407 1408
mysql_get_client_info(void)
{
  return (char*) MYSQL_SERVER_VERSION;
}

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1409 1410 1411 1412 1413
ulong STDCALL mysql_get_client_version(void)
{
  return MYSQL_VERSION_ID;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
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;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1429
MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1430 1431 1432 1433
{
  return res->data_cursor;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1434
MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1435 1436 1437 1438 1439 1440 1441 1442
{
  return (res)->current_field;
}

/* MYSQL */

unsigned int STDCALL mysql_field_count(MYSQL *mysql)
{
1443
  return mysql->last_used_con->field_count;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1444 1445 1446 1447
}

my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql)
{
1448
  return mysql->last_used_con->affected_rows;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1449 1450 1451 1452
}

my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql)
{
1453
  return mysql->last_used_con->insert_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1454 1455
}

1456 1457 1458 1459 1460
const char *STDCALL mysql_sqlstate(MYSQL *mysql)
{
  return mysql->net.sqlstate;
}

1461 1462 1463 1464 1465
uint STDCALL mysql_warning_count(MYSQL *mysql)
{
  return mysql->warning_count;
}

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1466
const char *STDCALL mysql_info(MYSQL *mysql)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1467
{
1468
  return mysql->info;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1469 1470 1471 1472 1473 1474 1475 1476 1477
}

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

const char * STDCALL mysql_character_set_name(MYSQL *mysql)
{
bar@mysql.com's avatar
bar@mysql.com committed
1478
  return mysql->charset->csname;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479 1480
}

1481
void STDCALL mysql_get_character_set_info(MYSQL *mysql, MY_CHARSET_INFO *csinfo)
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
{
  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;
}
monty@mysql.com's avatar
monty@mysql.com committed
1496

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1497 1498 1499 1500 1501 1502 1503 1504 1505
uint STDCALL mysql_thread_safe(void)
{
#ifdef THREAD
  return 1;
#else
  return 0;
#endif
}

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1516
/****************************************************************************
1517
  Some support functions
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1518 1519
****************************************************************************/

1520 1521 1522 1523 1524 1525 1526 1527 1528
/*
  Functions called my my_net_init() to set some application specific variables
*/

void my_net_local_init(NET *net)
{
  net->max_packet=   (uint) net_buffer_length;
  net->read_timeout= (uint) net_read_timeout;
  net->write_timeout=(uint) net_write_timeout;
1529
  net->retry_count=  1;
1530 1531 1532
  net->max_packet_size= max(net_buffer_length, max_allowed_packet);
}

monty@mysql.com's avatar
monty@mysql.com committed
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
/*
  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.
*/

bar@mysql.com's avatar
bar@mysql.com committed
1553 1554
ulong STDCALL
mysql_hex_string(char *to, const char *from, ulong length)
monty@mysql.com's avatar
monty@mysql.com committed
1555 1556 1557 1558 1559 1560
{
  char *to0= to;
  const char *end;
            
  for (end= from + length; from < end; from++)
  {
monty@mysql.com's avatar
monty@mysql.com committed
1561 1562
    *to++= _dig_vec_upper[((unsigned char) *from) >> 4];
    *to++= _dig_vec_upper[((unsigned char) *from) & 0x0F];
monty@mysql.com's avatar
monty@mysql.com committed
1563 1564 1565 1566 1567
  }
  *to= '\0';
  return (ulong) (to-to0);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1568
/*
1569 1570 1571
  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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1572 1573 1574 1575 1576
*/

ulong STDCALL
mysql_escape_string(char *to,const char *from,ulong length)
{
serg@serg.mylan's avatar
serg@serg.mylan committed
1577
  return escape_string_for_mysql(default_charset_info, to, 0, from, length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1578 1579 1580 1581 1582 1583
}

ulong STDCALL
mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
			 ulong length)
{
1584 1585
  if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
    return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
1586
  return escape_string_for_mysql(mysql->charset, to, 0, from, length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
}


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

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

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

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

/********************************************************************
1693
 Implementation of new client API for 4.1 version.
1694

1695
 mysql_stmt_* are real prototypes used by applications.
1696

1697 1698 1699 1700 1701
 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.
1702 1703
*********************************************************************/

1704
/******************* Declarations ***********************************/
1705

1706
/* Default number of rows fetched per one COM_STMT_FETCH command. */
1707

monty@mysql.com's avatar
monty@mysql.com committed
1708
#define DEFAULT_PREFETCH_ROWS (ulong) 1
1709

1710
/*
1711 1712 1713 1714 1715
  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)
1716 1717
*/

1718 1719
static int stmt_read_row_unbuffered(MYSQL_STMT *stmt, unsigned char **row);
static int stmt_read_row_buffered(MYSQL_STMT *stmt, unsigned char **row);
1720
static int stmt_read_row_from_cursor(MYSQL_STMT *stmt, unsigned char **row);
1721
static int stmt_read_row_no_data(MYSQL_STMT *stmt, unsigned char **row);
1722
static int stmt_read_row_no_result_set(MYSQL_STMT *stmt, unsigned char **row);
1723

1724 1725 1726 1727 1728
/*
  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);
1729
static my_bool setup_one_fetch_function(MYSQL_BIND *bind, MYSQL_FIELD *field);
1730

1731 1732 1733 1734
/* Auxilary function used to reset statement handle. */

#define RESET_SERVER_SIDE 1
#define RESET_LONG_DATA 2
1735
#define RESET_STORE_RESULT 4
1736 1737 1738

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

1739 1740 1741 1742 1743 1744
/*
  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) */
1745
#define MAX_DATE_REP_LENGTH 5
1746 1747 1748 1749 1750

/*
  1 (length) + 1 (is negative) + 4 (day count) + 1 (hour)
  + 1 (minute) + 1 (seconds) + 4 (microseconds)
*/
1751
#define MAX_TIME_REP_LENGTH 13
1752 1753 1754 1755 1756

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

1759
#define MAX_DOUBLE_STRING_REP_LENGTH 331
1760

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
/* 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

1775
/**************** Misc utility functions ****************************/
1776 1777

/*
1778
  Reallocate the NET package to have at least length bytes available.
1779

1780
  SYNPOSIS
1781 1782 1783 1784
    my_realloc_str()
    net                 The NET structure to modify.
    length              Ensure that net->buff has space for at least
                        this number of bytes.
1785

1786
  RETURN VALUES
1787 1788 1789
    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.
1790 1791
*/

1792
static my_bool my_realloc_str(NET *net, ulong length)
1793
{
1794 1795 1796 1797
  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)
1798
  {
1799 1800
    res= net_realloc(net, buf_length + length);
    net->write_pos= net->buff+ buf_length;
1801
  }
1802
  DBUG_RETURN(res);
1803 1804 1805
}


1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
/* Clear possible error statee of struct NET */

static void net_clear_error(NET *net)
{
  if (net->last_errno)
  {
    net->last_errno= 0;
    net->last_error[0]= '\0';
    strmov(net->sqlstate, not_error_sqlstate);
  }
}

1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
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);
  }
}

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
/*
  Set statement error code, sqlstate, and error message
  from given errcode and sqlstate.
*/

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

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

  DBUG_VOID_RETURN;
}


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

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

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

  DBUG_VOID_RETURN;
}
1866

1867
/*
1868
  Read and unpack server reply to COM_STMT_PREPARE command (sent from
1869
  mysql_stmt_prepare).
1870

1871 1872 1873 1874
  SYNOPSIS
    cli_read_prepare_result()
    mysql   connection handle
    stmt    statement handle
1875 1876 1877 1878

  RETURN VALUES
    0	ok
    1	error
1879 1880
*/

1881
my_bool cli_read_prepare_result(MYSQL *mysql, MYSQL_STMT *stmt)
1882 1883
{
  uchar *pos;
1884 1885
  uint field_count, param_count;
  ulong packet_length;
1886
  MYSQL_DATA *fields_data;
1887
  DBUG_ENTER("cli_read_prepare_result");
1888

1889
  mysql= mysql->last_used_con;
1890
  if ((packet_length= cli_safe_read(mysql)) == packet_error)
1891
    DBUG_RETURN(1);
monty@mysql.com's avatar
monty@mysql.com committed
1892
  mysql->warning_count= 0;
1893

1894
  pos= (uchar*) mysql->net.read_pos;
1895
  stmt->stmt_id= uint4korr(pos+1); pos+= 5;
1896
  /* Number of columns in result set */
1897
  field_count=   uint2korr(pos);   pos+= 2;
1898
  /* Number of placeholders in the statement */
1899
  param_count=   uint2korr(pos);   pos+= 2;
monty@mysql.com's avatar
monty@mysql.com committed
1900 1901
  if (packet_length >= 12)
    mysql->warning_count= uint2korr(pos+1);
1902

1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
  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);
  }

1913 1914 1915 1916
  if (field_count != 0)
  {
    if (!(mysql->server_status & SERVER_STATUS_AUTOCOMMIT))
      mysql->server_status|= SERVER_STATUS_IN_TRANS;
1917

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1918
    if (!(fields_data= (*mysql->methods->read_rows)(mysql,(MYSQL_FIELD*)0,7)))
1919 1920 1921 1922 1923 1924
      DBUG_RETURN(1);
    if (!(stmt->fields= unpack_fields(fields_data,&stmt->mem_root,
				      field_count,0,
				      mysql->server_capabilities)))
      DBUG_RETURN(1);
  }
monty@mysql.com's avatar
monty@mysql.com committed
1925
  stmt->field_count=  field_count;
1926
  stmt->param_count=  (ulong) param_count;
monty@mysql.com's avatar
monty@mysql.com committed
1927 1928
  DBUG_PRINT("exit",("field_count: %u  param_count: %u  warning_count: %u",
                     field_count, param_count, (uint) mysql->warning_count));
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1929

1930 1931 1932 1933 1934
  DBUG_RETURN(0);
}


/*
1935 1936
  Allocate memory and init prepared statement structure.

1937 1938
  SYNOPSIS
    mysql_stmt_init()
1939 1940 1941 1942 1943 1944 1945
    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
paul@ice.snake.net's avatar
paul@ice.snake.net committed
1946
    handle provided to this call: its lifetime is limited by lifetime
1947 1948 1949 1950 1951 1952
    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()),
paul@ice.snake.net's avatar
paul@ice.snake.net committed
1953
    - close statement handle and free its memory (mysql_stmt_close()),
1954 1955 1956 1957 1958
    - 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).
1959

1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
  RETURN VALUE
    statement structure upon success and NULL if out of
    memory
*/

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

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

1978
  init_alloc_root(&stmt->mem_root, 2048, 2048);
1979 1980
  init_alloc_root(&stmt->result.alloc, 4096, 4096);
  stmt->result.alloc.min_malloc= sizeof(MYSQL_ROWS);
1981 1982
  mysql->stmts= list_add(mysql->stmts, &stmt->list);
  stmt->list.data= stmt;
1983
  stmt->state= MYSQL_STMT_INIT_DONE;
1984
  stmt->mysql= mysql;
1985
  stmt->read_row_func= stmt_read_row_no_result_set;
1986
  stmt->prefetch_rows= DEFAULT_PREFETCH_ROWS;
1987
  strmov(stmt->sqlstate, not_error_sqlstate);
1988
  /* The rest of statement members was bzeroed inside malloc */
1989 1990 1991 1992

  DBUG_RETURN(stmt);
}

1993

1994
/*
1995 1996
  Prepare server side statement with query.

1997 1998
  SYNOPSIS
    mysql_stmt_prepare()
1999 2000 2001
    stmt    statement handle
    query   statement to prepare
    length  statement length
2002 2003

  DESCRIPTION
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
    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
2017
    structure on the server and free old statement data
2018
  - then send the query to server and get back number of placeholders,
2019
    number of columns in result set (if any), and result set metadata.
2020
    At the same time allocate memory for input and output parameters
2021
    to have less checks in mysql_stmt_bind_{param, result}.
2022

2023 2024
  RETURN VALUES
    0  success
2025
   !0  error
2026 2027
*/

2028 2029
int STDCALL
mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, ulong length)
2030
{
2031 2032 2033
  MYSQL *mysql= stmt->mysql;
  DBUG_ENTER("mysql_stmt_prepare");

2034
  if (!mysql)
2035
  {
2036 2037
    /* mysql can be reset in mysql_close called from mysql_reconnect */
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
2038
    DBUG_RETURN(1);
2039
  }
2040 2041 2042 2043

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

2046
    if (reset_stmt_handle(stmt, RESET_LONG_DATA | RESET_STORE_RESULT))
2047
      DBUG_RETURN(1);
2048
    /*
2049
      These members must be reset for API to
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
      function in case of error or misuse.
    */
    stmt->bind_param_done= stmt->bind_result_done= FALSE;
    stmt->param_count= stmt->field_count= 0;
    stmt->last_errno= 0;
    stmt->last_error[0]= '\0';
    free_root(&stmt->mem_root, MYF(MY_KEEP_PREALLOC));

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

2073
  if (stmt_command(mysql, COM_STMT_PREPARE, query, length, stmt))
2074
  {
2075 2076 2077
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                    mysql->net.sqlstate);
    DBUG_RETURN(1);
2078 2079
  }

hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2080
  if ((*mysql->methods->read_prepare_result)(mysql, stmt))
2081 2082 2083
  {
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                    mysql->net.sqlstate);
2084
    DBUG_RETURN(1);
2085
  }
hf@deer.(none)'s avatar
hf@deer.(none) committed
2086

2087
  /*
2088
    alloc_root will return valid address even in case when param_count
2089 2090 2091 2092
    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.
  */
hf@deer.(none)'s avatar
hf@deer.(none) committed
2093 2094
  if (!(stmt->params= (MYSQL_BIND *) alloc_root(&stmt->mem_root,
						sizeof(MYSQL_BIND)*
2095
                                                (stmt->param_count +
hf@deer.(none)'s avatar
hf@deer.(none) committed
2096 2097 2098
                                                 stmt->field_count))))
  {
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
2099
    DBUG_RETURN(1);
hf@deer.(none)'s avatar
hf@deer.(none) committed
2100 2101
  }
  stmt->bind= stmt->params + stmt->param_count;
2102
  stmt->state= MYSQL_STMT_PREPARE_DONE;
2103
  DBUG_PRINT("info", ("Parameter count: %ld", stmt->param_count));
2104
  DBUG_RETURN(0);
2105 2106
}

2107
/*
2108 2109 2110 2111
  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.
2112 2113
*/

2114
static unsigned int alloc_stmt_fields(MYSQL_STMT *stmt)
2115
{
2116 2117
  MYSQL_FIELD *fields, *field, *end;
  MEM_ROOT *alloc= &stmt->mem_root;
2118
  MYSQL *mysql= stmt->mysql->last_used_con;
2119

2120
  stmt->field_count= mysql->field_count;
2121

2122
  /*
2123
    Get the field information for non-select statements
2124 2125
    like SHOW and DESCRIBE commands
  */
2126
  if (!(stmt->fields= (MYSQL_FIELD *) alloc_root(alloc,
2127
						 sizeof(MYSQL_FIELD) *
2128 2129
						 stmt->field_count)) ||
      !(stmt->bind= (MYSQL_BIND *) alloc_root(alloc,
2130 2131
					      sizeof(MYSQL_BIND) *
					      stmt->field_count)))
2132
    return 0;
2133 2134

  for (fields= mysql->fields, end= fields+stmt->field_count,
2135
	 field= stmt->fields;
2136 2137 2138 2139 2140 2141 2142
       field && fields < end; fields++, field++)
  {
    field->db       = strdup_root(alloc,fields->db);
    field->table    = strdup_root(alloc,fields->table);
    field->org_table= strdup_root(alloc,fields->org_table);
    field->name     = strdup_root(alloc,fields->name);
    field->org_name = strdup_root(alloc,fields->org_name);
2143
    field->charsetnr= fields->charsetnr;
2144 2145 2146 2147 2148 2149 2150
    field->length   = fields->length;
    field->type     = fields->type;
    field->flags    = fields->flags;
    field->decimals = fields->decimals;
    field->def      = fields->def ? strdup_root(alloc,fields->def): 0;
    field->max_length= 0;
  }
2151 2152
  return stmt->field_count;
}
2153

2154 2155 2156

/*
  Update result set columns metadata if it was sent again in
2157
  reply to COM_STMT_EXECUTE.
2158 2159 2160 2161 2162 2163 2164
*/

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;
2165
  MYSQL_BIND *bind= stmt->bind_result_done ? stmt->bind : 0;
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175

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

  for (; field < field_end; ++field, ++stmt_field)
  {
    stmt_field->charsetnr= field->charsetnr;
    stmt_field->length   = field->length;
    stmt_field->type     = field->type;
    stmt_field->flags    = field->flags;
    stmt_field->decimals = field->decimals;
2176 2177 2178 2179 2180
    if (bind)
    {
      /* Ignore return value: it should be 0 if bind_result succeeded. */
      (void) setup_one_fetch_function(bind++, stmt_field);
    }
2181 2182 2183
  }
}

2184
/*
2185 2186 2187 2188 2189 2190 2191 2192 2193
  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
2194
    mysql_stmt_field_count(): if number of fields is not zero, you can call
2195 2196 2197 2198
    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
2199
      mysql_stmt_field_count())
2200 2201 2202 2203
    - 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.
2204 2205 2206 2207 2208 2209

  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
2210 2211 2212
*/

MYSQL_RES * STDCALL
2213
mysql_stmt_result_metadata(MYSQL_STMT *stmt)
2214 2215
{
  MYSQL_RES *result;
2216
  DBUG_ENTER("mysql_stmt_result_metadata");
2217

2218 2219 2220 2221 2222 2223 2224 2225 2226
  /*
    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))))
2227
  {
2228 2229 2230
    set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
    DBUG_RETURN(0);
  }
2231

2232 2233
  result->methods=	stmt->mysql->methods;
  result->eof=		1;                      /* Marker for buffered */
2234 2235
  result->fields=	stmt->fields;
  result->field_count=	stmt->field_count;
2236
  /* The rest of members of 'result' was bzeroed inside malloc */
2237
  DBUG_RETURN(result);
2238 2239
}

2240

2241
/*
2242 2243
  Returns parameter columns meta information in the form of
  result set.
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256

  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.
2257 2258 2259
*/

MYSQL_RES * STDCALL
2260
mysql_stmt_param_metadata(MYSQL_STMT *stmt)
2261
{
2262
  DBUG_ENTER("mysql_stmt_param_metadata");
2263

2264 2265 2266 2267
  if (!stmt->param_count)
    DBUG_RETURN(0);

  /*
2268 2269
    TODO: Fix this when server sends the information.
    Till then keep a dummy prototype.
2270 2271 2272 2273 2274
  */
  DBUG_RETURN(0); 
}


2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
/* Store type of parameter in network buffer. */

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


2285 2286
/*
  Functions to store parameter data in network packet.
2287

2288 2289 2290 2291 2292
  SYNOPSIS
    store_param_xxx()
    net			MySQL NET connection
    param		MySQL bind param

2293
  DESCRIPTION
2294 2295 2296 2297 2298
    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).
2299
*/
2300 2301 2302

static void store_param_tinyint(NET *net, MYSQL_BIND *param)
{
2303
  *(net->write_pos++)= *(uchar *) param->buffer;
2304 2305
}

2306 2307 2308 2309 2310 2311
static void store_param_short(NET *net, MYSQL_BIND *param)
{
  short value= *(short*) param->buffer;
  int2store(net->write_pos,value);
  net->write_pos+=2;
}
2312

2313
static void store_param_int32(NET *net, MYSQL_BIND *param)
2314
{
2315 2316 2317 2318
  int32 value= *(int32*) param->buffer;
  int4store(net->write_pos,value);
  net->write_pos+=4;
}
2319

2320 2321 2322 2323 2324 2325
static void store_param_int64(NET *net, MYSQL_BIND *param)
{
  longlong value= *(longlong*) param->buffer;
  int8store(net->write_pos,value);
  net->write_pos+= 8;
}
2326

2327 2328 2329 2330 2331
static void store_param_float(NET *net, MYSQL_BIND *param)
{
  float value= *(float*) param->buffer;
  float4store(net->write_pos, value);
  net->write_pos+= 4;
2332 2333
}

2334 2335 2336 2337 2338 2339
static void store_param_double(NET *net, MYSQL_BIND *param)
{
  double value= *(double*) param->buffer;
  float8store(net->write_pos, value);
  net->write_pos+= 8;
}
2340

2341 2342 2343
static void store_param_time(NET *net, MYSQL_BIND *param)
{
  MYSQL_TIME *tm= (MYSQL_TIME *) param->buffer;
2344
  char buff[MAX_TIME_REP_LENGTH], *pos;
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
  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)
2355
    length= 12;
2356 2357 2358 2359
  else if (tm->hour || tm->minute || tm->second || tm->day)
    length= 8;
  else
    length= 0;
2360
  buff[0]= (char) length++;
2361 2362 2363 2364 2365 2366
  memcpy((char *)net->write_pos, buff, length);
  net->write_pos+= length;
}

static void net_store_datetime(NET *net, MYSQL_TIME *tm)
{
2367
  char buff[MAX_DATETIME_REP_LENGTH], *pos;
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
  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;
2387
  buff[0]= (char) length++;
2388 2389 2390 2391 2392 2393
  memcpy((char *)net->write_pos, buff, length);
  net->write_pos+= length;
}

static void store_param_date(NET *net, MYSQL_BIND *param)
{
2394 2395 2396
  MYSQL_TIME tm= *((MYSQL_TIME *) param->buffer);
  tm.hour= tm.minute= tm.second= tm.second_part= 0;
  net_store_datetime(net, &tm);
2397 2398 2399 2400 2401 2402 2403
}

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

2405
static void store_param_str(NET *net, MYSQL_BIND *param)
2406
{
2407 2408
  /* param->length is always set in mysql_stmt_bind_param */
  ulong length= *param->length;
2409 2410
  char *to= (char *) net_store_length((char *) net->write_pos, length);
  memcpy(to, param->buffer, length);
2411
  net->write_pos= (uchar*) to+length;
2412 2413
}

2414

2415
/*
2416 2417 2418 2419 2420 2421 2422 2423 2424
  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
2425 2426
    if a parameter is NULL. Unlike bit string in result set row, here
    we don't have reserved bits for OK/error packet.
2427 2428
*/

2429
static void store_param_null(NET *net, MYSQL_BIND *param)
2430
{
2431
  uint pos= param->param_number;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2432
  net->buff[pos/8]|=  (uchar) (1 << (pos & 7));
2433
}
2434 2435 2436


/*
2437 2438 2439
  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.
2440 2441
*/

2442
static my_bool store_param(MYSQL_STMT *stmt, MYSQL_BIND *param)
2443
{
2444
  NET *net= &stmt->mysql->net;
2445
  DBUG_ENTER("store_param");
2446 2447 2448 2449 2450 2451
  DBUG_PRINT("enter",("type: %d, buffer:%lx, length: %lu  is_null: %d",
		      param->buffer_type,
		      param->buffer ? param->buffer : "0", *param->length,
		      *param->is_null));

  if (*param->is_null)
2452 2453
    store_param_null(net, param);
  else
venu@myvenu.com's avatar
venu@myvenu.com committed
2454
  {
2455 2456
    /*
      Param->length should ALWAYS point to the correct length for the type
2457
      Either to the length pointer given by the user or param->buffer_length
2458
    */
2459
    if ((my_realloc_str(net, *param->length)))
2460
    {
2461
      set_stmt_error(stmt, net->last_errno, unknown_sqlstate);
venu@myvenu.com's avatar
venu@myvenu.com committed
2462
      DBUG_RETURN(1);
2463
    }
2464
    (*param->store_param_func)(net, param);
venu@myvenu.com's avatar
venu@myvenu.com committed
2465 2466
  }
  DBUG_RETURN(0);
2467 2468
}

2469

2470
/*
2471
  Auxilary function to send COM_STMT_EXECUTE packet to server and read reply.
2472
  Used from cli_stmt_execute, which is in turn used by mysql_stmt_execute.
2473 2474
*/

2475
static my_bool execute(MYSQL_STMT *stmt, char *packet, ulong length)
2476
{
2477 2478
  MYSQL *mysql= stmt->mysql;
  NET	*net= &mysql->net;
2479
  char buff[4 /* size of stmt id */ +
2480
            5 /* execution flags */];
2481 2482
  my_bool res;

2483
  DBUG_ENTER("execute");
2484
  DBUG_DUMP("packet", packet, length);
2485

2486 2487
  mysql->last_used_con= mysql;
  int4store(buff, stmt->stmt_id);		/* Send stmt id to server */
2488
  buff[4]= (char) stmt->flags;
2489
  int4store(buff+5, 1);                         /* iteration count */
2490

2491
  res= test(cli_advanced_command(mysql, COM_STMT_EXECUTE, buff, sizeof(buff),
2492 2493 2494
                                 packet, length, 1, NULL) ||
            (*mysql->methods->read_query_result)(mysql));
  stmt->affected_rows= mysql->affected_rows;
2495
  stmt->server_status= mysql->server_status;
2496 2497
  stmt->insert_id= mysql->insert_id;
  if (res)
2498
  {
2499
    set_stmt_errmsg(stmt, net->last_error, net->last_errno, net->sqlstate);
2500
    DBUG_RETURN(1);
2501 2502 2503 2504
  }
  DBUG_RETURN(0);
}

2505 2506

int cli_stmt_execute(MYSQL_STMT *stmt)
2507
{
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2508
  DBUG_ENTER("cli_stmt_execute");
2509 2510 2511

  if (stmt->param_count)
  {
2512 2513
    MYSQL *mysql= stmt->mysql;
    NET        *net= &mysql->net;
2514
    MYSQL_BIND *param, *param_end;
2515
    char       *param_data;
venu@myvenu.com's avatar
venu@myvenu.com committed
2516 2517 2518
    ulong length;
    uint null_count;
    my_bool    result;
2519

2520 2521 2522 2523 2524
    if (!stmt->bind_param_done)
    {
      set_stmt_error(stmt, CR_PARAMS_NOT_BOUND, unknown_sqlstate);
      DBUG_RETURN(1);
    }
2525 2526
    if (mysql->status != MYSQL_STATUS_READY ||
        mysql->server_status & SERVER_MORE_RESULTS_EXISTS)
2527 2528 2529 2530
    {
      set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
      DBUG_RETURN(1);
    }
2531

2532 2533 2534
    net_clear(net);				/* Sets net->write_pos */
    /* Reserve place for null-marker bytes */
    null_count= (stmt->param_count+7) /8;
2535 2536 2537 2538 2539
    if (my_realloc_str(net, null_count + 1))
    {
      set_stmt_error(stmt, net->last_errno, unknown_sqlstate);
      DBUG_RETURN(1);
    }
2540 2541 2542 2543 2544
    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 */
venu@myvenu.com's avatar
venu@myvenu.com committed
2545 2546
    *(net->write_pos)++= (uchar) stmt->send_types_to_server;
    if (stmt->send_types_to_server)
2547
    {
2548 2549 2550 2551 2552
      if (my_realloc_str(net, 2 * stmt->param_count))
      {
        set_stmt_error(stmt, net->last_errno, unknown_sqlstate);
        DBUG_RETURN(1);
      }
2553 2554 2555 2556 2557
      /*
	Store types of parameters in first in first package
	that is sent to the server.
      */
      for (param= stmt->params;	param < param_end ; param++)
2558
        store_param_type((char**) &net->write_pos, param);
2559 2560 2561
    }

    for (param= stmt->params; param < param_end; param++)
2562
    {
2563
      /* check if mysql_stmt_send_long_data() was used */
2564 2565
      if (param->long_data_used)
	param->long_data_used= 0;	/* Clear for next execute call */
2566
      else if (store_param(stmt, param))
2567
	DBUG_RETURN(1);
2568
    }
2569 2570
    length= (ulong) (net->write_pos - net->buff);
    /* TODO: Look into avoding the following memdup */
2571
    if (!(param_data= my_memdup((const char*) net->buff, length, MYF(0))))
2572
    {
2573
      set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
2574
      DBUG_RETURN(1);
2575
    }
2576
    result= execute(stmt, param_data, length);
venu@myvenu.com's avatar
venu@myvenu.com committed
2577
    stmt->send_types_to_server=0;
2578
    my_free(param_data, MYF(MY_WME));
2579 2580 2581
    DBUG_RETURN(result);
  }
  DBUG_RETURN((int) execute(stmt,0,0));
2582 2583
}

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
/*
  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)
{
2598
  if (stmt->data_cursor)
2599
  {
2600 2601
    *row= (uchar *) stmt->data_cursor->data;
    stmt->data_cursor= stmt->data_cursor->next;
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
    return 0;
  }
  *row= 0;
  return MYSQL_NO_DATA;
}

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

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

  RETURN VALUE
    0           - success; *row contains valid address of a row;
                  row data is stored in network buffer
    1           - error; error code is written to
2622
                  stmt->last_{errno,error}; *row is not changed
2623
  MYSQL_NO_DATA - end of file was read from network;
2624
                  *row is set to NULL
2625 2626 2627 2628 2629 2630
*/

static int stmt_read_row_unbuffered(MYSQL_STMT *stmt, unsigned char **row)
{
  int rc= 1;
  MYSQL *mysql= stmt->mysql;
2631
  /*
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
    This function won't be called if stmt->field_count is zero
    or execution wasn't done: this is ensured by mysql_stmt_execute.
  */
  if (!mysql)
  {
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
    return 1;
  }
  if (mysql->status != MYSQL_STATUS_GET_RESULT)
  {
    set_stmt_error(stmt, stmt->unbuffered_fetch_cancelled ?
2643
                   CR_FETCH_CANCELED : CR_COMMANDS_OUT_OF_SYNC,
2644 2645 2646 2647 2648 2649 2650
                   unknown_sqlstate);
    goto error;
  }
  if ((*mysql->methods->unbuffered_fetch)(mysql, (char**) row))
  {
    set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                    mysql->net.sqlstate);
2651 2652 2653 2654 2655 2656 2657
    /*
      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;
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
    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;
}

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

/*
  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;
    char buff[4 /* statement id */ +
              4 /* number of rows to fetch */];

    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);
2706
    int4store(buff + 4, stmt->prefetch_rows); /* number of rows to fetch */
2707
    if ((*mysql->methods->advanced_command)(mysql, COM_STMT_FETCH,
holyfoot/hf@mysql.com/deer.(none)'s avatar
holyfoot/hf@mysql.com/deer.(none) committed
2708 2709
                                            buff, sizeof(buff), NullS, 0,
                                            1, NULL))
2710 2711 2712 2713
    {
      set_stmt_errmsg(stmt, net->last_error, net->last_errno, net->sqlstate);
      return 1;
    }
2714
    if ((*mysql->methods->read_rows_from_cursor)(stmt))
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
      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;
}


2726 2727 2728 2729 2730 2731 2732 2733
/*
  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)))
2734 2735 2736 2737 2738 2739 2740
{
  return MYSQL_NO_DATA;
}

static int
stmt_read_row_no_result_set(MYSQL_STMT *stmt  __attribute__((unused)),
                      unsigned char **row  __attribute__((unused)))
2741
{
2742 2743
  set_stmt_error(stmt, CR_NO_RESULT_SET, unknown_sqlstate);
  return 1;
2744 2745
}

2746 2747 2748 2749 2750 2751 2752 2753

/*
  Get/set statement attributes

  SYNOPSIS
    mysql_stmt_attr_get()
    mysql_stmt_attr_set()

paul@ice.snake.net's avatar
paul@ice.snake.net committed
2754
    attr_type  statement attribute
2755 2756 2757 2758 2759 2760
    value      casted to const void * pointer to value.

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

2762 2763 2764 2765 2766 2767 2768 2769
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;
2770
  case STMT_ATTR_CURSOR_TYPE:
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
  {
    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;
2785
    break;
2786
  }
2787
  default:
2788
    goto err_not_implemented;
2789 2790
  }
  return FALSE;
2791 2792 2793
err_not_implemented:
  set_stmt_error(stmt, CR_NOT_IMPLEMENTED, unknown_sqlstate);
  return TRUE;
2794 2795 2796
}


2797
my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
2798 2799 2800 2801 2802
                                    enum enum_stmt_attr_type attr_type,
                                    void *value)
{
  switch (attr_type) {
  case STMT_ATTR_UPDATE_MAX_LENGTH:
2803
    *(unsigned long *) value= stmt->update_max_length;
2804
    break;
2805
  case STMT_ATTR_CURSOR_TYPE:
2806
    *(ulong*) value= stmt->flags;
2807
      break;
2808 2809 2810
  case STMT_ATTR_PREFETCH_ROWS:
    *(ulong*) value= stmt->prefetch_rows;
    break;
2811
  default:
2812 2813 2814 2815 2816 2817
    return TRUE;
  }
  return FALSE;
}


hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2818
/*
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
  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().
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2860 2861
*/

2862
int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2863
{
2864
  MYSQL *mysql= stmt->mysql;
2865
  DBUG_ENTER("mysql_stmt_execute");
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2866

2867 2868 2869
  if (!mysql)
  {
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2870
    DBUG_RETURN(1);
2871 2872
  }

2873
  if (reset_stmt_handle(stmt, RESET_STORE_RESULT))
2874
    DBUG_RETURN(1);
2875 2876
  /*
    No need to check for stmt->state: if the statement wasn't
paul@ice.snake.net's avatar
paul@ice.snake.net committed
2877
    prepared we'll get 'unknown statement handler' error from server.
2878 2879 2880
  */
  if (mysql->methods->stmt_execute(stmt))
    DBUG_RETURN(1);
2881
  if (mysql->field_count)
2882
  {
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
    /* Server has sent result set metadata */
    if (stmt->field_count == 0)
    {
      /*
        This is 'SHOW'/'EXPLAIN'-like query. Current implementation of
        prepared statements can't send result set metadata for these queries
        on prepare stage. Read it now.
      */
      alloc_stmt_fields(stmt);
    }
    else
    {
      /*
        Update result set metadata if it for some reason changed between
        prepare and execute, i.e.:
        - in case of 'SELECT ?' we don't know column type unless data was
          supplied to mysql_stmt_execute, so updated column type is sent
          now.
        - if data dictionary changed between prepare and execute, for
          example a table used in the query was altered.
        Note, that now (4.1.3) we always send metadata in reply to
2904
        COM_STMT_EXECUTE (even if it is not necessary), so either this or
2905
        previous branch always works.
2906 2907 2908 2909 2910
        TODO: send metadata only when it's really necessary and add a warning
        'Metadata changed' when it's sent twice.
      */
      update_stmt_fields(stmt);
    }
2911 2912 2913 2914
  }
  stmt->state= MYSQL_STMT_EXECUTE_DONE;
  if (stmt->field_count)
  {
2915 2916 2917 2918 2919
    if (stmt->server_status & SERVER_STATUS_CURSOR_EXISTS)
    {
      mysql->status= MYSQL_STATUS_READY;
      stmt->read_row_func= stmt_read_row_from_cursor;
    }
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
    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.
      */
      DBUG_RETURN(mysql_stmt_store_result(stmt));
    }
2931 2932 2933 2934 2935 2936
    else
    {
      stmt->mysql->unbuffered_fetch_owner= &stmt->unbuffered_fetch_cancelled;
      stmt->unbuffered_fetch_cancelled= FALSE;
      stmt->read_row_func= stmt_read_row_unbuffered;
    }
2937
  }
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2938 2939 2940
  DBUG_RETURN(0);
}

2941

2942 2943 2944 2945
/*
  Return total parameters count in the statement
*/

2946
ulong STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt)
2947
{
2948
  DBUG_ENTER("mysql_stmt_param_count");
2949 2950 2951
  DBUG_RETURN(stmt->param_count);
}

2952 2953 2954 2955 2956 2957
/*
  Return total affected rows from the last statement
*/

my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt)
{
2958
  return stmt->affected_rows;
2959
}
2960

2961

2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
/*
  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;
}

2972
/*
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
  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.
2986 2987 2988 2989 2990 2991 2992
*/

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

2993

2994 2995 2996
static my_bool int_is_null_true= 1;		/* Used for MYSQL_TYPE_NULL */
static my_bool int_is_null_false= 0;

2997

2998
/*
2999
  Set up input data buffers for a statement.
3000 3001 3002 3003 3004 3005

  SYNOPSIS
    mysql_stmt_bind_param()
    stmt    statement handle
            The statement must be prepared with mysql_stmt_prepare().
    bind    Array of mysql_stmt_param_count() bind parameters.
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
            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
paul@ice.snake.net's avatar
paul@ice.snake.net committed
3021
    bind structure before setting its members. This will both shorten
3022 3023
    your application code and make it robust to future extensions of
    MYSQL_BIND structure.
3024
    Then you need to assign typecode of your application buffer to
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143
    MYSQL_BIND::buffer_type. The following typecodes with their
    correspondence to C language types are supported:
    MYSQL_TYPE_TINY       for 8-bit integer variables. Normally it's
                          'signed char' and 'unsigned char';
    MYSQL_TYPE_SHORT      for 16-bit signed and unsigned variables. This
                          is usually 'short' and 'unsigned short';
    MYSQL_TYPE_LONG       for 32-bit signed and unsigned variables. It
                          corresponds to 'int' and 'unsigned int' on
                          vast majority of platforms. On IA-32 and some
                          other 32-bit systems you can also use 'long'
                          here;
    MYSQL_TYPE_LONGLONG   64-bit signed or unsigned integer.  Stands for
                          '[unsigned] long long' on most platforms;
    MYSQL_TYPE_FLOAT      32-bit floating point type, 'float' on most
                          systems;
    MYSQL_TYPE_DOUBLE     64-bit floating point type, 'double' on most
                          systems;
    MYSQL_TYPE_TIME       broken-down time stored in MYSQL_TIME
                          structure
    MYSQL_TYPE_DATE       date stored in MYSQL_TIME structure
    MYSQL_TYPE_DATETIME   datetime stored in MYSQL_TIME structure See
                          more on how to use these types for sending
                          dates and times below;
    MYSQL_TYPE_STRING     character string, assumed to be in
                          character-set-client. If character set of
                          client is not equal to character set of
                          column, value for this placeholder will be
                          converted to destination character set before
                          insert.
    MYSQL_TYPE_BLOB       sequence of bytes. This sequence is assumed to
                          be in binary character set (which is the same
                          as no particular character set), and is never
                          converted to any other character set. See also
                          notes about supplying string/blob length
                          below.
    MYSQL_TYPE_NULL       special typecode for binding nulls.
    These C/C++ types are not supported yet by the API: long double,
    bool.

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

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

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

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

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

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

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

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

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

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

    See also: mysql_stmt_send_long_data() for sending long text/blob
3144
    data in pieces, examples in tests/mysql_client_test.c.
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
    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
3155 3156
    to call this routine after each assignment to bind buffers, you
    need to call it each time you change parameter typecodes, or other
3157 3158 3159
    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.
3160 3161 3162 3163

  RETURN
    0  success
    1  error, can be retrieved with mysql_stmt_error.
3164 3165
*/

3166
my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind)
3167
{
3168 3169
  uint count=0;
  MYSQL_BIND *param, *end;
3170
  DBUG_ENTER("mysql_stmt_bind_param");
3171

3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
  if (!stmt->param_count)
  {
    if ((int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE)
    {
      set_stmt_error(stmt, CR_NO_PREPARE_STMT, unknown_sqlstate);
      DBUG_RETURN(1);
    }
    DBUG_RETURN(0);
  }

3182 3183 3184 3185 3186 3187 3188
  /* Allocated on prepare */
  memcpy((char*) stmt->params, (char*) bind,
	 sizeof(MYSQL_BIND) * stmt->param_count);

  for (param= stmt->params, end= param+stmt->param_count;
       param < end ;
       param++)
3189
  {
3190
    param->param_number= count++;
3191 3192
    param->long_data_used= 0;

3193 3194 3195 3196
    /* 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;

3197 3198
    /* Setup data copy functions for the different supported types */
    switch (param->buffer_type) {
venu@myvenu.com's avatar
venu@myvenu.com committed
3199
    case MYSQL_TYPE_NULL:
3200
      param->is_null= &int_is_null_true;
venu@myvenu.com's avatar
venu@myvenu.com committed
3201
      break;
3202
    case MYSQL_TYPE_TINY:
3203
      /* Force param->length as this is fixed for this type */
3204 3205
      param->length= &param->buffer_length;
      param->buffer_length= 1;
3206 3207 3208
      param->store_param_func= store_param_tinyint;
      break;
    case MYSQL_TYPE_SHORT:
3209 3210
      param->length= &param->buffer_length;
      param->buffer_length= 2;
3211 3212 3213
      param->store_param_func= store_param_short;
      break;
    case MYSQL_TYPE_LONG:
3214 3215
      param->length= &param->buffer_length;
      param->buffer_length= 4;
3216 3217 3218
      param->store_param_func= store_param_int32;
      break;
    case MYSQL_TYPE_LONGLONG:
3219 3220
      param->length= &param->buffer_length;
      param->buffer_length= 8;
3221 3222 3223
      param->store_param_func= store_param_int64;
      break;
    case MYSQL_TYPE_FLOAT:
3224 3225
      param->length= &param->buffer_length;
      param->buffer_length= 4;
3226 3227 3228
      param->store_param_func= store_param_float;
      break;
    case MYSQL_TYPE_DOUBLE:
3229 3230
      param->length= &param->buffer_length;
      param->buffer_length= 8;
3231 3232
      param->store_param_func= store_param_double;
      break;
3233 3234
    case MYSQL_TYPE_TIME:
      param->store_param_func= store_param_time;
3235
      param->buffer_length= MAX_TIME_REP_LENGTH;
3236 3237 3238
      break;
    case MYSQL_TYPE_DATE:
      param->store_param_func= store_param_date;
3239
      param->buffer_length= MAX_DATE_REP_LENGTH;
3240 3241 3242 3243
      break;
    case MYSQL_TYPE_DATETIME:
    case MYSQL_TYPE_TIMESTAMP:
      param->store_param_func= store_param_datetime;
3244
      param->buffer_length= MAX_DATETIME_REP_LENGTH;
3245
      break;
3246 3247 3248
    case MYSQL_TYPE_TINY_BLOB:
    case MYSQL_TYPE_MEDIUM_BLOB:
    case MYSQL_TYPE_LONG_BLOB:
venu@myvenu.com's avatar
venu@myvenu.com committed
3249
    case MYSQL_TYPE_BLOB:
3250
    case MYSQL_TYPE_VARCHAR:
3251 3252
    case MYSQL_TYPE_VAR_STRING:
    case MYSQL_TYPE_STRING:
3253 3254
    case MYSQL_TYPE_DECIMAL:
    case MYSQL_TYPE_NEWDECIMAL:
3255
      param->store_param_func= store_param_str;
3256
      /*
3257 3258
        For variable length types user must set either length or
        buffer_length.
3259
      */
3260 3261
      break;
    default:
3262
      strmov(stmt->sqlstate, unknown_sqlstate);
3263 3264
      sprintf(stmt->last_error,
	      ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
3265
	      param->buffer_type, count);
3266
      DBUG_RETURN(1);
3267
    }
3268 3269 3270 3271 3272 3273
    /*
      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;
3274
  }
3275
  /* We have to send/resend type information to MySQL */
3276 3277
  stmt->send_types_to_server= TRUE;
  stmt->bind_param_done= TRUE;
3278 3279 3280
  DBUG_RETURN(0);
}

3281

3282 3283 3284 3285 3286
/********************************************************************
 Long data implementation
*********************************************************************/

/*
3287 3288 3289
  Send long data in pieces to the server

  SYNOPSIS
3290
    mysql_stmt_send_long_data()
3291 3292 3293 3294
    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)
3295

3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319
  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.

3320
  RETURN VALUES
3321 3322
    0	ok
    1	error
3323 3324
*/

3325
my_bool STDCALL
3326
mysql_stmt_send_long_data(MYSQL_STMT *stmt, uint param_number,
3327
		     const char *data, ulong length)
3328 3329
{
  MYSQL_BIND *param;
3330
  DBUG_ENTER("mysql_stmt_send_long_data");
3331
  DBUG_ASSERT(stmt != 0);
3332
  DBUG_PRINT("enter",("param no : %d, data : %lx, length : %ld",
3333
		      param_number, data, length));
3334

3335 3336 3337 3338 3339 3340 3341 3342 3343
  /*
    We only need to check for stmt->param_count, if it's not null
    prepare was done.
  */
  if (param_number >= stmt->param_count)
  {
    set_stmt_error(stmt, CR_INVALID_PARAMETER_NO, unknown_sqlstate);
    DBUG_RETURN(1);
  }
3344

3345
  param= stmt->params+param_number;
3346 3347 3348
  if (param->buffer_type < MYSQL_TYPE_TINY_BLOB ||
      param->buffer_type > MYSQL_TYPE_STRING)
  {
3349
    /* Long data handling should be used only for string/binary types */
3350
    strmov(stmt->sqlstate, unknown_sqlstate);
3351 3352 3353 3354
    sprintf(stmt->last_error, ER(stmt->last_errno= CR_INVALID_BUFFER_USE),
	    param->param_number);
    DBUG_RETURN(1);
  }
3355

3356
  /*
3357 3358 3359
    Send long data packet if there is data or we're sending long data
    for the first time.
  */
3360
  if (length || param->long_data_used == 0)
3361
  {
3362
    MYSQL *mysql= stmt->mysql;
3363
    /* Packet header: stmt id (4 bytes), param no (2 bytes) */
3364 3365
    char buff[MYSQL_LONG_DATA_HEADER];

3366 3367
    int4store(buff, stmt->stmt_id);
    int2store(buff + 4, param_number);
3368 3369
    param->long_data_used= 1;

3370 3371 3372 3373
    /*
      Note that we don't get any ok packet from the server in this case
      This is intentional to save bandwidth.
    */
3374 3375
    if ((*mysql->methods->advanced_command)(mysql, COM_STMT_SEND_LONG_DATA,
                                            buff, sizeof(buff), data,
3376
                                            length, 1, NULL))
3377
    {
3378 3379
      set_stmt_errmsg(stmt, mysql->net.last_error,
		      mysql->net.last_errno, mysql->net.sqlstate);
3380 3381 3382 3383 3384 3385
      DBUG_RETURN(1);
    }
  }
  DBUG_RETURN(0);
}

3386

3387
/********************************************************************
3388
 Fetch and conversion of result set rows (binary protocol).
3389 3390
*********************************************************************/

3391 3392 3393 3394 3395 3396 3397 3398
/*
  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.
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3399 3400
          These functions increase pos to point to the beginning of the
          next column.
3401 3402 3403 3404 3405 3406

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

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3407
static void read_binary_time(MYSQL_TIME *tm, uchar **pos)
3408
{
3409
  /* net_field_length will set pos to the first byte of data */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3410 3411 3412
  uint length= net_field_length(pos);

  if (length)
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3413 3414 3415
  {
    uchar *to= *pos;
    tm->neg= (bool) to[0];
3416

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3417 3418 3419 3420 3421 3422
    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;
3423 3424 3425 3426 3427 3428
    if (tm->day)
    {
      /* Convert days to hours at once */
      tm->hour+= tm->day*24;
      tm->day= 0;
    }
3429 3430
    tm->time_type= MYSQL_TIMESTAMP_TIME;

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3431
    *pos+= length;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3432
  }
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3433
  else
3434
    set_zero_time(tm, MYSQL_TIMESTAMP_TIME);
3435 3436
}

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3437
static void read_binary_datetime(MYSQL_TIME *tm, uchar **pos)
3438
{
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3439
  uint length= net_field_length(pos);
3440

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3441
  if (length)
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3442 3443
  {
    uchar *to= *pos;
3444

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3445 3446 3447 3448
    tm->neg=    0;
    tm->year=   (uint) sint2korr(to);
    tm->month=  (uint) to[2];
    tm->day=    (uint) to[3];
3449

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3450 3451 3452 3453 3454 3455 3456 3457 3458
    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;
3459
    tm->time_type= MYSQL_TIMESTAMP_DATETIME;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3460 3461

    *pos+= length;
3462
  }
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3463
  else
3464
    set_zero_time(tm, MYSQL_TIMESTAMP_DATETIME);
3465 3466
}

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3467
static void read_binary_date(MYSQL_TIME *tm, uchar **pos)
3468
{
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3469
  uint length= net_field_length(pos);
3470

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3471
  if (length)
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3472 3473 3474 3475 3476
  {
    uchar *to= *pos;
    tm->year =  (uint) sint2korr(to);
    tm->month=  (uint) to[2];
    tm->day= (uint) to[3];
3477

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3478 3479 3480
    tm->hour= tm->minute= tm->second= 0;
    tm->second_part= 0;
    tm->neg= 0;
3481
    tm->time_type= MYSQL_TIMESTAMP_DATE;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3482 3483

    *pos+= length;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3484
  }
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3485
  else
3486
    set_zero_time(tm, MYSQL_TIMESTAMP_DATE);
3487 3488
}

3489

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3490 3491 3492 3493 3494 3495 3496 3497 3498
/*
  Convert string to supplied buffer of any type.

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

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3500 3501
static void fetch_string_with_conversion(MYSQL_BIND *param, char *value,
                                         uint length)
3502
{
3503
  char *buffer= (char *)param->buffer;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3504
  int err= 0;
3505
  char *endptr= value + length;
3506

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3507 3508 3509 3510 3511
  /*
    This function should support all target buffer types: the rest
    of conversion functions can delegate conversion to it.
  */
  switch(param->buffer_type) {
3512 3513
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3514
  case MYSQL_TYPE_TINY:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3515
  {
3516
    longlong data= my_strtoll10(value, &endptr, &err);
3517
    *param->error= (IS_TRUNCATED(data, param->is_unsigned,
3518
                                 INT_MIN8, INT_MAX8, UINT_MAX8) || err > 0);
3519
    *buffer= (uchar) data;
3520
    break;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3521
  }
3522
  case MYSQL_TYPE_SHORT:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3523
  {
3524
    longlong data= my_strtoll10(value, &endptr, &err);
3525
    *param->error= (IS_TRUNCATED(data, param->is_unsigned,
3526
                                 INT_MIN16, INT_MAX16, UINT_MAX16) || err > 0);
3527
    shortstore(buffer, (short) data);
3528
    break;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3529
  }
3530
  case MYSQL_TYPE_LONG:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3531
  {
3532
    longlong data= my_strtoll10(value, &endptr, &err);
3533
    *param->error= (IS_TRUNCATED(data, param->is_unsigned,
3534
                                 INT_MIN32, INT_MAX32, UINT_MAX32) || err > 0);
3535
    longstore(buffer, (int32) data);
3536
    break;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3537
  }
3538
  case MYSQL_TYPE_LONGLONG:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3539
  {
3540 3541 3542
    longlong data= my_strtoll10(value, &endptr, &err);
    *param->error= param->is_unsigned ? err != 0 :
                                       (err > 0 || (err == 0 && data < 0));
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3543
    longlongstore(buffer, data);
3544
    break;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3545
  }
3546
  case MYSQL_TYPE_FLOAT:
3547
  {
3548 3549 3550 3551
    double data= my_strntod(&my_charset_latin1, value, length, &endptr, &err);
    float fdata= (float) data;
    *param->error= (fdata != data) | test(err);
    floatstore(buffer, fdata);
3552 3553
    break;
  }
3554
  case MYSQL_TYPE_DOUBLE:
3555
  {
3556 3557
    double data= my_strntod(&my_charset_latin1, value, length, &endptr, &err);
    *param->error= test(err);
3558
    doublestore(buffer, data);
3559 3560
    break;
  }
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3561 3562 3563 3564
  case MYSQL_TYPE_TIME:
  {
    MYSQL_TIME *tm= (MYSQL_TIME *)buffer;
    str_to_time(value, length, tm, &err);
3565
    *param->error= test(err);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3566 3567 3568 3569
    break;
  }
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_DATETIME:
3570
  case MYSQL_TYPE_TIMESTAMP:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3571 3572
  {
    MYSQL_TIME *tm= (MYSQL_TIME *)buffer;
3573
    (void) str_to_datetime(value, length, tm, TIME_FUZZY_DATE, &err);
3574 3575
    *param->error= test(err) && (param->buffer_type == MYSQL_TYPE_DATE &&
                                 tm->time_type != MYSQL_TIMESTAMP_DATE);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3576 3577 3578 3579 3580 3581
    break;
  }
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
3582 3583
  case MYSQL_TYPE_DECIMAL:
  case MYSQL_TYPE_NEWDECIMAL:
3584
  default:
3585
  {
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
    /*
      Copy column data to the buffer taking into account offset,
      data length and buffer length.
    */
    char *start= value + param->offset;
    char *end= value + length;
    ulong copy_length;
    if (start < end)
    {
      copy_length= end - start;
      /* We've got some data beyond offset: copy up to buffer_length bytes */
      if (param->buffer_length)
        memcpy(buffer, start, min(copy_length, param->buffer_length));
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3600
    else
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3601 3602 3603
      copy_length= 0;
    if (copy_length < param->buffer_length)
      buffer[copy_length]= '\0';
3604
    *param->error= copy_length > param->buffer_length;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3605 3606 3607 3608
    /*
      param->length will always contain length of entire column;
      number of copied bytes may be way different:
    */
3609
    *param->length= length;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3610
    break;
3611
  }
3612
  }
3613 3614
}

3615

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3616 3617
/*
  Convert integer value to client buffer of any type.
3618

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3619 3620 3621 3622 3623 3624
  SYNOPSIS
    fetch_long_with_conversion()
    param   output buffer descriptor
    field   column metadata
    value   column data
*/
3625

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3626
static void fetch_long_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
3627
                                       longlong value, my_bool is_unsigned)
3628
{
3629
  char *buffer= (char *)param->buffer;
3630

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3631
  switch (param->buffer_type) {
3632 3633
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3634
  case MYSQL_TYPE_TINY:
3635
    *param->error= IS_TRUNCATED(value, param->is_unsigned,
3636
                                INT_MIN8, INT_MAX8, UINT_MAX8);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3637
    *(uchar *)param->buffer= (uchar) value;
3638 3639
    break;
  case MYSQL_TYPE_SHORT:
3640
    *param->error= IS_TRUNCATED(value, param->is_unsigned,
3641
                                INT_MIN16, INT_MAX16, UINT_MAX16);
3642
    shortstore(buffer, (short) value);
3643 3644
    break;
  case MYSQL_TYPE_LONG:
3645
    *param->error= IS_TRUNCATED(value, param->is_unsigned,
3646
                                INT_MIN32, INT_MAX32, UINT_MAX32);
3647
    longstore(buffer, (int32) value);
3648 3649
    break;
  case MYSQL_TYPE_LONGLONG:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3650
    longlongstore(buffer, value);
3651
    *param->error= param->is_unsigned != is_unsigned && value < 0;
3652 3653
    break;
  case MYSQL_TYPE_FLOAT:
3654
  {
3655 3656 3657 3658 3659 3660
    /*
      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)
      AFAIU it does not guarantee to work.
    */
3661
    float data;
3662
    if (is_unsigned)
3663 3664 3665
      data= (float) ulonglong2double(value);
    else
      data= (float) value;
3666
    floatstore(buffer, data);
3667 3668 3669
    *param->error= is_unsigned ?
                   ((ulonglong) value) != ((ulonglong) (*(float*) buffer)) :
                   ((longlong) value) != ((longlong) (*(float*) buffer));
3670 3671
    break;
  }
3672
  case MYSQL_TYPE_DOUBLE:
3673
  {
3674
    double data;
3675
    if (is_unsigned)
3676 3677
      data= ulonglong2double(value);
    else
3678
      data= (double)value;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3679
    doublestore(buffer, data);
3680 3681 3682
    *param->error= is_unsigned ?
                   ((ulonglong) value) != ((ulonglong) (*(double*) buffer)) :
                   ((longlong) value) != ((longlong) (*(double*) buffer));
3683 3684
    break;
  }
3685 3686 3687 3688 3689 3690
  case MYSQL_TYPE_TIME:
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_TIMESTAMP:
  case MYSQL_TYPE_DATETIME:
  {
    int error;
3691 3692
    value= number_to_datetime(value, (MYSQL_TIME *) buffer, TIME_FUZZY_DATE,
                              &error);
3693 3694 3695
    *param->error= test(error);
    break;
  }
3696
  default:
3697
  {
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3698
    char buff[22];                              /* Enough for longlong */
3699
    char *end= longlong10_to_str(value, buff, is_unsigned ? 10: -10);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3700
    /* Resort to string conversion which supports all typecodes */
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
    uint length= (uint) (end-buff);

    if (field->flags & ZEROFILL_FLAG && length < field->length &&
        field->length < 21)
    {
      bmove_upp((char*) buff+field->length,buff+length, length);
      bfill((char*) buff, field->length - length,'0');
      length= field->length;
    }
    fetch_string_with_conversion(param, buff, length);
kent@mysql.com's avatar
kent@mysql.com committed
3711
    break;
3712
  }
3713
  }
3714 3715
}

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
/*
  Convert double/float column to supplied buffer of any type.

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

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3728 3729
static void fetch_float_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
                                        double value, int width)
3730
{
3731
  char *buffer= (char *)param->buffer;
3732
  double val64 = (value < 0 ? -floor(-value) : floor(value));
3733

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3734
  switch (param->buffer_type) {
3735 3736
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3737
  case MYSQL_TYPE_TINY:
3738 3739 3740 3741 3742 3743
    /*
      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.
    */
3744
    if (param->is_unsigned)
3745
      *buffer= (uint8) value;
3746
    else
3747
      *buffer= (int8) value;
3748 3749
    *param->error= val64 != (param->is_unsigned ? (double)((uint8) *buffer) :
                                                  (double)((int8) *buffer));
3750 3751
    break;
  case MYSQL_TYPE_SHORT:
3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
    if (param->is_unsigned)
    {
      ushort data= (ushort) value;
      shortstore(buffer, data);
    }
    else
    {
      short data= (short) value;
      shortstore(buffer, data);
    }
3762
    *param->error= val64 != (param->is_unsigned ? (double) (*(ushort*) buffer):
3763
                                                  (double) (*(short*) buffer));
3764 3765
    break;
  case MYSQL_TYPE_LONG:
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
    if (param->is_unsigned)
    {
      uint32 data= (uint32) value;
      longstore(buffer, data);
    }
    else
    {
      int32 data= (int32) value;
      longstore(buffer, data);
    }
3776
    *param->error= val64 != (param->is_unsigned ? (double) (*(uint32*) buffer):
3777 3778
                                                  (double) (*(int32*) buffer));
      break;
3779
  case MYSQL_TYPE_LONGLONG:
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
    if (param->is_unsigned)
    {
      ulonglong data= (ulonglong) value;
      longlongstore(buffer, data);
    }
    else
    {
      longlong data= (longlong) value;
      longlongstore(buffer, data);
    }
3790
    *param->error= val64 != (param->is_unsigned ?
3791
                             ulonglong2double(*(ulonglong*) buffer) :
3792
                             (double) (*(longlong*) buffer));
3793 3794 3795
    break;
  case MYSQL_TYPE_FLOAT:
  {
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3796
    float data= (float) value;
3797
    floatstore(buffer, data);
3798
    *param->error= (*(float*) buffer) != value;
3799 3800 3801 3802
    break;
  }
  case MYSQL_TYPE_DOUBLE:
  {
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3803
    doublestore(buffer, value);
3804 3805
    break;
  }
3806
  default:
3807
  {
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3808 3809 3810 3811 3812
    /*
      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
    */
3813
    char buff[MAX_DOUBLE_STRING_REP_LENGTH];
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3814 3815 3816
    char *end;
    /* TODO: move this to a header shared between client and server. */
#define NOT_FIXED_DEC  31
3817
    if (field->decimals >= NOT_FIXED_DEC)
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3818 3819
#undef NOT_FIXED_DEC
    {
3820 3821 3822 3823 3824 3825 3826 3827
      /*
        The 14 below is to ensure that the server and client has the same
        precisions. This will ensure that on the same machine you get the
        same value as a string independent of the protocol you use.
      */
      sprintf(buff, "%-*.*g", (int) min(sizeof(buff)-1,
                                        param->buffer_length),
	      min(14,width), value);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3828 3829 3830
      end= strcend(buff, ' ');
      *end= 0;
    }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3831
    else
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3832
    {
kent@mysql.com's avatar
kent@mysql.com committed
3833
      sprintf(buff, "%.*f", (int) field->decimals, value);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3834 3835
      end= strend(buff);
    }
monty@mysql.com's avatar
monty@mysql.com committed
3836
    fetch_string_with_conversion(param, buff, (uint) (end - buff));
3837 3838
    break;
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3839
  }
3840 3841
}

3842

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3843 3844 3845 3846 3847 3848 3849 3850 3851
/*
  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,
3852
                                           MYSQL_FIELD *field,
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3853
                                           MYSQL_TIME *time)
3854 3855
{
  switch (param->buffer_type) {
3856 3857
  case MYSQL_TYPE_NULL: /* do nothing */
    break;
3858
  case MYSQL_TYPE_DATE:
3859 3860 3861
    *(MYSQL_TIME *)(param->buffer)= *time;
    *param->error= time->time_type != MYSQL_TIMESTAMP_DATE;
    break;
3862
  case MYSQL_TYPE_TIME:
3863 3864 3865
    *(MYSQL_TIME *)(param->buffer)= *time;
    *param->error= time->time_type != MYSQL_TIMESTAMP_TIME;
    break;
3866 3867
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3868
    *(MYSQL_TIME *)(param->buffer)= *time;
3869
    /* No error: time and date are compatible with datetime */
3870
    break;
3871 3872 3873 3874 3875 3876 3877 3878
  case MYSQL_TYPE_YEAR:
    shortstore(param->buffer, time->year);
    *param->error= 1;
    break;
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
  {
    ulonglong value= TIME_to_ulonglong(time);
3879 3880 3881
    fetch_float_with_conversion(param, field,
                                ulonglong2double(value), DBL_DIG);
    break;
3882 3883 3884 3885 3886 3887 3888 3889
  }
  case MYSQL_TYPE_TINY:
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_LONGLONG:
  {
    longlong value= (longlong) TIME_to_ulonglong(time);
3890
    fetch_long_with_conversion(param, field, value, TRUE);
3891
    break;
3892
  }
3893 3894
  default:
  {
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3895 3896 3897 3898
    /*
      Convert time value  to string and delegate the rest to
      fetch_string_with_conversion:
    */
3899 3900
    char buff[MAX_DATE_STRING_REP_LENGTH];
    uint length= my_TIME_to_str(time, buff);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3901 3902 3903
    /* Resort to string conversion */
    fetch_string_with_conversion(param, (char *)buff, length);
    break;
3904 3905 3906
  }
  }
}
3907

3908

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
/*
  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.
*/
3924

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3925 3926
static void fetch_result_with_conversion(MYSQL_BIND *param, MYSQL_FIELD *field,
                                         uchar **row)
3927
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3928
  enum enum_field_types field_type= field->type;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3929
  uint field_is_unsigned= field->flags & UNSIGNED_FLAG;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3930

3931 3932 3933
  switch (field_type) {
  case MYSQL_TYPE_TINY:
  {
3934 3935 3936 3937
    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;
3938
    fetch_long_with_conversion(param, field, data, 0);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3939
    *row+= 1;
3940 3941 3942 3943 3944
    break;
  }
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_YEAR:
  {
3945
    short value= sint2korr(*row);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3946 3947
    longlong data= field_is_unsigned ? (longlong) (unsigned short) value :
                                       (longlong) value;
3948
    fetch_long_with_conversion(param, field, data, 0);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3949
    *row+= 2;
3950 3951
    break;
  }
3952
  case MYSQL_TYPE_INT24: /* mediumint is sent as 4 bytes int */
3953 3954
  case MYSQL_TYPE_LONG:
  {
3955 3956
    int32 value= sint4korr(*row);
    longlong data= field_is_unsigned ? (longlong) (uint32) value :
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3957
                                       (longlong) value;
3958
    fetch_long_with_conversion(param, field, data, 0);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3959
    *row+= 4;
3960 3961 3962 3963 3964
    break;
  }
  case MYSQL_TYPE_LONGLONG:
  {
    longlong value= (longlong)sint8korr(*row);
3965 3966
    fetch_long_with_conversion(param, field, value,
                               field->flags & UNSIGNED_FLAG);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3967
    *row+= 8;
3968 3969 3970 3971 3972 3973
    break;
  }
  case MYSQL_TYPE_FLOAT:
  {
    float value;
    float4get(value,*row);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3974
    fetch_float_with_conversion(param, field, value, FLT_DIG);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3975
    *row+= 4;
3976 3977 3978 3979 3980 3981
    break;
  }
  case MYSQL_TYPE_DOUBLE:
  {
    double value;
    float8get(value,*row);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3982
    fetch_float_with_conversion(param, field, value, DBL_DIG);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
3983
    *row+= 8;
3984 3985 3986 3987
    break;
  }
  case MYSQL_TYPE_DATE:
  {
3988
    MYSQL_TIME tm;
3989

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3990
    read_binary_date(&tm, row);
3991
    fetch_datetime_with_conversion(param, field, &tm);
3992 3993 3994 3995
    break;
  }
  case MYSQL_TYPE_TIME:
  {
3996
    MYSQL_TIME tm;
3997

konstantin@mysql.com's avatar
konstantin@mysql.com committed
3998
    read_binary_time(&tm, row);
3999
    fetch_datetime_with_conversion(param, field, &tm);
4000 4001 4002 4003 4004 4005
    break;
  }
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
  {
    MYSQL_TIME tm;
4006

konstantin@mysql.com's avatar
konstantin@mysql.com committed
4007
    read_binary_datetime(&tm, row);
4008
    fetch_datetime_with_conversion(param, field, &tm);
4009 4010
    break;
  }
4011
  default:
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4012 4013
  {
    ulong length= net_field_length(row);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4014
    fetch_string_with_conversion(param, (char*) *row, length);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4015
    *row+= length;
4016 4017
    break;
  }
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4018
  }
4019 4020
}

4021

4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040
/*
  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
*/

4041 4042
static void fetch_result_tinyint(MYSQL_BIND *param, MYSQL_FIELD *field,
                                 uchar **row)
venu@myvenu.com's avatar
venu@myvenu.com committed
4043
{
4044 4045 4046
  my_bool field_is_unsigned= test(field->flags & UNSIGNED_FLAG);
  uchar data= **row;
  *(uchar *)param->buffer= data;
4047
  *param->error= param->is_unsigned != field_is_unsigned && data > INT_MAX8;
4048
  (*row)++;
venu@myvenu.com's avatar
venu@myvenu.com committed
4049 4050
}

4051 4052
static void fetch_result_short(MYSQL_BIND *param, MYSQL_FIELD *field,
                               uchar **row)
venu@myvenu.com's avatar
venu@myvenu.com committed
4053
{
4054 4055 4056
  my_bool field_is_unsigned= test(field->flags & UNSIGNED_FLAG);
  ushort data= (ushort) sint2korr(*row);
  shortstore(param->buffer, data);
4057
  *param->error= param->is_unsigned != field_is_unsigned && data > INT_MAX16;
4058
  *row+= 2;
venu@myvenu.com's avatar
venu@myvenu.com committed
4059 4060
}

4061 4062 4063
static void fetch_result_int32(MYSQL_BIND *param,
                               MYSQL_FIELD *field __attribute__((unused)),
                               uchar **row)
venu@myvenu.com's avatar
venu@myvenu.com committed
4064
{
4065 4066 4067
  my_bool field_is_unsigned= test(field->flags & UNSIGNED_FLAG);
  uint32 data= (uint32) sint4korr(*row);
  longstore(param->buffer, data);
4068
  *param->error= param->is_unsigned != field_is_unsigned && data > INT_MAX32;
4069
  *row+= 4;
venu@myvenu.com's avatar
venu@myvenu.com committed
4070 4071
}

4072 4073 4074
static void fetch_result_int64(MYSQL_BIND *param,
                               MYSQL_FIELD *field __attribute__((unused)),
                               uchar **row)
4075
{
4076 4077
  my_bool field_is_unsigned= test(field->flags & UNSIGNED_FLAG);
  ulonglong data= (ulonglong) sint8korr(*row);
4078
  *param->error= param->is_unsigned != field_is_unsigned && data > LONGLONG_MAX;
4079
  longlongstore(param->buffer, data);
4080
  *row+= 8;
venu@myvenu.com's avatar
venu@myvenu.com committed
4081 4082
}

4083 4084 4085
static void fetch_result_float(MYSQL_BIND *param,
                               MYSQL_FIELD *field __attribute__((unused)),
                               uchar **row)
venu@myvenu.com's avatar
venu@myvenu.com committed
4086 4087 4088
{
  float value;
  float4get(value,*row);
4089
  floatstore(param->buffer, value);
4090
  *row+= 4;
venu@myvenu.com's avatar
venu@myvenu.com committed
4091 4092
}

4093 4094 4095
static void fetch_result_double(MYSQL_BIND *param,
                                MYSQL_FIELD *field __attribute__((unused)),
                                uchar **row)
venu@myvenu.com's avatar
venu@myvenu.com committed
4096 4097 4098
{
  double value;
  float8get(value,*row);
4099
  doublestore(param->buffer, value);
4100
  *row+= 8;
venu@myvenu.com's avatar
venu@myvenu.com committed
4101 4102
}

4103 4104 4105
static void fetch_result_time(MYSQL_BIND *param,
                              MYSQL_FIELD *field __attribute__((unused)),
                              uchar **row)
4106 4107
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4108
  read_binary_time(tm, row);
4109 4110
}

4111 4112 4113
static void fetch_result_date(MYSQL_BIND *param,
                              MYSQL_FIELD *field __attribute__((unused)),
                              uchar **row)
4114 4115
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4116
  read_binary_date(tm, row);
4117 4118
}

4119 4120 4121
static void fetch_result_datetime(MYSQL_BIND *param,
                                  MYSQL_FIELD *field __attribute__((unused)),
                                  uchar **row)
4122 4123
{
  MYSQL_TIME *tm= (MYSQL_TIME *)param->buffer;
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4124
  read_binary_datetime(tm, row);
4125 4126
}

4127 4128 4129
static void fetch_result_bin(MYSQL_BIND *param,
                             MYSQL_FIELD *field __attribute__((unused)),
                             uchar **row)
4130
{
4131 4132 4133
  ulong length= net_field_length(row);
  ulong copy_length= min(length, param->buffer_length);
  memcpy(param->buffer, (char *)*row, copy_length);
4134
  *param->length= length;
4135
  *param->error= copy_length < length;
4136 4137
  *row+= length;
}
4138

4139 4140 4141
static void fetch_result_str(MYSQL_BIND *param,
                             MYSQL_FIELD *field __attribute__((unused)),
                             uchar **row)
venu@myvenu.com's avatar
venu@myvenu.com committed
4142 4143
{
  ulong length= net_field_length(row);
4144 4145
  ulong copy_length= min(length, param->buffer_length);
  memcpy(param->buffer, (char *)*row, copy_length);
4146 4147
  /* Add an end null if there is room in the buffer */
  if (copy_length != param->buffer_length)
4148
    ((uchar *)param->buffer)[copy_length]= '\0';
4149
  *param->length= length;			/* return total length */
4150
  *param->error= copy_length < length;
4151
  *row+= length;
venu@myvenu.com's avatar
venu@myvenu.com committed
4152 4153
}

4154

4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190
/*
  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;
}


4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208
/*
  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
4209 4210 4211
    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 },
4212 4213 4214
    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,
4215 4216
                MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NULL };
  static const enum enum_field_types
4217 4218
   *range_list[]= { range1, range2, range3, range4 },
   **range_list_end= range_list + sizeof(range_list)/sizeof(*range_list);
4219
   const enum enum_field_types **range, *type;
4220 4221 4222 4223 4224 4225 4226

  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 */
    bool type1_found= FALSE, type2_found= FALSE;
4227
    for (type= *range; *type != MYSQL_TYPE_NULL; type++)
4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317
    {
      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)
{
  /* 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:
ramil@mysql.com's avatar
ramil@mysql.com committed
4318
  case MYSQL_TYPE_BIT:
4319 4320 4321 4322 4323
    DBUG_ASSERT(param->buffer_length != 0);
    param->fetch_result= fetch_result_bin;
    break;
  case MYSQL_TYPE_VAR_STRING:
  case MYSQL_TYPE_STRING:
4324 4325
  case MYSQL_TYPE_DECIMAL:
  case MYSQL_TYPE_NEWDECIMAL:
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
    DBUG_ASSERT(param->buffer_length != 0);
    param->fetch_result= fetch_result_str;
    break;
  default:
    return TRUE;
  }
  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:
    field->max_length= 15;                    /* 19:23:48.123456 */
    param->skip_result= skip_result_with_length;
  case MYSQL_TYPE_DATE:
    field->max_length= 10;                    /* 2003-11-11 */
    param->skip_result= skip_result_with_length;
    break;
    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:
4385
  case MYSQL_TYPE_NEWDECIMAL:
4386 4387 4388 4389 4390 4391 4392 4393 4394
  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:
ramil@mysql.com's avatar
ramil@mysql.com committed
4395
  case MYSQL_TYPE_BIT:
4396 4397 4398 4399 4400 4401 4402 4403 4404
    param->skip_result= skip_result_string;
    break;
  default:
    return TRUE;
  }
  return FALSE;
}


4405
/*
4406
  Setup the bind buffers for resultset processing
4407 4408
*/

4409
my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT *stmt, MYSQL_BIND *bind)
4410
{
4411
  MYSQL_BIND *param, *end;
4412
  MYSQL_FIELD *field;
4413
  ulong       bind_count= stmt->field_count;
4414
  uint        param_count= 0;
4415
  DBUG_ENTER("mysql_stmt_bind_result");
4416
  DBUG_PRINT("enter",("field_count: %d", bind_count));
4417

4418
  if (!bind_count)
4419
  {
4420 4421 4422 4423
    int errorcode= (int) stmt->state < (int) MYSQL_STMT_PREPARE_DONE ?
                   CR_NO_PREPARE_STMT : CR_NO_STMT_METADATA;
    set_stmt_error(stmt, errorcode, unknown_sqlstate);
    DBUG_RETURN(1);
4424 4425 4426 4427 4428
  }

  /*
    We only need to check that stmt->field_count - if it is not null
    stmt->bind was initialized in mysql_stmt_prepare
4429 4430 4431
    stmt->bind overlaps with bind if mysql_stmt_bind_param
    is called from mysql_stmt_store_result.
  */
4432

4433 4434
  if (stmt->bind != bind)
    memcpy((char*) stmt->bind, (char*) bind, sizeof(MYSQL_BIND) * bind_count);
4435

4436 4437 4438
  for (param= stmt->bind, end= param + bind_count, field= stmt->fields ;
       param < end ;
       param++, field++)
4439
  {
4440 4441
    DBUG_PRINT("info",("buffer_type: %u  field_type: %u",
                       (uint) param->buffer_type, (uint) field->type));
4442 4443
    /*
      Set param->is_null to point to a dummy variable if it's not set.
4444
      This is to make the execute code easier
4445 4446
    */
    if (!param->is_null)
4447
      param->is_null= &param->is_null_value;
4448

4449
    if (!param->length)
4450 4451 4452 4453
      param->length= &param->length_value;

    if (!param->error)
      param->error= &param->error_value;
4454

4455
    param->param_number= param_count++;
4456 4457
    param->offset= 0;

4458 4459
    if (setup_one_fetch_function(param, field))
    {
4460 4461
      strmov(stmt->sqlstate, unknown_sqlstate);
      sprintf(stmt->last_error,
4462 4463
              ER(stmt->last_errno= CR_UNSUPPORTED_PARAM_TYPE),
              field->type, param_count);
4464 4465
      DBUG_RETURN(1);
    }
4466
  }
4467 4468 4469 4470
  stmt->bind_result_done= BIND_RESULT_DONE;
  if (stmt->mysql->options.report_data_truncation)
    stmt->bind_result_done|= REPORT_DATA_TRUNCATION;

4471 4472 4473
  DBUG_RETURN(0);
}

4474

4475
/*
4476
  Fetch row data to bind buffers
4477 4478
*/

4479
static int stmt_fetch_row(MYSQL_STMT *stmt, uchar *row)
4480
{
4481
  MYSQL_BIND  *bind, *end;
4482
  MYSQL_FIELD *field;
4483
  uchar *null_ptr, bit;
4484
  int truncation_count= 0;
4485 4486 4487 4488 4489 4490
  /*
    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);
4491

4492 4493 4494
  if (!stmt->bind_result_done)
  {
    /* If output parameters were not bound we should just return success */
4495
    return 0;
4496
  }
4497 4498

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

venu@myvenu.com's avatar
venu@myvenu.com committed
4502
  /* Copy complete row to application buffers */
4503 4504
  for (bind= stmt->bind, end= bind + stmt->field_count, field= stmt->fields ;
       bind < end ;
4505
       bind++, field++)
4506
  {
4507
    *bind->error= 0;
4508
    if (*null_ptr & bit)
4509 4510
    {
      /*
4511
        We should set both row_ptr and is_null to be able to see
4512 4513 4514 4515 4516
        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.
      */
4517
      bind->row_ptr= NULL;
4518 4519
      *bind->is_null= 1;
    }
4520
    else
4521
    {
4522
      *bind->is_null= 0;
4523 4524 4525
      bind->row_ptr= row;
      (*bind->fetch_result)(bind, field, &row);
      truncation_count+= *bind->error;
4526
    }
4527
    if (!((bit<<=1) & 255))
4528
    {
4529
      bit= 1;					/* To next byte */
4530
      null_ptr++;
4531 4532
    }
  }
4533 4534
  if (truncation_count && (stmt->bind_result_done & REPORT_DATA_TRUNCATION))
    return MYSQL_DATA_TRUNCATED;
4535 4536 4537
  return 0;
}

4538

4539
int cli_unbuffered_fetch(MYSQL *mysql, char **row)
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
4540
{
4541
  if (packet_error == cli_safe_read(mysql))
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
4542 4543
    return 1;

4544 4545
  *row= ((mysql->net.read_pos[0] == 254) ? NULL :
	 (char*) (mysql->net.read_pos+1));
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
4546 4547
  return 0;
}
4548

4549

4550
/*
4551
  Fetch and return row data to bound buffers, if any
4552 4553
*/

4554
int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt)
4555
{
4556
  int rc;
4557
  uchar *row;
4558
  DBUG_ENTER("mysql_stmt_fetch");
4559

4560
  if ((rc= (*stmt->read_row_func)(stmt, &row)) ||
4561
      ((rc= stmt_fetch_row(stmt, row)) && rc != MYSQL_DATA_TRUNCATED))
4562
  {
4563
    stmt->state= MYSQL_STMT_PREPARE_DONE;       /* XXX: this is buggy */
4564 4565
    stmt->read_row_func= (rc == MYSQL_NO_DATA) ? 
      stmt_read_row_no_data : stmt_read_row_no_result_set;
4566
  }
4567
  else
4568
  {
4569 4570
    /* This is to know in mysql_stmt_fetch_column that data was fetched */
    stmt->state= MYSQL_STMT_FETCH_DONE;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
4571
  }
4572
  DBUG_RETURN(rc);
4573 4574
}

4575

4576
/*
4577
  Fetch data for one specified column data
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4578 4579

  SYNOPSIS
4580
    mysql_stmt_fetch_column()
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4581
    stmt		Prepared statement handler
4582
    bind		Where data should be placed. Should be filled in as
4583
			when calling mysql_stmt_bind_result()
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4584 4585 4586
    column		Column to fetch (first column is 0)
    ulong offset	Offset in result data (to fetch blob in pieces)
			This is normally 0
4587
  RETURN
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4588 4589
    0	ok
    1	error
4590 4591
*/

4592
int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
4593
                                    uint column, ulong offset)
4594
{
4595
  MYSQL_BIND *param= stmt->bind+column;
4596
  DBUG_ENTER("mysql_stmt_fetch_column");
4597

4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
  if ((int) stmt->state < (int) MYSQL_STMT_FETCH_DONE)
  {
    set_stmt_error(stmt, CR_NO_DATA, unknown_sqlstate);
    return 1;
  }
  if (column >= stmt->field_count)
  {
    set_stmt_error(stmt, CR_INVALID_PARAMETER_NO, unknown_sqlstate);
    DBUG_RETURN(1);
  }

4609 4610 4611 4612
  if (!bind->error)
    bind->error= &bind->error_value;
  *bind->error= 0;
  if (param->row_ptr)
4613
  {
4614
    MYSQL_FIELD *field= stmt->fields+column;
4615
    uchar *row= param->row_ptr;
4616 4617 4618 4619
    bind->offset= offset;
    if (bind->is_null)
      *bind->is_null= 0;
    if (bind->length) /* Set the length if non char/binary types */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4620
      *bind->length= *param->length;
4621
    else
4622
      bind->length= &param->length_value;       /* Needed for fetch_result() */
konstantin@mysql.com's avatar
konstantin@mysql.com committed
4623
    fetch_result_with_conversion(bind, field, &row);
4624
  }
4625 4626 4627 4628 4629
  else
  {
    if (bind->is_null)
      *bind->is_null= 1;
  }
4630 4631 4632 4633
  DBUG_RETURN(0);
}


4634
/*
4635 4636 4637
  Read all rows of data from server  (binary format)
*/

4638
int cli_read_binary_rows(MYSQL_STMT *stmt)
4639 4640 4641 4642
{
  ulong      pkt_len;
  uchar      *cp;
  MYSQL      *mysql= stmt->mysql;
4643 4644
  MYSQL_DATA *result= &stmt->result;
  MYSQL_ROWS *cur, **prev_ptr= &result->data;
4645
  NET        *net = &mysql->net;
4646
  DBUG_ENTER("cli_read_binary_rows");
4647

4648
  mysql= mysql->last_used_con;
4649

4650
  while ((pkt_len= cli_safe_read(mysql)) != packet_error)
4651
  {
4652 4653
    cp= net->read_pos;
    if (cp[0] != 254 || pkt_len >= 8)
4654
    {
4655 4656 4657 4658
      if (!(cur= (MYSQL_ROWS*) alloc_root(&result->alloc,
                                          sizeof(MYSQL_ROWS) + pkt_len - 1)))
      {
        set_stmt_error(stmt, CR_OUT_OF_MEMORY, unknown_sqlstate);
4659
        goto err;
4660 4661 4662 4663 4664
      }
      cur->data= (MYSQL_ROW) (cur+1);
      *prev_ptr= cur;
      prev_ptr= &cur->next;
      memcpy((char *) cur->data, (char *) cp+1, pkt_len-1);
4665 4666
      cur->length= pkt_len;		/* To allow us to do sanity checks */
      result->rows++;
4667
    }
4668
    else
4669
    {
4670 4671 4672 4673
      /* end of data */
      *prev_ptr= 0;
      mysql->warning_count= uint2korr(cp+1);
      mysql->server_status= uint2korr(cp+3);
4674 4675
      DBUG_PRINT("info",("status: %u  warning_count: %u",
                         mysql->server_status, mysql->warning_count));
4676 4677 4678
      DBUG_RETURN(0);
    }
  }
4679
  set_stmt_errmsg(stmt, net->last_error, net->last_errno, net->sqlstate);
4680 4681

err:
4682
  DBUG_RETURN(1);
4683 4684
}

4685

4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711
/*
  Update meta data for statement

  SYNOPSIS
    stmt_update_metadata()
    stmt			Statement handler
    row				Binary data

  NOTES
    Only updates MYSQL_FIELD->max_length for strings
*/

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

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

4712
  /* Go through all fields and calculate metadata */
4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
  for (bind= stmt->bind, end= bind + stmt->field_count, field= stmt->fields ;
       bind < end ;
       bind++, field++)
  {
    if (!(*null_ptr & bit))
      (*bind->skip_result)(bind, field, &row);
    DBUG_ASSERT(row <= row_end);
    if (!((bit<<=1) & 255))
    {
      bit= 1;					/* To next byte */
      null_ptr++;
    }
  }
}


4729 4730 4731 4732 4733 4734 4735
/*
  Store or buffer the binary results to stmt
*/

int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt)
{
  MYSQL *mysql= stmt->mysql;
4736
  MYSQL_DATA *result= &stmt->result;
4737
  DBUG_ENTER("mysql_stmt_store_result");
4738 4739 4740 4741 4742

  mysql= mysql->last_used_con;

  if (!stmt->field_count)
    DBUG_RETURN(0);
4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763

  if ((int) stmt->state < (int) MYSQL_STMT_EXECUTE_DONE)
  {
    set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
    DBUG_RETURN(1);
  }

  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;
    char buff[4 /* statement id */ +
              4 /* number of rows to fetch */];

    /* 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),
4764
                             NullS, 0, 1, NULL))
4765 4766 4767 4768 4769 4770
    {
      set_stmt_errmsg(stmt, net->last_error, net->last_errno, net->sqlstate);
      DBUG_RETURN(1);
    }
  }
  else if (mysql->status != MYSQL_STATUS_GET_RESULT)
4771
  {
4772
    set_stmt_error(stmt, CR_COMMANDS_OUT_OF_SYNC, unknown_sqlstate);
4773
    DBUG_RETURN(1);
4774
  }
4775

4776
  if (result->data)
4777
  {
4778 4779 4780 4781
    free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
    result->data= NULL;
    result->rows= 0;
    stmt->data_cursor= NULL;
4782
  }
4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797

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

    for (bind= stmt->bind, end= bind + stmt->field_count, field= stmt->fields;
	 bind < end ;
	 bind++, field++)
    {
4798
      bind->buffer_type= MYSQL_TYPE_NULL;
4799 4800 4801
      bind->buffer_length=1;
    }

4802 4803
    if (mysql_stmt_bind_result(stmt, stmt->bind))
      DBUG_RETURN(1);
4804 4805 4806
    stmt->bind_result_done= 0;			/* No normal bind done */
  }

4807
  if ((*mysql->methods->read_binary_rows)(stmt))
4808
  {
4809 4810 4811
    free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
    result->data= NULL;
    result->rows= 0;
4812
    mysql->status= MYSQL_STATUS_READY;
4813
    DBUG_RETURN(1);
4814
  }
4815

4816 4817 4818 4819
  /* 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));

4820 4821 4822 4823 4824 4825 4826
  if (stmt->update_max_length)
  {
    MYSQL_ROWS *cur= result->data;
    for(; cur; cur=cur->next)
      stmt_update_metadata(stmt, cur);
  }

4827 4828
  stmt->data_cursor= result->data;
  mysql->affected_rows= stmt->affected_rows= result->rows;
4829 4830 4831
  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 */
4832
  DBUG_RETURN(0); /* Data buffered, must be fetched with mysql_stmt_fetch() */
4833 4834
}

4835

4836 4837 4838 4839 4840 4841 4842
/*
  Seek to desired row in the statement result set
*/

MYSQL_ROW_OFFSET STDCALL
mysql_stmt_row_seek(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET row)
{
4843
  MYSQL_ROW_OFFSET offset= stmt->data_cursor;
4844
  DBUG_ENTER("mysql_stmt_row_seek");
4845

4846 4847
  stmt->data_cursor= row;
  DBUG_RETURN(offset);
4848 4849
}

4850

4851 4852 4853 4854
/*
  Return the current statement row cursor position
*/

4855
MYSQL_ROW_OFFSET STDCALL
4856 4857 4858
mysql_stmt_row_tell(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_row_tell");
4859

4860
  DBUG_RETURN(stmt->data_cursor);
4861 4862
}

4863

4864 4865 4866 4867 4868 4869 4870
/*
  Move the stmt result set data cursor to specified row
*/

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

4875 4876 4877
  for (; tmp && row; --row, tmp= tmp->next)
    ;
  stmt->data_cursor= tmp;
4878 4879 4880 4881 4882 4883
  if (!row && tmp)
  {
       /*  Rewind the counter */
    stmt->read_row_func= stmt_read_row_buffered;
    stmt->state= MYSQL_STMT_EXECUTE_DONE;
  }
4884
  DBUG_VOID_RETURN;
4885 4886
}

4887

4888 4889 4890 4891 4892 4893 4894
/*
  Return total rows the current statement result set
*/

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

4896
  DBUG_RETURN(stmt->result.rows);
4897
}
4898

4899

4900 4901 4902 4903 4904
/*
  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.
*/
4905

4906 4907 4908
static my_bool reset_stmt_handle(MYSQL_STMT *stmt, uint flags)
{
  /* If statement hasn't been prepared there is nothing to reset */
4909 4910 4911
  if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
  {
    MYSQL *mysql= stmt->mysql;
4912
    MYSQL_DATA *result= &stmt->result;
4913

4914 4915 4916 4917
    /*
      Reset stored result set if so was requested or it's a part
      of cursor fetch.
    */
4918
    if (result->data && (flags & RESET_STORE_RESULT))
4919 4920
    {
      /* Result buffered */
4921 4922 4923 4924
      free_root(&result->alloc, MYF(MY_KEEP_PREALLOC));
      result->data= NULL;
      result->rows= 0;
      stmt->data_cursor= NULL;
4925
    }
4926
    if (flags & RESET_LONG_DATA)
4927
    {
4928 4929 4930 4931 4932
      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;
    }
4933
    stmt->read_row_func= stmt_read_row_no_result_set;
4934 4935 4936
    if (mysql)
    {
      if ((int) stmt->state > (int) MYSQL_STMT_PREPARE_DONE)
4937
      {
4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948
        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 */
          (*mysql->methods->flush_use_result)(mysql);
          if (mysql->unbuffered_fetch_owner)
            *mysql->unbuffered_fetch_owner= TRUE;
          mysql->status= MYSQL_STATUS_READY;
        }
      }
4949
      if (flags & RESET_SERVER_SIDE)
4950 4951 4952 4953 4954 4955 4956
      {
        /*
          Reset the server side statement and close the server side
          cursor if it exists.
        */
        char buff[MYSQL_STMT_HEADER]; /* packet header: 4 bytes for stmt id */
        int4store(buff, stmt->stmt_id);
4957
        if ((*mysql->methods->advanced_command)(mysql, COM_STMT_RESET, buff,
holyfoot/hf@mysql.com/deer.(none)'s avatar
holyfoot/hf@mysql.com/deer.(none) committed
4958
                                                sizeof(buff), 0, 0, 0, NULL))
4959 4960 4961 4962 4963 4964
        {
          set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                          mysql->net.sqlstate);
          stmt->state= MYSQL_STMT_INIT_DONE;
          return 1;
        }
4965
        stmt_clear_error(stmt);
4966 4967 4968 4969
      }
    }
    stmt->state= MYSQL_STMT_PREPARE_DONE;
  }
4970 4971 4972 4973 4974 4975 4976 4977
  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 */
4978
  DBUG_RETURN(reset_stmt_handle(stmt, RESET_LONG_DATA | RESET_STORE_RESULT));
4979 4980
}

4981
/********************************************************************
4982
 statement error handling and close
4983
*********************************************************************/
4984

4985
/*
4986
  Close the statement handle by freeing all alloced resources
4987

4988
  SYNOPSIS
4989
    mysql_stmt_close()
4990
    stmt	       Statement handle
4991

4992 4993 4994 4995
  RETURN VALUES
    0	ok
    1	error
*/
4996

4997
my_bool STDCALL mysql_stmt_close(MYSQL_STMT *stmt)
4998
{
4999 5000 5001
  MYSQL *mysql= stmt->mysql;
  int rc= 0;
  DBUG_ENTER("mysql_stmt_close");
5002

5003
  free_root(&stmt->result.alloc, MYF(0));
5004 5005 5006
  free_root(&stmt->mem_root, MYF(0));

  if (mysql)
5007
  {
5008
    mysql->stmts= list_delete(mysql->stmts, &stmt->list);
5009 5010 5011 5012 5013
    /*
      Clear NET error state: if the following commands come through
      successfully, connection will still be usable for other commands.
    */
    net_clear_error(&mysql->net);
5014
    if ((int) stmt->state > (int) MYSQL_STMT_INIT_DONE)
5015
    {
5016
      char buff[MYSQL_STMT_HEADER];             /* 4 bytes - stmt id */
5017 5018 5019 5020 5021

      if (mysql->unbuffered_fetch_owner == &stmt->unbuffered_fetch_cancelled)
        mysql->unbuffered_fetch_owner= 0;
      if (mysql->status != MYSQL_STATUS_READY)
      {
5022
        /*
5023 5024 5025
          Flush result set of the connection. If it does not belong
          to this statement, set a warning.
        */
5026
        (*mysql->methods->flush_use_result)(mysql);
5027 5028 5029 5030 5031
        if (mysql->unbuffered_fetch_owner)
          *mysql->unbuffered_fetch_owner= TRUE;
        mysql->status= MYSQL_STATUS_READY;
      }
      int4store(buff, stmt->stmt_id);
5032
      if ((rc= stmt_command(mysql, COM_STMT_CLOSE, buff, 4, stmt)))
5033 5034 5035 5036
      {
        set_stmt_errmsg(stmt, mysql->net.last_error, mysql->net.last_errno,
                        mysql->net.sqlstate);
      }
5037
    }
5038
  }
5039

5040
  my_free((gptr) stmt, MYF(MY_WME));
5041

5042
  DBUG_RETURN(test(rc));
5043 5044
}

5045 5046 5047 5048 5049 5050 5051 5052
/*
  Reset the statement buffers in server
*/

my_bool STDCALL mysql_stmt_reset(MYSQL_STMT *stmt)
{
  DBUG_ENTER("mysql_stmt_reset");
  DBUG_ASSERT(stmt != 0);
5053 5054 5055 5056
  if (!stmt->mysql)
  {
    /* mysql can be reset in mysql_close called from mysql_reconnect */
    set_stmt_error(stmt, CR_SERVER_LOST, unknown_sqlstate);
5057 5058
    DBUG_RETURN(1);
  }
5059 5060
  /* Reset the client and server sides of the prepared statement */
  DBUG_RETURN(reset_stmt_handle(stmt, RESET_SERVER_SIDE | RESET_LONG_DATA));
5061 5062
}

5063 5064 5065 5066 5067 5068 5069
/*
  Return statement error code
*/

uint STDCALL mysql_stmt_errno(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_errno");
5070
  DBUG_RETURN(stmt->last_errno);
5071 5072
}

5073 5074 5075 5076 5077 5078
const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_sqlstate");
  DBUG_RETURN(stmt->sqlstate);
}

5079 5080 5081 5082 5083 5084 5085
/*
  Return statement error message
*/

const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt)
{
  DBUG_ENTER("mysql_stmt_error");
5086
  DBUG_RETURN(stmt->last_error);
5087 5088
}

5089

5090 5091 5092 5093
/********************************************************************
 Transactional APIs
*********************************************************************/

5094 5095 5096 5097
/*
  Commit the current transaction
*/

5098
my_bool STDCALL mysql_commit(MYSQL * mysql)
5099 5100
{
  DBUG_ENTER("mysql_commit");
5101
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "commit", 6));
5102 5103 5104
}

/*
5105
  Rollback the current transaction
5106 5107
*/

5108
my_bool STDCALL mysql_rollback(MYSQL * mysql)
5109 5110
{
  DBUG_ENTER("mysql_rollback");
5111
  DBUG_RETURN((my_bool) mysql_real_query(mysql, "rollback", 8));
5112 5113 5114 5115 5116 5117 5118
}


/*
  Set autocommit to either true or false
*/

5119
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode)
5120 5121 5122 5123
{
  DBUG_ENTER("mysql_autocommit");
  DBUG_PRINT("enter", ("mode : %d", auto_mode));

5124 5125 5126
  DBUG_RETURN((my_bool) mysql_real_query(mysql, auto_mode ?
                                         "set autocommit=1":"set autocommit=0",
                                         16));
5127
}
5128 5129 5130


/********************************************************************
5131
 Multi query execution + SPs APIs
5132 5133 5134
*********************************************************************/

/*
5135 5136
  Returns true/false to indicate whether any more query results exist
  to be read using mysql_next_result()
5137 5138 5139 5140
*/

my_bool STDCALL mysql_more_results(MYSQL *mysql)
{
5141
  my_bool res;
5142
  DBUG_ENTER("mysql_more_results");
5143 5144

  res= ((mysql->last_used_con->server_status & SERVER_MORE_RESULTS_EXISTS) ?
5145
	1: 0);
5146
  DBUG_PRINT("exit",("More results exists ? %d", res));
5147
  DBUG_RETURN(res);
5148 5149
}

5150

5151 5152 5153
/*
  Reads and returns the next query results
*/
5154
int STDCALL mysql_next_result(MYSQL *mysql)
5155
{
5156
  DBUG_ENTER("mysql_next_result");
5157

5158 5159 5160 5161 5162 5163 5164 5165
  if (mysql->status != MYSQL_STATUS_READY)
  {
    strmov(mysql->net.sqlstate, unknown_sqlstate);
    strmov(mysql->net.last_error,
	   ER(mysql->net.last_errno=CR_COMMANDS_OUT_OF_SYNC));
    DBUG_RETURN(1);
  }

5166 5167
  mysql->net.last_error[0]= 0;
  mysql->net.last_errno= 0;
5168
  strmov(mysql->net.sqlstate, not_error_sqlstate);
5169 5170 5171
  mysql->affected_rows= ~(my_ulonglong) 0;

  if (mysql->last_used_con->server_status & SERVER_MORE_RESULTS_EXISTS)
5172 5173
    DBUG_RETURN((*mysql->methods->next_result)(mysql));

5174
  DBUG_RETURN(-1);				/* No more results */
5175
}
hf@deer.(none)'s avatar
hf@deer.(none) committed
5176

5177

hf@deer.(none)'s avatar
hf@deer.(none) committed
5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
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);
}