~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/session.h

  • Committer: Monty Taylor
  • Date: 2009-04-25 20:45:19 UTC
  • mto: (997.2.5 mordred)
  • mto: This revision was merged to the branch mainline in revision 1003.
  • Revision ID: mordred@inaugust.com-20090425204519-lgrl7mz2r66v0jby
Blackhole.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
 
24
24
/* Classes in mysql */
25
25
 
26
 
#include "drizzled/plugin.h"
 
26
#include <drizzled/protocol.h>
27
27
#include <drizzled/sql_locale.h>
28
 
#include "drizzled/resource_context.h"
29
 
#include <drizzled/cursor.h>
 
28
#include <drizzled/ha_trx_info.h>
 
29
#include <mysys/my_tree.h>
 
30
#include <drizzled/handler.h>
30
31
#include <drizzled/current_session.h>
31
32
#include <drizzled/sql_error.h>
 
33
#include <drizzled/query_arena.h>
32
34
#include <drizzled/file_exchange.h>
33
35
#include <drizzled/select_result_interceptor.h>
 
36
#include <drizzled/authentication.h>
 
37
#include <drizzled/db.h>
34
38
#include <drizzled/xid.h>
35
 
#include "drizzled/query_id.h"
36
 
#include "drizzled/named_savepoint.h"
37
 
#include "drizzled/transaction_context.h"
38
39
 
39
40
#include <netdb.h>
40
 
#include <map>
41
41
#include <string>
42
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
43
 
53
44
#define MIN_HANDSHAKE_SIZE      6
54
45
 
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
46
class Lex_input_stream;
74
47
class user_var_entry;
75
 
class CopyField;
 
48
class Copy_field;
76
49
class Table_ident;
77
50
 
78
51
extern char internal_table_name[2];
83
56
#define TC_HEURISTIC_RECOVER_ROLLBACK 2
84
57
extern uint32_t tc_heuristic_recover;
85
58
 
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
 
/**
 
59
/*
95
60
  The COPY_INFO structure is used by INSERT/REPLACE code.
96
61
  The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
97
62
  UPDATE code:
103
68
      of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
104
69
      was actually changed or not.
105
70
*/
106
 
typedef struct st_copy_info 
107
 
{
 
71
typedef struct st_copy_info {
108
72
  ha_rows records; /**< Number of processed records */
109
73
  ha_rows deleted; /**< Number of deleted records */
110
74
  ha_rows updated; /**< Number of updated records */
120
84
  /* for VIEW ... WITH CHECK OPTION */
121
85
} COPY_INFO;
122
86
 
 
87
 
123
88
typedef struct drizzled_lock_st
124
89
{
125
90
  Table **table;
126
 
  uint32_t table_count;
127
 
  uint32_t lock_count;
 
91
  uint32_t table_count,lock_count;
128
92
  THR_LOCK_DATA **locks;
129
93
} DRIZZLE_LOCK;
130
94
 
131
 
} /* namespace drizzled */
132
95
 
133
 
/** @TODO why is this in the middle of the file */
134
96
#include <drizzled/lex_column.h>
135
97
 
136
 
namespace drizzled
137
 
