~ubuntu-branches/ubuntu/saucy/drizzle/saucy-proposed

« back to all changes in this revision

Viewing changes to drizzled/session.h

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2010-03-18 12:12:31 UTC
  • Revision ID: james.westby@ubuntu.com-20100318121231-k6g1xe6cshbwa0f8
Tags: upstream-2010.03.1347
ImportĀ upstreamĀ versionĀ 2010.03.1347

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 
3
 *
 
4
 *  Copyright (C) 2008 Sun Microsystems
 
5
 *
 
6
 *  This program is free software; you can redistribute it and/or modify
 
7
 *  it under the terms of the GNU General Public License as published by
 
8
 *  the Free Software Foundation; version 2 of the License.
 
9
 *
 
10
 *  This program is distributed in the hope that it will be useful,
 
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
 *  GNU General Public License for more details.
 
14
 *
 
15
 *  You should have received a copy of the GNU General Public License
 
16
 *  along with this program; if not, write to the Free Software
 
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
18
 */
 
19
 
 
20
 
 
21
#ifndef DRIZZLED_SESSION_H
 
22
#define DRIZZLED_SESSION_H
 
23
 
 
24
/* Classes in mysql */
 
25
 
 
26
#include "drizzled/plugin.h"
 
27
#include <drizzled/sql_locale.h>
 
28
#include "drizzled/resource_context.h"
 
29
#include <drizzled/cursor.h>
 
30
#include <drizzled/current_session.h>
 
31
#include <drizzled/sql_error.h>
 
32
#include <drizzled/file_exchange.h>
 
33
#include <drizzled/select_result_interceptor.h>
 
34
#include <drizzled/xid.h>
 
35
#include "drizzled/query_id.h"
 
36
#include "drizzled/named_savepoint.h"
 
37
#include "drizzled/transaction_context.h"
 
38
 
 
39
#include <netdb.h>
 
40
#include <map>
 
41
#include <string>
 
42
#include <bitset>
 
43
#include <deque>
 
44
 
 
45
#include <drizzled/security_context.h>
 
46
#include <drizzled/open_tables_state.h>
 
47
 
 
48
#include <drizzled/internal_error_handler.h>
 
49
#include <drizzled/diagnostics_area.h>
 
50
 
 
51
#include <drizzled/plugin/authorization.h>
 
52
 
 
53
#define MIN_HANDSHAKE_SIZE      6
 
54
 
 
55
namespace drizzled
 
56
{
 
57
 
 
58
namespace plugin
 
59
{
 
60
class Client;
 
61
class Scheduler;
 
62
}
 
63
namespace message
 
64
{
 
65
class Transaction;
 
66
class Statement;
 
67
}
 
68
namespace internal
 
69
{
 
70
struct st_my_thread_var;
 
71
}
 
72
 
 
73
class Lex_input_stream;
 
74
class user_var_entry;
 
75
class CopyField;
 
76
class Table_ident;
 
77
 
 
78
extern char internal_table_name[2];
 
79
extern char empty_c_string[1];
 
80
extern const char **errmesg;
 
81
 
 
82
#define TC_HEURISTIC_RECOVER_COMMIT   1
 
83
#define TC_HEURISTIC_RECOVER_ROLLBACK 2
 
84
extern uint32_t tc_heuristic_recover;
 
85
 
 
86
/**
 
87
  @brief
 
88
  Local storage for proto that are tmp table. This should be enlarged
 
89
  to hande the entire table-share for a local table. Once Hash is done,
 
90
  we should consider exchanging the map for it.
 
91
*/
 
92
typedef std::map <std::string, message::Table> ProtoCache;
 
93
 
 
94
/**
 
95
  The COPY_INFO structure is used by INSERT/REPLACE code.
 
96
  The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
 
97
  UPDATE code:
 
98
    If a row is inserted then the copied variable is incremented.
 
99
    If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
 
100
      new data differs from the old one then the copied and the updated
 
101
      variables are incremented.
 
102
    The touched variable is incremented if a row was touched by the update part
 
103
      of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
 
104
      was actually changed or not.
 
105
*/
 
106
typedef struct st_copy_info 
 
107
{
 
108
  ha_rows records; /**< Number of processed records */
 
109
  ha_rows deleted; /**< Number of deleted records */
 
110
  ha_rows updated; /**< Number of updated records */
 
111
  ha_rows copied;  /**< Number of copied records */
 
112
  ha_rows error_count;
 
113
  ha_rows touched; /* Number of touched records */
 
114
  enum enum_duplicates handle_duplicates;
 
115
  int escape_char, last_errno;
 
116
  bool ignore;
 
117
  /* for INSERT ... UPDATE */
 
118
  List<Item> *update_fields;
 
119
  List<Item> *update_values;
 
120
  /* for VIEW ... WITH CHECK OPTION */
 
121
} COPY_INFO;
 
122
 
 
123
typedef struct drizzled_lock_st
 
124
{
 
125
  Table **table;
 
126
  uint32_t table_count;
 
127
  uint32_t lock_count;
 
128
  THR_LOCK_DATA **locks;
 
129
} DRIZZLE_LOCK;
 
130
 
 
131
} /* namespace drizzled */
 
132
 
 
133
/** @TODO why is this in the middle of the file */
 
134
#include <drizzled/lex_column.h>
 
135
 
 
136
namespace drizzled
 
137
{
 
138
 
 
139
class select_result;
 
140
class Time_zone;
 
141
 
 
142
#define Session_SENTRY_MAGIC 0xfeedd1ff
 
143
#define Session_SENTRY_GONE  0xdeadbeef
 
144
 
 
145
#define Session_CHECK_SENTRY(session) assert(session->dbug_sentry == Session_SENTRY_MAGIC)
 
146
 
 
147
struct system_variables
 
148
{
 
149
  system_variables() {};
 
150
  /*
 
151
    How dynamically allocated system variables are handled:
 
152
 
 
153
    The global_system_variables and max_system_variables are "authoritative"
 
154
    They both should have the same 'version' and 'size'.
 
155
    When attempting to access a dynamic variable, if the session version
 
156
    is out of date, then the session version is updated and realloced if
 
157
    neccessary and bytes copied from global to make up for missing data.
 
158
  */
 
159
  ulong dynamic_variables_version;
 
160
  char * dynamic_variables_ptr;
 
161
  uint32_t dynamic_variables_head;  /* largest valid variable offset */
 
162
  uint32_t dynamic_variables_size;  /* how many bytes are in use */
 
163
 
 
164
  uint64_t myisam_max_extra_sort_file_size;
 
165
  uint64_t max_heap_table_size;
 
166
  uint64_t tmp_table_size;
 
167
  ha_rows select_limit;
 
168
  ha_rows max_join_size;
 
169
  uint64_t auto_increment_increment;
 
170
  uint64_t auto_increment_offset;
 
171
  uint64_t bulk_insert_buff_size;
 
172
  uint64_t join_buff_size;
 
173
  uint32_t max_allowed_packet;
 
174
  uint64_t max_error_count;
 
175
  uint64_t max_length_for_sort_data;
 
176
  size_t max_sort_length;
 
177
  uint64_t min_examined_row_limit;
 
178
  bool optimizer_prune_level;
 
179
  bool log_warnings;
 
180
 
 
181
  uint32_t optimizer_search_depth;
 
182
  uint32_t div_precincrement;
 
183
  uint64_t preload_buff_size;
 
184
  uint32_t read_buff_size;
 
185
  uint32_t read_rnd_buff_size;
 
186
  size_t sortbuff_size;
 
187
  uint32_t thread_handling;
 
188
  uint32_t tx_isolation;
 
189
  uint32_t completion_type;
 
190
  /* Determines which non-standard SQL behaviour should be enabled */
 
191
  uint32_t sql_mode;
 
192
  uint64_t max_seeks_for_key;
 
193
  size_t range_alloc_block_size;
 
194
  uint32_t query_alloc_block_size;
 
195
  uint32_t query_prealloc_size;
 
196
  uint64_t group_concat_max_len;
 
197
  uint64_t pseudo_thread_id;
 
198
 
 
199
  plugin::StorageEngine *storage_engine;
 
200
 
 
201
  /* Only charset part of these variables is sensible */
 
202
  const CHARSET_INFO  *character_set_filesystem;
 
203
 
 
204
  /* Both charset and collation parts of these variables are important */
 
205
  const CHARSET_INFO    *collation_server;
 
206
 
 
207
  inline const CHARSET_INFO  *getCollation(void) 
 
208
  {
 
209
    return collation_server;
 
210
  }
 
211
 
 
212
  /* Locale Support */
 
213
  MY_LOCALE *lc_time_names;
 
214
 
 
215
  Time_zone *time_zone;
 
216
};
 
217
 
 
218
extern struct system_variables global_system_variables;
 
219
 
 
220
} /* namespace drizzled */
 
