sql_show.cc 136 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2004 MySQL AB
2

unknown's avatar
unknown committed
3 4 5 6
   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
7

unknown's avatar
unknown committed
8 9 10 11
   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.
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20
   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"
21
#include "sql_select.h"                         // For select_describe
22
#include "repl_failsafe.h"
23
#include "sp.h"
24
#include "sp_head.h"
25
#include "sql_trigger.h"
unknown's avatar
unknown committed
26
#include <my_dir.h>
unknown's avatar
unknown committed
27

unknown's avatar
unknown committed
28 29 30 31
#ifdef HAVE_BERKELEY_DB
#include "ha_berkeley.h"			// For berkeley_show_logs
#endif

unknown's avatar
unknown committed
32 33 34 35
static const char *grant_names[]={
  "select","insert","update","delete","create","drop","reload","shutdown",
  "process","file","grant","references","index","alter"};

unknown's avatar
unknown committed
36
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
37
static TYPELIB grant_types = { sizeof(grant_names)/sizeof(char **),
38
                               "grant_types",
39
                               grant_names, NULL};
unknown's avatar
unknown committed
40
#endif
unknown's avatar
unknown committed
41 42

static int
unknown's avatar
unknown committed
43
store_create_info(THD *thd, TABLE_LIST *table_list, String *packet);
unknown's avatar
VIEW  
unknown committed
44
static int
45
view_store_create_info(THD *thd, TABLE_LIST *table, String *buff);
46
static bool schema_table_store_record(THD *thd, TABLE *table);
47

unknown's avatar
unknown committed
48

unknown's avatar
unknown committed
49 50 51 52
/***************************************************************************
** List all table types supported 
***************************************************************************/

unknown's avatar
unknown committed
53
bool mysqld_show_storage_engines(THD *thd)
unknown's avatar
unknown committed
54 55
{
  List<Item> field_list;
56
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
57
  DBUG_ENTER("mysqld_show_storage_engines");
unknown's avatar
unknown committed
58

unknown's avatar
unknown committed
59
  field_list.push_back(new Item_empty_string("Engine",10));
unknown's avatar
unknown committed
60
  field_list.push_back(new Item_empty_string("Support",10));
61
  field_list.push_back(new Item_empty_string("Comment",80));
unknown's avatar
unknown committed
62

63 64
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
65
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
66

67
  const char *default_type_name= 
unknown's avatar
unknown committed
68
    ha_get_storage_engine((enum db_type)thd->variables.table_type);
unknown's avatar
unknown committed
69

70 71
  handlerton **types;
  for (types= sys_table_types; *types; types++)
unknown's avatar
unknown committed
72
  {
73
    protocol->prepare_for_resend();
74 75
    protocol->store((*types)->name, system_charset_info);
    const char *option_name= show_comp_option_name[(int) (*types)->state];
76

77 78
    if ((*types)->state == SHOW_OPTION_YES &&
	!my_strcasecmp(system_charset_info, default_type_name, (*types)->name))
79
      option_name= "DEFAULT";
80
    protocol->store(option_name, system_charset_info);
81
    protocol->store((*types)->comment, system_charset_info);
82
    if (protocol->write())
unknown's avatar
unknown committed
83
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
84
  }
85
  send_eof(thd);
unknown's avatar
unknown committed
86
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
87 88
}

89

unknown's avatar
unknown committed
90
/***************************************************************************
91
 List all privileges supported
unknown's avatar
unknown committed
92 93
***************************************************************************/

94 95 96 97
struct show_privileges_st {
  const char *privilege;
  const char *context;
  const char *comment;
unknown's avatar
unknown committed
98 99
};

100 101
static struct show_privileges_st sys_privileges[]=
{
unknown's avatar
unknown committed
102
  {"Alter", "Tables",  "To alter the table"},
103
  {"Alter routine", "Functions,Procedures",  "To alter or drop stored functions/procedures"},
104
  {"Create", "Databases,Tables,Indexes",  "To create new databases and tables"},
105
  {"Create routine","Functions,Procedures","To use CREATE FUNCTION/PROCEDURE"},
unknown's avatar
unknown committed
106 107
  {"Create temporary tables","Databases","To use CREATE TEMPORARY TABLE"},
  {"Create view", "Tables",  "To create new views"},
108
  {"Create user", "Server Admin",  "To create new users"},
unknown's avatar
unknown committed
109
  {"Delete", "Tables",  "To delete existing rows"},
unknown's avatar
unknown committed
110
  {"Drop", "Databases,Tables", "To drop databases, tables, and views"},
111
  {"Execute", "Functions,Procedures", "To execute stored routines"},
unknown's avatar
unknown committed
112
  {"File", "File access on server",   "To read and write files on the server"},
113
  {"Grant option",  "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"},
unknown's avatar
unknown committed
114 115 116 117
  {"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"},
118
  {"References", "Databases,Tables", "To have references on tables"},
unknown's avatar
unknown committed
119 120 121 122 123
  {"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"},
unknown's avatar
unknown committed
124 125
  {"Show view","Tables","To see views with SHOW CREATE VIEW"},
  {"Shutdown","Server Admin", "To shut down the server"},
unknown's avatar
unknown committed
126 127 128
  {"Super","Server Admin","To use KILL thread, SET GLOBAL, CHANGE MASTER, etc."},
  {"Update", "Tables",  "To update existing rows"},
  {"Usage","Server Admin","No privileges - allow connect only"},
129 130 131
  {NullS, NullS, NullS}
};

unknown's avatar
unknown committed
132
bool mysqld_show_privileges(THD *thd)
unknown's avatar
unknown committed
133 134
{
  List<Item> field_list;
135
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
136 137 138 139 140 141
  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));
  field_list.push_back(new Item_empty_string("Comment",NAME_LEN));

142 143
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
144
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
145

146 147
  show_privileges_st *privilege= sys_privileges;
  for (privilege= sys_privileges; privilege->privilege ; privilege++)
unknown's avatar
unknown committed
148
  {
149
    protocol->prepare_for_resend();
150 151 152
    protocol->store(privilege->privilege, system_charset_info);
    protocol->store(privilege->context, system_charset_info);
    protocol->store(privilege->comment, system_charset_info);
153
    if (protocol->write())
unknown's avatar
unknown committed
154
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
155
  }
156
  send_eof(thd);
unknown's avatar
unknown committed
157
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
158 159 160 161
}


/***************************************************************************
162
  List all column types
unknown's avatar
unknown committed
163 164
***************************************************************************/

165 166
struct show_column_type_st
{
unknown's avatar
unknown committed
167 168
  const char *type;
  uint size;
169 170 171 172 173 174 175 176 177 178 179 180
  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;
unknown's avatar
unknown committed
181
};
182 183 184 185 186

/* TODO: Add remaning types */

static struct show_column_type_st sys_column_types[]=
{
unknown's avatar
unknown committed
187 188
  {"tinyint",
    1,  "-128",  "127",  0,  0,  "YES",  "YES",
unknown's avatar
unknown committed
189 190
    "NO",   "YES", "YES",  "NO",  "NULL,0",
    "A very small integer"},
unknown's avatar
unknown committed
191
  {"tinyint unsigned",
unknown's avatar
unknown committed
192 193
    1,  "0"   ,  "255",  0,  0,  "YES",  "YES",
    "YES",  "YES",  "YES",  "NO",  "NULL,0",
unknown's avatar
unknown committed
194 195 196
    "A very small integer"},
};

unknown's avatar
unknown committed
197
bool mysqld_show_column_types(THD *thd)
unknown's avatar
unknown committed
198 199
{
  List<Item> field_list;
200
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
201 202 203 204 205 206
  DBUG_ENTER("mysqld_show_column_types");

  field_list.push_back(new Item_empty_string("Type",30));
  field_list.push_back(new Item_int("Size",(longlong) 1,21));
  field_list.push_back(new Item_empty_string("Min_Value",20));
  field_list.push_back(new Item_empty_string("Max_Value",20));
207 208
  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));
unknown's avatar
unknown committed
209 210 211 212 213 214 215 216 217
  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));
  field_list.push_back(new Item_empty_string("Default",NAME_LEN));
  field_list.push_back(new Item_empty_string("Comment",NAME_LEN));

218 219
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
220
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
221

222
  /* TODO: Change the loop to not use 'i' */
unknown's avatar
unknown committed
223 224
  for (uint i=0; i < sizeof(sys_column_types)/sizeof(sys_column_types[0]); i++)
  {
225
    protocol->prepare_for_resend();
226
    protocol->store(sys_column_types[i].type, system_charset_info);
227
    protocol->store((ulonglong) sys_column_types[i].size);
228 229
    protocol->store(sys_column_types[i].min_value, system_charset_info);
    protocol->store(sys_column_types[i].max_value, system_charset_info);
230 231
    protocol->store_short((longlong) sys_column_types[i].precision);
    protocol->store_short((longlong) sys_column_types[i].scale);
232 233 234 235 236 237 238 239
    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);
240
    if (protocol->write())
unknown's avatar
unknown committed
241
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
242
  }
243
  send_eof(thd);
unknown's avatar
unknown committed
244
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
245 246 247
}


248
int
unknown's avatar
unknown committed
249
mysql_find_files(THD *thd,List<char> *files, const char *db,const char *path,
250
                 const char *wild, bool dir)
unknown's avatar
unknown committed
251 252 253 254 255
{
  uint i;
  char *ext;
  MY_DIR *dirp;
  FILEINFO *file;
unknown's avatar
unknown committed
256
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
257
  uint col_access=thd->col_access;
unknown's avatar
unknown committed
258
#endif
unknown's avatar
unknown committed
259 260 261
  TABLE_LIST table_list;
  DBUG_ENTER("mysql_find_files");

262 263
  if (wild && !wild[0])
    wild=0;
264

unknown's avatar
unknown committed
265 266
  bzero((char*) &table_list,sizeof(table_list));

267 268 269 270 271 272
  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);
unknown's avatar
unknown committed
273
    DBUG_RETURN(-1);
274
  }
unknown's avatar
unknown committed
275

276
  for (i=0 ; i < (uint) dirp->number_off_files  ; i++)
unknown's avatar
unknown committed
277 278 279
  {
    file=dirp->dir_entry+i;
    if (dir)
280
    {                                           /* Return databases */
unknown's avatar
unknown committed
281 282
#ifdef USE_SYMDIR
      char *ext;
283
      char buff[FN_REFLEN];
unknown's avatar
unknown committed
284
      if (my_use_symdir && !strcmp(ext=fn_ext(file->name), ".sym"))
285 286
      {
	/* Only show the sym file if it points to a directory */
287
	char *end;
288
        *ext=0;                                 /* Remove extension */
289 290 291 292
	unpack_dirname(buff, file->name);
	end= strend(buff);
	if (end != buff && end[-1] == FN_LIBCHAR)
	  end[-1]= 0;				// Remove end FN_LIBCHAR
293 294 295
        if (!my_stat(buff, file->mystat, MYF(0)))
               continue;
       }
unknown's avatar
unknown committed
296
#endif
unknown's avatar
unknown committed
297
        if (file->name[0] == '.' || !MY_S_ISDIR(file->mystat->st_mode) ||
298
            (wild && wild_compare(file->name,wild,0)))
299
          continue;
unknown's avatar
unknown committed
300 301 302
    }
    else
    {
303
        // Return only .frm files which aren't temp files.
304
      if (my_strcasecmp(system_charset_info, ext=fn_ext(file->name),reg_ext) ||
305
          is_prefix(file->name,tmp_file_prefix))
306
        continue;
unknown's avatar
unknown committed
307
      *ext=0;
308 309 310 311
      if (wild)
      {
	if (lower_case_table_names)
	{
312
	  if (wild_case_compare(files_charset_info, file->name, wild))
313 314
	    continue;
	}
315
	else if (wild_compare(file->name,wild,0))
316 317
	  continue;
      }
unknown's avatar
unknown committed
318
    }
unknown's avatar
unknown committed
319
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
320 321 322 323
    /* Don't show tables where we don't have any privileges */
    if (db && !(col_access & TABLE_ACLS))
    {
      table_list.db= (char*) db;
324
      table_list.db_length= strlen(db);
325
      table_list.table_name= file->name;
326
      table_list.table_name_length= strlen(file->name);
unknown's avatar
unknown committed
327
      table_list.grant.privilege=col_access;
unknown's avatar
unknown committed
328
      if (check_grant(thd, TABLE_ACLS, &table_list, 1, UINT_MAX, 1))
329
        continue;
unknown's avatar
unknown committed
330
    }
unknown's avatar
unknown committed
331
#endif
332
    if (files->push_back(thd->strdup(file->name)))
unknown's avatar
unknown committed
333 334 335 336 337 338 339
    {
      my_dirend(dirp);
      DBUG_RETURN(-1);
    }
  }
  DBUG_PRINT("info",("found: %d files", files->elements));
  my_dirend(dirp);
unknown's avatar
unknown committed
340 341 342

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

unknown's avatar
unknown committed
343 344 345
  DBUG_RETURN(0);
}

346

unknown's avatar
unknown committed
347
bool
unknown's avatar
unknown committed
348 349
mysqld_show_create(THD *thd, TABLE_LIST *table_list)
{
350 351 352
  Protocol *protocol= thd->protocol;
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
353 354
  DBUG_ENTER("mysqld_show_create");
  DBUG_PRINT("enter",("db: %s  table: %s",table_list->db,
355
                      table_list->table_name));
unknown's avatar
unknown committed
356

357 358 359
  /* We want to preserve the tree for views. */
  thd->lex->view_prepare_mode= TRUE;

unknown's avatar
VIEW  
unknown committed
360
  /* Only one table for now, but VIEW can involve several tables */
361
  if (open_normal_and_derived_tables(thd, table_list, 0))
unknown's avatar
unknown committed
362
    DBUG_RETURN(TRUE);
363

unknown's avatar
VIEW  
unknown committed
364 365 366
  /* TODO: add environment variables show when it become possible */
  if (thd->lex->only_view && !table_list->view)
  {
367
    my_error(ER_WRONG_OBJECT, MYF(0),
368
             table_list->db, table_list->table_name, "VIEW");
unknown's avatar
unknown committed
369
    DBUG_RETURN(TRUE);
unknown's avatar
VIEW  
unknown committed
370
  }
unknown's avatar
unknown committed
371

372
  buffer.length(0);
unknown's avatar
VIEW  
unknown committed
373 374
  if ((table_list->view ?
       view_store_create_info(thd, table_list, &buffer) :
unknown's avatar
unknown committed
375
       store_create_info(thd, table_list, &buffer)))
unknown's avatar
unknown committed
376
    DBUG_RETURN(TRUE);
377

unknown's avatar
unknown committed
378
  List<Item> field_list;
unknown's avatar
unknown committed
379 380 381 382 383 384 385 386 387 388 389 390 391
  if (table_list->view)
  {
    field_list.push_back(new Item_empty_string("View",NAME_LEN));
    field_list.push_back(new Item_empty_string("Create View",
                                               max(buffer.length(),1024)));
  }
  else
  {
    field_list.push_back(new Item_empty_string("Table",NAME_LEN));
    // 1024 is for not to confuse old clients
    field_list.push_back(new Item_empty_string("Create Table",
                                               max(buffer.length(),1024)));
  }
unknown's avatar
unknown committed
392

393 394
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
395
    DBUG_RETURN(TRUE);
396
  protocol->prepare_for_resend();
unknown's avatar
VIEW  
unknown committed
397 398 399 400
  if (table_list->view)
    protocol->store(table_list->view_name.str, system_charset_info);
  else
  {
unknown's avatar
unknown committed
401
    if (table_list->schema_table)
402 403
      protocol->store(table_list->schema_table->table_name,
                      system_charset_info);
unknown's avatar
unknown committed
404
    else
405
      protocol->store(table_list->table->alias, system_charset_info);
unknown's avatar
VIEW  
unknown committed
406
  }
407
  protocol->store(buffer.ptr(), buffer.length(), buffer.charset());
unknown's avatar
VIEW  
unknown committed
408

409
  if (protocol->write())
unknown's avatar
unknown committed
410
    DBUG_RETURN(TRUE);
411
  send_eof(thd);
unknown's avatar
unknown committed
412
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
413 414
}

unknown's avatar
unknown committed
415 416
bool mysqld_show_create_db(THD *thd, char *dbname,
                           HA_CREATE_INFO *create_info)
417
{
418
  Security_context *sctx= thd->security_ctx;
419
  int length;
420
  char path[FN_REFLEN];
421 422
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
423
#ifndef NO_EMBEDDED_ACCESS_CHECKS
424
  uint db_access;
unknown's avatar
unknown committed
425
#endif
426 427 428 429 430 431 432 433
  bool found_libchar;
  HA_CREATE_INFO create;
  uint create_options = create_info ? create_info->options : 0;
  Protocol *protocol=thd->protocol;
  DBUG_ENTER("mysql_show_create_db");

  if (check_db_name(dbname))
  {
434
    my_error(ER_WRONG_DB_NAME, MYF(0), dbname);
unknown's avatar
unknown committed
435
    DBUG_RETURN(TRUE);
436 437 438
  }

#ifndef NO_EMBEDDED_ACCESS_CHECKS
439
  if (test_all_bits(sctx->master_access, DB_ACLS))
440 441
    db_access=DB_ACLS;
  else
442 443
    db_access= (acl_get(sctx->host, sctx->ip, sctx->priv_user, dbname, 0) |
		sctx->master_access);
444 445
  if (!(db_access & DB_ACLS) && (!grant_option || check_grant_db(thd,dbname)))
  {
446
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
447
             sctx->priv_user, sctx->host_or_ip, dbname);
448
    mysql_log.write(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR),
449
		    sctx->priv_user, sctx->host_or_ip, dbname);
