~drizzle-trunk/drizzle/development

390.1.2 by Monty Taylor
Fixed copyright headers in drizzled/
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 *
4
 *  Copyright (C) 2008 Sun Microsystems
5
 *
6
 *  This program is free software; you can redistribute it and/or modify
7
 *  it under the terms of the GNU General Public License as published by
8
 *  the Free Software Foundation; version 2 of the License.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, write to the Free Software
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
 */
1 by brian
clean slate
19
20
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
21
#ifndef DRIZZLED_SESSION_H
22
#define DRIZZLED_SESSION_H
520.6.7 by Monty Taylor
Moved a bunch of crap out of common_includes.
23
1 by brian
clean slate
24
/* Classes in mysql */
538 by Monty Taylor
Moved gettext.h into drizzled in anticipation of the new client lib.
25
520.8.1 by Monty Taylor
Moved protocol.h out of common_includes.
26
#include <drizzled/protocol.h>
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
27
#include <drizzled/sql_locale.h>
575.1.3 by Monty Taylor
Moved some stuff out of handler.h.
28
#include <drizzled/ha_trx_info.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
29
#include <mysys/my_tree.h>
584.1.13 by Monty Taylor
Split out a little more code. Removed table_list.h from common_includes.
30
#include <drizzled/handler.h>
670.2.1 by Monty Taylor
Moved pthread keys
31
#include <drizzled/current_session.h>
584.1.14 by Monty Taylor
Removed field.h from common_includes.
32
#include <drizzled/sql_error.h>
722.1.5 by Monty Taylor
Split out query_arena.
33
#include <drizzled/query_arena.h>
831.1.3 by Brian Aker
Moved over file_exchange class.
34
#include <drizzled/file_exchange.h>
837 by Brian Aker
Reworked some classes out of session.h
35
#include <drizzled/select_result_interceptor.h>
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
36
#include <drizzled/authentication.h>
37
#include <drizzled/db.h>
934.2.15 by Jay Pipes
Pulls remainder of XID and xid_cache implementation into xid.cc and xid.h from drizzled/session.cc.
38
#include <drizzled/xid.h>
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
39
40
#include <netdb.h>
694 by Brian Aker
Refactor out char* strdup for string class in user.
41
#include <string>
590.2.18 by Monty Taylor
Changed the bitset<32> to a bitset<5>. Made the int constants into bitset constants.
42
#include <bitset>
1 by brian
clean slate
43
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
44
#define MIN_HANDSHAKE_SIZE      6
45
1 by brian
clean slate
46
class Lex_input_stream;
584.1.12 by Monty Taylor
HA! Removed item.h from common_includes. woot.
47
class user_var_entry;
584.1.14 by Monty Taylor
Removed field.h from common_includes.
48
class Copy_field;
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
49
class Table_ident;
1 by brian
clean slate
50
51
extern char internal_table_name[2];
52
extern char empty_c_string[1];
53
extern const char **errmesg;
54
55
#define TC_HEURISTIC_RECOVER_COMMIT   1
56
#define TC_HEURISTIC_RECOVER_ROLLBACK 2
482 by Brian Aker
Remove uint.
57
extern uint32_t tc_heuristic_recover;
1 by brian
clean slate
58
59
/*
60
  The COPY_INFO structure is used by INSERT/REPLACE code.
61
  The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
62
  UPDATE code:
63
    If a row is inserted then the copied variable is incremented.
64
    If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
65
      new data differs from the old one then the copied and the updated
66
      variables are incremented.
67
    The touched variable is incremented if a row was touched by the update part
68
      of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
69
      was actually changed or not.
70
*/
71
typedef struct st_copy_info {
72
  ha_rows records; /**< Number of processed records */
73
  ha_rows deleted; /**< Number of deleted records */
74
  ha_rows updated; /**< Number of updated records */
75
  ha_rows copied;  /**< Number of copied records */
76
  ha_rows error_count;
77
  ha_rows touched; /* Number of touched records */
78
  enum enum_duplicates handle_duplicates;
79
  int escape_char, last_errno;
80
  bool ignore;
81
  /* for INSERT ... UPDATE */
82
  List<Item> *update_fields;
83
  List<Item> *update_values;
84
  /* for VIEW ... WITH CHECK OPTION */
85
} COPY_INFO;
86
87
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
88
typedef struct drizzled_lock_st
1 by brian
clean slate
89
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
90
  Table **table;
482 by Brian Aker
Remove uint.
91
  uint32_t table_count,lock_count;