221
 
 
222
#include "drizzled/sql_lex.h"
 
223
 
 
224
namespace drizzled
 
225
{
 
226
 
 
227
/**
 
228
 * Per-session local status counters
 
229
 */
 
230
typedef struct system_status_var
 
231
{
 
232
  uint64_t bytes_received;
 
233
  uint64_t bytes_sent;
 
234
  ulong com_other;
 
235
  ulong com_stat[(uint32_t) SQLCOM_END];
 
236
  ulong created_tmp_disk_tables;
 
237
  ulong created_tmp_tables;
 
238
  ulong ha_commit_count;
 
239
  ulong ha_delete_count;
 
240
  ulong ha_read_first_count;
 
241
  ulong ha_read_last_count;
 
242
  ulong ha_read_key_count;
 
243
  ulong ha_read_next_count;
 
244
  ulong ha_read_prev_count;
 
245
  ulong ha_read_rnd_count;
 
246
  ulong ha_read_rnd_next_count;
 
247
  ulong ha_rollback_count;
 
248
  ulong ha_update_count;
 
249
  ulong ha_write_count;
 
250
  ulong ha_prepare_count;
 
251
  ulong ha_savepoint_count;
 
252
  ulong ha_savepoint_rollback_count;
 
253
 
 
254
  /* KEY_CACHE parts. These are copies of the original */
 
255
  ulong key_blocks_changed;
 
256
  ulong key_blocks_used;
 
257
  ulong key_cache_r_requests;
 
258
  ulong key_cache_read;
 
259
  ulong key_cache_w_requests;
 
260
  ulong key_cache_write;
 
261
  /* END OF KEY_CACHE parts */
 
262
 
 
263
  ulong net_big_packet_count;
 
264
  ulong select_full_join_count;
 
265
  ulong select_full_range_join_count;
 
266
  ulong select_range_count;
 
267
  ulong select_range_check_count;
 
268
  ulong select_scan_count;
 
269
  ulong long_query_count;
 
270
  ulong filesort_merge_passes;
 
271
  ulong filesort_range_count;
 
272
  ulong filesort_rows;
 
273
  ulong filesort_scan_count;
 
274
  /*
 
275
    Number of statements sent from the client
 
276
  */
 
277
  ulong questions;
 
278
 
 
279
  /*
 
280
    IMPORTANT!
 
281
    SEE last_system_status_var DEFINITION BELOW.
 
282
 
 
283
    Below 'last_system_status_var' are all variables which doesn't make any
 
284
    sense to add to the /global/ status variable counter.
 
285
  */
 
286
  double last_query_cost;
 
287
} system_status_var;
 
288
 
 
289
/*
 
290
  This is used for 'SHOW STATUS'. It must be updated to the last ulong
 
291
  variable in system_status_var which is makes sens to add to the global
 
292
  counter
 
293
*/
 
294
 
 
295
#define last_system_status_var questions
 
296
 
 
297
void mark_transaction_to_rollback(Session *session, bool all);
 
298
 
 
299
extern pthread_mutex_t LOCK_xid_cache;
 
300
extern HASH xid_cache;
 
301
 
 
302
 
 
303
/**
 
304
  Storage engine specific thread local data.
 
305
*/
 
306
struct Ha_data
 
307
{
 
308
  /**
 
309
    Storage engine specific thread local data.
 
310
    Lifetime: one user connection.
 
311
  */
 
312
  void *ha_ptr;
 
313
  /**
 
314
   * Resource contexts for both the "statement" and "normal"
 
315
   * transactions.
 
316
   *
 
317
   * Resource context at index 0:
 
318
   *
 
319
   * Life time: one statement within a transaction. If @@autocommit is
 
320
   * on, also represents the entire transaction.
 
321
   *
 
322
   * Resource context at index 1:
 
323
   *
 
324
   * Life time: one transaction within a connection. 
 
325
   *
 
326
   * @note
 
327
   *
 
328
   * If the storage engine does not participate in a transaction, 
 
329
   * there will not be a resource context.
 
330
   */
 
331
  drizzled::ResourceContext resource_context[2];
 
332
 
 
333
  Ha_data() :ha_ptr(NULL) {}
 
334
};
 
335
 
 
336
/**
 
337
 * Represents a client connection to the database server.
 
338
 *
 
339
 * Contains the client/server protocol object, the current statement
 
340
 * being executed, local-to-session variables and status counters, and
 
341
 * a host of other information.
 
342
 *
 
343
 * @todo
 
344
 *
 
345
 * The Session class should have a vector of Statement object pointers which
 
346
 * comprise the statements executed on the Session. Until this architectural
 
347
 * change is done, we can forget about parallel operations inside a session.
 
348
 *
 
349
 * @todo
 
350
 *
 
351
 * Make member variables private and have inlined accessors and setters.  Hide
 
352
 * all member variables that are not critical to non-internal operations of the
 
353
 * session object.
 
354
 */
 
355
class Session : public Open_tables_state
 
356
{
 
357
public:
 
358
  /*
 
359
    MARK_COLUMNS_NONE:  Means mark_used_colums is not set and no indicator to
 
360
                        handler of fields used is set
 
361
    MARK_COLUMNS_READ:  Means a bit in read set is set to inform handler
 
362
                        that the field is to be read. If field list contains
 
363
                        duplicates, then session->dup_field is set to point
 
364
                        to the last found duplicate.
 
365
    MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
 
366
                        that it needs to update this field in write_row
 
367
                        and update_row.
 
368
  */
 
369
  enum enum_mark_columns mark_used_columns;
 
370
  inline void* alloc(size_t size)
 
371
  {
 
372
    return alloc_root(mem_root,size);
 
373
  }
 
374
  inline void* calloc(size_t size)
 
375
  {
 
376
    void *ptr;
 
377
    if ((ptr= alloc_root(mem_root,size)))
 
378
      memset(ptr, 0, size);
 
379
    return ptr;
 
380
  }
 
381
  inline char *strdup(const char *str)
 
382
  {
 
383
    return strdup_root(mem_root,str);
 
384
  }
 
385
  inline char *strmake(const char *str, size_t size)
 
386
  {
 
387
    return strmake_root(mem_root,str,size);
 
388
  }
 
389
  inline void *memdup(const void *str, size_t size)
 
390
  {
 
391
    return memdup_root(mem_root,str,size);
 
392
  }
 
393
  inline void *memdup_w_gap(const void *str, size_t size, uint32_t gap)
 
394
  {
 
395
    void *ptr;
 
396
    if ((ptr= alloc_root(mem_root,size+gap)))
 
397
      memcpy(ptr,str,size);
 
398
    return ptr;
 
399
  }
 
400
  /** Frees all items attached to this Statement */
 
401
  void free_items();
 
402
  /**
 
403
   * List of items created in the parser for this query. Every item puts
 
404
   * itself to the list on creation (see Item::Item() for details))
 
405
   */
 
406
  Item *free_list;
 
407
  memory::Root *mem_root; /**< Pointer to current memroot */
 
408
  /**
 
409
   * Uniquely identifies each statement object in thread scope; change during
 
410
   * statement lifetime.
 
411
   *
 
412
   * @todo should be const
 
413
   */
 
414
  uint32_t id;
 
415
  LEX *lex; /**< parse tree descriptor */
 
416
  /** query associated with this statement */
 
417
  std::string query;
 
418
 
 
419
  /**
 
420
    Name of the current (default) database.
 
421
 
 
422
    If there is the current (default) database, "db" contains its name. If
 
423
    there is no current (default) database, "db" is NULL and "db_length" is
 
424
    0. In other words, "db", "db_length" must either be NULL, or contain a
 
425
    valid database name.
 
426
 
 
427
    @note this attribute is set and alloced by the slave SQL thread (for
 
428
    the Session of that thread); that thread is (and must remain, for now) the
 
429
    only responsible for freeing this member.
 
430
  */
 
431
  std::string db;
 
432
 
 
433
  /**
 
434
    Constant for Session::where initialization in the beginning of every query.
 
435
 
 
436
    It's needed because we do not save/restore Session::where normally during
 
437
    primary (non subselect) query execution.
 
438
  */
 
439
  static const char * const DEFAULT_WHERE;
 
440
 
 
441
  memory::Root warn_root; /**< Allocation area for warnings and errors */
 
442
  plugin::Client *client; /**< Pointer to client object */
 
443
  plugin::Scheduler *scheduler; /**< Pointer to scheduler object */
 
444
  void *scheduler_arg; /**< Pointer to the optional scheduler argument */
 
445
  HASH user_vars; /**< Hash of user variables defined during the session's lifetime */
 
446
  struct system_variables variables; /**< Mutable local variables local to the session */
 
447
  struct system_status_var status_var; /**< Session-local status counters */
 
448
  struct system_status_var *initial_status_var; /* used by show status */
 
449
  THR_LOCK_INFO lock_info; /**< Locking information for this session */
 
450
  THR_LOCK_OWNER main_lock_id; /**< To use for conventional queries */
 
451
  THR_LOCK_OWNER *lock_id; /**< If not main_lock_id, points to the lock_id of a cursor. */
 
452
  pthread_mutex_t LOCK_delete; /**< Locked before session is deleted */
 
453
 
 
454
  /**
 
455
   * A peek into the query string for the session. This is a best effort
 
456
   * delivery, there is no guarantee whether the content is meaningful.
 
457
   */
 
458
  char process_list_info[PROCESS_LIST_WIDTH+1];
 
459
 
 
460
  /**
 
461
   * A pointer to the stack frame of the scheduler thread
 
462
   * which is called first in the thread for handling a client
 
463
   */
 
464
  char *thread_stack;
 
465
 
 
466
private:
 
467
  SecurityContext security_ctx;
 
468
public:
 
469
  const SecurityContext& getSecurityContext() const
 
470
  {
 
471
    return security_ctx;
 
472
  }
 
473
 
 
474
  SecurityContext& getSecurityContext()
 
475
  {
 
476
    return security_ctx;
 
477
  }
 
478
 
 
479
  /**
 
480
   * Is this session viewable by the current user?
 
481
   */
 
482
  bool isViewable() const
 
483
  {
 
484
    return plugin::Authorization::isAuthorized(current_session->getSecurityContext(),
 
485
                                               this,
 
486
                                               false);
 
487
  }
 
488
 
 
489
  /**
 
490
    Used in error messages to tell user in what part of MySQL we found an
 
491
    error. E. g. when where= "having clause", if fix_fields() fails, user
 
492
    will know that the error was in having clause.
 
493
  */
 
494
  const char *where;
 
495
 
 
496
  /*
 
497
    One thread can hold up to one named user-level lock. This variable
 
498
    points to a lock object if the lock is present. See item_func.cc and
 
499
    chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
 
500
  */
 
501
  uint32_t dbug_sentry; /**< watch for memory corruption */
 
502
  internal::st_my_thread_var *mysys_var;
 
503
  /**
 
504
   * Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
 
505
   * first byte of the packet in executeStatement()
 
506
   */
 
507
  enum enum_server_command command;
 
508
  uint32_t file_id;     /**< File ID for LOAD DATA INFILE */
 
509
  /* @note the following three members should likely move to Client */
 
510
  uint32_t max_client_packet_length; /**< Maximum number of bytes a client can send in a single packet */
 
511
  time_t start_time;
 
512
  time_t user_time;
 
513
  uint64_t thr_create_utime; /**< track down slow pthread_create */
 
514
  uint64_t start_utime;
 
515
  uint64_t utime_after_lock;
 
516
 
 
517
  thr_lock_type update_lock_default;
 
518
 
 
519
  /*
 
520
    Both of the following container points in session will be converted to an API.
 
521
  */
 
522
 
 
523
private:
 
524
  /* container for handler's private per-connection data */
 
525
  std::vector<Ha_data> ha_data;
 
526
  /*
 
527
    Id of current query. Statement can be reused to execute several queries
 
528
    query_id is global in context of the whole MySQL server.
 
529
    ID is automatically generated from an atomic counter.
 
530
    It's used in Cursor code for various purposes: to check which columns
 
531
    from table are necessary for this select, to check if it's necessary to
 
532
    update auto-updatable fields (like auto_increment and timestamp).
 
533
  */
 
534
  query_id_t query_id;
 
535
  query_id_t warn_query_id;
 
536
public:
 
537
  void **getEngineData(const plugin::MonitoredInTransaction *monitored);
 
538
  ResourceContext *getResourceContext(const plugin::MonitoredInTransaction *monitored,
 
539
                                      size_t index= 0);
 
540
 
 
541
  struct st_transactions {
 
542
    std::deque<NamedSavepoint> savepoints;
 
543
    TransactionContext all; ///< Trans since BEGIN WORK
 
544
    TransactionContext stmt; ///< Trans for current statement
 
545
    XID_STATE xid_state;
 
546
 
 
547
    void cleanup()
 
548
    {
 
549
      savepoints.clear();
 
550
    }
 
551
    st_transactions() :
 
552
      savepoints(),
 
553
      all(),
 
554
      stmt(),
 
555
      xid_state()
 
556
    { }
 
557
  } transaction;
 
558
 
 
559
  Field *dup_field;
 
560
  sigset_t signals;
 
561
 
 
562
  /* Tells if LAST_INSERT_ID(#) was called for the current statement */
 
563
  bool arg_of_last_insert_id_function;
 
564
  /*
 
565
    ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
 
566
    insertion into an auto_increment column".
 
567
  */
 
568
  /**
 
569
    This is the first autogenerated insert id which was *successfully*
 
570
    inserted by the previous statement (exactly, if the previous statement
 
571
    didn't successfully insert an autogenerated insert id, then it's the one
 
572
    of the statement before, etc).
 
573
    It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
 
574
    It is returned by LAST_INSERT_ID().
 
575
  */
 
576
  uint64_t first_successful_insert_id_in_prev_stmt;
 
577
  /**
 
578
    This is the first autogenerated insert id which was *successfully*
 
579
    inserted by the current statement. It is maintained only to set
 
580
    first_successful_insert_id_in_prev_stmt when statement ends.
 
581
  */
 
582
  uint64_t first_successful_insert_id_in_cur_stmt;
 
583
  /**
 
584
    We follow this logic:
 
585
    - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
 
586
    first insert id successfully inserted by the previous stmt.
 
587
    - as stmt makes progress, handler::insert_id_for_cur_row changes;
 
588
    every time get_auto_increment() is called,
 
589
    auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
 
590
    reserved interval (if statement-based binlogging).
 
591
    - at first successful insertion of an autogenerated value,
 
592
    first_successful_insert_id_in_cur_stmt is set to
 
593
    handler::insert_id_for_cur_row.
 
594
    - when stmt goes to binlog,
 
595
    auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
 
596
    non-empty.
 
597
    - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
 
598
    first_successful_insert_id_in_cur_stmt.
 
599
 
 
600
    List of auto_increment intervals reserved by the thread so far, for
 
601
    storage in the statement-based binlog.
 
602
    Note that its minimum is not first_successful_insert_id_in_cur_stmt:
 
603
    assuming a table with an autoinc column, and this happens:
 
604
    INSERT INTO ... VALUES(3);
 
605
    SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
 
606
    then the latter INSERT will insert no rows
 
607
    (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
 
608
    in the binlog is still needed; the list's minimum will contain 3.
 
609
  */
 
610
  Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
 
611
  /** Used by replication and SET INSERT_ID */
 
612
  Discrete_intervals_list auto_inc_intervals_forced;
 
613
 
 
614
  uint64_t limit_found_rows;
 
615
  uint64_t options; /**< Bitmap of options */
 
616
  int64_t row_count_func; /**< For the ROW_COUNT() function */
 
617
  ha_rows cuted_fields; /**< Count of "cut" or truncated fields. @todo Kill this friggin thing. */
 
618
 
 
619
  /** 
 
620
   * Number of rows we actually sent to the client, including "synthetic"
 
621
   * rows in ROLLUP etc.
 
622
   */
 
623
  ha_rows sent_row_count;
 
624
 
 
625
  /**
 
626
   * Number of rows we read, sent or not, including in create_sort_index()
 
627
   */
 
628
  ha_rows examined_row_count;
 
629
 
 
630
  /**
 
631
   * The set of those tables whose fields are referenced in all subqueries
 
632
   * of the query.
 
633
   *
 
634
   * @todo
 
635
   * 
 
636
   * Possibly this it is incorrect to have used tables in Session because
 
637
   * with more than one subquery, it is not clear what does the field mean.
 
638
   */
 
639
  table_map used_tables;
 
640
 
 
641
  /**
 
642
    @todo
 
643
    
 
644
    This, and some other variables like 'count_cuted_fields'
 
645
    maybe should be statement/cursor local, that is, moved to Statement
 
646
    class. With current implementation warnings produced in each prepared
 
647
    statement/cursor settle here.
 
648
  */
 
649
  List<DRIZZLE_ERROR> warn_list;
 
650
  uint32_t warn_count[(uint32_t) DRIZZLE_ERROR::WARN_LEVEL_END];
 
651
  uint32_t total_warn_count;
 
652
  Diagnostics_area main_da;
 
653
 
 
654
  ulong col_access;
 
655
 
 
656
  /* Statement id is thread-wide. This counter is used to generate ids */
 
657
  uint32_t statement_id_counter;
 
658
  uint32_t rand_saved_seed1;
 
659
  uint32_t rand_saved_seed2;
 
660
  /**
 
661
    Row counter, mainly for errors and warnings. Not increased in
 
662
    create_sort_index(); may differ from examined_row_count.
 
663
  */
 
664
  uint32_t row_count;
 
665
  pthread_t real_id; /**< For debugging */
 
666
  uint64_t thread_id;
 
667
  uint32_t tmp_table;
 
668
  uint32_t global_read_lock;
 
669
  uint32_t server_status;
 
670
  uint32_t open_options;
 
671
  uint32_t select_number; /**< number of select (used for EXPLAIN) */
 
672
  /* variables.transaction_isolation is reset to this after each commit */
 
673
  enum_tx_isolation session_tx_isolation;
 
674
  enum_check_fields count_cuted_fields;
 
675
 
 
676
  enum killed_state
 
677
  {
 
678
    NOT_KILLED,
 
679
    KILL_BAD_DATA,
 
680
    KILL_CONNECTION,
 
681
    KILL_QUERY,
 
682
    KILLED_NO_VALUE /* means none of the above states apply */
 
683
  };
 
684
  killed_state volatile killed;
 
685
 
 
686
  bool some_tables_deleted;
 
687
  bool no_errors;
 
688
  bool password;
 
689
  /**
 
690
    Set to true if execution of the current compound statement
 
691
    can not continue. In particular, disables activation of
 
692
    CONTINUE or EXIT handlers of stored routines.
 
693
    Reset in the end of processing of the current user request, in
 
694
    @see mysql_reset_session_for_next_command().
 
695
  */
 
696
  bool is_fatal_error;
 
697
  /**
 
698
    Set by a storage engine to request the entire
 
699
    transaction (that possibly spans multiple engines) to
 
700
    rollback. Reset in ha_rollback.
 
701
  */
 
702
  bool transaction_rollback_request;
 
703
  /**
 
704
    true if we are in a sub-statement and the current error can
 
705
    not be safely recovered until we left the sub-statement mode.
 
706
    In particular, disables activation of CONTINUE and EXIT
 
707
    handlers inside sub-statements. E.g. if it is a deadlock
 
708
    error and requires a transaction-wide rollback, this flag is
 
709
    raised (traditionally, MySQL first has to close all the reads
 
710
    via @see handler::ha_index_or_rnd_end() and only then perform
 
711
    the rollback).
 
712
    Reset to false when we leave the sub-statement mode.
 
713
  */
 
714
  bool is_fatal_sub_stmt_error;
 
715
  /** for IS NULL => = last_insert_id() fix in remove_eq_conds() */
 
716
  bool substitute_null_with_insert_id;
 
717
  bool cleanup_done;
 
718
 
 
719
  bool abort_on_warning;
 
720
  bool got_warning; /**< Set on call to push_warning() */
 
721
  bool no_warnings_for_error; /**< no warnings on call to my_error() */
 
722
  /** set during loop of derived table processing */
 
723
  bool derived_tables_processing;
 
724
  bool tablespace_op; /**< This is true in DISCARD/IMPORT TABLESPACE */
 
725
 
 
726
  /** Used by the sys_var class to store temporary values */
 
727
  union
 
728
  {
 
729
    bool bool_value;
 
730
    uint32_t uint32_t_value;
 
731
    int32_t int32_t_value;
 
732
    uint64_t uint64_t_value;
 
733
  } sys_var_tmp;
 
734
 
 
735
  /**
 
736
    Character input stream consumed by the lexical analyser,
 
737
    used during parsing.
 
738
    Note that since the parser is not re-entrant, we keep only one input
 
739
    stream here. This member is valid only when executing code during parsing,
 
740
    and may point to invalid memory after that.
 
741
  */
 
742
  Lex_input_stream *m_lip;
 
743
  
 
744
  /** Place to store various things */
 
745
  void *session_marker;
 
746
 
 
747
  /** Keeps a copy of the previous table around in case we are just slamming on particular table */
 
748
  Table *cached_table;
 
749
 
 
750
  /**
 
751
    Points to info-string that we show in SHOW PROCESSLIST
 
752
    You are supposed to call Session_SET_PROC_INFO only if you have coded
 
753
    a time-consuming piece that MySQL can get stuck in for a long time.
 
754
 
 
755
    Set it using the  session_proc_info(Session *thread, const char *message)
 
756
    macro/function.
 
757
  */
 
758
  inline void set_proc_info(const char *info)
 
759
  { 
 
760
    proc_info= info;
 
761
  }
 
762
  inline const char* get_proc_info() const
 
763
  {
 
764
    return proc_info;
 
765
  }
 
766
 
 
767
  /** Sets this Session's current query ID */
 
768
  inline void setQueryId(query_id_t in_query_id)
 
769
  {
 
770
    query_id= in_query_id;
 
771
  }
 
772
 
 
773
  /** Returns the current query ID */
 
774
  inline query_id_t getQueryId()  const
 
775
  {
 
776
    return query_id;
 
777
  }
 
778
 
 
779
 
 
780
  /** Sets this Session's warning query ID */
 
781
  inline void setWarningQueryId(query_id_t in_query_id)
 
782
  {
 
783
    warn_query_id= in_query_id;
 
784
  }
 
785
 
 
786
  /** Returns the Session's warning query ID */
 
787
  inline query_id_t getWarningQueryId()  const
 
788
  {
 
789
    return warn_query_id;
 
790
  }
 
791
 
 
792
  /** Returns the current query text */
 
793
  inline const std::string &getQueryString()  const
 
794
  {
 
795
    return query;
 
796
  }
 
797
 
 
798
  /** Returns the length of the current query text */
 
799
  inline size_t getQueryLength() const
 
800
  {
 
801
    if (! query.empty())
 
802
      return query.length();
 
803
    else
 
804
      return 0;
 
805
  }
 
806
 
 
807
  /** Accessor method returning the session's ID. */
 
808
  inline uint64_t getSessionId()  const
 
809
  {
 
810
    return thread_id;
 
811
  }
 
812
 
 
813
  /** Accessor method returning the server's ID. */
 
814
  inline uint32_t getServerId()  const
 
815
  {
 
816
    /* We return the global server ID. */
 
817
    return server_id;
 
818
  }
 
819
 
 
820
  /** Returns the current transaction ID for the session's current statement */
 
821
  inline my_xid getTransactionId()
 
822
  {
 
823
    return transaction.xid_state.xid.quick_get_my_xid();
 
824
  }
 
825
  /**
 
826
    There is BUG#19630 where statement-based replication of stored
 
827
    functions/triggers with two auto_increment columns breaks.
 
828
    We however ensure that it works when there is 0 or 1 auto_increment
 
829
    column; our rules are
 
830
    a) on master, while executing a top statement involving substatements,
 
831
    first top- or sub- statement to generate auto_increment values wins the
 
832
    exclusive right to see its values be written to binlog (the write
 
833
    will be done by the statement or its caller), and the losers won't see
 
834
    their values be written to binlog.
 
835
    b) on slave, while replicating a top statement involving substatements,
 
836
    first top- or sub- statement to need to read auto_increment values from
 
837
    the master's binlog wins the exclusive right to read them (so the losers
 
838
    won't read their values from binlog but instead generate on their own).
 
839
    a) implies that we mustn't backup/restore
 
840
    auto_inc_intervals_in_cur_stmt_for_binlog.
 
841
    b) implies that we mustn't backup/restore auto_inc_intervals_forced.
 
842
 
 
843
    If there are more than 1 auto_increment columns, then intervals for
 
844
    different columns may mix into the
 
845
    auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
 
846
    but there is no point in preventing this mixing by preventing intervals
 
847
    from the secondly inserted column to come into the list, as such
 
848
    prevention would be wrong too.
 
849
    What will happen in the case of
 
850
    INSERT INTO t1 (auto_inc) VALUES(NULL);
 
851
    where t1 has a trigger which inserts into an auto_inc column of t2, is
 
852
    that in binlog we'll store the interval of t1 and the interval of t2 (when
 
853
    we store intervals, soon), then in slave, t1 will use both intervals, t2
 
854
    will use none; if t1 inserts the same number of rows as on master,
 
855
    normally the 2nd interval will not be used by t1, which is fine. t2's
 
856
    values will be wrong if t2's internal auto_increment counter is different
 
857
    from what it was on master (which is likely). In 5.1, in mixed binlogging
 
858
    mode, row-based binlogging is used for such cases where two
 
859
    auto_increment columns are inserted.
 
860
  */
 
861
  inline void record_first_successful_insert_id_in_cur_stmt(uint64_t id_arg)
 
862
  {
 
863
    if (first_successful_insert_id_in_cur_stmt == 0)
 
864
      first_successful_insert_id_in_cur_stmt= id_arg;
 
865
  }
 
866
  inline uint64_t read_first_successful_insert_id_in_prev_stmt(void)
 
867
  {
 
868
    return first_successful_insert_id_in_prev_stmt;
 
869
  }
 
870
  /**
 
871
    Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
 
872
    (mysqlbinlog). We'll soon add a variant which can take many intervals in
 
873
    argument.
 
874
  */
 
875
  inline void force_one_auto_inc_interval(uint64_t next_id)
 
876
  {
 
877
    auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
 
878
    auto_inc_intervals_forced.append(next_id, UINT64_MAX, 0);
 
879
  }
 
880
 
 
881
  Session(plugin::Client *client_arg);
 
882
  virtual ~Session();
 
883
 
 
884
  void cleanup(void);
 
885
  /**
 
886
   * Cleans up after query.
 
887
   *
 
888
   * @details
 
889
   *
 
890
   * This function is used to reset thread data to its default state.
 
891
   *
 
892
   * This function is not suitable for setting thread data to some
 
893
   * non-default values, as there is only one replication thread, so
 
894
   * different master threads may overwrite data of each other on
 
895
   * slave.
 
896
   */
 
897
  void cleanup_after_query();
 
898
  bool storeGlobals();
 
899
  void awake(Session::killed_state state_to_set);
 
900
  /**
 
901
   * Pulls thread-specific variables into Session state.
 
902
   *
 
903
   * Returns true most times, or false if there was a problem
 
904
   * allocating resources for thread-specific storage.
 
905
   *
 
906
   * @TODO Kill this.  It's not necessary once my_thr_init() is bye bye.
 
907
   *
 
908
   */
 
909
  bool initGlobals();
 
910
 
 
911
  /**
 
912
    Initialize memory roots necessary for query processing and (!)
 
913
    pre-allocate memory for it. We can't do that in Session constructor because
 
914
    there are use cases where it's vital to not allocate excessive and not used
 
915
    memory.
 
916
  */
 
917
  void prepareForQueries();
 
918
 
 
919
  /**
 
920
   * Executes a single statement received from the 
 
921
   * client connection.
 
922
   *
 
923
   * Returns true if the statement was successful, or false 
 
924
   * otherwise.
 
925
   *
 
926
   * @note
 
927
   *
 
928
   * For profiling to work, it must never be called recursively.
 
929
   *
 
930
   * In MySQL, this used to be the do_command() C function whic
 
931
   * accepted a single parameter of the THD pointer.
 
932
   */
 
933
  bool executeStatement();
 
934
 
 
935
  /**
 
936
   * Reads a query from packet and stores it.
 
937
   *
 
938
   * Returns true if query is read and allocated successfully, 
 
939
   * false otherwise.  On a return of false, Session::fatal_error
 
940
   * is set.
 
941
   *
 
942
   * @note Used in COM_QUERY and COM_STMT_PREPARE.
 
943
   *
 
944
   * Sets the following Session variables:
 
945
   *  - query
 
946
   *  - query_length
 
947
   *
 
948
   * @param The packet pointer to read from
 
949
   * @param The length of the query to read
 
950
   */
 
951
  bool readAndStoreQuery(const char *in_packet, uint32_t in_packet_length);
 
952
 
 
953
  /**
 
954
   * Ends the current transaction and (maybe) begins the next.
 
955
   *
 
956
   * Returns true if the transaction completed successfully, 
 
957
   * otherwise false.
 
958
   *
 
959
   * @param Completion type
 
960
   */
 
961
  bool endTransaction(enum enum_mysql_completiontype completion);
 
962
  bool endActiveTransaction();
 
963
  bool startTransaction(start_transaction_option_t opt= START_TRANS_NO_OPTIONS);
 
964
 
 
965
  /**
 
966
   * Authenticates users, with error reporting.
 
967
   *
 
968
   * Returns true on success, or false on failure.
 
969
   */
 
970
  bool authenticate();
 
971
 
 
972
  /**
 
973
   * Run a session.
 
974
   *
 
975
   * This will initialize the session and begin the command loop.
 
976
   */
 
977
  void run();
 
978
 
 
979
  /**
 
980
   * Schedule a session to be run on the default scheduler.
 
981
   */
 
982
  bool schedule();
 
983
 
 
984
  /*
 
985
    For enter_cond() / exit_cond() to work the mutex must be got before
 
986
    enter_cond(); this mutex is then released by exit_cond().
 
987
    Usage must be: lock mutex; enter_cond(); your code; exit_cond().
 
988
  */
 
989
  const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex, const char* msg);
 
990
  void exit_cond(const char* old_msg);
 
991
 
 
992
  inline time_t query_start() { return start_time; }
 
993
  inline void set_time()
 
994
  {
 
995
    if (user_time)
 
996
    {
 
997
      start_time= user_time;
 
998
      connect_microseconds= start_utime= utime_after_lock= my_micro_time();
 
999
    }
 
1000
    else
 
1001
      start_utime= utime_after_lock= my_micro_time_and_time(&start_time);
 
1002
  }
 
1003
  inline void   set_current_time()    { start_time= time(NULL); }
 
1004
  inline void   set_time(time_t t)
 
1005
  {
 
1006
    start_time= user_time= t;
 
1007
    start_utime= utime_after_lock= my_micro_time();
 
1008
  }
 
1009
  void set_time_after_lock()  { utime_after_lock= my_micro_time(); }
 
1010
  /**
 
1011
   * Returns the current micro-timestamp
 
1012
   */
 
1013
  inline uint64_t getCurrentTimestamp()  
 
1014
  { 
 
1015
    return my_micro_time(); 
 
1016
  }
 
1017
  inline uint64_t found_rows(void)
 
1018
  {
 
1019
    return limit_found_rows;
 
1020
  }
 
1021
  /** Returns whether the session is currently inside a transaction */
 
1022
  inline bool inTransaction()
 
1023
  {
 
1024
    return server_status & SERVER_STATUS_IN_TRANS;
 
1025
  }
 
1026
  inline bool fill_derived_tables()
 
1027
  {
 
1028
    return !lex->only_view_structure();
 
1029
  }
 
1030
 
 
1031
  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
 
1032
                              const char* str, uint32_t length,
 
1033
                              bool allocate_lex_string);
 
