~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
1046 by Brian Aker
Merge Jay.
3
  This program is free software; you can redistribute it and/or modify
4
  it under the terms of the GNU General Public License as published by
5
  the Free Software Foundation; version 2 of the License.
6
7
  This program is distributed in the hope that it will be useful,
8
  but WITHOUT ANY WARRANTY; without even the implied warranty of
9
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
  GNU General Public License for more details.
11
12
  You should have received a copy of the GNU General Public License
13
  along with this program; if not, write to the Free Software
1802.10.2 by Monty Taylor
Update all of the copyright headers to include the correct address.
14
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
1 by brian
clean slate
15
16
17
/* Basic functions needed by many modules */
1241.9.36 by Monty Taylor
ZOMG. I deleted drizzled/server_includes.h.
18
#include "config.h"
1046.1.4 by Brian Aker
Move lazy read of refresh to outside of LOCK_open (we don't lock the refresh
19
#include <assert.h>
584.1.13 by Monty Taylor
Split out a little more code. Removed table_list.h from common_includes.
20
575.4.7 by Monty Taylor
More header cleanup.
21
#include <signal.h>
1 by brian
clean slate
22
481.1.15 by Monty Taylor
Removed time.h and sys/time.h from global.h.
23
#if TIME_WITH_SYS_TIME
24
# include <sys/time.h>
25
# include <time.h>
26
#else
27
# if HAVE_SYS_TIME_H
28
#  include <sys/time.h>
29
# else
30
#  include <time.h>
31
# endif
32
#endif
1241.9.64 by Monty Taylor
Moved remaining non-public portions of mysys and mystrings to drizzled/internal.
33
#include "drizzled/internal/my_pthread.h"
1689.2.10 by Brian Aker
Move thread_var out to its own include file.
34
#include "drizzled/internal/thread_var.h"
575.4.7 by Monty Taylor
More header cleanup.
35
36
#include <drizzled/sql_select.h>
37
#include <drizzled/error.h>
38
#include <drizzled/gettext.h>
39
#include <drizzled/nested_join.h>
40
#include <drizzled/sql_base.h>
41
#include <drizzled/show.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
42
#include <drizzled/item/cmpfunc.h>
1039.5.31 by Jay Pipes
This patch does a few things:
43
#include <drizzled/replication_services.h>
670.2.4 by Monty Taylor
Removed more stuff from the headers.
44
#include <drizzled/check_stack_overrun.h>
45
#include <drizzled/lock.h>
1130.1.12 by Monty Taylor
Moved service stuff into plugin/
46
#include <drizzled/plugin/listen.h>
1241.9.44 by Monty Taylor
Made magic with cached_directory.
47
#include "drizzled/cached_directory.h"
1999.4.9 by Brian Aker
Created EPOCH
48
#include <drizzled/field/epoch.h>
1130.3.1 by Monty Taylor
Moved multi_malloc into drizzled since it's not going away any time soon. Also,
49
#include <drizzled/field/null.h>
1241.9.23 by Monty Taylor
Removed sql_table.h from server_includes.h.
50
#include "drizzled/sql_table.h"
1241.9.28 by Monty Taylor
Removed global_charset_info.h from server_includes.h
51
#include "drizzled/global_charset_info.h"
1241.9.31 by Monty Taylor
Moved global pthread variables into their own header.
52
#include "drizzled/pthread_globals.h"
1241.9.64 by Monty Taylor
Moved remaining non-public portions of mysys and mystrings to drizzled/internal.
53
#include "drizzled/internal/iocache.h"
1300.5.2 by Monty Taylor
Changed build to build the almost all of drizzle into libdrizzled and then
54
#include "drizzled/drizzled.h"
1317.2.5 by Monty Taylor
Prevent the user from seeing or attempting to access tables that he is not
55
#include "drizzled/plugin/authorization.h"
1843.8.4 by Brian Aker
Committing refactor of table out (this is part of the concurrency work).
56
#include "drizzled/table/temporary.h"
1843.8.6 by Brian Aker
Move placeholder to table directory.
57
#include "drizzled/table/placeholder.h"
1877.2.3 by Brian Aker
Move unused under table
58
#include "drizzled/table/unused.h"
1241.9.28 by Monty Taylor
Removed global_charset_info.h from server_includes.h
59
1089.2.4 by David Shrewsbury
Put CachedDirectory in mysys namespace; added std namespace to sql_base.cc and default.cc to replace std::
60
using namespace std;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
61
62
namespace drizzled
63
{
1089.2.4 by David Shrewsbury
Put CachedDirectory in mysys namespace; added std namespace to sql_base.cc and default.cc to replace std::
64
1241.9.33 by Monty Taylor
Moved most of the global vars to set_var where they belong.
65
extern bool volatile shutdown_in_progress;
66
1 by brian
clean slate
67
bool table_cache_init(void)
68
{
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
69
  return false;
70
}
71
72
uint32_t cached_open_tables(void)
73
{
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
74
  return table::getCache().size();
1 by brian
clean slate
75
}
76
77
void table_cache_free(void)
78
{
1109.1.4 by Brian Aker
More Table refactor
79
  refresh_version++;				// Force close of open tables
80
1877.2.3 by Brian Aker
Move unused under table
81
  table::getUnused().clear();
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
82
  table::getCache().clear();
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
83
}
1 by brian
clean slate
84
85
/*
1208.3.2 by brian
Update for Cursor renaming.
86
  Close cursor handle, but leave the table in the table cache
1 by brian
clean slate
87
88
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
89
  close_handle_and_leave_table_as_lock()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
90
  table		Table Cursor
1 by brian
clean slate
91
92
  NOTES
1046 by Brian Aker
Merge Jay.
93
  By leaving the table in the table cache, it disallows any other thread
94
  to open the table
95
1910.2.8 by Brian Aker
Enapsulate Kill.
96
  session->getKilled() will be set if we run out of memory
1046 by Brian Aker
Merge Jay.
97
98
  If closing a MERGE child, the calling function has to take care for
99
  closing the parent too, if necessary.
1 by brian
clean slate
100
*/
101
102
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
103
void close_handle_and_leave_table_as_lock(Table *table)
1 by brian
clean slate
104
{
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
105
  assert(table->db_stat);
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
106
  assert(table->getShare()->getType() == message::Table::STANDARD);
1 by brian
clean slate
107
108
  /*
109
    Make a local copy of the table share and free the current one.
110
    This has to be done to ensure that the table share is removed from
111
    the table defintion cache as soon as the last instance is removed
112
  */
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
113
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
114
  const TableIdentifier::Key &key(identifier.getKey());
1835.1.5 by Brian Aker
Cleans up some spots where we were using mutable but did not need too.
115
  TableShare *share= new TableShare(identifier.getType(),
116
                                    identifier,
1878.5.3 by Brian Aker
Update Key to work a bit faster.
117
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
1 by brian
clean slate
118
1208.3.2 by brian
Update for Cursor renaming.
119
  table->cursor->close();
120
  table->db_stat= 0;                            // Mark cursor closed
2069.4.4 by Brian Aker
Create a shared form of the instance which is a bit more heavier weight then
121
  table::instance::release(table->getMutableShare());
1574 by Brian Aker
Rollup patch for hiding tableshare.
122
  table->setShare(share);
1 by brian
clean slate
123
}
124
125
126
/*****************************************************************************
127
 *	 Functions to free open table cache
128
 ****************************************************************************/
129
130
1109.1.4 by Brian Aker
More Table refactor
131
void Table::intern_close_table()
1 by brian
clean slate
132
{						// Free all structures
1109.1.4 by Brian Aker
More Table refactor
133
  free_io_cache();
1208.3.2 by brian
Update for Cursor renaming.
134
  if (cursor)                              // Not true if name lock
1502.1.13 by Brian Aker
Next bit of TableShare to c++.
135
  {
1502.1.3 by Brian Aker
Cleanup to use references.
136
    delete_table(true);			// close cursor
1502.1.13 by Brian Aker
Next bit of TableShare to c++.
137
  }
1 by brian
clean slate
138
}
139
140
/* Free resources allocated by filesort() and read_record() */
141
1109.1.4 by Brian Aker
More Table refactor
142
void Table::free_io_cache()
1 by brian
clean slate
143
{
1109.1.4 by Brian Aker
More Table refactor
144
  if (sort.io_cache)
1 by brian
clean slate
145
  {
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
146
    sort.io_cache->close_cached_file();
1109.1.4 by Brian Aker
More Table refactor
147
    delete sort.io_cache;
148
    sort.io_cache= 0;
1 by brian
clean slate
149
  }
150
}
151
152
153
/*
154
  Close all tables which aren't in use by any thread
155
1046.1.12 by Brian Aker
Simplify close_cached_tables() (it now always locks).
156
  @param session Thread context (may be NULL)
1 by brian
clean slate
157
  @param tables List of tables to remove from the cache
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
158
  @param have_lock If table::Cache::singleton().mutex() is locked
1 by brian
clean slate
159
  @param wait_for_refresh Wait for a impending flush
160
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
1046 by Brian Aker
Merge Jay.
161
  won't proceed while write-locked tables are being reopened by other
162
  threads.
1 by brian
clean slate
163
520.1.21 by Brian Aker
THD -> Session rename
164
  @remark Session can be NULL, but then wait_for_refresh must be false
1046 by Brian Aker
Merge Jay.
165
  and tables must be NULL.
1 by brian
clean slate
166
*/
167
1109.1.4 by Brian Aker
More Table refactor
168
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
1 by brian
clean slate
169
{
1046.1.12 by Brian Aker
Simplify close_cached_tables() (it now always locks).
170
  bool result= false;
1109.1.4 by Brian Aker
More Table refactor
171
  Session *session= this;
1 by brian
clean slate
172
173
  {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
174
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
175
176
    if (tables == NULL)
177
    {
178
      refresh_version++;				// Force close of open tables
179
1877.2.3 by Brian Aker
Move unused under table
180
      table::getUnused().clear();
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
181
182
      if (wait_for_refresh)
183
      {
184
        /*
185
          Other threads could wait in a loop in open_and_lock_tables(),
186
          trying to lock one or more of our tables.
187
188
          If they wait for the locks in thr_multi_lock(), their lock
189
          request is aborted. They loop in open_and_lock_tables() and
190
          enter open_table(). Here they notice the table is refreshed and
191
          wait for COND_refresh. Then they loop again in
192
          openTablesLock() and this time open_table() succeeds. At
193
          this moment, if we (the FLUSH TABLES thread) are scheduled and
194
          on another FLUSH TABLES enter close_cached_tables(), they could
195
          awake while we sleep below, waiting for others threads (us) to
196
          close their open tables. If this happens, the other threads
197
          would find the tables unlocked. They would get the locks, one
198
          after the other, and could do their destructive work. This is an
199
          issue if we have LOCK TABLES in effect.
200
201
          The problem is that the other threads passed all checks in
202
          open_table() before we refresh the table.
203
204
          The fix for this problem is to set some_tables_deleted for all
205
          threads with open tables. These threads can still get their
206
          locks, but will immediately release them again after checking
207
          this variable. They will then loop in openTablesLock()
208
          again. There they will wait until we update all tables version
209
          below.
210
1887.2.5 by Brian Aker
OSX found a reference to a function that was no longer declared.
211
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
212
          in the other branch.
213
214
          In other words (reviewer suggestion): You need this setting of
215
          some_tables_deleted for the case when table was opened and all
216
          related checks were passed before incrementing refresh_version
217
          (which you already have) but attempt to lock the table happened
218
          after the call to Session::close_old_data_files() i.e. after removal of
219
          current thread locks.
220
        */
1877.2.6 by Brian Aker
Fixed header/etc.
221
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
222
             iter != table::getCache().end();
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
223
             iter++)
224
        {
225
          Table *table= (*iter).second;
226
          if (table->in_use)
227
            table->in_use->some_tables_deleted= false;
228
        }
229
      }
230
    }
231
    else
232
    {
233
      bool found= false;
234
      for (TableList *table= tables; table; table= table->next_local)
235
      {
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
236
        TableIdentifier identifier(table->getSchemaName(), table->getTableName());
1877.2.8 by Brian Aker
Additional encapsulation
237
        if (table::Cache::singleton().removeTable(session, identifier,
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
238
                                    RTFC_OWNED_BY_Session_FLAG))
239
        {
240
          found= true;
241
        }
242
      }
243
      if (!found)
244
        wait_for_refresh= false;			// Nothing to wait for
245
    }
1109.1.4 by Brian Aker
More Table refactor
246
1 by brian
clean slate
247
    if (wait_for_refresh)
248
    {
249
      /*
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
250
        If there is any table that has a lower refresh_version, wait until
251
        this is closed (or this thread is killed) before returning
252
      */
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
253
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
254
      session->mysys_var->current_cond= &COND_refresh;
255
      session->set_proc_info("Flushing tables");
256
257
      session->close_old_data_files();
258
259
      bool found= true;
260
      /* Wait until all threads has closed all the tables we had locked */
1910.2.8 by Brian Aker
Enapsulate Kill.
261
      while (found && ! session->getKilled())
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
262
      {
263
        found= false;
1877.2.6 by Brian Aker
Fixed header/etc.
264
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
265
             iter != table::getCache().end();
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
266
             iter++)
267
        {
268
          Table *table= (*iter).second;
269
          /* Avoid a self-deadlock. */
270
          if (table->in_use == session)
271
            continue;
272
          /*
273
            Note that we wait here only for tables which are actually open, and
274
            not for placeholders with Table::open_placeholder set. Waiting for
275
            latter will cause deadlock in the following scenario, for example:
276
277
            conn1-> lock table t1 write;
278
            conn2-> lock table t2 write;
279
            conn1-> flush tables;
280
            conn2-> flush tables;
281
282
            It also does not make sense to wait for those of placeholders that
283
            are employed by CREATE TABLE as in this case table simply does not
284
            exist yet.
285
          */
286
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
                                                     (table->open_placeholder && wait_for_placeholders)))
288
          {
289
            found= true;
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
290
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
1798.3.10 by Brian Aker
Remove additional (maybe last of?) native_handle actual calls (safe_mutex is
291
            COND_refresh.wait(scoped);
292
            scoped.release();
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
293
            break;
294
          }
295
        }
296
      }
297
      /*
298
        No other thread has the locked tables open; reopen them and get the
299
        old locks. This should always succeed (unless some external process
300
        has removed the tables)
301
      */
302
      result= session->reopen_tables(true, true);
303
304
      /* Set version for table */
305
      for (Table *table= session->open_tables; table ; table= table->getNext())
306
      {
1 by brian
clean slate
307
        /*
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
308
          Preserve the version (0) of write locked tables so that a impending
309
          global read lock won't sneak in.
1 by brian
clean slate
310
        */
1798.3.4 by Brian Aker
Remove a if 0 block, capture a lock inside of {}
311
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
          table->getMutableShare()->refreshVersion();
1 by brian
clean slate
313
      }
314
    }
1046.1.13 by Brian Aker
Remove malloc() of table.
315
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
316
    table::Cache::singleton().mutex().unlock();
1 by brian
clean slate
317
  }
1046.1.12 by Brian Aker
Simplify close_cached_tables() (it now always locks).
318
1 by brian
clean slate
319
  if (wait_for_refresh)
320
  {
1812.3.7 by Brian Aker
Typdef our lock type.
321
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
520.1.22 by Brian Aker
Second pass of thd cleanup
322
    session->mysys_var->current_mutex= 0;
323
    session->mysys_var->current_cond= 0;
324
    session->set_proc_info(0);
1 by brian
clean slate
325
  }
1046.1.12 by Brian Aker
Simplify close_cached_tables() (it now always locks).
326
327
  return result;
1 by brian
clean slate
328
}
329
330
331
/**
1046.1.6 by Brian Aker
Formatting/style cleanup.
332
  move one table to free list 
1 by brian
clean slate
333
*/
334
1089.1.7 by Brian Aker
Shuffled free_cached_table() to table
335
bool Session::free_cached_table()
1 by brian
clean slate
336
{
1046.1.12 by Brian Aker
Simplify close_cached_tables() (it now always locks).
337
  bool found_old_table= false;
1878.1.1 by Brian Aker
Stick to static cast.
338
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
339
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
340
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
341
  assert(table->key_read == 0);
1208.3.2 by brian
Update for Cursor renaming.
342
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
1 by brian
clean slate
343
1608 by Brian Aker
This encapsulates prev/next.
344
  open_tables= table->getNext();
1 by brian
clean slate
345
346
  if (table->needs_reopen_or_name_lock() ||
1089.1.7 by Brian Aker
Shuffled free_cached_table() to table
347
      version != refresh_version || !table->db_stat)
1 by brian
clean slate
348
  {
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
349
    table::remove_table(table);
1046.1.6 by Brian Aker
Formatting/style cleanup.
350
    found_old_table= true;
1 by brian
clean slate
351
  }
352
  else
353
  {
354
    /*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
355
      Open placeholders have Table::db_stat set to 0, so they should be
1 by brian
clean slate
356
      handled by the first alternative.
357
    */
1372.1.1 by Brian Aker
Removed/rewrite to remove goto in alter table.
358
    assert(not table->open_placeholder);
1 by brian
clean slate
359
360
    /* Free memory and reset for next loop */
1208.3.2 by brian
Update for Cursor renaming.
361
    table->cursor->ha_reset();
1891.2.1 by Monty Taylor
Fixed things to make things compile with clang
362
    table->in_use= NULL;
1089.1.7 by Brian Aker
Shuffled free_cached_table() to table
363
1877.2.3 by Brian Aker
Move unused under table
364
    table::getUnused().link(table);
1 by brian
clean slate
365
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
366
367
  return found_old_table;
368
}
369
370
371
/**
372
  Auxiliary function to close all tables in the open_tables list.
373
374
  @param session Thread context.
375
376
  @remark It should not ordinarily be called directly.
377
*/
378
379
void Session::close_open_tables()
380
{
381
  bool found_old_table= false;
382
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
383
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
1046.1.6 by Brian Aker
Formatting/style cleanup.
384
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
385
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
1046.1.6 by Brian Aker
Formatting/style cleanup.
386
387
  while (open_tables)
1532.1.14 by Brian Aker
We no longer use alloc for placeholders (due to HASH I didn't use a
388
  {
1089.1.7 by Brian Aker
Shuffled free_cached_table() to table
389
    found_old_table|= free_cached_table();
1532.1.14 by Brian Aker
We no longer use alloc for placeholders (due to HASH I didn't use a
390
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
391
  some_tables_deleted= false;
392
393
  if (found_old_table)
394
  {
395
    /* Tell threads waiting for refresh that something has happened */
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
396
    locking::broadcast_refresh();
1046.1.6 by Brian Aker
Formatting/style cleanup.
397
  }
1 by brian
clean slate
398
}
399
400
/*
401
  Find table in list.
402
403
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
404
  find_table_in_list()
405
  table		Pointer to table list
406
  offset		Offset to which list in table structure to use
407
  db_name		Data base name
408
  table_name		Table name
409
410
NOTES:
1109.1.5 by Brian Aker
More extraction from sql_base
411
This is called by find_table_in_global_list().
1046 by Brian Aker
Merge Jay.
412
413
RETURN VALUES
414
NULL	Table not found
415
#		Pointer to found table.
1 by brian
clean slate
416
*/
417
327.2.4 by Brian Aker
Refactoring table.h
418
TableList *find_table_in_list(TableList *table,
1046 by Brian Aker
Merge Jay.
419
                              TableList *TableList::*link,
420
                              const char *db_name,
421
                              const char *table_name)
1 by brian
clean slate
422
{
423
  for (; table; table= table->*link )
424
  {
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
425
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
1874.1.1 by Brian Aker
Encapsulate schema_name it table_list.
426
        strcasecmp(table->getSchemaName(), db_name) == 0 &&
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
427
        strcasecmp(table->getTableName(), table_name) == 0)
1 by brian
clean slate
428
      break;
429
  }
430
  return table;
431
}
432
433
434
/*
435
  Test that table is unique (It's only exists once in the table list)
436
437
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
438
  unique_table()
439
  session                   thread handle
440
  table                 table which should be checked
441
  table_list            list of tables
442
  check_alias           whether to check tables' aliases
443
444
NOTE: to exclude derived tables from check we use following mechanism:
445
a) during derived table processing set Session::derived_tables_processing
446
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
447
Session::derived_tables_processing set. (we can't use JOIN::execute
448
because for PS we perform only JOIN::prepare, but we can't set this
449
flag in JOIN::prepare if we are not sure that we are in derived table
450
processing loop, because multi-update call fix_fields() for some its
451
items (which mean JOIN::prepare for subqueries) before unique_table
452
call to detect which tables should be locked for write).
453
c) unique_table skip all tables which belong to SELECT with
454
SELECT::exclude_from_table_unique_test set.
455
Also SELECT::exclude_from_table_unique_test used to exclude from check
456
tables of main SELECT of multi-delete and multi-update
457
458
We also skip tables with TableList::prelocking_placeholder set,
459
because we want to allow SELECTs from them, and their modification
460
will rise the error anyway.
461
462
TODO: when we will have table/view change detection we can do this check
463
only once for PS/SP
464
465
RETURN
466
found duplicate
467
0 if table is unique
1 by brian
clean slate
468
*/
469
1220.1.13 by Brian Aker
Remove mysql_lock_have_duplicate() (we don't have merge, and our partition
470
TableList* unique_table(TableList *table, TableList *table_list,
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
471
                        bool check_alias)
1 by brian
clean slate
472
{
327.2.4 by Brian Aker
Refactoring table.h
473
  TableList *res;
1 by brian
clean slate
474
  const char *d_name, *t_name, *t_alias;
475
476
  /*
477
    If this function called for query which update table (INSERT/UPDATE/...)
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
478
    then we have in table->table pointer to Table object which we are
327.2.4 by Brian Aker
Refactoring table.h
479
    updating even if it is VIEW so we need TableList of this Table object
1 by brian
clean slate
480
    to get right names (even if lower_case_table_names used).
481
482
    If this function called for CREATE command that we have not opened table
327.2.4 by Brian Aker
Refactoring table.h
483
    (table->table equal to 0) and right names is in current TableList
1 by brian
clean slate
484
    object.
485
  */
486
  if (table->table)
487
  {
488
    /* temporary table is always unique */
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
489
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
1046.1.10 by Brian Aker
Formatting around return (style)
490
      return 0;
1 by brian
clean slate
491
    table= table->find_underlying_table(table->table);
492
    /*
327.2.4 by Brian Aker
Refactoring table.h
493
      as far as we have table->table we have to find real TableList of
1 by brian
clean slate
494
      it in underlying tables
495
    */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
496
    assert(table);
1 by brian
clean slate
497
  }
1874.1.1 by Brian Aker
Encapsulate schema_name it table_list.
498
  d_name= table->getSchemaName();
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
499
  t_name= table->getTableName();
1 by brian
clean slate
500
  t_alias= table->alias;
501
502
  for (;;)
503
  {
1220.1.13 by Brian Aker
Remove mysql_lock_have_duplicate() (we don't have merge, and our partition
504
    if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
1 by brian
clean slate
505
        ((!res->table || res->table != table->table) &&
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
506
         (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
1 by brian
clean slate
507
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
508
      break;
509
    /*
510
      If we found entry of this table or table of SELECT which already
511
      processed in derived table or top select of multi-update/multi-delete
512
      (exclude_from_table_unique_test) or prelocking placeholder.
513
    */
514
    table_list= res->next_global;
515
  }
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
516
  return(res);
1 by brian
clean slate
517
}
518
519
1923.1.2 by Brian Aker
Encapsulate temporary tables.
520
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
                                        std::set<std::string>& set_of_names)
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
522
{
1923.1.2 by Brian Aker
Encapsulate temporary tables.
523
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
524
  {
1532.1.15 by Brian Aker
Partial encapsulation of TableShare from Table.
525
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
526
    {
1532.1.15 by Brian Aker
Partial encapsulation of TableShare from Table.
527
      set_of_names.insert(table->getShare()->getTableName());
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
528
    }
529
  }
530
}
531
1923.1.2 by Brian Aker
Encapsulate temporary tables.
532
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
                                        const SchemaIdentifier &schema_identifier,
534
                                        std::set<std::string> &set_of_names)
1387 by Brian Aker
Fix for cases where not all files are removed during a deletion of a schema.
535
{
1415 by Brian Aker
Mass overhaul to use schema_identifier.
536
  doGetTableNames(schema_identifier, set_of_names);
1387 by Brian Aker
Fix for cases where not all files are removed during a deletion of a schema.
537
}
538
1923.1.2 by Brian Aker
Encapsulate temporary tables.
539
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
1966.2.4 by Brian Aker
Style cleanup.
540
                                              TableIdentifier::vector &set_of_identifiers)
1429.1.3 by Brian Aker
Merge in work for fetching a list of table identifiers.
541
{
1923.1.2 by Brian Aker
Encapsulate temporary tables.
542
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
1429.1.3 by Brian Aker
Merge in work for fetching a list of table identifiers.
543
  {
1532.1.15 by Brian Aker
Partial encapsulation of TableShare from Table.
544
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
1429.1.3 by Brian Aker
Merge in work for fetching a list of table identifiers.
545
    {
546
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
                                                   table->getShare()->getTableName(),
548
                                                   table->getShare()->getPath()));
549
    }
550
  }
551
}
552
1923.1.2 by Brian Aker
Encapsulate temporary tables.
553
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
1966.2.4 by Brian Aker
Style cleanup.
554
                                              const SchemaIdentifier &schema_identifier,
555
                                              TableIdentifier::vector &set_of_identifiers)
1429.1.3 by Brian Aker
Merge in work for fetching a list of table identifiers.
556
{
557
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
}
559
1923.1.2 by Brian Aker
Encapsulate temporary tables.
560
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
1358.1.1 by Brian Aker
Fixes regression in performance from Exists patch.
561
{
1923.1.2 by Brian Aker
Encapsulate temporary tables.
562
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
1358.1.1 by Brian Aker
Fixes regression in performance from Exists patch.
563
  {
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
564
    if (table->getShare()->getType() == message::Table::TEMPORARY)
1358.1.1 by Brian Aker
Fixes regression in performance from Exists patch.
565
    {
1669.2.2 by Brian Aker
Remove compare and need to keep around lower_table.
566
      if (identifier.getKey() == table->getShare()->getCacheKey())
1358.1.1 by Brian Aker
Fixes regression in performance from Exists patch.
567
      {
1415 by Brian Aker
Mass overhaul to use schema_identifier.
568
        return true;
1358.1.1 by Brian Aker
Fixes regression in performance from Exists patch.
569
      }
570
    }
571
  }
572
573
  return false;
574
}
575
1923.1.2 by Brian Aker
Encapsulate temporary tables.
576
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
1354.1.1 by Brian Aker
Modify ptr to reference.
577
                                  message::Table &table_proto)
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
578
{
1923.1.2 by Brian Aker
Encapsulate temporary tables.
579
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
580
  {
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
581
    if (table->getShare()->getType() == message::Table::TEMPORARY)
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
582
    {
1669.2.2 by Brian Aker
Remove compare and need to keep around lower_table.
583
      if (identifier.getKey() == table->getShare()->getCacheKey())
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
584
      {
1574 by Brian Aker
Rollup patch for hiding tableshare.
585
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
586
1415 by Brian Aker
Mass overhaul to use schema_identifier.
587
        return EEXIST;
1273.19.10 by Brian Aker
Add support for listing temporay tables from show commands.
588
      }
589
    }
590
  }
591
592
  return ENOENT;
593
}
594
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
595
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
1369 by Brian Aker
Small interface bits.
596
{
1608 by Brian Aker
This encapsulates prev/next.
597
  for (Table *table= temporary_tables ; table ; table= table->getNext())
1371 by Brian Aker
Small corrections.
598
  {
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
599
    if (identifier.getKey() == table->getShare()->getCacheKey())
1371 by Brian Aker
Small corrections.
600
      return table;
601
  }
602
603
  return NULL;                               // Not a temporary table
1369 by Brian Aker
Small interface bits.
604
}
605
1 by brian
clean slate
606
607
/**
608
  Drop a temporary table.
609
520.1.22 by Brian Aker
Second pass of thd cleanup
610
  Try to locate the table in the list of session->temporary_tables.
1 by brian
clean slate
611
  If the table is found:
1046 by Brian Aker
Merge Jay.
612
  - if the table is being used by some outer statement, fail.
613
  - if the table is in session->locked_tables, unlock it and
614
  remove it from the list of locked tables. Currently only transactional
615
  temporary tables are present in the locked_tables list.
616
  - Close the temporary table, remove its .FRM
617
  - remove the table from the list of temporary tables
1 by brian
clean slate
618
619
  This function is used to drop user temporary tables, as well as
620
  internal tables created in CREATE TEMPORARY TABLE ... SELECT
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
621
  or ALTER Table. Even though part of the work done by this function
1 by brian
clean slate
622
  is redundant when the table is internal, as long as we
623
  link both internal and user temporary tables into the same
520.1.22 by Brian Aker
Second pass of thd cleanup
624
  session->temporary_tables list, it's impossible to tell here whether
1 by brian
clean slate
625
  we're dealing with an internal or a user temporary table.
626
627
  @retval  0  the table was found and dropped successfully.
628
  @retval  1  the table was not found in the list of temporary tables
1046 by Brian Aker
Merge Jay.
629
  of this thread
1 by brian
clean slate
630
  @retval -1  the table is in use by a outer query
631
*/
632
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
633
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
1864.3.13 by Brian Aker
Usage of find_temporary_table() to identifier.
634
{
635
  Table *table;
636
637
  if (not (table= find_temporary_table(identifier)))
638
    return 1;
639
640
  /* Table might be in use by some outer statement. */
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
641
  if (table->query_id && table->query_id != getQueryId())
1864.3.13 by Brian Aker
Usage of find_temporary_table() to identifier.
642
  {
643
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
644
    return -1;
645
  }
646
647
  close_temporary_table(table);
648
649
  return 0;
650
}
651
1 by brian
clean slate
652
653
/**
1046 by Brian Aker
Merge Jay.
654
  Remove all instances of table from thread's open list and
655
  table cache.
656
657
  @param  session     Thread context
658
  @param  find    Table to remove
1859.2.8 by Brian Aker
Remove memcpy (though really this is just a shell, since it is still a
659
1938.4.1 by Brian Aker
Fix style on naming of shared_ptr for tableshare.
660
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
1 by brian
clean slate
661
*/
662
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
663
void Session::unlink_open_table(Table *find)
1 by brian
clean slate
664
{
1859.2.8 by Brian Aker
Remove memcpy (though really this is just a shell, since it is still a
665
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
  Table **prev;
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
667
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1 by brian
clean slate
668
669
  /*
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
670
    Note that we need to hold table::Cache::singleton().mutex() while changing the
1 by brian
clean slate
671
    open_tables list. Another thread may work on it.
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
672
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
1 by brian
clean slate
673
    Closing a MERGE child before the parent would be fatal if the
674
    other thread tries to abort the MERGE lock in between.
675
  */
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
676
  for (prev= &open_tables; *prev; )
1 by brian
clean slate
677
  {
1859.2.8 by Brian Aker
Remove memcpy (though really this is just a shell, since it is still a
678
    Table *list= *prev;
1 by brian
clean slate
679
1859.2.8 by Brian Aker
Remove memcpy (though really this is just a shell, since it is still a
680
    if (list->getShare()->getCacheKey() == find_key)
1 by brian
clean slate
681
    {
682
      /* Remove table from open_tables list. */
1608 by Brian Aker
This encapsulates prev/next.
683
      *prev= list->getNext();
1532.1.14 by Brian Aker
We no longer use alloc for placeholders (due to HASH I didn't use a
684
1 by brian
clean slate
685
      /* Close table. */
1887.2.1 by Brian Aker
Merge in refactoring tree. This breaks out TableShare into cache and
686
      table::remove_table(static_cast<table::Concurrent *>(list));
1 by brian
clean slate
687
    }
688
    else
689
    {
690
      /* Step to next entry in open_tables list. */
1608 by Brian Aker
This encapsulates prev/next.
691
      prev= list->getNextPtr();
1 by brian
clean slate
692
    }
693
  }
694
695
  // Notify any 'refresh' threads
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
696
  locking::broadcast_refresh();
1 by brian
clean slate
697
}
698
699
700
/**
1046 by Brian Aker
Merge Jay.
701
  Auxiliary routine which closes and drops open table.
702
703
  @param  session         Thread handle
704
  @param  table       Table object for table to be dropped
705
  @param  db_name     Name of database for this table
706
  @param  table_name  Name of this table
707
708
  @note This routine assumes that table to be closed is open only
709
  by calling thread so we needn't wait until other threads
710
  will close the table. Also unless called under implicit or
711
  explicit LOCK TABLES mode it assumes that table to be
712
  dropped is already unlocked. In the former case it will
713
  also remove lock on the table. But one should not rely on
714
  this behaviour as it may change in future.
715
  Currently, however, this function is never called for a
716
  table that was locked with LOCK TABLES.
1 by brian
clean slate
717
*/
718
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
719
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
1 by brian
clean slate
720
{
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
721
  if (table->getShare()->getType())
1237.6.12 by Brian Aker
Adding patch for engine methods for definition files.
722
  {
1216.1.1 by Brian Aker
Move print_error up to Engine.
723
    close_temporary_table(table);
1237.6.12 by Brian Aker
Adding patch for engine methods for definition files.
724
  }
1 by brian
clean slate
725
  else
726
  {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
727
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
1 by brian
clean slate
728
    /*
729
      unlink_open_table() also tells threads waiting for refresh or close
730
      that something has happened.
731
    */
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
732
    unlink_open_table(table);
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
733
    (void)plugin::StorageEngine::dropTable(*this, identifier);
1 by brian
clean slate
734
  }
735
}
736
737
738
/*
1046 by Brian Aker
Merge Jay.
739
  Wait for condition but allow the user to send a kill to mysqld
1 by brian
clean slate
740
1046 by Brian Aker
Merge Jay.
741
  SYNOPSIS
742
  wait_for_condition()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
743
  session	Thread Cursor
1046 by Brian Aker
Merge Jay.
744
  mutex	mutex that is currently hold that is associated with condition
745
  Will be unlocked on return
746
  cond	Condition to wait for
1 by brian
clean slate
747
*/
748
1812.3.5 by Brian Aker
Move to boost condition_any
749
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
1 by brian
clean slate
750
{
751
  /* Wait until the current table is up to date */
1054.1.10 by Brian Aker
Move open_table() to session.
752
  const char *saved_proc_info;
1786.2.1 by Brian Aker
Current boost work (more conversion).
753
  mysys_var->current_mutex= &mutex;
754
  mysys_var->current_cond= &cond;
1054.1.10 by Brian Aker
Move open_table() to session.
755
  saved_proc_info= get_proc_info();
756
  set_proc_info("Waiting for table");
1798.3.5 by Brian Aker
Scope wait_for_condition().
757
  {
758
    /*
759
      We must unlock mutex first to avoid deadlock becasue conditions are
760
      sent to this thread by doing locks in the following order:
761
      lock(mysys_var->mutex)
762
      lock(mysys_var->current_mutex)
763
764
      One by effect of this that one can only use wait_for_condition with
765
      condition variables that are guranteed to not disapper (freed) even if this
766
      mutex is unlocked
767
    */
1812.3.7 by Brian Aker
Typdef our lock type.
768
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
1910.2.8 by Brian Aker
Enapsulate Kill.
769
    if (not getKilled())
1798.3.5 by Brian Aker
Scope wait_for_condition().
770
    {
771
      cond.wait(scopedLock);
772
    }
773
  }
1812.3.7 by Brian Aker
Typdef our lock type.
774
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
1054.1.10 by Brian Aker
Move open_table() to session.
775
  mysys_var->current_mutex= 0;
776
  mysys_var->current_cond= 0;
777
  set_proc_info(saved_proc_info);
1 by brian
clean slate
778
}
779
780
781
/**
1046 by Brian Aker
Merge Jay.
782
  Create and insert into table cache placeholder for table
783
  which will prevent its opening (or creation) (a.k.a lock
784
  table name).
785
786
  @param session         Thread context
787
  @param key         Table cache key for name to be locked
788
  @param key_length  Table cache key length
789
790
  @return Pointer to Table object used for name locking or 0 in
791
  case of failure.
1 by brian
clean slate
792
*/
793
1877.2.1 by Brian Aker
Refactor table_cache_insert_placeholder.
794
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
1 by brian
clean slate
795
{
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
796
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1 by brian
clean slate
797
798
  /*
799
    Create a table entry with the right key and with an old refresh version
800
  */
1864.3.15 by Brian Aker
Fix placeholder to take identifier.
801
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
1843.8.6 by Brian Aker
Move placeholder to table directory.
802
  table::Placeholder *table= new table::Placeholder(this, identifier);
1 by brian
clean slate
803
1903.1.1 by Brian Aker
Merge of partial set of patches for locks.
804
  if (not table::Cache::singleton().insert(table))
1 by brian
clean slate
805
  {
1532.1.14 by Brian Aker
We no longer use alloc for placeholders (due to HASH I didn't use a
806
    delete table;
807
1019.1.6 by Brian Aker
A number of random cleanups.
808
    return NULL;
1 by brian
clean slate
809
  }
810
1039.1.10 by Brian Aker
Minor formating, change of one name to make grep easier :)
811
  return table;
1 by brian
clean slate
812
}
813
814
815
/**
1046 by Brian Aker
Merge Jay.
816
  Obtain an exclusive name lock on the table if it is not cached
817
  in the table cache.
818
819
  @param      session         Thread context
820
  @param      db          Name of database
821
  @param      table_name  Name of table
822
  @param[out] table       Out parameter which is either:
823
  - set to NULL if table cache contains record for
824
  the table or
825
  - set to point to the Table instance used for
826
  name-locking.
827
828
  @note This function takes into account all records for table in table
829
  cache, even placeholders used for name-locking. This means that
830
  'table' parameter can be set to NULL for some situations when
831
  table does not really exist.
832
833
  @retval  true   Error occured (OOM)
834
  @retval  false  Success. 'table' parameter set according to above rules.
1 by brian
clean slate
835
*/
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
836
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
1358.1.9 by Brian Aker
Update for std::string
837
{
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
838
  const TableIdentifier::Key &key(identifier.getKey());
641.4.1 by Toru Maesaka
First pass of replacing MySQL's my_stpcpy() with appropriate libc calls
839
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
840
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
1 by brian
clean slate
841
1877.2.6 by Brian Aker
Fixed header/etc.
842
  table::CacheMap::iterator iter;
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
843
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
844
  iter= table::getCache().find(key);
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
845
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
846
  if (iter != table::getCache().end())
1 by brian
clean slate
847
  {
848
    *table= 0;
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
849
    return false;
1 by brian
clean slate
850
  }
1532.1.14 by Brian Aker
We no longer use alloc for placeholders (due to HASH I didn't use a
851
1864.3.15 by Brian Aker
Fix placeholder to take identifier.
852
  if (not (*table= table_cache_insert_placeholder(identifier)))
1 by brian
clean slate
853
  {
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
854
    return true;
1 by brian
clean slate
855
  }
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
856
  (*table)->open_placeholder= true;
1608 by Brian Aker
This encapsulates prev/next.
857
  (*table)->setNext(open_tables);
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
858
  open_tables= *table;
859
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
860
  return false;
1 by brian
clean slate
861
}
862
863
/*
864
  Open a table.
865
866
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
867
  open_table()
868
  session                 Thread context.
869
  table_list          Open first table in list.
870
  refresh      INOUT  Pointer to memory that will be set to 1 if
871
  we need to close all tables and reopen them.
872
  If this is a NULL pointer, then the table is not
873
  put in the thread-open-list.
874
  flags               Bitmap of flags to modify how open works:
875
  DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
876
  someone has done a flush or namelock on it.
877
  No version number checking is done.
878
  DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
879
  table not the base table or view.
1 by brian
clean slate
880
881
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
882
  Uses a cache of open tables to find a table not in use.
1 by brian
clean slate
883
1046 by Brian Aker
Merge Jay.
884
  If table list element for the table to be opened has "create" flag
885
  set and table does not exist, this function will automatically insert
886
  a placeholder for exclusive name lock into the open tables cache and
887
  will return the Table instance that corresponds to this placeholder.
1 by brian
clean slate
888
889
  RETURN
1046 by Brian Aker
Merge Jay.
890
  NULL  Open failed.  If refresh is set then one should close
891
  all other tables and retry the open.
892
#     Success. Pointer to Table object for open table.
1 by brian
clean slate
893
*/
894
895
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
896
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
1 by brian
clean slate
897
{
1220.1.7 by Brian Aker
Cleanup interface for open session.
898
  Table *table;
1039.1.4 by Brian Aker
Modified alias to being const.
899
  const char *alias= table_list->alias;
1 by brian
clean slate
900
520.1.22 by Brian Aker
Second pass of thd cleanup
901
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1054.1.10 by Brian Aker
Move open_table() to session.
902
  assert(lex->is_lex_started);
1 by brian
clean slate
903
904
  /* find a unused table in the open table cache */
905
  if (refresh)
1046.1.5 by Brian Aker
Codestyle cleanup.
906
    *refresh= false;
1 by brian
clean slate
907
908
  /* an open table operation needs a lot of the stack space */
1054.1.10 by Brian Aker
Move open_table() to session.
909
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1046.1.5 by Brian Aker
Codestyle cleanup.
910
    return NULL;
520.1.22 by Brian Aker
Second pass of thd cleanup
911
1910.2.8 by Brian Aker
Enapsulate Kill.
912
  if (getKilled())
1046.1.5 by Brian Aker
Codestyle cleanup.
913
    return NULL;
520.1.22 by Brian Aker
Second pass of thd cleanup
914
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
915
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
916
  const TableIdentifier::Key &key(identifier.getKey());
1877.2.4 by Brian Aker
Shift over to cache definition in table/cache
917
  table::CacheRange ppp;
1 by brian
clean slate
918
919
  /*
920
    Unless requested otherwise, try to resolve this table in the list
921
    of temporary tables of this thread. In MySQL temporary tables
922
    are always thread-local and "shadow" possible base tables with the
923
    same name. This block implements the behaviour.
1046.1.5 by Brian Aker
Codestyle cleanup.
924
    TODO -> move this block into a separate function.
1 by brian
clean slate
925
  */
1798.3.2 by Brian Aker
Remove goto for reset.
926
  bool reset= false;
1923.1.2 by Brian Aker
Encapsulate temporary tables.
927
  for (table= getTemporaryTables(); table ; table=table->getNext())
1 by brian
clean slate
928
  {
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
929
    if (table->getShare()->getCacheKey() == key)
1 by brian
clean slate
930
    {
1046.1.4 by Brian Aker
Move lazy read of refresh to outside of LOCK_open (we don't lock the refresh
931
      /*
932
        We're trying to use the same temporary table twice in a query.
933
        Right now we don't support this because a temporary table
934
        is always represented by only one Table object in Session, and
935
        it can not be cloned. Emit an error for an unsupported behaviour.
936
      */
937
      if (table->query_id)
1 by brian
clean slate
938
      {
1669.2.6 by Brian Aker
First pass through encapsulating getAlias() from table.
939
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1046.1.5 by Brian Aker
Codestyle cleanup.
940
        return NULL;
1 by brian
clean slate
941
      }
1273.1.1 by Jay Pipes
* Changes Session::warn_id to Session::warn_query_id
942
      table->query_id= getQueryId();
1798.3.2 by Brian Aker
Remove goto for reset.
943
      reset= true;
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
944
      break;
1798.3.2 by Brian Aker
Remove goto for reset.
945
    }
946
  }
947
948
  if (not reset)
949
  {
950
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
    {
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
952
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
1798.3.2 by Brian Aker
Remove goto for reset.
953
      return NULL;
954
    }
955
1 by brian
clean slate
956
    /*
1798.3.2 by Brian Aker
Remove goto for reset.
957
      If it's the first table from a list of tables used in a query,
958
      remember refresh_version (the version of open_cache state).
959
      If the version changes while we're opening the remaining tables,
960
      we will have to back off, close all the tables opened-so-far,
961
      and try to reopen them.
962
963
      Note-> refresh_version is currently changed only during FLUSH TABLES.
1 by brian
clean slate
964
    */
1798.3.2 by Brian Aker
Remove goto for reset.
965
    if (!open_tables)
966
    {
967
      version= refresh_version;
968
    }
969
    else if ((version != refresh_version) &&
970
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
971
    {
972
      /* Someone did a refresh while thread was opening tables */
1 by brian
clean slate
973
      if (refresh)
1046.1.5 by Brian Aker
Codestyle cleanup.
974
        *refresh= true;
1798.3.2 by Brian Aker
Remove goto for reset.
975
1046.1.5 by Brian Aker
Codestyle cleanup.
976
      return NULL;
1 by brian
clean slate
977
    }
1798.3.2 by Brian Aker
Remove goto for reset.
978
979
    /*
980
      Before we test the global cache, we test our local session cache.
981
    */
982
    if (cached_table)
983
    {
984
      assert(false); /* Not implemented yet */
985
    }
986
987
    /*
988
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
      this is the normal use case.
990
      Now we should:
991
      - try to find the table in the table cache.
992
      - if one of the discovered Table instances is name-locked
993
      (table->getShare()->version == 0) back off -- we have to wait
994
      until no one holds a name lock on the table.
995
      - if there is no such Table in the name cache, read the table definition
996
      and insert it into the cache.
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
997
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
1798.3.2 by Brian Aker
Remove goto for reset.
998
      the open cache (also known as table cache) and table definitions stored
999
      on disk.
1000
    */
1001
1002
    {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1003
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1798.3.2 by Brian Aker
Remove goto for reset.
1004
1005
      /*
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1006
        Actually try to find the table in the open_cache.
1007
        The cache may contain several "Table" instances for the same
1008
        physical table. The instances that are currently "in use" by
1009
        some thread have their "in_use" member != NULL.
1010
        There is no good reason for having more than one entry in the
1011
        hash for the same physical table, except that we use this as
1012
        an implicit "pending locks queue" - see
1013
        wait_for_locked_table_names for details.
1798.3.2 by Brian Aker
Remove goto for reset.
1014
      */
1877.2.5 by Brian Aker
Shift a bit more of the guts of cache to its own space.
1015
      ppp= table::getCache().equal_range(key);
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1016
1017
      table= NULL;
1877.2.6 by Brian Aker
Fixed header/etc.
1018
      for (table::CacheMap::const_iterator iter= ppp.first;
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1019
           iter != ppp.second; ++iter, table= NULL)
1020
      {
1021
        table= (*iter).second;
1022
1023
        if (not table->in_use)
1024
          break;
1025
        /*
1026
          Here we flush tables marked for flush.
1027
          Normally, table->getShare()->version contains the value of
1028
          refresh_version from the moment when this table was
1029
          (re-)opened and added to the cache.
1030
          If since then we did (or just started) FLUSH TABLES
1031
          statement, refresh_version has been increased.
1032
          For "name-locked" Table instances, table->getShare()->version is set
1033
          to 0 (see lock_table_name for details).
1034
          In case there is a pending FLUSH TABLES or a name lock, we
1035
          need to back off and re-start opening tables.
1036
          If we do not back off now, we may dead lock in case of lock
1037
          order mismatch with some other thread:
1038
          c1-> name lock t1; -- sort of exclusive lock
1039
          c2-> open t2;      -- sort of shared lock
1040
          c1-> name lock t2; -- blocks
1041
          c2-> open t1; -- blocks
1042
        */
1043
        if (table->needs_reopen_or_name_lock())
1044
        {
1045
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1046
          {
1047
            /* Force close at once after usage */
1048
            version= table->getShare()->getVersion();
1049
            continue;
1050
          }
1051
1052
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
          if (table->open_placeholder && table->in_use == this)
1798.3.2 by Brian Aker
Remove goto for reset.
1054
          {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1055
            table::Cache::singleton().mutex().unlock();
1835.1.4 by Brian Aker
Update to remove more of the getMutableShare() uses.
1056
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1798.3.2 by Brian Aker
Remove goto for reset.
1057
            return NULL;
1058
          }
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1059
1060
          /*
1061
            Back off, part 1: mark the table as "unused" for the
1062
            purpose of name-locking by setting table->db_stat to 0. Do
1063
            that only for the tables in this thread that have an old
1064
            table->getShare()->version (this is an optimization (?)).
1065
            table->db_stat == 0 signals wait_for_locked_table_names
1066
            that the tables in question are not used any more. See
1067
            table_is_used call for details.
1068
          */
1069
          close_old_data_files(false, false);
1070
1071
          /*
1072
            Back-off part 2: try to avoid "busy waiting" on the table:
1073
            if the table is in use by some other thread, we suspend
1074
            and wait till the operation is complete: when any
1075
            operation that juggles with table->getShare()->version completes,
1076
            it broadcasts COND_refresh condition variable.
1077
            If 'old' table we met is in use by current thread we return
1078
            without waiting since in this situation it's this thread
1079
            which is responsible for broadcasting on COND_refresh
1080
            (and this was done already in Session::close_old_data_files()).
1081
            Good example of such situation is when we have statement
1082
            that needs two instances of table and FLUSH TABLES comes
1083
            after we open first instance but before we open second
1084
            instance.
1085
          */
1086
          if (table->in_use != this)
1087
          {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1088
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1090
          }
1091
          else
1092
          {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1093
            table::Cache::singleton().mutex().unlock();
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1094
          }
1095
          /*
1096
            There is a refresh in progress for this table.
1097
            Signal the caller that it has to try again.
1098
          */
1099
          if (refresh)
1100
            *refresh= true;
1101
          return NULL;
1102
        }
1103
      }
1104
      if (table)
1105
      {
1887.2.1 by Brian Aker
Merge in refactoring tree. This breaks out TableShare into cache and
1106
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1107
        table->in_use= this;
1108
      }
1109
      else
1110
      {
1111
        /* Insert a new Table instance into the open cache */
1112
        int error;
1113
        /* Free cache if too big */
1877.2.3 by Brian Aker
Move unused under table
1114
        table::getUnused().cull();
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1115
1116
        if (table_list->isCreate())
1117
        {
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1118
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1119
1120
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1121
          {
1122
            /*
1123
              Table to be created, so we need to create placeholder in table-cache.
1124
            */
1864.3.15 by Brian Aker
Fix placeholder to take identifier.
1125
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1126
            {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1127
              table::Cache::singleton().mutex().unlock();
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1128
              return NULL;
1129
            }
1130
            /*
1131
              Link placeholder to the open tables list so it will be automatically
1132
              removed once tables are closed. Also mark it so it won't be ignored
1133
              by other trying to take name-lock.
1134
            */
1135
            table->open_placeholder= true;
1136
            table->setNext(open_tables);
1137
            open_tables= table;
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1138
            table::Cache::singleton().mutex().unlock();
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1139
1140
            return table ;
1141
          }
1142
          /* Table exists. Let us try to open it. */
1143
        }
1144
1145
        /* make a new table */
1146
        {
1859.2.6 by Brian Aker
Merge in a bit more strictness around table type.
1147
          table::Concurrent *new_table= new table::Concurrent;
1148
          table= new_table;
1149
          if (new_table == NULL)
1150
          {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1151
            table::Cache::singleton().mutex().unlock();
1859.2.6 by Brian Aker
Merge in a bit more strictness around table type.
1152
            return NULL;
1153
          }
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1154
1874.3.2 by Brian Aker
Updating a few bits of the interface to be specific to table::Concurrent
1155
          error= new_table->open_unireg_entry(this, alias, identifier);
1859.2.6 by Brian Aker
Merge in a bit more strictness around table type.
1156
          if (error != 0)
1157
          {
1158
            delete new_table;
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1159
            table::Cache::singleton().mutex().unlock();
1859.2.6 by Brian Aker
Merge in a bit more strictness around table type.
1160
            return NULL;
1161
          }
1903.1.1 by Brian Aker
Merge of partial set of patches for locks.
1162
          (void)table::Cache::singleton().insert(new_table);
1798.3.6 by Brian Aker
This is just a refactor for {} so I can follow a different merge a bit
1163
        }
1164
      }
1165
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1166
      table::Cache::singleton().mutex().unlock();
1798.3.2 by Brian Aker
Remove goto for reset.
1167
    }
1168
    if (refresh)
1169
    {
1170
      table->setNext(open_tables); /* Link into simple list */
1171
      open_tables= table;
1172
    }
1173
    table->reginfo.lock_type= TL_READ; /* Assume read */
1174
1175
  }
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
1176
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1 by brian
clean slate
1177
1178
  /* Fix alias if table name changes */
1669.2.6 by Brian Aker
First pass through encapsulating getAlias() from table.
1179
  if (strcmp(table->getAlias(), alias))
1 by brian
clean slate
1180
  {
1864.4.4 by Brian Aker
We now handle the free of the alias inside of table.
1181
    table->setAlias(alias);
1 by brian
clean slate
1182
  }
1046.1.5 by Brian Aker
Codestyle cleanup.
1183
1 by brian
clean slate
1184
  /* These variables are also set in reopen_table() */
1054.1.10 by Brian Aker
Move open_table() to session.
1185
  table->tablenr= current_tablenr++;
1046.1.5 by Brian Aker
Codestyle cleanup.
1186
  table->used_fields= 0;
1187
  table->const_table= 0;
274 by Brian Aker
my_bool conversion in Table
1188
  table->null_row= false;
1189
  table->maybe_null= false;
1190
  table->force_index= false;
1 by brian
clean slate
1191
  table->status=STATUS_NO_RECORD;
1672.3.5 by Brian Aker
This replaces the allocation we do for insert/update.
1192
  table->insert_values.clear();
1 by brian
clean slate
1193
  /* Catch wrong handling of the auto_increment_field_not_null. */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1194
  assert(!table->auto_increment_field_not_null);
55 by brian
Update for using real bool types.
1195
  table->auto_increment_field_not_null= false;
1 by brian
clean slate
1196
  if (table->timestamp_field)
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
1197
  {
1 by brian
clean slate
1198
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
1199
  }
1 by brian
clean slate
1200
  table->pos_in_table_list= table_list;
1201
  table->clear_column_bitmaps();
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1202
  assert(table->key_read == 0);
1046.1.5 by Brian Aker
Codestyle cleanup.
1203
1204
  return table;
1 by brian
clean slate
1205
}
1206
1207
1208
/**
1046 by Brian Aker
Merge Jay.
1209
  Close all instances of a table open by this thread and replace
1210
  them with exclusive name-locks.
1211
1212
  @param session        Thread context
1213
  @param db         Database name for the table to be closed
1214
  @param table_name Name of the table to be closed
1215
1216
  @note This function assumes that if we are not under LOCK TABLES,
1217
  then there is only one table open and locked. This means that
1218
  the function probably has to be adjusted before it can be used
1219
  anywhere outside ALTER Table.
1220
1221
  @note Must not use TableShare::table_name/db of the table being closed,
1222
  the strings are used in a loop even after the share may be freed.
1 by brian
clean slate
1223
*/
1224
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
1225
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
1395.1.2 by Brian Aker
More logic pulling from ALTER TABLE
1226
{
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1227
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1 by brian
clean slate
1228
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1229
  if (lock)
1 by brian
clean slate
1230
  {
1231
    /*
1232
      If we are not under LOCK TABLES we should have only one table
1233
      open and locked so it makes sense to remove the lock at once.
1234
    */
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1235
    unlockTables(lock);
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1236
    lock= 0;
1 by brian
clean slate
1237
  }
1238
1239
  /*
1240
    Note that open table list may contain a name-lock placeholder
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1241
    for target table name if we process ALTER Table ... RENAME.
1 by brian
clean slate
1242
    So loop below makes sense even if we are not under LOCK TABLES.
1243
  */
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1244
  for (Table *table= open_tables; table ; table=table->getNext())
1 by brian
clean slate
1245
  {
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1246
    if (table->getShare()->getCacheKey() == identifier.getKey())
1 by brian
clean slate
1247
    {
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1248
      table->open_placeholder= true;
1 by brian
clean slate
1249
      close_handle_and_leave_table_as_lock(table);
1250
    }
1251
  }
1252
}
1253
1254
1255
/**
1046 by Brian Aker
Merge Jay.
1256
  Reopen all tables with closed data files.
1257
1258
  @param session         Thread context
1259
  @param get_locks   Should we get locks after reopening tables ?
1260
  @param mark_share_as_old  Mark share as old to protect from a impending
1261
  global read lock.
1262
1263
  @note Since this function can't properly handle prelocking and
1264
  create placeholders it should be used in very special
1265
  situations like FLUSH TABLES or ALTER Table. In general
1266
  case one should just repeat open_tables()/lock_tables()
1267
  combination when one needs tables to be reopened (for
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1268
  example see openTablesLock()).
1046 by Brian Aker
Merge Jay.
1269
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1270
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
1046 by Brian Aker
Merge Jay.
1271
1272
  @return false in case of success, true - otherwise.
1 by brian
clean slate
1273
*/
1274
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1275
bool Session::reopen_tables(bool get_locks, bool)
1 by brian
clean slate
1276
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1277
  Table *table,*next,**prev;
1278
  Table **tables,**tables_ptr;			// For locks
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1279
  bool error= false;
482 by Brian Aker
Remove uint.
1280
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1046 by Brian Aker
Merge Jay.
1281
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1282
    DRIZZLE_LOCK_IGNORE_FLUSH;
1 by brian
clean slate
1283
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1284
  if (open_tables == NULL)
1285
    return false;
1 by brian
clean slate
1286
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1287
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1 by brian
clean slate
1288
  if (get_locks)
1289
  {
1290
    /*
1291
      The ptr is checked later
1292
      Do not handle locks of MERGE children.
1293
    */
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1294
    uint32_t opens= 0;
1046.1.13 by Brian Aker
Remove malloc() of table.
1295
1608 by Brian Aker
This encapsulates prev/next.
1296
    for (table= open_tables; table ; table=table->getNext())
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1297
    {
1 by brian
clean slate
1298
      opens++;
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1299
    }
1046.1.13 by Brian Aker
Remove malloc() of table.
1300
    tables= new Table *[opens];
1 by brian
clean slate
1301
  }
1302
  else
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1303
  {
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1304
    tables= &open_tables;
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1305
  }
1 by brian
clean slate
1306
  tables_ptr =tables;
1307
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1308
  prev= &open_tables;
1309
  for (table= open_tables; table ; table=next)
1 by brian
clean slate
1310
  {
1608 by Brian Aker
This encapsulates prev/next.
1311
    next= table->getNext();
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1312
1669.2.6 by Brian Aker
First pass through encapsulating getAlias() from table.
1313
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1887.2.1 by Brian Aker
Merge in refactoring tree. This breaks out TableShare into cache and
1314
    table::remove_table(static_cast<table::Concurrent *>(table));
1502.1.1 by Brian Aker
This is a small update to remove reopen hack (this also moves us one more
1315
    error= 1;
1 by brian
clean slate
1316
  }
1317
  *prev=0;
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1318
1 by brian
clean slate
1319
  if (tables != tables_ptr)			// Should we get back old locks
1320
  {
1711.6.1 by Brian Aker
Style on structure cleanup
1321
    DrizzleLock *local_lock;
1 by brian
clean slate
1322
    /*
1323
      We should always get these locks. Anyway, we must not go into
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1324
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
1 by brian
clean slate
1325
      already locked.
1326
    */
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1327
    some_tables_deleted= false;
1328
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1329
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
1 by brian
clean slate
1330
    {
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1331
      /* unused */
1 by brian
clean slate
1332
    }
1333
    else
1334
    {
1335
      /*
1336
        This case should only happen if there is a bug in the reopen logic.
1337
        Need to issue error message to have a reply for the application.
1338
        Not exactly what happened though, but close enough.
1339
      */
1340
      my_error(ER_LOCK_DEADLOCK, MYF(0));
1341
      error=1;
1342
    }
1343
  }
1046.1.13 by Brian Aker
Remove malloc() of table.
1344
1 by brian
clean slate
1345
  if (get_locks && tables)
1046.1.13 by Brian Aker
Remove malloc() of table.
1346
    delete [] tables;
1347
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
1348
  locking::broadcast_refresh();
1046.1.13 by Brian Aker
Remove malloc() of table.
1349
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1350
  return(error);
1 by brian
clean slate
1351
}
1352
1353
1354
/**
1046 by Brian Aker
Merge Jay.
1355
  Close handlers for tables in list, but leave the Table structure
1356
  intact so that we can re-open these quickly.
1 by brian
clean slate
1357
1046 by Brian Aker
Merge Jay.
1358
  @param session           Thread context
1359
  @param table         Head of the list of Table objects
1360
  @param morph_locks   true  - remove locks which we have on tables being closed
1361
  but ensure that no DML or DDL will sneak in before
1362
  we will re-open the table (i.e. temporarily morph
1363
  our table-level locks into name-locks).
1364
  false - otherwise
1365
  @param send_refresh  Should we awake waiters even if we didn't close any tables?
1 by brian
clean slate
1366
*/
1367
1046.1.11 by Brian Aker
Refactor call close_old_data_files to Session object.
1368
void Session::close_old_data_files(bool morph_locks, bool send_refresh)
1 by brian
clean slate
1369
{
1370
  bool found= send_refresh;
1371
1046.1.11 by Brian Aker
Refactor call close_old_data_files to Session object.
1372
  Table *table= open_tables;
1373
1608 by Brian Aker
This encapsulates prev/next.
1374
  for (; table ; table=table->getNext())
1 by brian
clean slate
1375
  {
1376
    /*
1377
      Reopen marked for flush.
1378
    */
1379
    if (table->needs_reopen_or_name_lock())
1380
    {
1381
      found=1;
1382
      if (table->db_stat)
1383
      {
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1384
        if (morph_locks)
1385
        {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1386
          Table *ulcktbl= table;
1 by brian
clean slate
1387
          if (ulcktbl->lock_count)
1388
          {
1389
            /*
1390
              Wake up threads waiting for table-level lock on this table
1391
              so they won't sneak in when we will temporarily remove our
1392
              lock on it. This will also give them a chance to close their
1393
              instances of this table.
1394
            */
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1395
            abortLock(ulcktbl);
1396
            removeLock(ulcktbl);
1 by brian
clean slate
1397
            ulcktbl->lock_count= 0;
1398
          }
1399
          if ((ulcktbl != table) && ulcktbl->db_stat)
1400
          {
1401
            /*
1402
              Close the parent too. Note that parent can come later in
1403
              the list of tables. It will then be noticed as closed and
1404
              as a placeholder. When this happens, do not clear the
1405
              placeholder flag. See the branch below ("***").
1406
            */
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1407
            ulcktbl->open_placeholder= true;
1 by brian
clean slate
1408
            close_handle_and_leave_table_as_lock(ulcktbl);
1409
          }
1410
          /*
1411
            We want to protect the table from concurrent DDL operations
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1412
            (like RENAME Table) until we will re-open and re-lock it.
1 by brian
clean slate
1413
          */
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1414
          table->open_placeholder= true;
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1415
        }
1 by brian
clean slate
1416
        close_handle_and_leave_table_as_lock(table);
1417
      }
1418
      else if (table->open_placeholder && !morph_locks)
1419
      {
1420
        /*
1421
          We come here only in close-for-back-off scenario. So we have to
1422
          "close" create placeholder here to avoid deadlocks (for example,
1423
          in case of concurrent execution of CREATE TABLE t1 SELECT * FROM t2
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1424
          and RENAME Table t2 TO t1). In close-for-re-open scenario we will
1 by brian
clean slate
1425
          probably want to let it stay.
1426
1427
          Note "***": We must not enter this branch if the placeholder
1428
          flag has been set because of a former close through a child.
1429
          See above the comment that refers to this note.
1430
        */
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1431
        table->open_placeholder= false;
1 by brian
clean slate
1432
      }
1433
    }
1434
  }
1435
  if (found)
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
1436
    locking::broadcast_refresh();
1 by brian
clean slate
1437
}
1438
1439
1440
/*
1441
  drop tables from locked list
1442
1443
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1444
  drop_locked_tables()
1445
  session			Thread thandler
1446
  db			Database
1447
  table_name		Table name
1 by brian
clean slate
1448
1449
  INFORMATION
1046 by Brian Aker
Merge Jay.
1450
  This is only called on drop tables
1 by brian
clean slate
1451
1046 by Brian Aker
Merge Jay.
1452
  The Table object for the dropped table is unlocked but still kept around
1453
  as a name lock, which means that the table will be available for other
1454
  thread as soon as we call unlock_table_names().
1455
  If there is multiple copies of the table locked, all copies except
1456
  the first, which acts as a name lock, is removed.
1 by brian
clean slate
1457
1458
  RETURN
1046 by Brian Aker
Merge Jay.
1459
#    If table existed, return table
1460
0	 Table was not locked
1 by brian
clean slate
1461
*/
1462
1463
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1464
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1 by brian
clean slate
1465
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1466
  Table *table,*next,**prev, *found= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
1467
  prev= &session->open_tables;
1 by brian
clean slate
1468
1469
  /*
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1470
    Note that we need to hold table::Cache::singleton().mutex() while changing the
1 by brian
clean slate
1471
    open_tables list. Another thread may work on it.
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1472
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
1 by brian
clean slate
1473
    Closing a MERGE child before the parent would be fatal if the
1474
    other thread tries to abort the MERGE lock in between.
1475
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1476
  for (table= session->open_tables; table ; table=next)
1 by brian
clean slate
1477
  {
1608 by Brian Aker
This encapsulates prev/next.
1478
    next=table->getNext();
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1479
    if (table->getShare()->getCacheKey() == identifier.getKey())
1 by brian
clean slate
1480
    {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1481
      session->removeLock(table);
1 by brian
clean slate
1482
1483
      if (!found)
1484
      {
1485
        found= table;
1486
        /* Close engine table, but keep object around as a name lock */
1487
        if (table->db_stat)
1488
        {
1489
          table->db_stat= 0;
1208.3.2 by brian
Update for Cursor renaming.
1490
          table->cursor->close();
1 by brian
clean slate
1491
        }
1492
      }
1493
      else
1494
      {
1495
        /* We already have a name lock, remove copy */
1887.2.1 by Brian Aker
Merge in refactoring tree. This breaks out TableShare into cache and
1496
        table::remove_table(static_cast<table::Concurrent *>(table));
1 by brian
clean slate
1497
      }
1498
    }
1499
    else
1500
    {
1501
      *prev=table;
1608 by Brian Aker
This encapsulates prev/next.
1502
      prev= table->getNextPtr();
1 by brian
clean slate
1503
    }
1504
  }
1505
  *prev=0;
1506
  if (found)
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
1507
    locking::broadcast_refresh();
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1508
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1509
  return(found);
1 by brian
clean slate
1510
}
1511
1512
1513
/*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1514
  If we have the table open, which only happens when a LOCK Table has been
1 by brian
clean slate
1515
  done on the table, change the lock type to a lock that will abort all
1516
  other threads trying to get the lock.
1517
*/
1518
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1519
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1 by brian
clean slate
1520
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1521
  Table *table;
1608 by Brian Aker
This encapsulates prev/next.
1522
  for (table= session->open_tables; table ; table= table->getNext())
1 by brian
clean slate
1523
  {
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1524
    if (table->getShare()->getCacheKey() == identifier.getKey())
1 by brian
clean slate
1525
    {
1526
      /* If MERGE child, forward lock handling to parent. */
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1527
      session->abortLock(table);
1 by brian
clean slate
1528
      break;
1529
    }
1530
  }
1531
}
1532
1533
1534
/*
1535
  Open all tables in list
1536
1537
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1538
  open_tables()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1539
  session - thread Cursor
1046 by Brian Aker
Merge Jay.
1540
  start - list of tables in/out
1541
  counter - number of opened tables will be return using this parameter
1542
  flags   - bitmap of flags to modify how the tables will be open:
1543
  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
1544
  done a flush or namelock on it.
1 by brian
clean slate
1545
1546
  NOTE
1046 by Brian Aker
Merge Jay.
1547
  Unless we are already in prelocked mode, this function will also precache
1548
  all SP/SFs explicitly or implicitly (via views and triggers) used by the
1549
  query and add tables needed for their execution to table list. If resulting
1550
  tables list will be non empty it will mark query as requiring precaching.
1551
  Prelocked mode will be enabled for such query during lock_tables() call.
1 by brian
clean slate
1552
1046 by Brian Aker
Merge Jay.
1553
  If query for which we are opening tables is already marked as requiring
1554
  prelocking it won't do such precaching and will simply reuse table list
1555
  which is already built.
1 by brian
clean slate
1556
1557
  RETURN
1046 by Brian Aker
Merge Jay.
1558
  0  - OK
1559
  -1 - error
1 by brian
clean slate
1560
*/
1561
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1562
int Session::open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags)
1 by brian
clean slate
1563
{
327.2.4 by Brian Aker
Refactoring table.h
1564
  TableList *tables= NULL;
1 by brian
clean slate
1565
  bool refresh;
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1566
  int result= 0;
1 by brian
clean slate
1567
  /* Also used for indicating that prelocking is need */
1568
  bool safe_to_ignore_table;
1569
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1570
  current_tablenr= 0;
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1571
restart:
1 by brian
clean slate
1572
  *counter= 0;
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1573
  set_proc_info("Opening tables");
1 by brian
clean slate
1574
1575
  /*
1576
    For every table in the list of tables to open, try to find or open
1577
    a table.
1578
  */
1579
  for (tables= *start; tables ;tables= tables->next_global)
1580
  {
55 by brian
Update for using real bool types.
1581
    safe_to_ignore_table= false;
1 by brian
clean slate
1582
1583
    /*
1584
      Ignore placeholders for derived tables. After derived tables
1585
      processing, link to created temporary table will be put here.
1586
      If this is derived table for view then we still want to process
1587
      routines used by this view.
1046 by Brian Aker
Merge Jay.
1588
    */
1 by brian
clean slate
1589
    if (tables->derived)
1590
    {
1591
      continue;
1592
    }
1593
    (*counter)++;
1594
1595
    /*
1317.2.5 by Monty Taylor
Prevent the user from seeing or attempting to access tables that he is not
1596
     * Is the user authorized to see this table? Do this before we check
1597
     * to see if it exists so that an unauthorized user cannot phish for
1598
     * table/schema information via error messages
1599
     */
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1600
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
1601
    if (not plugin::Authorization::isAuthorized(user(), the_table))
1317.2.5 by Monty Taylor
Prevent the user from seeing or attempting to access tables that he is not
1602
    {
1603
      result= -1;                               // Fatal error
1604
      break;
1605
    }
1606
1607
1608
    /*
1 by brian
clean slate
1609
      Not a placeholder: must be a base table or a view, and the table is
1610
      not opened yet. Try to open the table.
1611
    */
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
1612
    if (tables->table == NULL)
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1613
      tables->table= openTable(tables, &refresh, flags);
1 by brian
clean slate
1614
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
1615
    if (tables->table == NULL)
1 by brian
clean slate
1616
    {
1617
      if (refresh)				// Refresh in progress
1618
      {
1619
        /*
1620
          We have met name-locked or old version of table. Now we have
1621
          to close all tables which are not up to date. We also have to
1622
          throw away set of prelocked tables (and thus close tables from
1623
          this set that were open by now) since it possible that one of
1624
          tables which determined its content was changed.
1625
1626
          Instead of implementing complex/non-robust logic mentioned
1627
          above we simply close and then reopen all tables.
1628
1629
          In order to prepare for recalculation of set of prelocked tables
1630
          we pretend that we have finished calculation which we were doing
1631
          currently.
1632
        */
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1633
        close_tables_for_reopen(start);
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1634
        goto restart;
1 by brian
clean slate
1635
      }
1636
1637
      if (safe_to_ignore_table)
1638
        continue;
1639
1640
      result= -1;				// Fatal error
1641
      break;
1642
    }
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1643
    if (tables->lock_type != TL_UNLOCK)
1 by brian
clean slate
1644
    {
1645
      if (tables->lock_type == TL_WRITE_DEFAULT)
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1646
        tables->table->reginfo.lock_type= update_lock_default;
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
1647
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
1 by brian
clean slate
1648
        tables->table->reginfo.lock_type= tables->lock_type;
1649
    }
1650
  }
1651
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1652
  set_proc_info(0);
1 by brian
clean slate
1653
1654
  if (result && tables)
1655
  {
1656
    /*
1657
      Some functions determine success as (tables->table != NULL).
520.1.22 by Brian Aker
Second pass of thd cleanup
1658
      tables->table is in session->open_tables.
1 by brian
clean slate
1659
    */
1660
    tables->table= NULL;
1661
  }
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1662
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1663
  return(result);
1 by brian
clean slate
1664
}
1665
1666
1667
/*
1668
  Open and lock one table
1669
1670
  SYNOPSIS
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
1671
  openTableLock()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1672
  session			Thread Cursor
1046 by Brian Aker
Merge Jay.
1673
  table_list		Table to open is first table in this list
1674
  lock_type		Lock to use for open
1675
  lock_flags          Flags passed to mysql_lock_table
1 by brian
clean slate
1676
1677
  NOTE
1046 by Brian Aker
Merge Jay.
1678
  This function don't do anything like SP/SF/views/triggers analysis done
1679
  in open_tables(). It is intended for opening of only one concrete table.
1680
  And used only in special contexts.
1 by brian
clean slate
1681
1682
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
1683
  table		Opened table
1684
  0			Error
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1685
1046 by Brian Aker
Merge Jay.
1686
  If ok, the following are also set:
1687
  table_list->lock_type 	lock_type
1688
  table_list->table		table
1 by brian
clean slate
1689
*/
1690
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1691
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
1 by brian
clean slate
1692
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1693
  Table *table;
1 by brian
clean slate
1694
  bool refresh;
1695
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1696
  set_proc_info("Opening table");
1697
  current_tablenr= 0;
2060.3.1 by Brian Aker
First pass, remove retry.
1698
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
1 by brian
clean slate
1699
1700
  if (table)
1701
  {
1702
    table_list->lock_type= lock_type;
1703
    table_list->table=	   table;
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1704
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1705
    assert(lock == 0);	// You must lock everything at once
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1706
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2060.3.1 by Brian Aker
First pass, remove retry.
1707
    {
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1708
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
        table= NULL;
2060.3.1 by Brian Aker
First pass, remove retry.
1710
    }
1 by brian
clean slate
1711
  }
1712
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1713
  set_proc_info(0);
1714
1715
  return table;
1 by brian
clean slate
1716
}
1717
1718
/*
1719
  Lock all tables in list
1720
1721
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1722
  lock_tables()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1723
  session			Thread Cursor
1046 by Brian Aker
Merge Jay.
1724
  tables		Tables to lock
1725
  count		Number of opened tables
1726
  need_reopen         Out parameter which if true indicates that some
1727
  tables were dropped or altered during this call
1728
  and therefore invoker should reopen tables and
1729
  try to lock them once again (in this case
1730
  lock_tables() will also return error).
1 by brian
clean slate
1731
1732
  NOTES
1046 by Brian Aker
Merge Jay.
1733
  You can't call lock_tables twice, as this would break the dead-lock-free
1734
  handling thr_lock gives us.  You most always get all needed locks at
1735
  once.
1 by brian
clean slate
1736
1046 by Brian Aker
Merge Jay.
1737
  If query for which we are calling this function marked as requring
1738
  prelocking, this function will do implicit LOCK TABLES and change
1739
  session::prelocked_mode accordingly.
1 by brian
clean slate
1740
1741
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
1742
  0	ok
1743
  -1	Error
1 by brian
clean slate
1744
*/
1745
1109.1.5 by Brian Aker
More extraction from sql_base
1746
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
1 by brian
clean slate
1747
{
327.2.4 by Brian Aker
Refactoring table.h
1748
  TableList *table;
1109.1.5 by Brian Aker
More extraction from sql_base
1749
  Session *session= this;
1 by brian
clean slate
1750
1751
  /*
1752
    We can't meet statement requiring prelocking if we already
1753
    in prelocked mode.
1754
  */
55 by brian
Update for using real bool types.
1755
  *need_reopen= false;
1 by brian
clean slate
1756
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
1757
  if (tables == NULL)
600 by Brian Aker
Removing more options around changing replication
1758
    return 0;
1 by brian
clean slate
1759
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1760
  assert(session->lock == 0);	// You must lock everything at once
1761
  Table **start,**ptr;
1762
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
1764
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
    return -1;
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1766
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1767
  for (table= tables; table; table= table->next_global)
1 by brian
clean slate
1768
  {
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1769
    if (!table->placeholder())
1770
      *(ptr++)= table->table;
1 by brian
clean slate
1771
  }
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1772
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1773
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
1 by brian
clean slate
1774
  {
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1775
    return -1;
1 by brian
clean slate
1776
  }
1777
600 by Brian Aker
Removing more options around changing replication
1778
  return 0;
1 by brian
clean slate
1779
}
1780
1781
1782
/*
1783
  Open a single table without table caching and don't set it in open_list
1784
1785
  SYNPOSIS
1046 by Brian Aker
Merge Jay.
1786
  open_temporary_table()
1787
  session		  Thread object
1788
  path	  Path (without .frm)
1789
  db		  database
1790
  table_name	  Table name
1791
  link_in_list  1 if table should be linked into session->temporary_tables
1792
1793
NOTES:
1794
Used by alter_table to open a temporary table and when creating
1795
a temporary table with CREATE TEMPORARY ...
1796
1797
RETURN
1798
0  Error
1799
#  Table object
1 by brian
clean slate
1800
*/
1801
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
1802
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
1803
                                               bool link_in_list)