unknown's avatar
unknown committed
450
    DBUG_RETURN(TRUE);
451 452
  }
#endif
453 454
  if (!my_strcasecmp(system_charset_info, dbname,
                     information_schema_name.str))
455
  {
456 457
    dbname= information_schema_name.str;
    create.default_table_charset= system_charset_info;
458
  }
459
  else
460
  {
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    (void) sprintf(path,"%s/%s",mysql_data_home, dbname);
    length=unpack_dirname(path,path);		// Convert if not unix
    found_libchar= 0;
    if (length && path[length-1] == FN_LIBCHAR)
    {
      found_libchar= 1;
      path[length-1]=0;				// remove ending '\'
    }
    if (access(path,F_OK))
    {
      my_error(ER_BAD_DB_ERROR, MYF(0), dbname);
      DBUG_RETURN(TRUE);
    }
    if (found_libchar)
      path[length-1]= FN_LIBCHAR;
    strmov(path+length, MY_DB_OPT_FILE);
    load_db_opt(thd, path, &create);
478 479 480 481 482
  }
  List<Item> field_list;
  field_list.push_back(new Item_empty_string("Database",NAME_LEN));
  field_list.push_back(new Item_empty_string("Create Database",1024));

483 484
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
485
    DBUG_RETURN(TRUE);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

  protocol->prepare_for_resend();
  protocol->store(dbname, strlen(dbname), system_charset_info);
  buffer.length(0);
  buffer.append("CREATE DATABASE ", 16);
  if (create_options & HA_LEX_CREATE_IF_NOT_EXISTS)
    buffer.append("/*!32312 IF NOT EXISTS*/ ", 25);
  append_identifier(thd, &buffer, dbname, strlen(dbname));

  if (create.default_table_charset)
  {
    buffer.append(" /*!40100", 9);
    buffer.append(" DEFAULT CHARACTER SET ", 23);
    buffer.append(create.default_table_charset->csname);
    if (!(create.default_table_charset->state & MY_CS_PRIMARY))
    {
      buffer.append(" COLLATE ", 9);
      buffer.append(create.default_table_charset->name);
    }
    buffer.append(" */", 3);
  }
  protocol->store(buffer.ptr(), buffer.length(), buffer.charset());

  if (protocol->write())
unknown's avatar
unknown committed
510
    DBUG_RETURN(TRUE);
511
  send_eof(thd);
unknown's avatar
unknown committed
512
  DBUG_RETURN(FALSE);
513
}
unknown's avatar
unknown committed
514

unknown's avatar
unknown committed
515
bool
unknown's avatar
unknown committed
516 517
mysqld_show_logs(THD *thd)
{
518 519
  List<Item> field_list;
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
520 521 522 523 524 525
  DBUG_ENTER("mysqld_show_logs");

  field_list.push_back(new Item_empty_string("File",FN_REFLEN));
  field_list.push_back(new Item_empty_string("Type",10));
  field_list.push_back(new Item_empty_string("Status",10));

526 527
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
528
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
529

530
#ifdef HAVE_BERKELEY_DB
531
  if ((have_berkeley_db == SHOW_OPTION_YES) && berkeley_show_logs(protocol))
unknown's avatar
unknown committed
532
    DBUG_RETURN(TRUE);
533
#endif
unknown's avatar
unknown committed
534

535
  send_eof(thd);
unknown's avatar
unknown committed
536
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
537 538 539
}


unknown's avatar
unknown committed
540
/****************************************************************************
541 542
  Return only fields for API mysql_list_fields
  Use "show table wildcard" in mysql instead of this
unknown's avatar
unknown committed
543 544 545 546 547 548 549
****************************************************************************/

void
mysqld_list_fields(THD *thd, TABLE_LIST *table_list, const char *wild)
{
  TABLE *table;
  DBUG_ENTER("mysqld_list_fields");
550
  DBUG_PRINT("enter",("table: %s",table_list->table_name));
unknown's avatar
unknown committed
551

552
  if (open_normal_and_derived_tables(thd, table_list, 0))
unknown's avatar
unknown committed
553
    DBUG_VOID_RETURN;
554 555
  table= table_list->table;

unknown's avatar
unknown committed
556 557 558 559 560
  List<Item> field_list;

  Field **ptr,*field;
  for (ptr=table->field ; (field= *ptr); ptr++)
  {
561 562
    if (!wild || !wild[0] || 
        !wild_case_compare(system_charset_info, field->field_name,wild))
unknown's avatar
unknown committed
563 564
      field_list.push_back(new Item_field(field));
  }
565
  restore_record(table, s->default_values);              // Get empty record
566 567
  if (thd->protocol->send_fields(&field_list, Protocol::SEND_DEFAULTS |
                                              Protocol::SEND_EOF))
unknown's avatar
unknown committed
568
    DBUG_VOID_RETURN;
569
  thd->protocol->flush();
unknown's avatar
unknown committed
570 571 572
  DBUG_VOID_RETURN;
}

573

unknown's avatar
unknown committed
574
int
unknown's avatar
unknown committed
575
mysqld_dump_create_info(THD *thd, TABLE_LIST *table_list, int fd)
unknown's avatar
unknown committed
576
{
577 578
  Protocol *protocol= thd->protocol;
  String *packet= protocol->storage_packet();
unknown's avatar
unknown committed
579
  DBUG_ENTER("mysqld_dump_create_info");
580
  DBUG_PRINT("enter",("table: %s",table_list->table->s->table_name));
581

582
  protocol->prepare_for_resend();
unknown's avatar
unknown committed
583
  if (store_create_info(thd, table_list, packet))
unknown's avatar
unknown committed
584
    DBUG_RETURN(-1);
585

586
  if (fd < 0)
587
  {
588
    if (protocol->write())
589
      DBUG_RETURN(-1);
590
    protocol->flush();
591
  }
unknown's avatar
unknown committed
592
  else
593
  {
594 595
    if (my_write(fd, (const byte*) packet->ptr(), packet->length(),
		 MYF(MY_WME)))
596 597
      DBUG_RETURN(-1);
  }
unknown's avatar
unknown committed
598 599
  DBUG_RETURN(0);
}
600

601
/*
602
  Go through all character combinations and ensure that sql_lex.cc can
603
  parse it as an identifier.
604 605

  SYNOPSIS
606 607 608 609 610 611 612
  require_quotes()
  name			attribute name
  name_length		length of name

  RETURN
    #	Pointer to conflicting character
    0	No conflicting character
613 614
*/

615
static const char *require_quotes(const char *name, uint name_length)
616
{
617 618 619
  uint length;
  const char *end= name + name_length;

620
  for (; name < end ; name++)
621
  {
622 623 624 625
    uchar chr= (uchar) *name;
    length= my_mbcharlen(system_charset_info, chr);
    if (length == 1 && !system_charset_info->ident_map[chr])
      return name;
626 627 628
  }
  return 0;
}
629

630

631 632
void
append_identifier(THD *thd, String *packet, const char *name, uint length)
633
{
634 635
  const char *name_end;
  char quote_char;
636
  int q= get_quote_char_for_identifier(thd, name, length);
637

638
  if (q == EOF)
639
  {
640
    packet->append(name, length, system_charset_info);
641 642 643
    return;
  }

644 645 646 647
  /*
    The identifier must be quoted as it includes a quote character or
   it's a keyword
  */
648 649

  packet->reserve(length*2 + 2);
650
  quote_char= (char) q;
651 652 653 654
  packet->append(&quote_char, 1, system_charset_info);

  for (name_end= name+length ; name < name_end ; name+= length)
  {
655
    uchar chr= (uchar) *name;
656
    length= my_mbcharlen(system_charset_info, chr);
657 658 659 660 661 662 663 664 665
    /*
      my_mbcharlen can retur 0 on a wrong multibyte
      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;
666
    if (length == 1 && chr == (uchar) quote_char)
667 668
      packet->append(&quote_char, 1, system_charset_info);
    packet->append(name, length, packet->charset());
669
  }
670
  packet->append(&quote_char, 1, system_charset_info);
671 672
}

673

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
/*
  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
    If name is a keyword or includes a special character, then force
    quoting.
    Otherwise identifier is quoted only if the option OPTION_QUOTE_SHOW_CREATE
    is set.

  RETURN
    EOF	  No quote character is needed
    #	  Quote character
*/
693 694 695 696 697 698 699

int get_quote_char_for_identifier(THD *thd, const char *name, uint length)
{
  if (!is_keyword(name,length) &&
      !require_quotes(name, length) &&
      !(thd->options & OPTION_QUOTE_SHOW_CREATE))
    return EOF;
700
  if (thd->variables.sql_mode & MODE_ANSI_QUOTES)
701
    return '"';
702
  return '`';
703 704 705
}


706 707 708 709 710
/* Append directory name (if exists) to CREATE INFO */

static void append_directory(THD *thd, String *packet, const char *dir_type,
			     const char *filename)
{
unknown's avatar
unknown committed
711
  if (filename && !(thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE))
712
  {
713
    uint length= dirname_length(filename);
714 715 716
    packet->append(' ');
    packet->append(dir_type);
    packet->append(" DIRECTORY='", 12);
717
#ifdef __WIN__
unknown's avatar
unknown committed
718 719 720 721 722 723 724 725 726
    /* 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;
727
#endif
unknown's avatar
unknown committed
728
    packet->append(filename, length);
729 730 731 732 733
    packet->append('\'');
  }
}


unknown's avatar
unknown committed
734
#define LIST_PROCESS_HOST_LEN 64
735

unknown's avatar
unknown committed
736
static int
unknown's avatar
unknown committed
737
store_create_info(THD *thd, TABLE_LIST *table_list, String *packet)
unknown's avatar
unknown committed
738
{
739
  List<Item> field_list;
740 741
  char tmp[MAX_FIELD_WIDTH], *for_str, buff[128], *end;
  const char *alias;
742
  String type(tmp, sizeof(tmp), system_charset_info);
743 744 745
  Field **ptr,*field;
  uint primary_key;
  KEY *key_info;
unknown's avatar
unknown committed
746
  TABLE *table= table_list->table;
747
  handler *file= table->file;
748
  TABLE_SHARE *share= table->s;
749
  HA_CREATE_INFO create_info;
750 751 752 753
  my_bool foreign_db_mode=    (thd->variables.sql_mode & (MODE_POSTGRESQL |
							  MODE_ORACLE |
							  MODE_MSSQL |
							  MODE_DB2 |
754
							  MODE_MAXDB |
755 756 757 758
							  MODE_ANSI)) != 0;
  my_bool limited_mysql_mode= (thd->variables.sql_mode &
			       (MODE_NO_FIELD_OPTIONS | MODE_MYSQL323 |
				MODE_MYSQL40)) != 0;
unknown's avatar
unknown committed
759
  DBUG_ENTER("store_create_info");
760
  DBUG_PRINT("enter",("table: %s", table->s->table_name));
unknown's avatar
unknown committed
761

762
  restore_record(table, s->default_values); // Get empty record
763

764
  if (share->tmp_table)
765 766 767
    packet->append("CREATE TEMPORARY TABLE ", 23);
  else
    packet->append("CREATE TABLE ", 13);
unknown's avatar
unknown committed
768
  if (table_list->schema_table)
769
    alias= table_list->schema_table->table_name;
unknown's avatar
unknown committed
770
  else
771 772
    alias= (lower_case_table_names == 2 ? table->alias :
            share->table_name);
unknown's avatar
unknown committed
773
  append_identifier(thd, packet, alias, strlen(alias));
774
  packet->append(" (\n", 3);
775

unknown's avatar
unknown committed
776 777
  for (ptr=table->field ; (field= *ptr); ptr++)
  {
778
    bool has_default;
779
    bool has_now_default;
780 781
    uint flags = field->flags;

782
    if (ptr != table->field)
783
      packet->append(",\n", 2);
784

785
    packet->append("  ", 2);
786
    append_identifier(thd,packet,field->field_name, strlen(field->field_name));
unknown's avatar
unknown committed
787 788
    packet->append(' ');
    // check for surprises from the previous call to Field::sql_type()
789
    if (type.ptr() != tmp)
790
      type.set(tmp, sizeof(tmp), system_charset_info);
unknown's avatar
unknown committed
791 792
    else
      type.set_charset(system_charset_info);
793

unknown's avatar
unknown committed
794
    field->sql_type(type);
795
    packet->append(type.ptr(), type.length(), system_charset_info);
796

797 798
    if (field->has_charset() && 
        !(thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)))
799
    {
800
      if (field->charset() != share->table_charset)
801
      {
802 803 804 805 806 807 808 809 810 811 812
	packet->append(" character set ", 15);
	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))
      {
	packet->append(" collate ", 9);
	packet->append(field->charset()->name);
813
      }
814
    }
815

816 817
    if (flags & NOT_NULL_FLAG)
      packet->append(" NOT NULL", 9);
818 819 820 821 822 823 824 825
    else if (field->type() == FIELD_TYPE_TIMESTAMP)
    {
      /*
        TIMESTAMP field require explicit NULL flag, because unlike
        all other fields they are treated as NOT NULL by default.
      */
      packet->append(" NULL", 5);
    }
826 827

    /* 
828
      Again we are using CURRENT_TIMESTAMP instead of NOW because it is
829 830 831 832 833
      more standard 
    */
    has_now_default= table->timestamp_field == field && 
                     field->unireg_check != Field::TIMESTAMP_UN_FIELD;
    
834
    has_default= (field->type() != FIELD_TYPE_BLOB &&
unknown's avatar
unknown committed
835
                  !(field->flags & NO_DEFAULT_VALUE_FLAG) &&
836
		  field->unireg_check != Field::NEXT_NUMBER &&
837
                  !((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
838
                    has_now_default));
839

840
    if (has_default)
841 842
    {
      packet->append(" default ", 9);
843 844 845
      if (has_now_default)
        packet->append("CURRENT_TIMESTAMP",17);
      else if (!field->is_null())
846
      {                                             // Not null by default
847
        type.set(tmp, sizeof(tmp), field->charset());
848
        field->val_str(&type);
849
	if (type.length())
850
	{
851
	  String def_val;
852
          uint dummy_errors;
853 854
	  /* convert to system_charset_info == utf8 */
	  def_val.copy(type.ptr(), type.length(), field->charset(),
855
		       system_charset_info, &dummy_errors);
856 857
          append_unescaped(packet, def_val.ptr(), def_val.length());
	}
858 859
        else
	  packet->append("''",2);
unknown's avatar
unknown committed
860
      }
861
      else if (field->maybe_null())
862 863
        packet->append("NULL", 4);                    // Null as default
      else
864
        packet->append(tmp);
865
    }
866

867
    if (!(thd->variables.sql_mode & MODE_NO_FIELD_OPTIONS) &&
868 869 870 871
        table->timestamp_field == field && 
        field->unireg_check != Field::TIMESTAMP_DN_FIELD)
      packet->append(" on update CURRENT_TIMESTAMP",28);

872 873
    if (field->unireg_check == Field::NEXT_NUMBER && 
        !(thd->variables.sql_mode & MODE_NO_FIELD_OPTIONS))
874 875 876 877 878 879 880
      packet->append(" auto_increment", 15 );

    if (field->comment.length)
    {
      packet->append(" COMMENT ",9);
      append_unescaped(packet, field->comment.str, field->comment.length);
    }
unknown's avatar
unknown committed
881 882
  }

883 884
  key_info= table->key_info;
  file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_TIME);
885
  bzero((char*) &create_info, sizeof(create_info));
886
  file->update_create_info(&create_info);
887
  primary_key= share->primary_key;
888

889
  for (uint i=0 ; i < share->keys ; i++,key_info++)
unknown's avatar
unknown committed
890
  {
891 892
    KEY_PART_INFO *key_part= key_info->key_part;
    bool found_primary=0;
893
    packet->append(",\n  ", 4);
894

895
    if (i == primary_key && !strcmp(key_info->name, primary_key_name))
896 897
    {
      found_primary=1;
898
      packet->append("PRIMARY ", 8);
899
    }
900
    else if (key_info->flags & HA_NOSAME)
901
      packet->append("UNIQUE ", 7);
902
    else if (key_info->flags & HA_FULLTEXT)
903
      packet->append("FULLTEXT ", 9);
unknown's avatar
unknown committed
904 905
    else if (key_info->flags & HA_SPATIAL)
      packet->append("SPATIAL ", 8);
906
    packet->append("KEY ", 4);
unknown's avatar
unknown committed
907

908
    if (!found_primary)
909
     append_identifier(thd, packet, key_info->name, strlen(key_info->name));
unknown's avatar
unknown committed
910

911 912 913
    if (!(thd->variables.sql_mode & MODE_NO_KEY_OPTIONS) &&
	!limited_mysql_mode && !foreign_db_mode)
    {
914
      if (key_info->algorithm == HA_KEY_ALG_BTREE)
unknown's avatar
Merge  
unknown committed
915 916
        packet->append(" USING BTREE", 12);

917
      if (key_info->algorithm == HA_KEY_ALG_HASH)
unknown's avatar
Merge  
unknown committed
918 919
        packet->append(" USING HASH", 11);

920 921 922
      // +BAR: send USING only in non-default case: non-spatial rtree
      if ((key_info->algorithm == HA_KEY_ALG_RTREE) &&
	  !(key_info->flags & HA_SPATIAL))
unknown's avatar
Merge  
unknown committed
923
        packet->append(" USING RTREE", 12);
924

unknown's avatar
Merge  
unknown committed
925
      // No need to send USING FULLTEXT, it is sent as FULLTEXT KEY
926
    }
927
    packet->append(" (", 2);
928

unknown's avatar
unknown committed
929 930
    for (uint j=0 ; j < key_info->key_parts ; j++,key_part++)
    {
931
      if (j)
932
        packet->append(',');
933

934
      if (key_part->field)
935 936
        append_identifier(thd,packet,key_part->field->field_name,
			  strlen(key_part->field->field_name));
unknown's avatar
unknown committed
937
      if (!key_part->field ||
938 939 940
          (key_part->length !=
           table->field[key_part->fieldnr-1]->key_length() &&
           !(key_info->flags & HA_FULLTEXT)))
unknown's avatar
unknown committed
941
      {
942
        buff[0] = '(';
943 944 945
        char* end=int10_to_str((long) key_part->length / 
			       key_part->field->charset()->mbmaxlen,
			       buff + 1,10);
946 947
        *end++ = ')';
        packet->append(buff,(uint) (end-buff));
unknown's avatar
unknown committed
948 949 950 951
      }
    }
    packet->append(')');
  }
952

953 954 955 956
  /*
    Get possible foreign key definitions stored in InnoDB and append them
    to the CREATE TABLE statement
  */
957

958
  if ((for_str= file->get_foreign_key_create_info()))
959 960 961
  {
    packet->append(for_str, strlen(for_str));
    file->free_foreign_key_create_info(for_str);
962 963 964
  }

  packet->append("\n)", 2);
965
  if (!(thd->variables.sql_mode & MODE_NO_TABLE_OPTIONS) && !foreign_db_mode)
966
  {
unknown's avatar
unknown committed
967 968 969 970
    if (thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40))
      packet->append(" TYPE=", 6);
    else
      packet->append(" ENGINE=", 8);
971 972
    packet->append(file->table_type());
    
973
    if (share->table_charset &&
974 975
	!(thd->variables.sql_mode & MODE_MYSQL323) &&
	!(thd->variables.sql_mode & MODE_MYSQL40))
976
    {
977
      packet->append(" DEFAULT CHARSET=", 17);
978 979
      packet->append(share->table_charset->csname);
      if (!(share->table_charset->state & MY_CS_PRIMARY))
980
      {
981
	packet->append(" COLLATE=", 9);
982
	packet->append(table->s->table_charset->name);
983
      }
984
    }
985

986
    if (share->min_rows)
987
    {
988
      packet->append(" MIN_ROWS=", 10);
989
      end= longlong10_to_str(share->min_rows, buff, 10);
unknown's avatar
unknown committed
990
      packet->append(buff, (uint) (end- buff));
991
    }
unknown's avatar
unknown committed
992

993
    if (share->max_rows && !table_list->schema_table)
994
    {
995
      packet->append(" MAX_ROWS=", 10);
996
      end= longlong10_to_str(share->max_rows, buff, 10);
unknown's avatar
unknown committed
997
      packet->append(buff, (uint) (end - buff));
998
    }
unknown's avatar
unknown committed
999

1000
    if (share->avg_row_length)
1001
    {
1002
      packet->append(" AVG_ROW_LENGTH=", 16);
1003
      end= longlong10_to_str(share->avg_row_length, buff,10);
unknown's avatar
unknown committed
1004
      packet->append(buff, (uint) (end - buff));
1005
    }
1006

1007
    if (share->db_create_options & HA_OPTION_PACK_KEYS)
1008
      packet->append(" PACK_KEYS=1", 12);
1009
    if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
1010
      packet->append(" PACK_KEYS=0", 12);
1011
    if (share->db_create_options & HA_OPTION_CHECKSUM)
1012
      packet->append(" CHECKSUM=1", 11);
1013
    if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE)
1014
      packet->append(" DELAY_KEY_WRITE=1",18);
1015
    if (share->row_type != ROW_TYPE_DEFAULT)
1016 1017
    {
      packet->append(" ROW_FORMAT=",12);
1018
      packet->append(ha_row_type[(uint) share->row_type]);
1019 1020
    }
    table->file->append_create_info(packet);
1021
    if (share->comment && share->comment[0])
1022 1023
    {
      packet->append(" COMMENT=", 9);
1024
      append_unescaped(packet, share->comment, strlen(share->comment));
1025
    }
1026 1027 1028 1029 1030
    if (share->connect_string.length)
    {
      packet->append(" CONNECTION=", 12);
      append_unescaped(packet, share->connect_string.str, share->connect_string.length);
    }
1031 1032
    if (file->raid_type)
    {
unknown's avatar
unknown committed
1033 1034 1035 1036 1037 1038
      uint length;
      length= my_snprintf(buff,sizeof(buff),
			  " RAID_TYPE=%s RAID_CHUNKS=%d RAID_CHUNKSIZE=%ld",
			  my_raid_type(file->raid_type), file->raid_chunks,
			  file->raid_chunksize/RAID_BLOCK_SIZE);
      packet->append(buff, length);
1039
    }
unknown's avatar
unknown committed
1040 1041
    append_directory(thd, packet, "DATA",  create_info.data_file_name);
    append_directory(thd, packet, "INDEX", create_info.index_file_name);
1042
  }