1034
  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
 
1035
                              const std::string &str,
 
1036
                              bool allocate_lex_string);
 
1037
 
 
1038
  int send_explain_fields(select_result *result);
 
1039
  /**
 
1040
    Clear the current error, if any.
 
1041
    We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
 
1042
    assume this is never called if the fatal error is set.
 
1043
    @todo: To silence an error, one should use Internal_error_handler
 
1044
    mechanism. In future this function will be removed.
 
1045
  */
 
1046
  inline void clear_error()
 
1047
  {
 
1048
    if (main_da.is_error())
 
1049
      main_da.reset_diagnostics_area();
 
1050
    return;
 
1051
  }
 
1052
 
 
1053
  /**
 
1054
    Mark the current error as fatal. Warning: this does not
 
1055
    set any error, it sets a property of the error, so must be
 
1056
    followed or prefixed with my_error().
 
1057
  */
 
1058
  inline void fatal_error()
 
1059
  {
 
1060
    assert(main_da.is_error());
 
1061
    is_fatal_error= true;
 
1062
  }
 
1063
  /**
 
1064
    true if there is an error in the error stack.
 
1065
 
 
1066
    Please use this method instead of direct access to
 
1067
    net.report_error.
 
1068
 
 
1069
    If true, the current (sub)-statement should be aborted.
 
1070
    The main difference between this member and is_fatal_error
 
1071
    is that a fatal error can not be handled by a stored
 
1072
    procedure continue handler, whereas a normal error can.
 
1073
 
 
1074
    To raise this flag, use my_error().
 
1075
  */
 
