~drizzle-trunk/drizzle/development

1063.4.5 by Padraig O'Sullivan
Fixed a stupid mistake I made in the innodb handler. Also reverted back to
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
520.4.14 by Monty Taylor
Removed korr.h and tztime.h from common_includes. Also removed the HAVE_DTRACE block and stuck it in autoconf.
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 *
4
 *  Copyright (C) 2008 Sun Microsystems
5
 *
6
 *  This program is free software; you can redistribute it and/or modify
7
 *  it under the terms of the GNU General Public License as published by
8
 *  the Free Software Foundation; version 2 of the License.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, write to the Free Software
17
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
 */
1 by brian
clean slate
19
20
21
/* Function with list databases, tables or fields */
1241.9.36 by Monty Taylor
ZOMG. I deleted drizzled/server_includes.h.
22
#include "config.h"
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
23
#include <drizzled/sql_select.h>
575.4.7 by Monty Taylor
More header cleanup.
24
#include <drizzled/show.h>
538 by Monty Taylor
Moved gettext.h into drizzled in anticipation of the new client lib.
25
#include <drizzled/gettext.h>
492.1.8 by Monty Taylor
Replaced some int10_to_str with to_string.
26
#include <drizzled/util/convert.h>
550 by Monty Taylor
Moved error.h into just the files that need it.
27
#include <drizzled/error.h>
520.4.14 by Monty Taylor
Removed korr.h and tztime.h from common_includes. Also removed the HAVE_DTRACE block and stuck it in autoconf.
28
#include <drizzled/tztime.h>
520.6.7 by Monty Taylor
Moved a bunch of crap out of common_includes.
29
#include <drizzled/data_home.h>
642.1.63 by Lee
more header file cleanup
30
#include <drizzled/item/blob.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
31
#include <drizzled/item/cmpfunc.h>
642.1.17 by Lee
header file clean up
32
#include <drizzled/item/return_int.h>
642.1.23 by Lee
more header file cleanup
33
#include <drizzled/item/empty_string.h>
642.1.18 by Lee
header file clean up
34
#include <drizzled/item/return_date_time.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
35
#include <drizzled/sql_base.h>
36
#include <drizzled/db.h>
584.5.1 by Monty Taylor
Removed field includes from field.h.
37
#include <drizzled/field/timestamp.h>
670.1.1 by Monty Taylor
Renamed fdecimal.* to decimal.*. Let's see how many things we can break!
38
#include <drizzled/field/decimal.h>
670.2.4 by Monty Taylor
Removed more stuff from the headers.
39
#include <drizzled/lock.h>
675 by Brian Aker
Cleanup around item includes.
40
#include <drizzled/item/return_date_time.h>
41
#include <drizzled/item/empty_string.h>
1110.1.5 by Monty Taylor
Renamed PluginRegistry to plugin::Registry.
42
#include "drizzled/plugin/registry.h"
1241.9.17 by Monty Taylor
Removed more bits from server_includes.
43
#include "drizzled/session_list.h"
1130.1.7 by Monty Taylor
Renamed plugin::InfoSchema to plugin::InfoSchemaTable as per Jay.
44
#include <drizzled/plugin/info_schema_table.h>
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
45
#include <drizzled/message/schema.pb.h>
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
46
#include <drizzled/plugin/client.h>
1241.9.44 by Monty Taylor
Made magic with cached_directory.
47
#include <drizzled/cached_directory.h>
1241.9.23 by Monty Taylor
Removed sql_table.h from server_includes.h.
48
#include "drizzled/sql_table.h"
1241.9.28 by Monty Taylor
Removed global_charset_info.h from server_includes.h
49
#include "drizzled/global_charset_info.h"
1241.9.31 by Monty Taylor
Moved global pthread variables into their own header.
50
#include "drizzled/pthread_globals.h"
1241.9.64 by Monty Taylor
Moved remaining non-public portions of mysys and mystrings to drizzled/internal.
51
#include "drizzled/internal/m_string.h"
52
#include "drizzled/internal/my_sys.h"
1241.9.28 by Monty Taylor
Removed global_charset_info.h from server_includes.h
53
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
54
#include <sys/stat.h>
584.1.13 by Monty Taylor
Split out a little more code. Removed table_list.h from common_includes.
55
56
#include <string>
629.4.1 by Monty Taylor
First step in support size_t sys_var stuff.
57
#include <iostream>
58
#include <sstream>
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
59
#include <vector>
60
#include <algorithm>
629.4.1 by Monty Taylor
First step in support size_t sys_var stuff.
61
62
using namespace std;
971.3.65 by Eric Day
Namespace cleanup for Protocol and Listen.
63
using namespace drizzled;
1 by brian
clean slate
64
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
65
inline const char *
66
str_or_nil(const char *str)
67
{
68
  return str ? str : "<nil>";
69
}
1 by brian
clean slate
70
1014.3.4 by Brian Aker
Remove dead session calls.
71
static void store_key_options(String *packet, Table *table, KEY *key_info);
1 by brian
clean slate
72
73
74
1273.13.38 by Brian Aker
Add in new show work.
75
int wild_case_compare(const CHARSET_INFO * const cs, const char *str, const char *wildstr)
1 by brian
clean slate
76
{
77
  register int flag;
78
  while (*wildstr)
79
  {
80
    while (*wildstr && *wildstr != wild_many && *wildstr != wild_one)
81
    {
82
      if (*wildstr == wild_prefix && wildstr[1])
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
83
        wildstr++;
84
      if (my_toupper(cs, *wildstr++) != my_toupper(cs, *str++))
1067.3.1 by Padraig O'Sullivan
Extracted the CHARACTER_SET I_S table into the I_S plugin.
85
        return (1);
1 by brian
clean slate
86
    }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
87
    if (! *wildstr )
88
      return (*str != 0);
1 by brian
clean slate
89
    if (*wildstr++ == wild_one)
90
    {
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
91
      if (! *str++)
92
        return (1);	/* One char; skip */
1 by brian
clean slate
93
    }
94
    else
95
    {						/* Found '*' */
1067.3.1 by Padraig O'Sullivan
Extracted the CHARACTER_SET I_S table into the I_S plugin.
96
      if (! *wildstr)
97
        return (0);		/* '*' as last char: OK */
1 by brian
clean slate
98
      flag=(*wildstr != wild_many && *wildstr != wild_one);
99
      do
100
      {
1067.3.1 by Padraig O'Sullivan
Extracted the CHARACTER_SET I_S table into the I_S plugin.
101
        if (flag)
102
        {
103
          char cmp;
104
          if ((cmp= *wildstr) == wild_prefix && wildstr[1])
105
            cmp= wildstr[1];
106
          cmp= my_toupper(cs, cmp);
107
          while (*str && my_toupper(cs, *str) != cmp)
108
            str++;
109
          if (! *str)
110
            return (1);
111
        }
112
        if (wild_case_compare(cs, str, wildstr) == 0)
113
          return (0);
114
      } while (*str++);
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
115
      return (1);
1 by brian
clean slate
116
    }
117
  }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
118
  return (*str != '\0');
1 by brian
clean slate
119
}
120
121
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
122
/**
123
 * @brief
1108.4.4 by David Shrewsbury
Minor style change. Renamed find_databases() to find_schemas() for consistency. Changed return type from int to bool.
124
 *   Find subdirectories (schemas) in a given directory (datadir).
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
125
 *
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
126
 * @param[in]  session    Thread Cursor
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
127
 * @param[out] files      Put found entries in this list
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
128
 * @param[in]  path       Path to database
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
129
 * @param[in]  wild       Filter for found entries
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
130
 *
1108.4.4 by David Shrewsbury
Minor style change. Renamed find_databases() to find_schemas() for consistency. Changed return type from int to bool.
131
 * @retval false   Success
132
 * @retval true    Error
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
133
 */
1108.4.4 by David Shrewsbury
Minor style change. Renamed find_databases() to find_schemas() for consistency. Changed return type from int to bool.
134
static bool find_schemas(Session *session, vector<LEX_STRING*> &files,
135
                         const char *path, const char *wild)
