mySQL 5.0.11 sources for tomato
[tomato.git] / release / src / router / mysql / sql / sql_class.h
blobfd83930a8e9185de2e5e043ede0f575842344508
1 /*
2 Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 /* Classes in mysql */
21 #ifdef USE_PRAGMA_INTERFACE
22 #pragma interface /* gcc class implementation */
23 #endif
25 #include "log.h"
26 #include "rpl_tblmap.h"
28 /**
29 An interface that is used to take an action when
30 the locking module notices that a table version has changed
31 since the last execution. "Table" here may refer to any kind of
32 table -- a base table, a temporary table, a view or an
33 information schema table.
35 When we open and lock tables for execution of a prepared
36 statement, we must verify that they did not change
37 since statement prepare. If some table did change, the statement
38 parse tree *may* be no longer valid, e.g. in case it contains
39 optimizations that depend on table metadata.
41 This class provides an interface (a method) that is
42 invoked when such a situation takes place.
43 The implementation of the method simply reports an error, but
44 the exact details depend on the nature of the SQL statement.
46 At most 1 instance of this class is active at a time, in which
47 case THD::m_reprepare_observer is not NULL.
49 @sa check_and_update_table_version() for details of the
50 version tracking algorithm
52 @sa Open_tables_state::m_reprepare_observer for the life cycle
53 of metadata observers.
56 class Reprepare_observer
58 public:
59 /**
60 Check if a change of metadata is OK. In future
61 the signature of this method may be extended to accept the old
62 and the new versions, but since currently the check is very
63 simple, we only need the THD to report an error.
65 bool report_error(THD *thd);
66 bool is_invalidated() const { return m_invalidated; }
67 void reset_reprepare_observer() { m_invalidated= FALSE; }
68 private:
69 bool m_invalidated;
73 class Relay_log_info;
75 class Query_log_event;
76 class Load_log_event;
77 class Slave_log_event;
78 class sp_rcontext;
79 class sp_cache;
80 class Parser_state;
81 class Rows_log_event;
83 enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE };
84 enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
85 enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE };
86 enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON,
87 DELAY_KEY_WRITE_ALL };
89 #define SLAVE_EXEC_MODE_STRICT (1U << 0)
90 #define SLAVE_EXEC_MODE_IDEMPOTENT (1U << 1)
92 enum enum_mark_columns
93 { MARK_COLUMNS_NONE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE};
95 extern char internal_table_name[2];
96 extern char empty_c_string[1];
97 extern MYSQL_PLUGIN_IMPORT const char **errmesg;
99 extern bool volatile shutdown_in_progress;
101 #define TC_LOG_PAGE_SIZE 8192
102 #define TC_LOG_MIN_SIZE (3*TC_LOG_PAGE_SIZE)
104 #define TC_HEURISTIC_RECOVER_COMMIT 1
105 #define TC_HEURISTIC_RECOVER_ROLLBACK 2
106 extern uint tc_heuristic_recover;
108 typedef struct st_user_var_events
110 user_var_entry *user_var_event;
111 char *value;
112 ulong length;
113 Item_result type;
114 uint charset_number;
115 } BINLOG_USER_VAR_EVENT;
117 #define RP_LOCK_LOG_IS_ALREADY_LOCKED 1
118 #define RP_FORCE_ROTATE 2
121 The COPY_INFO structure is used by INSERT/REPLACE code.
122 The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY
123 UPDATE code:
124 If a row is inserted then the copied variable is incremented.
125 If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
126 new data differs from the old one then the copied and the updated
127 variables are incremented.
128 The touched variable is incremented if a row was touched by the update part
129 of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
130 was actually changed or not.
132 typedef struct st_copy_info {
133 ha_rows records; /**< Number of processed records */
134 ha_rows deleted; /**< Number of deleted records */
135 ha_rows updated; /**< Number of updated records */
136 ha_rows copied; /**< Number of copied records */
137 ha_rows error_count;
138 ha_rows touched; /* Number of touched records */
139 enum enum_duplicates handle_duplicates;
140 int escape_char, last_errno;
141 bool ignore;
142 /* for INSERT ... UPDATE */
143 List<Item> *update_fields;
144 List<Item> *update_values;
145 /* for VIEW ... WITH CHECK OPTION */
146 TABLE_LIST *view;
147 } COPY_INFO;
150 class Key_part_spec :public Sql_alloc {
151 public:
152 const char *field_name;
153 uint length;
154 Key_part_spec(const char *name,uint len=0) :field_name(name), length(len) {}
155 bool operator==(const Key_part_spec& other) const;
157 Construct a copy of this Key_part_spec. field_name is copied
158 by-pointer as it is known to never change. At the same time
159 'length' may be reset in mysql_prepare_create_table, and this
160 is why we supply it with a copy.
162 @return If out of memory, 0 is returned and an error is set in
163 THD.
165 Key_part_spec *clone(MEM_ROOT *mem_root) const
166 { return new (mem_root) Key_part_spec(*this); }
170 class Alter_drop :public Sql_alloc {
171 public:
172 enum drop_type {KEY, COLUMN };
173 const char *name;
174 enum drop_type type;
175 Alter_drop(enum drop_type par_type,const char *par_name)
176 :name(par_name), type(par_type) {}
178 Used to make a clone of this object for ALTER/CREATE TABLE
179 @sa comment for Key_part_spec::clone
181 Alter_drop *clone(MEM_ROOT *mem_root) const
182 { return new (mem_root) Alter_drop(*this); }
186 class Alter_column :public Sql_alloc {
187 public:
188 const char *name;
189 Item *def;
190 Alter_column(const char *par_name,Item *literal)
191 :name(par_name), def(literal) {}
193 Used to make a clone of this object for ALTER/CREATE TABLE
194 @sa comment for Key_part_spec::clone
196 Alter_column *clone(MEM_ROOT *mem_root) const
197 { return new (mem_root) Alter_column(*this); }
201 class Key :public Sql_alloc {
202 public:
203 enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY};
204 enum Keytype type;
205 KEY_CREATE_INFO key_create_info;
206 List<Key_part_spec> columns;
207 const char *name;
208 bool generated;
210 Key(enum Keytype type_par, const char *name_arg,
211 KEY_CREATE_INFO *key_info_arg,
212 bool generated_arg, List<Key_part_spec> &cols)
213 :type(type_par), key_create_info(*key_info_arg), columns(cols),
214 name(name_arg), generated(generated_arg)
216 Key(const Key &rhs, MEM_ROOT *mem_root);
217 virtual ~Key() {}
218 /* Equality comparison of keys (ignoring name) */
219 friend bool foreign_key_prefix(Key *a, Key *b);
221 Used to make a clone of this object for ALTER/CREATE TABLE
222 @sa comment for Key_part_spec::clone
224 virtual Key *clone(MEM_ROOT *mem_root) const
225 { return new (mem_root) Key(*this, mem_root); }
228 class Table_ident;
230 class Foreign_key: public Key {
231 public:
232 enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
233 FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
234 enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
235 FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT};
237 Table_ident *ref_table;
238 List<Key_part_spec> ref_columns;
239 uint delete_opt, update_opt, match_opt;
240 Foreign_key(const char *name_arg, List<Key_part_spec> &cols,
241 Table_ident *table, List<Key_part_spec> &ref_cols,
242 uint delete_opt_arg, uint update_opt_arg, uint match_opt_arg)
243 :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols),
244 ref_table(table), ref_columns(ref_cols),
245 delete_opt(delete_opt_arg), update_opt(update_opt_arg),
246 match_opt(match_opt_arg)
248 Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root);
250 Used to make a clone of this object for ALTER/CREATE TABLE
251 @sa comment for Key_part_spec::clone
253 virtual Key *clone(MEM_ROOT *mem_root) const
254 { return new (mem_root) Foreign_key(*this, mem_root); }
257 typedef struct st_mysql_lock
259 TABLE **table;
260 uint table_count,lock_count;
261 THR_LOCK_DATA **locks;
262 } MYSQL_LOCK;
265 class LEX_COLUMN : public Sql_alloc
267 public:
268 String column;
269 uint rights;
270 LEX_COLUMN (const String& x,const uint& y ): column (x),rights (y) {}
273 #include "sql_lex.h" /* Must be here */
275 class Delayed_insert;
276 class select_result;
277 class Time_zone;
279 #define THD_SENTRY_MAGIC 0xfeedd1ff
280 #define THD_SENTRY_GONE 0xdeadbeef
282 #define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
284 struct system_variables
287 How dynamically allocated system variables are handled:
289 The global_system_variables and max_system_variables are "authoritative"
290 They both should have the same 'version' and 'size'.
291 When attempting to access a dynamic variable, if the session version
292 is out of date, then the session version is updated and realloced if
293 neccessary and bytes copied from global to make up for missing data.
295 ulong dynamic_variables_version;
296 char* dynamic_variables_ptr;
297 uint dynamic_variables_head; /* largest valid variable offset */
298 uint dynamic_variables_size; /* how many bytes are in use */
300 ulonglong myisam_max_extra_sort_file_size;
301 ulonglong myisam_max_sort_file_size;
302 ulonglong max_heap_table_size;
303 ulonglong tmp_table_size;
304 ulonglong long_query_time;
305 ha_rows select_limit;
306 ha_rows max_join_size;
307 ulong auto_increment_increment, auto_increment_offset;
308 ulong bulk_insert_buff_size;
309 ulong join_buff_size;
310 ulong max_allowed_packet;
311 ulong max_error_count;
312 ulong max_length_for_sort_data;
313 ulong max_sort_length;
314 ulong max_tmp_tables;
315 ulong max_insert_delayed_threads;
316 ulong min_examined_row_limit;
317 ulong multi_range_count;
318 ulong myisam_repair_threads;
319 ulong myisam_sort_buff_size;
320 ulong myisam_stats_method;
321 ulong net_buffer_length;
322 ulong net_interactive_timeout;
323 ulong net_read_timeout;
324 ulong net_retry_count;
325 ulong net_wait_timeout;
326 ulong net_write_timeout;
327 ulong optimizer_prune_level;
328 ulong optimizer_search_depth;
329 /* A bitmap for switching optimizations on/off */
330 ulong optimizer_switch;
331 ulong preload_buff_size;
332 ulong profiling_history_size;
333 ulong query_cache_type;
334 ulong read_buff_size;
335 ulong read_rnd_buff_size;
336 ulong div_precincrement;
337 ulong sortbuff_size;
338 ulong thread_handling;
339 ulong tx_isolation;
340 ulong completion_type;
341 /* Determines which non-standard SQL behaviour should be enabled */
342 ulong sql_mode;
343 ulong max_sp_recursion_depth;
344 /* check of key presence in updatable view */
345 ulong updatable_views_with_limit;
346 ulong default_week_format;
347 ulong max_seeks_for_key;
348 ulong range_alloc_block_size;
349 ulong query_alloc_block_size;
350 ulong query_prealloc_size;
351 ulong trans_alloc_block_size;
352 ulong trans_prealloc_size;
353 ulong log_warnings;
354 ulong group_concat_max_len;
355 ulong ndb_autoincrement_prefetch_sz;
356 ulong ndb_index_stat_cache_entries;
357 ulong ndb_index_stat_update_freq;
358 ulong binlog_format; // binlog format for this thd (see enum_binlog_format)
359 my_bool binlog_direct_non_trans_update;
361 In slave thread we need to know in behalf of which
362 thread the query is being run to replicate temp tables properly
364 my_thread_id pseudo_thread_id;
366 my_bool low_priority_updates;
367 my_bool new_mode;
369 compatibility option:
370 - index usage hints (USE INDEX without a FOR clause) behave as in 5.0
372 my_bool old_mode;
373 my_bool query_cache_wlock_invalidate;
374 my_bool engine_condition_pushdown;
375 my_bool keep_files_on_create;
376 my_bool ndb_force_send;
377 my_bool ndb_use_copying_alter_table;
378 my_bool ndb_use_exact_count;
379 my_bool ndb_use_transactions;
380 my_bool ndb_index_stat_enable;
382 my_bool old_alter_table;
383 my_bool old_passwords;
385 plugin_ref table_plugin;
387 /* Only charset part of these variables is sensible */
388 CHARSET_INFO *character_set_filesystem;
389 CHARSET_INFO *character_set_client;
390 CHARSET_INFO *character_set_results;
392 /* Both charset and collation parts of these variables are important */
393 CHARSET_INFO *collation_server;
394 CHARSET_INFO *collation_database;
395 CHARSET_INFO *collation_connection;
397 /* Locale Support */
398 MY_LOCALE *lc_time_names;
400 Time_zone *time_zone;
402 /* DATE, DATETIME and MYSQL_TIME formats */
403 DATE_TIME_FORMAT *date_format;
404 DATE_TIME_FORMAT *datetime_format;
405 DATE_TIME_FORMAT *time_format;
406 my_bool sysdate_is_now;
411 Per thread status variables.
412 Must be long/ulong up to last_system_status_var so that
413 add_to_status/add_diff_to_status can work.
416 typedef struct system_status_var
418 ulong com_other;
419 ulong com_stat[(uint) SQLCOM_END];
420 ulong created_tmp_disk_tables;
421 ulong created_tmp_tables;
422 ulong ha_commit_count;
423 ulong ha_delete_count;
424 ulong ha_read_first_count;
425 ulong ha_read_last_count;
426 ulong ha_read_key_count;
427 ulong ha_read_next_count;
428 ulong ha_read_prev_count;
429 ulong ha_read_rnd_count;
430 ulong ha_read_rnd_next_count;
431 ulong ha_rollback_count;
432 ulong ha_update_count;
433 ulong ha_write_count;
434 ulong ha_prepare_count;
435 ulong ha_discover_count;
436 ulong ha_savepoint_count;
437 ulong ha_savepoint_rollback_count;
439 /* KEY_CACHE parts. These are copies of the original */
440 ulong key_blocks_changed;
441 ulong key_blocks_used;
442 ulong key_cache_r_requests;
443 ulong key_cache_read;
444 ulong key_cache_w_requests;
445 ulong key_cache_write;
446 /* END OF KEY_CACHE parts */
448 ulong net_big_packet_count;
449 ulong opened_tables;
450 ulong opened_shares;
451 ulong select_full_join_count;
452 ulong select_full_range_join_count;
453 ulong select_range_count;
454 ulong select_range_check_count;
455 ulong select_scan_count;
456 ulong long_query_count;
457 ulong filesort_merge_passes;
458 ulong filesort_range_count;
459 ulong filesort_rows;
460 ulong filesort_scan_count;
461 /* Prepared statements and binary protocol */
462 ulong com_stmt_prepare;
463 ulong com_stmt_reprepare;
464 ulong com_stmt_execute;
465 ulong com_stmt_send_long_data;
466 ulong com_stmt_fetch;
467 ulong com_stmt_reset;
468 ulong com_stmt_close;
470 Number of statements sent from the client
472 ulong questions;
474 ulonglong bytes_received;
475 ulonglong bytes_sent;
477 IMPORTANT!
478 SEE last_system_status_var DEFINITION BELOW.
479 Below 'last_system_status_var' are all variables that cannot be handled
480 automatically by add_to_status()/add_diff_to_status().
482 double last_query_cost;
483 } STATUS_VAR;
486 This is used for 'SHOW STATUS'. It must be updated to the last ulong
487 variable in system_status_var which is makes sens to add to the global
488 counter
491 #define last_system_status_var questions
493 void mark_transaction_to_rollback(THD *thd, bool all);
495 #ifdef MYSQL_SERVER
497 void free_tmp_table(THD *thd, TABLE *entry);
500 /* The following macro is to make init of Query_arena simpler */
501 #ifndef DBUG_OFF
502 #define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE;
503 #else
504 #define INIT_ARENA_DBUG_INFO
505 #endif
507 class Query_arena
509 public:
511 List of items created in the parser for this query. Every item puts
512 itself to the list on creation (see Item::Item() for details))
514 Item *free_list;
515 MEM_ROOT *mem_root; // Pointer to current memroot
516 #ifndef DBUG_OFF
517 bool is_backup_arena; /* True if this arena is used for backup. */
518 bool is_reprepared;
519 #endif
521 The states relfects three diffrent life cycles for three
522 different types of statements:
523 Prepared statement: INITIALIZED -> PREPARED -> EXECUTED.
524 Stored procedure: INITIALIZED_FOR_SP -> EXECUTED.
525 Other statements: CONVENTIONAL_EXECUTION never changes.
527 enum enum_state
529 INITIALIZED= 0, INITIALIZED_FOR_SP= 1, PREPARED= 2,
530 CONVENTIONAL_EXECUTION= 3, EXECUTED= 4, ERROR= -1
533 enum_state state;
535 /* We build without RTTI, so dynamic_cast can't be used. */
536 enum Type
538 STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE
541 Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) :
542 free_list(0), mem_root(mem_root_arg), state(state_arg)
543 { INIT_ARENA_DBUG_INFO; }
545 This constructor is used only when Query_arena is created as
546 backup storage for another instance of Query_arena.
548 Query_arena() { INIT_ARENA_DBUG_INFO; }
550 virtual Type type() const;
551 virtual ~Query_arena() {};
553 inline bool is_stmt_prepare() const { return state == INITIALIZED; }
554 inline bool is_first_sp_execute() const
555 { return state == INITIALIZED_FOR_SP; }
556 inline bool is_stmt_prepare_or_first_sp_execute() const
557 { return (int)state < (int)PREPARED; }
558 inline bool is_stmt_prepare_or_first_stmt_execute() const
559 { return (int)state <= (int)PREPARED; }
560 inline bool is_first_stmt_execute() const { return state == PREPARED; }
561 inline bool is_stmt_execute() const
562 { return state == PREPARED || state == EXECUTED; }
563 inline bool is_conventional() const
564 { return state == CONVENTIONAL_EXECUTION; }
566 inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
567 inline void* calloc(size_t size)
569 void *ptr;
570 if ((ptr=alloc_root(mem_root,size)))
571 bzero(ptr, size);
572 return ptr;
574 inline char *strdup(const char *str)
575 { return strdup_root(mem_root,str); }
576 inline char *strmake(const char *str, size_t size)
577 { return strmake_root(mem_root,str,size); }
578 inline void *memdup(const void *str, size_t size)
579 { return memdup_root(mem_root,str,size); }
580 inline void *memdup_w_gap(const void *str, size_t size, uint gap)
582 void *ptr;
583 if ((ptr= alloc_root(mem_root,size+gap)))
584 memcpy(ptr,str,size);
585 return ptr;
588 void set_query_arena(Query_arena *set);
590 void free_items();
591 /* Close the active state associated with execution of this statement */
592 virtual void cleanup_stmt();
596 class Server_side_cursor;
599 @class Statement
600 @brief State of a single command executed against this connection.
602 One connection can contain a lot of simultaneously running statements,
603 some of which could be:
604 - prepared, that is, contain placeholders,
605 - opened as cursors. We maintain 1 to 1 relationship between
606 statement and cursor - if user wants to create another cursor for his
607 query, we create another statement for it.
608 To perform some action with statement we reset THD part to the state of
609 that statement, do the action, and then save back modified state from THD
610 to the statement. It will be changed in near future, and Statement will
611 be used explicitly.
614 class Statement: public ilink, public Query_arena
616 Statement(const Statement &rhs); /* not implemented: */
617 Statement &operator=(const Statement &rhs); /* non-copyable */
618 public:
620 Uniquely identifies each statement object in thread scope; change during
621 statement lifetime. FIXME: must be const
623 ulong id;
626 MARK_COLUMNS_NONE: Means mark_used_colums is not set and no indicator to
627 handler of fields used is set
628 MARK_COLUMNS_READ: Means a bit in read set is set to inform handler
629 that the field is to be read. If field list contains
630 duplicates, then thd->dup_field is set to point
631 to the last found duplicate.
632 MARK_COLUMNS_WRITE: Means a bit is set in write set to inform handler
633 that it needs to update this field in write_row
634 and update_row.
636 enum enum_mark_columns mark_used_columns;
638 LEX_STRING name; /* name for named prepared statements */
639 LEX *lex; // parse tree descriptor
641 Points to the query associated with this statement. It's const, but
642 we need to declare it char * because all table handlers are written
643 in C and need to point to it.
645 Note that if we set query = NULL, we must at the same time set
646 query_length = 0, and protect the whole operation with
647 LOCK_thd_data mutex. To avoid crashes in races, if we do not
648 know that thd->query cannot change at the moment, we should print
649 thd->query like this:
650 (1) reserve the LOCK_thd_data mutex;
651 (2) print or copy the value of query and query_length
652 (3) release LOCK_thd_data mutex.
653 This printing is needed at least in SHOW PROCESSLIST and SHOW
654 ENGINE INNODB STATUS.
656 LEX_STRING query_string;
657 Server_side_cursor *cursor;
659 inline char *query() { return query_string.str; }
660 inline uint32 query_length() { return query_string.length; }
661 void set_query_inner(char *query_arg, uint32 query_length_arg);
664 Name of the current (default) database.
666 If there is the current (default) database, "db" contains its name. If
667 there is no current (default) database, "db" is NULL and "db_length" is
668 0. In other words, "db", "db_length" must either be NULL, or contain a
669 valid database name.
671 @note this attribute is set and alloced by the slave SQL thread (for
672 the THD of that thread); that thread is (and must remain, for now) the
673 only responsible for freeing this member.
676 char *db;
677 size_t db_length;
679 public:
681 /* This constructor is called for backup statements */
682 Statement() {}
684 Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
685 enum enum_state state_arg, ulong id_arg);
686 virtual ~Statement();
688 /* Assign execution context (note: not all members) of given stmt to self */
689 virtual void set_statement(Statement *stmt);
690 void set_n_backup_statement(Statement *stmt, Statement *backup);
691 void restore_backup_statement(Statement *stmt, Statement *backup);
692 /* return class type */
693 virtual Type type() const;
698 Container for all statements created/used in a connection.
699 Statements in Statement_map have unique Statement::id (guaranteed by id
700 assignment in Statement::Statement)
701 Non-empty statement names are unique too: attempt to insert a new statement
702 with duplicate name causes older statement to be deleted
704 Statements are auto-deleted when they are removed from the map and when the
705 map is deleted.
708 class Statement_map
710 public:
711 Statement_map();
713 int insert(THD *thd, Statement *statement);
715 Statement *find_by_name(LEX_STRING *name)
717 Statement *stmt;
718 stmt= (Statement*)hash_search(&names_hash, (uchar*)name->str,
719 name->length);
720 return stmt;
723 Statement *find(ulong id)
725 if (last_found_statement == 0 || id != last_found_statement->id)
727 Statement *stmt;
728 stmt= (Statement *) hash_search(&st_hash, (uchar *) &id, sizeof(id));
729 if (stmt && stmt->name.str)
730 return NULL;
731 last_found_statement= stmt;
733 return last_found_statement;
736 Close all cursors of this connection that use tables of a storage
737 engine that has transaction-specific state and therefore can not
738 survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed.
740 void close_transient_cursors();
741 void erase(Statement *statement);
742 /* Erase all statements (calls Statement destructor) */
743 void reset();
744 ~Statement_map();
745 private:
746 HASH st_hash;
747 HASH names_hash;
748 I_List<Statement> transient_cursor_list;
749 Statement *last_found_statement;
752 struct st_savepoint {
753 struct st_savepoint *prev;
754 char *name;
755 uint length;
756 Ha_trx_info *ha_list;
759 enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY};
760 extern const char *xa_state_names[];
762 typedef struct st_xid_state {
763 /* For now, this is only used to catch duplicated external xids */
764 XID xid; // transaction identifier
765 enum xa_states xa_state; // used by external XA only
766 bool in_thd;
767 /* Error reported by the Resource Manager (RM) to the Transaction Manager. */
768 uint rm_error;
769 } XID_STATE;
771 extern pthread_mutex_t LOCK_xid_cache;
772 extern HASH xid_cache;
773 bool xid_cache_init(void);
774 void xid_cache_free(void);
775 XID_STATE *xid_cache_search(XID *xid);
776 bool xid_cache_insert(XID *xid, enum xa_states xa_state);
777 bool xid_cache_insert(XID_STATE *xid_state);
778 void xid_cache_delete(XID_STATE *xid_state);
781 @class Security_context
782 @brief A set of THD members describing the current authenticated user.
785 class Security_context {
786 public:
787 Security_context() {} /* Remove gcc warning */
789 host - host of the client
790 user - user of the client, set to NULL until the user has been read from
791 the connection
792 priv_user - The user privilege we are using. May be "" for anonymous user.
793 ip - client IP
795 char *host, *user, *priv_user, *ip;
796 /* The host privilege we are using */
797 char priv_host[MAX_HOSTNAME];
798 /* points to host if host is available, otherwise points to ip */
799 const char *host_or_ip;
800 ulong master_access; /* Global privileges from mysql.user */
801 ulong db_access; /* Privileges for current db */
803 void init();
804 void destroy();
805 void skip_grants();
806 inline char *priv_host_name()
808 return (*priv_host ? priv_host : (char *)"%");
811 bool set_user(char *user_arg);
813 #ifndef NO_EMBEDDED_ACCESS_CHECKS
814 bool
815 change_security_context(THD *thd,
816 LEX_STRING *definer_user,
817 LEX_STRING *definer_host,
818 LEX_STRING *db,
819 Security_context **backup);
821 void
822 restore_security_context(THD *thd, Security_context *backup);
823 #endif
824 bool user_matches(Security_context *);
829 A registry for item tree transformations performed during
830 query optimization. We register only those changes which require
831 a rollback to re-execute a prepared statement or stored procedure
832 yet another time.
835 struct Item_change_record;
836 typedef I_List<Item_change_record> Item_change_list;
840 Type of prelocked mode.
841 See comment for THD::prelocked_mode for complete description.
844 enum prelocked_mode_type {NON_PRELOCKED= 0, PRELOCKED= 1,
845 PRELOCKED_UNDER_LOCK_TABLES= 2};
849 Class that holds information about tables which were opened and locked
850 by the thread. It is also used to save/restore this information in
851 push_open_tables_state()/pop_open_tables_state().
854 class Open_tables_state
856 public:
858 As part of class THD, this member is set during execution
859 of a prepared statement. When it is set, it is used
860 by the locking subsystem to report a change in table metadata.
862 When Open_tables_state part of THD is reset to open
863 a system or INFORMATION_SCHEMA table, the member is cleared
864 to avoid spurious ER_NEED_REPREPARE errors -- system and
865 INFORMATION_SCHEMA tables are not subject to metadata version
866 tracking.
867 @sa check_and_update_table_version()
869 Reprepare_observer *m_reprepare_observer;
872 List of regular tables in use by this thread. Contains temporary and
873 base tables that were opened with @see open_tables().
875 TABLE *open_tables;
877 List of temporary tables used by this thread. Contains user-level
878 temporary tables, created with CREATE TEMPORARY TABLE, and
879 internal temporary tables, created, e.g., to resolve a SELECT,
880 or for an intermediate table used in ALTER.
881 XXX Why are internal temporary tables added to this list?
883 TABLE *temporary_tables;
885 List of tables that were opened with HANDLER OPEN and are
886 still in use by this thread.
888 TABLE *handler_tables;
889 TABLE *derived_tables;
891 During a MySQL session, one can lock tables in two modes: automatic
892 or manual. In automatic mode all necessary tables are locked just before
893 statement execution, and all acquired locks are stored in 'lock'
894 member. Unlocking takes place automatically as well, when the
895 statement ends.
896 Manual mode comes into play when a user issues a 'LOCK TABLES'
897 statement. In this mode the user can only use the locked tables.
898 Trying to use any other tables will give an error. The locked tables are
899 stored in 'locked_tables' member. Manual locking is described in
900 the 'LOCK_TABLES' chapter of the MySQL manual.
901 See also lock_tables() for details.
903 MYSQL_LOCK *lock;
905 Tables that were locked with explicit or implicit LOCK TABLES.
906 (Implicit LOCK TABLES happens when we are prelocking tables for
907 execution of statement which uses stored routines. See description
908 THD::prelocked_mode for more info.)
910 MYSQL_LOCK *locked_tables;
913 CREATE-SELECT keeps an extra lock for the table being
914 created. This field is used to keep the extra lock available for
915 lower level routines, which would otherwise miss that lock.
917 MYSQL_LOCK *extra_lock;
920 prelocked_mode_type enum and prelocked_mode member are used for
921 indicating whenever "prelocked mode" is on, and what type of
922 "prelocked mode" is it.
924 Prelocked mode is used for execution of queries which explicitly
925 or implicitly (via views or triggers) use functions, thus may need
926 some additional tables (mentioned in query table list) for their
927 execution.
929 First open_tables() call for such query will analyse all functions
930 used by it and add all additional tables to table its list. It will
931 also mark this query as requiring prelocking. After that lock_tables()
932 will issue implicit LOCK TABLES for the whole table list and change
933 thd::prelocked_mode to non-0. All queries called in functions invoked
934 by the main query will use prelocked tables. Non-0 prelocked_mode
935 will also surpress mentioned analysys in those queries thus saving
936 cycles. Prelocked mode will be turned off once close_thread_tables()
937 for the main query will be called.
939 Note: Since not all "tables" present in table list are really locked
940 thd::prelocked_mode does not imply thd::locked_tables.
942 prelocked_mode_type prelocked_mode;
943 ulong version;
944 uint current_tablenr;
946 enum enum_flags {
947 BACKUPS_AVAIL = (1U << 0) /* There are backups available */
951 Flags with information about the open tables state.
953 uint state_flags;
956 This constructor serves for creation of Open_tables_state instances
957 which are used as backup storage.
959 Open_tables_state() : state_flags(0U) { }
961 Open_tables_state(ulong version_arg);
963 void set_open_tables_state(Open_tables_state *state)
965 *this= *state;
968 void reset_open_tables_state()
970 open_tables= temporary_tables= handler_tables= derived_tables= 0;
971 extra_lock= lock= locked_tables= 0;
972 prelocked_mode= NON_PRELOCKED;
973 state_flags= 0U;
974 m_reprepare_observer= NULL;
979 @class Sub_statement_state
980 @brief Used to save context when executing a function or trigger
983 /* Defines used for Sub_statement_state::in_sub_stmt */
985 #define SUB_STMT_TRIGGER 1
986 #define SUB_STMT_FUNCTION 2
989 class Sub_statement_state
991 public:
992 ulonglong options;
993 ulonglong first_successful_insert_id_in_prev_stmt;
994 ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row;
995 Discrete_interval auto_inc_interval_for_cur_row;
996 Discrete_intervals_list auto_inc_intervals_forced;
997 ulonglong limit_found_rows;
998 ha_rows cuted_fields, sent_row_count, examined_row_count;
999 ulong client_capabilities;
1000 uint in_sub_stmt;
1001 bool enable_slow_log;
1002 bool last_insert_id_used;
1003 SAVEPOINT *savepoints;
1004 enum enum_check_fields count_cuted_fields;
1008 /* Flags for the THD::system_thread variable */
1009 enum enum_thread_type
1011 NON_SYSTEM_THREAD= 0,
1012 SYSTEM_THREAD_DELAYED_INSERT= 1,
1013 SYSTEM_THREAD_SLAVE_IO= 2,
1014 SYSTEM_THREAD_SLAVE_SQL= 4,
1015 SYSTEM_THREAD_NDBCLUSTER_BINLOG= 8,
1016 SYSTEM_THREAD_EVENT_SCHEDULER= 16,
1017 SYSTEM_THREAD_EVENT_WORKER= 32
1020 inline char const *
1021 show_system_thread(enum_thread_type thread)
1023 #define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME
1024 switch (thread) {
1025 static char buf[64];
1026 RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD);
1027 RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT);
1028 RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO);
1029 RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL);
1030 RETURN_NAME_AS_STRING(SYSTEM_THREAD_NDBCLUSTER_BINLOG);
1031 RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER);
1032 RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER);
1033 default:
1034 sprintf(buf, "<UNKNOWN SYSTEM THREAD: %d>", thread);
1035 return buf;
1037 #undef RETURN_NAME_AS_STRING
1041 This class represents the interface for internal error handlers.
1042 Internal error handlers are exception handlers used by the server
1043 implementation.
1045 class Internal_error_handler
1047 protected:
1048 Internal_error_handler() :
1049 m_prev_internal_handler(NULL)
1052 virtual ~Internal_error_handler() {}
1054 public:
1056 Handle an error condition.
1057 This method can be implemented by a subclass to achieve any of the
1058 following:
1059 - mask an error internally, prevent exposing it to the user,
1060 - mask an error and throw another one instead.
1061 When this method returns true, the error condition is considered
1062 'handled', and will not be propagated to upper layers.
1063 It is the responsability of the code installing an internal handler
1064 to then check for trapped conditions, and implement logic to recover
1065 from the anticipated conditions trapped during runtime.
1067 This mechanism is similar to C++ try/throw/catch:
1068 - 'try' correspond to <code>THD::push_internal_handler()</code>,
1069 - 'throw' correspond to <code>my_error()</code>,
1070 which invokes <code>my_message_sql()</code>,
1071 - 'catch' correspond to checking how/if an internal handler was invoked,
1072 before removing it from the exception stack with
1073 <code>THD::pop_internal_handler()</code>.
1075 @param sql_errno the error number
1076 @param level the error level
1077 @param thd the calling thread
1078 @return true if the error is handled
1080 virtual bool handle_error(uint sql_errno,
1081 const char *message,
1082 MYSQL_ERROR::enum_warning_level level,
1083 THD *thd) = 0;
1084 private:
1085 Internal_error_handler *m_prev_internal_handler;
1086 friend class THD;
1091 Implements the trivial error handler which cancels all error states
1092 and prevents an SQLSTATE to be set.
1095 class Dummy_error_handler : public Internal_error_handler
1097 public:
1098 bool handle_error(uint sql_errno,
1099 const char *message,
1100 MYSQL_ERROR::enum_warning_level level,
1101 THD *thd)
1103 /* Ignore error */
1104 return TRUE;
1110 This class is an internal error handler implementation for
1111 DROP TABLE statements. The thing is that there may be warnings during
1112 execution of these statements, which should not be exposed to the user.
1113 This class is intended to silence such warnings.
1116 class Drop_table_error_handler : public Internal_error_handler
1118 public:
1119 Drop_table_error_handler(Internal_error_handler *err_handler)
1120 :m_err_handler(err_handler)
1123 public:
1124 bool handle_error(uint sql_errno,
1125 const char *message,
1126 MYSQL_ERROR::enum_warning_level level,
1127 THD *thd);
1129 private:
1130 Internal_error_handler *m_err_handler;
1135 Stores status of the currently executed statement.
1136 Cleared at the beginning of the statement, and then
1137 can hold either OK, ERROR, or EOF status.
1138 Can not be assigned twice per statement.
1141 class Diagnostics_area
1143 public:
1144 enum enum_diagnostics_status
1146 /** The area is cleared at start of a statement. */
1147 DA_EMPTY= 0,
1148 /** Set whenever one calls my_ok(). */
1149 DA_OK,
1150 /** Set whenever one calls my_eof(). */
1151 DA_EOF,
1152 /** Set whenever one calls my_error() or my_message(). */
1153 DA_ERROR,
1154 /** Set in case of a custom response, such as one from COM_STMT_PREPARE. */
1155 DA_DISABLED
1157 /** True if status information is sent to the client. */
1158 bool is_sent;
1159 /** Set to make set_error_status after set_{ok,eof}_status possible. */
1160 bool can_overwrite_status;
1162 void set_ok_status(THD *thd, ha_rows affected_rows_arg,
1163 ulonglong last_insert_id_arg,
1164 const char *message);
1165 void set_eof_status(THD *thd);
1166 void set_error_status(THD *thd, uint sql_errno_arg, const char *message_arg);
1168 void disable_status();
1170 void reset_diagnostics_area();
1172 bool is_set() const { return m_status != DA_EMPTY; }
1173 bool is_error() const { return m_status == DA_ERROR; }
1174 bool is_eof() const { return m_status == DA_EOF; }
1175 bool is_ok() const { return m_status == DA_OK; }
1176 bool is_disabled() const { return m_status == DA_DISABLED; }
1177 enum_diagnostics_status status() const { return m_status; }
1179 const char *message() const
1180 { DBUG_ASSERT(m_status == DA_ERROR || m_status == DA_OK); return m_message; }
1182 uint sql_errno() const
1183 { DBUG_ASSERT(m_status == DA_ERROR); return m_sql_errno; }
1185 uint server_status() const
1187 DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
1188 return m_server_status;
1191 ha_rows affected_rows() const
1192 { DBUG_ASSERT(m_status == DA_OK); return m_affected_rows; }
1194 ulonglong last_insert_id() const
1195 { DBUG_ASSERT(m_status == DA_OK); return m_last_insert_id; }
1197 uint total_warn_count() const
1199 DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
1200 return m_total_warn_count;
1203 Diagnostics_area() { reset_diagnostics_area(); }
1205 private:
1206 /** Message buffer. Can be used by OK or ERROR status. */
1207 char m_message[MYSQL_ERRMSG_SIZE];
1209 SQL error number. One of ER_ codes from share/errmsg.txt.
1210 Set by set_error_status.
1212 uint m_sql_errno;
1215 Copied from thd->server_status when the diagnostics area is assigned.
1216 We need this member as some places in the code use the following pattern:
1217 thd->server_status|= ...
1218 my_eof(thd);
1219 thd->server_status&= ~...
1220 Assigned by OK, EOF or ERROR.
1222 uint m_server_status;
1224 The number of rows affected by the last statement. This is
1225 semantically close to thd->row_count_func, but has a different
1226 life cycle. thd->row_count_func stores the value returned by
1227 function ROW_COUNT() and is cleared only by statements that
1228 update its value, such as INSERT, UPDATE, DELETE and few others.
1229 This member is cleared at the beginning of the next statement.
1231 We could possibly merge the two, but life cycle of thd->row_count_func
1232 can not be changed.
1234 ha_rows m_affected_rows;
1236 Similarly to the previous member, this is a replacement of
1237 thd->first_successful_insert_id_in_prev_stmt, which is used
1238 to implement LAST_INSERT_ID().
1240 ulonglong m_last_insert_id;
1241 /** The total number of warnings. */
1242 uint m_total_warn_count;
1243 enum_diagnostics_status m_status;
1245 @todo: the following THD members belong here:
1246 - warn_list, warn_count,
1252 Storage engine specific thread local data.
1255 struct Ha_data
1258 Storage engine specific thread local data.
1259 Lifetime: one user connection.
1261 void *ha_ptr;
1263 0: Life time: one statement within a transaction. If @@autocommit is
1264 on, also represents the entire transaction.
1265 @sa trans_register_ha()
1267 1: Life time: one transaction within a connection.
1268 If the storage engine does not participate in a transaction,
1269 this should not be used.
1270 @sa trans_register_ha()
1272 Ha_trx_info ha_info[2];
1274 NULL: engine is not bound to this thread
1275 non-NULL: engine is bound to this thread, engine shutdown forbidden
1277 plugin_ref lock;
1278 Ha_data() :ha_ptr(NULL) {}
1283 @class THD
1284 For each client connection we create a separate thread with THD serving as
1285 a thread/connection descriptor
1288 class THD :public Statement,
1289 public Open_tables_state
1291 public:
1292 /* Used to execute base64 coded binlog events in MySQL server */
1293 Relay_log_info* rli_fake;
1294 /* Slave applier execution context */
1295 Relay_log_info* rli_slave;
1298 Constant for THD::where initialization in the beginning of every query.
1300 It's needed because we do not save/restore THD::where normally during
1301 primary (non subselect) query execution.
1303 static const char * const DEFAULT_WHERE;
1305 #ifdef EMBEDDED_LIBRARY
1306 struct st_mysql *mysql;
1307 unsigned long client_stmt_id;
1308 unsigned long client_param_count;
1309 struct st_mysql_bind *client_params;
1310 char *extra_data;
1311 ulong extra_length;
1312 struct st_mysql_data *cur_data;
1313 struct st_mysql_data *first_data;
1314 struct st_mysql_data **data_tail;
1315 void clear_data_list();
1316 struct st_mysql_data *alloc_new_dataset();
1318 In embedded server it points to the statement that is processed
1319 in the current query. We store some results directly in statement
1320 fields then.
1322 struct st_mysql_stmt *current_stmt;
1323 #endif
1324 NET net; // client connection descriptor
1325 MEM_ROOT warn_root; // For warnings and errors
1326 Protocol *protocol; // Current protocol
1327 Protocol_text protocol_text; // Normal protocol
1328 Protocol_binary protocol_binary; // Binary protocol
1329 HASH user_vars; // hash for user variables
1330 String packet; // dynamic buffer for network I/O
1331 String convert_buffer; // buffer for charset conversions
1332 struct sockaddr_in remote; // client socket address
1333 struct rand_struct rand; // used for authentication
1334 struct system_variables variables; // Changeable local variables
1335 struct system_status_var status_var; // Per thread statistic vars
1336 struct system_status_var *initial_status_var; /* used by show status */
1337 THR_LOCK_INFO lock_info; // Locking info of this thread
1338 THR_LOCK_OWNER main_lock_id; // To use for conventional queries
1339 THR_LOCK_OWNER *lock_id; // If not main_lock_id, points to
1340 // the lock_id of a cursor.
1342 Protects THD data accessed from other threads:
1343 - thd->query and thd->query_length (used by SHOW ENGINE
1344 INNODB STATUS and SHOW PROCESSLIST
1346 pthread_mutex_t LOCK_thd_data;
1349 - Protects thd->mysys_var (used during KILL statement and shutdown).
1350 - Is Locked when THD is deleted.
1352 Note: This responsibility was earlier handled by LOCK_thd_data.
1353 This lock is introduced to solve a deadlock issue waiting for
1354 LOCK_thd_data. As this lock reduces responsibility of LOCK_thd_data
1355 the deadlock issues is solved.
1356 Caution: LOCK_thd_kill should not be taken while holding LOCK_thd_data.
1357 THD::awake() currently takes LOCK_thd_data after holding
1358 LOCK_thd_kill.
1360 pthread_mutex_t LOCK_thd_kill;
1362 /* all prepared statements and cursors of this connection */
1363 Statement_map stmt_map;
1365 A pointer to the stack frame of handle_one_connection(),
1366 which is called first in the thread for handling a client
1368 char *thread_stack;
1371 Currently selected catalog.
1373 char *catalog;
1376 @note
1377 Some members of THD (currently 'Statement::db',
1378 'catalog' and 'query') are set and alloced by the slave SQL thread
1379 (for the THD of that thread); that thread is (and must remain, for now)
1380 the only responsible for freeing these 3 members. If you add members
1381 here, and you add code to set them in replication, don't forget to
1382 free_them_and_set_them_to_0 in replication properly. For details see
1383 the 'err:' label of the handle_slave_sql() in sql/slave.cc.
1385 @see handle_slave_sql
1388 Security_context main_security_ctx;
1389 Security_context *security_ctx;
1392 Points to info-string that we show in SHOW PROCESSLIST
1393 You are supposed to update thd->proc_info only if you have coded
1394 a time-consuming piece that MySQL can get stuck in for a long time.
1396 Set it using the thd_proc_info(THD *thread, const char *message)
1397 macro/function.
1399 This member is accessed and assigned without any synchronization.
1400 Therefore, it may point only to constant (statically
1401 allocated) strings, which memory won't go away over time.
1403 const char *proc_info;
1406 Used in error messages to tell user in what part of MySQL we found an
1407 error. E. g. when where= "having clause", if fix_fields() fails, user
1408 will know that the error was in having clause.
1410 const char *where;
1412 double tmp_double_value; /* Used in set_var.cc */
1413 ulong client_capabilities; /* What the client supports */
1414 ulong max_client_packet_length;
1416 HASH handler_tables_hash;
1418 One thread can hold up to one named user-level lock. This variable
1419 points to a lock object if the lock is present. See item_func.cc and
1420 chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK.
1422 User_level_lock *ull;
1423 #ifndef DBUG_OFF
1424 uint dbug_sentry; // watch out for memory corruption
1425 #endif
1426 struct st_my_thread_var *mysys_var;
1428 Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from
1429 first byte of the packet in do_command()
1431 enum enum_server_command command;
1432 uint32 server_id;
1433 uint32 file_id; // for LOAD DATA INFILE
1434 /* remote (peer) port */
1435 uint16 peer_port;
1436 time_t start_time, user_time;
1437 // track down slow pthread_create
1438 ulonglong prior_thr_create_utime, thr_create_utime;
1439 ulonglong start_utime, utime_after_lock;
1441 thr_lock_type update_lock_default;
1442 Delayed_insert *di;
1444 /* <> 0 if we are inside of trigger or stored function. */
1445 uint in_sub_stmt;
1447 /**
1448 Used by fill_status() to avoid acquiring LOCK_status mutex twice
1449 when this function is called recursively (e.g. queries
1450 that contains SELECT on I_S.GLOBAL_STATUS with subquery on the
1451 same I_S table).
1452 Incremented each time fill_status() function is entered and
1453 decremented each time before it returns from the function.
1455 uint fill_status_recursion_level;
1457 /* TRUE when the current top has SQL_LOG_BIN ON */
1458 bool sql_log_bin_toplevel;
1460 /* container for handler's private per-connection data */
1461 Ha_data ha_data[MAX_HA];
1463 #ifndef MYSQL_CLIENT
1464 int binlog_setup_trx_data();
1467 Public interface to write RBR events to the binlog
1469 void binlog_start_trans_and_stmt();
1470 void binlog_set_stmt_begin();
1471 int binlog_write_table_map(TABLE *table, bool is_transactional);
1472 int binlog_write_row(TABLE* table, bool is_transactional,
1473 MY_BITMAP const* cols, size_t colcnt,
1474 const uchar *buf);
1475 int binlog_delete_row(TABLE* table, bool is_transactional,
1476 MY_BITMAP const* cols, size_t colcnt,
1477 const uchar *buf);
1478 int binlog_update_row(TABLE* table, bool is_transactional,
1479 MY_BITMAP const* cols, size_t colcnt,
1480 const uchar *old_data, const uchar *new_data);
1482 void set_server_id(uint32 sid) { server_id = sid; }
1485 Member functions to handle pending event for row-level logging.
1487 template <class RowsEventT> Rows_log_event*
1488 binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
1489 MY_BITMAP const* cols,
1490 size_t colcnt,
1491 size_t needed,
1492 bool is_transactional,
1493 RowsEventT* hint);
1494 Rows_log_event* binlog_get_pending_rows_event() const;
1495 void binlog_set_pending_rows_event(Rows_log_event* ev);
1496 int binlog_flush_pending_rows_event(bool stmt_end);
1497 int binlog_remove_pending_rows_event(bool clear_maps);
1499 private:
1501 Number of outstanding table maps, i.e., table maps in the
1502 transaction cache.
1504 uint binlog_table_maps;
1506 enum enum_binlog_flag {
1507 BINLOG_FLAG_UNSAFE_STMT_PRINTED,
1508 BINLOG_FLAG_COUNT
1512 Flags with per-thread information regarding the status of the
1513 binary log.
1515 uint32 binlog_flags;
1516 public:
1517 uint get_binlog_table_maps() const {
1518 return binlog_table_maps;
1520 #endif /* MYSQL_CLIENT */
1522 public:
1524 struct st_transactions {
1525 SAVEPOINT *savepoints;
1526 THD_TRANS all; // Trans since BEGIN WORK
1527 THD_TRANS stmt; // Trans for current statement
1528 bool on; // see ha_enable_transaction()
1529 XID_STATE xid_state;
1530 Rows_log_event *m_pending_rows_event;
1533 Tables changed in transaction (that must be invalidated in query cache).
1534 List contain only transactional tables, that not invalidated in query
1535 cache (instead of full list of changed in transaction tables).
1537 CHANGED_TABLE_LIST* changed_tables;
1538 MEM_ROOT mem_root; // Transaction-life memory allocation pool
1539 void cleanup()
1541 changed_tables= 0;
1542 savepoints= 0;
1544 If rm_error is raised, it means that this piece of a distributed
1545 transaction has failed and must be rolled back. But the user must
1546 rollback it explicitly, so don't start a new distributed XA until
1547 then.
1549 if (!xid_state.rm_error)
1550 xid_state.xid.null();
1551 #ifdef USING_TRANSACTIONS
1552 free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
1553 #endif
1555 st_transactions()
1557 #ifdef USING_TRANSACTIONS
1558 bzero((char*)this, sizeof(*this));
1559 xid_state.xid.null();
1560 init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
1561 #else
1562 xid_state.xa_state= XA_NOTR;
1563 #endif
1565 } transaction;
1566 Field *dup_field;
1567 #ifndef __WIN__
1568 sigset_t signals;
1569 #endif
1570 #ifdef SIGNAL_WITH_VIO_CLOSE
1571 Vio* active_vio;
1572 #endif
1574 This is to track items changed during execution of a prepared
1575 statement/stored procedure. It's created by
1576 register_item_tree_change() in memory root of THD, and freed in
1577 rollback_item_tree_changes(). For conventional execution it's always
1578 empty.
1580 Item_change_list change_list;
1583 A permanent memory area of the statement. For conventional
1584 execution, the parsed tree and execution runtime reside in the same
1585 memory root. In this case stmt_arena points to THD. In case of
1586 a prepared statement or a stored procedure statement, thd->mem_root
1587 conventionally points to runtime memory, and thd->stmt_arena
1588 points to the memory of the PS/SP, where the parsed tree of the
1589 statement resides. Whenever you need to perform a permanent
1590 transformation of a parsed tree, you should allocate new memory in
1591 stmt_arena, to allow correct re-execution of PS/SP.
1592 Note: in the parser, stmt_arena == thd, even for PS/SP.
1594 Query_arena *stmt_arena;
1597 map for tables that will be updated for a multi-table update query
1598 statement, for other query statements, this will be zero.
1600 table_map table_map_for_update;
1602 /* Tells if LAST_INSERT_ID(#) was called for the current statement */
1603 bool arg_of_last_insert_id_function;
1605 ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for
1606 insertion into an auto_increment column".
1609 This is the first autogenerated insert id which was *successfully*
1610 inserted by the previous statement (exactly, if the previous statement
1611 didn't successfully insert an autogenerated insert id, then it's the one
1612 of the statement before, etc).
1613 It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#).
1614 It is returned by LAST_INSERT_ID().
1616 ulonglong first_successful_insert_id_in_prev_stmt;
1618 Variant of the above, used for storing in statement-based binlog. The
1619 difference is that the one above can change as the execution of a stored
1620 function progresses, while the one below is set once and then does not
1621 change (which is the value which statement-based binlog needs).
1623 ulonglong first_successful_insert_id_in_prev_stmt_for_binlog;
1625 This is the first autogenerated insert id which was *successfully*
1626 inserted by the current statement. It is maintained only to set
1627 first_successful_insert_id_in_prev_stmt when statement ends.
1629 ulonglong first_successful_insert_id_in_cur_stmt;
1631 We follow this logic:
1632 - when stmt starts, first_successful_insert_id_in_prev_stmt contains the
1633 first insert id successfully inserted by the previous stmt.
1634 - as stmt makes progress, handler::insert_id_for_cur_row changes;
1635 every time get_auto_increment() is called,
1636 auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the
1637 reserved interval (if statement-based binlogging).
1638 - at first successful insertion of an autogenerated value,
1639 first_successful_insert_id_in_cur_stmt is set to
1640 handler::insert_id_for_cur_row.
1641 - when stmt goes to binlog,
1642 auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if
1643 non-empty.
1644 - when stmt ends, first_successful_insert_id_in_prev_stmt is set to
1645 first_successful_insert_id_in_cur_stmt.
1648 stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when
1649 LAST_INSERT_ID() is used by a statement.
1650 If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be
1651 stored in the statement-based binlog.
1652 This variable is CUMULATIVE along the execution of a stored function or
1653 trigger: if one substatement sets it to 1 it will stay 1 until the
1654 function/trigger ends, thus making sure that
1655 first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore
1656 and is propagated to the caller for binlogging.
1658 bool stmt_depends_on_first_successful_insert_id_in_prev_stmt;
1660 List of auto_increment intervals reserved by the thread so far, for
1661 storage in the statement-based binlog.
1662 Note that its minimum is not first_successful_insert_id_in_cur_stmt:
1663 assuming a table with an autoinc column, and this happens:
1664 INSERT INTO ... VALUES(3);
1665 SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL);
1666 then the latter INSERT will insert no rows
1667 (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3"
1668 in the binlog is still needed; the list's minimum will contain 3.
1669 This variable is cumulative: if several statements are written to binlog
1670 as one (stored functions or triggers are used) this list is the
1671 concatenation of all intervals reserved by all statements.
1673 Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog;
1674 /* Used by replication and SET INSERT_ID */
1675 Discrete_intervals_list auto_inc_intervals_forced;
1677 There is BUG#19630 where statement-based replication of stored
1678 functions/triggers with two auto_increment columns breaks.
1679 We however ensure that it works when there is 0 or 1 auto_increment
1680 column; our rules are
1681 a) on master, while executing a top statement involving substatements,
1682 first top- or sub- statement to generate auto_increment values wins the
1683 exclusive right to see its values be written to binlog (the write
1684 will be done by the statement or its caller), and the losers won't see
1685 their values be written to binlog.
1686 b) on slave, while replicating a top statement involving substatements,
1687 first top- or sub- statement to need to read auto_increment values from
1688 the master's binlog wins the exclusive right to read them (so the losers
1689 won't read their values from binlog but instead generate on their own).
1690 a) implies that we mustn't backup/restore
1691 auto_inc_intervals_in_cur_stmt_for_binlog.
1692 b) implies that we mustn't backup/restore auto_inc_intervals_forced.
1694 If there are more than 1 auto_increment columns, then intervals for
1695 different columns may mix into the
1696 auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong,
1697 but there is no point in preventing this mixing by preventing intervals
1698 from the secondly inserted column to come into the list, as such
1699 prevention would be wrong too.
1700 What will happen in the case of
1701 INSERT INTO t1 (auto_inc) VALUES(NULL);
1702 where t1 has a trigger which inserts into an auto_inc column of t2, is
1703 that in binlog we'll store the interval of t1 and the interval of t2 (when
1704 we store intervals, soon), then in slave, t1 will use both intervals, t2
1705 will use none; if t1 inserts the same number of rows as on master,
1706 normally the 2nd interval will not be used by t1, which is fine. t2's
1707 values will be wrong if t2's internal auto_increment counter is different
1708 from what it was on master (which is likely). In 5.1, in mixed binlogging
1709 mode, row-based binlogging is used for such cases where two
1710 auto_increment columns are inserted.
1712 inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg)
1714 if (first_successful_insert_id_in_cur_stmt == 0)
1715 first_successful_insert_id_in_cur_stmt= id_arg;
1717 inline ulonglong read_first_successful_insert_id_in_prev_stmt(void)
1719 if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt)
1721 /* It's the first time we read it */
1722 first_successful_insert_id_in_prev_stmt_for_binlog=
1723 first_successful_insert_id_in_prev_stmt;
1724 stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1;
1726 return first_successful_insert_id_in_prev_stmt;
1729 Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
1730 (mysqlbinlog). We'll soon add a variant which can take many intervals in
1731 argument.
1733 inline void force_one_auto_inc_interval(ulonglong next_id)
1735 auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID
1736 auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0);
1739 ulonglong limit_found_rows;
1740 ulonglong options; /* Bitmap of states */
1741 longlong row_count_func; /* For the ROW_COUNT() function */
1742 ha_rows cuted_fields;
1745 number of rows we actually sent to the client, including "synthetic"
1746 rows in ROLLUP etc.
1748 ha_rows sent_row_count;
1751 Number of rows read and/or evaluated for a statement. Used for
1752 slow log reporting.
1754 An examined row is defined as a row that is read and/or evaluated
1755 according to a statement condition, including in
1756 create_sort_index(). Rows may be counted more than once, e.g., a
1757 statement including ORDER BY could possibly evaluate the row in
1758 filesort() before reading it for e.g. update.
1760 ha_rows examined_row_count;
1762 USER_CONN *user_connect;
1763 CHARSET_INFO *db_charset;
1765 FIXME: this, and some other variables like 'count_cuted_fields'
1766 maybe should be statement/cursor local, that is, moved to Statement
1767 class. With current implementation warnings produced in each prepared
1768 statement/cursor settle here.
1770 List <MYSQL_ERROR> warn_list;
1771 uint warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END];
1772 uint total_warn_count;
1773 Diagnostics_area main_da;
1774 #if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
1775 PROFILING profiling;
1776 #endif
1779 Id of current query. Statement can be reused to execute several queries
1780 query_id is global in context of the whole MySQL server.
1781 ID is automatically generated from mutex-protected counter.
1782 It's used in handler code for various purposes: to check which columns
1783 from table are necessary for this select, to check if it's necessary to
1784 update auto-updatable fields (like auto_increment and timestamp).
1786 query_id_t query_id, warn_id;
1787 ulong col_access;
1789 #ifdef ERROR_INJECT_SUPPORT
1790 ulong error_inject_value;
1791 #endif
1792 /* Statement id is thread-wide. This counter is used to generate ids */
1793 ulong statement_id_counter;
1794 ulong rand_saved_seed1, rand_saved_seed2;
1796 Row counter, mainly for errors and warnings. Not increased in
1797 create_sort_index(); may differ from examined_row_count.
1799 ulong row_count;
1800 pthread_t real_id; /* For debugging */
1801 my_thread_id thread_id;
1802 uint tmp_table, global_read_lock;
1803 uint server_status,open_options;
1804 enum enum_thread_type system_thread;
1805 uint select_number; //number of select (used for EXPLAIN)
1806 /* variables.transaction_isolation is reset to this after each commit */
1807 enum_tx_isolation session_tx_isolation;
1808 enum_check_fields count_cuted_fields;
1810 DYNAMIC_ARRAY user_var_events; /* For user variables replication */
1811 MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */
1813 enum killed_state
1815 NOT_KILLED=0,
1816 KILL_BAD_DATA=1,
1817 KILL_CONNECTION=ER_SERVER_SHUTDOWN,
1818 KILL_QUERY=ER_QUERY_INTERRUPTED,
1819 KILLED_NO_VALUE /* means neither of the states */
1821 killed_state volatile killed;
1823 /* scramble - random string sent to client on handshake */
1824 char scramble[SCRAMBLE_LENGTH+1];
1826 bool slave_thread, one_shot_set;
1827 /* tells if current statement should binlog row-based(1) or stmt-based(0) */
1828 bool current_stmt_binlog_row_based;
1829 bool locked, some_tables_deleted;
1830 bool last_cuted_field;
1831 bool no_errors, password;
1833 Set to TRUE if execution of the current compound statement
1834 can not continue. In particular, disables activation of
1835 CONTINUE or EXIT handlers of stored routines.
1836 Reset in the end of processing of the current user request, in
1837 @see mysql_reset_thd_for_next_command().
1839 bool is_fatal_error;
1841 Set by a storage engine to request the entire
1842 transaction (that possibly spans multiple engines) to
1843 rollback. Reset in ha_rollback.
1845 bool transaction_rollback_request;
1847 TRUE if we are in a sub-statement and the current error can
1848 not be safely recovered until we left the sub-statement mode.
1849 In particular, disables activation of CONTINUE and EXIT
1850 handlers inside sub-statements. E.g. if it is a deadlock
1851 error and requires a transaction-wide rollback, this flag is
1852 raised (traditionally, MySQL first has to close all the reads
1853 via @see handler::ha_index_or_rnd_end() and only then perform
1854 the rollback).
1855 Reset to FALSE when we leave the sub-statement mode.
1857 bool is_fatal_sub_stmt_error;
1858 bool query_start_used, rand_used, time_zone_used;
1859 /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */
1860 bool substitute_null_with_insert_id;
1861 bool in_lock_tables;
1863 True if a slave error. Causes the slave to stop. Not the same
1864 as the statement execution error (is_error()), since
1865 a statement may be expected to return an error, e.g. because
1866 it returned an error on master, and this is OK on the slave.
1868 bool is_slave_error;
1869 bool bootstrap, cleanup_done;
1871 /** is set if some thread specific value(s) used in a statement. */
1872 bool thread_specific_used;
1873 bool charset_is_system_charset, charset_is_collation_connection;
1874 bool charset_is_character_set_filesystem;
1875 bool enable_slow_log; /* enable slow log for current statement */
1876 bool abort_on_warning;
1877 bool got_warning; /* Set on call to push_warning() */
1878 bool no_warnings_for_error; /* no warnings on call to my_error() */
1879 /* set during loop of derived table processing */
1880 bool derived_tables_processing;
1881 my_bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */
1883 sp_rcontext *spcont; // SP runtime context
1884 sp_cache *sp_proc_cache;
1885 sp_cache *sp_func_cache;
1887 /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */
1888 uint query_name_consts;
1891 If we do a purge of binary logs, log index info of the threads
1892 that are currently reading it needs to be adjusted. To do that
1893 each thread that is using LOG_INFO needs to adjust the pointer to it
1895 LOG_INFO* current_linfo;
1896 NET* slave_net; // network connection from slave -> m.
1897 /* Used by the sys_var class to store temporary values */
1898 union
1900 my_bool my_bool_value;
1901 long long_value;
1902 ulong ulong_value;
1903 ulonglong ulonglong_value;
1904 } sys_var_tmp;
1906 struct {
1908 If true, mysql_bin_log::write(Log_event) call will not write events to
1909 binlog, and maintain 2 below variables instead (use
1910 mysql_bin_log.start_union_events to turn this on)
1912 bool do_union;
1914 If TRUE, at least one mysql_bin_log::write(Log_event) call has been
1915 made after last mysql_bin_log.start_union_events() call.
1917 bool unioned_events;
1919 If TRUE, at least one mysql_bin_log::write(Log_event e), where
1920 e.cache_stmt == TRUE call has been made after last
1921 mysql_bin_log.start_union_events() call.
1923 bool unioned_events_trans;
1926 'queries' (actually SP statements) that run under inside this binlog
1927 union have thd->query_id >= first_query_id.
1929 query_id_t first_query_id;
1930 } binlog_evt_union;
1933 Internal parser state.
1934 Note that since the parser is not re-entrant, we keep only one parser
1935 state here. This member is valid only when executing code during parsing.
1937 Parser_state *m_parser_state;
1939 #ifdef WITH_PARTITION_STORAGE_ENGINE
1940 partition_info *work_part_info;
1941 #endif
1943 #if defined(ENABLED_DEBUG_SYNC)
1944 /* Debug Sync facility. See debug_sync.cc. */
1945 struct st_debug_sync_control *debug_sync_control;
1946 #endif /* defined(ENABLED_DEBUG_SYNC) */
1948 THD();
1949 ~THD();
1951 void init(void);
1953 Initialize memory roots necessary for query processing and (!)
1954 pre-allocate memory for it. We can't do that in THD constructor because
1955 there are use cases (acl_init, delayed inserts, watcher threads,
1956 killing mysqld) where it's vital to not allocate excessive and not used
1957 memory. Note, that we still don't return error from init_for_queries():
1958 if preallocation fails, we should notice that at the first call to
1959 alloc_root.
1961 void init_for_queries();
1962 void change_user(void);
1963 void cleanup(void);
1964 void cleanup_after_query();
1965 bool store_globals();
1966 bool restore_globals();
1967 #ifdef SIGNAL_WITH_VIO_CLOSE
1968 inline void set_active_vio(Vio* vio)
1970 pthread_mutex_lock(&LOCK_thd_data);
1971 active_vio = vio;
1972 pthread_mutex_unlock(&LOCK_thd_data);
1974 inline void clear_active_vio()
1976 pthread_mutex_lock(&LOCK_thd_data);
1977 active_vio = 0;
1978 pthread_mutex_unlock(&LOCK_thd_data);
1980 void close_active_vio();
1981 #endif
1982 void awake(THD::killed_state state_to_set);
1984 #ifndef MYSQL_CLIENT
1985 enum enum_binlog_query_type {
1987 The query can be logged row-based or statement-based
1989 ROW_QUERY_TYPE,
1992 The query has to be logged statement-based
1994 STMT_QUERY_TYPE,
1997 The query represents a change to a table in the "mysql"
1998 database and is currently mapped to ROW_QUERY_TYPE.
2000 MYSQL_QUERY_TYPE,
2001 QUERY_TYPE_COUNT
2004 int binlog_query(enum_binlog_query_type qtype,
2005 char const *query, ulong query_len,
2006 bool is_trans, bool suppress_use,
2007 int errcode);
2008 #endif
2011 For enter_cond() / exit_cond() to work the mutex must be got before
2012 enter_cond(); this mutex is then released by exit_cond().
2013 Usage must be: lock mutex; enter_cond(); your code; exit_cond().
2015 inline const char* enter_cond(pthread_cond_t *cond, pthread_mutex_t* mutex,
2016 const char* msg)
2018 const char* old_msg = proc_info;
2019 safe_mutex_assert_owner(mutex);
2020 mysys_var->current_mutex = mutex;
2021 mysys_var->current_cond = cond;
2022 proc_info = msg;
2023 return old_msg;
2025 inline void exit_cond(const char* old_msg)
2028 Putting the mutex unlock in exit_cond() ensures that
2029 mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
2030 locked (if that would not be the case, you'll get a deadlock if someone
2031 does a THD::awake() on you).
2033 pthread_mutex_unlock(mysys_var->current_mutex);
2034 pthread_mutex_lock(&mysys_var->mutex);
2035 mysys_var->current_mutex = 0;
2036 mysys_var->current_cond = 0;
2037 proc_info = old_msg;
2038 pthread_mutex_unlock(&mysys_var->mutex);
2040 inline time_t query_start() { query_start_used=1; return start_time; }
2041 inline void set_time()
2043 if (user_time)
2045 start_time= user_time;
2046 start_utime= utime_after_lock= my_micro_time();
2048 else
2049 start_utime= utime_after_lock= my_micro_time_and_time(&start_time);
2051 inline void set_current_time() { start_time= my_time(MY_WME); }
2052 inline void set_time(time_t t)
2054 start_time= user_time= t;
2055 start_utime= utime_after_lock= my_micro_time();
2057 /*TODO: this will be obsolete when we have support for 64 bit my_time_t */
2058 inline bool is_valid_time()
2060 return (IS_TIME_T_VALID_FOR_TIMESTAMP(start_time));
2062 void set_time_after_lock() { utime_after_lock= my_micro_time(); }
2063 ulonglong current_utime() { return my_micro_time(); }
2064 inline ulonglong found_rows(void)
2066 return limit_found_rows;
2068 inline bool active_transaction()
2070 #ifdef USING_TRANSACTIONS
2071 return server_status & SERVER_STATUS_IN_TRANS;
2072 #else
2073 return 0;
2074 #endif
2076 inline bool fill_derived_tables()
2078 return !stmt_arena->is_stmt_prepare() && !lex->only_view_structure();
2080 inline bool fill_information_schema_tables()
2082 return !stmt_arena->is_stmt_prepare();
2084 inline void* trans_alloc(unsigned int size)
2086 return alloc_root(&transaction.mem_root,size);
2089 LEX_STRING *make_lex_string(LEX_STRING *lex_str,
2090 const char* str, uint length,
2091 bool allocate_lex_string);
2093 bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
2094 const char *from, uint from_length,
2095 CHARSET_INFO *from_cs);
2097 bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs);
2099 void add_changed_table(TABLE *table);
2100 void add_changed_table(const char *key, long key_length);
2101 CHANGED_TABLE_LIST * changed_table_dup(const char *key, long key_length);
2102 int send_explain_fields(select_result *result);
2104 Clear the current error, if any.
2105 We do not clear is_fatal_error or is_fatal_sub_stmt_error since we
2106 assume this is never called if the fatal error is set.
2107 @todo: To silence an error, one should use Internal_error_handler
2108 mechanism. In future this function will be removed.
2110 inline void clear_error()
2112 DBUG_ENTER("clear_error");
2113 if (main_da.is_error())
2114 main_da.reset_diagnostics_area();
2115 is_slave_error= 0;
2116 DBUG_VOID_RETURN;
2118 #ifndef EMBEDDED_LIBRARY
2119 inline bool vio_ok() const { return net.vio != 0; }
2120 #else
2121 inline bool vio_ok() const { return true; }
2122 #endif
2124 Mark the current error as fatal. Warning: this does not
2125 set any error, it sets a property of the error, so must be
2126 followed or prefixed with my_error().
2128 inline void fatal_error()
2130 is_fatal_error= 1;
2131 DBUG_PRINT("error",("Fatal error set"));
2134 TRUE if there is an error in the error stack.
2136 Please use this method instead of direct access to
2137 net.report_error.
2139 If TRUE, the current (sub)-statement should be aborted.
2140 The main difference between this member and is_fatal_error
2141 is that a fatal error can not be handled by a stored
2142 procedure continue handler, whereas a normal error can.
2144 To raise this flag, use my_error().
2146 inline bool is_error() const { return main_da.is_error(); }
2147 inline CHARSET_INFO *charset() { return variables.character_set_client; }
2148 void update_charset();
2150 inline Query_arena *activate_stmt_arena_if_needed(Query_arena *backup)
2153 Use the persistent arena if we are in a prepared statement or a stored
2154 procedure statement and we have not already changed to use this arena.
2156 if (!stmt_arena->is_conventional() && mem_root != stmt_arena->mem_root)
2158 set_n_backup_active_arena(stmt_arena, backup);
2159 return stmt_arena;
2161 return 0;
2164 void change_item_tree(Item **place, Item *new_value)
2166 /* TODO: check for OOM condition here */
2167 if (!stmt_arena->is_conventional())
2168 nocheck_register_item_tree_change(place, *place, mem_root);
2169 *place= new_value;
2171 void nocheck_register_item_tree_change(Item **place, Item *old_value,
2172 MEM_ROOT *runtime_memroot);
2173 void rollback_item_tree_changes();
2176 Cleanup statement parse state (parse tree, lex) and execution
2177 state after execution of a non-prepared SQL statement.
2179 void end_statement();
2180 inline int killed_errno() const
2182 killed_state killed_val; /* to cache the volatile 'killed' */
2183 return (killed_val= killed) != KILL_BAD_DATA ? killed_val : 0;
2185 inline void send_kill_message() const
2187 int err= killed_errno();
2188 if (err)
2190 if ((err == KILL_CONNECTION) && !shutdown_in_progress)
2191 err = KILL_QUERY;
2192 my_message(err, ER(err), MYF(0));
2195 /* return TRUE if we will abort query if we make a warning now */
2196 inline bool really_abort_on_warning()
2198 return (abort_on_warning &&
2199 (!transaction.stmt.modified_non_trans_table ||
2200 (variables.sql_mode & MODE_STRICT_ALL_TABLES)));
2202 void set_status_var_init();
2203 void reset_n_backup_open_tables_state(Open_tables_state *backup);
2204 void restore_backup_open_tables_state(Open_tables_state *backup);
2205 void reset_sub_statement_state(Sub_statement_state *backup, uint new_state);
2206 void restore_sub_statement_state(Sub_statement_state *backup);
2207 void set_n_backup_active_arena(Query_arena *set, Query_arena *backup);
2208 void restore_active_arena(Query_arena *set, Query_arena *backup);
2210 inline void set_current_stmt_binlog_row_based_if_mixed()
2213 If in a stored/function trigger, the caller should already have done the
2214 change. We test in_sub_stmt to prevent introducing bugs where people
2215 wouldn't ensure that, and would switch to row-based mode in the middle
2216 of executing a stored function/trigger (which is too late, see also
2217 reset_current_stmt_binlog_row_based()); this condition will make their
2218 tests fail and so force them to propagate the
2219 lex->binlog_row_based_if_mixed upwards to the caller.
2221 if ((variables.binlog_format == BINLOG_FORMAT_MIXED) &&
2222 (in_sub_stmt == 0))
2223 current_stmt_binlog_row_based= TRUE;
2225 inline void set_current_stmt_binlog_row_based()
2227 current_stmt_binlog_row_based= TRUE;
2229 inline void clear_current_stmt_binlog_row_based()
2231 current_stmt_binlog_row_based= FALSE;
2233 inline void reset_current_stmt_binlog_row_based()
2236 If there are temporary tables, don't reset back to
2237 statement-based. Indeed it could be that:
2238 CREATE TEMPORARY TABLE t SELECT UUID(); # row-based
2239 # and row-based does not store updates to temp tables
2240 # in the binlog.
2241 INSERT INTO u SELECT * FROM t; # stmt-based
2242 and then the INSERT will fail as data inserted into t was not logged.
2243 So we continue with row-based until the temp table is dropped.
2244 If we are in a stored function or trigger, we mustn't reset in the
2245 middle of its execution (as the binary logging way of a stored function
2246 or trigger is decided when it starts executing, depending for example on
2247 the caller (for a stored function: if caller is SELECT or
2248 INSERT/UPDATE/DELETE...).
2250 Don't reset binlog format for NDB binlog injector thread.
2252 DBUG_PRINT("debug",
2253 ("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s",
2254 YESNO(temporary_tables), YESNO(in_sub_stmt),
2255 show_system_thread(system_thread)));
2256 if ((temporary_tables == NULL) && (in_sub_stmt == 0) &&
2257 (system_thread != SYSTEM_THREAD_NDBCLUSTER_BINLOG))
2259 current_stmt_binlog_row_based=
2260 test(variables.binlog_format == BINLOG_FORMAT_ROW);
2265 Set the current database; use deep copy of C-string.
2267 @param new_db a pointer to the new database name.
2268 @param new_db_len length of the new database name.
2270 Initialize the current database from a NULL-terminated string with
2271 length. If we run out of memory, we free the current database and
2272 return TRUE. This way the user will notice the error as there will be
2273 no current database selected (in addition to the error message set by
2274 malloc).
2276 @note This operation just sets {db, db_length}. Switching the current
2277 database usually involves other actions, like switching other database
2278 attributes including security context. In the future, this operation
2279 will be made private and more convenient interface will be provided.
2281 @return Operation status
2282 @retval FALSE Success
2283 @retval TRUE Out-of-memory error
2285 bool set_db(const char *new_db, size_t new_db_len)
2288 Acquiring mutex LOCK_thd_data as we either free the memory allocated
2289 for the database and reallocate the memory for the new db or memcpy
2290 the new_db to the db.
2292 pthread_mutex_lock(&LOCK_thd_data);
2293 /* Do not reallocate memory if current chunk is big enough. */
2294 if (db && new_db && db_length >= new_db_len)
2295 memcpy(db, new_db, new_db_len+1);
2296 else
2298 x_free(db);
2299 db= new_db ? my_strndup(new_db, new_db_len, MYF(MY_WME)) : NULL;
2301 db_length= db ? new_db_len : 0;
2302 pthread_mutex_unlock(&LOCK_thd_data);
2303 return new_db && !db;
2307 Set the current database; use shallow copy of C-string.
2309 @param new_db a pointer to the new database name.
2310 @param new_db_len length of the new database name.
2312 @note This operation just sets {db, db_length}. Switching the current
2313 database usually involves other actions, like switching other database
2314 attributes including security context. In the future, this operation
2315 will be made private and more convenient interface will be provided.
2317 void reset_db(char *new_db, size_t new_db_len)
2319 db= new_db;
2320 db_length= new_db_len;
2323 Copy the current database to the argument. Use the current arena to
2324 allocate memory for a deep copy: current database may be freed after
2325 a statement is parsed but before it's executed.
2327 bool copy_db_to(char **p_db, size_t *p_db_length)
2329 if (db == NULL)
2331 my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
2332 return TRUE;
2334 *p_db= strmake(db, db_length);
2335 *p_db_length= db_length;
2336 return FALSE;
2338 thd_scheduler scheduler;
2340 public:
2341 inline Internal_error_handler *get_internal_handler()
2342 { return m_internal_handler; }
2345 Add an internal error handler to the thread execution context.
2346 @param handler the exception handler to add
2348 void push_internal_handler(Internal_error_handler *handler);
2351 Handle an error condition.
2352 @param sql_errno the error number
2353 @param level the error level
2354 @return true if the error is handled
2356 virtual bool handle_error(uint sql_errno, const char *message,
2357 MYSQL_ERROR::enum_warning_level level);
2360 Remove the error handler last pushed.
2362 Internal_error_handler *pop_internal_handler();
2364 /** Overloaded to guard query/query_length fields */
2365 virtual void set_statement(Statement *stmt);
2368 Assign a new value to thd->query.
2369 Protected with LOCK_thd_data mutex.
2371 void set_query(char *query_arg, uint32 query_length_arg);
2372 void binlog_invoker() { m_binlog_invoker= TRUE; }
2373 bool need_binlog_invoker() { return m_binlog_invoker; }
2374 void get_definer(LEX_USER *definer);
2375 void set_invoker(const LEX_STRING *user, const LEX_STRING *host)
2377 invoker_user= *user;
2378 invoker_host= *host;
2380 LEX_STRING get_invoker_user() { return invoker_user; }
2381 LEX_STRING get_invoker_host() { return invoker_host; }
2382 bool has_invoker() { return invoker_user.length > 0; }
2383 private:
2384 /** The current internal error handler for this thread, or NULL. */
2385 Internal_error_handler *m_internal_handler;
2387 The lex to hold the parsed tree of conventional (non-prepared) queries.
2388 Whereas for prepared and stored procedure statements we use an own lex
2389 instance for each new query, for conventional statements we reuse
2390 the same lex. (@see mysql_parse for details).
2392 LEX main_lex;
2394 This memory root is used for two purposes:
2395 - for conventional queries, to allocate structures stored in main_lex
2396 during parsing, and allocate runtime data (execution plan, etc.)
2397 during execution.
2398 - for prepared queries, only to allocate runtime data. The parsed
2399 tree itself is reused between executions and thus is stored elsewhere.
2401 MEM_ROOT main_mem_root;
2404 It will be set TURE if CURRENT_USER() is called in account management
2405 statements or default definer is set in CREATE/ALTER SP, SF, Event,
2406 TRIGGER or VIEW statements.
2408 Current user will be binlogged into Query_log_event if current_user_used
2409 is TRUE; It will be stored into invoker_host and invoker_user by SQL thread.
2411 bool m_binlog_invoker;
2414 It points to the invoker in the Query_log_event.
2415 SQL thread use it as the default definer in CREATE/ALTER SP, SF, Event,
2416 TRIGGER or VIEW statements or current user in account management
2417 statements if it is not NULL.
2419 LEX_STRING invoker_user;
2420 LEX_STRING invoker_host;
2424 /** A short cut for thd->main_da.set_ok_status(). */
2426 inline void
2427 my_ok(THD *thd, ha_rows affected_rows= 0, ulonglong id= 0,
2428 const char *message= NULL)
2430 thd->main_da.set_ok_status(thd, affected_rows, id, message);
2434 /** A short cut for thd->main_da.set_eof_status(). */
2436 inline void
2437 my_eof(THD *thd)
2439 thd->main_da.set_eof_status(thd);
2442 #define tmp_disable_binlog(A) \
2443 {ulonglong tmp_disable_binlog__save_options= (A)->options; \
2444 (A)->options&= ~OPTION_BIN_LOG
2446 #define reenable_binlog(A) (A)->options= tmp_disable_binlog__save_options;}
2450 Used to hold information about file and file structure in exchange
2451 via non-DB file (...INTO OUTFILE..., ...LOAD DATA...)
2452 XXX: We never call destructor for objects of this class.
2455 class sql_exchange :public Sql_alloc
2457 public:
2458 char *file_name;
2459 String *field_term,*enclosed,*line_term,*line_start,*escaped;
2460 bool opt_enclosed;
2461 bool dumpfile;
2462 ulong skip_lines;
2463 CHARSET_INFO *cs;
2464 sql_exchange(char *name,bool dumpfile_flag);
2465 bool escaped_given(void);
2468 #include "log_event.h"
2471 This is used to get result from a select
2474 class JOIN;
2476 class select_result :public Sql_alloc {
2477 protected:
2478 THD *thd;
2479 SELECT_LEX_UNIT *unit;
2480 int nest_level;
2481 public:
2482 select_result();
2483 virtual ~select_result() {};
2484 virtual int prepare(List<Item> &list, SELECT_LEX_UNIT *u)
2486 unit= u;
2487 return 0;
2489 virtual int prepare2(void) { return 0; }
2491 Because of peculiarities of prepared statements protocol
2492 we need to know number of columns in the result set (if
2493 there is a result set) apart from sending columns metadata.
2495 virtual uint field_count(List<Item> &fields) const
2496 { return fields.elements; }
2497 virtual bool send_fields(List<Item> &list, uint flags)=0;
2498 virtual bool send_data(List<Item> &items)=0;
2499 virtual bool initialize_tables (JOIN *join=0) { return 0; }
2500 virtual void send_error(uint errcode,const char *err);
2501 virtual bool send_eof()=0;
2503 Check if this query returns a result set and therefore is allowed in
2504 cursors and set an error message if it is not the case.
2506 @retval FALSE success
2507 @retval TRUE error, an error message is set
2509 virtual bool check_simple_select() const;
2510 virtual void abort() {}
2512 Cleanup instance of this class for next execution of a prepared
2513 statement/stored procedure.
2515 virtual void cleanup();
2516 void set_thd(THD *thd_arg) { thd= thd_arg; }
2518 The nest level, if supported.
2519 @return
2520 -1 if nest level is undefined, otherwise a positive integer.
2522 int get_nest_level() { return nest_level; }
2523 #ifdef EMBEDDED_LIBRARY
2524 virtual void begin_dataset() {}
2525 #else
2526 void begin_dataset() {}
2527 #endif
2532 Base class for select_result descendands which intercept and
2533 transform result set rows. As the rows are not sent to the client,
2534 sending of result set metadata should be suppressed as well.
2537 class select_result_interceptor: public select_result
2539 public:
2540 select_result_interceptor() {} /* Remove gcc warning */
2541 uint field_count(List<Item> &fields) const { return 0; }
2542 bool send_fields(List<Item> &fields, uint flag) { return FALSE; }
2546 class select_send :public select_result {
2548 True if we have sent result set metadata to the client.
2549 In this case the client always expects us to end the result
2550 set with an eof or error packet
2552 bool is_result_set_started;
2553 public:
2554 select_send() :is_result_set_started(FALSE) {}
2555 bool send_fields(List<Item> &list, uint flags);
2556 bool send_data(List<Item> &items);
2557 bool send_eof();
2558 virtual bool check_simple_select() const { return FALSE; }
2559 void abort();
2560 virtual void cleanup();
2564 class select_to_file :public select_result_interceptor {
2565 protected:
2566 sql_exchange *exchange;
2567 File file;
2568 IO_CACHE cache;
2569 ha_rows row_count;
2570 char path[FN_REFLEN];
2572 public:
2573 select_to_file(sql_exchange *ex) :exchange(ex), file(-1),row_count(0L)
2574 { path[0]=0; }
2575 ~select_to_file();
2576 void send_error(uint errcode,const char *err);
2577 bool send_eof();
2578 void cleanup();
2582 #define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape
2586 List of all possible characters of a numeric value text representation.
2588 #define NUMERIC_CHARS ".0123456789e+-"
2591 class select_export :public select_to_file {
2592 uint field_term_length;
2593 int field_sep_char,escape_char,line_sep_char;
2594 int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT
2596 The is_ambiguous_field_sep field is true if a value of the field_sep_char
2597 field is one of the 'n', 't', 'r' etc characters
2598 (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value).
2600 bool is_ambiguous_field_sep;
2602 The is_ambiguous_field_term is true if field_sep_char contains the first
2603 char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can
2604 contain this character.
2606 bool is_ambiguous_field_term;
2608 The is_unsafe_field_sep field is true if a value of the field_sep_char
2609 field is one of the '0'..'9', '+', '-', '.' and 'e' characters
2610 (see the NUMERIC_CHARS constant value).
2612 bool is_unsafe_field_sep;
2613 bool fixed_row_size;
2614 CHARSET_INFO *write_cs; // output charset
2615 public:
2616 select_export(sql_exchange *ex) :select_to_file(ex) {}
2618 Creates a select_export to represent INTO OUTFILE <filename> with a
2619 defined level of subquery nesting.
2621 select_export(sql_exchange *ex, int nest_level_arg) :select_to_file(ex)
2623 nest_level= nest_level_arg;
2625 ~select_export();
2626 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2627 bool send_data(List<Item> &items);
2631 class select_dump :public select_to_file {
2632 public:
2633 select_dump(sql_exchange *ex) :select_to_file(ex) {}
2635 Creates a select_export to represent INTO DUMPFILE <filename> with a
2636 defined level of subquery nesting.
2638 select_dump(sql_exchange *ex, int nest_level_arg) :
2639 select_to_file(ex)
2641 nest_level= nest_level_arg;
2643 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2644 bool send_data(List<Item> &items);
2648 class select_insert :public select_result_interceptor {
2649 protected:
2650 virtual int write_to_binlog(bool is_trans, int errcode);
2651 public:
2652 TABLE_LIST *table_list;
2653 TABLE *table;
2654 List<Item> *fields;
2655 ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not
2656 COPY_INFO info;
2657 bool insert_into_view;
2658 select_insert(TABLE_LIST *table_list_par,
2659 TABLE *table_par, List<Item> *fields_par,
2660 List<Item> *update_fields, List<Item> *update_values,
2661 enum_duplicates duplic, bool ignore);
2662 ~select_insert();
2663 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2664 virtual int prepare2(void);
2665 bool send_data(List<Item> &items);
2666 virtual void store_values(List<Item> &values);
2667 virtual bool can_rollback_data() { return 0; }
2668 void send_error(uint errcode,const char *err);
2669 bool send_eof();
2670 void abort();
2671 /* not implemented: select_insert is never re-used in prepared statements */
2672 void cleanup();
2676 class select_create: public select_insert {
2677 ORDER *group;
2678 TABLE_LIST *create_table;
2679 HA_CREATE_INFO *create_info;
2680 TABLE_LIST *select_tables;
2681 Alter_info *alter_info;
2682 Field **field;
2683 /* lock data for tmp table */
2684 MYSQL_LOCK *m_lock;
2685 /* m_lock or thd->extra_lock */
2686 MYSQL_LOCK **m_plock;
2688 virtual int write_to_binlog(bool is_trans, int errcode);
2689 public:
2690 select_create (TABLE_LIST *table_arg,
2691 HA_CREATE_INFO *create_info_par,
2692 Alter_info *alter_info_arg,
2693 List<Item> &select_fields,enum_duplicates duplic, bool ignore,
2694 TABLE_LIST *select_tables_arg)
2695 :select_insert (NULL, NULL, &select_fields, 0, 0, duplic, ignore),
2696 create_table(table_arg),
2697 create_info(create_info_par),
2698 select_tables(select_tables_arg),
2699 alter_info(alter_info_arg),
2700 m_plock(NULL)
2702 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2704 int binlog_show_create_table(TABLE **tables, uint count, int errcode);
2705 void store_values(List<Item> &values);
2706 void send_error(uint errcode,const char *err);
2707 bool send_eof();
2708 void abort();
2709 virtual bool can_rollback_data() { return 1; }
2711 // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted.
2712 const THD *get_thd(void) { return thd; }
2713 const HA_CREATE_INFO *get_create_info() { return create_info; };
2714 int prepare2(void) { return 0; }
2717 #include <myisam.h>
2720 Param to create temporary tables when doing SELECT:s
2721 NOTE
2722 This structure is copied using memcpy as a part of JOIN.
2725 class TMP_TABLE_PARAM :public Sql_alloc
2727 private:
2728 /* Prevent use of these (not safe because of lists and copy_field) */
2729 TMP_TABLE_PARAM(const TMP_TABLE_PARAM &);
2730 void operator=(TMP_TABLE_PARAM &);
2732 public:
2733 List<Item> copy_funcs;
2734 List<Item> save_copy_funcs;
2735 Copy_field *copy_field, *copy_field_end;
2736 Copy_field *save_copy_field, *save_copy_field_end;
2737 uchar *group_buff;
2738 Item **items_to_copy; /* Fields in tmp table */
2739 MI_COLUMNDEF *recinfo,*start_recinfo;
2740 KEY *keyinfo;
2741 ha_rows end_write_records;
2743 Number of normal fields in the query, including those referred to
2744 from aggregate functions. Hence, "SELECT `field1`,
2745 SUM(`field2`) from t1" sets this counter to 2.
2747 @see count_field_types
2749 uint field_count;
2751 Number of fields in the query that have functions. Includes both
2752 aggregate functions (e.g., SUM) and non-aggregates (e.g., RAND).
2753 Also counts functions referred to from aggregate functions, i.e.,
2754 "SELECT SUM(RAND())" sets this counter to 2.
2756 @see count_field_types
2758 uint func_count;
2760 Number of fields in the query that have aggregate functions. Note
2761 that the optimizer may choose to optimize away these fields by
2762 replacing them with constants, in which case sum_func_count will
2763 need to be updated.
2765 @see opt_sum_query, count_field_types
2767 uint sum_func_count;
2768 uint hidden_field_count;
2769 uint group_parts,group_length,group_null_parts;
2770 uint quick_group;
2771 bool using_indirect_summary_function;
2772 /* If >0 convert all blob fields to varchar(convert_blob_length) */
2773 uint convert_blob_length;
2774 CHARSET_INFO *table_charset;
2775 bool schema_table;
2777 True if GROUP BY and its aggregate functions are already computed
2778 by a table access method (e.g. by loose index scan). In this case
2779 query execution should not perform aggregation and should treat
2780 aggregate functions as normal functions.
2782 bool precomputed_group_by;
2783 bool force_copy_fields;
2785 TMP_TABLE_PARAM()
2786 :copy_field(0), group_parts(0),
2787 group_length(0), group_null_parts(0), convert_blob_length(0),
2788 schema_table(0), precomputed_group_by(0), force_copy_fields(0)
2790 ~TMP_TABLE_PARAM()
2792 cleanup();
2794 void init(void);
2795 inline void cleanup(void)
2797 if (copy_field) /* Fix for Intel compiler */
2799 delete [] copy_field;
2800 save_copy_field= copy_field= 0;
2805 class select_union :public select_result_interceptor
2807 TMP_TABLE_PARAM tmp_table_param;
2808 public:
2809 TABLE *table;
2811 select_union() :table(0) {}
2812 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
2813 bool send_data(List<Item> &items);
2814 bool send_eof();
2815 bool flush();
2817 bool create_result_table(THD *thd, List<Item> *column_types,
2818 bool is_distinct, ulonglong options,
2819 const char *alias);
2822 /* Base subselect interface class */
2823 class select_subselect :public select_result_interceptor
2825 protected:
2826 Item_subselect *item;
2827 public:
2828 select_subselect(Item_subselect *item);
2829 bool send_data(List<Item> &items)=0;
2830 bool send_eof() { return 0; };
2833 /* Single value subselect interface class */
2834 class select_singlerow_subselect :public select_subselect
2836 public:
2837 select_singlerow_subselect(Item_subselect *item_arg)
2838 :select_subselect(item_arg)
2840 bool send_data(List<Item> &items);
2843 /* used in independent ALL/ANY optimisation */
2844 class select_max_min_finder_subselect :public select_subselect
2846 Item_cache *cache;
2847 bool (select_max_min_finder_subselect::*op)();
2848 bool fmax;
2849 public:
2850 select_max_min_finder_subselect(Item_subselect *item_arg, bool mx)
2851 :select_subselect(item_arg), cache(0), fmax(mx)
2853 void cleanup();
2854 bool send_data(List<Item> &items);
2855 bool cmp_real();
2856 bool cmp_int();
2857 bool cmp_decimal();
2858 bool cmp_str();
2861 /* EXISTS subselect interface class */
2862 class select_exists_subselect :public select_subselect
2864 public:
2865 select_exists_subselect(Item_subselect *item_arg)
2866 :select_subselect(item_arg){}
2867 bool send_data(List<Item> &items);
2870 /* Structs used when sorting */
2872 typedef struct st_sort_field {
2873 Field *field; /* Field to sort */
2874 Item *item; /* Item if not sorting fields */
2875 uint length; /* Length of sort field */
2876 uint suffix_length; /* Length suffix (0-4) */
2877 Item_result result_type; /* Type of item */
2878 bool reverse; /* if descending sort */
2879 bool need_strxnfrm; /* If we have to use strxnfrm() */
2880 } SORT_FIELD;
2883 typedef struct st_sort_buffer {
2884 uint index; /* 0 or 1 */
2885 uint sort_orders;
2886 uint change_pos; /* If sort-fields changed */
2887 char **buff;
2888 SORT_FIELD *sortorder;
2889 } SORT_BUFFER;
2891 /* Structure for db & table in sql_yacc */
2893 class Table_ident :public Sql_alloc
2895 public:
2896 LEX_STRING db;
2897 LEX_STRING table;
2898 SELECT_LEX_UNIT *sel;
2899 inline Table_ident(THD *thd, LEX_STRING db_arg, LEX_STRING table_arg,
2900 bool force)
2901 :table(table_arg), sel((SELECT_LEX_UNIT *)0)
2903 if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA))
2904 db.str=0;
2905 else
2906 db= db_arg;
2908 inline Table_ident(LEX_STRING table_arg)
2909 :table(table_arg), sel((SELECT_LEX_UNIT *)0)
2911 db.str=0;
2914 This constructor is used only for the case when we create a derived
2915 table. A derived table has no name and doesn't belong to any database.
2916 Later, if there was an alias specified for the table, it will be set
2917 by add_table_to_list.
2919 inline Table_ident(SELECT_LEX_UNIT *s) : sel(s)
2921 /* We must have a table name here as this is used with add_table_to_list */
2922 db.str= empty_c_string; /* a subject to casedn_str */
2923 db.length= 0;
2924 table.str= internal_table_name;
2925 table.length=1;
2927 bool is_derived_table() const { return test(sel); }
2928 inline void change_db(char *db_name)
2930 db.str= db_name; db.length= (uint) strlen(db_name);
2934 // this is needed for user_vars hash
2935 class user_var_entry
2937 public:
2938 user_var_entry() {} /* Remove gcc warning */
2939 LEX_STRING name;
2940 char *value;
2941 ulong length;
2942 query_id_t update_query_id, used_query_id;
2943 Item_result type;
2944 bool unsigned_flag;
2946 double val_real(my_bool *null_value);
2947 longlong val_int(my_bool *null_value) const;
2948 String *val_str(my_bool *null_value, String *str, uint decimals);
2949 my_decimal *val_decimal(my_bool *null_value, my_decimal *result);
2950 DTCollation collation;
2954 Unique -- class for unique (removing of duplicates).
2955 Puts all values to the TREE. If the tree becomes too big,
2956 it's dumped to the file. User can request sorted values, or
2957 just iterate through them. In the last case tree merging is performed in
2958 memory simultaneously with iteration, so it should be ~2-3x faster.
2961 class Unique :public Sql_alloc
2963 DYNAMIC_ARRAY file_ptrs;
2964 ulong max_elements;
2965 ulonglong max_in_memory_size;
2966 IO_CACHE file;
2967 TREE tree;
2968 uchar *record_pointers;
2969 bool flush();
2970 uint size;
2972 public:
2973 ulong elements;
2974 Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg,
2975 uint size_arg, ulonglong max_in_memory_size_arg);
2976 ~Unique();
2977 ulong elements_in_tree() { return tree.elements_in_tree; }
2978 inline bool unique_add(void *ptr)
2980 DBUG_ENTER("unique_add");
2981 DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements));
2982 if (tree.elements_in_tree > max_elements && flush())
2983 DBUG_RETURN(1);
2984 DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg));
2987 bool get(TABLE *table);
2988 static double get_use_cost(uint *buffer, uint nkeys, uint key_size,
2989 ulonglong max_in_memory_size);
2991 // Returns the number of bytes needed in imerge_cost_buf.
2992 inline static int get_cost_calc_buff_size(ulong nkeys, uint key_size,
2993 ulonglong max_in_memory_size)
2995 register ulonglong max_elems_in_tree=
2996 (max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size));
2997 return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree));
3000 void reset();
3001 bool walk(tree_walk_action action, void *walk_action_arg);
3003 uint get_size() const { return size; }
3004 ulonglong get_max_in_memory_size() const { return max_in_memory_size; }
3006 friend int unique_write_to_file(uchar* key, element_count count, Unique *unique);
3007 friend int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique);
3011 class multi_delete :public select_result_interceptor
3013 TABLE_LIST *delete_tables, *table_being_deleted;
3014 Unique **tempfiles;
3015 ha_rows deleted, found;
3016 uint num_of_tables;
3017 int error;
3018 bool do_delete;
3019 /* True if at least one table we delete from is transactional */
3020 bool transactional_tables;
3021 /* True if at least one table we delete from is not transactional */
3022 bool normal_tables;
3023 bool delete_while_scanning;
3025 error handling (rollback and binlogging) can happen in send_eof()
3026 so that afterward send_error() needs to find out that.
3028 bool error_handled;
3030 public:
3031 multi_delete(TABLE_LIST *dt, uint num_of_tables);
3032 ~multi_delete();
3033 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
3034 bool send_data(List<Item> &items);
3035 bool initialize_tables (JOIN *join);
3036 void send_error(uint errcode,const char *err);
3037 int do_deletes();
3038 int do_table_deletes(TABLE *table, bool ignore);
3039 bool send_eof();
3040 virtual void abort();
3044 class multi_update :public select_result_interceptor
3046 TABLE_LIST *all_tables; /* query/update command tables */
3047 TABLE_LIST *leaves; /* list of leves of join table tree */
3048 TABLE_LIST *update_tables, *table_being_updated;
3049 TABLE **tmp_tables, *main_table, *table_to_update;
3050 TMP_TABLE_PARAM *tmp_table_param;
3051 ha_rows updated, found;
3052 List <Item> *fields, *values;
3053 List <Item> **fields_for_table, **values_for_table;
3054 uint table_count;
3056 List of tables referenced in the CHECK OPTION condition of
3057 the updated view excluding the updated table.
3059 List <TABLE> unupdated_check_opt_tables;
3060 Copy_field *copy_field;
3061 enum enum_duplicates handle_duplicates;
3062 bool do_update, trans_safe;
3063 /* True if the update operation has made a change in a transactional table */
3064 bool transactional_tables;
3065 bool ignore;
3067 error handling (rollback and binlogging) can happen in send_eof()
3068 so that afterward send_error() needs to find out that.
3070 bool error_handled;
3072 public:
3073 multi_update(TABLE_LIST *ut, TABLE_LIST *leaves_list,
3074 List<Item> *fields, List<Item> *values,
3075 enum_duplicates handle_duplicates, bool ignore);
3076 ~multi_update();
3077 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
3078 bool send_data(List<Item> &items);
3079 bool initialize_tables (JOIN *join);
3080 void send_error(uint errcode,const char *err);
3081 int do_updates();
3082 bool send_eof();
3083 virtual void abort();
3086 class my_var : public Sql_alloc {
3087 public:
3088 LEX_STRING s;
3089 #ifndef DBUG_OFF
3091 Routine to which this Item_splocal belongs. Used for checking if correct
3092 runtime context is used for variable handling.
3094 sp_head *sp;
3095 #endif
3096 bool local;
3097 uint offset;
3098 enum_field_types type;
3099 my_var (LEX_STRING& j, bool i, uint o, enum_field_types t)
3100 :s(j), local(i), offset(o), type(t)
3102 ~my_var() {}
3105 class select_dumpvar :public select_result_interceptor {
3106 ha_rows row_count;
3107 public:
3108 List<my_var> var_list;
3109 select_dumpvar() { var_list.empty(); row_count= 0;}
3111 Creates a select_dumpvar to represent INTO <variable> with a defined
3112 level of subquery nesting.
3114 select_dumpvar(int nest_level_arg)
3116 var_list.empty();
3117 row_count= 0;
3118 nest_level= nest_level_arg;
3120 ~select_dumpvar() {}
3121 int prepare(List<Item> &list, SELECT_LEX_UNIT *u);
3122 bool send_data(List<Item> &items);
3123 bool send_eof();
3124 virtual bool check_simple_select() const;
3125 void cleanup();
3128 /* Bits in sql_command_flags */
3130 #define CF_CHANGES_DATA 1
3131 #define CF_HAS_ROW_COUNT 2
3132 #define CF_STATUS_COMMAND 4
3133 #define CF_SHOW_TABLE_COMMAND 8
3134 #define CF_WRITE_LOGS_COMMAND 16
3136 Must be set for SQL statements that may contain
3137 Item expressions and/or use joins and tables.
3138 Indicates that the parse tree of such statement may
3139 contain rule-based optimizations that depend on metadata
3140 (i.e. number of columns in a table), and consequently
3141 that the statement must be re-prepared whenever
3142 referenced metadata changes. Must not be set for
3143 statements that themselves change metadata, e.g. RENAME,
3144 ALTER and other DDL, since otherwise will trigger constant
3145 reprepare. Consequently, complex item expressions and
3146 joins are currently prohibited in these statements.
3148 #define CF_REEXECUTION_FRAGILE 32
3150 /* Functions in sql_class.cc */
3152 void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var);
3154 void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
3155 STATUS_VAR *dec_var);
3156 void mark_transaction_to_rollback(THD *thd, bool all);
3158 #endif /* MYSQL_SERVER */