1076
  inline bool is_error() const { return main_da.is_error(); }
 
1077
  inline const CHARSET_INFO *charset() { return default_charset_info; }
 
1078
 
 
1079
  void change_item_tree(Item **place, Item *new_value)
 
1080
  {
 
1081
    *place= new_value;
 
1082
  }
 
1083
  /**
 
1084
    Cleanup statement parse state (parse tree, lex) and execution
 
1085
    state after execution of a non-prepared SQL statement.
 
1086
 
 
1087
    @todo
 
1088
 
 
1089
    Move this to Statement::~Statement
 
1090
  */
 
1091
  void end_statement();
 
1092
  inline int killed_errno() const
 
1093
  {
 
1094
    killed_state killed_val; /* to cache the volatile 'killed' */
 
1095
    return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0;
 
1096
  }
 
1097
  void send_kill_message() const;
 
1098
  /* return true if we will abort query if we make a warning now */
 
1099
  inline bool really_abort_on_warning()
 
1100
  {
 
1101
    return (abort_on_warning);
 
1102
  }
 
1103
  void set_status_var_init();
 
1104
  void reset_n_backup_open_tables_state(Open_tables_state *backup);
 
1105
  void restore_backup_open_tables_state(Open_tables_state *backup);
 
1106
 
 
1107
  /**
 
1108
    Set the current database; use deep copy of C-string.
 
1109
 
 
1110
    @param new_db     a pointer to the new database name.
 
1111
    @param new_db_len length of the new database name.
 
1112
 
 
1113
    Initialize the current database from a NULL-terminated string with
 
1114
    length. If we run out of memory, we free the current database and
 
1115
    return true.  This way the user will notice the error as there will be
 
1116
    no current database selected (in addition to the error message set by
 
1117
    malloc).
 
1118
 
 
1119
    @note This operation just sets {db, db_length}. Switching the current
 
1120
    database usually involves other actions, like switching other database
 
1121
    attributes including security context. In the future, this operation
 
1122
    will be made private and more convenient interface will be provided.
 
1123
 
 
1124
    @return Operation status
 
1125
      @retval false Success
 
1126
      @retval true  Out-of-memory error
 
1127
  */
 
