~drizzle-trunk/drizzle/development

1 by brian
clean slate
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
/* Classes in mysql */
18
19
#ifdef USE_PRAGMA_INTERFACE
20
#pragma interface			/* gcc class implementation */
21
#endif
22
23
#include <mysql/plugin_audit.h>
24
#include "log.h"
25
#include "rpl_tblmap.h"
26
27
class Relay_log_info;
28
29
class Query_log_event;
30
class Load_log_event;
31
class Slave_log_event;
32
class Lex_input_stream;
33
class Rows_log_event;
34
35
enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE };
36
enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
37
enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE };
38
enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON,
39
			    DELAY_KEY_WRITE_ALL };
40
enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT,
41
                            SLAVE_EXEC_MODE_IDEMPOTENT,
42
                            SLAVE_EXEC_MODE_LAST_BIT};
43
enum enum_mark_columns
44
{ MARK_COLUMNS_NONE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE};
45
enum enum_filetype { FILETYPE_CSV, FILETYPE_XML };
46
47
extern char internal_table_name[2];
48
extern char empty_c_string[1];
49
extern const char **errmesg;
50
51
#define TC_LOG_PAGE_SIZE   8192
52
#define TC_LOG_MIN_SIZE    (3*TC_LOG_PAGE_SIZE)
53
54
#define TC_HEURISTIC_RECOVER_COMMIT   1
55
#define TC_HEURISTIC_RECOVER_ROLLBACK 2
56
extern uint tc_heuristic_recover;
57
58
typedef struct st_user_var_events
59
{
60
  user_var_entry *user_var_event;
61
  char *value;
62
  ulong length;
63
  Item_result type;
64
  uint charset_number;
65
} BINLOG_USER_VAR_EVENT;
66
67
#define RP_LOCK_LOG_IS_ALREADY_LOCKED 1
68
#define RP_FORCE_ROTATE               2
69
70
/*
71
  The COPY_INFO structure is used by INSERT/REPLACE code.
72
  The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
73
  UPDATE code:
74
    If a row is inserted then the copied variable is incremented.
75
    If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
76
      new data differs from the old one then the copied and the updated
77
      variables are incremented.
78
    The touched variable is incremented if a row was touched by the update part
79
      of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
80
      was actually changed or not.
81
*/
82
typedef struct st_copy_info {
83
  ha_rows records; /**< Number of processed records */
84
  ha_rows deleted; /**< Number of deleted records */
85
  ha_rows updated; /**< Number of updated records */
86
  ha_rows copied;  /**< Number of copied records */
87
  ha_rows error_count;
88
  ha_rows touched; /* Number of touched records */
89
  enum enum_duplicates handle_duplicates;
90
  int escape_char, last_errno;
91
  bool ignore;
92
  /* for INSERT ... UPDATE */
93
  List<Item> *update_fields;
94
  List<Item> *update_values;
95
  /* for VIEW ... WITH CHECK OPTION */
96
} COPY_INFO;
97
98
99
class Key_part_spec :public Sql_alloc {
100
public:
101
  LEX_STRING field_name;
102
  uint length;
103
  Key_part_spec(const LEX_STRING &name, uint len)
104
    : field_name(name), length(len)
105
  {}
106
  Key_part_spec(const char *name, const size_t name_len, uint len)
107
    : length(len)
108
  { field_name.str= (char *)name; field_name.length= name_len; }
109
  bool operator==(const Key_part_spec& other) const;
110
  /**
111
    Construct a copy of this Key_part_spec. field_name is copied
112
    by-pointer as it is known to never change. At the same time
113
    'length' may be reset in mysql_prepare_create_table, and this
114
    is why we supply it with a copy.
115
116
    @return If out of memory, 0 is returned and an error is set in
117
    THD.
118
  */
119
  Key_part_spec *clone(MEM_ROOT *mem_root) const
120
  { return new (mem_root) Key_part_spec(*this); }
121
};
122
123
124
class Alter_drop :public Sql_alloc {
125
public:
126
  enum drop_type {KEY, COLUMN };
127
  const char *name;
128
  enum drop_type type;
129
  Alter_drop(enum drop_type par_type,const char *par_name)
130
    :name(par_name), type(par_type) {}
131
  /**
132
    Used to make a clone of this object for ALTER/CREATE TABLE
133
    @sa comment for Key_part_spec::clone
134
  */
135
  Alter_drop *clone(MEM_ROOT *mem_root) const
136
    { return new (mem_root) Alter_drop(*this); }
137
};
138
139
140
class Alter_column :public Sql_alloc {
141
public:
142
  const char *name;
143
  Item *def;
144
  Alter_column(const char *par_name,Item *literal)
145
    :name(par_name), def(literal) {}
146
  /**
147
    Used to make a clone of this object for ALTER/CREATE TABLE
148
    @sa comment for Key_part_spec::clone
149
  */
150
  Alter_column *clone(MEM_ROOT *mem_root) const
151
    { return new (mem_root) Alter_column(*this); }
152
};
153
154
155
class Key :public Sql_alloc {
156
public:
157
  enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FOREIGN_KEY};
158
  enum Keytype type;
159
  KEY_CREATE_INFO key_create_info;
160
  List<Key_part_spec> columns;
161
  LEX_STRING name;
162
  bool generated;
163
164
  Key(enum Keytype type_par, const LEX_STRING &name_arg,
165
      KEY_CREATE_INFO *key_info_arg,
166
      bool generated_arg, List<Key_part_spec> &cols)
167
    :type(type_par), key_create_info(*key_info_arg), columns(cols),
168
    name(name_arg), generated(generated_arg)
169
  {}
170
  Key(enum Keytype type_par, const char *name_arg, size_t name_len_arg,
171
      KEY_CREATE_INFO *key_info_arg, bool generated_arg,
172
      List<Key_part_spec> &cols)
173
    :type(type_par), key_create_info(*key_info_arg), columns(cols),
174
    generated(generated_arg)
175
  {
176
    name.str= (char *)name_arg;
177
    name.length= name_len_arg;
178
  }
179
  Key(const Key &rhs, MEM_ROOT *mem_root);
180
  virtual ~Key() {}
181
  /* Equality comparison of keys (ignoring name) */
182
  friend bool foreign_key_prefix(Key *a, Key *b);
183
  /**
184
    Used to make a clone of this object for ALTER/CREATE TABLE
185
    @sa comment for Key_part_spec::clone
186
  */
187
  virtual Key *clone(MEM_ROOT *mem_root) const
188
    { return new (mem_root) Key(*this, mem_root); }
189
};
190
191
class Table_ident;
192
193
class Foreign_key: public Key {
194
public:
195
  enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
196
		      FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
197
  enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
198
		   FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT};
199
200
  Table_ident *ref_table;
201
  List<Key_part_spec> ref_columns;
202
  uint delete_opt, update_opt, match_opt;
203
  Foreign_key(const LEX_STRING &name_arg, List<Key_part_spec> &cols,
204
	      Table_ident *table,   List<Key_part_spec> &ref_cols,
205
	      uint delete_opt_arg, uint update_opt_arg, uint match_opt_arg)
206
    :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols),
207
    ref_table(table), ref_columns(ref_cols),
208
    delete_opt(delete_opt_arg), update_opt(update_opt_arg),
209
    match_opt(match_opt_arg)
210
  {}
211
  Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root);
212
  /**
213
    Used to make a clone of this object for ALTER/CREATE TABLE
214
    @sa comment for Key_part_spec::clone
215
  */
216
  virtual Key *clone(MEM_ROOT *mem_root) const
217
  { return new (mem_root) Foreign_key(*this, mem_root); }