{
138
 
 
139
98
class select_result;
140
99
class Time_zone;
141
100
 
142
101
#define Session_SENTRY_MAGIC 0xfeedd1ff
143
102
#define Session_SENTRY_GONE  0xdeadbeef
144
103
 
 
104
#define Session_CHECK_SENTRY(session) assert(session->dbug_sentry == Session_SENTRY_MAGIC)
 
105
 
145
106
struct system_variables
146
107
{
147
108
  system_variables() {};
155
116
    neccessary and bytes copied from global to make up for missing data.
156
117
  */
157
118
  ulong dynamic_variables_version;
158
 
  char * dynamic_variables_ptr;
 
119
  char* dynamic_variables_ptr;
159
120
  uint32_t dynamic_variables_head;  /* largest valid variable offset */
160
121
  uint32_t dynamic_variables_size;  /* how many bytes are in use */
161
122
 
172
133
  uint64_t max_error_count;
173
134
  uint64_t max_length_for_sort_data;
174
135
  size_t max_sort_length;
 
136
  uint64_t max_tmp_tables;
175
137
  uint64_t min_examined_row_limit;
 
138
  uint32_t myisam_stats_method;
 
139
  uint32_t net_buffer_length;
 
140
  uint32_t net_read_timeout;
 
141
  uint32_t net_retry_count;
 
142
  uint32_t net_wait_timeout;
 
143
  uint32_t net_write_timeout;
176
144
  bool optimizer_prune_level;
177
 
  bool log_warnings;
178
 
 
179
145
  uint32_t optimizer_search_depth;
180
 
  uint32_t div_precincrement;
 
146
  /*
 
147
    Controls use of Engine-MRR:
 
148
      0 - auto, based on cost
 
149
      1 - force MRR when the storage engine is capable of doing it
 
150
      2 - disable MRR.
 
151
  */
 
152
  uint32_t optimizer_use_mrr;
 
153
  /* A bitmap for switching optimizations on/off */
 
154
  uint32_t optimizer_switch;
181
155
  uint64_t preload_buff_size;
182
156
  uint32_t read_buff_size;
183
157
  uint32_t read_rnd_buff_size;
 
158
  uint32_t div_precincrement;
184
159
  size_t sortbuff_size;
185
160
  uint32_t thread_handling;
186
161
  uint32_t tx_isolation;
191
166
  size_t range_alloc_block_size;
192
167
  uint32_t query_alloc_block_size;
193
168
  uint32_t query_prealloc_size;
 
169
  uint32_t trans_alloc_block_size;
 
170
  uint32_t trans_prealloc_size;
 
171
  bool log_warnings;
194
172
  uint64_t group_concat_max_len;
 
173
  /* TODO: change this to my_thread_id - but have to fix set_var first */
195
174
  uint64_t pseudo_thread_id;
196
175
 
197
 
  plugin::StorageEngine *storage_engine;
 
176
  bool low_priority_updates;
 
177
  bool new_mode;
 
178
  /*
 
179
    compatibility option:
 
180
      - index usage hints (USE INDEX without a FOR clause) behave as in 5.0
 
181
  */
 
182
  bool old_mode;
 
183
  bool engine_condition_pushdown;
 
184
  bool keep_files_on_create;
 
185
 
 
186
  bool old_alter_table;
 
187
 
 
188
  StorageEngine *storage_engine;
198
189
 
199
190
  /* Only charset part of these variables is sensible */
200
191
  const CHARSET_INFO  *character_set_filesystem;
201
192
 
202
193
  /* Both charset and collation parts of these variables are important */
203
194
  const CHARSET_INFO    *collation_server;
 
195
  const CHARSET_INFO    *collation_database;
204
196
 
205
197
  inline const CHARSET_INFO  *getCollation(void) 
206
198
  {
207
 
    return collation_server;
 
199
    return collation_database ? collation_database : collation_server;
208
200
  }
209
201
 
210
202
  /* Locale Support */
215
207
 
216
208
extern struct system_variables global_system_variables;
217
209
 
218
 
} /* namespace drizzled */
219
 
 
220
 
#include "drizzled/sql_lex.h"
221
 
 
222
 
namespace drizzled
223
 
{
224
 
 
225
 
/**
226
 
 * Per-session local status counters
227
 
 */
 
210
#include "sql_lex.h"  /* only for SQLCOM_END */
 
211
 
 
212
/* per thread status variables */
 
213
 
228
214
typedef struct system_status_var
229
215
{
230
216
  uint64_t bytes_received;
259
245
  /* END OF KEY_CACHE parts */
260
246
 
261
247
  ulong net_big_packet_count;
 
248
  ulong opened_tables;
 
249
  ulong opened_shares;
262
250
  ulong select_full_join_count;
263
251
  ulong select_full_range_join_count;
264
252
  ulong select_range_count;
282
270
    sense to add to the /global/ status variable counter.
283
271
  */
284
272
  double last_query_cost;
285
 
} system_status_var;
 
273
 
 
274
 
 
275
} STATUS_VAR;
286
276
 
287
277
/*
288
278
  This is used for 'SHOW STATUS'. It must be updated to the last ulong
294
284
 
295
285
void mark_transaction_to_rollback(Session *session, bool all);
296
286
 
297
 
extern pthread_mutex_t LOCK_xid_cache;
298
 
extern HASH xid_cache;
299
 
 
300
 
 
301
287
/**
302
 
  Storage engine specific thread local data.
 
288
  @class Statement
 
289
  @brief State of a single command executed against this connection.
 
290
 
 
291
  One connection can contain a lot of simultaneously running statements,
 
292
  some of which could be:
 
293
   - prepared, that is, contain placeholders,
 
294
  To perform some action with statement we reset Session part to the state  of
 
295
  that statement, do the action, and then save back modified state from Session
 
296
  to the statement. It will be changed in near future, and Statement will
 
297
  be used explicitly.
303
298
*/
304
 
struct Ha_data
 
299
 
 
300
class Statement: public ilink, public Query_arena
305
301
{
306
 
  /**
307
 
    Storage engine specific thread local data.
308
 
    Lifetime: one user connection.
 
302
  Statement(const Statement &rhs);              /* not implemented: */
 
303
  Statement &operator=(const Statement &rhs);   /* non-copyable */
 
304
public:
 
305
  /*
 
306
    Uniquely identifies each statement object in thread scope; change during
 
307
    statement lifetime. FIXME: must be const
309
308
  */
310
 
  void *ha_ptr;
311
 
  /**
312
 
   * Resource contexts for both the "statement" and "normal"
313
 
   * transactions.
314
 
   *
315
 
   * Resource context at index 0:
316
 
   *
317
 
   * Life time: one statement within a transaction. If @@autocommit is
318
 
   * on, also represents the entire transaction.
319
 
   *
320
 
   * Resource context at index 1:
321
 
   *
322
 
   * Life time: one transaction within a connection. 
323
 
   *
324
 
   * @note
325
 
   *
326
 
   * If the storage engine does not participate in a transaction, 
327
 
   * there will not be a resource context.
328
 
   */
329
 
  drizzled::ResourceContext resource_context[2];
330
 
 
331
 
  Ha_data() :ha_ptr(NULL) {}
332
 
};
333
 
 
334
 
/**
335
 
 * Represents a client connection to the database server.
336
 
 *
337
 
 * Contains the client/server protocol object, the current statement
338
 
 * being executed, local-to-session variables and status counters, and
339
 
 * a host of other information.
340
 
 *
341
 
 * @todo
342
 
 *
343
 
 * The Session class should have a vector of Statement object pointers which
344
 
 * comprise the statements executed on the Session. Until this architectural
345
 
 * change is done, we can forget about parallel operations inside a session.
346
 
 *
347
 
 * @todo
348
 
 *
349
 
 * Make member variables private and have inlined accessors and setters.  Hide
350
 
 * all member variables that are not critical to non-internal operations of the
351
 
 * session object.
352
 
 */
353
 
class Session : public Open_tables_state
354
 
{
355
 
public:
 
309
   ulong id;
 
310
 
356
311
  /*
357
312
    MARK_COLUMNS_NONE:  Means mark_used_colums is not set and no indicator to
358
313
                        handler of fields used is set
365
320
                        and update_row.
366
321
  */
367
322
  enum enum_mark_columns mark_used_columns;
368
 
  inline void* alloc(size_t size)
369
 
  {
370
 
    return alloc_root(mem_root,size);
371
 
  }
372
 
  inline void* calloc(size_t size)
373
 
  {
374
 
    void *ptr;
375
 
    if ((ptr= alloc_root(mem_root,size)))
376
 
      memset(ptr, 0, size);
377
 
    return ptr;
378
 
  }
379
 
  inline char *strdup(const char *str)
380
 
  {
381
 
    return strdup_root(mem_root,str);
382
 
  }
383
 
  inline char *strmake(const char *str, size_t size)
384
 
  {
385
 
    return strmake_root(mem_root,str,size);
386
 
  }
387
 
  inline void *memdup(const void *str, size_t size)
388
 
  {
389
 
    return memdup_root(mem_root,str,size);
390
 
  }
391
 
  inline void *memdup_w_gap(const void *str, size_t size, uint32_t gap)
392
 
  {
393
 
    void *ptr;
394
 
    if ((ptr= alloc_root(mem_root,size+gap)))
395
 
      memcpy(ptr,str,size);
396
 
    return ptr;
397
 
  }
398
 
  /** Frees all items attached to this Statement */
399
 
  void free_items();
400
 
  /**
401
 
   * List of items created in the parser for this query. Every item puts
402
 
   * itself to the list on creation (see Item::Item() for details))
403
 
   */
404
 
  Item *free_list;
405
 
  memory::Root *mem_root; /**< Pointer to current memroot */
406
 
  /**
407
 
   * Uniquely identifies each statement object in thread scope; change during
408
 
   * statement lifetime.
409
 
   *
410
 
   * @todo should be const
411
 
   */
412
 
  uint32_t id;
413
 
  LEX *lex; /**< parse tree descriptor */
414
 
  /** query associated with this statement */
415
 
  std::string query;
 
323
 
 
324
  LEX *lex;                                     // parse tree descriptor
 
325
  /*
 
326
    Points to the query associated with this statement. It's const, but
 
327
    we need to declare it char * because all table handlers are written
 
328
    in C and need to point to it.
 
329
 
 
330
    Note that (A) if we set query = NULL, we must at the same time set
 
331
    query_length = 0, and protect the whole operation with the
 
332
    LOCK_thread_count mutex. And (B) we are ONLY allowed to set query to a
 
333
    non-NULL value if its previous value is NULL. We do not need to protect
 
334
    operation (B) with any mutex. To avoid crashes in races, if we do not
 
335
    know that session->query cannot change at the moment, one should print
 
336
    session->query like this:
 
337
      (1) reserve the LOCK_thread_count mutex;
 
338
      (2) check if session->query is NULL;
 
339
      (3) if not NULL, then print at most session->query_length characters from
 
340
      it. We will see the query_length field as either 0, or the right value
 
341
      for it.
 
342
    Assuming that the write and read of an n-bit memory field in an n-bit
 
343
    computer is atomic, we can avoid races in the above way.
 
344
    This printing is needed at least in SHOW PROCESSLIST and SHOW INNODB
 
345
    STATUS.
 
346
  */
 
347
  char *query;
 
348
  uint32_t query_length;                          // current query length
416
349
 
417
350
  /**
418
351
    Name of the current (default) database.
426
359
    the Session of that thread); that thread is (and must remain, for now) the
427
360
    only responsible for freeing this member.
428
361
  */
429
 
  std::string db;
430
 
 
431
 
  /**
 
362
 
 
363
  char *db;
 
364
  uint32_t db_length;
 
365
 
 
366
public:
 
367
 
 
368
  /* This constructor is called for backup statements */
 
369
  Statement() {}
 
370
 
 
371
  Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg, ulong id_arg);
 
372
  ~Statement() {}
 
373
};
 
374
 
 
375
struct st_savepoint {
 
376
  struct st_savepoint *prev;
 
377
  char                *name;
 
378
  uint32_t                 length;
 
379
  Ha_trx_info         *ha_list;
 
380
};
 
381
 
 
382
extern pthread_mutex_t LOCK_xid_cache;
 
383
extern HASH xid_cache;
 
384
 
 
385
#include <drizzled/security_context.h>
 
386
#include <drizzled/open_tables_state.h>
 
387
 
 
388
#include <drizzled/internal_error_handler.h> 
 
389
#include <drizzled/diagnostics_area.h> 
 
390
 
 
391
/**
 
392
  Storage engine specific thread local data.
 
393
*/
 
394
struct Ha_data
 
395
{
 
396
  /**
 
397
    Storage engine specific thread local data.
 
398
    Lifetime: one user connection.
 
399
  */
 
400
  void *ha_ptr;
 
401
  /**
 
402
    0: Life time: one statement within a transaction. If @@autocommit is
 
403
    on, also represents the entire transaction.
 
404
    @sa trans_register_ha()
 
405
 
 
406
    1: Life time: one transaction within a connection.
 
407
    If the storage engine does not participate in a transaction,
 
408
    this should not be used.
 
409
    @sa trans_register_ha()
 
410
  */
 
411
  Ha_trx_info ha_info[2];
 
412
 
 
413
  Ha_data() :ha_ptr(NULL) {}
 
414
};
 
415
 
 
416
class Session :public Statement, public Open_tables_state
 