1 by brian
clean slate
92
  THR_LOCK_DATA **locks;
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
93
} DRIZZLE_LOCK;
1 by brian
clean slate
94
95
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
96
#include <drizzled/lex_column.h>
1 by brian
clean slate
97
98
class select_result;
99
class Time_zone;
100
520.1.21 by Brian Aker
THD -> Session rename
101
#define Session_SENTRY_MAGIC 0xfeedd1ff
102
#define Session_SENTRY_GONE  0xdeadbeef
1 by brian
clean slate
103
520.1.22 by Brian Aker
Second pass of thd cleanup
104
#define Session_CHECK_SENTRY(session) assert(session->dbug_sentry == Session_SENTRY_MAGIC)
1 by brian
clean slate
105
106
struct system_variables
107
{
896.1.4 by Monty Taylor
Fixed compiler warnings.
108
  system_variables() {};
1 by brian
clean slate
109
  /*
110
    How dynamically allocated system variables are handled:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
111
1 by brian
clean slate
112
    The global_system_variables and max_system_variables are "authoritative"
113
    They both should have the same 'version' and 'size'.
114
    When attempting to access a dynamic variable, if the session version
115
    is out of date, then the session version is updated and realloced if
116
    neccessary and bytes copied from global to make up for missing data.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
117
  */
1 by brian
clean slate
118
  ulong dynamic_variables_version;
119
  char* dynamic_variables_ptr;
482 by Brian Aker
Remove uint.
120
  uint32_t dynamic_variables_head;  /* largest valid variable offset */
121
  uint32_t dynamic_variables_size;  /* how many bytes are in use */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
122
151 by Brian Aker
Ulonglong to uint64_t
123
  uint64_t myisam_max_extra_sort_file_size;
124
  uint64_t max_heap_table_size;
125
  uint64_t tmp_table_size;
1 by brian
clean slate
126
  ha_rows select_limit;
127
  ha_rows max_join_size;
819.1.1 by Toru Maesaka
Removed the 16bit limitation of auto_increment_(increment|offset) system variables
128
  uint64_t auto_increment_increment;
129
  uint64_t auto_increment_offset;
616 by Brian Aker
ulong fixes.
130
  uint64_t bulk_insert_buff_size;
131
  uint64_t join_buff_size;
132
  uint32_t max_allowed_packet;
133
  uint64_t max_error_count;
134
  uint64_t max_length_for_sort_data;
910.4.4 by Stewart Smith
max_sort_length should be size_t everywhere. Causing numerous failures on SPARC and PowerPC due to strang value being retrieved in filesort. Basically, anything with filesort fails without this patch.
135
  size_t max_sort_length;
616 by Brian Aker
ulong fixes.
136
  uint64_t max_tmp_tables;
617 by Brian Aker
ulong fixes
137
  uint64_t min_examined_row_limit;
138
  uint32_t myisam_stats_method;
616 by Brian Aker
ulong fixes.
139
  uint32_t net_buffer_length;
140
  uint32_t net_read_timeout;
141
  uint32_t net_retry_count;
142
  uint32_t net_wait_timeout;
143
  uint32_t net_write_timeout;
619 by Brian Aker
Removed ulong methods from vars.
144
  bool optimizer_prune_level;
145
  uint32_t optimizer_search_depth;
1 by brian
clean slate
146
  /*
147
    Controls use of Engine-MRR:
148
      0 - auto, based on cost
149
      1 - force MRR when the storage engine is capable of doing it
150
      2 - disable MRR.
151
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
152
  uint32_t optimizer_use_mrr;
1 by brian
clean slate
153
  /* A bitmap for switching optimizations on/off */
617 by Brian Aker
ulong fixes
154
  uint32_t optimizer_switch;
619 by Brian Aker
Removed ulong methods from vars.
155
  uint64_t preload_buff_size;
156
  uint32_t read_buff_size;
157
  uint32_t read_rnd_buff_size;
158
  uint32_t div_precincrement;
629.4.1 by Monty Taylor
First step in support size_t sys_var stuff.
159
  size_t sortbuff_size;
619 by Brian Aker
Removed ulong methods from vars.
160
  uint32_t thread_handling;
617 by Brian Aker
ulong fixes
161
  uint32_t tx_isolation;
619 by Brian Aker
Removed ulong methods from vars.
162
  uint32_t completion_type;
1 by brian
clean slate
163
  /* Determines which non-standard SQL behaviour should be enabled */
619 by Brian Aker
Removed ulong methods from vars.
164
  uint32_t sql_mode;
617 by Brian Aker
ulong fixes
165
  uint64_t max_seeks_for_key;
629.4.1 by Monty Taylor
First step in support size_t sys_var stuff.
166
  size_t range_alloc_block_size;
615 by Brian Aker
Added 32bit system variable support
167
  uint32_t query_alloc_block_size;
168
  uint32_t query_prealloc_size;
169
  uint32_t trans_alloc_block_size;
170
  uint32_t trans_prealloc_size;
171
  bool log_warnings;
617 by Brian Aker
ulong fixes
172
  uint64_t group_concat_max_len;
555 by Monty
Fixed 32-bit issues.
173
  /* TODO: change this to my_thread_id - but have to fix set_var first */
174
  uint64_t pseudo_thread_id;
1 by brian
clean slate
175
200 by Brian Aker
my_bool from handler and set_var
176
  bool low_priority_updates;
177
  bool new_mode;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
178
  /*
1 by brian
clean slate
179
    compatibility option:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
180
      - index usage hints (USE INDEX without a FOR clause) behave as in 5.0
1 by brian
clean slate
181
  */
147 by Brian Aker
More my_bool conversion. This time the set_var class.
182
  bool old_mode;
200 by Brian Aker
my_bool from handler and set_var
183
  bool engine_condition_pushdown;
184
  bool keep_files_on_create;
1 by brian
clean slate
185
200 by Brian Aker
my_bool from handler and set_var
186
  bool old_alter_table;
1 by brian
clean slate
187
971.1.21 by Monty Taylor
Store StorageEngine in system variables, rather than storage engine plugin.
188
  StorageEngine *storage_engine;
1 by brian
clean slate
189
190
  /* Only charset part of these variables is sensible */
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
191
  const CHARSET_INFO  *character_set_filesystem;
1 by brian
clean slate
192
193
  /* Both charset and collation parts of these variables are important */
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
194
  const CHARSET_INFO	*collation_server;
195
  const CHARSET_INFO	*collation_database;
748 by Brian Aker
Removal of client side collation.
196
197
  inline const CHARSET_INFO  *getCollation(void) 
198
  {
199
    return collation_database ? collation_database : collation_server;
200
  }
1 by brian
clean slate
201
202
  /* Locale Support */
203
  MY_LOCALE *lc_time_names;
204
205
  Time_zone *time_zone;
206
};
207
520.6.7 by Monty Taylor
Moved a bunch of crap out of common_includes.
208
extern struct system_variables global_system_variables;
209
139.1.8 by Stewart Smith
UDFs are now normal Item_func objects. Simplifies handling them a lot.
210
#include "sql_lex.h"  /* only for SQLCOM_END */
1 by brian
clean slate
211
212
/* per thread status variables */
213
214
typedef struct system_status_var
215
{
151 by Brian Aker
Ulonglong to uint64_t
216
  uint64_t bytes_received;
217
  uint64_t bytes_sent;
1 by brian
clean slate
218
  ulong com_other;
895 by Brian Aker
Completion (?) of uint conversion.
219
  ulong com_stat[(uint32_t) SQLCOM_END];
1 by brian
clean slate
220
  ulong created_tmp_disk_tables;
221
  ulong created_tmp_tables;
222
  ulong ha_commit_count;
223
  ulong ha_delete_count;
224
  ulong ha_read_first_count;
225
  ulong ha_read_last_count;
226
  ulong ha_read_key_count;
227
  ulong ha_read_next_count;
228
  ulong ha_read_prev_count;
229
  ulong ha_read_rnd_count;
230
  ulong ha_read_rnd_next_count;
231
  ulong ha_rollback_count;
232
  ulong ha_update_count;
233
  ulong ha_write_count;
234
  ulong ha_prepare_count;
235
  ulong ha_savepoint_count;
236
  ulong ha_savepoint_rollback_count;
237
238
  /* KEY_CACHE parts. These are copies of the original */
239
  ulong key_blocks_changed;
240
  ulong key_blocks_used;
241
  ulong key_cache_r_requests;
242
  ulong key_cache_read;
243
  ulong key_cache_w_requests;
244
  ulong key_cache_write;
245
  /* END OF KEY_CACHE parts */
246
247
  ulong net_big_packet_count;
248
  ulong opened_tables;
249
  ulong opened_shares;
250
  ulong select_full_join_count;
251
  ulong select_full_range_join_count;
252
  ulong select_range_count;
253
  ulong select_range_check_count;
254
  ulong select_scan_count;
255
  ulong long_query_count;
256
  ulong filesort_merge_passes;
257
  ulong filesort_range_count;
258
  ulong filesort_rows;
259
  ulong filesort_scan_count;
260
  /*
261
    Number of statements sent from the client
262
  */
263
  ulong questions;
264
265
  /*
266
    IMPORTANT!
267
    SEE last_system_status_var DEFINITION BELOW.
268
269
    Below 'last_system_status_var' are all variables which doesn't make any
270
    sense to add to the /global/ status variable counter.
271
  */
272
  double last_query_cost;
273
274
275
} STATUS_VAR;
276
277
/*
278
  This is used for 'SHOW STATUS'. It must be updated to the last ulong
279
  variable in system_status_var which is makes sens to add to the global
280
  counter
281
*/
282
283
#define last_system_status_var questions
284
520.1.22 by Brian Aker
Second pass of thd cleanup
285
void mark_transaction_to_rollback(Session *session, bool all);
1 by brian
clean slate
286
287
/**
288
  @class Statement
289
  @brief State of a single command executed against this connection.
290
291
  One connection can contain a lot of simultaneously running statements,
292
  some of which could be:
293
   - prepared, that is, contain placeholders,
520.1.21 by Brian Aker
THD -> Session rename
294
  To perform some action with statement we reset Session part to the state  of
295
  that statement, do the action, and then save back modified state from Session
1 by brian
clean slate
296
  to the statement. It will be changed in near future, and Statement will
297
  be used explicitly.
298
*/
299
300
class Statement: public ilink, public Query_arena
301
{
302
  Statement(const Statement &rhs);              /* not implemented: */
303
  Statement &operator=(const Statement &rhs);   /* non-copyable */
304
public:
305
  /*
306
    Uniquely identifies each statement object in thread scope; change during
307
    statement lifetime. FIXME: must be const
308
  */
309
   ulong id;
310
311
  /*
312
    MARK_COLUMNS_NONE:  Means mark_used_colums is not set and no indicator to
313
                        handler of fields used is set
314
    MARK_COLUMNS_READ:  Means a bit in read set is set to inform handler
315
	                that the field is to be read. If field list contains
520.1.22 by Brian Aker
Second pass of thd cleanup
316
                        duplicates, then session->dup_field is set to point
1 by brian
clean slate
317
                        to the last found duplicate.
318
    MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
319
			that it needs to update this field in write_row
320
                        and update_row.
321
  */
322
  enum enum_mark_columns mark_used_columns;
323
324
  LEX *lex;                                     // parse tree descriptor
325
  /*
326
    Points to the query associated with this statement. It's const, but
327
    we need to declare it char * because all table handlers are written
328
    in C and need to point to it.
329
330
    Note that (A) if we set query = NULL, we must at the same time set
331
    query_length = 0, and protect the whole operation with the
332
    LOCK_thread_count mutex. And (B) we are ONLY allowed to set query to a
333
    non-NULL value if its previous value is NULL. We do not need to protect
334
    operation (B) with any mutex. To avoid crashes in races, if we do not
520.1.22 by Brian Aker
Second pass of thd cleanup
335
    know that session->query cannot change at the moment, one should print
336
    session->query like this:
1 by brian
clean slate
337
      (1) reserve the LOCK_thread_count mutex;
520.1.22 by Brian Aker
Second pass of thd cleanup
338
      (2) check if session->query is NULL;
339
      (3) if not NULL, then print at most session->query_length characters from
1 by brian
clean slate
340
      it. We will see the query_length field as either 0, or the right value
341
      for it.
342
    Assuming that the write and read of an n-bit memory field in an n-bit
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
343
    computer is atomic, we can avoid races in the above way.
1 by brian
clean slate
344
    This printing is needed at least in SHOW PROCESSLIST and SHOW INNODB
345
    STATUS.
346
  */
347
  char *query;
203 by Brian Aker
Small cleanup around uint32 types (need to merge).
348
  uint32_t query_length;                          // current query length
1 by brian
clean slate
349
350
  /**
351
    Name of the current (default) database.
352
353
    If there is the current (default) database, "db" contains its name. If
354
    there is no current (default) database, "db" is NULL and "db_length" is
355
    0. In other words, "db", "db_length" must either be NULL, or contain a
356
    valid database name.
357
358
    @note this attribute is set and alloced by the slave SQL thread (for
520.1.21 by Brian Aker
THD -> Session rename
359
    the Session of that thread); that thread is (and must remain, for now) the
1 by brian
clean slate
360
    only responsible for freeing this member.
361
  */
362
363
  char *db;
482 by Brian Aker
Remove uint.
364
  uint32_t db_length;
1 by brian
clean slate
365
366
public:
367
368
  /* This constructor is called for backup statements */
369
  Statement() {}
370
406 by Brian Aker
Cleanup around Query_arena.
371
  Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg, ulong id_arg);