218
};
219
220
typedef struct st_mysql_lock
221
{
222
  TABLE **table;
223
  uint table_count,lock_count;
224
  THR_LOCK_DATA **locks;
225
} MYSQL_LOCK;
226
227
228
class LEX_COLUMN : public Sql_alloc
229
{
230
public:
231
  String column;
232
  uint rights;
233
  LEX_COLUMN (const String& x,const  uint& y ): column (x),rights (y) {}
234
};
235
236
/**
237
  Query_cache_tls -- query cache thread local data.
238
*/
239
240
struct Query_cache_block;
241
242
struct Query_cache_tls
243
{
244
  /*
245
    'first_query_block' should be accessed only via query cache
246
    functions and methods to maintain proper locking.
247
  */
248
  Query_cache_block *first_query_block;
249
  void set_first_query_block(Query_cache_block *first_query_block_arg)
250
  {
251
    first_query_block= first_query_block_arg;
252
  }
253
254
  Query_cache_tls() :first_query_block(NULL) {}
255
};
256
257
#include "sql_lex.h"				/* Must be here */
258
259
class select_result;
260
class Time_zone;
261
262
#define THD_SENTRY_MAGIC 0xfeedd1ff
263
#define THD_SENTRY_GONE  0xdeadbeef
264
265
#define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
266
267
struct system_variables
268
{
269
  /*
270
    How dynamically allocated system variables are handled:
271
    
272
    The global_system_variables and max_system_variables are "authoritative"
273
    They both should have the same 'version' and 'size'.
274
    When attempting to access a dynamic variable, if the session version
275
    is out of date, then the session version is updated and realloced if
276
    neccessary and bytes copied from global to make up for missing data.
277
  */ 
278
  ulong dynamic_variables_version;
279
  char* dynamic_variables_ptr;
280
  uint dynamic_variables_head;  /* largest valid variable offset */
281
  uint dynamic_variables_size;  /* how many bytes are in use */
282
  
283
  ulonglong myisam_max_extra_sort_file_size;
284
  ulonglong myisam_max_sort_file_size;
285
  ulonglong max_heap_table_size;
286
  ulonglong tmp_table_size;
287
  ulonglong long_query_time;
288
  ha_rows select_limit;
289
  ha_rows max_join_size;
290
  ulong auto_increment_increment, auto_increment_offset;
291
  ulong bulk_insert_buff_size;
292
  ulong join_buff_size;
293
  ulong max_allowed_packet;
294
  ulong max_error_count;
295
  ulong max_length_for_sort_data;
296
  ulong max_sort_length;
297
  ulong max_tmp_tables;
298
  ulong min_examined_row_limit;
299
  ulong myisam_repair_threads;
300
  ulong myisam_sort_buff_size;
301
  ulong myisam_stats_method;
302
  ulong net_buffer_length;
303
  ulong net_interactive_timeout;
304
  ulong net_read_timeout;
305
  ulong net_retry_count;
306
  ulong net_wait_timeout;
307
  ulong net_write_timeout;
308
  ulong optimizer_prune_level;
309
  ulong optimizer_search_depth;
310
  /*
311
    Controls use of Engine-MRR:
312
      0 - auto, based on cost
313
      1 - force MRR when the storage engine is capable of doing it
314
      2 - disable MRR.
315
  */
316
  ulong optimizer_use_mrr; 
317
  /* A bitmap for switching optimizations on/off */
318
  ulong optimizer_switch;
319
  ulong preload_buff_size;
320
  ulong profiling_history_size;
321
  ulong query_cache_type;
322
  ulong read_buff_size;
323
  ulong read_rnd_buff_size;
324
  ulong div_precincrement;
325
  ulong sortbuff_size;
326
  ulong thread_handling;
327
  ulong tx_isolation;
328
  ulong completion_type;
329
  /* Determines which non-standard SQL behaviour should be enabled */
330
  ulong sql_mode;
331
  ulong default_week_format;
332
  ulong max_seeks_for_key;
333
  ulong range_alloc_block_size;
334
  ulong query_alloc_block_size;
335
  ulong query_prealloc_size;
336
  ulong trans_alloc_block_size;
337
  ulong trans_prealloc_size;
338
  ulong log_warnings;
339
  ulong group_concat_max_len;
340
  ulong binlog_format; // binlog format for this thd (see enum_binlog_format)
341
  /*
342
    In slave thread we need to know in behalf of which
343
    thread the query is being run to replicate temp tables properly
344
  */
345
  my_thread_id pseudo_thread_id;
346
347
  my_bool low_priority_updates;
348
  my_bool new_mode;
349
  /* 
350
    compatibility option:
351
      - index usage hints (USE INDEX without a FOR clause) behave as in 5.0 
352
  */
353
  my_bool old_mode;
354
  my_bool query_cache_wlock_invalidate;
355
  my_bool engine_condition_pushdown;
356
  my_bool keep_files_on_create;
357
358
  my_bool old_alter_table;
359
  my_bool old_passwords;
360
361
  plugin_ref table_plugin;
362
363
  /* Only charset part of these variables is sensible */
364
  CHARSET_INFO  *character_set_filesystem;
365
  CHARSET_INFO  *character_set_client;
366
  CHARSET_INFO  *character_set_results;
367
368
  /* Both charset and collation parts of these variables are important */
369
  CHARSET_INFO	*collation_server;
370
  CHARSET_INFO	*collation_database;
371
  CHARSET_INFO  *collation_connection;
372
373
  /* Locale Support */
374
  MY_LOCALE *lc_time_names;
375
376
  Time_zone *time_zone;
377
378
  /* DATE, DATETIME and MYSQL_TIME formats */
379
  DATE_TIME_FORMAT *date_format;
380
  DATE_TIME_FORMAT *datetime_format;
381
  DATE_TIME_FORMAT *time_format;
382
  my_bool sysdate_is_now;
383
384
};
385
386
387
/* per thread status variables */
388
389
typedef struct system_status_var
390
{
391
  ulonglong bytes_received;
392
  ulonglong bytes_sent;
393
  ulong com_other;
394
  ulong com_stat[(uint) SQLCOM_END];
395
  ulong created_tmp_disk_tables;
396
  ulong created_tmp_tables;
397
  ulong ha_commit_count;
398
  ulong ha_delete_count;
399
  ulong ha_read_first_count;
400
  ulong ha_read_last_count;
401
  ulong ha_read_key_count;
402
  ulong ha_read_next_count;
403
  ulong ha_read_prev_count;
404
  ulong ha_read_rnd_count;
405
  ulong ha_read_rnd_next_count;
406
  ulong ha_rollback_count;
407
  ulong ha_update_count;
408
  ulong ha_write_count;
409
  ulong ha_prepare_count;
410
  ulong ha_discover_count;
411
  ulong ha_savepoint_count;
412
  ulong ha_savepoint_rollback_count;
413
414
  /* KEY_CACHE parts. These are copies of the original */
415
  ulong key_blocks_changed;
416
  ulong key_blocks_used;
417
  ulong key_cache_r_requests;
418
  ulong key_cache_read;
419
  ulong key_cache_w_requests;
420
  ulong key_cache_write;
421
  /* END OF KEY_CACHE parts */
422
423
  ulong net_big_packet_count;
424
  ulong opened_tables;
425
  ulong opened_shares;
426
  ulong select_full_join_count;
427
  ulong select_full_range_join_count;
428
  ulong select_range_count;
429
  ulong select_range_check_count;
430
  ulong select_scan_count;
431
  ulong long_query_count;
432
  ulong filesort_merge_passes;
433
  ulong filesort_range_count;
434
  ulong filesort_rows;
435
  ulong filesort_scan_count;
436
  /* Prepared statements and binary protocol */
437
  ulong com_stmt_prepare;
438
  ulong com_stmt_execute;
439
  ulong com_stmt_send_long_data;
440
  ulong com_stmt_fetch;
441
  ulong com_stmt_reset;
442
  ulong com_stmt_close;
443
  /*
444
    Number of statements sent from the client
445
  */
446
  ulong questions;
447
448
  /*
449
    IMPORTANT!
450
    SEE last_system_status_var DEFINITION BELOW.
451
452
    Below 'last_system_status_var' are all variables which doesn't make any
453
    sense to add to the /global/ status variable counter.
454
  */
455
  double last_query_cost;
456
457
458
} STATUS_VAR;
459
460
/*
461
  This is used for 'SHOW STATUS'. It must be updated to the last ulong
462
  variable in system_status_var which is makes sens to add to the global
463
  counter
464
*/
465
466
#define last_system_status_var questions
467
468
void mark_transaction_to_rollback(THD *thd, bool all);
469
470
#ifdef MYSQL_SERVER
471
472
void free_tmp_table(THD *thd, TABLE *entry);
473
474
475
/* The following macro is to make init of Query_arena simpler */
476
#ifndef DBUG_OFF
477
#define INIT_ARENA_DBUG_INFO is_backup_arena= 0
478
#else
479
#define INIT_ARENA_DBUG_INFO
480
#endif
481
482
class Query_arena
483
{
484
public:
485
  /*
486
    List of items created in the parser for this query. Every item puts
487
    itself to the list on creation (see Item::Item() for details))
488
  */
489
  Item *free_list;
490
  MEM_ROOT *mem_root;                   // Pointer to current memroot
491
#ifndef DBUG_OFF
492
  bool is_backup_arena; /* True if this arena is used for backup. */
493
#endif
494
  /*
495
    The states relfects three diffrent life cycles for three
496
    different types of statements:
497
    Prepared statement: INITIALIZED -> PREPARED -> EXECUTED.
498
    Stored procedure:   INITIALIZED_FOR_SP -> EXECUTED.
499
    Other statements:   CONVENTIONAL_EXECUTION never changes.
500
  */
501
  enum enum_state
502
  {
503
    INITIALIZED= 0, INITIALIZED_FOR_SP= 1, PREPARED= 2,
504
    CONVENTIONAL_EXECUTION= 3, EXECUTED= 4, ERROR= -1
505
  };
506
507
  enum_state state;
508
509
  /* We build without RTTI, so dynamic_cast can't be used. */
510
  enum Type
511
  {
512
    STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE
513
  };
514
515
  Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) :
516
    free_list(0), mem_root(mem_root_arg), state(state_arg)
517
  { INIT_ARENA_DBUG_INFO; }
518
  /*
519
    This constructor is used only when Query_arena is created as
520
    backup storage for another instance of Query_arena.
521
  */
522
  Query_arena() { INIT_ARENA_DBUG_INFO; }
523
524
  virtual ~Query_arena() {};
525
526
  inline bool is_conventional() const
527
  { assert(state == CONVENTIONAL_EXECUTION); return state == CONVENTIONAL_EXECUTION; }
528
529
  inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
530
  inline void* calloc(size_t size)
531
  {
532
    void *ptr;
533
    if ((ptr=alloc_root(mem_root,size)))
534
      bzero(ptr, size);
535
    return ptr;
536
  }
537
  inline char *strdup(const char *str)
538
  { return strdup_root(mem_root,str); }
539
  inline char *strmake(const char *str, size_t size)
540
  { return strmake_root(mem_root,str,size); }
541
  inline void *memdup(const void *str, size_t size)
542
  { return memdup_root(mem_root,str,size); }
543
  inline void *memdup_w_gap(const void *str, size_t size, uint gap)
544
  {
545
    void *ptr;
546
    if ((ptr= alloc_root(mem_root,size+gap)))
547
      memcpy(ptr,str,size);
548
    return ptr;
549
  }
550
551
  void set_query_arena(Query_arena *set);
552
553
  void free_items();
554
  /* Close the active state associated with execution of this statement */
555
  virtual void cleanup_stmt();
556
};
557
558
559
/**
560
  @class Statement
561
  @brief State of a single command executed against this connection.
562
563
  One connection can contain a lot of simultaneously running statements,
564
  some of which could be:
565
   - prepared, that is, contain placeholders,
566
  To perform some action with statement we reset THD part to the state  of
567
  that statement, do the action, and then save back modified state from THD
568
  to the statement. It will be changed in near future, and Statement will
569
  be used explicitly.
570
*/
571
572
class Statement: public ilink, public Query_arena
573
{
574
  Statement(const Statement &rhs);              /* not implemented: */
575
  Statement &operator=(const Statement &rhs);   /* non-copyable */
576
public:
577
  /*
578
    Uniquely identifies each statement object in thread scope; change during
579
    statement lifetime. FIXME: must be const
580
  */
581
   ulong id;
582
583
  /*
584
    MARK_COLUMNS_NONE:  Means mark_used_colums is not set and no indicator to
585
                        handler of fields used is set
586
    MARK_COLUMNS_READ:  Means a bit in read set is set to inform handler
587
	                that the field is to be read. If field list contains
588
                        duplicates, then thd->dup_field is set to point
589
                        to the last found duplicate.
590
    MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
591
			that it needs to update this field in write_row
592
                        and update_row.
593
  */
594
  enum enum_mark_columns mark_used_columns;
595
596
  LEX_STRING name; /* name for named prepared statements */
597
  LEX *lex;                                     // parse tree descriptor
598
  /*
599
    Points to the query associated with this statement. It's const, but
600
    we need to declare it char * because all table handlers are written
601
    in C and need to point to it.
602
603
    Note that (A) if we set query = NULL, we must at the same time set
604
    query_length = 0, and protect the whole operation with the
605
    LOCK_thread_count mutex. And (B) we are ONLY allowed to set query to a
606
    non-NULL value if its previous value is NULL. We do not need to protect
607
    operation (B) with any mutex. To avoid crashes in races, if we do not
608
    know that thd->query cannot change at the moment, one should print
609
    thd->query like this:
610
      (1) reserve the LOCK_thread_count mutex;
611
      (2) check if thd->query is NULL;
612
      (3) if not NULL, then print at most thd->query_length characters from
613
      it. We will see the query_length field as either 0, or the right value
614
      for it.
615
    Assuming that the write and read of an n-bit memory field in an n-bit
616
    computer is atomic, we can avoid races in the above way. 
617
    This printing is needed at least in SHOW PROCESSLIST and SHOW INNODB
618
    STATUS.
619
  */
620
  char *query;
621
  uint32 query_length;                          // current query length
622
623
  /**
624
    Name of the current (default) database.
625
626
    If there is the current (default) database, "db" contains its name. If
627
    there is no current (default) database, "db" is NULL and "db_length" is
628
    0. In other words, "db", "db_length" must either be NULL, or contain a
629
    valid database name.
630
631
    @note this attribute is set and alloced by the slave SQL thread (for
632
    the THD of that thread); that thread is (and must remain, for now) the
633
    only responsible for freeing this member.
634
  */
635
636
  char *db;
637
  uint db_length;
638
639
public:
640
641
  /* This constructor is called for backup statements */
642
  Statement() {}
643
644
  Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
645
            enum enum_state state_arg, ulong id_arg);
646
  ~Statement() {}
647
648
  /* Assign execution context (note: not all members) of given stmt to self */
649
  void set_statement(Statement *stmt);
650
  void set_n_backup_statement(Statement *stmt, Statement *backup);
651
  void restore_backup_statement(Statement *stmt, Statement *backup);