417
{
 
418
public:
 
419
  /*
432
420
    Constant for Session::where initialization in the beginning of every query.
433
421
 
434
422
    It's needed because we do not save/restore Session::where normally during
436
424
  */
437
425
  static const char * const DEFAULT_WHERE;
438
426
 
439
 
  memory::Root warn_root; /**< Allocation area for warnings and errors */
440
 
  plugin::Client *client; /**< Pointer to client object */
441
 
  plugin::Scheduler *scheduler; /**< Pointer to scheduler object */
442
 
  void *scheduler_arg; /**< Pointer to the optional scheduler argument */
443
 
  HASH user_vars; /**< Hash of user variables defined during the session's lifetime */
444
 
  struct system_variables variables; /**< Mutable local variables local to the session */
445
 
  struct system_status_var status_var; /**< Session-local status counters */
446
 
  struct system_status_var *initial_status_var; /* used by show status */
447
 
  THR_LOCK_INFO lock_info; /**< Locking information for this session */
448
 
  THR_LOCK_OWNER main_lock_id; /**< To use for conventional queries */
449
 
  THR_LOCK_OWNER *lock_id; /**< If not main_lock_id, points to the lock_id of a cursor. */
450
 
  pthread_mutex_t LOCK_delete; /**< Locked before session is deleted */
451
 
 
452
 
  /**
453
 
   * A peek into the query string for the session. This is a best effort
454
 
   * delivery, there is no guarantee whether the content is meaningful.
455
 
   */
456
 
  char process_list_info[PROCESS_LIST_WIDTH+1];
457
 
 
458
 
  /**
459
 
   * A pointer to the stack frame of the scheduler thread
460
 
   * which is called first in the thread for handling a client
461
 
   */
462
 
  char *thread_stack;
463
 
 
464
 
private:
465
 
  SecurityContext security_ctx;
466
 
 
467
 
  inline void checkSentry() const
468
 
  {
469
 
    assert(this->dbug_sentry == Session_SENTRY_MAGIC);
470
 
  }
471
 
public:
472
 
  const SecurityContext& getSecurityContext() const
473
 
  {
474
 
    return security_ctx;
475
 
  }
476
 
 
477
 
  SecurityContext& getSecurityContext()
478
 
  {
479
 
    return security_ctx;
480
 
  }
481
 
 
482
 
  /**
483
 
   * Is this session viewable by the current user?
484
 
   */
485
 
  bool isViewable() const
486
 
  {
487
 
    return plugin::Authorization::isAuthorized(current_session->getSecurityContext(),
488
 
                                               this,
489
 
                                               false);
490
 
  }
491
 
 
492
 
  /**
 
427
  MEM_ROOT warn_root;                   // For warnings and errors
 
428
  Protocol *protocol;                   // Current protocol
 
429
  char    compression;
 
430
  HASH    user_vars;                    // hash for user variables
 
431
  String  packet;                       // dynamic buffer for network I/O
 
432
  String  convert_buffer;               // buffer for charset conversions
 
433
  struct  system_variables variables;   // Changeable local variables
 
434
  struct  system_status_var status_var; // Per thread statistic vars
 
435
  struct  system_status_var *initial_status_var; /* used by show status */
 
436
  THR_LOCK_INFO lock_info;              // Locking info of this thread
 
437
  THR_LOCK_OWNER main_lock_id;          // To use for conventional queries
 
438
  THR_LOCK_OWNER *lock_id;              // If not main_lock_id, points to
 
439
                                        // the lock_id of a cursor.
 
440
  pthread_mutex_t LOCK_delete;          // Locked before session is deleted
 
441
  char process_list_info[PROCESS_LIST_WIDTH];
 
442
  /*
 
443
    A pointer to the stack frame of handle_one_connection(),
 
444
    which is called first in the thread for handling a client
 
445
  */
 
446
  char    *thread_stack;
 
447
 
 
448
  /**
 
449
    Currently selected catalog.
 
450
  */
 
451
  char *catalog;
 
452
 
 
453
  /**
 
454
    @note
 
455
    Some members of Session (currently 'Statement::db',
 
456
    'catalog' and 'query')  are set and alloced by the slave SQL thread
 
457
    (for the Session of that thread); that thread is (and must remain, for now)
 
458
    the only responsible for freeing these 3 members. If you add members
 
459
    here, and you add code to set them in replication, don't forget to
 
460
    free_them_and_set_them_to_0 in replication properly. For details see
 
461
    the 'err:' label of the handle_slave_sql() in sql/slave.cc.
 
462
 
 
463
    @see handle_slave_sql
 
464
  */
 
465
 
 
466
  Security_context security_ctx;
 
467
 
 
468
  /*
 
469
    Points to info-string that we show in SHOW PROCESSLIST
 
470
    You are supposed to call Session_SET_PROC_INFO only if you have coded
 
471
    a time-consuming piece that MySQL can get stuck in for a long time.
 
472
 
 
473
    Set it using the  session_proc_info(Session *thread, const char *message)
 
474
    macro/function.
 
475
  */
 
476
  void        set_proc_info(const char *info) { proc_info= info; }
 
477
  const char* get_proc_info() const { return proc_info; }
 
478
 
 
479
  /*
493
480
    Used in error messages to tell user in what part of MySQL we found an
494
481
    error. E. g. when where= "having clause", if fix_fields() fails, user
495
482
    will know that the error was in having clause.
496
483
  */
497
484
  const char *where;
498
485
 
 
486
  double tmp_double_value;                    /* Used in set_var.cc */
 
487
  ulong client_capabilities;            /* What the client supports */
 
488
  ulong max_client_packet_length;
 
489
 
499
490
  /*
500
491
    One thread can hold up to one named user-level lock. This variable
501
492
    points to a lock object if the lock is present. See item_func.cc and
502
493
    chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
503
494
  */
504
 
  uint32_t dbug_sentry; /**< watch for memory corruption */
505
 
  internal::st_my_thread_var *mysys_var;
506
 
  /**
507
 
   * Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
508
 
   * first byte of the packet in executeStatement()
509
 
   */
 
495
  uint32_t dbug_sentry; // watch out for memory corruption
 
496
  struct st_my_thread_var *mysys_var;
 
497
  /*
 
498
    Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
 
499
    first byte of the packet in executeStatement()
 
500
  */
510
501
  enum enum_server_command command;
511
 
  uint32_t file_id;     /**< File ID for LOAD DATA INFILE */
512
 
  /* @note the following three members should likely move to Client */
513
 
  uint32_t max_client_packet_length; /**< Maximum number of bytes a client can send in a single packet */
514
 
  time_t start_time;
515
 
  time_t user_time;
516
 
  uint64_t thr_create_utime; /**< track down slow pthread_create */
517
 
  uint64_t start_utime;
518
 
  uint64_t utime_after_lock;
 
502
  uint32_t     file_id;                 // for LOAD DATA INFILE
 
503
  /* remote (peer) port */
 
504
  uint16_t peer_port;
 
505
  time_t     start_time, user_time;
 
506
  uint64_t  connect_utime, thr_create_utime; // track down slow pthread_create
 
507
  uint64_t  start_utime, utime_after_lock;
519
508
 
520
509
  thr_lock_type update_lock_default;
521
510
 
523
512
    Both of the following container points in session will be converted to an API.
524
513
  */
525
514
 
526
 
private:
527
515
  /* container for handler's private per-connection data */
528
 
  std::vector<Ha_data> ha_data;
529
 
  /*
530
 
    Id of current query. Statement can be reused to execute several queries
531
 
    query_id is global in context of the whole MySQL server.
532
 
    ID is automatically generated from an atomic counter.
533
 
    It's used in Cursor code for various purposes: to check which columns
534
 
    from table are necessary for this select, to check if it's necessary to
535
 
    update auto-updatable fields (like auto_increment and timestamp).
536
 
  */
537
 
  query_id_t query_id;
538
 
  query_id_t warn_query_id;
 
516
  Ha_data ha_data[MAX_HA];
 
517
 
 
518
  /* container for replication data */
 
519
  void *replication_data;
 
520
  inline void setReplicationData (void *data) { replication_data= data; }
 
521
  inline void *getReplicationData () { return replication_data; }
 
522
 
 
523
  /* Place to store various things */
 
524
  void *session_marker;
 
525
 
 
526
  /** Returns the current query ID */
 
527
  inline query_id_t getQueryId()  const
 
528
  {
 
529
    return query_id;
 
530
  }
 
531
 
 
532
  /** Returns the current query text */
 
533
  inline const char *getQueryString()  const
 
534
  {
 
535
    return query;
 
536
  }
 
537
 
 
538
  /** Returns the length of the current query text */
 
539
  inline size_t getQueryLength() const
 
540
  {
 
541
    return strlen(query);
 
542
  }
 
543
 
 
544
  /** Accessor method returning the server's ID. */
 
545
  inline uint32_t getServerId()  const
 
546
  {
 
547
    /* We return the global server ID. */
 
548
    return server_id;
 
549
  }
 
550
 
 
551
  /** Returns the current transaction ID for the session's current statement */
 
552
  inline my_xid getTransactionId()
 
553
  {
 
554
    return transaction.xid_state.xid.quick_get_my_xid();
 
555
  }
 
556
 
539
557
public:
540
 
  void **getEngineData(const plugin::MonitoredInTransaction *monitored);
541
 
  ResourceContext *getResourceContext(const plugin::MonitoredInTransaction *monitored,
542
 
                                      size_t index= 0);
543
558
 
544
559
  struct st_transactions {
545
 
    std::deque<NamedSavepoint> savepoints;
546
 
    TransactionContext all; ///< Trans since BEGIN WORK
547
 
    TransactionContext stmt; ///< Trans for current statement
 
560
    SAVEPOINT *savepoints;
 
561
    Session_TRANS all;                  // Trans since BEGIN WORK
 
562
    Session_TRANS stmt;                 // Trans for current statement
 
563
    bool on;                            // see ha_enable_transaction()
548
564
    XID_STATE xid_state;
549
565
 
 
566
    /*
 
567
       Tables changed in transaction (that must be invalidated in query cache).
 
568
       List contain only transactional tables, that not invalidated in query
 
569
       cache (instead of full list of changed in transaction tables).
 
570
    */
 
571
    CHANGED_TableList* changed_tables;
 
572
    MEM_ROOT mem_root; // Transaction-life memory allocation pool
550
573
    void cleanup()
551
574
    {
552
 
      savepoints.clear();
553
 
    }
554
 
    st_transactions() :
555
 
      savepoints(),
556
 
      all(),
557
 
      stmt(),
558
 
      xid_state()
559
 
    { }
 
575
      changed_tables= 0;
 
576
      savepoints= 0;
 
577
      free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
 
578
    }
 
579
    st_transactions()
 
580
    {
 
581
      memset(this, 0, sizeof(*this));
 
582
      xid_state.xid.null();
 
583
      init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
 
584
    }
560
585
  } transaction;