1 by brian
clean slate
1804
{
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
1805
  assert(identifier.isTmp());
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1806
1807
1808
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1809
                                                        identifier,
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
1810
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1811
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1669.2.4 by Brian Aker
Fix temp tables to use new over malloc.
1812
  if (not new_tmp_table)
684 by Brian Aker
Mass cleanup for casting.
1813
    return NULL;
1 by brian
clean slate
1814
1039.1.10 by Brian Aker
Minor formating, change of one name to make grep easier :)
1815
  /*
1816
    First open the share, and then open the table from the share we just opened.
1817
  */
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
1818
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1820
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1821
                                                                          HA_GET_INDEX),
1822
                                                              ha_open_options,
1823
                                                              *new_tmp_table))
1 by brian
clean slate
1824
  {
1825
    /* No need to lock share->mutex as this is not needed for tmp tables */
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1826
    delete new_tmp_table->getMutableShare();
1672.3.4 by Brian Aker
This change the style on a few TODO, and fixes an error path to correctly
1827
    delete new_tmp_table;
1502.1.19 by Brian Aker
Adds concept of table owned TableShare.
1828
1046.1.10 by Brian Aker
Formatting around return (style)
1829
    return 0;
1 by brian
clean slate
1830
  }
1831
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1832
  new_tmp_table->reginfo.lock_type= TL_WRITE;	 // Simulate locked
