]> git.pld-linux.org Git - packages/mysql.git/blob - userstat.patch
- rel 0.5 (consider this to be test before rel 1); update percona patches; drop obsol...
[packages/mysql.git] / userstat.patch
1 # name       : userstat.patch
2 # introduced : 11 or before
3 # maintainer : Oleg
4 #
5 #!!! notice !!!
6 # Any small change to this file in the main branch
7 # should be done or reviewed by the maintainer!
8 diff -ruN a/include/mysql/plugin.h b/include/mysql/plugin.h
9 --- a/include/mysql/plugin.h    2010-12-03 20:58:24.000000000 +0300
10 +++ b/include/mysql/plugin.h    2010-12-31 06:06:43.000000000 +0300
11 @@ -547,6 +547,9 @@
12  unsigned long thd_log_slow_verbosity(const MYSQL_THD thd);
13  int thd_opt_slow_log();
14  #define EXTENDED_SLOWLOG
15 +
16 +#define EXTENDED_FOR_USERSTAT
17 +
18  /**
19    Create a temporary file.
20  
21 diff -ruN a/include/mysql_com.h b/include/mysql_com.h
22 --- a/include/mysql_com.h       2010-12-03 20:58:24.000000000 +0300
23 +++ b/include/mysql_com.h       2010-12-31 06:12:05.000000000 +0300
24 @@ -31,6 +31,7 @@
25  
26  #define SERVER_VERSION_LENGTH 60
27  #define SQLSTATE_LENGTH 5
28 +#define LIST_PROCESS_HOST_LEN 64
29  
30  /*
31    Maximum length of comments
32 @@ -142,6 +143,11 @@
33  #define REFRESH_DES_KEY_FILE        0x40000L
34  #define REFRESH_USER_RESOURCES      0x80000L
35  #define REFRESH_QUERY_RESPONSE_TIME 0x100000L /* response time distibution */
36 +#define REFRESH_TABLE_STATS    0x200000L /* Refresh table stats my_hash table */
37 +#define REFRESH_INDEX_STATS    0x400000L /* Refresh index stats my_hash table */
38 +#define REFRESH_USER_STATS     0x800000L /* Refresh user stats my_hash table */
39 +#define REFRESH_CLIENT_STATS   0x1000000L /* Refresh client stats my_hash table */
40 +#define REFRESH_THREAD_STATS   0x2000000L /* Refresh thread stats my_hash table */
41  
42  #define CLIENT_LONG_PASSWORD   1       /* new more secure passwords */
43  #define CLIENT_FOUND_ROWS      2       /* Found instead of affected rows */
44 diff -ruN a/patch_info/userstats.patch b/patch_info/userstats.patch
45 --- a/patch_info/userstats.patch        1970-01-01 03:00:00.000000000 +0300
46 +++ b/patch_info/userstats.patch        2010-12-30 00:45:46.000000000 +0300
47 @@ -0,0 +1,15 @@
48 +File=userstats.patch
49 +Name=SHOW USER/TABLE/INDEX statistics
50 +Version=V2
51 +Author=Google
52 +License=GPL
53 +Comment=Added INFORMATION_SCHEMA.*_STATISTICS
54 +2008-12-01
55 +YK: fix behavior for prepared statements
56 +
57 +2008-11-26
58 +YK: add switch variable "userstat_running" to control INFORMATION_SCHEMA.*_STATISTICS (default:OFF)
59 +2010-12-31
60 +Ported to 5.5.8
61 +2011-1-5
62 +Fix porting
63 diff -ruN a/sql/handler.cc b/sql/handler.cc
64 --- a/sql/handler.cc    2010-12-03 20:58:26.000000000 +0300
65 +++ b/sql/handler.cc    2010-12-30 00:59:23.000000000 +0300
66 @@ -1239,6 +1239,8 @@
67      if (cookie)
68        tc_log->unlog(cookie, xid);
69      DBUG_EXECUTE_IF("crash_commit_after", DBUG_SUICIDE(););
70 +    if (is_real_trans)
71 +      thd->diff_commit_trans++;
72      RUN_HOOK(transaction, after_commit, (thd, FALSE));
73  end:
74      if (rw_trans && mdl_request.ticket)
75 @@ -1393,6 +1395,8 @@
76    /* Always cleanup. Even if nht==0. There may be savepoints. */
77    if (is_real_trans)
78      thd->transaction.cleanup();
79 +
80 +  thd->diff_rollback_trans++;
81    if (all)
82      thd->transaction_rollback_request= FALSE;
83  
84 @@ -1796,6 +1800,7 @@
85      ha_info->reset(); /* keep it conveniently zero-filled */
86    }
87    trans->ha_list= sv->ha_list;
88 +  thd->diff_rollback_trans++;
89    DBUG_RETURN(error);
90  }
91  
92 @@ -2165,6 +2170,8 @@
93        dup_ref=ref+ALIGN_SIZE(ref_length);
94      cached_table_flags= table_flags();
95    }
96 +  rows_read= rows_changed= 0;
97 +  memset(index_rows_read, 0, sizeof(index_rows_read));
98    DBUG_RETURN(error);
99  }
100  
101 @@ -3596,6 +3603,127 @@
102    return;
103  }
104  
105 +// Updates the global table stats with the TABLE this handler represents.
106 +void handler::update_global_table_stats()
107 +{
108 +  if (!opt_userstat_running)
109 +  {
110 +    rows_read= rows_changed= 0;
111 +    return;
112 +  }
113 +
114 +  if (!rows_read && !rows_changed)
115 +    return;  // Nothing to update.
116 +  // table_cache_key is db_name + '\0' + table_name + '\0'.
117 +  if (!table->s || !table->s->table_cache_key.str || !table->s->table_name.str)
118 +    return;
119 +
120 +  TABLE_STATS* table_stats;
121 +  char key[NAME_LEN * 2 + 2];
122 +  // [db] + '.' + [table]
123 +  sprintf(key, "%s.%s", table->s->table_cache_key.str, table->s->table_name.str);
124 +
125 +  mysql_mutex_lock(&LOCK_global_table_stats);
126 +  // Gets the global table stats, creating one if necessary.
127 +  if (!(table_stats = (TABLE_STATS *) my_hash_search(&global_table_stats,
128 +                                                     (uchar*)key,
129 +                                                     strlen(key))))
130 +  {
131 +    if (!(table_stats = ((TABLE_STATS *)
132 +                         my_malloc(sizeof(TABLE_STATS), MYF(MY_WME | MY_ZEROFILL)))))
133 +    {
134 +      // Out of memory.
135 +      sql_print_error("Allocating table stats failed.");
136 +      goto end;
137 +    }
138 +    strncpy(table_stats->table, key, sizeof(table_stats->table));
139 +    table_stats->rows_read=              0;
140 +    table_stats->rows_changed=           0;
141 +    table_stats->rows_changed_x_indexes= 0;
142 +    table_stats->engine_type=            (int) ht->db_type;
143 +
144 +    if (my_hash_insert(&global_table_stats, (uchar *) table_stats))
145 +    {
146 +      // Out of memory.
147 +      sql_print_error("Inserting table stats failed.");
148 +      my_free((char *) table_stats);
149 +      goto end;
150 +    }
151 +  }
152 +  // Updates the global table stats.
153 +  table_stats->rows_read+=              rows_read;
154 +  table_stats->rows_changed+=           rows_changed;
155 +  table_stats->rows_changed_x_indexes+=
156 +    rows_changed * (table->s->keys ? table->s->keys : 1);
157 +  current_thd->diff_total_read_rows+=   rows_read;
158 +  rows_read= rows_changed=              0;
159 +end:
160 +  mysql_mutex_unlock(&LOCK_global_table_stats);
161 +}
162 +
163 +// Updates the global index stats with this handler's accumulated index reads.
164 +void handler::update_global_index_stats()
165 +{
166 +  // table_cache_key is db_name + '\0' + table_name + '\0'.
167 +  if (!table->s || !table->s->table_cache_key.str || !table->s->table_name.str)
168 +    return;
169 +
170 +  if (!opt_userstat_running)
171 +  {
172 +    for (uint x= 0; x < table->s->keys; ++x)
173 +    {
174 +      index_rows_read[x]= 0;
175 +    }
176 +    return;
177 +  }
178 +
179 +  for (uint x = 0; x < table->s->keys; ++x)
180 +  {
181 +    if (index_rows_read[x])
182 +    {
183 +      // Rows were read using this index.
184 +      KEY* key_info = &table->key_info[x];
185 +
186 +      if (!key_info->name) continue;
187 +
188 +      INDEX_STATS* index_stats;
189 +      char key[NAME_LEN * 3 + 3];
190 +      // [db] + '.' + [table] + '.' + [index]
191 +      sprintf(key, "%s.%s.%s",  table->s->table_cache_key.str,
192 +              table->s->table_name.str, key_info->name);
193 +
194 +      mysql_mutex_lock(&LOCK_global_index_stats);
195 +      // Gets the global index stats, creating one if necessary.
196 +      if (!(index_stats = (INDEX_STATS *) my_hash_search(&global_index_stats,
197 +                                                         (uchar *) key,
198 +                                                         strlen(key))))
199 +      {
200 +        if (!(index_stats = ((INDEX_STATS *)
201 +                             my_malloc(sizeof(INDEX_STATS), MYF(MY_WME | MY_ZEROFILL)))))
202 +        {
203 +          // Out of memory.
204 +          sql_print_error("Allocating index stats failed.");
205 +          goto end;
206 +        }
207 +        strncpy(index_stats->index, key, sizeof(index_stats->index));
208 +        index_stats->rows_read= 0;
209 +
210 +        if (my_hash_insert(&global_index_stats, (uchar *) index_stats))
211 +        {
212 +          // Out of memory.
213 +          sql_print_error("Inserting index stats failed.");
214 +          my_free((char *) index_stats);
215 +          goto end;
216 +        }
217 +      }
218 +      // Updates the global index stats.
219 +      index_stats->rows_read+= index_rows_read[x];
220 +      index_rows_read[x]=      0;
221 +  end:
222 +      mysql_mutex_unlock(&LOCK_global_index_stats);
223 +    }
224 +  }
225 +}
226  
227  /****************************************************************************
228  ** Some general functions that isn't in the handler class
229 diff -ruN a/sql/handler.h b/sql/handler.h
230 --- a/sql/handler.h     2010-12-03 20:58:26.000000000 +0300
231 +++ b/sql/handler.h     2010-12-31 05:10:00.000000000 +0300
232 @@ -33,6 +33,10 @@
233  #include <ft_global.h>
234  #include <keycache.h>
235  
236 +#if MAX_KEY > 128
237 +#error MAX_KEY is too large.  Values up to 128 are supported.
238 +#endif
239 +
240  // the following is for checking tables
241  
242  #define HA_ADMIN_ALREADY_DONE    1
243 @@ -561,10 +565,12 @@
244  enum enum_schema_tables
245  {
246    SCH_CHARSETS= 0,
247 +  SCH_CLIENT_STATS,
248    SCH_COLLATIONS,
249    SCH_COLLATION_CHARACTER_SET_APPLICABILITY,
250    SCH_COLUMNS,
251    SCH_COLUMN_PRIVILEGES,
252 +  SCH_INDEX_STATS,
253    SCH_ENGINES,
254    SCH_EVENTS,
255    SCH_FILES,
256 @@ -592,9 +598,12 @@
257    SCH_TABLE_CONSTRAINTS,
258    SCH_TABLE_NAMES,
259    SCH_TABLE_PRIVILEGES,
260 +  SCH_TABLE_STATS,
261    SCH_TEMPORARY_TABLES,
262 +  SCH_THREAD_STATS,
263    SCH_TRIGGERS,
264    SCH_USER_PRIVILEGES,
265 +  SCH_USER_STATS,
266    SCH_VARIABLES,
267    SCH_VIEWS
268  };
269 @@ -1209,6 +1218,9 @@
270    bool locked;
271    bool implicit_emptied;                /* Can be !=0 only if HEAP */
272    const COND *pushed_cond;
273 +  ulonglong rows_read;
274 +  ulonglong rows_changed;
275 +  ulonglong index_rows_read[MAX_KEY];
276    /**
277      next_insert_id is the next value which should be inserted into the
278      auto_increment column: in a inserting-multi-row statement (like INSERT
279 @@ -1260,10 +1272,12 @@
280      ref_length(sizeof(my_off_t)),
281      ft_handler(0), inited(NONE),
282      locked(FALSE), implicit_emptied(0),
283 -    pushed_cond(0), next_insert_id(0), insert_id_for_cur_row(0),
284 +    pushed_cond(0), rows_read(0), rows_changed(0), next_insert_id(0), insert_id_for_cur_row(0),
285      auto_inc_intervals_count(0),
286      m_psi(NULL)
287 -    {}
288 +    {
289 +      memset(index_rows_read, 0, sizeof(index_rows_read));
290 +    }
291    virtual ~handler(void)
292    {
293      DBUG_ASSERT(locked == FALSE);
294 @@ -1386,6 +1400,8 @@
295    {
296      table= table_arg;
297      table_share= share;
298 +    rows_read = rows_changed= 0;
299 +    memset(index_rows_read, 0, sizeof(index_rows_read));
300    }
301    virtual double scan_time()
302    { return ulonglong2double(stats.data_file_length) / IO_SIZE + 2; }
303 @@ -1753,6 +1769,8 @@
304    virtual bool is_crashed() const  { return 0; }
305    virtual bool auto_repair() const { return 0; }
306  
307 +  void update_global_table_stats();
308 +  void update_global_index_stats();
309  
310  #define CHF_CREATE_FLAG 0
311  #define CHF_DELETE_FLAG 1
312 diff -ruN a/sql/lex.h b/sql/lex.h
313 --- a/sql/lex.h 2010-12-03 20:58:26.000000000 +0300
314 +++ b/sql/lex.h 2010-12-30 01:25:40.000000000 +0300
315 @@ -111,6 +111,7 @@
316    { "CIPHER",          SYM(CIPHER_SYM)},
317    { "CLASS_ORIGIN",     SYM(CLASS_ORIGIN_SYM)},
318    { "CLIENT",          SYM(CLIENT_SYM)},
319 +  { "CLIENT_STATISTICS",       SYM(CLIENT_STATS_SYM)},
320    { "CLOSE",           SYM(CLOSE_SYM)},
321    { "COALESCE",                SYM(COALESCE)},
322    { "CODE",             SYM(CODE_SYM)},
323 @@ -257,6 +258,7 @@
324    { "IN",              SYM(IN_SYM)},
325    { "INDEX",           SYM(INDEX_SYM)},
326    { "INDEXES",         SYM(INDEXES)},
327 +  { "INDEX_STATISTICS",        SYM(INDEX_STATS_SYM)},
328    { "INFILE",          SYM(INFILE)},
329    { "INITIAL_SIZE",    SYM(INITIAL_SIZE_SYM)},
330    { "INNER",           SYM(INNER_SYM)},
331 @@ -550,12 +552,14 @@
332    { "TABLES",          SYM(TABLES)},
333    { "TABLESPACE",              SYM(TABLESPACE)},
334    { "TABLE_CHECKSUM",  SYM(TABLE_CHECKSUM_SYM)},
335 +  { "TABLE_STATISTICS",        SYM(TABLE_STATS_SYM)},
336    { "TEMPORARY",       SYM(TEMPORARY)},
337    { "TEMPTABLE",       SYM(TEMPTABLE_SYM)},
338    { "TERMINATED",      SYM(TERMINATED)},
339    { "TEXT",            SYM(TEXT_SYM)},
340    { "THAN",             SYM(THAN_SYM)},
341    { "THEN",            SYM(THEN_SYM)},
342 +  { "THREAD_STATISTICS",       SYM(THREAD_STATS_SYM)},
343    { "TIME",            SYM(TIME_SYM)},
344    { "TIMESTAMP",       SYM(TIMESTAMP)},
345    { "TIMESTAMPADD",     SYM(TIMESTAMP_ADD)},
346 @@ -591,6 +595,7 @@
347    { "USE",             SYM(USE_SYM)},
348    { "USER",            SYM(USER)},
349    { "USER_RESOURCES",  SYM(RESOURCES)},
350 +  { "USER_STATISTICS", SYM(USER_STATS_SYM)},
351    { "USE_FRM",         SYM(USE_FRM)},
352    { "USING",           SYM(USING)},
353    { "UTC_DATE",         SYM(UTC_DATE_SYM)},
354 diff -ruN a/sql/log.cc b/sql/log.cc
355 --- a/sql/log.cc        2010-12-03 20:58:26.000000000 +0300
356 +++ b/sql/log.cc        2010-12-30 01:55:35.000000000 +0300
357 @@ -922,6 +922,13 @@
358      mysql_slow_log.reopen_file();
359  }
360  
361 +void Log_to_file_event_handler::flush_slow_log()
362 +{
363 +  /* reopen slow log file */
364 +  if (opt_slow_log)
365 +    mysql_slow_log.reopen_file();
366 +}
367 +
368  /*
369    Log error with all enabled log event handlers
370  
371 @@ -4843,6 +4850,8 @@
372                               thd->first_successful_insert_id_in_prev_stmt_for_binlog);
373            if (e.write(file))
374              goto err;
375 +          if (file == &log_file)
376 +            thd->binlog_bytes_written+= e.data_written;
377          }
378          if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0)
379          {
380 @@ -4854,12 +4863,16 @@
381                               minimum());
382            if (e.write(file))
383              goto err;
384 +          if (file == &log_file)
385 +            thd->binlog_bytes_written+= e.data_written;
386          }
387          if (thd->rand_used)
388          {
389            Rand_log_event e(thd,thd->rand_saved_seed1,thd->rand_saved_seed2);
390            if (e.write(file))
391              goto err;
392 +          if (file == &log_file)
393 +            thd->binlog_bytes_written+= e.data_written;
394          }
395          if (thd->user_var_events.elements)
396          {
397 @@ -4882,6 +4895,8 @@
398                                   flags);
399              if (e.write(file))
400                goto err;
401 +            if (file == &log_file)
402 +              thd->binlog_bytes_written+= e.data_written;
403            }
404          }
405        }
406 @@ -4893,6 +4908,8 @@
407      if (event_info->write(file) ||
408          DBUG_EVALUATE_IF("injecting_fault_writing", 1, 0))
409        goto err;
410 +    if (file == &log_file)
411 +      thd->binlog_bytes_written+= event_info->data_written;
412  
413      error= 0;
414  
415 @@ -5056,7 +5073,8 @@
416      be reset as a READ_CACHE to be able to read the contents from it.
417   */
418  
419 -int MYSQL_BIN_LOG::write_cache(IO_CACHE *cache, bool lock_log, bool sync_log)
420 +int MYSQL_BIN_LOG::write_cache(THD *thd, IO_CACHE *cache,
421 +                               bool lock_log, bool sync_log)
422  {
423    Mutex_sentry sentry(lock_log ? &LOCK_log : NULL);
424  
425 @@ -5103,6 +5121,7 @@
426        /* write the first half of the split header */
427        if (my_b_write(&log_file, header, carry))
428          return ER_ERROR_ON_WRITE;
429 +      thd->binlog_bytes_written+= carry;
430  
431        /*
432          copy fixed second half of header to cache so the correct
433 @@ -5171,6 +5190,7 @@
434      /* Write data to the binary log file */
435      if (my_b_write(&log_file, cache->read_pos, length))
436        return ER_ERROR_ON_WRITE;
437 +    thd->binlog_bytes_written+= length;
438      cache->read_pos=cache->read_end;           // Mark buffer used up
439    } while ((length= my_b_fill(cache)));
440  
441 @@ -5281,20 +5301,23 @@
442        Query_log_event qinfo(thd, STRING_WITH_LEN("BEGIN"), TRUE, FALSE, TRUE, 0);
443        if (qinfo.write(&log_file))
444          goto err;
445 +      thd->binlog_bytes_written+= qinfo.data_written;
446        DBUG_EXECUTE_IF("crash_before_writing_xid",
447                        {
448 -                        if ((write_error= write_cache(cache, false, true)))
449 +                        if ((write_error= write_cache(thd, cache, false, true)))
450                            DBUG_PRINT("info", ("error writing binlog cache: %d",
451                                                 write_error));
452                          DBUG_PRINT("info", ("crashing before writing xid"));
453                          DBUG_SUICIDE();
454                        });
455  
456 -      if ((write_error= write_cache(cache, false, false)))
457 +      if ((write_error= write_cache(thd, cache, false, false)))
458          goto err;
459  
460        if (commit_event && commit_event->write(&log_file))
461          goto err;
462 +      if (commit_event)
463 +        thd->binlog_bytes_written+= commit_event->data_written;
464  
465        if (incident && write_incident(thd, FALSE))
466          goto err;
467 diff -ruN a/sql/log.h b/sql/log.h
468 --- a/sql/log.h 2010-12-03 20:58:26.000000000 +0300
469 +++ b/sql/log.h 2010-12-30 01:56:04.000000000 +0300
470 @@ -414,7 +414,8 @@
471    bool write(THD *thd, IO_CACHE *cache, Log_event *commit_event, bool incident);
472    bool write_incident(THD *thd, bool lock);
473  
474 -  int  write_cache(IO_CACHE *cache, bool lock_log, bool flush_and_sync);
475 +  int  write_cache(THD *thd, IO_CACHE *cache,
476 +                   bool lock_log, bool flush_and_sync);
477    void set_write_error(THD *thd);
478    bool check_write_error(THD *thd);
479  
480 @@ -566,6 +567,7 @@
481                             const char *sql_text, uint sql_text_len,
482                             CHARSET_INFO *client_cs);
483    void flush();
484 +  void flush_slow_log();
485    void init_pthread_objects();
486    MYSQL_QUERY_LOG *get_mysql_slow_log() { return &mysql_slow_log; }
487    MYSQL_QUERY_LOG *get_mysql_log() { return &mysql_log; }
488 diff -ruN a/sql/mysqld.cc b/sql/mysqld.cc
489 --- a/sql/mysqld.cc     2010-12-03 20:58:26.000000000 +0300
490 +++ b/sql/mysqld.cc     2010-12-30 02:04:50.000000000 +0300
491 @@ -438,6 +438,7 @@
492  uint    opt_debug_sync_timeout= 0;
493  #endif /* defined(ENABLED_DEBUG_SYNC) */
494  my_bool opt_old_style_user_limits= 0, trust_function_creators= 0;
495 +my_bool opt_userstat_running= 0, opt_thread_statistics= 0;
496  my_bool opt_optimizer_fix= 0;
497  /*
498    True if there is at least one per-hour limit for some user, so we should
499 @@ -486,6 +487,7 @@
500  ulong specialflag=0;
501  ulong binlog_cache_use= 0, binlog_cache_disk_use= 0;
502  ulong max_connections, max_connect_errors;
503 +ulonglong denied_connections= 0;
504  
505  /* flashcache */
506  int cachedev_fd;
507 @@ -630,7 +632,9 @@
508    LOCK_crypt,
509    LOCK_global_system_variables,
510    LOCK_user_conn, LOCK_slave_list, LOCK_active_mi,
511 -  LOCK_connection_count, LOCK_error_messages;
512 +  LOCK_connection_count, LOCK_error_messages,
513 +  LOCK_stats, LOCK_global_user_client_stats,
514 +  LOCK_global_table_stats, LOCK_global_index_stats;
515  /**
516    The below lock protects access to two global server variables:
517    max_prepared_stmt_count and prepared_stmt_count. These variables
518 @@ -1490,6 +1494,11 @@
519  #ifdef HAVE_RESPONSE_TIME_DISTRIBUTION
520    query_response_time_free();
521  #endif // HAVE_RESPONSE_TIME_DISTRIBUTION
522 +  free_global_user_stats();
523 +  free_global_client_stats();
524 +  free_global_thread_stats();
525 +  free_global_table_stats();
526 +  free_global_index_stats();
527  #ifdef HAVE_REPLICATION
528    end_slave_list();
529  #endif
530 @@ -1593,6 +1602,10 @@
531    mysql_cond_destroy(&COND_thread_cache);
532    mysql_cond_destroy(&COND_flush_thread_cache);
533    mysql_cond_destroy(&COND_manager);
534 +  mysql_mutex_destroy(&LOCK_stats);
535 +  mysql_mutex_destroy(&LOCK_global_user_client_stats);
536 +  mysql_mutex_destroy(&LOCK_global_table_stats);
537 +  mysql_mutex_destroy(&LOCK_global_index_stats);
538  }
539  #endif /*EMBEDDED_LIBRARY*/
540  
541 @@ -3024,6 +3037,7 @@
542    {"show_binlog_events",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_BINLOG_EVENTS]), SHOW_LONG_STATUS},
543    {"show_binlogs",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_BINLOGS]), SHOW_LONG_STATUS},
544    {"show_charsets",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CHARSETS]), SHOW_LONG_STATUS},
545 +  {"show_client_statistics",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CLIENT_STATS]), SHOW_LONG_STATUS},
546    {"show_collations",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_COLLATIONS]), SHOW_LONG_STATUS},
547    {"show_contributors",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CONTRIBUTORS]), SHOW_LONG_STATUS},
548    {"show_create_db",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_DB]), SHOW_LONG_STATUS},
549 @@ -3044,6 +3058,7 @@
550  #endif
551    {"show_function_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS_FUNC]), SHOW_LONG_STATUS},
552    {"show_grants",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_GRANTS]), SHOW_LONG_STATUS},
553 +  {"show_index_statistics",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_INDEX_STATS]), SHOW_LONG_STATUS},
554    {"show_keys",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_KEYS]), SHOW_LONG_STATUS},
555    {"show_master_status",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_MASTER_STAT]), SHOW_LONG_STATUS},
556    {"show_new_master",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_NEW_MASTER]), SHOW_LONG_STATUS},
557 @@ -3063,10 +3078,13 @@
558    {"show_slave_status_nolock", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_SLAVE_NOLOCK_STAT]), SHOW_LONG_STATUS},
559    {"show_status",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS]), SHOW_LONG_STATUS},
560    {"show_storage_engines", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STORAGE_ENGINES]), SHOW_LONG_STATUS},
561 +  {"show_table_statistics",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLE_STATS]), SHOW_LONG_STATUS},
562    {"show_table_status",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLE_STATUS]), SHOW_LONG_STATUS},
563    {"show_tables",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLES]), SHOW_LONG_STATUS},
564    {"show_temporary_tables",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TEMPORARY_TABLES]), SHOW_LONG_STATUS},
565 +  {"show_thread_statistics",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_THREAD_STATS]), SHOW_LONG_STATUS},
566    {"show_triggers",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TRIGGERS]), SHOW_LONG_STATUS},
567 +  {"show_user_statistics", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_USER_STATS]), SHOW_LONG_STATUS},
568    {"show_variables",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_VARIABLES]), SHOW_LONG_STATUS},
569    {"show_warnings",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_WARNS]), SHOW_LONG_STATUS},
570    {"slave_start",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SLAVE_START]), SHOW_LONG_STATUS},
571 @@ -3587,6 +3605,13 @@
572    mysql_mutex_init(key_LOCK_server_started,
573                     &LOCK_server_started, MY_MUTEX_INIT_FAST);
574    mysql_cond_init(key_COND_server_started, &COND_server_started, NULL);
575 +  mysql_mutex_init(key_LOCK_stats, &LOCK_stats, MY_MUTEX_INIT_FAST);
576 +  mysql_mutex_init(key_LOCK_global_user_client_stats,
577 +    &LOCK_global_user_client_stats, MY_MUTEX_INIT_FAST);
578 +  mysql_mutex_init(key_LOCK_global_table_stats,
579 +    &LOCK_global_table_stats, MY_MUTEX_INIT_FAST);
580 +  mysql_mutex_init(key_LOCK_global_index_stats,
581 +    &LOCK_global_index_stats, MY_MUTEX_INIT_FAST);
582    sp_cache_init();
583  #ifdef HAVE_EVENT_SCHEDULER
584    Events::init_mutexes();
585 @@ -3956,6 +3981,9 @@
586    query_response_time_init();
587  #endif // HAVE_RESPONSE_TIME_DISTRIBUTION
588    /* We have to initialize the storage engines before CSV logging */
589 +  init_global_table_stats();
590 +  init_global_index_stats();
591 +
592    if (ha_init())
593    {
594      sql_print_error("Can't init databases");
595 @@ -4092,6 +4120,9 @@
596  
597    init_max_user_conn();
598    init_update_queries();
599 +  init_global_user_stats();
600 +  init_global_client_stats();
601 +  init_global_thread_stats();
602    DBUG_RETURN(0);
603  }
604  
605 @@ -5123,6 +5154,7 @@
606      {
607        sql_print_warning("%s", ER_DEFAULT(ER_CON_COUNT_ERROR));
608      }
609 +    statistic_increment(denied_connections, &LOCK_status);
610      delete thd;
611      DBUG_VOID_RETURN;
612    }
613 @@ -7820,6 +7852,8 @@
614    key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi,
615    key_LOCK_connection_count, key_LOCK_crypt, key_LOCK_delayed_create,
616    key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log,
617 +  key_LOCK_stats, key_LOCK_global_user_client_stats,
618 +  key_LOCK_global_table_stats, key_LOCK_global_index_stats,
619    key_LOCK_gdl, key_LOCK_global_system_variables,
620    key_LOCK_manager,
621    key_LOCK_prepared_stmt_count,
622 @@ -7857,6 +7891,13 @@
623    { &key_LOCK_delayed_insert, "LOCK_delayed_insert", PSI_FLAG_GLOBAL},
624    { &key_LOCK_delayed_status, "LOCK_delayed_status", PSI_FLAG_GLOBAL},
625    { &key_LOCK_error_log, "LOCK_error_log", PSI_FLAG_GLOBAL},
626 +  { &key_LOCK_stats, "LOCK_stats", PSI_FLAG_GLOBAL},
627 +  { &key_LOCK_global_user_client_stats,
628 +    "LOCK_global_user_client_stats", PSI_FLAG_GLOBAL},
629 +  { &key_LOCK_global_table_stats,
630 +     "LOCK_global_table_stats", PSI_FLAG_GLOBAL},
631 +  { &key_LOCK_global_index_stats,
632 +    "LOCK_global_index_stats", PSI_FLAG_GLOBAL},
633    { &key_LOCK_gdl, "LOCK_gdl", PSI_FLAG_GLOBAL},
634    { &key_LOCK_global_system_variables, "LOCK_global_system_variables", PSI_FLAG_GLOBAL},
635    { &key_LOCK_manager, "LOCK_manager", PSI_FLAG_GLOBAL},
636 diff -ruN a/sql/mysqld.h b/sql/mysqld.h
637 --- a/sql/mysqld.h      2010-12-03 20:58:26.000000000 +0300
638 +++ b/sql/mysqld.h      2010-12-31 06:04:59.000000000 +0300
639 @@ -23,6 +23,7 @@
640  #include "my_atomic.h"                     /* my_atomic_rwlock_t */
641  #include "mysql/psi/mysql_file.h"          /* MYSQL_FILE */
642  #include "sql_list.h"                      /* I_List */
643 +#include "hash.h"
644  
645  class THD;
646  struct handlerton;
647 @@ -114,6 +115,7 @@
648  extern ulonglong slave_type_conversions_options;
649  extern my_bool read_only, opt_readonly;
650  extern my_bool lower_case_file_system;
651 +extern my_bool opt_userstat_running, opt_thread_statistics;
652  extern my_bool opt_optimizer_fix;
653  extern my_bool opt_enable_named_pipe, opt_sync_frm, opt_allow_suspicious_udfs;
654  extern my_bool opt_secure_auth;
655 @@ -180,6 +182,7 @@
656  extern ulong slave_trans_retries;
657  extern uint  slave_net_timeout;
658  extern uint max_user_connections;
659 +extern ulonglong denied_connections;
660  extern ulong what_to_log,flush_time;
661  extern ulong max_prepared_stmt_count, prepared_stmt_count;
662  extern ulong binlog_cache_size, open_files_limit;
663 @@ -205,6 +208,11 @@
664  extern struct system_variables max_system_variables;
665  extern struct system_status_var global_status_var;
666  extern struct rand_struct sql_rand;
667 +extern HASH global_user_stats;
668 +extern HASH global_client_stats;
669 +extern HASH global_thread_stats;
670 +extern HASH global_table_stats;
671 +extern HASH global_index_stats;
672  extern const char *opt_date_time_formats[];
673  extern handlerton *partition_hton;
674  extern handlerton *myisam_hton;
675 @@ -242,6 +250,8 @@
676    key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi,
677    key_LOCK_connection_count, key_LOCK_crypt, key_LOCK_delayed_create,
678    key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log,
679 +  key_LOCK_stats, key_LOCK_global_user_client_stats,
680 +  key_LOCK_global_table_stats, key_LOCK_global_index_stats,
681    key_LOCK_gdl, key_LOCK_global_system_variables,
682    key_LOCK_logger, key_LOCK_manager,
683    key_LOCK_prepared_stmt_count,
684 @@ -338,7 +348,9 @@
685         LOCK_delayed_status, LOCK_delayed_create, LOCK_crypt, LOCK_timezone,
686         LOCK_slave_list, LOCK_active_mi, LOCK_manager,
687         LOCK_global_system_variables, LOCK_user_conn,
688 -       LOCK_prepared_stmt_count, LOCK_error_messages, LOCK_connection_count;
689 +       LOCK_prepared_stmt_count, LOCK_error_messages, LOCK_connection_count,
690 +       LOCK_stats, LOCK_global_user_client_stats,
691 +       LOCK_global_table_stats, LOCK_global_index_stats;
692  extern MYSQL_PLUGIN_IMPORT mysql_mutex_t LOCK_thread_count;
693  #ifdef HAVE_OPENSSL
694  extern mysql_mutex_t LOCK_des_key_file;
695 @@ -450,6 +462,16 @@
696    return id;
697  }
698  
699 +void init_global_user_stats(void);
700 +void init_global_table_stats(void);
701 +void init_global_index_stats(void);
702 +void init_global_client_stats(void);
703 +void init_global_thread_stats(void);
704 +void free_global_user_stats(void);
705 +void free_global_table_stats(void);
706 +void free_global_index_stats(void);
707 +void free_global_client_stats(void);
708 +void free_global_thread_stats(void);
709  
710  /*
711    TODO: Replace this with an inline function.
712 diff -ruN a/sql/sql_base.cc b/sql/sql_base.cc
713 --- a/sql/sql_base.cc   2010-12-03 20:58:26.000000000 +0300
714 +++ b/sql/sql_base.cc   2010-12-30 02:33:17.000000000 +0300
715 @@ -1524,6 +1524,11 @@
716    table->mdl_ticket= NULL;
717  
718    mysql_mutex_lock(&thd->LOCK_thd_data);
719 +  if(table->file)
720 +  {
721 +    table->file->update_global_table_stats();
722 +    table->file->update_global_index_stats();
723 +  }
724    *table_ptr=table->next;
725    mysql_mutex_unlock(&thd->LOCK_thd_data);
726  
727 @@ -2149,6 +2154,8 @@
728    DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
729                            table->s->db.str, table->s->table_name.str));
730  
731 +  table->file->update_global_table_stats();
732 +  table->file->update_global_index_stats();
733    free_io_cache(table);
734    closefrm(table, 0);
735    if (delete_table)
736 diff -ruN a/sql/sql_class.cc b/sql/sql_class.cc
737 --- a/sql/sql_class.cc  2010-12-03 20:58:26.000000000 +0300
738 +++ b/sql/sql_class.cc  2010-12-30 02:41:40.000000000 +0300
739 @@ -601,6 +601,13 @@
740    mysys_var=0;
741    binlog_evt_union.do_union= FALSE;
742    enable_slow_log= 0;
743 +  busy_time=            0;
744 +  cpu_time=             0;
745 +  bytes_received=       0;
746 +  bytes_sent=           0;
747 +  binlog_bytes_written= 0;
748 +  updated_row_count=    0;
749 +  sent_row_count_2=     0;
750  #ifndef DBUG_OFF
751    dbug_sentry=THD_SENTRY_MAGIC;
752  #endif
753 @@ -981,6 +988,7 @@
754      variables.option_bits|= OPTION_BIN_LOG;
755    else
756      variables.option_bits&= ~OPTION_BIN_LOG;
757 +  reset_stats();
758  
759  #if defined(ENABLED_DEBUG_SYNC)
760    /* Initialize the Debug Sync Facility. See debug_sync.cc. */
761 @@ -988,6 +996,94 @@
762  #endif /* defined(ENABLED_DEBUG_SYNC) */
763  }
764  
765 +// Resets stats in a THD.
766 +void THD::reset_stats(void)
767 +{
768 +  current_connect_time=    time(NULL);
769 +  last_global_update_time= current_connect_time;
770 +  reset_diff_stats();
771 +}
772 +
773 +// Resets the 'diff' stats, which are used to update global stats.
774 +void THD::reset_diff_stats(void)
775 +{
776 +  diff_total_busy_time=            0;
777 +  diff_total_cpu_time=             0;
778 +  diff_total_bytes_received=       0;
779 +  diff_total_bytes_sent=           0;
780 +  diff_total_binlog_bytes_written= 0;
781 +  diff_total_sent_rows=            0;
782 +  diff_total_updated_rows=         0;
783 +  diff_total_read_rows=            0;
784 +  diff_select_commands=            0;
785 +  diff_update_commands=            0;
786 +  diff_other_commands=             0;
787 +  diff_commit_trans=               0;
788 +  diff_rollback_trans=             0;
789 +  diff_denied_connections=         0;
790 +  diff_lost_connections=           0;
791 +  diff_access_denied_errors=       0;
792 +  diff_empty_queries=              0;
793 +}
794 +
795 +// Updates 'diff' stats of a THD.
796 +void THD::update_stats(bool ran_command)
797 +{
798 +  if (opt_userstat_running)
799 +  {
800 +  diff_total_busy_time+=            busy_time;
801 +  diff_total_cpu_time+=             cpu_time;
802 +  diff_total_bytes_received+=       bytes_received;
803 +  diff_total_bytes_sent+=           bytes_sent;
804 +  diff_total_binlog_bytes_written+= binlog_bytes_written;
805 +  diff_total_sent_rows+=            sent_row_count_2;
806 +  diff_total_updated_rows+=         updated_row_count;
807 +  // diff_total_read_rows is updated in handler.cc.
808 +
809 +  if (ran_command)
810 +  {
811 +    // The replication thread has the COM_CONNECT command.
812 +    if ((old_command == COM_QUERY || command == COM_CONNECT) &&
813 +        (lex->sql_command >= 0 && lex->sql_command < SQLCOM_END))
814 +    {
815 +      // A SQL query.
816 +      if (lex->sql_command == SQLCOM_SELECT)
817 +      {
818 +        diff_select_commands++;
819 +        if (!sent_row_count_2)
820 +          diff_empty_queries++;
821 +      }
822 +      else if (!sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND)
823 +      {
824 +        // 'SHOW ' commands become SQLCOM_SELECT.
825 +        diff_other_commands++;
826 +        // 'SHOW ' commands shouldn't inflate total sent row count.
827 +        diff_total_sent_rows-= sent_row_count_2;
828 +      } else if (is_update_query(lex->sql_command)) {
829 +        diff_update_commands++;
830 +      } else {
831 +        diff_other_commands++;
832 +      }
833 +    }
834 +  }
835 +  // diff_commit_trans is updated in handler.cc.
836 +  // diff_rollback_trans is updated in handler.cc.
837 +  // diff_denied_connections is updated in sql_parse.cc.
838 +  // diff_lost_connections is updated in sql_parse.cc.
839 +  // diff_access_denied_errors is updated in sql_parse.cc.
840 +
841 +  /* reset counters to zero to avoid double-counting since values
842 +     are already store in diff_total_*.
843 +  */
844 +  }
845 +  busy_time=            0;
846 +  cpu_time=             0;
847 +  bytes_received=       0;
848 +  bytes_sent=           0;
849 +  binlog_bytes_written= 0;
850 +  updated_row_count=    0;
851 +  sent_row_count_2=     0;
852 +}
853  
854  /*
855    Init THD for query processing.
856 @@ -1688,6 +1784,32 @@
857  }
858  #endif
859  
860 +char *THD::get_client_host_port(THD *client)
861 +{
862 +  Security_context *client_sctx= client->security_ctx;
863 +  char *client_host= NULL;
864 +
865 +  if (client->peer_port && (client_sctx->host || client_sctx->ip) &&
866 +      security_ctx->host_or_ip[0])
867 +  {
868 +    if ((client_host= (char *) this->alloc(LIST_PROCESS_HOST_LEN+1)))
869 +      my_snprintf((char *) client_host, LIST_PROCESS_HOST_LEN,
870 +                  "%s:%u", client_sctx->host_or_ip, client->peer_port);
871 +  }
872 +  else
873 +    client_host= this->strdup(client_sctx->host_or_ip[0] ?
874 +                              client_sctx->host_or_ip :
875 +                              client_sctx->host ? client_sctx->host : "");
876 +
877 +  return client_host;
878 +}
879 +
880 +const char *get_client_host(THD *client)
881 +{
882 +  return client->security_ctx->host_or_ip[0] ?
883 +      client->security_ctx->host_or_ip :
884 +      client->security_ctx->host ? client->security_ctx->host : "";
885 +}
886  
887  struct Item_change_record: public ilink
888  {
889 @@ -1864,6 +1986,7 @@
890    }
891  
892    thd->sent_row_count++;
893 +  thd->sent_row_count_2++;
894  
895    if (thd->vio_ok())
896      DBUG_RETURN(protocol->write());
897 @@ -1956,6 +2079,7 @@
898  select_export::~select_export()
899  {
900    thd->sent_row_count=row_count;
901 +  thd->sent_row_count_2= row_count;
902  }
903  
904  
905 @@ -2979,6 +3103,7 @@
906    if (likely(thd != 0))
907    { /* current_thd==0 when close_connection() calls net_send_error() */
908      thd->status_var.bytes_sent+= length;
909 +    thd->bytes_sent+= length;
910    }
911  }
912  
913 @@ -2986,6 +3111,7 @@
914  void thd_increment_bytes_received(ulong length)
915  {
916    current_thd->status_var.bytes_received+= length;
917 +  current_thd->bytes_received+= length;
918  }
919  
920  
921 diff -ruN a/sql/sql_class.h b/sql/sql_class.h
922 --- a/sql/sql_class.h   2010-12-03 20:58:26.000000000 +0300
923 +++ b/sql/sql_class.h   2010-12-31 05:15:57.000000000 +0300
924 @@ -1610,6 +1610,8 @@
925    */
926    enum enum_server_command command;
927    uint32     server_id;
928 +  // Used to save the command, before it is set to COM_SLEEP.
929 +  enum enum_server_command old_command;
930    uint32     file_id;                  // for LOAD DATA INFILE
931    /* remote (peer) port */
932    uint16 peer_port;
933 @@ -2081,6 +2083,8 @@
934    */
935    enum_tx_isolation tx_isolation;
936    enum_check_fields count_cuted_fields;
937 +  ha_rows    updated_row_count;
938 +  ha_rows    sent_row_count_2; /* for userstat */
939  
940    DYNAMIC_ARRAY user_var_events;        /* For user variables replication */
941    MEM_ROOT      *user_var_events_alloc; /* Allocate above array elements here */
942 @@ -2176,6 +2180,49 @@
943    */
944    LOG_INFO*  current_linfo;
945    NET*       slave_net;                        // network connection from slave -> m.
946 +
947 +  /*
948 +    Used to update global user stats.  The global user stats are updated
949 +    occasionally with the 'diff' variables.  After the update, the 'diff'
950 +    variables are reset to 0.
951 +  */
952 +  // Time when the current thread connected to MySQL.
953 +  time_t current_connect_time;
954 +  // Last time when THD stats were updated in global_user_stats.
955 +  time_t last_global_update_time;
956 +  // Busy (non-idle) time for just one command.
957 +  double busy_time;
958 +  // Busy time not updated in global_user_stats yet.
959 +  double diff_total_busy_time;
960 +  // Cpu (non-idle) time for just one thread.
961 +  double cpu_time;
962 +  // Cpu time not updated in global_user_stats yet.
963 +  double diff_total_cpu_time;
964 +  /* bytes counting */
965 +  ulonglong bytes_received;
966 +  ulonglong diff_total_bytes_received;
967 +  ulonglong bytes_sent;
968 +  ulonglong diff_total_bytes_sent;
969 +  ulonglong binlog_bytes_written;
970 +  ulonglong diff_total_binlog_bytes_written;
971 +
972 +  // Number of rows not reflected in global_user_stats yet.
973 +  ha_rows diff_total_sent_rows, diff_total_updated_rows, diff_total_read_rows;
974 +  // Number of commands not reflected in global_user_stats yet.
975 +  ulonglong diff_select_commands, diff_update_commands, diff_other_commands;
976 +  // Number of transactions not reflected in global_user_stats yet.
977 +  ulonglong diff_commit_trans, diff_rollback_trans;
978 +  // Number of connection errors not reflected in global_user_stats yet.
979 +  ulonglong diff_denied_connections, diff_lost_connections;
980 +  // Number of db access denied, not reflected in global_user_stats yet.
981 +  ulonglong diff_access_denied_errors;
982 +  // Number of queries that return 0 rows
983 +  ulonglong diff_empty_queries;
984 +
985 +  // Per account query delay in miliseconds. When not 0, sleep this number of
986 +  // milliseconds before every SQL command.
987 +  ulonglong query_delay_millis;
988 +
989    /* Used by the sys_var class to store temporary values */
990    union
991    {
992 @@ -2256,6 +2303,11 @@
993      alloc_root. 
994    */
995    void init_for_queries();
996 +  void reset_stats(void);
997 +  void reset_diff_stats(void);
998 +  // ran_command is true when this is called immediately after a
999 +  // command has been run.
1000 +  void update_stats(bool ran_command);
1001    void change_user(void);
1002    void cleanup(void);
1003    void cleanup_after_query();
1004 @@ -2726,6 +2778,15 @@
1005    }
1006    thd_scheduler scheduler;
1007  
1008 +  /* Returns string as 'IP:port' for the client-side
1009 +     of the connnection represented
1010 +     by 'client' as displayed by SHOW PROCESSLIST.
1011 +     Allocates memory from the heap of
1012 +     this THD and that is not reclaimed
1013 +     immediately, so use sparingly. May return NULL.
1014 +  */
1015 +  char *get_client_host_port(THD *client);
1016 +
1017  public:
1018    inline Internal_error_handler *get_internal_handler()
1019    { return m_internal_handler; }
1020 @@ -2913,6 +2974,10 @@
1021    LEX_STRING invoker_host;
1022  };
1023  
1024 +/* Returns string as 'IP' for the client-side of the connection represented by
1025 +   'client'. Does not allocate memory. May return "".
1026 +*/
1027 +const char *get_client_host(THD *client);
1028  
1029  /** A short cut for thd->stmt_da->set_ok_status(). */
1030  
1031 diff -ruN a/sql/sql_connect.cc b/sql/sql_connect.cc
1032 --- a/sql/sql_connect.cc        2010-12-03 20:58:26.000000000 +0300
1033 +++ b/sql/sql_connect.cc        2010-12-31 03:53:28.000000000 +0300
1034 @@ -55,6 +55,24 @@
1035  #define MIN_HANDSHAKE_SIZE      6
1036  #endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
1037  
1038 +// Increments connection count for user.
1039 +static int increment_connection_count(THD* thd, bool use_lock);
1040 +
1041 +// Uses the THD to update the global stats by user name and client IP
1042 +void update_global_user_stats(THD* thd, bool create_user, time_t now);
1043 +
1044 +HASH global_user_stats;
1045 +HASH global_client_stats;
1046 +HASH global_thread_stats;
1047 +// Protects global_user_stats and global_client_stats
1048 +extern mysql_mutex_t LOCK_global_user_client_stats;
1049 +
1050 +HASH global_table_stats;
1051 +extern mysql_mutex_t LOCK_global_table_stats;
1052 +
1053 +HASH global_index_stats;
1054 +extern mysql_mutex_t LOCK_global_index_stats;
1055 +
1056  /*
1057    Get structure for logging connection data for the current user
1058  */
1059 @@ -112,6 +130,586 @@
1060  
1061  }
1062  
1063 +extern "C" uchar *get_key_user_stats(USER_STATS *user_stats, size_t *length,
1064 +                         my_bool not_used __attribute__((unused)))
1065 +{
1066 +  *length= strlen(user_stats->user);
1067 +  return (uchar*) user_stats->user;
1068 +}
1069 +
1070 +extern "C" uchar *get_key_thread_stats(THREAD_STATS *thread_stats, size_t *length,
1071 +                         my_bool not_used __attribute__((unused)))
1072 +{
1073 +  *length= sizeof(my_thread_id);
1074 +  return (uchar *) &(thread_stats->id);
1075 +}
1076 +
1077 +void free_user_stats(USER_STATS* user_stats)
1078 +{
1079 +  my_free((char *) user_stats);
1080 +}
1081 +
1082 +void free_thread_stats(THREAD_STATS* thread_stats)
1083 +{
1084 +  my_free((char *) thread_stats);
1085 +}
1086 +
1087 +void init_user_stats(USER_STATS *user_stats,
1088 +                     const char *user,
1089 +                     const char *priv_user,
1090 +                     uint total_connections,
1091 +                     uint concurrent_connections,
1092 +                     time_t connected_time,
1093 +                     double busy_time,
1094 +                     double cpu_time,
1095 +                     ulonglong bytes_received,
1096 +                     ulonglong bytes_sent,
1097 +                     ulonglong binlog_bytes_written,
1098 +                     ha_rows rows_fetched,
1099 +                     ha_rows rows_updated,
1100 +                     ha_rows rows_read,
1101 +                     ulonglong select_commands,
1102 +                     ulonglong update_commands,
1103 +                     ulonglong other_commands,
1104 +                     ulonglong commit_trans,
1105 +                     ulonglong rollback_trans,
1106 +                     ulonglong denied_connections,
1107 +                     ulonglong lost_connections,
1108 +                     ulonglong access_denied_errors,
1109 +                     ulonglong empty_queries)
1110 +{
1111 +  DBUG_ENTER("init_user_stats");
1112 +  DBUG_PRINT("info",
1113 +             ("Add user_stats entry for user %s - priv_user %s",
1114 +              user, priv_user));
1115 +  strncpy(user_stats->user, user, sizeof(user_stats->user));
1116 +  strncpy(user_stats->priv_user, priv_user, sizeof(user_stats->priv_user));
1117 +
1118 +  user_stats->total_connections=      total_connections;
1119 +  user_stats->concurrent_connections= concurrent_connections;
1120 +  user_stats->connected_time=         connected_time;
1121 +  user_stats->busy_time=              busy_time;
1122 +  user_stats->cpu_time=               cpu_time;
1123 +  user_stats->bytes_received=         bytes_received;
1124 +  user_stats->bytes_sent=             bytes_sent;
1125 +  user_stats->binlog_bytes_written=   binlog_bytes_written;
1126 +  user_stats->rows_fetched=           rows_fetched;
1127 +  user_stats->rows_updated=           rows_updated;
1128 +  user_stats->rows_read=              rows_read;
1129 +  user_stats->select_commands=        select_commands;
1130 +  user_stats->update_commands=        update_commands;
1131 +  user_stats->other_commands=         other_commands;
1132 +  user_stats->commit_trans=           commit_trans;
1133 +  user_stats->rollback_trans=         rollback_trans;
1134 +  user_stats->denied_connections=     denied_connections;
1135 +  user_stats->lost_connections=       lost_connections;
1136 +  user_stats->access_denied_errors=   access_denied_errors;
1137 +  user_stats->empty_queries=          empty_queries;
1138 +  DBUG_VOID_RETURN;
1139 +}
1140 +
1141 +void init_thread_stats(THREAD_STATS *thread_stats,
1142 +                     my_thread_id id,
1143 +                     uint total_connections,
1144 +                     uint concurrent_connections,
1145 +                     time_t connected_time,
1146 +                     double busy_time,
1147 +                     double cpu_time,
1148 +                     ulonglong bytes_received,
1149 +                     ulonglong bytes_sent,
1150 +                     ulonglong binlog_bytes_written,
1151 +                     ha_rows rows_fetched,
1152 +                     ha_rows rows_updated,
1153 +                     ha_rows rows_read,
1154 +                     ulonglong select_commands,
1155 +                     ulonglong update_commands,
1156 +                     ulonglong other_commands,
1157 +                     ulonglong commit_trans,
1158 +                     ulonglong rollback_trans,
1159 +                     ulonglong denied_connections,
1160 +                     ulonglong lost_connections,
1161 +                     ulonglong access_denied_errors,
1162 +                     ulonglong empty_queries)
1163 +{
1164 +  DBUG_ENTER("init_thread_stats");
1165 +  DBUG_PRINT("info",
1166 +             ("Add thread_stats entry for thread %lu",
1167 +              id));
1168 +  thread_stats->id= id;
1169 +
1170 +  thread_stats->total_connections=      total_connections;
1171 +  thread_stats->concurrent_connections= concurrent_connections;
1172 +  thread_stats->connected_time=         connected_time;
1173 +  thread_stats->busy_time=              busy_time;
1174 +  thread_stats->cpu_time=               cpu_time;
1175 +  thread_stats->bytes_received=         bytes_received;
1176 +  thread_stats->bytes_sent=             bytes_sent;
1177 +  thread_stats->binlog_bytes_written=   binlog_bytes_written;
1178 +  thread_stats->rows_fetched=           rows_fetched;
1179 +  thread_stats->rows_updated=           rows_updated;
1180 +  thread_stats->rows_read=              rows_read;
1181 +  thread_stats->select_commands=        select_commands;
1182 +  thread_stats->update_commands=        update_commands;
1183 +  thread_stats->other_commands=         other_commands;
1184 +  thread_stats->commit_trans=           commit_trans;
1185 +  thread_stats->rollback_trans=         rollback_trans;
1186 +  thread_stats->denied_connections=     denied_connections;
1187 +  thread_stats->lost_connections=       lost_connections;
1188 +  thread_stats->access_denied_errors=   access_denied_errors;
1189 +  thread_stats->empty_queries=          empty_queries;
1190 +  DBUG_VOID_RETURN;
1191 +}
1192 +
1193 +void add_user_stats(USER_STATS *user_stats,
1194 +                    uint total_connections,
1195 +                    uint concurrent_connections,
1196 +                    time_t connected_time,
1197 +                    double busy_time,
1198 +                    double cpu_time,
1199 +                    ulonglong bytes_received,
1200 +                    ulonglong bytes_sent,
1201 +                    ulonglong binlog_bytes_written,
1202 +                    ha_rows rows_fetched,
1203 +                    ha_rows rows_updated,
1204 +                    ha_rows rows_read,
1205 +                    ulonglong select_commands,
1206 +                    ulonglong update_commands,
1207 +                    ulonglong other_commands,
1208 +                    ulonglong commit_trans,
1209 +                    ulonglong rollback_trans,
1210 +                    ulonglong denied_connections,
1211 +                    ulonglong lost_connections,
1212 +                    ulonglong access_denied_errors,
1213 +                    ulonglong empty_queries)
1214 +{
1215 +  user_stats->total_connections+=      total_connections;
1216 +  user_stats->concurrent_connections+= concurrent_connections;
1217 +  user_stats->connected_time+=         connected_time;
1218 +  user_stats->busy_time+=              busy_time;
1219 +  user_stats->cpu_time+=               cpu_time;
1220 +  user_stats->bytes_received+=         bytes_received;
1221 +  user_stats->bytes_sent+=             bytes_sent;
1222 +  user_stats->binlog_bytes_written+=   binlog_bytes_written;
1223 +  user_stats->rows_fetched+=           rows_fetched;
1224 +  user_stats->rows_updated+=           rows_updated;
1225 +  user_stats->rows_read+=              rows_read;
1226 +  user_stats->select_commands+=        select_commands;
1227 +  user_stats->update_commands+=        update_commands;
1228 +  user_stats->other_commands+=         other_commands;
1229 +  user_stats->commit_trans+=           commit_trans;
1230 +  user_stats->rollback_trans+=         rollback_trans;
1231 +  user_stats->denied_connections+=     denied_connections;
1232 +  user_stats->lost_connections+=       lost_connections;
1233 +  user_stats->access_denied_errors+=   access_denied_errors;
1234 +  user_stats->empty_queries+=          empty_queries;
1235 +}
1236 +
1237 +void add_thread_stats(THREAD_STATS *thread_stats,
1238 +                    uint total_connections,
1239 +                    uint concurrent_connections,
1240 +                    time_t connected_time,
1241 +                    double busy_time,
1242 +                    double cpu_time,
1243 +                    ulonglong bytes_received,
1244 +                    ulonglong bytes_sent,
1245 +                    ulonglong binlog_bytes_written,
1246 +                    ha_rows rows_fetched,
1247 +                    ha_rows rows_updated,
1248 +                    ha_rows rows_read,
1249 +                    ulonglong select_commands,
1250 +                    ulonglong update_commands,
1251 +                    ulonglong other_commands,
1252 +                    ulonglong commit_trans,
1253 +                    ulonglong rollback_trans,
1254 +                    ulonglong denied_connections,
1255 +                    ulonglong lost_connections,
1256 +                    ulonglong access_denied_errors,
1257 +                    ulonglong empty_queries)
1258 +{
1259 +  thread_stats->total_connections+=      total_connections;
1260 +  thread_stats->concurrent_connections+= concurrent_connections;
1261 +  thread_stats->connected_time+=         connected_time;
1262 +  thread_stats->busy_time+=              busy_time;
1263 +  thread_stats->cpu_time+=               cpu_time;
1264 +  thread_stats->bytes_received+=         bytes_received;
1265 +  thread_stats->bytes_sent+=             bytes_sent;
1266 +  thread_stats->binlog_bytes_written+=   binlog_bytes_written;
1267 +  thread_stats->rows_fetched+=           rows_fetched;
1268 +  thread_stats->rows_updated+=           rows_updated;
1269 +  thread_stats->rows_read+=              rows_read;
1270 +  thread_stats->select_commands+=        select_commands;
1271 +  thread_stats->update_commands+=        update_commands;
1272 +  thread_stats->other_commands+=         other_commands;
1273 +  thread_stats->commit_trans+=           commit_trans;
1274 +  thread_stats->rollback_trans+=         rollback_trans;
1275 +  thread_stats->denied_connections+=     denied_connections;
1276 +  thread_stats->lost_connections+=       lost_connections;
1277 +  thread_stats->access_denied_errors+=   access_denied_errors;
1278 +  thread_stats->empty_queries+=          empty_queries;
1279 +}
1280 +
1281 +void init_global_user_stats(void)
1282 +{
1283 +  if (my_hash_init(&global_user_stats, system_charset_info, max_connections,
1284 +                0, 0, (my_hash_get_key)get_key_user_stats,
1285 +                (my_hash_free_key)free_user_stats, 0)) {
1286 +    sql_print_error("Initializing global_user_stats failed.");
1287 +    exit(1);
1288 +  }
1289 +}
1290 +
1291 +void init_global_client_stats(void)
1292 +{
1293 +  if (my_hash_init(&global_client_stats, system_charset_info, max_connections,
1294 +                0, 0, (my_hash_get_key)get_key_user_stats,
1295 +                (my_hash_free_key)free_user_stats, 0)) {
1296 +    sql_print_error("Initializing global_client_stats failed.");
1297 +    exit(1);
1298 +  }
1299 +}
1300 +
1301 +void init_global_thread_stats(void)
1302 +{
1303 +  if (my_hash_init(&global_thread_stats, &my_charset_bin, max_connections,
1304 +                0, 0, (my_hash_get_key) get_key_thread_stats,
1305 +                (my_hash_free_key) free_thread_stats, 0))
1306 +  {
1307 +    sql_print_error("Initializing global_client_stats failed.");
1308 +    exit(1);
1309 +  }
1310 +}
1311 +
1312 +extern "C" uchar *get_key_table_stats(TABLE_STATS *table_stats, size_t *length,
1313 +                                     my_bool not_used __attribute__((unused)))
1314 +{
1315 +  *length= strlen(table_stats->table);
1316 +  return (uchar*) table_stats->table;
1317 +}
1318 +
1319 +extern "C" void free_table_stats(TABLE_STATS* table_stats)
1320 +{
1321 +  my_free((char*) table_stats);
1322 +}
1323 +
1324 +void init_global_table_stats(void)
1325 +{
1326 +  if (my_hash_init(&global_table_stats, system_charset_info, max_connections,
1327 +                0, 0, (my_hash_get_key)get_key_table_stats,
1328 +                (my_hash_free_key)free_table_stats, 0)) {
1329 +    sql_print_error("Initializing global_table_stats failed.");
1330 +    exit(1);
1331 +  }
1332 +}
1333 +
1334 +extern "C" uchar *get_key_index_stats(INDEX_STATS *index_stats, size_t *length,
1335 +                                     my_bool not_used __attribute__((unused)))
1336 +{
1337 +  *length= strlen(index_stats->index);
1338 +  return (uchar*) index_stats->index;
1339 +}
1340 +
1341 +extern "C" void free_index_stats(INDEX_STATS* index_stats)
1342 +{
1343 +  my_free((char*) index_stats);
1344 +}
1345 +
1346 +void init_global_index_stats(void)
1347 +{
1348 +  if (my_hash_init(&global_index_stats, system_charset_info, max_connections,
1349 +                0, 0, (my_hash_get_key)get_key_index_stats,
1350 +                (my_hash_free_key)free_index_stats, 0)) {
1351 +    sql_print_error("Initializing global_index_stats failed.");
1352 +    exit(1);
1353 +  }
1354 +}
1355 +
1356 +void free_global_user_stats(void)
1357 +{
1358 +  my_hash_free(&global_user_stats);
1359 +}
1360 +
1361 +void free_global_thread_stats(void)
1362 +{
1363 +  my_hash_free(&global_thread_stats);
1364 +}
1365 +
1366 +void free_global_table_stats(void)
1367 +{
1368 +  my_hash_free(&global_table_stats);
1369 +}
1370 +
1371 +void free_global_index_stats(void)
1372 +{
1373 +  my_hash_free(&global_index_stats);
1374 +}
1375 +
1376 +void free_global_client_stats(void)
1377 +{
1378 +  my_hash_free(&global_client_stats);
1379 +}
1380 +
1381 +// 'mysql_system_user' is used for when the user is not defined for a THD.
1382 +static char mysql_system_user[] = "#mysql_system#";
1383 +
1384 +// Returns 'user' if it's not NULL.  Returns 'mysql_system_user' otherwise.
1385 +static char* get_valid_user_string(char* user) {
1386 +  return user ? user : mysql_system_user;
1387 +}
1388 +
1389 +// Increments the global stats connection count for an entry from
1390 +// global_client_stats or global_user_stats. Returns 0 on success
1391 +// and 1 on error.
1392 +static int increment_count_by_name(const char *name, const char *role_name,
1393 +                                   HASH *users_or_clients, THD *thd)
1394 +{
1395 +  USER_STATS* user_stats;
1396 +
1397 +  if (!(user_stats = (USER_STATS *) my_hash_search(users_or_clients,
1398 +                                                   (uchar*) name,
1399 +                                                   strlen(name))))
1400 +  {
1401 +    // First connection for this user or client
1402 +    if (!(user_stats = ((USER_STATS *)
1403 +                        my_malloc(sizeof(USER_STATS), MYF(MY_WME | MY_ZEROFILL)))))
1404 +    {
1405 +      return 1; // Out of memory
1406 +    }
1407 +
1408 +    init_user_stats(user_stats, name, role_name,
1409 +                    0, 0,      // connections
1410 +                    0, 0, 0,   // time
1411 +                    0, 0, 0,   // bytes sent, received and written
1412 +                    0, 0, 0,   // rows fetched, updated and read
1413 +                    0, 0, 0,   // select, update and other commands
1414 +                    0, 0,      // commit and rollback trans
1415 +                    thd->diff_denied_connections,
1416 +                    0,         // lost connections
1417 +                    0,         // access denied errors
1418 +                    0);        // empty queries
1419 +
1420 +    if (my_hash_insert(users_or_clients, (uchar *) user_stats))
1421 +    {
1422 +      my_free((char *) user_stats);
1423 +      return 1; // Out of memory
1424 +    }
1425 +  }
1426 +  user_stats->total_connections++;
1427 +  return 0;
1428 +}
1429 +
1430 +static int increment_count_by_id(my_thread_id id,
1431 +                                 HASH *users_or_clients, THD *thd)
1432 +{
1433 +  THREAD_STATS* thread_stats;
1434 +
1435 +  if (!(thread_stats = (THREAD_STATS *) my_hash_search(users_or_clients,
1436 +                                                       (uchar*) &id,
1437 +                                                       sizeof(my_thread_id))))
1438 +  {
1439 +    // First connection for this user or client
1440 +    if (!(thread_stats = ((THREAD_STATS *)
1441 +                        my_malloc(sizeof(THREAD_STATS), MYF(MY_WME | MY_ZEROFILL)))))
1442 +    {
1443 +      return 1; // Out of memory
1444 +    }
1445 +
1446 +    init_thread_stats(thread_stats, id,
1447 +                    0, 0,      // connections
1448 +                    0, 0, 0,   // time
1449 +                    0, 0, 0,   // bytes sent, received and written
1450 +                    0, 0, 0,   // rows fetched, updated and read
1451 +                    0, 0, 0,   // select, update and other commands
1452 +                    0, 0,      // commit and rollback trans
1453 +                    thd->diff_denied_connections,
1454 +                    0,         // lost connections
1455 +                    0,         // access denied errors
1456 +                    0);        // empty queries
1457 +
1458 +    if (my_hash_insert(users_or_clients, (uchar *) thread_stats))
1459 +    {
1460 +      my_free((char *) thread_stats);
1461 +      return 1; // Out of memory
1462 +    }
1463 +  }
1464 +  thread_stats->total_connections++;
1465 +  return 0;
1466 +}
1467 +
1468 +/* Increments the global user and client stats connection count.  If 'use_lock'
1469 +   is true, LOCK_global_user_client_stats will be locked/unlocked.  Returns
1470 +   0 on success, 1 on error.
1471 +*/
1472 +static int increment_connection_count(THD* thd, bool use_lock)
1473 +{
1474 +  char* user_string=         get_valid_user_string(thd->main_security_ctx.user);
1475 +  const char* client_string= get_client_host(thd);
1476 +  int return_value=          0;
1477 +
1478 +  if (!opt_userstat_running)
1479 +    return return_value;
1480 +
1481 +  if (use_lock)
1482 +    mysql_mutex_lock(&LOCK_global_user_client_stats);
1483 +
1484 +  if (increment_count_by_name(user_string, user_string,
1485 +                              &global_user_stats, thd))
1486 +  {
1487 +    return_value= 1;
1488 +    goto end;
1489 +  }
1490 +  if (increment_count_by_name(client_string,
1491 +                              user_string,
1492 +                              &global_client_stats, thd))
1493 +  {
1494 +    return_value= 1;
1495 +    goto end;
1496 +  }
1497 +  if (opt_thread_statistics)
1498 +  {
1499 +    if (increment_count_by_id(thd->thread_id, &global_thread_stats, thd))
1500 +    {
1501 +      return_value= 1;
1502 +      goto end;
1503 +    }
1504 + }
1505 +
1506 +end:
1507 +  if (use_lock)
1508 +    mysql_mutex_unlock(&LOCK_global_user_client_stats);
1509 +  return return_value;
1510 +}
1511 +
1512 +// Used to update the global user and client stats.
1513 +static void update_global_user_stats_with_user(THD* thd,
1514 +                                               USER_STATS* user_stats,
1515 +                                               time_t now)
1516 +{
1517 +  user_stats->connected_time+=       now - thd->last_global_update_time;
1518 +//thd->last_global_update_time=      now;
1519 +  user_stats->busy_time+=            thd->diff_total_busy_time;
1520 +  user_stats->cpu_time+=             thd->diff_total_cpu_time;
1521 +  user_stats->bytes_received+=       thd->diff_total_bytes_received;
1522 +  user_stats->bytes_sent+=           thd->diff_total_bytes_sent;
1523 +  user_stats->binlog_bytes_written+= thd->diff_total_binlog_bytes_written;
1524 +  user_stats->rows_fetched+=         thd->diff_total_sent_rows;
1525 +  user_stats->rows_updated+=         thd->diff_total_updated_rows;
1526 +  user_stats->rows_read+=            thd->diff_total_read_rows;
1527 +  user_stats->select_commands+=      thd->diff_select_commands;
1528 +  user_stats->update_commands+=      thd->diff_update_commands;
1529 +  user_stats->other_commands+=       thd->diff_other_commands;
1530 +  user_stats->commit_trans+=         thd->diff_commit_trans;
1531 +  user_stats->rollback_trans+=       thd->diff_rollback_trans;
1532 +  user_stats->denied_connections+=   thd->diff_denied_connections;
1533 +  user_stats->lost_connections+=     thd->diff_lost_connections;
1534 +  user_stats->access_denied_errors+= thd->diff_access_denied_errors;
1535 +  user_stats->empty_queries+=        thd->diff_empty_queries;
1536 +}
1537 +
1538 +static void update_global_thread_stats_with_thread(THD* thd,
1539 +                                               THREAD_STATS* thread_stats,
1540 +                                               time_t now)
1541 +{
1542 +  thread_stats->connected_time+=       now - thd->last_global_update_time;
1543 +//thd->last_global_update_time=        now;
1544 +  thread_stats->busy_time+=            thd->diff_total_busy_time;
1545 +  thread_stats->cpu_time+=             thd->diff_total_cpu_time;
1546 +  thread_stats->bytes_received+=       thd->diff_total_bytes_received;
1547 +  thread_stats->bytes_sent+=           thd->diff_total_bytes_sent;
1548 +  thread_stats->binlog_bytes_written+= thd->diff_total_binlog_bytes_written;
1549 +  thread_stats->rows_fetched+=         thd->diff_total_sent_rows;
1550 +  thread_stats->rows_updated+=         thd->diff_total_updated_rows;
1551 +  thread_stats->rows_read+=            thd->diff_total_read_rows;
1552 +  thread_stats->select_commands+=      thd->diff_select_commands;
1553 +  thread_stats->update_commands+=      thd->diff_update_commands;
1554 +  thread_stats->other_commands+=       thd->diff_other_commands;
1555 +  thread_stats->commit_trans+=         thd->diff_commit_trans;
1556 +  thread_stats->rollback_trans+=       thd->diff_rollback_trans;
1557 +  thread_stats->denied_connections+=   thd->diff_denied_connections;
1558 +  thread_stats->lost_connections+=     thd->diff_lost_connections;
1559 +  thread_stats->access_denied_errors+= thd->diff_access_denied_errors;
1560 +  thread_stats->empty_queries+=        thd->diff_empty_queries;
1561 +}
1562 +
1563 +// Updates the global stats of a user or client
1564 +void update_global_user_stats(THD* thd, bool create_user, time_t now)
1565 +{
1566 +  if (opt_userstat_running)
1567 +  {
1568 +    char* user_string=         get_valid_user_string(thd->main_security_ctx.user);
1569 +    const char* client_string= get_client_host(thd);
1570 +
1571 +    USER_STATS* user_stats;
1572 +    THREAD_STATS* thread_stats;
1573 +    mysql_mutex_lock(&LOCK_global_user_client_stats);
1574 +
1575 +    // Update by user name
1576 +    if ((user_stats = (USER_STATS *) my_hash_search(&global_user_stats,
1577 +                                                    (uchar *) user_string,
1578 +                                                    strlen(user_string))))
1579 +    {
1580 +      // Found user.
1581 +      update_global_user_stats_with_user(thd, user_stats, now);
1582 +    }
1583 +    else
1584 +    {
1585 +      // Create the entry
1586 +      if (create_user)
1587 +      {
1588 +        increment_count_by_name(user_string, user_string,
1589 +                                &global_user_stats, thd);
1590 +      }
1591 +    }
1592 +
1593 +    // Update by client IP
1594 +    if ((user_stats = (USER_STATS *) my_hash_search(&global_client_stats,
1595 +                                                    (uchar *) client_string,
1596 +                                                    strlen(client_string))))
1597 +    {
1598 +      // Found by client IP
1599 +      update_global_user_stats_with_user(thd, user_stats, now);
1600 +    }
1601 +    else
1602 +    {
1603 +      // Create the entry
1604 +      if (create_user)
1605 +      {
1606 +        increment_count_by_name(client_string,
1607 +                                user_string,
1608 +                                &global_client_stats, thd);
1609 +      }
1610 +    }
1611 +
1612 +    if (opt_thread_statistics)
1613 +    {
1614 +      // Update by thread ID
1615 +      if ((thread_stats = (THREAD_STATS *) my_hash_search(&global_thread_stats,
1616 +                                                          (uchar *) &(thd->thread_id),
1617 +                                                          sizeof(my_thread_id))))
1618 +      {
1619 +        // Found by thread ID
1620 +        update_global_thread_stats_with_thread(thd, thread_stats, now);
1621 +      }
1622 +      else
1623 +      {
1624 +        // Create the entry
1625 +        if (create_user)
1626 +        {
1627 +          increment_count_by_id(thd->thread_id,
1628 +                                &global_thread_stats, thd);
1629 +        }
1630 +      }
1631 +    }
1632 +
1633 +    thd->last_global_update_time = now;
1634 +    thd->reset_diff_stats();
1635 +
1636 +    mysql_mutex_unlock(&LOCK_global_user_client_stats);
1637 +  }
1638 +  else
1639 +  {
1640 +    thd->reset_diff_stats();
1641 +  }
1642 +}
1643  
1644  /*
1645    check if user has already too many connections
1646 @@ -169,6 +767,7 @@
1647    if (error)
1648    {
1649      uc->connections--; // no need for decrease_user_connections() here
1650 +    statistic_increment(denied_connections, &LOCK_status);
1651      /*
1652        The thread may returned back to the pool and assigned to a user
1653        that doesn't have a limit. Ensure the user is not using resources
1654 @@ -565,11 +1164,18 @@
1655        my_sleep(1000);                          /* must wait after eof() */
1656  #endif
1657      statistic_increment(aborted_connects,&LOCK_status);
1658 +    thd->diff_denied_connections++;
1659      DBUG_RETURN(1);
1660    }
1661    /* Connect completed, set read/write timeouts back to default */
1662    my_net_set_read_timeout(net, thd->variables.net_read_timeout);
1663    my_net_set_write_timeout(net, thd->variables.net_write_timeout);
1664 +
1665 +  thd->reset_stats();
1666 +  // Updates global user connection stats.
1667 +  if (increment_connection_count(thd, true))
1668 +    DBUG_RETURN(1);
1669 +
1670    DBUG_RETURN(0);
1671  }
1672  
1673 @@ -599,6 +1205,7 @@
1674    if (thd->killed || (net->error && net->vio != 0))
1675    {
1676      statistic_increment(aborted_threads,&LOCK_status);
1677 +    thd->diff_lost_connections++;
1678    }
1679  
1680    if (net->error && net->vio != 0)
1681 @@ -728,10 +1335,14 @@
1682    for (;;)
1683    {
1684      NET *net= &thd->net;
1685 +    bool create_user= TRUE;
1686  
1687      lex_start(thd);
1688      if (login_connection(thd))
1689 +    {
1690 +      create_user= FALSE;
1691        goto end_thread;
1692 +    }
1693  
1694      MYSQL_CONNECTION_START(thd->thread_id, thd->security_ctx->priv_user,
1695                             (char *) thd->security_ctx->host_or_ip);
1696 @@ -758,6 +1369,8 @@
1697     
1698  end_thread:
1699      close_connection(thd, 0, 1);
1700 +    thd->update_stats(false);
1701 +    update_global_user_stats(thd, create_user, time(NULL));
1702      if (MYSQL_CALLBACK_ELSE(thread_scheduler, end_thread, (thd, 1), 0))
1703        return;                                 // Probably no-threads
1704  
1705 diff -ruN a/sql/sql_delete.cc b/sql/sql_delete.cc
1706 --- a/sql/sql_delete.cc 2010-12-03 20:58:26.000000000 +0300
1707 +++ b/sql/sql_delete.cc 2010-12-31 03:58:22.000000000 +0300
1708 @@ -411,6 +411,7 @@
1709      my_ok(thd, deleted);
1710      DBUG_PRINT("info",("%ld records deleted",(long) deleted));
1711    }
1712 +  thd->updated_row_count+= deleted;
1713    DBUG_RETURN(error >= 0 || thd->is_error());
1714  }
1715  
1716 @@ -1005,6 +1006,7 @@
1717    {
1718      ::my_ok(thd, deleted);
1719    }
1720 +  thd->updated_row_count+= deleted;
1721    return 0;
1722  }
1723  
1724 diff -ruN a/sql/sql_insert.cc b/sql/sql_insert.cc
1725 --- a/sql/sql_insert.cc 2010-12-03 20:58:26.000000000 +0300
1726 +++ b/sql/sql_insert.cc 2010-12-31 04:12:35.000000000 +0300
1727 @@ -1073,13 +1073,14 @@
1728  
1729    if (error)
1730      goto abort;
1731 +  ha_rows row_count;
1732    if (values_list.elements == 1 && (!(thd->variables.option_bits & OPTION_WARNINGS) ||
1733                                     !thd->cuted_fields))
1734    {
1735 -    my_ok(thd, info.copied + info.deleted +
1736 +    row_count= info.copied + info.deleted +
1737                 ((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
1738 -                info.touched : info.updated),
1739 -          id);
1740 +                info.touched : info.updated);
1741 +    my_ok(thd, row_count, id);
1742    }
1743    else
1744    {
1745 @@ -1095,8 +1096,10 @@
1746        sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
1747               (ulong) (info.deleted + updated),
1748                (ulong) thd->warning_info->statement_warn_count());
1749 -    ::my_ok(thd, info.copied + info.deleted + updated, id, buff);
1750 +    row_count= info.copied + info.deleted + updated;
1751 +    ::my_ok(thd, row_count, id, buff);
1752    }
1753 +  thd->updated_row_count+= row_count;
1754    thd->abort_on_warning= 0;
1755    DBUG_RETURN(FALSE);
1756  
1757 @@ -3585,6 +3588,7 @@
1758       thd->first_successful_insert_id_in_prev_stmt :
1759       (info.copied ? autoinc_value_of_last_inserted_row : 0));
1760    ::my_ok(thd, row_count, id, buff);
1761 +  thd->updated_row_count+= row_count;
1762    DBUG_RETURN(0);
1763  }
1764  
1765 diff -ruN a/sql/sql_lex.h b/sql/sql_lex.h
1766 --- a/sql/sql_lex.h     2010-12-03 20:58:26.000000000 +0300
1767 +++ b/sql/sql_lex.h     2010-12-31 05:07:18.000000000 +0300
1768 @@ -196,6 +196,9 @@
1769      When a command is added here, be sure it's also added in mysqld.cc
1770      in "struct show_var_st status_vars[]= {" ...
1771    */
1772 +  // TODO(mcallaghan): update status_vars in mysqld to export these
1773 +  SQLCOM_SHOW_USER_STATS, SQLCOM_SHOW_TABLE_STATS, SQLCOM_SHOW_INDEX_STATS,
1774 +  SQLCOM_SHOW_CLIENT_STATS, SQLCOM_SHOW_THREAD_STATS,
1775    /* This should be the last !!! */
1776    SQLCOM_END
1777  };
1778 diff -ruN a/sql/sql_parse.cc b/sql/sql_parse.cc
1779 --- a/sql/sql_parse.cc  2010-12-03 20:58:26.000000000 +0300
1780 +++ b/sql/sql_parse.cc  2010-12-31 04:57:45.000000000 +0300
1781 @@ -116,6 +116,9 @@
1782  static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
1783  static void sql_kill(THD *thd, ulong id, bool only_kill_query);
1784  
1785 +// Uses the THD to update the global stats by user name and client IP
1786 +void update_global_user_stats(THD* thd, bool create_user, time_t now);
1787 +
1788  const char *any_db="*any*";    // Special symbol for check_access
1789  
1790  const LEX_STRING command_name[]={
1791 @@ -701,6 +704,12 @@
1792    */
1793    thd->clear_error();                          // Clear error message
1794    thd->stmt_da->reset_diagnostics_area();
1795 +  thd->updated_row_count=    0;
1796 +  thd->busy_time=            0;
1797 +  thd->cpu_time=             0;
1798 +  thd->bytes_received=       0;
1799 +  thd->bytes_sent=           0;
1800 +  thd->binlog_bytes_written= 0;
1801  
1802    net_new_transaction(net);
1803  
1804 @@ -886,6 +895,10 @@
1805                        (char *) thd->security_ctx->host_or_ip);
1806    
1807    thd->command=command;
1808 +  /* To increment the corrent command counter for user stats, 'command' must
1809 +     be saved because it is set to COM_SLEEP at the end of this function.
1810 +  */
1811 +  thd->old_command= command;
1812    /*
1813      Commands which always take a long time are logged into
1814      the slow log only if opt_log_slow_admin_statements is set.
1815 @@ -1619,6 +1632,13 @@
1816      thd->profiling.discard_current_query();
1817  #endif
1818      break;
1819 +  case SCH_USER_STATS:
1820 +  case SCH_CLIENT_STATS:
1821 +  case SCH_THREAD_STATS:
1822 +    if (check_global_access(thd, SUPER_ACL | PROCESS_ACL))
1823 +      DBUG_RETURN(1);
1824 +  case SCH_TABLE_STATS:
1825 +  case SCH_INDEX_STATS:
1826    case SCH_OPEN_TABLES:
1827    case SCH_VARIABLES:
1828    case SCH_STATUS:
1829 @@ -1776,6 +1796,7 @@
1830                         thd->security_ctx->priv_host)) &&
1831          check_global_access(thd, SUPER_ACL))
1832      {
1833 +      thd->diff_access_denied_errors++;
1834        my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER");
1835        DBUG_RETURN(TRUE);
1836      }
1837 @@ -4705,6 +4726,7 @@
1838        case ACL_INTERNAL_ACCESS_DENIED:
1839          if (! no_errors)
1840          {
1841 +          thd->diff_access_denied_errors++;
1842            my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
1843                     sctx->priv_user, sctx->priv_host, db);
1844          }
1845 @@ -4755,6 +4777,7 @@
1846      DBUG_PRINT("error",("No possible access"));
1847      if (!no_errors)
1848      {
1849 +      thd->diff_access_denied_errors++;
1850        if (thd->password == 2)
1851          my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
1852                   sctx->priv_user,
1853 @@ -4871,6 +4894,7 @@
1854  
1855      if (!thd->col_access && check_grant_db(thd, dst_db_name))
1856      {
1857 +      thd->diff_access_denied_errors++;
1858        my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
1859                 thd->security_ctx->priv_user,
1860                 thd->security_ctx->priv_host,
1861 @@ -5141,6 +5165,7 @@
1862    if ((thd->security_ctx->master_access & want_access))
1863      return 0;
1864    get_privilege_desc(command, sizeof(command), want_access);
1865 +  thd->diff_access_denied_errors++;
1866    my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
1867    return 1;
1868  #else
1869 @@ -5529,6 +5554,32 @@
1870    lex_start(thd);
1871    mysql_reset_thd_for_next_command(thd);
1872  
1873 +  int start_time_error=   0;
1874 +  int end_time_error=     0;
1875 +  struct timeval start_time, end_time;
1876 +  double start_usecs=     0;
1877 +  double end_usecs=       0;
1878 +  /* cpu time */
1879 +  int cputime_error=      0;
1880 +  struct timespec tp;
1881 +  double start_cpu_nsecs= 0;
1882 +  double end_cpu_nsecs=   0;
1883 +
1884 +  if (opt_userstat_running)
1885 +  {
1886 +#ifdef HAVE_CLOCK_GETTIME
1887 +    /* get start cputime */
1888 +    if (!(cputime_error = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
1889 +      start_cpu_nsecs = tp.tv_sec*1000000000.0+tp.tv_nsec;
1890 +#endif
1891 +
1892 +    // Gets the start time, in order to measure how long this command takes.
1893 +    if (!(start_time_error = gettimeofday(&start_time, NULL)))
1894 +    {
1895 +      start_usecs = start_time.tv_sec * 1000000.0 + start_time.tv_usec;
1896 +    }
1897 +  }
1898 +
1899    if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0)
1900    {
1901      LEX *lex= thd->lex;
1902 @@ -5597,6 +5648,52 @@
1903      DBUG_ASSERT(thd->change_list.is_empty());
1904    }
1905  
1906 +  if (opt_userstat_running)
1907 +  {
1908 +    // Gets the end time.
1909 +    if (!(end_time_error= gettimeofday(&end_time, NULL)))
1910 +    {
1911 +      end_usecs= end_time.tv_sec * 1000000.0 + end_time.tv_usec;
1912 +    }
1913 +
1914 +    // Calculates the difference between the end and start times.
1915 +    if (start_usecs && end_usecs >= start_usecs && !start_time_error && !end_time_error)
1916 +    {
1917 +      thd->busy_time= (end_usecs - start_usecs) / 1000000;
1918 +      // In case there are bad values, 2629743 is the #seconds in a month.
1919 +      if (thd->busy_time > 2629743)
1920 +      {
1921 +        thd->busy_time= 0;
1922 +      }
1923 +    }
1924 +    else
1925 +    {
1926 +      // end time went back in time, or gettimeofday() failed.
1927 +      thd->busy_time= 0;
1928 +    }
1929 +
1930 +#ifdef HAVE_CLOCK_GETTIME
1931 +    /* get end cputime */
1932 +    if (!cputime_error &&
1933 +        !(cputime_error = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
1934 +      end_cpu_nsecs = tp.tv_sec*1000000000.0+tp.tv_nsec;
1935 +#endif
1936 +    if (start_cpu_nsecs && !cputime_error)
1937 +    {
1938 +      thd->cpu_time = (end_cpu_nsecs - start_cpu_nsecs) / 1000000000;
1939 +      // In case there are bad values, 2629743 is the #seconds in a month.
1940 +      if (thd->cpu_time > 2629743)
1941 +      {
1942 +        thd->cpu_time = 0;
1943 +      }
1944 +    }
1945 +    else
1946 +      thd->cpu_time = 0;
1947 +  }
1948 +  // Updates THD stats and the global user stats.
1949 +  thd->update_stats(true);
1950 +  update_global_user_stats(thd, true, time(NULL));
1951 +
1952    DBUG_VOID_RETURN;
1953  }
1954  
1955 diff -ruN a/sql/sql_prepare.cc b/sql/sql_prepare.cc
1956 --- a/sql/sql_prepare.cc        2010-12-03 20:58:26.000000000 +0300
1957 +++ b/sql/sql_prepare.cc        2010-12-31 04:25:04.000000000 +0300
1958 @@ -114,6 +114,9 @@
1959  #endif
1960  #include "lock.h"                               // MYSQL_OPEN_FORCE_SHARED_MDL
1961  
1962 +// Uses the THD to update the global stats by user name and client IP
1963 +void update_global_user_stats(THD* thd, bool create_user, time_t now);
1964 +
1965  /**
1966    A result class used to send cursor rows using the binary protocol.
1967  */
1968 @@ -2173,8 +2176,34 @@
1969    /* First of all clear possible warnings from the previous command */
1970    mysql_reset_thd_for_next_command(thd);
1971  
1972 +  int start_time_error=   0;
1973 +  int end_time_error=     0;
1974 +  struct timeval start_time, end_time;
1975 +  double start_usecs=     0;
1976 +  double end_usecs=       0;
1977 +  /* cpu time */
1978 +  int cputime_error=      0;
1979 +  struct timespec tp;
1980 +  double start_cpu_nsecs= 0;
1981 +  double end_cpu_nsecs=   0;
1982 +
1983 +  if (opt_userstat_running)
1984 +  {
1985 +#ifdef HAVE_CLOCK_GETTIME
1986 +    /* get start cputime */
1987 +    if (!(cputime_error= clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
1988 +      start_cpu_nsecs= tp.tv_sec * 1000000000.0 + tp.tv_nsec;
1989 +#endif
1990 +
1991 +    // Gets the start time, in order to measure how long this command takes.
1992 +    if (!(start_time_error= gettimeofday(&start_time, NULL)))
1993 +    {
1994 +      start_usecs= start_time.tv_sec * 1000000.0 + start_time.tv_usec;
1995 +    }
1996 +  }
1997 +
1998    if (! (stmt= new Prepared_statement(thd)))
1999 -    DBUG_VOID_RETURN; /* out of memory: error is set in Sql_alloc */
2000 +    goto end; /* out of memory: error is set in Sql_alloc */
2001  
2002    if (thd->stmt_map.insert(thd, stmt))
2003    {
2004 @@ -2182,7 +2211,7 @@
2005        The error is set in the insert. The statement itself
2006        will be also deleted there (this is how the hash works).
2007      */
2008 -    DBUG_VOID_RETURN;
2009 +    goto end;
2010    }
2011  
2012    thd->protocol= &thd->protocol_binary;
2013 @@ -2196,6 +2225,53 @@
2014    thd->protocol= save_protocol;
2015  
2016    /* check_prepared_statemnt sends the metadata packet in case of success */
2017 +end:
2018 +  if (opt_userstat_running)
2019 +  {
2020 +    // Gets the end time.
2021 +    if (!(end_time_error= gettimeofday(&end_time, NULL)))
2022 +    {
2023 +      end_usecs= end_time.tv_sec * 1000000.0 + end_time.tv_usec;
2024 +    }
2025 +
2026 +    // Calculates the difference between the end and start times.
2027 +    if (start_usecs && end_usecs >= start_usecs && !start_time_error && !end_time_error)
2028 +    {
2029 +      thd->busy_time= (end_usecs - start_usecs) / 1000000;
2030 +      // In case there are bad values, 2629743 is the #seconds in a month.
2031 +      if (thd->busy_time > 2629743)
2032 +      {
2033 +        thd->busy_time= 0;
2034 +      }
2035 +    }
2036 +    else
2037 +    {
2038 +      // end time went back in time, or gettimeofday() failed.
2039 +      thd->busy_time= 0;
2040 +    }
2041 +
2042 +#ifdef HAVE_CLOCK_GETTIME
2043 +    /* get end cputime */
2044 +    if (!cputime_error &&
2045 +        !(cputime_error= clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2046 +      end_cpu_nsecs= tp.tv_sec*1000000000.0+tp.tv_nsec;
2047 +#endif
2048 +    if (start_cpu_nsecs && !cputime_error)
2049 +    {
2050 +      thd->cpu_time= (end_cpu_nsecs - start_cpu_nsecs) / 1000000000;
2051 +      // In case there are bad values, 2629743 is the #seconds in a month.
2052 +      if (thd->cpu_time > 2629743)
2053 +      {
2054 +        thd->cpu_time= 0;
2055 +      }
2056 +    }
2057 +    else
2058 +      thd->cpu_time = 0;
2059 +  }
2060 +  // Updates THD stats and the global user stats.
2061 +  thd->update_stats(true);
2062 +  update_global_user_stats(thd, true, time(NULL));
2063 +
2064    DBUG_VOID_RETURN;
2065  }
2066  
2067 @@ -2553,12 +2629,38 @@
2068    /* First of all clear possible warnings from the previous command */
2069    mysql_reset_thd_for_next_command(thd);
2070  
2071 +  int start_time_error=   0;
2072 +  int end_time_error=     0;
2073 +  struct timeval start_time, end_time;
2074 +  double start_usecs=     0;
2075 +  double end_usecs=       0;
2076 +  /* cpu time */
2077 +  int cputime_error=      0;
2078 +  struct timespec tp;
2079 +  double start_cpu_nsecs= 0;
2080 +  double end_cpu_nsecs=   0;
2081 +
2082 +  if (opt_userstat_running)
2083 +  {
2084 +#ifdef HAVE_CLOCK_GETTIME
2085 +    /* get start cputime */
2086 +    if (!(cputime_error = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2087 +      start_cpu_nsecs = tp.tv_sec*1000000000.0+tp.tv_nsec;
2088 +#endif
2089 +
2090 +    // Gets the start time, in order to measure how long this command takes.
2091 +    if (!(start_time_error = gettimeofday(&start_time, NULL)))
2092 +    {
2093 +      start_usecs = start_time.tv_sec * 1000000.0 + start_time.tv_usec;
2094 +    }
2095 +  }
2096 +
2097    if (!(stmt= find_prepared_statement(thd, stmt_id)))
2098    {
2099      char llbuf[22];
2100      my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
2101               llstr(stmt_id, llbuf), "mysqld_stmt_execute");
2102 -    DBUG_VOID_RETURN;
2103 +    goto end;
2104    }
2105  
2106  #if defined(ENABLED_PROFILING)
2107 @@ -2576,6 +2678,53 @@
2108    /* Close connection socket; for use with client testing (Bug#43560). */
2109    DBUG_EXECUTE_IF("close_conn_after_stmt_execute", vio_close(thd->net.vio););
2110  
2111 +end:
2112 +  if (opt_userstat_running)
2113 +  {
2114 +    // Gets the end time.
2115 +    if (!(end_time_error= gettimeofday(&end_time, NULL)))
2116 +    {
2117 +      end_usecs= end_time.tv_sec * 1000000.0 + end_time.tv_usec;
2118 +    }
2119 +
2120 +    // Calculates the difference between the end and start times.
2121 +    if (start_usecs && end_usecs >= start_usecs && !start_time_error && !end_time_error)
2122 +    {
2123 +      thd->busy_time= (end_usecs - start_usecs) / 1000000;
2124 +      // In case there are bad values, 2629743 is the #seconds in a month.
2125 +      if (thd->busy_time > 2629743)
2126 +      {
2127 +        thd->busy_time= 0;
2128 +      }
2129 +    }
2130 +    else
2131 +    {
2132 +      // end time went back in time, or gettimeofday() failed.
2133 +      thd->busy_time= 0;
2134 +    }
2135 +
2136 +#ifdef HAVE_CLOCK_GETTIME
2137 +    /* get end cputime */
2138 +    if (!cputime_error &&
2139 +        !(cputime_error= clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2140 +      end_cpu_nsecs= tp.tv_sec*1000000000.0+tp.tv_nsec;
2141 +#endif
2142 +    if (start_cpu_nsecs && !cputime_error)
2143 +    {
2144 +      thd->cpu_time= (end_cpu_nsecs - start_cpu_nsecs) / 1000000000;
2145 +      // In case there are bad values, 2629743 is the #seconds in a month.
2146 +      if (thd->cpu_time > 2629743)
2147 +      {
2148 +        thd->cpu_time= 0;
2149 +      }
2150 +    }
2151 +    else
2152 +      thd->cpu_time = 0;
2153 +  }
2154 +  // Updates THD stats and the global user stats.
2155 +  thd->update_stats(true);
2156 +  update_global_user_stats(thd, true, time(NULL));
2157 +
2158    DBUG_VOID_RETURN;
2159  }
2160  
2161 @@ -2648,20 +2797,47 @@
2162  
2163    /* First of all clear possible warnings from the previous command */
2164    mysql_reset_thd_for_next_command(thd);
2165 +
2166 +  int start_time_error=   0;
2167 +  int end_time_error=     0;
2168 +  struct timeval start_time, end_time;
2169 +  double start_usecs=     0;
2170 +  double end_usecs=       0;
2171 +  /* cpu time */
2172 +  int cputime_error=      0;
2173 +  struct timespec tp;
2174 +  double start_cpu_nsecs= 0;
2175 +  double end_cpu_nsecs=   0;
2176 +
2177 +  if (opt_userstat_running)
2178 +  {
2179 +#ifdef HAVE_CLOCK_GETTIME
2180 +    /* get start cputime */
2181 +    if (!(cputime_error= clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2182 +      start_cpu_nsecs= tp.tv_sec*1000000000.0+tp.tv_nsec;
2183 +#endif
2184 +
2185 +    // Gets the start time, in order to measure how long this command takes.
2186 +    if (!(start_time_error= gettimeofday(&start_time, NULL)))
2187 +    {
2188 +      start_usecs= start_time.tv_sec * 1000000.0 + start_time.tv_usec;
2189 +    }
2190 +  }
2191 +
2192    status_var_increment(thd->status_var.com_stmt_fetch);
2193    if (!(stmt= find_prepared_statement(thd, stmt_id)))
2194    {
2195      char llbuf[22];
2196      my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
2197               llstr(stmt_id, llbuf), "mysqld_stmt_fetch");
2198 -    DBUG_VOID_RETURN;
2199 +    goto end;
2200    }
2201  
2202    cursor= stmt->cursor;
2203    if (!cursor)
2204    {
2205      my_error(ER_STMT_HAS_NO_OPEN_CURSOR, MYF(0), stmt_id);
2206 -    DBUG_VOID_RETURN;
2207 +    goto end;
2208    }
2209  
2210    thd->stmt_arena= stmt;
2211 @@ -2678,6 +2854,52 @@
2212    thd->restore_backup_statement(stmt, &stmt_backup);
2213    thd->stmt_arena= thd;
2214  
2215 +end:
2216 +  if (opt_userstat_running)
2217 +  {
2218 +    // Gets the end time.
2219 +    if (!(end_time_error = gettimeofday(&end_time, NULL)))
2220 +    {
2221 +      end_usecs = end_time.tv_sec * 1000000.0 + end_time.tv_usec;
2222 +    }
2223 +
2224 +    // Calculates the difference between the end and start times.
2225 +    if (start_usecs && end_usecs >= start_usecs && !start_time_error && !end_time_error)
2226 +    {
2227 +      thd->busy_time= (end_usecs - start_usecs) / 1000000;
2228 +      // In case there are bad values, 2629743 is the #seconds in a month.
2229 +      if (thd->busy_time > 2629743)
2230 +      {
2231 +        thd->busy_time= 0;
2232 +      }
2233 +    }
2234 +    else
2235 +    {
2236 +      // end time went back in time, or gettimeofday() failed.
2237 +      thd->busy_time= 0;
2238 +    }
2239 +
2240 +#ifdef HAVE_CLOCK_GETTIME
2241 +    /* get end cputime */
2242 +    if (!cputime_error &&
2243 +        !(cputime_error= clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2244 +      end_cpu_nsecs= tp.tv_sec*1000000000.0+tp.tv_nsec;
2245 +#endif
2246 +    if (start_cpu_nsecs && !cputime_error)
2247 +    {
2248 +      thd->cpu_time= (end_cpu_nsecs - start_cpu_nsecs) / 1000000000;
2249 +      // In case there are bad values, 2629743 is the #seconds in a month.
2250 +      if (thd->cpu_time > 2629743)
2251 +      {
2252 +        thd->cpu_time= 0;
2253 +      }
2254 +    } else
2255 +      thd->cpu_time= 0;
2256 +  }
2257 +  // Updates THD stats and the global user stats.
2258 +  thd->update_stats(true);
2259 +  update_global_user_stats(thd, true, time(NULL));
2260 +
2261    DBUG_VOID_RETURN;
2262  }
2263  
2264 @@ -2708,13 +2930,39 @@
2265    /* First of all clear possible warnings from the previous command */
2266    mysql_reset_thd_for_next_command(thd);
2267  
2268 +  int start_time_error=   0;
2269 +  int end_time_error=     0;
2270 +  struct timeval start_time, end_time;
2271 +  double start_usecs=     0;
2272 +  double end_usecs=       0;
2273 +  /* cpu time */
2274 +  int cputime_error=      0;
2275 +  struct timespec tp;
2276 +  double start_cpu_nsecs= 0;
2277 +  double end_cpu_nsecs=   0;
2278 +
2279 +  if (opt_userstat_running)
2280 +  {
2281 +#ifdef HAVE_CLOCK_GETTIME
2282 +    /* get start cputime */
2283 +    if (!(cputime_error= clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2284 +      start_cpu_nsecs= tp.tv_sec * 1000000000.0+tp.tv_nsec;
2285 +#endif
2286 +
2287 +    // Gets the start time, in order to measure how long this command takes.
2288 +    if (!(start_time_error= gettimeofday(&start_time, NULL)))
2289 +    {
2290 +      start_usecs= start_time.tv_sec * 1000000.0 + start_time.tv_usec;
2291 +    }
2292 +  }
2293 +
2294    status_var_increment(thd->status_var.com_stmt_reset);
2295    if (!(stmt= find_prepared_statement(thd, stmt_id)))
2296    {
2297      char llbuf[22];
2298      my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
2299               llstr(stmt_id, llbuf), "mysqld_stmt_reset");
2300 -    DBUG_VOID_RETURN;
2301 +    goto end;
2302    }
2303  
2304    stmt->close_cursor();
2305 @@ -2731,6 +2979,53 @@
2306  
2307    my_ok(thd);
2308  
2309 +end:
2310 +  if (opt_userstat_running)
2311 +  {
2312 +    // Gets the end time.
2313 +    if (!(end_time_error = gettimeofday(&end_time, NULL)))
2314 +    {
2315 +      end_usecs = end_time.tv_sec * 1000000.0 + end_time.tv_usec;
2316 +    }
2317 +
2318 +    // Calculates the difference between the end and start times.
2319 +    if (start_usecs && end_usecs >= start_usecs && !start_time_error && !end_time_error)
2320 +    {
2321 +      thd->busy_time= (end_usecs - start_usecs) / 1000000;
2322 +      // In case there are bad values, 2629743 is the #seconds in a month.
2323 +      if (thd->busy_time > 2629743)
2324 +      {
2325 +        thd->busy_time= 0;
2326 +      }
2327 +    }
2328 +    else
2329 +    {
2330 +      // end time went back in time, or gettimeofday() failed.
2331 +      thd->busy_time= 0;
2332 +    }
2333 +
2334 +#ifdef HAVE_CLOCK_GETTIME
2335 +    /* get end cputime */
2336 +    if (!cputime_error &&
2337 +        !(cputime_error = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp)))
2338 +      end_cpu_nsecs = tp.tv_sec*1000000000.0+tp.tv_nsec;
2339 +#endif
2340 +    if (start_cpu_nsecs && !cputime_error)
2341 +    {
2342 +      thd->cpu_time = (end_cpu_nsecs - start_cpu_nsecs) / 1000000000;
2343 +      // In case there are bad values, 2629743 is the #seconds in a month.
2344 +      if (thd->cpu_time > 2629743)
2345 +      {
2346 +        thd->cpu_time= 0;
2347 +      }
2348 +    }
2349 +    else
2350 +      thd->cpu_time= 0;
2351 +  }
2352 +  // Updates THD stats and the global user stats.
2353 +  thd->update_stats(true);
2354 +  update_global_user_stats(thd, true, time(NULL));
2355 +
2356    DBUG_VOID_RETURN;
2357  }
2358  
2359 diff -ruN a/sql/sql_reload.cc b/sql/sql_reload.cc
2360 --- a/sql/sql_reload.cc 2010-12-03 20:58:26.000000000 +0300
2361 +++ b/sql/sql_reload.cc 2010-12-31 05:00:59.000000000 +0300
2362 @@ -272,14 +272,48 @@
2363     mysql_mutex_unlock(&LOCK_active_mi);
2364   }
2365  #endif
2366 - if (options & REFRESH_USER_RESOURCES)
2367 -   reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
2368  #ifdef HAVE_RESPONSE_TIME_DISTRIBUTION
2369   if (options & REFRESH_QUERY_RESPONSE_TIME)
2370   {
2371     query_response_time_flush();
2372   }
2373  #endif // HAVE_RESPONSE_TIME_DISTRIBUTION
2374 +  if (options & REFRESH_USER_RESOURCES)
2375 +    reset_mqh((LEX_USER *) NULL, 0);             /* purecov: inspected */
2376 +  if (options & REFRESH_TABLE_STATS)
2377 +  {
2378 +    mysql_mutex_lock(&LOCK_global_table_stats);
2379 +    free_global_table_stats();
2380 +    init_global_table_stats();
2381 +    mysql_mutex_unlock(&LOCK_global_table_stats);
2382 +  }
2383 +  if (options & REFRESH_INDEX_STATS)
2384 +  {
2385 +    mysql_mutex_lock(&LOCK_global_index_stats);
2386 +    free_global_index_stats();
2387 +    init_global_index_stats();
2388 +    mysql_mutex_unlock(&LOCK_global_index_stats);
2389 +  }
2390 +  if (options & (REFRESH_USER_STATS | REFRESH_CLIENT_STATS | REFRESH_THREAD_STATS))
2391 +  {
2392 +    mysql_mutex_lock(&LOCK_global_user_client_stats);
2393 +    if (options & REFRESH_USER_STATS)
2394 +    {
2395 +      free_global_user_stats();
2396 +      init_global_user_stats();
2397 +    }
2398 +    if (options & REFRESH_CLIENT_STATS)
2399 +    {
2400 +      free_global_client_stats();
2401 +      init_global_client_stats();
2402 +    }
2403 +    if (options & REFRESH_THREAD_STATS)
2404 +    {
2405 +      free_global_thread_stats();
2406 +      init_global_thread_stats();
2407 +    }
2408 +    mysql_mutex_unlock(&LOCK_global_user_client_stats);
2409 +  }
2410   *write_to_binlog= tmp_write_to_binlog;
2411   /*
2412     If the query was killed then this function must fail.
2413 diff -ruN a/sql/sql_show.cc b/sql/sql_show.cc
2414 --- a/sql/sql_show.cc   2010-12-03 20:58:26.000000000 +0300
2415 +++ b/sql/sql_show.cc   2010-12-31 04:39:23.000000000 +0300
2416 @@ -114,6 +114,43 @@
2417  
2418  static COND * make_cond_for_info_schema(COND *cond, TABLE_LIST *table);
2419  
2420 +/*
2421 + * Solaris 10 does not have strsep().
2422 + *
2423 + * based on getToken from http://www.winehq.org/pipermail/wine-patches/2001-November/001322.html
2424 + *
2425 +*/
2426 +
2427 +#ifndef HAVE_STRSEP
2428 +static char* strsep(char** str, const char* delims)
2429 +{
2430 +  char *token;
2431 +
2432 +  if (*str == NULL)
2433 +  {
2434 +    /* No more tokens */
2435 +    return NULL;
2436 +  }
2437 +
2438 +  token= *str;
2439 +  while (**str != '\0')
2440 +  {
2441 +    if (strchr(delims, **str) != NULL)
2442 +    {
2443 +      **str= '\0';
2444 +      (*str)++;
2445 +      return token;
2446 +    }
2447 +    (*str)++;
2448 +  }
2449 +
2450 +  /* There is not another token */
2451 +  *str= NULL;
2452 +
2453 +  return token;
2454 +}
2455 +#endif
2456 +
2457  /***************************************************************************
2458  ** List all table types supported
2459  ***************************************************************************/
2460 @@ -799,6 +836,7 @@
2461                 sctx->master_access);
2462    if (!(db_access & DB_ACLS) && check_grant_db(thd,dbname))
2463    {
2464 +    thd->diff_access_denied_errors++;
2465      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
2466               sctx->priv_user, sctx->host_or_ip, dbname);
2467      general_log_print(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR),
2468 @@ -2351,6 +2389,284 @@
2469    DBUG_RETURN(res);
2470  }
2471  
2472 +/*
2473 +   Write result to network for SHOW USER_STATISTICS
2474 +
2475 +   SYNOPSIS
2476 +     send_user_stats
2477 +       all_user_stats - values to return
2478 +       table - I_S table
2479 +
2480 +   RETURN
2481 +     0 - OK
2482 +     1 - error
2483 +*/
2484 +int send_user_stats(THD* thd, HASH *all_user_stats, TABLE *table)
2485 +{
2486 +  DBUG_ENTER("send_user_stats");
2487 +  for (uint i = 0; i < all_user_stats->records; ++i)
2488 +  {
2489 +    restore_record(table, s->default_values);
2490 +    USER_STATS *user_stats = (USER_STATS *) my_hash_element(all_user_stats, i);
2491 +      table->field[0]->store(user_stats->user, strlen(user_stats->user), system_charset_info);
2492 +      table->field[1]->store((longlong)user_stats->total_connections);
2493 +      table->field[2]->store((longlong)user_stats->concurrent_connections);
2494 +      table->field[3]->store((longlong)user_stats->connected_time);
2495 +      table->field[4]->store((longlong)user_stats->busy_time);
2496 +      table->field[5]->store((longlong)user_stats->cpu_time);
2497 +      table->field[6]->store((longlong)user_stats->bytes_received);
2498 +      table->field[7]->store((longlong)user_stats->bytes_sent);
2499 +      table->field[8]->store((longlong)user_stats->binlog_bytes_written);
2500 +      table->field[9]->store((longlong)user_stats->rows_fetched);
2501 +      table->field[10]->store((longlong)user_stats->rows_updated);
2502 +      table->field[11]->store((longlong)user_stats->rows_read);
2503 +      table->field[12]->store((longlong)user_stats->select_commands);
2504 +      table->field[13]->store((longlong)user_stats->update_commands);
2505 +      table->field[14]->store((longlong)user_stats->other_commands);
2506 +      table->field[15]->store((longlong)user_stats->commit_trans);
2507 +      table->field[16]->store((longlong)user_stats->rollback_trans);
2508 +      table->field[17]->store((longlong)user_stats->denied_connections);
2509 +      table->field[18]->store((longlong)user_stats->lost_connections);
2510 +      table->field[19]->store((longlong)user_stats->access_denied_errors);
2511 +      table->field[20]->store((longlong)user_stats->empty_queries);
2512 +      if (schema_table_store_record(thd, table))
2513 +      {
2514 +             DBUG_PRINT("error", ("store record error"));
2515 +             DBUG_RETURN(1);
2516 +      }
2517 +  }
2518 +  DBUG_RETURN(0);
2519 +}
2520 +
2521 +int send_thread_stats(THD* thd, HASH *all_thread_stats, TABLE *table)
2522 +{
2523 +  DBUG_ENTER("send_thread_stats");
2524 +  for (uint i = 0; i < all_thread_stats->records; ++i)
2525 +  {
2526 +    restore_record(table, s->default_values);
2527 +    THREAD_STATS *user_stats = (THREAD_STATS *) my_hash_element(all_thread_stats, i);
2528 +      table->field[0]->store((longlong)user_stats->id);
2529 +      table->field[1]->store((longlong)user_stats->total_connections);
2530 +      table->field[2]->store((longlong)user_stats->concurrent_connections);
2531 +      table->field[3]->store((longlong)user_stats->connected_time);
2532 +      table->field[4]->store((longlong)user_stats->busy_time);
2533 +      table->field[5]->store((longlong)user_stats->cpu_time);
2534 +      table->field[6]->store((longlong)user_stats->bytes_received);
2535 +      table->field[7]->store((longlong)user_stats->bytes_sent);
2536 +      table->field[8]->store((longlong)user_stats->binlog_bytes_written);
2537 +      table->field[9]->store((longlong)user_stats->rows_fetched);
2538 +      table->field[10]->store((longlong)user_stats->rows_updated);
2539 +      table->field[11]->store((longlong)user_stats->rows_read);
2540 +      table->field[12]->store((longlong)user_stats->select_commands);
2541 +      table->field[13]->store((longlong)user_stats->update_commands);
2542 +      table->field[14]->store((longlong)user_stats->other_commands);
2543 +      table->field[15]->store((longlong)user_stats->commit_trans);
2544 +      table->field[16]->store((longlong)user_stats->rollback_trans);
2545 +      table->field[17]->store((longlong)user_stats->denied_connections);
2546 +      table->field[18]->store((longlong)user_stats->lost_connections);
2547 +      table->field[19]->store((longlong)user_stats->access_denied_errors);
2548 +      table->field[20]->store((longlong)user_stats->empty_queries);
2549 +      if (schema_table_store_record(thd, table))
2550 +      {
2551 +              DBUG_PRINT("error", ("store record error"));
2552 +              DBUG_RETURN(1);
2553 +      }
2554 +  }
2555 +  DBUG_RETURN(0);
2556 +}
2557 +
2558 +/*
2559 +   Process SHOW USER_STATISTICS
2560 +
2561 +   SYNOPSIS
2562 +     mysqld_show_user_stats
2563 +       thd - current thread
2564 +       wild - limit results to the entry for this user
2565 +       with_roles - when true, display role for mapped users
2566 +
2567 +   RETURN
2568 +     0 - OK
2569 +     1 - error
2570 +*/
2571 +
2572 +
2573 +int fill_schema_user_stats(THD* thd, TABLE_LIST* tables, COND* cond)
2574 +{
2575 +  TABLE *table= tables->table;
2576 +  DBUG_ENTER("fill_schema_user_stats");
2577 +
2578 +  if (check_global_access(thd, SUPER_ACL | PROCESS_ACL))
2579 +          DBUG_RETURN(1);
2580 +
2581 +  // Iterates through all the global stats and sends them to the client.
2582 +  // Pattern matching on the client IP is supported.
2583 +
2584 +  mysql_mutex_lock(&LOCK_global_user_client_stats);
2585 +  int result= send_user_stats(thd, &global_user_stats, table);
2586 +  mysql_mutex_unlock(&LOCK_global_user_client_stats);
2587 +  if (result)
2588 +    goto err;
2589 +
2590 +  DBUG_PRINT("exit", ("fill_schema_user_stats result is 0"));
2591 +  DBUG_RETURN(0);
2592 +
2593 + err:
2594 +  DBUG_PRINT("exit", ("fill_schema_user_stats result is 1"));
2595 +  DBUG_RETURN(1);
2596 +}
2597 +
2598 +/*
2599 +   Process SHOW CLIENT_STATISTICS
2600 +
2601 +   SYNOPSIS
2602 +     mysqld_show_client_stats
2603 +       thd - current thread
2604 +       wild - limit results to the entry for this client
2605 +
2606 +   RETURN
2607 +     0 - OK
2608 +     1 - error
2609 +*/
2610 +
2611 +
2612 +int fill_schema_client_stats(THD* thd, TABLE_LIST* tables, COND* cond)
2613 +{
2614 +  TABLE *table= tables->table;
2615 +  DBUG_ENTER("fill_schema_client_stats");
2616 +
2617 +  if (check_global_access(thd, SUPER_ACL | PROCESS_ACL))
2618 +          DBUG_RETURN(1);
2619 +
2620 +  // Iterates through all the global stats and sends them to the client.
2621 +  // Pattern matching on the client IP is supported.
2622 +
2623 +  mysql_mutex_lock(&LOCK_global_user_client_stats);
2624 +  int result= send_user_stats(thd, &global_client_stats, table);
2625 +  mysql_mutex_unlock(&LOCK_global_user_client_stats);
2626 +  if (result)
2627 +    goto err;
2628 +
2629 +  DBUG_PRINT("exit", ("mysqld_show_client_stats result is 0"));
2630 +  DBUG_RETURN(0);
2631 +
2632 + err:
2633 +  DBUG_PRINT("exit", ("mysqld_show_client_stats result is 1"));
2634 +  DBUG_RETURN(1);
2635 +}
2636 +
2637 +int fill_schema_thread_stats(THD* thd, TABLE_LIST* tables, COND* cond)
2638 +{
2639 +  TABLE *table= tables->table;
2640 +  DBUG_ENTER("fill_schema_thread_stats");
2641 +
2642 +  if (check_global_access(thd, SUPER_ACL | PROCESS_ACL))
2643 +          DBUG_RETURN(1);
2644 +
2645 +  // Iterates through all the global stats and sends them to the client.
2646 +  // Pattern matching on the client IP is supported.
2647 +
2648 +  mysql_mutex_lock(&LOCK_global_user_client_stats);
2649 +  int result= send_thread_stats(thd, &global_thread_stats, table);
2650 +  mysql_mutex_unlock(&LOCK_global_user_client_stats);
2651 +  if (result)
2652 +    goto err;
2653 +
2654 +  DBUG_PRINT("exit", ("mysqld_show_thread_stats result is 0"));
2655 +  DBUG_RETURN(0);
2656 +
2657 + err:
2658 +  DBUG_PRINT("exit", ("mysqld_show_thread_stats result is 1"));
2659 +  DBUG_RETURN(1);
2660 +}
2661 +
2662 +// Sends the global table stats back to the client.
2663 +int fill_schema_table_stats(THD* thd, TABLE_LIST* tables, COND* cond)
2664 +{
2665 +  TABLE *table= tables->table;
2666 +  DBUG_ENTER("fill_schema_table_stats");
2667 +  char *table_full_name, *table_schema;
2668 +
2669 +  mysql_mutex_lock(&LOCK_global_table_stats);
2670 +  for (uint i = 0; i < global_table_stats.records; ++i)
2671 +  {
2672 +    restore_record(table, s->default_values);
2673 +    TABLE_STATS *table_stats =
2674 +      (TABLE_STATS *) my_hash_element(&global_table_stats, i);
2675 +
2676 +    table_full_name= thd->strdup(table_stats->table);
2677 +    table_schema= strsep(&table_full_name, ".");
2678 +
2679 +    TABLE_LIST tmp_table;
2680 +    bzero((char *) &tmp_table,sizeof(tmp_table));
2681 +    tmp_table.table_name= table_full_name;
2682 +    tmp_table.db= table_schema;
2683 +    tmp_table.grant.privilege= 0;
2684 +    if (check_access(thd, SELECT_ACL, tmp_table.db,
2685 +                      &tmp_table.grant.privilege, 0, 0,
2686 +                      is_infoschema_db(table_schema)) ||
2687 +         check_grant(thd, SELECT_ACL, &tmp_table, 1, UINT_MAX, 1))
2688 +        continue;
2689 +
2690 +    table->field[0]->store(table_schema, strlen(table_schema), system_charset_info);
2691 +    table->field[1]->store(table_full_name, strlen(table_full_name), system_charset_info);
2692 +    table->field[2]->store((longlong)table_stats->rows_read, TRUE);
2693 +    table->field[3]->store((longlong)table_stats->rows_changed, TRUE);
2694 +    table->field[4]->store((longlong)table_stats->rows_changed_x_indexes, TRUE);
2695 +
2696 +    if (schema_table_store_record(thd, table))
2697 +    {
2698 +      mysql_mutex_unlock(&LOCK_global_table_stats);
2699 +      DBUG_RETURN(1);
2700 +    }
2701 +  }
2702 +  mysql_mutex_unlock(&LOCK_global_table_stats);
2703 +  DBUG_RETURN(0);
2704 +}
2705 +
2706 +// Sends the global index stats back to the client.
2707 +int fill_schema_index_stats(THD* thd, TABLE_LIST* tables, COND* cond)
2708 +{
2709 +  TABLE *table= tables->table;
2710 +  DBUG_ENTER("fill_schema_index_stats");
2711 +  char *index_full_name, *table_schema, *table_name;
2712 +
2713 +  mysql_mutex_lock(&LOCK_global_index_stats);
2714 +  for (uint i = 0; i < global_index_stats.records; ++i)
2715 +  {
2716 +    restore_record(table, s->default_values);
2717 +    INDEX_STATS *index_stats =
2718 +      (INDEX_STATS *) my_hash_element(&global_index_stats, i);
2719 +
2720 +    index_full_name= thd->strdup(index_stats->index);
2721 +    table_schema= strsep(&index_full_name, ".");
2722 +    table_name= strsep(&index_full_name, ".");
2723 +
2724 +    TABLE_LIST tmp_table;
2725 +    bzero((char *) &tmp_table,sizeof(tmp_table));
2726 +    tmp_table.table_name= table_name;
2727 +    tmp_table.db= table_schema;
2728 +    tmp_table.grant.privilege= 0;
2729 +    if (check_access(thd, SELECT_ACL, tmp_table.db,
2730 +                      &tmp_table.grant.privilege, 0, 0,
2731 +                      is_infoschema_db(table_schema)) ||
2732 +         check_grant(thd, SELECT_ACL, &tmp_table, 1, UINT_MAX, 1))
2733 +        continue;
2734 +
2735 +    table->field[0]->store(table_schema, strlen(table_schema), system_charset_info);
2736 +    table->field[1]->store(table_name, strlen(table_name), system_charset_info);
2737 +    table->field[2]->store(index_full_name, strlen(index_full_name), system_charset_info);
2738 +    table->field[3]->store((longlong)index_stats->rows_read, TRUE);
2739 +
2740 +    if (schema_table_store_record(thd, table))
2741 +    {
2742 +      mysql_mutex_unlock(&LOCK_global_index_stats);
2743 +      DBUG_RETURN(1);
2744 +    }
2745 +  }
2746 +  mysql_mutex_unlock(&LOCK_global_index_stats);
2747 +  DBUG_RETURN(0);
2748 +}
2749 +
2750  
2751  /* collect status for all running threads */
2752  
2753 @@ -7465,6 +7781,104 @@
2754  };
2755  
2756  
2757 +ST_FIELD_INFO user_stats_fields_info[]=
2758 +{
2759 +  {"USER", USERNAME_LENGTH, MYSQL_TYPE_STRING, 0, 0, "User", SKIP_OPEN_TABLE},
2760 +  {"TOTAL_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Total_connections", SKIP_OPEN_TABLE},
2761 +  {"CONCURRENT_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Concurrent_connections", SKIP_OPEN_TABLE},
2762 +  {"CONNECTED_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Connected_time", SKIP_OPEN_TABLE},
2763 +  {"BUSY_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Busy_time", SKIP_OPEN_TABLE},
2764 +  {"CPU_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Cpu_time", SKIP_OPEN_TABLE},
2765 +  {"BYTES_RECEIVED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Bytes_received", SKIP_OPEN_TABLE},
2766 +  {"BYTES_SENT", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Bytes_sent", SKIP_OPEN_TABLE},
2767 +  {"BINLOG_BYTES_WRITTEN", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Binlog_bytes_written", SKIP_OPEN_TABLE},
2768 +  {"ROWS_FETCHED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_fetched", SKIP_OPEN_TABLE},
2769 +  {"ROWS_UPDATED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_updated", SKIP_OPEN_TABLE},
2770 +  {"TABLE_ROWS_READ", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Table_rows_read", SKIP_OPEN_TABLE},
2771 +  {"SELECT_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Select_commands", SKIP_OPEN_TABLE},
2772 +  {"UPDATE_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Update_commands", SKIP_OPEN_TABLE},
2773 +  {"OTHER_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Other_commands", SKIP_OPEN_TABLE},
2774 +  {"COMMIT_TRANSACTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Commit_transactions", SKIP_OPEN_TABLE},
2775 +  {"ROLLBACK_TRANSACTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rollback_transactions", SKIP_OPEN_TABLE},
2776 +  {"DENIED_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Denied_connections", SKIP_OPEN_TABLE},
2777 +  {"LOST_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Lost_connections", SKIP_OPEN_TABLE},
2778 +  {"ACCESS_DENIED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Access_denied", SKIP_OPEN_TABLE},
2779 +  {"EMPTY_QUERIES", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Empty_queries", SKIP_OPEN_TABLE},
2780 +  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, 0}
2781 +};
2782 +
2783 +ST_FIELD_INFO client_stats_fields_info[]=
2784 +{
2785 +  {"CLIENT", LIST_PROCESS_HOST_LEN, MYSQL_TYPE_STRING, 0, 0, "Client", SKIP_OPEN_TABLE},
2786 +  {"TOTAL_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Total_connections", SKIP_OPEN_TABLE},
2787 +  {"CONCURRENT_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Concurrent_connections", SKIP_OPEN_TABLE},
2788 +  {"CONNECTED_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Connected_time", SKIP_OPEN_TABLE},
2789 +  {"BUSY_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Busy_time", SKIP_OPEN_TABLE},
2790 +  {"CPU_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Cpu_time", SKIP_OPEN_TABLE},
2791 +  {"BYTES_RECEIVED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Bytes_received", SKIP_OPEN_TABLE},
2792 +  {"BYTES_SENT", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Bytes_sent", SKIP_OPEN_TABLE},
2793 +  {"BINLOG_BYTES_WRITTEN", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Binlog_bytes_written", SKIP_OPEN_TABLE},
2794 +  {"ROWS_FETCHED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_fetched", SKIP_OPEN_TABLE},
2795 +  {"ROWS_UPDATED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_updated", SKIP_OPEN_TABLE},
2796 +  {"TABLE_ROWS_READ", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Table_rows_read", SKIP_OPEN_TABLE},
2797 +  {"SELECT_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Select_commands", SKIP_OPEN_TABLE},
2798 +  {"UPDATE_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Update_commands", SKIP_OPEN_TABLE},
2799 +  {"OTHER_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Other_commands", SKIP_OPEN_TABLE},
2800 +  {"COMMIT_TRANSACTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Commit_transactions", SKIP_OPEN_TABLE},
2801 +  {"ROLLBACK_TRANSACTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rollback_transactions", SKIP_OPEN_TABLE},
2802 +  {"DENIED_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Denied_connections", SKIP_OPEN_TABLE},
2803 +  {"LOST_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Lost_connections", SKIP_OPEN_TABLE},
2804 +  {"ACCESS_DENIED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Access_denied", SKIP_OPEN_TABLE},
2805 +  {"EMPTY_QUERIES", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Empty_queries", SKIP_OPEN_TABLE},
2806 +  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, 0}
2807 +};
2808 +
2809 +ST_FIELD_INFO thread_stats_fields_info[]=
2810 +{
2811 +  {"THREAD_ID", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Thread_id", SKIP_OPEN_TABLE},
2812 +  {"TOTAL_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Total_connections", SKIP_OPEN_TABLE},
2813 +  {"CONCURRENT_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Concurrent_connections", SKIP_OPEN_TABLE},
2814 +  {"CONNECTED_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Connected_time", SKIP_OPEN_TABLE},
2815 +  {"BUSY_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Busy_time", SKIP_OPEN_TABLE},
2816 +  {"CPU_TIME", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Cpu_time", SKIP_OPEN_TABLE},
2817 +  {"BYTES_RECEIVED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Bytes_received", SKIP_OPEN_TABLE},
2818 +  {"BYTES_SENT", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Bytes_sent", SKIP_OPEN_TABLE},
2819 +  {"BINLOG_BYTES_WRITTEN", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Binlog_bytes_written", SKIP_OPEN_TABLE},
2820 +  {"ROWS_FETCHED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_fetched", SKIP_OPEN_TABLE},
2821 +  {"ROWS_UPDATED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_updated", SKIP_OPEN_TABLE},
2822 +  {"TABLE_ROWS_READ", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Table_rows_read", SKIP_OPEN_TABLE},
2823 +  {"SELECT_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Select_commands", SKIP_OPEN_TABLE},
2824 +  {"UPDATE_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Update_commands", SKIP_OPEN_TABLE},
2825 +  {"OTHER_COMMANDS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Other_commands", SKIP_OPEN_TABLE},
2826 +  {"COMMIT_TRANSACTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Commit_transactions", SKIP_OPEN_TABLE},
2827 +  {"ROLLBACK_TRANSACTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rollback_transactions", SKIP_OPEN_TABLE},
2828 +  {"DENIED_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Denied_connections", SKIP_OPEN_TABLE},
2829 +  {"LOST_CONNECTIONS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Lost_connections", SKIP_OPEN_TABLE},
2830 +  {"ACCESS_DENIED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Access_denied", SKIP_OPEN_TABLE},
2831 +  {"EMPTY_QUERIES", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Empty_queries", SKIP_OPEN_TABLE},
2832 +  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, 0}
2833 +};
2834 +
2835 +ST_FIELD_INFO table_stats_fields_info[]=
2836 +{
2837 +  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_schema", SKIP_OPEN_TABLE},
2838 +  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_name", SKIP_OPEN_TABLE},
2839 +  {"ROWS_READ", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_read", SKIP_OPEN_TABLE},
2840 +  {"ROWS_CHANGED", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_changed", SKIP_OPEN_TABLE},
2841 +  {"ROWS_CHANGED_X_INDEXES", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_changed_x_#indexes", SKIP_OPEN_TABLE},
2842 +  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, 0}
2843 +};
2844 +
2845 +ST_FIELD_INFO index_stats_fields_info[]=
2846 +{
2847 +  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_schema", SKIP_OPEN_TABLE},
2848 +  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_name", SKIP_OPEN_TABLE},
2849 +  {"INDEX_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Index_name", SKIP_OPEN_TABLE},
2850 +  {"ROWS_READ", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONG, 0, 0, "Rows_read", SKIP_OPEN_TABLE},
2851 +  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, 0}
2852 +};
2853 +
2854 +
2855  ST_FIELD_INFO processlist_fields_info[]=
2856  {
2857    {"ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Id", SKIP_OPEN_TABLE},
2858 @@ -7654,6 +8068,8 @@
2859  {
2860    {"CHARACTER_SETS", charsets_fields_info, create_schema_table, 
2861     fill_schema_charsets, make_character_sets_old_format, 0, -1, -1, 0, 0},
2862 +  {"CLIENT_STATISTICS", client_stats_fields_info, create_schema_table,
2863 +    fill_schema_client_stats, make_old_format, 0, -1, -1, 0, 0},
2864    {"COLLATIONS", collation_fields_info, create_schema_table, 
2865     fill_schema_collation, make_old_format, 0, -1, -1, 0, 0},
2866    {"COLLATION_CHARACTER_SET_APPLICABILITY", coll_charset_app_fields_info,
2867 @@ -7663,6 +8079,8 @@
2868     OPTIMIZE_I_S_TABLE|OPEN_VIEW_FULL},
2869    {"COLUMN_PRIVILEGES", column_privileges_fields_info, create_schema_table,
2870     fill_schema_column_privileges, 0, 0, -1, -1, 0, 0},
2871 +  {"INDEX_STATISTICS", index_stats_fields_info, create_schema_table,
2872 +   fill_schema_index_stats, make_old_format, 0, -1, -1, 0, 0},
2873    {"ENGINES", engines_fields_info, create_schema_table,
2874     fill_schema_engines, make_old_format, 0, -1, -1, 0, 0},
2875  #ifdef HAVE_EVENT_SCHEDULER
2876 @@ -7735,14 +8153,20 @@
2877     get_all_tables, make_table_names_old_format, 0, 1, 2, 1, 0},
2878    {"TABLE_PRIVILEGES", table_privileges_fields_info, create_schema_table,
2879     fill_schema_table_privileges, 0, 0, -1, -1, 0, 0},
2880 +  {"TABLE_STATISTICS", table_stats_fields_info, create_schema_table,
2881 +    fill_schema_table_stats, make_old_format, 0, -1, -1, 0, 0},
2882    {"TEMPORARY_TABLES", temporary_table_fields_info, create_schema_table,
2883     fill_temporary_tables, make_temporary_tables_old_format, 0, 2, 3, 0,
2884     OPEN_TABLE_ONLY|OPTIMIZE_I_S_TABLE},
2885 +  {"THREAD_STATISTICS", thread_stats_fields_info, create_schema_table,
2886 +    fill_schema_thread_stats, make_old_format, 0, -1, -1, 0, 0},
2887    {"TRIGGERS", triggers_fields_info, create_schema_table,
2888     get_all_tables, make_old_format, get_schema_triggers_record, 5, 6, 0,
2889     OPEN_TRIGGER_ONLY|OPTIMIZE_I_S_TABLE},
2890    {"USER_PRIVILEGES", user_privileges_fields_info, create_schema_table, 
2891     fill_schema_user_privileges, 0, 0, -1, -1, 0, 0},
2892 +  {"USER_STATISTICS", user_stats_fields_info, create_schema_table,
2893 +    fill_schema_user_stats, make_old_format, 0, -1, -1, 0, 0},
2894    {"VARIABLES", variables_fields_info, create_schema_table, fill_variables,
2895     make_old_format, 0, 0, -1, 1, 0},
2896    {"VIEWS", view_fields_info, create_schema_table, 
2897 diff -ruN a/sql/sql_update.cc b/sql/sql_update.cc
2898 --- a/sql/sql_update.cc 2010-12-03 20:58:26.000000000 +0300
2899 +++ b/sql/sql_update.cc 2010-12-31 04:08:17.000000000 +0300
2900 @@ -894,8 +894,10 @@
2901      my_snprintf(buff, sizeof(buff), ER(ER_UPDATE_INFO), (ulong) found,
2902                  (ulong) updated,
2903                  (ulong) thd->warning_info->statement_warn_count());
2904 -    my_ok(thd, (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated,
2905 -          id, buff);
2906 +    ha_rows row_count=
2907 +      (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
2908 +    my_ok(thd, row_count, id, buff);
2909 +    thd->updated_row_count += row_count;
2910      DBUG_PRINT("info",("%ld records updated", (long) updated));
2911    }
2912    thd->count_cuted_fields= CHECK_FIELD_IGNORE;         /* calc cuted fields */
2913 @@ -2136,7 +2138,9 @@
2914      thd->first_successful_insert_id_in_prev_stmt : 0;
2915    my_snprintf(buff, sizeof(buff), ER(ER_UPDATE_INFO),
2916                (ulong) found, (ulong) updated, (ulong) thd->cuted_fields);
2917 -  ::my_ok(thd, (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated,
2918 -          id, buff);
2919 +  ha_rows row_count=
2920 +    (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
2921 +  ::my_ok(thd, row_count, id, buff);
2922 +  thd->updated_row_count+= row_count;
2923    DBUG_RETURN(FALSE);
2924  }
2925 diff -ruN a/sql/sql_yacc.yy b/sql/sql_yacc.yy
2926 --- a/sql/sql_yacc.yy   2010-12-03 20:58:26.000000000 +0300
2927 +++ b/sql/sql_yacc.yy   2010-12-31 05:06:16.000000000 +0300
2928 @@ -864,6 +864,7 @@
2929  %token  CIPHER_SYM
2930  %token  CLASS_ORIGIN_SYM              /* SQL-2003-N */
2931  %token  CLIENT_SYM
2932 +%token  CLIENT_STATS_SYM
2933  %token  CLOSE_SYM                     /* SQL-2003-R */
2934  %token  COALESCE                      /* SQL-2003-N */
2935  %token  CODE_SYM
2936 @@ -1017,6 +1018,7 @@
2937  %token  IMPORT
2938  %token  INDEXES
2939  %token  INDEX_SYM
2940 +%token  INDEX_STATS_SYM
2941  %token  INFILE
2942  %token  INITIAL_SIZE_SYM
2943  %token  INNER_SYM                     /* SQL-2003-R */
2944 @@ -1315,6 +1317,7 @@
2945  %token  TABLESPACE
2946  %token  TABLE_REF_PRIORITY
2947  %token  TABLE_SYM                     /* SQL-2003-R */
2948 +%token  TABLE_STATS_SYM
2949  %token  TABLE_CHECKSUM_SYM
2950  %token  TABLE_NAME_SYM                /* SQL-2003-N */
2951  %token  TEMPORARY                     /* SQL-2003-N */
2952 @@ -1324,6 +1327,7 @@
2953  %token  TEXT_SYM
2954  %token  THAN_SYM
2955  %token  THEN_SYM                      /* SQL-2003-R */
2956 +%token  THREAD_STATS_SYM
2957  %token  TIMESTAMP                     /* SQL-2003-R */
2958  %token  TIMESTAMP_ADD
2959  %token  TIMESTAMP_DIFF
2960 @@ -1361,6 +1365,7 @@
2961  %token  UPGRADE_SYM
2962  %token  USAGE                         /* SQL-2003-N */
2963  %token  USER                          /* SQL-2003-R */
2964 +%token  USER_STATS_SYM
2965  %token  USE_FRM
2966  %token  USE_SYM
2967  %token  USING                         /* SQL-2003-R */
2968 @@ -11109,6 +11114,41 @@
2969               MYSQL_YYABORT;
2970  #endif // HAVE_RESPONSE_TIME_DISTRIBUTION
2971           }
2972 +        | CLIENT_STATS_SYM wild_and_where
2973 +          {
2974 +           LEX *lex= Lex;
2975 +           Lex->sql_command= SQLCOM_SELECT;
2976 +           if (prepare_schema_table(YYTHD, lex, 0, SCH_CLIENT_STATS))
2977 +             MYSQL_YYABORT;
2978 +          }
2979 +        | USER_STATS_SYM wild_and_where
2980 +          {
2981 +           LEX *lex= Lex;
2982 +           lex->sql_command= SQLCOM_SELECT;
2983 +           if (prepare_schema_table(YYTHD, lex, 0, SCH_USER_STATS))
2984 +             MYSQL_YYABORT;
2985 +          }
2986 +        | THREAD_STATS_SYM wild_and_where
2987 +          {
2988 +           LEX *lex= Lex;
2989 +           Lex->sql_command= SQLCOM_SELECT;
2990 +           if (prepare_schema_table(YYTHD, lex, 0, SCH_THREAD_STATS))
2991 +             MYSQL_YYABORT;
2992 +          }
2993 +        | TABLE_STATS_SYM wild_and_where
2994 +          {
2995 +           LEX *lex= Lex;
2996 +           lex->sql_command= SQLCOM_SELECT;
2997 +           if (prepare_schema_table(YYTHD, lex, 0, SCH_TABLE_STATS))
2998 +             MYSQL_YYABORT;
2999 +          }
3000 +        | INDEX_STATS_SYM wild_and_where
3001 +          {
3002 +           LEX *lex= Lex;
3003 +           lex->sql_command= SQLCOM_SELECT;
3004 +           if (prepare_schema_table(YYTHD, lex, 0, SCH_INDEX_STATS))
3005 +             MYSQL_YYABORT;
3006 +          }
3007          | CREATE PROCEDURE_SYM sp_name
3008            {
3009              LEX *lex= Lex;
3010 @@ -11351,6 +11391,16 @@
3011              Lex->type|= REFRESH_QUERY_RESPONSE_TIME;
3012  #endif // HAVE_RESPONSE_TIME_DISTRIBUTION
3013            }
3014 +        | CLIENT_STATS_SYM
3015 +          { Lex->type|= REFRESH_CLIENT_STATS; }
3016 +        | USER_STATS_SYM
3017 +          { Lex->type|= REFRESH_USER_STATS; }
3018 +        | THREAD_STATS_SYM
3019 +          { Lex->type|= REFRESH_THREAD_STATS; }
3020 +        | TABLE_STATS_SYM
3021 +          { Lex->type|= REFRESH_TABLE_STATS; }
3022 +        | INDEX_STATS_SYM
3023 +          { Lex->type|= REFRESH_INDEX_STATS; }
3024          | MASTER_SYM
3025            { Lex->type|= REFRESH_MASTER; }
3026          | DES_KEY_FILE
3027 @@ -12473,6 +12523,7 @@
3028          | CHAIN_SYM                {}
3029          | CHANGED                  {}
3030          | CIPHER_SYM               {}
3031 +        | CLIENT_STATS_SYM         {}
3032          | CLIENT_SYM               {}
3033          | CLASS_ORIGIN_SYM         {}
3034          | COALESCE                 {}
3035 @@ -12541,6 +12592,7 @@
3036          | HOSTS_SYM                {}
3037          | HOUR_SYM                 {}
3038          | IDENTIFIED_SYM           {}
3039 +        | INDEX_STATS_SYM          {}
3040          | IGNORE_SERVER_IDS_SYM    {}
3041          | INVOKER_SYM              {}
3042          | IMPORT                   {}
3043 @@ -12692,6 +12744,7 @@
3044          | SUSPEND_SYM              {}
3045          | SWAPS_SYM                {}
3046          | SWITCHES_SYM             {}
3047 +        | TABLE_STATS_SYM          {}
3048          | TABLE_NAME_SYM           {}
3049          | TABLES                   {}
3050          | TABLE_CHECKSUM_SYM       {}
3051 @@ -12717,6 +12770,7 @@
3052          | UNKNOWN_SYM              {}
3053          | UNTIL_SYM                {}
3054          | USER                     {}
3055 +        | USER_STATS_SYM           {}
3056          | USE_FRM                  {}
3057          | VARIABLES                {}
3058          | VIEW_SYM                 {}
3059 diff -ruN a/sql/structs.h b/sql/structs.h
3060 --- a/sql/structs.h     2010-12-03 20:58:26.000000000 +0300
3061 +++ b/sql/structs.h     2010-12-31 05:12:04.000000000 +0300
3062 @@ -25,6 +25,7 @@
3063  #include "my_time.h"                   /* enum_mysql_timestamp_type */
3064  #include "thr_lock.h"                  /* thr_lock_type */
3065  #include "my_base.h"                   /* ha_rows, ha_key_alg */
3066 +#include "mysql_com.h"
3067  
3068  struct TABLE;
3069  class Field;
3070 @@ -218,6 +219,171 @@
3071    USER_RESOURCES user_resources;
3072  } USER_CONN;
3073  
3074 +typedef struct st_user_stats {
3075 +  char user[max(USERNAME_LENGTH, LIST_PROCESS_HOST_LEN) + 1];
3076 +  // Account name the user is mapped to when this is a user from mapped_user.
3077 +  // Otherwise, the same value as user.
3078 +  char priv_user[max(USERNAME_LENGTH, LIST_PROCESS_HOST_LEN) + 1];
3079 +  uint total_connections;
3080 +  uint concurrent_connections;
3081 +  time_t connected_time;  // in seconds
3082 +  double busy_time;       // in seconds
3083 +  double cpu_time;        // in seconds
3084 +  ulonglong bytes_received;
3085 +  ulonglong bytes_sent;
3086 +  ulonglong binlog_bytes_written;
3087 +  ha_rows rows_fetched, rows_updated, rows_read;
3088 +  ulonglong select_commands, update_commands, other_commands;
3089 +  ulonglong commit_trans, rollback_trans;
3090 +  ulonglong denied_connections, lost_connections;
3091 +  ulonglong access_denied_errors;
3092 +  ulonglong empty_queries;
3093 +} USER_STATS;
3094 +
3095 +/* Lookup function for my_hash tables with USER_STATS entries */
3096 +extern "C" uchar *get_key_user_stats(USER_STATS *user_stats, size_t *length,
3097 +                                my_bool not_used __attribute__((unused)));
3098 +
3099 +/* Free all memory for a my_hash table with USER_STATS entries */
3100 +extern void free_user_stats(USER_STATS* user_stats);
3101 +
3102 +/* Intialize an instance of USER_STATS */
3103 +extern void
3104 +init_user_stats(USER_STATS *user_stats,
3105 +                const char *user,
3106 +                const char *priv_user,
3107 +                uint total_connections,
3108 +                uint concurrent_connections,
3109 +                time_t connected_time,
3110 +                double busy_time,
3111 +                double cpu_time,
3112 +                ulonglong bytes_received,
3113 +                ulonglong bytes_sent,
3114 +                ulonglong binlog_bytes_written,
3115 +                ha_rows rows_fetched,
3116 +                ha_rows rows_updated,
3117 +                ha_rows rows_read,
3118 +                ulonglong select_commands,
3119 +                ulonglong update_commands,
3120 +                ulonglong other_commands,
3121 +                ulonglong commit_trans,
3122 +                ulonglong rollback_trans,
3123 +                ulonglong denied_connections,
3124 +                ulonglong lost_connections,
3125 +                ulonglong access_denied_errors,
3126 +                ulonglong empty_queries);
3127 +
3128 +/* Increment values of an instance of USER_STATS */
3129 +extern void
3130 +add_user_stats(USER_STATS *user_stats,
3131 +               uint total_connections,
3132 +               uint concurrent_connections,
3133 +               time_t connected_time,
3134 +               double busy_time,
3135 +               double cpu_time,
3136 +               ulonglong bytes_received,
3137 +               ulonglong bytes_sent,
3138 +               ulonglong binlog_bytes_written,
3139 +               ha_rows rows_fetched,
3140 +               ha_rows rows_updated,
3141 +               ha_rows rows_read,
3142 +               ulonglong select_commands,
3143 +               ulonglong update_commands,
3144 +               ulonglong other_commands,
3145 +               ulonglong commit_trans,
3146 +               ulonglong rollback_trans,
3147 +               ulonglong denied_connections,
3148 +               ulonglong lost_connections,
3149 +               ulonglong access_denied_errors,
3150 +               ulonglong empty_queries);
3151 +
3152 +typedef struct st_thread_stats {
3153 +  my_thread_id id;
3154 +  uint total_connections;
3155 +  uint concurrent_connections;
3156 +  time_t connected_time;  // in seconds
3157 +  double busy_time;       // in seconds
3158 +  double cpu_time;        // in seconds
3159 +  ulonglong bytes_received;
3160 +  ulonglong bytes_sent;
3161 +  ulonglong binlog_bytes_written;
3162 +  ha_rows rows_fetched, rows_updated, rows_read;
3163 +  ulonglong select_commands, update_commands, other_commands;
3164 +  ulonglong commit_trans, rollback_trans;
3165 +  ulonglong denied_connections, lost_connections;
3166 +  ulonglong access_denied_errors;
3167 +  ulonglong empty_queries;
3168 +} THREAD_STATS;
3169 +
3170 +/* Lookup function for my_hash tables with THREAD_STATS entries */
3171 +extern "C" uchar *get_key_thread_stats(THREAD_STATS *thread_stats, size_t *length,
3172 +                                my_bool not_used __attribute__((unused)));
3173 +
3174 +/* Free all memory for a my_hash table with THREAD_STATS entries */
3175 +extern void free_thread_stats(THREAD_STATS* thread_stats);
3176 +
3177 +/* Intialize an instance of THREAD_STATS */
3178 +extern void
3179 +init_thread_stats(THREAD_STATS *thread_stats,
3180 +                my_thread_id id,
3181 +                uint total_connections,
3182 +                uint concurrent_connections,
3183 +                time_t connected_time,
3184 +                double busy_time,
3185 +                double cpu_time,
3186 +                ulonglong bytes_received,
3187 +                ulonglong bytes_sent,
3188 +                ulonglong binlog_bytes_written,
3189 +                ha_rows rows_fetched,
3190 +                ha_rows rows_updated,
3191 +                ha_rows rows_read,
3192 +                ulonglong select_commands,
3193 +                ulonglong update_commands,
3194 +                ulonglong other_commands,
3195 +                ulonglong commit_trans,
3196 +                ulonglong rollback_trans,
3197 +                ulonglong denied_connections,
3198 +                ulonglong lost_connections,
3199 +                ulonglong access_denied_errors,
3200 +                ulonglong empty_queries);
3201 +
3202 +/* Increment values of an instance of THREAD_STATS */
3203 +extern void
3204 +add_thread_stats(THREAD_STATS *thread_stats,
3205 +               uint total_connections,
3206 +               uint concurrent_connections,
3207 +               time_t connected_time,
3208 +               double busy_time,
3209 +               double cpu_time,
3210 +               ulonglong bytes_received,
3211 +               ulonglong bytes_sent,
3212 +               ulonglong binlog_bytes_written,
3213 +               ha_rows rows_fetched,
3214 +               ha_rows rows_updated,
3215 +               ha_rows rows_read,
3216 +               ulonglong select_commands,
3217 +               ulonglong update_commands,
3218 +               ulonglong other_commands,
3219 +               ulonglong commit_trans,
3220 +               ulonglong rollback_trans,
3221 +               ulonglong denied_connections,
3222 +               ulonglong lost_connections,
3223 +               ulonglong access_denied_errors,
3224 +               ulonglong empty_queries);
3225 +
3226 +typedef struct st_table_stats {
3227 +  char table[NAME_LEN * 2 + 2];  // [db] + '.' + [table] + '\0'
3228 +  ulonglong rows_read, rows_changed;
3229 +  ulonglong rows_changed_x_indexes;
3230 +  /* Stores enum db_type, but forward declarations cannot be done */
3231 +  int engine_type;
3232 +} TABLE_STATS;
3233 +
3234 +typedef struct st_index_stats {
3235 +  char index[NAME_LEN * 3 + 3];  // [db] + '.' + [table] + '.' + [index] + '\0'
3236 +  ulonglong rows_read;
3237 +} INDEX_STATS;
3238 +
3239         /* Bits in form->update */
3240  #define REG_MAKE_DUPP          1       /* Make a copy of record when read */
3241  #define REG_NEW_RECORD         2       /* Write a new record if not found */
3242 diff -ruN a/sql/sys_vars.cc b/sql/sys_vars.cc
3243 --- a/sql/sys_vars.cc   2010-12-03 20:58:26.000000000 +0300
3244 +++ b/sql/sys_vars.cc   2010-12-30 02:22:25.000000000 +0300
3245 @@ -1547,6 +1547,17 @@
3246         NO_MUTEX_GUARD, NOT_IN_BINLOG,
3247         ON_CHECK(check_read_only), ON_UPDATE(fix_read_only));
3248  
3249 +static Sys_var_mybool Sys_userstat_running(
3250 +       "userstat_running",
3251 +       "Control USER_STATISTICS, CLIENT_STATISTICS, THREAD_STATISTICS, "
3252 +       "INDEX_STATISTICS and TABLE_STATISTICS running",
3253 +       GLOBAL_VAR(opt_userstat_running), CMD_LINE(OPT_ARG), DEFAULT(FALSE));
3254 +
3255 +static Sys_var_mybool Sys_thread_statistics(
3256 +       "thread_statistics",
3257 +       "Control TABLE_STATISTICS running, when userstat_running is enabled",
3258 +       GLOBAL_VAR(opt_thread_statistics), CMD_LINE(OPT_ARG), DEFAULT(FALSE));
3259 +
3260  // Small lower limit to be able to test MRR
3261  static Sys_var_ulong Sys_read_rnd_buff_size(
3262         "read_rnd_buffer_size",
3263 diff -ruN a/storage/myisam/ha_myisam.cc b/storage/myisam/ha_myisam.cc
3264 --- a/storage/myisam/ha_myisam.cc       2010-12-03 20:58:26.000000000 +0300
3265 +++ b/storage/myisam/ha_myisam.cc       2010-12-31 05:58:01.000000000 +0300
3266 @@ -769,6 +769,7 @@
3267  
3268  int ha_myisam::write_row(uchar *buf)
3269  {
3270 +  int error;
3271    ha_statistic_increment(&SSV::ha_write_count);
3272  
3273    /* If we have a timestamp column, update it to the current time */
3274 @@ -781,11 +782,13 @@
3275    */
3276    if (table->next_number_field && buf == table->record[0])
3277    {
3278 -    int error;
3279      if ((error= update_auto_increment()))
3280        return error;
3281    }
3282 -  return mi_write(file,buf);
3283 +  error=mi_write(file,buf);
3284 +  if (!error)
3285 +    rows_changed++;
3286 +  return error;
3287  }
3288  
3289  int ha_myisam::check(THD* thd, HA_CHECK_OPT* check_opt)
3290 @@ -1536,16 +1539,24 @@
3291  
3292  int ha_myisam::update_row(const uchar *old_data, uchar *new_data)
3293  {
3294 +  int error;
3295    ha_statistic_increment(&SSV::ha_update_count);
3296    if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
3297      table->timestamp_field->set_time();
3298 -  return mi_update(file,old_data,new_data);
3299 +  error=mi_update(file,old_data,new_data);
3300 +  if (!error)
3301 +    rows_changed++;
3302 +  return error;
3303  }
3304  
3305  int ha_myisam::delete_row(const uchar *buf)
3306  {
3307 +  int error;
3308    ha_statistic_increment(&SSV::ha_delete_count);
3309 -  return mi_delete(file,buf);
3310 +  error=mi_delete(file,buf);
3311 +  if (!error)
3312 +    rows_changed++;
3313 +  return error;
3314  }
3315  
3316  int ha_myisam::index_read_map(uchar *buf, const uchar *key,
3317 @@ -1557,6 +1568,14 @@
3318    ha_statistic_increment(&SSV::ha_read_key_count);
3319    int error=mi_rkey(file, buf, active_index, key, keypart_map, find_flag);
3320    table->status=error ? STATUS_NOT_FOUND: 0;
3321 +  if (!error)
3322 +  {
3323 +    rows_read++;
3324 +
3325 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3326 +    if (inx >= 0 && inx < MAX_KEY)
3327 +      index_rows_read[inx]++;
3328 +  }
3329    MYSQL_INDEX_READ_ROW_DONE(error);
3330    return error;
3331  }
3332 @@ -1569,6 +1588,14 @@
3333    ha_statistic_increment(&SSV::ha_read_key_count);
3334    int error=mi_rkey(file, buf, index, key, keypart_map, find_flag);
3335    table->status=error ? STATUS_NOT_FOUND: 0;
3336 +  if (!error)
3337 +  {
3338 +    rows_read++;
3339 +
3340 +    int inx = index;
3341 +    if (inx >= 0 && inx < MAX_KEY)
3342 +      index_rows_read[inx]++;
3343 +  }
3344    MYSQL_INDEX_READ_ROW_DONE(error);
3345    return error;
3346  }
3347 @@ -1583,6 +1610,14 @@
3348    int error=mi_rkey(file, buf, active_index, key, keypart_map,
3349                      HA_READ_PREFIX_LAST);
3350    table->status=error ? STATUS_NOT_FOUND: 0;
3351 +  if (!error)
3352 +  {
3353 +    rows_read++;
3354 +
3355 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3356 +    if (inx >= 0 && inx < MAX_KEY)
3357 +      index_rows_read[inx]++;
3358 +  }
3359    MYSQL_INDEX_READ_ROW_DONE(error);
3360    DBUG_RETURN(error);
3361  }
3362 @@ -1594,6 +1629,13 @@
3363    ha_statistic_increment(&SSV::ha_read_next_count);
3364    int error=mi_rnext(file,buf,active_index);
3365    table->status=error ? STATUS_NOT_FOUND: 0;
3366 +  if (!error) {
3367 +    rows_read++;
3368 +
3369 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3370 +    if (inx >= 0 && inx < MAX_KEY)
3371 +      index_rows_read[inx]++;
3372 +  }
3373    MYSQL_INDEX_READ_ROW_DONE(error);
3374    return error;
3375  }
3376 @@ -1605,6 +1647,13 @@
3377    ha_statistic_increment(&SSV::ha_read_prev_count);
3378    int error=mi_rprev(file,buf, active_index);
3379    table->status=error ? STATUS_NOT_FOUND: 0;
3380 +  if (!error) {
3381 +    rows_read++;
3382 +
3383 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3384 +    if (inx >= 0 && inx < MAX_KEY)
3385 +      index_rows_read[inx]++;
3386 +  }
3387    MYSQL_INDEX_READ_ROW_DONE(error);
3388    return error;
3389  }
3390 @@ -1616,6 +1665,14 @@
3391    ha_statistic_increment(&SSV::ha_read_first_count);
3392    int error=mi_rfirst(file, buf, active_index);
3393    table->status=error ? STATUS_NOT_FOUND: 0;
3394 +  if (!error)
3395 +  {
3396 +    rows_read++;
3397 +
3398 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3399 +    if (inx >= 0 && inx < MAX_KEY)
3400 +      index_rows_read[inx]++;
3401 +  }
3402    MYSQL_INDEX_READ_ROW_DONE(error);
3403    return error;
3404  }
3405 @@ -1627,6 +1684,14 @@
3406    ha_statistic_increment(&SSV::ha_read_last_count);
3407    int error=mi_rlast(file, buf, active_index);
3408    table->status=error ? STATUS_NOT_FOUND: 0;
3409 +  if (!error)
3410 +  {
3411 +    rows_read++;
3412 +
3413 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3414 +    if (inx >= 0 && inx < MAX_KEY)
3415 +      index_rows_read[inx]++;
3416 +  }
3417    MYSQL_INDEX_READ_ROW_DONE(error);
3418    return error;
3419  }
3420 @@ -1644,6 +1709,14 @@
3421      error= mi_rnext_same(file,buf);
3422    } while (error == HA_ERR_RECORD_DELETED);
3423    table->status=error ? STATUS_NOT_FOUND: 0;
3424 +  if (!error)
3425 +  {
3426 +    rows_read++;
3427 +
3428 +    int inx = (active_index == MAX_KEY) ? file->lastinx : active_index;
3429 +    if (inx >= 0 && inx < MAX_KEY)
3430 +      index_rows_read[inx]++;
3431 +  }
3432    MYSQL_INDEX_READ_ROW_DONE(error);
3433    return error;
3434  }
3435 @@ -1663,6 +1736,8 @@
3436    ha_statistic_increment(&SSV::ha_read_rnd_next_count);
3437    int error=mi_scan(file, buf);
3438    table->status=error ? STATUS_NOT_FOUND: 0;
3439 +  if (!error)
3440 +    rows_read++;
3441    MYSQL_READ_ROW_DONE(error);
3442    return error;
3443  }
3444 @@ -1679,6 +1754,8 @@
3445    ha_statistic_increment(&SSV::ha_read_rnd_count);
3446    int error=mi_rrnd(file, buf, my_get_ptr(pos,ref_length));
3447    table->status=error ? STATUS_NOT_FOUND: 0;
3448 +  if (!error)
3449 +    rows_read++;
3450    MYSQL_READ_ROW_DONE(error);
3451    return error;
3452  }
This page took 0.280252 seconds and 4 git commands to generate.