561
 
 
562
 
  Field *dup_field;
 
586
  Field      *dup_field;
563
587
  sigset_t signals;
564
588
 
565
589
  /* Tells if LAST_INSERT_ID(#) was called for the current statement */
568
592
    ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
569
593
    insertion into an auto_increment column".
570
594
  */
571
 
  /**
 
595
  /*
572
596
    This is the first autogenerated insert id which was *successfully*
573
597
    inserted by the previous statement (exactly, if the previous statement
574
598
    didn't successfully insert an autogenerated insert id, then it's the one
576
600
    It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
577
601
    It is returned by LAST_INSERT_ID().
578
602
  */
579
 
  uint64_t first_successful_insert_id_in_prev_stmt;
580
 
  /**
 
603
  uint64_t  first_successful_insert_id_in_prev_stmt;
 
604
  /*
581
605
    This is the first autogenerated insert id which was *successfully*
582
606
    inserted by the current statement. It is maintained only to set
583
607
    first_successful_insert_id_in_prev_stmt when statement ends.
584
608
  */
585
 
  uint64_t first_successful_insert_id_in_cur_stmt;
586
 
  /**
 
609
  uint64_t  first_successful_insert_id_in_cur_stmt;
 
610
  /*
587
611
    We follow this logic:
588
612
    - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
589
613
    first insert id successfully inserted by the previous stmt.
599
623
    non-empty.
600
624
    - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
601
625
    first_successful_insert_id_in_cur_stmt.
602
 
 
 
626
  */
 
627
  /*
603
628
    List of auto_increment intervals reserved by the thread so far, for
604
629
    storage in the statement-based binlog.
605
630
    Note that its minimum is not first_successful_insert_id_in_cur_stmt:
611
636
    in the binlog is still needed; the list's minimum will contain 3.
612
637
  */
613
638
  Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
614
 
  /** Used by replication and SET INSERT_ID */
 
639
  /* Used by replication and SET INSERT_ID */
615
640
  Discrete_intervals_list auto_inc_intervals_forced;
616
 
 
617
 
  uint64_t limit_found_rows;
618
 
  uint64_t options; /**< Bitmap of options */
619
 
  int64_t row_count_func; /**< For the ROW_COUNT() function */
620
 
  ha_rows cuted_fields; /**< Count of "cut" or truncated fields. @todo Kill this friggin thing. */
621
 
 
622
 
  /** 
623
 
   * Number of rows we actually sent to the client, including "synthetic"
624
 
   * rows in ROLLUP etc.
625
 
   */
626
 
  ha_rows sent_row_count;
627
 
 
628
 
  /**
629
 
   * Number of rows we read, sent or not, including in create_sort_index()
630
 
   */
631
 
  ha_rows examined_row_count;
632
 
 
633
 
  /**
634
 
   * The set of those tables whose fields are referenced in all subqueries
635
 
   * of the query.
636
 
   *
637
 
   * @todo
638
 
   * 
639
 
   * Possibly this it is incorrect to have used tables in Session because
640
 
   * with more than one subquery, it is not clear what does the field mean.
641
 
   */
642
 
  table_map used_tables;
643
 
 
644
 
  /**
645
 
    @todo
646
 
    
647
 
    This, and some other variables like 'count_cuted_fields'
648
 
    maybe should be statement/cursor local, that is, moved to Statement
649
 
    class. With current implementation warnings produced in each prepared
650
 
    statement/cursor settle here.
651
 
  */
652
 
  List<DRIZZLE_ERROR> warn_list;
653
 
  uint32_t warn_count[(uint32_t) DRIZZLE_ERROR::WARN_LEVEL_END];
654
 
  uint32_t total_warn_count;
655
 
  Diagnostics_area main_da;
656
 
 
657
 
  ulong col_access;
658
 
 
659
 
  /* Statement id is thread-wide. This counter is used to generate ids */
660
 
  uint32_t statement_id_counter;
661
 
  uint32_t rand_saved_seed1;
662
 
  uint32_t rand_saved_seed2;
663
 
  /**
664
 
    Row counter, mainly for errors and warnings. Not increased in
665
 
    create_sort_index(); may differ from examined_row_count.
666
 
  */
667
 
  uint32_t row_count;
668
 
  pthread_t real_id; /**< For debugging */
669
 
  uint64_t thread_id;
670
 
  uint32_t tmp_table;
671
 
  uint32_t global_read_lock;
672
 
  uint32_t server_status;
673
 
  uint32_t open_options;
674
 
  uint32_t select_number; /**< number of select (used for EXPLAIN) */
675
 
  /* variables.transaction_isolation is reset to this after each commit */
676
 
  enum_tx_isolation session_tx_isolation;
677
 
  enum_check_fields count_cuted_fields;
678
 
 
679
 
  enum killed_state
680
 
  {
681
 
    NOT_KILLED,
682
 
    KILL_BAD_DATA,
683
 
    KILL_CONNECTION,
684
 
    KILL_QUERY,
685
 
    KILLED_NO_VALUE /* means none of the above states apply */
686
 
  };
687
 
  killed_state volatile killed;
688
 
 
689
 
  bool some_tables_deleted;
690
 
  bool no_errors;
691
 
  bool password;
692
 
  /**
693
 
    Set to true if execution of the current compound statement
694
 
    can not continue. In particular, disables activation of
695
 
    CONTINUE or EXIT handlers of stored routines.
696
 
    Reset in the end of processing of the current user request, in
697
 
    @see mysql_reset_session_for_next_command().
698
 
  */
699
 
  bool is_fatal_error;
700
 
  /**
701
 
    Set by a storage engine to request the entire
702
 
    transaction (that possibly spans multiple engines) to
703
 
    rollback. Reset in ha_rollback.
704
 
  */
705
 
  bool transaction_rollback_request;
706
 
  /**
707
 
    true if we are in a sub-statement and the current error can
708
 
    not be safely recovered until we left the sub-statement mode.
709
 
    In particular, disables activation of CONTINUE and EXIT
710
 
    handlers inside sub-statements. E.g. if it is a deadlock
711
 
    error and requires a transaction-wide rollback, this flag is
712
 
    raised (traditionally, MySQL first has to close all the reads
713
 
    via @see handler::ha_index_or_rnd_end() and only then perform
714
 
    the rollback).
715
 
    Reset to false when we leave the sub-statement mode.
716
 
  */
717
 
  bool is_fatal_sub_stmt_error;
718
 
  /** for IS NULL => = last_insert_id() fix in remove_eq_conds() */
719
 
  bool substitute_null_with_insert_id;
720
 
  bool cleanup_done;
721
 
 
722
 
  bool abort_on_warning;
723
 
  bool got_warning; /**< Set on call to push_warning() */
724
 
  bool no_warnings_for_error; /**< no warnings on call to my_error() */
725
 
  /** set during loop of derived table processing */
726
 
  bool derived_tables_processing;
727
 
  bool tablespace_op; /**< This is true in DISCARD/IMPORT TABLESPACE */
728
 
 
729
 
  /** Used by the sys_var class to store temporary values */
730
 
  union
731
 
  {
732
 
    bool bool_value;
733
 
    uint32_t uint32_t_value;
734
 
    int32_t int32_t_value;
735
 
    uint64_t uint64_t_value;
736
 
  } sys_var_tmp;
737
 
 
738
 
  /**
739
 
    Character input stream consumed by the lexical analyser,
740
 
    used during parsing.
741
 
    Note that since the parser is not re-entrant, we keep only one input
742
 
    stream here. This member is valid only when executing code during parsing,
743
 
    and may point to invalid memory after that.
744
 
  */
745
 
  Lex_input_stream *m_lip;