unknown's avatar
unknown committed
1043 1044 1045
  DBUG_RETURN(0);
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
void
view_store_options(THD *thd, TABLE_LIST *table, String *buff)
{
  buff->append("ALGORITHM=", 10);
  switch ((int8)table->algorithm) {
  case VIEW_ALGORITHM_UNDEFINED:
    buff->append("UNDEFINED ", 10);
    break;
  case VIEW_ALGORITHM_TMPTABLE:
    buff->append("TEMPTABLE ", 10);
    break;
  case VIEW_ALGORITHM_MERGE:
    buff->append("MERGE ", 6);
    break;
  default:
    DBUG_ASSERT(0); // never should happen
  }
  buff->append("DEFINER=", 8);
  append_identifier(thd, buff,
                    table->definer.user.str, table->definer.user.length);
  buff->append('@');
  append_identifier(thd, buff,
                    table->definer.host.str, table->definer.host.length);
  if (table->view_suid)
    buff->append(" SQL SECURITY DEFINER ", 22);
  else
    buff->append(" SQL SECURITY INVOKER ", 22);
}
unknown's avatar
unknown committed
1074

unknown's avatar
VIEW  
unknown committed
1075 1076 1077 1078 1079 1080 1081 1082 1083
static int
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;
1084 1085 1086 1087 1088
  /*
     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
  */
1089
  if (!thd->db || strcmp(thd->db, table->view_db.str))
1090 1091 1092 1093
    table->compact_view_format= FALSE;
  else
  {
    TABLE_LIST *tbl;
1094
    table->compact_view_format= TRUE;
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
    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;
      }
    }
  }

unknown's avatar
VIEW  
unknown committed
1107
  buff->append("CREATE ", 7);
1108
  if (!foreign_db_mode)
unknown's avatar
VIEW  
unknown committed
1109
  {
1110
    view_store_options(thd, table, buff);
unknown's avatar
VIEW  
unknown committed
1111 1112
  }
  buff->append("VIEW ", 5);
1113 1114 1115 1116 1117
  if (!table->compact_view_format)
  {
    append_identifier(thd, buff, table->view_db.str, table->view_db.length);
    buff->append('.');
  }
1118
  append_identifier(thd, buff, table->view_name.str, table->view_name.length);
unknown's avatar
VIEW  
unknown committed
1119
  buff->append(" AS ", 4);
1120 1121 1122 1123 1124 1125 1126

  /*
    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);

1127 1128 1129 1130 1131 1132 1133
  if (table->with_check != VIEW_CHECK_NONE)
  {
    if (table->with_check == VIEW_CHECK_LOCAL)
      buff->append(" WITH LOCAL CHECK OPTION", 24);
    else
      buff->append(" WITH CASCADED CHECK OPTION", 27);
  }
unknown's avatar
VIEW  
unknown committed
1134 1135 1136 1137
  return 0;
}


unknown's avatar
unknown committed
1138
/****************************************************************************
1139 1140
  Return info about all processes
  returns for each thread: thread id, user, host, db, command, info
unknown's avatar
unknown committed
1141 1142 1143 1144
****************************************************************************/

class thread_info :public ilink {
public:
unknown's avatar
unknown committed
1145 1146 1147 1148
  static void *operator new(size_t size)
  {
    return (void*) sql_alloc((uint) size);
  }
unknown's avatar
unknown committed
1149
  static void operator delete(void *ptr __attribute__((unused)),
unknown's avatar
unknown committed
1150 1151
                              size_t size __attribute__((unused)))
  { TRASH(ptr, size); }
unknown's avatar
unknown committed
1152

unknown's avatar
unknown committed
1153 1154
  ulong thread_id;
  time_t start_time;
1155
  uint   command;
unknown's avatar
unknown committed
1156 1157 1158 1159
  const char *user,*host,*db,*proc_info,*state_info;
  char *query;
};

1160
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
1161 1162 1163 1164 1165 1166 1167 1168
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;
unknown's avatar
unknown committed
1169 1170
  ulong max_query_length= (verbose ? thd->variables.max_allowed_packet :
			   PROCESS_LIST_WIDTH);
1171
  Protocol *protocol= thd->protocol;
unknown's avatar
unknown committed
1172 1173
  DBUG_ENTER("mysqld_list_processes");

1174
  field_list.push_back(new Item_int("Id",0,11));
unknown's avatar
unknown committed
1175
  field_list.push_back(new Item_empty_string("User",16));
1176
  field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN));
unknown's avatar
unknown committed
1177 1178 1179
  field_list.push_back(field=new Item_empty_string("db",NAME_LEN));
  field->maybe_null=1;
  field_list.push_back(new Item_empty_string("Command",16));
1180
  field_list.push_back(new Item_return_int("Time",7, FIELD_TYPE_LONG));
unknown's avatar
unknown committed
1181 1182 1183 1184
  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;
1185 1186
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
1187 1188 1189 1190 1191 1192 1193 1194 1195
    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++))
    {
1196
      Security_context *tmp_sctx= tmp->security_ctx;
1197
      struct st_my_thread_var *mysys_var;
1198
      if ((tmp->vio_ok() || tmp->system_thread) &&
1199
          (!user || (tmp_sctx->user && !strcmp(tmp_sctx->user, user))))
unknown's avatar
unknown committed
1200
      {
1201
        thread_info *thd_info= new thread_info;
1202 1203

        thd_info->thread_id=tmp->thread_id;
1204 1205 1206 1207 1208
        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])
1209 1210
	{
	  if ((thd_info->host= thd->alloc(LIST_PROCESS_HOST_LEN+1)))
unknown's avatar
unknown committed
1211
	    my_snprintf((char *) thd_info->host, LIST_PROCESS_HOST_LEN,
1212
			"%s:%u", tmp_sctx->host_or_ip, tmp->peer_port);
1213 1214
	}
	else
1215
	  thd_info->host= thd->strdup(tmp_sctx->host_or_ip);
1216 1217 1218
        if ((thd_info->db=tmp->db))             // Safe test
          thd_info->db=thd->strdup(thd_info->db);
        thd_info->command=(int) tmp->command;
1219 1220
        if ((mysys_var= tmp->mysys_var))
          pthread_mutex_lock(&mysys_var->mutex);
unknown's avatar
SCRUM  
unknown committed
1221
        thd_info->proc_info= (char*) (tmp->killed == THD::KILL_CONNECTION? "Killed" : 0);
unknown's avatar
SCRUM  
unknown committed
1222
#ifndef EMBEDDED_LIBRARY
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
        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);
unknown's avatar
SCRUM  
unknown committed
1233 1234 1235
#else
        thd_info->state_info= (char*)"Writing to net";
#endif
1236 1237
        if (mysys_var)
          pthread_mutex_unlock(&mysys_var->mutex);
unknown's avatar
unknown committed
1238 1239

#if !defined(DONT_USE_THR_ALARM) && ! defined(SCO)
1240 1241
        if (pthread_kill(tmp->real_id,0))
          tmp->proc_info="*** DEAD ***";        // This shouldn't happen
unknown's avatar
unknown committed
1242
#endif
unknown's avatar
unknown committed
1243 1244 1245
#ifdef EXTRA_DEBUG
        thd_info->start_time= tmp->time_after_lock;
#else
1246
        thd_info->start_time= tmp->start_time;
unknown's avatar
unknown committed
1247
#endif
1248 1249 1250
        thd_info->query=0;
        if (tmp->query)
        {
unknown's avatar
unknown committed
1251 1252 1253 1254 1255
	  /* 
            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
          */
unknown's avatar
unknown committed
1256
          uint length= min(max_query_length, tmp->query_length);
1257
          thd_info->query=(char*) thd->strmake(tmp->query,length);
1258 1259
        }
        thread_infos.append(thd_info);
unknown's avatar
unknown committed
1260 1261 1262 1263 1264 1265
      }
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_thread_count));

  thread_info *thd_info;
1266
  time_t now= time(0);
unknown's avatar
unknown committed
1267 1268
  while ((thd_info=thread_infos.get()))
  {
1269 1270
    protocol->prepare_for_resend();
    protocol->store((ulonglong) thd_info->thread_id);
1271 1272 1273
    protocol->store(thd_info->user, system_charset_info);
    protocol->store(thd_info->host, system_charset_info);
    protocol->store(thd_info->db, system_charset_info);
unknown's avatar
unknown committed
1274
    if (thd_info->proc_info)
1275
      protocol->store(thd_info->proc_info, system_charset_info);
unknown's avatar
unknown committed
1276
    else
1277
      protocol->store(command_name[thd_info->command], system_charset_info);
unknown's avatar
unknown committed
1278
    if (thd_info->start_time)
1279
      protocol->store((uint32) (now - thd_info->start_time));
unknown's avatar
unknown committed
1280
    else
1281
      protocol->store_null();
1282 1283
    protocol->store(thd_info->state_info, system_charset_info);
    protocol->store(thd_info->query, system_charset_info);
1284
    if (protocol->write())
unknown's avatar
unknown committed
1285 1286
      break; /* purecov: inspected */
  }
1287
  send_eof(thd);
unknown's avatar
unknown committed
1288 1289 1290 1291
  DBUG_VOID_RETURN;
}

/*****************************************************************************
unknown's avatar
unknown committed
1292
  Status functions
unknown's avatar
unknown committed
1293 1294
*****************************************************************************/

1295 1296

static bool show_status_array(THD *thd, const char *wild,
1297 1298 1299 1300
                              show_var_st *variables,
                              enum enum_var_type value_type,
                              struct system_status_var *status_var,
                              const char *prefix, TABLE *table)
