~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/session.cc

  • Committer: Padraig O'Sullivan
  • Date: 2009-03-21 20:26:28 UTC
  • mto: (960.2.5 mordred)
  • mto: This revision was merged to the branch mainline in revision 961.
  • Revision ID: osullivan.padraig@gmail.com-20090321202628-nh6qsi825m4d4av6
Removing the queues.[h,cc] files from the mysys directory. The only place
where they are needed now is in the MyISAM storage engine. Thus, I moved the
files there and updated the files in the MyISAM storage engine
appropriately.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* Copyright (C) 2000-2006 MySQL AB
2
 
 
3
 
   This program is free software; you can redistribute it and/or modify
4
 
   it under the terms of the GNU General Public License as published by
5
 
   the Free Software Foundation; version 2 of the License.
6
 
 
7
 
   This program is distributed in the hope that it will be useful,
8
 
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 
   GNU General Public License for more details.
11
 
 
12
 
   You should have received a copy of the GNU General Public License
13
 
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
 
 
16
 
 
17
 
/*****************************************************************************
18
 
**
19
 
** This file implements classes defined in sql_class.h
20
 
** Especially the classes to handle a result from a select
21
 
**
22
 
*****************************************************************************/
 
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 
3
 *
 
4
 *  Copyright (C) 2008 Sun Microsystems
 
5
 *
 
6
 *  This program is free software; you can redistribute it and/or modify
 
7
 *  it under the terms of the GNU General Public License as published by
 
8
 *  the Free Software Foundation; version 2 of the License.
 
9
 *
 
10
 *  This program is distributed in the hope that it will be useful,
 
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
 *  GNU General Public License for more details.
 
14
 *
 
15
 *  You should have received a copy of the GNU General Public License
 
16
 *  along with this program; if not, write to the Free Software
 
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
18
 */
 
19
 
23
20
#include <drizzled/server_includes.h>
24
 
#include "rpl_rli.h"
25
 
#include "rpl_record.h"
26
 
#include "log_event.h"
 
21
#include <drizzled/session.h>
27
22
#include <sys/stat.h>
28
 
#include <mysys/thr_alarm.h>
29
23
#include <mysys/mysys_err.h>
30
 
#include <drizzled/drizzled_error_messages.h>
 
24
#include <drizzled/error.h>
 
25
#include <drizzled/query_id.h>
 
26
#include <drizzled/data_home.h>
 
27
#include <drizzled/sql_base.h>
 
28
#include <drizzled/lock.h>
 
29
#include <drizzled/item/cache.h>
 
30
#include <drizzled/item/float.h>
 
31
#include <drizzled/item/return_int.h>
 
32
#include <drizzled/item/empty_string.h>
 
33
#include <drizzled/show.h>
 
34
#include <drizzled/plugin_scheduling.h>
 
35
#include <libdrizzleclient/errmsg.h>
31
36
 
 
37
extern scheduling_st thread_scheduler;
32
38
/*
33
39
  The following is used to initialise Table_ident with a internal
34
40
  table name
36
42
char internal_table_name[2]= "*";
37
43
char empty_c_string[1]= {0};    /* used for not defined db */
38
44
 
39
 
const char * const THD::DEFAULT_WHERE= "field list";
40
 
 
 
45
const char * const Session::DEFAULT_WHERE= "field list";
 
46
extern pthread_key_t THR_Session;
 
47
extern pthread_key_t THR_Mem_root;
41
48
 
42
49
/*****************************************************************************
43
50
** Instansiate templates
58
65
/****************************************************************************
59
66
** User variables
60
67
****************************************************************************/
61
 
 
62
68
extern "C" unsigned char *get_var_key(user_var_entry *entry, size_t *length,
63
 
                              bool not_used __attribute__((unused)))
 
69
                              bool )
64
70
{
65
71
  *length= entry->name.length;
66
72
  return (unsigned char*) entry->name.str;
81
87
         !strcmp(field_name.str, other.field_name.str);
82
88
}
83
89
 
84
 
/**
85
 
  Construct an (almost) deep copy of this key. Only those
86
 
  elements that are known to never change are not copied.
87
 
  If out of memory, a partial copy is returned and an error is set
88
 
  in THD.
89
 
*/
90
 
 
91
 
Key::Key(const Key &rhs, MEM_ROOT *mem_root)
92
 
  :type(rhs.type),
93
 
  key_create_info(rhs.key_create_info),
94
 
  columns(rhs.columns, mem_root),
95
 
  name(rhs.name),
96
 
  generated(rhs.generated)
97
 
{
98
 
  list_copy_and_replace_each_value(columns, mem_root);
99
 
}
100
 
 
101
 
/**
102
 
  Construct an (almost) deep copy of this foreign key. Only those
103
 
  elements that are known to never change are not copied.
104
 
  If out of memory, a partial copy is returned and an error is set
105
 
  in THD.
106
 
*/
107
 
 
108
 
Foreign_key::Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root)
109
 
  :Key(rhs),
110
 
  ref_table(rhs.ref_table),
111
 
  ref_columns(rhs.ref_columns),
112
 
  delete_opt(rhs.delete_opt),
113
 
  update_opt(rhs.update_opt),
114
 
  match_opt(rhs.match_opt)
115
 
{
116
 
  list_copy_and_replace_each_value(ref_columns, mem_root);
117
 
}
118
 
 
119
 
/*
120
 
  Test if a foreign key (= generated key) is a prefix of the given key
121
 
  (ignoring key name, key type and order of columns)
122
 
 
123
 
  NOTES:
124
 
    This is only used to test if an index for a FOREIGN KEY exists
125
 
 
126
 
  IMPLEMENTATION
127
 
    We only compare field names
128
 
 
129
 
  RETURN
130
 
    0   Generated key is a prefix of other key
131
 
    1   Not equal
132
 
*/
133
 
 
134
 
bool foreign_key_prefix(Key *a, Key *b)
135
 