746
 
  
747
 
  /** Place to store various things */
748
 
  void *session_marker;
749
 
 
750
 
  /** Keeps a copy of the previous table around in case we are just slamming on particular table */
751
 
  Table *cached_table;
752
 
 
753
 
  /**
754
 
    Points to info-string that we show in SHOW PROCESSLIST
755
 
    You are supposed to call Session_SET_PROC_INFO only if you have coded
756
 
    a time-consuming piece that MySQL can get stuck in for a long time.
757
 
 
758
 
    Set it using the  session_proc_info(Session *thread, const char *message)
759
 
    macro/function.
760
 
  */
761
 
  inline void set_proc_info(const char *info)
762
 
  { 
763
 
    proc_info= info;
764
 
  }
765
 
  inline const char* get_proc_info() const
766
 
  {
767
 
    return proc_info;
768
 
  }
769
 
 
770
 
  /** Sets this Session's current query ID */
771
 
  inline void setQueryId(query_id_t in_query_id)
772
 
  {
773
 
    query_id= in_query_id;
774
 
  }
775
 
 
776
 
  /** Returns the current query ID */
777
 
  inline query_id_t getQueryId()  const
778
 
  {
779
 
    return query_id;
780
 
  }
781
 
 
782
 
 
783
 
  /** Sets this Session's warning query ID */
784
 
  inline void setWarningQueryId(query_id_t in_query_id)
785
 
  {
786
 
    warn_query_id= in_query_id;
787
 
  }
788
 
 
789
 
  /** Returns the Session's warning query ID */
790
 
  inline query_id_t getWarningQueryId()  const
791
 
  {
792
 
    return warn_query_id;
793
 
  }
794
 
 
795
 
  /** Returns the current query text */
796
 
  inline const std::string &getQueryString()  const
797
 
  {
798
 
    return query;
799
 
  }
800
 
 
801
 
  /** Returns the length of the current query text */
802
 
  inline size_t getQueryLength() const
803
 
  {
804
 
    if (! query.empty())
805
 
      return query.length();
806
 
    else
807
 
      return 0;
808
 
  }
809
 
 
810
 
  /** Accessor method returning the session's ID. */
811
 
  inline uint64_t getSessionId()  const
812
 
  {
813
 
    return thread_id;
814
 
  }
815
 
 
816
 
  /** Accessor method returning the server's ID. */
817
 
  inline uint32_t getServerId()  const
818
 
  {
819
 
    /* We return the global server ID. */
820
 
    return server_id;
821
 
  }
822
 
 
823
 
  /** Returns the current transaction ID for the session's current statement */
824
 
  inline my_xid getTransactionId()
825
 
  {
826
 
    return transaction.xid_state.xid.quick_get_my_xid();
827
 
  }
828
 
  /**
 
641
  /*
829
642
    There is BUG#19630 where statement-based replication of stored
830
643
    functions/triggers with two auto_increment columns breaks.
831
644
    We however ensure that it works when there is 0 or 1 auto_increment
870
683
  {
871
684
    return first_successful_insert_id_in_prev_stmt;
872
685
  }
873
 
  /**
 
686
  /*
874
687
    Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
875
688
    (mysqlbinlog). We'll soon add a variant which can take many intervals in
876
689
    argument.
881
694
    auto_inc_intervals_forced.append(next_id, UINT64_MAX, 0);
882
695
  }
883
696
 
884
 
  Session(plugin::Client *client_arg);
885
 
  virtual ~Session();
886
 
 
 
697
  uint64_t  limit_found_rows;
 
698
  uint64_t  options;           /* Bitmap of states */
 
699
  int64_t   row_count_func;    /* For the ROW_COUNT() function */
 
700
  ha_rows    cuted_fields;
 
701
 
 
702
  /*
 
703
    number of rows we actually sent to the client, including "synthetic"
 
704
    rows in ROLLUP etc.
 
705
  */
 
706
  ha_rows    sent_row_count;
 
707
 
 
708
  /*
 
709
    number of rows we read, sent or not, including in create_sort_index()
 
710
  */
 
711
  ha_rows    examined_row_count;
 
712
 
 
713
  /*
 
714
    The set of those tables whose fields are referenced in all subqueries
 
715
    of the query.
 
716
    TODO: possibly this it is incorrect to have used tables in Session because
 
717
    with more than one subquery, it is not clear what does the field mean.
 
718
  */
 
719
  table_map  used_tables;
 
720
  const CHARSET_INFO *db_charset;
 
721
  /*
 
722
    FIXME: this, and some other variables like 'count_cuted_fields'
 
723
    maybe should be statement/cursor local, that is, moved to Statement
 
724
    class. With current implementation warnings produced in each prepared
 
725
    statement/cursor settle here.
 
726
  */
 
727
  List       <DRIZZLE_ERROR> warn_list;
 
728
  uint32_t   warn_count[(uint32_t) DRIZZLE_ERROR::WARN_LEVEL_END];
 
729
  uint32_t   total_warn_count;
 
730
  Diagnostics_area main_da;
 
731
 
 
732
  /*
 
733
    Id of current query. Statement can be reused to execute several queries
 
734
    query_id is global in context of the whole MySQL server.
 
735
    ID is automatically generated from mutex-protected counter.
 
736
    It's used in handler code for various purposes: to check which columns
 
737
    from table are necessary for this select, to check if it's necessary to
 
738
    update auto-updatable fields (like auto_increment and timestamp).
 
739
  */
 
740
  query_id_t query_id, warn_id;
 
741
  ulong      col_access;
 
742
 
 
743
#ifdef ERROR_INJECT_SUPPORT
 
744
  ulong      error_inject_value;
 
745
#endif
 
746
  /* Statement id is thread-wide. This counter is used to generate ids */
 
747
  ulong      statement_id_counter;
 
748
  ulong      rand_saved_seed1, rand_saved_seed2;
 
749
  /*
 
750
    Row counter, mainly for errors and warnings. Not increased in
 
751
    create_sort_index(); may differ from examined_row_count.
 
752
  */
 
753
  ulong      row_count;
 
754
  pthread_t  real_id;                           /* For debugging */
 
755
  my_thread_id  thread_id;
 
756
  uint       tmp_table, global_read_lock;
 
757
  uint       server_status,open_options;
 
758
  uint32_t       select_number;             //number of select (used for EXPLAIN)
 
759
  /* variables.transaction_isolation is reset to this after each commit */
 
760
  enum_tx_isolation session_tx_isolation;
 
761
  enum_check_fields count_cuted_fields;
 
762
 
 
763
  enum killed_state
 
764
  {
 
765
    NOT_KILLED,
 
766
    KILL_BAD_DATA,
 
767
    KILL_CONNECTION,
 
768
    KILL_QUERY,
 
769
    KILLED_NO_VALUE      /* means neither of the states */
 
770
  };
 
771
  killed_state volatile killed;
 
772
 
 
773
  bool       some_tables_deleted;
 
774
  bool       last_cuted_field;
 
775
  bool       no_errors, password;
 
776
  /**
 
777
    Set to true if execution of the current compound statement
 
778
    can not continue. In particular, disables activation of
 
779
    CONTINUE or EXIT handlers of stored routines.
 
780
    Reset in the end of processing of the current user request, in
 
781
    @see mysql_reset_session_for_next_command().
 
782
  */
 
783
  bool is_fatal_error;
 
784
  /**
 
785
    Set by a storage engine to request the entire
 
786
    transaction (that possibly spans multiple engines) to
 
787
    rollback. Reset in ha_rollback.
 
788
  */
 
789
  bool       transaction_rollback_request;
 
790
  /**
 
791
    true if we are in a sub-statement and the current error can
 
792
    not be safely recovered until we left the sub-statement mode.
 
793
    In particular, disables activation of CONTINUE and EXIT
 
794
    handlers inside sub-statements. E.g. if it is a deadlock
 
795
    error and requires a transaction-wide rollback, this flag is
 
796
    raised (traditionally, MySQL first has to close all the reads
 
797
    via @see handler::ha_index_or_rnd_end() and only then perform
 
798
    the rollback).
 
799
    Reset to false when we leave the sub-statement mode.
 
800
  */
 
801
  bool       is_fatal_sub_stmt_error;
 
802
  /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
 
803
  bool       substitute_null_with_insert_id;
 
804
  bool       in_lock_tables;
 
805
  bool       cleanup_done;
 
806
 
 
807
  /**  is set if some thread specific value(s) used in a statement. */
 
808
  bool       thread_specific_used;
 
809
  bool       charset_is_system_charset, charset_is_collation_connection;
 
810
  bool       charset_is_character_set_filesystem;
 
811
  bool       abort_on_warning;
 
812
  bool       got_warning;       /* Set on call to push_warning() */
 
813
  bool       no_warnings_for_error; /* no warnings on call to my_error() */
 