1 by brian
clean slate
372
  ~Statement() {}
373
};
374
375
struct st_savepoint {
376
  struct st_savepoint *prev;
377
  char                *name;
482 by Brian Aker
Remove uint.
378
  uint32_t                 length;
1 by brian
clean slate
379
  Ha_trx_info         *ha_list;
380
};
381
382
extern pthread_mutex_t LOCK_xid_cache;
383
extern HASH xid_cache;
384
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
385
#include <drizzled/security_context.h>
386
#include <drizzled/open_tables_state.h>
1 by brian
clean slate
387
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
388
#include <drizzled/internal_error_handler.h> 
389
#include <drizzled/diagnostics_area.h> 
1 by brian
clean slate
390
391
/**
392
  Storage engine specific thread local data.
393
*/
394
struct Ha_data
395
{
396
  /**
397
    Storage engine specific thread local data.
398
    Lifetime: one user connection.
399
  */
400
  void *ha_ptr;
401
  /**
402
    0: Life time: one statement within a transaction. If @@autocommit is
403
    on, also represents the entire transaction.
404
    @sa trans_register_ha()
405
406
    1: Life time: one transaction within a connection.
407
    If the storage engine does not participate in a transaction,
408
    this should not be used.
409
    @sa trans_register_ha()
410
  */
411
  Ha_trx_info ha_info[2];
412
413
  Ha_data() :ha_ptr(NULL) {}
414
};
415
934.2.16 by Jay Pipes
Removes dead USER_CONN struct and member variable in Session class.
416
class Session :public Statement, public Open_tables_state
1 by brian
clean slate
417
{
418
public:
419
  /*
520.1.21 by Brian Aker
THD -> Session rename
420
    Constant for Session::where initialization in the beginning of every query.
1 by brian
clean slate
421
520.1.21 by Brian Aker
THD -> Session rename
422
    It's needed because we do not save/restore Session::where normally during
1 by brian
clean slate
423
    primary (non subselect) query execution.
424
  */
425
  static const char * const DEFAULT_WHERE;
426
427
  MEM_ROOT warn_root;			// For warnings and errors
428
  Protocol *protocol;			// Current protocol
429
  Protocol_text   protocol_text;	// Normal protocol
971.3.8 by Eric Day
Moved NET to Protocol. libdrizzleclient is now completely isolated, need to start reworking Protocol now.
430
  char    compression;
1 by brian
clean slate
431
  HASH    user_vars;			// hash for user variables
432
  String  packet;			// dynamic buffer for network I/O
433
  String  convert_buffer;               // buffer for charset conversions
434
  struct  system_variables variables;	// Changeable local variables
435
  struct  system_status_var status_var; // Per thread statistic vars
436
  struct  system_status_var *initial_status_var; /* used by show status */
437
  THR_LOCK_INFO lock_info;              // Locking info of this thread
438
  THR_LOCK_OWNER main_lock_id;          // To use for conventional queries
439
  THR_LOCK_OWNER *lock_id;              // If not main_lock_id, points to
440
                                        // the lock_id of a cursor.
520.1.22 by Brian Aker
Second pass of thd cleanup
441
  pthread_mutex_t LOCK_delete;		// Locked before session is deleted
961.1.3 by Brian Aker
Remove additional lock for proceslist.
442
  char process_list_info[PROCESS_LIST_WIDTH];
1 by brian
clean slate
443
  /*
444
    A pointer to the stack frame of handle_one_connection(),
445
    which is called first in the thread for handling a client
446
  */
447
  char	  *thread_stack;
448
449
  /**
450
    Currently selected catalog.
451
  */
452
  char *catalog;
453
454
  /**
455
    @note
520.1.21 by Brian Aker
THD -> Session rename
456
    Some members of Session (currently 'Statement::db',
1 by brian
clean slate
457
    'catalog' and 'query')  are set and alloced by the slave SQL thread
520.1.21 by Brian Aker
THD -> Session rename
458
    (for the Session of that thread); that thread is (and must remain, for now)
1 by brian
clean slate
459
    the only responsible for freeing these 3 members. If you add members
460
    here, and you add code to set them in replication, don't forget to
461
    free_them_and_set_them_to_0 in replication properly. For details see
462
    the 'err:' label of the handle_slave_sql() in sql/slave.cc.
463
464
    @see handle_slave_sql
465
  */
466
694 by Brian Aker
Refactor out char* strdup for string class in user.
467
  Security_context security_ctx;
1 by brian
clean slate
468
469
  /*
470
    Points to info-string that we show in SHOW PROCESSLIST
520.1.21 by Brian Aker
THD -> Session rename
471
    You are supposed to call Session_SET_PROC_INFO only if you have coded
1 by brian
clean slate
472
    a time-consuming piece that MySQL can get stuck in for a long time.
473
520.1.22 by Brian Aker
Second pass of thd cleanup
474
    Set it using the  session_proc_info(Session *thread, const char *message)
1 by brian
clean slate
475
    macro/function.
476
  */
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
477
  void        set_proc_info(const char *info) { proc_info= info; }
478
  const char* get_proc_info() const { return proc_info; }
1 by brian
clean slate
479
480
  /*
481
    Used in error messages to tell user in what part of MySQL we found an
482
    error. E. g. when where= "having clause", if fix_fields() fails, user
483
    will know that the error was in having clause.
484
  */
485
  const char *where;
486
487
  double tmp_double_value;                    /* Used in set_var.cc */
488
  ulong client_capabilities;		/* What the client supports */
489
  ulong max_client_packet_length;
490
491
  /*
492
    One thread can hold up to one named user-level lock. This variable
493
    points to a lock object if the lock is present. See item_func.cc and
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
494
    chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
1 by brian
clean slate
495
  */
482 by Brian Aker
Remove uint.
496
  uint32_t dbug_sentry; // watch out for memory corruption
1 by brian
clean slate
497
  struct st_my_thread_var *mysys_var;
498
  /*
499
    Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
500
    first byte of the packet in executeStatement()
1 by brian
clean slate
501
  */
502
  enum enum_server_command command;
203 by Brian Aker
Small cleanup around uint32 types (need to merge).
503
  uint32_t     server_id;
504
  uint32_t     file_id;			// for LOAD DATA INFILE
1 by brian
clean slate
505
  /* remote (peer) port */
206 by Brian Aker
Removed final uint dead types.
506
  uint16_t peer_port;
1 by brian
clean slate
507
  time_t     start_time, user_time;
151 by Brian Aker
Ulonglong to uint64_t
508
  uint64_t  connect_utime, thr_create_utime; // track down slow pthread_create
509
  uint64_t  start_utime, utime_after_lock;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
510
1 by brian
clean slate
511
  thr_lock_type update_lock_default;
512
661 by Brian Aker
First major pass through new replication.
513
  /*
514
    Both of the following container points in session will be converted to an API.
515
  */
516
1 by brian
clean slate
517
  /* container for handler's private per-connection data */
518
  Ha_data ha_data[MAX_HA];
519
661 by Brian Aker
First major pass through new replication.
520
  /* container for replication data */
521
  void *replication_data;
522
  inline void setReplicationData (void *data) { replication_data= data; }
523
  inline void *getReplicationData () { return replication_data; }
524
1 by brian
clean slate
525
  /* Place to store various things */
520.1.22 by Brian Aker
Second pass of thd cleanup
526
  void *session_marker;
1 by brian
clean slate
527
203 by Brian Aker
Small cleanup around uint32 types (need to merge).
528
  void set_server_id(uint32_t sid) { server_id = sid; }
1 by brian
clean slate
529
530
public:
531
532
  struct st_transactions {
533
    SAVEPOINT *savepoints;
520.1.21 by Brian Aker
THD -> Session rename
534
    Session_TRANS all;			// Trans since BEGIN WORK
535
    Session_TRANS stmt;			// Trans for current statement
1 by brian
clean slate
536
    bool on;                            // see ha_enable_transaction()
537
    XID_STATE xid_state;
538
539
    /*
540
       Tables changed in transaction (that must be invalidated in query cache).
541
       List contain only transactional tables, that not invalidated in query
542
       cache (instead of full list of changed in transaction tables).
543
    */
327.2.4 by Brian Aker
Refactoring table.h
544
    CHANGED_TableList* changed_tables;
1 by brian
clean slate
545
    MEM_ROOT mem_root; // Transaction-life memory allocation pool
546
    void cleanup()
547
    {
548
      changed_tables= 0;
549
      savepoints= 0;
550
      free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
551
    }
552
    st_transactions()
553
    {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
554
      memset(this, 0, sizeof(*this));
1 by brian
clean slate
555
      xid_state.xid.null();
556
      init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
557
    }
558
  } transaction;
559
  Field      *dup_field;
560
  sigset_t signals;
561
562
  /* Tells if LAST_INSERT_ID(#) was called for the current statement */
563
  bool arg_of_last_insert_id_function;
564
  /*
565
    ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
566
    insertion into an auto_increment column".
567
  */
568
  /*
569
    This is the first autogenerated insert id which was *successfully*
570
    inserted by the previous statement (exactly, if the previous statement
571
    didn't successfully insert an autogenerated insert id, then it's the one
572
    of the statement before, etc).
573
    It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
574
    It is returned by LAST_INSERT_ID().
575
  */
151 by Brian Aker
Ulonglong to uint64_t
576
  uint64_t  first_successful_insert_id_in_prev_stmt;
1 by brian
clean slate
577
  /*
578
    This is the first autogenerated insert id which was *successfully*
579
    inserted by the current statement. It is maintained only to set
580
    first_successful_insert_id_in_prev_stmt when statement ends.
581
  */
151 by Brian Aker
Ulonglong to uint64_t
582
  uint64_t  first_successful_insert_id_in_cur_stmt;
1 by brian
clean slate
583
  /*
584
    We follow this logic:
585
    - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
586
    first insert id successfully inserted by the previous stmt.
587
    - as stmt makes progress, handler::insert_id_for_cur_row changes;
588
    every time get_auto_increment() is called,
589
    auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
590
    reserved interval (if statement-based binlogging).
591
    - at first successful insertion of an autogenerated value,
592
    first_successful_insert_id_in_cur_stmt is set to
593
    handler::insert_id_for_cur_row.
594
    - when stmt goes to binlog,
595
    auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
596
    non-empty.
597
    - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
598
    first_successful_insert_id_in_cur_stmt.
599
  */
600
  /*
601
    List of auto_increment intervals reserved by the thread so far, for
602
    storage in the statement-based binlog.
603
    Note that its minimum is not first_successful_insert_id_in_cur_stmt:
604
    assuming a table with an autoinc column, and this happens:
605
    INSERT INTO ... VALUES(3);
606
    SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
607
    then the latter INSERT will insert no rows
608
    (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
609
    in the binlog is still needed; the list's minimum will contain 3.
610
  */
611
  Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
612
  /* Used by replication and SET INSERT_ID */
613
  Discrete_intervals_list auto_inc_intervals_forced;
614
  /*
615
    There is BUG#19630 where statement-based replication of stored
616
    functions/triggers with two auto_increment columns breaks.
617
    We however ensure that it works when there is 0 or 1 auto_increment
618
    column; our rules are
619
    a) on master, while executing a top statement involving substatements,
620
    first top- or sub- statement to generate auto_increment values wins the
621
    exclusive right to see its values be written to binlog (the write
622
    will be done by the statement or its caller), and the losers won't see
623
    their values be written to binlog.
624
    b) on slave, while replicating a top statement involving substatements,
625
    first top- or sub- statement to need to read auto_increment values from
626
    the master's binlog wins the exclusive right to read them (so the losers
627
    won't read their values from binlog but instead generate on their own).
628
    a) implies that we mustn't backup/restore
629
    auto_inc_intervals_in_cur_stmt_for_binlog.
630
    b) implies that we mustn't backup/restore auto_inc_intervals_forced.
631
632
    If there are more than 1 auto_increment columns, then intervals for
633
    different columns may mix into the
634
    auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
635
    but there is no point in preventing this mixing by preventing intervals
636
    from the secondly inserted column to come into the list, as such
637
    prevention would be wrong too.
638
    What will happen in the case of
639
    INSERT INTO t1 (auto_inc) VALUES(NULL);
640
    where t1 has a trigger which inserts into an auto_inc column of t2, is
641
    that in binlog we'll store the interval of t1 and the interval of t2 (when
642
    we store intervals, soon), then in slave, t1 will use both intervals, t2
643
    will use none; if t1 inserts the same number of rows as on master,
644
    normally the 2nd interval will not be used by t1, which is fine. t2's
645
    values will be wrong if t2's internal auto_increment counter is different
646
    from what it was on master (which is likely). In 5.1, in mixed binlogging
647
    mode, row-based binlogging is used for such cases where two
648
    auto_increment columns are inserted.
649
  */
151 by Brian Aker
Ulonglong to uint64_t
650
  inline void record_first_successful_insert_id_in_cur_stmt(uint64_t id_arg)
1 by brian
clean slate
651
  {
652
    if (first_successful_insert_id_in_cur_stmt == 0)
653
      first_successful_insert_id_in_cur_stmt= id_arg;
654
  }
151 by Brian Aker
Ulonglong to uint64_t
655
  inline uint64_t read_first_successful_insert_id_in_prev_stmt(void)
1 by brian
clean slate
656
  {
657
    return first_successful_insert_id_in_prev_stmt;
658
  }
659
  /*
660
    Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
661
    (mysqlbinlog). We'll soon add a variant which can take many intervals in
662
    argument.
663
  */
151 by Brian Aker
Ulonglong to uint64_t
664
  inline void force_one_auto_inc_interval(uint64_t next_id)
1 by brian
clean slate
665
  {
666
    auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
163 by Brian Aker
Merge Monty's code.
667
    auto_inc_intervals_forced.append(next_id, UINT64_MAX, 0);
1 by brian
clean slate
668
  }
669
151 by Brian Aker
Ulonglong to uint64_t
670
  uint64_t  limit_found_rows;
671
  uint64_t  options;           /* Bitmap of states */
152 by Brian Aker
longlong replacement
672
  int64_t   row_count_func;    /* For the ROW_COUNT() function */
1 by brian
clean slate
673
  ha_rows    cuted_fields;
674
675
  /*
676
    number of rows we actually sent to the client, including "synthetic"
677
    rows in ROLLUP etc.
678
  */
679
  ha_rows    sent_row_count;
680
681
  /*
682
    number of rows we read, sent or not, including in create_sort_index()
683
  */
684
  ha_rows    examined_row_count;
685
686
  /*
687
    The set of those tables whose fields are referenced in all subqueries
688
    of the query.
520.1.21 by Brian Aker
THD -> Session rename
689
    TODO: possibly this it is incorrect to have used tables in Session because
1 by brian
clean slate
690
    with more than one subquery, it is not clear what does the field mean.
691
  */
692
  table_map  used_tables;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
693
  const CHARSET_INFO *db_charset;
1 by brian
clean slate
694
  /*
695
    FIXME: this, and some other variables like 'count_cuted_fields'
696
    maybe should be statement/cursor local, that is, moved to Statement
697
    class. With current implementation warnings produced in each prepared
698
    statement/cursor settle here.
699
  */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
700
  List	     <DRIZZLE_ERROR> warn_list;
937.2.3 by Stewart Smith
yet another 4/8byte long issue with variables. Fix up warning and error count to use uint32_t instead.
701
  uint32_t   warn_count[(uint32_t) DRIZZLE_ERROR::WARN_LEVEL_END];
702
  uint32_t   total_warn_count;
1 by brian
clean slate
703
  Diagnostics_area main_da;
704
705
  /*
706
    Id of current query. Statement can be reused to execute several queries
707
    query_id is global in context of the whole MySQL server.
708
    ID is automatically generated from mutex-protected counter.
709
    It's used in handler code for various purposes: to check which columns
710
    from table are necessary for this select, to check if it's necessary to
711
    update auto-updatable fields (like auto_increment and timestamp).
712
  */
713
  query_id_t query_id, warn_id;
714
  ulong      col_access;
715
716
#ifdef ERROR_INJECT_SUPPORT
717
  ulong      error_inject_value;
718
#endif
719
  /* Statement id is thread-wide. This counter is used to generate ids */
720
  ulong      statement_id_counter;
721
  ulong	     rand_saved_seed1, rand_saved_seed2;
722
  /*
723
    Row counter, mainly for errors and warnings. Not increased in
724
    create_sort_index(); may differ from examined_row_count.
725
  */
726
  ulong      row_count;
727
  pthread_t  real_id;                           /* For debugging */
728
  my_thread_id  thread_id;
729
  uint	     tmp_table, global_read_lock;
730
  uint	     server_status,open_options;
482 by Brian Aker
Remove uint.
731
  uint32_t       select_number;             //number of select (used for EXPLAIN)
1 by brian
clean slate
732
  /* variables.transaction_isolation is reset to this after each commit */
733
  enum_tx_isolation session_tx_isolation;
734
  enum_check_fields count_cuted_fields;
735
736
  enum killed_state
737
  {
550 by Monty Taylor
Moved error.h into just the files that need it.
738
    NOT_KILLED,
739
    KILL_BAD_DATA,
740
    KILL_CONNECTION,
741
    KILL_QUERY,
1 by brian
clean slate
742
    KILLED_NO_VALUE      /* means neither of the states */
743
  };
744
  killed_state volatile killed;
745
746
  bool	     some_tables_deleted;
747
  bool       last_cuted_field;
748
  bool	     no_errors, password;
749
  /**
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
750
    Set to true if execution of the current compound statement
1 by brian
clean slate
751
    can not continue. In particular, disables activation of
752
    CONTINUE or EXIT handlers of stored routines.
753
    Reset in the end of processing of the current user request, in
520.1.22 by Brian Aker
Second pass of thd cleanup
754
    @see mysql_reset_session_for_next_command().
1 by brian
clean slate
755
  */
756
  bool is_fatal_error;
757
  /**
758
    Set by a storage engine to request the entire
759
    transaction (that possibly spans multiple engines) to
760
    rollback. Reset in ha_rollback.
761
  */
762
  bool       transaction_rollback_request;
763
  /**
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
764
    true if we are in a sub-statement and the current error can
1 by brian
clean slate
765
    not be safely recovered until we left the sub-statement mode.
766
    In particular, disables activation of CONTINUE and EXIT
767
    handlers inside sub-statements. E.g. if it is a deadlock
768
    error and requires a transaction-wide rollback, this flag is
769
    raised (traditionally, MySQL first has to close all the reads
770
    via @see handler::ha_index_or_rnd_end() and only then perform
771
    the rollback).
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
772
    Reset to false when we leave the sub-statement mode.
1 by brian
clean slate
773
  */
774
  bool       is_fatal_sub_stmt_error;
775
  /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
776
  bool       substitute_null_with_insert_id;
777
  bool	     in_lock_tables;
503 by Brian Aker
Removed dead bootstrap variable.
778
  bool       cleanup_done;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
779
1 by brian
clean slate
780
  /**  is set if some thread specific value(s) used in a statement. */
781
  bool       thread_specific_used;
782
  bool	     charset_is_system_charset, charset_is_collation_connection;
783
  bool       charset_is_character_set_filesystem;
784
  bool	     abort_on_warning;
785
  bool 	     got_warning;       /* Set on call to push_warning() */
786
  bool	     no_warnings_for_error; /* no warnings on call to my_error() */
787
  /* set during loop of derived table processing */
788
  bool       derived_tables_processing;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
789
  bool    tablespace_op;	/* This is true in DISCARD/IMPORT TABLESPACE */
1 by brian
clean slate
790
791
  /* Used by the sys_var class to store temporary values */
792
  union
793
  {
200 by Brian Aker
my_bool from handler and set_var
794
    bool   bool_value;
937.2.3 by Stewart Smith
yet another 4/8byte long issue with variables. Fix up warning and error count to use uint32_t instead.
795
    uint32_t  uint32_t_value;
1 by brian
clean slate
796
    long      long_value;
797
    ulong     ulong_value;
151 by Brian Aker
Ulonglong to uint64_t
798
    uint64_t uint64_t_value;
1 by brian
clean slate
799
  } sys_var_tmp;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
800
1 by brian
clean slate
801
  /**
802
    Character input stream consumed by the lexical analyser,
803
    used during parsing.
804
    Note that since the parser is not re-entrant, we keep only one input
805
    stream here. This member is valid only when executing code during parsing,
806
    and may point to invalid memory after that.
807
  */
808
  Lex_input_stream *m_lip;
809
520.1.21 by Brian Aker
THD -> Session rename
810
  Session();
811
  ~Session();
1 by brian
clean slate
812
813
  void init(void);
814
  /*
815
    Initialize memory roots necessary for query processing and (!)
520.1.21 by Brian Aker
THD -> Session rename
816
    pre-allocate memory for it. We can't do that in Session constructor because
1 by brian
clean slate
817
    there are use cases (acl_init, watcher threads,
818
    killing mysqld) where it's vital to not allocate excessive and not used
819
    memory. Note, that we still don't return error from init_for_queries():
820
    if preallocation fails, we should notice that at the first call to
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
821
    alloc_root.
1 by brian
clean slate
822
  */
823
  void init_for_queries();
824
  void cleanup(void);
825
  void cleanup_after_query();
826
  bool store_globals();
520.1.21 by Brian Aker
THD -> Session rename
827
  void awake(Session::killed_state state_to_set);
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
828
  /**
829
   * Pulls thread-specific variables into Session state.
830
   *
831
   * Returns true most times, or false if there was a problem
832
   * allocating resources for thread-specific storage.
833
   *
834
   * @TODO Kill this.  It's not necessary once my_thr_init() is bye bye.
835
   *
836
   */
837
  bool initGlobals();
838
839
  /**
840
   * Initializes the Session to handle queries.
841
   */
842
  void prepareForQueries();
1 by brian
clean slate
843
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
844
  /**
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
845
   * Executes a single statement received from the 
846
   * client connection.
847
   *
848
   * Returns true if the statement was successful, or false 
849
   * otherwise.
850
   *
851
   * @note
852
   *
853
   * For profiling to work, it must never be called recursively.
854
   *
855
   * In MySQL, this used to be the do_command() C function whic
856
   * accepted a single parameter of the THD pointer.
857
   */
858
  bool executeStatement();
859
860
  /**
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
861
   * Reads a query from packet and stores it.
862
   *
863
   * Returns true if query is read and allocated successfully, 
864
   * false otherwise.  On a return of false, Session::fatal_error
865
   * is set.
866
   *
867
   * @note Used in COM_QUERY and COM_STMT_PREPARE.
868
   *
869
   * Sets the following Session variables:
870
   *  - query
871
   *  - query_length
872
   *
873
   * @param The packet pointer to read from
874
   * @param The length of the query to read
875
   */
876
  bool readAndStoreQuery(const char *in_packet, uint32_t in_packet_length);
877
878
  /**
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
879
   * Ends the current transaction and (maybe) begins the next.
880
   *
881
   * Returns true if the transaction completed successfully, 
882
   * otherwise false.
883
   *
884
   * @param Completion type
885
   */
886
  bool endTransaction(enum enum_mysql_completiontype completion);
887
  bool endActiveTransaction();
888
  bool startTransaction();
889
890
  /**
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
891
   * Authenticates users, with error reporting.
892
   *
893
   * Returns true on success, or false on failure.
894
   */
895
  bool authenticate();
896
1 by brian
clean slate
897
  /*
898
    For enter_cond() / exit_cond() to work the mutex must be got before
899
    enter_cond(); this mutex is then released by exit_cond().
900
    Usage must be: lock mutex; enter_cond(); your code; exit_cond().
901
  */
821 by Brian Aker
Removed dead prepare2 call.
902
  inline const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex, const char* msg)