{
136
 
  /* Ensure that 'a' is the generated key */
137
 
  if (a->generated)
138
 
  {
139
 
    if (b->generated && a->columns.elements > b->columns.elements)
140
 
      std::swap(a, b);                       // Put shorter key in 'a'
141
 
  }
142
 
  else
143
 
  {
144
 
    if (!b->generated)
145
 
      return true;                              // No foreign key
146
 
    std::swap(a, b);                       // Put generated key in 'a'
147
 
  }
148
 
 
149
 
  /* Test if 'a' is a prefix of 'b' */
150
 
  if (a->columns.elements > b->columns.elements)
151
 
    return true;                                // Can't be prefix
152
 
 
153
 
  List_iterator<Key_part_spec> col_it1(a->columns);
154
 
  List_iterator<Key_part_spec> col_it2(b->columns);
155
 
  const Key_part_spec *col1, *col2;
156
 
 
157
 
#ifdef ENABLE_WHEN_INNODB_CAN_HANDLE_SWAPED_FOREIGN_KEY_COLUMNS
158
 
  while ((col1= col_it1++))
159
 
  {
160
 
    bool found= 0;
161
 
    col_it2.rewind();
162
 
    while ((col2= col_it2++))
163
 
    {
164
 
      if (*col1 == *col2)
165
 
      {
166
 
        found= true;
167
 
        break;
168
 
      }
169
 
    }
170
 
    if (!found)
171
 
      return true;                              // Error
172
 
  }
173
 
  return false;                                 // Is prefix
174
 
#else
175
 
  while ((col1= col_it1++))
176
 
  {
177
 
    col2= col_it2++;
178
 
    if (!(*col1 == *col2))
179
 
      return true;
180
 
  }
181
 
  return false;                                 // Is prefix
182
 
#endif
183
 
}
184
 
 
185
 
 
186
90
/****************************************************************************
187
91
** Thread specific functions
188
92
****************************************************************************/
200
104
extern "C" int mysql_tmpfile(const char *prefix)
201
105
{
202
106
  char filename[FN_REFLEN];
203
 
  File fd = create_temp_file(filename, mysql_tmpdir, prefix,
204
 
                             O_CREAT | O_EXCL | O_RDWR | O_TEMPORARY,
 
107
  File fd = create_temp_file(filename, drizzle_tmpdir, prefix,
 
108
                             O_CREAT | O_EXCL | O_RDWR,
205
109
                             MYF(MY_WME));
206
110
  if (fd >= 0) {
207
 
    /*
208
 
      This can be removed once the following bug is fixed:
209
 
      Bug #28903  create_temp_file() doesn't honor O_TEMPORARY option
210
 
                  (file not removed) (Unix)
211
 
    */
212
111
    unlink(filename);
213
112
  }
214
113
 
217
116
 
218
117
 
219
118
extern "C"
220
 
int thd_in_lock_tables(const THD *thd)
221
 
{
222
 
  return test(thd->in_lock_tables);
223
 
}
224
 
 
225
 
 
226
 
extern "C"
227
 
int thd_tablespace_op(const THD *thd)
228
 
{
229
 
  return test(thd->tablespace_op);
230
 
}
231
 
 
232
 
 
233
 
extern "C"
234
 
const char *set_thd_proc_info(THD *thd, const char *info,
235
 
                              const char *calling_function __attribute__((unused)),
236
 
                              const char *calling_file __attribute__((unused)),
237
 
                              const unsigned int calling_line __attribute__((unused)))
238
 
{
239
 
  const char *old_info= thd->get_proc_info();
240
 
  thd->set_proc_info(info);
241
 
  return old_info;
242
 
}
243
 
 
244
 
extern "C"
245
 
void **thd_ha_data(const THD *thd, const struct handlerton *hton)
246
 
{
247
 
  return (void **) &thd->ha_data[hton->slot].ha_ptr;
248
 
}
249
 
 
250
 
extern "C"
251
 
int64_t thd_test_options(const THD *thd, int64_t test_options)
252
 
{
253
 
  return thd->options & test_options;
254
 
}
255
 
 
256
 
extern "C"
257
 
int thd_sql_command(const THD *thd)
258
 
{
259
 
  return (int) thd->lex->sql_command;
260
 
}
261
 
 
262
 
extern "C"
263
 
int thd_tx_isolation(const THD *thd)
264
 
{
265
 
  return (int) thd->variables.tx_isolation;
266
 
}
267
 
 
268
 
extern "C"
269
 
void thd_inc_row_count(THD *thd)
270
 
{
271
 
  thd->row_count++;
272
 
}
273
 
 
274
 
/**
275
 
  Clear this diagnostics area. 
276
 
 
277
 
  Normally called at the end of a statement.
278
 
*/
279
 
 
280
 
void
281
 
Diagnostics_area::reset_diagnostics_area()
282
 
{
283
 
  can_overwrite_status= false;
284
 
  /** Don't take chances in production */
285
 
  m_message[0]= '\0';
286
 
  m_sql_errno= 0;
287
 
  m_server_status= 0;
288
 
  m_affected_rows= 0;
289
 
  m_last_insert_id= 0;
290
 
  m_total_warn_count= 0;
291
 
  is_sent= false;
292
 
  /** Tiny reset in debug mode to see garbage right away */
293
 
  m_status= DA_EMPTY;
294
 
}
295
 
 
296
 
 
297
 
/**
298
 
  Set OK status -- ends commands that do not return a
299
 
  result set, e.g. INSERT/UPDATE/DELETE.
300
 
*/
301
 
 
302
 
void
303
 
Diagnostics_area::set_ok_status(THD *thd, ha_rows affected_rows_arg,
304
 
                                uint64_t last_insert_id_arg,
305
 
                                const char *message_arg)
306
 
{
307
 
  assert(! is_set());
308
 
  /*
309
 
    In production, refuse to overwrite an error or a custom response
310
 
    with an OK packet.
311
 
  */
312
 
  if (is_error() || is_disabled())
313
 
    return;
314
 
  /** Only allowed to report success if has not yet reported an error */
315
 
 
316
 
  m_server_status= thd->server_status;
317
 
  m_total_warn_count= thd->total_warn_count;
318
 
  m_affected_rows= affected_rows_arg;
319
 
  m_last_insert_id= last_insert_id_arg;
320
 
  if (message_arg)
321
 
    strmake(m_message, message_arg, sizeof(m_message) - 1);
322
 
  else
323
 
    m_message[0]= '\0';
324
 
  m_status= DA_OK;
325
 
}
326
 
 
327
 
 
328
 
/**
329
 
  Set EOF status.
330
 
*/
331
 
 
332
 
void
333
 
Diagnostics_area::set_eof_status(THD *thd)
334
 
{
335
 
  /** Only allowed to report eof if has not yet reported an error */
336
 
 
337
 
  assert(! is_set());
338
 
  /*
339
 
    In production, refuse to overwrite an error or a custom response
340
 
    with an EOF packet.
341
 
  */
342
 
  if (is_error() || is_disabled())
343
 
    return;
344
 
 
345
 
  m_server_status= thd->server_status;
346
 
  /*
347
 
    If inside a stored procedure, do not return the total
348
 
    number of warnings, since they are not available to the client
349
 
    anyway.
350
 
  */
351
 
  m_total_warn_count= thd->total_warn_count;
352
 
 
353
 
  m_status= DA_EOF;
354
 
}
355
 
 
356
 
/**
357
 
  Set ERROR status.
358
 
*/
359
 
 
360
 
void
361
 
Diagnostics_area::set_error_status(THD *thd __attribute__((unused)),
362
 
                                   uint32_t sql_errno_arg,
363
 
                                   const char *message_arg)
364
 
{
365
 
  /*
366
 
    Only allowed to report error if has not yet reported a success
367
 
    The only exception is when we flush the message to the client,
368
 
    an error can happen during the flush.
369
 
  */
370
 
  assert(! is_set() || can_overwrite_status);
371
 
  /*
372
 
    In production, refuse to overwrite a custom response with an
373
 
    ERROR packet.
374
 
  */
375
 
  if (is_disabled())
376
 
    return;
377
 
 
378
 
  m_sql_errno= sql_errno_arg;
379
 
  strmake(m_message, message_arg, sizeof(m_message) - 1);
380
 
 
381
 
  m_status= DA_ERROR;
382
 
}
383
 
 
384
 
 
385
 
/**
386
 
  Mark the diagnostics area as 'DISABLED'.
387
 
 
388
 
  This is used in rare cases when the COM_ command at hand sends a response
389
 
  in a custom format. One example is the query cache, another is
390
 
  COM_STMT_PREPARE.
391
 
*/
392
 
 
393
 
void
394
 
Diagnostics_area::disable_status()
395
 
{
396
 
  assert(! is_set());
397
 
  m_status= DA_DISABLED;
398
 
}
399
 
 
400
 
 
401
 
THD::THD()
 
119
int session_in_lock_tables(const Session *session)
 
120
{
 
121
  return test(session->in_lock_tables);
 
122
}
 
123
 
 
124
 
 
125
extern "C"
 
126
int session_tablespace_op(const Session *session)
 
127
{
 
128
  return test(session->tablespace_op);
 
129
}
 
130
 
 
131
 
 
132
/**
 
133
   Set the process info field of the Session structure.
 
134
 
 
135
   This function is used by plug-ins. Internally, the
 
136
   Session::set_proc_info() function should be used.
 
137
 
 
138
   @see Session::set_proc_info
 
139
 */
 
140
extern "C" void
 
141
set_session_proc_info(Session *session, const char *info)
 
142
{
 
143
  session->set_proc_info(info);
 
144
}
 
145
 
 
146
extern "C"
 
147
const char *get_session_proc_info(Session *session)
 
148
{
 
149
  return session->get_proc_info();
 
150
}
 
151
 
 
152
extern "C"
 
153
void **session_ha_data(const Session *session, const struct handlerton *hton)
 
154
{
 
155
  return (void **) &session->ha_data[hton->slot].ha_ptr;
 
156
}
 
157
 
 
158
extern "C"
 
159
int64_t session_test_options(const Session *session, int64_t test_options)
 
160
{
 
161
  return session->options & test_options;
 
162
}
 
163
 
 
164
extern "C"
 
165
int session_sql_command(const Session *session)
 
166
{
 
167
  return (int) session->lex->sql_command;
 
168
}
 
169
 
 
170
extern "C"
 
171
int session_tx_isolation(const Session *session)
 
172
{
 
173
  return (int) session->variables.tx_isolation;
 
174
}
 
175
 
 
176
extern "C"
 
177
void session_inc_row_count(Session *session)
 
178
{
 
179
  session->row_count++;
 
180
}
 
181
 
 
182
Session::Session()
402
183
   :Statement(&main_lex, &main_mem_root,
403
184
              /* statement id */ 0),
404
 
   Open_tables_state(refresh_version), rli_fake(0),
 
185
   Open_tables_state(refresh_version),
405
186
   lock_id(&main_lock_id),
406
 
   user_time(0), in_sub_stmt(0),
407
 
   binlog_table_maps(0), binlog_flags(0UL),
 
187
   user_time(0),
408
188
   arg_of_last_insert_id_function(false),
409
189
   first_successful_insert_id_in_prev_stmt(0),
410
 
   first_successful_insert_id_in_prev_stmt_for_binlog(0),
411
190
   first_successful_insert_id_in_cur_stmt(0),
412
 
   stmt_depends_on_first_successful_insert_id_in_prev_stmt(false),
413
191
   global_read_lock(0),
414
192
   is_fatal_error(0),
415
193
   transaction_rollback_request(0),
416
194
   is_fatal_sub_stmt_error(0),
417
 
   rand_used(0),
418
 
   time_zone_used(0),
419
195
   in_lock_tables(0),
420
 
   bootstrap(0),
421
196
   derived_tables_processing(false),
422
 
   m_lip(NULL)
 
197
   m_lip(NULL),
 
198
   scheduler(0)
423
199
{
424
 
  ulong tmp;
 
200
  uint64_t tmp;
425
201
 
426
202
  /*
427
203
    Pass nominal parameters to init_alloc_root only to ensure that
431
207
  init_sql_alloc(&main_mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
432
208
  thread_stack= 0;
433
209
  catalog= (char*)"std"; // the only catalog we have for now
434
 
  main_security_ctx.init();
435
 
  security_ctx= &main_security_ctx;
436
210
  some_tables_deleted=no_errors=password= 0;
437
 
  query_start_used= 0;
438
211
  count_cuted_fields= CHECK_FIELD_IGNORE;
439
212
  killed= NOT_KILLED;
440
213
  col_access=0;
441
 
  is_slave_error= thread_specific_used= false;
442
 
  hash_clear(&handler_tables_hash);
 
214
  thread_specific_used= false;
443
215
  tmp_table=0;
444
216
  used_tables=0;
445
217
  cuted_fields= sent_row_count= row_count= 0L;
446
218
  limit_found_rows= 0;
447
219
  row_count_func= -1;
448
220
  statement_id_counter= 0UL;
449
 
  // Must be reset to handle error with THD's created for init of mysqld
 
221
  // Must be reset to handle error with Session's created for init of mysqld
450
222
  lex->current_select= 0;
451
223
  start_time=(time_t) 0;
452
224
  start_utime= 0L;
453
225
  utime_after_lock= 0L;
454
 
  current_linfo =  0;
455
 
  slave_thread = 0;
456
226
  memset(&variables, 0, sizeof(variables));
457
227
  thread_id= 0;
458
 
  one_shot_set= 0;
459
228
  file_id = 0;
460
229
  query_id= 0;
461
230
  warn_id= 0;
462
231
  db_charset= global_system_variables.collation_database;
463
232
  memset(ha_data, 0, sizeof(ha_data));
 
233
  replication_data= 0;
464
234
  mysys_var=0;
465
 
  binlog_evt_union.do_union= false;
466
 
  dbug_sentry=THD_SENTRY_MAGIC;
467
 
  net.vio=0;
 
235
  dbug_sentry=Session_SENTRY_MAGIC;
 
236
  net.vio= 0;
468
237
  client_capabilities= 0;                       // minimalistic client
469
238
  system_thread= NON_SYSTEM_THREAD;
470
 
  cleanup_done= abort_on_warning= no_warnings_for_error= 0;
 
239
  cleanup_done= abort_on_warning= no_warnings_for_error= false;
471
240
  peer_port= 0;                                 // For SHOW PROCESSLIST
472
 
  transaction.m_pending_rows_event= 0;
473
241
  transaction.on= 1;
474
242
  pthread_mutex_init(&LOCK_delete, MY_MUTEX_INIT_FAST);
475
243
 
476
244
  /* Variables with default values */
477
245
  proc_info="login";
478
 
  where= THD::DEFAULT_WHERE;
 
246
  where= Session::DEFAULT_WHERE;
479
247
  server_id = ::server_id;
480
 
  slave_net = 0;
481
248
  command=COM_CONNECT;
482
249
  *scramble= '\0';
483
250
 
484
251
  init();
485
252
  /* Initialize sub structures */
486
253
  init_sql_alloc(&warn_root, WARN_ALLOC_BLOCK_SIZE, WARN_ALLOC_PREALLOC_SIZE);
487
 
  user_connect=(USER_CONN *)0;
488
254
  hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
489
255
            (hash_get_key) get_var_key,
490
256
            (hash_free_key) free_user_var, 0);
491
257
 
492
 
  /* For user vars replication*/
493
 
  if (opt_bin_log)
494
 
    my_init_dynamic_array(&user_var_events,
495
 
                          sizeof(BINLOG_USER_VAR_EVENT *), 16, 16);
496
 
  else
497
 
    memset(&user_var_events, 0, sizeof(user_var_events));
498
 
 
499
258
  /* Protocol */
500
259
  protocol= &protocol_text;                     // Default protocol
501
260
  protocol_text.init(this);
502
261
 
 
262
  const Query_id& local_query_id= Query_id::get_query_id();
503
263
  tablespace_op= false;
504
264
  tmp= sql_rnd();
505
 
  randominit(&rand, tmp + (ulong) &rand, tmp + (ulong) ::global_query_id);
 
265
  drizzleclient_randominit(&rand, tmp + (uint64_t) &rand,
 
266
                           tmp + (uint64_t)local_query_id.value());
506
267
  substitute_null_with_insert_id = false;
507
268
  thr_lock_info_init(&lock_info); /* safety: will be reset after start */
508
269
  thr_lock_owner_init(&main_lock_id, &lock_info);
511
272
}
512
273
 
513
274
 
514
 
void THD::push_internal_handler(Internal_error_handler *handler)
 
275
void Session::push_internal_handler(Internal_error_handler *handler)
515
276
{
516
277
  /*
517
278
    TODO: The current implementation is limited to 1 handler at a time only.
518
 
    THD and sp_rcontext need to be modified to use a common handler stack.
 
279
    Session and sp_rcontext need to be modified to use a common handler stack.
519
280
  */
520
281
  assert(m_internal_handler == NULL);
521
282
  m_internal_handler= handler;
522
283
}
523
284
 
524
285
 
525
 
bool THD::handle_error(uint32_t sql_errno, const char *message,
 
286
bool Session::handle_error(uint32_t sql_errno, const char *message,
526
287
                       DRIZZLE_ERROR::enum_warning_level level)
527
288
{
528
289
  if (m_internal_handler)
534
295
}
535
296
 
536
297
 
537
 
void THD::pop_internal_handler()
 
298
void Session::pop_internal_handler()
538
299
{
539
300
  assert(m_internal_handler != NULL);
540
301
  m_internal_handler= NULL;
541
302
}
542
303
 
543
 
extern "C"
544
 
void *thd_alloc(DRIZZLE_THD thd, unsigned int size)
545
 
{
546
 
  return thd->alloc(size);
547
 
}
548
 
 
549
 
extern "C"
550
 
void *thd_calloc(DRIZZLE_THD thd, unsigned int size)
551
 
{
552
 
  return thd->calloc(size);
553
 
}
554
 
 
555
 
extern "C"
556
 
char *thd_strdup(DRIZZLE_THD thd, const char *str)
557
 
{
558
 
  return thd->strdup(str);
559
 
}
560
 
 
561
 
extern "C"
562
 
char *thd_strmake(DRIZZLE_THD thd, const char *str, unsigned int size)
563
 
{
564
 
  return thd->strmake(str, size);
565
 
}
566
 
 
567
 
extern "C"
568
 
LEX_STRING *thd_make_lex_string(THD *thd, LEX_STRING *lex_str,
569
 
                                const char *str, unsigned int size,
570
 
                                int allocate_lex_string)
571
 
{
572
 
  return thd->make_lex_string(lex_str, str, size,
573
 
                              (bool) allocate_lex_string);
574
 
}
575
 
 
576
 
extern "C"
577
 
void *thd_memdup(DRIZZLE_THD thd, const void* str, unsigned int size)
578
 
{
579
 
  return thd->memdup(str, size);
580
 
}
581
 
 
582
 
extern "C"
583
 
void thd_get_xid(const DRIZZLE_THD thd, DRIZZLE_XID *xid)
584
 
{
585
 
  *xid = *(DRIZZLE_XID *) &thd->transaction.xid_state.xid;
586
 
}
 
304
#if defined(__cplusplus)
 
305
extern "C" {
 
306
#endif
 
307
 
 
308
void *session_alloc(Session *session, unsigned int size)
 
309
{
 
310
  return session->alloc(size);
 
311
}
 
312
 
 
313
void *session_calloc(Session *session, unsigned int size)
 
314
{
 
315
  return session->calloc(size);
 
316
}
 
317
 
 
318
char *session_strdup(Session *session, const char *str)
 
319
{
 
320
  return session->strdup(str);
 
321
}
 
322
 
 
323
char *session_strmake(Session *session, const char *str, unsigned int size)
 
324
{
 
325
  return session->strmake(str, size);
 
326
}
 
327
 
 
328
void *session_memdup(Session *session, const void* str, unsigned int size)
 
329
{
 
330
  return session->memdup(str, size);
 
331
}
 
332
 
 
333
void session_get_xid(const Session *session, DRIZZLE_XID *xid)
 
334
{
 
335
  *xid = *(DRIZZLE_XID *) &session->transaction.xid_state.xid;
 
336
}
 
337
 
 
338
#if defined(__cplusplus)
 
339
}
 
340
#endif
587
341
 
588
342
/*
589
343
  Init common variables that has to be reset on start and on change_user
590
344
*/
591
345
 
592
 
void THD::init(void)
 
346
void Session::init(void)
593
347
{
594
348
  pthread_mutex_lock(&LOCK_global_system_variables);
595
 
  plugin_thdvar_init(this);
596
 
  variables.time_format= date_time_format_copy((THD*) 0,
597
 
                                               variables.time_format);
598
 
  variables.date_format= date_time_format_copy((THD*) 0,
599
 
                                               variables.date_format);
600
 
  variables.datetime_format= date_time_format_copy((THD*) 0,
601
 
                                                   variables.datetime_format);
 
349
  plugin_sessionvar_init(this);
602
350
  /*
603
351
    variables= global_system_variables above has reset
604
352
    variables.pseudo_thread_id to 0. We need to correct it here to
607
355
  variables.pseudo_thread_id= thread_id;
608
356
  pthread_mutex_unlock(&LOCK_global_system_variables);
609
357
  server_status= SERVER_STATUS_AUTOCOMMIT;
610
 
  options= thd_startup_options;
 
358
  options= session_startup_options;
611
359
 
612
360
  if (variables.max_join_size == HA_POS_ERROR)
613
361
    options |= OPTION_BIG_SELECTS;
616
364
 
617
365
  transaction.all.modified_non_trans_table= transaction.stmt.modified_non_trans_table= false;
618
366
  open_options=ha_open_options;
619
 
  update_lock_default= (variables.low_priority_updates ?
620
 
                        TL_WRITE_LOW_PRIORITY :
621
 
                        TL_WRITE);
 
367
  update_lock_default= TL_WRITE;
622
368
  session_tx_isolation= (enum_tx_isolation) variables.tx_isolation;
623
369
  warn_list.empty();
624
370
  memset(warn_count, 0, sizeof(warn_count));
625
371
  total_warn_count= 0;
626
372
  update_charset();
627
 
  reset_current_stmt_binlog_row_based();
628
373
  memset(&status_var, 0, sizeof(status_var));
629
374
}
630
375
 
631
376
 
632
377
/*
633
 
  Init THD for query processing.
 
378
  Init Session for query processing.
634
379
  This has to be called once before we call mysql_parse.
635
 
  See also comments in sql_class.h.
 
380
  See also comments in session.h.
636
381
*/
637
382
 
638
 
void THD::init_for_queries()
 
383
void Session::init_for_queries()
639
384
{
640
 
  set_time(); 
 
385
  set_time();
641
386
  ha_enable_transaction(this,true);
642
387
 
643
388
  reset_root_defaults(mem_root, variables.query_alloc_block_size,
646
391
                      variables.trans_alloc_block_size,
647
392
                      variables.trans_prealloc_size);
648
393
  transaction.xid_state.xid.null();
649
 
  transaction.xid_state.in_thd=1;
 
394
  transaction.xid_state.in_session=1;
650
395
}
651
396
 
652
397
 
653
398
/* Do operations that may take a long time */
654
399
 
655
 
void THD::cleanup(void)
 
400
void Session::cleanup(void)
656
401
{
657
 
  assert(cleanup_done == 0);
 
402
  assert(cleanup_done == false);
658
403
 
659
404
  killed= KILL_CONNECTION;
660
405
#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE
672
417
    lock=locked_tables; locked_tables=0;
673
418
    close_thread_tables(this);
674
419
  }
675
 
  mysql_ha_cleanup(this);
676
 
  delete_dynamic(&user_var_events);
677
420
  hash_free(&user_vars);
678
 
  close_temporary_tables(this);
679
 
  free((char*) variables.time_format);
680
 
  free((char*) variables.date_format);
681
 
  free((char*) variables.datetime_format);
682
 
  
 
421
  close_temporary_tables();
 
422
 
683
423
  if (global_read_lock)
684
424
    unlock_global_read_lock(this);
685
425
 
686
 
  cleanup_done=1;
 
426
  cleanup_done= true;
687
427
  return;
688
428
}
689
429
 
690
 
THD::~THD()
 
430
Session::~Session()
691
431
{
692
 
  THD_CHECK_SENTRY(this);
693
 
  /* Ensure that no one is using THD */
694
 
  pthread_mutex_lock(&LOCK_delete);
695
 
  pthread_mutex_unlock(&LOCK_delete);
 
432
  Session_CHECK_SENTRY(this);
696
433
  add_to_status(&global_status_var, &status_var);
697
434
 
 
435
  if (drizzleclient_vio_ok())
 
436
  {
 
437
    if (global_system_variables.log_warnings)
 
438
        errmsg_printf(ERRMSG_LVL_WARN, ER(ER_FORCING_CLOSE),my_progname,
 
439
                      thread_id,
 
440
                      (security_ctx.user.c_str() ?
 
441
                       security_ctx.user.c_str() : ""));
 
442
    disconnect(0, false);
 
443
  }
 
444
 
698
445
  /* Close connection */
699
446
  if (net.vio)
700
447
  {
701
 
    net_close(&net);
702
 
    net_end(&net);
 
448
    drizzleclient_net_close(&net);
 
449
    drizzleclient_net_end(&net);
703
450
  }
704
 
  if (!cleanup_done)
 
451
  if (cleanup_done == false)
705
452
    cleanup();
706
453
 
707
454
  ha_close_connection(this);
708
 
  plugin_thdvar_cleanup(this);
 
455
  plugin_sessionvar_cleanup(this);
709
456
 
710
 
  main_security_ctx.destroy();
711
457
  if (db)
712
458
  {
713
459
    free(db);
716
462
  free_root(&warn_root,MYF(0));
717
463
  free_root(&transaction.mem_root,MYF(0));
718
464
  mysys_var=0;                                  // Safety (shouldn't be needed)
 
465
  dbug_sentry= Session_SENTRY_GONE;
 
466
 
 
467
  free_root(&main_mem_root, MYF(0));
 
468
  pthread_setspecific(THR_Session,  0);
 
469
 
 
470
 
 
471
  /* Ensure that no one is using Session */
 
472
  pthread_mutex_unlock(&LOCK_delete);
719
473
  pthread_mutex_destroy(&LOCK_delete);
720
 
  dbug_sentry= THD_SENTRY_GONE;
721
 
  if (rli_fake)
722
 
  {
723
 
    delete rli_fake;
724
 
    rli_fake= NULL;
725
 
  }
726
 
  
727
 
  free_root(&main_mem_root, MYF(0));
728
 
  return;
729
474
}
730
475
 
731
476
 
762
507
    to_var       add to this array
763
508
    from_var     from this array
764
509
    dec_var      minus this array
765
 
  
 
510
 
766
511
  NOTE
767
512
    This function assumes that all variables are long/ulong.
768
513
*/
780
525
}
781
526
 
782
527
 
783
 
void THD::awake(THD::killed_state state_to_set)
 
528
void Session::awake(Session::killed_state state_to_set)
784
529
{
785
 
  THD_CHECK_SENTRY(this);
786
 
  safe_mutex_assert_owner(&LOCK_delete); 
 
530
  Session_CHECK_SENTRY(this);
 
531
  safe_mutex_assert_owner(&LOCK_delete);
787
532
 
788
533
  killed= state_to_set;
789
 
  if (state_to_set != THD::KILL_QUERY)
 
534
  if (state_to_set != Session::KILL_QUERY)
790
535
  {
791
 
    thr_alarm_kill(thread_id);
792
 
    if (!slave_thread)
793
 
      thread_scheduler.post_kill_notification(this);
 
536
    thread_scheduler.post_kill_notification(this);
794
537
  }
795
538
  if (mysys_var)
796
539
  {
813
556
      current_cond and current_mutex are 0), then the victim will not get
814
557
      a signal and it may wait "forever" on the cond (until
815
558
      we issue a second KILL or the status it's waiting for happens).
816
 
      It's true that we have set its thd->killed but it may not
 
559
      It's true that we have set its session->killed but it may not
817
560
      see it immediately and so may have time to reach the cond_wait().
818
561
    */
819
562
    if (mysys_var->current_cond && mysys_var->current_mutex)
831
574
  Remember the location of thread info, the structure needed for
832
575
  sql_alloc() and the structure for the net buffer
833
576
*/
834
 
 
835
 
bool THD::store_globals()
 
577
bool Session::store_globals()
836
578
{
837
579
  /*
838
580
    Assert that thread_stack is initialized: it's necessary to be able
840
582
  */
841
583
  assert(thread_stack);
842
584
 
843
 
  if (my_pthread_setspecific_ptr(THR_THD,  this) ||
844
 
      my_pthread_setspecific_ptr(THR_MALLOC, &mem_root))
 
585
  if (pthread_setspecific(THR_Session,  this) ||
 
586
      pthread_setspecific(THR_Mem_root, &mem_root))
845
587
    return 1;
846
588
  mysys_var=my_thread_var;
847
589
  /*
848
590
    Let mysqld define the thread id (not mysys)
849
 
    This allows us to move THD to different threads if needed.
 
591
    This allows us to move Session to different threads if needed.
850
592
  */
851
593
  mysys_var->id= thread_id;
852
594
  real_id= pthread_self();                      // For debugging
853
595
 
854
596
  /*
855
 
    We have to call thr_lock_info_init() again here as THD may have been
 
597
    We have to call thr_lock_info_init() again here as Session may have been
856
598
    created in another thread
857
599
  */
858
600
  thr_lock_info_init(&lock_info);
859
601
  return 0;
860
602
}
861
603
 
 
604
void Session::prepareForQueries()
 
605
{
 
606
  if (variables.max_join_size == HA_POS_ERROR)
 
607
    options |= OPTION_BIG_SELECTS;
 
608
  if (client_capabilities & CLIENT_COMPRESS)
 
609
    net.compress= true;
 
610
 
 
611
  version= refresh_version;
 
612
  set_proc_info(0);
 
613
  command= COM_SLEEP;
 
614
  set_time();
 
615
  init_for_queries();
 
616
 
 
617
  /* In the past this would only run of the user did not have SUPER_ACL */
 
618
  if (sys_init_connect.value_length)
 
619
  {
 
620
    execute_init_command(this, &sys_init_connect, &LOCK_sys_init_connect);
 
621
    if (is_error())
 
622
    {
 
623
      Security_context *sctx= &security_ctx;
 
624
      killed= Session::KILL_CONNECTION;
 
625
      errmsg_printf(ERRMSG_LVL_WARN
 
626
                  , ER(ER_NEW_ABORTING_CONNECTION)
 
627
                  , thread_id
 
628
                  , (db ? db : "unconnected")
 
629
                  , sctx->user.empty() == false ? sctx->user.c_str() : "unauthenticated"
 
630
                  , sctx->ip.c_str(), "init_connect command failed");
 
631
      errmsg_printf(ERRMSG_LVL_WARN, "%s", main_da.message());
 
632
    }
 
633
    set_proc_info(0);
 
634
    set_time();
 
635
    init_for_queries();
 
636
  }
 
637
}
 
638
 
 
639
bool Session::initGlobals()
 
640
{
 
641
  if (store_globals())
 
642
  {
 
643
    disconnect(ER_OUT_OF_RESOURCES, true);
 
644
    statistic_increment(aborted_connects, &LOCK_status);
 
645
    thread_scheduler.end_thread(this, 0);
 
646
    return false;
 
647
  }
 
648
  return true;
 
649
}
 
650
 
 
651
bool Session::authenticate()
 
652
{
 
653
  /* Use "connect_timeout" value during connection phase */
 
654
  drizzleclient_net_set_read_timeout(&net, connect_timeout);
 
655
  drizzleclient_net_set_write_timeout(&net, connect_timeout);
 
656
 
 
657
  lex_start(this);
 
658
 
 
659
  bool connection_is_valid= check_connection();
 
660
  drizzleclient_net_end_statement(this);
 
661
 
 
662
  if (! connection_is_valid)
 
663
  {     
 
664
    /* We got wrong permissions from check_connection() */
 
665
    statistic_increment(aborted_connects, &LOCK_status);
 
666
    return false;
 
667
  }
 
668
 
 
669
  /* Connect completed, set read/write timeouts back to default */
 
670
  drizzleclient_net_set_read_timeout(&net, variables.net_read_timeout);
 
671
  drizzleclient_net_set_write_timeout(&net, variables.net_write_timeout);
 
672
  return true;
 
673
}
 
674
 
 
675
bool Session::check_connection()
 
676
{
 
677
  uint32_t pkt_len= 0;
 
678
  char *end;
 
679
 
 
680
  // TCP/IP connection
 
681
  {
 
682
    char ip[NI_MAXHOST];
 
683
 
 
684
    if (drizzleclient_net_peer_addr(&net, ip, &peer_port, NI_MAXHOST))
 
685
    {
 
686
      my_error(ER_BAD_HOST_ERROR, MYF(0), security_ctx.ip.c_str());
 
687
      return false;
 
688
    }
 
689
 
 
690
    security_ctx.ip.assign(ip);
 
691
  }
 
692
  drizzleclient_net_keepalive(&net, true);
 
693
 
 
694
  uint32_t server_capabilites;
 
695
  {
 
696
    /* buff[] needs to big enough to hold the server_version variable */
 
697
    char buff[SERVER_VERSION_LENGTH + SCRAMBLE_LENGTH + 64];
 
698
 
 
699
    server_capabilites= CLIENT_BASIC_FLAGS;
 
700
 
 
701
#ifdef HAVE_COMPRESS
 
702
    server_capabilites|= CLIENT_COMPRESS;
 
703
#endif /* HAVE_COMPRESS */
 
704
 
 
705
    end= buff + strlen(server_version);
 
706
    if ((end - buff) >= SERVER_VERSION_LENGTH)
 
707
      end= buff + (SERVER_VERSION_LENGTH - 1);
 
708
    memcpy(buff, server_version, end - buff);
 
709
    *end= 0;
 
710
    end++;
 
711
 
 
712
    int4store((unsigned char*) end, thread_id);
 
713
    end+= 4;
 
714
    /*
 
715
      So as check_connection is the only entry point to authorization
 
716
      procedure, scramble is set here. This gives us new scramble for
 
717
      each handshake.
 
718
    */
 
719
    drizzleclient_create_random_string(scramble, SCRAMBLE_LENGTH, &rand);
 
720
    /*
 
721
      Old clients does not understand long scrambles, but can ignore packet
 
722
      tail: that's why first part of the scramble is placed here, and second
 
723
      part at the end of packet.
 
724
    */
 
725
    end= strncpy(end, scramble, SCRAMBLE_LENGTH_323);
 
726
    end+= SCRAMBLE_LENGTH_323;
 
727
 
 
728
    *end++= 0; /* an empty byte for some reason */
 
729
 
 
730
    int2store(end, server_capabilites);
 
731
    /* write server characteristics: up to 16 bytes allowed */
 
732
    end[2]=(char) default_charset_info->number;
 
733
    int2store(end+3, server_status);
 
734
    memset(end+5, 0, 13);
 
735
    end+= 18;
 
736
    /* write scramble tail */
 
737
    size_t scramble_len= SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323;
 
738
    end= strncpy(end, scramble + SCRAMBLE_LENGTH_323, scramble_len);
 
739
    end+= scramble_len;
 
740
 
 
741
    *end++= 0; /* an empty byte for some reason */
 
742
 
 
743
    /* At this point we write connection message and read reply */
 
744
    if (drizzleclient_net_write_command(&net
 
745
          , (unsigned char) protocol_version
 
746
          , (unsigned char*) ""
 
747
          , 0
 
748
          , (unsigned char*) buff
 
749
          , (size_t) (end-buff)) 
 
750
        ||      (pkt_len= drizzleclient_net_read(&net)) == packet_error 
 
751
        || pkt_len < MIN_HANDSHAKE_SIZE)
 
752
    {
 
753
      my_error(ER_HANDSHAKE_ERROR, MYF(0), security_ctx.ip.c_str());
 
754
      return false;
 
755
    }
 
756
  }
 
757
  if (packet.alloc(variables.net_buffer_length))
 
758
    return false; /* The error is set by alloc(). */
 
759
 
 
760
  client_capabilities= uint2korr(net.read_pos);
 
761
 
 
762
 
 
763
  client_capabilities|= ((uint32_t) uint2korr(net.read_pos + 2)) << 16;
 
764
  max_client_packet_length= uint4korr(net.read_pos + 4);
 
765
  update_charset();
 
766
  end= (char*) net.read_pos + 32;
 
767
 
 
768
  /*
 
769
    Disable those bits which are not supported by the server.
 
770
    This is a precautionary measure, if the client lies. See Bug#27944.
 
771
  */
 
772
  client_capabilities&= server_capabilites;
 
773
 
 
774
  if (end >= (char*) net.read_pos + pkt_len + 2)
 
775
  {
 
776
    my_error(ER_HANDSHAKE_ERROR, MYF(0), security_ctx.ip.c_str());
 
777
    return false;
 
778
  }
 
779
 
 
780
  net.return_status= &server_status;
 
781
 
 
782
  char *user= end;
 
783
  char *passwd= strchr(user, '\0')+1;
 
784
  uint32_t user_len= passwd - user - 1;
 
785
  char *l_db= passwd;
 
786
  char db_buff[NAME_LEN + 1];           // buffer to store db in utf8
 
787
  char user_buff[USERNAME_LENGTH + 1];  // buffer to store user in utf8
 
788
  uint32_t dummy_errors;
 
789
 
 
790
  /*
 
791
    Old clients send null-terminated string as password; new clients send
 
792
    the size (1 byte) + string (not null-terminated). Hence in case of empty
 
793
    password both send '\0'.
 
794
 
 
795
    This strlen() can't be easily deleted without changing protocol.
 
796
 
 
797
    Cast *passwd to an unsigned char, so that it doesn't extend the sign for
 
798
    *passwd > 127 and become 2**32-127+ after casting to uint.
 
799
  */
 
800
  uint32_t passwd_len= client_capabilities & CLIENT_SECURE_CONNECTION ?
 
801
    (unsigned char)(*passwd++) : strlen(passwd);
 
802
  l_db= client_capabilities & CLIENT_CONNECT_WITH_DB ? l_db + passwd_len + 1 : 0;
 
803
 
 
804
  /* strlen() can't be easily deleted without changing protocol */
 
805
  uint32_t db_len= l_db ? strlen(l_db) : 0;
 
806
 
 
807
  if (passwd + passwd_len + db_len > (char *) net.read_pos + pkt_len)
 
808
  {
 
809
    my_error(ER_HANDSHAKE_ERROR, MYF(0), security_ctx.ip.c_str());
 
810
    return false;
 
811
  }
 
812
 
 
813
  /* Since 4.1 all database names are stored in utf8 */
 
814
  if (l_db)
 
815
  {
 
816
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
 
817
                             system_charset_info,
 
818
                             l_db, db_len,
 
819
                             charset(), &dummy_errors)]= 0;
 
820
    l_db= db_buff;
 
821
  }
 
822
 
 
823
  user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
 
824
                                       system_charset_info, user, user_len,
 
825
                                       charset(), &dummy_errors)]= '\0';
 
826
  user= user_buff;
 
827
 
 
828
  /* If username starts and ends in "'", chop them off */
 
829
  if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'')
 