652
};
653
654
struct st_savepoint {
655
  struct st_savepoint *prev;
656
  char                *name;
657
  uint                 length;
658
  Ha_trx_info         *ha_list;
659
};
660
661
enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED};
662
extern const char *xa_state_names[];
663
664
typedef struct st_xid_state {
665
  /* For now, this is only used to catch duplicated external xids */
666
  XID  xid;                           // transaction identifier
667
  enum xa_states xa_state;            // used by external XA only
668
  bool in_thd;
669
} XID_STATE;
670
671
extern pthread_mutex_t LOCK_xid_cache;
672
extern HASH xid_cache;
673
bool xid_cache_init(void);
674
void xid_cache_free(void);
675
XID_STATE *xid_cache_search(XID *xid);
676
bool xid_cache_insert(XID *xid, enum xa_states xa_state);
677
bool xid_cache_insert(XID_STATE *xid_state);
678
void xid_cache_delete(XID_STATE *xid_state);
679
680
/**
681
  @class Security_context
682
  @brief A set of THD members describing the current authenticated user.
683
*/
684
685
class Security_context {
686
public:
687
  Security_context() {}                       /* Remove gcc warning */
688
  /*
689
    host - host of the client
690
    user - user of the client, set to NULL until the user has been read from
691
    the connection
692
    priv_user - The user privilege we are using. May be "" for anonymous user.
693
    ip - client IP
694
  */
695
  char   *host, *user, *priv_user, *ip;
696
  /* The host privilege we are using */
697
  char   priv_host[MAX_HOSTNAME];
698
  /* points to host if host is available, otherwise points to ip */
699
  const char *host_or_ip;
700
  ulong db_access;                     /* Privileges for current db */
701
702
  void init();
703
  void destroy();
704
  void skip_grants();
705
  inline char *priv_host_name()
706
  {
707
    return (*priv_host ? priv_host : (char *)"%");
708
  }
709
};
710
711
712
/**
713
  A registry for item tree transformations performed during
714
  query optimization. We register only those changes which require
715
  a rollback to re-execute a prepared statement or stored procedure
716
  yet another time.
717
*/
718
719
struct Item_change_record;
720
typedef I_List<Item_change_record> Item_change_list;
721
722
723
/**
724
  Class that holds information about tables which were opened and locked
725
  by the thread. It is also used to save/restore this information in
726
  push_open_tables_state()/pop_open_tables_state().
727
*/
728
729
class Open_tables_state
730
{
731
public:
732
  /**
733
    List of regular tables in use by this thread. Contains temporary and
734
    base tables that were opened with @see open_tables().
735
  */
736
  TABLE *open_tables;
737
  /**
738
    List of temporary tables used by this thread. Contains user-level
739
    temporary tables, created with CREATE TEMPORARY TABLE, and
740
    internal temporary tables, created, e.g., to resolve a SELECT,
741
    or for an intermediate table used in ALTER.
742
    XXX Why are internal temporary tables added to this list?
743
  */
744
  TABLE *temporary_tables;
745
  /**
746
    List of tables that were opened with HANDLER OPEN and are
747
    still in use by this thread.
748
  */
749
  TABLE *handler_tables;
750
  TABLE *derived_tables;
751
  /*
752
    During a MySQL session, one can lock tables in two modes: automatic
753
    or manual. In automatic mode all necessary tables are locked just before
754
    statement execution, and all acquired locks are stored in 'lock'
755
    member. Unlocking takes place automatically as well, when the
756
    statement ends.
757
    Manual mode comes into play when a user issues a 'LOCK TABLES'
758
    statement. In this mode the user can only use the locked tables.
759
    Trying to use any other tables will give an error. The locked tables are
760
    stored in 'locked_tables' member.  Manual locking is described in
761
    the 'LOCK_TABLES' chapter of the MySQL manual.
762
    See also lock_tables() for details.
763
  */
764
  MYSQL_LOCK *lock;
765
  /*
766
    Tables that were locked with explicit or implicit LOCK TABLES.
767
    (Implicit LOCK TABLES happens when we are prelocking tables for
768
     execution of statement which uses stored routines. See description
769
     THD::prelocked_mode for more info.)
770
  */
771
  MYSQL_LOCK *locked_tables;
772
773
  /*
774
    CREATE-SELECT keeps an extra lock for the table being
775
    created. This field is used to keep the extra lock available for
776
    lower level routines, which would otherwise miss that lock.
777
   */
778
  MYSQL_LOCK *extra_lock;
779
780
  ulong	version;
781
  uint current_tablenr;
782
783
  enum enum_flags {
784
    BACKUPS_AVAIL = (1U << 0)     /* There are backups available */
785
  };
786
787
  /*
788
    Flags with information about the open tables state.
789
  */
790
  uint state_flags;
791
792
  /*
793
    This constructor serves for creation of Open_tables_state instances
794
    which are used as backup storage.
795
  */
796
  Open_tables_state() : state_flags(0U) { }
797
798
  Open_tables_state(ulong version_arg);
799
800
  void set_open_tables_state(Open_tables_state *state)
801
  {
802
    *this= *state;
803
  }
804
805
  void reset_open_tables_state()
806
  {
807
    open_tables= temporary_tables= handler_tables= derived_tables= 0;
808
    extra_lock= lock= locked_tables= 0;
809
    state_flags= 0U;
810
  }
811
};
812
813
/**
814
  @class Sub_statement_state
815
  @brief Used to save context when executing a function or trigger
816
*/
817
818
/* Defines used for Sub_statement_state::in_sub_stmt */
819
820
#define SUB_STMT_TRIGGER 1
821
#define SUB_STMT_FUNCTION 2
822
823
824
class Sub_statement_state
825
{
826
public:
827
  ulonglong options;
828
  ulonglong first_successful_insert_id_in_prev_stmt;
829
  ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row;
830
  Discrete_interval auto_inc_interval_for_cur_row;
831
  Discrete_intervals_list auto_inc_intervals_forced;
832
  ulonglong limit_found_rows;
833
  ha_rows    cuted_fields, sent_row_count, examined_row_count;
834
  ulong client_capabilities;
835
  uint in_sub_stmt;
836
  bool enable_slow_log;
837
  bool last_insert_id_used;
838
  SAVEPOINT *savepoints;
839
};
840
841
842
/* Flags for the THD::system_thread variable */
843
enum enum_thread_type
844
{
845
  NON_SYSTEM_THREAD= 0,
846
  SYSTEM_THREAD_DELAYED_INSERT= 1,
847
  SYSTEM_THREAD_SLAVE_IO= 2,
848
  SYSTEM_THREAD_SLAVE_SQL= 4,
849
  SYSTEM_THREAD_NDBCLUSTER_BINLOG= 8,
850
  SYSTEM_THREAD_EVENT_SCHEDULER= 16,
851
  SYSTEM_THREAD_EVENT_WORKER= 32,
852
  SYSTEM_THREAD_BACKUP= 64
853
};
854
855
856
/**
857
  This class represents the interface for internal error handlers.
858
  Internal error handlers are exception handlers used by the server
859
  implementation.
860
*/
861
class Internal_error_handler
862
{
863
protected:
864
  Internal_error_handler() {}
865
  virtual ~Internal_error_handler() {}
866
867
public:
868
  /**
869
    Handle an error condition.
870
    This method can be implemented by a subclass to achieve any of the
871
    following:
872
    - mask an error internally, prevent exposing it to the user,
873
    - mask an error and throw another one instead.
874
    When this method returns true, the error condition is considered
875
    'handled', and will not be propagated to upper layers.
876
    It is the responsability of the code installing an internal handler
877
    to then check for trapped conditions, and implement logic to recover
878
    from the anticipated conditions trapped during runtime.
879
880
    This mechanism is similar to C++ try/throw/catch:
881
    - 'try' correspond to <code>THD::push_internal_handler()</code>,
882
    - 'throw' correspond to <code>my_error()</code>,
883
    which invokes <code>my_message_sql()</code>,
884
    - 'catch' correspond to checking how/if an internal handler was invoked,
885
    before removing it from the exception stack with
886
    <code>THD::pop_internal_handler()</code>.
887
888
    @param sql_errno the error number
889
    @param level the error level
890
    @param thd the calling thread
891
    @return true if the error is handled
892
  */
893
  virtual bool handle_error(uint sql_errno,
894
                            const char *message,
895
                            MYSQL_ERROR::enum_warning_level level,
896
                            THD *thd) = 0;
897
};
898
899
900
/**
901
  Stores status of the currently executed statement.
902
  Cleared at the beginning of the statement, and then
903
  can hold either OK, ERROR, or EOF status.
904
  Can not be assigned twice per statement.
905
*/
906
907
class Diagnostics_area
908
{
909
public:
910
  enum enum_diagnostics_status
911
  {
912
    /** The area is cleared at start of a statement. */
913
    DA_EMPTY= 0,
914
    /** Set whenever one calls my_ok(). */
915
    DA_OK,
916
    /** Set whenever one calls my_eof(). */
917
    DA_EOF,
918
    /** Set whenever one calls my_error() or my_message(). */
919
    DA_ERROR,
920
    /** Set in case of a custom response, such as one from COM_STMT_PREPARE. */
921
    DA_DISABLED
922
  };
923
  /** True if status information is sent to the client. */
924
  bool is_sent;
925
  /** Set to make set_error_status after set_{ok,eof}_status possible. */
926
  bool can_overwrite_status;
927
928
  void set_ok_status(THD *thd, ha_rows affected_rows_arg,
929
                     ulonglong last_insert_id_arg,
930
                     const char *message);
931
  void set_eof_status(THD *thd);
932
  void set_error_status(THD *thd, uint sql_errno_arg, const char *message_arg);
933
934
  void disable_status();
935
936
  void reset_diagnostics_area();
937
938
  bool is_set() const { return m_status != DA_EMPTY; }
939
  bool is_error() const { return m_status == DA_ERROR; }
940
  bool is_eof() const { return m_status == DA_EOF; }
941
  bool is_ok() const { return m_status == DA_OK; }
942
  bool is_disabled() const { return m_status == DA_DISABLED; }
943
  enum_diagnostics_status status() const { return m_status; }
944
945
  const char *message() const
946
  { DBUG_ASSERT(m_status == DA_ERROR || m_status == DA_OK); return m_message; }
947
948
  uint sql_errno() const
949
  { DBUG_ASSERT(m_status == DA_ERROR); return m_sql_errno; }
950
951
  uint server_status() const
952
  {
953
    DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
954
    return m_server_status;
955
  }
956
957
  ha_rows affected_rows() const
958
  { DBUG_ASSERT(m_status == DA_OK); return m_affected_rows; }
959
960
  ulonglong last_insert_id() const
961
  { DBUG_ASSERT(m_status == DA_OK); return m_last_insert_id; }
962
963
  uint total_warn_count() const
964
  {
965
    DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
966
    return m_total_warn_count;
967
  }
968
969
  Diagnostics_area() { reset_diagnostics_area(); }
970
971
private:
972
  /** Message buffer. Can be used by OK or ERROR status. */
973
  char m_message[MYSQL_ERRMSG_SIZE];
974
  /**
975
    SQL error number. One of ER_ codes from share/errmsg.txt.
976
    Set by set_error_status.
977
  */
978
  uint m_sql_errno;
979
980
  /**
981
    Copied from thd->server_status when the diagnostics area is assigned.
982
    We need this member as some places in the code use the following pattern:
983
    thd->server_status|= ...
984
    my_eof(thd);
985
    thd->server_status&= ~...
986
    Assigned by OK, EOF or ERROR.
987
  */
988
  uint m_server_status;
989
  /**
990
    The number of rows affected by the last statement. This is
991
    semantically close to thd->row_count_func, but has a different
992
    life cycle. thd->row_count_func stores the value returned by
993
    function ROW_COUNT() and is cleared only by statements that
994
    update its value, such as INSERT, UPDATE, DELETE and few others.
995
    This member is cleared at the beginning of the next statement.
996
997
    We could possibly merge the two, but life cycle of thd->row_count_func
998
    can not be changed.
999
  */
1000
  ha_rows    m_affected_rows;
1001
  /**
1002
    Similarly to the previous member, this is a replacement of
1003
    thd->first_successful_insert_id_in_prev_stmt, which is used
1004
    to implement LAST_INSERT_ID().
1005
  */
1006
  ulonglong   m_last_insert_id;
1007
  /** The total number of warnings. */
1008
  uint	     m_total_warn_count;
1009
  enum_diagnostics_status m_status;
1010
  /**
1011
    @todo: the following THD members belong here:
1012
    - warn_list, warn_count,
1013
  */
1014
};
1015
1016
1017
/**
1018
  Storage engine specific thread local data.
1019
*/
1020
1021
struct Ha_data
1022
{
1023
  /**
1024
    Storage engine specific thread local data.
1025
    Lifetime: one user connection.
1026
  */
1027
  void *ha_ptr;
1028
  /**
1029
    0: Life time: one statement within a transaction. If @@autocommit is
1030
    on, also represents the entire transaction.
1031
    @sa trans_register_ha()
1032
1033
    1: Life time: one transaction within a connection.
1034
    If the storage engine does not participate in a transaction,
1035
    this should not be used.
1036
    @sa trans_register_ha()
1037
  */
1038
  Ha_trx_info ha_info[2];
1039
1040
  Ha_data() :ha_ptr(NULL) {}
1041
};
1042
1043
1044
/**
1045
  @class THD
1046
  For each client connection we create a separate thread with THD serving as
1047
  a thread/connection descriptor
1048
*/
1049
1050
class THD :public Statement,
1051
           public Open_tables_state