unknown's avatar
unknown committed
1301
{
1302 1303 1304 1305
  char buff[1024], *prefix_end;
  /* the variable name should not be longer then 80 characters */
  char name_buffer[80];
  int len;
1306
  LEX_STRING null_lex_str;
1307
  DBUG_ENTER("show_status_array");
unknown's avatar
unknown committed
1308

1309
  null_lex_str.str= 0;				// For sys_var->value_ptr()
1310
  null_lex_str.length= 0;
unknown's avatar
unknown committed
1311

1312 1313 1314
  prefix_end=strnmov(name_buffer, prefix, sizeof(name_buffer)-1);
  len=name_buffer + sizeof(name_buffer) - prefix_end;

unknown's avatar
unknown committed
1315
  for (; variables->name; variables++)
unknown's avatar
unknown committed
1316
  {
1317 1318 1319 1320 1321 1322
    strnmov(prefix_end, variables->name, len);
    name_buffer[sizeof(name_buffer)-1]=0;       /* Safety */
    SHOW_TYPE show_type=variables->type;
    if (show_type == SHOW_VARS)
    {
      show_status_array(thd, wild, (show_var_st *) variables->value,
1323
                        value_type, status_var, variables->name, table);
1324 1325
    }
    else
unknown's avatar
unknown committed
1326
    {
1327 1328
      if (!(wild && wild[0] && wild_case_compare(system_charset_info,
                                                 name_buffer, wild)))
unknown's avatar
unknown committed
1329
      {
1330
        char *value=variables->value;
unknown's avatar
unknown committed
1331
        const char *pos, *end;                  // We assign a lot of const's
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        long nr;
        if (show_type == SHOW_SYS)
        {
          show_type= ((sys_var*) value)->type();
          value=     (char*) ((sys_var*) value)->value_ptr(thd, value_type,
                                                           &null_lex_str);
        }

        pos= end= buff;
        switch (show_type) {
        case SHOW_LONG_STATUS:
        case SHOW_LONG_CONST_STATUS:
          value= ((char *) status_var + (ulong) value);
          /* fall through */
        case SHOW_LONG:
        case SHOW_LONG_CONST:
          end= int10_to_str(*(long*) value, buff, 10);
          break;
        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_CONST:
        case SHOW_INT:
          end= int10_to_str((long) *(uint32*) value, buff, 10);
          break;
        case SHOW_HAVE:
unknown's avatar
unknown committed
1367 1368 1369 1370 1371 1372
        {
          SHOW_COMP_OPTION tmp= *(SHOW_COMP_OPTION*) value;
          pos= show_comp_option_name[(int) tmp];
          end= strend(pos);
          break;
        }
1373
        case SHOW_CHAR:
unknown's avatar
unknown committed
1374 1375 1376 1377 1378 1379
        {
          if (!(pos= value))
            pos= "";
          end= strend(pos);
          break;
        }
1380 1381 1382 1383 1384 1385 1386
        case SHOW_STARTTIME:
          nr= (long) (thd->query_start() - start_time);
          end= int10_to_str(nr, buff, 10);
          break;
        case SHOW_QUESTION:
          end= int10_to_str((long) thd->query_id, buff, 10);
          break;
unknown's avatar
unknown committed
1387
#ifdef HAVE_REPLICATION
1388 1389 1390 1391
        case SHOW_RPL_STATUS:
          end= strmov(buff, rpl_status_type[(int)rpl_status]);
          break;
        case SHOW_SLAVE_RUNNING:
unknown's avatar
unknown committed
1392 1393 1394 1395 1396 1397 1398
        {
          pthread_mutex_lock(&LOCK_active_mi);
          end= strmov(buff, (active_mi->slave_running &&
                             active_mi->rli.slave_running) ? "ON" : "OFF");
          pthread_mutex_unlock(&LOCK_active_mi);
          break;
        }
unknown's avatar
unknown committed
1399 1400 1401
        case SHOW_SLAVE_RETRIED_TRANS:
        {
          /*
unknown's avatar
unknown committed
1402 1403
            TODO: in 5.1 with multimaster, have one such counter per line in
            SHOW SLAVE STATUS, and have the sum over all lines here.
unknown's avatar
unknown committed
1404 1405 1406 1407 1408 1409 1410 1411
          */
	  pthread_mutex_lock(&LOCK_active_mi);
          pthread_mutex_lock(&active_mi->rli.data_lock);
	  end= int10_to_str(active_mi->rli.retried_trans, buff, 10);
          pthread_mutex_unlock(&active_mi->rli.data_lock);
	  pthread_mutex_unlock(&LOCK_active_mi);
	  break;
        }
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
        case SHOW_SLAVE_SKIP_ERRORS:
        {
          MY_BITMAP *bitmap= (MY_BITMAP *)value;
          if (!use_slave_mask || bitmap_is_clear_all(bitmap))
          {
            end= strmov(buff, "OFF");
          }
          else if (bitmap_is_set_all(bitmap))
          {
            end= strmov(buff, "ALL");
          }
          else
          {
unknown's avatar
unknown committed
1425 1426 1427 1428 1429
            /* 10 is enough assuming errors are max 4 digits */
            int i;
            for (i= 1;
                 i < MAX_SLAVE_ERROR && (uint) (end-buff) < sizeof(buff)-10;
                 i++)
1430 1431 1432
            {
              if (bitmap_is_set(bitmap, i))
              {
1433 1434
                end= int10_to_str(i, (char*) end, 10);
                *(char*) end++= ',';
1435 1436 1437 1438
              }
            }
            if (end != buff)
              end--;				// Remove last ','
unknown's avatar
unknown committed
1439 1440
            if (i < MAX_SLAVE_ERROR)
              end= strmov((char*) end, "...");  // Couldn't show all errors
1441 1442 1443
          }
          break;
        }
unknown's avatar
unknown committed
1444
#endif /* HAVE_REPLICATION */
1445 1446 1447 1448
        case SHOW_OPENTABLES:
          end= int10_to_str((long) cached_tables(), buff, 10);
          break;
        case SHOW_CHAR_PTR:
unknown's avatar
unknown committed
1449 1450 1451 1452 1453 1454
        {
          if (!(pos= *(char**) value))
            pos= "";
          end= strend(pos);
          break;
        }
1455
        case SHOW_DOUBLE_STATUS:
unknown's avatar
unknown committed
1456
        {
1457
          value= ((char *) status_var + (ulong) value);
unknown's avatar
unknown committed
1458 1459 1460
          end= buff + sprintf(buff, "%f", *(double*) value);
          break;
        }
unknown's avatar
unknown committed
1461
#ifdef HAVE_OPENSSL
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
          /* First group - functions relying on CTX */
        case SHOW_SSL_CTX_SESS_ACCEPT:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_accept(ssl_acceptor_fd->
                                                        ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_ACCEPT_GOOD:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_accept_good(ssl_acceptor_fd->
                                                             ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_CONNECT_GOOD:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_connect_good(ssl_acceptor_fd->
                                                              ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_ACCEPT_RENEGOTIATE:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_accept_renegotiate(ssl_acceptor_fd->ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_CONNECT_RENEGOTIATE:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_connect_renegotiate(ssl_acceptor_fd-> ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_CB_HITS:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_cb_hits(ssl_acceptor_fd->
                                                         ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_HITS:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_hits(ssl_acceptor_fd->
                                                      ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_CACHE_FULL:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_cache_full(ssl_acceptor_fd->
                                                            ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_MISSES:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_misses(ssl_acceptor_fd->
                                                        ssl_context)),
                            buff, 10);
          break;
        case SHOW_SSL_CTX_SESS_TIMEOUTS:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_timeouts(ssl_acceptor_fd->ssl_context)),
                            buff,10);
          break;
        case SHOW_SSL_CTX_SESS_NUMBER:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_number(ssl_acceptor_fd->ssl_context)),
                            buff,10);
          break;
        case SHOW_SSL_CTX_SESS_CONNECT:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_connect(ssl_acceptor_fd->ssl_context)),
                            buff,10);
          break;
        case SHOW_SSL_CTX_SESS_GET_CACHE_SIZE:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_sess_get_cache_size(ssl_acceptor_fd->ssl_context)),
                            buff,10);
          break;
        case SHOW_SSL_CTX_GET_VERIFY_MODE:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_get_verify_mode(ssl_acceptor_fd->ssl_context)),
                            buff,10);
          break;
        case SHOW_SSL_CTX_GET_VERIFY_DEPTH:
          end= int10_to_str((long) (!ssl_acceptor_fd ? 0 :
                                    SSL_CTX_get_verify_depth(ssl_acceptor_fd->ssl_context)),
                            buff,10);
          break;
        case SHOW_SSL_CTX_GET_SESSION_CACHE_MODE:
          if (!ssl_acceptor_fd)
          {
            pos= "NONE";
            end= pos+4;
            break;
          }
          switch (SSL_CTX_get_session_cache_mode(ssl_acceptor_fd->ssl_context))
          {
unknown's avatar
unknown committed
1554
          case SSL_SESS_CACHE_OFF:
1555
            pos= "OFF";
1556
            break;
unknown's avatar
unknown committed
1557
          case SSL_SESS_CACHE_CLIENT:
1558
            pos= "CLIENT";
1559
            break;
unknown's avatar
unknown committed
1560
          case SSL_SESS_CACHE_SERVER:
1561
            pos= "SERVER";
1562
            break;
unknown's avatar
unknown committed
1563
          case SSL_SESS_CACHE_BOTH:
1564
            pos= "BOTH";
1565
            break;
unknown's avatar
unknown committed
1566
          case SSL_SESS_CACHE_NO_AUTO_CLEAR:
1567
            pos= "NO_AUTO_CLEAR";
1568
            break;
unknown's avatar
unknown committed
1569
          case SSL_SESS_CACHE_NO_INTERNAL_LOOKUP:
1570
            pos= "NO_INTERNAL_LOOKUP";
1571 1572
            break;
          default:
1573
            pos= "Unknown";
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
            break;
          }
          end= strend(pos);
          break;
          /* First group - functions relying on SSL */
        case SHOW_SSL_GET_VERSION:
          pos= (thd->net.vio->ssl_arg ?
                SSL_get_version((SSL*) thd->net.vio->ssl_arg) : "");
          end= strend(pos);
          break;
        case SHOW_SSL_SESSION_REUSED:
          end= int10_to_str((long) (thd->net.vio->ssl_arg ?
                                    SSL_session_reused((SSL*) thd->net.vio->
                                                       ssl_arg) :
                                    0),
                            buff, 10);
          break;
        case SHOW_SSL_GET_DEFAULT_TIMEOUT:
          end= int10_to_str((long) (thd->net.vio->ssl_arg ?
                                    SSL_get_default_timeout((SSL*) thd->net.vio->
                                                            ssl_arg) :
                                    0),
                            buff, 10);
          break;
        case SHOW_SSL_GET_VERIFY_MODE:
          end= int10_to_str((long) (thd->net.vio->ssl_arg ?
                                    SSL_get_verify_mode((SSL*) thd->net.vio->
                                                        ssl_arg):
                                    0),
                            buff, 10);
          break;
        case SHOW_SSL_GET_VERIFY_DEPTH:
          end= int10_to_str((long) (thd->net.vio->ssl_arg ?
                                    SSL_get_verify_depth((SSL*) thd->net.vio->
                                                         ssl_arg):
                                    0),
                            buff, 10);
          break;
        case SHOW_SSL_GET_CIPHER:
          pos= (thd->net.vio->ssl_arg ?
                SSL_get_cipher((SSL*) thd->net.vio->ssl_arg) : "" );
          end= strend(pos);
          break;
        case SHOW_SSL_GET_CIPHER_LIST:
          if (thd->net.vio->ssl_arg)
          {
            char *to= buff;
            for (int i=0 ; i++ ;)
            {
              const char *p= SSL_get_cipher_list((SSL*) thd->net.vio->ssl_arg,i);
              if (p == NULL)
                break;
              to= strmov(to, p);
              *to++= ':';
            }
            if (to != buff)
              to--;				// Remove last ':'
            end= to;
          }
          break;
unknown's avatar
unknown committed
1634 1635

#endif /* HAVE_OPENSSL */
1636 1637
        case SHOW_KEY_CACHE_LONG:
        case SHOW_KEY_CACHE_CONST_LONG:
1638
          value= (value-(char*) &dflt_key_cache_var)+ (char*) dflt_key_cache;
1639 1640
          end= int10_to_str(*(long*) value, buff, 10);
          break;
1641 1642 1643 1644
        case SHOW_KEY_CACHE_LONGLONG:
	  value= (value-(char*) &dflt_key_cache_var)+ (char*) dflt_key_cache;
	  end= longlong10_to_str(*(longlong*) value, buff, 10);
	  break;
1645 1646 1647 1648 1649 1650
        case SHOW_UNDEF:				// Show never happen
        case SHOW_SYS:
          break;					// Return empty string
        default:
          break;
        }
1651
        restore_record(table, s->default_values);
1652 1653 1654
        table->field[0]->store(name_buffer, strlen(name_buffer),
                               system_charset_info);
        table->field[1]->store(pos, (uint32) (end - pos), system_charset_info);
1655 1656
        if (schema_table_store_record(thd, table))
          DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
1657 1658 1659
      }
    }
  }
1660 1661 1662 1663 1664

  DBUG_RETURN(FALSE);
}


1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
/* 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;
}


1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
LEX_STRING *make_lex_string(THD *thd, LEX_STRING *lex_str,
                            const char* str, uint length,
                            bool allocate_lex_string)
{
  MEM_ROOT *mem= thd->mem_root;
  if (allocate_lex_string)
    lex_str= (LEX_STRING *)thd->alloc(sizeof(LEX_STRING));
  lex_str->str= strmake_root(mem, str, length);
  lex_str->length= length;
  return lex_str;
}


/* INFORMATION_SCHEMA name */
LEX_STRING information_schema_name= {(char*)"information_schema", 18};
unknown's avatar
unknown committed
1704 1705

/* This is only used internally, but we need it here as a forward reference */
1706 1707 1708 1709 1710 1711 1712 1713
extern ST_SCHEMA_TABLE schema_tables[];

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


1714 1715 1716 1717 1718 1719 1720
/*
  Store record to I_S table, convert HEAP table
  to MyISAM if necessary

  SYNOPSIS
    schema_table_store_record()
    thd                   thread handler
1721 1722
    table                 Information schema table to be updated

1723 1724
  RETURN
    0	                  success
1725
    1	                  error
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
*/

static bool schema_table_store_record(THD *thd, TABLE *table)
{
  int error;
  if ((error= table->file->write_row(table->record[0])))
  {
    if (create_myisam_from_heap(thd, table, 
                                table->pos_in_table_list->schema_table_param,
                                error, 0))
      return 1;
  }
  return 0;
}


1742 1743 1744 1745 1746 1747 1748 1749 1750
void get_index_field_values(LEX *lex, INDEX_FIELD_VALUES *index_field_values)
{
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
  switch (lex->orig_sql_command) {
  case SQLCOM_SHOW_DATABASES:
    index_field_values->db_value= wild;
    break;
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_TABLE_STATUS:
1751
  case SQLCOM_SHOW_TRIGGERS:
unknown's avatar
unknown committed
1752
    index_field_values->db_value= lex->select_lex.db;
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    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();
unknown's avatar
unknown committed
1774
  if (!sel->add_table_to_list(thd, table_ident, 0, 0, TL_READ,
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
                             (List<String> *) 0, (List<String> *) 0))
    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;
    Item **child;
    Item **item_end= (item_func->arguments()) + item_func->argument_count();
    for (child= item_func->arguments(); child != item_end; child++)
1789
    {
1790 1791
      if (!uses_only_table_name_fields(*child, table))
        return 0;
1792
    }
1793 1794 1795 1796 1797 1798 1799
  }
  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;
unknown's avatar
unknown committed
1800 1801
    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 : "";
1802 1803 1804 1805 1806 1807 1808
    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)))
1809 1810
      return 0;
  }
1811 1812
  else if (item->type() == Item::REF_ITEM)
    return uses_only_table_name_fields(item->real_item(), table);
1813 1814 1815 1816
  if (item->type() == Item::SUBSELECT_ITEM &&
      !item->const_item())
    return 0;

1817
  return 1;
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 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
}


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;
}


1877 1878 1879 1880 1881 1882
enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table)
{
  return (enum enum_schema_tables) (schema_table - &schema_tables[0]);
}


unknown's avatar
unknown committed
1883
/*
1884
  Create db names list. Information schema name always is first in list
unknown's avatar
unknown committed
1885 1886

  SYNOPSIS
1887
    make_db_list()
unknown's avatar
unknown committed
1888 1889 1890
    thd                   thread handler
    files                 list of db names
    wild                  wild string
1891 1892
    idx_field_vals        idx_field_vals->db_name contains db name or
                          wild string
unknown's avatar
unknown committed
1893 1894
    with_i_schema         returns 1 if we added 'IS' name to list
                          otherwise returns 0
1895 1896
    is_wild_value         if value is 1 then idx_field_vals->db_name is
                          wild string otherwise it's db name; 
unknown's avatar
unknown committed
1897 1898 1899 1900 1901 1902

  RETURN
    1	                  error
    0	                  success
*/

1903 1904 1905
int make_db_list(THD *thd, List<char> *files,
                 INDEX_FIELD_VALUES *idx_field_vals,
                 bool *with_i_schema, bool is_wild_value)
1906
{
1907
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
1908
  *with_i_schema= 0;
1909 1910
  get_index_field_values(lex, idx_field_vals);
  if (is_wild_value)
unknown's avatar
unknown committed
1911
  {
1912 1913 1914 1915 1916
    /*
      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)
    */
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    if (!idx_field_vals->db_value ||
        !wild_case_compare(system_charset_info, 
                           information_schema_name.str,
                           idx_field_vals->db_value))
    {
      *with_i_schema= 1;
      if (files->push_back(thd->strdup(information_schema_name.str)))
        return 1;
    }
    return mysql_find_files(thd, files, NullS, mysql_data_home,
                            idx_field_vals->db_value, 1);
unknown's avatar
unknown committed
1928
  }
1929

1930 1931 1932 1933 1934 1935
  /*
    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()
    function). lex->orig_sql_command can be not equal to SQLCOM_END
    only in case of executing of SHOW commands.
  */
1936 1937
  if (lex->orig_sql_command != SQLCOM_END)
  {
1938
    if (!my_strcasecmp(system_charset_info, information_schema_name.str,
1939 1940 1941 1942 1943 1944 1945 1946
                       idx_field_vals->db_value))
    {
      *with_i_schema= 1;
      return files->push_back(thd->strdup(information_schema_name.str));
    }
    return files->push_back(thd->strdup(idx_field_vals->db_value));
  }

1947 1948 1949 1950
  /*
    Create list of existing databases. It is used in case
    of select from information schema table
  */
1951 1952 1953 1954
  if (files->push_back(thd->strdup(information_schema_name.str)))
    return 1;
  *with_i_schema= 1;
  return mysql_find_files(thd, files, NullS, mysql_data_home, NullS, 1);
1955 1956 1957 1958 1959 1960
}


int schema_tables_add(THD *thd, List<char> *files, const char *wild)
{
  ST_SCHEMA_TABLE *tmp_schema_table= schema_tables;
1961
  for (; tmp_schema_table->table_name; tmp_schema_table++)
1962
  {
1963 1964
    if (tmp_schema_table->hidden)
      continue;
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
    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)))
      return 1;
  }
  return 0;
}


1984 1985 1986 1987 1988
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;
1989
  SELECT_LEX *old_all_select_lex= lex->all_selects_list;