830
  {
 
831
    user[user_len-1]= 0;
 
832
    user++;
 
833
    user_len-= 2;
 
834
  }
 
835
 
 
836
  security_ctx.user.assign(user);
 
837
 
 
838
  return check_user(passwd, passwd_len, l_db);
 
839
}
 
840
 
 
841
bool Session::check_user(const char *passwd, uint32_t passwd_len, const char *in_db)
 
842
{
 
843
  LEX_STRING db_str= { (char *) in_db, in_db ? strlen(in_db) : 0 };
 
844
  bool is_authenticated;
 
845
 
 
846
  /*
 
847
    Clear session->db as it points to something, that will be freed when
 
848
    connection is closed. We don't want to accidentally free a wrong
 
849
    pointer if connect failed. Also in case of 'CHANGE USER' failure,
 
850
    current database will be switched to 'no database selected'.
 
851
  */
 
852
  reset_db(NULL, 0);
 
853
 
 
854
  if (passwd_len != 0 && passwd_len != SCRAMBLE_LENGTH)
 
855
  {
 
856
    my_error(ER_HANDSHAKE_ERROR, MYF(0), security_ctx.ip.c_str());
 
857
    return false;
 
858
  }
 
859
 
 
860
  is_authenticated= authenticate_user(this, passwd);
 
861
 
 
862
  if (is_authenticated != true)
 
863
  {
 
864
    my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
 
865
             security_ctx.user.c_str(),
 
866
             security_ctx.ip.c_str(),
 
867
             passwd_len ? ER(ER_YES) : ER(ER_NO));
 
868
 
 
869
    return false;
 
870
  }
 