1052
{
1053
public:
1054
  /* Used to execute base64 coded binlog events in MySQL server */
1055
  Relay_log_info* rli_fake;
1056
1057
  /*
1058
    Constant for THD::where initialization in the beginning of every query.
1059
1060
    It's needed because we do not save/restore THD::where normally during
1061
    primary (non subselect) query execution.
1062
  */
1063
  static const char * const DEFAULT_WHERE;
1064
1065
  NET	  net;				// client connection descriptor
1066
  MEM_ROOT warn_root;			// For warnings and errors
1067
  Protocol *protocol;			// Current protocol
1068
  Protocol_text   protocol_text;	// Normal protocol
1069
  HASH    user_vars;			// hash for user variables
1070
  String  packet;			// dynamic buffer for network I/O
1071
  String  convert_buffer;               // buffer for charset conversions
1072
  struct  rand_struct rand;		// used for authentication
1073
  struct  system_variables variables;	// Changeable local variables
1074
  struct  system_status_var status_var; // Per thread statistic vars
1075
  struct  system_status_var *initial_status_var; /* used by show status */
1076
  THR_LOCK_INFO lock_info;              // Locking info of this thread
1077
  THR_LOCK_OWNER main_lock_id;          // To use for conventional queries
1078
  THR_LOCK_OWNER *lock_id;              // If not main_lock_id, points to
1079
                                        // the lock_id of a cursor.
1080
  pthread_mutex_t LOCK_delete;		// Locked before thd is deleted
1081
  /*
1082
    A pointer to the stack frame of handle_one_connection(),
1083
    which is called first in the thread for handling a client
1084
  */
1085
  char	  *thread_stack;
1086
1087
  /**
1088
    Currently selected catalog.
1089
  */
1090
  char *catalog;
1091
1092
  /**
1093
    @note
1094
    Some members of THD (currently 'Statement::db',
1095
    'catalog' and 'query')  are set and alloced by the slave SQL thread
1096
    (for the THD of that thread); that thread is (and must remain, for now)
1097
    the only responsible for freeing these 3 members. If you add members
1098
    here, and you add code to set them in replication, don't forget to
1099
    free_them_and_set_them_to_0 in replication properly. For details see
1100
    the 'err:' label of the handle_slave_sql() in sql/slave.cc.
1101
1102
    @see handle_slave_sql
1103
  */
1104
1105
  Security_context main_security_ctx;
1106
  Security_context *security_ctx;
1107
1108
  /*
1109
    Points to info-string that we show in SHOW PROCESSLIST
1110
    You are supposed to call THD_SET_PROC_INFO only if you have coded
1111
    a time-consuming piece that MySQL can get stuck in for a long time.
1112
1113
    Set it using the  thd_proc_info(THD *thread, const char *message)
1114
    macro/function.
1115
  */
1116
#ifndef DBUG_OFF
1117
  #define THD_SET_PROC_INFO(thd, info) \
1118
    (thd)->set_proc_info(__FILE__, __LINE__, (info))
1119
1120
  void set_proc_info(const char* file, int line, const char* info);
1121
#else
1122
  #define THD_SET_PROC_INFO(thd, info) \
1123
    (thd)->proc_info= (info)
1124
#endif
1125
1126
  inline const char* get_proc_info() { return proc_info;}
1127
1128
  /* left public for the the storage engines, please avoid direct use */
1129
  const char *proc_info;
1130
1131
  /*
1132
    Used in error messages to tell user in what part of MySQL we found an
1133
    error. E. g. when where= "having clause", if fix_fields() fails, user
1134
    will know that the error was in having clause.
1135
  */
1136
  const char *where;
1137
1138
  double tmp_double_value;                    /* Used in set_var.cc */
1139
  ulong client_capabilities;		/* What the client supports */
1140
  ulong max_client_packet_length;
1141
1142
  HASH		handler_tables_hash;
1143
  /*
1144
    One thread can hold up to one named user-level lock. This variable
1145
    points to a lock object if the lock is present. See item_func.cc and
1146
    chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK. 
1147
  */
1148
#ifndef DBUG_OFF
1149
  uint dbug_sentry; // watch out for memory corruption
1150
#endif
1151
  struct st_my_thread_var *mysys_var;
1152
  /*
1153
    Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
1154
    first byte of the packet in do_command()
1155
  */
1156
  enum enum_server_command command;
1157
  uint32     server_id;
1158
  uint32     file_id;			// for LOAD DATA INFILE
1159
  /* remote (peer) port */
1160
  uint16 peer_port;
1161
  time_t     start_time, user_time;
1162
  ulonglong  connect_utime, thr_create_utime; // track down slow pthread_create
1163
  ulonglong  start_utime, utime_after_lock;
1164
  
1165
  thr_lock_type update_lock_default;
1166
1167
  /* <> 0 if we are inside of trigger or stored function. */
1168
  uint in_sub_stmt;
1169
1170
  /* container for handler's private per-connection data */
1171
  Ha_data ha_data[MAX_HA];
1172
1173
  /* Place to store various things */
1174
  void *thd_marker;
1175
#ifndef MYSQL_CLIENT
1176
  int binlog_setup_trx_data();
1177
1178
  /*
1179
    Public interface to write RBR events to the binlog
1180
  */
1181
  void binlog_start_trans_and_stmt();
1182
  void binlog_set_stmt_begin();
1183
  int binlog_write_table_map(TABLE *table, bool is_transactional);
1184
  int binlog_write_row(TABLE* table, bool is_transactional,
1185
                       const uchar *new_data);
1186
  int binlog_delete_row(TABLE* table, bool is_transactional,
1187
                        const uchar *old_data);
1188
  int binlog_update_row(TABLE* table, bool is_transactional,
1189
                        const uchar *old_data, const uchar *new_data);
1190
1191
  void set_server_id(uint32 sid) { server_id = sid; }
1192
1193
  /*
1194
    Member functions to handle pending event for row-level logging.
1195
  */
1196
  template <class RowsEventT> Rows_log_event*
1197
    binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
1198
                                      size_t needed,
1199
                                      bool is_transactional,
1200
				      RowsEventT* hint);
1201
  Rows_log_event* binlog_get_pending_rows_event() const;
1202
  void            binlog_set_pending_rows_event(Rows_log_event* ev);
1203
  int binlog_flush_pending_rows_event(bool stmt_end);
1204
1205
private:
1206
  uint binlog_table_maps; // Number of table maps currently in the binlog
1207
1208
  enum enum_binlog_flag {
1209
    BINLOG_FLAG_UNSAFE_STMT_PRINTED,
1210
    BINLOG_FLAG_COUNT
1211
  };
1212
1213
  /**
1214
     Flags with per-thread information regarding the status of the
1215
     binary log.
1216
   */
1217
  uint32 binlog_flags;
1218
public:
1219
  uint get_binlog_table_maps() const {
1220
    return binlog_table_maps;
1221
  }
1222
  void clear_binlog_table_maps() {
1223
    binlog_table_maps= 0;
1224
  }
1225
#endif /* MYSQL_CLIENT */
1226
1227
public:
1228
1229
  struct st_transactions {
1230
    SAVEPOINT *savepoints;
1231
    THD_TRANS all;			// Trans since BEGIN WORK
1232
    THD_TRANS stmt;			// Trans for current statement
1233
    bool on;                            // see ha_enable_transaction()
1234
    XID_STATE xid_state;
1235
    Rows_log_event *m_pending_rows_event;
1236
1237
    /*
1238
       Tables changed in transaction (that must be invalidated in query cache).
1239
       List contain only transactional tables, that not invalidated in query
1240
       cache (instead of full list of changed in transaction tables).
1241
    */
1242
    CHANGED_TABLE_LIST* changed_tables;
1243
    MEM_ROOT mem_root; // Transaction-life memory allocation pool
1244
    void cleanup()
1245
    {
1246
      changed_tables= 0;
1247
      savepoints= 0;
1248
      free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
1249
    }
1250
    st_transactions()
1251
    {
1252
      bzero((char*)this, sizeof(*this));
1253
      xid_state.xid.null();
1254
      init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
1255
    }
1256
  } transaction;
1257
  Field      *dup_field;
1258
  sigset_t signals;
1259
#ifdef SIGNAL_WITH_VIO_CLOSE
1260
  Vio* active_vio;
1261
#endif
1262
  /*
1263
    This is to track items changed during execution of a prepared
1264
    statement/stored procedure. It's created by
1265
    register_item_tree_change() in memory root of THD, and freed in
1266
    rollback_item_tree_changes(). For conventional execution it's always
1267
    empty.
1268
  */
1269
  Item_change_list change_list;
1270
1271
  /*
1272
    A permanent memory area of the statement. For conventional
1273
    execution, the parsed tree and execution runtime reside in the same
1274
    memory root. In this case stmt_arena points to THD. In case of
1275
    a prepared statement or a stored procedure statement, thd->mem_root
1276
    conventionally points to runtime memory, and thd->stmt_arena
1277
    points to the memory of the PS/SP, where the parsed tree of the
1278
    statement resides. Whenever you need to perform a permanent
1279
    transformation of a parsed tree, you should allocate new memory in
1280
    stmt_arena, to allow correct re-execution of PS/SP.
1281
    Note: in the parser, stmt_arena == thd, even for PS/SP.
1282
  */
1283
  Query_arena *stmt_arena;
1284
  /* Tells if LAST_INSERT_ID(#) was called for the current statement */
1285
  bool arg_of_last_insert_id_function;
1286
  /*
1287
    ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
1288
    insertion into an auto_increment column".
1289
  */
1290
  /*
1291
    This is the first autogenerated insert id which was *successfully*
1292
    inserted by the previous statement (exactly, if the previous statement
1293
    didn't successfully insert an autogenerated insert id, then it's the one
1294
    of the statement before, etc).
1295
    It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
1296
    It is returned by LAST_INSERT_ID().
1297
  */
1298
  ulonglong  first_successful_insert_id_in_prev_stmt;
1299
  /*
1300
    Variant of the above, used for storing in statement-based binlog. The
1301
    difference is that the one above can change as the execution of a stored
1302
    function progresses, while the one below is set once and then does not
1303
    change (which is the value which statement-based binlog needs).
1304
  */
1305
  ulonglong  first_successful_insert_id_in_prev_stmt_for_binlog;
1306
  /*
1307
    This is the first autogenerated insert id which was *successfully*
1308
    inserted by the current statement. It is maintained only to set
1309
    first_successful_insert_id_in_prev_stmt when statement ends.
1310
  */
1311
  ulonglong  first_successful_insert_id_in_cur_stmt;
1312
  /*
1313
    We follow this logic:
1314
    - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
1315
    first insert id successfully inserted by the previous stmt.
1316
    - as stmt makes progress, handler::insert_id_for_cur_row changes;
1317
    every time get_auto_increment() is called,
1318
    auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
1319
    reserved interval (if statement-based binlogging).
1320
    - at first successful insertion of an autogenerated value,
1321
    first_successful_insert_id_in_cur_stmt is set to
1322
    handler::insert_id_for_cur_row.
1323
    - when stmt goes to binlog,
1324
    auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
1325
    non-empty.
1326
    - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
1327
    first_successful_insert_id_in_cur_stmt.
1328
  */
1329
  /*
1330
    stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
1331
    LAST_INSERT_ID() is used by a statement.
1332
    If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
1333
    stored in the statement-based binlog.
1334
    This variable is CUMULATIVE along the execution of a stored function or
1335
    trigger: if one substatement sets it to 1 it will stay 1 until the
1336
    function/trigger ends, thus making sure that
1337
    first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
1338
    and is propagated to the caller for binlogging.
1339
  */
1340
  bool       stmt_depends_on_first_successful_insert_id_in_prev_stmt;
1341
  /*
1342
    List of auto_increment intervals reserved by the thread so far, for
1343
    storage in the statement-based binlog.
1344
    Note that its minimum is not first_successful_insert_id_in_cur_stmt:
1345
    assuming a table with an autoinc column, and this happens:
1346
    INSERT INTO ... VALUES(3);
1347
    SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
1348
    then the latter INSERT will insert no rows
1349
    (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
1350
    in the binlog is still needed; the list's minimum will contain 3.
1351
  */
1352
  Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
1353
  /* Used by replication and SET INSERT_ID */
1354
  Discrete_intervals_list auto_inc_intervals_forced;