1128
  bool set_db(const char *new_db, size_t new_db_len);
 
1129
 
 
1130
  /*
 
1131
    Copy the current database to the argument. Use the current arena to
 
1132
    allocate memory for a deep copy: current database may be freed after
 
1133
    a statement is parsed but before it's executed.
 
1134
  */
 
1135
  bool copy_db_to(char **p_db, size_t *p_db_length);
 
1136
 
 
1137
public:
 
1138
  /**
 
1139
    Add an internal error handler to the thread execution context.
 
1140
    @param handler the exception handler to add
 
1141
  */
 
1142
  void push_internal_handler(Internal_error_handler *handler);
 
1143
 
 
1144
  /**
 
1145
    Handle an error condition.
 
1146
    @param sql_errno the error number
 
1147
    @param level the error level
 
1148
    @return true if the error is handled
 
1149
  */
 
1150
  virtual bool handle_error(uint32_t sql_errno, const char *message,
 
1151
                            DRIZZLE_ERROR::enum_warning_level level);
 
1152
 
 
1153
  /**
 
1154
    Remove the error handler last pushed.
 
1155
  */
 
1156
  void pop_internal_handler();
 
1157
 
 
1158
  /**
 
1159
    Resets Session part responsible for command processing state.
 
1160
 
 
1161
    This needs to be called before execution of every statement
 
1162
    (prepared or conventional).
 
1163
    It is not called by substatements of routines.
 
1164
 
 
1165
    @todo
 
1166
    Make it a method of Session and align its name with the rest of
 
1167
    reset/end/start/init methods.
 
1168
    @todo
 
1169
    Call it after we use Session for queries, not before.
 
1170
  */
 