814
  /* set during loop of derived table processing */
 
815
  bool       derived_tables_processing;
 
816
  bool    tablespace_op;        /* This is true in DISCARD/IMPORT TABLESPACE */
 
817
 
 
818
  /* Used by the sys_var class to store temporary values */
 
819
  union
 
820
  {
 
821
    bool   bool_value;
 
822
    uint32_t  uint32_t_value;
 
823
    long      long_value;
 
824
    ulong     ulong_value;
 
825
    uint64_t uint64_t_value;
 
826
  } sys_var_tmp;
 
827
 
 
828
  /**
 
829
    Character input stream consumed by the lexical analyser,
 
830
    used during parsing.
 
831
    Note that since the parser is not re-entrant, we keep only one input
 
832
    stream here. This member is valid only when executing code during parsing,
 
833
    and may point to invalid memory after that.
 
834
  */
 
835
  Lex_input_stream *m_lip;
 
836
 
 
837
  Session(Protocol *protocol_arg);
 
838
  ~Session();
 
839
 
 
840
  void init(void);
 
841
  /*
 
842
    Initialize memory roots necessary for query processing and (!)
 
843
    pre-allocate memory for it. We can't do that in Session constructor because
 
844
    there are use cases (acl_init, watcher threads,
 
845
    killing mysqld) where it's vital to not allocate excessive and not used
 
846
    memory. Note, that we still don't return error from init_for_queries():
 
847
    if preallocation fails, we should notice that at the first call to
 
848
    alloc_root.
 
849
  */
 
850
  void init_for_queries();
887
851
  void cleanup(void);
888
 
  /**
889
 
   * Cleans up after query.
890
 
   *
891
 
   * @details
892
 
   *
893
 
   * This function is used to reset thread data to its default state.
894
 
   *
895
 
   * This function is not suitable for setting thread data to some
896
 
   * non-default values, as there is only one replication thread, so
897
 
   * different master threads may overwrite data of each other on
898
 
   * slave.
899
 
   */
900
852
  void cleanup_after_query();
901
 
  bool storeGlobals();
 
853
  bool store_globals();
902
854
  void awake(Session::killed_state state_to_set);
903
855
  /**
904
856
   * Pulls thread-specific variables into Session state.
912
864
  bool initGlobals();
913
865
 
914
866
  /**
915
 
    Initialize memory roots necessary for query processing and (!)
916
 
    pre-allocate memory for it. We can't do that in Session constructor because
917
 
    there are use cases where it's vital to not allocate excessive and not used
918
 
    memory.
919
 
  */
 
867
   * Initializes the Session to handle queries.
 
868
   */
920
869
  void prepareForQueries();
921
870
 
922
871
  /**
963
912
   */
964
913
  bool endTransaction(enum enum_mysql_completiontype completion);
965
914
  bool endActiveTransaction();
966
 
  bool startTransaction(start_transaction_option_t opt= START_TRANS_NO_OPTIONS);
 
915
  bool startTransaction();
967
916
 
968
917
  /**
969
918
   * Authenticates users, with error reporting.
972
921
   */
973
922
  bool authenticate();
974
923
 
975
 
  /**
976
 
   * Run a session.
977
 
   *
978
 
   * This will initialize the session and begin the command loop.
979
 
   */
980
 
  void run();
981
 
 
982
 
  /**
983
 
   * Schedule a session to be run on the default scheduler.
984
 
   */
985
 
  bool schedule();
986
 
 
987
924
  /*
988
925
    For enter_cond() / exit_cond() to work the mutex must be got before
989
926
    enter_cond(); this mutex is then released by exit_cond().
990
927
    Usage must be: lock mutex; enter_cond(); your code; exit_cond().
991
928
  */
992
 
  const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex, const char* msg);
993
 
  void exit_cond(const char* old_msg);
994
 
 
 
929
  inline const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex, const char* msg)
 
930
  {
 
931
    const char* old_msg = get_proc_info();
 
932
    safe_mutex_assert_owner(mutex);
 
933
    mysys_var->current_mutex = mutex;
 
934
    mysys_var->current_cond = cond;
 
935
    this->set_proc_info(msg);
 
936
    return old_msg;
 
937
  }
 
938
  inline void exit_cond(const char* old_msg)
 
939
  {
 
940
    /*
 
941
      Putting the mutex unlock in exit_cond() ensures that
 
942
      mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
 
943
      locked (if that would not be the case, you'll get a deadlock if someone
 
944
      does a Session::awake() on you).
 
945
    */
 
946
    pthread_mutex_unlock(mysys_var->current_mutex);
 
947
    pthread_mutex_lock(&mysys_var->mutex);
 
948
    mysys_var->current_mutex = 0;
 
949
    mysys_var->current_cond = 0;
 
950
    this->set_proc_info(old_msg);
 
951
    pthread_mutex_unlock(&mysys_var->mutex);
 
952
  }
995
953
  inline time_t query_start() { return start_time; }
996
954
  inline void set_time()
997
955
  {
998
956
    if (user_time)
999
957
    {
1000
958
      start_time= user_time;
1001
 
      connect_microseconds= start_utime= utime_after_lock= my_micro_time();
 
959
      start_utime= utime_after_lock= my_micro_time();
1002
960
    }
1003
961
    else
1004
962
      start_utime= utime_after_lock= my_micro_time_and_time(&start_time);
1030
988
  {
1031
989
    return !lex->only_view_structure();
1032
990
  }
 
991
  inline void* trans_alloc(unsigned int size)
 
992
  {
 
993
    return alloc_root(&transaction.mem_root,size);
 
994
  }
1033
995
 
1034
996
  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
1035
997
                              const char* str, uint32_t length,
1036
998
                              bool allocate_lex_string);
1037
 
  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
1038
 
                              const std::string &str,
1039
 
                              bool allocate_lex_string);
1040
 
 
 
999
 
 
1000
  bool convert_string(LEX_STRING *to, const CHARSET_INFO * const to_cs,
 
1001
                      const char *from, uint32_t from_length,
 
1002
                      const CHARSET_INFO * const from_cs);
 
1003
 
 
1004
  bool convert_string(String *s, const CHARSET_INFO * const from_cs, const CHARSET_INFO * const to_cs);
 
1005
 
 
1006
  void add_changed_table(Table *table);
 
1007
  void add_changed_table(const char *key, long key_length);
 
1008
  CHANGED_TableList * changed_table_dup(const char *key, long key_length);
1041
1009
  int send_explain_fields(select_result *result);
1042
1010
  /**
1043
1011
    Clear the current error, if any.
1061
1029
  inline void fatal_error()
1062
1030
  {
1063
1031
    assert(main_da.is_error());
1064
 
    is_fatal_error= true;
 
1032
    is_fatal_error= 1;
1065
1033
  }
1066
1034
  /**
1067
1035
    true if there is an error in the error stack.
1078
1046
  */
1079
1047
  inline bool is_error() const { return main_da.is_error(); }
1080
1048
  inline const CHARSET_INFO *charset() { return default_charset_info; }
 
1049
  void update_charset();
1081
1050
 
1082
1051
  void change_item_tree(Item **place, Item *new_value)
1083
1052
  {
1084
1053
    *place= new_value;
1085
1054
  }
1086
 
  /**
 
1055
  /*
1087
1056
    Cleanup statement parse state (parse tree, lex) and execution
1088
1057
    state after execution of a non-prepared SQL statement.
1089
 
 
1090
 
    @todo
1091
 
 
1092
 
    Move this to Statement::~Statement
1093
1058
  */
1094
1059
  void end_statement();
1095
1060
  inline int killed_errno() const
1128
1093
      @retval false Success
1129
1094
      @retval true  Out-of-memory error
1130
1095
  */
1131
 
  bool set_db(const std::string &new_db);
1132
 
 
 
1096
  bool set_db(const char *new_db, size_t new_db_len);
 
1097
 
 
1098
  /**
 
1099
    Set the current database; use shallow copy of C-string.
 
1100
 
 
1101
    @param new_db     a pointer to the new database name.
 
1102
    @param new_db_len length of the new database name.
 
1103
 
 
1104
    @note This operation just sets {db, db_length}. Switching the current
 
1105
    database usually involves other actions, like switching other database
 
1106
    attributes including security context. In the future, this operation
 
1107
    will be made private and more convenient interface will be provided.
 
1108
  */
 
1109
  void reset_db(char *new_db, size_t new_db_len)
 
1110
  {
 
1111
    db= new_db;
 
1112
    db_length= new_db_len;
 
1113
  }
1133
1114
  /*
1134
1115
    Copy the current database to the argument. Use the current arena to
1135
1116
    allocate memory for a deep copy: current database may be freed after
1136
1117
    a statement is parsed but before it's executed.
1137
1118
  */
1138
1119
  bool copy_db_to(char **p_db, size_t *p_db_length);
 