1990 1991
  TABLE_LIST **save_query_tables_last= lex->query_tables_last;
  enum_sql_command save_sql_command= lex->sql_command;
unknown's avatar
unknown committed
1992
  SELECT_LEX *lsel= tables->schema_select_lex;
1993
  ST_SCHEMA_TABLE *schema_table= tables->schema_table;
1994 1995 1996 1997 1998 1999 2000
  SELECT_LEX sel;
  INDEX_FIELD_VALUES idx_field_vals;
  char path[FN_REFLEN], *end, *base_name, *file_name;
  uint len;
  bool with_i_schema;
  enum enum_schema_tables schema_table_idx;
  List<char> bases;
unknown's avatar
unknown committed
2001
  List_iterator_fast<char> it(bases);
2002
  COND *partial_cond;
2003
  Security_context *sctx= thd->security_ctx;
2004
  uint derived_tables= lex->derived_tables; 
unknown's avatar
unknown committed
2005
  int error= 1;
2006
  Open_tables_state open_tables_state_backup;
2007 2008 2009 2010
  DBUG_ENTER("get_all_tables");

  LINT_INIT(end);
  LINT_INIT(len);
2011

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
  /*
    Let us set fake sql_command so views won't try to merge
    themselves into main statement.
  */
  lex->sql_command= SQLCOM_SHOW_FIELDS;

  /*
    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);

2025 2026 2027
  if (lsel)
  {
    TABLE_LIST *show_table_list= (TABLE_LIST*) lsel->table_list.first;
2028 2029
    bool res;

2030
    lex->all_selects_list= lsel;
2031 2032
    res= open_normal_and_derived_tables(thd, show_table_list,
                                        MYSQL_LOCK_IGNORE_FLUSH);
2033 2034 2035
    /*
      get_all_tables() returns 1 on failure and 0 on success thus
      return only these and not the result code of ::process_table()
2036 2037 2038 2039 2040 2041 2042

      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).
2043 2044
    */
    error= test(schema_table->process_table(thd, show_table_list,
2045 2046 2047 2048 2049
                                            table, res, 
                                            (show_table_list->view ?
                                             show_table_list->view_db.str :
                                             show_table_list->db),
                                            show_table_list->alias));
2050
    close_thread_tables(thd);
2051
    show_table_list->table= 0;
unknown's avatar
unknown committed
2052
    goto err;
2053 2054
  }

2055
  schema_table_idx= get_schema_table_idx(schema_table);
2056

2057 2058
  if (make_db_list(thd, &bases, &idx_field_vals,
                   &with_i_schema, 0))
unknown's avatar
unknown committed
2059
    goto err;
2060 2061

  partial_cond= make_cond_for_info_schema(cond, tables);
unknown's avatar
unknown committed
2062
  it.rewind(); /* To get access to new elements in basis list */
2063
  while ((base_name= it++) ||
2064 2065 2066 2067 2068 2069 2070 2071 2072
	 /*
	   generate error for non existing database.
	   (to save old behaviour for SHOW TABLES FROM db)
	 */
	 ((lex->orig_sql_command == SQLCOM_SHOW_TABLES ||
           lex->orig_sql_command == SQLCOM_SHOW_TABLE_STATUS) &&
	  (base_name= select_lex->db) && !bases.elements))
  {
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2073 2074
    if (!check_access(thd,SELECT_ACL, base_name, 
                      &thd->col_access, 0, 1, with_i_schema) ||
2075 2076
        sctx->master_access & (DB_ACLS | SHOW_DB_ACL) ||
	acl_get(sctx->host, sctx->ip, sctx->priv_user, base_name,0) ||
2077 2078 2079 2080
	(grant_option && !check_grant_db(thd, base_name)))
#endif
    {
      List<char> files;
2081 2082 2083
      if (with_i_schema)                      // information schema table names
      {
        if (schema_tables_add(thd, &files, idx_field_vals.table_value))
unknown's avatar
unknown committed
2084
          goto err;
2085 2086 2087 2088 2089 2090 2091 2092
      }
      else
      {
        strxmov(path, mysql_data_home, "/", base_name, NullS);
        end= path + (len= unpack_dirname(path,path));
        len= FN_LEN - len;
        if (mysql_find_files(thd, &files, base_name, 
                             path, idx_field_vals.table_value, 0))
unknown's avatar
unknown committed
2093
          goto err;
2094
      }
2095

2096 2097
      List_iterator_fast<char> it_files(files);
      while ((file_name= it_files++))
2098
      {
2099
	restore_record(table, s->default_values);
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
        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)
          {
            if (lex->verbose || lex->orig_sql_command == SQLCOM_END)
            {
2110
              if (with_i_schema)
2111
              {
2112
                table->field[3]->store("SYSTEM VIEW", 11, system_charset_info);
2113 2114 2115 2116
              }
              else
              {
                my_snprintf(end, len, "/%s%s", file_name, reg_ext);
2117
                switch (mysql_frm_type(path)) {
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
                case FRMTYPE_ERROR:
                  table->field[3]->store("ERROR", 5, system_charset_info);
                  break;
                case FRMTYPE_TABLE:
                  table->field[3]->store("BASE TABLE", 10, system_charset_info);
                  break;
                case FRMTYPE_VIEW:
                  table->field[3]->store("VIEW", 4, system_charset_info);
                  break;
                default:
                  DBUG_ASSERT(0);
                }
2130 2131
              }
            }
2132
            if (schema_table_store_record(thd, table))
2133
              goto err;
2134 2135 2136 2137
          }
          else
          {
            int res;
unknown's avatar
unknown committed
2138 2139 2140 2141 2142
            /*
              Set the parent lex of 'sel' because it is needed by sel.init_query()
              which is called inside make_table_list.
            */
            sel.parent_lex= lex;
2143
            if (make_table_list(thd, &sel, base_name, file_name))
unknown's avatar
unknown committed
2144
              goto err;
2145
            TABLE_LIST *show_table_list= (TABLE_LIST*) sel.table_list.first;
2146 2147
            lex->all_selects_list= &sel;
            lex->derived_tables= 0;
2148 2149
            res= open_normal_and_derived_tables(thd, show_table_list,
                                                MYSQL_LOCK_IGNORE_FLUSH);
2150 2151 2152 2153 2154 2155 2156
            /*
              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.
            */
2157
            res= schema_table->process_table(thd, show_table_list, table,
2158
                                            res, base_name,
2159
                                            show_table_list->alias);
2160
            close_thread_tables(thd);
2161 2162
            if (res)
              goto err;
2163 2164 2165
          }
        }
      }
2166 2167 2168 2169
      /*
        If we have information schema its always the first table and only
        the first table. Reset for other tables.
      */
2170
      with_i_schema= 0;
2171 2172
    }
  }
unknown's avatar
unknown committed
2173 2174 2175

  error= 0;
err:
2176
  thd->restore_backup_open_tables_state(&open_tables_state_backup);
2177 2178
  lex->derived_tables= derived_tables;
  lex->all_selects_list= old_all_select_lex;
2179 2180 2181
  lex->query_tables_last= save_query_tables_last;
  *save_query_tables_last= 0;
  lex->sql_command= save_sql_command;
unknown's avatar
unknown committed
2182
  DBUG_RETURN(error);
2183 2184 2185
}


2186
bool store_schema_shemata(THD* thd, TABLE *table, const char *db_name,
2187
                          CHARSET_INFO *cs)
2188
{
2189
  restore_record(table, s->default_values);
2190
  table->field[1]->store(db_name, strlen(db_name), system_charset_info);
2191 2192
  table->field[2]->store(cs->csname, strlen(cs->csname), system_charset_info);
  table->field[3]->store(cs->name, strlen(cs->name), system_charset_info);
2193
  return schema_table_store_record(thd, table);
2194 2195 2196
}


2197 2198
int fill_schema_shemata(THD *thd, TABLE_LIST *tables, COND *cond)
{
2199
  char path[FN_REFLEN];
2200 2201 2202 2203 2204
  bool found_libchar;
  INDEX_FIELD_VALUES idx_field_vals;
  List<char> files;
  char *file_name;
  uint length;
unknown's avatar
unknown committed
2205
  bool with_i_schema;
2206 2207
  HA_CREATE_INFO create;
  TABLE *table= tables->table;
2208
  Security_context *sctx= thd->security_ctx;
2209
  DBUG_ENTER("fill_schema_shemata");
2210

2211 2212
  if (make_db_list(thd, &files, &idx_field_vals,
                   &with_i_schema, 1))
2213
    DBUG_RETURN(1);
2214

2215 2216 2217
  List_iterator_fast<char> it(files);
  while ((file_name=it++))
  {
2218 2219
    if (with_i_schema)       // information schema name is always first in list
    {
2220
      if (store_schema_shemata(thd, table, file_name,
2221
                               system_charset_info))
2222
        DBUG_RETURN(1);
2223 2224 2225
      with_i_schema= 0;
      continue;
    }
2226
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2227 2228
    if (sctx->master_access & (DB_ACLS | SHOW_DB_ACL) ||
	acl_get(sctx->host, sctx->ip, sctx->priv_user, file_name,0) ||
2229 2230 2231
	(grant_option && !check_grant_db(thd, file_name)))
#endif
    {
unknown's avatar
unknown committed
2232
      strxmov(path, mysql_data_home, "/", file_name, NullS);
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
      length=unpack_dirname(path,path);		// Convert if not unix
      found_libchar= 0;
      if (length && path[length-1] == FN_LIBCHAR)
      {
	found_libchar= 1;
	path[length-1]=0;			// remove ending '\'
      }

      if (found_libchar)
	path[length-1]= FN_LIBCHAR;
      strmov(path+length, MY_DB_OPT_FILE);
      load_db_opt(thd, path, &create);
2245
      if (store_schema_shemata(thd, table, file_name, 
2246
                               create.default_table_charset))
2247
        DBUG_RETURN(1);
2248 2249
    }
  }
2250
  DBUG_RETURN(0);
2251 2252 2253
}


unknown's avatar
unknown committed
2254 2255 2256 2257
static int get_schema_tables_record(THD *thd, struct st_table_list *tables,
				    TABLE *table, bool res,
				    const char *base_name,
				    const char *file_name)
2258 2259 2260 2261 2262
{
  const char *tmp_buff;
  TIME time;
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_schema_tables_record");
2263 2264

  restore_record(table, s->default_values);
2265 2266
  table->field[1]->store(base_name, strlen(base_name), cs);
  table->field[2]->store(file_name, strlen(file_name), cs);
unknown's avatar
unknown committed
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
  if (res)
  {
    /*
      there was errors during opening tables
    */
    const char *error= thd->net.last_error;
    table->field[20]->store(error, strlen(error), cs);
    thd->clear_error();
  }
  else if (tables->view)
2277 2278
  {
    table->field[3]->store("VIEW", 4, cs);
2279
    table->field[20]->store("VIEW", 4, cs);
2280 2281 2282 2283
  }
  else
  {
    TABLE *show_table= tables->table;
2284
    TABLE_SHARE *share= show_table->s;
2285
    handler *file= show_table->file;
2286

2287 2288
    file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_AUTO |
               HA_STATUS_NO_LOCK);
2289 2290 2291
    if (share->tmp_table == SYSTEM_TMP_TABLE)
      table->field[3]->store("SYSTEM VIEW", 11, cs);
    else if (share->tmp_table)
2292
      table->field[3]->store("LOCAL TEMPORARY", 15, cs);
2293 2294 2295
    else
      table->field[3]->store("BASE TABLE", 10, cs);

2296 2297
    for (int i= 4; i < 20; i++)
    {
2298
      if (i == 7 || (i > 12 && i < 17) || i == 18)
2299 2300 2301 2302 2303
        continue;
      table->field[i]->set_notnull();
    }
    tmp_buff= file->table_type();
    table->field[4]->store(tmp_buff, strlen(tmp_buff), cs);
2304
    table->field[5]->store((longlong) share->frm_version, TRUE);
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
    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;
    }
2330
    table->field[6]->store(tmp_buff, strlen(tmp_buff), cs);
2331 2332
    if (!tables->schema_table)
    {
2333
      table->field[7]->store((longlong) file->records, TRUE);
2334 2335
      table->field[7]->set_notnull();
    }
2336 2337
    table->field[8]->store((longlong) file->mean_rec_length, TRUE);
    table->field[9]->store((longlong) file->data_file_length, TRUE);
2338 2339
    if (file->max_data_file_length)
    {
2340
      table->field[10]->store((longlong) file->max_data_file_length, TRUE);
2341
    }
2342 2343
    table->field[11]->store((longlong) file->index_file_length, TRUE);
    table->field[12]->store((longlong) file->delete_length, TRUE);
2344
    if (show_table->found_next_number_field)
2345
    {
2346
      table->field[13]->store((longlong) file->auto_increment_value, TRUE);
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
      table->field[13]->set_notnull();
    }
    if (file->create_time)
    {
      thd->variables.time_zone->gmt_sec_to_TIME(&time,
                                                file->create_time);
      table->field[14]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
      table->field[14]->set_notnull();
    }
    if (file->update_time)
    {
      thd->variables.time_zone->gmt_sec_to_TIME(&time,
                                                file->update_time);
      table->field[15]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
      table->field[15]->set_notnull();
    }
    if (file->check_time)
    {
      thd->variables.time_zone->gmt_sec_to_TIME(&time, file->check_time);
      table->field[16]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
      table->field[16]->set_notnull();
    }
2369 2370
    tmp_buff= (share->table_charset ?
               share->table_charset->name : "default");
2371
    table->field[17]->store(tmp_buff, strlen(tmp_buff), cs);
unknown's avatar
unknown committed
2372
    if (file->table_flags() & (ulong) HA_HAS_CHECKSUM)
2373
    {
2374
      table->field[18]->store((longlong) file->checksum(), TRUE);
2375 2376 2377 2378 2379
      table->field[18]->set_notnull();
    }

    char option_buff[350],*ptr;
    ptr=option_buff;
2380
    if (share->min_rows)
2381 2382
    {
      ptr=strmov(ptr," min_rows=");
2383
      ptr=longlong10_to_str(share->min_rows,ptr,10);
2384
    }
2385
    if (share->max_rows)
2386 2387
    {
      ptr=strmov(ptr," max_rows=");
2388
      ptr=longlong10_to_str(share->max_rows,ptr,10);
2389
    }
2390
    if (share->avg_row_length)
2391 2392
    {
      ptr=strmov(ptr," avg_row_length=");
2393
      ptr=longlong10_to_str(share->avg_row_length,ptr,10);
2394
    }
2395
    if (share->db_create_options & HA_OPTION_PACK_KEYS)
2396
      ptr=strmov(ptr," pack_keys=1");
2397
    if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
2398
      ptr=strmov(ptr," pack_keys=0");
2399
    if (share->db_create_options & HA_OPTION_CHECKSUM)
2400
      ptr=strmov(ptr," checksum=1");
2401
    if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE)
2402
      ptr=strmov(ptr," delay_key_write=1");
2403
    if (share->row_type != ROW_TYPE_DEFAULT)
2404
      ptr=strxmov(ptr, " row_format=", 
2405
                  ha_row_type[(uint) share->row_type],
2406 2407 2408 2409
                  NullS);
    if (file->raid_type)
    {
      char buff[100];
unknown's avatar
unknown committed
2410 2411 2412 2413
      my_snprintf(buff,sizeof(buff),
                  " raid_type=%s raid_chunks=%d raid_chunksize=%ld",
                  my_raid_type(file->raid_type), file->raid_chunks,
                  file->raid_chunksize/RAID_BLOCK_SIZE);
2414 2415 2416 2417 2418
      ptr=strmov(ptr,buff);
    }
    table->field[19]->store(option_buff+1,
                            (ptr == option_buff ? 0 : 
                             (uint) (ptr-option_buff)-1), cs);
2419
    {
2420 2421
      char *comment;
      comment= show_table->file->update_table_comment(share->comment);
2422 2423 2424
      if (comment)
      {
        table->field[20]->store(comment, strlen(comment), cs);
2425 2426
        if (comment != share->comment)
          my_free(comment, MYF(0));
2427 2428
      }
    }
2429
  }
2430
  DBUG_RETURN(schema_table_store_record(thd, table));
2431 2432 2433
}


unknown's avatar
unknown committed
2434 2435 2436 2437
static int get_schema_column_record(THD *thd, struct st_table_list *tables,
				    TABLE *table, bool res,
				    const char *base_name,
				    const char *file_name)