1171
  void reset_for_next_command();
 
1172
 
 
1173
  /**
 
1174
   * Disconnects the session from a client connection and
 
1175
   * updates any status variables necessary.
 
1176
   *
 
1177
   * @param errcode     Error code to print to console
 
1178
   * @param should_lock 1 if we have have to lock LOCK_thread_count
 
1179
   *
 
1180
   * @note  For the connection that is doing shutdown, this is called twice
 
1181
   */
 
1182
  void disconnect(uint32_t errcode, bool lock);
 
1183
 
 
1184
  /**
 
1185
   * Check if user exists and the password supplied is correct.
 
1186
   *
 
1187
   * Returns true on success, and false on failure.
 
1188
   *
 
1189
   * @note Host, user and passwd may point to communication buffer.
 
1190
   * Current implementation does not depend on that, but future changes
 
1191
   * should be done with this in mind; 
 
1192
   *
 
1193
   * @param  Scrambled password received from client
 
1194
   * @param  Length of scrambled password
 
1195
   * @param  Database name to connect to, may be NULL
 
1196
   */
 
1197
  bool checkUser(const char *passwd, uint32_t passwd_len, const char *db);
 
1198
  
 
1199
  /**
 
1200
   * Returns the timestamp (in microseconds) of when the Session 
 
1201
   * connected to the server.
 
1202
   */
 