1 by brian
clean slate
136
{
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
137
  if (wild && (wild[0] == '\0'))
138
    wild= 0;
139
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
140
  CachedDirectory directory(path);
141
142
  if (directory.fail())
1 by brian
clean slate
143
  {
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
144
    errno= directory.getError();
145
    my_error(ER_CANT_READ_DIR, MYF(0), path, errno);
1183.1.15 by Brian Aker
I_S now provides its own tables via the SE interface
146
147
    return true;
1 by brian
clean slate
148
  }
149
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
150
  CachedDirectory::Entries entries= directory.getEntries();
151
  CachedDirectory::Entries::iterator entry_iter= entries.begin();
152
153
  while (entry_iter != entries.end())
1 by brian
clean slate
154
  {
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
155
    uint32_t file_name_len;
1 by brian
clean slate
156
    char uname[NAME_LEN + 1];                   /* Unencoded name */
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
157
    struct stat entry_stat;
158
    CachedDirectory::Entry *entry= *entry_iter;
159
160
    if ((entry->filename == ".") || (entry->filename == ".."))
161
    {
162
      ++entry_iter;
163
      continue;
164
    }
165
166
    if (stat(entry->filename.c_str(), &entry_stat))
167
    {
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
168
      errno= errno;
169
      my_error(ER_CANT_GET_STAT, MYF(0), entry->filename.c_str(), errno);
1108.4.4 by David Shrewsbury
Minor style change. Renamed find_databases() to find_schemas() for consistency. Changed return type from int to bool.
170
      return(true);
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
171
    }
172
1108.4.4 by David Shrewsbury
Minor style change. Renamed find_databases() to find_schemas() for consistency. Changed return type from int to bool.
173
    if (! S_ISDIR(entry_stat.st_mode))
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
174
    {
175
      ++entry_iter;
176
      continue;
177
    }
178
179
    file_name_len= filename_to_tablename(entry->filename.c_str(), uname,
180
                                         sizeof(uname));
181
    if (wild && wild_compare(uname, wild, 0))
182
    {
183
      ++entry_iter;
184
      continue;
1 by brian
clean slate
185
    }
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
186
187
    LEX_STRING *file_name= 0;
188
    file_name= session->make_lex_string(file_name, uname, file_name_len, true);
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
189
    if (file_name == NULL)
1108.4.4 by David Shrewsbury
Minor style change. Renamed find_databases() to find_schemas() for consistency. Changed return type from int to bool.
190
      return(true);
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
191
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
192
    files.push_back(file_name);
1108.4.2 by David Shrewsbury
Replace my_dir in find_files() with CachedDirectory. Renamed find_files() to find_dirs() to more accurately reflect what it is doing after removing dead code inside it.
193
    ++entry_iter;
1 by brian
clean slate
194
  }
1071.1.1 by Nathan Williams
Refactored find_files function: style cleanup, removing dead variables, doxygenized-header, and removed unneeded LEX_STRING creation.
195
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
196
  return false;
1 by brian
clean slate
197
}
198
199
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
200
bool drizzled_show_create(Session *session, TableList *table_list, bool is_if_not_exists)
1 by brian
clean slate
201
{
202
  char buff[2048];
203
  String buffer(buff, sizeof(buff), system_charset_info);
204
205
  /* Only one table for now, but VIEW can involve several tables */
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
206
  if (session->openTables(table_list))
1 by brian
clean slate
207
  {
737 by Brian Aker
Updates for dead code removal (and forced assert() in delete).
208
    if (session->is_error())
1014.3.4 by Brian Aker
Remove dead session calls.
209
      return true;
1 by brian
clean slate
210
211
    /*
212
      Clear all messages with 'error' level status and
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
213
      issue a warning with 'warning' level status in
1 by brian
clean slate
214
      case of invalid view and last error is ER_VIEW_INVALID
215
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
216
    drizzle_reset_errors(session, true);
217
    session->clear_error();
1 by brian
clean slate
218
  }
219
220
  buffer.length(0);
221
1222.1.3 by Brian Aker
Remove used flag for engine.
222
  if (store_create_info(table_list, &buffer, is_if_not_exists))
1014.3.4 by Brian Aker
Remove dead session calls.
223
    return true;
1 by brian
clean slate
224
225
  List<Item> field_list;
226
  {
227
    field_list.push_back(new Item_empty_string("Table",NAME_CHAR_LEN));
228
    // 1024 is for not to confuse old clients
229
    field_list.push_back(new Item_empty_string("Create Table",
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
230
                                               max(buffer.length(),(uint32_t)1024)));
1 by brian
clean slate
231
  }
232
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
233
  if (session->client->sendFields(&field_list))
1014.3.4 by Brian Aker
Remove dead session calls.
234
    return true;
1 by brian
clean slate
235
  {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
236
    session->client->store(table_list->table->alias);
1 by brian
clean slate
237
  }
238
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
239
  session->client->store(buffer.ptr(), buffer.length());
1 by brian
clean slate
240
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
241
  if (session->client->flush())
1014.3.4 by Brian Aker
Remove dead session calls.
242
    return true;
1 by brian
clean slate
243
836 by Brian Aker
Fixed session call from function to method.
244
  session->my_eof();
1014.3.4 by Brian Aker
Remove dead session calls.
245
  return false;
1 by brian
clean slate
246
}
247
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
248
/**
249
  Get a CREATE statement for a given database.
250
251
  The database is identified by its name, passed as @c dbname parameter.
252
  The name should be encoded using the system character set (UTF8 currently).
253
254
  Resulting statement is stored in the string pointed by @c buffer. The string
255
  is emptied first and its character set is set to the system character set.
256
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
257
  If is_if_not_exists is set, then
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
258
  the resulting CREATE statement contains "IF NOT EXISTS" clause. Other flags
259
  in @c create_options are ignored.
260
261
  @param  session           The current thread instance.
262
  @param  dbname        The name of the database.
263
  @param  buffer        A String instance where the statement is stored.
264
  @param  create_info   If not NULL, the options member influences the resulting
265
                        CRATE statement.
266
267
  @returns true if errors are detected, false otherwise.
268
*/
269
270
static bool store_db_create_info(const char *dbname, String *buffer, bool if_not_exists)
271
{
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
272
  message::Schema schema;
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
273
1273.13.38 by Brian Aker
Add in new show work.
274
  if (not my_strcasecmp(system_charset_info, dbname,
275
                        INFORMATION_SCHEMA_NAME.c_str()))
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
276
  {
277
    dbname= INFORMATION_SCHEMA_NAME.c_str();
278
  }
1273.13.38 by Brian Aker
Add in new show work.
279
  else if (not my_strcasecmp(system_charset_info, dbname,
280
                             "data_dictionary"))
1273.13.1 by Brian Aker
First pass through data dictionary.
281
  {
282
    dbname= "data_dictionary";
283
  }
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
284
  else
285
  {
1273.13.38 by Brian Aker
Add in new show work.
286
    int r= get_database_metadata(dbname, schema);
287
    if (r < 0)
1089.10.1 by Stewart Smith
fix SHOW CREATE DATABASE for default collation. Move database metadata reading code around to be a bit more sane.
288
      return true;
289
  }
290
291
  buffer->length(0);
292
  buffer->free();
293
  buffer->set_charset(system_charset_info);
294
  buffer->append(STRING_WITH_LEN("CREATE DATABASE "));
295
296
  if (if_not_exists)
297
    buffer->append(STRING_WITH_LEN("IF NOT EXISTS "));
298
299
  buffer->append_identifier(dbname, strlen(dbname));
300
301
  if (schema.has_collation() && strcmp(schema.collation().c_str(),
302
                                       default_charset_info->name))
303
  {
304
    buffer->append(" COLLATE = ");
305
    buffer->append(schema.collation().c_str());
306
  }
307
308
  return false;
309
}
310
1273 by Brian Aker
Revert db patch.
311
bool mysqld_show_create_db(Session *session, char *dbname, bool if_not_exists)
1 by brian
clean slate
312
{
313
  char buff[2048];
314
  String buffer(buff, sizeof(buff), system_charset_info);
315
1273 by Brian Aker
Revert db patch.
316
  if (store_db_create_info(dbname, &buffer, if_not_exists))
1 by brian
clean slate
317
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
318
    /*
1 by brian
clean slate
319
      This assumes that the only reason for which store_db_create_info()
320
      can fail is incorrect database name (which is the case now).
321
    */
1273 by Brian Aker
Revert db patch.
322
    my_error(ER_BAD_DB_ERROR, MYF(0), dbname);
1014.3.4 by Brian Aker
Remove dead session calls.
323
    return true;
1 by brian
clean slate
324
  }
325
326
  List<Item> field_list;
327
  field_list.push_back(new Item_empty_string("Database",NAME_CHAR_LEN));
328
  field_list.push_back(new Item_empty_string("Create Database",1024));
329
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
330
  if (session->client->sendFields(&field_list))
1014.3.4 by Brian Aker
Remove dead session calls.
331
    return true;
1 by brian
clean slate
332
1273 by Brian Aker
Revert db patch.
333
  session->client->store(dbname, strlen(dbname));
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
334
  session->client->store(buffer.ptr(), buffer.length());
1 by brian
clean slate
335
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
336
  if (session->client->flush())
1014.3.4 by Brian Aker
Remove dead session calls.
337
    return true;
836 by Brian Aker
Fixed session call from function to method.
338
  session->my_eof();
1014.3.4 by Brian Aker
Remove dead session calls.
339
  return false;
1 by brian
clean slate
340
}
341
342
/*
343
  Get the quote character for displaying an identifier.
344
345
  SYNOPSIS
346
    get_quote_char_for_identifier()
347
348
  IMPLEMENTATION
349
    Force quoting in the following cases:
350
      - name is empty (for one, it is possible when we use this function for
351
        quoting user and host names for DEFINER clause);
352
      - name is a keyword;
353
      - name includes a special character;
354
    Otherwise identifier is quoted only if the option OPTION_QUOTE_SHOW_CREATE
355
    is set.
356
357
  RETURN
358
    EOF	  No quote character is needed
359
    #	  Quote character
360
*/
361
1014.3.4 by Brian Aker
Remove dead session calls.
362
int get_quote_char_for_identifier()
1 by brian
clean slate
363
{
352.2.1 by Harrison Fisk
Fix for bugs 259843 and 256482
364
  return '`';
1 by brian
clean slate
365
}
366
367
368
#define LIST_PROCESS_HOST_LEN 64
369
1014.3.4 by Brian Aker
Remove dead session calls.
370
static bool get_field_default_value(Field *timestamp_field,
1 by brian
clean slate
371
                                    Field *field, String *def_value,
372
                                    bool quoted)
373
{
374
  bool has_default;
375
  bool has_now_default;
376
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
377
  /*
1 by brian
clean slate
378
     We are using CURRENT_TIMESTAMP instead of NOW because it is
379
     more standard
380
  */
381
  has_now_default= (timestamp_field == field &&
382
                    field->unireg_check != Field::TIMESTAMP_UN_FIELD);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
383
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
384
  has_default= (field->type() != DRIZZLE_TYPE_BLOB &&
1 by brian
clean slate
385
                !(field->flags & NO_DEFAULT_VALUE_FLAG) &&
884.2.1 by Toru Maesaka
Fixed the bug of SHOW CREATE TABLE not outputting DEFAULT values. Killed some tabular indents on the way too
386
                field->unireg_check != Field::NEXT_NUMBER);
1 by brian
clean slate
387
388
  def_value->length(0);
389
  if (has_default)
390
  {
391
    if (has_now_default)
392
      def_value->append(STRING_WITH_LEN("CURRENT_TIMESTAMP"));
393
    else if (!field->is_null())
394
    {                                             // Not null by default
395
      char tmp[MAX_FIELD_WIDTH];
396
      String type(tmp, sizeof(tmp), field->charset());
397
      field->val_str(&type);
398
      if (type.length())
399
      {
400
        String def_val;
482 by Brian Aker
Remove uint.
401
        uint32_t dummy_errors;
1 by brian
clean slate
402
        /* convert to system_charset_info == utf8 */
403
        def_val.copy(type.ptr(), type.length(), field->charset(),
404
                     system_charset_info, &dummy_errors);
405
        if (quoted)
406
          append_unescaped(def_value, def_val.ptr(), def_val.length());
407
        else
408
          def_value->append(def_val.ptr(), def_val.length());
409
      }
410
      else if (quoted)
411
        def_value->append(STRING_WITH_LEN("''"));
412
    }
413
    else if (field->maybe_null() && quoted)
414
      def_value->append(STRING_WITH_LEN("NULL"));    // Null as default
415
    else
1014.3.4 by Brian Aker
Remove dead session calls.
416
      return false;
1 by brian
clean slate
417
  }
418
  return has_default;
419
}
420
421
/*
422
  Build a CREATE TABLE statement for a table.
423
424
  SYNOPSIS
425
    store_create_info()
426
    table_list        A list containing one table to write statement
427
                      for.
428
    packet            Pointer to a string where statement will be
429
                      written.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
430
1 by brian
clean slate
431
  NOTE
432
    Currently always return 0, but might return error code in the
433
    future.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
434
1 by brian
clean slate
435
  RETURN
436
    0       OK
437
 */
438
1222.1.3 by Brian Aker
Remove used flag for engine.
439
int store_create_info(TableList *table_list, String *packet, bool is_if_not_exists)
1 by brian
clean slate
440
{
441
  List<Item> field_list;
492.1.8 by Monty Taylor
Replaced some int10_to_str with to_string.
442
  char tmp[MAX_FIELD_WIDTH], *for_str, def_value_buf[MAX_FIELD_WIDTH];
1 by brian
clean slate
443
  const char *alias;
670.3.3 by Toru Maesaka
Added namespacing for std to .cc files that needed it
444
  string buff;
1 by brian
clean slate
445
  String type(tmp, sizeof(tmp), system_charset_info);
446
  String def_value(def_value_buf, sizeof(def_value_buf), system_charset_info);
447
  Field **ptr,*field;
482 by Brian Aker
Remove uint.
448
  uint32_t primary_key;
1 by brian
clean slate
449
  KEY *key_info;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
450
  Table *table= table_list->table;
1208.3.2 by brian
Update for Cursor renaming.
451
  Cursor *cursor= table->cursor;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
452
  TableShare *share= table->s;
1 by brian
clean slate
453
  HA_CREATE_INFO create_info;
163 by Brian Aker
Merge Monty's code.
454
  bool show_table_options= false;
1005.2.3 by Monty Taylor
Further reversion of P.
455
  my_bitmap_map *old_map;
1 by brian
clean slate
456
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
457
  table->restoreRecordAsDefault(); // Get empty record
1 by brian
clean slate
458
459
  if (share->tmp_table)
460
    packet->append(STRING_WITH_LEN("CREATE TEMPORARY TABLE "));
461
  else
462
    packet->append(STRING_WITH_LEN("CREATE TABLE "));
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
463
  if (is_if_not_exists)
1 by brian
clean slate
464
    packet->append(STRING_WITH_LEN("IF NOT EXISTS "));
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
465
  alias= share->table_name.str;
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
466
794 by Brian Aker
Refactor append_identifier and remove dead OPTION_QUOTE_SHOW_CREATE option
467
  packet->append_identifier(alias, strlen(alias));
1 by brian
clean slate
468
  packet->append(STRING_WITH_LEN(" (\n"));
469
  /*
470
    We need this to get default values from the table
471
    We have to restore the read_set if we are called from insert in case
472
    of row based replication.
473
  */
1005.2.3 by Monty Taylor
Further reversion of P.
474
  old_map= table->use_all_columns(table->read_set);
1 by brian
clean slate
475
476
  for (ptr=table->field ; (field= *ptr); ptr++)
477
  {
482 by Brian Aker
Remove uint.
478
    uint32_t flags = field->flags;
1 by brian
clean slate
479
480
    if (ptr != table->field)
481
      packet->append(STRING_WITH_LEN(",\n"));
482
483
    packet->append(STRING_WITH_LEN("  "));
794 by Brian Aker
Refactor append_identifier and remove dead OPTION_QUOTE_SHOW_CREATE option
484
    packet->append_identifier(field->field_name, strlen(field->field_name));
1 by brian
clean slate
485
    packet->append(' ');
486
    // check for surprises from the previous call to Field::sql_type()
487
    if (type.ptr() != tmp)
488
      type.set(tmp, sizeof(tmp), system_charset_info);
489
    else
490
      type.set_charset(system_charset_info);
491
492
    field->sql_type(type);
493
    packet->append(type.ptr(), type.length(), system_charset_info);
494
495
    if (field->has_charset())
496
    {
497
      if (field->charset() != share->table_charset)
498
      {
884.2.1 by Toru Maesaka
Fixed the bug of SHOW CREATE TABLE not outputting DEFAULT values. Killed some tabular indents on the way too
499
        packet->append(STRING_WITH_LEN(" CHARACTER SET "));
500
        packet->append(field->charset()->csname);
1 by brian
clean slate
501
      }
884.2.1 by Toru Maesaka
Fixed the bug of SHOW CREATE TABLE not outputting DEFAULT values. Killed some tabular indents on the way too
502
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
503
      /*
884.2.1 by Toru Maesaka
Fixed the bug of SHOW CREATE TABLE not outputting DEFAULT values. Killed some tabular indents on the way too
504
        For string types dump collation name only if
505
        collation is not primary for the given charset
1 by brian
clean slate
506
      */
507
      if (!(field->charset()->state & MY_CS_PRIMARY))
508
      {
884.2.1 by Toru Maesaka
Fixed the bug of SHOW CREATE TABLE not outputting DEFAULT values. Killed some tabular indents on the way too
509
        packet->append(STRING_WITH_LEN(" COLLATE "));
510
        packet->append(field->charset()->name);
1 by brian
clean slate
511
      }
512
    }
513
514
    if (flags & NOT_NULL_FLAG)
515
      packet->append(STRING_WITH_LEN(" NOT NULL"));
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
516
    else if (field->type() == DRIZZLE_TYPE_TIMESTAMP)
1 by brian
clean slate
517
    {
518
      /*
519
        TIMESTAMP field require explicit NULL flag, because unlike
520
        all other fields they are treated as NOT NULL by default.
521
      */
522
      packet->append(STRING_WITH_LEN(" NULL"));
523
    }
524
    {
525
      /*
526
        Add field flags about FIELD FORMAT (FIXED or DYNAMIC)
527
        and about STORAGE (DISK or MEMORY).
528
      */
529
      enum column_format_type column_format= (enum column_format_type)
530
        ((flags >> COLUMN_FORMAT_FLAGS) & COLUMN_FORMAT_MASK);
531
      if (column_format)
532
      {
533
        packet->append(STRING_WITH_LEN(" /*!"));
534
        packet->append(STRING_WITH_LEN(" COLUMN_FORMAT"));
535
        if (column_format == COLUMN_FORMAT_TYPE_FIXED)
536
          packet->append(STRING_WITH_LEN(" FIXED */"));
537
        else
538
          packet->append(STRING_WITH_LEN(" DYNAMIC */"));
539
      }
540
    }
1014.3.4 by Brian Aker
Remove dead session calls.
541
    if (get_field_default_value(table->timestamp_field, field, &def_value, 1))
1 by brian
clean slate
542
    {
543
      packet->append(STRING_WITH_LEN(" DEFAULT "));
544
      packet->append(def_value.ptr(), def_value.length(), system_charset_info);
545
    }
546
547
    if (table->timestamp_field == field && field->unireg_check != Field::TIMESTAMP_DN_FIELD)
548
      packet->append(STRING_WITH_LEN(" ON UPDATE CURRENT_TIMESTAMP"));
549
550
    if (field->unireg_check == Field::NEXT_NUMBER)
551
      packet->append(STRING_WITH_LEN(" AUTO_INCREMENT"));
552
553
    if (field->comment.length)
554
    {
555
      packet->append(STRING_WITH_LEN(" COMMENT "));
556
      append_unescaped(packet, field->comment.str, field->comment.length);
557
    }
558
  }
559
560
  key_info= table->key_info;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
561
  memset(&create_info, 0, sizeof(create_info));
1 by brian
clean slate
562
  /* Allow update_create_info to update row type */
563
  create_info.row_type= share->row_type;
1208.3.2 by brian
Update for Cursor renaming.
564
  cursor->update_create_info(&create_info);
1 by brian
clean slate
565
  primary_key= share->primary_key;
566
482 by Brian Aker
Remove uint.
567
  for (uint32_t i=0 ; i < share->keys ; i++,key_info++)
1 by brian
clean slate
568
  {
569
    KEY_PART_INFO *key_part= key_info->key_part;
570
    bool found_primary=0;
571
    packet->append(STRING_WITH_LEN(",\n  "));
572
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
573
    if (i == primary_key && is_primary_key(key_info))
1 by brian
clean slate
574
    {
575
      found_primary=1;
576
      /*
577
        No space at end, because a space will be added after where the
578
        identifier would go, but that is not added for primary key.
579
      */
580
      packet->append(STRING_WITH_LEN("PRIMARY KEY"));
581
    }
582
    else if (key_info->flags & HA_NOSAME)
583
      packet->append(STRING_WITH_LEN("UNIQUE KEY "));
584
    else
585
      packet->append(STRING_WITH_LEN("KEY "));
586
587
    if (!found_primary)
794 by Brian Aker
Refactor append_identifier and remove dead OPTION_QUOTE_SHOW_CREATE option
588
     packet->append_identifier(key_info->name, strlen(key_info->name));
1 by brian
clean slate
589
590
    packet->append(STRING_WITH_LEN(" ("));
591
482 by Brian Aker
Remove uint.
592
    for (uint32_t j=0 ; j < key_info->key_parts ; j++,key_part++)
1 by brian
clean slate
593
    {
594
      if (j)
595
        packet->append(',');
596
597
      if (key_part->field)
794 by Brian Aker
Refactor append_identifier and remove dead OPTION_QUOTE_SHOW_CREATE option
598
        packet->append_identifier(key_part->field->field_name,
884.2.1 by Toru Maesaka
Fixed the bug of SHOW CREATE TABLE not outputting DEFAULT values. Killed some tabular indents on the way too
599
                                  strlen(key_part->field->field_name));
1 by brian
clean slate
600
      if (key_part->field &&
601
          (key_part->length !=
602
           table->field[key_part->fieldnr-1]->key_length()))
603
      {
1008.3.8 by Stewart Smith
remove more evil that is operator overloading.
604
        buff.assign("(");
1008.3.7 by Stewart Smith
remove evil that is operator overloading.
605
        buff.append(to_string((int32_t) key_part->length /
606
                              key_part->field->charset()->mbmaxlen));
607
        buff.append(")");
492.1.8 by Monty Taylor
Replaced some int10_to_str with to_string.
608
        packet->append(buff.c_str(), buff.length());
1 by brian
clean slate
609
      }
610
    }
611
    packet->append(')');
1014.3.4 by Brian Aker
Remove dead session calls.
612
    store_key_options(packet, table, key_info);
1 by brian
clean slate
613
  }
614
615
  /*
616
    Get possible foreign key definitions stored in InnoDB and append them
617
    to the CREATE TABLE statement
618
  */
619
1208.3.2 by brian
Update for Cursor renaming.
620
  if ((for_str= cursor->get_foreign_key_create_info()))
1 by brian
clean slate
621
  {
622
    packet->append(for_str, strlen(for_str));
1208.3.2 by brian
Update for Cursor renaming.
623
    cursor->free_foreign_key_create_info(for_str);
1 by brian
clean slate
624
  }
625
626
  packet->append(STRING_WITH_LEN("\n)"));
627
  {
163 by Brian Aker
Merge Monty's code.
628
    show_table_options= true;
1 by brian
clean slate
629
    /*
630
      Get possible table space definitions and append them
631
      to the CREATE TABLE statement
632
    */
633
1222.1.3 by Brian Aker
Remove used flag for engine.
634
    /* 
635
      We should always store engine since we will now be 
636
      making sure engines accept options (aka... no
637
      dangling arguments for engines.
1 by brian
clean slate
638
    */
1222.1.3 by Brian Aker
Remove used flag for engine.
639
    packet->append(STRING_WITH_LEN(" ENGINE="));
640
    packet->append(cursor->engine->getName().c_str());
1 by brian
clean slate
641
642
    if (share->db_create_options & HA_OPTION_PACK_KEYS)
643
      packet->append(STRING_WITH_LEN(" PACK_KEYS=1"));
644
    if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
645
      packet->append(STRING_WITH_LEN(" PACK_KEYS=0"));
646
    if (create_info.row_type != ROW_TYPE_DEFAULT)
647
    {
648
      packet->append(STRING_WITH_LEN(" ROW_FORMAT="));
895 by Brian Aker
Completion (?) of uint conversion.
649
      packet->append(ha_row_type[(uint32_t) create_info.row_type]);
1 by brian
clean slate
650
    }
1188.2.1 by Stewart Smith
move key_block_size out of table_share and into the table proto. init it in parser
651
    if (table->s->hasKeyBlockSize())
1 by brian
clean slate
652
    {
653
      packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE="));
1188.2.1 by Stewart Smith
move key_block_size out of table_share and into the table proto. init it in parser
654
      buff= to_string(table->s->getKeyBlockSize());
492.1.8 by Monty Taylor
Replaced some int10_to_str with to_string.
655
      packet->append(buff.c_str(), buff.length());
1 by brian
clean slate
656
    }
244.1.1 by Harrison Fisk
Port Ebay/Google memory storage engine variable width columns.
657
    if (share->block_size)
658
    {
659
      packet->append(STRING_WITH_LEN(" BLOCK_SIZE="));
492.1.8 by Monty Taylor
Replaced some int10_to_str with to_string.
660
      buff= to_string(share->block_size);
661
      packet->append(buff.c_str(), buff.length());
244.1.1 by Harrison Fisk
Port Ebay/Google memory storage engine variable width columns.
662
    }
1208.3.2 by brian
Update for Cursor renaming.
663
    table->cursor->append_create_info(packet);
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
664
    if (share->hasComment() && share->getCommentLength())
1 by brian
clean slate
665
    {
666
      packet->append(STRING_WITH_LEN(" COMMENT="));
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
667
      append_unescaped(packet, share->getComment(),
668
                       share->getCommentLength());
1 by brian
clean slate
669
    }
670
  }
1005.2.3 by Monty Taylor
Further reversion of P.
671
  table->restore_column_map(old_map);
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
672
  return(0);
1 by brian
clean slate
673
}
674
1014.3.4 by Brian Aker
Remove dead session calls.
675
static void store_key_options(String *packet, Table *table, KEY *key_info)
1 by brian
clean slate
676
{
677
  char *end, buff[32];
678
679
  if (key_info->algorithm == HA_KEY_ALG_BTREE)
680
    packet->append(STRING_WITH_LEN(" USING BTREE"));
681
682
  if (key_info->algorithm == HA_KEY_ALG_HASH)
683
    packet->append(STRING_WITH_LEN(" USING HASH"));
684
685
  if ((key_info->flags & HA_USES_BLOCK_SIZE) &&
1188.2.1 by Stewart Smith
move key_block_size out of table_share and into the table proto. init it in parser
686
      table->s->getKeyBlockSize() != key_info->block_size)
1 by brian
clean slate
687
  {
688
    packet->append(STRING_WITH_LEN(" KEY_BLOCK_SIZE="));
152 by Brian Aker
longlong replacement
689
    end= int64_t10_to_str(key_info->block_size, buff, 10);
895 by Brian Aker
Completion (?) of uint conversion.
690
    packet->append(buff, (uint32_t) (end - buff));
1 by brian
clean slate
691
  }
692
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
693
  assert(test(key_info->flags & HA_USES_COMMENT) ==
1 by brian
clean slate
694
              (key_info->comment.length > 0));
695
  if (key_info->flags & HA_USES_COMMENT)
696
  {
697
    packet->append(STRING_WITH_LEN(" COMMENT "));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
698
    append_unescaped(packet, key_info->comment.str,
1 by brian
clean slate
699
                     key_info->comment.length);
700
  }
701
}
702
703
704
/****************************************************************************
705
  Return info about all processes
706
  returns for each thread: thread id, user, host, db, command, info
707
****************************************************************************/
708
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
709
class thread_info
710
{
711
  thread_info();
1 by brian
clean slate
712
public:
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
713
  uint64_t thread_id;
1 by brian
clean slate
714
  time_t start_time;
482 by Brian Aker
Remove uint.
715
  uint32_t   command;
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
716
  string user, host, db, proc_info, state_info, query;
1245.2.7 by Monty Taylor
Merged up with trunk.
717
  thread_info(uint64_t thread_id_arg,
718
              time_t start_time_arg,
719
              uint32_t command_arg,
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
720
              const string &user_arg,
721
              const string &host_arg,
722
              const string &db_arg,
723
              const string &proc_info_arg,
724
              const string &state_info_arg,
725
              const string &query_arg)
726
    : thread_id(thread_id_arg), start_time(start_time_arg), command(command_arg),
727
      user(user_arg), host(host_arg), db(db_arg), proc_info(proc_info_arg),
728
      state_info(state_info_arg), query(query_arg)
729
  {}
1 by brian
clean slate
730
};
731
1273.13.37 by Brian Aker
Remove "full" syntax.
732
void mysqld_list_processes(Session *session,const char *user)
1 by brian
clean slate
733
{
734
  Item *field;
735
  List<Item> field_list;
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
736
  vector<thread_info> thread_infos;
1 by brian
clean slate
737
738
  field_list.push_back(new Item_int("Id", 0, MY_INT32_NUM_DECIMAL_DIGITS));
739
  field_list.push_back(new Item_empty_string("User",16));
740
  field_list.push_back(new Item_empty_string("Host",LIST_PROCESS_HOST_LEN));
741
  field_list.push_back(field=new Item_empty_string("db",NAME_CHAR_LEN));
961.1.3 by Brian Aker
Remove additional lock for proceslist.
742
  field->maybe_null= true;
1 by brian
clean slate
743
  field_list.push_back(new Item_empty_string("Command",16));
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
744
  field_list.push_back(new Item_return_int("Time",7, DRIZZLE_TYPE_LONG));
1 by brian
clean slate
745
  field_list.push_back(field=new Item_empty_string("State",30));
961.1.3 by Brian Aker
Remove additional lock for proceslist.
746
  field->maybe_null= true;
747
  field_list.push_back(field=new Item_empty_string("Info", PROCESS_LIST_WIDTH));
748
  field->maybe_null= true;
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
749
  if (session->client->sendFields(&field_list))
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
750
    return;
1 by brian
clean slate
751
398.1.6 by Monty Taylor
Removed __alpha__ references.
752
  pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
520.1.22 by Brian Aker
Second pass of thd cleanup
753
  if (!session->killed)
1 by brian
clean slate
754
  {
520.1.21 by Brian Aker
THD -> Session rename
755
    Session *tmp;
1241.9.17 by Monty Taylor
Removed more bits from server_includes.
756
    for(vector<Session*>::iterator it= getSessionList().begin(); it != getSessionList().end(); ++it)
1 by brian
clean slate
757
    {
1014.7.1 by Nathan Williams
Replaced global I_List<Session> with std::vector<Session*>
758
      tmp= *it;
694 by Brian Aker
Refactor out char* strdup for string class in user.
759
      Security_context *tmp_sctx= &tmp->security_ctx;
1 by brian
clean slate
760
      struct st_my_thread_var *mysys_var;
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
761
      if (tmp->client->isConnected() && (!user || (tmp_sctx->user.c_str() && !strcmp(tmp_sctx->user.c_str(), user))))
1 by brian
clean slate
762
      {
763
764
        if ((mysys_var= tmp->mysys_var))
765
          pthread_mutex_lock(&mysys_var->mutex);
971.3.18 by Eric Day
Finished store() cleanup.
766
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
767
        const string tmp_proc_info((tmp->killed == Session::KILL_CONNECTION) ? "Killed" : command_name[tmp->command].str);
971.3.18 by Eric Day
Finished store() cleanup.
768
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
769
        const string tmp_state_info(tmp->client->isWriting()
770
                                     ? "Writing to net"
771
                                     : tmp->client->isReading()
772
                                       ? (tmp->command == COM_SLEEP
773
                                            ? ""
774
                                            : "Reading from net")
775
                                       : tmp->get_proc_info()
776
                                         ? tmp->get_proc_info()
777
                                         : (tmp->mysys_var && tmp->mysys_var->current_cond)
778
                                           ? "Waiting on cond"
779
                                           : "");
1 by brian
clean slate
780
        if (mysys_var)
781
          pthread_mutex_unlock(&mysys_var->mutex);
782
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
783
        const string tmp_query((tmp->process_list_info[0]) ? tmp->process_list_info : "");
784
        thread_infos.push_back(thread_info(tmp->thread_id,
785
                                           tmp->start_time,
786
                                           tmp->command,
787
                                           tmp_sctx->user.empty()
788
                                             ? string("unauthenticated user")
789
                                             : tmp_sctx->user,
790
                                           tmp_sctx->ip,
791
                                           tmp->db,
792
                                           tmp_proc_info,
793
                                           tmp_state_info,
794
                                           tmp_query));
1 by brian
clean slate
795
      }
796
    }
797
  }
398.1.6 by Monty Taylor
Removed __alpha__ references.
798
  pthread_mutex_unlock(&LOCK_thread_count);
685.3.4 by Toru Maesaka
Fixed the issues pointed out by Jay's code review
799
  time_t now= time(NULL);
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
800
  for(vector<thread_info>::iterator iter= thread_infos.begin();
801
      iter != thread_infos.end();
802
      ++iter)
1 by brian
clean slate
803
  {
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
804
    session->client->store((uint64_t) (*iter).thread_id);
805
    session->client->store((*iter).user);
806
    session->client->store((*iter).host);
807
    session->client->store((*iter).db);
808
    session->client->store((*iter).proc_info);
971.3.18 by Eric Day
Finished store() cleanup.
809
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
810
    if ((*iter).start_time)
811
      session->client->store((uint32_t) (now - (*iter).start_time));
1 by brian
clean slate
812
    else
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
813
      session->client->store();
814
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
815
    session->client->store((*iter).state_info);
816
    session->client->store((*iter).query);
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
817
818
    if (session->client->flush())
971.6.11 by Eric Day
Removed purecov messages.
819
      break;
1 by brian
clean slate
820
  }
836 by Brian Aker
Fixed session call from function to method.
821
  session->my_eof();
1245.2.1 by Monty Taylor
Removed final use if I_List<> in the server.
822
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
823
  return;
1 by brian
clean slate
824
}
825
826
/*****************************************************************************
827
  Status functions
828
*****************************************************************************/
829
901.1.3 by Padraig
More work on removing DYNAMIC_ARRAY from show.cc
830
static vector<SHOW_VAR *> all_status_vars;
1 by brian
clean slate
831
static bool status_vars_inited= 0;
1165.1.122 by Stewart Smith
make show_var_cmp() static in drizzled/show.cc
832
static int show_var_cmp(const void *var1, const void *var2)
1 by brian
clean slate
833
{
834
  return strcmp(((SHOW_VAR*)var1)->name, ((SHOW_VAR*)var2)->name);
835
}
836
901.1.13 by Padraig
Renaming the function object for the std::sort() algorithm.
837
class show_var_cmp_functor
901.1.9 by Padraig
Modified function object to be used as comparison parameter for sort()
838
{
839
  public:
901.1.13 by Padraig
Renaming the function object for the std::sort() algorithm.
840
  show_var_cmp_functor() { }
901.1.22 by Padraig
Small modifications based on Jay's merge review comments. Should be all good
841
  inline bool operator()(const SHOW_VAR *var1, const SHOW_VAR *var2) const
901.1.9 by Padraig
Modified function object to be used as comparison parameter for sort()
842
  {
901.1.22 by Padraig
Small modifications based on Jay's merge review comments. Should be all good
843
    int val= strcmp(var1->name, var2->name);
844
    return (val < 0);
901.1.9 by Padraig
Modified function object to be used as comparison parameter for sort()
845
  }
846
};
847
901.1.14 by Padraig
Changing name of functor show_var_if to show_var_remove_if.
848
class show_var_remove_if
901.1.4 by Padraig
Added function object to be used for removing elements from the vector. This
849
{
850
  public:
901.1.14 by Padraig
Changing name of functor show_var_if to show_var_remove_if.
851
  show_var_remove_if() { }
901.1.22 by Padraig
Small modifications based on Jay's merge review comments. Should be all good
852
  inline bool operator()(const SHOW_VAR *curr) const
901.1.4 by Padraig
Added function object to be used for removing elements from the vector. This
853
  {
901.1.8 by Padraig
Removed function which has become unused and also added some more comments.
854
    return (curr->type == SHOW_UNDEF);
901.1.4 by Padraig
Added function object to be used for removing elements from the vector. This
855
  }
856
};
857
1088.1.1 by Padraig O'Sullivan
Extracted the 3 STATUS tables into the I_S plugin.
858
SHOW_VAR *getFrontOfStatusVars()
859
{
860
  return all_status_vars.front();
861
}
862
1273.13.22 by Brian Aker
Added status bits. Variables next!
863
SHOW_VAR *getCommandStatusVars()
864
{
865
  SHOW_VAR *tmp= all_status_vars.front();
866
867
  for (; tmp->name; tmp++)
868
  {
869
    if (tmp->type == SHOW_ARRAY)
870
      return (SHOW_VAR *) tmp->value;
871
  }
872
873
  return NULL;
874
}
875
1 by brian
clean slate
876
/*
877
  Adds an array of SHOW_VAR entries to the output of SHOW STATUS
878
879
  SYNOPSIS
880
    add_status_vars(SHOW_VAR *list)
881
    list - an array of SHOW_VAR entries to add to all_status_vars
882
           the last entry must be {0,0,SHOW_UNDEF}
883
884
  NOTE
885
    The handling of all_status_vars[] is completely internal, it's allocated
886
    automatically when something is added to it, and deleted completely when
887
    the last entry is removed.
888
889
    As a special optimization, if add_status_vars() is called before
890
    init_status_vars(), it assumes "startup mode" - neither concurrent access
891
    to the array nor SHOW STATUS are possible (thus it skips locks and qsort)
892
*/
893
int add_status_vars(SHOW_VAR *list)
894
{
895
  int res= 0;
896
  if (status_vars_inited)
897
    pthread_mutex_lock(&LOCK_status);
898
  while (list->name)
901.1.22 by Padraig
Small modifications based on Jay's merge review comments. Should be all good
899
    all_status_vars.insert(all_status_vars.begin(), list++);
1 by brian
clean slate
900
  if (status_vars_inited)
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
901
    sort(all_status_vars.begin(), all_status_vars.end(),
901.1.17 by Padraig
cleaning up comments a little bit.
902
         show_var_cmp_functor());
1 by brian
clean slate
903
  if (status_vars_inited)
904
    pthread_mutex_unlock(&LOCK_status);
905
  return res;
906
}
907
908
/*
909
  Make all_status_vars[] usable for SHOW STATUS
910
911
  NOTE
912
    See add_status_vars(). Before init_status_vars() call, add_status_vars()
913
    works in a special fast "startup" mode. Thus init_status_vars()
914
    should be called as late as possible but before enabling multi-threading.
915
*/
916
void init_status_vars()
917
{
901.1.3 by Padraig
More work on removing DYNAMIC_ARRAY from show.cc
918
  status_vars_inited= 1;
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
919
  sort(all_status_vars.begin(), all_status_vars.end(),
901.1.17 by Padraig
cleaning up comments a little bit.
920
       show_var_cmp_functor());
1 by brian
clean slate
921
}
922
923
void reset_status_vars()
924
{
901.1.3 by Padraig
More work on removing DYNAMIC_ARRAY from show.cc
925
  vector<SHOW_VAR *>::iterator p= all_status_vars.begin();
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
926
  while (p != all_status_vars.end())
1 by brian
clean slate
927
  {
928
    /* Note that SHOW_LONG_NOFLUSH variables are not reset */
901.1.3 by Padraig
More work on removing DYNAMIC_ARRAY from show.cc
929
    if ((*p)->type == SHOW_LONG)
930
      (*p)->value= 0;
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
931
    ++p;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
932
  }
1 by brian
clean slate
933
}
934
935
/*
936
  catch-all cleanup function, cleans up everything no matter what
937
938
  DESCRIPTION
939
    This function is not strictly required if all add_to_status/
940
    remove_status_vars are properly paired, but it's a safety measure that
901.1.17 by Padraig
cleaning up comments a little bit.
941
    deletes everything from the all_status_vars vector even if some
1 by brian
clean slate
942
    remove_status_vars were forgotten
943
*/
901.1.3 by Padraig
More work on removing DYNAMIC_ARRAY from show.cc
944
void free_status_vars()
945
{
901.1.12 by Padraig
Modifying free_status_vars() for std::vector.
946
  all_status_vars.clear();
901.1.3 by Padraig
More work on removing DYNAMIC_ARRAY from show.cc
947
}
1 by brian
clean slate
948
949
/*
950
  Removes an array of SHOW_VAR entries from the output of SHOW STATUS
951
952
  SYNOPSIS
953
    remove_status_vars(SHOW_VAR *list)
954
    list - an array of SHOW_VAR entries to remove to all_status_vars
955
           the last entry must be {0,0,SHOW_UNDEF}
956
957
  NOTE
958
    there's lots of room for optimizing this, especially in non-sorted mode,
959
    but nobody cares - it may be called only in case of failed plugin
960
    initialization in the mysqld startup.
961
*/
962
963
void remove_status_vars(SHOW_VAR *list)
964
{
965
  if (status_vars_inited)
966
  {
967
    pthread_mutex_lock(&LOCK_status);
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
968
    SHOW_VAR *all= all_status_vars.front();
969
    int a= 0, b= all_status_vars.size(), c= (a+b)/2;
1 by brian
clean slate
970
971
    for (; list->name; list++)
972
    {
973
      int res= 0;
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
974
      for (a= 0, b= all_status_vars.size(); b-a > 1; c= (a+b)/2)
1 by brian
clean slate
975
      {
976
        res= show_var_cmp(list, all+c);
977
        if (res < 0)
978
          b= c;
979
        else if (res > 0)
980
          a= c;
981
        else
982
          break;
983
      }
984
      if (res == 0)
985
        all[c].type= SHOW_UNDEF;
986
    }
901.1.8 by Padraig
Removed function which has become unused and also added some more comments.
987
    /* removes all the SHOW_UNDEF elements from the vector */
901.1.18 by Padraig
Adding std:: prefix to remove_if since that caused compilation errors on
988
    all_status_vars.erase(std::remove_if(all_status_vars.begin(),
901.1.14 by Padraig
Changing name of functor show_var_if to show_var_remove_if.
989
                            all_status_vars.end(),show_var_remove_if()),
901.1.4 by Padraig
Added function object to be used for removing elements from the vector. This
990
                            all_status_vars.end());
1 by brian
clean slate
991
    pthread_mutex_unlock(&LOCK_status);
992
  }
993
  else
994
  {
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
995
    SHOW_VAR *all= all_status_vars.front();
482 by Brian Aker
Remove uint.
996
    uint32_t i;
1 by brian
clean slate
997
    for (; list->name; list++)
998
    {
901.1.1 by Padraig
Initial work to replace an instance of DYNAMIC_ARRAY in show.cc with STL
999
      for (i= 0; i < all_status_vars.size(); i++)
1 by brian
clean slate
1000
      {
1001
        if (show_var_cmp(list, all+i))
1002
          continue;
1003
        all[i].type= SHOW_UNDEF;
1004
        break;
1005
      }
1006
    }
901.1.8 by Padraig
Removed function which has become unused and also added some more comments.
1007
    /* removes all the SHOW_UNDEF elements from the vector */
901.1.18 by Padraig
Adding std:: prefix to remove_if since that caused compilation errors on
1008
    all_status_vars.erase(std::remove_if(all_status_vars.begin(),
901.1.14 by Padraig
Changing name of functor show_var_if to show_var_remove_if.
1009
                            all_status_vars.end(),show_var_remove_if()),
901.1.4 by Padraig
Added function object to be used for removing elements from the vector. This
1010
                            all_status_vars.end());
1 by brian
clean slate
1011
  }
1012
}
1013
1014
/* collect status for all running threads */
1015
1016
void calc_sum_of_all_status(STATUS_VAR *to)
1017
{
1018
  /* Ensure that thread id not killed during loop */
398.1.6 by Monty Taylor
Removed __alpha__ references.
1019
  pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
1 by brian
clean slate
1020
1021
  /* Get global values as base */
1022
  *to= global_status_var;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1023
1 by brian
clean slate
1024
  /* Add to this status from existing threads */
1241.9.17 by Monty Taylor
Removed more bits from server_includes.
1025
  for(vector<Session*>::iterator it= getSessionList().begin(); it != getSessionList().end(); ++it )
1014.7.1 by Nathan Williams
Replaced global I_List<Session> with std::vector<Session*>
1026
  {
1027
    add_to_status(to, &((*it)->status_var));
1028
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1029
398.1.6 by Monty Taylor
Removed __alpha__ references.
1030
  pthread_mutex_unlock(&LOCK_thread_count);
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1031
  return;
1 by brian
clean slate
1032
}
1033
1034
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
1035
static int make_table_list(Session *session, Select_Lex *sel,
1036
                           LEX_STRING *db_name, LEX_STRING *table_name)
1 by brian
clean slate
1037
{
1038
  Table_ident *table_ident;
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
1039
  table_ident= new Table_ident(*db_name, *table_name);
1 by brian
clean slate
1040
  sel->init_query();
971.3.70 by Eric Day
Fixed style issues found by Jay.
1041
  if (! sel->add_table_to_list(session, table_ident, 0, 0, TL_READ))
1 by brian
clean slate
1042
    return 1;
1043
  return 0;
1044
}
1045
1046
1047
/**
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1048
  @brief    Get lookup value from the part of 'WHERE' condition
1 by brian
clean slate
1049
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1050
  @details This function gets lookup value from
1051
           the part of 'WHERE' condition if it's possible and
1 by brian
clean slate
1052
           fill appropriate lookup_field_vals struct field
1053
           with this value.
1054
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1055
  @param[in]      session                   thread Cursor
1 by brian
clean slate
1056
  @param[in]      item_func             part of WHERE condition
1057
  @param[in]      table                 I_S table
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1058
  @param[in, out] lookup_field_vals     Struct which holds lookup values
1 by brian
clean slate
1059
1060
  @return
1061
    0             success
1062
    1             error, there can be no matching records for the condition
1063
*/
1064
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
1065
static bool get_lookup_value(Session *session, Item_func *item_func,
1066
                             TableList *table,
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1067
                             LOOKUP_FIELD_VALUES *lookup_field_vals,
1068
                             plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1069
{
1063.4.10 by Padraig O'Sullivan
Changing name of FieldInfo class to ColumnInfo based on some feedback from
1070
  const char *field_name1= schema_table->getFirstColumnIndex() >= 0 ?
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
1071
    schema_table->getColumnName(schema_table->getFirstColumnIndex()).c_str() : "";
1063.4.10 by Padraig O'Sullivan
Changing name of FieldInfo class to ColumnInfo based on some feedback from
1072
  const char *field_name2= schema_table->getSecondColumnIndex() >= 0 ?
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
1073
    schema_table->getColumnName(schema_table->getSecondColumnIndex()).c_str() : "";
1 by brian
clean slate
1074
1075
  if (item_func->functype() == Item_func::EQ_FUNC ||
1076
      item_func->functype() == Item_func::EQUAL_FUNC)
1077
  {
1078
    int idx_field, idx_val;
1079
    char tmp[MAX_FIELD_WIDTH];
1080
    String *tmp_str, str_buff(tmp, sizeof(tmp), system_charset_info);
1081
    Item_field *item_field;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1082
    const CHARSET_INFO * const cs= system_charset_info;
1 by brian
clean slate
1083
1084
    if (item_func->arguments()[0]->type() == Item::FIELD_ITEM &&
1085
        item_func->arguments()[1]->const_item())
1086
    {
1087
      idx_field= 0;
1088
      idx_val= 1;
1089
    }
1090
    else if (item_func->arguments()[1]->type() == Item::FIELD_ITEM &&
1091
             item_func->arguments()[0]->const_item())
1092
    {
1093
      idx_field= 1;
1094
      idx_val= 0;
1095
    }
1096
    else
1097
      return 0;
1098
1099
    item_field= (Item_field*) item_func->arguments()[idx_field];
1100
    if (table->table != item_field->field->table)
1101
      return 0;
1102
    tmp_str= item_func->arguments()[idx_val]->val_str(&str_buff);
1103
1104
    /* impossible value */
1105
    if (!tmp_str)
1106
      return 1;
1107
1108
    /* Lookup value is database name */
481 by Brian Aker
Remove all of uchar.
1109
    if (!cs->coll->strnncollsp(cs, (unsigned char *) field_name1, strlen(field_name1),
1110
                               (unsigned char *) item_field->field_name,
1 by brian
clean slate
1111
                               strlen(item_field->field_name), 0))
1112
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1113
      session->make_lex_string(&lookup_field_vals->db_value, tmp_str->ptr(),
163 by Brian Aker
Merge Monty's code.
1114
                           tmp_str->length(), false);
1 by brian
clean slate
1115
    }
1116
    /* Lookup value is table name */
481 by Brian Aker
Remove all of uchar.
1117
    else if (!cs->coll->strnncollsp(cs, (unsigned char *) field_name2,
1 by brian
clean slate
1118
                                    strlen(field_name2),
481 by Brian Aker
Remove all of uchar.
1119
                                    (unsigned char *) item_field->field_name,
1 by brian
clean slate
1120
                                    strlen(item_field->field_name), 0))
1121
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1122
      session->make_lex_string(&lookup_field_vals->table_value, tmp_str->ptr(),
163 by Brian Aker
Merge Monty's code.
1123
                           tmp_str->length(), false);
1 by brian
clean slate
1124
    }
1125
  }
1126
  return 0;
1127
}
1128
1129
1130
/**
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1131
  @brief    Calculates lookup values from 'WHERE' condition
1 by brian
clean slate
1132
1133
  @details This function calculates lookup value(database name, table name)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1134
           from 'WHERE' condition if it's possible and
1 by brian
clean slate
1135
           fill lookup_field_vals struct fields with these values.
1136
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1137
  @param[in]      session                   thread Cursor
1 by brian
clean slate
1138
  @param[in]      cond                  WHERE condition
1139
  @param[in]      table                 I_S table
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1140
  @param[in, out] lookup_field_vals     Struct which holds lookup values
1 by brian
clean slate
1141
1142
  @return
1143
    0             success
1144
    1             error, there can be no matching records for the condition
1145
*/
1146
520.1.22 by Brian Aker
Second pass of thd cleanup
1147
bool calc_lookup_values_from_cond(Session *session, COND *cond, TableList *table,
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1148
                                  LOOKUP_FIELD_VALUES *lookup_field_vals,
1149
                                  plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1150
{
1151
  if (!cond)
1152
    return 0;
1153
1154
  if (cond->type() == Item::COND_ITEM)
1155
  {
1156
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
1157
    {
1158
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1159
      Item *item;
1160
      while ((item= li++))
1161
      {
1162
        if (item->type() == Item::FUNC_ITEM)
1163
        {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1164
          if (get_lookup_value(session, (Item_func*)item, table, lookup_field_vals, schema_table))
1 by brian
clean slate
1165
            return 1;
1166
        }
1167
        else
1168
        {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1169
          if (calc_lookup_values_from_cond(session, item, table, lookup_field_vals, schema_table))
1 by brian
clean slate
1170
            return 1;
1171
        }
1172
      }
1173
    }
1174
    return 0;
1175
  }
1176
  else if (cond->type() == Item::FUNC_ITEM &&
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1177
           get_lookup_value(session, (Item_func*) cond, table, lookup_field_vals, schema_table))
1 by brian
clean slate
1178
    return 1;
1179
  return 0;
1180
}
1181
1182
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1183
static bool uses_only_table_name_fields(Item *item, Table *table, plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1184
{
1185
  if (item->type() == Item::FUNC_ITEM)
1186
  {
1187
    Item_func *item_func= (Item_func*)item;
482 by Brian Aker
Remove uint.
1188
    for (uint32_t i=0; i<item_func->argument_count(); i++)
1 by brian
clean slate
1189
    {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1190
      if (! uses_only_table_name_fields(item_func->arguments()[i], table, schema_table))
1 by brian
clean slate
1191
        return 0;
1192
    }
1193
  }
1194
  else if (item->type() == Item::FIELD_ITEM)
1195
  {
1196
    Item_field *item_field= (Item_field*)item;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1197
    const CHARSET_INFO * const cs= system_charset_info;
1063.4.10 by Padraig O'Sullivan
Changing name of FieldInfo class to ColumnInfo based on some feedback from
1198
    const char *field_name1= schema_table->getFirstColumnIndex() >= 0 ?
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
1199
      schema_table->getColumnName(schema_table->getFirstColumnIndex()).c_str() : "";
1063.4.10 by Padraig O'Sullivan
Changing name of FieldInfo class to ColumnInfo based on some feedback from
1200
    const char *field_name2= schema_table->getSecondColumnIndex() >= 0 ?
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
1201
      schema_table->getColumnName(schema_table->getSecondColumnIndex()).c_str() : "";
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1202
    if (table != item_field->field->table ||
481 by Brian Aker
Remove all of uchar.
1203
        (cs->coll->strnncollsp(cs, (unsigned char *) field_name1, strlen(field_name1),
1204
                               (unsigned char *) item_field->field_name,
1 by brian
clean slate
1205
                               strlen(item_field->field_name), 0) &&
481 by Brian Aker
Remove all of uchar.
1206
         cs->coll->strnncollsp(cs, (unsigned char *) field_name2, strlen(field_name2),
1207
                               (unsigned char *) item_field->field_name,
1 by brian
clean slate
1208
                               strlen(item_field->field_name), 0)))
1209
      return 0;
1210
  }
1211
  else if (item->type() == Item::REF_ITEM)
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1212
    return uses_only_table_name_fields(item->real_item(), table, schema_table);
1 by brian
clean slate
1213
1214
  if (item->type() == Item::SUBSELECT_ITEM && !item->const_item())
1215
    return 0;
1216
1217
  return 1;
1218
}
1219
1220
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1221
static COND * make_cond_for_info_schema(COND *cond, Table *table, plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1222
{
1223
  if (!cond)
1224
    return (COND*) 0;
1225
  if (cond->type() == Item::COND_ITEM)
1226
  {
1227
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
1228
    {
1229
      /* Create new top level AND item */
1230
      Item_cond_and *new_cond=new Item_cond_and;
1231
      if (!new_cond)
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1232
        return (COND*) 0;
1 by brian
clean slate
1233
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1234
      Item *item;
1235
      while ((item=li++))
1236
      {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1237
        Item *fix= make_cond_for_info_schema(item, table, schema_table);
1238
        if (fix)
1239
          new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
1240
      }
1241
      switch (new_cond->argument_list()->elements) {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1242
        case 0:
1243
          return (COND*) 0;
1244
        case 1:
1245
          return new_cond->argument_list()->head();
1246
        default:
1247
          new_cond->quick_fix_field();
1248
          return new_cond;
1 by brian
clean slate
1249
      }
1250
    }
1251
    else
1252
    {						// Or list
1253
      Item_cond_or *new_cond=new Item_cond_or;
1254
      if (!new_cond)
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1255
        return (COND*) 0;
1 by brian
clean slate
1256
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1257
      Item *item;
1258
      while ((item=li++))
1259
      {
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1260
        Item *fix=make_cond_for_info_schema(item, table, schema_table);
1261
        if (!fix)
1262
          return (COND*) 0;
1263
        new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
1264
      }
1265
      new_cond->quick_fix_field();
1266
      new_cond->top_level_item();
1267
      return new_cond;
1268
    }
1269
  }
1270
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1271
  if (! uses_only_table_name_fields(cond, table, schema_table))
1 by brian
clean slate
1272
    return (COND*) 0;
1273
  return cond;
1274
}
1275
1276
1277
/**
1278
  @brief   Calculate lookup values(database name, table name)
1279
1280
  @details This function calculates lookup values(database name, table name)
1281
           from 'WHERE' condition or wild values (for 'SHOW' commands only)
1282
           from LEX struct and fill lookup_field_vals struct field
1283
           with these values.
1284
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1285
  @param[in]      session                   thread Cursor
1 by brian
clean slate
1286
  @param[in]      cond                  WHERE condition
1287
  @param[in]      tables                I_S table
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1288
  @param[in, out] lookup_field_values   Struct which holds lookup values
1 by brian
clean slate
1289
1290
  @return
1291
    0             success
1292
    1             error, there can be no matching records for the condition
1293
*/
1294
520.1.22 by Brian Aker
Second pass of thd cleanup
1295
bool get_lookup_field_values(Session *session, COND *cond, TableList *tables,
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1296
                             LOOKUP_FIELD_VALUES *lookup_field_values,
1297
                             plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1298
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1299
  LEX *lex= session->lex;
461 by Monty Taylor
Removed NullS. bu-bye.
1300
  const char *wild= lex->wild ? lex->wild->ptr() : NULL;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1301
  memset(lookup_field_values, 0, sizeof(LOOKUP_FIELD_VALUES));
1 by brian
clean slate
1302
  switch (lex->sql_command) {
1303
  case SQLCOM_SHOW_DATABASES:
1304
    if (wild)
1305
    {
1306
      lookup_field_values->db_value.str= (char*) wild;
1307
      lookup_field_values->db_value.length= strlen(wild);
1308
      lookup_field_values->wild_db_value= 1;
1309
    }
1310
    return 0;
1311
  case SQLCOM_SHOW_TABLES:
1312
  case SQLCOM_SHOW_TABLE_STATUS:
1313
    lookup_field_values->db_value.str= lex->select_lex.db;
1314
    lookup_field_values->db_value.length=strlen(lex->select_lex.db);
1315
    if (wild)
1316
    {
1317
      lookup_field_values->table_value.str= (char*)wild;
1318
      lookup_field_values->table_value.length= strlen(wild);
1319
      lookup_field_values->wild_table_value= 1;
1320
    }
1321
    return 0;
1322
  default:
1323
    /*
1324
      The "default" is for queries over I_S.
1325
      All previous cases handle SHOW commands.
1326
    */
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1327
    return calc_lookup_values_from_cond(session, cond, tables, lookup_field_values, schema_table);
1 by brian
clean slate
1328
  }
1329
}
1330
1331
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1332
/**
1108.4.6 by David Shrewsbury
Fix to make sure make_db_list gets the directory entries in sorted order, with I_S first.
1333
 * Function used for sorting with std::sort within make_db_list.
1334
 *
1335
 * @returns true if a < b, false otherwise
1336
 */
1337
1338
static bool lex_string_sort(const LEX_STRING *a, const LEX_STRING *b)
1339
{
1340
  return (strcmp(a->str, b->str) < 0);
1341
}
1342
1343
1344
/**
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1345
 * @brief
1346
 *   Create db names list. Information schema name always is first in list
1347
 *
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1348
 * @param[in]  session          Thread Cursor
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1349
 * @param[out] files            List of db names
1350
 * @param[in]  wild             Wild string
1351
 * @param[in]  idx_field_vals   idx_field_vals->db_name contains db name or
1352
 *                              wild string
1353
 * @param[out] with_i_schema    Returns 1 if we added 'IS' name to list
1354
 *                              otherwise returns 0
1355
 *
1356
 * @retval 0   Success
1357
 * @retval 1   Error
1358
 */
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1359
int make_db_list(Session *session, vector<LEX_STRING*> &files,
1 by brian
clean slate
1360
                 LOOKUP_FIELD_VALUES *lookup_field_vals,
1361
                 bool *with_i_schema)
1362
{
1363
  LEX_STRING *i_s_name_copy= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
1364
  i_s_name_copy= session->make_lex_string(i_s_name_copy,
575.4.7 by Monty Taylor
More header cleanup.
1365
                                      INFORMATION_SCHEMA_NAME.c_str(),
1366
                                      INFORMATION_SCHEMA_NAME.length(), true);
1 by brian
clean slate
1367
  *with_i_schema= 0;
1368
  if (lookup_field_vals->wild_db_value)
1369
  {
1370
    /*
1371
      This part of code is only for SHOW DATABASES command.
1372
      idx_field_vals->db_value can be 0 when we don't use
1373
      LIKE clause (see also get_index_field_values() function)
1374
    */
1375
    if (!lookup_field_vals->db_value.str ||
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1376
        !wild_case_compare(system_charset_info,
575.4.7 by Monty Taylor
More header cleanup.
1377
                           INFORMATION_SCHEMA_NAME.c_str(),
1 by brian
clean slate
1378
                           lookup_field_vals->db_value.str))
1379
    {
1380
      *with_i_schema= 1;
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1381
      files.push_back(i_s_name_copy);
1 by brian
clean slate
1382
    }
1108.4.6 by David Shrewsbury
Fix to make sure make_db_list gets the directory entries in sorted order, with I_S first.
1383
1384
    if (find_schemas(session, files, drizzle_data_home,
1385
                     lookup_field_vals->db_value.str) == true)
1386
    {
1093.1.47 by Jay Pipes
Merge David's my_dir_removal
1387
      return 1;
1108.4.6 by David Shrewsbury
Fix to make sure make_db_list gets the directory entries in sorted order, with I_S first.
1388
    }
1389
1390
    sort(files.begin()+1, files.end(), lex_string_sort);
1093.1.47 by Jay Pipes
Merge David's my_dir_removal
1391
    return 0;
1 by brian
clean slate
1392
  }
1393
1394
1395
  /*
1396
    If we have db lookup vaule we just add it to list and
1397
    exit from the function
1398
  */
1399
  if (lookup_field_vals->db_value.str)
1400
  {
575.4.7 by Monty Taylor
More header cleanup.
1401
    if (!my_strcasecmp(system_charset_info, INFORMATION_SCHEMA_NAME.c_str(),
1 by brian
clean slate
1402
                       lookup_field_vals->db_value.str))
1403
    {
1404
      *with_i_schema= 1;
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1405
      files.push_back(i_s_name_copy);
1 by brian
clean slate
1406
      return 0;
1407
    }
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1408
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1409
    files.push_back(&lookup_field_vals->db_value);
1 by brian
clean slate
1410
    return 0;
1411
  }
1412
1413
  /*
1414
    Create list of existing databases. It is used in case
1415
    of select from information schema table
1416
  */
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1417
  files.push_back(i_s_name_copy);
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1418
1 by brian
clean slate
1419
  *with_i_schema= 1;
1108.4.6 by David Shrewsbury
Fix to make sure make_db_list gets the directory entries in sorted order, with I_S first.
1420
1421
  if (find_schemas(session, files, drizzle_data_home, NULL) == true)
1422
  {
1093.1.47 by Jay Pipes
Merge David's my_dir_removal
1423
    return 1;
1108.4.6 by David Shrewsbury
Fix to make sure make_db_list gets the directory entries in sorted order, with I_S first.
1424
  }
1425
1426
  sort(files.begin()+1, files.end(), lex_string_sort);
1093.1.47 by Jay Pipes
Merge David's my_dir_removal
1427
  return 0;
1 by brian
clean slate
1428
}
1429
1430
1431
/**
1432
  @brief          Create table names list
1433
1434
  @details        The function creates the list of table names in
1435
                  database
1436
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1437
  @param[in]      session                   thread Cursor
1 by brian
clean slate
1438
  @param[in]      table_names           List of table names in database
1439
  @param[in]      lex                   pointer to LEX struct
1440
  @param[in]      lookup_field_vals     pointer to LOOKUP_FIELD_VALUE struct
163 by Brian Aker
Merge Monty's code.
1441
  @param[in]      with_i_schema         true means that we add I_S tables to list
1 by brian
clean slate
1442
  @param[in]      db_name               database name
1443
1444
  @return         Operation status
1445
    @retval       0           ok
1446
    @retval       1           fatal error
1208.3.2 by brian
Update for Cursor renaming.
1447
    @retval       2           Not fatal error; Safe to ignore this cursor list
1 by brian
clean slate
1448
*/
1449
1450
static int
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
1451
make_table_name_list(Session *session, vector<LEX_STRING*> &table_names,
1 by brian
clean slate
1452
                     LOOKUP_FIELD_VALUES *lookup_field_vals,
1453
                     bool with_i_schema, LEX_STRING *db_name)
1454
{
1455
  char path[FN_REFLEN];
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
1456
  set<string> set_of_names;
1160.1.1 by Brian Aker
Refactor SE createTable back to engine class.
1457
1039.1.6 by Brian Aker
Refactor for build_table_filename()
1458
  build_table_filename(path, sizeof(path), db_name->str, "", false);
1183.1.15 by Brian Aker
I_S now provides its own tables via the SE interface
1459
1 by brian
clean slate
1460
  if (!lookup_field_vals->wild_table_value &&
1461
      lookup_field_vals->table_value.str)
1462
  {
1463
    if (with_i_schema)
1464
    {
1130.1.12 by Monty Taylor
Moved service stuff into plugin/
1465
      if (plugin::InfoSchemaTable::getTable(lookup_field_vals->table_value.str))
1 by brian
clean slate
1466
      {
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1467
        table_names.push_back(&lookup_field_vals->table_value);
1 by brian
clean slate
1468
      }
1469
    }
1470
    else
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1471
    {
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1472
      table_names.push_back(&lookup_field_vals->table_value);
1 by brian
clean slate
1473
    }
1474
    return 0;
1475
  }
1476
1095.3.20 by Stewart Smith
start using an iterator like object for traversing tables in a database (SHOW TABLES)
1477
  string db(db_name->str);
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
1478
  plugin::StorageEngine::getTableNames(db, set_of_names);
1479
1480
  /*  
1481
    New I_S engine will make this go away, so ignore lack of foreach() usage.
1482
1483
    Notice how bad this design is... sure we created a set... but then we
1484
    are just pushing to another set. --
1485
    Also... callback design won't work, so we need to rewrite this to
1486
    feed (which means new I_S). For the moment we will not optimize this.
1487
1488
  */
1489
  for (set<string>::iterator it= set_of_names.begin(); it != set_of_names.end(); it++)
1095.3.20 by Stewart Smith
start using an iterator like object for traversing tables in a database (SHOW TABLES)
1490
  {
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
1491
    LEX_STRING *file_name= NULL;
1492
    
1493
    file_name= session->make_lex_string(file_name, (*it).c_str(),
1494
                                        (*it).length(), true);
1495
    const char* wild= lookup_field_vals->table_value.str;
1496
    if (wild && wild_compare((*it).c_str(), wild, 0))
1497
      continue;
1183.1.15 by Brian Aker
I_S now provides its own tables via the SE interface
1498
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
1499
    table_names.push_back(file_name);
1 by brian
clean slate
1500
  }
1095.3.20 by Stewart Smith
start using an iterator like object for traversing tables in a database (SHOW TABLES)
1501
1 by brian
clean slate
1502
  return 0;
1503
}
1504
1505
1506
/**
1507
  @brief          Fill I_S table for SHOW COLUMNS|INDEX commands
1508
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1509
  @param[in]      session                      thread Cursor
327.2.4 by Brian Aker
Refactoring table.h
1510
  @param[in]      tables                   TableList for I_S table
1 by brian
clean slate
1511
  @param[in]      schema_table             pointer to I_S structure
1512
  @param[in]      open_tables_state_backup pointer to Open_tables_state object
1513
                                           which is used to save|restore original
1514
                                           status of variables related to
1515
                                           open tables state
1516
1517
  @return         Operation status
1518
    @retval       0           success
1519
    @retval       1           error
1520
*/
1521
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1522
static int
520.1.22 by Brian Aker
Second pass of thd cleanup
1523
fill_schema_show_cols_or_idxs(Session *session, TableList *tables,
1130.1.7 by Monty Taylor
Renamed plugin::InfoSchema to plugin::InfoSchemaTable as per Jay.
1524
                              plugin::InfoSchemaTable *schema_table,
1 by brian
clean slate
1525
                              Open_tables_state *open_tables_state_backup)
1526
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1527
  LEX *lex= session->lex;
1 by brian
clean slate
1528
  bool res;
1529
  LEX_STRING tmp_lex_string, tmp_lex_string1, *db_name, *table_name;
1530
  enum_sql_command save_sql_command= lex->sql_command;
327.2.4 by Brian Aker
Refactoring table.h
1531
  TableList *show_table_list= (TableList*) tables->schema_select_lex->
1 by brian
clean slate
1532
    table_list.first;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1533
  Table *table= tables->table;
1 by brian
clean slate
1534
  int error= 1;
1535
1536
  lex->all_selects_list= tables->schema_select_lex;
1537
  /*
520.1.22 by Brian Aker
Second pass of thd cleanup
1538
    Restore session->temporary_tables to be able to process
1 by brian
clean slate
1539
    temporary tables(only for 'show index' & 'show columns').
1540
    This should be changed when processing of temporary tables for
1541
    I_S tables will be done.
1542
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1543
  session->temporary_tables= open_tables_state_backup->temporary_tables;
1 by brian
clean slate
1544
  /*
1545
    Let us set fake sql_command so views won't try to merge
1546
    themselves into main statement. If we don't do this,
1547
    SELECT * from information_schema.xxxx will cause problems.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1548
    SQLCOM_SHOW_FIELDS is used because it satisfies 'only_view_structure()'
1 by brian
clean slate
1549
  */
1550
  lex->sql_command= SQLCOM_SHOW_FIELDS;
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1551
  res= session->openTables(show_table_list, DRIZZLE_LOCK_IGNORE_FLUSH);
1 by brian
clean slate
1552
  lex->sql_command= save_sql_command;
1553
  /*
1554
    get_all_tables() returns 1 on failure and 0 on success thus
1555
    return only these and not the result code of ::process_table()
1556
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1557
    We should use show_table_list->alias instead of
1 by brian
clean slate
1558
    show_table_list->table_name because table_name
1559
    could be changed during opening of I_S tables. It's safe
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1560
    to use alias because alias contains original table name
1561
    in this case(this part of code is used only for
1 by brian
clean slate
1562
    'show columns' & 'show statistics' commands).
1563
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1564
   table_name= session->make_lex_string(&tmp_lex_string1, show_table_list->alias,
163 by Brian Aker
Merge Monty's code.
1565
                                    strlen(show_table_list->alias), false);
520.1.22 by Brian Aker
Second pass of thd cleanup
1566
   db_name= session->make_lex_string(&tmp_lex_string, show_table_list->db,
163 by Brian Aker
Merge Monty's code.
1567
                                 show_table_list->db_length, false);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1568
1 by brian
clean slate
1569
1089.1.3 by Brian Aker
Fix protobuf to release memory. Add in assert() for wrong column usage. Fix
1570
   table->setWriteSet();
1063.4.3 by Padraig O'Sullivan
Removed the function pointers in the InfoSchemaTable class. Added a new
1571
   error= test(schema_table->processTable(session, show_table_list,
1572
                                          table, res, db_name,
1573
                                          table_name));
520.1.22 by Brian Aker
Second pass of thd cleanup
1574
   session->temporary_tables= 0;
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1575
   session->close_tables_for_reopen(&show_table_list);
1576
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1577
   return(error);
1 by brian
clean slate
1578
}
1579
1580
1581
/**
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1582
  @brief          Fill I_S table for SHOW Table NAMES commands
1 by brian
clean slate
1583
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1584
  @param[in]      session                      thread Cursor
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1585
  @param[in]      table                    Table struct for I_S table
1 by brian
clean slate
1586
  @param[in]      db_name                  database name
1587
  @param[in]      table_name               table name
163 by Brian Aker
Merge Monty's code.
1588
  @param[in]      with_i_schema            I_S table if true
1 by brian
clean slate
1589
1590
  @return         Operation status
1591
    @retval       0           success
1592
    @retval       1           error
1593
*/
1594
520.1.22 by Brian Aker
Second pass of thd cleanup
1595
static int fill_schema_table_names(Session *session, Table *table,
1 by brian
clean slate
1596
                                   LEX_STRING *db_name, LEX_STRING *table_name,
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1597
                                   bool with_i_schema,
1598
                                   plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1599
{
1600
  if (with_i_schema)
1601
  {
1602
    table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"),
1603
                           system_charset_info);
1604
  }
1605
  else
1606
  {
1607
    char path[FN_REFLEN];
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1608
    (void) build_table_filename(path, sizeof(path), db_name->str,
1039.1.6 by Brian Aker
Refactor for build_table_filename()
1609
                                table_name->str, false);
590.1.7 by Stewart Smith
remove mysql_frm_type
1610
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1611
      table->field[3]->store(STRING_WITH_LEN("BASE Table"),
1612
                             system_charset_info);
1613
520.1.22 by Brian Aker
Second pass of thd cleanup
1614
    if (session->is_error() && session->main_da.sql_errno() == ER_NO_SUCH_TABLE)
1 by brian
clean slate
1615
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1616
      session->clear_error();
1 by brian
clean slate
1617
      return 0;
1618
    }
1619
  }
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1620
  schema_table->addRow(table->record[0], table->s->reclength);
1 by brian
clean slate
1621
  return 0;
1622
}
1623
1259.5.2 by Stewart Smith
remove mention of getting information from FRM files for INFORMATION_SCHEMA. The comment was now pretty much all lies anyway
1624
int plugin::InfoSchemaMethods::fillTable(Session *session,
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1625
                                         Table *table,
1626
                                         plugin::InfoSchemaTable *schema_table)
1 by brian
clean slate
1627
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1628
  LEX *lex= session->lex;
846 by Brian Aker
Removing on typedeffed class.
1629
  Select_Lex *old_all_select_lex= lex->all_selects_list;
1 by brian
clean slate
1630
  enum_sql_command save_sql_command= lex->sql_command;
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1631
  Select_Lex *lsel= table->pos_in_table_list->schema_select_lex;
846 by Brian Aker
Removing on typedeffed class.
1632
  Select_Lex sel;
1 by brian
clean slate
1633
  LOOKUP_FIELD_VALUES lookup_field_vals;
1634
  bool with_i_schema;
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1635
  vector<LEX_STRING*> db_names, table_names;
1183.1.31 by Padraig O'Sullivan
Changed the fillTable method to not take a COND parameter anymore.
1636
  /* the WHERE clause */
1637
  COND *cond= table->reginfo.join_tab->select_cond;
1 by brian
clean slate
1638
  COND *partial_cond= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1639
  uint32_t derived_tables= lex->derived_tables;
1 by brian
clean slate
1640
  int error= 1;
1641
  Open_tables_state open_tables_state_backup;
1642
  Query_tables_list query_tables_list_backup;
520.1.22 by Brian Aker
Second pass of thd cleanup
1643
  bool old_value= session->no_warnings_for_error;
1 by brian
clean slate
1644
1645
  /*
1646
    We should not introduce deadlocks even if we already have some
1647
    tables open and locked, since we won't lock tables which we will
1648
    open and will ignore possible name-locks for these tables.
1649
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1650
  session->reset_n_backup_open_tables_state(&open_tables_state_backup);
1 by brian
clean slate
1651
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1652
  /*
1 by brian
clean slate
1653
    this branch processes SHOW FIELDS, SHOW INDEXES commands.
1654
    see sql_parse.cc, prepare_schema_table() function where
1655
    this values are initialized
1656
  */
1657
  if (lsel && lsel->table_list.first)
1658
  {
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1659
    error= fill_schema_show_cols_or_idxs(session, table->pos_in_table_list, schema_table,
1 by brian
clean slate
1660
                                         &open_tables_state_backup);
1661
    goto err;
1662
  }
1663
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1664
  if (get_lookup_field_values(session, 
1665
                              cond, 
1666
                              table->pos_in_table_list, 
1667
                              &lookup_field_vals,
1668
                              schema_table))
1 by brian
clean slate
1669
  {
1670
    error= 0;
1671
    goto err;
1672
  }
1673
1674
  if (!lookup_field_vals.wild_db_value && !lookup_field_vals.wild_table_value)
1675
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1676
    /*
1 by brian
clean slate
1677
      if lookup value is empty string then
1678
      it's impossible table name or db name
1679
    */
140 by Brian Aker
Remove dead class, clean up warning.
1680
    if ((lookup_field_vals.db_value.str && !lookup_field_vals.db_value.str[0]) ||
1681
        (lookup_field_vals.table_value.str && !lookup_field_vals.table_value.str[0]))
1 by brian
clean slate
1682
    {
1683
      error= 0;
1684
      goto err;
1685
    }
1686
  }
1687
1688
  if (lookup_field_vals.db_value.length &&
1689
      !lookup_field_vals.wild_db_value)
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1690
    table->pos_in_table_list->has_db_lookup_value= true;
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1691
1 by brian
clean slate
1692
  if (lookup_field_vals.table_value.length &&
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1693
      !lookup_field_vals.wild_table_value)
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1694
    table->pos_in_table_list->has_table_lookup_value= true;
1 by brian
clean slate
1695
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1696
  if (table->pos_in_table_list->has_db_lookup_value && 
1697
      table->pos_in_table_list->has_table_lookup_value)
1 by brian
clean slate
1698
    partial_cond= 0;
1699
  else
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1700
    partial_cond= make_cond_for_info_schema(cond, table, schema_table);
1 by brian
clean slate
1701
1702
  if (lex->describe)
1703
  {
1704
    /* EXPLAIN SELECT */
1705
    error= 0;
1706
    goto err;
1707
  }
1708
1089.1.3 by Brian Aker
Fix protobuf to release memory. Add in assert() for wrong column usage. Fix
1709
  table->setWriteSet();
1071.1.3 by Nathan Williams
Removed st_add_schema_table struct and moved data members into the AddSchemaTable class/functor. That was the only place it was used.
1710
  if (make_db_list(session, db_names, &lookup_field_vals, &with_i_schema))
1 by brian
clean slate
1711
    goto err;
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1712
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1713
  for (vector<LEX_STRING*>::iterator db_name= db_names.begin(); db_name != db_names.end(); ++db_name )
1 by brian
clean slate
1714
  {
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1715
    session->no_warnings_for_error= 1;
1716
    table_names.clear();
1183.1.5 by Brian Aker
Reworked getTableNames() interface. Way simpler, less mallocs....
1717
    int res= make_table_name_list(session, table_names,
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1718
                                  &lookup_field_vals,
1719
                                  with_i_schema, *db_name);
1720
1721
    if (res == 2)   /* Not fatal error, continue */
1722
      continue;
1723
1724
    if (res)
1725
      goto err;
1726
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1727
    
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1728
    for (vector<LEX_STRING*>::iterator table_name= table_names.begin(); table_name != table_names.end(); ++table_name)
1 by brian
clean slate
1729
    {
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1730
      table->restoreRecordAsDefault();
1731
      table->field[schema_table->getFirstColumnIndex()]->
1732
        store((*db_name)->str, (*db_name)->length, system_charset_info);
1733
      table->field[schema_table->getSecondColumnIndex()]->
1734
        store((*table_name)->str, (*table_name)->length, system_charset_info);
1 by brian
clean slate
1735
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1736
      if (!partial_cond || partial_cond->val_int())
1 by brian
clean slate
1737
      {
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1738
        /* SHOW Table NAMES command */
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1739
        if (schema_table->getTableName().compare("TABLE_NAMES") == 0)
1 by brian
clean slate
1740
        {
1225.1.12 by Padraig O'Sullivan
Removed fill_schema_table_from_frm method.
1741
          if (fill_schema_table_names(session, 
1225.1.19 by Padraig O'Sullivan
Modified the fillTable method to not take a TableList parameter anymore. Instead we now take a Table
1742
                                      table, 
1225.1.12 by Padraig O'Sullivan
Removed fill_schema_table_from_frm method.
1743
                                      *db_name,
1744
                                      *table_name, 
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1745
                                      with_i_schema,
1746
                                      schema_table))
1 by brian
clean slate
1747
            continue;
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1748
        }
1749
        else
1750
        {
1751
          LEX_STRING tmp_lex_string, orig_db_name;
1752
          /*
1753
            Set the parent lex of 'sel' because it is needed by
1754
            sel.init_query() which is called inside make_table_list.
1755
          */
1756
          session->no_warnings_for_error= 1;
1757
          sel.parent_lex= lex;
1758
          /* db_name can be changed in make_table_list() func */
1225.1.12 by Padraig O'Sullivan
Removed fill_schema_table_from_frm method.
1759
          if (! session->make_lex_string(&orig_db_name, 
1760
                                         (*db_name)->str,
1761
                                         (*db_name)->length, 
1762
                                         false))
1763
          {
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1764
            goto err;
1225.1.12 by Padraig O'Sullivan
Removed fill_schema_table_from_frm method.
1765
          }
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1766
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1767
          if (make_table_list(session, &sel, *db_name, *table_name))
1768
            goto err;
1071.1.4 by Nathan Williams
Merged trunk, resolved conflicts.
1769
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1770
          TableList *show_table_list= (TableList*) sel.table_list.first;
1771
          lex->all_selects_list= &sel;
1772
          lex->derived_tables= 0;
1773
          lex->sql_command= SQLCOM_SHOW_FIELDS;
1774
          show_table_list->i_s_requested_object=
1775
            schema_table->getRequestedObject();
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1776
          res= session->openTables(show_table_list, DRIZZLE_LOCK_IGNORE_FLUSH);
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1777
          lex->sql_command= save_sql_command;
1778
          /*
1779
            XXX->  show_table_list has a flag i_is_requested,
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1780
            and when it's set, openTables()
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1781
            can return an error without setting an error message
1782
            in Session, which is a hack. This is why we have to
1783
            check for res, then for session->is_error() only then
1784
            for session->main_da.sql_errno().
1785
          */
1786
          if (res && session->is_error() &&
1787
              session->main_da.sql_errno() == ER_NO_SUCH_TABLE)
1788
          {
1789
            /*
1790
              Hide error for not existing table.
1791
              This error can occur for example when we use
1792
              where condition with db name and table name and this
1793
              table does not exist.
1794
            */
1795
            res= 0;
1796
            session->clear_error();
1797
          }
1 by brian
clean slate
1798
          else
1799
          {
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1800
            /*
1801
              We should use show_table_list->alias instead of
1802
              show_table_list->table_name because table_name
1803
              could be changed during opening of I_S tables. It's safe
1804
              to use alias because alias contains original table name
1805
              in this case.
1806
            */
1807
            session->make_lex_string(&tmp_lex_string, show_table_list->alias,
1808
                                     strlen(show_table_list->alias), false);
1809
            res= schema_table->processTable(session, show_table_list, table,
1810
                                            res, &orig_db_name,
1811
                                            &tmp_lex_string);
1812
            session->close_tables_for_reopen(&show_table_list);
1 by brian
clean slate
1813
          }
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1814
          assert(!lex->query_tables_own_last);
1815
          if (res)
1816
            goto err;
1 by brian
clean slate
1817
        }
1818
      }
1819
    }
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1820
    /*
1821
      If we have information schema its always the first table and only
1822
      the first table. Reset for other tables.
1823
    */
1824
    with_i_schema= 0;
1 by brian
clean slate
1825
  }
1826
1827
  error= 0;
1071.1.2 by Nathan Williams
Converted st_add_schema_table::files from List<LEX_STRING> to std::vector<LEX_STRING*>.
1828
1 by brian
clean slate
1829
err:
520.1.22 by Brian Aker
Second pass of thd cleanup
1830
  session->restore_backup_open_tables_state(&open_tables_state_backup);
1 by brian
clean slate
1831
  lex->derived_tables= derived_tables;
1832
  lex->all_selects_list= old_all_select_lex;
1833
  lex->sql_command= save_sql_command;
520.1.22 by Brian Aker
Second pass of thd cleanup
1834
  session->no_warnings_for_error= old_value;
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1835
  return(error);
1 by brian
clean slate
1836
}
1837
1838
1839
/**
1840
  @brief    Store field characteristics into appropriate I_S table columns
1841
1842
  @param[in]      table             I_S table
1843
  @param[in]      field             processed field
1844
  @param[in]      cs                I_S table charset
1845
  @param[in]      offset            offset from beginning of table
1846
                                    to DATE_TYPE column in I_S table
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1847
1 by brian
clean slate
1848
  @return         void
1849
*/
1850
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
1851
static void store_column_type(Table *table, Field *field,
1852
                              const CHARSET_INFO * const cs,
1853
                              uint32_t offset)
1 by brian
clean slate
1854
{
1855
  bool is_blob;
1856
  int decimals, field_length;
1857
  const char *tmp_buff;
1858
  char column_type_buff[MAX_FIELD_WIDTH];
1859
  String column_type(column_type_buff, sizeof(column_type_buff), cs);
1860
1861
  field->sql_type(column_type);
1862
  /* DTD_IDENTIFIER column */
1863
  table->field[offset + 7]->store(column_type.ptr(), column_type.length(), cs);
1864
  table->field[offset + 7]->set_notnull();
1865
  tmp_buff= strchr(column_type.ptr(), '(');
1866
  /* DATA_TYPE column */
1867
  table->field[offset]->store(column_type.ptr(),
1868
                         (tmp_buff ? tmp_buff - column_type.ptr() :
1869
                          column_type.length()), cs);
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1870
  is_blob= (field->type() == DRIZZLE_TYPE_BLOB);
1 by brian
clean slate
1871
  if (field->has_charset() || is_blob ||
238 by Brian Aker
Pass through sql_show to remove type to be removed.
1872
      field->real_type() == DRIZZLE_TYPE_VARCHAR)  // For varbinary type
1 by brian
clean slate
1873
  {
205 by Brian Aker
uint32 -> uin32_t
1874
    uint32_t octet_max_length= field->max_display_length();
1875
    if (is_blob && octet_max_length != (uint32_t) 4294967295U)
1 by brian
clean slate
1876
      octet_max_length /= field->charset()->mbmaxlen;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1877
    int64_t char_max_len= is_blob ?
152 by Brian Aker
longlong replacement
1878
      (int64_t) octet_max_length / field->charset()->mbminlen :
1879
      (int64_t) octet_max_length / field->charset()->mbmaxlen;
1 by brian
clean slate
1880
    /* CHARACTER_MAXIMUM_LENGTH column*/
163 by Brian Aker
Merge Monty's code.
1881
    table->field[offset + 1]->store(char_max_len, true);
1 by brian
clean slate
1882
    table->field[offset + 1]->set_notnull();
1883
    /* CHARACTER_OCTET_LENGTH column */
163 by Brian Aker
Merge Monty's code.
1884
    table->field[offset + 2]->store((int64_t) octet_max_length, true);
1 by brian
clean slate
1885
    table->field[offset + 2]->set_notnull();
1886
  }
1887
1888
  /*
1889
    Calculate field_length and decimals.
1890
    They are set to -1 if they should not be set (we should return NULL)
1891
  */
1892
1893
  decimals= field->decimals();
1894
  switch (field->type()) {
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
1895
  case DRIZZLE_TYPE_DECIMAL:
1896
    field_length= ((Field_decimal*) field)->precision;
1 by brian
clean slate
1897
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1898
  case DRIZZLE_TYPE_LONG:
1899
  case DRIZZLE_TYPE_LONGLONG:
1 by brian
clean slate
1900
    field_length= field->max_display_length() - 1;
1901
    break;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1902
  case DRIZZLE_TYPE_DOUBLE:
1 by brian
clean slate
1903
    field_length= field->field_length;
1904
    if (decimals == NOT_FIXED_DEC)
1905
      decimals= -1;                           // return NULL
1906
    break;
1907
  default:
1908
    field_length= decimals= -1;
1909
    break;
1910
  }
1911
1912
  /* NUMERIC_PRECISION column */
1913
  if (field_length >= 0)
1914
  {
163 by Brian Aker
Merge Monty's code.
1915
    table->field[offset + 3]->store((int64_t) field_length, true);
1 by brian
clean slate
1916
    table->field[offset + 3]->set_notnull();
1917
  }
1918
  /* NUMERIC_SCALE column */
1919
  if (decimals >= 0)
1920
  {
163 by Brian Aker
Merge Monty's code.
1921
    table->field[offset + 4]->store((int64_t) decimals, true);
1 by brian
clean slate
1922
    table->field[offset + 4]->set_notnull();
1923
  }
1924
  if (field->has_charset())
1925
  {
1926
    /* CHARACTER_SET_NAME column*/
1927
    tmp_buff= field->charset()->csname;
1928
    table->field[offset + 5]->store(tmp_buff, strlen(tmp_buff), cs);
1929
    table->field[offset + 5]->set_notnull();
1930
    /* COLLATION_NAME column */
1931
    tmp_buff= field->charset()->name;
1932
    table->field[offset + 6]->store(tmp_buff, strlen(tmp_buff), cs);
1933
    table->field[offset + 6]->set_notnull();
1934
  }
1935
}
1936
1937
1225.1.2 by Padraig O'Sullivan
Resolved issue with segmentation fault on some queries on some I_S tables. Needed to change the
1938
int plugin::InfoSchemaMethods::processTable(
1939
            plugin::InfoSchemaTable *store_table,
1940
            Session *session, 
1941
            TableList *tables,
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1942
				    Table *table, bool res,
1 by brian
clean slate
1943
				    LEX_STRING *db_name,
1225.1.2 by Padraig O'Sullivan
Resolved issue with segmentation fault on some queries on some I_S tables. Needed to change the
1944
				    LEX_STRING *table_name)
1 by brian
clean slate
1945
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1946
  LEX *lex= session->lex;
461 by Monty Taylor
Removed NullS. bu-bye.
1947
  const char *wild= lex->wild ? lex->wild->ptr() : NULL;
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
1948
  const CHARSET_INFO * const cs= system_charset_info;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1949
  Table *show_table;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
1950
  TableShare *show_table_share;
1 by brian
clean slate
1951
  Field **ptr, *field, *timestamp_field;
1952
  int count;
1953
1954
  if (res)
1955
  {
1956
    if (lex->sql_command != SQLCOM_SHOW_FIELDS)
1957
    {
1958
      /*
1959
        I.e. we are in SELECT FROM INFORMATION_SCHEMA.COLUMS
1960
        rather than in SHOW COLUMNS
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1961
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1962
      if (session->is_error())
1963
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1964
                     session->main_da.sql_errno(), session->main_da.message());
1965
      session->clear_error();
1 by brian
clean slate
1966
      res= 0;
1967
    }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1968
    return(res);
1 by brian
clean slate
1969
  }
1970
1971
  show_table= tables->table;
1972
  show_table_share= show_table->s;
1973
  count= 0;
1974
1225.1.20 by Padraig O'Sullivan
Removed all remnants of schema_table from the TableList class. This cleans up a bunch of code.
1975
  ptr= show_table_share->field;
1976
  timestamp_field= show_table_share->timestamp_field;
1089.1.3 by Brian Aker
Fix protobuf to release memory. Add in assert() for wrong column usage. Fix
1977
1978
  /* For the moment we just set everything to read */
1979
  if (!show_table->read_set)
1980
  {
1103.6.3 by Padraig O'Sullivan
Fixing up more calls to the old bitmap API.
1981
    show_table->def_read_set.setAll();
1089.1.3 by Brian Aker
Fix protobuf to release memory. Add in assert() for wrong column usage. Fix
1982
    show_table->read_set= &show_table->def_read_set;
1983
  }
1984
  show_table->use_all_columns();               // Required for default
1 by brian
clean slate
1985
1986
  for (; (field= *ptr) ; ptr++)
1987
  {
481 by Brian Aker
Remove all of uchar.
1988
    unsigned char *pos;
1 by brian
clean slate
1989
    char tmp[MAX_FIELD_WIDTH];
1990
    String type(tmp,sizeof(tmp), system_charset_info);
1991
    char *end;
1992
1993
    /* to satisfy 'field->val_str' ASSERTs */
1994
    field->table= show_table;
520.1.22 by Brian Aker
Second pass of thd cleanup
1995
    show_table->in_use= session;
1 by brian
clean slate
1996
1997
    if (wild && wild[0] &&
1998
        wild_case_compare(system_charset_info, field->field_name,wild))
1999
      continue;
2000
2001
    count++;
2002
    /* Get default row, with all NULL fields set to NULL */
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
2003
    table->restoreRecordAsDefault();
1 by brian
clean slate
2004
2005
    table->field[1]->store(db_name->str, db_name->length, cs);
2006
    table->field[2]->store(table_name->str, table_name->length, cs);
2007
    table->field[3]->store(field->field_name, strlen(field->field_name),
2008
                           cs);
163 by Brian Aker
Merge Monty's code.
2009
    table->field[4]->store((int64_t) count, true);
1 by brian
clean slate
2010
1014.3.4 by Brian Aker
Remove dead session calls.
2011
    if (get_field_default_value(timestamp_field, field, &type, 0))
1 by brian
clean slate
2012
    {
2013
      table->field[5]->store(type.ptr(), type.length(), cs);
2014
      table->field[5]->set_notnull();
2015
    }
481 by Brian Aker
Remove all of uchar.
2016
    pos=(unsigned char*) ((field->flags & NOT_NULL_FLAG) ?  "NO" : "YES");
1 by brian
clean slate
2017
    table->field[6]->store((const char*) pos,
2018
                           strlen((const char*) pos), cs);
2019
    store_column_type(table, field, cs, 7);
2020
481 by Brian Aker
Remove all of uchar.
2021
    pos=(unsigned char*) ((field->flags & PRI_KEY_FLAG) ? "PRI" :
1 by brian
clean slate
2022
                 (field->flags & UNIQUE_KEY_FLAG) ? "UNI" :
2023
                 (field->flags & MULTIPLE_KEY_FLAG) ? "MUL":"");
2024
    table->field[15]->store((const char*) pos,
2025
                            strlen((const char*) pos), cs);
2026
2027
    end= tmp;
2028
    if (field->unireg_check == Field::NEXT_NUMBER)
2029
      table->field[16]->store(STRING_WITH_LEN("auto_increment"), cs);
2030
    if (timestamp_field == field &&
2031
        field->unireg_check != Field::TIMESTAMP_DN_FIELD)
2032
      table->field[16]->store(STRING_WITH_LEN("on update CURRENT_TIMESTAMP"),
2033
                              cs);
2034
    table->field[18]->store(field->comment.str, field->comment.length, cs);
2035
    {
2036
      enum column_format_type column_format= (enum column_format_type)
2037
        ((field->flags >> COLUMN_FORMAT_FLAGS) & COLUMN_FORMAT_MASK);
481 by Brian Aker
Remove all of uchar.
2038
      pos=(unsigned char*)"Default";
1 by brian
clean slate
2039
      table->field[19]->store((const char*) pos,
2040
                              strlen((const char*) pos), cs);
481 by Brian Aker
Remove all of uchar.
2041
      pos=(unsigned char*)(column_format == COLUMN_FORMAT_TYPE_DEFAULT ? "Default" :
1 by brian
clean slate
2042
                   column_format == COLUMN_FORMAT_TYPE_FIXED ? "Fixed" :
2043
                                                             "Dynamic");
2044
      table->field[20]->store((const char*) pos,
2045
                              strlen((const char*) pos), cs);
2046
    }
1225.1.2 by Padraig O'Sullivan
Resolved issue with segmentation fault on some queries on some I_S tables. Needed to change the
2047
    store_table->addRow(table->record[0], table->s->reclength);
1 by brian
clean slate
2048
  }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
2049
  return(0);
1 by brian
clean slate
2050
}
2051
2052
2053
/*
2054
  For old SHOW compatibility. It is used when
2055
  old SHOW doesn't have generated column names
2056
  Make list of fields for SHOW
2057
2058
  SYNOPSIS
1130.1.1 by Monty Taylor
Merged in plugin-slot-reorg patches.
2059
    plugin::InfoSchemaMethods::oldFormat()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2060
    session			thread Cursor
1 by brian
clean slate
2061
    schema_table        pointer to 'schema_tables' element
2062
2063
  RETURN
2064
   1	error
2065
   0	success
2066
*/
2067
1130.1.7 by Monty Taylor
Renamed plugin::InfoSchema to plugin::InfoSchemaTable as per Jay.
2068
int plugin::InfoSchemaMethods::oldFormat(Session *session, plugin::InfoSchemaTable *schema_table)
1063.4.3 by Padraig O'Sullivan
Removed the function pointers in the InfoSchemaTable class. Added a new
2069
  const
1 by brian
clean slate
2070
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2071
  Name_resolution_context *context= &session->lex->select_lex.context;
1130.1.7 by Monty Taylor
Renamed plugin::InfoSchema to plugin::InfoSchemaTable as per Jay.
2072
  const plugin::InfoSchemaTable::Columns columns= schema_table->getColumns();
2073
  plugin::InfoSchemaTable::Columns::const_iterator iter= columns.begin();
1067.2.9 by Padraig O'Sullivan
Removed the getSpecificColumn(), beginColumnInfo(), endColumnInfo() methods
2074
2075
  while (iter != columns.end())
1 by brian
clean slate
2076
  {
1130.1.1 by Monty Taylor
Merged in plugin-slot-reorg patches.
2077
    const plugin::ColumnInfo *column= *iter;
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
2078
    if (column->getOldName().length() != 0)
1 by brian
clean slate
2079
    {
2080
      Item_field *field= new Item_field(context,
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
2081
                                        NULL, NULL,
2082
                                        column->getName().c_str());
1 by brian
clean slate
2083
      if (field)
2084
      {
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
2085
        field->set_name(column->getOldName().c_str(),
2086
                        column->getOldName().length(),
1 by brian
clean slate
2087
                        system_charset_info);
838 by Brian Aker
More class adoption/method
2088
        if (session->add_item_to_list(field))
1 by brian
clean slate
2089
          return 1;
2090
      }
2091
    }
1067.2.9 by Padraig O'Sullivan
Removed the getSpecificColumn(), beginColumnInfo(), endColumnInfo() methods
2092
    ++iter;
1 by brian
clean slate
2093
  }
2094
  return 0;
2095
}
2096
2097
2098
/*
2099
  Generate select from information_schema table
2100
2101
  SYNOPSIS
2102
    make_schema_select()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2103
    session                  thread Cursor
846 by Brian Aker
Removing on typedeffed class.
2104
    sel                  pointer to Select_Lex
1079.2.9 by Padraig O'Sullivan
Removed the dependency on knowing the position of an I_S table in the
2105
    schema_table_name    name of 'schema_tables' element
1 by brian
clean slate
2106
2107
  RETURN
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
2108
    true on error
1 by brian
clean slate
2109
*/
2110
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
2111
bool make_schema_select(Session *session, Select_Lex *sel,
1079.2.9 by Padraig O'Sullivan
Removed the dependency on knowing the position of an I_S table in the
2112
                        const string& schema_table_name)
1 by brian
clean slate
2113
{
1130.1.12 by Monty Taylor
Moved service stuff into plugin/
2114
  plugin::InfoSchemaTable *schema_table= plugin::InfoSchemaTable::getTable(schema_table_name.c_str());
1 by brian
clean slate
2115
  LEX_STRING db, table;
2116
  /*
2117
     We have to make non const db_name & table_name
2118
     because of lower_case_table_names
2119
  */
575.4.7 by Monty Taylor
More header cleanup.
2120
  session->make_lex_string(&db, INFORMATION_SCHEMA_NAME.c_str(),
2121
                       INFORMATION_SCHEMA_NAME.length(), 0);
1076.2.2 by Padraig O'Sullivan
Converted the const char * members of InfoSchemaTable to be std::string
2122
  session->make_lex_string(&table, schema_table->getTableName().c_str(),
2123
                           schema_table->getTableName().length(), 0);
1063.4.3 by Padraig O'Sullivan
Removed the function pointers in the InfoSchemaTable class. Added a new
2124
  if (schema_table->oldFormat(session, schema_table) ||   /* Handle old syntax */
1093.1.57 by Jay Pipes
Merge and resolved conflicts for Monty's plugins/slots reorganization
2125
      ! sel->add_table_to_list(session, new Table_ident(db, table), 0, 0, TL_READ))
1 by brian
clean slate
2126
  {
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
2127
    return true;
1 by brian
clean slate
2128
  }
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
2129
  return false;
1 by brian
clean slate
2130
}
2131