1
/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
17
/* Classes in mysql */
19
#ifdef USE_PRAGMA_INTERFACE
20
#pragma interface /* gcc class implementation */
24
#include "rpl_tblmap.h"
27
An interface that is used to take an action when
28
the locking module notices that a table version has changed
29
since the last execution. "Table" here may refer to any kind of
30
table -- a base table, a temporary table, a view or an
31
information schema table.
33
When we open and lock tables for execution of a prepared
34
statement, we must verify that they did not change
35
since statement prepare. If some table did change, the statement
36
parse tree *may* be no longer valid, e.g. in case it contains
37
optimizations that depend on table metadata.
39
This class provides an interface (a method) that is
40
invoked when such a situation takes place.
41
The implementation of the method simply reports an error, but
42
the exact details depend on the nature of the SQL statement.
44
At most 1 instance of this class is active at a time, in which
45
case THD::m_reprepare_observer is not NULL.
47
@sa check_and_update_table_version() for details of the
48
version tracking algorithm
50
@sa Open_tables_state::m_reprepare_observer for the life cycle
51
of metadata observers.
54
class Reprepare_observer
58
Check if a change of metadata is OK. In future
59
the signature of this method may be extended to accept the old
60
and the new versions, but since currently the check is very
61
simple, we only need the THD to report an error.
63
bool report_error(THD *thd);
64
bool is_invalidated() const { return m_invalidated; }
65
void reset_reprepare_observer() { m_invalidated= FALSE; }
73
class Query_log_event;
75
class Slave_log_event;
81
enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE };
82
enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
83
enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE };
84
enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON,
85
DELAY_KEY_WRITE_ALL };
86
enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT,
87
SLAVE_EXEC_MODE_IDEMPOTENT,
88
SLAVE_EXEC_MODE_LAST_BIT};
89
enum enum_mark_columns
90
{ MARK_COLUMNS_NONE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE};
92
extern char internal_table_name[2];
93
extern char empty_c_string[1];
94
extern MYSQL_PLUGIN_IMPORT const char **errmesg;
96
extern bool volatile shutdown_in_progress;
98
#define TC_LOG_PAGE_SIZE 8192
99
#define TC_LOG_MIN_SIZE (3*TC_LOG_PAGE_SIZE)
101
#define TC_HEURISTIC_RECOVER_COMMIT 1
102
#define TC_HEURISTIC_RECOVER_ROLLBACK 2
103
extern uint tc_heuristic_recover;
105
typedef struct st_user_var_events
107
user_var_entry *user_var_event;
112
} BINLOG_USER_VAR_EVENT;
114
#define RP_LOCK_LOG_IS_ALREADY_LOCKED 1
115
#define RP_FORCE_ROTATE 2
118
The COPY_INFO structure is used by INSERT/REPLACE code.
119
The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
121
If a row is inserted then the copied variable is incremented.
122
If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
123
new data differs from the old one then the copied and the updated
124
variables are incremented.
125
The touched variable is incremented if a row was touched by the update part
126
of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
127
was actually changed or not.
129
typedef struct st_copy_info {
130
ha_rows records; /**< Number of processed records */
131
ha_rows deleted; /**< Number of deleted records */
132
ha_rows updated; /**< Number of updated records */
133
ha_rows copied; /**< Number of copied records */
135
ha_rows touched; /* Number of touched records */
136
enum enum_duplicates handle_duplicates;
137
int escape_char, last_errno;
139
/* for INSERT ... UPDATE */
140
List<Item> *update_fields;
141
List<Item> *update_values;
142
/* for VIEW ... WITH CHECK OPTION */
147
class Key_part_spec :public Sql_alloc {
149
const char *field_name;
151
Key_part_spec(const char *name,uint len=0) :field_name(name), length(len) {}
152
bool operator==(const Key_part_spec& other) const;
154
Construct a copy of this Key_part_spec. field_name is copied
155
by-pointer as it is known to never change. At the same time
156
'length' may be reset in mysql_prepare_create_table, and this
157
is why we supply it with a copy.
159
@return If out of memory, 0 is returned and an error is set in
162
Key_part_spec *clone(MEM_ROOT *mem_root) const
163
{ return new (mem_root) Key_part_spec(*this); }
167
class Alter_drop :public Sql_alloc {
169
enum drop_type {KEY, COLUMN };
172
Alter_drop(enum drop_type par_type,const char *par_name)
173
:name(par_name), type(par_type) {}
175
Used to make a clone of this object for ALTER/CREATE TABLE
176
@sa comment for Key_part_spec::clone
178
Alter_drop *clone(MEM_ROOT *mem_root) const
179
{ return new (mem_root) Alter_drop(*this); }
183
class Alter_column :public Sql_alloc {
187
Alter_column(const char *par_name,Item *literal)
188
:name(par_name), def(literal) {}
190
Used to make a clone of this object for ALTER/CREATE TABLE
191
@sa comment for Key_part_spec::clone
193
Alter_column *clone(MEM_ROOT *mem_root) const
194
{ return new (mem_root) Alter_column(*this); }
198
class Key :public Sql_alloc {
200
enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY};
202
KEY_CREATE_INFO key_create_info;
203
List<Key_part_spec> columns;
207
Key(enum Keytype type_par, const char *name_arg,
208
KEY_CREATE_INFO *key_info_arg,
209
bool generated_arg, List<Key_part_spec> &cols)
210
:type(type_par), key_create_info(*key_info_arg), columns(cols),
211
name(name_arg), generated(generated_arg)
213
Key(const Key &rhs, MEM_ROOT *mem_root);
215
/* Equality comparison of keys (ignoring name) */
216
friend bool foreign_key_prefix(Key *a, Key *b);
218
Used to make a clone of this object for ALTER/CREATE TABLE
219
@sa comment for Key_part_spec::clone
221
virtual Key *clone(MEM_ROOT *mem_root) const
222
{ return new (mem_root) Key(*this, mem_root); }
227
class Foreign_key: public Key {
229
enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
230
FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
231
enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
232
FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT};
234
Table_ident *ref_table;
235
List<Key_part_spec> ref_columns;
236
uint delete_opt, update_opt, match_opt;
237
Foreign_key(const char *name_arg, List<Key_part_spec> &cols,
238
Table_ident *table, List<Key_part_spec> &ref_cols,
239
uint delete_opt_arg, uint update_opt_arg, uint match_opt_arg)
240
:Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols),
241
ref_table(table), ref_columns(ref_cols),
242
delete_opt(delete_opt_arg), update_opt(update_opt_arg),
243
match_opt(match_opt_arg)
245
Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root);
247
Used to make a clone of this object for ALTER/CREATE TABLE
248
@sa comment for Key_part_spec::clone
250
virtual Key *clone(MEM_ROOT *mem_root) const
251
{ return new (mem_root) Foreign_key(*this, mem_root); }
254
typedef struct st_mysql_lock
257
uint table_count,lock_count;
258
THR_LOCK_DATA **locks;
262
class LEX_COLUMN : public Sql_alloc
267
LEX_COLUMN (const String& x,const uint& y ): column (x),rights (y) {}
270
#include "sql_lex.h" /* Must be here */
272
class Delayed_insert;
276
#define THD_SENTRY_MAGIC 0xfeedd1ff
277
#define THD_SENTRY_GONE 0xdeadbeef
279
#define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
281
struct system_variables
284
How dynamically allocated system variables are handled:
286
The global_system_variables and max_system_variables are "authoritative"
287
They both should have the same 'version' and 'size'.
288
When attempting to access a dynamic variable, if the session version
289
is out of date, then the session version is updated and realloced if
290
neccessary and bytes copied from global to make up for missing data.
292
ulong dynamic_variables_version;
293
char* dynamic_variables_ptr;
294
uint dynamic_variables_head; /* largest valid variable offset */
295
uint dynamic_variables_size; /* how many bytes are in use */
297
ulonglong myisam_max_extra_sort_file_size;
298
ulonglong myisam_max_sort_file_size;
299
ulonglong max_heap_table_size;
300
ulonglong tmp_table_size;
301
ulonglong long_query_time;
302
ha_rows select_limit;
303
ha_rows max_join_size;
304
ulong auto_increment_increment, auto_increment_offset;
305
ulong bulk_insert_buff_size;
306
ulong join_buff_size;
307
ulong max_allowed_packet;
308
ulong max_error_count;
309
ulong max_length_for_sort_data;
310
ulong max_sort_length;
311
ulong max_tmp_tables;
312
ulong max_insert_delayed_threads;
313
ulong min_examined_row_limit;
314
ulong multi_range_count;
315
ulong myisam_repair_threads;
316
ulong myisam_sort_buff_size;
317
ulong myisam_stats_method;
318
ulong net_buffer_length;
319
ulong net_interactive_timeout;
320
ulong net_read_timeout;
321
ulong net_retry_count;
322
ulong net_wait_timeout;
323
ulong net_write_timeout;
324
ulong optimizer_prune_level;
325
ulong optimizer_search_depth;
326
/* A bitmap for switching optimizations on/off */
327
ulong optimizer_switch;
328
ulong preload_buff_size;
329
ulong profiling_history_size;
330
ulong query_cache_type;
331
ulong read_buff_size;
332
ulong read_rnd_buff_size;
333
ulong div_precincrement;
335
ulong thread_handling;
337
ulong completion_type;
338
/* Determines which non-standard SQL behaviour should be enabled */
340
ulong max_sp_recursion_depth;
341
/* check of key presence in updatable view */
342
ulong updatable_views_with_limit;
343
ulong default_week_format;
344
ulong max_seeks_for_key;
345
ulong range_alloc_block_size;
346
ulong query_alloc_block_size;
347
ulong query_prealloc_size;
348
ulong trans_alloc_block_size;
349
ulong trans_prealloc_size;
351
ulong group_concat_max_len;
352
ulong ndb_autoincrement_prefetch_sz;
353
ulong ndb_index_stat_cache_entries;
354
ulong ndb_index_stat_update_freq;
355
ulong binlog_format; // binlog format for this thd (see enum_binlog_format)
356
my_bool binlog_direct_non_trans_update;
358
In slave thread we need to know in behalf of which
359
thread the query is being run to replicate temp tables properly
361
my_thread_id pseudo_thread_id;
363
my_bool low_priority_updates;
366
compatibility option:
367
- index usage hints (USE INDEX without a FOR clause) behave as in 5.0
370
my_bool query_cache_wlock_invalidate;
371
my_bool engine_condition_pushdown;
372
my_bool keep_files_on_create;
373
my_bool ndb_force_send;
374
my_bool ndb_use_copying_alter_table;
375
my_bool ndb_use_exact_count;
376
my_bool ndb_use_transactions;
377
my_bool ndb_index_stat_enable;
379
my_bool old_alter_table;
380
my_bool old_passwords;
382
plugin_ref table_plugin;
384
/* Only charset part of these variables is sensible */
385
CHARSET_INFO *character_set_filesystem;
386
CHARSET_INFO *character_set_client;
387
CHARSET_INFO *character_set_results;
389
/* Both charset and collation parts of these variables are important */
390
CHARSET_INFO *collation_server;
391
CHARSET_INFO *collation_database;
392
CHARSET_INFO *collation_connection;
395
MY_LOCALE *lc_time_names;
397
Time_zone *time_zone;
399
/* DATE, DATETIME and MYSQL_TIME formats */
400
DATE_TIME_FORMAT *date_format;
401
DATE_TIME_FORMAT *datetime_format;
402
DATE_TIME_FORMAT *time_format;
403
my_bool sysdate_is_now;
407
/* per thread status variables */
409
typedef struct system_status_var
411
ulonglong bytes_received;
412
ulonglong bytes_sent;
414
ulong com_stat[(uint) SQLCOM_END];
415
ulong created_tmp_disk_tables;
416
ulong created_tmp_tables;
417
ulong ha_commit_count;
418
ulong ha_delete_count;
419
ulong ha_read_first_count;
420
ulong ha_read_last_count;
421
ulong ha_read_key_count;
422
ulong ha_read_next_count;
423
ulong ha_read_prev_count;
424
ulong ha_read_rnd_count;
425
ulong ha_read_rnd_next_count;
426
ulong ha_rollback_count;
427
ulong ha_update_count;
428
ulong ha_write_count;
429
ulong ha_prepare_count;
430
ulong ha_discover_count;
431
ulong ha_savepoint_count;
432
ulong ha_savepoint_rollback_count;
434
/* KEY_CACHE parts. These are copies of the original */
435
ulong key_blocks_changed;
436
ulong key_blocks_used;
437
ulong key_cache_r_requests;
438
ulong key_cache_read;
439
ulong key_cache_w_requests;
440
ulong key_cache_write;
441
/* END OF KEY_CACHE parts */
443
ulong net_big_packet_count;
446
ulong select_full_join_count;
447
ulong select_full_range_join_count;
448
ulong select_range_count;
449
ulong select_range_check_count;
450
ulong select_scan_count;
451
ulong long_query_count;
452
ulong filesort_merge_passes;
453
ulong filesort_range_count;
455
ulong filesort_scan_count;
456
/* Prepared statements and binary protocol */
457
ulong com_stmt_prepare;
458
ulong com_stmt_reprepare;
459
ulong com_stmt_execute;
460
ulong com_stmt_send_long_data;
461
ulong com_stmt_fetch;
462
ulong com_stmt_reset;
463
ulong com_stmt_close;
465
Number of statements sent from the client
470
SEE last_system_status_var DEFINITION BELOW.
471
Below 'last_system_status_var' are all variables which doesn't make any
472
sense to add to the /global/ status variable counter.
473
Status variables which it does not make sense to add to
474
global status variable counter
476
double last_query_cost;
480
This is used for 'SHOW STATUS'. It must be updated to the last ulong
481
variable in system_status_var which is makes sens to add to the global
485
#define last_system_status_var questions
487
void mark_transaction_to_rollback(THD *thd, bool all);
491
void free_tmp_table(THD *thd, TABLE *entry);
494
/* The following macro is to make init of Query_arena simpler */
496
#define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE;
498
#define INIT_ARENA_DBUG_INFO
505
List of items created in the parser for this query. Every item puts
506
itself to the list on creation (see Item::Item() for details))
509
MEM_ROOT *mem_root; // Pointer to current memroot
511
bool is_backup_arena; /* True if this arena is used for backup. */
515
The states relfects three diffrent life cycles for three
516
different types of statements:
517
Prepared statement: INITIALIZED -> PREPARED -> EXECUTED.
518
Stored procedure: INITIALIZED_FOR_SP -> EXECUTED.
519
Other statements: CONVENTIONAL_EXECUTION never changes.
523
INITIALIZED= 0, INITIALIZED_FOR_SP= 1, PREPARED= 2,
524
CONVENTIONAL_EXECUTION= 3, EXECUTED= 4, ERROR= -1
529
/* We build without RTTI, so dynamic_cast can't be used. */
532
STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE
535
Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) :
536
free_list(0), mem_root(mem_root_arg), state(state_arg)
537
{ INIT_ARENA_DBUG_INFO; }
539
This constructor is used only when Query_arena is created as
540
backup storage for another instance of Query_arena.
542
Query_arena() { INIT_ARENA_DBUG_INFO; }
544
virtual Type type() const;
545
virtual ~Query_arena() {};
547
inline bool is_stmt_prepare() const { return state == INITIALIZED; }
548
inline bool is_first_sp_execute() const
549
{ return state == INITIALIZED_FOR_SP; }
550
inline bool is_stmt_prepare_or_first_sp_execute() const
551
{ return (int)state < (int)PREPARED; }
552
inline bool is_stmt_prepare_or_first_stmt_execute() const
553
{ return (int)state <= (int)PREPARED; }
554
inline bool is_first_stmt_execute() const { return state == PREPARED; }
555
inline bool is_stmt_execute() const
556
{ return state == PREPARED || state == EXECUTED; }
557
inline bool is_conventional() const
558
{ return state == CONVENTIONAL_EXECUTION; }
560
inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
561
inline void* calloc(size_t size)
564
if ((ptr=alloc_root(mem_root,size)))
568
inline char *strdup(const char *str)
569
{ return strdup_root(mem_root,str); }
570
inline char *strmake(const char *str, size_t size)
571
{ return strmake_root(mem_root,str,size); }
572
inline void *memdup(const void *str, size_t size)
573
{ return memdup_root(mem_root,str,size); }
574
inline void *memdup_w_gap(const void *str, size_t size, uint gap)
577
if ((ptr= alloc_root(mem_root,size+gap)))
578
memcpy(ptr,str,size);
582
void set_query_arena(Query_arena *set);
585
/* Close the active state associated with execution of this statement */
586
virtual void cleanup_stmt();
590
class Server_side_cursor;
594
@brief State of a single command executed against this connection.
596
One connection can contain a lot of simultaneously running statements,
597
some of which could be:
598
- prepared, that is, contain placeholders,
599
- opened as cursors. We maintain 1 to 1 relationship between
600
statement and cursor - if user wants to create another cursor for his
601
query, we create another statement for it.
602
To perform some action with statement we reset THD part to the state of
603
that statement, do the action, and then save back modified state from THD
604
to the statement. It will be changed in near future, and Statement will
608
class Statement: public ilink, public Query_arena
610
Statement(const Statement &rhs); /* not implemented: */
611
Statement &operator=(const Statement &rhs); /* non-copyable */
614
Uniquely identifies each statement object in thread scope; change during
615
statement lifetime. FIXME: must be const
620
MARK_COLUMNS_NONE: Means mark_used_colums is not set and no indicator to
621
handler of fields used is set
622
MARK_COLUMNS_READ: Means a bit in read set is set to inform handler
623
that the field is to be read. If field list contains
624
duplicates, then thd->dup_field is set to point
625
to the last found duplicate.
626
MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
627
that it needs to update this field in write_row
630
enum enum_mark_columns mark_used_columns;
632
LEX_STRING name; /* name for named prepared statements */
633
LEX *lex; // parse tree descriptor
635
Points to the query associated with this statement. It's const, but
636
we need to declare it char * because all table handlers are written
637
in C and need to point to it.
639
Note that if we set query = NULL, we must at the same time set
640
query_length = 0, and protect the whole operation with
641
LOCK_thd_data mutex. To avoid crashes in races, if we do not
642
know that thd->query cannot change at the moment, we should print
643
thd->query like this:
644
(1) reserve the LOCK_thd_data mutex;
645
(2) print or copy the value of query and query_length
646
(3) release LOCK_thd_data mutex.
647
This printing is needed at least in SHOW PROCESSLIST and SHOW
648
ENGINE INNODB STATUS.
650
LEX_STRING query_string;
651
Server_side_cursor *cursor;
653
inline char *query() { return query_string.str; }
654
inline uint32 query_length() { return query_string.length; }
655
void set_query_inner(char *query_arg, uint32 query_length_arg);
658
Name of the current (default) database.
660
If there is the current (default) database, "db" contains its name. If
661
there is no current (default) database, "db" is NULL and "db_length" is
662
0. In other words, "db", "db_length" must either be NULL, or contain a
665
@note this attribute is set and alloced by the slave SQL thread (for
666
the THD of that thread); that thread is (and must remain, for now) the
667
only responsible for freeing this member.
675
/* This constructor is called for backup statements */
678
Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
679
enum enum_state state_arg, ulong id_arg);
680
virtual ~Statement();
682
/* Assign execution context (note: not all members) of given stmt to self */
683
virtual void set_statement(Statement *stmt);
684
void set_n_backup_statement(Statement *stmt, Statement *backup);
685
void restore_backup_statement(Statement *stmt, Statement *backup);
686
/* return class type */
687
virtual Type type() const;
692
Container for all statements created/used in a connection.
693
Statements in Statement_map have unique Statement::id (guaranteed by id
694
assignment in Statement::Statement)
695
Non-empty statement names are unique too: attempt to insert a new statement
696
with duplicate name causes older statement to be deleted
698
Statements are auto-deleted when they are removed from the map and when the
707
int insert(THD *thd, Statement *statement);
709
Statement *find_by_name(LEX_STRING *name)
712
stmt= (Statement*)hash_search(&names_hash, (uchar*)name->str,
717
Statement *find(ulong id)
719
if (last_found_statement == 0 || id != last_found_statement->id)
722
stmt= (Statement *) hash_search(&st_hash, (uchar *) &id, sizeof(id));
723
if (stmt && stmt->name.str)
725
last_found_statement= stmt;
727
return last_found_statement;
730
Close all cursors of this connection that use tables of a storage
731
engine that has transaction-specific state and therefore can not
732
survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed.
734
void close_transient_cursors();
735
void erase(Statement *statement);
736
/* Erase all statements (calls Statement destructor) */
742
I_List<Statement> transient_cursor_list;
743
Statement *last_found_statement;
746
struct st_savepoint {
747
struct st_savepoint *prev;
750
Ha_trx_info *ha_list;
753
enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY};
754
extern const char *xa_state_names[];
756
typedef struct st_xid_state {
757
/* For now, this is only used to catch duplicated external xids */
758
XID xid; // transaction identifier
759
enum xa_states xa_state; // used by external XA only
761
/* Error reported by the Resource Manager (RM) to the Transaction Manager. */
765
extern pthread_mutex_t LOCK_xid_cache;
766
extern HASH xid_cache;
767
bool xid_cache_init(void);
768
void xid_cache_free(void);
769
XID_STATE *xid_cache_search(XID *xid);
770
bool xid_cache_insert(XID *xid, enum xa_states xa_state);
771
bool xid_cache_insert(XID_STATE *xid_state);
772
void xid_cache_delete(XID_STATE *xid_state);
775
@class Security_context
776
@brief A set of THD members describing the current authenticated user.
779
class Security_context {
781
Security_context() {} /* Remove gcc warning */
783
host - host of the client
784
user - user of the client, set to NULL until the user has been read from
786
priv_user - The user privilege we are using. May be "" for anonymous user.
789
char *host, *user, *priv_user, *ip;
790
/* The host privilege we are using */
791
char priv_host[MAX_HOSTNAME];
792
/* points to host if host is available, otherwise points to ip */
793
const char *host_or_ip;
794
ulong master_access; /* Global privileges from mysql.user */
795
ulong db_access; /* Privileges for current db */
800
inline char *priv_host_name()
802
return (*priv_host ? priv_host : (char *)"%");
805
bool set_user(char *user_arg);
807
#ifndef NO_EMBEDDED_ACCESS_CHECKS
809
change_security_context(THD *thd,
810
LEX_STRING *definer_user,
811
LEX_STRING *definer_host,
813
Security_context **backup);
816
restore_security_context(THD *thd, Security_context *backup);
818
bool user_matches(Security_context *);
823
A registry for item tree transformations performed during
824
query optimization. We register only those changes which require
825
a rollback to re-execute a prepared statement or stored procedure
829
struct Item_change_record;
830
typedef I_List<Item_change_record> Item_change_list;
834
Type of prelocked mode.
835
See comment for THD::prelocked_mode for complete description.
838
enum prelocked_mode_type {NON_PRELOCKED= 0, PRELOCKED= 1,
839
PRELOCKED_UNDER_LOCK_TABLES= 2};
843
Class that holds information about tables which were opened and locked
844
by the thread. It is also used to save/restore this information in
845
push_open_tables_state()/pop_open_tables_state().
848
class Open_tables_state
852
As part of class THD, this member is set during execution
853
of a prepared statement. When it is set, it is used
854
by the locking subsystem to report a change in table metadata.
856
When Open_tables_state part of THD is reset to open
857
a system or INFORMATION_SCHEMA table, the member is cleared
858
to avoid spurious ER_NEED_REPREPARE errors -- system and
859
INFORMATION_SCHEMA tables are not subject to metadata version
861
@sa check_and_update_table_version()
863
Reprepare_observer *m_reprepare_observer;
866
List of regular tables in use by this thread. Contains temporary and
867
base tables that were opened with @see open_tables().
871
List of temporary tables used by this thread. Contains user-level
872
temporary tables, created with CREATE TEMPORARY TABLE, and
873
internal temporary tables, created, e.g., to resolve a SELECT,
874
or for an intermediate table used in ALTER.
875
XXX Why are internal temporary tables added to this list?
877
TABLE *temporary_tables;
879
List of tables that were opened with HANDLER OPEN and are
880
still in use by this thread.
882
TABLE *handler_tables;
883
TABLE *derived_tables;
885
During a MySQL session, one can lock tables in two modes: automatic
886
or manual. In automatic mode all necessary tables are locked just before
887
statement execution, and all acquired locks are stored in 'lock'
888
member. Unlocking takes place automatically as well, when the
890
Manual mode comes into play when a user issues a 'LOCK TABLES'
891
statement. In this mode the user can only use the locked tables.
892
Trying to use any other tables will give an error. The locked tables are
893
stored in 'locked_tables' member. Manual locking is described in
894
the 'LOCK_TABLES' chapter of the MySQL manual.
895
See also lock_tables() for details.
899
Tables that were locked with explicit or implicit LOCK TABLES.
900
(Implicit LOCK TABLES happens when we are prelocking tables for
901
execution of statement which uses stored routines. See description
902
THD::prelocked_mode for more info.)
904
MYSQL_LOCK *locked_tables;
907
CREATE-SELECT keeps an extra lock for the table being
908
created. This field is used to keep the extra lock available for
909
lower level routines, which would otherwise miss that lock.
911
MYSQL_LOCK *extra_lock;
914
prelocked_mode_type enum and prelocked_mode member are used for
915
indicating whenever "prelocked mode" is on, and what type of
916
"prelocked mode" is it.
918
Prelocked mode is used for execution of queries which explicitly
919
or implicitly (via views or triggers) use functions, thus may need
920
some additional tables (mentioned in query table list) for their
923
First open_tables() call for such query will analyse all functions
924
used by it and add all additional tables to table its list. It will
925
also mark this query as requiring prelocking. After that lock_tables()
926
will issue implicit LOCK TABLES for the whole table list and change
927
thd::prelocked_mode to non-0. All queries called in functions invoked
928
by the main query will use prelocked tables. Non-0 prelocked_mode
929
will also surpress mentioned analysys in those queries thus saving
930
cycles. Prelocked mode will be turned off once close_thread_tables()
931
for the main query will be called.
933
Note: Since not all "tables" present in table list are really locked
934
thd::prelocked_mode does not imply thd::locked_tables.
936
prelocked_mode_type prelocked_mode;
938
uint current_tablenr;
941
BACKUPS_AVAIL = (1U << 0) /* There are backups available */
945
Flags with information about the open tables state.
950
This constructor serves for creation of Open_tables_state instances
951
which are used as backup storage.
953
Open_tables_state() : state_flags(0U) { }
955
Open_tables_state(ulong version_arg);
957
void set_open_tables_state(Open_tables_state *state)
962
void reset_open_tables_state()
964
open_tables= temporary_tables= handler_tables= derived_tables= 0;
965
extra_lock= lock= locked_tables= 0;
966
prelocked_mode= NON_PRELOCKED;
968
m_reprepare_observer= NULL;
973
@class Sub_statement_state
974
@brief Used to save context when executing a function or trigger
977
/* Defines used for Sub_statement_state::in_sub_stmt */
979
#define SUB_STMT_TRIGGER 1
980
#define SUB_STMT_FUNCTION 2
983
class Sub_statement_state
987
ulonglong first_successful_insert_id_in_prev_stmt;
988
ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row;
989
Discrete_interval auto_inc_interval_for_cur_row;
990
Discrete_intervals_list auto_inc_intervals_forced;
991
ulonglong limit_found_rows;
992
ha_rows cuted_fields, sent_row_count, examined_row_count;
993
ulong client_capabilities;
995
bool enable_slow_log;
996
bool last_insert_id_used;
997
SAVEPOINT *savepoints;
1001
/* Flags for the THD::system_thread variable */
1002
enum enum_thread_type
1004
NON_SYSTEM_THREAD= 0,
1005
SYSTEM_THREAD_DELAYED_INSERT= 1,
1006
SYSTEM_THREAD_SLAVE_IO= 2,
1007
SYSTEM_THREAD_SLAVE_SQL= 4,
1008
SYSTEM_THREAD_NDBCLUSTER_BINLOG= 8,
1009
SYSTEM_THREAD_EVENT_SCHEDULER= 16,
1010
SYSTEM_THREAD_EVENT_WORKER= 32
1014
show_system_thread(enum_thread_type thread)
1016
#define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME
1018
static char buf[64];
1019
RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD);
1020
RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT);
1021
RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO);
1022
RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL);
1023
RETURN_NAME_AS_STRING(SYSTEM_THREAD_NDBCLUSTER_BINLOG);
1024
RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER);
1025
RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER);
1027
sprintf(buf, "<UNKNOWN SYSTEM THREAD: %d>", thread);
1030
#undef RETURN_NAME_AS_STRING
1034
This class represents the interface for internal error handlers.
1035
Internal error handlers are exception handlers used by the server
1038
class Internal_error_handler
1041
Internal_error_handler() :
1042
m_prev_internal_handler(NULL)
1045
virtual ~Internal_error_handler() {}
1049
Handle an error condition.
1050
This method can be implemented by a subclass to achieve any of the
1052
- mask an error internally, prevent exposing it to the user,
1053
- mask an error and throw another one instead.
1054
When this method returns true, the error condition is considered
1055
'handled', and will not be propagated to upper layers.
1056
It is the responsability of the code installing an internal handler
1057
to then check for trapped conditions, and implement logic to recover
1058
from the anticipated conditions trapped during runtime.
1060
This mechanism is similar to C++ try/throw/catch:
1061
- 'try' correspond to <code>THD::push_internal_handler()</code>,
1062
- 'throw' correspond to <code>my_error()</code>,
1063
which invokes <code>my_message_sql()</code>,
1064
- 'catch' correspond to checking how/if an internal handler was invoked,
1065
before removing it from the exception stack with
1066
<code>THD::pop_internal_handler()</code>.
1068
@param sql_errno the error number
1069
@param level the error level
1070
@param thd the calling thread
1071
@return true if the error is handled
1073
virtual bool handle_error(uint sql_errno,
1074
const char *message,
1075
MYSQL_ERROR::enum_warning_level level,
1078
Internal_error_handler *m_prev_internal_handler;
1084
Implements the trivial error handler which cancels all error states
1085
and prevents an SQLSTATE to be set.
1088
class Dummy_error_handler : public Internal_error_handler
1091
bool handle_error(uint sql_errno,
1092
const char *message,
1093
MYSQL_ERROR::enum_warning_level level,
1103
This class is an internal error handler implementation for
1104
DROP TABLE statements. The thing is that there may be warnings during
1105
execution of these statements, which should not be exposed to the user.
1106
This class is intended to silence such warnings.
1109
class Drop_table_error_handler : public Internal_error_handler
1112
Drop_table_error_handler(Internal_error_handler *err_handler)
1113
:m_err_handler(err_handler)
1117
bool handle_error(uint sql_errno,
1118
const char *message,
1119
MYSQL_ERROR::enum_warning_level level,
1123
Internal_error_handler *m_err_handler;
1128
Stores status of the currently executed statement.
1129
Cleared at the beginning of the statement, and then
1130
can hold either OK, ERROR, or EOF status.
1131
Can not be assigned twice per statement.
1134
class Diagnostics_area
1137
enum enum_diagnostics_status
1139
/** The area is cleared at start of a statement. */
1141
/** Set whenever one calls my_ok(). */
1143
/** Set whenever one calls my_eof(). */
1145
/** Set whenever one calls my_error() or my_message(). */
1147
/** Set in case of a custom response, such as one from COM_STMT_PREPARE. */
1150
/** True if status information is sent to the client. */
1152
/** Set to make set_error_status after set_{ok,eof}_status possible. */
1153
bool can_overwrite_status;
1155
void set_ok_status(THD *thd, ha_rows affected_rows_arg,
1156
ulonglong last_insert_id_arg,
1157
const char *message);
1158
void set_eof_status(THD *thd);
1159
void set_error_status(THD *thd, uint sql_errno_arg, const char *message_arg);
1161
void disable_status();
1163
void reset_diagnostics_area();
1165
bool is_set() const { return m_status != DA_EMPTY; }
1166
bool is_error() const { return m_status == DA_ERROR; }
1167
bool is_eof() const { return m_status == DA_EOF; }
1168
bool is_ok() const { return m_status == DA_OK; }
1169
bool is_disabled() const { return m_status == DA_DISABLED; }
1170
enum_diagnostics_status status() const { return m_status; }
1172
const char *message() const
1173
{ DBUG_ASSERT(m_status == DA_ERROR || m_status == DA_OK); return m_message; }
1175
uint sql_errno() const
1176
{ DBUG_ASSERT(m_status == DA_ERROR); return m_sql_errno; }
1178
uint server_status() const
1180
DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
1181
return m_server_status;
1184
ha_rows affected_rows() const
1185
{ DBUG_ASSERT(m_status == DA_OK); return m_affected_rows; }
1187
ulonglong last_insert_id() const
1188
{ DBUG_ASSERT(m_status == DA_OK); return m_last_insert_id; }
1190
uint total_warn_count() const
1192
DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
1193
return m_total_warn_count;
1196
Diagnostics_area() { reset_diagnostics_area(); }
1199
/** Message buffer. Can be used by OK or ERROR status. */
1200
char m_message[MYSQL_ERRMSG_SIZE];
1202
SQL error number. One of ER_ codes from share/errmsg.txt.
1203
Set by set_error_status.
1208
Copied from thd->server_status when the diagnostics area is assigned.
1209
We need this member as some places in the code use the following pattern:
1210
thd->server_status|= ...
1212
thd->server_status&= ~...
1213
Assigned by OK, EOF or ERROR.
1215
uint m_server_status;
1217
The number of rows affected by the last statement. This is
1218
semantically close to thd->row_count_func, but has a different
1219
life cycle. thd->row_count_func stores the value returned by
1220
function ROW_COUNT() and is cleared only by statements that
1221
update its value, such as INSERT, UPDATE, DELETE and few others.
1222
This member is cleared at the beginning of the next statement.
1224
We could possibly merge the two, but life cycle of thd->row_count_func
1227
ha_rows m_affected_rows;
1229
Similarly to the previous member, this is a replacement of
1230
thd->first_successful_insert_id_in_prev_stmt, which is used
1231
to implement LAST_INSERT_ID().
1233
ulonglong m_last_insert_id;
1234
/** The total number of warnings. */
1235
uint m_total_warn_count;
1236
enum_diagnostics_status m_status;
1238
@todo: the following THD members belong here:
1239
- warn_list, warn_count,
1245
Storage engine specific thread local data.
1251
Storage engine specific thread local data.
1252
Lifetime: one user connection.
1256
0: Life time: one statement within a transaction. If @@autocommit is
1257
on, also represents the entire transaction.
1258
@sa trans_register_ha()
1260
1: Life time: one transaction within a connection.
1261
If the storage engine does not participate in a transaction,
1262
this should not be used.
1263
@sa trans_register_ha()
1265
Ha_trx_info ha_info[2];
1267
Ha_data() :ha_ptr(NULL) {}
1273
For each client connection we create a separate thread with THD serving as
1274
a thread/connection descriptor
1277
class THD :public Statement,
1278
public Open_tables_state
1281
/* Used to execute base64 coded binlog events in MySQL server */
1282
Relay_log_info* rli_fake;
1285
Constant for THD::where initialization in the beginning of every query.
1287
It's needed because we do not save/restore THD::where normally during
1288
primary (non subselect) query execution.
1290
static const char * const DEFAULT_WHERE;
1292
#ifdef EMBEDDED_LIBRARY
1293
struct st_mysql *mysql;
1294
unsigned long client_stmt_id;
1295
unsigned long client_param_count;
1296
struct st_mysql_bind *client_params;
1299
struct st_mysql_data *cur_data;
1300
struct st_mysql_data *first_data;
1301
struct st_mysql_data **data_tail;
1302
void clear_data_list();
1303
struct st_mysql_data *alloc_new_dataset();
1305
In embedded server it points to the statement that is processed
1306
in the current query. We store some results directly in statement
1309
struct st_mysql_stmt *current_stmt;
1311
NET net; // client connection descriptor
1312
MEM_ROOT warn_root; // For warnings and errors
1313
Protocol *protocol; // Current protocol
1314
Protocol_text protocol_text; // Normal protocol
1315
Protocol_binary protocol_binary; // Binary protocol
1316
HASH user_vars; // hash for user variables
1317
String packet; // dynamic buffer for network I/O
1318
String convert_buffer; // buffer for charset conversions
1319
struct sockaddr_in remote; // client socket address
1320
struct rand_struct rand; // used for authentication
1321
struct system_variables variables; // Changeable local variables
1322
struct system_status_var status_var; // Per thread statistic vars
1323
struct system_status_var *initial_status_var; /* used by show status */
1324
THR_LOCK_INFO lock_info; // Locking info of this thread
1325
THR_LOCK_OWNER main_lock_id; // To use for conventional queries
1326
THR_LOCK_OWNER *lock_id; // If not main_lock_id, points to
1327
// the lock_id of a cursor.
1329
Protects THD data accessed from other threads:
1330
- thd->query and thd->query_length (used by SHOW ENGINE
1331
INNODB STATUS and SHOW PROCESSLIST
1332
- thd->mysys_var (used by KILL statement and shutdown).
1333
Is locked when THD is deleted.
1335
pthread_mutex_t LOCK_thd_data;
1337
/* all prepared statements and cursors of this connection */
1338
Statement_map stmt_map;
1340
A pointer to the stack frame of handle_one_connection(),
1341
which is called first in the thread for handling a client
1346
Currently selected catalog.
1352
Some members of THD (currently 'Statement::db',
1353
'catalog' and 'query') are set and alloced by the slave SQL thread
1354
(for the THD of that thread); that thread is (and must remain, for now)
1355
the only responsible for freeing these 3 members. If you add members
1356
here, and you add code to set them in replication, don't forget to
1357
free_them_and_set_them_to_0 in replication properly. For details see
1358
the 'err:' label of the handle_slave_sql() in sql/slave.cc.
1360
@see handle_slave_sql
1363
Security_context main_security_ctx;
1364
Security_context *security_ctx;
1367
Points to info-string that we show in SHOW PROCESSLIST
1368
You are supposed to update thd->proc_info only if you have coded
1369
a time-consuming piece that MySQL can get stuck in for a long time.
1371
Set it using the thd_proc_info(THD *thread, const char *message)
1374
This member is accessed and assigned without any synchronization.
1375
Therefore, it may point only to constant (statically
1376
allocated) strings, which memory won't go away over time.
1378
const char *proc_info;
1381
Used in error messages to tell user in what part of MySQL we found an
1382
error. E. g. when where= "having clause", if fix_fields() fails, user
1383
will know that the error was in having clause.
1387
double tmp_double_value; /* Used in set_var.cc */
1388
ulong client_capabilities; /* What the client supports */
1389
ulong max_client_packet_length;
1391
HASH handler_tables_hash;
1393
One thread can hold up to one named user-level lock. This variable
1394
points to a lock object if the lock is present. See item_func.cc and
1395
chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
1397
User_level_lock *ull;
1399
uint dbug_sentry; // watch out for memory corruption
1401
struct st_my_thread_var *mysys_var;
1403
Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
1404
first byte of the packet in do_command()
1406
enum enum_server_command command;
1408
uint32 file_id; // for LOAD DATA INFILE
1409
/* remote (peer) port */
1411
time_t start_time, user_time;
1412
// track down slow pthread_create
1413
ulonglong prior_thr_create_utime, thr_create_utime;
1414
ulonglong start_utime, utime_after_lock;
1416
thr_lock_type update_lock_default;
1419
/* <> 0 if we are inside of trigger or stored function. */
1421
/* TRUE when the current top has SQL_LOG_BIN ON */
1422
bool sql_log_bin_toplevel;
1424
/* container for handler's private per-connection data */
1425
Ha_data ha_data[MAX_HA];
1427
#ifndef MYSQL_CLIENT
1428
int binlog_setup_trx_data();
1431
Public interface to write RBR events to the binlog
1433
void binlog_start_trans_and_stmt();
1434
void binlog_set_stmt_begin();
1435
int binlog_write_table_map(TABLE *table, bool is_transactional);
1436
int binlog_write_row(TABLE* table, bool is_transactional,
1437
MY_BITMAP const* cols, size_t colcnt,
1439
int binlog_delete_row(TABLE* table, bool is_transactional,
1440
MY_BITMAP const* cols, size_t colcnt,
1442
int binlog_update_row(TABLE* table, bool is_transactional,
1443
MY_BITMAP const* cols, size_t colcnt,
1444
const uchar *old_data, const uchar *new_data);
1446
void set_server_id(uint32 sid) { server_id = sid; }
1449
Member functions to handle pending event for row-level logging.
1451
template <class RowsEventT> Rows_log_event*
1452
binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
1453
MY_BITMAP const* cols,
1456
bool is_transactional,
1458
Rows_log_event* binlog_get_pending_rows_event() const;
1459
void binlog_set_pending_rows_event(Rows_log_event* ev);
1460
int binlog_flush_pending_rows_event(bool stmt_end);
1461
int binlog_remove_pending_rows_event(bool clear_maps);
1465
Number of outstanding table maps, i.e., table maps in the
1468
uint binlog_table_maps;
1470
enum enum_binlog_flag {
1471
BINLOG_FLAG_UNSAFE_STMT_PRINTED,
1476
Flags with per-thread information regarding the status of the
1479
uint32 binlog_flags;
1481
uint get_binlog_table_maps() const {
1482
return binlog_table_maps;
1484
#endif /* MYSQL_CLIENT */
1488
struct st_transactions {
1489
SAVEPOINT *savepoints;
1490
THD_TRANS all; // Trans since BEGIN WORK
1491
THD_TRANS stmt; // Trans for current statement
1492
bool on; // see ha_enable_transaction()
1493
XID_STATE xid_state;
1494
Rows_log_event *m_pending_rows_event;
1497
Tables changed in transaction (that must be invalidated in query cache).
1498
List contain only transactional tables, that not invalidated in query
1499
cache (instead of full list of changed in transaction tables).
1501
CHANGED_TABLE_LIST* changed_tables;
1502
MEM_ROOT mem_root; // Transaction-life memory allocation pool
1508
If rm_error is raised, it means that this piece of a distributed
1509
transaction has failed and must be rolled back. But the user must
1510
rollback it explicitly, so don't start a new distributed XA until
1513
if (!xid_state.rm_error)
1514
xid_state.xid.null();
1515
#ifdef USING_TRANSACTIONS
1516
free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
1521
#ifdef USING_TRANSACTIONS
1522
bzero((char*)this, sizeof(*this));
1523
xid_state.xid.null();
1524
init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
1526
xid_state.xa_state= XA_NOTR;
1534
#ifdef SIGNAL_WITH_VIO_CLOSE
1538
This is to track items changed during execution of a prepared
1539
statement/stored procedure. It's created by
1540
register_item_tree_change() in memory root of THD, and freed in
1541
rollback_item_tree_changes(). For conventional execution it's always
1544
Item_change_list change_list;
1547
A permanent memory area of the statement. For conventional
1548
execution, the parsed tree and execution runtime reside in the same
1549
memory root. In this case stmt_arena points to THD. In case of
1550
a prepared statement or a stored procedure statement, thd->mem_root
1551
conventionally points to runtime memory, and thd->stmt_arena
1552
points to the memory of the PS/SP, where the parsed tree of the
1553
statement resides. Whenever you need to perform a permanent
1554
transformation of a parsed tree, you should allocate new memory in
1555
stmt_arena, to allow correct re-execution of PS/SP.
1556
Note: in the parser, stmt_arena == thd, even for PS/SP.
1558
Query_arena *stmt_arena;
1561
map for tables that will be updated for a multi-table update query
1562
statement, for other query statements, this will be zero.
1564
table_map table_map_for_update;
1566
/* Tells if LAST_INSERT_ID(#) was called for the current statement */
1567
bool arg_of_last_insert_id_function;
1569
ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
1570
insertion into an auto_increment column".
1573
This is the first autogenerated insert id which was *successfully*
1574
inserted by the previous statement (exactly, if the previous statement
1575
didn't successfully insert an autogenerated insert id, then it's the one
1576
of the statement before, etc).
1577
It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
1578
It is returned by LAST_INSERT_ID().
1580
ulonglong first_successful_insert_id_in_prev_stmt;
1582
Variant of the above, used for storing in statement-based binlog. The
1583
difference is that the one above can change as the execution of a stored
1584
function progresses, while the one below is set once and then does not
1585
change (which is the value which statement-based binlog needs).
1587
ulonglong first_successful_insert_id_in_prev_stmt_for_binlog;
1589
This is the first autogenerated insert id which was *successfully*
1590
inserted by the current statement. It is maintained only to set
1591
first_successful_insert_id_in_prev_stmt when statement ends.
1593
ulonglong first_successful_insert_id_in_cur_stmt;
1595
We follow this logic:
1596
- when stmt starts, first_successful_insert_id_in_prev_stmt contains the
1597
first insert id successfully inserted by the previous stmt.
1598
- as stmt makes progress, handler::insert_id_for_cur_row changes;
1599
every time get_auto_increment() is called,
1600
auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
1601
reserved interval (if statement-based binlogging).
1602
- at first successful insertion of an autogenerated value,
1603
first_successful_insert_id_in_cur_stmt is set to
1604
handler::insert_id_for_cur_row.
1605
- when stmt goes to binlog,
1606
auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
1608
- when stmt ends, first_successful_insert_id_in_prev_stmt is set to
1609
first_successful_insert_id_in_cur_stmt.
1612
stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
1613
LAST_INSERT_ID() is used by a statement.
1614
If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
1615
stored in the statement-based binlog.
1616
This variable is CUMULATIVE along the execution of a stored function or
1617
trigger: if one substatement sets it to 1 it will stay 1 until the
1618
function/trigger ends, thus making sure that
1619
first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
1620
and is propagated to the caller for binlogging.
1622
bool stmt_depends_on_first_successful_insert_id_in_prev_stmt;
1624
List of auto_increment intervals reserved by the thread so far, for
1625
storage in the statement-based binlog.
1626
Note that its minimum is not first_successful_insert_id_in_cur_stmt:
1627
assuming a table with an autoinc column, and this happens:
1628
INSERT INTO ... VALUES(3);
1629
SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
1630
then the latter INSERT will insert no rows
1631
(first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
1632
in the binlog is still needed; the list's minimum will contain 3.
1633
This variable is cumulative: if several statements are written to binlog
1634
as one (stored functions or triggers are used) this list is the
1635
concatenation of all intervals reserved by all statements.
1637
Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
1638
/* Used by replication and SET INSERT_ID */
1639
Discrete_intervals_list auto_inc_intervals_forced;
1641
There is BUG#19630 where statement-based replication of stored
1642
functions/triggers with two auto_increment columns breaks.
1643
We however ensure that it works when there is 0 or 1 auto_increment
1644
column; our rules are
1645
a) on master, while executing a top statement involving substatements,
1646
first top- or sub- statement to generate auto_increment values wins the
1647
exclusive right to see its values be written to binlog (the write
1648
will be done by the statement or its caller), and the losers won't see
1649
their values be written to binlog.
1650
b) on slave, while replicating a top statement involving substatements,
1651
first top- or sub- statement to need to read auto_increment values from
1652
the master's binlog wins the exclusive right to read them (so the losers
1653
won't read their values from binlog but instead generate on their own).
1654
a) implies that we mustn't backup/restore
1655
auto_inc_intervals_in_cur_stmt_for_binlog.
1656
b) implies that we mustn't backup/restore auto_inc_intervals_forced.
1658
If there are more than 1 auto_increment columns, then intervals for
1659
different columns may mix into the
1660
auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
1661
but there is no point in preventing this mixing by preventing intervals
1662
from the secondly inserted column to come into the list, as such
1663
prevention would be wrong too.
1664
What will happen in the case of
1665
INSERT INTO t1 (auto_inc) VALUES(NULL);
1666
where t1 has a trigger which inserts into an auto_inc column of t2, is
1667
that in binlog we'll store the interval of t1 and the interval of t2 (when
1668
we store intervals, soon), then in slave, t1 will use both intervals, t2
1669
will use none; if t1 inserts the same number of rows as on master,
1670
normally the 2nd interval will not be used by t1, which is fine. t2's
1671
values will be wrong if t2's internal auto_increment counter is different
1672
from what it was on master (which is likely). In 5.1, in mixed binlogging
1673
mode, row-based binlogging is used for such cases where two
1674
auto_increment columns are inserted.
1676
inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)
1678
if (first_successful_insert_id_in_cur_stmt == 0)
1679
first_successful_insert_id_in_cur_stmt= id_arg;
1681
inline ulonglong read_first_successful_insert_id_in_prev_stmt(void)
1683
if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt)
1685
/* It's the first time we read it */
1686
first_successful_insert_id_in_prev_stmt_for_binlog=
1687
first_successful_insert_id_in_prev_stmt;
1688
stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1;
1690
return first_successful_insert_id_in_prev_stmt;
1693
Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
1694
(mysqlbinlog). We'll soon add a variant which can take many intervals in
1697
inline void force_one_auto_inc_interval(ulonglong next_id)
1699
auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
1700
auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0);
1703
ulonglong limit_found_rows;
1704
ulonglong options; /* Bitmap of states */
1705
longlong row_count_func; /* For the ROW_COUNT() function */
1706
ha_rows cuted_fields;
1709
number of rows we actually sent to the client, including "synthetic"
1712
ha_rows sent_row_count;
1715
number of rows we read, sent or not, including in create_sort_index()
1717
ha_rows examined_row_count;
1720
The set of those tables whose fields are referenced in all subqueries
1722
TODO: possibly this it is incorrect to have used tables in THD because
1723
with more than one subquery, it is not clear what does the field mean.
1725
table_map used_tables;
1726
USER_CONN *user_connect;
1727
CHARSET_INFO *db_charset;
1729
FIXME: this, and some other variables like 'count_cuted_fields'
1730
maybe should be statement/cursor local, that is, moved to Statement
1731
class. With current implementation warnings produced in each prepared
1732
statement/cursor settle here.
1734
List <MYSQL_ERROR> warn_list;
1735
uint warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END];
1736
uint total_warn_count;
1737
Diagnostics_area main_da;
1738
#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
1739
PROFILING profiling;
1743
Id of current query. Statement can be reused to execute several queries
1744
query_id is global in context of the whole MySQL server.
1745
ID is automatically generated from mutex-protected counter.
1746
It's used in handler code for various purposes: to check which columns
1747
from table are necessary for this select, to check if it's necessary to
1748
update auto-updatable fields (like auto_increment and timestamp).
1750
query_id_t query_id, warn_id;
1753
#ifdef ERROR_INJECT_SUPPORT
1754
ulong error_inject_value;
1756
/* Statement id is thread-wide. This counter is used to generate ids */
1757
ulong statement_id_counter;
1758
ulong rand_saved_seed1, rand_saved_seed2;
1760
Row counter, mainly for errors and warnings. Not increased in
1761
create_sort_index(); may differ from examined_row_count.
1764
pthread_t real_id; /* For debugging */
1765
my_thread_id thread_id;
1766
uint tmp_table, global_read_lock;
1767
uint server_status,open_options;
1768
enum enum_thread_type system_thread;
1769
uint select_number; //number of select (used for EXPLAIN)
1770
/* variables.transaction_isolation is reset to this after each commit */
1771
enum_tx_isolation session_tx_isolation;
1772
enum_check_fields count_cuted_fields;
1774
DYNAMIC_ARRAY user_var_events; /* For user variables replication */
1775
MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */
1781
KILL_CONNECTION=ER_SERVER_SHUTDOWN,
1782
KILL_QUERY=ER_QUERY_INTERRUPTED,
1783
KILLED_NO_VALUE /* means neither of the states */
1785
killed_state volatile killed;
1787
/* scramble - random string sent to client on handshake */
1788
char scramble[SCRAMBLE_LENGTH+1];
1790
bool slave_thread, one_shot_set;
1791
/* tells if current statement should binlog row-based(1) or stmt-based(0) */
1792
bool current_stmt_binlog_row_based;
1793
bool locked, some_tables_deleted;
1794
bool last_cuted_field;
1795
bool no_errors, password;
1797
Set to TRUE if execution of the current compound statement
1798
can not continue. In particular, disables activation of
1799
CONTINUE or EXIT handlers of stored routines.
1800
Reset in the end of processing of the current user request, in
1801
@see mysql_reset_thd_for_next_command().
1803
bool is_fatal_error;
1805
Set by a storage engine to request the entire
1806
transaction (that possibly spans multiple engines) to
1807
rollback. Reset in ha_rollback.
1809
bool transaction_rollback_request;
1811
TRUE if we are in a sub-statement and the current error can
1812
not be safely recovered until we left the sub-statement mode.
1813
In particular, disables activation of CONTINUE and EXIT
1814
handlers inside sub-statements. E.g. if it is a deadlock
1815
error and requires a transaction-wide rollback, this flag is
1816
raised (traditionally, MySQL first has to close all the reads
1817
via @see handler::ha_index_or_rnd_end() and only then perform
1819
Reset to FALSE when we leave the sub-statement mode.
1821
bool is_fatal_sub_stmt_error;
1822
bool query_start_used, rand_used, time_zone_used;
1823
/* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
1824
bool substitute_null_with_insert_id;
1825
bool in_lock_tables;
1827
True if a slave error. Causes the slave to stop. Not the same
1828
as the statement execution error (is_error()), since
1829
a statement may be expected to return an error, e.g. because
1830
it returned an error on master, and this is OK on the slave.
1832
bool is_slave_error;
1833
bool bootstrap, cleanup_done;
1835
/** is set if some thread specific value(s) used in a statement. */
1836
bool thread_specific_used;
1837
bool charset_is_system_charset, charset_is_collation_connection;
1838
bool charset_is_character_set_filesystem;
1839
bool enable_slow_log; /* enable slow log for current statement */
1840
bool abort_on_warning;
1841
bool got_warning; /* Set on call to push_warning() */
1842
bool no_warnings_for_error; /* no warnings on call to my_error() */
1843
/* set during loop of derived table processing */
1844
bool derived_tables_processing;
1845
my_bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */
1847
sp_rcontext *spcont; // SP runtime context
1848
sp_cache *sp_proc_cache;
1849
sp_cache *sp_func_cache;
1851
/** number of name_const() substitutions, see sp_head.cc:subst_spvars() */
1852
uint query_name_consts;
1855
If we do a purge of binary logs, log index info of the threads
1856
that are currently reading it needs to be adjusted. To do that
1857
each thread that is using LOG_INFO needs to adjust the pointer to it
1859
LOG_INFO* current_linfo;
1860
NET* slave_net; // network connection from slave -> m.
1861
/* Used by the sys_var class to store temporary values */
1864
my_bool my_bool_value;
1867
ulonglong ulonglong_value;
1872
If true, mysql_bin_log::write(Log_event) call will not write events to
1873
binlog, and maintain 2 below variables instead (use
1874
mysql_bin_log.start_union_events to turn this on)
1878
If TRUE, at least one mysql_bin_log::write(Log_event) call has been
1879
made after last mysql_bin_log.start_union_events() call.
1881
bool unioned_events;
1883
If TRUE, at least one mysql_bin_log::write(Log_event e), where
1884
e.cache_stmt == TRUE call has been made after last
1885
mysql_bin_log.start_union_events() call.
1887
bool unioned_events_trans;
1890
'queries' (actually SP statements) that run under inside this binlog
1891
union have thd->query_id >= first_query_id.
1893
query_id_t first_query_id;
1897
Internal parser state.
1898
Note that since the parser is not re-entrant, we keep only one parser
1899
state here. This member is valid only when executing code during parsing.
1901
Parser_state *m_parser_state;
1903
#ifdef WITH_PARTITION_STORAGE_ENGINE
1904
partition_info *work_part_info;
1907
#if defined(ENABLED_DEBUG_SYNC)
1908
/* Debug Sync facility. See debug_sync.cc. */
1909
struct st_debug_sync_control *debug_sync_control;
1910
#endif /* defined(ENABLED_DEBUG_SYNC) */
1917
Initialize memory roots necessary for query processing and (!)
1918
pre-allocate memory for it. We can't do that in THD constructor because
1919
there are use cases (acl_init, delayed inserts, watcher threads,
1920
killing mysqld) where it's vital to not allocate excessive and not used
1921
memory. Note, that we still don't return error from init_for_queries():
1922
if preallocation fails, we should notice that at the first call to
1925
void init_for_queries();
1926
void change_user(void);
1928
void cleanup_after_query();
1929
bool store_globals();
1930
#ifdef SIGNAL_WITH_VIO_CLOSE
1931
inline void set_active_vio(Vio* vio)
1933
pthread_mutex_lock(&LOCK_thd_data);
1935
pthread_mutex_unlock(&LOCK_thd_data);
1937
inline void clear_active_vio()
1939
pthread_mutex_lock(&LOCK_thd_data);
1941
pthread_mutex_unlock(&LOCK_thd_data);
1943
void close_active_vio();
1945
void awake(THD::killed_state state_to_set);
1947
#ifndef MYSQL_CLIENT
1948
enum enum_binlog_query_type {
1950
The query can be logged row-based or statement-based
1955
The query has to be logged statement-based
1960
The query represents a change to a table in the "mysql"
1961
database and is currently mapped to ROW_QUERY_TYPE.
1967
int binlog_query(enum_binlog_query_type qtype,
1968
char const *query, ulong query_len,
1969
bool is_trans, bool suppress_use,
1974
For enter_cond() / exit_cond() to work the mutex must be got before
1975
enter_cond(); this mutex is then released by exit_cond().
1976
Usage must be: lock mutex; enter_cond(); your code; exit_cond().
1978
inline const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex,
1981
const char* old_msg = proc_info;
1982
safe_mutex_assert_owner(mutex);
1983
mysys_var->current_mutex = mutex;
1984
mysys_var->current_cond = cond;
1988
inline void exit_cond(const char* old_msg)
1991
Putting the mutex unlock in exit_cond() ensures that
1992
mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
1993
locked (if that would not be the case, you'll get a deadlock if someone
1994
does a THD::awake() on you).
1996
pthread_mutex_unlock(mysys_var->current_mutex);
1997
pthread_mutex_lock(&mysys_var->mutex);
1998
mysys_var->current_mutex = 0;
1999
mysys_var->current_cond = 0;
2000
proc_info = old_msg;
2001
pthread_mutex_unlock(&mysys_var->mutex);
2003
inline time_t query_start() { query_start_used=1; return start_time; }
2004
inline void set_time()
2008
start_time= user_time;
2009
start_utime= utime_after_lock= my_micro_time();
2012
start_utime= utime_after_lock= my_micro_time_and_time(&start_time);
2014
inline void set_current_time() { start_time= my_time(MY_WME); }
2015
inline void set_time(time_t t)
2017
start_time= user_time= t;
2018
start_utime= utime_after_lock= my_micro_time();
2020
void set_time_after_lock() { utime_after_lock= my_micro_time(); }
2021
ulonglong current_utime() { return my_micro_time(); }
2022
inline ulonglong found_rows(void)
2024
return limit_found_rows;
2026
inline bool active_transaction()
2028
#ifdef USING_TRANSACTIONS
2029
return server_status & SERVER_STATUS_IN_TRANS;
2034
inline bool fill_derived_tables()
2036
return !stmt_arena->is_stmt_prepare() && !lex->only_view_structure();
2038
inline bool fill_information_schema_tables()
2040
return !stmt_arena->is_stmt_prepare();
2042
inline void* trans_alloc(unsigned int size)
2044
return alloc_root(&transaction.mem_root,size);
2047
LEX_STRING *make_lex_string(LEX_STRING *lex_str,
2048
const char* str, uint length,
2049
bool allocate_lex_string);
2051
bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
2052
const char *from, uint from_length,
2053
CHARSET_INFO *from_cs);
2055
bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs);
2057
void add_changed_table(TABLE *table);
2058
void add_changed_table(const char *key, long key_length);
2059
CHANGED_TABLE_LIST * changed_table_dup(const char *key, long key_length);
2060
int send_explain_fields(select_result *result);
2061
#ifndef EMBEDDED_LIBRARY
2063
Clear the current error, if any.
2064
We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
2065
assume this is never called if the fatal error is set.
2066
@todo: To silence an error, one should use Internal_error_handler
2067
mechanism. In future this function will be removed.
2069
inline void clear_error()
2071
DBUG_ENTER("clear_error");
2072
if (main_da.is_error())
2073
main_da.reset_diagnostics_area();
2077
inline bool vio_ok() const { return net.vio != 0; }
2080
inline bool vio_ok() const { return true; }
2083
Mark the current error as fatal. Warning: this does not
2084
set any error, it sets a property of the error, so must be
2085
followed or prefixed with my_error().
2087
inline void fatal_error()
2090
DBUG_PRINT("error",("Fatal error set"));
2093
TRUE if there is an error in the error stack.
2095
Please use this method instead of direct access to
2098
If TRUE, the current (sub)-statement should be aborted.
2099
The main difference between this member and is_fatal_error
2100
is that a fatal error can not be handled by a stored
2101
procedure continue handler, whereas a normal error can.
2103
To raise this flag, use my_error().
2105
inline bool is_error() const { return main_da.is_error(); }
2106
inline CHARSET_INFO *charset() { return variables.character_set_client; }
2107
void update_charset();
2109
inline Query_arena *activate_stmt_arena_if_needed(Query_arena *backup)
2112
Use the persistent arena if we are in a prepared statement or a stored
2113
procedure statement and we have not already changed to use this arena.
2115
if (!stmt_arena->is_conventional() && mem_root != stmt_arena->mem_root)
2117
set_n_backup_active_arena(stmt_arena, backup);
2123
void change_item_tree(Item **place, Item *new_value)
2125
/* TODO: check for OOM condition here */
2126
if (!stmt_arena->is_conventional())
2127
nocheck_register_item_tree_change(place, *place, mem_root);
2130
void nocheck_register_item_tree_change(Item **place, Item *old_value,
2131
MEM_ROOT *runtime_memroot);
2132
void rollback_item_tree_changes();
2135
Cleanup statement parse state (parse tree, lex) and execution
2136
state after execution of a non-prepared SQL statement.
2138
void end_statement();
2139
inline int killed_errno() const
2141
killed_state killed_val; /* to cache the volatile 'killed' */
2142
return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0;
2144
inline void send_kill_message() const
2146
int err= killed_errno();
2149
if ((err == KILL_CONNECTION) && !shutdown_in_progress)
2151
my_message(err, ER(err), MYF(0));
2154
/* return TRUE if we will abort query if we make a warning now */
2155
inline bool really_abort_on_warning()
2157
return (abort_on_warning &&
2158
(!transaction.stmt.modified_non_trans_table ||
2159
(variables.sql_mode & MODE_STRICT_ALL_TABLES)));
2161
void set_status_var_init();
2162
bool is_context_analysis_only()
2163
{ return stmt_arena->is_stmt_prepare() || lex->view_prepare_mode; }
2164
void reset_n_backup_open_tables_state(Open_tables_state *backup);
2165
void restore_backup_open_tables_state(Open_tables_state *backup);
2166
void reset_sub_statement_state(Sub_statement_state *backup, uint new_state);
2167
void restore_sub_statement_state(Sub_statement_state *backup);
2168
void set_n_backup_active_arena(Query_arena *set, Query_arena *backup);
2169
void restore_active_arena(Query_arena *set, Query_arena *backup);
2171
inline void set_current_stmt_binlog_row_based_if_mixed()
2174
If in a stored/function trigger, the caller should already have done the
2175
change. We test in_sub_stmt to prevent introducing bugs where people
2176
wouldn't ensure that, and would switch to row-based mode in the middle
2177
of executing a stored function/trigger (which is too late, see also
2178
reset_current_stmt_binlog_row_based()); this condition will make their
2179
tests fail and so force them to propagate the
2180
lex->binlog_row_based_if_mixed upwards to the caller.
2182
if ((variables.binlog_format == BINLOG_FORMAT_MIXED) &&
2184
current_stmt_binlog_row_based= TRUE;
2186
inline void set_current_stmt_binlog_row_based()
2188
current_stmt_binlog_row_based= TRUE;
2190
inline void clear_current_stmt_binlog_row_based()
2192
current_stmt_binlog_row_based= FALSE;
2194
inline void reset_current_stmt_binlog_row_based()
2197
If there are temporary tables, don't reset back to
2198
statement-based. Indeed it could be that:
2199
CREATE TEMPORARY TABLE t SELECT UUID(); # row-based
2200
# and row-based does not store updates to temp tables
2202
INSERT INTO u SELECT * FROM t; # stmt-based
2203
and then the INSERT will fail as data inserted into t was not logged.
2204
So we continue with row-based until the temp table is dropped.
2205
If we are in a stored function or trigger, we mustn't reset in the
2206
middle of its execution (as the binary logging way of a stored function
2207
or trigger is decided when it starts executing, depending for example on
2208
the caller (for a stored function: if caller is SELECT or
2209
INSERT/UPDATE/DELETE...).
2211
Don't reset binlog format for NDB binlog injector thread.
2214
("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s",
2215
YESNO(temporary_tables), YESNO(in_sub_stmt),
2216
show_system_thread(system_thread)));
2217
if ((temporary_tables == NULL) && (in_sub_stmt == 0) &&
2218
(system_thread != SYSTEM_THREAD_NDBCLUSTER_BINLOG))
2220
current_stmt_binlog_row_based=
2221
test(variables.binlog_format == BINLOG_FORMAT_ROW);
2226
Set the current database; use deep copy of C-string.
2228
@param new_db a pointer to the new database name.
2229
@param new_db_len length of the new database name.
2231
Initialize the current database from a NULL-terminated string with
2232
length. If we run out of memory, we free the current database and
2233
return TRUE. This way the user will notice the error as there will be
2234
no current database selected (in addition to the error message set by
2237
@note This operation just sets {db, db_length}. Switching the current
2238
database usually involves other actions, like switching other database
2239
attributes including security context. In the future, this operation
2240
will be made private and more convenient interface will be provided.
2242
@return Operation status
2243
@retval FALSE Success
2244
@retval TRUE Out-of-memory error
2246
bool set_db(const char *new_db, size_t new_db_len)
2248
/* Do not reallocate memory if current chunk is big enough. */
2249
if (db && new_db && db_length >= new_db_len)
2250
memcpy(db, new_db, new_db_len+1);
2254
db= new_db ? my_strndup(new_db, new_db_len, MYF(MY_WME)) : NULL;
2256
db_length= db ? new_db_len : 0;
2257
return new_db && !db;
2261
Set the current database; use shallow copy of C-string.
2263
@param new_db a pointer to the new database name.
2264
@param new_db_len length of the new database name.
2266
@note This operation just sets {db, db_length}. Switching the current
2267
database usually involves other actions, like switching other database
2268
attributes including security context. In the future, this operation
2269
will be made private and more convenient interface will be provided.
2271
void reset_db(char *new_db, size_t new_db_len)
2274
db_length= new_db_len;
2277
Copy the current database to the argument. Use the current arena to
2278
allocate memory for a deep copy: current database may be freed after
2279
a statement is parsed but before it's executed.
2281
bool copy_db_to(char **p_db, size_t *p_db_length)
2285
my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
2288
*p_db= strmake(db, db_length);
2289
*p_db_length= db_length;
2292
thd_scheduler scheduler;
2295
inline Internal_error_handler *get_internal_handler()
2296
{ return m_internal_handler; }
2299
Add an internal error handler to the thread execution context.
2300
@param handler the exception handler to add
2302
void push_internal_handler(Internal_error_handler *handler);
2305
Handle an error condition.
2306
@param sql_errno the error number
2307
@param level the error level
2308
@return true if the error is handled
2310
virtual bool handle_error(uint sql_errno, const char *message,
2311
MYSQL_ERROR::enum_warning_level level);
2314
Remove the error handler last pushed.
2316
Internal_error_handler *pop_internal_handler();
2318
/** Overloaded to guard query/query_length fields */
2319
virtual void set_statement(Statement *stmt);
2322
Assign a new value to thd->query.
2323
Protected with LOCK_thd_data mutex.
2325
void set_query(char *query_arg, uint32 query_length_arg);
2327
/** The current internal error handler for this thread, or NULL. */
2328
Internal_error_handler *m_internal_handler;
2330
The lex to hold the parsed tree of conventional (non-prepared) queries.
2331
Whereas for prepared and stored procedure statements we use an own lex
2332
instance for each new query, for conventional statements we reuse
2333
the same lex. (@see mysql_parse for details).
2337
This memory root is used for two purposes:
2338
- for conventional queries, to allocate structures stored in main_lex
2339
during parsing, and allocate runtime data (execution plan, etc.)
2341
- for prepared queries, only to allocate runtime data. The parsed
2342
tree itself is reused between executions and thus is stored elsewhere.
2344
MEM_ROOT main_mem_root;
2348
/** A short cut for thd->main_da.set_ok_status(). */
2351
my_ok(THD *thd, ha_rows affected_rows= 0, ulonglong id= 0,
2352
const char *message= NULL)
2354
thd->main_da.set_ok_status(thd, affected_rows, id, message);
2358
/** A short cut for thd->main_da.set_eof_status(). */
2363
thd->main_da.set_eof_status(thd);
2366
#define tmp_disable_binlog(A) \
2367
{ulonglong tmp_disable_binlog__save_options= (A)->options; \
2368
(A)->options&= ~OPTION_BIN_LOG
2370
#define reenable_binlog(A) (A)->options= tmp_disable_binlog__save_options;}
2374
Used to hold information about file and file structure in exchange
2375
via non-DB file (...INTO OUTFILE..., ...LOAD DATA...)
2376
XXX: We never call destructor for objects of this class.
2379
class sql_exchange :public Sql_alloc
2383
String *field_term,*enclosed,*line_term,*line_start,*escaped;
2388
sql_exchange(char *name,bool dumpfile_flag);
2389
bool escaped_given(void);
2392
#include "log_event.h"
2395
This is used to get result from a select
2400
class select_result :public Sql_alloc {
2403
SELECT_LEX_UNIT *unit;
2407
virtual ~select_result() {};
2408
virtual int prepare(List<Item> &list, SELECT_LEX_UNIT *u)
2413
virtual int prepare2(void) { return 0; }
2415
Because of peculiarities of prepared statements protocol
2416
we need to know number of columns in the result set (if
2417
there is a result set) apart from sending columns metadata.
2419
virtual uint field_count(List<Item> &fields) const
2420
{ return fields.elements; }
2421
virtual bool send_fields(List<Item> &list, uint flags)=0;
2422
virtual bool send_data(List<Item> &items)=0;
2423
virtual bool initialize_tables (JOIN *join=0) { return 0; }
2424
virtual void send_error(uint errcode,const char *err);
2425
virtual bool send_eof()=0;
2427
Check if this query returns a result set and therefore is allowed in
2428
cursors and set an error message if it is not the case.
2430
@retval FALSE success
2431
@retval TRUE error, an error message is set
2433
virtual bool check_simple_select() const;
2434
virtual void abort() {}
2436
Cleanup instance of this class for next execution of a prepared
2437
statement/stored procedure.
2439
virtual void cleanup();
2440
void set_thd(THD *thd_arg) { thd= thd_arg; }
2442
The nest level, if supported.
2444
-1 if nest level is undefined, otherwise a positive integer.
2446
int get_nest_level() { return nest_level; }
2447
#ifdef EMBEDDED_LIBRARY
2448
virtual void begin_dataset() {}
2450
void begin_dataset() {}
2456
Base class for select_result descendands which intercept and
2457
transform result set rows. As the rows are not sent to the client,
2458
sending of result set metadata should be suppressed as well.
2461
class select_result_interceptor: public select_result
2464
select_result_interceptor() {} /* Remove gcc warning */
2465
uint field_count(List<Item> &fields) const { return 0; }
2466
bool send_fields(List<Item> &fields, uint flag) { return FALSE; }
2470
class select_send :public select_result {
2472
True if we have sent result set metadata to the client.
2473
In this case the client always expects us to end the result
2474
set with an eof or error packet
2476
bool is_result_set_started;
2478
select_send() :is_result_set_started(FALSE) {}
2479
bool send_fields(List<Item> &list, uint flags);
2480
bool send_data(List<Item> &items);
2482
virtual bool check_simple_select() const { return FALSE; }
2484
virtual void cleanup();
2488
class select_to_file :public select_result_interceptor {
2490
sql_exchange *exchange;
2494
char path[FN_REFLEN];
2497
select_to_file(sql_exchange *ex) :exchange(ex), file(-1),row_count(0L)
2500
void send_error(uint errcode,const char *err);
2506
#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
2510
List of all possible characters of a numeric value text representation.
2512
#define NUMERIC_CHARS ".0123456789e+-"
2515
class select_export :public select_to_file {
2516
uint field_term_length;
2517
int field_sep_char,escape_char,line_sep_char;
2518
int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT
2520
The is_ambiguous_field_sep field is true if a value of the field_sep_char
2521
field is one of the 'n', 't', 'r' etc characters
2522
(see the READ_INFO::unescape method and the ESCAPE_CHARS constant value).
2524
bool is_ambiguous_field_sep;
2526
The is_ambiguous_field_term is true if field_sep_char contains the first
2527
char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can
2528
contain this character.
2530
bool is_ambiguous_field_term;
2532
The is_unsafe_field_sep field is true if a value of the field_sep_char
2533
field is one of the '0'..'9', '+', '-', '.' and 'e' characters
2534
(see the NUMERIC_CHARS constant value).
2536
bool is_unsafe_field_sep;
2537
bool fixed_row_size;
2538
CHARSET_INFO *write_cs; // output charset
2540
select_export(sql_exchange *ex) :select_to_file(ex) {}
2542
Creates a select_export to represent INTO OUTFILE <filename> with a
2543
defined level of subquery nesting.
2545
select_export(sql_exchange *ex, uint nest_level_arg) :select_to_file(ex)
2547
nest_level= nest_level_arg;
2550
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2551
bool send_data(List<Item> &items);
2555
class select_dump :public select_to_file {
2557
select_dump(sql_exchange *ex) :select_to_file(ex) {}
2559
Creates a select_export to represent INTO DUMPFILE <filename> with a
2560
defined level of subquery nesting.
2562
select_dump(sql_exchange *ex, uint nest_level_arg) :
2565
nest_level= nest_level_arg;
2567
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2568
bool send_data(List<Item> &items);
2572
class select_insert :public select_result_interceptor {
2574
TABLE_LIST *table_list;
2577
ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not
2579
bool insert_into_view;
2580
select_insert(TABLE_LIST *table_list_par,
2581
TABLE *table_par, List<Item> *fields_par,
2582
List<Item> *update_fields, List<Item> *update_values,
2583
enum_duplicates duplic, bool ignore);
2585
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2586
virtual int prepare2(void);
2587
bool send_data(List<Item> &items);
2588
virtual void store_values(List<Item> &values);
2589
virtual bool can_rollback_data() { return 0; }
2590
void send_error(uint errcode,const char *err);
2593
/* not implemented: select_insert is never re-used in prepared statements */
2598
class select_create: public select_insert {
2600
TABLE_LIST *create_table;
2601
HA_CREATE_INFO *create_info;
2602
TABLE_LIST *select_tables;
2603
Alter_info *alter_info;
2605
/* lock data for tmp table */
2607
/* m_lock or thd->extra_lock */
2608
MYSQL_LOCK **m_plock;
2610
select_create (TABLE_LIST *table_arg,
2611
HA_CREATE_INFO *create_info_par,
2612
Alter_info *alter_info_arg,
2613
List<Item> &select_fields,enum_duplicates duplic, bool ignore,
2614
TABLE_LIST *select_tables_arg)
2615
:select_insert (NULL, NULL, &select_fields, 0, 0, duplic, ignore),
2616
create_table(table_arg),
2617
create_info(create_info_par),
2618
select_tables(select_tables_arg),
2619
alter_info(alter_info_arg),
2622
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2624
int binlog_show_create_table(TABLE **tables, uint count);
2625
void store_values(List<Item> &values);
2626
void send_error(uint errcode,const char *err);
2629
virtual bool can_rollback_data() { return 1; }
2631
// Needed for access from local class MY_HOOKS in prepare(), since thd is proteted.
2632
const THD *get_thd(void) { return thd; }
2633
const HA_CREATE_INFO *get_create_info() { return create_info; };
2634
int prepare2(void) { return 0; }
2640
Param to create temporary tables when doing SELECT:s
2642
This structure is copied using memcpy as a part of JOIN.
2645
class TMP_TABLE_PARAM :public Sql_alloc
2648
/* Prevent use of these (not safe because of lists and copy_field) */
2649
TMP_TABLE_PARAM(const TMP_TABLE_PARAM &);
2650
void operator=(TMP_TABLE_PARAM &);
2653
List<Item> copy_funcs;
2654
List<Item> save_copy_funcs;
2655
Copy_field *copy_field, *copy_field_end;
2656
Copy_field *save_copy_field, *save_copy_field_end;
2658
Item **items_to_copy; /* Fields in tmp table */
2659
MI_COLUMNDEF *recinfo,*start_recinfo;
2661
ha_rows end_write_records;
2663
Number of normal fields in the query, including those referred to
2664
from aggregate functions. Hence, "SELECT `field1`,
2665
SUM(`field2`) from t1" sets this counter to 2.
2667
@see count_field_types
2671
Number of fields in the query that have functions. Includes both
2672
aggregate functions (e.g., SUM) and non-aggregates (e.g., RAND).
2673
Also counts functions referred to from aggregate functions, i.e.,
2674
"SELECT SUM(RAND())" sets this counter to 2.
2676
@see count_field_types
2680
Number of fields in the query that have aggregate functions. Note
2681
that the optimizer may choose to optimize away these fields by
2682
replacing them with constants, in which case sum_func_count will
2685
@see opt_sum_query, count_field_types
2687
uint sum_func_count;
2688
uint hidden_field_count;
2689
uint group_parts,group_length,group_null_parts;
2691
bool using_indirect_summary_function;
2692
/* If >0 convert all blob fields to varchar(convert_blob_length) */
2693
uint convert_blob_length;
2694
CHARSET_INFO *table_charset;
2697
True if GROUP BY and its aggregate functions are already computed
2698
by a table access method (e.g. by loose index scan). In this case
2699
query execution should not perform aggregation and should treat
2700
aggregate functions as normal functions.
2702
bool precomputed_group_by;
2703
bool force_copy_fields;
2706
:copy_field(0), group_parts(0),
2707
group_length(0), group_null_parts(0), convert_blob_length(0),
2708
schema_table(0), precomputed_group_by(0), force_copy_fields(0)
2715
inline void cleanup(void)
2717
if (copy_field) /* Fix for Intel compiler */
2719
delete [] copy_field;
2720
save_copy_field= copy_field= 0;
2725
class select_union :public select_result_interceptor
2727
TMP_TABLE_PARAM tmp_table_param;
2731
select_union() :table(0) {}
2732
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2733
bool send_data(List<Item> &items);
2737
bool create_result_table(THD *thd, List<Item> *column_types,
2738
bool is_distinct, ulonglong options,
2742
/* Base subselect interface class */
2743
class select_subselect :public select_result_interceptor
2746
Item_subselect *item;
2748
select_subselect(Item_subselect *item);
2749
bool send_data(List<Item> &items)=0;
2750
bool send_eof() { return 0; };
2753
/* Single value subselect interface class */
2754
class select_singlerow_subselect :public select_subselect
2757
select_singlerow_subselect(Item_subselect *item_arg)
2758
:select_subselect(item_arg)
2760
bool send_data(List<Item> &items);
2763
/* used in independent ALL/ANY optimisation */
2764
class select_max_min_finder_subselect :public select_subselect
2767
bool (select_max_min_finder_subselect::*op)();
2770
select_max_min_finder_subselect(Item_subselect *item_arg, bool mx)
2771
:select_subselect(item_arg), cache(0), fmax(mx)
2774
bool send_data(List<Item> &items);
2781
/* EXISTS subselect interface class */
2782
class select_exists_subselect :public select_subselect
2785
select_exists_subselect(Item_subselect *item_arg)
2786
:select_subselect(item_arg){}
2787
bool send_data(List<Item> &items);
2790
/* Structs used when sorting */
2792
typedef struct st_sort_field {
2793
Field *field; /* Field to sort */
2794
Item *item; /* Item if not sorting fields */
2795
uint length; /* Length of sort field */
2796
uint suffix_length; /* Length suffix (0-4) */
2797
Item_result result_type; /* Type of item */
2798
bool reverse; /* if descending sort */
2799
bool need_strxnfrm; /* If we have to use strxnfrm() */
2803
typedef struct st_sort_buffer {
2804
uint index; /* 0 or 1 */
2806
uint change_pos; /* If sort-fields changed */
2808
SORT_FIELD *sortorder;
2811
/* Structure for db & table in sql_yacc */
2813
class Table_ident :public Sql_alloc
2818
SELECT_LEX_UNIT *sel;
2819
inline Table_ident(THD *thd, LEX_STRING db_arg, LEX_STRING table_arg,
2821
:table(table_arg), sel((SELECT_LEX_UNIT *)0)
2823
if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA))
2828
inline Table_ident(LEX_STRING table_arg)
2829
:table(table_arg), sel((SELECT_LEX_UNIT *)0)
2834
This constructor is used only for the case when we create a derived
2835
table. A derived table has no name and doesn't belong to any database.
2836
Later, if there was an alias specified for the table, it will be set
2837
by add_table_to_list.
2839
inline Table_ident(SELECT_LEX_UNIT *s) : sel(s)
2841
/* We must have a table name here as this is used with add_table_to_list */
2842
db.str= empty_c_string; /* a subject to casedn_str */
2844
table.str= internal_table_name;
2847
bool is_derived_table() const { return test(sel); }
2848
inline void change_db(char *db_name)
2850
db.str= db_name; db.length= (uint) strlen(db_name);
2854
// this is needed for user_vars hash
2855
class user_var_entry
2858
user_var_entry() {} /* Remove gcc warning */
2862
query_id_t update_query_id, used_query_id;
2866
double val_real(my_bool *null_value);
2867
longlong val_int(my_bool *null_value) const;
2868
String *val_str(my_bool *null_value, String *str, uint decimals);
2869
my_decimal *val_decimal(my_bool *null_value, my_decimal *result);
2870
DTCollation collation;
2874
Unique -- class for unique (removing of duplicates).
2875
Puts all values to the TREE. If the tree becomes too big,
2876
it's dumped to the file. User can request sorted values, or
2877
just iterate through them. In the last case tree merging is performed in
2878
memory simultaneously with iteration, so it should be ~2-3x faster.
2881
class Unique :public Sql_alloc
2883
DYNAMIC_ARRAY file_ptrs;
2885
ulonglong max_in_memory_size;
2888
uchar *record_pointers;
2894
Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg,
2895
uint size_arg, ulonglong max_in_memory_size_arg);
2897
ulong elements_in_tree() { return tree.elements_in_tree; }
2898
inline bool unique_add(void *ptr)
2900
DBUG_ENTER("unique_add");
2901
DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements));
2902
if (tree.elements_in_tree > max_elements && flush())
2904
DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg));
2907
bool get(TABLE *table);
2908
static double get_use_cost(uint *buffer, uint nkeys, uint key_size,
2909
ulonglong max_in_memory_size);
2910
inline static int get_cost_calc_buff_size(ulong nkeys, uint key_size,
2911
ulonglong max_in_memory_size)
2913
register ulonglong max_elems_in_tree=
2914
(1 + max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size));
2915
return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree));
2919
bool walk(tree_walk_action action, void *walk_action_arg);
2921
friend int unique_write_to_file(uchar* key, element_count count, Unique *unique);
2922
friend int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique);
2926
class multi_delete :public select_result_interceptor
2928
TABLE_LIST *delete_tables, *table_being_deleted;
2930
ha_rows deleted, found;
2934
/* True if at least one table we delete from is transactional */
2935
bool transactional_tables;
2936
/* True if at least one table we delete from is not transactional */
2938
bool delete_while_scanning;
2940
error handling (rollback and binlogging) can happen in send_eof()
2941
so that afterward send_error() needs to find out that.
2946
multi_delete(TABLE_LIST *dt, uint num_of_tables);
2948
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2949
bool send_data(List<Item> &items);
2950
bool initialize_tables (JOIN *join);
2951
void send_error(uint errcode,const char *err);
2953
int do_table_deletes(TABLE *table, bool ignore);
2955
virtual void abort();
2959
class multi_update :public select_result_interceptor
2961
TABLE_LIST *all_tables; /* query/update command tables */
2962
TABLE_LIST *leaves; /* list of leves of join table tree */
2963
TABLE_LIST *update_tables, *table_being_updated;
2964
TABLE **tmp_tables, *main_table, *table_to_update;
2965
TMP_TABLE_PARAM *tmp_table_param;
2966
ha_rows updated, found;
2967
List <Item> *fields, *values;
2968
List <Item> **fields_for_table, **values_for_table;
2971
List of tables referenced in the CHECK OPTION condition of
2972
the updated view excluding the updated table.
2974
List <TABLE> unupdated_check_opt_tables;
2975
Copy_field *copy_field;
2976
enum enum_duplicates handle_duplicates;
2977
bool do_update, trans_safe;
2978
/* True if the update operation has made a change in a transactional table */
2979
bool transactional_tables;
2982
error handling (rollback and binlogging) can happen in send_eof()
2983
so that afterward send_error() needs to find out that.
2988
multi_update(TABLE_LIST *ut, TABLE_LIST *leaves_list,
2989
List<Item> *fields, List<Item> *values,
2990
enum_duplicates handle_duplicates, bool ignore);
2992
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2993
bool send_data(List<Item> &items);
2994
bool initialize_tables (JOIN *join);
2995
void send_error(uint errcode,const char *err);
2998
virtual void abort();
3001
class my_var : public Sql_alloc {
3006
Routine to which this Item_splocal belongs. Used for checking if correct
3007
runtime context is used for variable handling.
3013
enum_field_types type;
3014
my_var (LEX_STRING& j, bool i, uint o, enum_field_types t)
3015
:s(j), local(i), offset(o), type(t)
3020
class select_dumpvar :public select_result_interceptor {
3023
List<my_var> var_list;
3024
select_dumpvar() { var_list.empty(); row_count= 0;}
3026
Creates a select_dumpvar to represent INTO <variable> with a defined
3027
level of subquery nesting.
3029
select_dumpvar(uint nest_level_arg)
3033
nest_level= nest_level_arg;
3035
~select_dumpvar() {}
3036
int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
3037
bool send_data(List<Item> &items);
3039
virtual bool check_simple_select() const;
3043
/* Bits in sql_command_flags */
3045
#define CF_CHANGES_DATA 1
3046
#define CF_HAS_ROW_COUNT 2
3047
#define CF_STATUS_COMMAND 4
3048
#define CF_SHOW_TABLE_COMMAND 8
3049
#define CF_WRITE_LOGS_COMMAND 16
3051
Must be set for SQL statements that may contain
3052
Item expressions and/or use joins and tables.
3053
Indicates that the parse tree of such statement may
3054
contain rule-based optimizations that depend on metadata
3055
(i.e. number of columns in a table), and consequently
3056
that the statement must be re-prepared whenever
3057
referenced metadata changes. Must not be set for
3058
statements that themselves change metadata, e.g. RENAME,
3059
ALTER and other DDL, since otherwise will trigger constant
3060
reprepare. Consequently, complex item expressions and
3061
joins are currently prohibited in these statements.
3063
#define CF_REEXECUTION_FRAGILE 32
3065
/* Functions in sql_class.cc */
3067
void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
3069
void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
3070
STATUS_VAR *dec_var);
3071
void mark_transaction_to_rollback(THD *thd, bool all);
3073
#endif /* MYSQL_SERVER */