2438
{
2439 2440
  LEX *lex= thd->lex;
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
2441
  CHARSET_INFO *cs= system_charset_info;
2442 2443 2444 2445 2446
  TABLE *show_table;
  handler *file;
  Field **ptr,*field;
  int count;
  uint base_name_length, file_name_length;
2447
  DBUG_ENTER("get_schema_column_record");
2448

2449 2450
  if (res)
  {
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
    if (lex->orig_sql_command != SQLCOM_SHOW_FIELDS)
    {
      /*
        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);
2463 2464
  }

2465 2466 2467
  show_table= tables->table;
  file= show_table->file;
  count= 0;
2468
  file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
2469
  restore_record(show_table, s->default_values);
2470 2471 2472
  base_name_length= strlen(base_name);
  file_name_length= strlen(file_name);

2473 2474
  for (ptr=show_table->field; (field= *ptr) ; ptr++)
  {
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
    const char *tmp_buff;
    byte *pos;
    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);
2493 2494

#ifndef NO_EMBEDDED_ACCESS_CHECKS
2495 2496
    uint col_access;
    check_access(thd,SELECT_ACL | EXTRA_ACL, base_name,
2497
                 &tables->grant.privilege, 0, 0, test(tables->schema_table));
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    col_access= get_column_grant(thd, &tables->grant, 
                                 base_name, file_name,
                                 field->field_name) & COL_ACLS;
    if (lex->orig_sql_command != SQLCOM_SHOW_FIELDS  && 
        !tables->schema_table && !col_access)
      continue;
    end= tmp;
    for (uint bitnr=0; col_access ; col_access>>=1,bitnr++)
    {
      if (col_access & 1)
2508
      {
2509 2510
        *end++=',';
        end=strmov(end,grant_types.type_names[bitnr]);
2511
      }
2512
    }
2513
    table->field[17]->store(tmp+1,end == tmp ? 0 : (uint) (end-tmp-1), cs);
2514

unknown's avatar
unknown committed
2515
#endif
2516 2517 2518 2519
    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);
2520
    table->field[4]->store((longlong) count, TRUE);
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
    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)
    {
      table->field[5]->store("CURRENT_TIMESTAMP", 17, cs);
      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 ||
             lex->orig_sql_command != SQLCOM_SHOW_FIELDS ||
             field->maybe_null())
      table->field[5]->set_null();                // Null as default
    else
    {
      table->field[5]->store("",0, cs);
      table->field[5]->set_notnull();
    }
    pos=(byte*) ((flags & NOT_NULL_FLAG) &&
                 field->type() != FIELD_TYPE_TIMESTAMP ?
                 "NO" : "YES");
    table->field[6]->store((const char*) pos,
                           strlen((const char*) pos), cs);
    is_blob= (field->type() == FIELD_TYPE_BLOB);
    if (field->has_charset() || is_blob)
    {
      longlong c_octet_len= is_blob ? (longlong) field->max_length() :
        (longlong) field->max_length()/field->charset()->mbmaxlen;
2564
      table->field[8]->store((longlong) field->max_length(), TRUE);
2565
      table->field[8]->set_notnull();
2566
      table->field[9]->store(c_octet_len, TRUE);
2567 2568
      table->field[9]->set_notnull();
    }
2569

2570 2571 2572 2573
    /*
      Calculate field_length and decimals.
      They are set to -1 if they should not be set (we should return NULL)
    */
unknown's avatar
unknown committed
2574

2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
    decimals= field->decimals();
    switch (field->type()) {
    case FIELD_TYPE_NEWDECIMAL:
      field_length= ((Field_new_decimal*) field)->precision;
      break;
    case FIELD_TYPE_DECIMAL:
      field_length= field->field_length - (decimals  ? 2 : 1);
      break;
    case FIELD_TYPE_TINY:
    case FIELD_TYPE_SHORT:
    case FIELD_TYPE_LONG:
    case FIELD_TYPE_LONGLONG:
    case FIELD_TYPE_INT24:
      field_length= field->max_length() - 1;
      break;
    case FIELD_TYPE_BIT:
      field_length= field->max_length();
      decimals= -1;                             // return NULL
      break;
    case FIELD_TYPE_FLOAT:  
    case FIELD_TYPE_DOUBLE:
      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)
    {
2607
      table->field[10]->store((longlong) field_length, TRUE);
2608
      table->field[10]->set_notnull();
2609
    }
2610 2611
    if (decimals >= 0)
    {
2612
      table->field[11]->store((longlong) decimals, TRUE);
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
      table->field[11]->set_notnull();
    }

    if (field->has_charset())
    {
      pos=(byte*) field->charset()->csname;
      table->field[12]->store((const char*) pos,
                              strlen((const char*) pos), cs);
      table->field[12]->set_notnull();
      pos=(byte*) field->charset()->name;
      table->field[13]->store((const char*) pos,
                              strlen((const char*) pos), cs);
      table->field[13]->set_notnull();
    }
    pos=(byte*) ((field->flags & PRI_KEY_FLAG) ? "PRI" :
                 (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);
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
  }
  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;
2653 2654

  for (cs= all_charsets ; cs < all_charsets+255 ; cs++)
2655 2656 2657 2658 2659 2660 2661
  {
    CHARSET_INFO *tmp_cs= cs[0];
    if (tmp_cs && (tmp_cs->state & MY_CS_PRIMARY) && 
        (tmp_cs->state & MY_CS_AVAILABLE) &&
        !(wild && wild[0] &&
	  wild_case_compare(scs, tmp_cs->csname,wild)))
    {
2662
      const char *comment;
2663
      restore_record(table, s->default_values);
2664
      table->field[0]->store(tmp_cs->csname, strlen(tmp_cs->csname), scs);
2665
      table->field[1]->store(tmp_cs->name, strlen(tmp_cs->name), scs);
2666 2667
      comment= tmp_cs->comment ? tmp_cs->comment : "";
      table->field[2]->store(comment, strlen(comment), scs);
2668
      table->field[3]->store((longlong) tmp_cs->mbmaxlen, TRUE);
2669 2670
      if (schema_table_store_record(thd, table))
        return 1;
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
    }
  }
  return 0;
}


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;
2683
  for (cs= all_charsets ; cs < all_charsets+255 ; cs++ )
2684 2685 2686 2687 2688 2689
  {
    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;
2690
    for (cl= all_charsets; cl < all_charsets+255 ;cl ++)
2691 2692 2693 2694 2695 2696 2697 2698 2699
    {
      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;
2700
	restore_record(table, s->default_values);
2701 2702
	table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs);
        table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs);
2703
        table->field[2]->store((longlong) tmp_cl->number, TRUE);
2704 2705 2706 2707
        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);
2708
        table->field[5]->store((longlong) tmp_cl->strxfrm_multiply, TRUE);
2709 2710
        if (schema_table_store_record(thd, table))
          return 1;
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
      }
    }
  }
  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;
2723
  for (cs= all_charsets ; cs < all_charsets+255 ; cs++ )
2724 2725 2726 2727 2728 2729
  {
    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;
2730
    for (cl= all_charsets; cl < all_charsets+255 ;cl ++)
2731 2732 2733 2734 2735
    {
      CHARSET_INFO *tmp_cl= cl[0];
      if (!tmp_cl || !(tmp_cl->state & MY_CS_AVAILABLE) || 
          !my_charset_same(tmp_cs,tmp_cl))
	continue;
2736
      restore_record(table, s->default_values);
2737 2738
      table->field[0]->store(tmp_cl->name, strlen(tmp_cl->name), scs);
      table->field[1]->store(tmp_cl->csname , strlen(tmp_cl->csname), scs);
2739 2740
      if (schema_table_store_record(thd, table))
        return 1;
2741 2742 2743 2744 2745 2746
    }
  }
  return 0;
}


2747
bool store_schema_proc(THD *thd, TABLE *table, TABLE *proc_table,
2748
                       const char *wild, bool full_access, const char *sp_user)
2749 2750 2751 2752 2753
{
  String tmp_string;
  TIME time;
  LEX *lex= thd->lex;
  CHARSET_INFO *cs= system_charset_info;
2754 2755 2756 2757 2758 2759
  const char *sp_db, *sp_name, *definer;
  sp_db= get_field(thd->mem_root, proc_table->field[0]);
  sp_name= get_field(thd->mem_root, proc_table->field[1]);
  definer= get_field(thd->mem_root, proc_table->field[11]);
  if (!full_access)
    full_access= !strcmp(sp_user, definer);
2760 2761
  if (!full_access && check_some_routine_access(thd, sp_db, sp_name,
			proc_table->field[2]->val_int() == TYPE_ENUM_PROCEDURE))
2762
    return 0;
2763

2764 2765 2766 2767 2768 2769
  if (lex->orig_sql_command == SQLCOM_SHOW_STATUS_PROC &&
      proc_table->field[2]->val_int() == TYPE_ENUM_PROCEDURE ||
      lex->orig_sql_command == SQLCOM_SHOW_STATUS_FUNC &&
      proc_table->field[2]->val_int() == TYPE_ENUM_FUNCTION ||
      lex->orig_sql_command == SQLCOM_END)
  {
2770 2771
    restore_record(table, s->default_values);
    if (!wild || !wild[0] || !wild_compare(sp_name, wild, 0))
2772
    {
2773
      int enum_idx= proc_table->field[5]->val_int();
2774
      table->field[3]->store(sp_name, strlen(sp_name), cs);
2775 2776
      get_field(thd->mem_root, proc_table->field[3], &tmp_string);
      table->field[0]->store(tmp_string.ptr(), tmp_string.length(), cs);
2777
      table->field[2]->store(sp_db, strlen(sp_db), cs);
2778 2779
      get_field(thd->mem_root, proc_table->field[2], &tmp_string);
      table->field[4]->store(tmp_string.ptr(), tmp_string.length(), cs);
2780 2781 2782 2783 2784 2785
      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();
      }
2786 2787 2788 2789 2790
      if (full_access)
      {
        get_field(thd->mem_root, proc_table->field[10], &tmp_string);
        table->field[7]->store(tmp_string.ptr(), tmp_string.length(), cs);
      }
2791
      table->field[6]->store("SQL", 3, cs);
2792
      table->field[10]->store("SQL", 3, cs);
2793
      get_field(thd->mem_root, proc_table->field[6], &tmp_string);
2794
      table->field[11]->store(tmp_string.ptr(), tmp_string.length(), cs);
2795 2796
      table->field[12]->store(sp_data_access_name[enum_idx].str, 
                              sp_data_access_name[enum_idx].length , cs);
2797 2798
      get_field(thd->mem_root, proc_table->field[7], &tmp_string);
      table->field[14]->store(tmp_string.ptr(), tmp_string.length(), cs);
2799 2800
      bzero((char *)&time, sizeof(time));
      ((Field_timestamp *) proc_table->field[12])->get_time(&time);
2801
      table->field[15]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
2802 2803
      bzero((char *)&time, sizeof(time));
      ((Field_timestamp *) proc_table->field[13])->get_time(&time);
2804
      table->field[16]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
2805
      get_field(thd->mem_root, proc_table->field[14], &tmp_string);
2806
      table->field[17]->store(tmp_string.ptr(), tmp_string.length(), cs);
2807
      get_field(thd->mem_root, proc_table->field[15], &tmp_string);
2808
      table->field[18]->store(tmp_string.ptr(), tmp_string.length(), cs);
2809
      table->field[19]->store(definer, strlen(definer), cs);
2810
      return schema_table_store_record(thd, table);
2811 2812
    }
  }
2813
  return 0;
2814 2815 2816 2817 2818 2819 2820 2821 2822
}


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;
2823
  TABLE *table= tables->table;
2824 2825
  bool full_access;
  char definer[HOSTNAME_LENGTH+USERNAME_LENGTH+2];
2826
  Open_tables_state open_tables_state_backup;
2827 2828
  DBUG_ENTER("fill_schema_proc");

2829 2830
  strxmov(definer, thd->security_ctx->priv_user, "@",
          thd->security_ctx->priv_host, NullS);
2831
  /* We use this TABLE_LIST instance only for checking of privileges. */
2832 2833
  bzero((char*) &proc_tables,sizeof(proc_tables));
  proc_tables.db= (char*) "mysql";
2834
  proc_tables.db_length= 5;
2835
  proc_tables.table_name= proc_tables.alias= (char*) "proc";
2836
  proc_tables.table_name_length= 4;
2837
  proc_tables.lock_type= TL_READ;
2838
  full_access= !check_table_access(thd, SELECT_ACL, &proc_tables, 1);
2839
  if (!(proc_table= open_proc_table_for_read(thd, &open_tables_state_backup)))
2840 2841 2842 2843 2844 2845 2846 2847 2848
  {
    DBUG_RETURN(1);
  }
  proc_table->file->ha_index_init(0);
  if ((res= proc_table->file->index_first(proc_table->record[0])))
  {
    res= (res == HA_ERR_END_OF_FILE) ? 0 : 1;
    goto err;
  }
2849 2850 2851 2852 2853
  if (store_schema_proc(thd, table, proc_table, wild, full_access, definer))
  {
    res= 1;
    goto err;
  }
2854
  while (!proc_table->file->index_next(proc_table->record[0]))
2855 2856 2857 2858 2859 2860 2861
  {
    if (store_schema_proc(thd, table, proc_table, wild, full_access, definer))
    {
      res= 1;
      goto err;
    }
  }
2862 2863 2864

err:
  proc_table->file->ha_index_end();
2865
  close_proc_table(thd, &open_tables_state_backup);
2866 2867 2868 2869
  DBUG_RETURN(res);
}


unknown's avatar
unknown committed
2870 2871 2872 2873
static int get_schema_stat_record(THD *thd, struct st_table_list *tables,
				  TABLE *table, bool res,
				  const char *base_name,
				  const char *file_name)
2874 2875 2876
{
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_schema_stat_record");
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
  if (res)
  {
    if (thd->lex->orig_sql_command != SQLCOM_SHOW_KEYS)
    {
      /*
        I.e. we are in SELECT FROM INFORMATION_SCHEMA.STATISTICS
        rather than in SHOW KEYS
      */ 
      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)
2894 2895 2896 2897 2898 2899
  {
    TABLE *show_table= tables->table;
    KEY *key_info=show_table->key_info;
    show_table->file->info(HA_STATUS_VARIABLE | 
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);
2900
    for (uint i=0 ; i < show_table->s->keys ; i++,key_info++)
2901 2902 2903 2904 2905
    {
      KEY_PART_INFO *key_part= key_info->key_part;
      const char *str;
      for (uint j=0 ; j < key_info->key_parts ; j++,key_part++)
      {
2906
        restore_record(table, s->default_values);
2907 2908 2909
        table->field[1]->store(base_name, strlen(base_name), cs);
        table->field[2]->store(file_name, strlen(file_name), cs);
        table->field[3]->store((longlong) ((key_info->flags & 
2910
                                            HA_NOSAME) ? 0 : 1), TRUE);
2911 2912
        table->field[4]->store(base_name, strlen(base_name), cs);
        table->field[5]->store(key_info->name, strlen(key_info->name), cs);
2913
        table->field[6]->store((longlong) (j+1), TRUE);
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
        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])
        {
          ha_rows records=(show_table->file->records /
                           key->rec_per_key[j]);
2929
          table->field[9]->store((longlong) records, TRUE);
2930 2931 2932 2933 2934 2935 2936
          table->field[9]->set_notnull();
        }
        if (!(key_info->flags & HA_FULLTEXT) && 
            (!key_part->field ||
             key_part->length != 
             show_table->field[key_part->fieldnr-1]->key_length()))
        {
unknown's avatar
unknown committed
2937 2938
          table->field[10]->store((longlong) key_part->length / 
                                  key_part->field->charset()->mbmaxlen);
2939 2940 2941 2942 2943 2944 2945
          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);
2946
        if (!show_table->s->keys_in_use.is_set(i))
2947 2948 2949 2950
          table->field[14]->store("disabled", 8, cs);
        else
          table->field[14]->store("", 0, cs);
        table->field[14]->set_notnull();
2951 2952
        if (schema_table_store_record(thd, table))
          DBUG_RETURN(1);
2953 2954 2955
      }
    }
  }
unknown's avatar
unknown committed
2956
  DBUG_RETURN(res);
2957 2958 2959
}


unknown's avatar
unknown committed
2960 2961 2962 2963
static int get_schema_views_record(THD *thd, struct st_table_list *tables,
				   TABLE *table, bool res,
				   const char *base_name,
				   const char *file_name)
2964 2965 2966
{
  CHARSET_INFO *cs= system_charset_info;
  DBUG_ENTER("get_schema_views_record");
unknown's avatar
unknown committed
2967
  char definer[HOSTNAME_LENGTH + USERNAME_LENGTH + 2];
unknown's avatar
unknown committed
2968
  uint definer_len;
2969 2970 2971 2972
  if (!res)
  {
    if (tables->view)
    {
2973
      restore_record(table, s->default_values);
2974
      table->field[1]->store(tables->view_db.str, tables->view_db.length, cs);
2975 2976
      table->field[2]->store(tables->view_name.str, tables->view_name.length,
                             cs);
2977
      table->field[3]->store(tables->query.str, tables->query.length, cs);
unknown's avatar
unknown committed
2978 2979 2980 2981

      if (tables->with_check != VIEW_CHECK_NONE)
      {
        if (tables->with_check == VIEW_CHECK_LOCAL)
unknown's avatar
unknown committed
2982
          table->field[4]->store(STRING_WITH_LEN("LOCAL"), cs);
unknown's avatar
unknown committed
2983
        else
unknown's avatar
unknown committed
2984
          table->field[4]->store(STRING_WITH_LEN("CASCADED"), cs);
unknown's avatar
unknown committed
2985 2986
      }
      else
unknown's avatar
unknown committed
2987
        table->field[4]->store(STRING_WITH_LEN("NONE"), cs);
unknown's avatar
unknown committed
2988

2989
      if (tables->updatable_view)
unknown's avatar
unknown committed
2990
        table->field[5]->store(STRING_WITH_LEN("YES"), cs);
2991
      else
unknown's avatar
unknown committed
2992
        table->field[5]->store(STRING_WITH_LEN("NO"), cs);
unknown's avatar
unknown committed
2993 2994 2995
      definer_len= (strxmov(definer, tables->definer.user.str, "@",
                            tables->definer.host.str, NullS) - definer);
      table->field[6]->store(definer, definer_len, cs);
unknown's avatar
unknown committed
2996 2997 2998 2999
      if (tables->view_suid)
        table->field[7]->store(STRING_WITH_LEN("DEFINER"), cs);
      else
        table->field[7]->store(STRING_WITH_LEN("INVOKER"), cs);
3000
      DBUG_RETURN(schema_table_store_record(thd, table));
3001 3002
    }
  }
3003 3004 3005 3006 3007 3008 3009 3010
  else
  {
    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);
3011 3012 3013
}