1120
  /* session_scheduler for events */
 
1121
  void *scheduler;
1139
1122
 
1140
1123
public:
1141
1124
  /**
1159
1142
  void pop_internal_handler();
1160
1143
 
1161
1144
  /**
1162
 
    Resets Session part responsible for command processing state.
1163
 
 
1164
 
    This needs to be called before execution of every statement
1165
 
    (prepared or conventional).
1166
 
    It is not called by substatements of routines.
1167
 
 
1168
 
    @todo
1169
 
    Make it a method of Session and align its name with the rest of
1170
 
    reset/end/start/init methods.
1171
 
    @todo
1172
 
    Call it after we use Session for queries, not before.
 
1145
    Reset object after executing commands.
1173
1146
  */
1174
1147
  void reset_for_next_command();
1175
1148
 
1183
1156
   * @note  For the connection that is doing shutdown, this is called twice
1184
1157
   */
1185
1158
  void disconnect(uint32_t errcode, bool lock);
 
1159
  void close_temporary_tables();
1186
1160
 
1187
1161
  /**
1188
1162
   * Check if user exists and the password supplied is correct.
1198
1172
   * @param  Database name to connect to, may be NULL
1199
1173
   */
1200
1174
  bool checkUser(const char *passwd, uint32_t passwd_len, const char *db);
1201
 
  
1202
 
  /**
1203
 
   * Returns the timestamp (in microseconds) of when the Session 
1204
 
   * connected to the server.
1205
 
   */
1206
 
  inline uint64_t getConnectMicroseconds() const
1207
 
  {
1208
 
    return connect_microseconds;
1209
 
  }
1210
 
 
1211
 
  /**
1212
 
   * Returns a pointer to the active Transaction message for this
1213
 
   * Session being managed by the ReplicationServices component, or
1214
 
   * NULL if no active message.
1215
 
   */
1216
 
  message::Transaction *getTransactionMessage() const
1217
 
  {
1218
 
    return transaction_message;
1219
 
  }
1220
 
 
1221
 
  /**
1222
 
   * Returns a pointer to the active Statement message for this
1223
 
   * Session, or NULL if no active message.
1224
 
   */
1225
 
  message::Statement *getStatementMessage() const
1226
 
  {
1227
 
    return statement_message;
1228
 
  }
1229
 
 
1230
 
  /**
1231
 
   * Sets the active transaction message used by the ReplicationServices
1232
 
   * component.
1233
 
   *
1234
 
   * @param[in] Pointer to the message
1235
 
   */
1236
 
  void setTransactionMessage(message::Transaction *in_message)
1237
 
  {
1238
 
    transaction_message= in_message;
1239
 
  }
1240
 
 
1241
 
  /**
1242
 
   * Sets the active statement message used by the ReplicationServices
1243
 
   * component.
1244
 
   *
1245
 
   * @param[in] Pointer to the message
1246
 
   */
1247
 
  void setStatementMessage(message::Statement *in_message)
1248
 
  {
1249
 
    statement_message= in_message;
1250
 
  }
 
1175
 
1251
1176
private:
1252
 
  /** Pointers to memory managed by the ReplicationServices component */
1253
 
  message::Transaction *transaction_message;
1254
 
  message::Statement *statement_message;
1255
 
  /** Microsecond timestamp of when Session connected */
1256
 
  uint64_t connect_microseconds;
1257
1177
  const char *proc_info;
1258
1178
 
1259
1179
  /** The current internal error handler for this thread, or NULL. */
1273
1193
    - for prepared queries, only to allocate runtime data. The parsed
1274
1194
    tree itself is reused between executions and thus is stored elsewhere.
1275
1195
  */
1276
 
  memory::Root main_mem_root;
1277
 
 
1278
 
  /**
1279
 
   * Marks all tables in the list which were used by current substatement
1280
 
   * as free for reuse.
1281
 
   *
1282
 
   * @param Head of the list of tables
1283
 
   *
1284
 
   * @note
1285
 
   *
1286
 
   * The reason we reset query_id is that it's not enough to just test
1287
 
   * if table->query_id != session->query_id to know if a table is in use.
1288
 
   *
1289
 
   * For example
1290
 
   * 
1291
 
   *  SELECT f1_that_uses_t1() FROM t1;
1292
 
   *  
1293
 
   * In f1_that_uses_t1() we will see one instance of t1 where query_id is
1294
 
   * set to query_id of original query.
1295
 
   */
1296
 
  void mark_used_tables_as_free_for_reuse(Table *table);
1297
 
  /**
1298
 
    Mark all temporary tables which were used by the current statement or
1299
 
    substatement as free for reuse, but only if the query_id can be cleared.
1300
 
 
1301
 
    @param session thread context
1302
 
 
1303
 
    @remark For temp tables associated with a open SQL HANDLER the query_id
1304
 
            is not reset until the HANDLER is closed.
1305
 
  */
1306
 
  void mark_temp_tables_as_free_for_reuse();
 
1196
  MEM_ROOT main_mem_root;
1307
1197
 
1308
1198
public:
1309
 
 
1310
1199
  /** A short cut for session->main_da.set_ok_status(). */
1311
 
  inline void my_ok(ha_rows affected_rows= 0, ha_rows found_rows_arg= 0,
1312
 
                    uint64_t passed_id= 0, const char *message= NULL)
 
1200
  inline void my_ok(ha_rows affected_rows= 0, uint64_t passed_id= 0, const char *message= NULL)
1313
1201
  {
1314
 
    main_da.set_ok_status(this, affected_rows, found_rows_arg, passed_id, message);
 
1202
    main_da.set_ok_status(this, affected_rows, passed_id, message);
1315
1203
  }
1316
1204
 
1317
1205
 
1344
1232
    return lex->current_select->add_group_to_list(this, item, asc);
1345
1233
  }
1346
1234
  void refresh_status();
1347
 
  user_var_entry *getVariable(LEX_STRING &name, bool create_if_not_exists);
1348
 
  
1349
 
  /**
1350
 
   * Closes all tables used by the current substatement, or all tables
1351
 
   * used by this thread if we are on the upper level.
1352
 
   */
1353
 
  void close_thread_tables();
1354
 
  void close_old_data_files(bool morph_locks= false,
1355
 
                            bool send_refresh= false);
1356
 
  void close_open_tables();
1357
 
  void close_data_files_and_morph_locks(TableIdentifier &identifier);
1358
 
  void close_data_files_and_morph_locks(const char *db, const char *table_name);
1359
 
 
1360
 
private:
1361
 
  bool free_cached_table();
1362
 
public:
1363
 
 
1364
 
  /**
1365
 
   * Prepares statement for reopening of tables and recalculation of set of
1366
 
   * prelocked tables.
1367
 
   *
1368
 
   * @param Pointer to a pointer to a list of tables which we were trying to open and lock
1369
 
   */
1370
 
  void close_tables_for_reopen(TableList **tables);
1371
 
 
1372
 
 
1373
 
  /**
1374
 
   * Open all tables in list, locks them (all, including derived)
1375
 
   *
1376
 
   * @param Pointer to a list of tables for open & locking
1377
 
   *
1378
 
   * @retval
1379
 
   *  false - ok
1380
 
   * @retval
1381
 
   *  true  - error
1382
 
   *
1383
 
   * @note
1384
 
   * 
1385
 
   * The lock will automaticaly be freed by close_thread_tables()
1386
 
   */
1387
 
  bool openTablesLock(TableList *tables);
1388
 
 
1389
 
  /**
1390
 
   * Open all tables in list and process derived tables
1391
 
   *
1392
 
   * @param Pointer to a list of tables for open
1393
 
   * @param Bitmap of flags to modify how the tables will be open:
1394
 
   *        DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
1395
 
   *        done a flush or namelock on it.
1396
 
   *
1397
 
   * @retval
1398
 
   *  false - ok
1399
 
   * @retval
1400
 
   *  true  - error
1401
 
   *
1402
 
   * @note
1403
 
   *
1404
 
   * This is to be used on prepare stage when you don't read any
1405
 
   * data from the tables.
1406
 
   */
1407
 
  bool openTables(TableList *tables, uint32_t flags= 0);
1408
 
 
1409
 
  int open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags= 0);
1410
 
 
1411
 
  Table *openTableLock(TableList *table_list, thr_lock_type lock_type);
1412
 
  Table *openTable(TableList *table_list, bool *refresh, uint32_t flags= 0);
1413
 
 
1414
 
  void unlink_open_table(Table *find);
1415
 
  void drop_open_table(Table *table, TableIdentifier &identifier);
1416
 
  void close_cached_table(Table *table);
1417
 
 
1418
 
  /* Create a lock in the cache */
1419
 
  Table *table_cache_insert_placeholder(const char *key, uint32_t key_length);
1420
 
  bool lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table);
