sql_show.cc 205 KB
Newer Older
monty@mysql.com's avatar
monty@mysql.com committed
1
/* Copyright (C) 2000-2004 MySQL AB
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
11

bk@work.mysql.com's avatar
bk@work.mysql.com committed
12 13 14 15 16 17 18 19
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/* Function with list databases, tables or fields */

#include "mysql_priv.h"
20
#include "sql_select.h"                         // For select_describe
21
#include "sql_show.h"
22
#include "repl_failsafe.h"
23
#include "sp.h"
24
#include "sp_head.h"
25
#include "sql_trigger.h"
brian@grrr.local's avatar
brian@grrr.local committed
26
#include "authors.h"
27
#include "contributors.h"
28
#include "events.h"
29
#include "event_data_objects.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
30
#include <my_dir.h>
31

32 33 34
#ifdef WITH_PARTITION_STORAGE_ENGINE
#include "ha_partition.h"
#endif
35 36 37 38 39 40
enum enum_i_s_events_fields
{
  ISE_EVENT_CATALOG= 0,
  ISE_EVENT_SCHEMA,
  ISE_EVENT_NAME,
  ISE_DEFINER,
41
  ISE_TIME_ZONE,
42 43 44 45 46 47 48 49 50 51 52 53 54 55
  ISE_EVENT_BODY,
  ISE_EVENT_DEFINITION,
  ISE_EVENT_TYPE,
  ISE_EXECUTE_AT,
  ISE_INTERVAL_VALUE,
  ISE_INTERVAL_FIELD,
  ISE_SQL_MODE,
  ISE_STARTS,
  ISE_ENDS,
  ISE_STATUS,
  ISE_ON_COMPLETION,
  ISE_CREATED,
  ISE_LAST_ALTERED,
  ISE_LAST_EXECUTED,
56
  ISE_EVENT_COMMENT,
57 58 59 60
  ISE_ORIGINATOR,
  ISE_CLIENT_CS,
  ISE_CONNECTION_CL,
  ISE_DB_CL
61 62
};

63
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
64 65 66 67 68
static const char *grant_names[]={
  "select","insert","update","delete","create","drop","reload","shutdown",
  "process","file","grant","references","index","alter"};

static TYPELIB grant_types = { sizeof(grant_names)/sizeof(char **),
69
                               "grant_types",
70
                               grant_names, NULL};
71
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
72

73 74 75
static void store_key_options(THD *thd, String *packet, TABLE *table,
                              KEY *key_info);

76 77
static void
append_algorithm(TABLE_LIST *table, String *buff);
78

tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
79

80
/***************************************************************************
81
** List all table types supported
82 83
***************************************************************************/

84 85
static int make_version_string(char *buf, int buf_length, uint version)
{
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
86
  return my_snprintf(buf, buf_length, "%d.%d", version>>8,version&0xff);
87 88
}

antony@ppcg5.local's avatar
antony@ppcg5.local committed
89
static my_bool show_plugins(THD *thd, plugin_ref plugin,
90 91 92
                            void *arg)
{
  TABLE *table= (TABLE*) arg;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
93 94
  struct st_mysql_plugin *plug= plugin_decl(plugin);
  struct st_plugin_dl *plugin_dl= plugin_dlib(plugin);
95 96 97 98 99
  CHARSET_INFO *cs= system_charset_info;
  char version_buf[20];

  restore_record(table, s->default_values);

antony@ppcg5.local's avatar
antony@ppcg5.local committed
100 101
  table->field[0]->store(plugin_name(plugin)->str,
                         plugin_name(plugin)->length, cs);
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
102 103 104 105 106

  table->field[1]->store(version_buf,
        make_version_string(version_buf, sizeof(version_buf), plug->version),
        cs);

serg@sergbook.mysql.com's avatar
fixes  
serg@sergbook.mysql.com committed
107

antony@ppcg5.local's avatar
antony@ppcg5.local committed
108
  switch (plugin_state(plugin)) {
109 110
  /* case PLUGIN_IS_FREED: does not happen */
  case PLUGIN_IS_DELETED:
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
111
    table->field[2]->store(STRING_WITH_LEN("DELETED"), cs);
112 113
    break;
  case PLUGIN_IS_UNINITIALIZED:
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
114
    table->field[2]->store(STRING_WITH_LEN("INACTIVE"), cs);
115 116
    break;
  case PLUGIN_IS_READY:
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
117
    table->field[2]->store(STRING_WITH_LEN("ACTIVE"), cs);
118 119 120 121 122
    break;
  default:
    DBUG_ASSERT(0);
  }

serg@serg.mylan's avatar
serg@serg.mylan committed
123 124 125
  table->field[3]->store(plugin_type_names[plug->type].str,
                         plugin_type_names[plug->type].length,
                         cs);
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
126
  table->field[4]->store(version_buf,
serg@serg.mylan's avatar
serg@serg.mylan committed
127
        make_version_string(version_buf, sizeof(version_buf),
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
128
                            *(uint *)plug->info), cs);
129

antony@ppcg5.local's avatar
antony@ppcg5.local committed
130
  if (plugin_dl)
131
  {
antony@ppcg5.local's avatar
antony@ppcg5.local committed
132
    table->field[5]->store(plugin_dl->dl.str, plugin_dl->dl.length, cs);
133
    table->field[5]->set_notnull();
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
134
    table->field[6]->store(version_buf,
serg@serg.mylan's avatar
serg@serg.mylan committed
135
          make_version_string(version_buf, sizeof(version_buf),
antony@ppcg5.local's avatar
antony@ppcg5.local committed
136
                              plugin_dl->version),
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
137 138
          cs);
    table->field[6]->set_notnull();
139 140
  }
  else
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
141
  {
142
    table->field[5]->set_null();
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
143 144 145 146
    table->field[6]->set_null();
  }


147 148
  if (plug->author)
  {
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
149 150
    table->field[7]->store(plug->author, strlen(plug->author), cs);
    table->field[7]->set_notnull();
151 152
  }
  else
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
153
    table->field[7]->set_null();
154 155 156

  if (plug->descr)
  {
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
157 158
    table->field[8]->store(plug->descr, strlen(plug->descr), cs);
    table->field[8]->set_notnull();
159 160
  }
  else
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
161
    table->field[8]->set_null();
162

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  switch (plug->license) {
  case PLUGIN_LICENSE_GPL:
    table->field[9]->store(PLUGIN_LICENSE_GPL_STRING, 
                           strlen(PLUGIN_LICENSE_GPL_STRING), cs);
    break;
  case PLUGIN_LICENSE_BSD:
    table->field[9]->store(PLUGIN_LICENSE_BSD_STRING, 
                           strlen(PLUGIN_LICENSE_BSD_STRING), cs);
    break;
  default:
    table->field[9]->store(PLUGIN_LICENSE_PROPRIETARY_STRING, 
                           strlen(PLUGIN_LICENSE_PROPRIETARY_STRING), cs);
    break;
  }
  table->field[9]->set_notnull();

179 180 181 182 183 184 185 186 187
  return schema_table_store_record(thd, table);
}


int fill_plugins(THD *thd, TABLE_LIST *tables, COND *cond)
{
  DBUG_ENTER("fill_plugins");
  TABLE *table= tables->table;

188 189
  if (plugin_foreach_with_mask(thd, show_plugins, MYSQL_ANY_PLUGIN,
                               ~PLUGIN_IS_FREED, table))
190
    DBUG_RETURN(1);
191

192 193 194 195
  DBUG_RETURN(0);
}


brian@grrr.local's avatar
brian@grrr.local committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
/***************************************************************************
** List all Authors.
** If you can update it, you get to be in it :)
***************************************************************************/

bool mysqld_show_authors(THD *thd)
{
  List<Item> field_list;
  Protocol *protocol= thd->protocol;
  DBUG_ENTER("mysqld_show_authors");

  field_list.push_back(new Item_empty_string("Name",40));
  field_list.push_back(new Item_empty_string("Location",40));
  field_list.push_back(new Item_empty_string("Comment",80));

  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
    DBUG_RETURN(TRUE);

  show_table_authors_st *authors;
  for (authors= show_table_authors; authors->name; authors++)
  {
    protocol->prepare_for_resend();
    protocol->store(authors->name, system_charset_info);
    protocol->store(authors->location, system_charset_info);
    protocol->store(authors->comment, system_charset_info);
    if (protocol->write())
      DBUG_RETURN(TRUE);
  }
  send_eof(thd);
  DBUG_RETURN(FALSE);
}
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

/***************************************************************************
** List all Contributors.
** Please get permission before updating
***************************************************************************/

bool mysqld_show_contributors(THD *thd)
{
  List<Item> field_list;
  Protocol *protocol= thd->protocol;
  DBUG_ENTER("mysqld_show_contributors");

  field_list.push_back(new Item_empty_string("Name",40));
  field_list.push_back(new Item_empty_string("Location",40));
  field_list.push_back(new Item_empty_string("Comment",80));

  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
    DBUG_RETURN(TRUE);

  show_table_contributors_st *contributors;
  for (contributors= show_table_contributors; contributors->name; contributors++)
  {
    protocol->prepare_for_resend();
    protocol->store(contributors->name, system_charset_info);
    protocol->store(contributors->location, system_charset_info);
    protocol->store(contributors->comment, system_charset_info);
    if (protocol->write())
      DBUG_RETURN(TRUE);
  }
  send_eof(thd);
  DBUG_RETURN(FALSE);
}


264
/***************************************************************************
265
 List all privileges supported
266 267
***************************************************************************/

268 269 270 271
struct show_privileges_st {
  const char *privilege;
  const char *context;
  const char *comment;
272 273
};

274 275
static struct show_privileges_st sys_privileges[]=
{
276
  {"Alter", "Tables",  "To alter the table"},
277
  {"Alter routine", "Functions,Procedures",  "To alter or drop stored functions/procedures"},
278
  {"Create", "Databases,Tables,Indexes",  "To create new databases and tables"},
279
  {"Create routine","Functions,Procedures","To use CREATE FUNCTION/PROCEDURE"},
paul@kite-hub.kitebird.com's avatar
paul@kite-hub.kitebird.com committed
280 281
  {"Create temporary tables","Databases","To use CREATE TEMPORARY TABLE"},
  {"Create view", "Tables",  "To create new views"},
282
  {"Create user", "Server Admin",  "To create new users"},
283
  {"Delete", "Tables",  "To delete existing rows"},
paul@kite-hub.kitebird.com's avatar
paul@kite-hub.kitebird.com committed
284
  {"Drop", "Databases,Tables", "To drop databases, tables, and views"},
285
  {"Event","Server Admin","To create, alter, drop and execute events"},
286
  {"Execute", "Functions,Procedures", "To execute stored routines"},
287
  {"File", "File access on server",   "To read and write files on the server"},
288
  {"Grant option",  "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"},
289 290 291 292
  {"Index", "Tables",  "To create or drop indexes"},
  {"Insert", "Tables",  "To insert data into tables"},
  {"Lock tables","Databases","To use LOCK TABLES (together with SELECT privilege)"},
  {"Process", "Server Admin", "To view the plain text of currently executing queries"},
293
  {"References", "Databases,Tables", "To have references on tables"},
294 295 296 297 298
  {"Reload", "Server Admin", "To reload or refresh tables, logs and privileges"},
  {"Replication client","Server Admin","To ask where the slave or master servers are"},
  {"Replication slave","Server Admin","To read binary log events from the master"},
  {"Select", "Tables",  "To retrieve rows from table"},
  {"Show databases","Server Admin","To see all databases with SHOW DATABASES"},
paul@kite-hub.kitebird.com's avatar
paul@kite-hub.kitebird.com committed
299 300
  {"Show view","Tables","To see views with SHOW CREATE VIEW"},
  {"Shutdown","Server Admin", "To shut down the server"},
301
  {"Super","Server Admin","To use KILL thread, SET GLOBAL, CHANGE MASTER, etc."},
302
  {"Trigger","Tables", "To use triggers"},
303 304
  {"Update", "Tables",  "To update existing rows"},
  {"Usage","Server Admin","No privileges - allow connect only"},
305 306 307
  {NullS, NullS, NullS}
};

308
bool mysqld_show_privileges(THD *thd)
309 310
{
  List<Item> field_list;
311
  Protocol *protocol= thd->protocol;
312 313 314 315
  DBUG_ENTER("mysqld_show_privileges");

  field_list.push_back(new Item_empty_string("Privilege",10));
  field_list.push_back(new Item_empty_string("Context",15));
316
  field_list.push_back(new Item_empty_string("Comment",NAME_CHAR_LEN));
317

318 319
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
320
    DBUG_RETURN(TRUE);
321

322 323
  show_privileges_st *privilege= sys_privileges;
  for (privilege= sys_privileges; privilege->privilege ; privilege++)
324
  {
325
    protocol->prepare_for_resend();
326 327 328
    protocol->store(privilege->privilege, system_charset_info);
    protocol->store(privilege->context, system_charset_info);
    protocol->store(privilege->comment, system_charset_info);
329
    if (protocol->write())
330
      DBUG_RETURN(TRUE);
331
  }
332
  send_eof(thd);
333
  DBUG_RETURN(FALSE);
334 335 336 337
}


/***************************************************************************
338
  List all column types
339 340
***************************************************************************/

341 342
struct show_column_type_st
{
343 344
  const char *type;
  uint size;
345 346 347 348 349 350 351 352 353 354 355 356
  const char *min_value;
  const char *max_value;
  uint precision;
  uint scale;
  const char *nullable;
  const char *auto_increment;
  const char *unsigned_attr;
  const char *zerofill;
  const char *searchable;
  const char *case_sensitivity;
  const char *default_value;
  const char *comment;
357
};
358 359 360 361 362

/* TODO: Add remaning types */

static struct show_column_type_st sys_column_types[]=
{
363 364
  {"tinyint",
    1,  "-128",  "127",  0,  0,  "YES",  "YES",
365 366
    "NO",   "YES", "YES",  "NO",  "NULL,0",
    "A very small integer"},
367
  {"tinyint unsigned",
368 369
    1,  "0"   ,  "255",  0,  0,  "YES",  "YES",
    "YES",  "YES",  "YES",  "NO",  "NULL,0",
370 371 372
    "A very small integer"},
};

373
bool mysqld_show_column_types(THD *thd)
374 375
{
  List<Item> field_list;
376
  Protocol *protocol= thd->protocol;
377 378 379
  DBUG_ENTER("mysqld_show_column_types");

  field_list.push_back(new Item_empty_string("Type",30));
380 381
  field_list.push_back(new Item_int("Size",(longlong) 1,
                                    MY_INT64_NUM_DECIMAL_DIGITS));
382 383
  field_list.push_back(new Item_empty_string("Min_Value",20));
  field_list.push_back(new Item_empty_string("Max_Value",20));
384 385
  field_list.push_back(new Item_return_int("Prec", 4, MYSQL_TYPE_SHORT));
  field_list.push_back(new Item_return_int("Scale", 4, MYSQL_TYPE_SHORT));
386 387 388 389 390 391
  field_list.push_back(new Item_empty_string("Nullable",4));
  field_list.push_back(new Item_empty_string("Auto_Increment",4));
  field_list.push_back(new Item_empty_string("Unsigned",4));
  field_list.push_back(new Item_empty_string("Zerofill",4));
  field_list.push_back(new Item_empty_string("Searchable",4));
  field_list.push_back(new Item_empty_string("Case_Sensitive",4));
392 393
  field_list.push_back(new Item_empty_string("Default",NAME_CHAR_LEN));
  field_list.push_back(new Item_empty_string("Comment",NAME_CHAR_LEN));
394

395 396
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
397
    DBUG_RETURN(TRUE);
398

399
  /* TODO: Change the loop to not use 'i' */
400 401
  for (uint i=0; i < sizeof(sys_column_types)/sizeof(sys_column_types[0]); i++)
  {
402
    protocol->prepare_for_resend();
403
    protocol->store(sys_column_types[i].type, system_charset_info);
404
    protocol->store((ulonglong) sys_column_types[i].size);
405 406
    protocol->store(sys_column_types[i].min_value, system_charset_info);
    protocol->store(sys_column_types[i].max_value, system_charset_info);
407 408
    protocol->store_short((longlong) sys_column_types[i].precision);
    protocol->store_short((longlong) sys_column_types[i].scale);
409 410 411 412 413 414 415 416
    protocol->store(sys_column_types[i].nullable, system_charset_info);
    protocol->store(sys_column_types[i].auto_increment, system_charset_info);
    protocol->store(sys_column_types[i].unsigned_attr, system_charset_info);
    protocol->store(sys_column_types[i].zerofill, system_charset_info);
    protocol->store(sys_column_types[i].searchable, system_charset_info);
    protocol->store(sys_column_types[i].case_sensitivity, system_charset_info);
    protocol->store(sys_column_types[i].default_value, system_charset_info);
    protocol->store(sys_column_types[i].comment, system_charset_info);
417
    if (protocol->write())
418
      DBUG_RETURN(TRUE);
419
  }
420
  send_eof(thd);
421
  DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
422 423 424
}


425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
/*
  find_files() - find files in a given directory.

  SYNOPSIS
    find_files()
    thd                 thread handler
    files               put found files in this list
    db                  database name to set in TABLE_LIST structure
    path                path to database
    wild                filter for found files
    dir                 read databases in path if TRUE, read .frm files in
                        database otherwise

  RETURN
    FIND_FILES_OK       success
    FIND_FILES_OOM      out of memory error
    FIND_FILES_DIR      no such directory, or directory can't be read
*/


find_files_result
find_files(THD *thd, List<char> *files, const char *db,
           const char *path, const char *wild, bool dir)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
