~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/session.h

  • Committer: Brian Aker
  • Date: 2009-10-16 10:27:33 UTC
  • mfrom: (1183.1.4 merge)
  • Revision ID: brian@gaz-20091016102733-b10po5oup0hjlilh
MergeĀ EngineĀ changes.

Show diffs side-by-side

added added

removed removed

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