1203
  inline uint64_t getConnectMicroseconds() const
 
1204
  {
 
1205
    return connect_microseconds;
 
1206
  }
 
1207
 
 
1208
  /**
 
1209
   * Returns a pointer to the active Transaction message for this
 
1210
   * Session being managed by the ReplicationServices component, or
 
1211
   * NULL if no active message.
 
1212
   */
 
1213
  message::Transaction *getTransactionMessage() const
 
1214
  {
 
1215
    return transaction_message;
 
1216
  }
 
1217
 
 
1218
  /**
 
1219
   * Returns a pointer to the active Statement message for this
 
1220
   * Session, or NULL if no active message.
 
1221
   */
 
1222
  message::Statement *getStatementMessage() const
 
1223
  {
 
1224
    return statement_message;
 
1225
  }
 
1226
 
 
1227
  /**
 
1228
   * Sets the active transaction message used by the ReplicationServices
 
1229
   * component.
 
1230
   *
 
1231
   * @param[in] Pointer to the message
 
1232
   */
 
1233
  void setTransactionMessage(message::Transaction *in_message)
 
1234
  {
 
1235
    transaction_message= in_message;
 
1236
  }
 
1237
 
 
1238
  /**
 
1239
   * Sets the active statement message used by the ReplicationServices
 
1240
   * component.
 
1241
   *
 
1242
   * @param[in] Pointer to the message
 
1243
   */
 
1244
  void setStatementMessage(message::Statement *in_message)
 
1245
  {
 
1246
    statement_message= in_message;
 
1247
  }
 
1248
private:
 
1249
  /** Pointers to memory managed by the ReplicationServices component */
 
1250
  message::Transaction *transaction_message;
 
1251
  message::Statement *statement_message;
 
1252
  /** Microsecond timestamp of when Session connected */
 
1253
  uint64_t connect_microseconds;
 
1254
  const char *proc_info;
 
1255
 
 
1256
  /** The current internal error handler for this thread, or NULL. */
 
1257
  Internal_error_handler *m_internal_handler;
 
1258
  /**
 
1259
    The lex to hold the parsed tree of conventional (non-prepared) queries.
 
1260
    Whereas for prepared and stored procedure statements we use an own lex
 
1261
    instance for each new query, for conventional statements we reuse
 
1262
    the same lex. (@see mysql_parse for details).
 
1263
  */
 
1264
  LEX main_lex;
 
1265
  /**
 
1266
    This memory root is used for two purposes:
 
1267
    - for conventional queries, to allocate structures stored in main_lex
 
1268
    during parsing, and allocate runtime data (execution plan, etc.)
 
1269
    during execution.
 
1270
    - for prepared queries, only to allocate runtime data. The parsed
 
1271
    tree itself is reused between executions and thus is stored elsewhere.
 
1272
  */
 
1273
  memory::Root main_mem_root;
 
1274
 
 
1275
  /**
 
1276
   * Marks all tables in the list which were used by current substatement
 
1277
   * as free for reuse.
 
1278
   *
 
1279
   * @param Head of the list of tables
 
1280
   *
 
1281
   * @note
 
1282
   *
 
1283
   * The reason we reset query_id is that it's not enough to just test
 
1284
   * if table->query_id != session->query_id to know if a table is in use.
 
1285
   *
 
1286
   * For example
 
1287
   * 
 
1288
   *  SELECT f1_that_uses_t1() FROM t1;
 
1289
   *  
 
1290
   * In f1_that_uses_t1() we will see one instance of t1 where query_id is
 
1291
   * set to query_id of original query.
 
1292
   */
 
1293
  void mark_used_tables_as_free_for_reuse(Table *table);
 
1294
  /**
 
1295
    Mark all temporary tables which were used by the current statement or
 
1296
    substatement as free for reuse, but only if the query_id can be cleared.
 
1297
 
 
1298
    @param session thread context
 
1299
 
 
1300
    @remark For temp tables associated with a open SQL HANDLER the query_id
 
1301
            is not reset until the HANDLER is closed.
 
1302
  */
 
1303
  void mark_temp_tables_as_free_for_reuse();
 
1304
 
 
1305
public:
 
1306
 
 
1307
  /** A short cut for session->main_da.set_ok_status(). */
 
1308
  inline void my_ok(ha_rows affected_rows= 0, ha_rows found_rows_arg= 0,
 
1309
                    uint64_t passed_id= 0, const char *message= NULL)
 
1310
  {
 
1311
    main_da.set_ok_status(this, affected_rows, found_rows_arg, passed_id, message);
 
1312
  }
 
1313
 
 
1314
 
 
1315
  /** A short cut for session->main_da.set_eof_status(). */
 
1316
 
 
1317
  inline void my_eof()
 
1318
  {
 
1319
    main_da.set_eof_status(this);
 
1320
  }
 
1321
 
 
1322
  /* Some inline functions for more speed */
 
1323
 
 
1324
  inline bool add_item_to_list(Item *item)
 
1325
  {
 
1326
    return lex->current_select->add_item_to_list(this, item);
 
1327
  }
 
1328
 
 
1329
  inline bool add_value_to_list(Item *value)
 
1330
  {
 
1331
    return lex->value_list.push_back(value);
 
1332
  }
 
1333
 
 
1334
  inline bool add_order_to_list(Item *item, bool asc)
 
1335
  {
 
1336
    return lex->current_select->add_order_to_list(this, item, asc);
 
1337
  }
 
1338
 
 
1339
  inline bool add_group_to_list(Item *item, bool asc)
 
1340
  {
 
1341
    return lex->current_select->add_group_to_list(this, item, asc);
 
1342
  }
 
1343
  void refresh_status();
 
1344
  user_var_entry *getVariable(LEX_STRING &name, bool create_if_not_exists);
 
1345
  
 
1346
  /**
 
1347
   * Closes all tables used by the current substatement, or all tables
 
1348
   * used by this thread if we are on the upper level.
 
1349
   */
 
1350
  void close_thread_tables();
 
1351
  void close_old_data_files(bool morph_locks= false,
 
1352
                            bool send_refresh= false);
 
1353
  void close_open_tables();
 
1354
  void close_data_files_and_morph_locks(const char *db, const char *table_name);
 
1355
 
 
1356
private:
 
1357
  bool free_cached_table();
 
1358
public:
 
1359
 
 
1360
  /**
 
1361
   * Prepares statement for reopening of tables and recalculation of set of
 
1362
   * prelocked tables.
 
1363
   *
 
1364
   * @param Pointer to a pointer to a list of tables which we were trying to open and lock
 
1365
   */
 
1366
  void close_tables_for_reopen(TableList **tables);
 
1367
 
 
1368
 
 
1369
  /**
 
1370
   * Open all tables in list, locks them (all, including derived)
 
1371
   *
 
1372
   * @param Pointer to a list of tables for open & locking
 
1373
   *
 
1374
   * @retval
 
1375
   *  false - ok
 
1376
   * @retval
 
1377
   *  true  - error
 
1378
   *
 
1379
   * @note
 
1380
   * 
 
1381
   * The lock will automaticaly be freed by close_thread_tables()
 
1382
   */
 
1383
  bool openTablesLock(TableList *tables);
 