1 by brian
clean slate
1833
1834
  if (link_in_list)
1835
  {
1836
    /* growing temp list at the head */
1608 by Brian Aker
This encapsulates prev/next.
1837
    new_tmp_table->setNext(this->temporary_tables);
1838
    if (new_tmp_table->getNext())
1839
    {
1840
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1841
    }
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1842
    this->temporary_tables= new_tmp_table;
1608 by Brian Aker
This encapsulates prev/next.
1843
    this->temporary_tables->setPrev(0);
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1844
  }
1845
  new_tmp_table->pos_in_table_list= 0;
1846
1847
  return new_tmp_table;
1 by brian
clean slate
1848
}
1849
1850
1851
/*****************************************************************************
1046 by Brian Aker
Merge Jay.
1852
 * The following find_field_in_XXX procedures implement the core of the
1853
 * name resolution functionality. The entry point to resolve a column name in a
1854
 * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
1855
 * for each table reference. In turn, depending on the type of table reference,
1856
 * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
1857
 * below specific for the type of table reference.
1858
 ******************************************************************************/
1 by brian
clean slate
1859
1860
/* Special Field pointers as return values of find_field_in_XXX functions. */
1861
Field *not_found_field= (Field*) 0x1;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1862
Field *view_ref_found= (Field*) 0x2;
1 by brian
clean slate
1863
520.1.22 by Brian Aker
Second pass of thd cleanup
1864
static void update_field_dependencies(Session *session, Field *field, Table *table)
1 by brian
clean slate
1865
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1866
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1 by brian
clean slate
1867
  {
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1868
    boost::dynamic_bitset<> *current_bitmap= NULL;
1 by brian
clean slate
1869
1870
    /*
1871
      We always want to register the used keys, as the column bitmap may have
1872
      been set for all fields (for example for view).
1873
    */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1874
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1875
    table->covering_keys&= field->part_of_key;
1876
    table->merge_keys|= field->part_of_key;
1 by brian
clean slate
1877
520.1.22 by Brian Aker
Second pass of thd cleanup
1878
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1 by brian
clean slate
1879
    {
1880
      current_bitmap= table->read_set;
1881
    }
1882
    else
1883
    {
1884
      current_bitmap= table->write_set;
1885
    }
1886
1999.4.2 by Brian Aker
Encapsulate the field's position.
1887
    //if (current_bitmap->testAndSet(field->position()))
1888
    if (current_bitmap->test(field->position()))
1 by brian
clean slate
1889
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1890
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
        session->dup_field= field;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1892
      return;
1 by brian
clean slate
1893
    }
