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