~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_class.h

  • Committer: Monty Taylor
  • Date: 2008-10-16 06:32:59 UTC
  • mfrom: (518 drizzle)
  • mto: (511.1.5 codestyle)
  • mto: This revision was merged to the branch mainline in revision 521.
  • Revision ID: monty@inaugust.com-20081016063259-fwbqogq7lnezct0l
Merged with trunk.

Show diffs side-by-side

added added

removed removed

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