1 by brian
clean slate
903
  {
904
    const char* old_msg = get_proc_info();
905
    safe_mutex_assert_owner(mutex);
906
    mysys_var->current_mutex = mutex;
907
    mysys_var->current_cond = cond;
322.2.5 by Mats Kindahl
Replaced use of thd_proc_info() macro with calls to
908
    this->set_proc_info(msg);
1 by brian
clean slate
909
    return old_msg;
910
  }
911
  inline void exit_cond(const char* old_msg)
912
  {
913
    /*
914
      Putting the mutex unlock in exit_cond() ensures that
915
      mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
916
      locked (if that would not be the case, you'll get a deadlock if someone
520.1.21 by Brian Aker
THD -> Session rename
917
      does a Session::awake() on you).
1 by brian
clean slate
918
    */
919
    pthread_mutex_unlock(mysys_var->current_mutex);
920
    pthread_mutex_lock(&mysys_var->mutex);
921
    mysys_var->current_mutex = 0;
922
    mysys_var->current_cond = 0;
322.2.5 by Mats Kindahl
Replaced use of thd_proc_info() macro with calls to
923
    this->set_proc_info(old_msg);
1 by brian
clean slate
924
    pthread_mutex_unlock(&mysys_var->mutex);
925
  }
735 by Brian Aker
Refactor session.
926
  inline time_t query_start() { return start_time; }
