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