871
 
 
872
  security_ctx.skip_grants();
 
873
 
 
874
  /* Change database if necessary */
 
875
  if (in_db && in_db[0])
 
876
  {
 
877
    if (mysql_change_db(this, &db_str, false))
 
878
    {
 
879
      /* mysql_change_db() has pushed the error message. */
 
880
      return false;
 
881
    }
 
882
  }
 
883
  my_ok();
 
884
  password= test(passwd_len);          // remember for error messages
 
885
 
 
886
  /* Ready to handle queries */
 
887
  return true;
 
888
}
 
889
 
 
890
bool Session::executeStatement()
 
891
{
 
892
  bool return_value;
 
893
  char *l_packet= 0;
 
894
  uint32_t packet_length;
 
895
 
 
896
  enum enum_server_command l_command;
 
897
 
 
898
  /*
 
899
    indicator of uninitialized lex => normal flow of errors handling
 
900
    (see my_message_sql)
 
901
  */
 
902
  lex->current_select= 0;
 
903
 
 
904
  /*
 
905
    This thread will do a blocking read from the client which
 
906
    will be interrupted when the next command is received from
 
907
    the client, the connection is closed or "net_wait_timeout"
 
908
    number of seconds has passed
 
909
  */
 
910
  drizzleclient_net_set_read_timeout(&net, variables.net_wait_timeout);
 
911
 
 
912
  /*
 
913
    XXX: this code is here only to clear possible errors of init_connect.
 
914
    Consider moving to init_connect() instead.
 
915
  */
 
916
  clear_error();                                // Clear error message
 
917
  main_da.reset_diagnostics_area();
 
918
 
 
919
  net_new_transaction(&net);
 
920
 
 
921
  packet_length= drizzleclient_net_read(&net);
 
922
  if (packet_length == packet_error)
 
923
  {
 
924
    /* Check if we can continue without closing the connection */
 
925
 
 
926
    if(net.last_errno== CR_NET_PACKET_TOO_LARGE)
 
927
      my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
 
928
    /* Assert is invalid for dirty connection shutdown
 
929
     *     assert(session->is_error());
 
930
     */
 
931
    drizzleclient_net_end_statement(this);
 
932
 
 
933
    if (net.error != 3)
 
934
    {
 
935
      return_value= false;                       // We have to close it.
 
936
      goto out;
 
937
    }
 
938
 
 
939
    net.error= 0;
 
940
    return_value= true;
 
941
    goto out;
 
942
  }
 
943
 
 
944
  l_packet= (char*) net.read_pos;
 
945
  /*
 
946
    'packet_length' contains length of data, as it was stored in packet
 
947
    header. In case of malformed header, drizzleclient_net_read returns zero.
 
948
    If packet_length is not zero, drizzleclient_net_read ensures that the returned
 
949
    number of bytes was actually read from network.
 
950
    There is also an extra safety measure in drizzleclient_net_read:
 
951
    it sets packet[packet_length]= 0, but only for non-zero packets.
 
952
  */
 
953
  if (packet_length == 0)                       /* safety */
 
954
  {
 
955
    /* Initialize with COM_SLEEP packet */
 
956
    l_packet[0]= (unsigned char) COM_SLEEP;
 
957
    packet_length= 1;
 
958
  }
 
959
  /* Do not rely on drizzleclient_net_read, extra safety against programming errors. */
 
960
  l_packet[packet_length]= '\0';                  /* safety */
 
961
 
 
962
  l_command= (enum enum_server_command) (unsigned char) l_packet[0];
 
963
 
 
964
  if (command >= COM_END)
 
965
    command= COM_END;                           // Wrong command
 
966
 
 
967
  /* Restore read timeout value */
 
968
  drizzleclient_net_set_read_timeout(&net, variables.net_read_timeout);
 
969
 
 
970
  assert(packet_length);
 
971
  return_value= ! dispatch_command(l_command, this, l_packet+1, (uint32_t) (packet_length-1));
 
972
 
 
973
out:
 
974
  return return_value;
 
975
}
 
976
 
 
977
bool Session::readAndStoreQuery(const char *in_packet, uint32_t in_packet_length)
 
978
{
 
979
  /* Remove garbage at start and end of query */
 
980
  while (in_packet_length > 0 && my_isspace(charset(), in_packet[0]))
 
981
  {
 
982
    in_packet++;
 
983
    in_packet_length--;
 
984
  }
 
985
  const char *pos= in_packet + in_packet_length; /* Point at end null */
 
986
  while (in_packet_length > 0 &&
 
987
         (pos[-1] == ';' || my_isspace(charset() ,pos[-1])))
 
988
  {
 
989
    pos--;
 
990
    in_packet_length--;
 
991
  }
 
992
 
 
993
  /* We must allocate some extra memory for the cached query string */
 
994
  query_length= 0; /* Extra safety: Avoid races */
 
995
  query= (char*) memdup_w_gap((unsigned char*) in_packet, in_packet_length, db_length + 1);
 
996
  if (! query)
 
997
    return false;
 
998
 
 
999
  query[in_packet_length]=0;
 
1000
  query_length= in_packet_length;
 
1001
 
 
1002
  /* Reclaim some memory */
 
1003
  packet.shrink(variables.net_buffer_length);
 
1004
  convert_buffer.shrink(variables.net_buffer_length);
 
1005
 
 
1006
  return true;
 
1007
}
 
1008
 
 
1009
bool Session::endTransaction(enum enum_mysql_completiontype completion)
 
1010
{
 
1011
  bool do_release= 0;
 
1012
  bool result= true;
 
1013
 
 
1014
  if (transaction.xid_state.xa_state != XA_NOTR)
 
1015
  {
 
1016
    my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[transaction.xid_state.xa_state]);
 
1017
    return false;
 
1018
  }
 
1019
  switch (completion) 
 
1020
  {
 
1021
    case COMMIT:
 
1022
      /*
 
1023
       * We don't use endActiveTransaction() here to ensure that this works
 
1024
       * even if there is a problem with the OPTION_AUTO_COMMIT flag
 
1025
       * (Which of course should never happen...)
 
1026
       */
 
1027
      server_status&= ~SERVER_STATUS_IN_TRANS;
 
1028
      if (ha_commit(this))
 
1029
        result= false;
 
1030
      options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
 
1031
      transaction.all.modified_non_trans_table= false;
 
1032
      break;
 
1033
    case COMMIT_RELEASE:
 
1034
      do_release= 1; /* fall through */
 
1035
    case COMMIT_AND_CHAIN:
 
1036
      result= endActiveTransaction();
 
1037
      if (result == true && completion == COMMIT_AND_CHAIN)
 
1038
        result= startTransaction();
 
1039
      break;
 
1040
    case ROLLBACK_RELEASE:
 
1041
      do_release= 1; /* fall through */
 
1042
    case ROLLBACK:
 
1043
    case ROLLBACK_AND_CHAIN:
 
1044
    {
 
1045
      server_status&= ~SERVER_STATUS_IN_TRANS;
 
1046
      if (ha_rollback(this))
 
1047
        result= false;
 
1048
      options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
 
1049
      transaction.all.modified_non_trans_table= false;
 
1050
      if (result == true && (completion == ROLLBACK_AND_CHAIN))
 
1051
        result= startTransaction();
 
1052
      break;
 
1053
    }
 
1054
    default:
 
1055
      my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
 
1056
      return false;
 
1057
  }
 
1058
 
 
1059
  if (result == false)
 
1060
    my_error(killed_errno(), MYF(0));
 
1061
  else if ((result == true) && do_release)
 
1062
    killed= Session::KILL_CONNECTION;
 
1063
 
 
1064
  return result;
 
1065
}
 
1066
 
 
1067
bool Session::endActiveTransaction()
 
1068
{
 
1069
  bool result= true;
 
1070
 
 
1071
  if (transaction.xid_state.xa_state != XA_NOTR)
 
1072
  {
 
1073
    my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[transaction.xid_state.xa_state]);
 
1074
    return false;
 
1075
  }
 
1076
  if (options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN | OPTION_TABLE_LOCK))
 
1077
  {
 
1078
    /* Safety if one did "drop table" on locked tables */
 
1079
    if (! locked_tables)
 
1080
      options&= ~OPTION_TABLE_LOCK;
 
1081
    server_status&= ~SERVER_STATUS_IN_TRANS;
 
1082
    if (ha_commit(this))
 
1083
      result= false;
 
1084
  }
 
1085
  options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
 
1086
  transaction.all.modified_non_trans_table= false;
 
1087
  return result;
 
1088
}
 
1089
 
 
1090
bool Session::startTransaction()
 