1355
  /*
1356
    There is BUG#19630 where statement-based replication of stored
1357
    functions/triggers with two auto_increment columns breaks.
1358
    We however ensure that it works when there is 0 or 1 auto_increment
1359
    column; our rules are
1360
    a) on master, while executing a top statement involving substatements,
1361
    first top- or sub- statement to generate auto_increment values wins the
1362
    exclusive right to see its values be written to binlog (the write
1363
    will be done by the statement or its caller), and the losers won't see
1364
    their values be written to binlog.
1365
    b) on slave, while replicating a top statement involving substatements,
1366
    first top- or sub- statement to need to read auto_increment values from
1367
    the master's binlog wins the exclusive right to read them (so the losers
1368
    won't read their values from binlog but instead generate on their own).
1369
    a) implies that we mustn't backup/restore
1370
    auto_inc_intervals_in_cur_stmt_for_binlog.
1371
    b) implies that we mustn't backup/restore auto_inc_intervals_forced.
1372
1373
    If there are more than 1 auto_increment columns, then intervals for
1374
    different columns may mix into the
1375
    auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
1376
    but there is no point in preventing this mixing by preventing intervals
1377
    from the secondly inserted column to come into the list, as such
1378
    prevention would be wrong too.
1379
    What will happen in the case of
1380
    INSERT INTO t1 (auto_inc) VALUES(NULL);
1381
    where t1 has a trigger which inserts into an auto_inc column of t2, is
1382
    that in binlog we'll store the interval of t1 and the interval of t2 (when
1383
    we store intervals, soon), then in slave, t1 will use both intervals, t2
1384
    will use none; if t1 inserts the same number of rows as on master,
1385
    normally the 2nd interval will not be used by t1, which is fine. t2's
1386
    values will be wrong if t2's internal auto_increment counter is different
1387
    from what it was on master (which is likely). In 5.1, in mixed binlogging
1388
    mode, row-based binlogging is used for such cases where two
1389
    auto_increment columns are inserted.
1390
  */
1391
  inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)
1392
  {
1393
    if (first_successful_insert_id_in_cur_stmt == 0)
1394
      first_successful_insert_id_in_cur_stmt= id_arg;
1395
  }
1396
  inline ulonglong read_first_successful_insert_id_in_prev_stmt(void)
1397
  {
1398
    if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt)
1399
    {
1400
      /* It's the first time we read it */
1401
      first_successful_insert_id_in_prev_stmt_for_binlog=
1402
        first_successful_insert_id_in_prev_stmt;
1403
      stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1;
1404
    }
1405
    return first_successful_insert_id_in_prev_stmt;
1406
  }
1407
  /*
1408
    Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
1409
    (mysqlbinlog). We'll soon add a variant which can take many intervals in
1410
    argument.
1411
  */
1412
  inline void force_one_auto_inc_interval(ulonglong next_id)
1413
  {
1414
    auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
1415
    auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0);
1416
  }
1417
1418
  ulonglong  limit_found_rows;
1419
  ulonglong  options;           /* Bitmap of states */
1420
  longlong   row_count_func;    /* For the ROW_COUNT() function */
1421
  ha_rows    cuted_fields;
1422
1423
  /*
1424
    number of rows we actually sent to the client, including "synthetic"
1425
    rows in ROLLUP etc.
1426
  */
1427
  ha_rows    sent_row_count;
1428
1429
  /*
1430
    number of rows we read, sent or not, including in create_sort_index()
1431
  */
1432
  ha_rows    examined_row_count;
1433
1434
  /*
1435
    The set of those tables whose fields are referenced in all subqueries
1436
    of the query.
1437
    TODO: possibly this it is incorrect to have used tables in THD because
1438
    with more than one subquery, it is not clear what does the field mean.
1439
  */
1440
  table_map  used_tables;
1441
  USER_CONN *user_connect;
1442
  CHARSET_INFO *db_charset;
1443
  /*
1444
    FIXME: this, and some other variables like 'count_cuted_fields'
1445
    maybe should be statement/cursor local, that is, moved to Statement
1446
    class. With current implementation warnings produced in each prepared
1447
    statement/cursor settle here.
1448
  */
1449
  List	     <MYSQL_ERROR> warn_list;
1450
  uint	     warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END];
1451
  uint	     total_warn_count;
1452
  Diagnostics_area main_da;
1453
1454
  /*
1455
    Id of current query. Statement can be reused to execute several queries
1456
    query_id is global in context of the whole MySQL server.
1457
    ID is automatically generated from mutex-protected counter.
1458
    It's used in handler code for various purposes: to check which columns
1459
    from table are necessary for this select, to check if it's necessary to
1460
    update auto-updatable fields (like auto_increment and timestamp).
1461
  */
1462
  query_id_t query_id, warn_id;
1463
  ulong      col_access;
1464
1465
#ifdef ERROR_INJECT_SUPPORT
1466
  ulong      error_inject_value;
1467
#endif
1468
  /* Statement id is thread-wide. This counter is used to generate ids */
1469
  ulong      statement_id_counter;
1470
  ulong	     rand_saved_seed1, rand_saved_seed2;
1471
  /*
1472
    Row counter, mainly for errors and warnings. Not increased in
1473
    create_sort_index(); may differ from examined_row_count.
1474
  */
1475
  ulong      row_count;
1476
  pthread_t  real_id;                           /* For debugging */
1477
  my_thread_id  thread_id;
1478
  uint	     tmp_table, global_read_lock;
1479
  uint	     server_status,open_options;
1480
  enum enum_thread_type system_thread;
1481
  uint       select_number;             //number of select (used for EXPLAIN)
1482
  /* variables.transaction_isolation is reset to this after each commit */
1483
  enum_tx_isolation session_tx_isolation;
1484
  enum_check_fields count_cuted_fields;
1485
1486
  DYNAMIC_ARRAY user_var_events;        /* For user variables replication */
1487
  MEM_ROOT      *user_var_events_alloc; /* Allocate above array elements here */
1488
1489
  enum killed_state
1490
  {
1491
    NOT_KILLED=0,
1492
    KILL_BAD_DATA=1,
1493
    KILL_CONNECTION=ER_SERVER_SHUTDOWN,
1494
    KILL_QUERY=ER_QUERY_INTERRUPTED,
1495
    KILLED_NO_VALUE      /* means neither of the states */
1496
  };
1497
  killed_state volatile killed;
1498
1499
  /* scramble - random string sent to client on handshake */
1500
  char	     scramble[SCRAMBLE_LENGTH+1];
1501
1502
  bool       slave_thread, one_shot_set;
1503
  /* tells if current statement should binlog row-based(1) or stmt-based(0) */
1504
  bool       current_stmt_binlog_row_based;
1505
  bool	     some_tables_deleted;
1506
  bool       last_cuted_field;
1507
  bool	     no_errors, password;
1508
  /**
1509
    Set to TRUE if execution of the current compound statement
1510
    can not continue. In particular, disables activation of
1511
    CONTINUE or EXIT handlers of stored routines.
1512
    Reset in the end of processing of the current user request, in
1513
    @see mysql_reset_thd_for_next_command().
1514
  */
1515
  bool is_fatal_error;
1516
  /**
1517
    Set by a storage engine to request the entire
1518
    transaction (that possibly spans multiple engines) to
1519
    rollback. Reset in ha_rollback.
1520
  */
1521
  bool       transaction_rollback_request;
1522
  /**
1523
    TRUE if we are in a sub-statement and the current error can
1524
    not be safely recovered until we left the sub-statement mode.
1525
    In particular, disables activation of CONTINUE and EXIT
1526
    handlers inside sub-statements. E.g. if it is a deadlock
1527
    error and requires a transaction-wide rollback, this flag is
1528
    raised (traditionally, MySQL first has to close all the reads
1529
    via @see handler::ha_index_or_rnd_end() and only then perform
1530
    the rollback).
1531
    Reset to FALSE when we leave the sub-statement mode.
1532
  */
1533
  bool       is_fatal_sub_stmt_error;
1534
  bool	     query_start_used, rand_used, time_zone_used;
1535
  /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
1536
  bool       substitute_null_with_insert_id;
1537
  bool	     in_lock_tables;
1538
  /**
1539
    True if a slave error. Causes the slave to stop. Not the same
1540
    as the statement execution error (is_error()), since
1541
    a statement may be expected to return an error, e.g. because
1542
    it returned an error on master, and this is OK on the slave.
1543
  */
1544
  bool       is_slave_error;
1545
  bool       bootstrap, cleanup_done;
1546
  
1547
  /**  is set if some thread specific value(s) used in a statement. */
1548
  bool       thread_specific_used;
1549
  bool	     charset_is_system_charset, charset_is_collation_connection;
1550
  bool       charset_is_character_set_filesystem;
1551
  bool       enable_slow_log;   /* enable slow log for current statement */
1552
  bool	     abort_on_warning;
1553
  bool 	     got_warning;       /* Set on call to push_warning() */
1554
  bool	     no_warnings_for_error; /* no warnings on call to my_error() */
1555
  /* set during loop of derived table processing */
1556
  bool       derived_tables_processing;
1557
  my_bool    tablespace_op;	/* This is TRUE in DISCARD/IMPORT TABLESPACE */
1558
1559
  /*
1560
    If we do a purge of binary logs, log index info of the threads
1561
    that are currently reading it needs to be adjusted. To do that
1562
    each thread that is using LOG_INFO needs to adjust the pointer to it
1563
  */
1564
  LOG_INFO*  current_linfo;
1565
  NET*       slave_net;			// network connection from slave -> m.
1566
  /* Used by the sys_var class to store temporary values */
1567
  union
1568
  {
1569
    my_bool   my_bool_value;
1570
    long      long_value;
1571
    ulong     ulong_value;
1572
    ulonglong ulonglong_value;
1573
  } sys_var_tmp;
1574
  
1575
  struct {
1576
    /* 
1577
      If true, mysql_bin_log::write(Log_event) call will not write events to 
1578
      binlog, and maintain 2 below variables instead (use
1579
      mysql_bin_log.start_union_events to turn this on)
1580
    */
1581
    bool do_union;
1582
    /*
1583
      If TRUE, at least one mysql_bin_log::write(Log_event) call has been
1584
      made after last mysql_bin_log.start_union_events() call.
1585
    */
1586
    bool unioned_events;
1587
    /*
1588
      If TRUE, at least one mysql_bin_log::write(Log_event e), where 
1589
      e.cache_stmt == TRUE call has been made after last 
1590
      mysql_bin_log.start_union_events() call.
1591
    */
1592
    bool unioned_events_trans;
1593
    
1594
    /* 
1595
      'queries' (actually SP statements) that run under inside this binlog
1596
      union have thd->query_id >= first_query_id.
1597
    */
1598
    query_id_t first_query_id;
1599
  } binlog_evt_union;
1600
1601
  /**
1602
    Character input stream consumed by the lexical analyser,
1603
    used during parsing.
1604
    Note that since the parser is not re-entrant, we keep only one input
1605
    stream here. This member is valid only when executing code during parsing,
1606
    and may point to invalid memory after that.
1607
  */
1608
  Lex_input_stream *m_lip;
1609
1610
  /*
1611
    @todo The following is a work around for online backup and the DDL blocker.
1612
          It should be removed when the generalized solution is in place.
1613
          This is needed to ensure the restore (which uses DDL) is not blocked
1614
          when the DDL blocker is engaged.
1615
  */
1616
  my_bool DDL_exception; // Allow some DDL if there is an exception
1617
1618
  THD();
1619
  ~THD();
1620
1621
  void init(void);
1622
  /*
1623
    Initialize memory roots necessary for query processing and (!)
1624
    pre-allocate memory for it. We can't do that in THD constructor because
1625
    there are use cases (acl_init, watcher threads,
1626
    killing mysqld) where it's vital to not allocate excessive and not used
1627
    memory. Note, that we still don't return error from init_for_queries():
1628
    if preallocation fails, we should notice that at the first call to
1629
    alloc_root. 
1630
  */
1631
  void init_for_queries();
1632
  void change_user(void);
1633
  void cleanup(void);
1634
  void cleanup_after_query();
1635
  bool store_globals();
1636
#ifdef SIGNAL_WITH_VIO_CLOSE
1637
  inline void set_active_vio(Vio* vio)
1638
  {
1639
    pthread_mutex_lock(&LOCK_delete);
1640
    active_vio = vio;
1641
    pthread_mutex_unlock(&LOCK_delete);
1642
  }
1643
  inline void clear_active_vio()
1644
  {
1645
    pthread_mutex_lock(&LOCK_delete);
1646
    active_vio = 0;
1647
    pthread_mutex_unlock(&LOCK_delete);
1648
  }
1649
  void close_active_vio();
1650
#endif
1651
  void awake(THD::killed_state state_to_set);
