~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/session.h

Merged in latest plugin-slot-reorg.

Show diffs side-by-side

added added

removed removed

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