1091
{
 
1092
  bool result= true;
 
1093
 
 
1094
  if (locked_tables)
 
1095
  {
 
1096
    lock= locked_tables;
 
1097
    locked_tables= 0;                   // Will be automatically closed
 
1098
    close_thread_tables(this);                  // Free tables
 
1099
  }
 
1100
  if (! endActiveTransaction())
 
1101
    result= false;
 
1102
  else
 
1103
  {
 
1104
    options|= OPTION_BEGIN;
 
1105
    server_status|= SERVER_STATUS_IN_TRANS;
 
1106
    if (lex->start_transaction_opt & DRIZZLE_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
 
1107
      if (ha_start_consistent_snapshot(this))
 
1108
        result= false;
 
1109
  }
 
1110
  return result;
 
1111
}
862
1112
 
863
1113
/*
864
1114
  Cleanup after query.
865
1115
 
866
1116
  SYNOPSIS
867
 
    THD::cleanup_after_query()
 
1117
    Session::cleanup_after_query()
868
1118
 
869
1119
  DESCRIPTION
870
1120
    This function is used to reset thread data to its default state.
875
1125
    different master threads may overwrite data of each other on
876
1126
    slave.
877
1127
*/
878
 
 
879
 
void THD::cleanup_after_query()
 
1128
void Session::cleanup_after_query()
880
1129
{
881
1130
  /*
882
 
    Reset rand_used so that detection of calls to rand() will save random 
 
1131
    Reset rand_used so that detection of calls to rand() will save random
883
1132
    seeds if needed by the slave.
884
 
 
885
 
    Do not reset rand_used if inside a stored function or trigger because 
886
 
    only the call to these operations is logged. Thus only the calling 
887
 
    statement needs to detect rand() calls made by its substatements. These
888
 
    substatements must not set rand_used to 0 because it would remove the
889
 
    detection of rand() by the calling statement. 
890
1133
  */
891
 
  if (!in_sub_stmt) /* stored functions and triggers are a special case */
892
1134
  {
893
1135
    /* Forget those values, for next binlogger: */
894
 
    stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
895
1136
    auto_inc_intervals_in_cur_stmt_for_binlog.empty();
896
 
    rand_used= 0;
897
1137
  }
898
1138
  if (first_successful_insert_id_in_cur_stmt > 0)
899
1139
  {
900
1140
    /* set what LAST_INSERT_ID() will return */
901
 
    first_successful_insert_id_in_prev_stmt= 
 
1141
    first_successful_insert_id_in_prev_stmt=
902
1142
      first_successful_insert_id_in_cur_stmt;
903
1143
    first_successful_insert_id_in_cur_stmt= 0;
904
1144
    substitute_null_with_insert_id= true;
907
1147
  /* Free Items that were created during this execution */
908
1148
  free_items();
909
1149
  /* Reset where. */
910
 
  where= THD::DEFAULT_WHERE;
 
1150
  where= Session::DEFAULT_WHERE;
911
1151
}
912
1152
 
913
1153
 
921
1161
                              instead of using lex_str value
922
1162
  @return  NULL on failure, or pointer to the LEX_STRING object
923
1163
*/
924
 
LEX_STRING *THD::make_lex_string(LEX_STRING *lex_str,
 
1164
LEX_STRING *Session::make_lex_string(LEX_STRING *lex_str,
925
1165
                                 const char* str, uint32_t length,
926
1166
                                 bool allocate_lex_string)
927
1167
{
955
1195
        In this case to->str will point to 0 and to->length will be 0.
956
1196
*/
957
1197
 
958
 
bool THD::convert_string(LEX_STRING *to, const CHARSET_INFO * const to_cs,
 
1198
bool Session::convert_string(LEX_STRING *to, const CHARSET_INFO * const to_cs,
959
1199
                         const char *from, uint32_t from_length,
960
1200
                         const CHARSET_INFO * const from_cs)
961
1201
{
977
1217
  Convert string from source character set to target character set inplace.
978
1218
 
979
1219
  SYNOPSIS
980
 
    THD::convert_string
 
1220
    Session::convert_string
981
1221
 
982
1222
  DESCRIPTION
983
 
    Convert string using convert_buffer - buffer for character set 
 
1223
    Convert string using convert_buffer - buffer for character set
984
1224
    conversion shared between all protocols.
985
1225
 
986
1226
  RETURN
988
1228
   !0   out of memory
989
1229
*/
990
1230
 
991
 
bool THD::convert_string(String *s, const CHARSET_INFO * const from_cs,
 
1231
bool Session::convert_string(String *s, const CHARSET_INFO * const from_cs,
992
1232
                         const CHARSET_INFO * const to_cs)
993
1233
{
994
1234
  uint32_t dummy_errors;
1009
1249
  Update some cache variables when character set changes
1010
1250
*/
1011
1251
 
1012
 
void THD::update_charset()
 
1252
void Session::update_charset()
1013
1253
{
1014
1254
  uint32_t not_used;
1015
1255
  charset_is_system_charset= !String::needs_conversion(0,charset(),
1016
1256
                                                       system_charset_info,
1017
1257
                                                       &not_used);
1018
 
  charset_is_collation_connection= 
1019
 
    !String::needs_conversion(0,charset(),variables.collation_connection,
 
1258
  charset_is_collation_connection=
 
1259
    !String::needs_conversion(0,charset(),variables.getCollation(),
1020
1260
                              &not_used);
1021
 
  charset_is_character_set_filesystem= 
 
1261
  charset_is_character_set_filesystem=
1022
1262
    !String::needs_conversion(0, charset(),
1023
1263
                              variables.character_set_filesystem, &not_used);
1024
1264
}
1039
1279
 
1040
1280
/* add table to list of changed in transaction tables */
1041
1281
 
1042
 
void THD::add_changed_table(Table *table)
 
1282
void Session::add_changed_table(Table *table)
1043
1283
{
1044
1284
  assert((options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) &&
1045
1285
              table->file->has_transactions());
1049
1289
}
1050
1290
 
1051
1291
 
1052
 
void THD::add_changed_table(const char *key, long key_length)
 
1292
void Session::add_changed_table(const char *key, long key_length)
1053
1293
{
1054
1294
  CHANGED_TableList **prev_changed = &transaction.changed_tables;
1055
1295
  CHANGED_TableList *curr = transaction.changed_tables;
1081
1321
}
1082
1322
 
1083
1323
 
1084
 
CHANGED_TableList* THD::changed_table_dup(const char *key, long key_length)
 
1324
CHANGED_TableList* Session::changed_table_dup(const char *key, long key_length)
1085
1325
{
1086
 
  CHANGED_TableList* new_table = 
 
1326
  CHANGED_TableList* new_table =
1087
1327
    (CHANGED_TableList*) trans_alloc(ALIGN_SIZE(sizeof(CHANGED_TableList))+
1088
1328
                                      key_length + 1);
1089
1329
  if (!new_table)
1102
1342
}
1103
1343
 
1104
1344
 
1105
 
int THD::send_explain_fields(select_result *result)
 
1345
int Session::send_explain_fields(select_result *result)
1106
1346
{
1107
1347
  List<Item> field_list;
1108
1348
  Item *item;
1141
1381
                              Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF));
1142
1382
}
1143
1383
 
1144
 
 
1145
 
struct Item_change_record: public ilink
1146
 
{
1147
 
  Item **place;
1148
 
  Item *old_value;
1149
 
  /* Placement new was hidden by `new' in ilink (TODO: check): */
1150
 
  static void *operator new(size_t size __attribute__((unused)),
1151
 
                            void *mem)
1152
 
    { return mem; }
1153
 
  static void operator delete(void *ptr __attribute__((unused)),
1154
 
                              size_t size __attribute__((unused)))
1155
 
    {}
1156
 
  static void operator delete(void *ptr __attribute__((unused)),
1157
 
                              void *mem __attribute__((unused)))
1158
 
    { /* never called */ }
1159
 
};
1160
 
 
1161
 
 
1162
 
/*
1163
 
  Register an item tree tree transformation, performed by the query
1164
 
  optimizer. We need a pointer to runtime_memroot because it may be !=
1165
 
  thd->mem_root (this may no longer be a true statement)
1166
 
*/
1167
 
 
1168
 
void THD::nocheck_register_item_tree_change(Item **place, Item *old_value,
1169
 
                                            MEM_ROOT *runtime_memroot)
1170
 
{
1171
 
  Item_change_record *change;
1172
 
  /*
1173
 
    Now we use one node per change, which adds some memory overhead,
1174
 
    but still is rather fast as we use alloc_root for allocations.
1175
 
    A list of item tree changes of an average query should be short.
1176
 
  */
1177
 
  void *change_mem= alloc_root(runtime_memroot, sizeof(*change));
1178
 
  if (change_mem == 0)
1179
 
  {
1180
 
    /*
1181
 
      OOM, thd->fatal_error() is called by the error handler of the
1182
 
      memroot. Just return.
1183
 
    */
1184
 
    return;
1185
 
  }
1186
 
  change= new (change_mem) Item_change_record;
1187
 
  change->place= place;
1188
 
  change->old_value= old_value;
1189
 
  change_list.append(change);
1190
 
}
1191
 
 
1192
 
 
1193
 
void THD::rollback_item_tree_changes()
1194
 
{
1195
 
  I_List_iterator<Item_change_record> it(change_list);
1196
 
  Item_change_record *change;
1197
 
 
1198
 
  while ((change= it++))
1199
 
    *change->place= change->old_value;
1200
 
  /* We can forget about changes memory: it's allocated in runtime memroot */
1201
 
  change_list.empty();
1202
 
  return;
1203
 
}
1204
 
 
1205
 
 
1206
 
/*****************************************************************************
1207
 
** Functions to provide a interface to select results
1208
 
*****************************************************************************/
1209
 
 
1210
 
select_result::select_result()
1211
 
{
1212
 
  thd=current_thd;
1213
 
}
1214
 
 
1215
 
void select_result::send_error(uint32_t errcode,const char *err)
1216
 
{
1217
 
  my_message(errcode, err, MYF(0));
1218
 
}
1219
 
 
1220
 
 
1221
 
void select_result::cleanup()
1222
 
{
1223
 
  /* do nothing */
1224
 
}
1225
 
 
1226
 
bool select_result::check_simple_select() const
1227
 
{
1228
 
  my_error(ER_SP_BAD_CURSOR_QUERY, MYF(0));
1229
 
  return true;
1230
 
}
1231
 
 
1232
 
 
1233
 
static String default_line_term("\n",default_charset_info);
1234
 
static String default_escaped("\\",default_charset_info);
1235
 
static String default_field_term("\t",default_charset_info);
1236
 
 
1237
 
sql_exchange::sql_exchange(char *name, bool flag,
1238
 
                           enum enum_filetype filetype_arg)
1239
 
  :file_name(name), opt_enclosed(0), dumpfile(flag), skip_lines(0)
1240
 
{
1241
 
  filetype= filetype_arg;
1242
 
  field_term= &default_field_term;
1243
 
  enclosed=   line_start= &my_empty_string;
1244
 
  line_term=  &default_line_term;
1245
 
  escaped=    &default_escaped;
1246
 
  cs= NULL;
1247
 
}
1248
 
 
1249
 
bool select_send::send_fields(List<Item> &list, uint32_t flags)
1250
 
{
1251
 
  bool res;
1252
 
  if (!(res= thd->protocol->send_fields(&list, flags)))
1253
 
    is_result_set_started= 1;
1254
 
  return res;
1255
 
}
1256
 
 
1257
 
void select_send::abort()
1258
 
{
1259
 
  return;
1260
 
}
1261
 
 
1262
 
 
1263
 
/** 
1264
 
  Cleanup an instance of this class for re-use
1265
 
  at next execution of a prepared statement/
1266
 
  stored procedure statement.
1267
 
*/
1268
 
 
1269
 
void select_send::cleanup()
1270
 
{
1271
 
  is_result_set_started= false;
1272
 
}
1273
 
 
1274
 
/* Send data to client. Returns 0 if ok */
1275
 
 
1276
 
bool select_send::send_data(List<Item> &items)
1277
 
{
1278
 
  if (unit->offset_limit_cnt)
1279
 
  {                                             // using limit offset,count
1280
 
    unit->offset_limit_cnt--;
1281
 
    return 0;
1282
 
  }
1283
 
 
1284
 
  /*
1285
 
    We may be passing the control from mysqld to the client: release the
1286
 
    InnoDB adaptive hash S-latch to avoid thread deadlocks if it was reserved
1287
 
    by thd
1288
 
  */
1289
 
  ha_release_temporary_latches(thd);
1290
 
 
1291
 
  List_iterator_fast<Item> li(items);
1292
 
  Protocol *protocol= thd->protocol;
1293
 
  char buff[MAX_FIELD_WIDTH];
1294
 
  String buffer(buff, sizeof(buff), &my_charset_bin);
1295
 
 
1296
 
  protocol->prepare_for_resend();
1297
 
  Item *item;
1298
 
  while ((item=li++))
1299
 
  {
1300
 
    if (item->send(protocol, &buffer))
1301
 
    {
1302
 
      protocol->free();                         // Free used buffer
1303
 
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1304
 
      break;
1305
 
    }
1306
 
  }
1307
 
  thd->sent_row_count++;
1308
 
  if (thd->is_error())
1309
 
  {
1310
 
    protocol->remove_last_row();
1311
 
    return(1);
1312
 
  }
1313
 
  if (thd->vio_ok())
1314
 
    return(protocol->write());
1315
 
  return(0);
1316
 
}
1317
 
 
1318
 
bool select_send::send_eof()
1319
 
{
1320
 
  /* 
1321
 
    We may be passing the control from mysqld to the client: release the
1322
 
    InnoDB adaptive hash S-latch to avoid thread deadlocks if it was reserved
1323
 
    by thd 
1324
 
  */
1325
 
  ha_release_temporary_latches(thd);
1326
 
 
1327
 
  /* Unlock tables before sending packet to gain some speed */
1328
 
  if (thd->lock)
1329
 
  {
1330
 
    mysql_unlock_tables(thd, thd->lock);
1331
 
    thd->lock=0;
1332
 
  }
1333
 
  ::my_eof(thd);
1334
 
  is_result_set_started= 0;
1335
 
  return false;
1336
 
}
1337
 
 
1338
 
 
1339
1384
/************************************************************************
1340
1385
  Handling writing to file
1341
1386
************************************************************************/
1365
1410
      function, SELECT INTO has to have an own SQLCOM.
1366
1411
      TODO: split from SQLCOM_SELECT
1367
1412
    */
1368
 
    ::my_ok(thd,row_count);
 
1413
    session->my_ok(row_count);
1369
1414
  }
1370
1415
  file= -1;
1371
1416
  return error;
1402
1447
 
1403
1448
select_export::~select_export()
1404
1449
{
1405
 
  thd->sent_row_count=row_count;
 
1450
  session->sent_row_count=row_count;
1406
1451
}
1407
1452
 
1408
1453
 
1411
1456
 
1412
1457
  SYNOPSIS
1413
1458
    create_file()
1414
 
    thd                 Thread handle
 
1459
    session                     Thread handle
1415
1460
    path                File name
1416
1461
    exchange            Excange class
1417
1462
    cache               IO cache
1422
1467
*/
1423
1468
 
1424
1469
 
1425
 
static File create_file(THD *thd, char *path, sql_exchange *exchange,
1426
 
                        IO_CACHE *cache)
 
1470
static File create_file(Session *session, char *path, file_exchange *exchange, IO_CACHE *cache)
1427
1471
{
1428
1472
  File file;
1429
1473
  uint32_t option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH;
1434
1478
 
1435
1479
  if (!dirname_length(exchange->file_name))
1436
1480
  {
1437
 
    strxnmov(path, FN_REFLEN-1, mysql_real_data_home, thd->db ? thd->db : "",
1438
 
             NULL);
 
1481
    strcpy(path, drizzle_real_data_home);
 
1482
    if (session->db)
 
1483
      strncat(path, session->db, FN_REFLEN-strlen(drizzle_real_data_home)-1);
1439
1484
    (void) fn_format(path, exchange->file_name, path, "", option);
1440
1485
  }
1441
1486
  else
1442
 
    (void) fn_format(path, exchange->file_name, mysql_real_data_home, "", option);
 
1487
    (void) fn_format(path, exchange->file_name, drizzle_real_data_home, "", option);
1443
1488
 
1444
1489
  if (opt_secure_file_priv &&
1445
1490
      strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv)))
1465
1510
  if (init_io_cache(cache, file, 0L, WRITE_CACHE, 0L, 1, MYF(MY_WME)))
1466
1511
  {
1467
1512
    my_close(file, MYF(0));
1468
 
    my_delete(path, MYF(0));  // Delete file on error, it was just created 
 
1513
    my_delete(path, MYF(0));  // Delete file on error, it was just created
1469
1514
    return -1;
1470
1515
  }
1471
1516
  return file;
1473
1518
 
1474
1519
 
1475
1520
int
1476
 
select_export::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
 
1521
select_export::prepare(List<Item> &list, Select_Lex_Unit *u)
1477
1522
{
1478
1523
  bool blob_flag=0;
1479
1524
  bool string_results= false, non_string_results= false;
1480
1525
  unit= u;
1481
 
  if ((uint) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
1482
 
    strmake(path,exchange->file_name,FN_REFLEN-1);
 
1526
  if ((uint32_t) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
 
1527
    strncpy(path,exchange->file_name,FN_REFLEN-1);
1483
1528
 
1484
 
  if ((file= create_file(thd, path, exchange, &cache)) < 0)
1485
 
    return 1;
1486
1529
  /* Check if there is any blobs in data */
1487
1530
  {
1488
1531
    List_iterator_fast<Item> li(list);
1524
1567
      (exchange->opt_enclosed && non_string_results &&
1525
1568
       field_term_length && strchr(NUMERIC_CHARS, field_term_char)))
1526
1569
  {
1527
 
    push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1528
 
                 ER_AMBIGUOUS_FIELD_TERM, ER(ER_AMBIGUOUS_FIELD_TERM));
1529
 
    is_ambiguous_field_term= true;
 
1570
    my_error(ER_AMBIGUOUS_FIELD_TERM, MYF(0));
 
1571
    return 1;
1530
1572
  }
1531
 
  else
1532
 
    is_ambiguous_field_term= false;
 
1573
 
 
1574
  if ((file= create_file(session, path, exchange, &cache)) < 0)
 
1575
    return 1;
1533
1576
 
1534
1577
  return 0;
1535
1578
}
1603
1646
      {
1604
1647
        char *pos, *start, *end;
1605
1648
        const CHARSET_INFO * const res_charset= res->charset();
1606
 
        const CHARSET_INFO * const character_set_client= thd->variables.
1607
 
                                                            character_set_client;
 
1649
        const CHARSET_INFO * const character_set_client= default_charset_info;
 
1650
 
1608
1651
        bool check_second_byte= (res_charset == &my_charset_bin) &&
1609
1652
                                 character_set_client->
1610
1653
                                 escape_with_backslash_is_dangerous;
1611
1654
        assert(character_set_client->mbmaxlen == 2 ||
1612
 
                    !character_set_client->escape_with_backslash_is_dangerous);
 
1655
               !character_set_client->escape_with_backslash_is_dangerous);
1613
1656
        for (start=pos=(char*) res->ptr(),end=pos+used_length ;
1614
1657
             pos != end ;
1615
1658
             pos++)
1631
1674
            for the clients with character sets big5, cp932, gbk and sjis,
1632
1675
            which can have the escape character (0x5C "\" by default)
1633
1676
            as the second byte of a multi-byte sequence.
1634
 
            
 
1677
 
1635
1678
            If
1636
1679
            - pos[0] is a valid multi-byte head (e.g 0xEE) and
1637
1680
            - pos[1] is 0x00, which will be escaped as "\0",
1638
 
            
 
1681
 
1639
1682
            then we'll get "0xEE + 0x5C + 0x30" in the output file.
1640
 
            
 
1683
 
1641
1684
            If this file is later loaded using this sequence of commands:
1642
 
            
 
1685
 
1643
1686
            mysql> create table t1 (a varchar(128)) character set big5;
1644
1687
            mysql> LOAD DATA INFILE 'dump.txt' INTO Table t1;
1645
 
            
 
1688
 
1646
1689
            then 0x5C will be misinterpreted as the second byte
1647
1690
            of a multi-byte character "0xEE + 0x5C", instead of
1648
1691
            escape character for 0x00.
1649
 
            
 
1692
 
1650
1693
            To avoid this confusion, we'll escape the multi-byte
1651
1694
            head character too, so the sequence "0xEE + 0x00" will be
1652
1695
            dumped as "0x5C + 0xEE + 0x5C + 0x30".
1653
 
            
 
1696
 
1654
1697
            Note, in the condition below we only check if
1655
1698
            mbcharlen is equal to 2, because there are no
1656
1699
            character sets with mbmaxlen longer than 2
1675
1718
                          is_ambiguous_field_sep) ?
1676
1719
                          field_sep_char : escape_char;
1677
1720
            tmp_buff[1]= *pos ? *pos : '0';
1678
 
            if (my_b_write(&cache,(unsigned char*) start,(uint) (pos-start)) ||
 
1721
            if (my_b_write(&cache,(unsigned char*) start,(uint32_t) (pos-start)) ||
1679
1722
                my_b_write(&cache,(unsigned char*) tmp_buff,2))
1680
1723
              goto err;
1681
1724
            start=pos+1;
1682
1725
          }
1683
1726
        }
1684
 
        if (my_b_write(&cache,(unsigned char*) start,(uint) (pos-start)))
 
1727
        if (my_b_write(&cache,(unsigned char*) start,(uint32_t) (pos-start)))
1685
1728
          goto err;
1686
1729
      }
1687
1730
      else if (my_b_write(&cache,(unsigned char*) res->ptr(),used_length))
1735
1778
 
1736
1779
 
1737
1780
int
1738
 
select_dump::prepare(List<Item> &list __attribute__((unused)),
1739
 
                     SELECT_LEX_UNIT *u)
 
1781
select_dump::prepare(List<Item> &, Select_Lex_Unit *u)
1740
1782
{
1741
1783
  unit= u;
1742
 
  return (int) ((file= create_file(thd, path, exchange, &cache)) < 0);
 
1784
  return (int) ((file= create_file(session, path, exchange, &cache)) < 0);
1743
1785
}
1744
1786
 
1745
1787
 
1756
1798
    unit->offset_limit_cnt--;
1757
1799
    return(0);
1758
1800
  }
1759
 
  if (row_count++ > 1) 
 
1801
  if (row_count++ > 1)
1760
1802
  {
1761
1803
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
1762
1804
    goto err;
1919
1961
     sortcmp(val1, val2, cache->collation.collation) < 0);
1920
1962
}
1921
1963
 
1922
 
bool select_exists_subselect::send_data(List<Item> &items __attribute__((unused)))
 
1964
bool select_exists_subselect::send_data(List<Item> &)
1923
1965
{
1924
1966
  Item_exists_subselect *it= (Item_exists_subselect *)item;
1925
1967
  if (unit->offset_limit_cnt)
1933
1975
}
1934
1976
 
1935
1977
 
1936
 
/***************************************************************************
1937
 
  Dump of select to variables
1938
 
***************************************************************************/
1939
 
 
1940
 
int select_dumpvar::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
1941
 
{
1942
 
  unit= u;
1943
 
  
1944
 
  if (var_list.elements != list.elements)
1945
 
  {
1946
 
    my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
1947
 
               ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), MYF(0));
1948
 
    return 1;
1949
 
  }               
1950
 
  return 0;
1951
 
}
1952
 
 
1953
 
 
1954
 