1652
1653
#ifndef MYSQL_CLIENT
1654
  enum enum_binlog_query_type {
1655
    /*
1656
      The query can be logged row-based or statement-based
1657
    */
1658
    ROW_QUERY_TYPE,
1659
    
1660
    /*
1661
      The query has to be logged statement-based
1662
    */
1663
    STMT_QUERY_TYPE,
1664
    
1665
    /*
1666
      The query represents a change to a table in the "mysql"
1667
      database and is currently mapped to ROW_QUERY_TYPE.
1668
    */
1669
    MYSQL_QUERY_TYPE,
1670
    QUERY_TYPE_COUNT
1671
  };
1672
  
1673
  int binlog_query(enum_binlog_query_type qtype,
1674
                   char const *query, ulong query_len,
1675
                   bool is_trans, bool suppress_use,
1676
                   THD::killed_state killed_err_arg= THD::KILLED_NO_VALUE);
1677
#endif
1678
1679
  /*
1680
    For enter_cond() / exit_cond() to work the mutex must be got before
1681
    enter_cond(); this mutex is then released by exit_cond().
1682
    Usage must be: lock mutex; enter_cond(); your code; exit_cond().
1683
  */
1684
  inline const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex,
1685
			  const char* msg)
1686
  {
1687
    const char* old_msg = get_proc_info();
1688
    safe_mutex_assert_owner(mutex);
1689
    mysys_var->current_mutex = mutex;
1690
    mysys_var->current_cond = cond;
1691
    thd_proc_info(this, msg);
1692
    return old_msg;
1693
  }
1694
  inline void exit_cond(const char* old_msg)
1695
  {
1696
    /*
1697
      Putting the mutex unlock in exit_cond() ensures that
1698
      mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
1699
      locked (if that would not be the case, you'll get a deadlock if someone
1700
      does a THD::awake() on you).
1701
    */
1702
    pthread_mutex_unlock(mysys_var->current_mutex);
1703
    pthread_mutex_lock(&mysys_var->mutex);
1704
    mysys_var->current_mutex = 0;
1705
    mysys_var->current_cond = 0;
1706
    thd_proc_info(this, old_msg);
1707
    pthread_mutex_unlock(&mysys_var->mutex);
1708
  }
1709
  inline time_t query_start() { query_start_used=1; return start_time; }
1710
  inline void set_time()
1711
  {
1712
    if (user_time)
1713
    {
1714
      start_time= user_time;
1715
      start_utime= utime_after_lock= my_micro_time();
1716
    }
1717
    else
1718
      start_utime= utime_after_lock= my_micro_time_and_time(&start_time);
1719
  }
1720
  inline void	set_current_time()    { start_time= my_time(MY_WME); }
1721
  inline void	set_time(time_t t)
1722
  {
1723
    start_time= user_time= t;
1724
    start_utime= utime_after_lock= my_micro_time();
1725
  }
1726
  void set_time_after_lock()  { utime_after_lock= my_micro_time(); }
1727
  ulonglong current_utime()  { return my_micro_time(); }
1728
  inline ulonglong found_rows(void)
1729
  {
1730
    return limit_found_rows;
1731
  }
1732
  inline bool active_transaction()
1733
  {
1734
    return server_status & SERVER_STATUS_IN_TRANS;
1735
  }
1736
  inline bool fill_derived_tables()
1737
  {
1738
    return !lex->only_view_structure();
1739
  }
1740
  inline void* trans_alloc(unsigned int size)
1741
  {
1742
    return alloc_root(&transaction.mem_root,size);
1743
  }
1744
1745
  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
1746
                              const char* str, uint length,
1747
                              bool allocate_lex_string);
1748
1749
  bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
1750
		      const char *from, uint from_length,
1751
		      CHARSET_INFO *from_cs);
1752
1753
  bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs);
1754
1755
  void add_changed_table(TABLE *table);
1756
  void add_changed_table(const char *key, long key_length);
1757
  CHANGED_TABLE_LIST * changed_table_dup(const char *key, long key_length);
1758
  int send_explain_fields(select_result *result);
1759
  /**
1760
    Clear the current error, if any.
1761
    We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
1762
    assume this is never called if the fatal error is set.
1763
    @todo: To silence an error, one should use Internal_error_handler
1764
    mechanism. In future this function will be removed.
1765
  */
1766
  inline void clear_error()
1767
  {
1768
    DBUG_ENTER("clear_error");
1769
    if (main_da.is_error())
1770
      main_da.reset_diagnostics_area();
1771
    is_slave_error= 0;
1772
    DBUG_VOID_RETURN;
1773
  }
1774
  inline bool vio_ok() const { return net.vio != 0; }
1775
  /** Return FALSE if connection to client is broken. */
1776
  bool vio_is_connected();
1777
  /**
1778
    Mark the current error as fatal. Warning: this does not
1779
    set any error, it sets a property of the error, so must be
1780
    followed or prefixed with my_error().
1781
  */
1782
  inline void fatal_error()
1783
  {
1784
    DBUG_ASSERT(main_da.is_error());
1785
    is_fatal_error= 1;
1786
    DBUG_PRINT("error",("Fatal error set"));
1787
  }
1788
  /**
1789
    TRUE if there is an error in the error stack.
1790
1791
    Please use this method instead of direct access to
1792
    net.report_error.
1793
1794
    If TRUE, the current (sub)-statement should be aborted.
1795
    The main difference between this member and is_fatal_error
1796
    is that a fatal error can not be handled by a stored
1797
    procedure continue handler, whereas a normal error can.
1798
1799
    To raise this flag, use my_error().
1800
  */
1801
  inline bool is_error() const { return main_da.is_error(); }
1802
  inline CHARSET_INFO *charset() { return variables.character_set_client; }
1803
  void update_charset();
1804
1805
  void change_item_tree(Item **place, Item *new_value)
1806
  {
1807
    /* TODO: check for OOM condition here */
1808
    if (!stmt_arena->is_conventional())
1809
      nocheck_register_item_tree_change(place, *place, mem_root);
1810
    *place= new_value;
1811
  }
1812
  void nocheck_register_item_tree_change(Item **place, Item *old_value,
1813
                                         MEM_ROOT *runtime_memroot);
1814
  void rollback_item_tree_changes();
1815
1816
  /*
1817
    Cleanup statement parse state (parse tree, lex) and execution
1818
    state after execution of a non-prepared SQL statement.
1819
  */
1820
  void end_statement();
1821
  inline int killed_errno() const
1822
  {
1823
    killed_state killed_val; /* to cache the volatile 'killed' */
1824
    return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0;
1825
  }
1826
  inline void send_kill_message() const
1827
  {
1828
    int err= killed_errno();
1829
    if (err)
1830
      my_message(err, ER(err), MYF(0));
1831
  }
1832
  /* return TRUE if we will abort query if we make a warning now */
1833
  inline bool really_abort_on_warning()
1834
  {
1835
    return (abort_on_warning);
1836
  }
1837
  void set_status_var_init();
1838
  bool is_context_analysis_only()
1839
    { return lex->view_prepare_mode; }
1840
  void reset_n_backup_open_tables_state(Open_tables_state *backup);
1841
  void restore_backup_open_tables_state(Open_tables_state *backup);
1842
  void restore_sub_statement_state(Sub_statement_state *backup);
1843
  void set_n_backup_active_arena(Query_arena *set, Query_arena *backup);
1844
  void restore_active_arena(Query_arena *set, Query_arena *backup);
1845
1846
  inline void set_current_stmt_binlog_row_based_if_mixed()
1847
  {
1848
    /*
1849
      If in a stored/function trigger, the caller should already have done the
1850
      change. We test in_sub_stmt to prevent introducing bugs where people
1851
      wouldn't ensure that, and would switch to row-based mode in the middle
1852
      of executing a stored function/trigger (which is too late, see also
1853
      reset_current_stmt_binlog_row_based()); this condition will make their
1854
      tests fail and so force them to propagate the
1855
      lex->binlog_row_based_if_mixed upwards to the caller.
1856
    */
1857
    if ((variables.binlog_format == BINLOG_FORMAT_MIXED) &&
1858
        (in_sub_stmt == 0))
1859
      current_stmt_binlog_row_based= TRUE;
1860
  }
1861
  inline void set_current_stmt_binlog_row_based()
1862
  {
1863
    current_stmt_binlog_row_based= TRUE;
1864
  }
1865
  inline void clear_current_stmt_binlog_row_based()
1866
  {
1867
    current_stmt_binlog_row_based= FALSE;
1868
  }
1869
  inline void reset_current_stmt_binlog_row_based()
1870
  {
1871
    /*
1872
      If there are temporary tables, don't reset back to
1873
      statement-based. Indeed it could be that:
1874
      CREATE TEMPORARY TABLE t SELECT UUID(); # row-based
1875
      # and row-based does not store updates to temp tables
1876
      # in the binlog.
1877
      INSERT INTO u SELECT * FROM t; # stmt-based
1878
      and then the INSERT will fail as data inserted into t was not logged.
1879
      So we continue with row-based until the temp table is dropped.
1880
      If we are in a stored function or trigger, we mustn't reset in the
1881
      middle of its execution (as the binary logging way of a stored function
1882
      or trigger is decided when it starts executing, depending for example on
1883
      the caller (for a stored function: if caller is SELECT or
1884
      INSERT/UPDATE/DELETE...).
1885
1886
      Don't reset binlog format for NDB binlog injector thread.
1887
    */
1888
    if ((temporary_tables == NULL) && (in_sub_stmt == 0) &&
1889
        (system_thread != SYSTEM_THREAD_NDBCLUSTER_BINLOG))
1890
    {
1891
      current_stmt_binlog_row_based= 
1892
        test(variables.binlog_format == BINLOG_FORMAT_ROW);
1893
    }
1894
  }
1895
1896
  /**
1897
    Set the current database; use deep copy of C-string.
1898
1899
    @param new_db     a pointer to the new database name.
1900
    @param new_db_len length of the new database name.
1901
1902
    Initialize the current database from a NULL-terminated string with
1903
    length. If we run out of memory, we free the current database and
1904
    return TRUE.  This way the user will notice the error as there will be
1905
    no current database selected (in addition to the error message set by
1906
    malloc).
1907
1908
    @note This operation just sets {db, db_length}. Switching the current
1909
    database usually involves other actions, like switching other database
1910
    attributes including security context. In the future, this operation
1911
    will be made private and more convenient interface will be provided.
1912
1913
    @return Operation status
1914
      @retval FALSE Success
1915
      @retval TRUE  Out-of-memory error
1916
  */
1917
  bool set_db(const char *new_db, size_t new_db_len)
1918
  {
1919
    /* Do not reallocate memory if current chunk is big enough. */
1920
    if (db && new_db && db_length >= new_db_len)
1921
      memcpy(db, new_db, new_db_len+1);
1922
    else
1923
    {
1924
      x_free(db);
1925
      if (new_db)
1926
        db= my_strndup(new_db, new_db_len, MYF(MY_WME | ME_FATALERROR));
1927
      else
1928
        db= NULL;
1929
    }
1930
    db_length= db ? new_db_len : 0;
1931
    return new_db && !db;
1932
  }
1933
1934
  /**
1935
    Set the current database; use shallow copy of C-string.
1936
1937
    @param new_db     a pointer to the new database name.
1938
    @param new_db_len length of the new database name.
1939
1940
    @note This operation just sets {db, db_length}. Switching the current
1941
    database usually involves other actions, like switching other database
1942
    attributes including security context. In the future, this operation
1943
    will be made private and more convenient interface will be provided.
1944
  */
1945
  void reset_db(char *new_db, size_t new_db_len)
1946
  {
1947
    db= new_db;
1948
    db_length= new_db_len;
1949
  }
1950
  /*
1951
    Copy the current database to the argument. Use the current arena to
1952
    allocate memory for a deep copy: current database may be freed after
1953
    a statement is parsed but before it's executed.
1954
  */
1955
  bool copy_db_to(char **p_db, size_t *p_db_length)
1956
  {
1957
    if (db == NULL)
1958
    {
1959
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
1960
      return TRUE;
1961
    }
1962
    *p_db= strmake(db, db_length);
1963
    *p_db_length= db_length;
1964
    return FALSE;
1965
  }
1966
  thd_scheduler scheduler;
1967
1968
public:
1969
  /**
1970
    Add an internal error handler to the thread execution context.
1971
    @param handler the exception handler to add
1972
  */
1973
  void push_internal_handler(Internal_error_handler *handler);
1974
1975
  /**
1976
    Handle an error condition.
1977
    @param sql_errno the error number
1978
    @param level the error level
1979
    @return true if the error is handled
1980
  */