1894
    table->used_fields++;
1895
  }
1896
}
1897
1898
1899
/*
1900
  Find field by name in a NATURAL/USING join table reference.
1901
1902
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1903
  find_field_in_natural_join()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1904
  session			 [in]  thread Cursor
1046 by Brian Aker
Merge Jay.
1905
  table_ref            [in]  table reference to search
1906
  name		 [in]  name of field
1907
  length		 [in]  length of name
1908
  ref                  [in/out] if 'name' is resolved to a view field, ref is
1909
  set to point to the found view field
1910
  register_tree_change [in]  true if ref is not stack variable and we
1911
  need register changes in item tree
1912
  actual_table         [out] the original table reference where the field
1913
  belongs - differs from 'table_list' only for
1914
  NATURAL/USING joins
1 by brian
clean slate
1915
1916
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
1917
  Search for a field among the result fields of a NATURAL/USING join.
1918
  Notice that this procedure is called only for non-qualified field
1919
  names. In the case of qualified fields, we search directly the base
1920
  tables of a natural join.
1 by brian
clean slate
1921
1922
  RETURN
1046 by Brian Aker
Merge Jay.
1923
  NULL        if the field was not found
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
1924
  PTR         Pointer to the found Field
1 by brian
clean slate
1925
*/
1926
1927
static Field *
779.3.1 by Monty Taylor
More cleanup.
1928
find_field_in_natural_join(Session *session, TableList *table_ref,
1929
                           const char *name, uint32_t , Item **,
1930
                           bool, TableList **actual_table)
1 by brian
clean slate
1931
{
1932
  List_iterator_fast<Natural_join_column>
1933
    field_it(*(table_ref->join_columns));
1934
  Natural_join_column *nj_col, *curr_nj_col;
1935
  Field *found_field;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1936
1937
  assert(table_ref->is_natural_join && table_ref->join_columns);
1938
  assert(*actual_table == NULL);
1 by brian
clean slate
1939
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1940
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
1 by brian
clean slate
1941
       curr_nj_col= field_it++)
1942
  {
1943
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
1944
    {
1945
      if (nj_col)
1946
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1947
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1019.1.6 by Brian Aker
A number of random cleanups.
1948
        return NULL;
1 by brian
clean slate
1949
      }
1950
      nj_col= curr_nj_col;
1951
    }
1952
  }
1953
  if (!nj_col)
1019.1.6 by Brian Aker
A number of random cleanups.
1954
    return NULL;
1 by brian
clean slate
1955
  {
1956
    /* This is a base table. */
1660.1.3 by Brian Aker
Encapsulate Table in field
1957
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
1 by brian
clean slate
1958
    found_field= nj_col->table_field;
520.1.22 by Brian Aker
Second pass of thd cleanup
1959
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1 by brian
clean slate
1960
  }
1961
1962
  *actual_table= nj_col->table_ref;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1963
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1964
  return(found_field);
1 by brian
clean slate
1965
}
1966
1967
1968
/*
1969
  Find field by name in a base table or a view with temp table algorithm.
1970
1971
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1972
  find_field_in_table()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1973
  session				thread Cursor
1046 by Brian Aker
Merge Jay.
1974
  table			table where to search for the field
1975
  name			name of field
1976
  length			length of name
1977
  allow_rowid			do allow finding of "_rowid" field?
1978
  cached_field_index_ptr	cached position in field list (used to speedup
1979
  lookup for fields in prepared tables)
1 by brian
clean slate
1980
1981
  RETURN
1046 by Brian Aker
Merge Jay.
1982
  0	field is not found
1983
#	pointer to field
1 by brian
clean slate
1984
*/
1985
1986
Field *
520.1.22 by Brian Aker
Second pass of thd cleanup
1987
find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
482 by Brian Aker
Remove uint.
1988
                    bool allow_rowid, uint32_t *cached_field_index_ptr)