3014 3015 3016
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)
3017 3018
{
  CHARSET_INFO *cs= system_charset_info;
3019
  restore_record(table, s->default_values);
3020 3021 3022 3023 3024
  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);
3025
  return schema_table_store_record(thd, table);
3026 3027 3028
}


unknown's avatar
unknown committed
3029
static int get_schema_constraints_record(THD *thd, struct st_table_list *tables,
unknown's avatar
unknown committed
3030 3031 3032
					 TABLE *table, bool res,
					 const char *base_name,
					 const char *file_name)
3033
{
unknown's avatar
unknown committed
3034
  DBUG_ENTER("get_schema_constraints_record");
3035 3036 3037 3038 3039 3040 3041 3042 3043
  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)
3044 3045 3046 3047
  {
    List<FOREIGN_KEY_INFO> f_key_list;
    TABLE *show_table= tables->table;
    KEY *key_info=show_table->key_info;
3048
    uint primary_key= show_table->s->primary_key;
3049 3050 3051
    show_table->file->info(HA_STATUS_VARIABLE | 
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);
3052
    for (uint i=0 ; i < show_table->s->keys ; i++, key_info++)
3053 3054
    {
      if (i != primary_key && !(key_info->flags & HA_NOSAME))
3055 3056
        continue;

3057
      if (i == primary_key && !strcmp(key_info->name, primary_key_name))
3058 3059 3060 3061 3062
      {
        if (store_constraints(thd, table, base_name, file_name, key_info->name,
                              strlen(key_info->name), "PRIMARY KEY", 11))
          DBUG_RETURN(1);
      }
3063
      else if (key_info->flags & HA_NOSAME)
3064 3065 3066 3067 3068
      {
        if (store_constraints(thd, table, base_name, file_name, key_info->name,
                              strlen(key_info->name), "UNIQUE", 6))
          DBUG_RETURN(1);
      }
3069 3070 3071 3072 3073 3074 3075
    }

    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++))
    {
3076 3077 3078 3079 3080
      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);
3081 3082
    }
  }
unknown's avatar
unknown committed
3083
  DBUG_RETURN(res);
3084 3085 3086
}


3087 3088 3089 3090
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,
3091 3092
                          LEX_STRING *trigger_stmt,
                          ulong sql_mode)
3093 3094
{
  CHARSET_INFO *cs= system_charset_info;
3095 3096 3097
  byte *sql_mode_str;
  ulong sql_mode_len;

3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
  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);
  table->field[10]->store("ROW", 3, cs);
  table->field[11]->store(trg_action_time_type_names[timing].str,
                          trg_action_time_type_names[timing].length, cs);
  table->field[14]->store("OLD", 3, cs);
  table->field[15]->store("NEW", 3, cs);
3111 3112 3113 3114 3115

  sql_mode_str=
    sys_var_thd_sql_mode::symbolic_mode_representation(thd,
                                                       sql_mode,
                                                       &sql_mode_len);
unknown's avatar
unknown committed
3116
  table->field[17]->store((const char*)sql_mode_str, sql_mode_len, cs);
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
  return schema_table_store_record(thd, table);
}


static int get_schema_triggers_record(THD *thd, struct st_table_list *tables,
				      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;
3149
        ulong sql_mode;
3150 3151
        if (triggers->get_trigger_info(thd, (enum trg_event_type) event,
                                       (enum trg_action_time_type)timing,
3152 3153
                                       &trigger_name, &trigger_stmt,
                                       &sql_mode))
3154 3155 3156
          continue;
        if (store_trigger(thd, table, base_name, file_name, &trigger_name,
                         (enum trg_event_type) event,
3157 3158
                         (enum trg_action_time_type) timing, &trigger_stmt,
                         sql_mode))
3159 3160 3161 3162 3163 3164 3165 3166
          DBUG_RETURN(1);
      }
    }
  }
  DBUG_RETURN(0);
}


3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
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);
3177
  table->field[7]->store((longlong) idx, TRUE);
3178 3179 3180
}


unknown's avatar
unknown committed
3181 3182 3183 3184 3185
static int get_schema_key_column_usage_record(THD *thd,
					      struct st_table_list *tables,
					      TABLE *table, bool res,
					      const char *base_name,
					      const char *file_name)
3186 3187
{
  DBUG_ENTER("get_schema_key_column_usage_record");
3188 3189 3190 3191 3192 3193 3194 3195 3196
  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)
3197 3198 3199 3200
  {
    List<FOREIGN_KEY_INFO> f_key_list;
    TABLE *show_table= tables->table;
    KEY *key_info=show_table->key_info;
3201
    uint primary_key= show_table->s->primary_key;
3202 3203 3204
    show_table->file->info(HA_STATUS_VARIABLE | 
                           HA_STATUS_NO_LOCK |
                           HA_STATUS_TIME);
3205
    for (uint i=0 ; i < show_table->s->keys ; i++, key_info++)
3206 3207
    {
      if (i != primary_key && !(key_info->flags & HA_NOSAME))
unknown's avatar
unknown committed
3208
        continue;
3209 3210 3211 3212 3213 3214 3215
      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++;
3216
          restore_record(table, s->default_values);
3217 3218 3219 3220 3221 3222
          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);
3223 3224
          if (schema_table_store_record(thd, table))
            DBUG_RETURN(1);
3225 3226 3227 3228 3229 3230 3231 3232 3233
        }
      }
    }

    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++))
    {
3234
      LEX_STRING *f_info;
3235
      LEX_STRING *r_info;
3236 3237 3238 3239 3240
      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++))
      {
3241
        r_info= it1++;
3242
        f_idx++;
3243
        restore_record(table, s->default_values);
3244 3245 3246 3247 3248
        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);
3249
        table->field[8]->store((longlong) f_idx, TRUE);
3250
        table->field[8]->set_notnull();
3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
        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();
3262 3263
        if (schema_table_store_record(thd, table))
          DBUG_RETURN(1);
3264 3265 3266
      }
    }
  }
unknown's avatar
unknown committed
3267
  DBUG_RETURN(res);
3268 3269 3270
}


3271 3272 3273 3274 3275 3276 3277
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;
3278 3279
  if (!(open_list=list_open_tables(thd,thd->lex->select_lex.db, wild))
            && thd->is_fatal_error)
3280 3281 3282 3283
    DBUG_RETURN(1);

  for (; open_list ; open_list=open_list->next)
  {
3284
    restore_record(table, s->default_values);
3285 3286
    table->field[0]->store(open_list->db, strlen(open_list->db), cs);
    table->field[1]->store(open_list->table, strlen(open_list->table), cs);
3287 3288
    table->field[2]->store((longlong) open_list->in_use, TRUE);
    table->field[3]->store((longlong) open_list->locked, TRUE);
3289 3290
    if (schema_table_store_record(thd, table))
      DBUG_RETURN(1);
3291 3292 3293 3294 3295 3296 3297 3298
  }
  DBUG_RETURN(0);
}


int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond)
{
  DBUG_ENTER("fill_variables");
3299
  int res= 0;
3300 3301
  LEX *lex= thd->lex;
  const char *wild= lex->wild ? lex->wild->ptr() : NullS;
3302 3303 3304 3305
  pthread_mutex_lock(&LOCK_global_system_variables);
  res= show_status_array(thd, wild, init_vars, 
                         lex->option_type, 0, "", tables->table);
  pthread_mutex_unlock(&LOCK_global_system_variables);
3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
  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;
  STATUS_VAR tmp;
3317 3318
  ha_update_statistics();                    /* Export engines statistics */
  pthread_mutex_lock(&LOCK_status);
3319 3320
  if (lex->option_type == OPT_GLOBAL)
    calc_sum_of_all_status(&tmp);
3321 3322 3323 3324
  res= show_status_array(thd, wild, status_vars, OPT_GLOBAL,
                         (lex->option_type == OPT_GLOBAL ? 
                          &tmp: &thd->status_var), "",tables->table);
  pthread_mutex_unlock(&LOCK_status);
3325 3326 3327 3328
  DBUG_RETURN(res);
}


3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
/*
  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)
{
  ST_SCHEMA_TABLE *schema_table= schema_tables;
3345
  for (; schema_table->table_name; schema_table++)
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
  {
    if (!my_strcasecmp(system_charset_info,
                       schema_table->table_name,
                       table_name))
      return schema_table;
  }
  return 0;
}


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
*/

3375
TABLE *create_schema_table(THD *thd, TABLE_LIST *table_list)
3376 3377 3378 3379 3380
{
  int field_count= 0;
  Item *item;
  TABLE *table;
  List<Item> field_list;
3381
  ST_SCHEMA_TABLE *schema_table= table_list->schema_table;
3382
  ST_FIELD_INFO *fields_info= schema_table->fields_info;
unknown's avatar
unknown committed
3383
  CHARSET_INFO *cs= system_charset_info;
3384 3385
  DBUG_ENTER("create_schema_table");

3386
  for (; fields_info->field_name; fields_info++)
3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
  {
    switch (fields_info->field_type) {
    case MYSQL_TYPE_LONG:
      if (!(item= new Item_int(fields_info->field_name,
                               fields_info->value,
                               fields_info->field_length)))
      {
        DBUG_RETURN(0);
      }
      break;
    case MYSQL_TYPE_TIMESTAMP:
      if (!(item=new Item_datetime(fields_info->field_name)))
      {
        DBUG_RETURN(0);
      }
      break;
    default:
3404 3405
      /* this should be changed when Item_empty_string is fixed(in 4.1) */
      if (!(item= new Item_empty_string("", 0, cs)))
3406 3407 3408
      {
        DBUG_RETURN(0);
      }
3409
      item->max_length= fields_info->field_length * cs->mbmaxlen;
unknown's avatar
unknown committed
3410 3411
      item->set_name(fields_info->field_name,
                     strlen(fields_info->field_name), cs);
3412 3413 3414 3415 3416 3417 3418 3419 3420
      break;
    }
    field_list.push_back(item);
    item->maybe_null= fields_info->maybe_null;
    field_count++;
  }
  TMP_TABLE_PARAM *tmp_table_param =
    (TMP_TABLE_PARAM*) (thd->calloc(sizeof(TMP_TABLE_PARAM)));
  tmp_table_param->init();
unknown's avatar
unknown committed
3421
  tmp_table_param->table_charset= cs;
3422
  tmp_table_param->field_count= field_count;
3423
  tmp_table_param->schema_table= 1;
3424 3425 3426 3427
  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 |
3428
                                 TMP_TABLE_ALL_COLUMNS),
unknown's avatar
unknown committed
3429
                                HA_POS_ERROR, table_list->alias)))
3430
    DBUG_RETURN(0);
3431
  table_list->schema_table_param= tmp_table_param;
3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
  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
   -1	errror
    0	success
*/

int make_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
  ST_FIELD_INFO *field_info= schema_table->fields_info;
3454
  Name_resolution_context *context= &thd->lex->select_lex.context;
3455
  for (; field_info->field_name; field_info++)
3456 3457 3458
  {
    if (field_info->old_name)
    {
3459 3460
      Item_field *field= new Item_field(context,
                                        NullS, NullS, field_info->field_name);
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
      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;
3480
  Name_resolution_context *context= &sel->context;
3481 3482 3483 3484 3485

  if (!sel->item_list.elements)
  {
    ST_FIELD_INFO *field_info= &schema_table->fields_info[1];
    String buffer(tmp,sizeof(tmp), system_charset_info);
3486 3487
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508
    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())
    {
      buffer.append(" (");
      buffer.append(lex->wild->ptr());
      buffer.append(")");
    }
    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;
3509
  Name_resolution_context *context= &lex->select_lex.context;
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520

  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())
  {
    buffer.append(" (");
    buffer.append(lex->wild->ptr());
    buffer.append(")");
  }
3521 3522
  Item_field *field= new Item_field(context,
                                    NullS, NullS, field_info->field_name);
3523 3524 3525 3526 3527 3528 3529
  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];