bool select_dumpvar::check_simple_select() const
1955
 
{
1956
 
  my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0));
1957
 
  return true;
1958
 
}
1959
 
 
1960
 
 
1961
 
void select_dumpvar::cleanup()
1962
 
{
1963
 
  row_count= 0;
1964
 
}
1965
 
 
1966
 
 
1967
 
void Query_arena::free_items()
1968
 
{
1969
 
  Item *next;
1970
 
  /* This works because items are allocated with sql_alloc() */
1971
 
  for (; free_list; free_list= next)
1972
 
  {
1973
 
    next= free_list->next;
1974
 
    free_list->delete_self();
1975
 
  }
1976
 
  /* Postcondition: free_list is 0 */
1977
 
  return;
1978
 
}
1979
 
 
1980
 
 
1981
1978
/*
1982
1979
  Statement functions
1983
1980
*/
1999
1996
  Don't free mem_root, as mem_root is freed in the end of dispatch_command
2000
1997
  (once for any command).
2001
1998
*/
2002
 
void THD::end_statement()
 
1999
void Session::end_statement()
2003
2000
{
2004
2001
  /* Cleanup SQL processing state to reuse this statement in next query. */
2005
2002
  lex_end(lex);
2006
2003
}
2007
2004
 
2008
2005
 
2009
 
bool THD::copy_db_to(char **p_db, size_t *p_db_length)
 
