~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/session.h

  • Committer: Brian Aker
  • Date: 2009-01-24 09:43:35 UTC
  • Revision ID: brian@gir-3.local-20090124094335-6qdtvc35gl5fvivz
Adding in an example singe thread scheduler

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