1 by brian
clean slate
1989
{
1990
  Field **field_ptr, *field;
482 by Brian Aker
Remove uint.
1991
  uint32_t cached_field_index= *cached_field_index_ptr;
1 by brian
clean slate
1992
1993
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
1578.2.10 by Brian Aker
keys and fields partial encapsulation.
1994
  if (cached_field_index < table->getShare()->sizeFields() &&
1 by brian
clean slate
1995
      !my_strcasecmp(system_charset_info,
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1996
                     table->getField(cached_field_index)->field_name, name))
1578.2.14 by Brian Aker
Additional pass through to remove raw field access.
1997
  {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1998
    field_ptr= table->getFields() + cached_field_index;
1578.2.14 by Brian Aker
Additional pass through to remove raw field access.
1999
  }
1669.3.1 by Brian Aker
Remove usage of my_hash in table_share.
2000
  else if (table->getShare()->getNamedFieldSize())
1 by brian
clean slate
2001
  {
1669.3.1 by Brian Aker
Remove usage of my_hash in table_share.
2002
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
1 by brian
clean slate
2003
    if (field_ptr)
2004
    {
2005
      /*
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
2006
        field_ptr points to field in TableShare. Convert it to the matching
1 by brian
clean slate
2007
        field in table
2008
      */
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2009
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
1 by brian
clean slate
2010
    }
2011
  }
2012
  else
2013
  {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2014
    if (!(field_ptr= table->getFields()))
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2015
      return((Field *)0);
1 by brian
clean slate
2016
    for (; *field_ptr; ++field_ptr)
2017
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2018
        break;
2019
  }
2020
2021
  if (field_ptr && *field_ptr)
2022
  {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2023
    *cached_field_index_ptr= field_ptr - table->getFields();
1 by brian
clean slate
2024
    field= *field_ptr;
2025
  }
2026
  else
2027
  {
2028
    if (!allow_rowid ||
2029
        my_strcasecmp(system_charset_info, name, "_rowid") ||
1574 by Brian Aker
Rollup patch for hiding tableshare.
2030
        table->getShare()->rowid_field_offset == 0)
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2031
      return((Field*) 0);
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2032
    field= table->getField(table->getShare()->rowid_field_offset-1);
1 by brian
clean slate
2033
  }
2034
520.1.22 by Brian Aker
Second pass of thd cleanup
2035
  update_field_dependencies(session, field, table);
1 by brian
clean slate
2036
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2037
  return field;
1 by brian
clean slate
2038
}
2039
2040
2041
/*
2042
  Find field in a table reference.
2043
2044
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2045
  find_field_in_table_ref()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2046
  session			   [in]  thread Cursor
1046 by Brian Aker
Merge Jay.
2047
  table_list		   [in]  table reference to search
2048
  name		   [in]  name of field
2049
  length		   [in]  field length of name
2050
  item_name              [in]  name of item if it will be created (VIEW)
2051
  db_name                [in]  optional database name that qualifies the
2052
  table_name             [in]  optional table name that qualifies the field
2053
  ref		       [in/out] if 'name' is resolved to a view field, ref
2054
  is set to point to the found view field
2055
  allow_rowid		   [in]  do allow finding of "_rowid" field?
2056
  cached_field_index_ptr [in]  cached position in field list (used to
2057
  speedup lookup for fields in prepared tables)
2058
  register_tree_change   [in]  true if ref is not stack variable and we
2059
  need register changes in item tree
2060
  actual_table           [out] the original table reference where the field
2061
  belongs - differs from 'table_list' only for
2062
  NATURAL_USING joins.
1 by brian
clean slate
2063
2064
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2065
  Find a field in a table reference depending on the type of table
2066
  reference. There are three types of table references with respect
2067
  to the representation of their result columns:
2068
  - an array of Field_translator objects for MERGE views and some
2069
  information_schema tables,
2070
  - an array of Field objects (and possibly a name hash) for stored
2071
  tables,
2072
  - a list of Natural_join_column objects for NATURAL/USING joins.
2073
  This procedure detects the type of the table reference 'table_list'
2074
  and calls the corresponding search routine.
1 by brian
clean slate
2075
2076
  RETURN
1046 by Brian Aker
Merge Jay.
2077
  0			field is not found
2078
  view_ref_found	found value in VIEW (real result is in *ref)
2079
#			pointer to field
1 by brian
clean slate
2080
*/
2081
2082
Field *
520.1.22 by Brian Aker
Second pass of thd cleanup
2083
find_field_in_table_ref(Session *session, TableList *table_list,
482 by Brian Aker
Remove uint.
2084
                        const char *name, uint32_t length,
1 by brian
clean slate
2085
                        const char *item_name, const char *db_name,
2086
                        const char *table_name, Item **ref,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2087
                        bool allow_rowid,
482 by Brian Aker
Remove uint.
2088
                        uint32_t *cached_field_index_ptr,
327.2.4 by Brian Aker
Refactoring table.h
2089
                        bool register_tree_change, TableList **actual_table)
1 by brian
clean slate
2090
{
327.2.5 by Brian Aker
Refactoring show command
2091
  Field *fld= NULL;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2092
2093
  assert(table_list->alias);
2094
  assert(name);
2095
  assert(item_name);
1 by brian
clean slate
2096
2097
  /*
2098
    Check that the table and database that qualify the current field name
2099
    are the same as the table reference we are going to search for the field.
2100
2101
    Exclude from the test below nested joins because the columns in a
2102
    nested join generally originate from different tables. Nested joins
2103
    also have no table name, except when a nested join is a merge view
2104
    or an information schema table.
2105
2106
    We include explicitly table references with a 'field_translation' table,
2107
    because if there are views over natural joins we don't want to search
2108
    inside the view, but we want to search directly in the view columns
2109
    which are represented as a 'field_translation'.
2110
1532.1.2 by Brian Aker
Remove need for memset on Table object.
2111
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
1 by brian
clean slate
2112
  */
2113
  if (/* Exclude nested joins. */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2114
      (!table_list->getNestedJoin()) &&
1046 by Brian Aker
Merge Jay.
2115
      /* Include merge views and information schema tables. */
1 by brian
clean slate
2116
      /*
2117
        Test if the field qualifiers match the table reference we plan
2118
        to search.
2119
      */
2120
      table_name && table_name[0] &&
2121
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
1874.1.1 by Brian Aker
Encapsulate schema_name it table_list.
2122
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2123
        strcmp(db_name, table_list->getSchemaName()))))
1046.1.10 by Brian Aker
Formatting around return (style)
2124
    return 0;
1 by brian
clean slate
2125
2126
  *actual_table= NULL;
2127
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2128
  if (!table_list->getNestedJoin())
1 by brian
clean slate
2129
  {
2130
    /* 'table_list' is a stored table. */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2131
    assert(table_list->table);
520.1.22 by Brian Aker
Second pass of thd cleanup
2132
    if ((fld= find_field_in_table(session, table_list->table, name, length,
1 by brian
clean slate
2133
                                  allow_rowid,
2134
                                  cached_field_index_ptr)))
2135
      *actual_table= table_list;
2136
  }
2137
  else
2138
  {
2139
    /*
2140
      'table_list' is a NATURAL/USING join, or an operand of such join that
2141
      is a nested join itself.
2142
2143
      If the field name we search for is qualified, then search for the field
2144
      in the table references used by NATURAL/USING the join.
2145
    */
2146
    if (table_name && table_name[0])
2147
    {
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2148
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
327.2.4 by Brian Aker
Refactoring table.h
2149
      TableList *table;
1 by brian
clean slate
2150
      while ((table= it++))
2151
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
2152
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
1 by brian
clean slate
2153
                                          db_name, table_name, ref,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2154
                                          allow_rowid,
1 by brian
clean slate
2155
                                          cached_field_index_ptr,
2156
                                          register_tree_change, actual_table)))
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2157
          return fld;
1 by brian
clean slate
2158
      }
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2159
      return NULL;
1 by brian
clean slate
2160
    }
2161
    /*
2162
      Non-qualified field, search directly in the result columns of the
2163
      natural join. The condition of the outer IF is true for the top-most
2164
      natural join, thus if the field is not qualified, we will search
2165
      directly the top-most NATURAL/USING join.
2166
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
2167
    fld= find_field_in_natural_join(session, table_list, name, length, ref,
1 by brian
clean slate
2168
                                    register_tree_change, actual_table);
2169
  }
2170
2171
  if (fld)
2172
  {
1046 by Brian Aker
Merge Jay.
2173
    if (session->mark_used_columns != MARK_COLUMNS_NONE)
2174
    {
2175
      /*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2176
        Get rw_set correct for this field so that the Cursor
1046 by Brian Aker
Merge Jay.
2177
        knows that this field is involved in the query and gets
2178
        retrieved/updated
2179
      */
2180
      Field *field_to_set= NULL;
2181
      if (fld == view_ref_found)
1 by brian
clean slate
2182
      {
1046 by Brian Aker
Merge Jay.
2183
        Item *it= (*ref)->real_item();
2184
        if (it->type() == Item::FIELD_ITEM)
2185
          field_to_set= ((Item_field*)it)->field;
1 by brian
clean slate
2186
        else
2187
        {
520.1.22 by Brian Aker
Second pass of thd cleanup
2188
          if (session->mark_used_columns == MARK_COLUMNS_READ)
1046 by Brian Aker
Merge Jay.
2189
            it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
1 by brian
clean slate
2190
        }
2191
      }
1046 by Brian Aker
Merge Jay.
2192
      else
2193
        field_to_set= fld;
2194
      if (field_to_set)
2195
      {
1660.1.3 by Brian Aker
Encapsulate Table in field
2196
        Table *table= field_to_set->getTable();
1046 by Brian Aker
Merge Jay.
2197
        if (session->mark_used_columns == MARK_COLUMNS_READ)
1999.4.2 by Brian Aker
Encapsulate the field's position.
2198
          table->setReadSet(field_to_set->position());
1046 by Brian Aker
Merge Jay.
2199
        else
1999.4.2 by Brian Aker
Encapsulate the field's position.
2200
          table->setWriteSet(field_to_set->position());
1046 by Brian Aker
Merge Jay.
2201
      }
2202
    }
1 by brian
clean slate
2203
  }
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2204
  return(fld);
1 by brian
clean slate
2205
}
2206
2207
2208
/*
2209
  Find field in table list.
2210
2211
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2212
  find_field_in_tables()
2213
  session			  pointer to current thread structure
2214
  item		  field item that should be found
2215
  first_table           list of tables to be searched for item
2216
  last_table            end of the list of tables to search for item. If NULL
2217
  then search to the end of the list 'first_table'.
2218
  ref			  if 'item' is resolved to a view field, ref is set to
2219
  point to the found view field
2220
  report_error	  Degree of error reporting:
2221
  - IGNORE_ERRORS then do not report any error
2222
  - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2223
  fields, suppress all other errors
2224
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2225
  except when non-unique fields were found
2226
  - REPORT_ALL_ERRORS
2227
  register_tree_change  true if ref is not a stack variable and we
2228
  to need register changes in item tree
1 by brian
clean slate
2229
2230
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
2231
  0			If error: the found field is not unique, or there are
2232
  no sufficient access priviliges for the found field,
2233
  or the field is qualified with non-existing table.
2234
  not_found_field	The function was called with report_error ==
2235
  (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2236
  field was not found.
2237
  view_ref_found	View field is found, item passed through ref parameter
2238
  found field         If a item was resolved to some field
1 by brian
clean slate
2239
*/
2240
2241
Field *
520.1.22 by Brian Aker
Second pass of thd cleanup
2242
find_field_in_tables(Session *session, Item_ident *item,
327.2.4 by Brian Aker
Refactoring table.h
2243
                     TableList *first_table, TableList *last_table,
1046 by Brian Aker
Merge Jay.
2244
                     Item **ref, find_item_error_report_type report_error,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2245
                     bool register_tree_change)
1 by brian
clean slate
2246
{
2247
  Field *found=0;
2248
  const char *db= item->db_name;
2249
  const char *table_name= item->table_name;
2250
  const char *name= item->field_name;
895 by Brian Aker
Completion (?) of uint conversion.
2251
  uint32_t length=(uint32_t) strlen(name);
1 by brian
clean slate
2252
  char name_buff[NAME_LEN+1];
327.2.4 by Brian Aker
Refactoring table.h
2253
  TableList *cur_table= first_table;
2254
  TableList *actual_table;
1 by brian
clean slate
2255
  bool allow_rowid;
2256
2257
  if (!table_name || !table_name[0])
2258
  {
2259
    table_name= 0;                              // For easier test
2260
    db= 0;
2261
  }
2262
2263
  allow_rowid= table_name || (cur_table && !cur_table->next_local);
2264
2265
  if (item->cached_table)
2266
  {
2267
    /*
2268
      This shortcut is used by prepared statements. We assume that
327.2.4 by Brian Aker
Refactoring table.h
2269
      TableList *first_table is not changed during query execution (which
1 by brian
clean slate
2270
      is true for all queries except RENAME but luckily RENAME doesn't
2271
      use fields...) so we can rely on reusing pointer to its member.
2272
      With this optimization we also miss case when addition of one more
2273
      field makes some prepared query ambiguous and so erroneous, but we
2274
      accept this trade off.
2275
    */
327.2.4 by Brian Aker
Refactoring table.h
2276
    TableList *table_ref= item->cached_table;
1 by brian
clean slate
2277
    /*
2278
      The condition (table_ref->view == NULL) ensures that we will call
2279
      find_field_in_table even in the case of information schema tables
2280
      when table_ref->field_translation != NULL.
1046 by Brian Aker
Merge Jay.
2281
    */
1 by brian
clean slate
2282
    if (table_ref->table)
520.1.22 by Brian Aker
Second pass of thd cleanup
2283
      found= find_field_in_table(session, table_ref->table, name, length,
55 by brian
Update for using real bool types.
2284
                                 true, &(item->cached_field_index));
1 by brian
clean slate
2285
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
2286
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2287
                                     NULL, NULL, ref,
55 by brian
Update for using real bool types.
2288
                                     true, &(item->cached_field_index),
1 by brian
clean slate
2289
                                     register_tree_change,
2290
                                     &actual_table);
2291
    if (found)
2292
    {
2293
      /*
2294
        Only views fields should be marked as dependent, not an underlying
2295
        fields.
2296
      */
2297
      {
846 by Brian Aker
Removing on typedeffed class.
2298
        Select_Lex *current_sel= session->lex->current_select;
2299
        Select_Lex *last_select= table_ref->select_lex;
1 by brian
clean slate
2300
        /*
2301
          If the field was an outer referencee, mark all selects using this
2302
          sub query as dependent on the outer query
2303
        */
2304
        if (current_sel != last_select)
520.1.22 by Brian Aker
Second pass of thd cleanup
2305
          mark_select_range_as_dependent(session, last_select, current_sel,
1 by brian
clean slate
2306
                                         found, *ref, item);
2307
      }
2308
      return found;
2309
    }
2310
  }
2311
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
2312
  if (db)
1 by brian
clean slate
2313
  {
2314
    /*
2315
      convert database to lower case for comparison.
2316
      We can't do this in Item_field as this would change the
2317
      'name' of the item which may be used in the select list
2318
    */
629.5.3 by Toru Maesaka
Third pass of replacing MySQL's strmake() with libc calls
2319
    strncpy(name_buff, db, sizeof(name_buff)-1);
1 by brian
clean slate
2320
    my_casedn_str(files_charset_info, name_buff);
2321
    db= name_buff;
2322
  }
2323
2324
  if (last_table)
2325
    last_table= last_table->next_name_resolution_table;
2326
2327
  for (; cur_table != last_table ;
2328
       cur_table= cur_table->next_name_resolution_table)
2329
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
2330
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
1 by brian
clean slate
2331
                                              item->name, db, table_name, ref,
2332
                                              allow_rowid,
2333
                                              &(item->cached_field_index),
2334
                                              register_tree_change,
2335
                                              &actual_table);
2336
    if (cur_field)
2337
    {
2338
      /*
2339
        Store the original table of the field, which may be different from
2340
        cur_table in the case of NATURAL/USING join.
2341
      */
1019.1.2 by Brian Aker
Removed dead code from table_list.
2342
      item->cached_table= found ?  0 : actual_table;
1 by brian
clean slate
2343
520.1.22 by Brian Aker
Second pass of thd cleanup
2344
      assert(session->where);
1 by brian
clean slate
2345
      /*
2346
        If we found a fully qualified field we return it directly as it can't
2347
        have duplicates.
1046 by Brian Aker
Merge Jay.
2348
      */
1 by brian
clean slate
2349
      if (db)
2350
        return cur_field;
2351
2352
      if (found)
2353
      {
2354
        if (report_error == REPORT_ALL_ERRORS ||
2355
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
2357
                   table_name ? item->full_name() : name, session->where);
1 by brian
clean slate
2358
        return (Field*) 0;
2359
      }
2360
      found= cur_field;
2361
    }
2362
  }
2363
2364
  if (found)
2365
    return found;
2366
2367
  /*
2368
    If the field was qualified and there were no tables to search, issue
2369
    an error that an unknown table was given. The situation is detected
2370
    as follows: if there were no tables we wouldn't go through the loop
2371
    and cur_table wouldn't be updated by the loop increment part, so it
2372
    will be equal to the first table.
2373
  */
2374
  if (table_name && (cur_table == first_table) &&
2375
      (report_error == REPORT_ALL_ERRORS ||
2376
       report_error == REPORT_EXCEPT_NON_UNIQUE))
2377
  {
2378
    char buff[NAME_LEN*2+1];
2379
    if (db && db[0])
2380
    {
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
2381
      /* We're in an error condition, two extra strlen's aren't going
2382
       * to kill us */
2383
      assert(strlen(db) <= NAME_LEN);
2384
      assert(strlen(table_name) <= NAME_LEN);
2385
      strcpy(buff, db);
2386
      strcat(buff,".");
2387
      strcat(buff, table_name);
1 by brian
clean slate
2388
      table_name=buff;
2389
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
2390
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
1 by brian
clean slate
2391
  }
2392
  else
2393
  {
2394
    if (report_error == REPORT_ALL_ERRORS ||
2395
        report_error == REPORT_EXCEPT_NON_UNIQUE)
520.1.22 by Brian Aker
Second pass of thd cleanup
2396
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
1 by brian
clean slate
2397
    else
2398
      found= not_found_field;
2399
  }
2400
  return found;
2401
}
2402
2403
2404
/*
2405
  Find Item in list of items (find_field_in_tables analog)
2406
2407
  TODO
1046 by Brian Aker
Merge Jay.
2408
  is it better return only counter?
1 by brian
clean slate
2409
2410
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2411
  find_item_in_list()
2412
  find			Item to find
2413
  items			List of items
2414
  counter			To return number of found item
2415
  report_error
2416
  REPORT_ALL_ERRORS		report errors, return 0 if error
2417
  REPORT_EXCEPT_NOT_FOUND	Do not report 'not found' error and
2418
  return not_found_item, report other errors,
2419
  return 0
2420
  IGNORE_ERRORS		Do not report errors, return 0 if error
2421
  resolution                  Set to the resolution type if the item is found
2422
  (it says whether the item is resolved
2423
  against an alias name,
2424
  or as a field name without alias,
2425
  or as a field hidden by alias,
2426
  or ignoring alias)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2427
1 by brian
clean slate
2428
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
2429
  0			Item is not found or item is not unique,
2430
  error message is reported
2431
  not_found_item	Function was called with
2432
  report_error == REPORT_EXCEPT_NOT_FOUND and
2433
  item was not found. No error message was reported
2434
  found field
1 by brian
clean slate
2435
*/
2436
2437
/* Special Item pointer to serve as a return value from find_item_in_list(). */
2438
Item **not_found_item= (Item**) 0x1;
2439
2440
2441
Item **
1578.6.3 by Brian Aker
More current_session removal.
2442
find_item_in_list(Session *session,
2443
                  Item *find, List<Item> &items, uint32_t *counter,
1 by brian
clean slate
2444
                  find_item_error_report_type report_error,
2445
                  enum_resolution_type *resolution)
2446
{
2447
  List_iterator<Item> li(items);
2448
  Item **found=0, **found_unaliased= 0, *item;
2449
  const char *db_name=0;
2450
  const char *field_name=0;
2451
  const char *table_name=0;
2452
  bool found_unaliased_non_uniq= 0;
2453
  /*
2454
    true if the item that we search for is a valid name reference
2455
    (and not an item that happens to have a name).
2456
  */
2457
  bool is_ref_by_name= 0;
482 by Brian Aker
Remove uint.
2458
  uint32_t unaliased_counter= 0;
1 by brian
clean slate
2459
2460
  *resolution= NOT_RESOLVED;
2461
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2462
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
1 by brian
clean slate
2463
                   find->type() == Item::REF_ITEM);
2464
  if (is_ref_by_name)
2465
  {
2466
    field_name= ((Item_ident*) find)->field_name;
2467
    table_name= ((Item_ident*) find)->table_name;
2468
    db_name=    ((Item_ident*) find)->db_name;
2469
  }
2470
482 by Brian Aker
Remove uint.
2471
  for (uint32_t i= 0; (item=li++); i++)