1 by brian
clean slate
927
  inline void set_time()
928
  {
929
    if (user_time)
930
    {
931
      start_time= user_time;
932
      start_utime= utime_after_lock= my_micro_time();
933
    }
934
    else
935
      start_utime= utime_after_lock= my_micro_time_and_time(&start_time);
936
  }
713.1.3 by Monty Taylor
Fixed one more my_time thing.
937
  inline void	set_current_time()    { start_time= time(NULL); }
1 by brian
clean slate
938
  inline void	set_time(time_t t)
939
  {
940
    start_time= user_time= t;
941
    start_utime= utime_after_lock= my_micro_time();
942
  }
943
  void set_time_after_lock()  { utime_after_lock= my_micro_time(); }
151 by Brian Aker
Ulonglong to uint64_t
944
  uint64_t current_utime()  { return my_micro_time(); }
945
  inline uint64_t found_rows(void)
1 by brian
clean slate
946
  {
947
    return limit_found_rows;
948
  }
934.2.28 by Jay Pipes
Renamed some things to our standards and made private methods private...
949
  /** Returns whether the session is currently inside a transaction */
950
  inline bool inTransaction()
1 by brian
clean slate
951
  {
952
    return server_status & SERVER_STATUS_IN_TRANS;
953
  }
954
  inline bool fill_derived_tables()