3530
    field= new Item_field(context, NullS, NullS, field_info->field_name);
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541
    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)
{
3542 3543 3544
  int fields_arr[]= {3, 14, 13, 6, 15, 5, 16, 17, 18, -1};
  int *field_num= fields_arr;
  ST_FIELD_INFO *field_info;
3545 3546
  Name_resolution_context *context= &thd->lex->select_lex.context;

3547
  for (; *field_num >= 0; field_num++)
3548
  {
3549 3550 3551 3552 3553
    field_info= &schema_table->fields_info[*field_num];
    if (!thd->lex->verbose && (*field_num == 13 ||
                               *field_num == 17 ||
                               *field_num == 18))
      continue;
3554 3555
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
3556
    if (field)
3557
    {
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
      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;
}


3569 3570 3571 3572 3573
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;
3574 3575
  Name_resolution_context *context= &thd->lex->select_lex.context;

3576 3577 3578
  for (; *field_num >= 0; field_num++)
  {
    field_info= &schema_table->fields_info[*field_num];
3579 3580
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
    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;
}


3594 3595 3596 3597 3598
int make_proc_old_format(THD *thd, ST_SCHEMA_TABLE *schema_table)
{
  int fields_arr[]= {2, 3, 4, 19, 16, 15, 14, 18, -1};
  int *field_num= fields_arr;
  ST_FIELD_INFO *field_info;
3599 3600
  Name_resolution_context *context= &thd->lex->select_lex.context;

3601 3602 3603
  for (; *field_num >= 0; field_num++)
  {
    field_info= &schema_table->fields_info[*field_num];
3604 3605
    Item_field *field= new Item_field(context,
                                      NullS, NullS, field_info->field_name);
3606 3607 3608 3609 3610 3611 3612
    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;
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
    }
  }
  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");
3637
  if (!(table= table_list->schema_table->create_table(thd, table_list)))
3638 3639 3640
  {
    DBUG_RETURN(1);
  }
3641
  table->s->tmp_table= SYSTEM_TMP_TABLE;
3642
  table->grant.privilege= SELECT_ACL;
3643 3644 3645 3646 3647 3648 3649
  /*
    This test is necessary to make
    case insensitive file systems +
    upper case table names(information schema tables) +
    views
    working correctly
  */
3650 3651 3652 3653
  if (table_list->schema_table_name)
    table->alias_name_used= my_strcasecmp(table_alias_charset,
                                          table_list->schema_table_name,
                                          table_list->alias);
3654
  table_list->table_name= (char*) table->s->table_name;
3655
  table_list->table_name_length= strlen(table->s->table_name);
3656 3657 3658 3659
  table_list->table= table;
  table->next= thd->derived_tables;
  thd->derived_tables= table;
  table_list->select_lex->options |= OPTION_SCHEMA_TABLE;
3660
  lex->safe_to_cache_query= 0;
3661 3662 3663 3664 3665

  if (table_list->schema_table_reformed) // show command
  {
    SELECT_LEX *sel= lex->current_select;
    Item *item;
unknown's avatar
unknown committed
3666
    Field_translator *transl, *org_transl;
3667 3668 3669

    if (table_list->field_translation)
    {
3670
      Field_translator *end= table_list->field_translation_end;
3671 3672 3673
      for (transl= table_list->field_translation; transl < end; transl++)
      {
        if (!transl->item->fixed &&
3674
            transl->item->fix_fields(thd, &transl->item))
3675 3676 3677 3678 3679 3680
          DBUG_RETURN(1);
      }
      DBUG_RETURN(0);
    }
    List_iterator_fast<Item> it(sel->item_list);
    if (!(transl=
unknown's avatar
unknown committed
3681
          (Field_translator*)(thd->stmt_arena->
3682 3683 3684 3685 3686
                              alloc(sel->item_list.elements *
                                    sizeof(Field_translator)))))
    {
      DBUG_RETURN(1);
    }
unknown's avatar
unknown committed
3687
    for (org_transl= transl; (item= it++); transl++)
3688
    {
unknown's avatar
unknown committed
3689 3690 3691 3692
      transl->item= item;
      transl->name= item->name;
      if (!item->fixed && item->fix_fields(thd, &transl->item))
      {
3693
        DBUG_RETURN(1);
unknown's avatar
unknown committed
3694
      }
3695
    }
unknown's avatar
unknown committed
3696 3697
    table_list->field_translation= org_transl;
    table_list->field_translation_end= transl;
3698 3699
  }

3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
  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");
3724
  /*
3725 3726 3727 3728 3729 3730 3731
     We have to make non const db_name & table_name
     because of lower_case_table_names
  */
  make_lex_string(thd, &db, information_schema_name.str,
                  information_schema_name.length, 0);
  make_lex_string(thd, &table, schema_table->table_name,
                  strlen(schema_table->table_name), 0);
3732
  if (schema_table->old_format(thd, schema_table) ||   /* Handle old syntax */
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
      !sel->add_table_to_list(thd, new Table_ident(thd, db, table, 0),
                              0, 0, TL_READ, (List<String> *) 0,
                              (List<String> *) 0))
  {
    DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}


/*
3744
  Fill temporary schema tables before SELECT
3745 3746 3747 3748 3749 3750

  SYNOPSIS
    get_schema_tables_result()
    join  join which use schema tables

  RETURN
unknown's avatar
unknown committed
3751 3752
    FALSE success
    TRUE  error
3753 3754
*/

unknown's avatar
unknown committed
3755
bool get_schema_tables_result(JOIN *join)
3756 3757 3758
{
  JOIN_TAB *tmp_join_tab= join->join_tab+join->tables;
  THD *thd= join->thd;
unknown's avatar
unknown committed
3759 3760
  LEX *lex= thd->lex;
  bool result= 0;
3761 3762 3763
  DBUG_ENTER("get_schema_tables_result");

  thd->no_warnings_for_error= 1;
3764 3765 3766 3767
  for (JOIN_TAB *tab= join->join_tab; tab < tmp_join_tab; tab++)
  {  
    if (!tab->table || !tab->table->pos_in_table_list)
      break;
unknown's avatar
unknown committed
3768

unknown's avatar
unknown committed
3769
    TABLE_LIST *table_list= tab->table->pos_in_table_list;
unknown's avatar
unknown committed
3770
    if (table_list->schema_table && thd->fill_derived_tables())
3771
    {
unknown's avatar
unknown committed
3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
      if (&lex->unit != lex->current_select->master_unit()) // is subselect
      {
        table_list->table->file->extra(HA_EXTRA_RESET_STATE);
        table_list->table->file->delete_all_rows();
        free_io_cache(table_list->table);
        filesort_free_buffers(table_list->table);
      }
      else
        table_list->table->file->records= 0;

3782 3783
      if (table_list->schema_table->fill_table(thd, table_list,
                                               tab->select_cond))
unknown's avatar
unknown committed
3784
        result= 1;
3785 3786
    }
  }
3787
  thd->no_warnings_for_error= 0;
unknown's avatar
unknown committed
3788
  DBUG_RETURN(result);
3789 3790 3791 3792 3793
}


ST_FIELD_INFO schema_fields_info[]=
{
unknown's avatar
unknown committed
3794 3795
  {"CATALOG_NAME", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"SCHEMA_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Database"},
3796
  {"DEFAULT_CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
3797
  {"DEFAULT_COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
3798
  {"SQL_PATH", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
unknown's avatar
unknown committed
3799
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3800 3801 3802 3803 3804
};


ST_FIELD_INFO tables_fields_info[]=
{
unknown's avatar
unknown committed
3805 3806 3807 3808 3809 3810 3811
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA",NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Name"},
  {"TABLE_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ENGINE", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, "Engine"},
  {"VERSION", 21 , MYSQL_TYPE_LONG, 0, 1, "Version"},
  {"ROW_FORMAT", 10, MYSQL_TYPE_STRING, 0, 1, "Row_format"},
3812
  {"TABLE_ROWS", 21 , MYSQL_TYPE_LONG, 0, 1, "Rows"},
unknown's avatar
unknown committed
3813 3814 3815 3816 3817 3818 3819 3820 3821
  {"AVG_ROW_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, "Avg_row_length"},
  {"DATA_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, "Data_length"},
  {"MAX_DATA_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, "Max_data_length"},
  {"INDEX_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, "Index_length"},
  {"DATA_FREE", 21 , MYSQL_TYPE_LONG, 0, 1, "Data_free"},
  {"AUTO_INCREMENT", 21 , MYSQL_TYPE_LONG, 0, 1, "Auto_increment"},
  {"CREATE_TIME", 0, MYSQL_TYPE_TIMESTAMP, 0, 1, "Create_time"},
  {"UPDATE_TIME", 0, MYSQL_TYPE_TIMESTAMP, 0, 1, "Update_time"},
  {"CHECK_TIME", 0, MYSQL_TYPE_TIMESTAMP, 0, 1, "Check_time"},
3822
  {"TABLE_COLLATION", 64, MYSQL_TYPE_STRING, 0, 1, "Collation"},
unknown's avatar
unknown committed
3823 3824
  {"CHECKSUM", 21 , MYSQL_TYPE_LONG, 0, 1, "Checksum"},
  {"CREATE_OPTIONS", 255, MYSQL_TYPE_STRING, 0, 1, "Create_options"},
3825
  {"TABLE_COMMENT", 80, MYSQL_TYPE_STRING, 0, 0, "Comment"},
unknown's avatar
unknown committed
3826
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3827 3828 3829 3830 3831
};


ST_FIELD_INFO columns_fields_info[]=
{
unknown's avatar
unknown committed
3832 3833 3834 3835 3836
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLUMN_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Field"},
  {"ORDINAL_POSITION", 21 , MYSQL_TYPE_LONG, 0, 0, 0},
3837 3838
  {"COLUMN_DEFAULT", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, "Default"},
  {"IS_NULLABLE", 3, MYSQL_TYPE_STRING, 0, 0, "Null"},
3839
  {"DATA_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
3840 3841
  {"CHARACTER_MAXIMUM_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0},
  {"CHARACTER_OCTET_LENGTH", 21 , MYSQL_TYPE_LONG, 0, 1, 0},
3842 3843
  {"NUMERIC_PRECISION", 21 , MYSQL_TYPE_LONG, 0, 1, 0},
  {"NUMERIC_SCALE", 21 , MYSQL_TYPE_LONG, 0, 1, 0},
3844 3845
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 1, 0},
  {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 1, "Collation"},
unknown's avatar
unknown committed
3846
  {"COLUMN_TYPE", 65535, MYSQL_TYPE_STRING, 0, 0, "Type"},
3847
  {"COLUMN_KEY", 3, MYSQL_TYPE_STRING, 0, 0, "Key"},
unknown's avatar
unknown committed
3848 3849
  {"EXTRA", 20, MYSQL_TYPE_STRING, 0, 0, "Extra"},
  {"PRIVILEGES", 80, MYSQL_TYPE_STRING, 0, 0, "Privileges"},
3850
  {"COLUMN_COMMENT", 255, MYSQL_TYPE_STRING, 0, 0, "Comment"},
unknown's avatar
unknown committed
3851
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3852 3853 3854 3855 3856
};


ST_FIELD_INFO charsets_fields_info[]=
{
3857 3858
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Charset"},
  {"DEFAULT_COLLATE_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Default collation"},
3859
  {"DESCRIPTION", 60, MYSQL_TYPE_STRING, 0, 0, "Description"},
3860
  {"MAXLEN", 3 ,MYSQL_TYPE_LONG, 0, 0, "Maxlen"},
unknown's avatar
unknown committed
3861
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3862 3863 3864 3865 3866
};


ST_FIELD_INFO collation_fields_info[]=
{
3867 3868
  {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Collation"},
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, "Charset"},
3869
  {"ID", 11, MYSQL_TYPE_LONG, 0, 0, "Id"},
3870 3871
  {"IS_DEFAULT", 3, MYSQL_TYPE_STRING, 0, 0, "Default"},
  {"IS_COMPILED", 3, MYSQL_TYPE_STRING, 0, 0, "Compiled"},
3872
  {"SORTLEN", 3 ,MYSQL_TYPE_LONG, 0, 0, "Sortlen"},
unknown's avatar
unknown committed
3873
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3874 3875 3876 3877 3878
};


ST_FIELD_INFO coll_charset_app_fields_info[]=
{
3879 3880
  {"COLLATION_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CHARACTER_SET_NAME", 64, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3881
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3882 3883 3884 3885 3886
};


ST_FIELD_INFO proc_fields_info[]=
{
unknown's avatar
unknown committed
3887 3888 3889 3890 3891
  {"SPECIFIC_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ROUTINE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"ROUTINE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Db"},
  {"ROUTINE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Name"},
  {"ROUTINE_TYPE", 9, MYSQL_TYPE_STRING, 0, 0, "Type"},
3892 3893
  {"DTD_IDENTIFIER", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"ROUTINE_BODY", 8, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3894
  {"ROUTINE_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
3895 3896
  {"EXTERNAL_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"EXTERNAL_LANGUAGE", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
3897
  {"PARAMETER_STYLE", 8, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3898 3899 3900 3901
  {"IS_DETERMINISTIC", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {"SQL_DATA_ACCESS", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"SQL_PATH", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, "Security_type"},
3902 3903
  {"CREATED", 0, MYSQL_TYPE_TIMESTAMP, 0, 0, "Created"},
  {"LAST_ALTERED", 0, MYSQL_TYPE_TIMESTAMP, 0, 0, "Modified"},
unknown's avatar
unknown committed
3904
  {"SQL_MODE", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3905
  {"ROUTINE_COMMENT", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Comment"},
3906
  {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, "Definer"},
unknown's avatar
unknown committed
3907
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3908 3909 3910 3911 3912
};


ST_FIELD_INFO stat_fields_info[]=
{
unknown's avatar
unknown committed
3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table"},
  {"NON_UNIQUE", 1, MYSQL_TYPE_LONG, 0, 0, "Non_unique"},
  {"INDEX_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"INDEX_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Key_name"},
  {"SEQ_IN_INDEX", 2, MYSQL_TYPE_LONG, 0, 0, "Seq_in_index"},
  {"COLUMN_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Column_name"},
  {"COLLATION", 1, MYSQL_TYPE_STRING, 0, 1, "Collation"},
  {"CARDINALITY", 21, MYSQL_TYPE_LONG, 0, 1, "Cardinality"},
  {"SUB_PART", 3, MYSQL_TYPE_LONG, 0, 1, "Sub_part"},
  {"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}
3929 3930 3931 3932 3933
};


ST_FIELD_INFO view_fields_info[]=
{
unknown's avatar
unknown committed
3934 3935 3936 3937
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"VIEW_DEFINITION", 65535, MYSQL_TYPE_STRING, 0, 0, 0},
3938
  {"CHECK_OPTION", 8, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3939
  {"IS_UPDATABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3940 3941
  {"DEFINER", 77, MYSQL_TYPE_STRING, 0, 0, 0},
  {"SECURITY_TYPE", 7, MYSQL_TYPE_STRING, 0, 0, 0},
unknown's avatar
unknown committed
3942
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3943 3944 3945 3946 3947
};


ST_FIELD_INFO user_privileges_fields_info[]=
{
unknown's avatar
unknown committed
3948 3949 3950 3951 3952
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"PRIVILEGE_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3953 3954 3955 3956 3957
};


ST_FIELD_INFO schema_privileges_fields_info[]=
{
unknown's avatar
unknown committed
3958 3959 3960 3961 3962 3963
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PRIVILEGE_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3964 3965 3966 3967 3968
};


ST_FIELD_INFO table_privileges_fields_info[]=
{
unknown's avatar
unknown committed
3969 3970 3971 3972 3973 3974 3975
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PRIVILEGE_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3976 3977 3978 3979 3980
};


ST_FIELD_INFO column_privileges_fields_info[]=
{
unknown's avatar
unknown committed
3981 3982 3983 3984 3985 3986 3987 3988
  {"GRANTEE", 81, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLUMN_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"PRIVILEGE_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"IS_GRANTABLE", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
3989 3990 3991 3992 3993
};


ST_FIELD_INFO table_constraints_fields_info[]=
{
unknown's avatar
unknown committed
3994 3995 3996 3997 3998 3999 4000
  {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"CONSTRAINT_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
4001 4002 4003 4004 4005
};


ST_FIELD_INFO key_column_usage_fields_info[]=
{
unknown's avatar
unknown committed
4006 4007 4008
  {"CONSTRAINT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"CONSTRAINT_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CONSTRAINT_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
4009
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
unknown's avatar
unknown committed
4010 4011 4012 4013
  {"TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"COLUMN_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ORDINAL_POSITION", 10 ,MYSQL_TYPE_LONG, 0, 0, 0},
4014
  {"POSITION_IN_UNIQUE_CONSTRAINT", 10 ,MYSQL_TYPE_LONG, 0, 1, 0},
4015 4016 4017
  {"REFERENCED_TABLE_SCHEMA", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"REFERENCED_TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"REFERENCED_COLUMN_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
unknown's avatar
unknown committed
4018
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
4019 4020 4021 4022 4023
};


ST_FIELD_INFO table_names_fields_info[]=
{
unknown's avatar
unknown committed
4024 4025 4026 4027 4028
  {"TABLE_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TABLE_SCHEMA",NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TABLE_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Tables_in_"},
  {"TABLE_TYPE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table_type"},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
4029 4030 4031
};


4032 4033 4034 4035 4036 4037 4038 4039 4040 4041
ST_FIELD_INFO open_tables_fields_info[]=
{
  {"Database", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Database"},
  {"Table",NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table"},
  {"In_use", 1, MYSQL_TYPE_LONG, 0, 0, "In_use"},
  {"Name_locked", 4, MYSQL_TYPE_LONG, 0, 0, "Name_locked"},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060
ST_FIELD_INFO triggers_fields_info[]=
{
  {"TRIGGER_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"TRIGGER_SCHEMA",NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"TRIGGER_NAME", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Trigger"},
  {"EVENT_MANIPULATION", 6, MYSQL_TYPE_STRING, 0, 0, "Event"},
  {"EVENT_OBJECT_CATALOG", FN_REFLEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"EVENT_OBJECT_SCHEMA",NAME_LEN, MYSQL_TYPE_STRING, 0, 0, 0},
  {"EVENT_OBJECT_TABLE", NAME_LEN, MYSQL_TYPE_STRING, 0, 0, "Table"},
  {"ACTION_ORDER", 4, MYSQL_TYPE_LONG, 0, 0, 0},
  {"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"},
  {"ACTION_REFERENCE_OLD_TABLE", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"ACTION_REFERENCE_NEW_TABLE", NAME_LEN, MYSQL_TYPE_STRING, 0, 1, 0},
  {"ACTION_REFERENCE_OLD_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {"ACTION_REFERENCE_NEW_ROW", 3, MYSQL_TYPE_STRING, 0, 0, 0},
  {"CREATED", 0, MYSQL_TYPE_TIMESTAMP, 0, 1, "Created"},
4061
  {"SQL_MODE", 65535, MYSQL_TYPE_STRING, 0, 0, "sql_mode"},
4062 4063 4064 4065
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


4066 4067 4068 4069 4070 4071 4072 4073
ST_FIELD_INFO variables_fields_info[]=
{
  {"Variable_name", 80, MYSQL_TYPE_STRING, 0, 0, "Variable_name"},
  {"Value", 255, MYSQL_TYPE_STRING, 0, 0, "Value"},
  {0, 0, MYSQL_TYPE_STRING, 0, 0, 0}
};


4074 4075 4076 4077 4078 4079 4080
/*
  Description of ST_FIELD_INFO in table.h
*/

ST_SCHEMA_TABLE schema_tables[]=
{
  {"CHARACTER_SETS", charsets_fields_info, create_schema_table, 
4081
   fill_schema_charsets, make_character_sets_old_format, 0, -1, -1, 0},
4082
  {"COLLATIONS", collation_fields_info, create_schema_table, 
4083
   fill_schema_collation, make_old_format, 0, -1, -1, 0},
4084
  {"COLLATION_CHARACTER_SET_APPLICABILITY", coll_charset_app_fields_info,
4085
   create_schema_table, fill_schema_coll_charset_app, 0, 0, -1, -1, 0},
4086 4087
  {"COLUMNS", columns_fields_info, create_schema_table, 
   get_all_tables, make_columns_old_format, get_schema_column_record, 1, 2, 0},
4088
  {"COLUMN_PRIVILEGES", column_privileges_fields_info, create_schema_table,
4089
    fill_schema_column_privileges, 0, 0, -1, -1, 0},
4090
  {"KEY_COLUMN_USAGE", key_column_usage_fields_info, create_schema_table,
4091
    get_all_tables, 0, get_schema_key_column_usage_record, 4, 5, 0},
4092 4093
  {"OPEN_TABLES", open_tables_fields_info, create_schema_table,
   fill_open_tables, make_old_format, 0, -1, -1, 1},
4094 4095 4096 4097 4098 4099 4100 4101
  {"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},
  {"STATISTICS", stat_fields_info, create_schema_table, 
    get_all_tables, make_old_format, get_schema_stat_record, 1, 2, 0},
4102 4103
  {"STATUS", variables_fields_info, create_schema_table, fill_status, 
   make_old_format, 0, -1, -1, 1},
4104 4105 4106 4107 4108 4109 4110 4111
  {"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},
4112
  {"TRIGGERS", triggers_fields_info, create_schema_table,
4113
   get_all_tables, make_old_format, get_schema_triggers_record, 5, 6, 0},
4114 4115
  {"VARIABLES", variables_fields_info, create_schema_table, fill_variables,
   make_old_format, 0, -1, -1, 1},
4116 4117 4118 4119
  {"VIEWS", view_fields_info, create_schema_table, 
    get_all_tables, 0, get_schema_views_record, 1, 2, 0},
  {"USER_PRIVILEGES", user_privileges_fields_info, create_schema_table, 
    fill_schema_user_privileges, 0, 0, -1, -1, 0},
4120
  {0, 0, 0, 0, 0, 0, 0, 0, 0}
4121 4122 4123
};


4124
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
4125
template class List_iterator_fast<char>;
unknown's avatar
unknown committed
4126 4127
template class List<char>;
#endif