~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/session.h

  • Committer: Stewart Smith
  • Author(s): Marko Mäkelä
  • Date: 2010-12-20 03:21:44 UTC
  • mto: (2021.1.2 build)
  • mto: This revision was merged to the branch mainline in revision 2022.
  • Revision ID: stewart@flamingspork.com-20101220032144-7aqh2z403u7d7bdp
Merge Revision revid:marko.makela@oracle.com-20101104131215-pfxnpidlrzd4krg0 from MySQL InnoDB

Original revid:marko.makela@oracle.com-20101104131215-pfxnpidlrzd4krg0

Original Authors: Marko Mäkelä <marko.makela@oracle.com>
Original commit message:
row_ins_index_entry(): Note that only CREATE INDEX sets foreign=FALSE.

Show diffs side-by-side

added added

removed removed

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