955
  {
956
    return !lex->only_view_structure();
957
  }
958
  inline void* trans_alloc(unsigned int size)
959
  {
960
    return alloc_root(&transaction.mem_root,size);
961
  }
962
963
  LEX_STRING *make_lex_string(LEX_STRING *lex_str,
482 by Brian Aker
Remove uint.
964
                              const char* str, uint32_t length,
1 by brian
clean slate
965
                              bool allocate_lex_string);
966
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
967
  bool convert_string(LEX_STRING *to, const CHARSET_INFO * const to_cs,
482 by Brian Aker
Remove uint.
968
		      const char *from, uint32_t from_length,
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
969
		      const CHARSET_INFO * const from_cs);
1 by brian
clean slate
970
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
971
  bool convert_string(String *s, const CHARSET_INFO * const from_cs, const CHARSET_INFO * const to_cs);
1 by brian
clean slate
972
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
973
  void add_changed_table(Table *table);
1 by brian
clean slate
974
  void add_changed_table(const char *key, long key_length);
327.2.4 by Brian Aker
Refactoring table.h
975
  CHANGED_TableList * changed_table_dup(const char *key, long key_length);
1 by brian
clean slate
976
  int send_explain_fields(select_result *result);
977
  /**
978
    Clear the current error, if any.
979
    We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
980
    assume this is never called if the fatal error is set.
981
    @todo: To silence an error, one should use Internal_error_handler
982
    mechanism. In future this function will be removed.
983
  */