2006
bool Session::copy_db_to(char **p_db, size_t *p_db_length)
2010
2007
{
2011
2008
  if (db == NULL)
2012
2009
  {
2019
2016
}
2020
2017
 
2021
2018
 
2022
 
bool select_dumpvar::send_data(List<Item> &items)
2023
 
{
2024
 
  List_iterator_fast<my_var> var_li(var_list);
2025
 
  List_iterator<Item> it(items);
2026
 
  Item *item;
2027
 
  my_var *mv;
2028
 
 
2029
 
  if (unit->offset_limit_cnt)
2030
 
  {                                             // using limit offset,count
2031
 
    unit->offset_limit_cnt--;
2032
 
    return(0);
2033
 
  }
2034
 
  if (row_count++) 
2035
 
  {
2036
 
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
2037
 
    return(1);
2038
 
  }
2039
 
  while ((mv= var_li++) && (item= it++))
2040
 
  {
2041
 
    if (mv->local == 0)
2042
 
    {
2043
 
      Item_func_set_user_var *suv= new Item_func_set_user_var(mv->s, item);
2044
 
      suv->fix_fields(thd, 0);
2045
 
      suv->check(0);
2046
 
      suv->update();
2047
 
    }
2048
 
  }
2049
 
  return(thd->is_error());
2050
 
}
2051
 
 
2052
 
bool select_dumpvar::send_eof()
2053
 
{
2054
 
  if (! row_count)
2055
 
    push_warning(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
2056
 
                 ER_SP_FETCH_NO_DATA, ER(ER_SP_FETCH_NO_DATA));
2057
 
  /*
2058
 
    In order to remember the value of affected rows for ROW_COUNT()
2059
 
    function, SELECT INTO has to have an own SQLCOM.
2060
 
    TODO: split from SQLCOM_SELECT
2061
 
  */
2062
 
  ::my_ok(thd,row_count);
2063
 
  return 0;
2064
 
}
2065
 
 
2066
2019
/****************************************************************************
2067
 
  TMP_TABLE_PARAM
 
2020
  Tmp_Table_Param
2068
2021
****************************************************************************/
2069
2022
 
2070
 
void TMP_TABLE_PARAM::init()
 
2023
void Tmp_Table_Param::init()
2071
2024
{
2072
2025
  field_count= sum_func_count= func_count= hidden_field_count= 0;
2073
2026
  group_parts= group_length= group_null_parts= 0;
2078
2031
  return;
2079
2032
}
2080
2033
 
2081
 
 
2082
 
void thd_increment_bytes_sent(ulong length)
2083
 
{
2084
 
  THD *thd=current_thd;
2085
 
  if (likely(thd != 0))
2086
 
  { /* current_thd==0 when close_connection() calls net_send_error() */
2087
 
    thd->status_var.bytes_sent+= length;
2088
 
  }
2089
 
}
2090
 
 
2091
 
 
2092
 
void thd_increment_bytes_received(ulong length)
2093
 
{
2094
 
  current_thd->status_var.bytes_received+= length;
2095
 
}
2096
 
 
2097
 
 
2098
 
void thd_increment_net_big_packet_count(ulong length)
2099
 
{
2100
 
  current_thd->status_var.net_big_packet_count+= length;
2101
 
}
2102
 
 
2103
 
void THD::send_kill_message() const
 
2034
void Tmp_Table_Param::cleanup(void)
 
2035
{
 
2036
  /* Fix for Intel compiler */
 
2037
  if (copy_field)
 
2038
  {
 
2039
    delete [] copy_field;
 
2040
    save_copy_field= copy_field= 0;
 
2041
  }
 
2042
}
 
2043
 
 
2044
 
 
2045
void session_increment_bytes_sent(ulong length)
 
2046
{
 
2047
  Session *session=current_session;
 
2048
  if (likely(session != 0))
 
2049
  { /* current_session==0 when disconnect() calls net_send_error() */
 
2050
    session->status_var.bytes_sent+= length;
 
2051
  }
 
2052
}
 
2053
 
 
2054
 
 
2055
void session_increment_bytes_received(ulong length)
 
2056
{
 
2057
  current_session->status_var.bytes_received+= length;
 
2058
}
 
2059
 
 
2060
 
 
2061
void session_increment_net_big_packet_count(ulong length)
 
2062
{
 
2063
  current_session->status_var.net_big_packet_count+= length;
 
2064
}
 
2065
 
 
2066
void Session::send_kill_message() const
2104
2067
{
2105
2068
  int err= killed_errno();
2106
2069
  if (err)
2107
2070
    my_message(err, ER(err), MYF(0));
2108
2071
}
2109
2072
 
2110
 
void THD::set_status_var_init()
 
2073
void Session::set_status_var_init()
2111
2074
{
2112
2075
  memset(&status_var, 0, sizeof(status_var));
2113
2076
}
2114
2077
 
2115
 
 
2116
 
void Security_context::init()
2117
 
{
2118
 
  user= ip= 0;
2119
 
}
2120
 
 
2121
 
 
2122
 
void Security_context::destroy()
2123
 
{
2124
 
  // If not pointer to constant
2125
 
  if (user)
2126
 
  {
2127
 
    free(user);
2128
 
    user= NULL;
2129
 
  }
2130
 
  if (ip)
2131
 
  {
2132
 
    free(ip);
2133
 
    ip= NULL;
2134
 
  }
2135
 
}
2136
 
 
2137
 
 
2138
2078
void Security_context::skip_grants()
2139
2079
{
2140
2080
  /* privileges for the user are unknown everything is allowed */
2149
2089
  access to mysql.proc table to find definitions of stored routines.
2150
2090
****************************************************************************/
2151
2091
 
2152
 
void THD::reset_n_backup_open_tables_state(Open_tables_state *backup)
 
2092
void Session::reset_n_backup_open_tables_state(Open_tables_state *backup)
2153
2093
{
2154
2094
  backup->set_open_tables_state(this);
2155
2095
  reset_open_tables_state();
2158
2098
}
2159
2099
 
2160
2100
 
2161
 
void THD::restore_backup_open_tables_state(Open_tables_state *backup)
 
2101
void Session::restore_backup_open_tables_state(Open_tables_state *backup)
2162
2102
{
2163
2103
  /*
2164
2104
    Before we will throw away current open tables state we want
2171
2111
  return;
2172
2112
}
2173
2113
 
 
2114
 
 
2115
bool Session::set_db(const char *new_db, size_t new_db_len)
 
2116
{
 
2117
  /* Do not reallocate memory if current chunk is big enough. */
 
2118
  if (db && new_db && db_length >= new_db_len)
 
2119
    memcpy(db, new_db, new_db_len+1);
 
2120
  else
 
2121
  {
 
2122
    if (db)
 
2123
      free(db);
 
2124
    if (new_db)
 
2125
    {
 
2126
      db= (char *)malloc(new_db_len + 1);
 
2127
      if (db != NULL)
 
2128
      {
 
2129
        memcpy(db, new_db, new_db_len);
 
2130
        db[new_db_len]= 0;
 
2131
      }
 
2132
    }
 
2133
    else
 
2134
      db= NULL;
 
2135
  }
 
2136
  db_length= db ? new_db_len : 0;
 
2137
  return new_db && !db;
 
2138
}
 
2139
 
 
2140
 
2174
2141
/**
2175
2142
  Check the killed state of a user thread
2176
 
  @param thd  user thread
 
2143
  @param session  user thread
2177
2144
  @retval 0 the user thread is active
2178
2145
  @retval 1 the user thread has been killed
2179
2146
*/
2180
 
extern "C" int thd_killed(const DRIZZLE_THD thd)
 
2147
extern "C" int session_killed(const Session *session)
2181
2148
{
2182
 
  return(thd->killed);
 
2149
  return(session->killed);
2183
2150
}
2184
2151
 
2185
2152
/**
2186
2153
  Return the thread id of a user thread
2187
 
  @param thd user thread
 
2154
  @param session user thread
2188
2155
  @return thread id
2189
2156
*/
2190
 
extern "C" unsigned long thd_get_thread_id(const DRIZZLE_THD thd)
2191
 
{
2192
 
  return((unsigned long)thd->thread_id);
2193
 
}
2194
 
 
2195
 
 
2196
 
#ifdef INNODB_COMPATIBILITY_HOOKS
2197
 
extern "C" const struct charset_info_st *thd_charset(DRIZZLE_THD thd)
2198
 
{
2199
 
  return(thd->charset());
2200
 
}
2201
 
 
2202
 
extern "C" char **thd_query(DRIZZLE_THD thd)
2203
 
{
2204
 
  return(&thd->query);
2205
 
}
2206
 
 
2207
 
extern "C" int thd_slave_thread(const DRIZZLE_THD thd)
2208
 
{
2209
 
  return(thd->slave_thread);
2210
 
}
2211
 
 
2212
 
extern "C" int thd_non_transactional_update(const DRIZZLE_THD thd)
2213
 
{
2214
 
  return(thd->transaction.all.modified_non_trans_table);
2215
 
}
2216
 
 
2217
 
extern "C" int thd_binlog_format(const DRIZZLE_THD thd)
2218
 
{
2219
 
  return (int) thd->variables.binlog_format;
2220
 
}
2221
 
 
2222
 
extern "C" void thd_mark_transaction_to_rollback(DRIZZLE_THD thd, bool all)
2223
 
{
2224
 
  mark_transaction_to_rollback(thd, all);
2225
 
}
2226
 
#endif // INNODB_COMPATIBILITY_HOOKS */
 
2157
extern "C" unsigned long session_get_thread_id(const Session *session)
 
2158
{
 
2159
  return((unsigned long)session->thread_id);
 
2160
}
 
2161
 
 
2162
 
 
2163
extern "C"
 
2164
LEX_STRING *session_make_lex_string(Session *session, LEX_STRING *lex_str,
 
2165
                                const char *str, unsigned int size,
 
2166
                                int allocate_lex_string)
 
2167
{
 
2168
  return session->make_lex_string(lex_str, str, size,
 
2169
                              (bool) allocate_lex_string);
 
2170
}
 
2171
 
 
2172
extern "C" const struct charset_info_st *session_charset(Session *session)
 
2173
{
 
2174
  return(session->charset());
 
2175
}
 
2176
 
 
2177
extern "C" char **session_query(Session *session)
 
2178
{
 
2179
  return(&session->query);
 
2180
}
 
2181
 
 
2182
extern "C" int session_non_transactional_update(const Session *session)
 
2183
{
 
2184
  return(session->transaction.all.modified_non_trans_table);
 
2185
}
 
2186
 
 
2187
extern "C" void session_mark_transaction_to_rollback(Session *session, bool all)
 
2188
{
 
2189
  mark_transaction_to_rollback(session, all);
 
2190
}
2227
2191
 
2228
2192
 
2229
2193
/**
2230
2194
  Mark transaction to rollback and mark error as fatal to a sub-statement.
2231
2195
 
2232
 
  @param  thd   Thread handle
 
2196
  @param  session   Thread handle
2233
2197
  @param  all   true <=> rollback main transaction.
2234
2198
*/
2235
2199
 
2236
 
void mark_transaction_to_rollback(THD *thd, bool all)
2237
 
{
2238
 
  if (thd)
2239
 
  {
2240
 
    thd->is_fatal_sub_stmt_error= true;
2241
 
    thd->transaction_rollback_request= all;
2242
 
  }
2243
 
}
2244
 
/***************************************************************************
2245
 
  Handling of XA id cacheing
2246
 
***************************************************************************/
2247
 
 
2248
 
pthread_mutex_t LOCK_xid_cache;
2249
 
HASH xid_cache;
2250
 
 
2251
 
extern "C" unsigned char *xid_get_hash_key(const unsigned char *, size_t *, bool);
2252
 
extern "C" void xid_free_hash(void *);
2253
 
 
2254
 
unsigned char *xid_get_hash_key(const unsigned char *ptr, size_t *length,
2255
 
                        bool not_used __attribute__((unused)))
2256
 
{
2257
 
  *length=((XID_STATE*)ptr)->xid.key_length();
2258
 
  return ((XID_STATE*)ptr)->xid.key();
2259
 
}
2260
 
 
2261
 
void xid_free_hash(void *ptr)
2262
 
{
2263
 
  if (!((XID_STATE*)ptr)->in_thd)
2264
 
    free((unsigned char*)ptr);
2265
 
}
2266
 
 
2267
 
bool xid_cache_init()
2268
 
{
2269
 
  pthread_mutex_init(&LOCK_xid_cache, MY_MUTEX_INIT_FAST);
2270
 
  return hash_init(&xid_cache, &my_charset_bin, 100, 0, 0,
2271
 
                   xid_get_hash_key, xid_free_hash, 0) != 0;
2272
 
}
2273
 
 
2274
 
void xid_cache_free()
2275
 
{
2276
 
  if (hash_inited(&xid_cache))
2277
 
  {
2278
 
    hash_free(&xid_cache);
2279
 
    pthread_mutex_destroy(&LOCK_xid_cache);
2280
 
  }
2281
 
}
2282
 
 
2283
 
XID_STATE *xid_cache_search(XID *xid)
2284
 
{
2285
 
  pthread_mutex_lock(&LOCK_xid_cache);
2286
 
  XID_STATE *res=(XID_STATE *)hash_search(&xid_cache, xid->key(), xid->key_length());
2287
 
  pthread_mutex_unlock(&LOCK_xid_cache);
2288
 
  return res;
2289
 
}
2290
 
 
2291
 
 
2292
 
bool xid_cache_insert(XID *xid, enum xa_states xa_state)
2293
 
{
2294
 
  XID_STATE *xs;
2295
 
  bool res;
2296
 
  pthread_mutex_lock(&LOCK_xid_cache);
2297
 
  if (hash_search(&xid_cache, xid->key(), xid->key_length()))
2298
 
    res=0;
2299
 
  else if (!(xs=(XID_STATE *)my_malloc(sizeof(*xs), MYF(MY_WME))))
2300
 
    res=1;
2301
 
  else
2302
 
  {
2303
 
    xs->xa_state=xa_state;
2304
 
    xs->xid.set(xid);
2305
 
    xs->in_thd=0;
2306
 
    res=my_hash_insert(&xid_cache, (unsigned char*)xs);
2307
 
  }
2308
 
  pthread_mutex_unlock(&LOCK_xid_cache);
2309
 
  return res;
2310
 
}
2311
 
 
2312
 
 
2313
 
bool xid_cache_insert(XID_STATE *xid_state)
2314
 
{
2315
 
  pthread_mutex_lock(&LOCK_xid_cache);
2316
 
  assert(hash_search(&xid_cache, xid_state->xid.key(),
2317
 
                          xid_state->xid.key_length())==0);
2318
 
  bool res=my_hash_insert(&xid_cache, (unsigned char*)xid_state);
2319
 
  pthread_mutex_unlock(&LOCK_xid_cache);
2320
 
  return res;
2321
 
}
2322
 
 
2323
 
 
2324
 
void xid_cache_delete(XID_STATE *xid_state)
2325
 
{
2326
 
  pthread_mutex_lock(&LOCK_xid_cache);
2327
 
  hash_delete(&xid_cache, (unsigned char *)xid_state);
2328
 
  pthread_mutex_unlock(&LOCK_xid_cache);
2329
 
}
2330
 
 
2331
 
/*
2332
 
  Implementation of interface to write rows to the binary log through the
2333
 
  thread.  The thread is responsible for writing the rows it has
2334
 
  inserted/updated/deleted.
2335
 
*/
2336
 
 
2337
 
 
2338
 
/*
2339
 
  Template member function for ensuring that there is an rows log
2340
 
  event of the apropriate type before proceeding.
2341
 
 
2342
 
  PRE CONDITION:
2343
 
    - Events of type 'RowEventT' have the type code 'type_code'.
2344
 
    
2345
 
  POST CONDITION:
2346
 
    If a non-NULL pointer is returned, the pending event for thread 'thd' will
2347
 
    be an event of type 'RowEventT' (which have the type code 'type_code')
2348
 
    will either empty or have enough space to hold 'needed' bytes.  In
2349
 
    addition, the columns bitmap will be correct for the row, meaning that
2350
 
    the pending event will be flushed if the columns in the event differ from
2351
 
    the columns suppled to the function.
2352
 
 
2353
 
  RETURNS
2354
 
    If no error, a non-NULL pending event (either one which already existed or
2355
 
    the newly created one).
2356
 
    If error, NULL.
2357
 
 */
2358
 
 
2359
 
template <class RowsEventT> Rows_log_event* 
2360
 
THD::binlog_prepare_pending_rows_event(Table* table, uint32_t serv_id,
2361
 
                                       size_t needed,
2362
 
                                       bool is_transactional,
2363
 
                                       RowsEventT *hint __attribute__((unused)))
2364
 
{
2365
 
  /* Pre-conditions */
2366
 
  assert(table->s->table_map_id != UINT32_MAX);
2367
 
 
2368
 
  /* Fetch the type code for the RowsEventT template parameter */
2369
 
  int const type_code= RowsEventT::TYPE_CODE;
2370
 
 
2371
 
  /*
2372
 
    There is no good place to set up the transactional data, so we
2373
 
    have to do it here.
2374
 
  */
2375
 
  if (binlog_setup_trx_data())
2376
 
    return(NULL);
2377
 
 
2378
 
  Rows_log_event* pending= binlog_get_pending_rows_event();
2379
 
 
2380
 
  if (unlikely(pending && !pending->is_valid()))
2381
 
    return(NULL);
2382
 
 
2383
 
  /*
2384
 
    Check if the current event is non-NULL and a write-rows
2385
 
    event. Also check if the table provided is mapped: if it is not,
2386
 
    then we have switched to writing to a new table.
2387
 
    If there is no pending event, we need to create one. If there is a pending
2388
 
    event, but it's not about the same table id, or not of the same type
2389
 
    (between Write, Update and Delete), or not the same affected columns, or
2390
 
    going to be too big, flush this event to disk and create a new pending
2391
 
    event.
2392
 
 
2393
 
    The last test is necessary for the Cluster injector to work
2394
 
    correctly. The reason is that the Cluster can inject two write
2395
 
    rows with different column bitmaps if there is an insert followed
2396
 
    by an update in the same transaction, and these are grouped into a
2397
 
    single epoch/transaction when fed to the injector.
2398
 
 
2399
 
    TODO: Fix the code so that the last test can be removed.
2400
 
  */
2401
 
  if (!pending ||
2402
 
      pending->server_id != serv_id || 
2403
 
      pending->get_table_id() != table->s->table_map_id ||
2404
 
      pending->get_type_code() != type_code || 
2405
 
      pending->get_data_size() + needed > opt_binlog_rows_event_max_size ||
2406
 
      !bitmap_cmp(pending->get_cols(), table->write_set))
2407
 
    {
2408
 
    /* Create a new RowsEventT... */
2409
 
    Rows_log_event* const
2410
 
        ev= new RowsEventT(this, table, table->s->table_map_id,
2411
 
                           is_transactional);
2412
 
    if (unlikely(!ev))
2413
 
      return(NULL);
2414
 
    ev->server_id= serv_id; // I don't like this, it's too easy to forget.
2415
 
    /*
2416
 
      flush the pending event and replace it with the newly created
2417
 
      event...
2418
 
    */
2419
 
    if (unlikely(mysql_bin_log.flush_and_set_pending_rows_event(this, ev)))
2420
 
    {
2421
 
      delete ev;
2422
 
      return(NULL);
2423
 
    }
2424
 
 
2425
 
    return(ev);               /* This is the new pending event */
2426
 
  }
2427
 
  return(pending);        /* This is the current pending event */
2428
 
}
2429
 
 
2430
 
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
2431
 
/*
2432
 
  Instantiate the versions we need, we have -fno-implicit-template as
2433
 
  compiling option.
2434
 
*/
2435
 
template Rows_log_event*
2436
 
THD::binlog_prepare_pending_rows_event(Table*, uint32_t, size_t, bool,
2437
 
                                       Write_rows_log_event*);
2438
 
 
2439
 
template Rows_log_event*
2440
 
THD::binlog_prepare_pending_rows_event(Table*, uint32_t, size_t, bool,
2441
 
                                       Delete_rows_log_event *);
2442
 
 
2443
 
template Rows_log_event* 
2444
 
THD::binlog_prepare_pending_rows_event(Table*, uint32_t, size_t, bool,
2445
 
                                       Update_rows_log_event *);
2446
 
#endif
2447
 
 
2448
 
namespace {
2449
 
  /**
2450
 
     Class to handle temporary allocation of memory for row data.
2451
 
 
2452
 
     The responsibilities of the class is to provide memory for
2453
 
     packing one or two rows of packed data (depending on what
2454
 
     constructor is called).
2455
 
 
2456
 
     In order to make the allocation more efficient for "simple" rows,
2457
 
     i.e., rows that do not contain any blobs, a pointer to the
2458
 
     allocated memory is of memory is stored in the table structure
2459
 
     for simple rows.  If memory for a table containing a blob field
2460
 
     is requested, only memory for that is allocated, and subsequently
2461
 
     released when the object is destroyed.
2462
 
 
2463
 
   */
2464
 
  class Row_data_memory {
2465
 
  public:
2466
 
    /**
2467
 
      Build an object to keep track of a block-local piece of memory
2468
 
      for storing a row of data.
2469
 
 
2470
 
      @param table
2471
 
      Table where the pre-allocated memory is stored.
2472
 
 
2473
 
      @param length
2474
 
      Length of data that is needed, if the record contain blobs.
2475
 
     */
2476
 
    Row_data_memory(Table *table, size_t const len1)
2477
 
      : m_memory(0)
2478
 
    {
2479
 
      m_alloc_checked= false;
2480
 
      allocate_memory(table, len1);
2481
 
      m_ptr[0]= has_memory() ? m_memory : 0;
2482
 
      m_ptr[1]= 0;
2483
 
    }
2484
 
 
2485
 
    Row_data_memory(Table *table, size_t const len1, size_t const len2)
2486
 
      : m_memory(0)
2487
 
    {
2488
 
      m_alloc_checked= false;
2489
 
      allocate_memory(table, len1 + len2);
2490
 
      m_ptr[0]= has_memory() ? m_memory        : 0;
2491
 
      m_ptr[1]= has_memory() ? m_memory + len1 : 0;
2492
 
    }
2493
 
 
2494
 
    ~Row_data_memory()
2495
 
    {
2496
 
      if (m_memory != 0 && m_release_memory_on_destruction)
2497
 
        free((unsigned char*) m_memory);
2498
 
    }
2499
 
 
2500
 
    /**
2501
 
       Is there memory allocated?
2502
 
 
2503
 
       @retval true There is memory allocated
2504
 
       @retval false Memory allocation failed
2505
 
     */
2506
 
    bool has_memory() const {
2507
 
      m_alloc_checked= true;
2508
 
      return m_memory != 0;
2509
 
    }
2510
 
 
2511
 
    unsigned char *slot(uint32_t s)
2512
 
    {
2513
 
      assert(s < sizeof(m_ptr)/sizeof(*m_ptr));
2514
 
      assert(m_ptr[s] != 0);
2515
 
      assert(m_alloc_checked == true);
2516
 
      return m_ptr[s];
2517
 
    }
2518
 
 
2519
 
  private:
2520
 
    void allocate_memory(Table *const table, size_t const total_length)
2521
 
    {
2522
 
      if (table->s->blob_fields == 0)
2523
 
      {
2524
 
        /*
2525
 
          The maximum length of a packed record is less than this
2526
 
          length. We use this value instead of the supplied length
2527
 
          when allocating memory for records, since we don't know how
2528
 
          the memory will be used in future allocations.
2529
 
 
2530
 
          Since table->s->reclength is for unpacked records, we have
2531
 
          to add two bytes for each field, which can potentially be
2532
 
          added to hold the length of a packed field.
2533
 
        */
2534
 
        size_t const maxlen= table->s->reclength + 2 * table->s->fields;
2535
 
 
2536
 
        /*
2537
 
          Allocate memory for two records if memory hasn't been
2538
 
          allocated. We allocate memory for two records so that it can
2539
 
          be used when processing update rows as well.
2540
 
        */
2541
 
        if (table->write_row_record == 0)
2542
 
          table->write_row_record=
2543
 
            (unsigned char *) alloc_root(&table->mem_root, 2 * maxlen);
2544
 
        m_memory= table->write_row_record;
2545
 
        m_release_memory_on_destruction= false;
2546
 
      }
2547
 
      else
2548
 
      {
2549
 
        m_memory= (unsigned char *) my_malloc(total_length, MYF(MY_WME));
2550
 
        m_release_memory_on_destruction= true;
2551
 
      }
2552
 
    }
2553
 
 
2554
 
    mutable bool m_alloc_checked;
2555
 
    bool m_release_memory_on_destruction;
2556
 
    unsigned char *m_memory;
2557
 
    unsigned char *m_ptr[2];
2558
 
  };
2559
 
}
2560
 
 
2561
 
 
2562
 
int THD::binlog_write_row(Table* table, bool is_trans, 
2563
 
                          unsigned char const *record) 
2564
 
2565
 
  assert(current_stmt_binlog_row_based && mysql_bin_log.is_open());
2566
 
 
2567
 
  /*
2568
 
    Pack records into format for transfer. We are allocating more
2569
 
    memory than needed, but that doesn't matter.
2570
 
  */
2571
 
  Row_data_memory memory(table, table->max_row_length(record));
2572
 
  if (!memory.has_memory())
2573
 
    return HA_ERR_OUT_OF_MEM;
2574
 
 
2575
 
  unsigned char *row_data= memory.slot(0);
2576
 
 
2577
 
  size_t const len= pack_row(table, table->write_set, row_data, record);
2578
 
 
2579
 
  Rows_log_event* const ev=
2580
 
    binlog_prepare_pending_rows_event(table, server_id, len, is_trans,
2581
 
                                      static_cast<Write_rows_log_event*>(0));
2582
 
 
2583
 
  if (unlikely(ev == 0))
2584
 
    return HA_ERR_OUT_OF_MEM;
2585
 
 
2586
 
  return ev->add_row_data(row_data, len);
2587
 
}
2588
 
 
2589
 
int THD::binlog_update_row(Table* table, bool is_trans,
2590
 
                           const unsigned char *before_record,
2591
 
                           const unsigned char *after_record)
2592
 
2593
 
  assert(current_stmt_binlog_row_based && mysql_bin_log.is_open());
2594
 
 
2595
 
  size_t const before_maxlen = table->max_row_length(before_record);
2596
 
  size_t const after_maxlen  = table->max_row_length(after_record);
2597
 
 
2598
 
  Row_data_memory row_data(table, before_maxlen, after_maxlen);
2599
 
  if (!row_data.has_memory())
2600
 
    return HA_ERR_OUT_OF_MEM;
2601
 
 
2602
 
  unsigned char *before_row= row_data.slot(0);
2603
 
  unsigned char *after_row= row_data.slot(1);
2604
 
 
2605
 
  size_t const before_size= pack_row(table, table->read_set, before_row,
2606
 
                                        before_record);
2607
 
  size_t const after_size= pack_row(table, table->write_set, after_row,
2608
 
                                       after_record);
2609
 
 
2610
 
  Rows_log_event* const ev=
2611
 
    binlog_prepare_pending_rows_event(table, server_id,
2612
 
                                      before_size + after_size, is_trans,
2613
 
                                      static_cast<Update_rows_log_event*>(0));
2614
 
 
2615
 
  if (unlikely(ev == 0))
2616
 
    return HA_ERR_OUT_OF_MEM;
2617
 
 
2618
 
  return
2619
 
    ev->add_row_data(before_row, before_size) ||
2620
 
    ev->add_row_data(after_row, after_size);
2621
 
}
2622
 
 
2623
 