448 449 450 451 452
{
  uint i;
  char *ext;
  MY_DIR *dirp;
  FILEINFO *file;
453
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
454
  uint col_access=thd->col_access;
455
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
456
  TABLE_LIST table_list;
457
  DBUG_ENTER("find_files");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
458

459 460
  if (wild && !wild[0])
    wild=0;
461

bk@work.mysql.com's avatar
bk@work.mysql.com committed
462 463
  bzero((char*) &table_list,sizeof(table_list));

464 465 466 467 468 469
  if (!(dirp = my_dir(path,MYF(dir ? MY_WANT_STAT : 0))))
  {
    if (my_errno == ENOENT)
      my_error(ER_BAD_DB_ERROR, MYF(ME_BELL+ME_WAITTANG), db);
    else
      my_error(ER_CANT_READ_DIR, MYF(ME_BELL+ME_WAITTANG), path, my_errno);
470
    DBUG_RETURN(FIND_FILES_DIR);
471
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
472

473
  for (i=0 ; i < (uint) dirp->number_off_files  ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
474
  {
475
    char uname[NAME_LEN + 1];                   /* Unencoded name */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
476 477
    file=dirp->dir_entry+i;
    if (dir)
478
    {                                           /* Return databases */
479 480 481 482
      if ((file->name[0] == '.' && 
          ((file->name[1] == '.' && file->name[2] == '\0') ||
            file->name[1] == '\0')))
        continue;                               /* . or .. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
483 484
#ifdef USE_SYMDIR
      char *ext;
485
      char buff[FN_REFLEN];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
486
      if (my_use_symdir && !strcmp(ext=fn_ext(file->name), ".sym"))
487 488
      {
	/* Only show the sym file if it points to a directory */
489
	char *end;
490
        *ext=0;                                 /* Remove extension */
491 492 493 494
	unpack_dirname(buff, file->name);
	end= strend(buff);
	if (end != buff && end[-1] == FN_LIBCHAR)
	  end[-1]= 0;				// Remove end FN_LIBCHAR
495 496 497
        if (!my_stat(buff, file->mystat, MYF(0)))
               continue;
       }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
498
#endif
499 500
      if (!MY_S_ISDIR(file->mystat->st_mode))
        continue;
501
      VOID(filename_to_tablename(file->name, uname, sizeof(uname)));
502
      if (wild && wild_compare(uname, wild, 0))
503 504
        continue;
      file->name= uname;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
505 506 507
    }
    else
    {
508
        // Return only .frm files which aren't temp files.
509
      if (my_strcasecmp(system_charset_info, ext=fn_rext(file->name),reg_ext) ||
510
          is_prefix(file->name, tmp_file_prefix))
511
        continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
512
      *ext=0;
513 514
      VOID(filename_to_tablename(file->name, uname, sizeof(uname)));
      file->name= uname;
515 516 517 518
      if (wild)
      {
	if (lower_case_table_names)
	{
519
	  if (wild_case_compare(files_charset_info, file->name, wild))
520 521
	    continue;
	}
522
	else if (wild_compare(file->name,wild,0))
523 524
	  continue;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
525
    }
hf@deer.(none)'s avatar
hf@deer.(none) committed
526
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bk@work.mysql.com's avatar
bk@work.mysql.com committed
527 528 529 530
    /* Don't show tables where we don't have any privileges */
    if (db && !(col_access & TABLE_ACLS))
    {
      table_list.db= (char*) db;
531
      table_list.db_length= strlen(db);
532
      table_list.table_name= file->name;
533
      table_list.table_name_length= strlen(file->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
534
      table_list.grant.privilege=col_access;
535
      if (check_grant(thd, TABLE_ACLS, &table_list, 1, 1, 1))
536
        continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
537
    }
hf@deer.(none)'s avatar
hf@deer.(none) committed
538
#endif
539
    if (files->push_back(thd->strdup(file->name)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
540 541
    {
      my_dirend(dirp);
542
      DBUG_RETURN(FIND_FILES_OOM);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
543 544 545 546
    }
  }
  DBUG_PRINT("info",("found: %d files", files->elements));
  my_dirend(dirp);
547 548 549

  VOID(ha_find_files(thd,db,path,wild,dir,files));

550
  DBUG_RETURN(FIND_FILES_OK);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
551 552
}

553

554
bool
bk@work.mysql.com's avatar
bk@work.mysql.com committed
555 556
mysqld_show_create(THD *thd, TABLE_LIST *table_list)
{
557 558 559
  Protocol *protocol= thd->protocol;
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
560 561
  DBUG_ENTER("mysqld_show_create");
  DBUG_PRINT("enter",("db: %s  table: %s",table_list->db,
562
                      table_list->table_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
563

564 565 566
  /* We want to preserve the tree for views. */
  thd->lex->view_prepare_mode= TRUE;

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
567
  /* Only one table for now, but VIEW can involve several tables */
568
  if (open_normal_and_derived_tables(thd, table_list, 0))
569 570 571
  {
    if (!table_list->view || thd->net.last_errno != ER_VIEW_INVALID)
      DBUG_RETURN(TRUE);
572

573 574 575 576 577 578
    /*
      Clear all messages with 'error' level status and
      issue a warning with 'warning' level status in 
      case of invalid view and last error is ER_VIEW_INVALID
    */
    mysql_reset_errors(thd, true);
579 580
    thd->clear_error();

581 582 583 584 585 586
    push_warning_printf(thd,MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_VIEW_INVALID,
                        ER(ER_VIEW_INVALID),
                        table_list->view_db.str,
                        table_list->view_name.str);
  }
587

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
588 589 590
  /* TODO: add environment variables show when it become possible */
  if (thd->lex->only_view && !table_list->view)
  {
591
    my_error(ER_WRONG_OBJECT, MYF(0),
592
             table_list->db, table_list->table_name, "VIEW");
593
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
594
  }
595

596
  buffer.length(0);
597 598 599 600

  if (table_list->view)
    buffer.set_charset(table_list->view_creation_ctx->get_client_cs());

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
601 602
  if ((table_list->view ?
       view_store_create_info(thd, table_list, &buffer) :
603
       store_create_info(thd, table_list, &buffer, NULL)))
604
    DBUG_RETURN(TRUE);
605

bk@work.mysql.com's avatar
bk@work.mysql.com committed
606
  List<Item> field_list;
607 608
  if (table_list->view)
  {
609
    field_list.push_back(new Item_empty_string("View",NAME_CHAR_LEN));
610 611
    field_list.push_back(new Item_empty_string("Create View",
                                               max(buffer.length(),1024)));
612 613 614 615
    field_list.push_back(new Item_empty_string("character_set_client",
                                               MY_CS_NAME_SIZE));
    field_list.push_back(new Item_empty_string("collation_connection",
                                               MY_CS_NAME_SIZE));
616 617 618
  }
  else
  {
619
    field_list.push_back(new Item_empty_string("Table",NAME_CHAR_LEN));
620 621 622 623
    // 1024 is for not to confuse old clients
    field_list.push_back(new Item_empty_string("Create Table",
                                               max(buffer.length(),1024)));
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
624

625 626
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
627
    DBUG_RETURN(TRUE);
628
  protocol->prepare_for_resend();
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
629 630 631 632
  if (table_list->view)
    protocol->store(table_list->view_name.str, system_charset_info);
  else
  {
633
    if (table_list->schema_table)
634 635
      protocol->store(table_list->schema_table->table_name,
                      system_charset_info);
636
    else
637
      protocol->store(table_list->table->alias, system_charset_info);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
638
  }
639 640 641

  if (table_list->view)
  {
642 643
    protocol->store(buffer.ptr(), buffer.length(),
                    table_list->view_creation_ctx->get_client_cs());
644 645 646 647 648 649 650 651 652

    protocol->store(table_list->view_creation_ctx->get_client_cs()->csname,
                    system_charset_info);

    protocol->store(table_list->view_creation_ctx->get_connection_cl()->name,
                    system_charset_info);
  }
  else
    protocol->store(buffer.ptr(), buffer.length(), buffer.charset());
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
653

654
  if (protocol->write())
655
    DBUG_RETURN(TRUE);
656

657
  send_eof(thd);
658
  DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
659 660
}

661 662
bool mysqld_show_create_db(THD *thd, char *dbname,
                           HA_CREATE_INFO *create_info)
663 664 665
{
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
666
#ifndef NO_EMBEDDED_ACCESS_CHECKS
667
  Security_context *sctx= thd->security_ctx;
668
  uint db_access;
669
#endif
670 671 672 673 674 675
  HA_CREATE_INFO create;
  uint create_options = create_info ? create_info->options : 0;
  Protocol *protocol=thd->protocol;
  DBUG_ENTER("mysql_show_create_db");

#ifndef NO_EMBEDDED_ACCESS_CHECKS
676
  if (test_all_bits(sctx->master_access, DB_ACLS))
677 678
    db_access=DB_ACLS;
  else
679 680
    db_access= (acl_get(sctx->host, sctx->ip, sctx->priv_user, dbname, 0) |
		sctx->master_access);
681
  if (!(db_access & DB_ACLS) && check_grant_db(thd,dbname))
682
  {
683
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
684
             sctx->priv_user, sctx->host_or_ip, dbname);
685 686
    general_log_print(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR),
                      sctx->priv_user, sctx->host_or_ip, dbname);
687
    DBUG_RETURN(TRUE);
688 689
  }
#endif
690
  if (!my_strcasecmp(system_charset_info, dbname,
691
                     INFORMATION_SCHEMA_NAME.str))
692
  {
693
    dbname= INFORMATION_SCHEMA_NAME.str;
694
    create.default_table_charset= system_charset_info;
695
  }
696
  else
697
  {
698
    if (check_db_dir_existence(dbname))
699 700 701 702
    {
      my_error(ER_BAD_DB_ERROR, MYF(0), dbname);
      DBUG_RETURN(TRUE);
    }
703 704

    load_db_opt_by_name(thd, dbname, &create);
705 706
  }
  List<Item> field_list;
707
  field_list.push_back(new Item_empty_string("Database",NAME_CHAR_LEN));
708 709
  field_list.push_back(new Item_empty_string("Create Database",1024));

710 711
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
712
    DBUG_RETURN(TRUE);
713 714 715 716

  protocol->prepare_for_resend();
  protocol->store(dbname, strlen(dbname), system_charset_info);
  buffer.length(0);
717
  buffer.append(STRING_WITH_LEN("CREATE DATABASE "));
718
  if (create_options & HA_LEX_CREATE_IF_NOT_EXISTS)
719
    buffer.append(STRING_WITH_LEN("/*!32312 IF NOT EXISTS*/ "));
720 721 722 723
  append_identifier(thd, &buffer, dbname, strlen(dbname));

  if (create.default_table_charset)
  {
724 725
    buffer.append(STRING_WITH_LEN(" /*!40100"));
    buffer.append(STRING_WITH_LEN(" DEFAULT CHARACTER SET "));
726 727 728
    buffer.append(create.default_table_charset->csname);
    if (!(create.default_table_charset->state & MY_CS_PRIMARY))
    {
729
      buffer.append(STRING_WITH_LEN(" COLLATE "));
730 731
      buffer.append(create.default_table_charset->name);
    }
732
    buffer.append(STRING_WITH_LEN(" */"));
733 734 735 736
  }
  protocol->store(buffer.ptr(), buffer.length(), buffer.charset());

  if (protocol->write())
737
    DBUG_RETURN(TRUE);
738
  send_eof(thd);
739
  DBUG_RETURN(FALSE);
740
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
741

tim@cane.mysql.fi's avatar
tim@cane.mysql.fi committed
742 743


bk@work.mysql.com's avatar
bk@work.mysql.com committed
744
/****************************************************************************
745 746
  Return only fields for API mysql_list_fields
  Use "show table wildcard" in mysql instead of this
bk@work.mysql.com's avatar
bk@work.mysql.com committed
747 748 749 750 751 752 753
****************************************************************************/

void
mysqld_list_fields(THD *thd, TABLE_LIST *table_list, const char *wild)
{
  TABLE *table;
  DBUG_ENTER("mysqld_list_fields");
754
  DBUG_PRINT("enter",("table: %s",table_list->table_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
755

756
  if (open_normal_and_derived_tables(thd, table_list, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
757
    DBUG_VOID_RETURN;
758 759
  table= table_list->table;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
760 761 762 763 764
  List<Item> field_list;

  Field **ptr,*field;
  for (ptr=table->field ; (field= *ptr); ptr++)
  {
765 766
    if (!wild || !wild[0] || 
        !wild_case_compare(system_charset_info, field->field_name,wild))
767 768 769 770 771 772 773 774
    {
      if (table_list->view)
        field_list.push_back(new Item_ident_for_show(field,
                                                     table_list->view_db.str,
                                                     table_list->view_name.str));
      else
        field_list.push_back(new Item_field(field));
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
775
  }
776
  restore_record(table, s->default_values);              // Get empty record
777
  table->use_all_columns();
778 779
  if (thd->protocol->send_fields(&field_list, Protocol::SEND_DEFAULTS |
                                              Protocol::SEND_EOF))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
780
    DBUG_VOID_RETURN;
781
  thd->protocol->flush();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
782 783 784
  DBUG_VOID_RETURN;
}

785

bk@work.mysql.com's avatar
bk@work.mysql.com committed
786
int
787
mysqld_dump_create_info(THD *thd, TABLE_LIST *table_list, int fd)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
788
{
789 790
  Protocol *protocol= thd->protocol;
  String *packet= protocol->storage_packet();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
791
  DBUG_ENTER("mysqld_dump_create_info");
792
  DBUG_PRINT("enter",("table: %s",table_list->table->s->table_name.str));
793

794
  protocol->prepare_for_resend();
795
  if (store_create_info(thd, table_list, packet, NULL))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
796
    DBUG_RETURN(-1);
797

798
  if (fd < 0)
799
  {
800
    if (protocol->write())
801
      DBUG_RETURN(-1);
802
    protocol->flush();
803
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
804
  else
805
  {
806
    if (my_write(fd, (const uchar*) packet->ptr(), packet->length(),
807
		 MYF(MY_WME)))
808 809
      DBUG_RETURN(-1);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
810 811
  DBUG_RETURN(0);
}
812

813
/*
814
  Go through all character combinations and ensure that sql_lex.cc can
815
  parse it as an identifier.
816 817

  SYNOPSIS
818 819 820 821 822 823 824
  require_quotes()
  name			attribute name
  name_length		length of name

  RETURN
    #	Pointer to conflicting character
    0	No conflicting character
825 826
*/

827
static const char *require_quotes(const char *name, uint name_length)
828
{
829
  uint length;
830
  bool pure_digit= TRUE;
831 832
  const char *end= name + name_length;

833
  for (; name < end ; name++)
834
  {
835 836 837 838
    uchar chr= (uchar) *name;
    length= my_mbcharlen(system_charset_info, chr);
    if (length == 1 && !system_charset_info->ident_map[chr])
      return name;
839 840
    if (length == 1 && (chr < '0' || chr > '9'))
      pure_digit= FALSE;
841
  }
842 843
  if (pure_digit)
    return name;
844 845
  return 0;
}
846

847

848 849 850 851 852 853 854 855 856 857 858 859
/*
  Quote the given identifier if needed and append it to the target string.
  If the given identifier is empty, it will be quoted.

  SYNOPSIS
  append_identifier()
  thd                   thread handler
  packet                target string
  name                  the identifier to be appended
  name_length           length of the appending identifier
*/

860 861
void
append_identifier(THD *thd, String *packet, const char *name, uint length)
862
{
863 864
  const char *name_end;
  char quote_char;
865
  int q= get_quote_char_for_identifier(thd, name, length);
866

867
  if (q == EOF)
868
  {
869
    packet->append(name, length, packet->charset());
870 871 872
    return;
  }

873 874 875 876
  /*
    The identifier must be quoted as it includes a quote character or
   it's a keyword
  */
877

878
  VOID(packet->reserve(length*2 + 2));
879
  quote_char= (char) q;
880 881 882 883
  packet->append(&quote_char, 1, system_charset_info);

  for (name_end= name+length ; name < name_end ; name+= length)
  {
884
    uchar chr= (uchar) *name;
885
    length= my_mbcharlen(system_charset_info, chr);
886
    /*
887
      my_mbcharlen can return 0 on a wrong multibyte
888 889 890 891 892 893 894
      sequence. It is possible when upgrading from 4.0,
      and identifier contains some accented characters.
      The manual says it does not work. So we'll just
      change length to 1 not to hang in the endless loop.
    */
    if (!length)
      length= 1;
895
    if (length == 1 && chr == (uchar) quote_char)
896
      packet->append(&quote_char, 1, system_charset_info);
897
    packet->append(name, length, system_charset_info);
898
  }
899
  packet->append(&quote_char, 1, system_charset_info);
900 901
}

902

903 904 905 906 907 908 909 910 911 912
/*
  Get the quote character for displaying an identifier.

  SYNOPSIS
    get_quote_char_for_identifier()
    thd		Thread handler
    name	name to quote
    length	length of name

  IMPLEMENTATION
913 914 915 916 917
    Force quoting in the following cases:
      - name is empty (for one, it is possible when we use this function for
        quoting user and host names for DEFINER clause);
      - name is a keyword;
      - name includes a special character;
918 919 920 921 922 923 924
    Otherwise identifier is quoted only if the option OPTION_QUOTE_SHOW_CREATE
    is set.

  RETURN
    EOF	  No quote character is needed
    #	  Quote character
*/
925 926 927

int get_quote_char_for_identifier(THD *thd, const char *name, uint length)
{
anozdrin@mysql.com's avatar
anozdrin@mysql.com committed
928
  if (length &&
929
      !is_keyword(name,length) &&
930 931 932
      !require_quotes(name, length) &&
      !(thd->options & OPTION_QUOTE_SHOW_CREATE))
    return EOF;
933
  if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
934
    return '"';
935
  return '`';
936 937 938
}


939 940 941 942 943
/* Append directory name (if exists) to CREATE INFO */

static void append_directory(THD *thd, String *packet, const char *dir_type,
			     const char *filename)
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
944
  if (filename && !(thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE))
945
  {
946
    uint length= dirname_length(filename);
947 948
    packet->append(' ');
    packet->append(dir_type);
949
    packet->append(STRING_WITH_LEN(" DIRECTORY='"));
950
#ifdef __WIN__
monty@mysql.com's avatar
monty@mysql.com committed
951 952 953 954 955 956 957 958 959
    /* Convert \ to / to be able to create table on unix */
    char *winfilename= (char*) thd->memdup(filename, length);
    char *pos, *end;
    for (pos= winfilename, end= pos+length ; pos < end ; pos++)
    {
      if (*pos == '\\')
        *pos = '/';
    }
    filename= winfilename;
960
#endif
monty@mysql.com's avatar
monty@mysql.com committed
961
    packet->append(filename, length);
962 963 964 965 966
    packet->append('\'');
  }
}


monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
967
#define LIST_PROCESS_HOST_LEN 64
968

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
/*
  Build a CREATE TABLE statement for a table.

  SYNOPSIS
    store_create_info()
    thd               The thread
    table_list        A list containing one table to write statement
                      for.
    packet            Pointer to a string where statement will be
                      written.
    create_info_arg   Pointer to create information that can be used
                      to tailor the format of the statement.  Can be
                      NULL, in which case only SQL_MODE is considered
                      when building the statement.

  NOTE
    Currently always return 0, but might return error code in the
    future.

  RETURN
    0       OK
 */
991 992 993

int store_create_info(THD *thd, TABLE_LIST *table_list, String *packet,
                      HA_CREATE_INFO *create_info_arg)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
994
{
995
  List<Item> field_list;
996
  char tmp[MAX_FIELD_WIDTH], *for_str, buff[128];
997
  const char *alias;
998
  String type(tmp, sizeof(tmp), system_charset_info);
999 1000 1001
  Field **ptr,*field;
  uint primary_key;
  KEY *key_info;
1002
  TABLE *table= table_list->table;
1003
  handler *file= table->file;
1004
  TABLE_SHARE *share= table->s;
1005
  HA_CREATE_INFO create_info;
1006
  bool show_table_options= FALSE;
1007 1008 1009 1010 1011 1012
  bool foreign_db_mode=  (thd->variables.sql_mode & (MODE_POSTGRESQL |
                                                     MODE_ORACLE |
                                                     MODE_MSSQL |
                                                     MODE_DB2 |
                                                     MODE_MAXDB |
                                                     MODE_ANSI)) != 0;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1013 1014 1015
  bool limited_mysql_mode= (thd->variables.sql_mode & (MODE_NO_FIELD_OPTIONS |
                                                       MODE_MYSQL323 |
                                                       MODE_MYSQL40)) != 0;
1016
  my_bitmap_map *old_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1017
  DBUG_ENTER("store_create_info");
1018
  DBUG_PRINT("enter",("table: %s", table->s->table_name.str));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1019

1020
  restore_record(table, s->default_values); // Get empty record
1021

1022
  if (share->tmp_table)
1023
    packet->append(STRING_WITH_LEN("CREATE TEMPORARY TABLE "));
1024
  else
1025
    packet->append(STRING_WITH_LEN("CREATE TABLE "));
1026 1027 1028
  if (create_info_arg &&
      (create_info_arg->options & HA_LEX_CREATE_IF_NOT_EXISTS))
    packet->append(STRING_WITH_LEN("IF NOT EXISTS "));
1029
  if (table_list->schema_table)
1030
    alias= table_list->schema_table->table_name;
1031
  else
1032 1033 1034 1035 1036 1037 1038 1039
  {
    if (lower_case_table_names == 2)
      alias= table->alias;
    else
    {
      alias= share->table_name.str;
    }
  }
monty@mysql.com's avatar
monty@mysql.com committed
1040
  append_identifier(thd, packet, alias, strlen(alias));
1041
  packet->append(STRING_WITH_LEN(" (\n"));
1042 1043 1044 1045 1046 1047
  /*
    We need this to get default values from the table
    We have to restore the read_set if we are called from insert in case
    of row based replication.
  */
  old_map= tmp_use_all_columns(table, table->read_set);
1048

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1049 1050
  for (ptr=table->field ; (field= *ptr); ptr++)
  {
1051
    bool has_default;
1052
    bool has_now_default;
1053 1054
    uint flags = field->flags;

1055
    if (ptr != table->field)
1056
      packet->append(STRING_WITH_LEN(",\n"));
1057

1058
    packet->append(STRING_WITH_LEN("  "));
1059
    append_identifier(thd,packet,field->field_name, strlen(field->field_name));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1060 1061
    packet->append(' ');
    // check for surprises from the previous call to Field::sql_type()
1062
    if (type.ptr() != tmp)
1063
      type.set(tmp, sizeof(tmp), system_charset_info);
1064 1065
    else
      type.set_charset(system_charset_info);
1066

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1067
    field->sql_type(type);
1068
    packet->append(type.ptr(), type.length(), system_charset_info);
1069

1070 1071
    if (field->has_charset() && 
        !(thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)))
1072
    {
1073
      if (field->charset() != share->table_charset)
1074
      {
1075
	packet->append(STRING_WITH_LEN(" CHARACTER SET "));
1076 1077 1078 1079 1080 1081 1082 1083
	packet->append(field->charset()->csname);
      }
      /* 
	For string types dump collation name only if 
	collation is not primary for the given charset
      */
      if (!(field->charset()->state & MY_CS_PRIMARY))
      {
1084
	packet->append(STRING_WITH_LEN(" COLLATE "));
1085
	packet->append(field->charset()->name);
1086
      }
1087
    }
1088

1089
    if (flags & NOT_NULL_FLAG)
1090
      packet->append(STRING_WITH_LEN(" NOT NULL"));
1091
    else if (field->type() == MYSQL_TYPE_TIMESTAMP)
1092 1093 1094 1095 1096
    {
      /*
        TIMESTAMP field require explicit NULL flag, because unlike
        all other fields they are treated as NOT NULL by default.
      */
1097
      packet->append(STRING_WITH_LEN(" NULL"));
1098
    }
1099 1100

    /* 
1101
      Again we are using CURRENT_TIMESTAMP instead of NOW because it is
1102 1103 1104 1105 1106
      more standard 
    */
    has_now_default= table->timestamp_field == field && 
                     field->unireg_check != Field::TIMESTAMP_UN_FIELD;
    
1107
    has_default= (field->type() != MYSQL_TYPE_BLOB &&
1108
                  !(field->flags & NO_DEFAULT_VALUE_FLAG) &&
1109
		  field->unireg_check != Field::NEXT_NUMBER &&
1110 1111
                  !((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40))
		    && has_now_default));
1112

1113
    if (has_default)
1114
    {
1115
      packet->append(STRING_WITH_LEN(" DEFAULT "));
1116
      if (has_now_default)
1117
        packet->append(STRING_WITH_LEN("CURRENT_TIMESTAMP"));
1118
      else if (!field->is_null())
1119
      {                                             // Not null by default
1120
        type.set(tmp, sizeof(tmp), field->charset());
1121
        field->val_str(&type);
1122
	if (type.length())
1123
	{
1124
	  String def_val;
1125
          uint dummy_errors;
1126 1127
	  /* convert to system_charset_info == utf8 */
	  def_val.copy(type.ptr(), type.length(), field->charset(),
1128
		       system_charset_info, &dummy_errors);
1129 1130
          append_unescaped(packet, def_val.ptr(), def_val.length());
	}
1131
        else
1132
	  packet->append(STRING_WITH_LEN("''"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1133
      }
1134
      else if (field->maybe_null())
1135
        packet->append(STRING_WITH_LEN("NULL"));    // Null as default
1136
      else
1137
        packet->append(tmp);
1138
    }
1139

1140
    if (!limited_mysql_mode && table->timestamp_field == field && 
1141
        field->unireg_check != Field::TIMESTAMP_DN_FIELD)
1142
      packet->append(STRING_WITH_LEN(" ON UPDATE CURRENT_TIMESTAMP"));
1143

1144 1145
    if (field->unireg_check == Field::NEXT_NUMBER && 
        !(thd->variables.sql_mode & MODE_NO_FIELD_OPTIONS))
1146
      packet->append(STRING_WITH_LEN(" AUTO_INCREMENT"));
1147 1148 1149

    if (field->comment.length)
    {
1150
      packet->append(STRING_WITH_LEN(" COMMENT "));
1151 1152
      append_unescaped(packet, field->comment.str, field->comment.length);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1153 1154
  }

1155
  key_info= table->key_info;
1156
  bzero((char*) &create_info, sizeof(create_info));
1157
  file->update_create_info(&create_info);
1158
  primary_key= share->primary_key;
1159

1160
  for (uint i=0 ; i < share->keys ; i++,key_info++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1161
  {
1162 1163
    KEY_PART_INFO *key_part= key_info->key_part;
    bool found_primary=0;
1164
    packet->append(STRING_WITH_LEN(",\n  "));
1165

1166
    if (i == primary_key && !strcmp(key_info->name, primary_key_name))
1167 1168
    {
      found_primary=1;
1169 1170 1171 1172 1173
      /*
        No space at end, because a space will be added after where the
        identifier would go, but that is not added for primary key.
      */
      packet->append(STRING_WITH_LEN("PRIMARY KEY"));
1174
    }
1175
    else if (key_info->flags & HA_NOSAME)
1176
      packet->append(STRING_WITH_LEN("UNIQUE KEY "));
1177
    else if (key_info->flags & HA_FULLTEXT)
1178
      packet->append(STRING_WITH_LEN("FULLTEXT KEY "));
1179
    else if (key_info->flags & HA_SPATIAL)
1180 1181 1182
      packet->append(STRING_WITH_LEN("SPATIAL KEY "));
    else
      packet->append(STRING_WITH_LEN("KEY "));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1183

1184
    if (!found_primary)
1185
     append_identifier(thd, packet, key_info->name, strlen(key_info->name));
1186

1187
    packet->append(STRING_WITH_LEN(" ("));
1188

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1189 1190
    for (uint j=0 ; j < key_info->key_parts ; j++,key_part++)
    {
1191
      if (j)
1192
        packet->append(',');
1193

1194
      if (key_part->field)
1195 1196
        append_identifier(thd,packet,key_part->field->field_name,
			  strlen(key_part->field->field_name));
1197
      if (key_part->field &&
1198 1199
          (key_part->length !=
           table->field[key_part->fieldnr-1]->key_length() &&
gkodinov/kgeorge@magare.gmz's avatar
gkodinov/kgeorge@magare.gmz committed
1200
           !(key_info->flags & (HA_FULLTEXT | HA_SPATIAL))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1201
      {
1202
        char *end;
1203
        buff[0] = '(';
1204 1205 1206
        end= int10_to_str((long) key_part->length /
                          key_part->field->charset()->mbmaxlen,
                          buff + 1,10);
1207 1208
        *end++ = ')';
        packet->append(buff,(uint) (end-buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1209 1210 1211
      }
    }
    packet->append(')');
1212
    store_key_options(thd, packet, table, key_info);
1213 1214
    if (key_info->parser)
    {
antony@ppcg5.local's avatar
antony@ppcg5.local committed
1215
      LEX_STRING *parser_name= plugin_name(key_info->parser);
1216
      packet->append(STRING_WITH_LEN(" /*!50100 WITH PARSER "));
antony@ppcg5.local's avatar
antony@ppcg5.local committed
1217
      append_identifier(thd, packet, parser_name->str, parser_name->length);
1218
      packet->append(STRING_WITH_LEN(" */ "));
1219
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1220
  }
1221

1222 1223 1224 1225
  /*
    Get possible foreign key definitions stored in InnoDB and append them
    to the CREATE TABLE statement
  */
1226

1227
  if ((for_str= file->get_foreign_key_create_info()))
1228 1229 1230
  {
    packet->append(for_str, strlen(for_str));
    file->free_foreign_key_create_info(for_str);
1231 1232
  }

1233
  packet->append(STRING_WITH_LEN("\n)"));
1234
  if (!(thd->variables.sql_mode & MODE_NO_TABLE_OPTIONS) && !foreign_db_mode)
1235
  {
1236
    show_table_options= TRUE;
1237 1238 1239 1240 1241
    /*
      Get possible table space definitions and append them
      to the CREATE TABLE statement
    */

1242
    if ((for_str= file->get_tablespace_name(thd,0,0)))
1243
    {
1244
      packet->append(STRING_WITH_LEN(" /*!50100 TABLESPACE "));
1245
      packet->append(for_str, strlen(for_str));
1246
      packet->append(STRING_WITH_LEN(" STORAGE DISK */"));
1247 1248 1249
      my_free(for_str, MYF(0));
    }

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    /*
      IF   check_create_info
      THEN add ENGINE only if it was used when creating the table
    */
    if (!create_info_arg ||
        (create_info_arg->used_fields & HA_CREATE_USED_ENGINE))
    {
      if (thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40))
        packet->append(STRING_WITH_LEN(" TYPE="));
      else
        packet->append(STRING_WITH_LEN(" ENGINE="));
1261
#ifdef WITH_PARTITION_STORAGE_ENGINE
1262
    if (table->part_info)
1263 1264
      packet->append(ha_resolve_storage_engine_name(
                        table->part_info->default_engine_type));
1265
    else
1266
      packet->append(file->table_type());
1267
#else
1268
      packet->append(file->table_type());
1269
#endif
1270
    }
1271

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    /*
      Add AUTO_INCREMENT=... if there is an AUTO_INCREMENT column,
      and NEXT_ID > 1 (the default).  We must not print the clause
      for engines that do not support this as it would break the
      import of dumps, but as of this writing, the test for whether
      AUTO_INCREMENT columns are allowed and wether AUTO_INCREMENT=...
      is supported is identical, !(file->table_flags() & HA_NO_AUTO_INCREMENT))
      Because of that, we do not explicitly test for the feature,
      but may extrapolate its existence from that of an AUTO_INCREMENT column.
    */

1283
    if (create_info.auto_increment_value > 1)
1284
    {
1285
      char *end;
1286
      packet->append(STRING_WITH_LEN(" AUTO_INCREMENT="));
1287 1288 1289
      end= longlong10_to_str(create_info.auto_increment_value, buff,10);
      packet->append(buff, (uint) (end - buff));
    }
1290

1291
    
1292
    if (share->table_charset &&
1293 1294
	!(thd->variables.sql_mode & MODE_MYSQL323) &&
	!(thd->variables.sql_mode & MODE_MYSQL40))
1295
    {
1296 1297 1298 1299 1300 1301
      /*
        IF   check_create_info
        THEN add DEFAULT CHARSET only if it was used when creating the table
      */
      if (!create_info_arg ||
          (create_info_arg->used_fields & HA_CREATE_USED_DEFAULT_CHARSET))
1302
      {
1303 1304 1305 1306 1307 1308 1309
        packet->append(STRING_WITH_LEN(" DEFAULT CHARSET="));
        packet->append(share->table_charset->csname);
        if (!(share->table_charset->state & MY_CS_PRIMARY))
        {
          packet->append(STRING_WITH_LEN(" COLLATE="));
          packet->append(table->s->table_charset->name);
        }
1310
      }
1311
    }
1312

1313
    if (share->min_rows)
1314
    {
1315
      char *end;
1316
      packet->append(STRING_WITH_LEN(" MIN_ROWS="));
1317
      end= longlong10_to_str(share->min_rows, buff, 10);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1318
      packet->append(buff, (uint) (end- buff));
1319
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1320

1321
    if (share->max_rows && !table_list->schema_table)
1322
    {
1323
      char *end;
1324
      packet->append(STRING_WITH_LEN(" MAX_ROWS="));
1325
      end= longlong10_to_str(share->max_rows, buff, 10);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1326
      packet->append(buff, (uint) (end - buff));
1327
    }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1328

1329
    if (share->avg_row_length)
1330
    {
1331
      char *end;
1332
      packet->append(STRING_WITH_LEN(" AVG_ROW_LENGTH="));
1333
      end= longlong10_to_str(share->avg_row_length, buff,10);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1334
      packet->append(buff, (uint) (end - buff));
1335
    }
1336

1337
    if (share->db_create_options & HA_OPTION_PACK_KEYS)
1338
      packet->append(STRING_WITH_LEN(" PACK_KEYS=1"));
1339
    if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
1340
      packet->append(STRING_WITH_LEN(" PACK_KEYS=0"));
1341
    if (share->db_create_options & HA_OPTION_CHECKSUM)
1342
      packet->append(STRING_WITH_LEN(" CHECKSUM=1"));
1343
    if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE)
1344
      packet->append(STRING_WITH_LEN(" DELAY_KEY_WRITE=1"));
1345
    if (share->row_type != ROW_TYPE_DEFAULT)
1346
    {
1347
      packet->append(STRING_WITH_LEN(" ROW_FORMAT="));
1348
      packet->append(ha_row_type[(uint) share->row_type]);
1349
    }
1350 1351
    if (table->s->key_block_size)
    {
1352
      char *end;
1353 1354 1355 1356
      packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE="));
      end= longlong10_to_str(table->s->key_block_size, buff, 10);
      packet->append(buff, (uint) (end - buff));
    }
1357
    table->file->append_create_info(packet);
1358
    if (share->comment.length)
1359
    {
1360
      packet->append(STRING_WITH_LEN(" COMMENT="));
1361
      append_unescaped(packet, share->comment.str, share->comment.length);
1362
    }
1363 1364
    if (share->connect_string.length)
    {
1365
      packet->append(STRING_WITH_LEN(" CONNECTION="));
1366 1367
      append_unescaped(packet, share->connect_string.str, share->connect_string.length);
    }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1368 1369
    append_directory(thd, packet, "DATA",  create_info.data_file_name);
    append_directory(thd, packet, "INDEX", create_info.index_file_name);
1370
  }
1371
#ifdef WITH_PARTITION_STORAGE_ENGINE
1372 1373 1374 1375 1376 1377
  {
    /*
      Partition syntax for CREATE TABLE is at the end of the syntax.
    */
    uint part_syntax_len;
    char *part_syntax;
1378
    if (table->part_info &&
1379
        (!table->part_info->is_auto_partitioned) &&
1380
        ((part_syntax= generate_partition_syntax(table->part_info,
1381
                                                  &part_syntax_len,
1382
                                                  FALSE,
1383
                                                  show_table_options))))
1384
    {
rburnett@bk-internal.mysql.com's avatar
rburnett@bk-internal.mysql.com committed
1385
       packet->append(STRING_WITH_LEN(" /*!50100"));
1386
       packet->append(part_syntax, part_syntax_len);
rburnett@bk-internal.mysql.com's avatar
rburnett@bk-internal.mysql.com committed
1387
       packet->append(STRING_WITH_LEN(" */"));
1388 1389 1390 1391
       my_free(part_syntax, MYF(0));
    }
  }
#endif
1392
  tmp_restore_column_map(table->read_set, old_map);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1393 1394 1395
  DBUG_RETURN(0);
}

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

static void store_key_options(THD *thd, String *packet, TABLE *table,
                              KEY *key_info)
{
  bool limited_mysql_mode= (thd->variables.sql_mode &
                            (MODE_NO_FIELD_OPTIONS | MODE_MYSQL323 |
                             MODE_MYSQL40)) != 0;
  bool foreign_db_mode=  (thd->variables.sql_mode & (MODE_POSTGRESQL |
                                                     MODE_ORACLE |
                                                     MODE_MSSQL |
                                                     MODE_DB2 |
                                                     MODE_MAXDB |
                                                     MODE_ANSI)) != 0;
  char *end, buff[32];

  if (!(thd->variables.sql_mode & MODE_NO_KEY_OPTIONS) &&
      !limited_mysql_mode && !foreign_db_mode)
  {

    if (key_info->algorithm == HA_KEY_ALG_BTREE)
      packet->append(STRING_WITH_LEN(" USING BTREE"));

    if (key_info->algorithm == HA_KEY_ALG_HASH)
      packet->append(STRING_WITH_LEN(" USING HASH"));

    /* send USING only in non-default case: non-spatial rtree */
    if ((key_info->algorithm == HA_KEY_ALG_RTREE) &&
        !(key_info->flags & HA_SPATIAL))
      packet->append(STRING_WITH_LEN(" USING RTREE"));

    if ((key_info->flags & HA_USES_BLOCK_SIZE) &&
        table->s->key_block_size != key_info->block_size)
    {
      packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE="));
      end= longlong10_to_str(key_info->block_size, buff, 10);
      packet->append(buff, (uint) (end - buff));
    }
  }
}


1437 1438
void
view_store_options(THD *thd, TABLE_LIST *table, String *buff)
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
{
  append_algorithm(table, buff);
  append_definer(thd, buff, &table->definer.user, &table->definer.host);
  if (table->view_suid)
    buff->append(STRING_WITH_LEN("SQL SECURITY DEFINER "));
  else
    buff->append(STRING_WITH_LEN("SQL SECURITY INVOKER "));
}


/*
  Append DEFINER clause to the given buffer.
  
  SYNOPSIS
    append_definer()
    thd           [in] thread handle
    buffer        [inout] buffer to hold DEFINER clause
    definer_user  [in] user name part of definer
    definer_host  [in] host name part of definer
*/

static void append_algorithm(TABLE_LIST *table, String *buff)
1461
{
1462
  buff->append(STRING_WITH_LEN("ALGORITHM="));
1463 1464
  switch ((int8)table->algorithm) {
  case VIEW_ALGORITHM_UNDEFINED:
1465
    buff->append(STRING_WITH_LEN("UNDEFINED "));
1466 1467
    break;
  case VIEW_ALGORITHM_TMPTABLE:
1468
    buff->append(STRING_WITH_LEN("TEMPTABLE "));
1469 1470
    break;
  case VIEW_ALGORITHM_MERGE:
1471
    buff->append(STRING_WITH_LEN("MERGE "));
1472 1473 1474 1475 1476
    break;
  default:
    DBUG_ASSERT(0); // never should happen
  }
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1477

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
/*
  Append DEFINER clause to the given buffer.
  
  SYNOPSIS
    append_definer()
    thd           [in] thread handle
    buffer        [inout] buffer to hold DEFINER clause
    definer_user  [in] user name part of definer
    definer_host  [in] host name part of definer
*/

void append_definer(THD *thd, String *buffer, const LEX_STRING *definer_user,
                    const LEX_STRING *definer_host)
{
  buffer->append(STRING_WITH_LEN("DEFINER="));
  append_identifier(thd, buffer, definer_user->str, definer_user->length);
  buffer->append('@');
  append_identifier(thd, buffer, definer_host->str, definer_host->length);
  buffer->append(' ');
}


1500
int
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1501 1502 1503 1504 1505 1506 1507 1508
view_store_create_info(THD *thd, TABLE_LIST *table, String *buff)
{
  my_bool foreign_db_mode= (thd->variables.sql_mode & (MODE_POSTGRESQL |
                                                       MODE_ORACLE |
                                                       MODE_MSSQL |
                                                       MODE_DB2 |
                                                       MODE_MAXDB |
                                                       MODE_ANSI)) != 0;
1509 1510 1511 1512 1513
  /*
     Compact output format for view can be used
     - if user has db of this view as current db
     - if this view only references table inside it's own db
  */
1514
  if (!thd->db || strcmp(thd->db, table->view_db.str))
1515 1516 1517 1518
    table->compact_view_format= FALSE;
  else
  {
    TABLE_LIST *tbl;
1519
    table->compact_view_format= TRUE;
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    for (tbl= thd->lex->query_tables;
         tbl;
         tbl= tbl->next_global)
    {
      if (strcmp(table->view_db.str, tbl->view ? tbl->view_db.str :tbl->db)!= 0)
      {
        table->compact_view_format= FALSE;
        break;
      }
    }
  }

1532
  buff->append(STRING_WITH_LEN("CREATE "));
1533
  if (!foreign_db_mode)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1534
  {
1535
    view_store_options(thd, table, buff);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1536
  }
1537
  buff->append(STRING_WITH_LEN("VIEW "));
1538 1539 1540 1541 1542
  if (!table->compact_view_format)
  {
    append_identifier(thd, buff, table->view_db.str, table->view_db.length);
    buff->append('.');
  }
1543
  append_identifier(thd, buff, table->view_name.str, table->view_name.length);
1544
  buff->append(STRING_WITH_LEN(" AS "));
1545 1546 1547 1548 1549 1550 1551

  /*
    We can't just use table->query, because our SQL_MODE may trigger
    a different syntax, like when ANSI_QUOTES is defined.
  */
  table->view->unit.print(buff);

1552 1553 1554
  if (table->with_check != VIEW_CHECK_NONE)
  {
    if (table->with_check == VIEW_CHECK_LOCAL)
1555
      buff->append(STRING_WITH_LEN(" WITH LOCAL CHECK OPTION"));
1556
    else
1557
      buff->append(STRING_WITH_LEN(" WITH CASCADED CHECK OPTION"));
1558
  }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1559 1560 1561 1562
  return 0;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1563
/****************************************************************************
1564 1565
  Return info about all processes
  returns for each thread: thread id, user, host, db, command, info
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1566 1567 1568 1569
****************************************************************************/

class thread_info :public ilink {
public:
1570 1571 1572 1573
  static void *operator new(size_t size)
  {
    return (void*) sql_alloc((uint) size);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1574
  static void operator delete(void *ptr __attribute__((unused)),
1575 1576
                              size_t size __attribute__((unused)))
  { TRASH(ptr, size); }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1577

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1578 1579
  ulong thread_id;
  time_t start_time;
1580
  uint   command;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1581 1582 1583 1584
  const char *user,*host,*db,*proc_info,*state_info;
  char *query;
};

1585
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1586 1587 1588 1589 1590 1591 1592 1593
template class I_List<thread_info>;
#endif

void mysqld_list_processes(THD *thd,const char *user, bool verbose)
{
  Item *field;
  List<Item> field_list;
  I_List<thread_info> thread_infos;
1594 1595
  ulong max_query_length= (verbose ? thd->variables.max_allowed_packet :
			   PROCESS_LIST_WIDTH);
1596
  Protocol *protocol= thd->protocol;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1597 1598
  DBUG_ENTER("mysqld_list_processes");

1599
  field_list.push_back(new Item_int("Id", 0, MY_INT32_NUM_DECIMAL_DIGITS));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1600
  field_list.push_back(new Item_empty_string("User",16));
1601
  field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN));
1602
  field_list.push_back(field=new Item_empty_string("db",NAME_CHAR_LEN));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1603 1604
  field->maybe_null=1;
  field_list.push_back(new Item_empty_string("Command",16));
1605
  field_list.push_back(new Item_return_int("Time",7, MYSQL_TYPE_LONG));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1606 1607 1608 1609
  field_list.push_back(field=new Item_empty_string("State",30));
  field->maybe_null=1;
  field_list.push_back(field=new Item_empty_string("Info",max_query_length));
  field->maybe_null=1;
1610 1611
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1612 1613 1614 1615 1616 1617 1618 1619 1620
    DBUG_VOID_RETURN;

  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
  if (!thd->killed)
  {
    I_List_iterator<THD> it(threads);
    THD *tmp;
    while ((tmp=it++))
    {
1621
      Security_context *tmp_sctx= tmp->security_ctx;
1622
      struct st_my_thread_var *mysys_var;
1623
      if ((tmp->vio_ok() || tmp->system_thread) &&
1624
          (!user || (tmp_sctx->user && !strcmp(tmp_sctx->user, user))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1625
      {
1626
        thread_info *thd_info= new thread_info;
1627 1628

        thd_info->thread_id=tmp->thread_id;
1629 1630 1631 1632 1633
        thd_info->user= thd->strdup(tmp_sctx->user ? tmp_sctx->user :
                                    (tmp->system_thread ?
                                     "system user" : "unauthenticated user"));
	if (tmp->peer_port && (tmp_sctx->host || tmp_sctx->ip) &&
            thd->security_ctx->host_or_ip[0])
1634
	{
1635
	  if ((thd_info->host= (char*) thd->alloc(LIST_PROCESS_HOST_LEN+1)))
1636
	    my_snprintf((char *) thd_info->host, LIST_PROCESS_HOST_LEN,
1637
			"%s:%u", tmp_sctx->host_or_ip, tmp->peer_port);
1638 1639
	}
	else
1640 1641 1642
	  thd_info->host= thd->strdup(tmp_sctx->host_or_ip[0] ? 
                                      tmp_sctx->host_or_ip : 
                                      tmp_sctx->host ? tmp_sctx->host : "");
1643 1644 1645
        if ((thd_info->db=tmp->db))             // Safe test
          thd_info->db=thd->strdup(thd_info->db);
        thd_info->command=(int) tmp->command;
1646 1647
        if ((mysys_var= tmp->mysys_var))
          pthread_mutex_lock(&mysys_var->mutex);
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1648
        thd_info->proc_info= (char*) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0);
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1649
#ifndef EMBEDDED_LIBRARY
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
        thd_info->state_info= (char*) (tmp->locked ? "Locked" :
                                       tmp->net.reading_or_writing ?
                                       (tmp->net.reading_or_writing == 2 ?
                                        "Writing to net" :
                                        thd_info->command == COM_SLEEP ? "" :
                                        "Reading from net") :
                                       tmp->proc_info ? tmp->proc_info :
                                       tmp->mysys_var &&
                                       tmp->mysys_var->current_cond ?
                                       "Waiting on cond" : NullS);
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1660 1661 1662
#else
        thd_info->state_info= (char*)"Writing to net";
#endif
1663 1664
        if (mysys_var)
          pthread_mutex_unlock(&mysys_var->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1665

1666 1667 1668
#ifdef EXTRA_DEBUG
        thd_info->start_time= tmp->time_after_lock;
#else
1669
        thd_info->start_time= tmp->start_time;
1670
#endif
1671 1672 1673
        thd_info->query=0;
        if (tmp->query)
        {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1674 1675 1676 1677 1678
	  /* 
            query_length is always set to 0 when we set query = NULL; see
	    the comment in sql_class.h why this prevents crashes in possible
            races with query_length
          */
1679
          uint length= min(max_query_length, tmp->query_length);
1680
          thd_info->query=(char*) thd->strmake(tmp->query,length);
1681 1682
        }
        thread_infos.append(thd_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1683 1684 1685 1686 1687 1688
      }
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_thread_count));

  thread_info *thd_info;
1689
  time_t now= time(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1690 1691
  while ((thd_info=thread_infos.get()))
  {
1692 1693
    protocol->prepare_for_resend();
    protocol->store((ulonglong) thd_info->thread_id);
1694 1695 1696
    protocol->store(thd_info->user, system_charset_info);
    protocol->store(thd_info->host, system_charset_info);
    protocol->store(thd_info->db, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1697
    if (thd_info->proc_info)
1698
      protocol->store(thd_info->proc_info, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1699
    else
1700
      protocol->store(command_name[thd_info->command].str, system_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1701
    if (thd_info->start_time)
1702
      protocol->store((uint32) (now - thd_info->start_time));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1703
    else
1704
      protocol->store_null();
1705 1706
    protocol->store(thd_info->state_info, system_charset_info);
    protocol->store(thd_info->query, system_charset_info);
1707
    if (protocol->write())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1708 1709
      break; /* purecov: inspected */
  }
1710
  send_eof(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1711 1712 1713
  DBUG_VOID_RETURN;
}

1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
int fill_schema_processlist(THD* thd, TABLE_LIST* tables, COND* cond)
{
  TABLE *table= tables->table;
  CHARSET_INFO *cs= system_charset_info;
  char *user;
  time_t now= time(0);
  DBUG_ENTER("fill_process_list");

  user= thd->security_ctx->master_access & PROCESS_ACL ?
        NullS : thd->security_ctx->priv_user;

  VOID(pthread_mutex_lock(&LOCK_thread_count));

  if (!thd->killed)
  {
    I_List_iterator<THD> it(threads);
    THD* tmp;

    while ((tmp= it++))
    {
      Security_context *tmp_sctx= tmp->security_ctx;
      struct st_my_thread_var *mysys_var;
      const char *val;

      if ((!tmp->vio_ok() && !tmp->system_thread) ||
          (user && (!tmp_sctx->user || strcmp(tmp_sctx->user, user))))
        continue;

      restore_record(table, s->default_values);
      /* ID */
      table->field[0]->store((longlong) tmp->thread_id, TRUE);
      /* USER */
      val= tmp_sctx->user ? tmp_sctx->user :
            (tmp->system_thread ? "system user" : "unauthenticated user");
      table->field[1]->store(val, strlen(val), cs);
      /* HOST */
      if (tmp->peer_port && (tmp_sctx->host || tmp_sctx->ip) &&
          thd->security_ctx->host_or_ip[0])
      {
        char host[LIST_PROCESS_HOST_LEN + 1];
        my_snprintf(host, LIST_PROCESS_HOST_LEN, "%s:%u",
                    tmp_sctx->host_or_ip, tmp->peer_port);
        table->field[2]->store(host, strlen(host), cs);
      }
      else
        table->field[2]->store(tmp_sctx->host_or_ip,
                               strlen(tmp_sctx->host_or_ip), cs);
      /* DB */
      if (tmp->db)
      {
        table->field[3]->store(tmp->db, strlen(tmp->db), cs);
        table->field[3]->set_notnull();
      }

      if ((mysys_var= tmp->mysys_var))
        pthread_mutex_lock(&mysys_var->mutex);
      /* COMMAND */
      if ((val= (char *) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0)))
        table->field[4]->store(val, strlen(val), cs);
      else
        table->field[4]->store(command_name[tmp->command].str,
                               command_name[tmp->command].length, cs);
1776
      /* MYSQL_TIME */
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
      table->field[5]->store((uint32)(tmp->start_time ?
                                      now - tmp->start_time : 0), TRUE);
      /* STATE */
#ifndef EMBEDDED_LIBRARY
      val= (char*) (tmp->locked ? "Locked" :
                    tmp->net.reading_or_writing ?
                    (tmp->net.reading_or_writing == 2 ?
                     "Writing to net" :
                     tmp->command == COM_SLEEP ? "" :
                     "Reading from net") :
                    tmp->proc_info ? tmp->proc_info :
                    tmp->mysys_var &&
                    tmp->mysys_var->current_cond ?
                    "Waiting on cond" : NullS);
#else
      val= (char *) "Writing to net";
#endif
      if (val)
      {
        table->field[6]->store(val, strlen(val), cs);
        table->field[6]->set_notnull();
      }

      if (mysys_var)
        pthread_mutex_unlock(&mysys_var->mutex);

      /* INFO */
      if (tmp->query)
      {
        table->field[7]->store(tmp->query,
1807 1808
                               min(PROCESS_LIST_INFO_WIDTH,
                                   tmp->query_length), cs);
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
        table->field[7]->set_notnull();
      }

      if (schema_table_store_record(thd, table))
      {
        VOID(pthread_mutex_unlock(&LOCK_thread_count));
        DBUG_RETURN(1);
      }
    }
  }

  VOID(pthread_mutex_unlock(&LOCK_thread_count));
  DBUG_RETURN(0);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1824
/*****************************************************************************
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1825
  Status functions
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1826 1827
*****************************************************************************/

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
static DYNAMIC_ARRAY all_status_vars;
static bool status_vars_inited= 0;
static int show_var_cmp(const void *var1, const void *var2)
{
  return strcmp(((SHOW_VAR*)var1)->name, ((SHOW_VAR*)var2)->name);
}

/*
  deletes all the SHOW_UNDEF elements from the array and calls
  delete_dynamic() if it's completely empty.
*/
static void shrink_var_array(DYNAMIC_ARRAY *array)
{
1841
  uint a,b;
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
  SHOW_VAR *all= dynamic_element(array, 0, SHOW_VAR *);

  for (a= b= 0; b < array->elements; b++)
    if (all[b].type != SHOW_UNDEF)
      all[a++]= all[b];
  if (a)
  {
    bzero(all+a, sizeof(SHOW_VAR)); // writing NULL-element to the end
    array->elements= a;
  }
  else // array is completely empty - delete it
    delete_dynamic(array);
}

/*
  Adds an array of SHOW_VAR entries to the output of SHOW STATUS

  SYNOPSIS
    add_status_vars(SHOW_VAR *list)
    list - an array of SHOW_VAR entries to add to all_status_vars
           the last entry must be {0,0,SHOW_UNDEF}

  NOTE
    The handling of all_status_vars[] is completely internal, it's allocated
    automatically when something is added to it, and deleted completely when
    the last entry is removed.

    As a special optimization, if add_status_vars() is called before
    init_status_vars(), it assumes "startup mode" - neither concurrent access
    to the array nor SHOW STATUS are possible (thus it skips locks and qsort)

    The last entry of the all_status_vars[] should always be {0,0,SHOW_UNDEF}
*/
int add_status_vars(SHOW_VAR *list)
{
  int res= 0;
  if (status_vars_inited)
    pthread_mutex_lock(&LOCK_status);
  if (!all_status_vars.buffer && // array is not allocated yet - do it now
      my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20))
  {
    res= 1;
    goto err;
  }
  while (list->name)
1887 1888
    res|= insert_dynamic(&all_status_vars, (uchar*)list++);
  res|= insert_dynamic(&all_status_vars, (uchar*)list); // appending NULL-element
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
  all_status_vars.elements--; // but next insert_dynamic should overwite it
  if (status_vars_inited)
    sort_dynamic(&all_status_vars, show_var_cmp);
err:
  if (status_vars_inited)
    pthread_mutex_unlock(&LOCK_status);
  return res;
}

/*
  Make all_status_vars[] usable for SHOW STATUS

  NOTE
    See add_status_vars(). Before init_status_vars() call, add_status_vars()
    works in a special fast "startup" mode. Thus init_status_vars()
    should be called as late as possible but before enabling multi-threading.
*/
void init_status_vars()
{
  status_vars_inited=1;
  sort_dynamic(&all_status_vars, show_var_cmp);
}

antony@ppcg5.local's avatar
antony@ppcg5.local committed
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
void reset_status_vars()
{
  SHOW_VAR *ptr= (SHOW_VAR*) all_status_vars.buffer;
  SHOW_VAR *last= ptr + all_status_vars.elements;
  for (; ptr < last; ptr++)
  {
    /* Note that SHOW_LONG_NOFLUSH variables are not reset */
    if (ptr->type == SHOW_LONG)
      *(ulong*) ptr->value= 0;
  }  
}

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
/*
  catch-all cleanup function, cleans up everything no matter what

  DESCRIPTION
    This function is not strictly required if all add_to_status/
    remove_status_vars are properly paired, but it's a safety measure that
    deletes everything from the all_status_vars[] even if some
    remove_status_vars were forgotten
*/
void free_status_vars()
{
  delete_dynamic(&all_status_vars);
}

/*
  Removes an array of SHOW_VAR entries from the output of SHOW STATUS

  SYNOPSIS
    remove_status_vars(SHOW_VAR *list)
    list - an array of SHOW_VAR entries to remove to all_status_vars
           the last entry must be {0,0,SHOW_UNDEF}

  NOTE
    there's lots of room for optimizing this, especially in non-sorted mode,
    but nobody cares - it may be called only in case of failed plugin
    initialization in the mysqld startup.
*/
1951

1952 1953 1954 1955 1956 1957
void remove_status_vars(SHOW_VAR *list)
{
  if (status_vars_inited)
  {
    pthread_mutex_lock(&LOCK_status);
    SHOW_VAR *all= dynamic_element(&all_status_vars, 0, SHOW_VAR *);
1958
    int a= 0, b= all_status_vars.elements, c= (a+b)/2;
1959 1960 1961

    for (; list->name; list++)
    {
1962
      int res= 0;
1963 1964 1965 1966 1967 1968 1969
      for (a= 0, b= all_status_vars.elements; b-a > 1; c= (a+b)/2)
      {
        res= show_var_cmp(list, all+c);
        if (res < 0)
          b= c;
        else if (res > 0)
          a= c;
1970 1971
        else
          break;
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
      }
      if (res == 0)
        all[c].type= SHOW_UNDEF;
    }
    shrink_var_array(&all_status_vars);
    pthread_mutex_unlock(&LOCK_status);
  }
  else
  {
    SHOW_VAR *all= dynamic_element(&all_status_vars, 0, SHOW_VAR *);
1982
    uint i;
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
    for (; list->name; list++)
    {
      for (i= 0; i < all_status_vars.elements; i++)
      {
        if (show_var_cmp(list, all+i))
          continue;
        all[i].type= SHOW_UNDEF;
        break;
      }
    }
    shrink_var_array(&all_status_vars);
  }
}

1997 1998 1999 2000 2001 2002
inline void make_upper(char *buf)
{
  for (; *buf; buf++)
    *buf= my_toupper(system_charset_info, *buf);
}

2003
static bool show_status_array(THD *thd, const char *wild,
2004
                              SHOW_VAR *variables,
2005 2006
                              enum enum_var_type value_type,
                              struct system_status_var *status_var,
2007 2008
                              const char *prefix, TABLE *table,
                              bool ucase_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2009
{
2010 2011 2012
  MY_ALIGNED_BYTE_ARRAY(buff_data, SHOW_VAR_FUNC_BUFF_SIZE, long);
  char * const buff= (char *) &buff_data;
  char *prefix_end;
2013 2014
  /* the variable name should not be longer than 64 characters */
  char name_buffer[64];
2015
  int len;
2016
  LEX_STRING null_lex_str;
2017
  SHOW_VAR tmp, *var;
2018
  DBUG_ENTER("show_status_array");
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2019

2020
  null_lex_str.str= 0;				// For sys_var->value_ptr()
2021
  null_lex_str.length= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2022

2023
  prefix_end=strnmov(name_buffer, prefix, sizeof(name_buffer)-1);
2024 2025
  if (*prefix)
    *prefix_end++= '_';
2026 2027
  len=name_buffer + sizeof(name_buffer) - prefix_end;

2028
  for (; variables->name; variables++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2029
  {
2030 2031
    strnmov(prefix_end, variables->name, len);
    name_buffer[sizeof(name_buffer)-1]=0;       /* Safety */
2032 2033
    if (ucase_names)
      make_upper(name_buffer);
2034

2035 2036 2037 2038
    /*
      if var->type is SHOW_FUNC, call the function.
      Repeat as necessary, if new var is again SHOW_FUNC
    */
2039
    for (var=variables; var->type == SHOW_FUNC; var= &tmp)
2040
      ((mysql_show_var_func)(var->value))(thd, &tmp, buff);
2041 2042 2043

    SHOW_TYPE show_type=var->type;
    if (show_type == SHOW_ARRAY)
2044
    {
2045 2046
      show_status_array(thd, wild, (SHOW_VAR *) var->value, value_type,
                        status_var, name_buffer, table, ucase_names);
2047 2048
    }
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2049
    {
2050 2051
      if (!(wild && wild[0] && wild_case_compare(system_charset_info,
                                                 name_buffer, wild)))
2052
      {
2053
        char *value=var->value;
2054
        const char *pos, *end;                  // We assign a lot of const's
2055

antony@ppcg5.local's avatar
antony@ppcg5.local committed
2056 2057
        pthread_mutex_lock(&LOCK_global_system_variables);

2058 2059
        if (show_type == SHOW_SYS)
        {
2060
          show_type= ((sys_var*) value)->show_type();
2061 2062 2063 2064 2065
          value=     (char*) ((sys_var*) value)->value_ptr(thd, value_type,
                                                           &null_lex_str);
        }

        pos= end= buff;
2066 2067 2068 2069
        /*
          note that value may be == buff. All SHOW_xxx code below
          should still work in this case
        */
2070
        switch (show_type) {
2071 2072 2073 2074 2075 2076
        case SHOW_DOUBLE_STATUS:
        {
          value= ((char *) status_var + (ulong) value);
          end= buff + sprintf(buff, "%f", *(double*) value);
          break;
        }
2077 2078 2079 2080
        case SHOW_LONG_STATUS:
          value= ((char *) status_var + (ulong) value);
          /* fall through */
        case SHOW_LONG:
2081
        case SHOW_LONG_NOFLUSH: // the difference lies in refresh_status()
2082 2083
          end= int10_to_str(*(long*) value, buff, 10);
          break;
2084 2085
        case SHOW_LONGLONG_STATUS:
          value= ((char *) status_var + (ulonglong) value);
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
        case SHOW_LONGLONG:
          end= longlong10_to_str(*(longlong*) value, buff, 10);
          break;
        case SHOW_HA_ROWS:
          end= longlong10_to_str((longlong) *(ha_rows*) value, buff, 10);
          break;
        case SHOW_BOOL:
          end= strmov(buff, *(bool*) value ? "ON" : "OFF");
          break;
        case SHOW_MY_BOOL:
          end= strmov(buff, *(my_bool*) value ? "ON" : "OFF");
          break;
        case SHOW_INT:
          end= int10_to_str((long) *(uint32*) value, buff, 10);
          break;
        case SHOW_HAVE:
petr@mysql.com's avatar
petr@mysql.com committed
2102 2103 2104 2105 2106 2107
        {
          SHOW_COMP_OPTION tmp= *(SHOW_COMP_OPTION*) value;
          pos= show_comp_option_name[(int) tmp];
          end= strend(pos);
          break;
        }
2108
        case SHOW_CHAR:
petr@mysql.com's avatar
petr@mysql.com committed
2109 2110 2111 2112 2113 2114
        {
          if (!(pos= value))
            pos= "";
          end= strend(pos);
          break;
        }
2115
       case SHOW_CHAR_PTR:
petr@mysql.com's avatar
petr@mysql.com committed
2116 2117 2118 2119 2120 2121
        {
          if (!(pos= *(char**) value))
            pos= "";
          end= strend(pos);
          break;
        }
2122
        case SHOW_KEY_CACHE_LONG:
2123
          value= (char*) dflt_key_cache + (ulong)value;
2124 2125
          end= int10_to_str(*(long*) value, buff, 10);
          break;
2126
        case SHOW_KEY_CACHE_LONGLONG:
2127
          value= (char*) dflt_key_cache + (ulong)value;
2128 2129
	  end= longlong10_to_str(*(longlong*) value, buff, 10);
	  break;
2130
        case SHOW_UNDEF:
2131 2132
          break;                                        // Return empty string
        case SHOW_SYS:                                  // Cannot happen
2133
        default:
2134
          DBUG_ASSERT(0);
2135 2136
          break;
        }
2137
        restore_record(table, s->default_values);
2138 2139 2140
        table->field[0]->store(name_buffer, strlen(name_buffer),
                               system_charset_info);
        table->field[1]->store(pos, (uint32) (end - pos), system_charset_info);
2141
        table->field[1]->set_notnull();
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2142 2143 2144

        pthread_mutex_unlock(&LOCK_global_system_variables);

2145 2146
        if (schema_table_store_record(thd, table))
          DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2147 2148 2149
      }
    }
  }
2150 2151 2152 2153 2154

  DBUG_RETURN(FALSE);
}


2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
/* collect status for all running threads */

void calc_sum_of_all_status(STATUS_VAR *to)
{
  DBUG_ENTER("calc_sum_of_all_status");

  /* Ensure that thread id not killed during loop */
  VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list

  I_List_iterator<THD> it(threads);
  THD *tmp;
  
  /* Get global values as base */
  *to= global_status_var;
  
  /* Add to this status from existing threads */
  while ((tmp= it++))
    add_to_status(to, &tmp->status_var);
  
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
  DBUG_VOID_RETURN;
}


2179
/* This is only used internally, but we need it here as a forward reference */
2180 2181 2182 2183 2184 2185 2186 2187
extern ST_SCHEMA_TABLE schema_tables[];

typedef struct st_index_field_values
{
  const char *db_value, *table_value;
} INDEX_FIELD_VALUES;


2188 2189 2190 2191 2192 2193 2194
/*
  Store record to I_S table, convert HEAP table
  to MyISAM if necessary

  SYNOPSIS
    schema_table_store_record()
    thd                   thread handler
2195 2196
    table                 Information schema table to be updated

2197 2198
  RETURN
    0	                  success
2199
    1	                  error
2200 2201
*/

2202
bool schema_table_store_record(THD *thd, TABLE *table)
2203 2204
{
  int error;
2205
  if ((error= table->file->ha_write_row(table->record[0])))
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
  {
    if (create_myisam_from_heap(thd, table, 
                                table->pos_in_table_list->schema_table_param,
                                error, 0))
      return 1;
  }
  return 0;
}


2216 2217 2218
void get_index_field_values(LEX *lex, INDEX_FIELD_VALUES *index_field_values)
{
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
2219
  switch (lex->sql_command) {
2220 2221 2222 2223 2224
  case SQLCOM_SHOW_DATABASES:
    index_field_values->db_value= wild;
    break;
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_TABLE_STATUS:
2225
  case SQLCOM_SHOW_TRIGGERS:
2226
  case SQLCOM_SHOW_EVENTS:
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
2227
    index_field_values->db_value= lex->select_lex.db;
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
    index_field_values->table_value= wild;
    break;
  default:
    index_field_values->db_value= NullS;
    index_field_values->table_value= NullS;
    break;
  }
}


int make_table_list(THD *thd, SELECT_LEX *sel,
                    char *db, char *table)
{
  Table_ident *table_ident;
  LEX_STRING ident_db, ident_table;
  ident_db.str= db; 
  ident_db.length= strlen(db);
  ident_table.str= table;
  ident_table.length= strlen(table);
  table_ident= new Table_ident(thd, ident_db, ident_table, 1);
  sel->init_query();
2249
  if (!sel->add_table_to_list(thd, table_ident, 0, 0, TL_READ))
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
    return 1;
  return 0;
}


bool uses_only_table_name_fields(Item *item, TABLE_LIST *table)
{
  if (item->type() == Item::FUNC_ITEM)
  {
    Item_func *item_func= (Item_func*)item;
2260
    for (uint i=0; i<item_func->argument_count(); i++)
2261
    {
2262
      if (!uses_only_table_name_fields(item_func->arguments()[i], table))
2263
        return 0;
2264
    }
2265 2266 2267 2268 2269 2270 2271
  }
  else if (item->type() == Item::FIELD_ITEM)
  {
    Item_field *item_field= (Item_field*)item;
    CHARSET_INFO *cs= system_charset_info;
    ST_SCHEMA_TABLE *schema_table= table->schema_table;
    ST_FIELD_INFO *field_info= schema_table->fields_info;
2272 2273
    const char *field_name1= schema_table->idx_field1 >= 0 ? field_info[schema_table->idx_field1].field_name : "";
    const char *field_name2= schema_table->idx_field2 >= 0 ? field_info[schema_table->idx_field2].field_name : "";
2274 2275 2276 2277 2278 2279 2280
    if (table->table != item_field->field->table ||
        (cs->coll->strnncollsp(cs, (uchar *) field_name1, strlen(field_name1),
                               (uchar *) item_field->field_name, 
                               strlen(item_field->field_name), 0) &&
         cs->coll->strnncollsp(cs, (uchar *) field_name2, strlen(field_name2),
                               (uchar *) item_field->field_name, 
                               strlen(item_field->field_name), 0)))
2281 2282
      return 0;
  }
2283 2284
  else if (item->type() == Item::REF_ITEM)
    return uses_only_table_name_fields(item->real_item(), table);
2285 2286 2287 2288
  if (item->type() == Item::SUBSELECT_ITEM &&
      !item->const_item())
    return 0;

2289
  return 1;
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
}


static COND * make_cond_for_info_schema(COND *cond, TABLE_LIST *table)
{
  if (!cond)
    return (COND*) 0;
  if (cond->type() == Item::COND_ITEM)
  {
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
    {
      /* Create new top level AND item */
      Item_cond_and *new_cond=new Item_cond_and;
      if (!new_cond)
	return (COND*) 0;
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
      Item *item;
      while ((item=li++))
      {
	Item *fix= make_cond_for_info_schema(item, table);
	if (fix)
	  new_cond->argument_list()->push_back(fix);
      }
      switch (new_cond->argument_list()->elements) {
      case 0:
	return (COND*) 0;
      case 1:
	return new_cond->argument_list()->head();
      default:
	new_cond->quick_fix_field();
	return new_cond;
      }
    }
    else
    {						// Or list
      Item_cond_or *new_cond=new Item_cond_or;
      if (!new_cond)
	return (COND*) 0;
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
      Item *item;
      while ((item=li++))
      {
	Item *fix=make_cond_for_info_schema(item, table);
	if (!fix)
	  return (COND*) 0;
	new_cond->argument_list()->push_back(fix);
      }
      new_cond->quick_fix_field();
      new_cond->top_level_item();
      return new_cond;
    }
  }

  if (!uses_only_table_name_fields(cond, table))
    return (COND*) 0;
  return cond;
}


2349 2350 2351 2352 2353 2354
enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table)
{
  return (enum enum_schema_tables) (schema_table - &schema_tables[0]);
}


2355
/*
2356
  Create db names list. Information schema name always is first in list
2357 2358

  SYNOPSIS
2359
    make_db_list()
2360 2361 2362
    thd                   thread handler
    files                 list of db names
    wild                  wild string
2363 2364
    idx_field_vals        idx_field_vals->db_name contains db name or
                          wild string
2365 2366
    with_i_schema         returns 1 if we added 'IS' name to list
                          otherwise returns 0
2367 2368
    is_wild_value         if value is 1 then idx_field_vals->db_name is
                          wild string otherwise it's db name; 
2369 2370

  RETURN
2371 2372
    zero                  success
    non-zero              error
2373 2374
*/

2375 2376 2377
int make_db_list(THD *thd, List<char> *files,
                 INDEX_FIELD_VALUES *idx_field_vals,
                 bool *with_i_schema, bool is_wild_value)
2378
{
2379
  LEX *lex= thd->lex;
2380
  *with_i_schema= 0;
2381
  get_index_field_values(lex, idx_field_vals);
2382

2383
  if (is_wild_value)
2384
  {
2385 2386 2387 2388 2389
    /*
      This part of code is only for SHOW DATABASES command.
      idx_field_vals->db_value can be 0 when we don't use
      LIKE clause (see also get_index_field_values() function)
    */
2390 2391
    if (!idx_field_vals->db_value ||
        !wild_case_compare(system_charset_info, 
2392
                           INFORMATION_SCHEMA_NAME.str,
2393 2394 2395
                           idx_field_vals->db_value))
    {
      *with_i_schema= 1;
2396
      if (files->push_back(thd->strdup(INFORMATION_SCHEMA_NAME.str)))
2397 2398
        return 1;
    }
2399 2400
    return (find_files(thd, files, NullS, mysql_data_home,
                       idx_field_vals->db_value, 1) != FIND_FILES_OK);
2401
  }
2402

2403 2404 2405
  /*
    This part of code is for SHOW TABLES, SHOW TABLE STATUS commands.
    idx_field_vals->db_value can't be 0 (see get_index_field_values()
2406
    function).
2407
  */
2408
  if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND)
2409
  {
2410
    if (!my_strcasecmp(system_charset_info, INFORMATION_SCHEMA_NAME.str,
2411 2412 2413
                       idx_field_vals->db_value))
    {
      *with_i_schema= 1;
2414
      return files->push_back(thd->strdup(INFORMATION_SCHEMA_NAME.str));
2415 2416 2417 2418
    }
    return files->push_back(thd->strdup(idx_field_vals->db_value));
  }

2419 2420 2421 2422
  /*
    Create list of existing databases. It is used in case
    of select from information schema table
  */
2423
  if (files->push_back(thd->strdup(INFORMATION_SCHEMA_NAME.str)))
2424 2425
    return 1;
  *with_i_schema= 1;
2426 2427
  return (find_files(thd, files, NullS,
                     mysql_data_home, NullS, 1) != FIND_FILES_OK);
2428 2429
}

brian@zim.(none)'s avatar
brian@zim.(none) committed
2430 2431 2432 2433 2434 2435
struct st_add_schema_table 
{
  List<char> *files;
  const char *wild;
};

antony@ppcg5.local's avatar
antony@ppcg5.local committed
2436
static my_bool add_schema_table(THD *thd, plugin_ref plugin,
brian@zim.(none)'s avatar
brian@zim.(none) committed
2437 2438 2439 2440 2441
                                void* p_data)
{
  st_add_schema_table *data= (st_add_schema_table *)p_data;
  List<char> *file_list= data->files;
  const char *wild= data->wild;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2442
  ST_SCHEMA_TABLE *schema_table= plugin_data(plugin, ST_SCHEMA_TABLE *);
brian@zim.(none)'s avatar
brian@zim.(none) committed
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
  DBUG_ENTER("add_schema_table");

  if (schema_table->hidden)
      DBUG_RETURN(0);
  if (wild)
  {
    if (lower_case_table_names)
    {
      if (wild_case_compare(files_charset_info,
                            schema_table->table_name,
                            wild))
        DBUG_RETURN(0);
    }
    else if (wild_compare(schema_table->table_name, wild, 0))
      DBUG_RETURN(0);
  }

  if (file_list->push_back(thd->strdup(schema_table->table_name)))
    DBUG_RETURN(1);

  DBUG_RETURN(0);
}
2465 2466 2467 2468

int schema_tables_add(THD *thd, List<char> *files, const char *wild)
{
  ST_SCHEMA_TABLE *tmp_schema_table= schema_tables;
brian@zim.(none)'s avatar
brian@zim.(none) committed
2469 2470 2471
  st_add_schema_table add_data;
  DBUG_ENTER("schema_tables_add");

2472
  for (; tmp_schema_table->table_name; tmp_schema_table++)
2473
  {
2474 2475
    if (tmp_schema_table->hidden)
      continue;
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    if (wild)
    {
      if (lower_case_table_names)
      {
        if (wild_case_compare(files_charset_info,
                              tmp_schema_table->table_name,
                              wild))
          continue;
      }
      else if (wild_compare(tmp_schema_table->table_name, wild, 0))
        continue;
    }
    if (files->push_back(thd->strdup(tmp_schema_table->table_name)))
brian@zim.(none)'s avatar
brian@zim.(none) committed
2489
      DBUG_RETURN(1);
2490
  }
brian@zim.(none)'s avatar
brian@zim.(none) committed
2491 2492 2493 2494 2495 2496 2497 2498

  add_data.files= files;
  add_data.wild= wild;
  if (plugin_foreach(thd, add_schema_table,
                     MYSQL_INFORMATION_SCHEMA_PLUGIN, &add_data))
      DBUG_RETURN(1);

  DBUG_RETURN(0);
2499 2500 2501
}


2502 2503 2504 2505 2506
int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
{
  LEX *lex= thd->lex;
  TABLE *table= tables->table;
  SELECT_LEX *select_lex= &lex->select_lex;
2507
  SELECT_LEX *old_all_select_lex= lex->all_selects_list;
2508
  enum_sql_command save_sql_command= lex->sql_command;
2509
  SELECT_LEX *lsel= tables->schema_select_lex;
2510
  ST_SCHEMA_TABLE *schema_table= tables->schema_table;
2511 2512
  SELECT_LEX sel;
  INDEX_FIELD_VALUES idx_field_vals;
2513
  char path[FN_REFLEN], *base_name, *orig_base_name, *file_name;
2514 2515 2516 2517
  uint len;
  bool with_i_schema;
  enum enum_schema_tables schema_table_idx;
  List<char> bases;
monty@mysql.com's avatar
monty@mysql.com committed
2518
  List_iterator_fast<char> it(bases);
2519
  COND *partial_cond;
2520
  uint derived_tables= lex->derived_tables; 
monty@mysql.com's avatar
monty@mysql.com committed
2521
  int error= 1;
2522
  enum legacy_db_type not_used;
2523
  Open_tables_state open_tables_state_backup;
2524
  bool save_view_prepare_mode= lex->view_prepare_mode;
2525
  Query_tables_list query_tables_list_backup;
2526 2527 2528
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  Security_context *sctx= thd->security_ctx;
#endif
2529 2530 2531
  DBUG_ENTER("get_all_tables");

  LINT_INIT(len);
2532

2533
  lex->view_prepare_mode= TRUE;
2534 2535
  lex->reset_n_backup_query_tables_list(&query_tables_list_backup);

2536 2537 2538 2539 2540 2541 2542
  /*
    We should not introduce deadlocks even if we already have some
    tables open and locked, since we won't lock tables which we will
    open and will ignore possible name-locks for these tables.
  */
  thd->reset_n_backup_open_tables_state(&open_tables_state_backup);

2543
  if (lsel && lsel->table_list.first)
2544 2545
  {
    TABLE_LIST *show_table_list= (TABLE_LIST*) lsel->table_list.first;
2546 2547
    bool res;

2548
    lex->all_selects_list= lsel;
2549 2550 2551 2552 2553 2554 2555
    /*
      Restore thd->temporary_tables to be able to process
      temporary tables(only for 'show index' & 'show columns').
      This should be changed when processing of temporary tables for
      I_S tables will be done.
    */
    thd->temporary_tables= open_tables_state_backup.temporary_tables;
2556 2557 2558 2559 2560 2561 2562
    /*
      Let us set fake sql_command so views won't try to merge
      themselves into main statement. If we don't do this,
      SELECT * from information_schema.xxxx will cause problems.
      SQLCOM_SHOW_FIELDS is used because it satisfies 'only_view_structure()' 
    */
    lex->sql_command= SQLCOM_SHOW_FIELDS;
2563 2564
    res= open_normal_and_derived_tables(thd, show_table_list,
                                        MYSQL_LOCK_IGNORE_FLUSH);
2565
    lex->sql_command= save_sql_command;
2566 2567 2568
    /*
      get_all_tables() returns 1 on failure and 0 on success thus
      return only these and not the result code of ::process_table()
2569 2570 2571 2572 2573 2574 2575

      We should use show_table_list->alias instead of 
      show_table_list->table_name because table_name
      could be changed during opening of I_S tables. It's safe
      to use alias because alias contains original table name 
      in this case(this part of code is used only for 
      'show columns' & 'show statistics' commands).
2576 2577
    */
    error= test(schema_table->process_table(thd, show_table_list,
2578 2579 2580 2581 2582
                                            table, res, 
                                            (show_table_list->view ?
                                             show_table_list->view_db.str :
                                             show_table_list->db),
                                            show_table_list->alias));
2583
    thd->temporary_tables= 0;
2584
    close_tables_for_reopen(thd, &show_table_list);
monty@mysql.com's avatar
monty@mysql.com committed
2585
    goto err;
2586 2587
  }

2588
  schema_table_idx= get_schema_table_idx(schema_table);
2589

2590 2591
  if (make_db_list(thd, &bases, &idx_field_vals,
                   &with_i_schema, 0))
monty@mysql.com's avatar
monty@mysql.com committed
2592
    goto err;
2593 2594

  partial_cond= make_cond_for_info_schema(cond, tables);
monty@mysql.com's avatar
monty@mysql.com committed
2595
  it.rewind(); /* To get access to new elements in basis list */
2596 2597 2598 2599 2600

  /*
    Below we generate error for non existing database.
    (to save old behaviour for SHOW TABLES FROM db)
  */
2601
  while ((orig_base_name= base_name= it++) ||
2602
         ((sql_command_flags[save_sql_command] & CF_SHOW_TABLE_COMMAND) &&
2603 2604 2605
	  (base_name= select_lex->db) && !bases.elements))
  {
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2606 2607
    if (!check_access(thd,SELECT_ACL, base_name, 
                      &thd->col_access, 0, 1, with_i_schema) ||
2608 2609
        sctx->master_access & (DB_ACLS | SHOW_DB_ACL) ||
	acl_get(sctx->host, sctx->ip, sctx->priv_user, base_name,0) ||
2610
	!check_grant_db(thd, base_name))
2611 2612 2613
#endif
    {
      List<char> files;
2614 2615 2616
      if (with_i_schema)                      // information schema table names
      {
        if (schema_tables_add(thd, &files, idx_field_vals.table_value))
monty@mysql.com's avatar
monty@mysql.com committed
2617
          goto err;
2618 2619 2620
      }
      else
      {
2621
        len= build_table_filename(path, sizeof(path), base_name, "", "", 0);
2622
        len= FN_LEN - len;
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
        find_files_result res= find_files(thd, &files, base_name, 
                                          path, idx_field_vals.table_value, 0);
        if (res != FIND_FILES_OK)
        {
          /*
            Downgrade errors about problems with database directory to
            warnings if this is not a 'SHOW' command.  Another thread
            may have dropped database, and we may still have a name
            for that directory.
          */
2633
          if (res == FIND_FILES_DIR && lex->sql_command == SQLCOM_END)
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
          {
            push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                         thd->net.last_errno, thd->net.last_error);
            thd->clear_error();
            continue;
          }
          else
          {
            goto err;
          }
        }
2645 2646
        if (lower_case_table_names)
          orig_base_name= thd->strdup(base_name);
2647
      }
2648

2649 2650
      List_iterator_fast<char> it_files(files);
      while ((file_name= it_files++))
2651
      {
2652
	restore_record(table, s->default_values);
2653 2654 2655 2656 2657 2658 2659 2660
        table->field[schema_table->idx_field1]->
          store(base_name, strlen(base_name), system_charset_info);
        table->field[schema_table->idx_field2]->
          store(file_name, strlen(file_name),system_charset_info);
        if (!partial_cond || partial_cond->val_int())
        {
          if (schema_table_idx == SCH_TABLE_NAMES)
          {
2661 2662
            if (lex->verbose ||
                (sql_command_flags[save_sql_command] & CF_STATUS_COMMAND) == 0)
2663
            {
2664
              if (with_i_schema)
2665
              {
2666 2667
                table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"),
                                       system_charset_info);
2668 2669 2670
              }
              else
              {
2671 2672 2673
                build_table_filename(path, sizeof(path),
                                     base_name, file_name, reg_ext, 0);

2674
                switch (mysql_frm_type(thd, path, &not_used)) {
2675
                case FRMTYPE_ERROR:
2676 2677
                  table->field[3]->store(STRING_WITH_LEN("ERROR"),
                                         system_charset_info);
2678 2679
                  break;
                case FRMTYPE_TABLE:
2680 2681
                  table->field[3]->store(STRING_WITH_LEN("BASE TABLE"),
                                         system_charset_info);
2682 2683
                  break;
                case FRMTYPE_VIEW:
2684 2685
                  table->field[3]->store(STRING_WITH_LEN("VIEW"),
                                         system_charset_info);
2686 2687 2688 2689
                  break;
                default:
                  DBUG_ASSERT(0);
                }
2690 2691
              }
            }
2692
            if (schema_table_store_record(thd, table))
2693
              goto err;
2694 2695 2696 2697
          }
          else
          {
            int res;
2698
            /*
2699 2700
              Set the parent lex of 'sel' because it is needed by
              sel.init_query() which is called inside make_table_list.
2701 2702
            */
            sel.parent_lex= lex;
2703
            if (make_table_list(thd, &sel, base_name, file_name))
monty@mysql.com's avatar
monty@mysql.com committed
2704
              goto err;
2705
            TABLE_LIST *show_table_list= (TABLE_LIST*) sel.table_list.first;
2706 2707
            lex->all_selects_list= &sel;
            lex->derived_tables= 0;
2708
            lex->sql_command= SQLCOM_SHOW_FIELDS;
2709 2710
            res= open_normal_and_derived_tables(thd, show_table_list,
                                                MYSQL_LOCK_IGNORE_FLUSH);
2711
            lex->sql_command= save_sql_command;
2712 2713 2714 2715 2716
            /* 
              They can drop table after table names list creation and
              before table opening. We open non existing table and 
              get ER_NO_SUCH_TABLE error. In this case we do not store
              the record into I_S table and clear error.
2717
            */
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
            if (thd->net.last_errno == ER_NO_SUCH_TABLE)
            {
              res= 0;
              thd->clear_error();
            }
            else
            {
              /*
                We should use show_table_list->alias instead of 
                show_table_list->table_name because table_name
                could be changed during opening of I_S tables. It's safe
                to use alias because alias contains original table name 
                in this case.
              */
              res= schema_table->process_table(thd, show_table_list, table,
                                               res, orig_base_name,
                                               show_table_list->alias);
              close_tables_for_reopen(thd, &show_table_list);
              DBUG_ASSERT(!lex->query_tables_own_last);
            }
2738
            if (res)
monty@mysql.com's avatar
monty@mysql.com committed
2739
              goto err;
2740 2741 2742
          }
        }
      }
2743 2744 2745 2746
      /*
        If we have information schema its always the first table and only
        the first table. Reset for other tables.
      */
2747
      with_i_schema= 0;
2748 2749
    }
  }
monty@mysql.com's avatar
monty@mysql.com committed
2750 2751 2752

  error= 0;
err:
2753
  thd->restore_backup_open_tables_state(&open_tables_state_backup);
2754
  lex->restore_backup_query_tables_list(&query_tables_list_backup);
2755 2756
  lex->derived_tables= derived_tables;
  lex->all_selects_list= old_all_select_lex;
2757
  lex->view_prepare_mode= save_view_prepare_mode;
2758
  lex->sql_command= save_sql_command;
monty@mysql.com's avatar
monty@mysql.com committed
2759
  DBUG_RETURN(error);
2760 2761 2762
}


2763
bool store_schema_shemata(THD* thd, TABLE *table, const char *db_name,
2764
                          CHARSET_INFO *cs)
2765
{
2766
  restore_record(table, s->default_values);
2767
  table->field[1]->store(db_name, strlen(db_name), system_charset_info);
2768 2769
  table->field[2]->store(cs->csname, strlen(cs->csname), system_charset_info);
  table->field[3]->store(cs->name, strlen(cs->name), system_charset_info);
2770
  return schema_table_store_record(thd, table);
2771 2772 2773
}


2774 2775
int fill_schema_shemata(THD *thd, TABLE_LIST *tables, COND *cond)
{
2776 2777 2778 2779 2780
  /*
    TODO: fill_schema_shemata() is called when new client is connected.
    Returning error status in this case leads to client hangup.
  */

2781 2782 2783
  INDEX_FIELD_VALUES idx_field_vals;
  List<char> files;
  char *file_name;
2784
  bool with_i_schema;
2785 2786
  HA_CREATE_INFO create;
  TABLE *table= tables->table;
2787
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2788
  Security_context *sctx= thd->security_ctx;
2789
#endif
2790
  DBUG_ENTER("fill_schema_shemata");
2791

2792 2793
  if (make_db_list(thd, &files, &idx_field_vals,
                   &with_i_schema, 1))
2794
    DBUG_RETURN(1);
2795

2796 2797 2798
  List_iterator_fast<char> it(files);
  while ((file_name=it++))
  {
2799 2800
    if (with_i_schema)       // information schema name is always first in list
    {
2801
      if (store_schema_shemata(thd, table, file_name,
2802
                               system_charset_info))
2803
        DBUG_RETURN(1);
2804 2805 2806
      with_i_schema= 0;
      continue;
    }
2807
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2808 2809
    if (sctx->master_access & (DB_ACLS | SHOW_DB_ACL) ||
	acl_get(sctx->host, sctx->ip, sctx->priv_user, file_name,0) ||
2810
	!check_grant_db(thd, file_name))
2811 2812
#endif
    {
2813
      load_db_opt_by_name(thd, file_name, &create);
2814

2815
      if (store_schema_shemata(thd, table, file_name,
2816
                               create.default_table_charset))
2817
        DBUG_RETURN(1);
2818 2819
    }
  }
2820
  DBUG_RETURN(0);
2821 2822 2823
}


2824
static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2825 2826 2827
				    TABLE *table, bool res,
				    const char *base_name,
				    const char *file_name)
2828 2829
{
  const char *tmp_buff;
2830
  MYSQL_TIME time;
2831 2832
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_schema_tables_record");
2833 2834

  restore_record(table, s->default_values);
2835 2836
  table->field[1]->store(base_name, strlen(base_name), cs);
  table->field[2]->store(file_name, strlen(file_name), cs);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2837 2838 2839 2840 2841 2842
  if (res)
  {
    /*
      there was errors during opening tables
    */
    const char *error= thd->net.last_error;
2843 2844 2845 2846 2847 2848
    if (tables->view)
      table->field[3]->store(STRING_WITH_LEN("VIEW"), cs);
    else if (tables->schema_table)
      table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs);
    else
      table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2849 2850 2851 2852
    table->field[20]->store(error, strlen(error), cs);
    thd->clear_error();
  }
  else if (tables->view)
2853
  {
2854 2855
    table->field[3]->store(STRING_WITH_LEN("VIEW"), cs);
    table->field[20]->store(STRING_WITH_LEN("VIEW"), cs);
2856 2857 2858 2859
  }
  else
  {
    TABLE *show_table= tables->table;
2860
    TABLE_SHARE *share= show_table->s;
2861
    handler *file= show_table->file;
2862

2863 2864
    file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_AUTO |
               HA_STATUS_NO_LOCK);
2865
    if (share->tmp_table == SYSTEM_TMP_TABLE)
2866
      table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs);
2867
    else if (share->tmp_table)
2868
      table->field[3]->store(STRING_WITH_LEN("LOCAL TEMPORARY"), cs);
2869
    else
2870
      table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs);
2871

2872 2873
    for (int i= 4; i < 20; i++)
    {
2874
      if (i == 7 || (i > 12 && i < 17) || i == 18)
2875 2876 2877 2878 2879
        continue;
      table->field[i]->set_notnull();
    }
    tmp_buff= file->table_type();
    table->field[4]->store(tmp_buff, strlen(tmp_buff), cs);
2880
    table->field[5]->store((longlong) share->frm_version, TRUE);
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
    enum row_type row_type = file->get_row_type();
    switch (row_type) {
    case ROW_TYPE_NOT_USED:
    case ROW_TYPE_DEFAULT:
      tmp_buff= ((share->db_options_in_use &
		  HA_OPTION_COMPRESS_RECORD) ? "Compressed" :
		 (share->db_options_in_use & HA_OPTION_PACK_RECORD) ?
		 "Dynamic" : "Fixed");
      break;
    case ROW_TYPE_FIXED:
      tmp_buff= "Fixed";
      break;
    case ROW_TYPE_DYNAMIC:
      tmp_buff= "Dynamic";
      break;
    case ROW_TYPE_COMPRESSED:
      tmp_buff= "Compressed";
      break;
    case ROW_TYPE_REDUNDANT:
      tmp_buff= "Redundant";
      break;
    case ROW_TYPE_COMPACT:
      tmp_buff= "Compact";
      break;
2905 2906 2907
    case ROW_TYPE_PAGES:
      tmp_buff= "Paged";
      break;
2908
    }
2909
    table->field[6]->store(tmp_buff, strlen(tmp_buff), cs);
2910 2911
    if (!tables->schema_table)
    {
2912
      table->field[7]->store((longlong) file->stats.records, TRUE);
2913 2914
      table->field[7]->set_notnull();
    }
2915 2916 2917
    table->field[8]->store((longlong) file->stats.mean_rec_length, TRUE);
    table->field[9]->store((longlong) file->stats.data_file_length, TRUE);
    if (file->stats.max_data_file_length)
2918
    {
2919 2920
      table->field[10]->store((longlong) file->stats.max_data_file_length,
                              TRUE);
2921
    }
2922 2923
    table->field[11]->store((longlong) file->stats.index_file_length, TRUE);
    table->field[12]->store((longlong) file->stats.delete_length, TRUE);
2924
    if (show_table->found_next_number_field)
2925
    {
2926 2927
      table->field[13]->store((longlong) file->stats.auto_increment_value,
                              TRUE);
2928 2929
      table->field[13]->set_notnull();
    }
2930
    if (file->stats.create_time)
2931 2932
    {
      thd->variables.time_zone->gmt_sec_to_TIME(&time,
2933
                                                (my_time_t) file->stats.create_time);
2934 2935 2936
      table->field[14]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
      table->field[14]->set_notnull();
    }
2937
    if (file->stats.update_time)
2938 2939
    {
      thd->variables.time_zone->gmt_sec_to_TIME(&time,
2940
                                                (my_time_t) file->stats.update_time);
2941 2942 2943
      table->field[15]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
      table->field[15]->set_notnull();
    }
2944
    if (file->stats.check_time)
2945
    {
2946 2947
      thd->variables.time_zone->gmt_sec_to_TIME(&time,
                                                (my_time_t) file->stats.check_time);
2948 2949 2950
      table->field[16]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
      table->field[16]->set_notnull();
    }
2951 2952
    tmp_buff= (share->table_charset ?
               share->table_charset->name : "default");
2953
    table->field[17]->store(tmp_buff, strlen(tmp_buff), cs);
2954
    if (file->ha_table_flags() & (ulong) HA_HAS_CHECKSUM)
2955
    {
2956
      table->field[18]->store((longlong) file->checksum(), TRUE);
2957 2958 2959 2960 2961
      table->field[18]->set_notnull();
    }

    char option_buff[350],*ptr;
    ptr=option_buff;
2962
    if (share->min_rows)
2963 2964
    {
      ptr=strmov(ptr," min_rows=");
2965
      ptr=longlong10_to_str(share->min_rows,ptr,10);
2966
    }
2967
    if (share->max_rows)
2968 2969
    {
      ptr=strmov(ptr," max_rows=");
2970
      ptr=longlong10_to_str(share->max_rows,ptr,10);
2971
    }
2972
    if (share->avg_row_length)
2973 2974
    {
      ptr=strmov(ptr," avg_row_length=");
2975
      ptr=longlong10_to_str(share->avg_row_length,ptr,10);
2976
    }
2977
    if (share->db_create_options & HA_OPTION_PACK_KEYS)
2978
      ptr=strmov(ptr," pack_keys=1");
2979
    if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
2980
      ptr=strmov(ptr," pack_keys=0");
2981
    if (share->db_create_options & HA_OPTION_CHECKSUM)
2982
      ptr=strmov(ptr," checksum=1");
2983
    if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE)
2984
      ptr=strmov(ptr," delay_key_write=1");
2985
    if (share->row_type != ROW_TYPE_DEFAULT)
2986
      ptr=strxmov(ptr, " row_format=", 
2987
                  ha_row_type[(uint) share->row_type],
2988
                  NullS);
2989
#ifdef WITH_PARTITION_STORAGE_ENGINE
antony@ppcg5.local's avatar
antony@ppcg5.local committed
2990
    if (show_table->s->db_type() == partition_hton && 
2991 2992
        show_table->part_info != NULL && 
        show_table->part_info->no_parts > 0)
2993 2994
      ptr= strmov(ptr, " partitioned");
#endif
2995 2996 2997
    table->field[19]->store(option_buff+1,
                            (ptr == option_buff ? 0 : 
                             (uint) (ptr-option_buff)-1), cs);
2998
    {
2999
      char *comment;
3000
      comment= show_table->file->update_table_comment(share->comment.str);
3001 3002
      if (comment)
      {
3003 3004 3005 3006 3007
        table->field[20]->store(comment,
                                (comment == share->comment.str ?
                                 share->comment.length : 
                                 strlen(comment)), cs);
        if (comment != share->comment.str)
3008
          my_free(comment, MYF(0));
3009 3010
      }
    }
3011
  }
3012
  DBUG_RETURN(schema_table_store_record(thd, table));
3013 3014 3015
}


3016
static int get_schema_column_record(THD *thd, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3017 3018 3019
				    TABLE *table, bool res,
				    const char *base_name,
				    const char *file_name)
3020
{
3021 3022
  LEX *lex= thd->lex;
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
3023
  CHARSET_INFO *cs= system_charset_info;
3024 3025 3026 3027 3028
  TABLE *show_table;
  handler *file;
  Field **ptr,*field;
  int count;
  uint base_name_length, file_name_length;
3029
  DBUG_ENTER("get_schema_column_record");
3030

3031 3032
  if (res)
  {
3033
    if (lex->sql_command != SQLCOM_SHOW_FIELDS)
3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
    {
      /*
        I.e. we are in SELECT FROM INFORMATION_SCHEMA.COLUMS
        rather than in SHOW COLUMNS
      */ 
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   thd->net.last_errno, thd->net.last_error);
      thd->clear_error();
      res= 0;
    }
    DBUG_RETURN(res);
3045 3046
  }

3047 3048 3049
  show_table= tables->table;
  file= show_table->file;
  count= 0;
3050
  file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
3051
  restore_record(show_table, s->default_values);
3052 3053
  base_name_length= strlen(base_name);
  file_name_length= strlen(file_name);
3054
  show_table->use_all_columns();               // Required for default
3055

3056 3057
  for (ptr=show_table->field; (field= *ptr) ; ptr++)
  {
3058
    const char *tmp_buff;
3059
    uchar *pos;
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
    bool is_blob;
    uint flags=field->flags;
    char tmp[MAX_FIELD_WIDTH];
    char tmp1[MAX_FIELD_WIDTH];
    String type(tmp,sizeof(tmp), system_charset_info);
    char *end;
    int decimals, field_length;

    if (wild && wild[0] &&
        wild_case_compare(system_charset_info, field->field_name,wild))
      continue;

    flags= field->flags;
    count++;
    /* Get default row, with all NULL fields set to NULL */
    restore_record(table, s->default_values);
3076 3077

#ifndef NO_EMBEDDED_ACCESS_CHECKS
3078 3079
    uint col_access;
    check_access(thd,SELECT_ACL | EXTRA_ACL, base_name,
3080
                 &tables->grant.privilege, 0, 0, test(tables->schema_table));
3081 3082 3083
    col_access= get_column_grant(thd, &tables->grant, 
                                 base_name, file_name,
                                 field->field_name) & COL_ACLS;
3084
    if (lex->sql_command != SQLCOM_SHOW_FIELDS  &&
3085 3086 3087 3088 3089 3090
        !tables->schema_table && !col_access)
      continue;
    end= tmp;
    for (uint bitnr=0; col_access ; col_access>>=1,bitnr++)
    {
      if (col_access & 1)
3091
      {
3092 3093
        *end++=',';
        end=strmov(end,grant_types.type_names[bitnr]);
3094
      }
3095
    }
3096
    table->field[17]->store(tmp+1,end == tmp ? 0 : (uint) (end-tmp-1), cs);
3097

3098
#endif
3099 3100 3101 3102
    table->field[1]->store(base_name, base_name_length, cs);
    table->field[2]->store(file_name, file_name_length, cs);
    table->field[3]->store(field->field_name, strlen(field->field_name),
                           cs);
3103
    table->field[4]->store((longlong) count, TRUE);
3104 3105 3106 3107 3108 3109 3110 3111 3112
    field->sql_type(type);
    table->field[14]->store(type.ptr(), type.length(), cs);		
    tmp_buff= strchr(type.ptr(), '(');
    table->field[7]->store(type.ptr(),
                           (tmp_buff ? tmp_buff - type.ptr() :
                            type.length()), cs);
    if (show_table->timestamp_field == field &&
        field->unireg_check != Field::TIMESTAMP_UN_FIELD)
    {
3113
      table->field[5]->store(STRING_WITH_LEN("CURRENT_TIMESTAMP"), cs);
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
      table->field[5]->set_notnull();
    }
    else if (field->unireg_check != Field::NEXT_NUMBER &&
             !field->is_null() &&
             !(field->flags & NO_DEFAULT_VALUE_FLAG))
    {
      String def(tmp1,sizeof(tmp1), cs);
      type.set(tmp, sizeof(tmp), field->charset());
      field->val_str(&type);
      uint dummy_errors;
      def.copy(type.ptr(), type.length(), type.charset(), cs, &dummy_errors);
      table->field[5]->store(def.ptr(), def.length(), def.charset());
      table->field[5]->set_notnull();
    }
    else if (field->unireg_check == Field::NEXT_NUMBER ||
3129
             lex->sql_command != SQLCOM_SHOW_FIELDS ||
3130 3131 3132 3133 3134 3135 3136
             field->maybe_null())
      table->field[5]->set_null();                // Null as default
    else
    {
      table->field[5]->store("",0, cs);
      table->field[5]->set_notnull();
    }
3137
    pos=(uchar*) ((flags & NOT_NULL_FLAG) ?  "NO" : "YES");
3138 3139
    table->field[6]->store((const char*) pos,
                           strlen((const char*) pos), cs);
3140
    is_blob= (field->type() == MYSQL_TYPE_BLOB);
3141 3142 3143
    if (field->has_charset() || is_blob ||
        field->real_type() == MYSQL_TYPE_VARCHAR ||  // For varbinary type
        field->real_type() == MYSQL_TYPE_STRING)     // For binary type
3144
    {
3145
      uint32 octet_max_length= field->max_display_length();
3146
      if (is_blob && octet_max_length != (uint32) 4294967295U)
bar@mysql.com's avatar
bar@mysql.com committed
3147
        octet_max_length /= field->charset()->mbmaxlen;
3148
      longlong char_max_len= is_blob ? 
bar@mysql.com's avatar
bar@mysql.com committed
3149 3150
        (longlong) octet_max_length / field->charset()->mbminlen :
        (longlong) octet_max_length / field->charset()->mbmaxlen;
3151
      table->field[8]->store(char_max_len, TRUE);
3152
      table->field[8]->set_notnull();
bar@mysql.com's avatar
bar@mysql.com committed
3153
      table->field[9]->store((longlong) octet_max_length, TRUE);
3154 3155
      table->field[9]->set_notnull();
    }
3156

3157 3158 3159 3160
    /*
      Calculate field_length and decimals.
      They are set to -1 if they should not be set (we should return NULL)
    */
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3161

3162 3163
    decimals= field->decimals();
    switch (field->type()) {
3164
    case MYSQL_TYPE_NEWDECIMAL:
3165 3166
      field_length= ((Field_new_decimal*) field)->precision;
      break;
3167
    case MYSQL_TYPE_DECIMAL:
3168 3169
      field_length= field->field_length - (decimals  ? 2 : 1);
      break;
3170 3171 3172 3173 3174
    case MYSQL_TYPE_TINY:
    case MYSQL_TYPE_SHORT:
    case MYSQL_TYPE_LONG:
    case MYSQL_TYPE_LONGLONG:
    case MYSQL_TYPE_INT24:
3175
      field_length= field->max_display_length() - 1;
3176
      break;
3177
    case MYSQL_TYPE_BIT:
3178
      field_length= field->max_display_length();
3179 3180
      decimals= -1;                             // return NULL
      break;
3181 3182
    case MYSQL_TYPE_FLOAT:  
    case MYSQL_TYPE_DOUBLE:
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
      field_length= field->field_length;
      if (decimals == NOT_FIXED_DEC)
        decimals= -1;                           // return NULL
    break;
    default:
      field_length= decimals= -1;
      break;
    }

    if (field_length >= 0)
    {
3194
      table->field[10]->store((longlong) field_length, TRUE);
3195
      table->field[10]->set_notnull();
3196
    }
3197 3198
    if (decimals >= 0)
    {
3199
      table->field[11]->store((longlong) decimals, TRUE);
3200 3201 3202 3203 3204
      table->field[11]->set_notnull();
    }

    if (field->has_charset())
    {
3205
      pos=(uchar*) field->charset()->csname;
3206 3207 3208
      table->field[12]->store((const char*) pos,
                              strlen((const char*) pos), cs);
      table->field[12]->set_notnull();
3209
      pos=(uchar*) field->charset()->name;
3210 3211 3212 3213
      table->field[13]->store((const char*) pos,
                              strlen((const char*) pos), cs);
      table->field[13]->set_notnull();
    }
3214
    pos=(uchar*) ((field->flags & PRI_KEY_FLAG) ? "PRI" :
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227
                 (field->flags & UNIQUE_KEY_FLAG) ? "UNI" :
                 (field->flags & MULTIPLE_KEY_FLAG) ? "MUL":"");
    table->field[15]->store((const char*) pos,
                            strlen((const char*) pos), cs);

    end= tmp;
    if (field->unireg_check == Field::NEXT_NUMBER)
      end=strmov(tmp,"auto_increment");
    table->field[16]->store(tmp, (uint) (end-tmp), cs);

    table->field[18]->store(field->comment.str, field->comment.length, cs);
    if (schema_table_store_record(thd, table))
      DBUG_RETURN(1);
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239
  }
  DBUG_RETURN(0);
}



int fill_schema_charsets(THD *thd, TABLE_LIST *tables, COND *cond)
{
  CHARSET_INFO **cs;
  const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS;
  TABLE *table= tables->table;
  CHARSET_INFO *scs= system_charset_info;
3240 3241

  for (cs= all_charsets ; cs < all_charsets+255 ; cs++)
3242 3243 3244 3245
  {
    CHARSET_INFO *tmp_cs= cs[0];
    if (tmp_cs && (tmp_cs->state & MY_CS_PRIMARY) && 
        (tmp_cs->state & MY_CS_AVAILABLE) &&
bar@mysql.com's avatar
bar@mysql.com committed
3246
        !(tmp_cs->state & MY_CS_HIDDEN) &&
3247 3248 3249
        !(wild && wild[0] &&
	  wild_case_compare(scs, tmp_cs->csname,wild)))
    {
3250
      const char *comment;
3251
      restore_record(table, s->default_values);
3252
      table->field[0]->store(tmp_cs->csname, strlen(tmp_cs->csname), scs);
3253
      table->field[1]->store(tmp_cs->name, strlen(tmp_cs->name), scs);
3254 3255
      comment= tmp_cs->comment ? tmp_cs->comment : "";
      table->field[2]->store(comment, strlen(comment), scs);
3256
      table->field[3]->store((longlong) tmp_cs->mbmaxlen, TRUE);
3257 3258
      if (schema_table_store_record(thd, table))
        return 1;
3259 3260 3261 3262 3263 3264
    }
  }
  return 0;
}


antony@ppcg5.local's avatar
antony@ppcg5.local committed
3265
static my_bool iter_schema_engines(THD *thd, plugin_ref plugin,
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3266
                                   void *ptable)
3267
{
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3268
  TABLE *table= (TABLE *) ptable;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
3269
  handlerton *hton= plugin_data(plugin, handlerton *);
3270 3271
  const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS;
  CHARSET_INFO *scs= system_charset_info;
3272
  handlerton *default_type= ha_default_handlerton(thd);
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3273
  DBUG_ENTER("iter_schema_engines");
3274

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3275
  if (!(hton->flags & HTON_HIDDEN))
3276
  {
antony@ppcg5.local's avatar
antony@ppcg5.local committed
3277
    LEX_STRING *name= plugin_name(plugin);
3278
    if (!(wild && wild[0] &&
antony@ppcg5.local's avatar
antony@ppcg5.local committed
3279
          wild_case_compare(scs, name->str,wild)))
3280
    {
andrey@example.com's avatar
andrey@example.com committed
3281 3282
      LEX_STRING yesno[2]= {{ C_STRING_WITH_LEN("NO") },
                            { C_STRING_WITH_LEN("YES") }};
3283
      LEX_STRING *tmp;
3284
      const char *option_name= show_comp_option_name[(int) hton->state];
3285 3286
      restore_record(table, s->default_values);

antony@ppcg5.local's avatar
antony@ppcg5.local committed
3287
      table->field[0]->store(name->str, name->length, scs);
3288
      if (hton->state == SHOW_OPTION_YES && default_type == hton)
3289 3290
        option_name= "DEFAULT";
      table->field[1]->store(option_name, strlen(option_name), scs);
antony@ppcg5.local's avatar
antony@ppcg5.local committed
3291 3292
      table->field[2]->store(plugin_decl(plugin)->descr,
                             strlen(plugin_decl(plugin)->descr), scs);
3293 3294 3295 3296 3297 3298
      tmp= &yesno[test(hton->commit)];
      table->field[3]->store(tmp->str, tmp->length, scs);
      tmp= &yesno[test(hton->prepare)];
      table->field[4]->store(tmp->str, tmp->length, scs);
      tmp= &yesno[test(hton->savepoint_set)];
      table->field[5]->store(tmp->str, tmp->length, scs);
3299 3300 3301 3302 3303 3304 3305 3306 3307

      if (schema_table_store_record(thd, table))
        DBUG_RETURN(1);
    }
  }
  DBUG_RETURN(0);
}


acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3308 3309
int fill_schema_engines(THD *thd, TABLE_LIST *tables, COND *cond)
{
3310
  return plugin_foreach(thd, iter_schema_engines,
serg@sergbook.mysql.com's avatar
fixes  
serg@sergbook.mysql.com committed
3311
                        MYSQL_STORAGE_ENGINE_PLUGIN, tables->table);
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
3312 3313 3314
}


3315 3316 3317 3318 3319 3320
int fill_schema_collation(THD *thd, TABLE_LIST *tables, COND *cond)
{
  CHARSET_INFO **cs;
  const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS;
  TABLE *table= tables->table;
  CHARSET_INFO *scs= system_charset_info;
3321
  for (cs= all_charsets ; cs < all_charsets+255 ; cs++ )
3322 3323 3324
  {
    CHARSET_INFO **cl;
    CHARSET_INFO *tmp_cs= cs[0];
3325
    if (!tmp_cs || !(tmp_cs->state & MY_CS_AVAILABLE) ||
bar@mysql.com's avatar
bar@mysql.com committed
3326
         (tmp_cs->state & MY_CS_HIDDEN) ||
3327 3328
        !(tmp_cs->state & MY_CS_PRIMARY))
      continue;
3329
    for (cl= all_charsets; cl < all_charsets+255 ;cl ++)
3330 3331 3332 3333 3334 3335 3336 3337 3338
    {
      CHARSET_INFO *tmp_cl= cl[0];
      if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || 
          !my_charset_same(tmp_cs, tmp_cl))
	continue;
      if (!(wild && wild[0] &&
	  wild_case_compare(scs, tmp_cl->name,wild)))
      {
	const char *tmp_buff;
3339
	restore_record(table, s->default_values);
3340 3341
	table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs);
        table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs);
3342
        table->field[2]->store((longlong) tmp_cl->number, TRUE);
3343 3344 3345 3346
        tmp_buff= (tmp_cl->state & MY_CS_PRIMARY) ? "Yes" : "";
	table->field[3]->store(tmp_buff, strlen(tmp_buff), scs);
        tmp_buff= (tmp_cl->state & MY_CS_COMPILED)? "Yes" : "";
	table->field[4]->store(tmp_buff, strlen(tmp_buff), scs);
3347
        table->field[5]->store((longlong) tmp_cl->strxfrm_multiply, TRUE);
3348 3349
        if (schema_table_store_record(thd, table))
          return 1;
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
      }
    }
  }
  return 0;
}


int fill_schema_coll_charset_app(THD *thd, TABLE_LIST *tables, COND *cond)
{
  CHARSET_INFO **cs;
  TABLE *table= tables->table;
  CHARSET_INFO *scs= system_charset_info;
3362
  for (cs= all_charsets ; cs < all_charsets+255 ; cs++ )
3363 3364 3365 3366 3367 3368
  {
    CHARSET_INFO **cl;
    CHARSET_INFO *tmp_cs= cs[0];
    if (!tmp_cs || !(tmp_cs->state & MY_CS_AVAILABLE) || 
        !(tmp_cs->state & MY_CS_PRIMARY))
      continue;
3369
    for (cl= all_charsets; cl < all_charsets+255 ;cl ++)
3370 3371 3372 3373 3374
    {
      CHARSET_INFO *tmp_cl= cl[0];
      if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || 
          !my_charset_same(tmp_cs,tmp_cl))
	continue;
3375
      restore_record(table, s->default_values);
3376 3377
      table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs);
      table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs);
3378 3379
      if (schema_table_store_record(thd, table))
        return 1;
3380 3381 3382 3383 3384 3385
    }
  }
  return 0;
}


3386
bool store_schema_proc(THD *thd, TABLE *table, TABLE *proc_table,
3387
                       const char *wild, bool full_access, const char *sp_user)
3388 3389
{
  String tmp_string;
3390
  String sp_db, sp_name, definer;
3391
  MYSQL_TIME time;
3392 3393
  LEX *lex= thd->lex;
  CHARSET_INFO *cs= system_charset_info;
3394 3395 3396
  get_field(thd->mem_root, proc_table->field[0], &sp_db);
  get_field(thd->mem_root, proc_table->field[1], &sp_name);
  get_field(thd->mem_root, proc_table->field[11], &definer);
3397
  if (!full_access)
3398
    full_access= !strcmp(sp_user, definer.ptr());
3399 3400 3401 3402
  if (!full_access && check_some_routine_access(thd, sp_db.ptr(),
                                                sp_name.ptr(),
                                                proc_table->field[2]->
                                                val_int() ==
3403
                                                TYPE_ENUM_PROCEDURE))
3404
    return 0;
3405

3406
  if (lex->sql_command == SQLCOM_SHOW_STATUS_PROC &&
3407
      proc_table->field[2]->val_int() == TYPE_ENUM_PROCEDURE ||
3408
      lex->sql_command == SQLCOM_SHOW_STATUS_FUNC &&
3409
      proc_table->field[2]->val_int() == TYPE_ENUM_FUNCTION ||
3410
      (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0)
3411
  {
3412
    restore_record(table, s->default_values);
3413
    if (!wild || !wild[0] || !wild_compare(sp_name.ptr(), wild, 0))
3414
    {
3415
      int enum_idx= (int) proc_table->field[5]->val_int();
3416
      table->field[3]->store(sp_name.ptr(), sp_name.length(), cs);
3417 3418
      get_field(thd->mem_root, proc_table->field[3], &tmp_string);
      table->field[0]->store(tmp_string.ptr(), tmp_string.length(), cs);
3419
      table->field[2]->store(sp_db.ptr(), sp_db.length(), cs);
3420 3421
      get_field(thd->mem_root, proc_table->field[2], &tmp_string);
      table->field[4]->store(tmp_string.ptr(), tmp_string.length(), cs);
3422 3423 3424 3425 3426 3427
      if (proc_table->field[2]->val_int() == TYPE_ENUM_FUNCTION)
      {
        get_field(thd->mem_root, proc_table->field[9], &tmp_string);
        table->field[5]->store(tmp_string.ptr(), tmp_string.length(), cs);
        table->field[5]->set_notnull();
      }
3428 3429
      if (full_access)
      {
3430
        get_field(thd->mem_root, proc_table->field[19], &tmp_string);
3431
        table->field[7]->store(tmp_string.ptr(), tmp_string.length(), cs);
3432
        table->field[7]->set_notnull();
3433
      }
3434 3435
      table->field[6]->store(STRING_WITH_LEN("SQL"), cs);
      table->field[10]->store(STRING_WITH_LEN("SQL"), cs);
3436
      get_field(thd->mem_root, proc_table->field[6], &tmp_string);
3437
      table->field[11]->store(tmp_string.ptr(), tmp_string.length(), cs);
3438 3439
      table->field[12]->store(sp_data_access_name[enum_idx].str, 
                              sp_data_access_name[enum_idx].length , cs);
3440 3441
      get_field(thd->mem_root, proc_table->field[7], &tmp_string);
      table->field[14]->store(tmp_string.ptr(), tmp_string.length(), cs);
3442 3443
      bzero((char *)&time, sizeof(time));
      ((Field_timestamp *) proc_table->field[12])->get_time(&time);
3444
      table->field[15]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
3445 3446
      bzero((char *)&time, sizeof(time));
      ((Field_timestamp *) proc_table->field[13])->get_time(&time);
3447
      table->field[16]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
3448
      get_field(thd->mem_root, proc_table->field[14], &tmp_string);
3449
      table->field[17]->store(tmp_string.ptr(), tmp_string.length(), cs);
3450
      get_field(thd->mem_root, proc_table->field[15], &tmp_string);
3451
      table->field[18]->store(tmp_string.ptr(), tmp_string.length(), cs);
3452
      table->field[19]->store(definer.ptr(), definer.length(), cs);
3453 3454 3455 3456 3457 3458 3459 3460 3461 3462

      get_field(thd->mem_root, proc_table->field[16], &tmp_string);
      table->field[20]->store(tmp_string.ptr(), tmp_string.length(), cs);

      get_field(thd->mem_root, proc_table->field[17], &tmp_string);
      table->field[21]->store(tmp_string.ptr(), tmp_string.length(), cs);

      get_field(thd->mem_root, proc_table->field[18], &tmp_string);
      table->field[22]->store(tmp_string.ptr(), tmp_string.length(), cs);

3463
      return schema_table_store_record(thd, table);
3464 3465
    }
  }
3466
  return 0;
3467 3468 3469 3470 3471 3472 3473 3474 3475
}


int fill_schema_proc(THD *thd, TABLE_LIST *tables, COND *cond)
{
  TABLE *proc_table;
  TABLE_LIST proc_tables;
  const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS;
  int res= 0;
3476
  TABLE *table= tables->table;
3477
  bool full_access;
3478
  char definer[USER_HOST_BUFF_SIZE];
3479
  Open_tables_state open_tables_state_backup;
3480 3481
  DBUG_ENTER("fill_schema_proc");

3482 3483
  strxmov(definer, thd->security_ctx->priv_user, "@",
          thd->security_ctx->priv_host, NullS);
3484
  /* We use this TABLE_LIST instance only for checking of privileges. */
3485 3486
  bzero((char*) &proc_tables,sizeof(proc_tables));
  proc_tables.db= (char*) "mysql";
3487
  proc_tables.db_length= 5;
3488
  proc_tables.table_name= proc_tables.alias= (char*) "proc";
3489
  proc_tables.table_name_length= 4;
3490
  proc_tables.lock_type= TL_READ;
3491
  full_access= !check_table_access(thd, SELECT_ACL, &proc_tables, 1);
3492
  if (!(proc_table= open_proc_table_for_read(thd, &open_tables_state_backup)))
3493 3494 3495
  {
    DBUG_RETURN(1);
  }
3496
  proc_table->file->ha_index_init(0, 1);
3497 3498 3499 3500 3501
  if ((res= proc_table->file->index_first(proc_table->record[0])))
  {
    res= (res == HA_ERR_END_OF_FILE) ? 0 : 1;
    goto err;
  }
3502 3503 3504 3505 3506
  if (store_schema_proc(thd, table, proc_table, wild, full_access, definer))
  {
    res= 1;
    goto err;
  }
3507
  while (!proc_table->file->index_next(proc_table->record[0]))
3508 3509 3510 3511 3512 3513 3514
  {
    if (store_schema_proc(thd, table, proc_table, wild, full_access, definer))
    {
      res= 1;
      goto err;
    }
  }
3515 3516 3517

err:
  proc_table->file->ha_index_end();
3518
  close_system_tables(thd, &open_tables_state_backup);
3519 3520 3521 3522
  DBUG_RETURN(res);
}


3523
static int get_schema_stat_record(THD *thd, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3524 3525 3526
				  TABLE *table, bool res,
				  const char *base_name,
				  const char *file_name)
3527 3528 3529
{
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_schema_stat_record");
3530 3531
  if (res)
  {
3532
    if (thd->lex->sql_command != SQLCOM_SHOW_KEYS)
3533 3534 3535 3536
    {
      /*
        I.e. we are in SELECT FROM INFORMATION_SCHEMA.STATISTICS
        rather than in SHOW KEYS
3537
      */
3538 3539 3540 3541 3542 3543 3544 3545 3546
      if (!tables->view)
        push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                     thd->net.last_errno, thd->net.last_error);
      thd->clear_error();
      res= 0;
    }
    DBUG_RETURN(res);
  }
  else if (!tables->view)
3547 3548 3549
  {
    TABLE *show_table= tables->table;
    KEY *key_info=show_table->key_info;
3550
    show_table->file->info(HA_STATUS_VARIABLE |
3551 3552
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);
3553
    for (uint i=0 ; i < show_table->s->keys ; i++,key_info++)
3554 3555 3556 3557 3558
    {
      KEY_PART_INFO *key_part= key_info->key_part;
      const char *str;
      for (uint j=0 ; j < key_info->key_parts ; j++,key_part++)
      {
3559
        restore_record(table, s->default_values);
3560 3561
        table->field[1]->store(base_name, strlen(base_name), cs);
        table->field[2]->store(file_name, strlen(file_name), cs);
3562
        table->field[3]->store((longlong) ((key_info->flags &
3563
                                            HA_NOSAME) ? 0 : 1), TRUE);
3564 3565
        table->field[4]->store(base_name, strlen(base_name), cs);
        table->field[5]->store(key_info->name, strlen(key_info->name), cs);
3566
        table->field[6]->store((longlong) (j+1), TRUE);
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579
        str=(key_part->field ? key_part->field->field_name :
             "?unknown field?");
        table->field[7]->store(str, strlen(str), cs);
        if (show_table->file->index_flags(i, j, 0) & HA_READ_ORDER)
        {
          table->field[8]->store(((key_part->key_part_flag &
                                   HA_REVERSE_SORT) ?
                                  "D" : "A"), 1, cs);
          table->field[8]->set_notnull();
        }
        KEY *key=show_table->key_info+i;
        if (key->rec_per_key[j])
        {
3580
          ha_rows records=(show_table->file->stats.records /
3581
                           key->rec_per_key[j]);
3582
          table->field[9]->store((longlong) records, TRUE);
3583 3584
          table->field[9]->set_notnull();
        }
3585 3586 3587
        if (!(key_info->flags & HA_FULLTEXT) &&
            (key_part->field &&
             key_part->length !=
3588 3589
             show_table->field[key_part->fieldnr-1]->key_length()))
        {
3590
          table->field[10]->store((longlong) key_part->length /
3591
                                  key_part->field->charset()->mbmaxlen, TRUE);
3592 3593 3594 3595 3596 3597 3598
          table->field[10]->set_notnull();
        }
        uint flags= key_part->field ? key_part->field->flags : 0;
        const char *pos=(char*) ((flags & NOT_NULL_FLAG) ? "" : "YES");
        table->field[12]->store(pos, strlen(pos), cs);
        pos= show_table->file->index_type(i);
        table->field[13]->store(pos, strlen(pos), cs);
3599
        if (!show_table->s->keys_in_use.is_set(i))
3600
          table->field[14]->store(STRING_WITH_LEN("disabled"), cs);
3601 3602 3603
        else
          table->field[14]->store("", 0, cs);
        table->field[14]->set_notnull();
3604 3605
        if (schema_table_store_record(thd, table))
          DBUG_RETURN(1);
3606 3607 3608
      }
    }
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3609
  DBUG_RETURN(res);
3610 3611 3612
}


3613
static int get_schema_views_record(THD *thd, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3614 3615 3616
				   TABLE *table, bool res,
				   const char *base_name,
				   const char *file_name)
3617 3618 3619
{
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_schema_views_record");
3620
  char definer[USER_HOST_BUFF_SIZE];
3621
  uint definer_len;
3622
  bool updatable_view;
3623

3624 3625
  if (tables->view)
  {
3626
    Security_context *sctx= thd->security_ctx;
3627
    if (!tables->allowed_show)
3628
    {
3629 3630 3631 3632 3633
      if (!my_strcasecmp(system_charset_info, tables->definer.user.str,
                         sctx->priv_user) &&
          !my_strcasecmp(system_charset_info, tables->definer.host.str,
                         sctx->priv_host))
        tables->allowed_show= TRUE;
3634
    }
3635 3636
    restore_record(table, s->default_values);
    table->field[1]->store(tables->view_db.str, tables->view_db.length, cs);
3637
    table->field[2]->store(tables->view_name.str, tables->view_name.length, cs);
3638
    if (tables->allowed_show)
3639
    {
3640 3641 3642
      table->field[3]->store(tables->view_body_utf8.str,
                             tables->view_body_utf8.length,
                             cs);
3643
    }
3644

3645 3646 3647 3648
    if (tables->with_check != VIEW_CHECK_NONE)
    {
      if (tables->with_check == VIEW_CHECK_LOCAL)
        table->field[4]->store(STRING_WITH_LEN("LOCAL"), cs);
3649
      else
3650
        table->field[4]->store(STRING_WITH_LEN("CASCADED"), cs);
3651
    }
3652 3653 3654
    else
      table->field[4]->store(STRING_WITH_LEN("NONE"), cs);

3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682
    updatable_view= 0;
    if (tables->algorithm != VIEW_ALGORITHM_TMPTABLE)
    {
      /*
        We should use tables->view->select_lex.item_list here and
        can not use Field_iterator_view because the view always uses
        temporary algorithm during opening for I_S and
        TABLE_LIST fields 'field_translation' & 'field_translation_end'
        are uninitialized is this case.
      */
      List<Item> *fields= &tables->view->select_lex.item_list;
      List_iterator<Item> it(*fields);
      Item *item;
      Item_field *field;
      /*
        chech that at least one coulmn in view is updatable
      */
      while ((item= it++))
      {
        if ((field= item->filed_for_view_update()) && field->field &&
            !field->field->table->pos_in_table_list->schema_table)
        {
          updatable_view= 1;
          break;
        }
      }
    }
    if (updatable_view)
3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
      table->field[5]->store(STRING_WITH_LEN("YES"), cs);
    else
      table->field[5]->store(STRING_WITH_LEN("NO"), cs);
    definer_len= (strxmov(definer, tables->definer.user.str, "@",
                          tables->definer.host.str, NullS) - definer);
    table->field[6]->store(definer, definer_len, cs);
    if (tables->view_suid)
      table->field[7]->store(STRING_WITH_LEN("DEFINER"), cs);
    else
      table->field[7]->store(STRING_WITH_LEN("INVOKER"), cs);
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703

    table->field[8]->store(
      tables->view_creation_ctx->get_client_cs()->csname,
      strlen(tables->view_creation_ctx->get_client_cs()->csname),
      cs);

    table->field[9]->store(
      tables->view_creation_ctx->get_connection_cl()->name,
      strlen(tables->view_creation_ctx->get_connection_cl()->name),
      cs);

3704 3705 3706
    if (schema_table_store_record(thd, table))
      DBUG_RETURN(1);
    if (res)
3707 3708 3709
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 
                   thd->net.last_errno, thd->net.last_error);
  }
3710 3711
  if (res) 
    thd->clear_error();
3712
  DBUG_RETURN(0);
3713 3714 3715
}


3716 3717 3718
bool store_constraints(THD *thd, TABLE *table, const char *db,
                       const char *tname, const char *key_name,
                       uint key_len, const char *con_type, uint con_len)
3719 3720
{
  CHARSET_INFO *cs= system_charset_info;
3721
  restore_record(table, s->default_values);
3722 3723 3724 3725 3726
  table->field[1]->store(db, strlen(db), cs);
  table->field[2]->store(key_name, key_len, cs);
  table->field[3]->store(db, strlen(db), cs);
  table->field[4]->store(tname, strlen(tname), cs);
  table->field[5]->store(con_type, con_len, cs);
3727
  return schema_table_store_record(thd, table);
3728 3729 3730
}


3731
static int get_schema_constraints_record(THD *thd, TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3732 3733 3734
					 TABLE *table, bool res,
					 const char *base_name,
					 const char *file_name)
3735
{
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3736
  DBUG_ENTER("get_schema_constraints_record");
3737 3738 3739 3740 3741 3742 3743 3744 3745
  if (res)
  {
    if (!tables->view)
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   thd->net.last_errno, thd->net.last_error);
    thd->clear_error();
    DBUG_RETURN(0);
  }
  else if (!tables->view)
3746 3747 3748 3749
  {
    List<FOREIGN_KEY_INFO> f_key_list;
    TABLE *show_table= tables->table;
    KEY *key_info=show_table->key_info;
3750
    uint primary_key= show_table->s->primary_key;
3751 3752 3753
    show_table->file->info(HA_STATUS_VARIABLE | 
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);
3754
    for (uint i=0 ; i < show_table->s->keys ; i++, key_info++)
3755 3756
    {
      if (i != primary_key && !(key_info->flags & HA_NOSAME))
3757 3758
        continue;

3759
      if (i == primary_key && !strcmp(key_info->name, primary_key_name))
3760 3761
      {
        if (store_constraints(thd, table, base_name, file_name, key_info->name,
3762 3763
                              strlen(key_info->name),
                              STRING_WITH_LEN("PRIMARY KEY")))
3764 3765
          DBUG_RETURN(1);
      }
3766
      else if (key_info->flags & HA_NOSAME)
3767 3768
      {
        if (store_constraints(thd, table, base_name, file_name, key_info->name,
3769 3770
                              strlen(key_info->name),
                              STRING_WITH_LEN("UNIQUE")))
3771 3772
          DBUG_RETURN(1);
      }
3773 3774 3775 3776 3777 3778 3779
    }

    show_table->file->get_foreign_key_list(thd, &f_key_list);
    FOREIGN_KEY_INFO *f_key_info;
    List_iterator_fast<FOREIGN_KEY_INFO> it(f_key_list);
    while ((f_key_info=it++))
    {
3780 3781 3782 3783 3784
      if (store_constraints(thd, table, base_name, file_name, 
                            f_key_info->forein_id->str,
                            strlen(f_key_info->forein_id->str),
                            "FOREIGN KEY", 11))
        DBUG_RETURN(1);
3785 3786
    }
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3787
  DBUG_RETURN(res);
3788 3789 3790
}


3791 3792 3793 3794
static bool store_trigger(THD *thd, TABLE *table, const char *db,
                          const char *tname, LEX_STRING *trigger_name,
                          enum trg_event_type event,
                          enum trg_action_time_type timing,
3795
                          LEX_STRING *trigger_stmt,
3796
                          ulong sql_mode,
3797 3798 3799 3800
                          LEX_STRING *definer_buffer,
                          LEX_STRING *client_cs_name,
                          LEX_STRING *connection_cl_name,
                          LEX_STRING *db_cl_name)
3801 3802
{
  CHARSET_INFO *cs= system_charset_info;
3803
  LEX_STRING sql_mode_rep;
3804

3805 3806 3807 3808 3809 3810 3811 3812
  restore_record(table, s->default_values);
  table->field[1]->store(db, strlen(db), cs);
  table->field[2]->store(trigger_name->str, trigger_name->length, cs);
  table->field[3]->store(trg_event_type_names[event].str,
                         trg_event_type_names[event].length, cs);
  table->field[5]->store(db, strlen(db), cs);
  table->field[6]->store(tname, strlen(tname), cs);
  table->field[9]->store(trigger_stmt->str, trigger_stmt->length, cs);
3813
  table->field[10]->store(STRING_WITH_LEN("ROW"), cs);
3814 3815
  table->field[11]->store(trg_action_time_type_names[timing].str,
                          trg_action_time_type_names[timing].length, cs);
3816 3817
  table->field[14]->store(STRING_WITH_LEN("OLD"), cs);
  table->field[15]->store(STRING_WITH_LEN("NEW"), cs);
3818

3819 3820 3821
  sys_var_thd_sql_mode::symbolic_mode_representation(thd, sql_mode,
                                                     &sql_mode_rep);
  table->field[17]->store(sql_mode_rep.str, sql_mode_rep.length, cs);
3822 3823 3824 3825 3826 3827
  table->field[18]->store(definer_buffer->str, definer_buffer->length, cs);
  table->field[19]->store(client_cs_name->str, client_cs_name->length, cs);
  table->field[20]->store(connection_cl_name->str,
                          connection_cl_name->length, cs);
  table->field[21]->store(db_cl_name->str, db_cl_name->length, cs);

3828 3829 3830 3831
  return schema_table_store_record(thd, table);
}


3832
static int get_schema_triggers_record(THD *thd, TABLE_LIST *tables,
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
				      TABLE *table, bool res,
				      const char *base_name,
				      const char *file_name)
{
  DBUG_ENTER("get_schema_triggers_record");
  /*
    res can be non zero value when processed table is a view or
    error happened during opening of processed table.
  */
  if (res)
  {
    if (!tables->view)
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   thd->net.last_errno, thd->net.last_error);
    thd->clear_error();
    DBUG_RETURN(0);
  }
  if (!tables->view && tables->table->triggers)
  {
    Table_triggers_list *triggers= tables->table->triggers;
    int event, timing;
    for (event= 0; event < (int)TRG_EVENT_MAX; event++)
    {
      for (timing= 0; timing < (int)TRG_ACTION_MAX; timing++)
      {
        LEX_STRING trigger_name;
        LEX_STRING trigger_stmt;
3860
        ulong sql_mode;
3861
        char definer_holder[USER_HOST_BUFF_SIZE];
3862
        LEX_STRING definer_buffer;
3863 3864 3865 3866
        LEX_STRING client_cs_name;
        LEX_STRING connection_cl_name;
        LEX_STRING db_cl_name;

3867
        definer_buffer.str= definer_holder;
3868 3869
        if (triggers->get_trigger_info(thd, (enum trg_event_type) event,
                                       (enum trg_action_time_type)timing,
3870
                                       &trigger_name, &trigger_stmt,
3871
                                       &sql_mode,
3872 3873 3874 3875
                                       &definer_buffer,
                                       &client_cs_name,
                                       &connection_cl_name,
                                       &db_cl_name))
3876
          continue;
3877

3878 3879
        if (store_trigger(thd, table, base_name, file_name, &trigger_name,
                         (enum trg_event_type) event,
3880
                         (enum trg_action_time_type) timing, &trigger_stmt,
3881
                         sql_mode,
3882 3883 3884 3885
                         &definer_buffer,
                         &client_cs_name,
                         &connection_cl_name,
                         &db_cl_name))
3886 3887 3888 3889 3890 3891 3892 3893
          DBUG_RETURN(1);
      }
    }
  }
  DBUG_RETURN(0);
}


3894 3895 3896 3897 3898 3899 3900 3901 3902 3903
void store_key_column_usage(TABLE *table, const char*db, const char *tname,
                            const char *key_name, uint key_len, 
                            const char *con_type, uint con_len, longlong idx)
{
  CHARSET_INFO *cs= system_charset_info;
  table->field[1]->store(db, strlen(db), cs);
  table->field[2]->store(key_name, key_len, cs);
  table->field[4]->store(db, strlen(db), cs);
  table->field[5]->store(tname, strlen(tname), cs);
  table->field[6]->store(con_type, con_len, cs);
3904
  table->field[7]->store((longlong) idx, TRUE);
3905 3906 3907
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3908
static int get_schema_key_column_usage_record(THD *thd,
3909
					      TABLE_LIST *tables,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3910 3911 3912
					      TABLE *table, bool res,
					      const char *base_name,
					      const char *file_name)
3913 3914
{
  DBUG_ENTER("get_schema_key_column_usage_record");
3915 3916 3917 3918 3919 3920 3921 3922 3923
  if (res)
  {
    if (!tables->view)
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   thd->net.last_errno, thd->net.last_error);
    thd->clear_error();
    DBUG_RETURN(0);
  }
  else if (!tables->view)
3924 3925 3926 3927
  {
    List<FOREIGN_KEY_INFO> f_key_list;
    TABLE *show_table= tables->table;
    KEY *key_info=show_table->key_info;
3928
    uint primary_key= show_table->s->primary_key;
3929 3930 3931
    show_table->file->info(HA_STATUS_VARIABLE | 
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);
3932
    for (uint i=0 ; i < show_table->s->keys ; i++, key_info++)
3933 3934
    {
      if (i != primary_key && !(key_info->flags & HA_NOSAME))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3935
        continue;
3936 3937 3938 3939 3940 3941 3942
      uint f_idx= 0;
      KEY_PART_INFO *key_part= key_info->key_part;
      for (uint j=0 ; j < key_info->key_parts ; j++,key_part++)
      {
        if (key_part->field)
        {
          f_idx++;
3943
          restore_record(table, s->default_values);
3944 3945 3946 3947 3948 3949
          store_key_column_usage(table, base_name, file_name,
                                 key_info->name,
                                 strlen(key_info->name), 
                                 key_part->field->field_name, 
                                 strlen(key_part->field->field_name),
                                 (longlong) f_idx);
3950 3951
          if (schema_table_store_record(thd, table))
            DBUG_RETURN(1);
3952 3953 3954 3955 3956 3957
        }
      }
    }

    show_table->file->get_foreign_key_list(thd, &f_key_list);
    FOREIGN_KEY_INFO *f_key_info;
3958 3959
    List_iterator_fast<FOREIGN_KEY_INFO> fkey_it(f_key_list);
    while ((f_key_info= fkey_it++))
3960
    {
3961
      LEX_STRING *f_info;
3962
      LEX_STRING *r_info;
3963 3964 3965 3966 3967
      List_iterator_fast<LEX_STRING> it(f_key_info->foreign_fields),
        it1(f_key_info->referenced_fields);
      uint f_idx= 0;
      while ((f_info= it++))
      {
3968
        r_info= it1++;
3969
        f_idx++;
3970
        restore_record(table, s->default_values);
3971 3972 3973 3974 3975
        store_key_column_usage(table, base_name, file_name,
                               f_key_info->forein_id->str,
                               f_key_info->forein_id->length,
                               f_info->str, f_info->length,
                               (longlong) f_idx);
3976
        table->field[8]->store((longlong) f_idx, TRUE);
3977
        table->field[8]->set_notnull();
3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
        table->field[9]->store(f_key_info->referenced_db->str,
                               f_key_info->referenced_db->length,
                               system_charset_info);
        table->field[9]->set_notnull();
        table->field[10]->store(f_key_info->referenced_table->str,
                                f_key_info->referenced_table->length, 
                                system_charset_info);
        table->field[10]->set_notnull();
        table->field[11]->store(r_info->str, r_info->length,
                                system_charset_info);
        table->field[11]->set_notnull();
3989 3990
        if (schema_table_store_record(thd, table))
          DBUG_RETURN(1);
3991 3992 3993
      }
    }
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3994
  DBUG_RETURN(res);
3995 3996 3997
}


3998
#ifdef WITH_PARTITION_STORAGE_ENGINE
3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012
static void collect_partition_expr(List<char> &field_list, String *str)
{
  List_iterator<char> part_it(field_list);
  ulong no_fields= field_list.elements;
  const char *field_str;
  str->length(0);
  while ((field_str= part_it++))
  {
    str->append(field_str);
    if (--no_fields != 0)
      str->append(",");
  }
  return;
}
4013
#endif
4014 4015


4016 4017
static void store_schema_partitions_record(THD *thd, TABLE *schema_table,
                                           TABLE *showing_table,
4018 4019 4020
                                           partition_element *part_elem,
                                           handler *file, uint part_id)
{
4021
  TABLE* table= schema_table;
4022 4023
  CHARSET_INFO *cs= system_charset_info;
  PARTITION_INFO stat_info;
4024
  MYSQL_TIME time;
4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038
  file->get_dynamic_partition_info(&stat_info, part_id);
  table->field[12]->store((longlong) stat_info.records, TRUE);
  table->field[13]->store((longlong) stat_info.mean_rec_length, TRUE);
  table->field[14]->store((longlong) stat_info.data_file_length, TRUE);
  if (stat_info.max_data_file_length)
  {
    table->field[15]->store((longlong) stat_info.max_data_file_length, TRUE);
    table->field[15]->set_notnull();
  }
  table->field[16]->store((longlong) stat_info.index_file_length, TRUE);
  table->field[17]->store((longlong) stat_info.delete_length, TRUE);
  if (stat_info.create_time)
  {
    thd->variables.time_zone->gmt_sec_to_TIME(&time,
4039
                                              (my_time_t)stat_info.create_time);
4040 4041 4042 4043 4044 4045
    table->field[18]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
    table->field[18]->set_notnull();
  }
  if (stat_info.update_time)
  {
    thd->variables.time_zone->gmt_sec_to_TIME(&time,
4046
                                              (my_time_t)stat_info.update_time);
4047 4048 4049 4050 4051
    table->field[19]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
    table->field[19]->set_notnull();
  }
  if (stat_info.check_time)
  {
4052 4053
    thd->variables.time_zone->gmt_sec_to_TIME(&time,
                                              (my_time_t)stat_info.check_time);
4054 4055 4056
    table->field[20]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
    table->field[20]->set_notnull();
  }
4057
  if (file->ha_table_flags() & (ulong) HA_HAS_CHECKSUM)
4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
  {
    table->field[21]->store((longlong) stat_info.check_sum, TRUE);
    table->field[21]->set_notnull();
  }
  if (part_elem)
  {
    if (part_elem->part_comment)
      table->field[22]->store(part_elem->part_comment,
                              strlen(part_elem->part_comment), cs);
    else
4068
      table->field[22]->store(STRING_WITH_LEN(""), cs);
4069 4070 4071 4072
    if (part_elem->nodegroup_id != UNDEF_NODEGROUP)
      table->field[23]->store((longlong) part_elem->nodegroup_id, TRUE);
    else
      table->field[23]->store(STRING_WITH_LEN("default"), cs);
4073 4074

    table->field[24]->set_notnull();
4075 4076 4077 4078
    if (part_elem->tablespace_name)
      table->field[24]->store(part_elem->tablespace_name,
                              strlen(part_elem->tablespace_name), cs);
    else
4079
    {
4080
      char *ts= showing_table->file->get_tablespace_name(thd,0,0);
4081
      if(ts)
4082
      {
4083
        table->field[24]->store(ts, strlen(ts), cs);
4084 4085
        my_free(ts, MYF(0));
      }
4086 4087 4088
      else
        table->field[24]->set_null();
    }
4089 4090 4091 4092 4093
  }
  return;
}


4094
static int get_schema_partitions_record(THD *thd, TABLE_LIST *tables,
4095 4096 4097 4098 4099 4100 4101 4102 4103
                                        TABLE *table, bool res,
                                        const char *base_name,
                                        const char *file_name)
{
  CHARSET_INFO *cs= system_charset_info;
  char buff[61];
  String tmp_res(buff, sizeof(buff), cs);
  String tmp_str;
  TABLE *show_table= tables->table;
4104
  handler *file;
4105
#ifdef WITH_PARTITION_STORAGE_ENGINE
4106
  partition_info *part_info;
4107
#endif
4108 4109 4110 4111
  DBUG_ENTER("get_schema_partitions_record");

  if (res)
  {
4112
    if (!tables->view)
4113 4114 4115 4116 4117
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   thd->net.last_errno, thd->net.last_error);
    thd->clear_error();
    DBUG_RETURN(0);
  }
4118
  file= show_table->file;
4119
#ifdef WITH_PARTITION_STORAGE_ENGINE
4120
  part_info= show_table->part_info;
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172
  if (part_info)
  {
    partition_element *part_elem;
    List_iterator<partition_element> part_it(part_info->partitions);
    uint part_pos= 0, part_id= 0;

    restore_record(table, s->default_values);
    table->field[1]->store(base_name, strlen(base_name), cs);
    table->field[2]->store(file_name, strlen(file_name), cs);


    /* Partition method*/
    switch (part_info->part_type) {
    case RANGE_PARTITION:
      table->field[7]->store(partition_keywords[PKW_RANGE].str,
                             partition_keywords[PKW_RANGE].length, cs);
      break;
    case LIST_PARTITION:
      table->field[7]->store(partition_keywords[PKW_LIST].str,
                             partition_keywords[PKW_LIST].length, cs);
      break;
    case HASH_PARTITION:
      tmp_res.length(0);
      if (part_info->linear_hash_ind)
        tmp_res.append(partition_keywords[PKW_LINEAR].str,
                       partition_keywords[PKW_LINEAR].length);
      if (part_info->list_of_part_fields)
        tmp_res.append(partition_keywords[PKW_KEY].str,
                       partition_keywords[PKW_KEY].length);
      else
        tmp_res.append(partition_keywords[PKW_HASH].str, 
                       partition_keywords[PKW_HASH].length);
      table->field[7]->store(tmp_res.ptr(), tmp_res.length(), cs);
      break;
    default:
      DBUG_ASSERT(0);
      current_thd->fatal_error();
      DBUG_RETURN(1);
    }
    table->field[7]->set_notnull();

    /* Partition expression */
    if (part_info->part_expr)
    {
      table->field[9]->store(part_info->part_func_string,
                             part_info->part_func_len, cs);
    }
    else if (part_info->list_of_part_fields)
    {
      collect_partition_expr(part_info->part_field_list, &tmp_str);
      table->field[9]->store(tmp_str.ptr(), tmp_str.length(), cs);
    }
4173
    table->field[9]->set_notnull();
4174

4175
    if (part_info->is_sub_partitioned())
4176 4177
    {
      /* Subpartition method */
4178 4179 4180 4181
      tmp_res.length(0);
      if (part_info->linear_hash_ind)
        tmp_res.append(partition_keywords[PKW_LINEAR].str,
                       partition_keywords[PKW_LINEAR].length);
4182
      if (part_info->list_of_subpart_fields)
4183 4184
        tmp_res.append(partition_keywords[PKW_KEY].str,
                       partition_keywords[PKW_KEY].length);
4185
      else
4186 4187 4188
        tmp_res.append(partition_keywords[PKW_HASH].str, 
                       partition_keywords[PKW_HASH].length);
      table->field[8]->store(tmp_res.ptr(), tmp_res.length(), cs);
4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201
      table->field[8]->set_notnull();

      /* Subpartition expression */
      if (part_info->subpart_expr)
      {
        table->field[10]->store(part_info->subpart_func_string,
                                part_info->subpart_func_len, cs);
      }
      else if (part_info->list_of_subpart_fields)
      {
        collect_partition_expr(part_info->subpart_field_list, &tmp_str);
        table->field[10]->store(tmp_str.ptr(), tmp_str.length(), cs);
      }
4202
      table->field[10]->set_notnull();
4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
    }

    while ((part_elem= part_it++))
    {
      table->field[3]->store(part_elem->partition_name,
                             strlen(part_elem->partition_name), cs);
      table->field[3]->set_notnull();
      /* PARTITION_ORDINAL_POSITION */
      table->field[5]->store((longlong) ++part_pos, TRUE);
      table->field[5]->set_notnull();

      /* Partition description */
      if (part_info->part_type == RANGE_PARTITION)
      {
        if (part_elem->range_value != LONGLONG_MAX)
          table->field[11]->store((longlong) part_elem->range_value, FALSE);
        else
          table->field[11]->store(partition_keywords[PKW_MAXVALUE].str,
                                 partition_keywords[PKW_MAXVALUE].length, cs);
        table->field[11]->set_notnull();
      }
      else if (part_info->part_type == LIST_PARTITION)
      {
4226 4227
        List_iterator<part_elem_value> list_val_it(part_elem->list_val_list);
        part_elem_value *list_value;
4228 4229 4230
        uint no_items= part_elem->list_val_list.elements;
        tmp_str.length(0);
        tmp_res.length(0);
4231 4232 4233 4234 4235 4236
        if (part_elem->has_null_value)
        {
          tmp_str.append("NULL");
          if (no_items > 0)
            tmp_str.append(",");
        }
4237 4238
        while ((list_value= list_val_it++))
        {
4239 4240 4241 4242
          if (!list_value->unsigned_flag)
            tmp_res.set(list_value->value, cs);
          else
            tmp_res.set((ulonglong)list_value->value, cs);
4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265
          tmp_str.append(tmp_res);
          if (--no_items != 0)
            tmp_str.append(",");
        };
        table->field[11]->store(tmp_str.ptr(), tmp_str.length(), cs);
        table->field[11]->set_notnull();
      }

      if (part_elem->subpartitions.elements)
      {
        List_iterator<partition_element> sub_it(part_elem->subpartitions);
        partition_element *subpart_elem;
        uint subpart_pos= 0;

        while ((subpart_elem= sub_it++))
        {
          table->field[4]->store(subpart_elem->partition_name,
                                 strlen(subpart_elem->partition_name), cs);
          table->field[4]->set_notnull();
          /* SUBPARTITION_ORDINAL_POSITION */
          table->field[6]->store((longlong) ++subpart_pos, TRUE);
          table->field[6]->set_notnull();
          
4266
          store_schema_partitions_record(thd, table, show_table, subpart_elem,
4267 4268 4269 4270 4271 4272 4273 4274
                                         file, part_id);
          part_id++;
          if(schema_table_store_record(thd, table))
            DBUG_RETURN(1);
        }
      }
      else
      {
4275
        store_schema_partitions_record(thd, table, show_table, part_elem,
4276 4277 4278 4279 4280 4281 4282 4283 4284
                                       file, part_id);
        part_id++;
        if(schema_table_store_record(thd, table))
          DBUG_RETURN(1);
      }
    }
    DBUG_RETURN(0);
  }
  else
4285
#endif
4286
  {
4287
    store_schema_partitions_record(thd, table, show_table, 0, file, 0);
4288 4289 4290 4291 4292 4293 4294
    if(schema_table_store_record(thd, table))
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}


4295
#ifdef NOT_USED
4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331
static interval_type get_real_interval_type(interval_type i_type)
{
  switch (i_type) {
  case INTERVAL_YEAR:
    return INTERVAL_YEAR;

  case INTERVAL_QUARTER:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
    return INTERVAL_MONTH;

  case INTERVAL_WEEK:
  case INTERVAL_DAY:
    return INTERVAL_DAY;

  case INTERVAL_DAY_HOUR:
  case INTERVAL_HOUR:
    return INTERVAL_HOUR;

  case INTERVAL_DAY_MINUTE:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_MINUTE:
    return INTERVAL_MINUTE;

  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    return INTERVAL_SECOND;

  case INTERVAL_DAY_MICROSECOND:
  case INTERVAL_HOUR_MICROSECOND:
  case INTERVAL_MINUTE_MICROSECOND:
  case INTERVAL_SECOND_MICROSECOND:
  case INTERVAL_MICROSECOND:
    return INTERVAL_MICROSECOND;
4332 4333
  case INTERVAL_LAST:
    DBUG_ASSERT(0);
4334 4335 4336 4337 4338
  }
  DBUG_ASSERT(0);
  return INTERVAL_SECOND;
}

4339 4340
#endif

4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356

/*
  Loads an event from mysql.event and copies it's data to a row of
  I_S.EVENTS

  Synopsis
    copy_event_to_schema_table()
      thd         Thread
      sch_table   The schema table (information_schema.event)
      event_table The event table to use for loading (mysql.event).

  Returns
    0  OK
    1  Error
*/

4357
int
4358
copy_event_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table)
4359 4360 4361
{
  const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS;
  CHARSET_INFO *scs= system_charset_info;
4362
  MYSQL_TIME time;
4363
  Event_timed et;
4364
  DBUG_ENTER("copy_event_to_schema_table");
4365 4366 4367

  restore_record(sch_table, s->default_values);

4368
  if (et.load_from_row(thd, event_table))
4369
  {
4370
    my_error(ER_CANNOT_LOAD_FROM_TABLE, MYF(0), event_table->alias);
4371 4372 4373 4374 4375
    DBUG_RETURN(1);
  }

  if (!(!wild || !wild[0] || !wild_compare(et.name.str, wild, 0)))
    DBUG_RETURN(0);
4376 4377 4378 4379 4380 4381

  /*
    Skip events in schemas one does not have access to. The check is
    optimized. It's guaranteed in case of SHOW EVENTS that the user
    has access.
  */
4382
  if (thd->lex->sql_command != SQLCOM_SHOW_EVENTS &&
4383 4384 4385 4386
      check_access(thd, EVENT_ACL, et.dbname.str, 0, 0, 1,
                   is_schema_db(et.dbname.str)))
    DBUG_RETURN(0);

4387
  /* ->field[0] is EVENT_CATALOG and is by default NULL */
4388

4389 4390 4391 4392 4393 4394
  sch_table->field[ISE_EVENT_SCHEMA]->
                                store(et.dbname.str, et.dbname.length,scs);
  sch_table->field[ISE_EVENT_NAME]->
                                store(et.name.str, et.name.length, scs);
  sch_table->field[ISE_DEFINER]->
                                store(et.definer.str, et.definer.length, scs);
4395 4396 4397
  const String *tz_name= et.time_zone->get_name();
  sch_table->field[ISE_TIME_ZONE]->
                                store(tz_name->ptr(), tz_name->length(), scs);
4398 4399
  sch_table->field[ISE_EVENT_BODY]->
                                store(STRING_WITH_LEN("SQL"), scs);
4400 4401
  sch_table->field[ISE_EVENT_DEFINITION]->store(
    et.body_utf8.str, et.body_utf8.length, scs);
4402 4403

  /* SQL_MODE */
4404
  {
4405 4406 4407
    LEX_STRING sql_mode;
    sys_var_thd_sql_mode::symbolic_mode_representation(thd, et.sql_mode,
                                                       &sql_mode);
4408
    sch_table->field[ISE_SQL_MODE]->
4409
                                store(sql_mode.str, sql_mode.length, scs);
4410
  }
4411

4412 4413
  int not_used=0;

4414 4415
  if (et.expression)
  {
4416
    String show_str;
4417
    /* type */
4418
    sch_table->field[ISE_EVENT_TYPE]->store(STRING_WITH_LEN("RECURRING"), scs);
4419

4420 4421
    if (Events::reconstruct_interval_expression(&show_str, et.interval,
                                                et.expression))
4422
      DBUG_RETURN(1);
4423

4424 4425 4426
    sch_table->field[ISE_INTERVAL_VALUE]->set_notnull();
    sch_table->field[ISE_INTERVAL_VALUE]->
                                store(show_str.ptr(), show_str.length(), scs);
4427 4428

    LEX_STRING *ival= &interval_type_to_name[et.interval];
4429 4430
    sch_table->field[ISE_INTERVAL_FIELD]->set_notnull();
    sch_table->field[ISE_INTERVAL_FIELD]->store(ival->str, ival->length, scs);
4431

4432
    /* starts & ends . STARTS is always set - see sql_yacc.yy */
4433
    et.time_zone->gmt_sec_to_TIME(&time, et.starts);
4434 4435
    sch_table->field[ISE_STARTS]->set_notnull();
    sch_table->field[ISE_STARTS]->
4436
                                store_time(&time, MYSQL_TIMESTAMP_DATETIME);
4437 4438 4439

    if (!et.ends_null)
    {
4440
      et.time_zone->gmt_sec_to_TIME(&time, et.ends);
4441 4442
      sch_table->field[ISE_ENDS]->set_notnull();
      sch_table->field[ISE_ENDS]->
4443
                                store_time(&time, MYSQL_TIMESTAMP_DATETIME);
4444
    }
4445 4446 4447
  }
  else
  {
4448 4449
    /* type */
    sch_table->field[ISE_EVENT_TYPE]->store(STRING_WITH_LEN("ONE TIME"), scs);
4450

4451
    et.time_zone->gmt_sec_to_TIME(&time, et.execute_at);
4452 4453
    sch_table->field[ISE_EXECUTE_AT]->set_notnull();
    sch_table->field[ISE_EXECUTE_AT]->
4454
                          store_time(&time, MYSQL_TIMESTAMP_DATETIME);
4455 4456
  }

4457
  /* status */
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474

  switch (et.status)
  {
    case Event_timed::ENABLED:
      sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("ENABLED"), scs);
      break;
    case Event_timed::SLAVESIDE_DISABLED:
      sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("SLAVESIDE_DISABLED"),
                                          scs);
      break;
    case Event_timed::DISABLED:
      sch_table->field[ISE_STATUS]->store(STRING_WITH_LEN("DISABLED"), scs);
      break;
    default:
      DBUG_ASSERT(0);
  }
  sch_table->field[ISE_ORIGINATOR]->store(et.originator, TRUE);
4475

4476
  /* on_completion */
4477
  if (et.on_completion == Event_timed::ON_COMPLETION_DROP)
4478 4479
    sch_table->field[ISE_ON_COMPLETION]->
                                store(STRING_WITH_LEN("NOT PRESERVE"), scs);
4480
  else
4481 4482
    sch_table->field[ISE_ON_COMPLETION]->
                                store(STRING_WITH_LEN("PRESERVE"), scs);
4483 4484 4485
    
  number_to_datetime(et.created, &time, 0, &not_used);
  DBUG_ASSERT(not_used==0);
4486
  sch_table->field[ISE_CREATED]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
4487 4488 4489

  number_to_datetime(et.modified, &time, 0, &not_used);
  DBUG_ASSERT(not_used==0);
4490 4491
  sch_table->field[ISE_LAST_ALTERED]->
                                store_time(&time, MYSQL_TIMESTAMP_DATETIME);
4492

4493
  if (et.last_executed)
4494
  {
4495
    et.time_zone->gmt_sec_to_TIME(&time, et.last_executed);
4496 4497
    sch_table->field[ISE_LAST_EXECUTED]->set_notnull();
    sch_table->field[ISE_LAST_EXECUTED]->
4498
                       store_time(&time, MYSQL_TIMESTAMP_DATETIME);
4499
  }
4500

4501 4502
  sch_table->field[ISE_EVENT_COMMENT]->
                      store(et.comment.str, et.comment.length, scs);
4503

4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521
  sch_table->field[ISE_CLIENT_CS]->set_notnull();
  sch_table->field[ISE_CLIENT_CS]->store(
    et.creation_ctx->get_client_cs()->csname,
    strlen(et.creation_ctx->get_client_cs()->csname),
    scs);

  sch_table->field[ISE_CONNECTION_CL]->set_notnull();
  sch_table->field[ISE_CONNECTION_CL]->store(
    et.creation_ctx->get_connection_cl()->name,
    strlen(et.creation_ctx->get_connection_cl()->name),
    scs);

  sch_table->field[ISE_DB_CL]->set_notnull();
  sch_table->field[ISE_DB_CL]->store(
    et.creation_ctx->get_db_cl()->name,
    strlen(et.creation_ctx->get_db_cl()->name),
    scs);

4522 4523 4524 4525 4526 4527 4528
  if (schema_table_store_record(thd, sch_table))
    DBUG_RETURN(1);

  DBUG_RETURN(0);
}


4529 4530 4531 4532 4533 4534 4535
int fill_open_tables(THD *thd, TABLE_LIST *tables, COND *cond)
{
  DBUG_ENTER("fill_open_tables");
  const char *wild= thd->lex->wild ? thd->lex->wild->ptr() : NullS;
  TABLE *table= tables->table;
  CHARSET_INFO *cs= system_charset_info;
  OPEN_TABLE_LIST *open_list;
4536 4537
  if (!(open_list=list_open_tables(thd,thd->lex->select_lex.db, wild))
            && thd->is_fatal_error)
4538 4539 4540 4541
    DBUG_RETURN(1);

  for (; open_list ; open_list=open_list->next)
  {
4542
    restore_record(table, s->default_values);
4543 4544
    table->field[0]->store(open_list->db, strlen(open_list->db), cs);
    table->field[1]->store(open_list->table, strlen(open_list->table), cs);
4545 4546
    table->field[2]->store((longlong) open_list->in_use, TRUE);
    table->field[3]->store((longlong) open_list->locked, TRUE);
4547 4548
    if (schema_table_store_record(thd, table))
      DBUG_RETURN(1);
4549 4550 4551 4552 4553 4554 4555 4556
  }
  DBUG_RETURN(0);
}


int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond)
{
  DBUG_ENTER("fill_variables");
4557
  int res= 0;
4558 4559
  LEX *lex= thd->lex;
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569
  enum enum_schema_tables schema_table_idx=
    get_schema_table_idx(tables->schema_table);
  enum enum_var_type option_type= OPT_SESSION;
  bool upper_case_names= (schema_table_idx != SCH_VARIABLES);
  bool sorted_vars= (schema_table_idx == SCH_VARIABLES);

  if (lex->option_type == OPT_GLOBAL ||
      schema_table_idx == SCH_GLOBAL_VARIABLES)
    option_type= OPT_GLOBAL;

antony@ppcg5.local's avatar
antony@ppcg5.local committed
4570
  rw_rdlock(&LOCK_system_variables_hash);
4571 4572
  res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars),
                         option_type, NULL, "", tables->table, upper_case_names);
antony@ppcg5.local's avatar
antony@ppcg5.local committed
4573
  rw_unlock(&LOCK_system_variables_hash);
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
  DBUG_RETURN(res);
}


int fill_status(THD *thd, TABLE_LIST *tables, COND *cond)
{
  DBUG_ENTER("fill_status");
  LEX *lex= thd->lex;
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
  int res= 0;
4584 4585 4586 4587 4588 4589
  STATUS_VAR *tmp1, tmp;
  enum enum_schema_tables schema_table_idx=
    get_schema_table_idx(tables->schema_table);
  enum enum_var_type option_type;
  bool upper_case_names= (schema_table_idx != SCH_STATUS);

4590 4591 4592 4593 4594 4595 4596 4597 4598
  if (schema_table_idx == SCH_STATUS)
  {
    option_type= lex->option_type;
    if (option_type == OPT_GLOBAL)
      tmp1= &tmp;
    else
      tmp1= thd->initial_status_var;
  }
  else if (schema_table_idx == SCH_GLOBAL_STATUS)
4599 4600 4601 4602 4603
  {
    option_type= OPT_GLOBAL;
    tmp1= &tmp;
  }
  else
4604
  { 
4605
    option_type= OPT_SESSION;
4606
    tmp1= &thd->status_var;
4607 4608
  }

4609
  pthread_mutex_lock(&LOCK_status);
4610
  if (option_type == OPT_GLOBAL)
4611
    calc_sum_of_all_status(&tmp);
4612 4613
  res= show_status_array(thd, wild,
                         (SHOW_VAR *)all_status_vars.buffer,
4614 4615
                         option_type, tmp1, "", tables->table,
                         upper_case_names);
4616
  pthread_mutex_unlock(&LOCK_status);
4617 4618 4619 4620
  DBUG_RETURN(res);
}


4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639
/*
  Fill and store records into I_S.referential_constraints table

  SYNOPSIS
    get_referential_constraints_record()
    thd                 thread handle
    tables              table list struct(processed table)
    table               I_S table
    res                 1 means the error during opening of the processed table
                        0 means processed table is opened without error
    base_name           db name
    file_name           table name

  RETURN
    0	ok
    #   error
*/

static int
4640
get_referential_constraints_record(THD *thd, TABLE_LIST *tables,
4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674
                                   TABLE *table, bool res,
                                   const char *base_name, const char *file_name)
{
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_referential_constraints_record");

  if (res)
  {
    if (!tables->view)
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                   thd->net.last_errno, thd->net.last_error);
    thd->clear_error();
    DBUG_RETURN(0);
  }
  if (!tables->view)
  {
    List<FOREIGN_KEY_INFO> f_key_list;
    TABLE *show_table= tables->table;
    show_table->file->info(HA_STATUS_VARIABLE | 
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);

    show_table->file->get_foreign_key_list(thd, &f_key_list);
    FOREIGN_KEY_INFO *f_key_info;
    List_iterator_fast<FOREIGN_KEY_INFO> it(f_key_list);
    while ((f_key_info= it++))
    {
      restore_record(table, s->default_values);
      table->field[1]->store(base_name, strlen(base_name), cs);
      table->field[9]->store(file_name, strlen(file_name), cs);
      table->field[2]->store(f_key_info->forein_id->str,
                             f_key_info->forein_id->length, cs);
      table->field[4]->store(f_key_info->referenced_db->str, 
                             f_key_info->referenced_db->length, cs);
4675
      table->field[10]->store(f_key_info->referenced_table->str, 
4676
                             f_key_info->referenced_table->length, cs);
4677 4678
      table->field[5]->store(f_key_info->referenced_key_name->str, 
                             f_key_info->referenced_key_name->length, cs);
4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690
      table->field[6]->store(STRING_WITH_LEN("NONE"), cs);
      table->field[7]->store(f_key_info->update_method->str, 
                             f_key_info->update_method->length, cs);
      table->field[8]->store(f_key_info->delete_method->str, 
                             f_key_info->delete_method->length, cs);
      if (schema_table_store_record(thd, table))
        DBUG_RETURN(1);
    }
  }
  DBUG_RETURN(0);
}

brian@zim.(none)'s avatar
brian@zim.(none) committed
4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710
struct schema_table_ref 
{
  const char *table_name;
  ST_SCHEMA_TABLE *schema_table;
};


/*
  Find schema_tables elment by name

  SYNOPSIS
    find_schema_table_in_plugin()
    thd                 thread handler
    plugin              plugin
    table_name          table name

  RETURN
    0	table not found
    1   found the schema table
*/
antony@ppcg5.local's avatar
antony@ppcg5.local committed
4711
static my_bool find_schema_table_in_plugin(THD *thd, plugin_ref plugin,
brian@zim.(none)'s avatar
brian@zim.(none) committed
4712 4713 4714 4715
                                           void* p_table)
{
  schema_table_ref *p_schema_table= (schema_table_ref *)p_table;
  const char* table_name= p_schema_table->table_name;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
4716
  ST_SCHEMA_TABLE *schema_table= plugin_data(plugin, ST_SCHEMA_TABLE *);
brian@zim.(none)'s avatar
brian@zim.(none) committed
4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
  DBUG_ENTER("find_schema_table_in_plugin");

  if (!my_strcasecmp(system_charset_info,
                     schema_table->table_name,
                     table_name)) {
    p_schema_table->schema_table= schema_table;
    DBUG_RETURN(1);
  }

  DBUG_RETURN(0);
}

4729

4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
/*
  Find schema_tables elment by name

  SYNOPSIS
    find_schema_table()
    thd                 thread handler
    table_name          table name

  RETURN
    0	table not found
    #   pointer to 'shema_tables' element
*/

ST_SCHEMA_TABLE *find_schema_table(THD *thd, const char* table_name)
{
brian@zim.(none)'s avatar
brian@zim.(none) committed
4745
  schema_table_ref schema_table_a;
4746
  ST_SCHEMA_TABLE *schema_table= schema_tables;
brian@zim.(none)'s avatar
brian@zim.(none) committed
4747 4748
  DBUG_ENTER("find_schema_table");

4749
  for (; schema_table->table_name; schema_table++)
4750 4751 4752 4753
  {
    if (!my_strcasecmp(system_charset_info,
                       schema_table->table_name,
                       table_name))
brian@zim.(none)'s avatar
brian@zim.(none) committed
4754
      DBUG_RETURN(schema_table);
4755
  }
brian@zim.(none)'s avatar
brian@zim.(none) committed
4756 4757 4758 4759 4760 4761 4762

  schema_table_a.table_name= table_name;
  if (plugin_foreach(thd, find_schema_table_in_plugin, 
                     MYSQL_INFORMATION_SCHEMA_PLUGIN, &schema_table_a))
    DBUG_RETURN(schema_table_a.schema_table);

  DBUG_RETURN(NULL);
4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
}


ST_SCHEMA_TABLE *get_schema_table(enum enum_schema_tables schema_table_idx)
{
  return &schema_tables[schema_table_idx];
}


/*
  Create information_schema table using schema_table data

  SYNOPSIS
    create_schema_table()
    thd	       	          thread handler
    schema_table          pointer to 'shema_tables' element

  RETURN
    #	                  Pointer to created table
    0	                  Can't create table
*/

4785
TABLE *create_schema_table(THD *thd, TABLE_LIST *table_list)
4786 4787 4788 4789 4790
{
  int field_count= 0;
  Item *item;
  TABLE *table;
  List<Item> field_list;
4791
  ST_SCHEMA_TABLE *schema_table= table_list->schema_table;
4792
  ST_FIELD_INFO *fields_info= schema_table->fields_info;
4793
  CHARSET_INFO *cs= system_charset_info;
4794 4795
  DBUG_ENTER("create_schema_table");

4796
  for (; fields_info->field_name; fields_info++)
4797 4798
  {
    switch (fields_info->field_type) {
4799
    case MYSQL_TYPE_TINY:
4800
    case MYSQL_TYPE_LONG:
4801 4802 4803 4804 4805 4806 4807
    case MYSQL_TYPE_SHORT:
    case MYSQL_TYPE_LONGLONG:
    case MYSQL_TYPE_INT24:
      if (!(item= new Item_return_int(fields_info->field_name,
                                      fields_info->field_length,
                                      fields_info->field_type,
                                      fields_info->value)))
4808 4809 4810
      {
        DBUG_RETURN(0);
      }
4811
      item->unsigned_flag= (fields_info->field_flags & MY_I_S_UNSIGNED);
4812
      break;
4813 4814
    case MYSQL_TYPE_DATE:
    case MYSQL_TYPE_TIME:
4815
    case MYSQL_TYPE_TIMESTAMP:
4816 4817 4818
    case MYSQL_TYPE_DATETIME:
      if (!(item=new Item_return_date_time(fields_info->field_name,
                                           fields_info->field_type)))
4819 4820 4821 4822
      {
        DBUG_RETURN(0);
      }
      break;
4823 4824 4825 4826 4827 4828
    case MYSQL_TYPE_FLOAT:
    case MYSQL_TYPE_DOUBLE:
      if ((item= new Item_float(fields_info->field_name, 0.0, NOT_FIXED_DEC, 
                           fields_info->field_length)) == NULL)
        DBUG_RETURN(NULL);
      break;
4829 4830 4831 4832 4833
    case MYSQL_TYPE_DECIMAL:
      if (!(item= new Item_decimal((longlong) fields_info->value, false)))
      {
        DBUG_RETURN(0);
      }
4834
      item->unsigned_flag= (fields_info->field_flags & MY_I_S_UNSIGNED);
4835 4836 4837 4838 4839 4840 4841 4842 4843
      item->decimals= fields_info->field_length%10;
      item->max_length= (fields_info->field_length/100)%100;
      if (item->unsigned_flag == 0)
        item->max_length+= 1;
      if (item->decimals > 0)
        item->max_length+= 1;
      item->set_name(fields_info->field_name,
                     strlen(fields_info->field_name), cs);
      break;
4844 4845 4846 4847 4848 4849 4850 4851 4852 4853
    case MYSQL_TYPE_TINY_BLOB:
    case MYSQL_TYPE_MEDIUM_BLOB:
    case MYSQL_TYPE_LONG_BLOB:
    case MYSQL_TYPE_BLOB:
      if (!(item= new Item_blob(fields_info->field_name,
                                fields_info->field_length)))
      {
        DBUG_RETURN(0);
      }
      break;
4854
    default:
4855 4856 4857
      /* Don't let unimplemented types pass through. Could be a grave error. */
      DBUG_ASSERT(fields_info->field_type == MYSQL_TYPE_STRING);

4858
      if (!(item= new Item_empty_string("", fields_info->field_length, cs)))
4859 4860 4861
      {
        DBUG_RETURN(0);
      }
4862 4863
      item->set_name(fields_info->field_name,
                     strlen(fields_info->field_name), cs);
4864 4865 4866
      break;
    }
    field_list.push_back(item);
4867
    item->maybe_null= (fields_info->field_flags & MY_I_S_MAYBE_NULL);
4868 4869 4870
    field_count++;
  }
  TMP_TABLE_PARAM *tmp_table_param =
4871
    (TMP_TABLE_PARAM*) (thd->alloc(sizeof(TMP_TABLE_PARAM)));
4872
  tmp_table_param->init();
4873
  tmp_table_param->table_charset= cs;
4874
  tmp_table_param->field_count= field_count;
4875
  tmp_table_param->schema_table= 1;
4876 4877 4878 4879 4880
  SELECT_LEX *select_lex= thd->lex->current_select;
  if (!(table= create_tmp_table(thd, tmp_table_param,
                                field_list, (ORDER*) 0, 0, 0, 
                                (select_lex->options | thd->options |
                                 TMP_TABLE_ALL_COLUMNS),
4881
                                HA_POS_ERROR, table_list->alias)))
4882
    DBUG_RETURN(0);
4883
  table_list->schema_table_param= tmp_table_param;
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898
  DBUG_RETURN(table);
}


/*
  For old SHOW compatibility. It is used when
  old SHOW doesn't have generated column names
  Make list of fields for SHOW

  SYNOPSIS
    make_old_format()
    thd			thread handler
    schema_table        pointer to 'schema_tables' element

  RETURN
4899 4900
   1	error
   0	success
4901 4902 4903 4904 4905
*/

int make_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
  ST_FIELD_INFO *field_info= schema_table->fields_info;
4906
  Name_resolution_context *context= &thd->lex->select_lex.context;
4907
  for (; field_info->field_name; field_info++)
4908 4909 4910
  {
    if (field_info->old_name)
    {
4911 4912
      Item_field *field= new Item_field(context,
                                        NullS, NullS, field_info->field_name);
4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931
      if (field)
      {
        field->set_name(field_info->old_name,
                        strlen(field_info->old_name),
                        system_charset_info);
        if (add_item_to_list(thd, field))
          return 1;
      }
    }
  }
  return 0;
}


int make_schemata_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
  char tmp[128];
  LEX *lex= thd->lex;
  SELECT_LEX *sel= lex->current_select;
4932
  Name_resolution_context *context= &sel->context;
4933 4934 4935 4936 4937

  if (!sel->item_list.elements)
  {
    ST_FIELD_INFO *field_info= &schema_table->fields_info[1];
    String buffer(tmp,sizeof(tmp), system_charset_info);
4938 4939
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
4940 4941 4942 4943 4944 4945
    if (!field || add_item_to_list(thd, field))
      return 1;
    buffer.length(0);
    buffer.append(field_info->old_name);
    if (lex->wild && lex->wild->ptr())
    {
4946
      buffer.append(STRING_WITH_LEN(" ("));
4947
      buffer.append(lex->wild->ptr());
4948
      buffer.append(')');
4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960
    }
    field->set_name(buffer.ptr(), buffer.length(), system_charset_info);
  }
  return 0;
}


int make_table_names_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
  char tmp[128];
  String buffer(tmp,sizeof(tmp), thd->charset());
  LEX *lex= thd->lex;
4961
  Name_resolution_context *context= &lex->select_lex.context;
4962 4963 4964 4965 4966 4967 4968

  ST_FIELD_INFO *field_info= &schema_table->fields_info[2];
  buffer.length(0);
  buffer.append(field_info->old_name);
  buffer.append(lex->select_lex.db);
  if (lex->wild && lex->wild->ptr())
  {
4969
    buffer.append(STRING_WITH_LEN(" ("));
4970
    buffer.append(lex->wild->ptr());
4971
    buffer.append(')');
4972
  }
4973 4974
  Item_field *field= new Item_field(context,
                                    NullS, NullS, field_info->field_name);
4975 4976 4977 4978 4979 4980 4981
  if (add_item_to_list(thd, field))
    return 1;
  field->set_name(buffer.ptr(), buffer.length(), system_charset_info);
  if (thd->lex->verbose)
  {
    field->set_name(buffer.ptr(), buffer.length(), system_charset_info);
    field_info= &schema_table->fields_info[3];
4982
    field= new Item_field(context, NullS, NullS, field_info->field_name);
4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
    if (add_item_to_list(thd, field))
      return 1;
    field->set_name(field_info->old_name, strlen(field_info->old_name),
                    system_charset_info);
  }
  return 0;
}


int make_columns_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
4994 4995 4996
  int fields_arr[]= {3, 14, 13, 6, 15, 5, 16, 17, 18, -1};
  int *field_num= fields_arr;
  ST_FIELD_INFO *field_info;
4997 4998
  Name_resolution_context *context= &thd->lex->select_lex.context;

4999
  for (; *field_num >= 0; field_num++)
5000
  {
5001 5002 5003 5004 5005
    field_info= &schema_table->fields_info[*field_num];
    if (!thd->lex->verbose && (*field_num == 13 ||
                               *field_num == 17 ||
                               *field_num == 18))
      continue;
5006 5007
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
5008
    if (field)
5009
    {
5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020
      field->set_name(field_info->old_name,
                      strlen(field_info->old_name),
                      system_charset_info);
      if (add_item_to_list(thd, field))
        return 1;
    }
  }
  return 0;
}


5021 5022 5023 5024 5025
int make_character_sets_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
  int fields_arr[]= {0, 2, 1, 3, -1};
  int *field_num= fields_arr;
  ST_FIELD_INFO *field_info;
5026 5027
  Name_resolution_context *context= &thd->lex->select_lex.context;

5028 5029 5030
  for (; *field_num >= 0; field_num++)
  {
    field_info= &schema_table->fields_info[*field_num];
5031 5032
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045
    if (field)
    {
      field->set_name(field_info->old_name,
                      strlen(field_info->old_name),
                      system_charset_info);
      if (add_item_to_list(thd, field))
        return 1;
    }
  }
  return 0;
}