1421
 
  bool lock_table_name_if_not_cached(const char *db,
1422
 
                                     const char *table_name, Table **table);
1423
 
 
1424
 
  typedef drizzled::hash_map<std::string, message::Table> TableMessageCache;
1425
 
  TableMessageCache table_message_cache;
1426
 
 
1427
 
  bool storeTableMessage(TableIdentifier &identifier, message::Table &table_message);
1428
 
  bool removeTableMessage(TableIdentifier &identifier);
1429
 
  bool getTableMessage(TableIdentifier &identifier, message::Table &table_message);
1430
 
  bool doesTableMessageExist(TableIdentifier &identifier);
1431
 
  bool renameTableMessage(TableIdentifier &from, TableIdentifier &to);
1432
 
 
1433
 
  /* Work with temporary tables */
1434
 
  Table *find_temporary_table(TableList *table_list);
1435
 
  Table *find_temporary_table(const char *db, const char *table_name);
1436
 
  Table *find_temporary_table(TableIdentifier &identifier);
1437
 
 
1438
 
  void doGetTableNames(CachedDirectory &directory,
1439
 
                       SchemaIdentifier &schema_identifier,
1440
 
                       std::set<std::string>& set_of_names);
1441
 
  void doGetTableNames(SchemaIdentifier &schema_identifier,
1442
 
                       std::set<std::string>& set_of_names);
1443
 
 
1444
 
  void doGetTableIdentifiers(CachedDirectory &directory,
1445
 
                             SchemaIdentifier &schema_identifier,
1446
 
                             TableIdentifiers &set_of_identifiers);
1447
 
  void doGetTableIdentifiers(SchemaIdentifier &schema_identifier,
1448
 
                             TableIdentifiers &set_of_identifiers);
1449
 
 
1450
 
  int doGetTableDefinition(drizzled::TableIdentifier &identifier,
1451
 
                           message::Table &table_proto);
1452
 
  bool doDoesTableExist(TableIdentifier &identifier);
1453
 
 
1454
 
  void close_temporary_tables();
1455
 
  void close_temporary_table(Table *table);
1456
 
  // The method below just handles the de-allocation of the table. In
1457
 
  // a better memory type world, this would not be needed.
1458
 
private:
1459
 
  void nukeTable(Table *table);
1460
 
public:
1461
 
 
1462
 
  void dumpTemporaryTableNames(const char *id);
1463
 
  int drop_temporary_table(TableList *table_list);
1464
 
  bool rm_temporary_table(plugin::StorageEngine *base, TableIdentifier &identifier);
1465
 
  bool rm_temporary_table(TableIdentifier &identifier);
1466
 
  Table *open_temporary_table(TableIdentifier &identifier,
1467
 
                              bool link_in_list= true);
1468
 
 
1469
 
  /* Reopen operations */
1470
 
  bool reopen_tables(bool get_locks, bool mark_share_as_old);
1471
 
  bool reopen_name_locked_table(TableList* table_list, bool link_in);
1472
 
  bool close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders);
1473
 
 
1474
 
  void wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond);
1475
 
  int setup_conds(TableList *leaves, COND **conds);
1476
 
  int lock_tables(TableList *tables, uint32_t count, bool *need_reopen);
1477
 
 
1478
 
 
1479
 
  /**
1480
 
    Return the default storage engine
1481
 
 
1482
 
    @param getDefaultStorageEngine()
1483
 
 
1484
 
    @return
1485
 
    pointer to plugin::StorageEngine
1486
 
  */
1487
 
  plugin::StorageEngine *getDefaultStorageEngine()
1488
 
  {
1489
 
    if (variables.storage_engine)
1490
 
      return variables.storage_engine;
1491
 
    return global_system_variables.storage_engine;
1492
 
  };
1493
 
 
1494
 
  static void unlink(Session *session);
1495
 
 
1496
1235
};
1497
1236
 
 
1237
/*
 
1238
  This is used to get result from a select
 
1239
*/
 
1240
 
1498
1241
class JOIN;
1499
1242
 
 
1243
 
1500
1244
#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
1501
1245
 
1502
 
} /* namespace drizzled */
1503
 
 
1504
 
/** @TODO why is this in the middle of the file */
1505
1246
#include <drizzled/select_to_file.h>
 
1247
 
1506
1248
#include <drizzled/select_export.h>
 
1249
 
1507
1250
#include <drizzled/select_dump.h>
 
1251
 
1508
1252
#include <drizzled/select_insert.h>
 
1253
 
1509
1254
#include <drizzled/select_create.h>
 
1255
 
 
1256
 
 
1257
 
 
1258
#include <plugin/myisam/myisam.h>
 
1259
 
1510
1260
#include <drizzled/tmp_table_param.h>
 
1261
 
1511
1262
#include <drizzled/select_union.h>
 
1263
 
1512
1264
#include <drizzled/select_subselect.h>
 
1265
 
1513
1266
#include <drizzled/select_singlerow_subselect.h>
1514
1267
#include <drizzled/select_max_min_finder_subselect.h>
1515
1268
#include <drizzled/select_exists_subselect.h>
1516
1269
 
1517
 
namespace drizzled
1518
 
{
 
1270
/* Structs used when sorting */
1519
1271
 
1520
 
/**
1521
 
 * A structure used to describe sort information
1522
 
 * for a field or item used in ORDER BY.
1523
 
 */
1524
 
typedef struct st_sort_field 
1525
 
{
1526
 
  Field *field; /**< Field to sort */
1527
 
  Item  *item; /**< Item if not sorting fields */
1528
 
  size_t length; /**< Length of sort field */
1529
 
  uint32_t suffix_length; /**< Length suffix (0-4) */
1530
 
  Item_result result_type; /**< Type of item */
1531
 
  bool reverse; /**< if descending sort */
1532
 
  bool need_strxnfrm;   /**< If we have to use strxnfrm() */
 
1272
typedef struct st_sort_field {
 
1273
  Field *field;                         /* Field to sort */
 
1274
  Item  *item;                          /* Item if not sorting fields */
 
1275
  size_t length;                        /* Length of sort field */
 
1276
  uint32_t   suffix_length;                 /* Length suffix (0-4) */
 
1277
  Item_result result_type;              /* Type of item */
 
1278
  bool reverse;                         /* if descending sort */
 
1279
  bool need_strxnfrm;                   /* If we have to use strxnfrm() */
1533
1280
} SORT_FIELD;
1534
1281
 
1535
 
typedef struct st_sort_buffer 
1536
 
{
1537
 
  uint32_t index;       /* 0 or 1 */
 
1282
 
 
1283
typedef struct st_sort_buffer {
 
1284
  uint32_t index;                                       /* 0 or 1 */
1538
1285
  uint32_t sort_orders;
1539
 
  uint32_t change_pos; /* If sort-fields changed */
 
1286
  uint32_t change_pos;                          /* If sort-fields changed */
1540
1287
  char **buff;
1541
1288
  SORT_FIELD *sortorder;
1542
1289
} SORT_BUFFER;
1543
1290
 
1544
 
} /* namespace drizzled */
1545
 
 
1546
 
/** @TODO why is this in the middle of the file */
1547
1291
 
1548
1292
#include <drizzled/table_ident.h>
1549
1293
#include <drizzled/user_var_entry.h>
1550
1294
#include <drizzled/unique.h>
1551
 
#include <drizzled/var.h>
 
1295
#include <drizzled/multi_delete.h>
 
1296
#include <drizzled/multi_update.h>
 
1297
#include <drizzled/my_var.h>
1552
1298
#include <drizzled/select_dumpvar.h>
1553
1299
 
1554
 
namespace drizzled
1555
 
{
1556
 
 
1557
1300
/* Bits in sql_command_flags */
1558
1301
 
1559
 
enum sql_command_flag_bits 
1560
 
{
 
1302
enum sql_command_flag_bits {
1561
1303
  CF_BIT_CHANGES_DATA,
1562
1304
  CF_BIT_HAS_ROW_COUNT,
1563
1305
  CF_BIT_STATUS_COMMAND,
1573
1315
static const std::bitset<CF_BIT_SIZE> CF_WRITE_LOGS_COMMAND(1 << CF_BIT_WRITE_LOGS_COMMAND);
1574
1316
 
1575
1317
/* Functions in sql_class.cc */
1576
 
void add_to_status(system_status_var *to_var, system_status_var *from_var);
1577
 
 
1578
 
void add_diff_to_status(system_status_var *to_var, system_status_var *from_var,
1579
 
                        system_status_var *dec_var);
1580
 
 
1581
 
} /* namespace drizzled */
 
1318
 
 
1319
void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
 
1320
 
 
1321
void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
 
1322
                        STATUS_VAR *dec_var);
1582
1323
 
1583
1324
#endif /* DRIZZLED_SESSION_H */