int THD::binlog_delete_row(Table* table, bool is_trans, 
2624
 
                           unsigned char const *record)
2625
 
2626
 
  assert(current_stmt_binlog_row_based && mysql_bin_log.is_open());
2627
 
 
2628
 
  /* 
2629
 
     Pack records into format for transfer. We are allocating more
2630
 
     memory than needed, but that doesn't matter.
2631
 
  */
2632
 
  Row_data_memory memory(table, table->max_row_length(record));
2633
 
  if (unlikely(!memory.has_memory()))
2634
 
    return HA_ERR_OUT_OF_MEM;
2635
 
 
2636
 
  unsigned char *row_data= memory.slot(0);
2637
 
 
2638
 
  size_t const len= pack_row(table, table->read_set, row_data, record);
2639
 
 
2640
 
  Rows_log_event* const ev=
2641
 
    binlog_prepare_pending_rows_event(table, server_id, len, is_trans,
2642
 
                                      static_cast<Delete_rows_log_event*>(0));
2643
 
 
2644
 
  if (unlikely(ev == 0))
2645
 
    return HA_ERR_OUT_OF_MEM;
2646
 
 
2647
 
  return ev->add_row_data(row_data, len);
2648
 
}
2649
 
 
2650
 
 
2651
 
int THD::binlog_flush_pending_rows_event(bool stmt_end)
2652
 
{
2653
 
  /*
2654
 
    We shall flush the pending event even if we are not in row-based
2655
 
    mode: it might be the case that we left row-based mode before
2656
 
    flushing anything (e.g., if we have explicitly locked tables).
2657
 
   */
2658
 
  if (!mysql_bin_log.is_open())
2659
 
    return(0);
2660
 
 
2661
 
  /*
2662
 
    Mark the event as the last event of a statement if the stmt_end
2663
 
    flag is set.
2664
 
  */
2665
 
  int error= 0;
2666
 
  if (Rows_log_event *pending= binlog_get_pending_rows_event())
2667
 
  {
2668
 
    if (stmt_end)
2669
 
    {
2670
 
      pending->set_flags(Rows_log_event::STMT_END_F);
2671
 
      pending->flags|= LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F;
2672
 
      binlog_table_maps= 0;
2673
 
    }
2674
 
 
2675
 
    error= mysql_bin_log.flush_and_set_pending_rows_event(this, 0);
2676
 
  }
2677
 
 
2678
 
  return(error);
2679
 
}
2680
 
 
2681
 
 
2682
 
/*
2683
 
  Member function that will log query, either row-based or
2684
 
  statement-based depending on the value of the 'current_stmt_binlog_row_based'
2685
 
  the value of the 'qtype' flag.
2686
 
 
2687
 
  This function should be called after the all calls to ha_*_row()
2688
 
  functions have been issued, but before tables are unlocked and
2689
 
  closed.
2690
 
 
2691
 
  OBSERVE
2692
 
    There shall be no writes to any system table after calling
2693
 
    binlog_query(), so these writes has to be moved to before the call
2694
 
    of binlog_query() for correct functioning.
2695
 
 
2696
 
    This is necessesary not only for RBR, but the master might crash
2697
 
    after binlogging the query but before changing the system tables.
2698
 
    This means that the slave and the master are not in the same state
2699
 
    (after the master has restarted), so therefore we have to
2700
 
    eliminate this problem.
2701
 
 
2702
 
  RETURN VALUE
2703
 
    Error code, or 0 if no error.
2704
 
*/
2705
 
int THD::binlog_query(THD::enum_binlog_query_type qtype, char const *query_arg,
2706
 
                      ulong query_len, bool is_trans, bool suppress_use,
2707
 
                      THD::killed_state killed_status_arg)
2708
 
{
2709
 
  assert(query_arg && mysql_bin_log.is_open());
2710
 
 
2711
 
  if (int error= binlog_flush_pending_rows_event(true))
2712
 
    return(error);
2713
 
 
2714
 
  /*
2715
 
    If we are in statement mode and trying to log an unsafe statement,
2716
 
    we should print a warning.
2717
 
  */
2718
 
  if (lex->is_stmt_unsafe() &&
2719
 
      variables.binlog_format == BINLOG_FORMAT_STMT)
2720
 
  {
2721
 
    assert(this->query != NULL);
2722
 
    push_warning(this, DRIZZLE_ERROR::WARN_LEVEL_WARN,
2723
 
                 ER_BINLOG_UNSAFE_STATEMENT,
2724
 
                 ER(ER_BINLOG_UNSAFE_STATEMENT));
2725
 
    if (!(binlog_flags & BINLOG_FLAG_UNSAFE_STMT_PRINTED))
2726
 
    {
2727
 
      char warn_buf[DRIZZLE_ERRMSG_SIZE];
2728
 
      snprintf(warn_buf, DRIZZLE_ERRMSG_SIZE, "%s Statement: %s",
2729
 
               ER(ER_BINLOG_UNSAFE_STATEMENT), this->query);
2730
 
      sql_print_warning(warn_buf);
2731
 
      binlog_flags|= BINLOG_FLAG_UNSAFE_STMT_PRINTED;
2732
 
    }
2733
 
  }
2734
 
 
2735
 
  switch (qtype) {
2736
 
  case THD::ROW_QUERY_TYPE:
2737
 
    if (current_stmt_binlog_row_based)
2738
 
      return(0);
2739
 
    /* Otherwise, we fall through */
2740
 
  case THD::DRIZZLE_QUERY_TYPE:
2741
 
    /*
2742
 
      Using this query type is a conveniece hack, since we have been
2743
 
      moving back and forth between using RBR for replication of
2744
 
      system tables and not using it.
2745
 
 
2746
 
      Make sure to change in check_table_binlog_row_based() according
2747
 
      to how you treat this.
2748
 
    */
2749
 
  case THD::STMT_QUERY_TYPE:
2750
 
    /*
2751
 
      The DRIZZLE_LOG::write() function will set the STMT_END_F flag and
2752
 
      flush the pending rows event if necessary.
2753
 
     */
2754
 
    {
2755
 
      Query_log_event qinfo(this, query_arg, query_len, is_trans, suppress_use,
2756
 
                            killed_status_arg);
2757
 
      qinfo.flags|= LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F;
2758
 
      /*
2759
 
        Binlog table maps will be irrelevant after a Query_log_event
2760
 
        (they are just removed on the slave side) so after the query
2761
 
        log event is written to the binary log, we pretend that no
2762
 
        table maps were written.
2763
 
       */
2764
 
      int error= mysql_bin_log.write(&qinfo);
2765
 
      binlog_table_maps= 0;
2766
 
      return(error);
2767
 
    }
2768
 
    break;
2769
 
 
2770
 
  case THD::QUERY_TYPE_COUNT:
2771
 
  default:
2772
 
    assert(0 <= qtype && qtype < QUERY_TYPE_COUNT);
2773
 
  }
2774
 
  return(0);
2775
 
}
2776
 
 
2777
 
bool Discrete_intervals_list::append(uint64_t start, uint64_t val,
2778
 
                                 uint64_t incr)
2779
 
{
2780
 
  /* first, see if this can be merged with previous */
2781
 
  if ((head == NULL) || tail->merge_if_contiguous(start, val, incr))
2782
 
  {
2783
 
    /* it cannot, so need to add a new interval */
2784
 
    Discrete_interval *new_interval= new Discrete_interval(start, val, incr);
2785
 
    return(append(new_interval));
2786
 
  }
2787
 
  return(0);
2788
 
}
2789
 
 
2790
 
bool Discrete_intervals_list::append(Discrete_interval *new_interval)
2791
 
{
2792
 
  if (unlikely(new_interval == NULL))
2793
 
    return(1);
2794
 
  if (head == NULL)
2795
 
    head= current= new_interval;
2796
 
  else
2797
 
    tail->next= new_interval;
2798
 
  tail= new_interval;
2799
 
  elements++;
2800
 
  return(0);
 
2200
void mark_transaction_to_rollback(Session *session, bool all)
 
2201
{
 
2202
  if (session)
 
2203
  {
 
2204
    session->is_fatal_sub_stmt_error= true;
 
2205
    session->transaction_rollback_request= all;
 
2206
  }
 
2207
}
 
2208
 
 
2209
void Session::disconnect(uint32_t errcode, bool should_lock)
 
2210
{
 
2211
  /* Allow any plugins to cleanup their session variables */
 
2212
  plugin_sessionvar_cleanup(this);
 
2213
 
 
2214
  /* If necessary, log any aborted or unauthorized connections */
 
2215
  if (killed || (net.error && net.vio != 0))
 
2216
    statistic_increment(aborted_threads, &LOCK_status);
 
2217
 
 
2218
  if (net.error && net.vio != 0)
 
2219
  {
 
2220
    if (! killed && variables.log_warnings > 1)
 
2221
    {
 
2222
      Security_context *sctx= &security_ctx;
 
2223
 
 
2224
      errmsg_printf(ERRMSG_LVL_WARN, ER(ER_NEW_ABORTING_CONNECTION)
 
2225
                  , thread_id
 
2226
                  , (db ? db : "unconnected")
 
2227
                  , sctx->user.empty() == false ? sctx->user.c_str() : "unauthenticated"
 
2228
                  , sctx->ip.c_str()
 
2229
                  , (main_da.is_error() ? main_da.message() : ER(ER_UNKNOWN_ERROR)));
 
2230
    }
 
2231
  }
 
2232
 
 
2233
  /* Close out our connection to the client */
 
2234
  st_vio *vio;
 
2235
  if (should_lock)
 
2236
    (void) pthread_mutex_lock(&LOCK_thread_count);
 
2237
  killed= Session::KILL_CONNECTION;
 
2238
  if ((vio= net.vio) != 0)
 
2239
  {
 
2240
    if (errcode)
 
2241
      net_send_error(this, errcode, ER(errcode)); /* purecov: inspected */
 
2242
    drizzleclient_net_close(&net);              /* vio is freed in delete session */
 
2243
  }
 
2244
  if (should_lock)
 
2245
    (void) pthread_mutex_unlock(&LOCK_thread_count);
 
2246
}
 
2247
 
 
2248
/**
 
2249
 Reset Session part responsible for command processing state.
 
2250
 
 
2251
   This needs to be called before execution of every statement
 
2252
   (prepared or conventional).
 
2253
   It is not called by substatements of routines.
 
2254
 
 
2255
  @todo
 
2256
   Make it a method of Session and align its name with the rest of
 
2257
   reset/end/start/init methods.
 
2258
  @todo
 
2259
   Call it after we use Session for queries, not before.
 
2260
*/
 
2261
 
 
2262
void Session::reset_for_next_command()
 
2263
{
 
2264
  free_list= 0;
 
2265
  select_number= 1;
 
2266
  /*
 
2267
    Those two lines below are theoretically unneeded as
 
2268
    Session::cleanup_after_query() should take care of this already.
 
2269
  */
 
2270
  auto_inc_intervals_in_cur_stmt_for_binlog.empty();
 
2271
 
 
2272
  is_fatal_error= 0;
 
2273
  server_status&= ~ (SERVER_MORE_RESULTS_EXISTS |
 
2274
                          SERVER_QUERY_NO_INDEX_USED |
 
2275
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
 
2276
  /*
 
2277
    If in autocommit mode and not in a transaction, reset
 
2278
    OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings
 
2279
    in ha_rollback_trans() about some tables couldn't be rolled back.
 
2280
  */
 
2281
  if (!(options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
 
2282
  {
 
2283
    options&= ~OPTION_KEEP_LOG;
 
2284
    transaction.all.modified_non_trans_table= false;
 
2285
  }
 
2286
  thread_specific_used= false;
 
2287
 
 
2288
  clear_error();
 
2289
  main_da.reset_diagnostics_area();
 
2290
  total_warn_count=0;                   // Warnings for this query
 
2291
  sent_row_count= examined_row_count= 0;
 
2292
 
 
2293
  return;
 
2294
}
 
2295
 
 
2296
/*
 
2297
  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
 
2298
  creates one DROP TEMPORARY Table binlog event for each pseudo-thread
 
2299
*/
 
2300
 
 
2301
void Session::close_temporary_tables()
 
2302
{
 
2303
  Table *table;
 
2304
  Table *tmp_next;
 
2305
 
 
2306
  if (!temporary_tables)
 
2307
    return;
 
2308
 
 
2309
  for (table= temporary_tables; table; table= tmp_next)
 
2310
  {
 
2311
    tmp_next= table->next;
 
2312
    close_temporary(table, 1, 1);
 
2313
  }
 
2314
  temporary_tables= 0;
 
2315
 
 
2316
  return;
 
2317
}
 
2318
 
 
2319
 
 
2320
/** Clear most status variables. */
 
2321
extern time_t flush_status_time;
 
2322
extern uint32_t max_used_connections;
 
2323
 
 
2324
void Session::refresh_status()
 
2325
{
 
2326
  pthread_mutex_lock(&LOCK_status);
 
2327
 
 
2328
  /* Add thread's status variabes to global status */
 
2329
  add_to_status(&global_status_var, &status_var);
 
2330
 
 
2331
  /* Reset thread's status variables */
 
2332
  memset(&status_var, 0, sizeof(status_var));
 
2333
 
 
2334
  /* Reset some global variables */
 
2335
  reset_status_vars();
 
2336
 
 
2337
  /* Reset the counters of all key caches (default and named). */
 
2338
  process_key_caches(reset_key_cache_counters);
 
2339
  flush_status_time= time((time_t*) 0);
 
2340
  max_used_connections= 1; /* We set it to one, because we know we exist */
 
2341
  pthread_mutex_unlock(&LOCK_status);
2801
2342
}