5046 5047
int make_proc_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
5048
  int fields_arr[]= {2, 3, 4, 19, 16, 15, 14, 18, 20, 21, 22, -1};
5049 5050
  int *field_num= fields_arr;
  ST_FIELD_INFO *field_info;
5051 5052
  Name_resolution_context *context= &thd->lex->select_lex.context;

5053 5054 5055
  for (; *field_num >= 0; field_num++)
  {
    field_info= &schema_table->fields_info[*field_num];
5056 5057
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
5058 5059 5060 5061 5062 5063 5064
    if (field)
    {
      field->set_name(field_info->old_name,
                      strlen(field_info->old_name),
                      system_charset_info);
      if (add_item_to_list(thd, field))
        return 1;
5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088
    }
  }
  return 0;
}


/*
  Create information_schema table

  SYNOPSIS
  mysql_schema_table()
    thd                thread handler
    lex                pointer to LEX
    table_list         pointer to table_list

  RETURN
    0	success
    1   error
*/

int mysql_schema_table(THD *thd, LEX *lex, TABLE_LIST *table_list)
{
  TABLE *table;
  DBUG_ENTER("mysql_schema_table");
5089
  if (!(table= table_list->schema_table->create_table(thd, table_list)))
5090
    DBUG_RETURN(1);
5091
  table->s->tmp_table= SYSTEM_TMP_TABLE;
5092
  table->grant.privilege= SELECT_ACL;
5093 5094 5095 5096 5097 5098 5099
  /*
    This test is necessary to make
    case insensitive file systems +
    upper case table names(information schema tables) +
    views
    working correctly
  */
5100 5101 5102 5103
  if (table_list->schema_table_name)
    table->alias_name_used= my_strcasecmp(table_alias_charset,
                                          table_list->schema_table_name,
                                          table_list->alias);
5104 5105
  table_list->table_name= table->s->table_name.str;
  table_list->table_name_length= table->s->table_name.length;
5106 5107 5108 5109
  table_list->table= table;
  table->next= thd->derived_tables;
  thd->derived_tables= table;
  table_list->select_lex->options |= OPTION_SCHEMA_TABLE;
5110
  lex->safe_to_cache_query= 0;
5111 5112 5113 5114 5115

  if (table_list->schema_table_reformed) // show command
  {
    SELECT_LEX *sel= lex->current_select;
    Item *item;
5116
    Field_translator *transl, *org_transl;
5117 5118 5119

    if (table_list->field_translation)
    {
5120
      Field_translator *end= table_list->field_translation_end;
5121 5122 5123
      for (transl= table_list->field_translation; transl < end; transl++)
      {
        if (!transl->item->fixed &&
5124
            transl->item->fix_fields(thd, &transl->item))
5125 5126 5127 5128 5129 5130
          DBUG_RETURN(1);
      }
      DBUG_RETURN(0);
    }
    List_iterator_fast<Item> it(sel->item_list);
    if (!(transl=
konstantin@mysql.com's avatar
konstantin@mysql.com committed
5131
          (Field_translator*)(thd->stmt_arena->
5132 5133 5134 5135 5136
                              alloc(sel->item_list.elements *
                                    sizeof(Field_translator)))))
    {
      DBUG_RETURN(1);
    }
5137
    for (org_transl= transl; (item= it++); transl++)
5138
    {
5139 5140 5141 5142
      transl->item= item;
      transl->name= item->name;
      if (!item->fixed && item->fix_fields(thd, &transl->item))
      {
5143
        DBUG_RETURN(1);
5144
      }
5145
    }
5146 5147
    table_list->field_translation= org_transl;
    table_list->field_translation_end= transl;
5148 5149
  }

5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173
  DBUG_RETURN(0);
}


