~drizzle-trunk/drizzle/development

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