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