sql_class.h

Go to the documentation of this file.
00001 /* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
00002 
00003    This program is free software; you can redistribute it and/or modify
00004    it under the terms of the GNU General Public License as published by
00005    the Free Software Foundation; either version 2 of the License, or
00006    (at your option) any later version.
00007 
00008    This program is distributed in the hope that it will be useful,
00009    but WITHOUT ANY WARRANTY; without even the implied warranty of
00010    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00011    GNU General Public License for more details.
00012 
00013    You should have received a copy of the GNU General Public License
00014    along with this program; if not, write to the Free Software
00015    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
00016 
00017 
00018 /* Classes in mysql */
00019 
00020 #ifdef __GNUC__
00021 #pragma interface                       /* gcc class implementation */
00022 #endif
00023 
00024 // TODO: create log.h and move all the log header stuff there
00025 
00026 class Query_log_event;
00027 class Load_log_event;
00028 class Slave_log_event;
00029 class Format_description_log_event;
00030 class sp_rcontext;
00031 class sp_cache;
00032 
00033 enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE };
00034 enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME };
00035 enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_IGNORE, DUP_UPDATE };
00036 enum enum_log_type { LOG_CLOSED, LOG_TO_BE_OPENED, LOG_NORMAL, LOG_NEW, LOG_BIN};
00037 enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON,
00038                             DELAY_KEY_WRITE_ALL };
00039 
00040 enum enum_check_fields { CHECK_FIELD_IGNORE, CHECK_FIELD_WARN,
00041                          CHECK_FIELD_ERROR_FOR_NULL };
00042 
00043 extern char internal_table_name[2];
00044 extern const char **errmesg;
00045 
00046 /* log info errors */
00047 #define LOG_INFO_EOF -1
00048 #define LOG_INFO_IO  -2
00049 #define LOG_INFO_INVALID -3
00050 #define LOG_INFO_SEEK -4
00051 #define LOG_INFO_MEM -6
00052 #define LOG_INFO_FATAL -7
00053 #define LOG_INFO_IN_USE -8
00054 
00055 /* bitmap to SQL_LOG::close() */
00056 #define LOG_CLOSE_INDEX         1
00057 #define LOG_CLOSE_TO_BE_OPENED  2
00058 #define LOG_CLOSE_STOP_EVENT    4
00059 
00060 struct st_relay_log_info;
00061 
00062 typedef struct st_log_info
00063 {
00064   char log_file_name[FN_REFLEN];
00065   my_off_t index_file_offset, index_file_start_offset;
00066   my_off_t pos;
00067   bool fatal; // if the purge happens to give us a negative offset
00068   pthread_mutex_t lock;
00069   st_log_info():fatal(0) { pthread_mutex_init(&lock, MY_MUTEX_INIT_FAST);}
00070   ~st_log_info() { pthread_mutex_destroy(&lock);}
00071 } LOG_INFO;
00072 
00073 typedef struct st_user_var_events
00074 {
00075   user_var_entry *user_var_event;
00076   char *value;
00077   ulong length;
00078   Item_result type;
00079   uint charset_number;
00080 } BINLOG_USER_VAR_EVENT;
00081 
00082 class Log_event;
00083 
00084 class MYSQL_LOG
00085  {
00086  private:
00087   /* LOCK_log and LOCK_index are inited by init_pthread_objects() */
00088   pthread_mutex_t LOCK_log, LOCK_index;
00089   pthread_cond_t update_cond;
00090   ulonglong bytes_written;
00091   time_t last_time,query_start;
00092   IO_CACHE log_file;
00093   IO_CACHE index_file;
00094   char *name;
00095   char time_buff[20],db[NAME_LEN+1];
00096   char log_file_name[FN_REFLEN],index_file_name[FN_REFLEN];
00097   // current file sequence number for load data infile binary logging
00098   uint file_id;
00099   uint open_count;                              // For replication
00100   volatile enum_log_type log_type;
00101   enum cache_type io_cache_type;
00102   bool write_error, inited;
00103   bool need_start_event;
00104   /*
00105     no_auto_events means we don't want any of these automatic events :
00106     Start/Rotate/Stop. That is, in 4.x when we rotate a relay log, we don't want
00107     a Rotate_log event to be written to the relay log. When we start a relay log
00108     etc. So in 4.x this is 1 for relay logs, 0 for binlogs.
00109     In 5.0 it's 0 for relay logs too!
00110   */
00111   bool no_auto_events;                       
00112   /* 
00113      The max size before rotation (usable only if log_type == LOG_BIN: binary
00114      logs and relay logs).
00115      For a binlog, max_size should be max_binlog_size.
00116      For a relay log, it should be max_relay_log_size if this is non-zero,
00117      max_binlog_size otherwise.
00118      max_size is set in init(), and dynamically changed (when one does SET
00119      GLOBAL MAX_BINLOG_SIZE|MAX_RELAY_LOG_SIZE) by fix_max_binlog_size and
00120      fix_max_relay_log_size). 
00121   */
00122   ulong max_size;
00123   friend class Log_event;
00124 
00125 public:
00126   MYSQL_LOG();
00127   ~MYSQL_LOG();
00128 
00129   /* 
00130      These describe the log's format. This is used only for relay logs.
00131      _for_exec is used by the SQL thread, _for_queue by the I/O thread. It's
00132      necessary to have 2 distinct objects, because the I/O thread may be reading
00133      events in a different format from what the SQL thread is reading (consider
00134      the case of a master which has been upgraded from 5.0 to 5.1 without doing
00135      RESET MASTER, or from 4.x to 5.0).
00136   */
00137   Format_description_log_event *description_event_for_exec,
00138     *description_event_for_queue;
00139 
00140   void reset_bytes_written()
00141   {
00142     bytes_written = 0;
00143   }
00144   void harvest_bytes_written(ulonglong* counter)
00145   {
00146 #ifndef DBUG_OFF
00147     char buf1[22],buf2[22];
00148 #endif  
00149     DBUG_ENTER("harvest_bytes_written");
00150     (*counter)+=bytes_written;
00151     DBUG_PRINT("info",("counter: %s  bytes_written: %s", llstr(*counter,buf1),
00152                        llstr(bytes_written,buf2)));
00153     bytes_written=0;
00154     DBUG_VOID_RETURN;
00155   }
00156   void set_max_size(ulong max_size_arg);
00157   void signal_update();
00158   void wait_for_update(THD* thd, bool master_or_slave);
00159   void set_need_start_event() { need_start_event = 1; }
00160   void init(enum_log_type log_type_arg,
00161             enum cache_type io_cache_type_arg,
00162             bool no_auto_events_arg, ulong max_size);
00163   void init_pthread_objects();
00164   void cleanup();
00165   bool open(const char *log_name,enum_log_type log_type,
00166             const char *new_name, const char *index_file_name_arg,
00167             enum cache_type io_cache_type_arg,
00168             bool no_auto_events_arg, ulong max_size,
00169             bool null_created);
00170   void new_file(bool need_lock= 1);
00171   bool write(THD *thd, enum enum_server_command command,
00172              const char *format,...);
00173   bool write(THD *thd, const char *query, uint query_length,
00174              time_t query_start=0);
00175   bool write(Log_event* event_info); // binary log write
00176   bool write(THD *thd, IO_CACHE *cache, bool commit_or_rollback);
00177 
00178   /*
00179     v stands for vector
00180     invoked as appendv(buf1,len1,buf2,len2,...,bufn,lenn,0)
00181   */
00182   bool appendv(const char* buf,uint len,...);
00183   bool append(Log_event* ev);
00184   
00185   int generate_new_name(char *new_name,const char *old_name);
00186   void make_log_name(char* buf, const char* log_ident);
00187   bool is_active(const char* log_file_name);
00188   int update_log_index(LOG_INFO* linfo, bool need_update_threads);
00189   int purge_logs(const char *to_log, bool included, 
00190                  bool need_mutex, bool need_update_threads,
00191                  ulonglong *decrease_log_space);
00192   int purge_logs_before_date(time_t purge_time);
00193   int purge_first_log(struct st_relay_log_info* rli, bool included); 
00194   bool reset_logs(THD* thd);
00195   void close(uint exiting);
00196   bool cut_spurious_tail();
00197   void report_pos_in_innodb();
00198 
00199   // iterating through the log index file
00200   int find_log_pos(LOG_INFO* linfo, const char* log_name,
00201                    bool need_mutex);
00202   int find_next_log(LOG_INFO* linfo, bool need_mutex);
00203   int get_current_log(LOG_INFO* linfo);
00204   uint next_file_id();
00205   inline bool is_open() { return log_type != LOG_CLOSED; }
00206   inline char* get_index_fname() { return index_file_name;}
00207   inline char* get_log_fname() { return log_file_name; }
00208   inline pthread_mutex_t* get_log_lock() { return &LOCK_log; }
00209   inline IO_CACHE* get_log_file() { return &log_file; }
00210 
00211   inline void lock_index() { pthread_mutex_lock(&LOCK_index);}
00212   inline void unlock_index() { pthread_mutex_unlock(&LOCK_index);}
00213   inline IO_CACHE *get_index_file() { return &index_file;}
00214   inline uint32 get_open_count() { return open_count; }
00215 };
00216 
00217 /* character conversion tables */
00218 
00219 
00220 typedef struct st_copy_info {
00221   ha_rows records;
00222   ha_rows deleted;
00223   ha_rows updated;
00224   ha_rows copied;
00225   ha_rows error_count;
00226   enum enum_duplicates handle_duplicates;
00227   int escape_char, last_errno;
00228 /* for INSERT ... UPDATE */
00229   List<Item> *update_fields;
00230   List<Item> *update_values;
00231 /* for VIEW ... WITH CHECK OPTION */
00232   TABLE_LIST *view;
00233   bool ignore;
00234 } COPY_INFO;
00235 
00236 
00237 class key_part_spec :public Sql_alloc {
00238 public:
00239   const char *field_name;
00240   uint length;
00241   key_part_spec(const char *name,uint len=0) :field_name(name), length(len) {}
00242   bool operator==(const key_part_spec& other) const;
00243 };
00244 
00245 
00246 class Alter_drop :public Sql_alloc {
00247 public:
00248   enum drop_type {KEY, COLUMN };
00249   const char *name;
00250   enum drop_type type;
00251   Alter_drop(enum drop_type par_type,const char *par_name)
00252     :name(par_name), type(par_type) {}
00253 };
00254 
00255 
00256 class Alter_column :public Sql_alloc {
00257 public:
00258   const char *name;
00259   Item *def;
00260   Alter_column(const char *par_name,Item *literal)
00261     :name(par_name), def(literal) {}
00262 };
00263 
00264 
00265 class Key :public Sql_alloc {
00266 public:
00267   enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY};
00268   enum Keytype type;
00269   enum ha_key_alg algorithm;
00270   List<key_part_spec> columns;
00271   const char *name;
00272   bool generated;
00273 
00274   Key(enum Keytype type_par, const char *name_arg, enum ha_key_alg alg_par,
00275       bool generated_arg, List<key_part_spec> &cols)
00276     :type(type_par), algorithm(alg_par), columns(cols), name(name_arg),
00277     generated(generated_arg)
00278   {}
00279   ~Key() {}
00280   /* Equality comparison of keys (ignoring name) */
00281   friend bool foreign_key_prefix(Key *a, Key *b);
00282 };
00283 
00284 class Table_ident;
00285 
00286 class foreign_key: public Key {
00287 public:
00288   enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL,
00289                       FK_MATCH_PARTIAL, FK_MATCH_SIMPLE};
00290   enum fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE,
00291                    FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_DEFAULT};
00292 
00293   Table_ident *ref_table;
00294   List<key_part_spec> ref_columns;
00295   uint delete_opt, update_opt, match_opt;
00296   foreign_key(const char *name_arg, List<key_part_spec> &cols,
00297               Table_ident *table,   List<key_part_spec> &ref_cols,
00298               uint delete_opt_arg, uint update_opt_arg, uint match_opt_arg)
00299     :Key(FOREIGN_KEY, name_arg, HA_KEY_ALG_UNDEF, 0, cols),
00300     ref_table(table), ref_columns(cols),
00301     delete_opt(delete_opt_arg), update_opt(update_opt_arg),
00302     match_opt(match_opt_arg)
00303   {}
00304 };
00305 
00306 typedef struct st_mysql_lock
00307 {
00308   TABLE **table;
00309   uint table_count,lock_count;
00310   THR_LOCK_DATA **locks;
00311 } MYSQL_LOCK;
00312 
00313 
00314 class LEX_COLUMN : public Sql_alloc
00315 {
00316 public:
00317   String column;
00318   uint rights;
00319   LEX_COLUMN (const String& x,const  uint& y ): column (x),rights (y) {}
00320 };
00321 
00322 #include "sql_lex.h"                            /* Must be here */
00323 
00324 /* Needed to be able to have an I_List of char* strings in mysqld.cc. */
00325 
00326 class i_string: public ilink
00327 {
00328 public:
00329   char* ptr;
00330   i_string():ptr(0) { }
00331   i_string(char* s) : ptr(s) {}
00332 };
00333 
00334 /* needed for linked list of two strings for replicate-rewrite-db */
00335 class i_string_pair: public ilink
00336 {
00337 public:
00338   char* key;
00339   char* val;
00340   i_string_pair():key(0),val(0) { }
00341   i_string_pair(char* key_arg, char* val_arg) : key(key_arg),val(val_arg) {}
00342 };
00343 
00344 
00345 class MYSQL_ERROR: public Sql_alloc
00346 {
00347 public:
00348   enum enum_warning_level
00349   { WARN_LEVEL_NOTE, WARN_LEVEL_WARN, WARN_LEVEL_ERROR, WARN_LEVEL_END};
00350 
00351   uint code;
00352   enum_warning_level level;
00353   char *msg;
00354   
00355   MYSQL_ERROR(THD *thd, uint code_arg, enum_warning_level level_arg,
00356               const char *msg_arg)
00357     :code(code_arg), level(level_arg)
00358   {
00359     if (msg_arg)
00360       set_msg(thd, msg_arg);
00361   }
00362   void set_msg(THD *thd, const char *msg_arg);
00363 };
00364 
00365 
00366 class delayed_insert;
00367 class select_result;
00368 
00369 #define THD_SENTRY_MAGIC 0xfeedd1ff
00370 #define THD_SENTRY_GONE  0xdeadbeef
00371 
00372 #define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC)
00373 
00374 struct system_variables
00375 {
00376   ulonglong myisam_max_extra_sort_file_size;
00377   ulonglong myisam_max_sort_file_size;
00378   ha_rows select_limit;
00379   ha_rows max_join_size;
00380   ulong auto_increment_increment, auto_increment_offset;
00381   ulong bulk_insert_buff_size;
00382   ulong join_buff_size;
00383   ulong long_query_time;
00384   ulong max_allowed_packet;
00385   ulong max_error_count;
00386   ulong max_heap_table_size;
00387   ulong max_length_for_sort_data;
00388   ulong max_sort_length;
00389   ulong max_tmp_tables;
00390   ulong max_insert_delayed_threads;
00391   ulong myisam_repair_threads;
00392   ulong myisam_sort_buff_size;
00393   ulong net_buffer_length;
00394   ulong net_interactive_timeout;
00395   ulong net_read_timeout;
00396   ulong net_retry_count;
00397   ulong net_wait_timeout;
00398   ulong net_write_timeout;
00399   ulong optimizer_prune_level;
00400   ulong optimizer_search_depth;
00401   ulong preload_buff_size;
00402   ulong query_cache_type;
00403   ulong read_buff_size;
00404   ulong read_rnd_buff_size;
00405   ulong sortbuff_size;
00406   ulong table_type;
00407   ulong tmp_table_size;
00408   ulong tx_isolation;
00409   /* Determines which non-standard SQL behaviour should be enabled */
00410   ulong sql_mode;
00411   /* check of key presence in updatable view */
00412   ulong updatable_views_with_limit;
00413   ulong default_week_format;
00414   ulong max_seeks_for_key;
00415   ulong range_alloc_block_size;
00416   ulong query_alloc_block_size;
00417   ulong query_prealloc_size;
00418   ulong trans_alloc_block_size;
00419   ulong trans_prealloc_size;
00420   ulong log_warnings;
00421   ulong group_concat_max_len;
00422   /*
00423     In slave thread we need to know in behalf of which
00424     thread the query is being run to replicate temp tables properly
00425   */
00426   ulong pseudo_thread_id;
00427 
00428   my_bool low_priority_updates;
00429   my_bool new_mode;
00430   my_bool query_cache_wlock_invalidate;
00431 #ifdef HAVE_INNOBASE_DB
00432   my_bool innodb_table_locks;
00433 #endif /* HAVE_INNOBASE_DB */
00434 #ifdef HAVE_NDBCLUSTER_DB
00435   ulong ndb_autoincrement_prefetch_sz;
00436   my_bool ndb_force_send;
00437   my_bool ndb_use_exact_count;
00438   my_bool ndb_use_transactions;
00439 #endif /* HAVE_NDBCLUSTER_DB */
00440   my_bool old_passwords;
00441   
00442   /* Only charset part of these variables is sensible */
00443   CHARSET_INFO  *character_set_client;
00444   CHARSET_INFO  *character_set_results;
00445   
00446   /* Both charset and collation parts of these variables are important */
00447   CHARSET_INFO  *collation_server;
00448   CHARSET_INFO  *collation_database;
00449   CHARSET_INFO  *collation_connection;
00450 
00451   Time_zone *time_zone;
00452 
00453   /* DATE, DATETIME and TIME formats */
00454   DATE_TIME_FORMAT *date_format;
00455   DATE_TIME_FORMAT *datetime_format;
00456   DATE_TIME_FORMAT *time_format;
00457 };
00458 
00459 
00460 /* per thread status variables */
00461 
00462 typedef struct system_status_var
00463 {
00464   ulong bytes_received;
00465   ulong bytes_sent;
00466   ulong com_other;
00467   ulong com_stat[(uint) SQLCOM_END];
00468   ulong created_tmp_disk_tables;
00469   ulong created_tmp_tables;
00470   ulong ha_commit_count;
00471   ulong ha_delete_count;
00472   ulong ha_read_first_count;
00473   ulong ha_read_last_count;
00474   ulong ha_read_key_count;
00475   ulong ha_read_next_count;
00476   ulong ha_read_prev_count;
00477   ulong ha_read_rnd_count;
00478   ulong ha_read_rnd_next_count;
00479   ulong ha_rollback_count;
00480   ulong ha_update_count;
00481   ulong ha_write_count;
00482 
00483   /* KEY_CACHE parts. These are copies of the original */
00484   ulong key_blocks_changed;
00485   ulong key_blocks_used;
00486   ulong key_cache_r_requests;
00487   ulong key_cache_read;
00488   ulong key_cache_w_requests;
00489   ulong key_cache_write;
00490   /* END OF KEY_CACHE parts */
00491 
00492   ulong net_big_packet_count;
00493   ulong opened_tables;
00494   ulong select_full_join_count;
00495   ulong select_full_range_join_count;
00496   ulong select_range_count;
00497   ulong select_range_check_count;
00498   ulong select_scan_count;
00499   ulong long_query_count;
00500   ulong filesort_merge_passes;
00501   ulong filesort_range_count;
00502   ulong filesort_rows;
00503   ulong filesort_scan_count;
00504 } STATUS_VAR;
00505 
00506 /*
00507   This is used for 'show status'. It must be updated to the last ulong
00508   variable in system_status_var
00509 */
00510 
00511 #define last_system_status_var filesort_scan_count
00512 
00513 
00514 void free_tmp_table(THD *thd, TABLE *entry);
00515 
00516 
00517 class Item_arena
00518 {
00519 public:
00520   /*
00521     List of items created in the parser for this query. Every item puts
00522     itself to the list on creation (see Item::Item() for details))
00523   */
00524   Item *free_list;
00525   MEM_ROOT main_mem_root;
00526   MEM_ROOT *mem_root;                   // Pointer to current memroot
00527 #ifndef DBUG_OFF
00528   bool backup_arena;
00529 #endif
00530   enum enum_state 
00531   {
00532     INITIALIZED= 0, PREPARED= 1, EXECUTED= 3, CONVENTIONAL_EXECUTION= 2, 
00533     ERROR= -1
00534   };
00535   
00536   enum_state state;
00537 
00538   /* We build without RTTI, so dynamic_cast can't be used. */
00539   enum Type
00540   {
00541     STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE
00542   };
00543 
00544   /*
00545     This constructor is used only when Item_arena is created as
00546     backup storage for another instance of Item_arena.
00547   */
00548   Item_arena() {};
00549   /*
00550     Create arena for already constructed THD using its variables as
00551     parameters for memory root initialization.
00552   */
00553   Item_arena(THD *thd);
00554   /*
00555     Create arena and optionally init memory root with minimal values.
00556     Particularly used if Item_arena is part of Statement.
00557   */
00558   Item_arena(bool init_mem_root);
00559   virtual Type type() const;
00560   virtual ~Item_arena() {};
00561 
00562   inline bool is_stmt_prepare() const { return (int)state < (int)PREPARED; }
00563   inline bool is_first_stmt_execute() const { return state == PREPARED; }
00564   inline bool is_stmt_execute() const
00565   { return state == PREPARED || state == EXECUTED; }
00566   inline bool is_conventional() const
00567   { return state == CONVENTIONAL_EXECUTION; }
00568   inline gptr alloc(unsigned int size) { return alloc_root(mem_root,size); }
00569   inline gptr calloc(unsigned int size)
00570   {
00571     gptr ptr;
00572     if ((ptr=alloc_root(mem_root,size)))
00573       bzero((char*) ptr,size);
00574     return ptr;
00575   }
00576   inline char *strdup(const char *str)
00577   { return strdup_root(mem_root,str); }
00578   inline char *strmake(const char *str, uint size)
00579   { return strmake_root(mem_root,str,size); }
00580   inline char *memdup(const char *str, uint size)
00581   { return memdup_root(mem_root,str,size); }
00582   inline char *memdup_w_gap(const char *str, uint size, uint gap)
00583   {
00584     gptr ptr;
00585     if ((ptr=alloc_root(mem_root,size+gap)))
00586       memcpy(ptr,str,size);
00587     return ptr;
00588   }
00589 
00590   void set_n_backup_item_arena(Item_arena *set, Item_arena *backup);
00591   void restore_backup_item_arena(Item_arena *set, Item_arena *backup);
00592   void set_item_arena(Item_arena *set);
00593 };
00594 
00595 
00596 class Cursor;
00597 
00598 /*
00599   State of a single command executed against this connection.
00600   One connection can contain a lot of simultaneously running statements,
00601   some of which could be:
00602    - prepared, that is, contain placeholders,
00603    - opened as cursors. We maintain 1 to 1 relationship between
00604      statement and cursor - if user wants to create another cursor for his
00605      query, we create another statement for it. 
00606   To perform some action with statement we reset THD part to the state  of
00607   that statement, do the action, and then save back modified state from THD
00608   to the statement. It will be changed in near future, and Statement will
00609   be used explicitly.
00610 */
00611 
00612 class Statement: public Item_arena
00613 {
00614   Statement(const Statement &rhs);              /* not implemented: */
00615   Statement &operator=(const Statement &rhs);   /* non-copyable */
00616 public:
00617   /* FIXME: must be private */
00618   LEX     main_lex;
00619 
00620   /*
00621     Uniquely identifies each statement object in thread scope; change during
00622     statement lifetime. FIXME: must be const
00623   */
00624    ulong id;
00625 
00626   /*
00627     - if set_query_id=1, we set field->query_id for all fields. In that case 
00628     field list can not contain duplicates.
00629   */
00630   bool set_query_id;
00631   /*
00632     This variable is used in post-parse stage to declare that sum-functions,
00633     or functions which have sense only if GROUP BY is present, are allowed.
00634     For example in queries
00635     SELECT MIN(i) FROM foo
00636     SELECT GROUP_CONCAT(a, b, MIN(i)) FROM ... GROUP BY ...
00637     MIN(i) have no sense.
00638     Though it's grammar-related issue, it's hard to catch it out during the
00639     parse stage because GROUP BY clause goes in the end of query. This
00640     variable is mainly used in setup_fields/fix_fields.
00641     See item_sum.cc for details.
00642   */
00643   bool allow_sum_func;
00644 
00645   LEX_STRING name; /* name for named prepared statements */
00646   LEX *lex;                                     // parse tree descriptor
00647   /*
00648     Points to the query associated with this statement. It's const, but
00649     we need to declare it char * because all table handlers are written
00650     in C and need to point to it.
00651 
00652     Note that (A) if we set query = NULL, we must at the same time set
00653     query_length = 0, and protect the whole operation with the
00654     LOCK_thread_count mutex. And (B) we are ONLY allowed to set query to a
00655     non-NULL value if its previous value is NULL. We do not need to protect
00656     operation (B) with any mutex. To avoid crashes in races, if we do not
00657     know that thd->query cannot change at the moment, one should print
00658     thd->query like this:
00659       (1) reserve the LOCK_thread_count mutex;
00660       (2) check if thd->query is NULL;
00661       (3) if not NULL, then print at most thd->query_length characters from
00662       it. We will see the query_length field as either 0, or the right value
00663       for it.
00664     Assuming that the write and read of an n-bit memory field in an n-bit
00665     computer is atomic, we can avoid races in the above way. 
00666     This printing is needed at least in SHOW PROCESSLIST and SHOW INNODB
00667     STATUS.
00668   */
00669   char *query;
00670   uint32 query_length;                          // current query length
00671   Cursor *cursor;
00672 
00673 public:
00674 
00675   /*
00676     This constructor is called when statement is a subobject of THD:
00677     some variables are initialized in THD::init due to locking problems
00678   */
00679   Statement();
00680 
00681   Statement(THD *thd);
00682   virtual ~Statement();
00683 
00684   /* Assign execution context (note: not all members) of given stmt to self */
00685   void set_statement(Statement *stmt);
00686   void set_n_backup_statement(Statement *stmt, Statement *backup);
00687   void restore_backup_statement(Statement *stmt, Statement *backup);
00688   /* return class type */
00689   virtual Type type() const;
00690 };
00691 
00692 
00693 /*
00694   Container for all statements created/used in a connection.
00695   Statements in Statement_map have unique Statement::id (guaranteed by id
00696   assignment in Statement::Statement)
00697   Non-empty statement names are unique too: attempt to insert a new statement
00698   with duplicate name causes older statement to be deleted
00699 
00700   Statements are auto-deleted when they are removed from the map and when the
00701   map is deleted.
00702 */
00703 
00704 class Statement_map
00705 {
00706 public:
00707   Statement_map();
00708 
00709   int insert(Statement *statement);
00710 
00711   Statement *find_by_name(LEX_STRING *name)
00712   {
00713     Statement *stmt;
00714     stmt= (Statement*)hash_search(&names_hash, (byte*)name->str,
00715                                   name->length);
00716     return stmt;
00717   }
00718 
00719   Statement *find(ulong id)
00720   {
00721     if (last_found_statement == 0 || id != last_found_statement->id)
00722     {
00723       Statement *stmt;
00724       stmt= (Statement *) hash_search(&st_hash, (byte *) &id, sizeof(id));
00725       if (stmt && stmt->name.str)
00726         return NULL;
00727       last_found_statement= stmt;
00728     }
00729     return last_found_statement;
00730   }
00731   void erase(Statement *statement)
00732   {
00733     if (statement == last_found_statement)
00734       last_found_statement= 0;
00735     if (statement->name.str)
00736     {
00737       hash_delete(&names_hash, (byte *) statement);  
00738     }
00739     hash_delete(&st_hash, (byte *) statement);
00740   }
00741   /* Erase all statements (calls Statement destructor) */
00742   void reset()
00743   {
00744     hash_reset(&names_hash);
00745     hash_reset(&st_hash);
00746     last_found_statement= 0;
00747   }
00748 
00749   ~Statement_map()
00750   {
00751     hash_free(&names_hash);
00752     hash_free(&st_hash);
00753   }
00754 private:
00755   HASH st_hash;
00756   HASH names_hash;
00757   Statement *last_found_statement;
00758 };
00759 
00760 
00761 /*
00762   A registry for item tree transformations performed during
00763   query optimization. We register only those changes which require
00764   a rollback to re-execute a prepared statement or stored procedure
00765   yet another time.
00766 */
00767 
00768 struct Item_change_record;
00769 typedef I_List<Item_change_record> Item_change_list;
00770 
00771 
00772 /*
00773   For each client connection we create a separate thread with THD serving as
00774   a thread/connection descriptor
00775 */
00776 
00777 class THD :public ilink,
00778            public Statement
00779 {
00780 public:
00781 #ifdef EMBEDDED_LIBRARY
00782   struct st_mysql  *mysql;
00783   struct st_mysql_data *data;
00784   unsigned long  client_stmt_id;
00785   unsigned long  client_param_count;
00786   struct st_mysql_bind *client_params;
00787   char *extra_data;
00788   ulong extra_length;
00789   String query_rest;
00790 #endif
00791   NET     net;                          // client connection descriptor
00792   MEM_ROOT warn_root;                   // For warnings and errors
00793   Protocol *protocol;                   // Current protocol
00794   Protocol_simple protocol_simple;      // Normal protocol
00795   Protocol_prep protocol_prep;          // Binary protocol
00796   HASH    user_vars;                    // hash for user variables
00797   String  packet;                       // dynamic buffer for network I/O
00798   String  convert_buffer;               // buffer for charset conversions
00799   struct  sockaddr_in remote;           // client socket address
00800   struct  rand_struct rand;             // used for authentication
00801   struct  system_variables variables;   // Changeable local variables
00802   struct  system_status_var status_var; // Per thread statistic vars
00803   pthread_mutex_t LOCK_delete;          // Locked before thd is deleted
00804   /* all prepared statements and cursors of this connection */
00805   Statement_map stmt_map; 
00806   /*
00807     keeps THD state while it is used for active statement
00808     Note: we perform special cleanup for it in THD destructor.
00809   */
00810   Statement stmt_backup;
00811   /*
00812     A pointer to the stack frame of handle_one_connection(),
00813     which is called first in the thread for handling a client
00814   */
00815   char    *thread_stack;
00816 
00817   /*
00818     host - host of the client
00819     user - user of the client, set to NULL until the user has been read from
00820      the connection
00821     priv_user - The user privilege we are using. May be '' for anonymous user.
00822     db - currently selected database
00823     catalog - currently selected catalog
00824     ip - client IP
00825     WARNING: some members of THD (currently 'db', 'catalog' and 'query')  are
00826     set and alloced by the slave SQL thread (for the THD of that thread); that
00827     thread is (and must remain, for now) the only responsible for freeing these
00828     3 members. If you add members here, and you add code to set them in
00829     replication, don't forget to free_them_and_set_them_to_0 in replication
00830     properly. For details see the 'err:' label of the pthread_handler_decl of
00831     the slave SQL thread, in sql/slave.cc.
00832    */
00833   char    *host,*user,*priv_user,*db,*catalog,*ip;
00834   char    priv_host[MAX_HOSTNAME];
00835   /* remote (peer) port */
00836   uint16 peer_port;
00837   /*
00838     Points to info-string that we show in SHOW PROCESSLIST
00839     You are supposed to update thd->proc_info only if you have coded
00840     a time-consuming piece that MySQL can get stuck in for a long time.
00841   */
00842   const char *proc_info;
00843   /* points to host if host is available, otherwise points to ip */
00844   const char *host_or_ip;
00845 
00846   ulong client_capabilities;            /* What the client supports */
00847   ulong max_client_packet_length;
00848   ulong master_access;                  /* Global privileges from mysql.user */
00849   ulong db_access;                      /* Privileges for current db */
00850 
00851   /*
00852     open_tables - list of regular tables in use by this thread
00853     temporary_tables - list of temp tables in use by this thread
00854     handler_tables - list of tables that were opened with HANDLER OPEN
00855      and are still in use by this thread
00856   */
00857   TABLE   *open_tables,*temporary_tables, *handler_tables, *derived_tables;
00858   /*
00859     During a MySQL session, one can lock tables in two modes: automatic
00860     or manual. In automatic mode all necessary tables are locked just before
00861     statement execution, and all acquired locks are stored in 'lock'
00862     member. Unlocking takes place automatically as well, when the
00863     statement ends.
00864     Manual mode comes into play when a user issues a 'LOCK TABLES'
00865     statement. In this mode the user can only use the locked tables.
00866     Trying to use any other tables will give an error. The locked tables are
00867     stored in 'locked_tables' member.  Manual locking is described in
00868     the 'LOCK_TABLES' chapter of the MySQL manual.
00869     See also lock_tables() for details.
00870   */
00871   MYSQL_LOCK    *lock;                          /* Current locks */
00872   MYSQL_LOCK    *locked_tables;                 /* Tables locked with LOCK */
00873   HASH          handler_tables_hash;
00874   /*
00875     One thread can hold up to one named user-level lock. This variable
00876     points to a lock object if the lock is present. See item_func.cc and
00877     chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK. 
00878   */
00879   User_level_lock *ull;
00880 #ifndef DBUG_OFF
00881   uint dbug_sentry; // watch out for memory corruption
00882 #endif
00883   struct st_my_thread_var *mysys_var;
00884   /*
00885     Type of current query: COM_PREPARE, COM_QUERY, etc. Set from 
00886     first byte of the packet in do_command()
00887   */
00888   enum enum_server_command command;
00889   uint32     server_id;
00890   uint32     file_id;                   // for LOAD DATA INFILE
00891   /*
00892     Used in error messages to tell user in what part of MySQL we found an
00893     error. E. g. when where= "having clause", if fix_fields() fails, user
00894     will know that the error was in having clause.
00895   */
00896   const char *where;
00897   time_t     start_time,time_after_lock,user_time;
00898   time_t     connect_time,thr_create_time; // track down slow pthread_create
00899   thr_lock_type update_lock_default;
00900   delayed_insert *di;
00901   my_bool    tablespace_op;     /* This is TRUE in DISCARD/IMPORT TABLESPACE */
00902   struct st_transactions {
00903     IO_CACHE trans_log;                 // Inited ONLY if binlog is open !
00904     THD_TRANS all;                      // Trans since BEGIN WORK
00905     THD_TRANS stmt;                     // Trans for current statement
00906     uint bdb_lock_count;
00907 #ifdef HAVE_NDBCLUSTER_DB
00908     void* thd_ndb;
00909 #endif
00910     bool on;
00911     /*
00912        Tables changed in transaction (that must be invalidated in query cache).
00913        List contain only transactional tables, that not invalidated in query
00914        cache (instead of full list of changed in transaction tables).
00915     */
00916     CHANGED_TABLE_LIST* changed_tables;
00917     MEM_ROOT mem_root; // Transaction-life memory allocation pool
00918     void cleanup()
00919     {
00920       changed_tables = 0;
00921       free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
00922     }
00923   } transaction;
00924   Field      *dupp_field;
00925 #ifndef __WIN__
00926   sigset_t signals,block_signals;
00927 #endif
00928 #ifdef SIGNAL_WITH_VIO_CLOSE
00929   Vio* active_vio;
00930 #endif
00931   /*
00932     This is to track items changed during execution of a prepared
00933     statement/stored procedure. It's created by
00934     register_item_tree_change() in memory root of THD, and freed in
00935     rollback_item_tree_changes(). For conventional execution it's always 0.
00936   */
00937   Item_change_list change_list;
00938 
00939   /*
00940     Current prepared Item_arena if there one, or 0
00941   */
00942   Item_arena *current_arena;
00943   /*
00944     next_insert_id is set on SET INSERT_ID= #. This is used as the next
00945     generated auto_increment value in handler.cc
00946   */
00947   ulonglong  next_insert_id;
00948   /* Remember last next_insert_id to reset it if something went wrong */
00949   ulonglong  prev_insert_id;
00950   /*
00951     The insert_id used for the last statement or set by SET LAST_INSERT_ID=#
00952     or SELECT LAST_INSERT_ID(#).  Used for binary log and returned by
00953     LAST_INSERT_ID()
00954   */
00955   ulonglong  last_insert_id;
00956   /*
00957     Set to the first value that LAST_INSERT_ID() returned for the last
00958     statement.  When this is set, last_insert_id_used is set to true.
00959   */
00960   ulonglong  current_insert_id;
00961   ulonglong  limit_found_rows;
00962   ha_rows    cuted_fields,
00963              sent_row_count, examined_row_count;
00964   table_map  used_tables;
00965   USER_CONN *user_connect;
00966   CHARSET_INFO *db_charset;
00967   List<TABLE> temporary_tables_should_be_free; // list of temporary tables
00968   /*
00969     FIXME: this, and some other variables like 'count_cuted_fields'
00970     maybe should be statement/cursor local, that is, moved to Statement
00971     class. With current implementation warnings produced in each prepared
00972     statement/cursor settle here.
00973   */
00974   List       <MYSQL_ERROR> warn_list;
00975   uint       warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END];
00976   uint       total_warn_count;
00977   /*
00978     Id of current query. Statement can be reused to execute several queries
00979     query_id is global in context of the whole MySQL server.
00980     ID is automatically generated from mutex-protected counter.
00981     It's used in handler code for various purposes: to check which columns
00982     from table are necessary for this select, to check if it's necessary to
00983     update auto-updatable fields (like auto_increment and timestamp).
00984   */
00985   ulong      query_id;
00986   ulong      warn_id, version, options, thread_id, col_access;
00987 
00988   /* Statement id is thread-wide. This counter is used to generate ids */
00989   ulong      statement_id_counter;
00990   ulong      rand_saved_seed1, rand_saved_seed2;
00991   ulong      row_count;  // Row counter, mainly for errors and warnings
00992   long       dbug_thread_id;
00993   pthread_t  real_id;
00994   uint       current_tablenr,tmp_table,global_read_lock;
00995   uint       server_status,open_options,system_thread;
00996   uint32     db_length;
00997   uint       select_number;             //number of select (used for EXPLAIN)
00998   /* variables.transaction_isolation is reset to this after each commit */
00999   enum_tx_isolation session_tx_isolation;
01000   enum_check_fields count_cuted_fields;
01001   /* for user variables replication*/
01002   DYNAMIC_ARRAY user_var_events;
01003 
01004   enum killed_state { NOT_KILLED=0, KILL_BAD_DATA=1, KILL_CONNECTION=ER_SERVER_SHUTDOWN, KILL_QUERY=ER_QUERY_INTERRUPTED };
01005   killed_state volatile killed;
01006 
01007   /* scramble - random string sent to client on handshake */
01008   char       scramble[SCRAMBLE_LENGTH+1];
01009 
01010   bool       slave_thread, one_shot_set;
01011   bool       locked, some_tables_deleted;
01012   bool       last_cuted_field;
01013   bool       no_errors, password, is_fatal_error;
01014   bool       query_start_used, rand_used, time_zone_used;
01015   bool       last_insert_id_used,insert_id_used, clear_next_insert_id;
01016   bool       in_lock_tables;
01017   bool       query_error, bootstrap, cleanup_done;
01018   bool       tmp_table_used;
01019   bool       charset_is_system_charset, charset_is_collation_connection;
01020   bool       slow_command;
01021   bool       no_trans_update, abort_on_warning;
01022   longlong   row_count_func;    /* For the ROW_COUNT() function */
01023   sp_rcontext *spcont;          // SP runtime context
01024   sp_cache   *sp_proc_cache;
01025   sp_cache   *sp_func_cache;
01026 
01027   /*
01028     If we do a purge of binary logs, log index info of the threads
01029     that are currently reading it needs to be adjusted. To do that
01030     each thread that is using LOG_INFO needs to adjust the pointer to it
01031   */
01032   LOG_INFO*  current_linfo;
01033   NET*       slave_net;                 // network connection from slave -> m.
01034   /* Used by the sys_var class to store temporary values */
01035   union
01036   {
01037     my_bool my_bool_value;
01038     long    long_value;
01039   } sys_var_tmp;
01040 
01041   THD();
01042   ~THD();
01043 
01044   void init(void);
01045   /*
01046     Initialize memory roots necessary for query processing and (!)
01047     pre-allocate memory for it. We can't do that in THD constructor because
01048     there are use cases (acl_init, delayed inserts, watcher threads,
01049     killing mysqld) where it's vital to not allocate excessive and not used
01050     memory. Note, that we still don't return error from init_for_queries():
01051     if preallocation fails, we should notice that at the first call to
01052     alloc_root. 
01053   */
01054   void init_for_queries();
01055   void change_user(void);
01056   void cleanup(void);
01057   void cleanup_after_query();
01058   bool store_globals();
01059 #ifdef SIGNAL_WITH_VIO_CLOSE
01060   inline void</