~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_class.h

  • Committer: Monty Taylor
  • Date: 2008-11-16 05:36:13 UTC
  • mto: (584.1.9 devel)
  • mto: This revision was merged to the branch mainline in revision 589.
  • Revision ID: monty@inaugust.com-20081116053613-bld4rqxhlkb49c02
Split out cache_row and type_holder.

Show diffs side-by-side

added added

removed removed

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