1384
 
 
1385
  /**
 
1386
   * Open all tables in list and process derived tables
 
1387
   *
 
1388
   * @param Pointer to a list of tables for open
 
1389
   * @param Bitmap of flags to modify how the tables will be open:
 
1390
   *        DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
 
1391
   *        done a flush or namelock on it.
 
1392
   *
 
1393
   * @retval
 
1394
   *  false - ok
 
1395
   * @retval
 
1396
   *  true  - error
 
1397
   *
 
1398
   * @note
 
1399
   *
 
1400
   * This is to be used on prepare stage when you don't read any
 
1401
   * data from the tables.
 
1402
   */
 
1403
  bool openTables(TableList *tables, uint32_t flags= 0);
 
1404
 
 
1405
  int open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags= 0);
 
1406
 
 
1407
  Table *openTableLock(TableList *table_list, thr_lock_type lock_type);
 
1408
  Table *openTable(TableList *table_list, bool *refresh, uint32_t flags= 0);
 
1409
 
 
1410
  void unlink_open_table(Table *find);
 
1411
  void drop_open_table(Table *table, const char *db_name,
 
1412
                       const char *table_name);
 
1413
  void close_cached_table(Table *table);
 
1414
 
 
1415
  /* Create a lock in the cache */
 
1416
  Table *table_cache_insert_placeholder(const char *key, uint32_t key_length);
 
1417
  bool lock_table_name_if_not_cached(const char *db,
 
1418
                                     const char *table_name, Table **table);
 
1419
 
 
1420
  /* Work with temporary tables */
 
1421
  Table *find_temporary_table(TableList *table_list);
 
1422
  Table *find_temporary_table(const char *db, const char *table_name);
 
1423
  void doGetTableNames(CachedDirectory &directory,
 
1424
                       const std::string& db_name,
 
1425
                       std::set<std::string>& set_of_names);
 
1426
  int doGetTableDefinition(const char *path,
 
1427
                           const char *db,
 
1428
                           const char *table_name,
 
1429
                           const bool is_tmp,
 
1430
                           message::Table *table_proto);
 
1431
 
 
1432
  void close_temporary_tables();
 
1433
  void close_temporary_table(Table *table);
 
1434
  // The method below just handles the de-allocation of the table. In
 
1435
  // a better memory type world, this would not be needed.
 
1436
private:
 
1437
  void close_temporary(Table *table);
 
1438
public:
 
1439
 
 
1440
  int drop_temporary_table(TableList *table_list);
 
1441
  bool rm_temporary_table(plugin::StorageEngine *base, const char *path);
 
1442
  bool rm_temporary_table(TableIdentifier &identifier);
 
1443
  Table *open_temporary_table(TableIdentifier &identifier,
 
1444
                              bool link_in_list= true);
 
1445
 
 
1446
  /* Reopen operations */
 
1447
  bool reopen_tables(bool get_locks, bool mark_share_as_old);
 
1448
  bool reopen_name_locked_table(TableList* table_list, bool link_in);
 
1449
  bool close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders);
 
1450
 
 
1451
  void wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond);
 
1452
  int setup_conds(TableList *leaves, COND **conds);
 
1453
  int lock_tables(TableList *tables, uint32_t count, bool *need_reopen);
 
1454
 
 
1455
 
 
1456
  /**
 
1457
    Return the default storage engine
 
1458
 
 
1459
    @param getDefaultStorageEngine()
 
1460
 
 
1461
    @return
 
1462
    pointer to plugin::StorageEngine
 
1463
  */
 
1464
  plugin::StorageEngine *getDefaultStorageEngine()
 
1465
  {
 
1466
    if (variables.storage_engine)
 
1467
      return variables.storage_engine;
 
1468
    return global_system_variables.storage_engine;
 
1469
  };
 
1470
 
 
1471
  static void unlink(Session *session);
 
1472
 
 
1473
};
 
1474
 
 
1475
class JOIN;
 
1476
 
 
1477
#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
 
1478
 
 
1479
} /* namespace drizzled */
 
1480
 
 
1481
/** @TODO why is this in the middle of the file */
 
1482
#include <drizzled/select_to_file.h>
 
1483
#include <drizzled/select_export.h>
 
1484
#include <drizzled/select_dump.h>
 
1485
#include <drizzled/select_insert.h>
 
1486
#include <drizzled/select_create.h>
 
1487
#include <drizzled/tmp_table_param.h>
 
1488
#include <drizzled/select_union.h>
 
1489
#include <drizzled/select_subselect.h>
 
1490
#include <drizzled/select_singlerow_subselect.h>
 
1491
#include <drizzled/select_max_min_finder_subselect.h>
 
1492
#include <drizzled/select_exists_subselect.h>
 
1493
 
 
1494
namespace drizzled
 
1495
{
 
1496
 
 
1497
/**
 
1498
 * A structure used to describe sort information
 
1499
 * for a field or item used in ORDER BY.
 
1500
 */
 
1501
typedef struct st_sort_field 
 
1502
{
 
1503
  Field *field; /**< Field to sort */
 
1504
  Item  *item; /**< Item if not sorting fields */
 
1505
  size_t length; /**< Length of sort field */
 
1506
  uint32_t suffix_length; /**< Length suffix (0-4) */
 
1507
  Item_result result_type; /**< Type of item */
 
1508
  bool reverse; /**< if descending sort */
 
1509
  bool need_strxnfrm;   /**< If we have to use strxnfrm() */
 
1510
} SORT_FIELD;
 
1511
 
 
1512
typedef struct st_sort_buffer 
 
1513
{
 
1514
  uint32_t index;       /* 0 or 1 */
 
1515
  uint32_t sort_orders;
 
1516
  uint32_t change_pos; /* If sort-fields changed */
 
1517
  char **buff;
 
1518
  SORT_FIELD *sortorder;
 
1519
} SORT_BUFFER;
 
1520
 
 
1521
} /* namespace drizzled */
 
1522
 
 
1523
/** @TODO why is this in the middle of the file */
 
1524
 
 
1525
#include <drizzled/table_ident.h>
 
1526
#include <drizzled/user_var_entry.h>
 
1527
#include <drizzled/unique.h>
 
1528
#include <drizzled/my_var.h>
 
1529
#include <drizzled/select_dumpvar.h>
 
1530
 
 
1531
namespace drizzled
 
1532
{
 
1533
 
 
1534
/* Bits in sql_command_flags */
 
1535
 
 
1536
enum sql_command_flag_bits 
 
1537
{
 
1538
  CF_BIT_CHANGES_DATA,
 
1539
  CF_BIT_HAS_ROW_COUNT,
 
1540
  CF_BIT_STATUS_COMMAND,
 
1541
  CF_BIT_SHOW_TABLE_COMMAND,
 
1542
  CF_BIT_WRITE_LOGS_COMMAND,
 
1543
  CF_BIT_SIZE
 
1544
};
 
1545
 
 
1546
static const std::bitset<CF_BIT_SIZE> CF_CHANGES_DATA(1 << CF_BIT_CHANGES_DATA);
 
1547
static const std::bitset<CF_BIT_SIZE> CF_HAS_ROW_COUNT(1 << CF_BIT_HAS_ROW_COUNT);
 
1548
static const std::bitset<CF_BIT_SIZE> CF_STATUS_COMMAND(1 << CF_BIT_STATUS_COMMAND);
 
1549
static const std::bitset<CF_BIT_SIZE> CF_SHOW_TABLE_COMMAND(1 << CF_BIT_SHOW_TABLE_COMMAND);
 
1550
static const std::bitset<CF_BIT_SIZE> CF_WRITE_LOGS_COMMAND(1 << CF_BIT_WRITE_LOGS_COMMAND);
 
1551
 
 
1552
/* Functions in sql_class.cc */
 
1553
void add_to_status(system_status_var *to_var, system_status_var *from_var);
 
1554
 
 
1555
void add_diff_to_status(system_status_var *to_var, system_status_var *from_var,
 
1556
                        system_status_var *dec_var);
 
1557
 
 
1558
} /* namespace drizzled */
 
1559
 
 
1560
#endif /* DRIZZLED_SESSION_H */