984
  inline void clear_error()
985
  {
986
    if (main_da.is_error())
987
      main_da.reset_diagnostics_area();
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
988
    return;
1 by brian
clean slate
989
  }
383.1.55 by Monty Taylor
Removed libvio deps from drizzled.
990
1 by brian
clean slate
991
  /**
992
    Mark the current error as fatal. Warning: this does not
993
    set any error, it sets a property of the error, so must be
994
    followed or prefixed with my_error().
995
  */
996
  inline void fatal_error()
997
  {
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
998
    assert(main_da.is_error());
1 by brian
clean slate
999
    is_fatal_error= 1;
1000
  }
1001
  /**
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1002
    true if there is an error in the error stack.
1 by brian
clean slate
1003
1004
    Please use this method instead of direct access to
1005
    net.report_error.
1006
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1007
    If true, the current (sub)-statement should be aborted.
1 by brian
clean slate
1008
    The main difference between this member and is_fatal_error
1009
    is that a fatal error can not be handled by a stored
1010
    procedure continue handler, whereas a normal error can.
1011
1012
    To raise this flag, use my_error().
1013
  */
1014
  inline bool is_error() const { return main_da.is_error(); }
748 by Brian Aker
Removal of client side collation.
1015
  inline const CHARSET_INFO *charset() { return default_charset_info; }
1 by brian
clean slate
1016
  void update_charset();
1017
1018
  void change_item_tree(Item **place, Item *new_value)
1019
  {
1020
    *place= new_value;
1021
  }
1022
  /*
1023
    Cleanup statement parse state (parse tree, lex) and execution
1024
    state after execution of a non-prepared SQL statement.
1025
  */
1026
  void end_statement();
1027
  inline int killed_errno() const
1028
  {
1029
    killed_state killed_val; /* to cache the volatile 'killed' */
1030
    return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0;
1031
  }
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1032
  void send_kill_message() const;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1033
  /* return true if we will abort query if we make a warning now */
1 by brian
clean slate
1034
  inline bool really_abort_on_warning()
1035
  {
1036
    return (abort_on_warning);
1037
  }
1038
  void set_status_var_init();
1039
  void reset_n_backup_open_tables_state(Open_tables_state *backup);
1040
  void restore_backup_open_tables_state(Open_tables_state *backup);
1041
1042
  /**
1043
    Set the current database; use deep copy of C-string.
1044
1045
    @param new_db     a pointer to the new database name.
1046
    @param new_db_len length of the new database name.
1047
1048
    Initialize the current database from a NULL-terminated string with
1049
    length. If we run out of memory, we free the current database and
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1050
    return true.  This way the user will notice the error as there will be
1 by brian
clean slate
1051
    no current database selected (in addition to the error message set by
1052
    malloc).
1053
1054
    @note This operation just sets {db, db_length}. Switching the current
1055
    database usually involves other actions, like switching other database
1056
    attributes including security context. In the future, this operation
1057
    will be made private and more convenient interface will be provided.
1058
1059
    @return Operation status
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1060
      @retval false Success
1061
      @retval true  Out-of-memory error
1 by brian
clean slate
1062
  */
656.1.22 by Monty Taylor
Removed my_malloc related stuff from log_event and session.
1063
  bool set_db(const char *new_db, size_t new_db_len);
1 by brian
clean slate
1064
1065
  /**
1066
    Set the current database; use shallow copy of C-string.
1067
1068
    @param new_db     a pointer to the new database name.
1069
    @param new_db_len length of the new database name.
1070
1071
    @note This operation just sets {db, db_length}. Switching the current
1072
    database usually involves other actions, like switching other database
1073
    attributes including security context. In the future, this operation
1074
    will be made private and more convenient interface will be provided.
1075
  */
1076
  void reset_db(char *new_db, size_t new_db_len)
1077
  {
1078
    db= new_db;
1079
    db_length= new_db_len;
1080
  }
1081
  /*
1082
    Copy the current database to the argument. Use the current arena to
1083
    allocate memory for a deep copy: current database may be freed after
1084
    a statement is parsed but before it's executed.
1085
  */
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1086
  bool copy_db_to(char **p_db, size_t *p_db_length);
803 by Brian Aker
Refactored all current scheduler to be behind scheduler plugin api.
1087
  /* session_scheduler for events */
1088
  void *scheduler;
1 by brian
clean slate
1089
1090
public:
1091
  /**
1092
    Add an internal error handler to the thread execution context.
1093
    @param handler the exception handler to add
1094
  */
1095
  void push_internal_handler(Internal_error_handler *handler);
1096
1097
  /**
1098
    Handle an error condition.
1099
    @param sql_errno the error number
1100
    @param level the error level
1101
    @return true if the error is handled
1102
  */
482 by Brian Aker
Remove uint.
1103
  virtual bool handle_error(uint32_t sql_errno, const char *message,
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1104
                            DRIZZLE_ERROR::enum_warning_level level);
1 by brian
clean slate
1105
1106
  /**
1107
    Remove the error handler last pushed.
1108
  */
1109
  void pop_internal_handler();
1110
693 by Brian Aker
Cleaning up session class.
1111
  /**
735 by Brian Aker
Refactor session.
1112
    Reset object after executing commands.
1113
  */
1114
  void reset_for_next_command();
1115
1116
  /**
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1117
   * Disconnects the session from a client connection and
1118
   * updates any status variables necessary.
1119
   *
1120
   * @param errcode	Error code to print to console
1121
   * @param should_lock 1 if we have have to lock LOCK_thread_count
1122
   *
1123
   * @note  For the connection that is doing shutdown, this is called twice
1124
   */
1125
  void disconnect(uint32_t errcode, bool lock);
793 by Brian Aker
Pass through on refactoring functions to clases.
1126
  void close_temporary_tables();
693 by Brian Aker
Cleaning up session class.
1127
934.2.28 by Jay Pipes
Renamed some things to our standards and made private methods private...
1128
  /**
1129
   * Check if user exists and the password supplied is correct.
1130
   *
1131
   * Returns true on success, and false on failure.
1132
   *
1133
   * @note Host, user and passwd may point to communication buffer.
1134
   * Current implementation does not depend on that, but future changes
1135
   * should be done with this in mind; 
1136
   *
1137
   * @param  Scrambled password received from client
1138
   * @param  Length of scrambled password
1139
   * @param  Database name to connect to, may be NULL
1140
   */
