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