1 by brian
clean slate
2472
  {
2473
    if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
2474
    {
2475
      Item_ident *item_field= (Item_ident*) item;
2476
2477
      /*
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
2478
        In case of group_concat() with ORDER BY condition in the QUERY
2479
        item_field can be field of temporary table without item name
2480
        (if this field created from expression argument of group_concat()),
2481
        => we have to check presence of name before compare
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2482
      */
1 by brian
clean slate
2483
      if (!item_field->name)
2484
        continue;
2485
2486
      if (table_name)
2487
      {
2488
        /*
2489
          If table name is specified we should find field 'field_name' in
2490
          table 'table_name'. According to SQL-standard we should ignore
2491
          aliases in this case.
2492
2493
          Since we should NOT prefer fields from the select list over
2494
          other fields from the tables participating in this select in
2495
          case of ambiguity we have to do extra check outside this function.
2496
2497
          We use strcmp for table names and database names as these may be
2498
          case sensitive. In cases where they are not case sensitive, they
2499
          are always in lower case.
2500
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
2501
          item_field->field_name and item_field->table_name can be 0x0 if
2502
          item is not fix_field()'ed yet.
1 by brian
clean slate
2503
        */
2504
        if (item_field->field_name && item_field->table_name &&
1046 by Brian Aker
Merge Jay.
2505
            !my_strcasecmp(system_charset_info, item_field->field_name,
1 by brian
clean slate
2506
                           field_name) &&
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2507
            !my_strcasecmp(table_alias_charset, item_field->table_name,
1 by brian
clean slate
2508
                           table_name) &&
2509
            (!db_name || (item_field->db_name &&
2510
                          !strcmp(item_field->db_name, db_name))))
2511
        {
2512
          if (found_unaliased)
2513
          {
2514
            if ((*found_unaliased)->eq(item, 0))
2515
              continue;
2516
            /*
2517
              Two matching fields in select list.
2518
              We already can bail out because we are searching through
2519
              unaliased names only and will have duplicate error anyway.
2520
            */
2521
            if (report_error != IGNORE_ERRORS)
2522
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2523
                       find->full_name(), session->where);
1 by brian
clean slate
2524
            return (Item**) 0;
2525
          }
2526
          found_unaliased= li.ref();
2527
          unaliased_counter= i;
2528
          *resolution= RESOLVED_IGNORING_ALIAS;
2529
          if (db_name)
2530
            break;                              // Perfect match
2531
        }
2532
      }
2533
      else
2534
      {
2535
        int fname_cmp= my_strcasecmp(system_charset_info,
2536
                                     item_field->field_name,
2537
                                     field_name);
2538
        if (!my_strcasecmp(system_charset_info,
2539
                           item_field->name,field_name))
2540
        {
2541
          /*
2542
            If table name was not given we should scan through aliases
2543
            and non-aliased fields first. We are also checking unaliased
2544
            name of the field in then next  else-if, to be able to find
2545
            instantly field (hidden by alias) if no suitable alias or
2546
            non-aliased field was found.
2547
          */
2548
          if (found)
2549
          {
2550
            if ((*found)->eq(item, 0))
2551
              continue;                           // Same field twice
2552
            if (report_error != IGNORE_ERRORS)
2553
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2554
                       find->full_name(), session->where);
1 by brian
clean slate
2555
            return (Item**) 0;
2556
          }
2557
          found= li.ref();
2558
          *counter= i;
2559
          *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
1046 by Brian Aker
Merge Jay.
2560
            RESOLVED_WITH_NO_ALIAS;
1 by brian
clean slate
2561
        }
2562
        else if (!fname_cmp)
2563
        {
2564
          /*
2565
            We will use non-aliased field or react on such ambiguities only if
2566
            we won't be able to find aliased field.
2567
            Again if we have ambiguity with field outside of select list
2568
            we should prefer fields from select list.
2569
          */
2570
          if (found_unaliased)
2571
          {
2572
            if ((*found_unaliased)->eq(item, 0))
2573
              continue;                           // Same field twice
2574
            found_unaliased_non_uniq= 1;
2575
          }
2576
          found_unaliased= li.ref();
2577
          unaliased_counter= i;
2578
        }
2579
      }
2580
    }
2581
    else if (!table_name)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2582
    {
1 by brian
clean slate
2583
      if (is_ref_by_name && find->name && item->name &&
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
2584
          !my_strcasecmp(system_charset_info,item->name,find->name))
1 by brian
clean slate
2585
      {
2586
        found= li.ref();
2587
        *counter= i;
2588
        *resolution= RESOLVED_AGAINST_ALIAS;
2589
        break;
2590
      }
2591
      else if (find->eq(item,0))
2592
      {
2593
        found= li.ref();
2594
        *counter= i;
2595
        *resolution= RESOLVED_IGNORING_ALIAS;
2596
        break;
2597
      }
2598
    }
2599
  }
2600
  if (!found)
2601
  {
2602
    if (found_unaliased_non_uniq)
2603
    {
2604
      if (report_error != IGNORE_ERRORS)
2605
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2606
                 find->full_name(), session->where);
1 by brian
clean slate
2607
      return (Item **) 0;
2608
    }
2609
    if (found_unaliased)
2610
    {
2611
      found= found_unaliased;
2612
      *counter= unaliased_counter;
2613
      *resolution= RESOLVED_BEHIND_ALIAS;
2614
    }
2615
  }
2616
  if (found)
2617
    return found;
2618
  if (report_error != REPORT_EXCEPT_NOT_FOUND)
2619
  {
2620
    if (report_error == REPORT_ALL_ERRORS)
2621
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2622
               find->full_name(), session->where);
1 by brian
clean slate
2623
    return (Item **) 0;
2624
  }
2625
  else
2626
    return (Item **) not_found_item;
2627
}
2628
2629
2630
/*
2631
  Test if a string is a member of a list of strings.
2632
2633
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2634
  test_if_string_in_list()
2635
  find      the string to look for
2636
  str_list  a list of strings to be searched
1 by brian
clean slate
2637
2638
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2639
  Sequentially search a list of strings for a string, and test whether
2640
  the list contains the same string.
1 by brian
clean slate
2641
2642
  RETURN
1046 by Brian Aker
Merge Jay.
2643
  true  if find is in str_list
2644
  false otherwise
1 by brian
clean slate
2645
*/
2646
2647
static bool
2648
test_if_string_in_list(const char *find, List<String> *str_list)
2649
{
2650
  List_iterator<String> str_list_it(*str_list);
2651
  String *curr_str;
2652
  size_t find_length= strlen(find);
2653
  while ((curr_str= str_list_it++))
2654
  {
2655
    if (find_length != curr_str->length())
2656
      continue;
2657
    if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
55 by brian
Update for using real bool types.
2658
      return true;
1 by brian
clean slate
2659
  }
55 by brian
Update for using real bool types.
2660
  return false;
1 by brian
clean slate
2661
}
2662
2663
2664
/*
2665
  Create a new name resolution context for an item so that it is
2666
  being resolved in a specific table reference.
2667
2668
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2669
  set_new_item_local_context()
2670
  session        pointer to current thread
2671
  item       item for which new context is created and set
2672
  table_ref  table ref where an item showld be resolved
1 by brian
clean slate
2673
2674
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2675
  Create a new name resolution context for an item, so that the item
2676
  is resolved only the supplied 'table_ref'.
1 by brian
clean slate
2677
2678
  RETURN
1046 by Brian Aker
Merge Jay.
2679
  false  if all OK
2680
  true   otherwise
1 by brian
clean slate
2681
*/
2682
2683
static bool
520.1.22 by Brian Aker
Second pass of thd cleanup
2684
set_new_item_local_context(Session *session, Item_ident *item, TableList *table_ref)
1 by brian
clean slate
2685
{
2686
  Name_resolution_context *context;
520.1.22 by Brian Aker
Second pass of thd cleanup
2687
  if (!(context= new (session->mem_root) Name_resolution_context))
55 by brian
Update for using real bool types.
2688
    return true;
1 by brian
clean slate
2689
  context->init();
2690
  context->first_name_resolution_table=
2691
    context->last_name_resolution_table= table_ref;
2692
  item->context= context;
55 by brian
Update for using real bool types.
2693
  return false;
1 by brian
clean slate
2694
}
2695
2696
2697
/*
2698
  Find and mark the common columns of two table references.
2699
2700
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2701
  mark_common_columns()
2702
  session                [in] current thread
2703
  table_ref_1        [in] the first (left) join operand
2704
  table_ref_2        [in] the second (right) join operand
2705
  using_fields       [in] if the join is JOIN...USING - the join columns,
2706
  if NATURAL join, then NULL
2707
  found_using_fields [out] number of fields from the USING clause that were
2708
  found among the common fields
1 by brian
clean slate
2709
2710
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2711
  The procedure finds the common columns of two relations (either
2712
  tables or intermediate join results), and adds an equi-join condition
2713
  to the ON clause of 'table_ref_2' for each pair of matching columns.
2714
  If some of table_ref_XXX represents a base table or view, then we
2715
  create new 'Natural_join_column' instances for each column
2716
  reference and store them in the 'join_columns' of the table
2717
  reference.
1 by brian
clean slate
2718
2719
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
2720
  The procedure assumes that store_natural_using_join_columns() was
2721
  called for the previous level of NATURAL/USING joins.
1 by brian
clean slate
2722
2723
  RETURN
1046 by Brian Aker
Merge Jay.
2724
  true   error when some common column is non-unique, or out of memory
2725
  false  OK
1 by brian
clean slate
2726
*/
2727
2728
static bool
520.1.22 by Brian Aker
Second pass of thd cleanup
2729
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
482 by Brian Aker
Remove uint.
2730
                    List<String> *using_fields, uint32_t *found_using_fields)
1 by brian
clean slate
2731
{
2732
  Field_iterator_table_ref it_1, it_2;
2733
  Natural_join_column *nj_col_1, *nj_col_2;
55 by brian
Update for using real bool types.
2734
  bool result= true;
2735
  bool first_outer_loop= true;
1 by brian
clean slate
2736
  /*
2737
    Leaf table references to which new natural join columns are added
2738
    if the leaves are != NULL.
2739
  */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2740
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2741
                      ! table_ref_1->is_natural_join) ?
1046 by Brian Aker
Merge Jay.
2742
    NULL : table_ref_1;
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2743
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2744
                      ! table_ref_2->is_natural_join) ?
1046 by Brian Aker
Merge Jay.
2745
    NULL : table_ref_2;
1 by brian
clean slate
2746
2747
  *found_using_fields= 0;
2748
2749
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2750
  {
55 by brian
Update for using real bool types.
2751
    bool found= false;
1 by brian
clean slate
2752
    const char *field_name_1;
2753
    /* true if field_name_1 is a member of using_fields */
2754
    bool is_using_column_1;
2755
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2756
      return(result);
1 by brian
clean slate
2757
    field_name_1= nj_col_1->name();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2758
    is_using_column_1= using_fields &&
1 by brian
clean slate
2759
      test_if_string_in_list(field_name_1, using_fields);
2760
2761
    /*
2762
      Find a field with the same name in table_ref_2.
2763
2764
      Note that for the second loop, it_2.set() will iterate over
2765
      table_ref_2->join_columns and not generate any new elements or
2766
      lists.
2767
    */
2768
    nj_col_2= NULL;
2769
    for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
2770
    {
2771
      Natural_join_column *cur_nj_col_2;
2772
      const char *cur_field_name_2;
2773
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2774
        return(result);
1 by brian
clean slate
2775
      cur_field_name_2= cur_nj_col_2->name();
2776
2777
      /*
2778
        Compare the two columns and check for duplicate common fields.
2779
        A common field is duplicate either if it was already found in
55 by brian
Update for using real bool types.
2780
        table_ref_2 (then found == true), or if a field in table_ref_2
1 by brian
clean slate
2781
        was already matched by some previous field in table_ref_1
55 by brian
Update for using real bool types.
2782
        (then cur_nj_col_2->is_common == true).
1 by brian
clean slate
2783
        Note that it is too early to check the columns outside of the
2784
        USING list for ambiguity because they are not actually "referenced"
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2785
        here. These columns must be checked only on unqualified reference
1 by brian
clean slate
2786
        by name (e.g. in SELECT list).
2787
      */
2788
      if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
2789
      {
2790
        if (cur_nj_col_2->is_common ||
2791
            (found && (!using_fields || is_using_column_1)))
2792
        {
520.1.22 by Brian Aker
Second pass of thd cleanup
2793
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2794
          return(result);
1 by brian
clean slate
2795
        }
2796
        nj_col_2= cur_nj_col_2;
55 by brian
Update for using real bool types.
2797
        found= true;
1 by brian
clean slate
2798
      }
2799
    }
2800
    if (first_outer_loop && leaf_2)
2801
    {
2802
      /*
2803
        Make sure that the next inner loop "knows" that all columns
2804
        are materialized already.
2805
      */
55 by brian
Update for using real bool types.
2806
      leaf_2->is_join_columns_complete= true;
2807
      first_outer_loop= false;
1 by brian
clean slate
2808
    }
2809
    if (!found)
2810
      continue;                                 // No matching field
2811
2812
    /*
2813
      field_1 and field_2 have the same names. Check if they are in the USING
2814
      clause (if present), mark them as common fields, and add a new
2815
      equi-join condition to the ON clause.
2816
    */
2817
    if (nj_col_2 && (!using_fields ||is_using_column_1))
2818
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
2819
      Item *item_1=   nj_col_1->create_item(session);
2820
      Item *item_2=   nj_col_2->create_item(session);
1 by brian
clean slate
2821
      Field *field_1= nj_col_1->field();
2822
      Field *field_2= nj_col_2->field();
2823
      Item_ident *item_ident_1, *item_ident_2;
2824
      Item_func_eq *eq_cond;
2825
2826
      if (!item_1 || !item_2)
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2827
        return(result); // out of memory
1 by brian
clean slate
2828
2829
      /*
2830
        In the case of no_wrap_view_item == 0, the created items must be
2831
        of sub-classes of Item_ident.
2832
      */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2833
      assert(item_1->type() == Item::FIELD_ITEM ||
1046 by Brian Aker
Merge Jay.
2834
             item_1->type() == Item::REF_ITEM);
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2835
      assert(item_2->type() == Item::FIELD_ITEM ||
1046 by Brian Aker
Merge Jay.
2836
             item_2->type() == Item::REF_ITEM);
1 by brian
clean slate
2837
2838
      /*
2839
        We need to cast item_1,2 to Item_ident, because we need to hook name
2840
        resolution contexts specific to each item.
2841
      */
2842
      item_ident_1= (Item_ident*) item_1;
2843
      item_ident_2= (Item_ident*) item_2;
2844
      /*
2845
        Create and hook special name resolution contexts to each item in the
2846
        new join condition . We need this to both speed-up subsequent name
2847
        resolution of these items, and to enable proper name resolution of
2848
        the items during the execute phase of PS.
2849
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
2850
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2851
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2852
        return(result);
1 by brian
clean slate
2853
2854
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2855
        return(result);                               /* Out of memory. */
1 by brian
clean slate
2856
2857
      /*
2858
        Add the new equi-join condition to the ON clause. Notice that
2859
        fix_fields() is applied to all ON conditions in setup_conds()
2860
        so we don't do it here.
1046 by Brian Aker
Merge Jay.
2861
      */
1 by brian
clean slate
2862
      add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
2863
                   table_ref_1 : table_ref_2),
2864
                  eq_cond);
2865
55 by brian
Update for using real bool types.
2866
      nj_col_1->is_common= nj_col_2->is_common= true;
1 by brian
clean slate
2867
2868
      if (field_1)
2869
      {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2870
        Table *table_1= nj_col_1->table_ref->table;
1 by brian
clean slate
2871
        /* Mark field_1 used for table cache. */
1999.4.2 by Brian Aker
Encapsulate the field's position.
2872
        table_1->setReadSet(field_1->position());
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2873
        table_1->covering_keys&= field_1->part_of_key;
2874
        table_1->merge_keys|= field_1->part_of_key;
1 by brian
clean slate
2875
      }
2876
      if (field_2)
2877
      {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2878
        Table *table_2= nj_col_2->table_ref->table;
1 by brian
clean slate
2879
        /* Mark field_2 used for table cache. */
1999.4.2 by Brian Aker
Encapsulate the field's position.
2880
        table_2->setReadSet(field_2->position());
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2881
        table_2->covering_keys&= field_2->part_of_key;
2882
        table_2->merge_keys|= field_2->part_of_key;
1 by brian
clean slate
2883
      }
2884
2885
      if (using_fields != NULL)
2886
        ++(*found_using_fields);
2887
    }
2888
  }
2889
  if (leaf_1)
55 by brian
Update for using real bool types.
2890
    leaf_1->is_join_columns_complete= true;
1 by brian
clean slate
2891
2892
  /*
2893
    Everything is OK.
2894
    Notice that at this point there may be some column names in the USING
2895
    clause that are not among the common columns. This is an SQL error and
2896
    we check for this error in store_natural_using_join_columns() when
2897
    (found_using_fields < length(join_using_fields)).
2898
  */
55 by brian
Update for using real bool types.
2899
  result= false;
1 by brian
clean slate
2900
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2901
  return(result);
1 by brian
clean slate
2902
}
2903
2904
2905
2906
/*
2907
  Materialize and store the row type of NATURAL/USING join.
2908
2909
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2910
  store_natural_using_join_columns()
2911
  session                current thread
2912
  natural_using_join the table reference of the NATURAL/USING join
2913
  table_ref_1        the first (left) operand (of a NATURAL/USING join).
2914
  table_ref_2        the second (right) operand (of a NATURAL/USING join).
2915
  using_fields       if the join is JOIN...USING - the join columns,
2916
  if NATURAL join, then NULL
2917
  found_using_fields number of fields from the USING clause that were
2918
  found among the common fields
1 by brian
clean slate
2919
2920
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2921
  Iterate over the columns of both join operands and sort and store
2922
  all columns into the 'join_columns' list of natural_using_join
2923
  where the list is formed by three parts:
2924
part1: The coalesced columns of table_ref_1 and table_ref_2,
2925
sorted according to the column order of the first table.
2926
part2: The other columns of the first table, in the order in
2927
which they were defined in CREATE TABLE.
2928
part3: The other columns of the second table, in the order in
2929
which they were defined in CREATE TABLE.
2930
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
2931
2932
IMPLEMENTATION
2933
The procedure assumes that mark_common_columns() has been called
2934
for the join that is being processed.
2935
2936
RETURN
2937
true    error: Some common column is ambiguous
2938
false   OK
1 by brian
clean slate
2939
*/
2940
2941
static bool
1578.6.3 by Brian Aker
More current_session removal.
2942
store_natural_using_join_columns(Session *session,
327.2.4 by Brian Aker
Refactoring table.h
2943
                                 TableList *natural_using_join,
2944
                                 TableList *table_ref_1,
2945
                                 TableList *table_ref_2,
1 by brian
clean slate
2946
                                 List<String> *using_fields,
482 by Brian Aker
Remove uint.
2947
                                 uint32_t found_using_fields)
1 by brian
clean slate
2948
{
2949
  Field_iterator_table_ref it_1, it_2;
2950
  Natural_join_column *nj_col_1, *nj_col_2;
55 by brian
Update for using real bool types.
2951
  bool result= true;
1 by brian
clean slate
2952
  List<Natural_join_column> *non_join_columns;
2953
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2954
  assert(!natural_using_join->join_columns);
1 by brian
clean slate
2955
2956
  if (!(non_join_columns= new List<Natural_join_column>) ||
2957
      !(natural_using_join->join_columns= new List<Natural_join_column>))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2958
  {
2959
    return(result);
2960
  }
1 by brian
clean slate
2961
2962
  /* Append the columns of the first join operand. */
2963
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2964
  {
2965
    nj_col_1= it_1.get_natural_column_ref();
2966
    if (nj_col_1->is_common)
2967
    {
2968
      natural_using_join->join_columns->push_back(nj_col_1);
2969
      /* Reset the common columns for the next call to mark_common_columns. */
55 by brian
Update for using real bool types.
2970
      nj_col_1->is_common= false;
1 by brian
clean slate
2971
    }
2972
    else
2973
      non_join_columns->push_back(nj_col_1);
2974
  }
2975
2976
  /*
2977
    Check that all columns in the USING clause are among the common
2978
    columns. If this is not the case, report the first one that was
2979
    not found in an error.
2980
  */
2981
  if (using_fields && found_using_fields < using_fields->elements)
2982
  {
2983
    String *using_field_name;
2984
    List_iterator_fast<String> using_fields_it(*using_fields);
2985
    while ((using_field_name= using_fields_it++))
2986
    {
2987
      const char *using_field_name_ptr= using_field_name->c_ptr();
2988
      List_iterator_fast<Natural_join_column>
2989
        it(*(natural_using_join->join_columns));
2990
      Natural_join_column *common_field;
2991
2992
      for (;;)
2993
      {
2994
        /* If reached the end of fields, and none was found, report error. */
2995
        if (!(common_field= it++))
2996
        {
2997
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
1578.6.3 by Brian Aker
More current_session removal.
2998
                   session->where);
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
2999
          return(result);
1 by brian
clean slate
3000
        }
3001
        if (!my_strcasecmp(system_charset_info,
3002
                           common_field->name(), using_field_name_ptr))
3003
          break;                                // Found match
3004
      }
3005
    }
3006
  }
3007
3008
  /* Append the non-equi-join columns of the second join operand. */
3009
  for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
3010
  {
3011
    nj_col_2= it_2.get_natural_column_ref();
3012
    if (!nj_col_2->is_common)
3013
      non_join_columns->push_back(nj_col_2);
3014
    else
3015
    {
3016
      /* Reset the common columns for the next call to mark_common_columns. */
55 by brian
Update for using real bool types.
3017
      nj_col_2->is_common= false;
1 by brian
clean slate
3018
    }
3019
  }