1981
  virtual bool handle_error(uint sql_errno, const char *message,
1982
                            MYSQL_ERROR::enum_warning_level level);
1983
1984
  /**
1985
    Remove the error handler last pushed.
1986
  */
1987
  void pop_internal_handler();
1988
1989
private:
1990
  /** The current internal error handler for this thread, or NULL. */
1991
  Internal_error_handler *m_internal_handler;
1992
  /**
1993
    The lex to hold the parsed tree of conventional (non-prepared) queries.
1994
    Whereas for prepared and stored procedure statements we use an own lex
1995
    instance for each new query, for conventional statements we reuse
1996
    the same lex. (@see mysql_parse for details).
1997
  */
1998
  LEX main_lex;
1999
  /**
2000
    This memory root is used for two purposes:
2001
    - for conventional queries, to allocate structures stored in main_lex
2002
    during parsing, and allocate runtime data (execution plan, etc.)
2003
    during execution.
2004
    - for prepared queries, only to allocate runtime data. The parsed
2005
    tree itself is reused between executions and thus is stored elsewhere.
2006
  */
2007
  MEM_ROOT main_mem_root;
2008
};
2009
2010
2011
/** A short cut for thd->main_da.set_ok_status(). */
2012
2013
inline void
2014
my_ok(THD *thd, ha_rows affected_rows= 0, ulonglong id= 0,
2015
        const char *message= NULL)
2016
{
2017
  thd->main_da.set_ok_status(thd, affected_rows, id, message);
2018
}
2019
2020
2021
/** A short cut for thd->main_da.set_eof_status(). */
2022
2023
inline void
2024
my_eof(THD *thd)
2025
{
2026
  thd->main_da.set_eof_status(thd);
2027
}
2028
2029
#define tmp_disable_binlog(A)       \
2030
  {ulonglong tmp_disable_binlog__save_options= (A)->options; \
2031
  (A)->options&= ~OPTION_BIN_LOG
2032
2033
#define reenable_binlog(A)   (A)->options= tmp_disable_binlog__save_options;}
2034
2035
2036
/*
2037
  Used to hold information about file and file structure in exchange
2038
  via non-DB file (...INTO OUTFILE..., ...LOAD DATA...)
2039
  XXX: We never call destructor for objects of this class.
2040
*/
2041
2042
class sql_exchange :public Sql_alloc
2043
{
2044
public:
2045
  enum enum_filetype filetype; /* load XML, Added by Arnold & Erik */ 
2046
  char *file_name;
2047
  String *field_term,*enclosed,*line_term,*line_start,*escaped;
2048
  bool opt_enclosed;
2049
  bool dumpfile;
2050
  ulong skip_lines;
2051
  CHARSET_INFO *cs;
2052
  sql_exchange(char *name, bool dumpfile_flag,
2053
               enum_filetype filetype_arg= FILETYPE_CSV);
2054
};
2055
2056
#include "log_event.h"
2057
2058
/*
2059
  This is used to get result from a select
2060
*/
2061
2062
class JOIN;
2063
2064
class select_result :public Sql_alloc {
2065
protected:
2066
  THD *thd;
2067
  SELECT_LEX_UNIT *unit;
2068
public:
2069
  select_result();
2070
  virtual ~select_result() {};
2071
  virtual int prepare(List<Item> &list, SELECT_LEX_UNIT *u)
2072
  {
2073
    unit= u;
2074
    return 0;
2075
  }
2076
  virtual int prepare2(void) { return 0; }
2077
  /*
2078
    Because of peculiarities of prepared statements protocol
2079
    we need to know number of columns in the result set (if
2080
    there is a result set) apart from sending columns metadata.
2081
  */
2082
  virtual uint field_count(List<Item> &fields) const
2083
  { return fields.elements; }
2084
  virtual bool send_fields(List<Item> &list, uint flags)=0;
2085
  virtual bool send_data(List<Item> &items)=0;
2086
  virtual bool initialize_tables (JOIN *join=0) { return 0; }
2087
  virtual void send_error(uint errcode,const char *err);
2088
  virtual bool send_eof()=0;
2089
  /**
2090
    Check if this query returns a result set and therefore is allowed in
2091
    cursors and set an error message if it is not the case.
2092
2093
    @retval FALSE     success
2094
    @retval TRUE      error, an error message is set
2095
  */
2096
  virtual bool check_simple_select() const;
2097
  virtual void abort() {}
2098
  /*
2099
    Cleanup instance of this class for next execution of a prepared
2100
    statement/stored procedure.
2101
  */
2102
  virtual void cleanup();
2103
  void set_thd(THD *thd_arg) { thd= thd_arg; }
2104
  void begin_dataset() {}
2105
};
2106
2107
2108
/*
2109
  Base class for select_result descendands which intercept and
2110
  transform result set rows. As the rows are not sent to the client,
2111
  sending of result set metadata should be suppressed as well.
2112
*/
2113
2114
class select_result_interceptor: public select_result
2115
{
2116
public:
2117
  select_result_interceptor() {}              /* Remove gcc warning */
2118
  uint field_count(List<Item> &fields) const { return 0; }
2119
  bool send_fields(List<Item> &fields, uint flag) { return FALSE; }
2120
};
2121
2122
2123
class select_send :public select_result {
2124
  /**
2125
    True if we have sent result set metadata to the client.
2126
    In this case the client always expects us to end the result
2127
    set with an eof or error packet
2128
  */
2129
  bool is_result_set_started;
2130
public:
2131
  select_send() :is_result_set_started(FALSE) {}
2132
  bool send_fields(List<Item> &list, uint flags);
2133
  bool send_data(List<Item> &items);
2134
  bool send_eof();
2135
  virtual bool check_simple_select() const { return FALSE; }
2136
  void abort();
2137
  virtual void cleanup();
2138
};
2139
2140
2141
class select_to_file :public select_result_interceptor {
2142
protected:
2143
  sql_exchange *exchange;
2144
  File file;
2145
  IO_CACHE cache;
2146
  ha_rows row_count;
2147
  char path[FN_REFLEN];
2148
2149
public:
2150
  select_to_file(sql_exchange *ex) :exchange(ex), file(-1),row_count(0L)
2151
  { path[0]=0; }
2152
  ~select_to_file();
2153
  void send_error(uint errcode,const char *err);
2154
  bool send_eof();
2155
  void cleanup();
2156
};
2157
2158
2159
#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
2160
2161
2162
/*
2163
 List of all possible characters of a numeric value text representation.
2164
*/
2165
#define NUMERIC_CHARS ".0123456789e+-"
2166
2167
2168
class select_export :public select_to_file {
2169
  uint field_term_length;
2170
  int field_sep_char,escape_char,line_sep_char;
2171
  int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT
2172
  /*
2173
    The is_ambiguous_field_sep field is true if a value of the field_sep_char
2174
    field is one of the 'n', 't', 'r' etc characters
2175
    (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value).
2176
  */
2177
  bool is_ambiguous_field_sep;
2178
  /*
2179
     The is_ambiguous_field_term is true if field_sep_char contains the first
2180
     char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can
2181
     contain this character.
2182
  */
2183
  bool is_ambiguous_field_term;
2184
  /*
2185
    The is_unsafe_field_sep field is true if a value of the field_sep_char
2186
    field is one of the '0'..'9', '+', '-', '.' and 'e' characters
2187
    (see the NUMERIC_CHARS constant value).
2188
  */
2189
  bool is_unsafe_field_sep;
2190
  bool fixed_row_size;
2191
public:
2192
  select_export(sql_exchange *ex) :select_to_file(ex) {}
2193
  ~select_export();
2194
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2195
  bool send_data(List<Item> &items);
2196
};
2197
2198
2199
class select_dump :public select_to_file {
2200
public:
2201
  select_dump(sql_exchange *ex) :select_to_file(ex) {}
2202
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2203
  bool send_data(List<Item> &items);
2204
};
2205
2206
2207
class select_insert :public select_result_interceptor {
2208
 public:
2209
  TABLE_LIST *table_list;
2210
  TABLE *table;
2211
  List<Item> *fields;
2212
  ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not
2213
  COPY_INFO info;
2214
  bool insert_into_view;
2215
  select_insert(TABLE_LIST *table_list_par,
2216
		TABLE *table_par, List<Item> *fields_par,
2217
		List<Item> *update_fields, List<Item> *update_values,
2218
		enum_duplicates duplic, bool ignore);
2219
  ~select_insert();
2220
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2221
  virtual int prepare2(void);
2222
  bool send_data(List<Item> &items);
2223
  virtual void store_values(List<Item> &values);
2224
  virtual bool can_rollback_data() { return 0; }
2225
  void send_error(uint errcode,const char *err);
2226
  bool send_eof();
2227
  void abort();
2228
  /* not implemented: select_insert is never re-used in prepared statements */
2229
  void cleanup();
2230
};
2231
2232
2233
class select_create: public select_insert {
2234
  ORDER *group;
2235
  TABLE_LIST *create_table;
2236
  HA_CREATE_INFO *create_info;
2237
  TABLE_LIST *select_tables;
2238
  Alter_info *alter_info;
2239
  Field **field;
2240
  /* lock data for tmp table */
2241
  MYSQL_LOCK *m_lock;
2242
  /* m_lock or thd->extra_lock */
2243
  MYSQL_LOCK **m_plock;
2244
public:
2245
  select_create (TABLE_LIST *table_arg,
2246
		 HA_CREATE_INFO *create_info_par,
2247
                 Alter_info *alter_info_arg,
2248
		 List<Item> &select_fields,enum_duplicates duplic, bool ignore,
2249
                 TABLE_LIST *select_tables_arg)
2250
    :select_insert (NULL, NULL, &select_fields, 0, 0, duplic, ignore),
2251
    create_table(table_arg),
2252
    create_info(create_info_par),
2253
    select_tables(select_tables_arg),
2254
    alter_info(alter_info_arg),
2255
    m_plock(NULL)
2256
    {}
2257
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2258
2259
  void binlog_show_create_table(TABLE **tables, uint count);
2260
  void store_values(List<Item> &values);
2261
  void send_error(uint errcode,const char *err);
2262
  bool send_eof();
2263
  void abort();
2264
  virtual bool can_rollback_data() { return 1; }
2265
2266
  // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted.
2267
  const THD *get_thd(void) { return thd; }
2268
  const HA_CREATE_INFO *get_create_info() { return create_info; };
2269
  int prepare2(void) { return 0; }
2270
};
2271
2272
#include <myisam.h>
2273
2274
/* 
2275
  Param to create temporary tables when doing SELECT:s 
2276
  NOTE
2277
    This structure is copied using memcpy as a part of JOIN.
2278
*/
2279
2280
class TMP_TABLE_PARAM :public Sql_alloc
2281
{
2282
private:
2283
  /* Prevent use of these (not safe because of lists and copy_field) */
2284
  TMP_TABLE_PARAM(const TMP_TABLE_PARAM &);
2285
  void operator=(TMP_TABLE_PARAM &);
2286
2287
public:
2288
  List<Item> copy_funcs;
2289
  List<Item> save_copy_funcs;
2290
  Copy_field *copy_field, *copy_field_end;
2291
  Copy_field *save_copy_field, *save_copy_field_end;
2292
  uchar	    *group_buff;
2293
  Item	    **items_to_copy;			/* Fields in tmp table */
2294
  MI_COLUMNDEF *recinfo,*start_recinfo;
2295
  KEY *keyinfo;
2296
  ha_rows end_write_records;
2297
  uint	field_count,sum_func_count,func_count;
2298
  uint  hidden_field_count;
2299
  uint	group_parts,group_length,group_null_parts;
2300
  uint	quick_group;
2301
  bool  using_indirect_summary_function;
2302
  /* If >0 convert all blob fields to varchar(convert_blob_length) */
2303
  uint  convert_blob_length; 
2304
  CHARSET_INFO *table_charset; 
2305
  bool schema_table;
2306
  /*
2307
    True if GROUP BY and its aggregate functions are already computed
2308
    by a table access method (e.g. by loose index scan). In this case
2309
    query execution should not perform aggregation and should treat
2310
    aggregate functions as normal functions.
2311
  */
2312
  bool precomputed_group_by;
2313
  bool force_copy_fields;
2314
  /*
2315
    If TRUE, create_tmp_field called from create_tmp_table will convert
2316
    all BIT fields to 64-bit longs. This is a workaround the limitation
2317
    that MEMORY tables cannot index BIT columns.
2318
  */
2319
  bool bit_fields_as_long;
2320
2321
  TMP_TABLE_PARAM()
2322
    :copy_field(0), group_parts(0),
2323
     group_length(0), group_null_parts(0), convert_blob_length(0),
2324
     schema_table(0), precomputed_group_by(0), force_copy_fields(0),
2325
     bit_fields_as_long(0)
2326
  {}
2327
  ~TMP_TABLE_PARAM()
2328
  {
2329
    cleanup();
2330
  }
2331
  void init(void);
2332
  inline void cleanup(void)
2333
  {
2334
    if (copy_field)				/* Fix for Intel compiler */
2335
    {
2336
      delete [] copy_field;
2337
      save_copy_field= copy_field= 0;
2338
    }
2339
  }
2340
};
2341
2342
class select_union :public select_result_interceptor
2343
{
2344
  TMP_TABLE_PARAM tmp_table_param;
2345
public:
2346
  TABLE *table;
2347
2348
  select_union() :table(0) {}
2349
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2350
  bool send_data(List<Item> &items);
2351
  bool send_eof();
2352
  bool flush();
2353
  void cleanup();
2354
  bool create_result_table(THD *thd, List<Item> *column_types,
2355
                           bool is_distinct, ulonglong options,
2356
                           const char *alias, bool bit_fields_as_long);
2357
};
2358
2359
/* Base subselect interface class */
2360
class select_subselect :public select_result_interceptor
2361
{
2362
protected:
2363
  Item_subselect *item;
2364
public:
2365
  select_subselect(Item_subselect *item);
2366
  bool send_data(List<Item> &items)=0;
2367
  bool send_eof() { return 0; };
2368
};
2369
2370
/* Single value subselect interface class */
2371
class select_singlerow_subselect :public select_subselect
2372
{
2373
public:
2374
  select_singlerow_subselect(Item_subselect *item_arg)
2375
    :select_subselect(item_arg)
2376
  {}
2377
  bool send_data(List<Item> &items);
2378
};
2379
2380
/* used in independent ALL/ANY optimisation */
2381
class select_max_min_finder_subselect :public select_subselect
2382
{
2383
  Item_cache *cache;
2384
  bool (select_max_min_finder_subselect::*op)();
2385
  bool fmax;
2386
public:
2387
  select_max_min_finder_subselect(Item_subselect *item_arg, bool mx)
2388
    :select_subselect(item_arg), cache(0), fmax(mx)
2389
  {}
2390
  void cleanup();
2391
  bool send_data(List<Item> &items);
2392
  bool cmp_real();
2393
  bool cmp_int();
2394
  bool cmp_decimal();
2395
  bool cmp_str();
2396
};
2397
2398
/* EXISTS subselect interface class */
2399
class select_exists_subselect :public select_subselect
2400
{
2401
public:
2402
  select_exists_subselect(Item_subselect *item_arg)
2403
    :select_subselect(item_arg){}
2404
  bool send_data(List<Item> &items);
2405
};
2406
2407
/* Structs used when sorting */
2408
2409
typedef struct st_sort_field {
2410
  Field *field;				/* Field to sort */
2411
  Item	*item;				/* Item if not sorting fields */
2412
  uint	 length;			/* Length of sort field */
2413
  uint   suffix_length;                 /* Length suffix (0-4) */
2414
  Item_result result_type;		/* Type of item */
2415
  bool reverse;				/* if descending sort */
2416
  bool need_strxnfrm;			/* If we have to use strxnfrm() */
2417
} SORT_FIELD;
2418
2419
2420
typedef struct st_sort_buffer {
2421
  uint index;					/* 0 or 1 */
2422
  uint sort_orders;
2423
  uint change_pos;				/* If sort-fields changed */
2424
  char **buff;
2425
  SORT_FIELD *sortorder;
2426
} SORT_BUFFER;
2427
2428
/* Structure for db & table in sql_yacc */
2429
2430
class Table_ident :public Sql_alloc
2431
{
2432
public:
2433
  LEX_STRING db;
2434
  LEX_STRING table;
2435
  SELECT_LEX_UNIT *sel;
2436
  inline Table_ident(THD *thd, LEX_STRING db_arg, LEX_STRING table_arg,
2437
		     bool force)
2438
    :table(table_arg), sel((SELECT_LEX_UNIT *)0)
2439
  {
2440
    if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA))
2441
      db.str=0;
2442
    else
2443
      db= db_arg;
2444
  }