/*
  Generate select from information_schema table

  SYNOPSIS
    make_schema_select()
    thd                  thread handler
    sel                  pointer to SELECT_LEX
    schema_table_idx     index of 'schema_tables' element

  RETURN
    0	success
    1   error
*/

int make_schema_select(THD *thd, SELECT_LEX *sel,
		       enum enum_schema_tables schema_table_idx)
{
  ST_SCHEMA_TABLE *schema_table= get_schema_table(schema_table_idx);
  LEX_STRING db, table;
  DBUG_ENTER("mysql_schema_select");
5174
  DBUG_PRINT("enter", ("mysql_schema_select: %s", schema_table->table_name));
5175
  /*
5176 5177 5178
     We have to make non const db_name & table_name
     because of lower_case_table_names
  */
5179 5180 5181 5182
  thd->make_lex_string(&db, INFORMATION_SCHEMA_NAME.str,
                       INFORMATION_SCHEMA_NAME.length, 0);
  thd->make_lex_string(&table, schema_table->table_name,
                       strlen(schema_table->table_name), 0);
5183
  if (schema_table->old_format(thd, schema_table) ||   /* Handle old syntax */
5184
      !sel->add_table_to_list(thd, new Table_ident(thd, db, table, 0),
5185
                              0, 0, TL_READ))
5186 5187 5188 5189 5190 5191 5192 5193
  {
    DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}


/*
5194
  Fill temporary schema tables before SELECT
5195 5196 5197 5198

  SYNOPSIS
    get_schema_tables_result()
    join  join which use schema tables
5199
    executed_place place where I_S table processed
5200 5201

  RETURN
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5202 5203
    FALSE success
    TRUE  error
5204 5205
*/

5206 5207
bool get_schema_tables_result(JOIN *join,
                              enum enum_schema_table_state executed_place)
5208 5209 5210
{
  JOIN_TAB *tmp_join_tab= join->join_tab+join->tables;
  THD *thd= join->thd;
5211 5212
  LEX *lex= thd->lex;
  bool result= 0;
5213 5214 5215
  DBUG_ENTER("get_schema_tables_result");

  thd->no_warnings_for_error= 1;
5216 5217 5218 5219
  for (JOIN_TAB *tab= join->join_tab; tab < tmp_join_tab; tab++)
  {  
    if (!tab->table || !tab->table->pos_in_table_list)
      break;
5220

5221
    TABLE_LIST *table_list= tab->table->pos_in_table_list;
5222
    if (table_list->schema_table && thd->fill_information_schema_tables())
5223
    {
5224 5225
      bool is_subselect= (&lex->unit != lex->current_select->master_unit() &&
                          lex->current_select->master_unit()->item);
5226
      /*
5227 5228 5229 5230 5231 5232 5233
        If schema table is already processed and
        the statement is not a subselect then
        we don't need to fill this table again.
        If schema table is already processed and
        schema_table_state != executed_place then
        table is already processed and
        we should skip second data processing.
5234
      */
5235 5236
      if (table_list->schema_table_state &&
          (!is_subselect || table_list->schema_table_state != executed_place))
5237 5238
        continue;

5239 5240 5241 5242 5243 5244
      /*
        if table is used in a subselect and
        table has been processed earlier with the same
        'executed_place' value then we should refresh the table.
      */
      if (table_list->schema_table_state && is_subselect)
5245
      {
5246
        table_list->table->file->extra(HA_EXTRA_NO_CACHE);
5247 5248 5249
        table_list->table->file->extra(HA_EXTRA_RESET_STATE);
        table_list->table->file->delete_all_rows();
        free_io_cache(table_list->table);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
5250
        filesort_free_buffers(table_list->table,1);
5251
        table_list->table->null_row= 0;
5252 5253
      }
      else
5254
        table_list->table->file->stats.records= 0;
5255

5256 5257
      if (table_list->schema_table->fill_table(thd, table_list,
                                               tab->select_cond))
5258
      {
5259
        result= 1;
5260
        join->error= 1;
5261
        table_list->schema_table_state= executed_place;
5262 5263
        break;
      }
5264
      table_list->schema_table_state= executed_place;
5265 5266
    }
  }
5267
  thd->no_warnings_for_error= 0;
5268
  DBUG_RETURN(result);
5269 5270
}

5271 5272 5273 5274 5275 5276
struct run_hton_fill_schema_files_args
{
  TABLE_LIST *tables;
  COND *cond;
};

antony@ppcg5.local's avatar
antony@ppcg5.local committed
5277
static my_bool run_hton_fill_schema_files(THD *thd, plugin_ref plugin,
5278 5279 5280 5281
                                          void *arg)
{
  struct run_hton_fill_schema_files_args *args=
    (run_hton_fill_schema_files_args *) arg;
antony@ppcg5.local's avatar
antony@ppcg5.local committed
5282
  handlerton *hton= plugin_data(plugin, handlerton *);
5283
  if(hton->fill_files_table && hton->state == SHOW_OPTION_YES)
5284
    hton->fill_files_table(hton, thd, args->tables, args->cond);
5285 5286 5287 5288 5289
  return false;
}

int fill_schema_files(THD *thd, TABLE_LIST *tables, COND *cond)
{
5290
  DBUG_ENTER("fill_schema_files");
5291 5292 5293 5294 5295 5296 5297 5298 5299 5300

  struct run_hton_fill_schema_files_args args;
  args.tables= tables;
  args.cond= cond;

  plugin_foreach(thd, run_hton_fill_schema_files,
                 MYSQL_STORAGE_ENGINE_PLUGIN, &args);

  DBUG_RETURN(0);
}
5301

5302

5303 5304
ST_FIELD_INFO schema_fields_info[]=
{
5305
  {"CATALOG_NAME", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5306
  {"SCHEMA_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Database"},
5307
  {"DEFAULT_CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
5308
  {"DEFAULT_COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
5309
  {"SQL_PATH", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5310
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5311 5312 5313 5314 5315
};


ST_FIELD_INFO tables_fields_info[]=
{
5316
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5317 5318 5319 5320
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name"},
  {"TABLE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Engine"},
5321 5322
  {"VERSION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Version"},
5323
  {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format"},
5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340
  {"TABLE_ROWS", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Rows"},
  {"AVG_ROW_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Avg_row_length"},
  {"DATA_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_length"},
  {"MAX_DATA_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Max_data_length"},
  {"INDEX_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Index_length"},
  {"DATA_FREE", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_free"},
  {"AUTO_INCREMENT", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Auto_increment"},
  {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Create_time"},
  {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Update_time"},
  {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Check_time"},
5341
  {"TABLE_COLLATION", 64, MYSQL_TYPE_STRING, 0, 1, "Collation"},
5342 5343
  {"CHECKSUM", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Checksum"},
5344
  {"CREATE_OPTIONS", 255, MYSQL_TYPE_STRING, 0, 1, "Create_options"},
5345
  {"TABLE_COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, "Comment"},
5346
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5347 5348 5349 5350 5351
};


ST_FIELD_INFO columns_fields_info[]=
{
5352
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5353 5354 5355
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Field"},
5356 5357 5358 5359
  {"ORDINAL_POSITION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0,
   MY_I_S_UNSIGNED, 0},
  {"COLUMN_DEFAULT", MAX_FIELD_VARCHARLENGTH, MYSQL_TYPE_STRING, 0,
   1, "Default"},
5360
  {"IS_NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null"},
5361
  {"DATA_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5362 5363 5364 5365 5366 5367 5368 5369
  {"CHARACTER_MAXIMUM_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG,
   0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"CHARACTER_OCTET_LENGTH", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG,
   0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"NUMERIC_PRECISION", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG,
   0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"NUMERIC_SCALE", MY_INT64_NUM_DECIMAL_DIGITS , MYSQL_TYPE_LONGLONG,
   0, (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
5370 5371
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0},
  {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 1, "Collation"},
5372
  {"COLUMN_TYPE", 65535, MYSQL_TYPE_STRING, 0, 0, "Type"},
5373
  {"COLUMN_KEY", 3, MYSQL_TYPE_STRING, 0, 0, "Key"},
5374 5375
  {"EXTRA", 20, MYSQL_TYPE_STRING, 0, 0, "Extra"},
  {"PRIVILEGES", 80, MYSQL_TYPE_STRING, 0, 0, "Privileges"},
5376
  {"COLUMN_COMMENT", 255, MYSQL_TYPE_STRING, 0, 0, "Comment"},
5377
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5378 5379 5380 5381 5382
};


ST_FIELD_INFO charsets_fields_info[]=
{
5383 5384
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Charset"},
  {"DEFAULT_COLLATE_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Default collation"},
5385
  {"DESCRIPTION", 60, MYSQL_TYPE_STRING, 0, 0, "Description"},
5386
  {"MAXLEN", 3, MYSQL_TYPE_LONGLONG, 0, 0, "Maxlen"},
5387
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5388 5389 5390 5391 5392
};


ST_FIELD_INFO collation_fields_info[]=
{
5393 5394
  {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Collation"},
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Charset"},
5395
  {"ID", MY_INT32_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 0, "Id"},
5396 5397
  {"IS_DEFAULT", 3, MYSQL_TYPE_STRING, 0, 0, "Default"},
  {"IS_COMPILED", 3, MYSQL_TYPE_STRING, 0, 0, "Compiled"},
5398
  {"SORTLEN", 3, MYSQL_TYPE_LONGLONG, 0, 0, "Sortlen"},
5399
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5400 5401 5402
};


5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414
ST_FIELD_INFO engines_fields_info[]=
{
  {"ENGINE", 64, MYSQL_TYPE_STRING, 0, 0, "Engine"},
  {"SUPPORT", 8, MYSQL_TYPE_STRING, 0, 0, "Support"},
  {"COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, "Comment"},
  {"TRANSACTIONS", 3, MYSQL_TYPE_STRING, 0, 0, "Transactions"},
  {"XA", 3, MYSQL_TYPE_STRING, 0, 0, "XA"},
  {"SAVEPOINTS", 3 ,MYSQL_TYPE_STRING, 0, 0, "Savepoints"},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5415 5416
ST_FIELD_INFO events_fields_info[]=
{
5417 5418 5419
  {"EVENT_CATALOG", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"EVENT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Db"},
  {"EVENT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name"},
5420
  {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer"},
5421
  {"TIME_ZONE", 64, MYSQL_TYPE_STRING, 0, 0, "Time zone"},
5422 5423
  {"EVENT_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0},
  {"EVENT_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
5424
  {"EVENT_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type"},
5425
  {"EXECUTE_AT", 0, MYSQL_TYPE_DATETIME, 0, 1, "Execute at"},
5426
  {"INTERVAL_VALUE", 256, MYSQL_TYPE_STRING, 0, 1, "Interval value"},
5427
  {"INTERVAL_FIELD", 18, MYSQL_TYPE_STRING, 0, 1, "Interval field"},
5428
  {"SQL_MODE", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
5429 5430
  {"STARTS", 0, MYSQL_TYPE_DATETIME, 0, 1, "Starts"},
  {"ENDS", 0, MYSQL_TYPE_DATETIME, 0, 1, "Ends"},
5431
  {"STATUS", 18, MYSQL_TYPE_STRING, 0, 0, "Status"},
5432
  {"ON_COMPLETION", 12, MYSQL_TYPE_STRING, 0, 0, 0},
5433 5434 5435
  {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 0, 0},
  {"LAST_ALTERED", 0, MYSQL_TYPE_DATETIME, 0, 0, 0},
  {"LAST_EXECUTED", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
5436
  {"EVENT_COMMENT", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5437 5438 5439 5440 5441 5442 5443 5444
  {"ORIGINATOR", 10, MYSQL_TYPE_LONGLONG, 0, 0, "Originator"},
  {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "character_set_client"},
  {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "collation_connection"},
  {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "Database Collation"},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5445 5446 5447 5448
};



5449 5450
ST_FIELD_INFO coll_charset_app_fields_info[]=
{
5451 5452
  {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
5453
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5454 5455 5456 5457 5458
};


ST_FIELD_INFO proc_fields_info[]=
{
5459
  {"SPECIFIC_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5460
  {"ROUTINE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5461 5462
  {"ROUTINE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Db"},
  {"ROUTINE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name"},
5463
  {"ROUTINE_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type"},
5464
  {"DTD_IDENTIFIER", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5465
  {"ROUTINE_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0},
5466
  {"ROUTINE_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 1, 0},
5467 5468
  {"EXTERNAL_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"EXTERNAL_LANGUAGE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5469
  {"PARAMETER_STYLE", 8, MYSQL_TYPE_STRING, 0, 0, 0},
5470
  {"IS_DETERMINISTIC", 3, MYSQL_TYPE_STRING, 0, 0, 0},
5471 5472
  {"SQL_DATA_ACCESS", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"SQL_PATH", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5473
  {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, "Security_type"},
5474 5475
  {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 0, "Created"},
  {"LAST_ALTERED", 0, MYSQL_TYPE_DATETIME, 0, 0, "Modified"},
5476
  {"SQL_MODE", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
5477
  {"ROUTINE_COMMENT", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Comment"},
5478
  {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer"},
5479 5480 5481 5482 5483 5484
  {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "character_set_client"},
  {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "collation_connection"},
  {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "Database Collation"},
5485
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5486 5487 5488 5489 5490
};


ST_FIELD_INFO stat_fields_info[]=
{
5491
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5492 5493
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table"},
5494
  {"NON_UNIQUE", 1, MYSQL_TYPE_LONGLONG, 0, 0, "Non_unique"},
5495 5496
  {"INDEX_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"INDEX_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Key_name"},
5497
  {"SEQ_IN_INDEX", 2, MYSQL_TYPE_LONGLONG, 0, 0, "Seq_in_index"},
5498
  {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Column_name"},
5499
  {"COLLATION", 1, MYSQL_TYPE_STRING, 0, 1, "Collation"},
5500 5501 5502
  {"CARDINALITY", MY_INT64_NUM_DECIMAL_DIGITS, MYSQL_TYPE_LONGLONG, 0, 1,
   "Cardinality"},
  {"SUB_PART", 3, MYSQL_TYPE_LONGLONG, 0, 1, "Sub_part"},
5503 5504 5505 5506 5507
  {"PACKED", 10, MYSQL_TYPE_STRING, 0, 1, "Packed"},
  {"NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null"},
  {"INDEX_TYPE", 16, MYSQL_TYPE_STRING, 0, 0, "Index_type"},
  {"COMMENT", 16, MYSQL_TYPE_STRING, 0, 1, "Comment"},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5508 5509 5510 5511 5512
};


ST_FIELD_INFO view_fields_info[]=
{
5513
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5514 5515
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5516
  {"VIEW_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
5517
  {"CHECK_OPTION", 8, MYSQL_TYPE_STRING, 0, 0, 0},
5518
  {"IS_UPDATABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
5519 5520
  {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, 0},
  {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, 0},
5521 5522
  {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0, 0},
5523
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5524 5525 5526 5527 5528
};


ST_FIELD_INFO user_privileges_fields_info[]=
{
5529 5530
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5531
  {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5532 5533
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5534 5535 5536 5537 5538
};


ST_FIELD_INFO schema_privileges_fields_info[]=
{
5539 5540
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5541 5542
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5543 5544
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5545 5546 5547 5548 5549
};


ST_FIELD_INFO table_privileges_fields_info[]=
{
5550 5551
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5552 5553 5554
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5555 5556
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5557 5558 5559 5560 5561
};


ST_FIELD_INFO column_privileges_fields_info[]=
{
5562 5563
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5564 5565 5566 5567
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PRIVILEGE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5568 5569
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5570 5571 5572 5573 5574
};


ST_FIELD_INFO table_constraints_fields_info[]=
{
5575
  {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5576 5577 5578 5579 5580
  {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5581
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5582 5583 5584 5585 5586
};


ST_FIELD_INFO key_column_usage_fields_info[]=
{
5587
  {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5588 5589
  {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5590
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5591 5592 5593
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5594 5595
  {"ORDINAL_POSITION", 10 ,MYSQL_TYPE_LONGLONG, 0, 0, 0},
  {"POSITION_IN_UNIQUE_CONSTRAINT", 10 ,MYSQL_TYPE_LONGLONG, 0, 1, 0},
5596 5597 5598
  {"REFERENCED_TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"REFERENCED_TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"REFERENCED_COLUMN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5599
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5600 5601 5602 5603 5604
};


ST_FIELD_INFO table_names_fields_info[]=
{
5605
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5606 5607 5608
  {"TABLE_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Tables_in_"},
  {"TABLE_TYPE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_type"},
5609
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
5610 5611 5612
};


5613 5614
ST_FIELD_INFO open_tables_fields_info[]=
{
5615 5616
  {"Database", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Database"},
  {"Table",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table"},
5617 5618
  {"In_use", 1, MYSQL_TYPE_LONGLONG, 0, 0, "In_use"},
  {"Name_locked", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Name_locked"},
5619 5620 5621 5622
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5623 5624 5625
ST_FIELD_INFO triggers_fields_info[]=
{
  {"TRIGGER_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5626 5627
  {"TRIGGER_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TRIGGER_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Trigger"},
5628 5629
  {"EVENT_MANIPULATION", 6, MYSQL_TYPE_STRING, 0, 0, "Event"},
  {"EVENT_OBJECT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5630 5631
  {"EVENT_OBJECT_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"EVENT_OBJECT_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Table"},
5632
  {"ACTION_ORDER", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0},
5633 5634 5635 5636
  {"ACTION_CONDITION", 65535, MYSQL_TYPE_STRING, 0, 1, 0},
  {"ACTION_STATEMENT", 65535, MYSQL_TYPE_STRING, 0, 0, "Statement"},
  {"ACTION_ORIENTATION", 9, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ACTION_TIMING", 6, MYSQL_TYPE_STRING, 0, 0, "Timing"},
5637 5638
  {"ACTION_REFERENCE_OLD_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"ACTION_REFERENCE_NEW_TABLE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5639 5640
  {"ACTION_REFERENCE_OLD_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ACTION_REFERENCE_NEW_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0},
5641
  {"CREATED", 0, MYSQL_TYPE_DATETIME, 0, 1, "Created"},
5642
  {"SQL_MODE", 65535, MYSQL_TYPE_STRING, 0, 0, "sql_mode"},
5643
  {"DEFINER", 65535, MYSQL_TYPE_STRING, 0, 0, "Definer"},
5644 5645 5646 5647 5648 5649
  {"CHARACTER_SET_CLIENT", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "character_set_client"},
  {"COLLATION_CONNECTION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "collation_connection"},
  {"DATABASE_COLLATION", MY_CS_NAME_SIZE, MYSQL_TYPE_STRING, 0, 0,
   "Database Collation"},
5650 5651 5652 5653
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5654 5655 5656
ST_FIELD_INFO partitions_fields_info[]=
{
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5657 5658 5659 5660
  {"TABLE_SCHEMA",NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PARTITION_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"SUBPARTITION_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5661 5662 5663 5664
  {"PARTITION_ORDINAL_POSITION", 21 , MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"SUBPARTITION_ORDINAL_POSITION", 21 , MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
5665
  {"PARTITION_METHOD", 12, MYSQL_TYPE_STRING, 0, 1, 0},
5666
  {"SUBPARTITION_METHOD", 12, MYSQL_TYPE_STRING, 0, 1, 0},
5667 5668 5669
  {"PARTITION_EXPRESSION", 65535, MYSQL_TYPE_STRING, 0, 1, 0},
  {"SUBPARTITION_EXPRESSION", 65535, MYSQL_TYPE_STRING, 0, 1, 0},
  {"PARTITION_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0},
5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681
  {"TABLE_ROWS", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0},
  {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0},
  {"DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0},
  {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0},
  {"DATA_FREE", 21 , MYSQL_TYPE_LONGLONG, 0, MY_I_S_UNSIGNED, 0},
  {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
  {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
  {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
  {"CHECKSUM", 21 , MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
5682
  {"PARTITION_COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, 0},
5683
  {"NODEGROUP", 12 , MYSQL_TYPE_STRING, 0, 0, 0},
5684
  {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5685 5686 5687 5688
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5689
ST_FIELD_INFO variables_fields_info[]=
5690 5691
{
  {"VARIABLE_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Variable_name"},
5692
  {"VARIABLE_VALUE", 20480, MYSQL_TYPE_STRING, 0, 1, "Value"},
5693 5694 5695 5696
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5697 5698
ST_FIELD_INFO processlist_fields_info[]=
{
5699
  {"ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, "Id"},
5700 5701
  {"USER", 16, MYSQL_TYPE_STRING, 0, 0, "User"},
  {"HOST", LIST_PROCESS_HOST_LEN,  MYSQL_TYPE_STRING, 0, 0, "Host"},
5702
  {"DB", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Db"},
5703
  {"COMMAND", 16, MYSQL_TYPE_STRING, 0, 0, "Command"},
5704
  {"TIME", 7, MYSQL_TYPE_LONGLONG, 0, 0, "Time"},
5705
  {"STATE", 64, MYSQL_TYPE_STRING, 0, 1, "State"},
5706
  {"INFO", PROCESS_LIST_INFO_WIDTH, MYSQL_TYPE_STRING, 0, 1, "Info"},
5707 5708 5709 5710
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5711 5712
ST_FIELD_INFO plugin_fields_info[]=
{
5713
  {"PLUGIN_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, "Name"},
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
5714
  {"PLUGIN_VERSION", 20, MYSQL_TYPE_STRING, 0, 0, 0},
5715
  {"PLUGIN_STATUS", 10, MYSQL_TYPE_STRING, 0, 0, "Status"},
5716
  {"PLUGIN_TYPE", 80, MYSQL_TYPE_STRING, 0, 0, "Type"},
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
5717
  {"PLUGIN_TYPE_VERSION", 20, MYSQL_TYPE_STRING, 0, 0, 0},
5718
  {"PLUGIN_LIBRARY", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, "Library"},
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
5719
  {"PLUGIN_LIBRARY_VERSION", 20, MYSQL_TYPE_STRING, 0, 1, 0},
5720
  {"PLUGIN_AUTHOR", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5721
  {"PLUGIN_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0},
5722
  {"PLUGIN_LICENSE", 80, MYSQL_TYPE_STRING, 0, 1, "License"},
5723 5724 5725
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};

5726 5727
ST_FIELD_INFO files_fields_info[]=
{
5728
  {"FILE_ID", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0},
5729
  {"FILE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5730
  {"FILE_TYPE", 20, MYSQL_TYPE_STRING, 0, 0, 0},
5731 5732 5733 5734 5735
  {"TABLESPACE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_CATALOG", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"LOGFILE_GROUP_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5736
  {"LOGFILE_GROUP_NUMBER", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
5737 5738
  {"ENGINE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"FULLTEXT_KEYS", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756
  {"DELETED_ROWS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
  {"UPDATE_COUNT", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
  {"FREE_EXTENTS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
  {"TOTAL_EXTENTS", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
  {"EXTENT_SIZE", 4, MYSQL_TYPE_LONGLONG, 0, 0, 0},
  {"INITIAL_SIZE", 21, MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"MAXIMUM_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"AUTOEXTEND_SIZE", 21, MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), 0},
  {"CREATION_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
  {"LAST_UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
  {"LAST_ACCESS_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, 0},
  {"RECOVER_TIME", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
  {"TRANSACTION_COUNTER", 4, MYSQL_TYPE_LONGLONG, 0, 1, 0},
  {"VERSION", 21 , MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Version"},
5757
  {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format"},
5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774
  {"TABLE_ROWS", 21 , MYSQL_TYPE_LONGLONG, 0,
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Rows"},
  {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Avg_row_length"},
  {"DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_length"},
  {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Max_data_length"},
  {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Index_length"},
  {"DATA_FREE", 21 , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Data_free"},
  {"CREATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Create_time"},
  {"UPDATE_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Update_time"},
  {"CHECK_TIME", 0, MYSQL_TYPE_DATETIME, 0, 1, "Check_time"},
  {"CHECKSUM", 21 , MYSQL_TYPE_LONGLONG, 0, 
   (MY_I_S_MAYBE_NULL | MY_I_S_UNSIGNED), "Checksum"},
5775
  {"STATUS", 20, MYSQL_TYPE_STRING, 0, 0, 0},
5776
  {"EXTRA", 255, MYSQL_TYPE_STRING, 0, 1, 0},
5777 5778
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};
5779

5780 5781 5782 5783 5784 5785 5786 5787 5788 5789
void init_fill_schema_files_row(TABLE* table)
{
  int i;
  for(i=0; files_fields_info[i].field_name!=NULL; i++)
    table->field[i]->set_null();

  table->field[IS_FILES_STATUS]->set_notnull();
  table->field[IS_FILES_STATUS]->store("NORMAL", 6, system_charset_info);
}

5790 5791 5792
ST_FIELD_INFO referential_constraints_fields_info[]=
{
  {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5793 5794
  {"CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5795
  {"UNIQUE_CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
5796 5797 5798 5799 5800 5801 5802
  {"UNIQUE_CONSTRAINT_SCHEMA", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"UNIQUE_CONSTRAINT_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"MATCH_OPTION", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"UPDATE_RULE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"DELETE_RULE", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"REFERENCED_TABLE_NAME", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
5803 5804 5805 5806
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


5807 5808
/*
  Description of ST_FIELD_INFO in table.h
5809 5810 5811

  Make sure that the order of schema_tables and enum_schema_tables are the same.

5812 5813 5814 5815 5816
*/

ST_SCHEMA_TABLE schema_tables[]=
{
  {"CHARACTER_SETS", charsets_fields_info, create_schema_table, 
5817
   fill_schema_charsets, make_character_sets_old_format, 0, -1, -1, 0},
5818
  {"COLLATIONS", collation_fields_info, create_schema_table, 
5819
   fill_schema_collation, make_old_format, 0, -1, -1, 0},
5820
  {"COLLATION_CHARACTER_SET_APPLICABILITY", coll_charset_app_fields_info,
5821
   create_schema_table, fill_schema_coll_charset_app, 0, 0, -1, -1, 0},
5822 5823
  {"COLUMNS", columns_fields_info, create_schema_table, 
   get_all_tables, make_columns_old_format, get_schema_column_record, 1, 2, 0},
5824
  {"COLUMN_PRIVILEGES", column_privileges_fields_info, create_schema_table,
5825
    fill_schema_column_privileges, 0, 0, -1, -1, 0},
5826
  {"ENGINES", engines_fields_info, create_schema_table,
5827
   fill_schema_engines, make_old_format, 0, -1, -1, 0},
5828
  {"EVENTS", events_fields_info, create_schema_table,
5829
   Events::fill_schema_events, make_old_format, 0, -1, -1, 0},
5830 5831
  {"FILES", files_fields_info, create_schema_table,
   fill_schema_files, 0, 0, -1, -1, 0},
5832 5833 5834 5835
  {"GLOBAL_STATUS", variables_fields_info, create_schema_table,
   fill_status, make_old_format, 0, -1, -1, 0},
  {"GLOBAL_VARIABLES", variables_fields_info, create_schema_table,
   fill_variables, make_old_format, 0, -1, -1, 0},
5836
  {"KEY_COLUMN_USAGE", key_column_usage_fields_info, create_schema_table,
5837
    get_all_tables, 0, get_schema_key_column_usage_record, 4, 5, 0},
5838 5839
  {"OPEN_TABLES", open_tables_fields_info, create_schema_table,
   fill_open_tables, make_old_format, 0, -1, -1, 1},
5840 5841
  {"PARTITIONS", partitions_fields_info, create_schema_table,
   get_all_tables, 0, get_schema_partitions_record, 1, 2, 0},
5842 5843
  {"PLUGINS", plugin_fields_info, create_schema_table,
    fill_plugins, make_old_format, 0, -1, -1, 0},
5844 5845
  {"PROCESSLIST", processlist_fields_info, create_schema_table,
    fill_schema_processlist, make_old_format, 0, -1, -1, 0},
5846 5847 5848
  {"REFERENTIAL_CONSTRAINTS", referential_constraints_fields_info,
   create_schema_table, get_all_tables, 0, get_referential_constraints_record,
   1, 9, 0},
5849 5850 5851 5852 5853 5854
  {"ROUTINES", proc_fields_info, create_schema_table, 
    fill_schema_proc, make_proc_old_format, 0, -1, -1, 0},
  {"SCHEMATA", schema_fields_info, create_schema_table,
   fill_schema_shemata, make_schemata_old_format, 0, 1, -1, 0},
  {"SCHEMA_PRIVILEGES", schema_privileges_fields_info, create_schema_table,
    fill_schema_schema_privileges, 0, 0, -1, -1, 0},
5855 5856 5857 5858
  {"SESSION_STATUS", variables_fields_info, create_schema_table,
    fill_status, make_old_format, 0, -1, -1, 0},
  {"SESSION_VARIABLES", variables_fields_info, create_schema_table,
    fill_variables, make_old_format, 0, -1, -1, 0},
5859 5860
  {"STATISTICS", stat_fields_info, create_schema_table, 
    get_all_tables, make_old_format, get_schema_stat_record, 1, 2, 0},
5861 5862
  {"STATUS", variables_fields_info, create_schema_table, fill_status, 
   make_old_format, 0, -1, -1, 1},
5863 5864 5865 5866 5867 5868 5869 5870
  {"TABLES", tables_fields_info, create_schema_table, 
   get_all_tables, make_old_format, get_schema_tables_record, 1, 2, 0},
  {"TABLE_CONSTRAINTS", table_constraints_fields_info, create_schema_table,
    get_all_tables, 0, get_schema_constraints_record, 3, 4, 0},
  {"TABLE_NAMES", table_names_fields_info, create_schema_table,
   get_all_tables, make_table_names_old_format, 0, 1, 2, 1},
  {"TABLE_PRIVILEGES", table_privileges_fields_info, create_schema_table,
    fill_schema_table_privileges, 0, 0, -1, -1, 0},
5871
  {"TRIGGERS", triggers_fields_info, create_schema_table,
5872
   get_all_tables, make_old_format, get_schema_triggers_record, 5, 6, 0},
5873 5874
  {"USER_PRIVILEGES", user_privileges_fields_info, create_schema_table, 
    fill_schema_user_privileges, 0, 0, -1, -1, 0},
5875 5876
  {"VARIABLES", variables_fields_info, create_schema_table, fill_variables,
   make_old_format, 0, -1, -1, 1},
5877 5878
  {"VIEWS", view_fields_info, create_schema_table, 
    get_all_tables, 0, get_schema_views_record, 1, 2, 0},
5879
  {0, 0, 0, 0, 0, 0, 0, 0, 0}
5880 5881 5882
};


5883
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5884
template class List_iterator_fast<char>;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5885 5886
template class List<char>;
#endif
brian@zim.(none)'s avatar
brian@zim.(none) committed
5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903

int initialize_schema_table(st_plugin_int *plugin)
{
  ST_SCHEMA_TABLE *schema_table;
  DBUG_ENTER("initialize_schema_table");

  if (!(schema_table= (ST_SCHEMA_TABLE *)my_malloc(sizeof(ST_SCHEMA_TABLE),
                                MYF(MY_WME | MY_ZEROFILL))))
      DBUG_RETURN(1);
  /* Historical Requirement */
  plugin->data= schema_table; // shortcut for the future
  if (plugin->plugin->init)
  {
    schema_table->create_table= create_schema_table;
    schema_table->old_format= make_old_format;
    schema_table->idx_field1= -1, 
    schema_table->idx_field2= -1; 
5904 5905

    /* Make the name available to the init() function. */
5906
    schema_table->table_name= plugin->name.str;
brian@zim.(none)'s avatar
brian@zim.(none) committed
5907 5908 5909 5910 5911 5912 5913

    if (plugin->plugin->init(schema_table))
    {
      sql_print_error("Plugin '%s' init function returned error.",
                      plugin->name.str);
      goto err;
    }
5914 5915 5916
    
    /* Make sure the plugin name is not set inside the init() function. */
    schema_table->table_name= plugin->name.str;
brian@zim.(none)'s avatar
brian@zim.(none) committed
5917 5918 5919 5920
  }

  DBUG_RETURN(0);
err:
5921
  my_free(schema_table, MYF(0));
brian@zim.(none)'s avatar
brian@zim.(none) committed
5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937
  DBUG_RETURN(1);
}

int finalize_schema_table(st_plugin_int *plugin)
{
  ST_SCHEMA_TABLE *schema_table= (ST_SCHEMA_TABLE *)plugin->data;
  DBUG_ENTER("finalize_schema_table");

  if (schema_table && plugin->plugin->deinit)
  {
    DBUG_PRINT("info", ("Deinitializing plugin: '%s'", plugin->name.str));
    if (plugin->plugin->deinit(NULL))
    {
      DBUG_PRINT("warning", ("Plugin '%s' deinit function returned error.",
                             plugin->name.str));
    }
5938
    my_free(schema_table, MYF(0));
brian@zim.(none)'s avatar
brian@zim.(none) committed
5939 5940 5941
  }
  DBUG_RETURN(0);
}
5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972


/**
  Output trigger information (SHOW CREATE TRIGGER) to the client.

  @param thd          Thread context.
  @param triggers     List of triggers for the table.
  @param trigger_idx  Index of the trigger to dump.

  @return Operation status
    @retval TRUE Error.
    @retval FALSE Success.
*/

static bool show_create_trigger_impl(THD *thd,
                                     Table_triggers_list *triggers,
                                     int trigger_idx)
{
  int ret_code;

  Protocol *p= thd->protocol;
  List<Item> fields;

  LEX_STRING trg_name;
  ulonglong trg_sql_mode;
  LEX_STRING trg_sql_mode_str;
  LEX_STRING trg_sql_original_stmt;
  LEX_STRING trg_client_cs_name;
  LEX_STRING trg_connection_cl_name;
  LEX_STRING trg_db_cl_name;

5973 5974
  CHARSET_INFO *trg_client_cs;

5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999
  /*
    TODO: Check privileges here. This functionality will be added by
    implementation of the following WL items:
      - WL#2227: New privileges for new objects
      - WL#3482: Protect SHOW CREATE PROCEDURE | FUNCTION | VIEW | TRIGGER
        properly

    SHOW TRIGGERS and I_S.TRIGGERS will be affected too.
  */

  /* Prepare trigger "object". */

  triggers->get_trigger_info(thd,
                             trigger_idx,
                             &trg_name,
                             &trg_sql_mode,
                             &trg_sql_original_stmt,
                             &trg_client_cs_name,
                             &trg_connection_cl_name,
                             &trg_db_cl_name);

  sys_var_thd_sql_mode::symbolic_mode_representation(thd,
                                                     trg_sql_mode,
                                                     &trg_sql_mode_str);

6000 6001 6002 6003 6004
  /* Resolve trigger client character set. */

  if (resolve_charset(trg_client_cs_name.str, NULL, &trg_client_cs))
    return TRUE;

6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050
  /* Send header. */

  fields.push_back(new Item_empty_string("Trigger", NAME_LEN));
  fields.push_back(new Item_empty_string("sql_mode", trg_sql_mode_str.length));

  {
    /*
      NOTE: SQL statement field must be not less than 1024 in order not to
      confuse old clients.
    */

    Item_empty_string *stmt_fld=
      new Item_empty_string("SQL Original Statement",
                            max(trg_sql_original_stmt.length, 1024));

    stmt_fld->maybe_null= TRUE;

    fields.push_back(stmt_fld);
  }

  fields.push_back(new Item_empty_string("character_set_client",
                                         MY_CS_NAME_SIZE));

  fields.push_back(new Item_empty_string("collation_connection",
                                         MY_CS_NAME_SIZE));

  fields.push_back(new Item_empty_string("Database Collation",
                                         MY_CS_NAME_SIZE));

  if (p->send_fields(&fields, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
    return TRUE;

  /* Send data. */

  p->prepare_for_resend();

  p->store(trg_name.str,
           trg_name.length,
           system_charset_info);

  p->store(trg_sql_mode_str.str,
           trg_sql_mode_str.length,
           system_charset_info);

  p->store(trg_sql_original_stmt.str,
           trg_sql_original_stmt.length,
6051
           trg_client_cs);
6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239

  p->store(trg_client_cs_name.str,
           trg_client_cs_name.length,
           system_charset_info);

  p->store(trg_connection_cl_name.str,
           trg_connection_cl_name.length,
           system_charset_info);

  p->store(trg_db_cl_name.str,
           trg_db_cl_name.length,
           system_charset_info);

  ret_code= p->write();

  if (!ret_code)
    send_eof(thd);

  return ret_code != 0;
}


/**
  Read TRN and TRG files to obtain base table name for the specified
  trigger name and construct TABE_LIST object for the base table.

  @param thd      Thread context.
  @param trg_name Trigger name.

  @return TABLE_LIST object corresponding to the base table.

  TODO: This function is a copy&paste from add_table_to_list() and
  sp_add_to_query_tables(). The problem is that in order to be compatible
  with Stored Programs (Prepared Statements), we should not touch thd->lex.
  The "source" functions also add created TABLE_LIST object to the
  thd->lex->query_tables.

  The plan to eliminate this copy&paste is to:

    - get rid of sp_add_to_query_tables() and use Lex::add_table_to_list().
      Only add_table_to_list() must be used to add tables from the parser
      into Lex::query_tables list.

    - do not update Lex::query_tables in add_table_to_list().
*/

static TABLE_LIST *get_trigger_table_impl(
  THD *thd,
  const sp_name *trg_name)
{
  char trn_path_buff[FN_REFLEN];

  LEX_STRING trn_path= { trn_path_buff, 0 };
  LEX_STRING tbl_name;

  build_trn_path(thd, trg_name, &trn_path);

  if (check_trn_exists(&trn_path))
  {
    my_error(ER_TRG_DOES_NOT_EXIST, MYF(0));
    return NULL;
  }

  if (load_table_name_for_trigger(thd, trg_name, &trn_path, &tbl_name))
    return NULL;

  /* We need to reset statement table list to be PS/SP friendly. */

  TABLE_LIST *table;

  if (!(table= (TABLE_LIST *)thd->calloc(sizeof(TABLE_LIST))))
  {
    my_error(ER_OUTOFMEMORY, MYF(0), sizeof(TABLE_LIST));
    return NULL;
  }

  table->db_length= trg_name->m_db.length;
  table->db= thd->strmake(trg_name->m_db.str, trg_name->m_db.length);

  table->table_name_length= tbl_name.length;
  table->table_name= thd->strmake(tbl_name.str, tbl_name.length);

  table->alias= thd->strmake(tbl_name.str, tbl_name.length);

  table->lock_type= TL_IGNORE;
  table->cacheable_table= 0;

  return table;
}

/**
  Read TRN and TRG files to obtain base table name for the specified
  trigger name and construct TABE_LIST object for the base table. Acquire
  LOCK_open when doing this.

  @param thd      Thread context.
  @param trg_name Trigger name.

  @return TABLE_LIST object corresponding to the base table.
*/

static TABLE_LIST *get_trigger_table(THD *thd, const sp_name *trg_name)
{
  /* Acquire LOCK_open (stop the server). */

  pthread_mutex_lock(&LOCK_open);

  /*
    Load base table name from the TRN-file and create TABLE_LIST object.
  */

  TABLE_LIST *lst= get_trigger_table_impl(thd, trg_name);

  /* Release LOCK_open (continue the server). */

  pthread_mutex_unlock(&LOCK_open);

  /* That's it. */

  return lst;
}


/**
  SHOW CREATE TRIGGER high-level implementation.

  @param thd      Thread context.
  @param trg_name Trigger name.

  @return Operation status
    @retval TRUE Error.
    @retval FALSE Success.
*/

bool show_create_trigger(THD *thd, const sp_name *trg_name)
{
  TABLE_LIST *lst= get_trigger_table(thd, trg_name);

  /*
    Open the table by name in order to load Table_triggers_list object.

    NOTE: there is race condition here -- the table can be dropped after
    LOCK_open is released. It will be fixed later by introducing
    acquire-shared-table-name-lock functionality.
  */

  uint num_tables; /* NOTE: unused, only to pass to open_tables(). */

  if (open_tables(thd, &lst, &num_tables, 0))
  {
    my_error(ER_TRG_CANT_OPEN_TABLE, MYF(0),
             (const char *) trg_name->m_db.str,
             (const char *) lst->table_name);

    return TRUE;

    /* Perform closing actions and return error status. */
  }

  DBUG_ASSERT(num_tables == 1);

  Table_triggers_list *triggers= lst->table->triggers;

  if (!triggers)
  {
    my_error(ER_TRG_DOES_NOT_EXIST, MYF(0));
    return TRUE;
  }

  int trigger_idx= triggers->find_trigger_by_name(&trg_name->m_name);

  if (trigger_idx < 0)
  {
    my_error(ER_TRG_CORRUPTED_FILE, MYF(0),
             (const char *) trg_name->m_db.str,
             (const char *) lst->table_name);

    return TRUE;
  }

  return show_create_trigger_impl(thd, triggers, trigger_idx);

  /*
    NOTE: if show_create_trigger_impl() failed, that means we could not
    send data to the client. In this case we simply raise the error
    status and client connection will be closed.
  */
}