3020
3021
  if (non_join_columns->elements > 0)
3022
    natural_using_join->join_columns->concat(non_join_columns);
55 by brian
Update for using real bool types.
3023
  natural_using_join->is_join_columns_complete= true;
1 by brian
clean slate
3024
55 by brian
Update for using real bool types.
3025
  result= false;
1 by brian
clean slate
3026
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3027
  return(result);
1 by brian
clean slate
3028
}
3029
3030
3031
/*
3032
  Precompute and store the row types of the top-most NATURAL/USING joins.
3033
3034
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3035
  store_top_level_join_columns()
3036
  session            current thread
3037
  table_ref      nested join or table in a FROM clause
3038
  left_neighbor  neighbor table reference to the left of table_ref at the
3039
  same level in the join tree
3040
  right_neighbor neighbor table reference to the right of table_ref at the
3041
  same level in the join tree
1 by brian
clean slate
3042
3043
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
3044
  The procedure performs a post-order traversal of a nested join tree
3045
  and materializes the row types of NATURAL/USING joins in a
3046
  bottom-up manner until it reaches the TableList elements that
3047
  represent the top-most NATURAL/USING joins. The procedure should be
3048
  applied to each element of Select_Lex::top_join_list (i.e. to each
3049
  top-level element of the FROM clause).
1 by brian
clean slate
3050
3051
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
3052
  Notice that the table references in the list nested_join->join_list
3053
  are in reverse order, thus when we iterate over it, we are moving
3054
  from the right to the left in the FROM clause.
1 by brian
clean slate
3055
3056
  RETURN
1046 by Brian Aker
Merge Jay.
3057
  true   Error
3058
  false  OK
1 by brian
clean slate
3059
*/
3060
3061
static bool
520.1.22 by Brian Aker
Second pass of thd cleanup
3062
store_top_level_join_columns(Session *session, TableList *table_ref,
327.2.4 by Brian Aker
Refactoring table.h
3063
                             TableList *left_neighbor,
3064
                             TableList *right_neighbor)
1 by brian
clean slate
3065
{
55 by brian
Update for using real bool types.
3066
  bool result= true;
1 by brian
clean slate
3067
3068
  /* Call the procedure recursively for each nested table reference. */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3069
  if (table_ref->getNestedJoin())
1 by brian
clean slate
3070
  {
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3071
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
327.2.4 by Brian Aker
Refactoring table.h
3072
    TableList *same_level_left_neighbor= nested_it++;
3073
    TableList *same_level_right_neighbor= NULL;
1 by brian
clean slate
3074
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
327.2.4 by Brian Aker
Refactoring table.h
3075
    TableList *real_left_neighbor, *real_right_neighbor;
1 by brian
clean slate
3076
3077
    while (same_level_left_neighbor)
3078
    {
327.2.4 by Brian Aker
Refactoring table.h
3079
      TableList *cur_table_ref= same_level_left_neighbor;
1 by brian
clean slate
3080
      same_level_left_neighbor= nested_it++;
3081
      /*
3082
        The order of RIGHT JOIN operands is reversed in 'join list' to
3083
        transform it into a LEFT JOIN. However, in this procedure we need
3084
        the join operands in their lexical order, so below we reverse the
3085
        join operands. Notice that this happens only in the first loop,
3086
        and not in the second one, as in the second loop
3087
        same_level_left_neighbor == NULL.
3088
        This is the correct behavior, because the second loop sets
3089
        cur_table_ref reference correctly after the join operands are
3090
        swapped in the first loop.
3091
      */
3092
      if (same_level_left_neighbor &&
3093
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3094
      {
3095
        /* This can happen only for JOIN ... ON. */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3096
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
3097
        std::swap(same_level_left_neighbor, cur_table_ref);
1 by brian
clean slate
3098
      }
3099
3100
      /*
3101
        Pick the parent's left and right neighbors if there are no immediate
3102
        neighbors at the same level.
3103
      */
3104
      real_left_neighbor=  (same_level_left_neighbor) ?
1046 by Brian Aker
Merge Jay.
3105
        same_level_left_neighbor : left_neighbor;
1 by brian
clean slate
3106
      real_right_neighbor= (same_level_right_neighbor) ?
1046 by Brian Aker
Merge Jay.
3107
        same_level_right_neighbor : right_neighbor;
1 by brian
clean slate
3108
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3109
      if (cur_table_ref->getNestedJoin() &&
520.1.22 by Brian Aker
Second pass of thd cleanup
3110
          store_top_level_join_columns(session, cur_table_ref,
1 by brian
clean slate
3111
                                       real_left_neighbor, real_right_neighbor))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3112
        return(result);
1 by brian
clean slate
3113
      same_level_right_neighbor= cur_table_ref;
3114
    }
3115
  }
3116
3117
  /*
3118
    If this is a NATURAL/USING join, materialize its result columns and
3119
    convert to a JOIN ... ON.
3120
  */
3121
  if (table_ref->is_natural_join)
3122
  {
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3123
    assert(table_ref->getNestedJoin() &&
3124
           table_ref->getNestedJoin()->join_list.elements == 2);
3125
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
1 by brian
clean slate
3126
    /*
3127
      Notice that the order of join operands depends on whether table_ref
3128
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3129
      in inverted order.
1046 by Brian Aker
Merge Jay.
3130
    */
327.2.4 by Brian Aker
Refactoring table.h
3131
    TableList *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
3132
    TableList *table_ref_1= operand_it++; /* First NATURAL join operand. */
1 by brian
clean slate
3133
    List<String> *using_fields= table_ref->join_using_fields;
482 by Brian Aker
Remove uint.
3134
    uint32_t found_using_fields;
1 by brian
clean slate
3135
3136
    /*
3137
      The two join operands were interchanged in the parser, change the order
3138
      back for 'mark_common_columns'.
3139
    */
3140
    if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
3141
      std::swap(table_ref_1, table_ref_2);
520.1.22 by Brian Aker
Second pass of thd cleanup
3142
    if (mark_common_columns(session, table_ref_1, table_ref_2,
1 by brian
clean slate
3143
                            using_fields, &found_using_fields))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3144
      return(result);
1 by brian
clean slate
3145
3146
    /*
3147
      Swap the join operands back, so that we pick the columns of the second
3148
      one as the coalesced columns. In this way the coalesced columns are the
3149
      same as of an equivalent LEFT JOIN.
3150
    */
3151
    if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
322.2.2 by Mats Kindahl
Hiding THD::proc_info field and providing a setter and getter.
3152
      std::swap(table_ref_1, table_ref_2);
520.1.22 by Brian Aker
Second pass of thd cleanup
3153
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
1 by brian
clean slate
3154
                                         table_ref_2, using_fields,
3155
                                         found_using_fields))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3156
      return(result);
1 by brian
clean slate
3157
3158
    /*
3159
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3160
      because either one of them or the other is the one with the
3161
      natural join flag because RIGHT joins are transformed into LEFT,
3162
      and the two tables may be reordered.
3163
    */
3164
    table_ref_1->natural_join= table_ref_2->natural_join= NULL;
3165
55 by brian
Update for using real bool types.
3166
    /* Add a true condition to outer joins that have no common columns. */
1 by brian
clean slate
3167
    if (table_ref_2->outer_join &&
3168
        !table_ref_1->on_expr && !table_ref_2->on_expr)
152 by Brian Aker
longlong replacement
3169
      table_ref_2->on_expr= new Item_int((int64_t) 1,1);   /* Always true. */
1 by brian
clean slate
3170
3171
    /* Change this table reference to become a leaf for name resolution. */
3172
    if (left_neighbor)
3173
    {
327.2.4 by Brian Aker
Refactoring table.h
3174
      TableList *last_leaf_on_the_left;
1 by brian
clean slate
3175
      last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
3176
      last_leaf_on_the_left->next_name_resolution_table= table_ref;
3177
    }
3178
    if (right_neighbor)
3179
    {
327.2.4 by Brian Aker
Refactoring table.h
3180
      TableList *first_leaf_on_the_right;
1 by brian
clean slate
3181
      first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
3182
      table_ref->next_name_resolution_table= first_leaf_on_the_right;
3183
    }
3184
    else
3185
      table_ref->next_name_resolution_table= NULL;
3186
  }
55 by brian
Update for using real bool types.
3187
  result= false; /* All is OK. */
1 by brian
clean slate
3188
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3189
  return(result);
1 by brian
clean slate
3190
}
3191
3192
3193
/*
3194
  Compute and store the row types of the top-most NATURAL/USING joins
3195
  in a FROM clause.
3196
3197
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3198
  setup_natural_join_row_types()
3199
  session          current thread
3200
  from_clause  list of top-level table references in a FROM clause
1 by brian
clean slate
3201
3202
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
3203
  Apply the procedure 'store_top_level_join_columns' to each of the
3204
  top-level table referencs of the FROM clause. Adjust the list of tables
3205
  for name resolution - context->first_name_resolution_table to the
3206
  top-most, lef-most NATURAL/USING join.
1 by brian
clean slate
3207
3208
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
3209
  Notice that the table references in 'from_clause' are in reverse
3210
  order, thus when we iterate over it, we are moving from the right
3211
  to the left in the FROM clause.
1 by brian
clean slate
3212
3213
  RETURN
1046 by Brian Aker
Merge Jay.
3214
  true   Error
3215
  false  OK
1 by brian
clean slate
3216
*/
520.1.22 by Brian Aker
Second pass of thd cleanup
3217
static bool setup_natural_join_row_types(Session *session,
327.2.4 by Brian Aker
Refactoring table.h
3218
                                         List<TableList> *from_clause,
1 by brian
clean slate
3219
                                         Name_resolution_context *context)
3220
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3221
  session->where= "from clause";
1 by brian
clean slate
3222
  if (from_clause->elements == 0)
55 by brian
Update for using real bool types.
3223
    return false; /* We come here in the case of UNIONs. */
1 by brian
clean slate
3224
327.2.4 by Brian Aker
Refactoring table.h
3225
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3226
  TableList *table_ref; /* Current table reference. */
1 by brian
clean slate
3227
  /* Table reference to the left of the current. */
327.2.4 by Brian Aker
Refactoring table.h
3228
  TableList *left_neighbor;
1 by brian
clean slate
3229
  /* Table reference to the right of the current. */
327.2.4 by Brian Aker
Refactoring table.h
3230
  TableList *right_neighbor= NULL;
1 by brian
clean slate
3231
3232
  /* Note that tables in the list are in reversed order */
3233
  for (left_neighbor= table_ref_it++; left_neighbor ; )
3234
  {
3235
    table_ref= left_neighbor;
3236
    left_neighbor= table_ref_it++;
520.1.22 by Brian Aker
Second pass of thd cleanup
3237
    if (store_top_level_join_columns(session, table_ref,
404 by Brian Aker
Removed dead variable
3238
                                     left_neighbor, right_neighbor))
3239
      return true;
3240
    if (left_neighbor)
1 by brian
clean slate
3241
    {
404 by Brian Aker
Removed dead variable
3242
      TableList *first_leaf_on_the_right;
3243
      first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
3244
      left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
1 by brian
clean slate
3245
    }
3246
    right_neighbor= table_ref;
3247
  }
3248
3249
  /*
3250
    Store the top-most, left-most NATURAL/USING join, so that we start
3251
    the search from that one instead of context->table_list. At this point
3252
    right_neighbor points to the left-most top-level table reference in the
3253
    FROM clause.
3254
  */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3255
  assert(right_neighbor);
1 by brian
clean slate
3256
  context->first_name_resolution_table=
3257
    right_neighbor->first_leaf_for_name_resolution();
3258
55 by brian
Update for using real bool types.
3259
  return false;
1 by brian
clean slate
3260
}
3261
3262
3263
/****************************************************************************
1046 by Brian Aker
Merge Jay.
3264
 ** Expand all '*' in given fields
3265
 ****************************************************************************/
1 by brian
clean slate
3266
1034.1.7 by Brian Aker
Remove dead bits to the end of functions.
3267
int setup_wild(Session *session, List<Item> &fields,
77.1.45 by Monty Taylor
Warning fixes.
3268
               List<Item> *sum_func_list,
482 by Brian Aker
Remove uint.
3269
               uint32_t wild_num)
1 by brian
clean slate
3270
{
3271
  if (!wild_num)
1034.1.7 by Brian Aker
Remove dead bits to the end of functions.
3272
    return 0;
1 by brian
clean slate
3273
3274
  Item *item;
3275
  List_iterator<Item> it(fields);
3276
520.1.22 by Brian Aker
Second pass of thd cleanup
3277
  session->lex->current_select->cur_pos_in_select_list= 0;
1 by brian
clean slate
3278
  while (wild_num && (item= it++))
3279
  {
3280
    if (item->type() == Item::FIELD_ITEM &&
3281
        ((Item_field*) item)->field_name &&
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
3282
        ((Item_field*) item)->field_name[0] == '*' &&
3283
        !((Item_field*) item)->field)
1 by brian
clean slate
3284
    {
482 by Brian Aker
Remove uint.
3285
      uint32_t elem= fields.elements;
1 by brian
clean slate
3286
      bool any_privileges= ((Item_field *) item)->any_privileges;
520.1.22 by Brian Aker
Second pass of thd cleanup
3287
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
1 by brian
clean slate
3288
      if (subsel &&
3289
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3290
      {
3291
        /*
3292
          It is EXISTS(SELECT * ...) and we can replace * by any constant.
3293
3294
          Item_int do not need fix_fields() because it is basic constant.
3295
        */
152 by Brian Aker
longlong replacement
3296
        it.replace(new Item_int("Not_used", (int64_t) 1,
1 by brian
clean slate
3297
                                MY_INT64_NUM_DECIMAL_DIGITS));
3298
      }
520.1.22 by Brian Aker
Second pass of thd cleanup
3299
      else if (insert_fields(session, ((Item_field*) item)->context,
1 by brian
clean slate
3300
                             ((Item_field*) item)->db_name,
3301
                             ((Item_field*) item)->table_name, &it,
3302
                             any_privileges))
3303
      {
1046.1.10 by Brian Aker
Formatting around return (style)
3304
        return -1;
1 by brian
clean slate
3305
      }
3306
      if (sum_func_list)
3307
      {
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
3308
        /*
3309
          sum_func_list is a list that has the fields list as a tail.
3310
          Because of this we have to update the element count also for this
3311
          list after expanding the '*' entry.
3312
        */
3313
        sum_func_list->elements+= fields.elements - elem;
1 by brian
clean slate
3314
      }
3315
      wild_num--;
3316
    }
3317
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
3318
      session->lex->current_select->cur_pos_in_select_list++;
1 by brian
clean slate
3319
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3320
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
3321
1046.1.10 by Brian Aker
Formatting around return (style)
3322
  return 0;
1 by brian
clean slate
3323
}
3324
3325
/****************************************************************************
1046 by Brian Aker
Merge Jay.
3326
 ** Check that all given fields exists and fill struct with current data
3327
 ****************************************************************************/
1 by brian
clean slate
3328
520.1.22 by Brian Aker
Second pass of thd cleanup
3329
bool setup_fields(Session *session, Item **ref_pointer_array,
1 by brian
clean slate
3330
                  List<Item> &fields, enum_mark_columns mark_used_columns,
3331
                  List<Item> *sum_func_list, bool allow_sum_func)
3332
{
3333
  register Item *item;
520.1.22 by Brian Aker
Second pass of thd cleanup
3334
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3335
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
1 by brian
clean slate
3336
  List_iterator<Item> it(fields);
3337
  bool save_is_item_list_lookup;
3338
520.1.22 by Brian Aker
Second pass of thd cleanup
3339
  session->mark_used_columns= mark_used_columns;
1 by brian
clean slate
3340
  if (allow_sum_func)
520.1.22 by Brian Aker
Second pass of thd cleanup
3341
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3342
  session->where= Session::DEFAULT_WHERE;
3343
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3344
  session->lex->current_select->is_item_list_lookup= 0;
1 by brian
clean slate
3345
3346
  /*
3347
    To prevent fail on forward lookup we fill it with zerows,
3348
    then if we got pointer on zero after find_item_in_list we will know
3349
    that it is forward lookup.
3350
3351
    There is other way to solve problem: fill array with pointers to list,
3352
    but it will be slower.
3353
1046 by Brian Aker
Merge Jay.
3354
TODO: remove it when (if) we made one list for allfields and
3355
ref_pointer_array
1 by brian
clean slate
3356
  */
3357
  if (ref_pointer_array)
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
3358
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
1 by brian
clean slate
3359
3360
  Item **ref= ref_pointer_array;
520.1.22 by Brian Aker
Second pass of thd cleanup
3361
  session->lex->current_select->cur_pos_in_select_list= 0;
1 by brian
clean slate
3362
  while ((item= it++))
3363
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
3364
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
1 by brian
clean slate
3365
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
3366
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3367
      session->lex->allow_sum_func= save_allow_sum_func;
3368
      session->mark_used_columns= save_mark_used_columns;
971.6.11 by Eric Day
Removed purecov messages.
3369
      return true;
1 by brian
clean slate
3370
    }
3371
    if (ref)
3372
      *(ref++)= item;
3373
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
1046 by Brian Aker
Merge Jay.
3374
        sum_func_list)
520.1.22 by Brian Aker
Second pass of thd cleanup
3375
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3376
    session->used_tables|= item->used_tables();
3377
    session->lex->current_select->cur_pos_in_select_list++;
1 by brian
clean slate
3378
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3379
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3380
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
1 by brian
clean slate
3381
520.1.22 by Brian Aker
Second pass of thd cleanup
3382
  session->lex->allow_sum_func= save_allow_sum_func;
3383
  session->mark_used_columns= save_mark_used_columns;
3384
  return(test(session->is_error()));
1 by brian
clean slate
3385
}
3386
3387
3388
/*
3389
  make list of leaves of join table tree
3390
3391
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3392
  make_leaves_list()
3393
  list    pointer to pointer on list first element
3394
  tables  table list
1 by brian
clean slate
3395
3396
  RETURN pointer on pointer to next_leaf of last element
3397
*/
3398
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
3399
static TableList **make_leaves_list(TableList **list, TableList *tables)
1 by brian
clean slate
3400
{
327.2.4 by Brian Aker
Refactoring table.h
3401
  for (TableList *table= tables; table; table= table->next_local)
1 by brian
clean slate
3402
  {
3403
    {
3404
      *list= table;
3405
      list= &table->next_leaf;
3406
    }
3407
  }
3408
  return list;
3409
}
3410
3411
/*
3412
  prepare tables
3413
3414
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3415
  setup_tables()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3416
  session		  Thread Cursor
1046 by Brian Aker
Merge Jay.
3417
  context       name resolution contest to setup table list there
3418
  from_clause   Top-level list of table references in the FROM clause
3419
  tables	  Table list (select_lex->table_list)
3420
  leaves        List of join table leaves list (select_lex->leaf_tables)
3421
  refresh       It is onle refresh for subquery
3422
  select_insert It is SELECT ... INSERT command
1 by brian
clean slate
3423
3424
  NOTE
1046 by Brian Aker
Merge Jay.
3425
  Check also that the 'used keys' and 'ignored keys' exists and set up the
3426
  table structure accordingly.
3427
  Create a list of leaf tables. For queries with NATURAL/USING JOINs,
3428
  compute the row types of the top most natural/using join table references
3429
  and link these into a list of table references for name resolution.
1 by brian
clean slate
3430
1046 by Brian Aker
Merge Jay.
3431
  This has to be called for all tables that are used by items, as otherwise
3432
  table->map is not set and all Item_field will be regarded as const items.
1 by brian
clean slate
3433
3434
  RETURN
1046 by Brian Aker
Merge Jay.
3435
  false ok;  In this case *map will includes the chosen index
3436
  true  error
1 by brian
clean slate
3437
*/
3438
520.1.22 by Brian Aker
Second pass of thd cleanup
3439
bool setup_tables(Session *session, Name_resolution_context *context,
327.2.4 by Brian Aker
Refactoring table.h
3440
                  List<TableList> *from_clause, TableList *tables,
3441
                  TableList **leaves, bool select_insert)
1 by brian
clean slate
3442
{
482 by Brian Aker
Remove uint.
3443
  uint32_t tablenr= 0;
1 by brian
clean slate
3444
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3445
  assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
1046 by Brian Aker
Merge Jay.
3446
          (context->table_list && context->first_name_resolution_table));
1 by brian
clean slate
3447
  /*
3448
    this is used for INSERT ... SELECT.
3449
    For select we setup tables except first (and its underlying tables)
3450
  */
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
3451
  TableList *first_select_table= (select_insert ?  tables->next_local: NULL);
3452
1 by brian
clean slate
3453
  if (!(*leaves))
3454
    make_leaves_list(leaves, tables);
3455
327.2.4 by Brian Aker
Refactoring table.h
3456
  TableList *table_list;
1 by brian
clean slate
3457
  for (table_list= *leaves;
3458
       table_list;
3459
       table_list= table_list->next_leaf, tablenr++)