2445
  inline Table_ident(LEX_STRING table_arg) 
2446
    :table(table_arg), sel((SELECT_LEX_UNIT *)0)
2447
  {
2448
    db.str=0;
2449
  }
2450
  /*
2451
    This constructor is used only for the case when we create a derived
2452
    table. A derived table has no name and doesn't belong to any database.
2453
    Later, if there was an alias specified for the table, it will be set
2454
    by add_table_to_list.
2455
  */
2456
  inline Table_ident(SELECT_LEX_UNIT *s) : sel(s)
2457
  {
2458
    /* We must have a table name here as this is used with add_table_to_list */
2459
    db.str= empty_c_string;                    /* a subject to casedn_str */
2460
    db.length= 0;
2461
    table.str= internal_table_name;
2462
    table.length=1;
2463
  }
2464
  bool is_derived_table() const { return test(sel); }
2465
  inline void change_db(char *db_name)
2466
  {
2467
    db.str= db_name; db.length= (uint) strlen(db_name);
2468
  }
2469
};
2470
2471
// this is needed for user_vars hash
2472
class user_var_entry
2473
{
2474
 public:
2475
  user_var_entry() {}                         /* Remove gcc warning */
2476
  LEX_STRING name;
2477
  char *value;
2478
  ulong length;
2479
  query_id_t update_query_id, used_query_id;
2480
  Item_result type;
2481
  bool unsigned_flag;
2482
2483
  double val_real(my_bool *null_value);
2484
  longlong val_int(my_bool *null_value) const;
2485
  String *val_str(my_bool *null_value, String *str, uint decimals);
2486
  my_decimal *val_decimal(my_bool *null_value, my_decimal *result);
2487
  DTCollation collation;
2488
};
2489
2490
/*
2491
   Unique -- class for unique (removing of duplicates). 
2492
   Puts all values to the TREE. If the tree becomes too big,
2493
   it's dumped to the file. User can request sorted values, or
2494
   just iterate through them. In the last case tree merging is performed in
2495
   memory simultaneously with iteration, so it should be ~2-3x faster.
2496
 */
2497
2498
class Unique :public Sql_alloc
2499
{
2500
  DYNAMIC_ARRAY file_ptrs;
2501
  ulong max_elements;
2502
  ulonglong max_in_memory_size;
2503
  IO_CACHE file;
2504
  TREE tree;
2505
  uchar *record_pointers;
2506
  bool flush();
2507
  uint size;
2508
2509
public:
2510
  ulong elements;
2511
  Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg,
2512
	 uint size_arg, ulonglong max_in_memory_size_arg);
2513
  ~Unique();
2514
  ulong elements_in_tree() { return tree.elements_in_tree; }
2515
  inline bool unique_add(void *ptr)
2516
  {
2517
    DBUG_ENTER("unique_add");
2518
    DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements));
2519
    if (tree.elements_in_tree > max_elements && flush())
2520
      DBUG_RETURN(1);
2521
    DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg));
2522
  }
2523
2524
  bool get(TABLE *table);
2525
  static double get_use_cost(uint *buffer, uint nkeys, uint key_size, 
2526
                             ulonglong max_in_memory_size);
2527
  inline static int get_cost_calc_buff_size(ulong nkeys, uint key_size, 
2528
                                            ulonglong max_in_memory_size)
2529
  {
2530
    register ulonglong max_elems_in_tree=
2531
      (1 + max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size));
2532
    return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree));
2533
  }
2534
2535
  void reset();
2536
  bool walk(tree_walk_action action, void *walk_action_arg);
2537
2538
  friend int unique_write_to_file(uchar* key, element_count count, Unique *unique);
2539
  friend int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique);
2540
};
2541
2542
2543
class multi_delete :public select_result_interceptor
2544
{
2545
  TABLE_LIST *delete_tables, *table_being_deleted;
2546
  Unique **tempfiles;
2547
  ha_rows deleted, found;
2548
  uint num_of_tables;
2549
  int error;
2550
  bool do_delete;
2551
  /* True if at least one table we delete from is transactional */
2552
  bool transactional_tables;
2553
  /* True if at least one table we delete from is not transactional */
2554
  bool normal_tables;
2555
  bool delete_while_scanning;
2556
  /*
2557
     error handling (rollback and binlogging) can happen in send_eof()
2558
     so that afterward send_error() needs to find out that.
2559
  */
2560
  bool error_handled;
2561
2562
public:
2563
  multi_delete(TABLE_LIST *dt, uint num_of_tables);
2564
  ~multi_delete();
2565
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2566
  bool send_data(List<Item> &items);
2567
  bool initialize_tables (JOIN *join);
2568
  void send_error(uint errcode,const char *err);
2569
  int  do_deletes();
2570
  bool send_eof();
2571
  virtual void abort();
2572
};
2573
2574
2575
class multi_update :public select_result_interceptor
2576
{
2577
  TABLE_LIST *all_tables; /* query/update command tables */
2578
  TABLE_LIST *leaves;     /* list of leves of join table tree */
2579
  TABLE_LIST *update_tables, *table_being_updated;
2580
  TABLE **tmp_tables, *main_table, *table_to_update;
2581
  TMP_TABLE_PARAM *tmp_table_param;
2582
  ha_rows updated, found;
2583
  List <Item> *fields, *values;
2584
  List <Item> **fields_for_table, **values_for_table;
2585
  uint table_count;
2586
  /*
2587
   List of tables referenced in the CHECK OPTION condition of
2588
   the updated view excluding the updated table. 
2589
  */
2590
  List <TABLE> unupdated_check_opt_tables;
2591
  Copy_field *copy_field;
2592
  enum enum_duplicates handle_duplicates;
2593
  bool do_update, trans_safe;
2594
  /* True if the update operation has made a change in a transactional table */
2595
  bool transactional_tables;
2596
  bool ignore;
2597
  /* 
2598
     error handling (rollback and binlogging) can happen in send_eof()
2599
     so that afterward send_error() needs to find out that.
2600
  */
2601
  bool error_handled;
2602
2603
public:
2604
  multi_update(TABLE_LIST *ut, TABLE_LIST *leaves_list,
2605
	       List<Item> *fields, List<Item> *values,
2606
	       enum_duplicates handle_duplicates, bool ignore);
2607
  ~multi_update();
2608
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2609
  bool send_data(List<Item> &items);
2610
  bool initialize_tables (JOIN *join);
2611
  void send_error(uint errcode,const char *err);
2612
  int  do_updates();
2613
  bool send_eof();
2614
  virtual void abort();
2615
};
2616
2617
class my_var : public Sql_alloc  {
2618
public:
2619
  LEX_STRING s;
2620
  bool local;
2621
  uint offset;
2622
  enum_field_types type;
2623
  my_var (LEX_STRING& j, bool i, uint o, enum_field_types t)
2624
    :s(j), local(i), offset(o), type(t)
2625
  {}
2626
  ~my_var() {}
2627
};
2628
2629
class select_dumpvar :public select_result_interceptor {
2630
  ha_rows row_count;
2631
public:
2632
  List<my_var> var_list;
2633
  select_dumpvar()  { var_list.empty(); row_count= 0;}
2634
  ~select_dumpvar() {}
2635
  int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2636
  bool send_data(List<Item> &items);
2637
  bool send_eof();
2638
  virtual bool check_simple_select() const;
2639
  void cleanup();
2640
};
2641
2642
/* Bits in sql_command_flags */
2643
2644
#define CF_CHANGES_DATA		1
2645
#define CF_HAS_ROW_COUNT	2
2646
#define CF_STATUS_COMMAND	4
2647
#define CF_SHOW_TABLE_COMMAND	8
2648
#define CF_WRITE_LOGS_COMMAND  16
2649
2650
/* Functions in sql_class.cc */
2651
2652
void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
2653
2654
void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
2655
                        STATUS_VAR *dec_var);
2656
void mark_transaction_to_rollback(THD *thd, bool all);
2657
2658
#endif /* MYSQL_SERVER */