965 by Brian Aker
Merge with Jay
1141
  bool checkUser(const char *passwd, uint32_t passwd_len, const char *db);
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
1142
1143
private:
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
1144
  const char *proc_info;
1145
1 by brian
clean slate
1146
  /** The current internal error handler for this thread, or NULL. */
1147
  Internal_error_handler *m_internal_handler;
1148
  /**
1149
    The lex to hold the parsed tree of conventional (non-prepared) queries.
1150
    Whereas for prepared and stored procedure statements we use an own lex
1151
    instance for each new query, for conventional statements we reuse
1152
    the same lex. (@see mysql_parse for details).
1153
  */
1154
  LEX main_lex;
1155
  /**
1156
    This memory root is used for two purposes:
1157
    - for conventional queries, to allocate structures stored in main_lex
1158
    during parsing, and allocate runtime data (execution plan, etc.)
1159
    during execution.
1160
    - for prepared queries, only to allocate runtime data. The parsed
1161
    tree itself is reused between executions and thus is stored elsewhere.
1162
  */
1163
  MEM_ROOT main_mem_root;
836 by Brian Aker
Fixed session call from function to method.
1164
1165
public:
1166
  /** A short cut for session->main_da.set_ok_status(). */
1167
  inline void my_ok(ha_rows affected_rows= 0, uint64_t passed_id= 0, const char *message= NULL)
1168
  {
1169
    main_da.set_ok_status(this, affected_rows, passed_id, message);
1170
  }
1171
1172
1173
  /** A short cut for session->main_da.set_eof_status(). */
1174
1175
  inline void my_eof()
1176
  {
1177
    main_da.set_eof_status(this);
1178
  }
838 by Brian Aker
More class adoption/method
1179
1180
  /* Some inline functions for more speed */
1181
1182
  inline bool add_item_to_list(Item *item)
1183
  {
1184
    return lex->current_select->add_item_to_list(this, item);
1185
  }
1186
1187
  inline bool add_value_to_list(Item *value)
1188
  {
1189
    return lex->value_list.push_back(value);
1190
  }
1191
1192
  inline bool add_order_to_list(Item *item, bool asc)
1193
  {
1194
    return lex->current_select->add_order_to_list(this, item, asc);
1195
  }
1196
1197
  inline bool add_group_to_list(Item *item, bool asc)
1198
  {
1199
    return lex->current_select->add_group_to_list(this, item, asc);
1200
  }
855 by Brian Aker
Refactor reset of status.
1201
  void refresh_status();
1 by brian
clean slate
1202
};
1203
1204
/*
1205
  This is used to get result from a select
1206
*/
1207
1208
class JOIN;
1209
1210
1211
#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
1212
850 by Brian Aker
More class creation.
1213
#include <drizzled/select_to_file.h>
1214
1215
#include <drizzled/select_export.h>
1216
1217
#include <drizzled/select_dump.h>
1218
1219
#include <drizzled/select_insert.h>
1220
1221
#include <drizzled/select_create.h>
1222
1223
1 by brian
clean slate
1224
212.4.2 by Monty Taylor
Fixed the includes in places to make the myisam header file move work.
1225
#include <storage/myisam/myisam.h>
1 by brian
clean slate
1226
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
1227
#include <drizzled/tmp_table_param.h>
1228
1229
#include <drizzled/select_union.h>
1230
1231
#include <drizzled/select_subselect.h>
1232
1233
#include <drizzled/select_singlerow_subselect.h>
1234
#include <drizzled/select_max_min_finder_subselect.h>
1235
#include <drizzled/select_exists_subselect.h>
1 by brian
clean slate
1236
1237
/* Structs used when sorting */
1238
1239
typedef struct st_sort_field {
1240
  Field *field;				/* Field to sort */
1241
  Item	*item;				/* Item if not sorting fields */
892.2.2 by Monty Taylor
More solaris warnings.
1242
  size_t length;			/* Length of sort field */
482 by Brian Aker
Remove uint.
1243
  uint32_t   suffix_length;                 /* Length suffix (0-4) */
1 by brian
clean slate
1244
  Item_result result_type;		/* Type of item */
1245
  bool reverse;				/* if descending sort */
1246
  bool need_strxnfrm;			/* If we have to use strxnfrm() */
1247
} SORT_FIELD;
1248
1249
1250
typedef struct st_sort_buffer {
482 by Brian Aker
Remove uint.
1251
  uint32_t index;					/* 0 or 1 */
1252
  uint32_t sort_orders;
1253
  uint32_t change_pos;				/* If sort-fields changed */
1 by brian
clean slate
1254
  char **buff;
1255
  SORT_FIELD *sortorder;
1256
} SORT_BUFFER;
1257
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
1258
1259
#include <drizzled/table_ident.h>
1260
#include <drizzled/user_var_entry.h>
1261
#include <drizzled/unique.h>
1262
#include <drizzled/multi_delete.h>
1263
#include <drizzled/multi_update.h>
1264
#include <drizzled/my_var.h>
1265
#include <drizzled/select_dumpvar.h>
1 by brian
clean slate
1266
1267
/* Bits in sql_command_flags */
1268
590.2.17 by Monty Taylor
Changed CF_BIT_* to an enum.
1269
enum sql_command_flag_bits {
1270
  CF_BIT_CHANGES_DATA,
1271
  CF_BIT_HAS_ROW_COUNT,
1272
  CF_BIT_STATUS_COMMAND,
1273
  CF_BIT_SHOW_TABLE_COMMAND,
590.2.18 by Monty Taylor
Changed the bitset<32> to a bitset<5>. Made the int constants into bitset constants.
1274
  CF_BIT_WRITE_LOGS_COMMAND,
1275
  CF_BIT_SIZE
590.2.17 by Monty Taylor
Changed CF_BIT_* to an enum.
1276
};
602.2.2 by Yoshinori Sano
Fix bugs in params of sql_command_flags[...].test(). Previously, the value such as, 0, 1, 2, 4, 8 and 16 is given to std::bitset.test() in that place, which is misunderstanding of the spec of the test(). The test(size_t n) returns true if bit n is set.
1277
590.2.18 by Monty Taylor
Changed the bitset<32> to a bitset<5>. Made the int constants into bitset constants.
1278
static const std::bitset<CF_BIT_SIZE> CF_CHANGES_DATA(1 << CF_BIT_CHANGES_DATA);
1279
static const std::bitset<CF_BIT_SIZE> CF_HAS_ROW_COUNT(1 << CF_BIT_HAS_ROW_COUNT);
1280
static const std::bitset<CF_BIT_SIZE> CF_STATUS_COMMAND(1 << CF_BIT_STATUS_COMMAND);
1281
static const std::bitset<CF_BIT_SIZE> CF_SHOW_TABLE_COMMAND(1 << CF_BIT_SHOW_TABLE_COMMAND);
1282
static const std::bitset<CF_BIT_SIZE> CF_WRITE_LOGS_COMMAND(1 << CF_BIT_WRITE_LOGS_COMMAND);
1 by brian
clean slate
1283
1284
/* Functions in sql_class.cc */
1285
1286
void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
1287
1288
void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
1289
                        STATUS_VAR *dec_var);
1290
897.2.2 by Jay Pipes
Replaced custom List in select_dumpvar.h with std::vector<>
1291
#endif /* DRIZZLED_SESSION_H */