3460
  {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3461
    Table *table= table_list->table;
1 by brian
clean slate
3462
    table->pos_in_table_list= table_list;
3463
    if (first_select_table &&
3464
        table_list->top_table() == first_select_table)
3465
    {
3466
      /* new counting for SELECT of INSERT ... SELECT command */
3467
      first_select_table= 0;
3468
      tablenr= 0;
3469
    }
934.1.1 by Brian Aker
Moved two functions in classes.
3470
    table->setup_table_map(table_list, tablenr);
1 by brian
clean slate
3471
    if (table_list->process_index_hints(table))
1046.1.10 by Brian Aker
Formatting around return (style)
3472
      return 1;
1 by brian
clean slate
3473
  }
3474
  if (tablenr > MAX_TABLES)
3475
  {
3476
    my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
1046.1.10 by Brian Aker
Formatting around return (style)
3477
    return 1;
1 by brian
clean slate
3478
  }
3479
3480
  /* Precompute and store the row types of NATURAL/USING joins. */
520.1.22 by Brian Aker
Second pass of thd cleanup
3481
  if (setup_natural_join_row_types(session, from_clause, context))
1046.1.10 by Brian Aker
Formatting around return (style)
3482
    return 1;
1 by brian
clean slate
3483
1046.1.10 by Brian Aker
Formatting around return (style)
3484
  return 0;
1 by brian
clean slate
3485
}
3486
3487
3488
/*
3489
  prepare tables and check access for the view tables
3490
3491
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3492
  setup_tables_and_check_view_access()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3493
  session		  Thread Cursor
1046 by Brian Aker
Merge Jay.
3494
  context       name resolution contest to setup table list there
3495
  from_clause   Top-level list of table references in the FROM clause
3496
  tables	  Table list (select_lex->table_list)
3497
  conds	  Condition of current SELECT (can be changed by VIEW)
3498
  leaves        List of join table leaves list (select_lex->leaf_tables)
3499
  refresh       It is onle refresh for subquery
3500
  select_insert It is SELECT ... INSERT command
3501
  want_access   what access is needed
1 by brian
clean slate
3502
3503
  NOTE
1046 by Brian Aker
Merge Jay.
3504
  a wrapper for check_tables that will also check the resulting
3505
  table leaves list for access to all the tables that belong to a view
1 by brian
clean slate
3506
3507
  RETURN
1046 by Brian Aker
Merge Jay.
3508
  false ok;  In this case *map will include the chosen index
3509
  true  error
1 by brian
clean slate
3510
*/
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3511
bool setup_tables_and_check_access(Session *session,
1 by brian
clean slate
3512
                                   Name_resolution_context *context,
327.2.4 by Brian Aker
Refactoring table.h
3513
                                   List<TableList> *from_clause,
3514
                                   TableList *tables,
3515
                                   TableList **leaves,
1 by brian
clean slate
3516
                                   bool select_insert)
3517
{
327.2.4 by Brian Aker
Refactoring table.h
3518
  TableList *leaves_tmp= NULL;
1 by brian
clean slate
3519
520.1.22 by Brian Aker
Second pass of thd cleanup
3520
  if (setup_tables(session, context, from_clause, tables,
1 by brian
clean slate
3521
                   &leaves_tmp, select_insert))
55 by brian
Update for using real bool types.
3522
    return true;
1 by brian
clean slate
3523
3524
  if (leaves)
3525
    *leaves= leaves_tmp;
3526
55 by brian
Update for using real bool types.
3527
  return false;
1 by brian
clean slate
3528
}
3529
3530
3531
/*
3532
  Drops in all fields instead of current '*' field
3533
3534
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3535
  insert_fields()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3536
  session			Thread Cursor
1046 by Brian Aker
Merge Jay.
3537
  context             Context for name resolution
3538
  db_name		Database name in case of 'database_name.table_name.*'
3539
  table_name		Table name in case of 'table_name.*'
3540
  it			Pointer to '*'
3541
  any_privileges	0 If we should ensure that we have SELECT privileges
3542
  for all columns
3543
  1 If any privilege is ok
1 by brian
clean slate
3544
  RETURN
1046 by Brian Aker
Merge Jay.
3545
  0	ok     'it' is updated to point at last inserted
3546
  1	error.  Error message is generated but not sent to client
1 by brian
clean slate
3547
*/
3548
3549
bool
520.1.22 by Brian Aker
Second pass of thd cleanup
3550
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
77.1.45 by Monty Taylor
Warning fixes.
3551
              const char *table_name, List_iterator<Item> *it,
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
3552
              bool )
1 by brian
clean slate
3553
{
3554
  Field_iterator_table_ref field_iterator;
3555
  bool found;
3556
  char name_buff[NAME_LEN+1];
3557
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
3558
  if (db_name)
1 by brian
clean slate
3559
  {
3560
    /*
3561
      convert database to lower case for comparison
3562
      We can't do this in Item_field as this would change the
3563
      'name' of the item which may be used in the select list
3564
    */
629.5.3 by Toru Maesaka
Third pass of replacing MySQL's strmake() with libc calls
3565
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
1 by brian
clean slate
3566
    my_casedn_str(files_charset_info, name_buff);
3567
    db_name= name_buff;
3568
  }
3569
55 by brian
Update for using real bool types.
3570
  found= false;
1 by brian
clean slate
3571
3572
  /*
3573
    If table names are qualified, then loop over all tables used in the query,
3574
    else treat natural joins as leaves and do not iterate over their underlying
3575
    tables.
3576
  */
327.2.4 by Brian Aker
Refactoring table.h
3577
  for (TableList *tables= (table_name ? context->table_list :
1046 by Brian Aker
Merge Jay.
3578
                           context->first_name_resolution_table);
1 by brian
clean slate
3579
       tables;
3580
       tables= (table_name ? tables->next_local :
3581
                tables->next_name_resolution_table)
1046 by Brian Aker
Merge Jay.
3582
      )
1 by brian
clean slate
3583
  {
3584
    Field *field;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3585
    Table *table= tables->table;
1 by brian
clean slate
3586
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3587
    assert(tables->is_leaf_for_name_resolution());
1 by brian
clean slate
3588
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3589
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
1874.1.1 by Brian Aker
Encapsulate schema_name it table_list.
3590
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
1 by brian
clean slate
3591
      continue;
3592
3593
    /*
3594
      Update the tables used in the query based on the referenced fields. For
3595
      views and natural joins this update is performed inside the loop below.
3596
    */
3597
    if (table)
520.1.22 by Brian Aker
Second pass of thd cleanup
3598
      session->used_tables|= table->map;
1 by brian
clean slate
3599
3600
    /*
3601
      Initialize a generic field iterator for the current table reference.
3602
      Notice that it is guaranteed that this iterator will iterate over the
3603
      fields of a single table reference, because 'tables' is a leaf (for
3604
      name resolution purposes).
3605
    */
3606
    field_iterator.set(tables);
3607
3608
    for (; !field_iterator.end_of_fields(); field_iterator.next())
3609
    {
3610
      Item *item;
3611
520.1.22 by Brian Aker
Second pass of thd cleanup
3612
      if (!(item= field_iterator.create_item(session)))
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
3613
        return true;
1 by brian
clean slate
3614
3615
      if (!found)
3616
      {
55 by brian
Update for using real bool types.
3617
        found= true;
1 by brian
clean slate
3618
        it->replace(item); /* Replace '*' with the first found item. */
3619
      }
3620
      else
3621
        it->after(item);   /* Add 'item' to the SELECT list. */
3622
3623
      if ((field= field_iterator.field()))
3624
      {
3625
        /* Mark fields as used to allow storage engine to optimze access */
1999.4.2 by Brian Aker
Encapsulate the field's position.
3626
        field->getTable()->setReadSet(field->position());
1 by brian
clean slate
3627
        if (table)
3628
        {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3629
          table->covering_keys&= field->part_of_key;
3630
          table->merge_keys|= field->part_of_key;
1 by brian
clean slate
3631
        }
3632
        if (tables->is_natural_join)
3633
        {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3634
          Table *field_table;
1 by brian
clean slate
3635
          /*
3636
            In this case we are sure that the column ref will not be created
3637
            because it was already created and stored with the natural join.
3638
          */
3639
          Natural_join_column *nj_col;
3640
          if (!(nj_col= field_iterator.get_natural_column_ref()))
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
3641
            return true;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3642
          assert(nj_col->table_field);
1 by brian
clean slate
3643
          field_table= nj_col->table_ref->table;
3644
          if (field_table)
3645
          {
520.1.22 by Brian Aker
Second pass of thd cleanup
3646
            session->used_tables|= field_table->map;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3647
            field_table->covering_keys&= field->part_of_key;
3648
            field_table->merge_keys|= field->part_of_key;
1 by brian
clean slate
3649
            field_table->used_fields++;
3650
          }
3651
        }
3652
      }
3653
      else
2041.3.15 by Brian Aker
Cleanup error usage around identifier usage.
3654
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
3655
        session->used_tables|= item->used_tables();
2041.3.15 by Brian Aker
Cleanup error usage around identifier usage.
3656
      }
3657
520.1.22 by Brian Aker
Second pass of thd cleanup
3658
      session->lex->current_select->cur_pos_in_select_list++;
1 by brian
clean slate
3659
    }
3660
    /*
3661
      In case of stored tables, all fields are considered as used,
3662
      while in the case of views, the fields considered as used are the
3663
      ones marked in setup_tables during fix_fields of view columns.
3664
      For NATURAL joins, used_tables is updated in the IF above.
3665
    */
3666
    if (table)
1578.2.10 by Brian Aker
keys and fields partial encapsulation.
3667
      table->used_fields= table->getShare()->sizeFields();
1 by brian
clean slate
3668
  }
3669
  if (found)
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
3670
    return false;
1 by brian
clean slate
3671
3672
  /*
1273.19.1 by Brian Aker
Update for show fields.
3673
    @TODO in the case when we skipped all columns because there was a
3674
    qualified '*', and all columns were coalesced, we have to give a more
3675
    meaningful message than ER_BAD_TABLE_ERROR.
1 by brian
clean slate
3676
  */
2041.3.15 by Brian Aker
Cleanup error usage around identifier usage.
3677
  if (not table_name)
3678
  {
1 by brian
clean slate
3679
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
2041.3.15 by Brian Aker
Cleanup error usage around identifier usage.
3680
  }
1 by brian
clean slate
3681
  else
2041.3.15 by Brian Aker
Cleanup error usage around identifier usage.
3682
  {
1 by brian
clean slate
3683
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
2041.3.15 by Brian Aker
Cleanup error usage around identifier usage.
3684
  }
1 by brian
clean slate
3685
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
3686
  return true;
1 by brian
clean slate
3687
}
3688
3689
3690
/*
3691
  Fix all conditions and outer join expressions.
3692
3693
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3694
  setup_conds()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3695
  session     thread Cursor
1046 by Brian Aker
Merge Jay.
3696
  tables  list of tables for name resolving (select_lex->table_list)
3697
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
3698
  conds   WHERE clause
1 by brian
clean slate
3699
3700
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
3701
  TODO
1 by brian
clean slate
3702
3703
  RETURN
1046 by Brian Aker
Merge Jay.
3704
  true  if some error occured (e.g. out of memory)
3705
  false if all is OK
1 by brian
clean slate
3706
*/
3707
1109.1.5 by Brian Aker
More extraction from sql_base
3708
int Session::setup_conds(TableList *leaves, COND **conds)
1 by brian
clean slate
3709
{
1109.1.5 by Brian Aker
More extraction from sql_base
3710
  Session *session= this;
846 by Brian Aker
Removing on typedeffed class.
3711
  Select_Lex *select_lex= session->lex->current_select;
327.2.4 by Brian Aker
Refactoring table.h
3712
  TableList *table= NULL;	// For HP compilers
520.1.22 by Brian Aker
Second pass of thd cleanup
3713
  void *save_session_marker= session->session_marker;
1 by brian
clean slate
3714
  /*
846 by Brian Aker
Removing on typedeffed class.
3715
    it_is_update set to true when tables of primary Select_Lex (Select_Lex
1 by brian
clean slate
3716
    which belong to LEX, i.e. most up SELECT) will be updated by
3717
    INSERT/UPDATE/LOAD
1046.1.10 by Brian Aker
Formatting around return (style)
3718
    NOTE-> using this condition helps to prevent call of prepare_check_option()
3719
    from subquery of VIEW, because tables of subquery belongs to VIEW
3720
    (see condition before prepare_check_option() call)
1 by brian
clean slate
3721
  */
3722
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
3723
  select_lex->is_item_list_lookup= 0;
3724
520.1.22 by Brian Aker
Second pass of thd cleanup
3725
  session->mark_used_columns= MARK_COLUMNS_READ;
1 by brian
clean slate
3726
  select_lex->cond_count= 0;
3727
  select_lex->between_count= 0;
3728
  select_lex->max_equal_elems= 0;
3729
520.1.22 by Brian Aker
Second pass of thd cleanup
3730
  session->session_marker= (void*)1;
1 by brian
clean slate
3731
  if (*conds)
3732
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
3733
    session->where="where clause";
3734
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
1046 by Brian Aker
Merge Jay.
3735
        (*conds)->check_cols(1))
1 by brian
clean slate
3736
      goto err_no_arena;
3737
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3738
  session->session_marker= save_session_marker;
1 by brian
clean slate
3739
3740
  /*
3741
    Apply fix_fields() to all ON clauses at all levels of nesting,
3742
    including the ones inside view definitions.
3743
  */
3744
  for (table= leaves; table; table= table->next_leaf)
3745
  {
327.2.4 by Brian Aker
Refactoring table.h
3746
    TableList *embedded; /* The table at the current level of nesting. */
3747
    TableList *embedding= table; /* The parent nested table reference. */
1 by brian
clean slate
3748
    do
3749
    {
3750
      embedded= embedding;
3751
      if (embedded->on_expr)
3752
      {
3753
        /* Make a join an a expression */
520.1.22 by Brian Aker
Second pass of thd cleanup
3754
        session->session_marker= (void*)embedded;
3755
        session->where="on clause";
3756
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
3757
            embedded->on_expr->check_cols(1))
3758
          goto err_no_arena;
1 by brian
clean slate
3759
        select_lex->cond_count++;
3760
      }
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3761
      embedding= embedded->getEmbedding();
1 by brian
clean slate
3762
    }
3763
    while (embedding &&
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3764
           embedding->getNestedJoin()->join_list.head() == embedded);
1 by brian
clean slate
3765
3766
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3767
  session->session_marker= save_session_marker;
1 by brian
clean slate
3768
520.1.22 by Brian Aker
Second pass of thd cleanup
3769
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3770
  return(test(session->is_error()));
1 by brian
clean slate
3771
3772
err_no_arena:
3773
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
1046.1.10 by Brian Aker
Formatting around return (style)
3774
3775
  return 1;
1 by brian
clean slate
3776
}
3777
3778
3779
/******************************************************************************
1046 by Brian Aker
Merge Jay.
3780
 ** Fill a record with data (for INSERT or UPDATE)
3781
 ** Returns : 1 if some field has wrong type
3782
 ******************************************************************************/
1 by brian
clean slate
3783
3784
3785
/*
3786
  Fill fields with given items.
3787
3788
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3789
  fill_record()
3790
  fields        Item_fields list to be filled
3791
  values        values to fill with
3792
  ignore_errors true if we should ignore errors
1 by brian
clean slate
3793
3794
  NOTE
1046 by Brian Aker
Merge Jay.
3795
  fill_record() may set table->auto_increment_field_not_null and a
3796
  caller should make sure that it is reset after their last call to this
3797
  function.
1 by brian
clean slate
3798
3799
  RETURN
1046 by Brian Aker
Merge Jay.
3800
  false   OK
3801
  true    error occured
1 by brian
clean slate
3802
*/
3803
3804
bool
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3805
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
1 by brian
clean slate
3806
{
3807
  List_iterator_fast<Item> f(fields),v(values);
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3808
  Item *value;
1 by brian
clean slate
3809
  Item_field *field;
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3810
  Table *table;
1 by brian
clean slate
3811
3812
  /*
3813
    Reset the table->auto_increment_field_not_null as it is valid for
3814
    only one row.
3815
  */
3816
  if (fields.elements)
3817
  {
3818
    /*
3819
      On INSERT or UPDATE fields are checked to be from the same table,
3820
      thus we safely can take table from the first field.
3821
    */
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3822
    field= static_cast<Item_field *>(f++);
1660.1.3 by Brian Aker
Encapsulate Table in field
3823
    table= field->field->getTable();
55 by brian
Update for using real bool types.
3824
    table->auto_increment_field_not_null= false;
1 by brian
clean slate
3825
    f.rewind();
3826
  }
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3827
3828
  while ((field= static_cast<Item_field *>(f++)))
1 by brian
clean slate
3829
  {
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3830
    value= v++;
3831
1 by brian
clean slate
3832
    Field *rfield= field->field;
1660.1.3 by Brian Aker
Encapsulate Table in field
3833
    table= rfield->getTable();
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3834
1 by brian
clean slate
3835
    if (rfield == table->next_number_field)
55 by brian
Update for using real bool types.
3836
      table->auto_increment_field_not_null= true;
1 by brian
clean slate
3837
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3838
    {
3839
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3840
      if (table)
3841
        table->auto_increment_field_not_null= false;
3842
3843
      return true;
1 by brian
clean slate
3844
    }
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3845
  }
3846
3847
  return session->is_error();
1 by brian
clean slate
3848
}
3849
3850
3851
/*
3852
  Fill field buffer with values from Field list
3853
3854
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3855
  fill_record()
3856
  ptr           pointer on pointer to record
3857
  values        list of fields
3858
  ignore_errors true if we should ignore errors
1 by brian
clean slate
3859
3860
  NOTE
1046 by Brian Aker
Merge Jay.
3861
  fill_record() may set table->auto_increment_field_not_null and a
3862
  caller should make sure that it is reset after their last call to this
3863
  function.
1 by brian
clean slate
3864
3865
  RETURN
1046 by Brian Aker
Merge Jay.
3866
  false   OK
3867
  true    error occured
1 by brian
clean slate
3868
*/
3869
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3870
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
1 by brian
clean slate
3871
{
3872
  List_iterator_fast<Item> v(values);
3873
  Item *value;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3874
  Table *table= 0;
1 by brian
clean slate
3875
  Field *field;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3876
1 by brian
clean slate
3877
  /*
3878
    Reset the table->auto_increment_field_not_null as it is valid for
3879
    only one row.
3880
  */
3881
  if (*ptr)
3882
  {
3883
    /*
3884
      On INSERT or UPDATE fields are checked to be from the same table,
3885
      thus we safely can take table from the first field.
3886
    */
1660.1.3 by Brian Aker
Encapsulate Table in field
3887
    table= (*ptr)->getTable();
55 by brian
Update for using real bool types.
3888
    table->auto_increment_field_not_null= false;
1 by brian
clean slate
3889
  }
2069.2.1 by Brian Aker
Fix issue with now() not storing fractional seconds in timestamp(6)
3890
520.1.22 by Brian Aker
Second pass of thd cleanup
3891
  while ((field = *ptr++) && ! session->is_error())
1 by brian
clean slate
3892
  {
3893
    value=v++;
1660.1.3 by Brian Aker
Encapsulate Table in field
3894
    table= field->getTable();
2069.2.1 by Brian Aker
Fix issue with now() not storing fractional seconds in timestamp(6)
3895
1 by brian
clean slate
3896
    if (field == table->next_number_field)
55 by brian
Update for using real bool types.
3897
      table->auto_increment_field_not_null= true;
2069.2.1 by Brian Aker
Fix issue with now() not storing fractional seconds in timestamp(6)
3898
1 by brian
clean slate
3899
    if (value->save_in_field(field, 0) < 0)
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3900
    {
3901
      if (table)
3902
        table->auto_increment_field_not_null= false;
3903
3904
      return true;
3905
    }
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3906
  }
3907
520.1.22 by Brian Aker
Second pass of thd cleanup
3908
  return(session->is_error());
1 by brian
clean slate
3909
}
3910
3911
1130.1.12 by Monty Taylor
Moved service stuff into plugin/
3912
bool drizzle_rm_tmp_tables()
1 by brian
clean slate
3913
{
3914
1556.1.1 by Brian Aker
Updates for moving temporary directory.
3915
  assert(drizzle_tmpdir.size());
2039.6.3 by Brian Aker
Update for session to have a catalog object.
3916
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3917
2039.6.3 by Brian Aker
Update for session to have a catalog object.
3918
  if (not session)
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3919
    return true;
2039.6.3 by Brian Aker
Update for session to have a catalog object.
3920
  session->thread_stack= (char*) session.get();
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
3921
  session->storeGlobals();
1 by brian
clean slate
3922
1556.1.1 by Brian Aker
Updates for moving temporary directory.
3923
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3924
3925
  return false;
1 by brian
clean slate
3926
}
3927
3928
3929
3930
/*****************************************************************************
1046 by Brian Aker
Merge Jay.
3931
  unireg support functions
3932
 *****************************************************************************/
1 by brian
clean slate
3933
1877.2.8 by Brian Aker
Additional encapsulation
3934
1 by brian
clean slate
3935
3936
3937
/**
3938
  @} (end of group Data_Dictionary)
3939
*/
575.4.7 by Monty Taylor
More header cleanup.
3940
3941
void kill_drizzle(void)
3942
{
3943
  pthread_kill(signal_thread, SIGTERM);
929.1.6 by Brian Aker
Pushing thread attribute for threads down to engine.
3944
  shutdown_in_progress= 1;			// Safety if kill didn't work
575.4.7 by Monty Taylor
More header cleanup.
3945
}
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
3946
3947
} /* namespace drizzled */