~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"
1130.3.1 by Monty Taylor
Moved multi_malloc into drizzled since it's not going away any time soon. Also,
48
#include <drizzled/field/timestamp.h>
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
1574 by Brian Aker
Rollup patch for hiding tableshare.
121
  TableShare::release(table->getMutableShare());
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.
1887.2.5 by Brian Aker
OSX found a reference to a function that was no longer declared.
672
    (See: table::Cache::singleton().removeTable(), mysql_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);
1954.2.4 by Brian Aker
Remove quick_rm_table().
733
    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
1 by brian
clean slate
1279
  bool error=0, not_used;
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;
1318
  if (tables != tables_ptr)			// Should we get back old locks
1319
  {
1711.6.1 by Brian Aker
Style on structure cleanup
1320
    DrizzleLock *local_lock;
1 by brian
clean slate
1321
    /*
1322
      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
1323
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
1 by brian
clean slate
1324
      already locked.
1325
    */
1046.1.14 by Brian Aker
More redactoring of all lock issue code that is session bound, to be a
1326
    some_tables_deleted= false;
1327
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1328
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1910.2.3 by Brian Aker
Second pass on move code to global lock encapsulation.
1329
                                       flags, &not_used)))
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
/* Wait until all used tables are refreshed */
1441
520.1.22 by Brian Aker
Second pass of thd cleanup
1442
bool wait_for_tables(Session *session)
1 by brian
clean slate
1443
{
1444
  bool result;
1445
520.1.22 by Brian Aker
Second pass of thd cleanup
1446
  session->set_proc_info("Waiting for tables");
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
1447
  {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1448
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1910.2.8 by Brian Aker
Enapsulate Kill.
1449
    while (not session->getKilled())
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
1450
    {
1451
      session->some_tables_deleted= false;
1452
      session->close_old_data_files(false, dropping_tables != 0);
1877.2.7 by Brian Aker
Encapsulate more of the table cache.
1453
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
      {
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
1455
        break;
1877.2.7 by Brian Aker
Encapsulate more of the table cache.
1456
      }
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
1457
      COND_refresh.wait(lock);
1458
    }
1910.2.8 by Brian Aker
Enapsulate Kill.
1459
    if (session->getKilled())
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
1460
      result= true;					// aborted
1461
    else
1462
    {
1463
      /* Now we can open all tables without any interference */
1464
      session->set_proc_info("Reopen tables");
1465
      session->version= refresh_version;
1466
      result= session->reopen_tables(false, false);
1467
    }
1468
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1469
  session->set_proc_info(0);
1046.1.12 by Brian Aker
Simplify close_cached_tables() (it now always locks).
1470
1471
  return result;
1 by brian
clean slate
1472
}
1473
1474
1475
/*
1476
  drop tables from locked list
1477
1478
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1479
  drop_locked_tables()
1480
  session			Thread thandler
1481
  db			Database
1482
  table_name		Table name
1 by brian
clean slate
1483
1484
  INFORMATION
1046 by Brian Aker
Merge Jay.
1485
  This is only called on drop tables
1 by brian
clean slate
1486
1046 by Brian Aker
Merge Jay.
1487
  The Table object for the dropped table is unlocked but still kept around
1488
  as a name lock, which means that the table will be available for other
1489
  thread as soon as we call unlock_table_names().
1490
  If there is multiple copies of the table locked, all copies except
1491
  the first, which acts as a name lock, is removed.
1 by brian
clean slate
1492
1493
  RETURN
1046 by Brian Aker
Merge Jay.
1494
#    If table existed, return table
1495
0	 Table was not locked
1 by brian
clean slate
1496
*/
1497
1498
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1499
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1 by brian
clean slate
1500
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1501
  Table *table,*next,**prev, *found= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
1502
  prev= &session->open_tables;
1 by brian
clean slate
1503
1504
  /*
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1505
    Note that we need to hold table::Cache::singleton().mutex() while changing the
1 by brian
clean slate
1506
    open_tables list. Another thread may work on it.
1887.2.5 by Brian Aker
OSX found a reference to a function that was no longer declared.
1507
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
1 by brian
clean slate
1508
    Closing a MERGE child before the parent would be fatal if the
1509
    other thread tries to abort the MERGE lock in between.
1510
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1511
  for (table= session->open_tables; table ; table=next)
1 by brian
clean slate
1512
  {
1608 by Brian Aker
This encapsulates prev/next.
1513
    next=table->getNext();
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1514
    if (table->getShare()->getCacheKey() == identifier.getKey())
1 by brian
clean slate
1515
    {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1516
      session->removeLock(table);
1 by brian
clean slate
1517
1518
      if (!found)
1519
      {
1520
        found= table;
1521
        /* Close engine table, but keep object around as a name lock */
1522
        if (table->db_stat)
1523
        {
1524
          table->db_stat= 0;
1208.3.2 by brian
Update for Cursor renaming.
1525
          table->cursor->close();
1 by brian
clean slate
1526
        }
1527
      }
1528
      else
1529
      {
1530
        /* 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
1531
        table::remove_table(static_cast<table::Concurrent *>(table));
1 by brian
clean slate
1532
      }
1533
    }
1534
    else
1535
    {
1536
      *prev=table;
1608 by Brian Aker
This encapsulates prev/next.
1537
      prev= table->getNextPtr();
1 by brian
clean slate
1538
    }
1539
  }
1540
  *prev=0;
1541
  if (found)
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
1542
    locking::broadcast_refresh();
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1543
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1544
  return(found);
1 by brian
clean slate
1545
}
1546
1547
1548
/*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1549
  If we have the table open, which only happens when a LOCK Table has been
1 by brian
clean slate
1550
  done on the table, change the lock type to a lock that will abort all
1551
  other threads trying to get the lock.
1552
*/
1553
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1554
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1 by brian
clean slate
1555
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1556
  Table *table;
1608 by Brian Aker
This encapsulates prev/next.
1557
  for (table= session->open_tables; table ; table= table->getNext())
1 by brian
clean slate
1558
  {
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
1559
    if (table->getShare()->getCacheKey() == identifier.getKey())
1 by brian
clean slate
1560
    {
1561
      /* If MERGE child, forward lock handling to parent. */
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1562
      session->abortLock(table);
1 by brian
clean slate
1563
      break;
1564
    }
1565
  }
1566
}
1567
1568
1569
/*
1570
  Open all tables in list
1571
1572
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1573
  open_tables()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1574
  session - thread Cursor
1046 by Brian Aker
Merge Jay.
1575
  start - list of tables in/out
1576
  counter - number of opened tables will be return using this parameter
1577
  flags   - bitmap of flags to modify how the tables will be open:
1578
  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
1579
  done a flush or namelock on it.
1 by brian
clean slate
1580
1581
  NOTE
1046 by Brian Aker
Merge Jay.
1582
  Unless we are already in prelocked mode, this function will also precache
1583
  all SP/SFs explicitly or implicitly (via views and triggers) used by the
1584
  query and add tables needed for their execution to table list. If resulting
1585
  tables list will be non empty it will mark query as requiring precaching.
1586
  Prelocked mode will be enabled for such query during lock_tables() call.
1 by brian
clean slate
1587
1046 by Brian Aker
Merge Jay.
1588
  If query for which we are opening tables is already marked as requiring
1589
  prelocking it won't do such precaching and will simply reuse table list
1590
  which is already built.
1 by brian
clean slate
1591
1592
  RETURN
1046 by Brian Aker
Merge Jay.
1593
  0  - OK
1594
  -1 - error
1 by brian
clean slate
1595
*/
1596
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1597
int Session::open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags)
1 by brian
clean slate
1598
{
327.2.4 by Brian Aker
Refactoring table.h
1599
  TableList *tables= NULL;
1 by brian
clean slate
1600
  bool refresh;
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1601
  int result= 0;
1 by brian
clean slate
1602
  /* Also used for indicating that prelocking is need */
1603
  bool safe_to_ignore_table;
1604
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1605
  current_tablenr= 0;
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1606
restart:
1 by brian
clean slate
1607
  *counter= 0;
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1608
  set_proc_info("Opening tables");
1 by brian
clean slate
1609
1610
  /*
1611
    For every table in the list of tables to open, try to find or open
1612
    a table.
1613
  */
1614
  for (tables= *start; tables ;tables= tables->next_global)
1615
  {
55 by brian
Update for using real bool types.
1616
    safe_to_ignore_table= false;
1 by brian
clean slate
1617
1618
    /*
1619
      Ignore placeholders for derived tables. After derived tables
1620
      processing, link to created temporary table will be put here.
1621
      If this is derived table for view then we still want to process
1622
      routines used by this view.
1046 by Brian Aker
Merge Jay.
1623
    */
1 by brian
clean slate
1624
    if (tables->derived)
1625
    {
1626
      continue;
1627
    }
1628
    (*counter)++;
1629
1630
    /*
1317.2.5 by Monty Taylor
Prevent the user from seeing or attempting to access tables that he is not
1631
     * Is the user authorized to see this table? Do this before we check
1632
     * to see if it exists so that an unauthorized user cannot phish for
1633
     * table/schema information via error messages
1634
     */
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1635
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1317.2.5 by Monty Taylor
Prevent the user from seeing or attempting to access tables that he is not
1636
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1471.2.4 by Monty Taylor
Fixed a stoopid.
1637
                                                the_table))
1317.2.5 by Monty Taylor
Prevent the user from seeing or attempting to access tables that he is not
1638
    {
1639
      result= -1;                               // Fatal error
1640
      break;
1641
    }
1642
1643
1644
    /*
1 by brian
clean slate
1645
      Not a placeholder: must be a base table or a view, and the table is
1646
      not opened yet. Try to open the table.
1647
    */
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
1648
    if (tables->table == NULL)
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1649
      tables->table= openTable(tables, &refresh, flags);
1 by brian
clean slate
1650
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
1651
    if (tables->table == NULL)
1 by brian
clean slate
1652
    {
1653
      if (refresh)				// Refresh in progress
1654
      {
1655
        /*
1656
          We have met name-locked or old version of table. Now we have
1657
          to close all tables which are not up to date. We also have to
1658
          throw away set of prelocked tables (and thus close tables from
1659
          this set that were open by now) since it possible that one of
1660
          tables which determined its content was changed.
1661
1662
          Instead of implementing complex/non-robust logic mentioned
1663
          above we simply close and then reopen all tables.
1664
1665
          In order to prepare for recalculation of set of prelocked tables
1666
          we pretend that we have finished calculation which we were doing
1667
          currently.
1668
        */
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1669
        close_tables_for_reopen(start);
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1670
        goto restart;
1 by brian
clean slate
1671
      }
1672
1673
      if (safe_to_ignore_table)
1674
        continue;
1675
1676
      result= -1;				// Fatal error
1677
      break;
1678
    }
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1679
    if (tables->lock_type != TL_UNLOCK)
1 by brian
clean slate
1680
    {
1681
      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
1682
        tables->table->reginfo.lock_type= update_lock_default;
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
1683
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
1 by brian
clean slate
1684
        tables->table->reginfo.lock_type= tables->lock_type;
1685
    }
1686
  }
1687
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1688
  set_proc_info(0);
1 by brian
clean slate
1689
1690
  if (result && tables)
1691
  {
1692
    /*
1693
      Some functions determine success as (tables->table != NULL).
520.1.22 by Brian Aker
Second pass of thd cleanup
1694
      tables->table is in session->open_tables.
1 by brian
clean slate
1695
    */
1696
    tables->table= NULL;
1697
  }
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1698
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1699
  return(result);
1 by brian
clean slate
1700
}
1701
1702
1703
/*
1704
  Open and lock one table
1705
1706
  SYNOPSIS
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
1707
  openTableLock()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1708
  session			Thread Cursor
1046 by Brian Aker
Merge Jay.
1709
  table_list		Table to open is first table in this list
1710
  lock_type		Lock to use for open
1711
  lock_flags          Flags passed to mysql_lock_table
1 by brian
clean slate
1712
1713
  NOTE
1046 by Brian Aker
Merge Jay.
1714
  This function don't do anything like SP/SF/views/triggers analysis done
1715
  in open_tables(). It is intended for opening of only one concrete table.
1716
  And used only in special contexts.
1 by brian
clean slate
1717
1718
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
1719
  table		Opened table
1720
  0			Error
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1721
1046 by Brian Aker
Merge Jay.
1722
  If ok, the following are also set:
1723
  table_list->lock_type 	lock_type
1724
  table_list->table		table
1 by brian
clean slate
1725
*/
1726
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1727
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
1 by brian
clean slate
1728
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1729
  Table *table;
1 by brian
clean slate
1730
  bool refresh;
1731
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1732
  set_proc_info("Opening table");
1733
  current_tablenr= 0;
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1734
  while (!(table= openTable(table_list, &refresh)) &&
1 by brian
clean slate
1735
         refresh)
1736
    ;
1737
1738
  if (table)
1739
  {
1740
    table_list->lock_type= lock_type;
1741
    table_list->table=	   table;
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1742
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1743
    assert(lock == 0);	// You must lock everything at once
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1744
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1745
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
1746
        table= 0;
1 by brian
clean slate
1747
  }
1748
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1749
  set_proc_info(0);
1750
1751
  return table;
1 by brian
clean slate
1752
}
1753
1754
/*
1755
  Lock all tables in list
1756
1757
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1758
  lock_tables()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1759
  session			Thread Cursor
1046 by Brian Aker
Merge Jay.
1760
  tables		Tables to lock
1761
  count		Number of opened tables
1762
  need_reopen         Out parameter which if true indicates that some
1763
  tables were dropped or altered during this call
1764
  and therefore invoker should reopen tables and
1765
  try to lock them once again (in this case
1766
  lock_tables() will also return error).
1 by brian
clean slate
1767
1768
  NOTES
1046 by Brian Aker
Merge Jay.
1769
  You can't call lock_tables twice, as this would break the dead-lock-free
1770
  handling thr_lock gives us.  You most always get all needed locks at
1771
  once.
1 by brian
clean slate
1772
1046 by Brian Aker
Merge Jay.
1773
  If query for which we are calling this function marked as requring
1774
  prelocking, this function will do implicit LOCK TABLES and change
1775
  session::prelocked_mode accordingly.
1 by brian
clean slate
1776
1777
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
1778
  0	ok
1779
  -1	Error
1 by brian
clean slate
1780
*/
1781
1109.1.5 by Brian Aker
More extraction from sql_base
1782
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
1 by brian
clean slate
1783
{
327.2.4 by Brian Aker
Refactoring table.h
1784
  TableList *table;
1109.1.5 by Brian Aker
More extraction from sql_base
1785
  Session *session= this;
1 by brian
clean slate
1786
1787
  /*
1788
    We can't meet statement requiring prelocking if we already
1789
    in prelocked mode.
1790
  */
55 by brian
Update for using real bool types.
1791
  *need_reopen= false;
1 by brian
clean slate
1792
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
1793
  if (tables == NULL)
600 by Brian Aker
Removing more options around changing replication
1794
    return 0;
1 by brian
clean slate
1795
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1796
  assert(session->lock == 0);	// You must lock everything at once
1797
  Table **start,**ptr;
1798
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1799
1800
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1801
    return -1;
1802
  for (table= tables; table; table= table->next_global)
1 by brian
clean slate
1803
  {
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1804
    if (!table->placeholder())
1805
      *(ptr++)= table->table;
1 by brian
clean slate
1806
  }
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1807
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1808
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
1 by brian
clean slate
1809
  {
1054.1.8 by Brian Aker
Remove lock_tables list from session.
1810
    return -1;
1 by brian
clean slate
1811
  }
1812
600 by Brian Aker
Removing more options around changing replication
1813
  return 0;
1 by brian
clean slate
1814
}
1815
1816
1817
/*
1818
  Open a single table without table caching and don't set it in open_list
1819
1820
  SYNPOSIS
1046 by Brian Aker
Merge Jay.
1821
  open_temporary_table()
1822
  session		  Thread object
1823
  path	  Path (without .frm)
1824
  db		  database
1825
  table_name	  Table name
1826
  link_in_list  1 if table should be linked into session->temporary_tables
1827
1828
NOTES:
1829
Used by alter_table to open a temporary table and when creating
1830
a temporary table with CREATE TEMPORARY ...
1831
1832
RETURN
1833
0  Error
1834
#  Table object
1 by brian
clean slate
1835
*/
1836
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
1837
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)
1838
                                               bool link_in_list)
1 by brian
clean slate
1839
{
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
1840
  assert(identifier.isTmp());
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1841
1842
1843
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1844
                                                        identifier,
1954.2.3 by Brian Aker
Update tableidentifier so that it is const in many callers.
1845
                                                        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
1846
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1669.2.4 by Brian Aker
Fix temp tables to use new over malloc.
1847
  if (not new_tmp_table)
684 by Brian Aker
Mass cleanup for casting.
1848
    return NULL;
1 by brian
clean slate
1849
1039.1.10 by Brian Aker
Minor formating, change of one name to make grep easier :)
1850
  /*
1851
    First open the share, and then open the table from the share we just opened.
1852
  */
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
1853
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
      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
1855
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1856
                                                                          HA_GET_INDEX),
1857
                                                              ha_open_options,
1858
                                                              *new_tmp_table))
1 by brian
clean slate
1859
  {
1860
    /* 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
1861
    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
1862
    delete new_tmp_table;
1502.1.19 by Brian Aker
Adds concept of table owned TableShare.
1863
1046.1.10 by Brian Aker
Formatting around return (style)
1864
    return 0;
1 by brian
clean slate
1865
  }
1866
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1867
  new_tmp_table->reginfo.lock_type= TL_WRITE;	 // Simulate locked
1 by brian
clean slate
1868
1869
  if (link_in_list)
1870
  {
1871
    /* growing temp list at the head */
1608 by Brian Aker
This encapsulates prev/next.
1872
    new_tmp_table->setNext(this->temporary_tables);
1873
    if (new_tmp_table->getNext())
1874
    {
1875
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1876
    }
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1877
    this->temporary_tables= new_tmp_table;
1608 by Brian Aker
This encapsulates prev/next.
1878
    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
1879
  }
1880
  new_tmp_table->pos_in_table_list= 0;
1881
1882
  return new_tmp_table;
1 by brian
clean slate
1883
}
1884
1885
1886
/*****************************************************************************
1046 by Brian Aker
Merge Jay.
1887
 * The following find_field_in_XXX procedures implement the core of the
1888
 * name resolution functionality. The entry point to resolve a column name in a
1889
 * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
1890
 * for each table reference. In turn, depending on the type of table reference,
1891
 * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
1892
 * below specific for the type of table reference.
1893
 ******************************************************************************/
1 by brian
clean slate
1894
1895
/* Special Field pointers as return values of find_field_in_XXX functions. */
1896
Field *not_found_field= (Field*) 0x1;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1897
Field *view_ref_found= (Field*) 0x2;
1 by brian
clean slate
1898
520.1.22 by Brian Aker
Second pass of thd cleanup
1899
static void update_field_dependencies(Session *session, Field *field, Table *table)
1 by brian
clean slate
1900
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1901
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1 by brian
clean slate
1902
  {
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1903
    boost::dynamic_bitset<> *current_bitmap= NULL;
1 by brian
clean slate
1904
1905
    /*
1906
      We always want to register the used keys, as the column bitmap may have
1907
      been set for all fields (for example for view).
1908
    */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1909
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1910
    table->covering_keys&= field->part_of_key;
1911
    table->merge_keys|= field->part_of_key;
1 by brian
clean slate
1912
520.1.22 by Brian Aker
Second pass of thd cleanup
1913
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1 by brian
clean slate
1914
    {
1915
      current_bitmap= table->read_set;
1916
    }
1917
    else
1918
    {
1919
      current_bitmap= table->write_set;
1920
    }
1921
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1922
    //if (current_bitmap->testAndSet(field->field_index))
1923
    if (current_bitmap->test(field->field_index))
1 by brian
clean slate
1924
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1925
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
        session->dup_field= field;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1927
      return;
1 by brian
clean slate
1928
    }
1929
    table->used_fields++;
1930
  }
1931
}
1932
1933
1934
/*
1935
  Find field by name in a NATURAL/USING join table reference.
1936
1937
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
1938
  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
1939
  session			 [in]  thread Cursor
1046 by Brian Aker
Merge Jay.
1940
  table_ref            [in]  table reference to search
1941
  name		 [in]  name of field
1942
  length		 [in]  length of name
1943
  ref                  [in/out] if 'name' is resolved to a view field, ref is
1944
  set to point to the found view field
1945
  register_tree_change [in]  true if ref is not stack variable and we
1946
  need register changes in item tree
1947
  actual_table         [out] the original table reference where the field
1948
  belongs - differs from 'table_list' only for
1949
  NATURAL/USING joins
1 by brian
clean slate
1950
1951
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
1952
  Search for a field among the result fields of a NATURAL/USING join.
1953
  Notice that this procedure is called only for non-qualified field
1954
  names. In the case of qualified fields, we search directly the base
1955
  tables of a natural join.
1 by brian
clean slate
1956
1957
  RETURN
1046 by Brian Aker
Merge Jay.
1958
  NULL        if the field was not found
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
1959
  PTR         Pointer to the found Field
1 by brian
clean slate
1960
*/
1961
1962
static Field *
779.3.1 by Monty Taylor
More cleanup.
1963
find_field_in_natural_join(Session *session, TableList *table_ref,
1964
                           const char *name, uint32_t , Item **,
1965
                           bool, TableList **actual_table)
1 by brian
clean slate
1966
{
1967
  List_iterator_fast<Natural_join_column>
1968
    field_it(*(table_ref->join_columns));
1969
  Natural_join_column *nj_col, *curr_nj_col;
1970
  Field *found_field;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1971
1972
  assert(table_ref->is_natural_join && table_ref->join_columns);
1973
  assert(*actual_table == NULL);
1 by brian
clean slate
1974
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1975
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
1 by brian
clean slate
1976
       curr_nj_col= field_it++)
1977
  {
1978
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
1979
    {
1980
      if (nj_col)
1981
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1982
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1019.1.6 by Brian Aker
A number of random cleanups.
1983
        return NULL;
1 by brian
clean slate
1984
      }
1985
      nj_col= curr_nj_col;
1986
    }
1987
  }
1988
  if (!nj_col)
1019.1.6 by Brian Aker
A number of random cleanups.
1989
    return NULL;
1 by brian
clean slate
1990
  {
1991
    /* This is a base table. */
1660.1.3 by Brian Aker
Encapsulate Table in field
1992
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
1 by brian
clean slate
1993
    found_field= nj_col->table_field;
520.1.22 by Brian Aker
Second pass of thd cleanup
1994
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
1 by brian
clean slate
1995
  }
1996
1997
  *actual_table= nj_col->table_ref;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1998
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1999
  return(found_field);
1 by brian
clean slate
2000
}
2001
2002
2003
/*
2004
  Find field by name in a base table or a view with temp table algorithm.
2005
2006
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2007
  find_field_in_table()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2008
  session				thread Cursor
1046 by Brian Aker
Merge Jay.
2009
  table			table where to search for the field
2010
  name			name of field
2011
  length			length of name
2012
  allow_rowid			do allow finding of "_rowid" field?
2013
  cached_field_index_ptr	cached position in field list (used to speedup
2014
  lookup for fields in prepared tables)
1 by brian
clean slate
2015
2016
  RETURN
1046 by Brian Aker
Merge Jay.
2017
  0	field is not found
2018
#	pointer to field
1 by brian
clean slate
2019
*/
2020
2021
Field *
520.1.22 by Brian Aker
Second pass of thd cleanup
2022
find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
482 by Brian Aker
Remove uint.
2023
                    bool allow_rowid, uint32_t *cached_field_index_ptr)
1 by brian
clean slate
2024
{
2025
  Field **field_ptr, *field;
482 by Brian Aker
Remove uint.
2026
  uint32_t cached_field_index= *cached_field_index_ptr;
1 by brian
clean slate
2027
2028
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
1578.2.10 by Brian Aker
keys and fields partial encapsulation.
2029
  if (cached_field_index < table->getShare()->sizeFields() &&
1 by brian
clean slate
2030
      !my_strcasecmp(system_charset_info,
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2031
                     table->getField(cached_field_index)->field_name, name))
1578.2.14 by Brian Aker
Additional pass through to remove raw field access.
2032
  {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2033
    field_ptr= table->getFields() + cached_field_index;
1578.2.14 by Brian Aker
Additional pass through to remove raw field access.
2034
  }
1669.3.1 by Brian Aker
Remove usage of my_hash in table_share.
2035
  else if (table->getShare()->getNamedFieldSize())
1 by brian
clean slate
2036
  {
1669.3.1 by Brian Aker
Remove usage of my_hash in table_share.
2037
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
1 by brian
clean slate
2038
    if (field_ptr)
2039
    {
2040
      /*
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
2041
        field_ptr points to field in TableShare. Convert it to the matching
1 by brian
clean slate
2042
        field in table
2043
      */
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2044
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
1 by brian
clean slate
2045
    }
2046
  }
2047
  else
2048
  {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2049
    if (!(field_ptr= table->getFields()))
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2050
      return((Field *)0);
1 by brian
clean slate
2051
    for (; *field_ptr; ++field_ptr)
2052
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2053
        break;
2054
  }
2055
2056
  if (field_ptr && *field_ptr)
2057
  {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2058
    *cached_field_index_ptr= field_ptr - table->getFields();
1 by brian
clean slate
2059
    field= *field_ptr;
2060
  }
2061
  else
2062
  {
2063
    if (!allow_rowid ||
2064
        my_strcasecmp(system_charset_info, name, "_rowid") ||
1574 by Brian Aker
Rollup patch for hiding tableshare.
2065
        table->getShare()->rowid_field_offset == 0)
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2066
      return((Field*) 0);
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
2067
    field= table->getField(table->getShare()->rowid_field_offset-1);
1 by brian
clean slate
2068
  }
2069
520.1.22 by Brian Aker
Second pass of thd cleanup
2070
  update_field_dependencies(session, field, table);
1 by brian
clean slate
2071
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2072
  return field;
1 by brian
clean slate
2073
}
2074
2075
2076
/*
2077
  Find field in a table reference.
2078
2079
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2080
  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
2081
  session			   [in]  thread Cursor
1046 by Brian Aker
Merge Jay.
2082
  table_list		   [in]  table reference to search
2083
  name		   [in]  name of field
2084
  length		   [in]  field length of name
2085
  item_name              [in]  name of item if it will be created (VIEW)
2086
  db_name                [in]  optional database name that qualifies the
2087
  table_name             [in]  optional table name that qualifies the field
2088
  ref		       [in/out] if 'name' is resolved to a view field, ref
2089
  is set to point to the found view field
2090
  allow_rowid		   [in]  do allow finding of "_rowid" field?
2091
  cached_field_index_ptr [in]  cached position in field list (used to
2092
  speedup lookup for fields in prepared tables)
2093
  register_tree_change   [in]  true if ref is not stack variable and we
2094
  need register changes in item tree
2095
  actual_table           [out] the original table reference where the field
2096
  belongs - differs from 'table_list' only for
2097
  NATURAL_USING joins.
1 by brian
clean slate
2098
2099
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2100
  Find a field in a table reference depending on the type of table
2101
  reference. There are three types of table references with respect
2102
  to the representation of their result columns:
2103
  - an array of Field_translator objects for MERGE views and some
2104
  information_schema tables,
2105
  - an array of Field objects (and possibly a name hash) for stored
2106
  tables,
2107
  - a list of Natural_join_column objects for NATURAL/USING joins.
2108
  This procedure detects the type of the table reference 'table_list'
2109
  and calls the corresponding search routine.
1 by brian
clean slate
2110
2111
  RETURN
1046 by Brian Aker
Merge Jay.
2112
  0			field is not found
2113
  view_ref_found	found value in VIEW (real result is in *ref)
2114
#			pointer to field
1 by brian
clean slate
2115
*/
2116
2117
Field *
520.1.22 by Brian Aker
Second pass of thd cleanup
2118
find_field_in_table_ref(Session *session, TableList *table_list,
482 by Brian Aker
Remove uint.
2119
                        const char *name, uint32_t length,
1 by brian
clean slate
2120
                        const char *item_name, const char *db_name,
2121
                        const char *table_name, Item **ref,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2122
                        bool allow_rowid,
482 by Brian Aker
Remove uint.
2123
                        uint32_t *cached_field_index_ptr,
327.2.4 by Brian Aker
Refactoring table.h
2124
                        bool register_tree_change, TableList **actual_table)
1 by brian
clean slate
2125
{
327.2.5 by Brian Aker
Refactoring show command
2126
  Field *fld= NULL;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2127
2128
  assert(table_list->alias);
2129
  assert(name);
2130
  assert(item_name);
1 by brian
clean slate
2131
2132
  /*
2133
    Check that the table and database that qualify the current field name
2134
    are the same as the table reference we are going to search for the field.
2135
2136
    Exclude from the test below nested joins because the columns in a
2137
    nested join generally originate from different tables. Nested joins
2138
    also have no table name, except when a nested join is a merge view
2139
    or an information schema table.
2140
2141
    We include explicitly table references with a 'field_translation' table,
2142
    because if there are views over natural joins we don't want to search
2143
    inside the view, but we want to search directly in the view columns
2144
    which are represented as a 'field_translation'.
2145
1532.1.2 by Brian Aker
Remove need for memset on Table object.
2146
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
1 by brian
clean slate
2147
  */
2148
  if (/* Exclude nested joins. */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2149
      (!table_list->getNestedJoin()) &&
1046 by Brian Aker
Merge Jay.
2150
      /* Include merge views and information schema tables. */
1 by brian
clean slate
2151
      /*
2152
        Test if the field qualifiers match the table reference we plan
2153
        to search.
2154
      */
2155
      table_name && table_name[0] &&
2156
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
1874.1.1 by Brian Aker
Encapsulate schema_name it table_list.
2157
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
        strcmp(db_name, table_list->getSchemaName()))))
1046.1.10 by Brian Aker
Formatting around return (style)
2159
    return 0;
1 by brian
clean slate
2160
2161
  *actual_table= NULL;
2162
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2163
  if (!table_list->getNestedJoin())
1 by brian
clean slate
2164
  {
2165
    /* 'table_list' is a stored table. */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2166
    assert(table_list->table);
520.1.22 by Brian Aker
Second pass of thd cleanup
2167
    if ((fld= find_field_in_table(session, table_list->table, name, length,
1 by brian
clean slate
2168
                                  allow_rowid,
2169
                                  cached_field_index_ptr)))
2170
      *actual_table= table_list;
2171
  }
2172
  else
2173
  {
2174
    /*
2175
      'table_list' is a NATURAL/USING join, or an operand of such join that
2176
      is a nested join itself.
2177
2178
      If the field name we search for is qualified, then search for the field
2179
      in the table references used by NATURAL/USING the join.
2180
    */
2181
    if (table_name && table_name[0])
2182
    {
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2183
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
327.2.4 by Brian Aker
Refactoring table.h
2184
      TableList *table;
1 by brian
clean slate
2185
      while ((table= it++))
2186
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
2187
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
1 by brian
clean slate
2188
                                          db_name, table_name, ref,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2189
                                          allow_rowid,
1 by brian
clean slate
2190
                                          cached_field_index_ptr,
2191
                                          register_tree_change, actual_table)))
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2192
          return fld;
1 by brian
clean slate
2193
      }
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2194
      return NULL;
1 by brian
clean slate
2195
    }
2196
    /*
2197
      Non-qualified field, search directly in the result columns of the
2198
      natural join. The condition of the outer IF is true for the top-most
2199
      natural join, thus if the field is not qualified, we will search
2200
      directly the top-most NATURAL/USING join.
2201
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
2202
    fld= find_field_in_natural_join(session, table_list, name, length, ref,
1 by brian
clean slate
2203
                                    register_tree_change, actual_table);
2204
  }
2205
2206
  if (fld)
2207
  {
1046 by Brian Aker
Merge Jay.
2208
    if (session->mark_used_columns != MARK_COLUMNS_NONE)
2209
    {
2210
      /*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2211
        Get rw_set correct for this field so that the Cursor
1046 by Brian Aker
Merge Jay.
2212
        knows that this field is involved in the query and gets
2213
        retrieved/updated
2214
      */
2215
      Field *field_to_set= NULL;
2216
      if (fld == view_ref_found)
1 by brian
clean slate
2217
      {
1046 by Brian Aker
Merge Jay.
2218
        Item *it= (*ref)->real_item();
2219
        if (it->type() == Item::FIELD_ITEM)
2220
          field_to_set= ((Item_field*)it)->field;
1 by brian
clean slate
2221
        else
2222
        {
520.1.22 by Brian Aker
Second pass of thd cleanup
2223
          if (session->mark_used_columns == MARK_COLUMNS_READ)
1046 by Brian Aker
Merge Jay.
2224
            it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
1 by brian
clean slate
2225
        }
2226
      }
1046 by Brian Aker
Merge Jay.
2227
      else
2228
        field_to_set= fld;
2229
      if (field_to_set)
2230
      {
1660.1.3 by Brian Aker
Encapsulate Table in field
2231
        Table *table= field_to_set->getTable();
1046 by Brian Aker
Merge Jay.
2232
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
          table->setReadSet(field_to_set->field_index);
2234
        else
2235
          table->setWriteSet(field_to_set->field_index);
2236
      }
2237
    }
1 by brian
clean slate
2238
  }
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2239
  return(fld);
1 by brian
clean slate
2240
}
2241
2242
2243
/*
2244
  Find field in table list.
2245
2246
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2247
  find_field_in_tables()
2248
  session			  pointer to current thread structure
2249
  item		  field item that should be found
2250
  first_table           list of tables to be searched for item
2251
  last_table            end of the list of tables to search for item. If NULL
2252
  then search to the end of the list 'first_table'.
2253
  ref			  if 'item' is resolved to a view field, ref is set to
2254
  point to the found view field
2255
  report_error	  Degree of error reporting:
2256
  - IGNORE_ERRORS then do not report any error
2257
  - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2258
  fields, suppress all other errors
2259
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2260
  except when non-unique fields were found
2261
  - REPORT_ALL_ERRORS
2262
  register_tree_change  true if ref is not a stack variable and we
2263
  to need register changes in item tree
1 by brian
clean slate
2264
2265
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
2266
  0			If error: the found field is not unique, or there are
2267
  no sufficient access priviliges for the found field,
2268
  or the field is qualified with non-existing table.
2269
  not_found_field	The function was called with report_error ==
2270
  (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2271
  field was not found.
2272
  view_ref_found	View field is found, item passed through ref parameter
2273
  found field         If a item was resolved to some field
1 by brian
clean slate
2274
*/
2275
2276
Field *
520.1.22 by Brian Aker
Second pass of thd cleanup
2277
find_field_in_tables(Session *session, Item_ident *item,
327.2.4 by Brian Aker
Refactoring table.h
2278
                     TableList *first_table, TableList *last_table,
1046 by Brian Aker
Merge Jay.
2279
                     Item **ref, find_item_error_report_type report_error,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
2280
                     bool register_tree_change)
1 by brian
clean slate
2281
{
2282
  Field *found=0;
2283
  const char *db= item->db_name;
2284
  const char *table_name= item->table_name;
2285
  const char *name= item->field_name;
895 by Brian Aker
Completion (?) of uint conversion.
2286
  uint32_t length=(uint32_t) strlen(name);
1 by brian
clean slate
2287
  char name_buff[NAME_LEN+1];
327.2.4 by Brian Aker
Refactoring table.h
2288
  TableList *cur_table= first_table;
2289
  TableList *actual_table;
1 by brian
clean slate
2290
  bool allow_rowid;
2291
2292
  if (!table_name || !table_name[0])
2293
  {
2294
    table_name= 0;                              // For easier test
2295
    db= 0;
2296
  }
2297
2298
  allow_rowid= table_name || (cur_table && !cur_table->next_local);
2299
2300
  if (item->cached_table)
2301
  {
2302
    /*
2303
      This shortcut is used by prepared statements. We assume that
327.2.4 by Brian Aker
Refactoring table.h
2304
      TableList *first_table is not changed during query execution (which
1 by brian
clean slate
2305
      is true for all queries except RENAME but luckily RENAME doesn't
2306
      use fields...) so we can rely on reusing pointer to its member.
2307
      With this optimization we also miss case when addition of one more
2308
      field makes some prepared query ambiguous and so erroneous, but we
2309
      accept this trade off.
2310
    */
327.2.4 by Brian Aker
Refactoring table.h
2311
    TableList *table_ref= item->cached_table;
1 by brian
clean slate
2312
    /*
2313
      The condition (table_ref->view == NULL) ensures that we will call
2314
      find_field_in_table even in the case of information schema tables
2315
      when table_ref->field_translation != NULL.
1046 by Brian Aker
Merge Jay.
2316
    */
1 by brian
clean slate
2317
    if (table_ref->table)
520.1.22 by Brian Aker
Second pass of thd cleanup
2318
      found= find_field_in_table(session, table_ref->table, name, length,
55 by brian
Update for using real bool types.
2319
                                 true, &(item->cached_field_index));
1 by brian
clean slate
2320
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
2321
      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.
2322
                                     NULL, NULL, ref,
55 by brian
Update for using real bool types.
2323
                                     true, &(item->cached_field_index),
1 by brian
clean slate
2324
                                     register_tree_change,
2325
                                     &actual_table);
2326
    if (found)
2327
    {
2328
      /*
2329
        Only views fields should be marked as dependent, not an underlying
2330
        fields.
2331
      */
2332
      {
846 by Brian Aker
Removing on typedeffed class.
2333
        Select_Lex *current_sel= session->lex->current_select;
2334
        Select_Lex *last_select= table_ref->select_lex;
1 by brian
clean slate
2335
        /*
2336
          If the field was an outer referencee, mark all selects using this
2337
          sub query as dependent on the outer query
2338
        */
2339
        if (current_sel != last_select)
520.1.22 by Brian Aker
Second pass of thd cleanup
2340
          mark_select_range_as_dependent(session, last_select, current_sel,
1 by brian
clean slate
2341
                                         found, *ref, item);
2342
      }
2343
      return found;
2344
    }
2345
  }
2346
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
2347
  if (db)
1 by brian
clean slate
2348
  {
2349
    /*
2350
      convert database to lower case for comparison.
2351
      We can't do this in Item_field as this would change the
2352
      'name' of the item which may be used in the select list
2353
    */
629.5.3 by Toru Maesaka
Third pass of replacing MySQL's strmake() with libc calls
2354
    strncpy(name_buff, db, sizeof(name_buff)-1);
1 by brian
clean slate
2355
    my_casedn_str(files_charset_info, name_buff);
2356
    db= name_buff;
2357
  }
2358
2359
  if (last_table)
2360
    last_table= last_table->next_name_resolution_table;
2361
2362
  for (; cur_table != last_table ;
2363
       cur_table= cur_table->next_name_resolution_table)
2364
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
2365
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
1 by brian
clean slate
2366
                                              item->name, db, table_name, ref,
2367
                                              allow_rowid,
2368
                                              &(item->cached_field_index),
2369
                                              register_tree_change,
2370
                                              &actual_table);
2371
    if (cur_field)
2372
    {
2373
      /*
2374
        Store the original table of the field, which may be different from
2375
        cur_table in the case of NATURAL/USING join.
2376
      */
1019.1.2 by Brian Aker
Removed dead code from table_list.
2377
      item->cached_table= found ?  0 : actual_table;
1 by brian
clean slate
2378
520.1.22 by Brian Aker
Second pass of thd cleanup
2379
      assert(session->where);
1 by brian
clean slate
2380
      /*
2381
        If we found a fully qualified field we return it directly as it can't
2382
        have duplicates.
1046 by Brian Aker
Merge Jay.
2383
      */
1 by brian
clean slate
2384
      if (db)
2385
        return cur_field;
2386
2387
      if (found)
2388
      {
2389
        if (report_error == REPORT_ALL_ERRORS ||
2390
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2391
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
2392
                   table_name ? item->full_name() : name, session->where);
1 by brian
clean slate
2393
        return (Field*) 0;
2394
      }
2395
      found= cur_field;
2396
    }
2397
  }
2398
2399
  if (found)
2400
    return found;
2401
2402
  /*
2403
    If the field was qualified and there were no tables to search, issue
2404
    an error that an unknown table was given. The situation is detected
2405
    as follows: if there were no tables we wouldn't go through the loop
2406
    and cur_table wouldn't be updated by the loop increment part, so it
2407
    will be equal to the first table.
2408
  */
2409
  if (table_name && (cur_table == first_table) &&
2410
      (report_error == REPORT_ALL_ERRORS ||
2411
       report_error == REPORT_EXCEPT_NON_UNIQUE))
2412
  {
2413
    char buff[NAME_LEN*2+1];
2414
    if (db && db[0])
2415
    {
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
2416
      /* We're in an error condition, two extra strlen's aren't going
2417
       * to kill us */
2418
      assert(strlen(db) <= NAME_LEN);
2419
      assert(strlen(table_name) <= NAME_LEN);
2420
      strcpy(buff, db);
2421
      strcat(buff,".");
2422
      strcat(buff, table_name);
1 by brian
clean slate
2423
      table_name=buff;
2424
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
2425
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
1 by brian
clean slate
2426
  }
2427
  else
2428
  {
2429
    if (report_error == REPORT_ALL_ERRORS ||
2430
        report_error == REPORT_EXCEPT_NON_UNIQUE)
520.1.22 by Brian Aker
Second pass of thd cleanup
2431
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
1 by brian
clean slate
2432
    else
2433
      found= not_found_field;
2434
  }
2435
  return found;
2436
}
2437
2438
2439
/*
2440
  Find Item in list of items (find_field_in_tables analog)
2441
2442
  TODO
1046 by Brian Aker
Merge Jay.
2443
  is it better return only counter?
1 by brian
clean slate
2444
2445
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2446
  find_item_in_list()
2447
  find			Item to find
2448
  items			List of items
2449
  counter			To return number of found item
2450
  report_error
2451
  REPORT_ALL_ERRORS		report errors, return 0 if error
2452
  REPORT_EXCEPT_NOT_FOUND	Do not report 'not found' error and
2453
  return not_found_item, report other errors,
2454
  return 0
2455
  IGNORE_ERRORS		Do not report errors, return 0 if error
2456
  resolution                  Set to the resolution type if the item is found
2457
  (it says whether the item is resolved
2458
  against an alias name,
2459
  or as a field name without alias,
2460
  or as a field hidden by alias,
2461
  or ignoring alias)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2462
1 by brian
clean slate
2463
  RETURN VALUES
1046 by Brian Aker
Merge Jay.
2464
  0			Item is not found or item is not unique,
2465
  error message is reported
2466
  not_found_item	Function was called with
2467
  report_error == REPORT_EXCEPT_NOT_FOUND and
2468
  item was not found. No error message was reported
2469
  found field
1 by brian
clean slate
2470
*/
2471
2472
/* Special Item pointer to serve as a return value from find_item_in_list(). */
2473
Item **not_found_item= (Item**) 0x1;
2474
2475
2476
Item **
1578.6.3 by Brian Aker
More current_session removal.
2477
find_item_in_list(Session *session,
2478
                  Item *find, List<Item> &items, uint32_t *counter,
1 by brian
clean slate
2479
                  find_item_error_report_type report_error,
2480
                  enum_resolution_type *resolution)
2481
{
2482
  List_iterator<Item> li(items);
2483
  Item **found=0, **found_unaliased= 0, *item;
2484
  const char *db_name=0;
2485
  const char *field_name=0;
2486
  const char *table_name=0;
2487
  bool found_unaliased_non_uniq= 0;
2488
  /*
2489
    true if the item that we search for is a valid name reference
2490
    (and not an item that happens to have a name).
2491
  */
2492
  bool is_ref_by_name= 0;
482 by Brian Aker
Remove uint.
2493
  uint32_t unaliased_counter= 0;
1 by brian
clean slate
2494
2495
  *resolution= NOT_RESOLVED;
2496
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2497
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
1 by brian
clean slate
2498
                   find->type() == Item::REF_ITEM);
2499
  if (is_ref_by_name)
2500
  {
2501
    field_name= ((Item_ident*) find)->field_name;
2502
    table_name= ((Item_ident*) find)->table_name;
2503
    db_name=    ((Item_ident*) find)->db_name;
2504
  }
2505
482 by Brian Aker
Remove uint.
2506
  for (uint32_t i= 0; (item=li++); i++)
1 by brian
clean slate
2507
  {
2508
    if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
2509
    {
2510
      Item_ident *item_field= (Item_ident*) item;
2511
2512
      /*
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
2513
        In case of group_concat() with ORDER BY condition in the QUERY
2514
        item_field can be field of temporary table without item name
2515
        (if this field created from expression argument of group_concat()),
2516
        => we have to check presence of name before compare
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2517
      */
1 by brian
clean slate
2518
      if (!item_field->name)
2519
        continue;
2520
2521
      if (table_name)
2522
      {
2523
        /*
2524
          If table name is specified we should find field 'field_name' in
2525
          table 'table_name'. According to SQL-standard we should ignore
2526
          aliases in this case.
2527
2528
          Since we should NOT prefer fields from the select list over
2529
          other fields from the tables participating in this select in
2530
          case of ambiguity we have to do extra check outside this function.
2531
2532
          We use strcmp for table names and database names as these may be
2533
          case sensitive. In cases where they are not case sensitive, they
2534
          are always in lower case.
2535
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
2536
          item_field->field_name and item_field->table_name can be 0x0 if
2537
          item is not fix_field()'ed yet.
1 by brian
clean slate
2538
        */
2539
        if (item_field->field_name && item_field->table_name &&
1046 by Brian Aker
Merge Jay.
2540
            !my_strcasecmp(system_charset_info, item_field->field_name,
1 by brian
clean slate
2541
                           field_name) &&
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2542
            !my_strcasecmp(table_alias_charset, item_field->table_name,
1 by brian
clean slate
2543
                           table_name) &&
2544
            (!db_name || (item_field->db_name &&
2545
                          !strcmp(item_field->db_name, db_name))))
2546
        {
2547
          if (found_unaliased)
2548
          {
2549
            if ((*found_unaliased)->eq(item, 0))
2550
              continue;
2551
            /*
2552
              Two matching fields in select list.
2553
              We already can bail out because we are searching through
2554
              unaliased names only and will have duplicate error anyway.
2555
            */
2556
            if (report_error != IGNORE_ERRORS)
2557
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2558
                       find->full_name(), session->where);
1 by brian
clean slate
2559
            return (Item**) 0;
2560
          }
2561
          found_unaliased= li.ref();
2562
          unaliased_counter= i;
2563
          *resolution= RESOLVED_IGNORING_ALIAS;
2564
          if (db_name)
2565
            break;                              // Perfect match
2566
        }
2567
      }
2568
      else
2569
      {
2570
        int fname_cmp= my_strcasecmp(system_charset_info,
2571
                                     item_field->field_name,
2572
                                     field_name);
2573
        if (!my_strcasecmp(system_charset_info,
2574
                           item_field->name,field_name))
2575
        {
2576
          /*
2577
            If table name was not given we should scan through aliases
2578
            and non-aliased fields first. We are also checking unaliased
2579
            name of the field in then next  else-if, to be able to find
2580
            instantly field (hidden by alias) if no suitable alias or
2581
            non-aliased field was found.
2582
          */
2583
          if (found)
2584
          {
2585
            if ((*found)->eq(item, 0))
2586
              continue;                           // Same field twice
2587
            if (report_error != IGNORE_ERRORS)
2588
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2589
                       find->full_name(), session->where);
1 by brian
clean slate
2590
            return (Item**) 0;
2591
          }
2592
          found= li.ref();
2593
          *counter= i;
2594
          *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
1046 by Brian Aker
Merge Jay.
2595
            RESOLVED_WITH_NO_ALIAS;
1 by brian
clean slate
2596
        }
2597
        else if (!fname_cmp)
2598
        {
2599
          /*
2600
            We will use non-aliased field or react on such ambiguities only if
2601
            we won't be able to find aliased field.
2602
            Again if we have ambiguity with field outside of select list
2603
            we should prefer fields from select list.
2604
          */
2605
          if (found_unaliased)
2606
          {
2607
            if ((*found_unaliased)->eq(item, 0))
2608
              continue;                           // Same field twice
2609
            found_unaliased_non_uniq= 1;
2610
          }
2611
          found_unaliased= li.ref();
2612
          unaliased_counter= i;
2613
        }
2614
      }
2615
    }
2616
    else if (!table_name)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2617
    {
1 by brian
clean slate
2618
      if (is_ref_by_name && find->name && item->name &&
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
2619
          !my_strcasecmp(system_charset_info,item->name,find->name))
1 by brian
clean slate
2620
      {
2621
        found= li.ref();
2622
        *counter= i;
2623
        *resolution= RESOLVED_AGAINST_ALIAS;
2624
        break;
2625
      }
2626
      else if (find->eq(item,0))
2627
      {
2628
        found= li.ref();
2629
        *counter= i;
2630
        *resolution= RESOLVED_IGNORING_ALIAS;
2631
        break;
2632
      }
2633
    }
2634
  }
2635
  if (!found)
2636
  {
2637
    if (found_unaliased_non_uniq)
2638
    {
2639
      if (report_error != IGNORE_ERRORS)
2640
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2641
                 find->full_name(), session->where);
1 by brian
clean slate
2642
      return (Item **) 0;
2643
    }
2644
    if (found_unaliased)
2645
    {
2646
      found= found_unaliased;
2647
      *counter= unaliased_counter;
2648
      *resolution= RESOLVED_BEHIND_ALIAS;
2649
    }
2650
  }
2651
  if (found)
2652
    return found;
2653
  if (report_error != REPORT_EXCEPT_NOT_FOUND)
2654
  {
2655
    if (report_error == REPORT_ALL_ERRORS)
2656
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
1578.6.3 by Brian Aker
More current_session removal.
2657
               find->full_name(), session->where);
1 by brian
clean slate
2658
    return (Item **) 0;
2659
  }
2660
  else
2661
    return (Item **) not_found_item;
2662
}
2663
2664
2665
/*
2666
  Test if a string is a member of a list of strings.
2667
2668
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2669
  test_if_string_in_list()
2670
  find      the string to look for
2671
  str_list  a list of strings to be searched
1 by brian
clean slate
2672
2673
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2674
  Sequentially search a list of strings for a string, and test whether
2675
  the list contains the same string.
1 by brian
clean slate
2676
2677
  RETURN
1046 by Brian Aker
Merge Jay.
2678
  true  if find is in str_list
2679
  false otherwise
1 by brian
clean slate
2680
*/
2681
2682
static bool
2683
test_if_string_in_list(const char *find, List<String> *str_list)
2684
{
2685
  List_iterator<String> str_list_it(*str_list);
2686
  String *curr_str;
2687
  size_t find_length= strlen(find);
2688
  while ((curr_str= str_list_it++))
2689
  {
2690
    if (find_length != curr_str->length())
2691
      continue;
2692
    if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
55 by brian
Update for using real bool types.
2693
      return true;
1 by brian
clean slate
2694
  }
55 by brian
Update for using real bool types.
2695
  return false;
1 by brian
clean slate
2696
}
2697
2698
2699
/*
2700
  Create a new name resolution context for an item so that it is
2701
  being resolved in a specific table reference.
2702
2703
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2704
  set_new_item_local_context()
2705
  session        pointer to current thread
2706
  item       item for which new context is created and set
2707
  table_ref  table ref where an item showld be resolved
1 by brian
clean slate
2708
2709
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2710
  Create a new name resolution context for an item, so that the item
2711
  is resolved only the supplied 'table_ref'.
1 by brian
clean slate
2712
2713
  RETURN
1046 by Brian Aker
Merge Jay.
2714
  false  if all OK
2715
  true   otherwise
1 by brian
clean slate
2716
*/
2717
2718
static bool
520.1.22 by Brian Aker
Second pass of thd cleanup
2719
set_new_item_local_context(Session *session, Item_ident *item, TableList *table_ref)
1 by brian
clean slate
2720
{
2721
  Name_resolution_context *context;
520.1.22 by Brian Aker
Second pass of thd cleanup
2722
  if (!(context= new (session->mem_root) Name_resolution_context))
55 by brian
Update for using real bool types.
2723
    return true;
1 by brian
clean slate
2724
  context->init();
2725
  context->first_name_resolution_table=
2726
    context->last_name_resolution_table= table_ref;
2727
  item->context= context;
55 by brian
Update for using real bool types.
2728
  return false;
1 by brian
clean slate
2729
}
2730
2731
2732
/*
2733
  Find and mark the common columns of two table references.
2734
2735
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2736
  mark_common_columns()
2737
  session                [in] current thread
2738
  table_ref_1        [in] the first (left) join operand
2739
  table_ref_2        [in] the second (right) join operand
2740
  using_fields       [in] if the join is JOIN...USING - the join columns,
2741
  if NATURAL join, then NULL
2742
  found_using_fields [out] number of fields from the USING clause that were
2743
  found among the common fields
1 by brian
clean slate
2744
2745
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2746
  The procedure finds the common columns of two relations (either
2747
  tables or intermediate join results), and adds an equi-join condition
2748
  to the ON clause of 'table_ref_2' for each pair of matching columns.
2749
  If some of table_ref_XXX represents a base table or view, then we
2750
  create new 'Natural_join_column' instances for each column
2751
  reference and store them in the 'join_columns' of the table
2752
  reference.
1 by brian
clean slate
2753
2754
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
2755
  The procedure assumes that store_natural_using_join_columns() was
2756
  called for the previous level of NATURAL/USING joins.
1 by brian
clean slate
2757
2758
  RETURN
1046 by Brian Aker
Merge Jay.
2759
  true   error when some common column is non-unique, or out of memory
2760
  false  OK
1 by brian
clean slate
2761
*/
2762
2763
static bool
520.1.22 by Brian Aker
Second pass of thd cleanup
2764
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
482 by Brian Aker
Remove uint.
2765
                    List<String> *using_fields, uint32_t *found_using_fields)
1 by brian
clean slate
2766
{
2767
  Field_iterator_table_ref it_1, it_2;
2768
  Natural_join_column *nj_col_1, *nj_col_2;
55 by brian
Update for using real bool types.
2769
  bool result= true;
2770
  bool first_outer_loop= true;
1 by brian
clean slate
2771
  /*
2772
    Leaf table references to which new natural join columns are added
2773
    if the leaves are != NULL.
2774
  */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2775
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
                      ! table_ref_1->is_natural_join) ?
1046 by Brian Aker
Merge Jay.
2777
    NULL : table_ref_1;
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
2778
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
                      ! table_ref_2->is_natural_join) ?
1046 by Brian Aker
Merge Jay.
2780
    NULL : table_ref_2;
1 by brian
clean slate
2781
2782
  *found_using_fields= 0;
2783
2784
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2785
  {
55 by brian
Update for using real bool types.
2786
    bool found= false;
1 by brian
clean slate
2787
    const char *field_name_1;
2788
    /* true if field_name_1 is a member of using_fields */
2789
    bool is_using_column_1;
2790
    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
2791
      return(result);
1 by brian
clean slate
2792
    field_name_1= nj_col_1->name();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2793
    is_using_column_1= using_fields &&
1 by brian
clean slate
2794
      test_if_string_in_list(field_name_1, using_fields);
2795
2796
    /*
2797
      Find a field with the same name in table_ref_2.
2798
2799
      Note that for the second loop, it_2.set() will iterate over
2800
      table_ref_2->join_columns and not generate any new elements or
2801
      lists.
2802
    */
2803
    nj_col_2= NULL;
2804
    for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
2805
    {
2806
      Natural_join_column *cur_nj_col_2;
2807
      const char *cur_field_name_2;
2808
      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
2809
        return(result);
1 by brian
clean slate
2810
      cur_field_name_2= cur_nj_col_2->name();
2811
2812
      /*
2813
        Compare the two columns and check for duplicate common fields.
2814
        A common field is duplicate either if it was already found in
55 by brian
Update for using real bool types.
2815
        table_ref_2 (then found == true), or if a field in table_ref_2
1 by brian
clean slate
2816
        was already matched by some previous field in table_ref_1
55 by brian
Update for using real bool types.
2817
        (then cur_nj_col_2->is_common == true).
1 by brian
clean slate
2818
        Note that it is too early to check the columns outside of the
2819
        USING list for ambiguity because they are not actually "referenced"
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2820
        here. These columns must be checked only on unqualified reference
1 by brian
clean slate
2821
        by name (e.g. in SELECT list).
2822
      */
2823
      if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
2824
      {
2825
        if (cur_nj_col_2->is_common ||
2826
            (found && (!using_fields || is_using_column_1)))
2827
        {
520.1.22 by Brian Aker
Second pass of thd cleanup
2828
          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
2829
          return(result);
1 by brian
clean slate
2830
        }
2831
        nj_col_2= cur_nj_col_2;
55 by brian
Update for using real bool types.
2832
        found= true;
1 by brian
clean slate
2833
      }
2834
    }
2835
    if (first_outer_loop && leaf_2)
2836
    {
2837
      /*
2838
        Make sure that the next inner loop "knows" that all columns
2839
        are materialized already.
2840
      */
55 by brian
Update for using real bool types.
2841
      leaf_2->is_join_columns_complete= true;
2842
      first_outer_loop= false;
1 by brian
clean slate
2843
    }
2844
    if (!found)
2845
      continue;                                 // No matching field
2846
2847
    /*
2848
      field_1 and field_2 have the same names. Check if they are in the USING
2849
      clause (if present), mark them as common fields, and add a new
2850
      equi-join condition to the ON clause.
2851
    */
2852
    if (nj_col_2 && (!using_fields ||is_using_column_1))
2853
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
2854
      Item *item_1=   nj_col_1->create_item(session);
2855
      Item *item_2=   nj_col_2->create_item(session);
1 by brian
clean slate
2856
      Field *field_1= nj_col_1->field();
2857
      Field *field_2= nj_col_2->field();
2858
      Item_ident *item_ident_1, *item_ident_2;
2859
      Item_func_eq *eq_cond;
2860
2861
      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
2862
        return(result); // out of memory
1 by brian
clean slate
2863
2864
      /*
2865
        In the case of no_wrap_view_item == 0, the created items must be
2866
        of sub-classes of Item_ident.
2867
      */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2868
      assert(item_1->type() == Item::FIELD_ITEM ||
1046 by Brian Aker
Merge Jay.
2869
             item_1->type() == Item::REF_ITEM);
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2870
      assert(item_2->type() == Item::FIELD_ITEM ||
1046 by Brian Aker
Merge Jay.
2871
             item_2->type() == Item::REF_ITEM);
1 by brian
clean slate
2872
2873
      /*
2874
        We need to cast item_1,2 to Item_ident, because we need to hook name
2875
        resolution contexts specific to each item.
2876
      */
2877
      item_ident_1= (Item_ident*) item_1;
2878
      item_ident_2= (Item_ident*) item_2;
2879
      /*
2880
        Create and hook special name resolution contexts to each item in the
2881
        new join condition . We need this to both speed-up subsequent name
2882
        resolution of these items, and to enable proper name resolution of
2883
        the items during the execute phase of PS.
2884
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
2885
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
          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
2887
        return(result);
1 by brian
clean slate
2888
2889
      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
2890
        return(result);                               /* Out of memory. */
1 by brian
clean slate
2891
2892
      /*
2893
        Add the new equi-join condition to the ON clause. Notice that
2894
        fix_fields() is applied to all ON conditions in setup_conds()
2895
        so we don't do it here.
1046 by Brian Aker
Merge Jay.
2896
      */
1 by brian
clean slate
2897
      add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
2898
                   table_ref_1 : table_ref_2),
2899
                  eq_cond);
2900
55 by brian
Update for using real bool types.
2901
      nj_col_1->is_common= nj_col_2->is_common= true;
1 by brian
clean slate
2902
2903
      if (field_1)
2904
      {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2905
        Table *table_1= nj_col_1->table_ref->table;
1 by brian
clean slate
2906
        /* Mark field_1 used for table cache. */
1003.1.12 by Brian Aker
Begin of abstract out the bitmap from direct reference.
2907
        table_1->setReadSet(field_1->field_index);
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2908
        table_1->covering_keys&= field_1->part_of_key;
2909
        table_1->merge_keys|= field_1->part_of_key;
1 by brian
clean slate
2910
      }
2911
      if (field_2)
2912
      {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2913
        Table *table_2= nj_col_2->table_ref->table;
1 by brian
clean slate
2914
        /* Mark field_2 used for table cache. */
1003.1.12 by Brian Aker
Begin of abstract out the bitmap from direct reference.
2915
        table_2->setReadSet(field_2->field_index);
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2916
        table_2->covering_keys&= field_2->part_of_key;
2917
        table_2->merge_keys|= field_2->part_of_key;
1 by brian
clean slate
2918
      }
2919
2920
      if (using_fields != NULL)
2921
        ++(*found_using_fields);
2922
    }
2923
  }
2924
  if (leaf_1)
55 by brian
Update for using real bool types.
2925
    leaf_1->is_join_columns_complete= true;
1 by brian
clean slate
2926
2927
  /*
2928
    Everything is OK.
2929
    Notice that at this point there may be some column names in the USING
2930
    clause that are not among the common columns. This is an SQL error and
2931
    we check for this error in store_natural_using_join_columns() when
2932
    (found_using_fields < length(join_using_fields)).
2933
  */
55 by brian
Update for using real bool types.
2934
  result= false;
1 by brian
clean slate
2935
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2936
  return(result);
1 by brian
clean slate
2937
}
2938
2939
2940
2941
/*
2942
  Materialize and store the row type of NATURAL/USING join.
2943
2944
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
2945
  store_natural_using_join_columns()
2946
  session                current thread
2947
  natural_using_join the table reference of the NATURAL/USING join
2948
  table_ref_1        the first (left) operand (of a NATURAL/USING join).
2949
  table_ref_2        the second (right) operand (of a NATURAL/USING join).
2950
  using_fields       if the join is JOIN...USING - the join columns,
2951
  if NATURAL join, then NULL
2952
  found_using_fields number of fields from the USING clause that were
2953
  found among the common fields
1 by brian
clean slate
2954
2955
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
2956
  Iterate over the columns of both join operands and sort and store
2957
  all columns into the 'join_columns' list of natural_using_join
2958
  where the list is formed by three parts:
2959
part1: The coalesced columns of table_ref_1 and table_ref_2,
2960
sorted according to the column order of the first table.
2961
part2: The other columns of the first table, in the order in
2962
which they were defined in CREATE TABLE.
2963
part3: The other columns of the second table, in the order in
2964
which they were defined in CREATE TABLE.
2965
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
2966
2967
IMPLEMENTATION
2968
The procedure assumes that mark_common_columns() has been called
2969
for the join that is being processed.
2970
2971
RETURN
2972
true    error: Some common column is ambiguous
2973
false   OK
1 by brian
clean slate
2974
*/
2975
2976
static bool
1578.6.3 by Brian Aker
More current_session removal.
2977
store_natural_using_join_columns(Session *session,
327.2.4 by Brian Aker
Refactoring table.h
2978
                                 TableList *natural_using_join,
2979
                                 TableList *table_ref_1,
2980
                                 TableList *table_ref_2,
1 by brian
clean slate
2981
                                 List<String> *using_fields,
482 by Brian Aker
Remove uint.
2982
                                 uint32_t found_using_fields)
1 by brian
clean slate
2983
{
2984
  Field_iterator_table_ref it_1, it_2;
2985
  Natural_join_column *nj_col_1, *nj_col_2;
55 by brian
Update for using real bool types.
2986
  bool result= true;
1 by brian
clean slate
2987
  List<Natural_join_column> *non_join_columns;
2988
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
2989
  assert(!natural_using_join->join_columns);
1 by brian
clean slate
2990
2991
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
      !(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
2993
  {
2994
    return(result);
2995
  }
1 by brian
clean slate
2996
2997
  /* Append the columns of the first join operand. */
2998
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2999
  {
3000
    nj_col_1= it_1.get_natural_column_ref();
3001
    if (nj_col_1->is_common)
3002
    {
3003
      natural_using_join->join_columns->push_back(nj_col_1);
3004
      /* Reset the common columns for the next call to mark_common_columns. */
55 by brian
Update for using real bool types.
3005
      nj_col_1->is_common= false;
1 by brian
clean slate
3006
    }
3007
    else
3008
      non_join_columns->push_back(nj_col_1);
3009
  }
3010
3011
  /*
3012
    Check that all columns in the USING clause are among the common
3013
    columns. If this is not the case, report the first one that was
3014
    not found in an error.
3015
  */
3016
  if (using_fields && found_using_fields < using_fields->elements)
3017
  {
3018
    String *using_field_name;
3019
    List_iterator_fast<String> using_fields_it(*using_fields);
3020
    while ((using_field_name= using_fields_it++))
3021
    {
3022
      const char *using_field_name_ptr= using_field_name->c_ptr();
3023
      List_iterator_fast<Natural_join_column>
3024
        it(*(natural_using_join->join_columns));
3025
      Natural_join_column *common_field;
3026
3027
      for (;;)
3028
      {
3029
        /* If reached the end of fields, and none was found, report error. */
3030
        if (!(common_field= it++))
3031
        {
3032
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
1578.6.3 by Brian Aker
More current_session removal.
3033
                   session->where);
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3034
          return(result);
1 by brian
clean slate
3035
        }
3036
        if (!my_strcasecmp(system_charset_info,
3037
                           common_field->name(), using_field_name_ptr))
3038
          break;                                // Found match
3039
      }
3040
    }
3041
  }
3042
3043
  /* Append the non-equi-join columns of the second join operand. */
3044
  for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
3045
  {
3046
    nj_col_2= it_2.get_natural_column_ref();
3047
    if (!nj_col_2->is_common)
3048
      non_join_columns->push_back(nj_col_2);
3049
    else
3050
    {
3051
      /* Reset the common columns for the next call to mark_common_columns. */
55 by brian
Update for using real bool types.
3052
      nj_col_2->is_common= false;
1 by brian
clean slate
3053
    }
3054
  }
3055
3056
  if (non_join_columns->elements > 0)
3057
    natural_using_join->join_columns->concat(non_join_columns);
55 by brian
Update for using real bool types.
3058
  natural_using_join->is_join_columns_complete= true;
1 by brian
clean slate
3059
55 by brian
Update for using real bool types.
3060
  result= false;
1 by brian
clean slate
3061
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3062
  return(result);
1 by brian
clean slate
3063
}
3064
3065
3066
/*
3067
  Precompute and store the row types of the top-most NATURAL/USING joins.
3068
3069
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3070
  store_top_level_join_columns()
3071
  session            current thread
3072
  table_ref      nested join or table in a FROM clause
3073
  left_neighbor  neighbor table reference to the left of table_ref at the
3074
  same level in the join tree
3075
  right_neighbor neighbor table reference to the right of table_ref at the
3076
  same level in the join tree
1 by brian
clean slate
3077
3078
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
3079
  The procedure performs a post-order traversal of a nested join tree
3080
  and materializes the row types of NATURAL/USING joins in a
3081
  bottom-up manner until it reaches the TableList elements that
3082
  represent the top-most NATURAL/USING joins. The procedure should be
3083
  applied to each element of Select_Lex::top_join_list (i.e. to each
3084
  top-level element of the FROM clause).
1 by brian
clean slate
3085
3086
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
3087
  Notice that the table references in the list nested_join->join_list
3088
  are in reverse order, thus when we iterate over it, we are moving
3089
  from the right to the left in the FROM clause.
1 by brian
clean slate
3090
3091
  RETURN
1046 by Brian Aker
Merge Jay.
3092
  true   Error
3093
  false  OK
1 by brian
clean slate
3094
*/
3095
3096
static bool
520.1.22 by Brian Aker
Second pass of thd cleanup
3097
store_top_level_join_columns(Session *session, TableList *table_ref,
327.2.4 by Brian Aker
Refactoring table.h
3098
                             TableList *left_neighbor,
3099
                             TableList *right_neighbor)
1 by brian
clean slate
3100
{
55 by brian
Update for using real bool types.
3101
  bool result= true;
1 by brian
clean slate
3102
3103
  /* Call the procedure recursively for each nested table reference. */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3104
  if (table_ref->getNestedJoin())
1 by brian
clean slate
3105
  {
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3106
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
327.2.4 by Brian Aker
Refactoring table.h
3107
    TableList *same_level_left_neighbor= nested_it++;
3108
    TableList *same_level_right_neighbor= NULL;
1 by brian
clean slate
3109
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
327.2.4 by Brian Aker
Refactoring table.h
3110
    TableList *real_left_neighbor, *real_right_neighbor;
1 by brian
clean slate
3111
3112
    while (same_level_left_neighbor)
3113
    {
327.2.4 by Brian Aker
Refactoring table.h
3114
      TableList *cur_table_ref= same_level_left_neighbor;
1 by brian
clean slate
3115
      same_level_left_neighbor= nested_it++;
3116
      /*
3117
        The order of RIGHT JOIN operands is reversed in 'join list' to
3118
        transform it into a LEFT JOIN. However, in this procedure we need
3119
        the join operands in their lexical order, so below we reverse the
3120
        join operands. Notice that this happens only in the first loop,
3121
        and not in the second one, as in the second loop
3122
        same_level_left_neighbor == NULL.
3123
        This is the correct behavior, because the second loop sets
3124
        cur_table_ref reference correctly after the join operands are
3125
        swapped in the first loop.
3126
      */
3127
      if (same_level_left_neighbor &&
3128
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
      {
3130
        /* This can happen only for JOIN ... ON. */
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3131
        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.
3132
        std::swap(same_level_left_neighbor, cur_table_ref);
1 by brian
clean slate
3133
      }
3134
3135
      /*
3136
        Pick the parent's left and right neighbors if there are no immediate
3137
        neighbors at the same level.
3138
      */
3139
      real_left_neighbor=  (same_level_left_neighbor) ?
1046 by Brian Aker
Merge Jay.
3140
        same_level_left_neighbor : left_neighbor;
1 by brian
clean slate
3141
      real_right_neighbor= (same_level_right_neighbor) ?
1046 by Brian Aker
Merge Jay.
3142
        same_level_right_neighbor : right_neighbor;
1 by brian
clean slate
3143
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3144
      if (cur_table_ref->getNestedJoin() &&
520.1.22 by Brian Aker
Second pass of thd cleanup
3145
          store_top_level_join_columns(session, cur_table_ref,
1 by brian
clean slate
3146
                                       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
3147
        return(result);
1 by brian
clean slate
3148
      same_level_right_neighbor= cur_table_ref;
3149
    }
3150
  }
3151
3152
  /*
3153
    If this is a NATURAL/USING join, materialize its result columns and
3154
    convert to a JOIN ... ON.
3155
  */
3156
  if (table_ref->is_natural_join)
3157
  {
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3158
    assert(table_ref->getNestedJoin() &&
3159
           table_ref->getNestedJoin()->join_list.elements == 2);
3160
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
1 by brian
clean slate
3161
    /*
3162
      Notice that the order of join operands depends on whether table_ref
3163
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3164
      in inverted order.
1046 by Brian Aker
Merge Jay.
3165
    */
327.2.4 by Brian Aker
Refactoring table.h
3166
    TableList *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
3167
    TableList *table_ref_1= operand_it++; /* First NATURAL join operand. */
1 by brian
clean slate
3168
    List<String> *using_fields= table_ref->join_using_fields;
482 by Brian Aker
Remove uint.
3169
    uint32_t found_using_fields;
1 by brian
clean slate
3170
3171
    /*
3172
      The two join operands were interchanged in the parser, change the order
3173
      back for 'mark_common_columns'.
3174
    */
3175
    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.
3176
      std::swap(table_ref_1, table_ref_2);
520.1.22 by Brian Aker
Second pass of thd cleanup
3177
    if (mark_common_columns(session, table_ref_1, table_ref_2,
1 by brian
clean slate
3178
                            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
3179
      return(result);
1 by brian
clean slate
3180
3181
    /*
3182
      Swap the join operands back, so that we pick the columns of the second
3183
      one as the coalesced columns. In this way the coalesced columns are the
3184
      same as of an equivalent LEFT JOIN.
3185
    */
3186
    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.
3187
      std::swap(table_ref_1, table_ref_2);
520.1.22 by Brian Aker
Second pass of thd cleanup
3188
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
1 by brian
clean slate
3189
                                         table_ref_2, using_fields,
3190
                                         found_using_fields))
1859.2.13 by Brian Aker
Remove a number of goto'. Also I removed the std::cerr that slipped in on
3191
      return(result);
1 by brian
clean slate
3192
3193
    /*
3194
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3195
      because either one of them or the other is the one with the
3196
      natural join flag because RIGHT joins are transformed into LEFT,
3197
      and the two tables may be reordered.
3198
    */
3199
    table_ref_1->natural_join= table_ref_2->natural_join= NULL;
3200
55 by brian
Update for using real bool types.
3201
    /* Add a true condition to outer joins that have no common columns. */
1 by brian
clean slate
3202
    if (table_ref_2->outer_join &&
3203
        !table_ref_1->on_expr && !table_ref_2->on_expr)
152 by Brian Aker
longlong replacement
3204
      table_ref_2->on_expr= new Item_int((int64_t) 1,1);   /* Always true. */
1 by brian
clean slate
3205
3206
    /* Change this table reference to become a leaf for name resolution. */
3207
    if (left_neighbor)
3208
    {
327.2.4 by Brian Aker
Refactoring table.h
3209
      TableList *last_leaf_on_the_left;
1 by brian
clean slate
3210
      last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
3211
      last_leaf_on_the_left->next_name_resolution_table= table_ref;
3212
    }
3213
    if (right_neighbor)
3214
    {
327.2.4 by Brian Aker
Refactoring table.h
3215
      TableList *first_leaf_on_the_right;
1 by brian
clean slate
3216
      first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
3217
      table_ref->next_name_resolution_table= first_leaf_on_the_right;
3218
    }
3219
    else
3220
      table_ref->next_name_resolution_table= NULL;
3221
  }
55 by brian
Update for using real bool types.
3222
  result= false; /* All is OK. */
1 by brian
clean slate
3223
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3224
  return(result);
1 by brian
clean slate
3225
}
3226
3227
3228
/*
3229
  Compute and store the row types of the top-most NATURAL/USING joins
3230
  in a FROM clause.
3231
3232
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3233
  setup_natural_join_row_types()
3234
  session          current thread
3235
  from_clause  list of top-level table references in a FROM clause
1 by brian
clean slate
3236
3237
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
3238
  Apply the procedure 'store_top_level_join_columns' to each of the
3239
  top-level table referencs of the FROM clause. Adjust the list of tables
3240
  for name resolution - context->first_name_resolution_table to the
3241
  top-most, lef-most NATURAL/USING join.
1 by brian
clean slate
3242
3243
  IMPLEMENTATION
1046 by Brian Aker
Merge Jay.
3244
  Notice that the table references in 'from_clause' are in reverse
3245
  order, thus when we iterate over it, we are moving from the right
3246
  to the left in the FROM clause.
1 by brian
clean slate
3247
3248
  RETURN
1046 by Brian Aker
Merge Jay.
3249
  true   Error
3250
  false  OK
1 by brian
clean slate
3251
*/
520.1.22 by Brian Aker
Second pass of thd cleanup
3252
static bool setup_natural_join_row_types(Session *session,
327.2.4 by Brian Aker
Refactoring table.h
3253
                                         List<TableList> *from_clause,
1 by brian
clean slate
3254
                                         Name_resolution_context *context)
3255
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3256
  session->where= "from clause";
1 by brian
clean slate
3257
  if (from_clause->elements == 0)
55 by brian
Update for using real bool types.
3258
    return false; /* We come here in the case of UNIONs. */
1 by brian
clean slate
3259
327.2.4 by Brian Aker
Refactoring table.h
3260
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3261
  TableList *table_ref; /* Current table reference. */
1 by brian
clean slate
3262
  /* Table reference to the left of the current. */
327.2.4 by Brian Aker
Refactoring table.h
3263
  TableList *left_neighbor;
1 by brian
clean slate
3264
  /* Table reference to the right of the current. */
327.2.4 by Brian Aker
Refactoring table.h
3265
  TableList *right_neighbor= NULL;
1 by brian
clean slate
3266
3267
  /* Note that tables in the list are in reversed order */
3268
  for (left_neighbor= table_ref_it++; left_neighbor ; )
3269
  {
3270
    table_ref= left_neighbor;
3271
    left_neighbor= table_ref_it++;
520.1.22 by Brian Aker
Second pass of thd cleanup
3272
    if (store_top_level_join_columns(session, table_ref,
404 by Brian Aker
Removed dead variable
3273
                                     left_neighbor, right_neighbor))
3274
      return true;
3275
    if (left_neighbor)
1 by brian
clean slate
3276
    {
404 by Brian Aker
Removed dead variable
3277
      TableList *first_leaf_on_the_right;
3278
      first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
3279
      left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
1 by brian
clean slate
3280
    }
3281
    right_neighbor= table_ref;
3282
  }
3283
3284
  /*
3285
    Store the top-most, left-most NATURAL/USING join, so that we start
3286
    the search from that one instead of context->table_list. At this point
3287
    right_neighbor points to the left-most top-level table reference in the
3288
    FROM clause.
3289
  */
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3290
  assert(right_neighbor);
1 by brian
clean slate
3291
  context->first_name_resolution_table=
3292
    right_neighbor->first_leaf_for_name_resolution();
3293
55 by brian
Update for using real bool types.
3294
  return false;
1 by brian
clean slate
3295
}
3296
3297
3298
/****************************************************************************
1046 by Brian Aker
Merge Jay.
3299
 ** Expand all '*' in given fields
3300
 ****************************************************************************/
1 by brian
clean slate
3301
1034.1.7 by Brian Aker
Remove dead bits to the end of functions.
3302
int setup_wild(Session *session, List<Item> &fields,
77.1.45 by Monty Taylor
Warning fixes.
3303
               List<Item> *sum_func_list,
482 by Brian Aker
Remove uint.
3304
               uint32_t wild_num)
1 by brian
clean slate
3305
{
3306
  if (!wild_num)
1034.1.7 by Brian Aker
Remove dead bits to the end of functions.
3307
    return 0;
1 by brian
clean slate
3308
3309
  Item *item;
3310
  List_iterator<Item> it(fields);
3311
520.1.22 by Brian Aker
Second pass of thd cleanup
3312
  session->lex->current_select->cur_pos_in_select_list= 0;
1 by brian
clean slate
3313
  while (wild_num && (item= it++))
3314
  {
3315
    if (item->type() == Item::FIELD_ITEM &&
3316
        ((Item_field*) item)->field_name &&
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
3317
        ((Item_field*) item)->field_name[0] == '*' &&
3318
        !((Item_field*) item)->field)
1 by brian
clean slate
3319
    {
482 by Brian Aker
Remove uint.
3320
      uint32_t elem= fields.elements;
1 by brian
clean slate
3321
      bool any_privileges= ((Item_field *) item)->any_privileges;
520.1.22 by Brian Aker
Second pass of thd cleanup
3322
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
1 by brian
clean slate
3323
      if (subsel &&
3324
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3325
      {
3326
        /*
3327
          It is EXISTS(SELECT * ...) and we can replace * by any constant.
3328
3329
          Item_int do not need fix_fields() because it is basic constant.
3330
        */
152 by Brian Aker
longlong replacement
3331
        it.replace(new Item_int("Not_used", (int64_t) 1,
1 by brian
clean slate
3332
                                MY_INT64_NUM_DECIMAL_DIGITS));
3333
      }
520.1.22 by Brian Aker
Second pass of thd cleanup
3334
      else if (insert_fields(session, ((Item_field*) item)->context,
1 by brian
clean slate
3335
                             ((Item_field*) item)->db_name,
3336
                             ((Item_field*) item)->table_name, &it,
3337
                             any_privileges))
3338
      {
1046.1.10 by Brian Aker
Formatting around return (style)
3339
        return -1;
1 by brian
clean slate
3340
      }
3341
      if (sum_func_list)
3342
      {
1039.2.8 by Jay Pipes
Yet more indentation and style cleanup
3343
        /*
3344
          sum_func_list is a list that has the fields list as a tail.
3345
          Because of this we have to update the element count also for this
3346
          list after expanding the '*' entry.
3347
        */
3348
        sum_func_list->elements+= fields.elements - elem;
1 by brian
clean slate
3349
      }
3350
      wild_num--;
3351
    }
3352
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
3353
      session->lex->current_select->cur_pos_in_select_list++;
1 by brian
clean slate
3354
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3355
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
3356
1046.1.10 by Brian Aker
Formatting around return (style)
3357
  return 0;
1 by brian
clean slate
3358
}
3359
3360
/****************************************************************************
1046 by Brian Aker
Merge Jay.
3361
 ** Check that all given fields exists and fill struct with current data
3362
 ****************************************************************************/
1 by brian
clean slate
3363
520.1.22 by Brian Aker
Second pass of thd cleanup
3364
bool setup_fields(Session *session, Item **ref_pointer_array,
1 by brian
clean slate
3365
                  List<Item> &fields, enum_mark_columns mark_used_columns,
3366
                  List<Item> *sum_func_list, bool allow_sum_func)
3367
{
3368
  register Item *item;
520.1.22 by Brian Aker
Second pass of thd cleanup
3369
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3370
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
1 by brian
clean slate
3371
  List_iterator<Item> it(fields);
3372
  bool save_is_item_list_lookup;
3373
520.1.22 by Brian Aker
Second pass of thd cleanup
3374
  session->mark_used_columns= mark_used_columns;
1 by brian
clean slate
3375
  if (allow_sum_func)
520.1.22 by Brian Aker
Second pass of thd cleanup
3376
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3377
  session->where= Session::DEFAULT_WHERE;
3378
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3379
  session->lex->current_select->is_item_list_lookup= 0;
1 by brian
clean slate
3380
3381
  /*
3382
    To prevent fail on forward lookup we fill it with zerows,
3383
    then if we got pointer on zero after find_item_in_list we will know
3384
    that it is forward lookup.
3385
3386
    There is other way to solve problem: fill array with pointers to list,
3387
    but it will be slower.
3388
1046 by Brian Aker
Merge Jay.
3389
TODO: remove it when (if) we made one list for allfields and
3390
ref_pointer_array
1 by brian
clean slate
3391
  */
3392
  if (ref_pointer_array)
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
3393
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
1 by brian
clean slate
3394
3395
  Item **ref= ref_pointer_array;
520.1.22 by Brian Aker
Second pass of thd cleanup
3396
  session->lex->current_select->cur_pos_in_select_list= 0;
1 by brian
clean slate
3397
  while ((item= it++))
3398
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
3399
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
1 by brian
clean slate
3400
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
3401
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3402
      session->lex->allow_sum_func= save_allow_sum_func;
3403
      session->mark_used_columns= save_mark_used_columns;
971.6.11 by Eric Day
Removed purecov messages.
3404
      return true;
1 by brian
clean slate
3405
    }
3406
    if (ref)
3407
      *(ref++)= item;
3408
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
1046 by Brian Aker
Merge Jay.
3409
        sum_func_list)
520.1.22 by Brian Aker
Second pass of thd cleanup
3410
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3411
    session->used_tables|= item->used_tables();
3412
    session->lex->current_select->cur_pos_in_select_list++;
1 by brian
clean slate
3413
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3414
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3415
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
1 by brian
clean slate
3416
520.1.22 by Brian Aker
Second pass of thd cleanup
3417
  session->lex->allow_sum_func= save_allow_sum_func;
3418
  session->mark_used_columns= save_mark_used_columns;
3419
  return(test(session->is_error()));
1 by brian
clean slate
3420
}
3421
3422
3423
/*
3424
  make list of leaves of join table tree
3425
3426
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3427
  make_leaves_list()
3428
  list    pointer to pointer on list first element
3429
  tables  table list
1 by brian
clean slate
3430
3431
  RETURN pointer on pointer to next_leaf of last element
3432
*/
3433
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
3434
static TableList **make_leaves_list(TableList **list, TableList *tables)
1 by brian
clean slate
3435
{
327.2.4 by Brian Aker
Refactoring table.h
3436
  for (TableList *table= tables; table; table= table->next_local)
1 by brian
clean slate
3437
  {
3438
    {
3439
      *list= table;
3440
      list= &table->next_leaf;
3441
    }
3442
  }
3443
  return list;
3444
}
3445
3446
/*
3447
  prepare tables
3448
3449
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3450
  setup_tables()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3451
  session		  Thread Cursor
1046 by Brian Aker
Merge Jay.
3452
  context       name resolution contest to setup table list there
3453
  from_clause   Top-level list of table references in the FROM clause
3454
  tables	  Table list (select_lex->table_list)
3455
  leaves        List of join table leaves list (select_lex->leaf_tables)
3456
  refresh       It is onle refresh for subquery
3457
  select_insert It is SELECT ... INSERT command
1 by brian
clean slate
3458
3459
  NOTE
1046 by Brian Aker
Merge Jay.
3460
  Check also that the 'used keys' and 'ignored keys' exists and set up the
3461
  table structure accordingly.
3462
  Create a list of leaf tables. For queries with NATURAL/USING JOINs,
3463
  compute the row types of the top most natural/using join table references
3464
  and link these into a list of table references for name resolution.
1 by brian
clean slate
3465
1046 by Brian Aker
Merge Jay.
3466
  This has to be called for all tables that are used by items, as otherwise
3467
  table->map is not set and all Item_field will be regarded as const items.
1 by brian
clean slate
3468
3469
  RETURN
1046 by Brian Aker
Merge Jay.
3470
  false ok;  In this case *map will includes the chosen index
3471
  true  error
1 by brian
clean slate
3472
*/
3473
520.1.22 by Brian Aker
Second pass of thd cleanup
3474
bool setup_tables(Session *session, Name_resolution_context *context,
327.2.4 by Brian Aker
Refactoring table.h
3475
                  List<TableList> *from_clause, TableList *tables,
3476
                  TableList **leaves, bool select_insert)
1 by brian
clean slate
3477
{
482 by Brian Aker
Remove uint.
3478
  uint32_t tablenr= 0;
1 by brian
clean slate
3479
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3480
  assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
1046 by Brian Aker
Merge Jay.
3481
          (context->table_list && context->first_name_resolution_table));
1 by brian
clean slate
3482
  /*
3483
    this is used for INSERT ... SELECT.
3484
    For select we setup tables except first (and its underlying tables)
3485
  */
1034.1.4 by Brian Aker
Fixed TableList to correctly construct (and removed memset() calls in
3486
  TableList *first_select_table= (select_insert ?  tables->next_local: NULL);
3487
1 by brian
clean slate
3488
  if (!(*leaves))
3489
    make_leaves_list(leaves, tables);
3490
327.2.4 by Brian Aker
Refactoring table.h
3491
  TableList *table_list;
1 by brian
clean slate
3492
  for (table_list= *leaves;
3493
       table_list;
3494
       table_list= table_list->next_leaf, tablenr++)
3495
  {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3496
    Table *table= table_list->table;
1 by brian
clean slate
3497
    table->pos_in_table_list= table_list;
3498
    if (first_select_table &&
3499
        table_list->top_table() == first_select_table)
3500
    {
3501
      /* new counting for SELECT of INSERT ... SELECT command */
3502
      first_select_table= 0;
3503
      tablenr= 0;
3504
    }
934.1.1 by Brian Aker
Moved two functions in classes.
3505
    table->setup_table_map(table_list, tablenr);
1 by brian
clean slate
3506
    if (table_list->process_index_hints(table))
1046.1.10 by Brian Aker
Formatting around return (style)
3507
      return 1;
1 by brian
clean slate
3508
  }
3509
  if (tablenr > MAX_TABLES)
3510
  {
3511
    my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
1046.1.10 by Brian Aker
Formatting around return (style)
3512
    return 1;
1 by brian
clean slate
3513
  }
3514
3515
  /* Precompute and store the row types of NATURAL/USING joins. */
520.1.22 by Brian Aker
Second pass of thd cleanup
3516
  if (setup_natural_join_row_types(session, from_clause, context))
1046.1.10 by Brian Aker
Formatting around return (style)
3517
    return 1;
1 by brian
clean slate
3518
1046.1.10 by Brian Aker
Formatting around return (style)
3519
  return 0;
1 by brian
clean slate
3520
}
3521
3522
3523
/*
3524
  prepare tables and check access for the view tables
3525
3526
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3527
  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
3528
  session		  Thread Cursor
1046 by Brian Aker
Merge Jay.
3529
  context       name resolution contest to setup table list there
3530
  from_clause   Top-level list of table references in the FROM clause
3531
  tables	  Table list (select_lex->table_list)
3532
  conds	  Condition of current SELECT (can be changed by VIEW)
3533
  leaves        List of join table leaves list (select_lex->leaf_tables)
3534
  refresh       It is onle refresh for subquery
3535
  select_insert It is SELECT ... INSERT command
3536
  want_access   what access is needed
1 by brian
clean slate
3537
3538
  NOTE
1046 by Brian Aker
Merge Jay.
3539
  a wrapper for check_tables that will also check the resulting
3540
  table leaves list for access to all the tables that belong to a view
1 by brian
clean slate
3541
3542
  RETURN
1046 by Brian Aker
Merge Jay.
3543
  false ok;  In this case *map will include the chosen index
3544
  true  error
1 by brian
clean slate
3545
*/
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3546
bool setup_tables_and_check_access(Session *session,
1 by brian
clean slate
3547
                                   Name_resolution_context *context,
327.2.4 by Brian Aker
Refactoring table.h
3548
                                   List<TableList> *from_clause,
3549
                                   TableList *tables,
3550
                                   TableList **leaves,
1 by brian
clean slate
3551
                                   bool select_insert)
3552
{
327.2.4 by Brian Aker
Refactoring table.h
3553
  TableList *leaves_tmp= NULL;
1 by brian
clean slate
3554
520.1.22 by Brian Aker
Second pass of thd cleanup
3555
  if (setup_tables(session, context, from_clause, tables,
1 by brian
clean slate
3556
                   &leaves_tmp, select_insert))
55 by brian
Update for using real bool types.
3557
    return true;
1 by brian
clean slate
3558
3559
  if (leaves)
3560
    *leaves= leaves_tmp;
3561
55 by brian
Update for using real bool types.
3562
  return false;
1 by brian
clean slate
3563
}
3564
3565
3566
/*
3567
  Drops in all fields instead of current '*' field
3568
3569
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3570
  insert_fields()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3571
  session			Thread Cursor
1046 by Brian Aker
Merge Jay.
3572
  context             Context for name resolution
3573
  db_name		Database name in case of 'database_name.table_name.*'
3574
  table_name		Table name in case of 'table_name.*'
3575
  it			Pointer to '*'
3576
  any_privileges	0 If we should ensure that we have SELECT privileges
3577
  for all columns
3578
  1 If any privilege is ok
1 by brian
clean slate
3579
  RETURN
1046 by Brian Aker
Merge Jay.
3580
  0	ok     'it' is updated to point at last inserted
3581
  1	error.  Error message is generated but not sent to client
1 by brian
clean slate
3582
*/
3583
3584
bool
520.1.22 by Brian Aker
Second pass of thd cleanup
3585
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
77.1.45 by Monty Taylor
Warning fixes.
3586
              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.
3587
              bool )
1 by brian
clean slate
3588
{
3589
  Field_iterator_table_ref field_iterator;
3590
  bool found;
3591
  char name_buff[NAME_LEN+1];
3592
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
3593
  if (db_name)
1 by brian
clean slate
3594
  {
3595
    /*
3596
      convert database to lower case for comparison
3597
      We can't do this in Item_field as this would change the
3598
      'name' of the item which may be used in the select list
3599
    */
629.5.3 by Toru Maesaka
Third pass of replacing MySQL's strmake() with libc calls
3600
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
1 by brian
clean slate
3601
    my_casedn_str(files_charset_info, name_buff);
3602
    db_name= name_buff;
3603
  }
3604
55 by brian
Update for using real bool types.
3605
  found= false;
1 by brian
clean slate
3606
3607
  /*
3608
    If table names are qualified, then loop over all tables used in the query,
3609
    else treat natural joins as leaves and do not iterate over their underlying
3610
    tables.
3611
  */
327.2.4 by Brian Aker
Refactoring table.h
3612
  for (TableList *tables= (table_name ? context->table_list :
1046 by Brian Aker
Merge Jay.
3613
                           context->first_name_resolution_table);
1 by brian
clean slate
3614
       tables;
3615
       tables= (table_name ? tables->next_local :
3616
                tables->next_name_resolution_table)
1046 by Brian Aker
Merge Jay.
3617
      )
1 by brian
clean slate
3618
  {
3619
    Field *field;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3620
    Table *table= tables->table;
1 by brian
clean slate
3621
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3622
    assert(tables->is_leaf_for_name_resolution());
1 by brian
clean slate
3623
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3624
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
1874.1.1 by Brian Aker
Encapsulate schema_name it table_list.
3625
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
1 by brian
clean slate
3626
      continue;
3627
3628
    /*
3629
      Update the tables used in the query based on the referenced fields. For
3630
      views and natural joins this update is performed inside the loop below.
3631
    */
3632
    if (table)
520.1.22 by Brian Aker
Second pass of thd cleanup
3633
      session->used_tables|= table->map;
1 by brian
clean slate
3634
3635
    /*
3636
      Initialize a generic field iterator for the current table reference.
3637
      Notice that it is guaranteed that this iterator will iterate over the
3638
      fields of a single table reference, because 'tables' is a leaf (for
3639
      name resolution purposes).
3640
    */
3641
    field_iterator.set(tables);
3642
3643
    for (; !field_iterator.end_of_fields(); field_iterator.next())
3644
    {
3645
      Item *item;
3646
520.1.22 by Brian Aker
Second pass of thd cleanup
3647
      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
3648
        return true;
1 by brian
clean slate
3649
3650
      if (!found)
3651
      {
55 by brian
Update for using real bool types.
3652
        found= true;
1 by brian
clean slate
3653
        it->replace(item); /* Replace '*' with the first found item. */
3654
      }
3655
      else
3656
        it->after(item);   /* Add 'item' to the SELECT list. */
3657
3658
      if ((field= field_iterator.field()))
3659
      {
3660
        /* Mark fields as used to allow storage engine to optimze access */
1660.1.3 by Brian Aker
Encapsulate Table in field
3661
        field->getTable()->setReadSet(field->field_index);
1 by brian
clean slate
3662
        if (table)
3663
        {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3664
          table->covering_keys&= field->part_of_key;
3665
          table->merge_keys|= field->part_of_key;
1 by brian
clean slate
3666
        }
3667
        if (tables->is_natural_join)
3668
        {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3669
          Table *field_table;
1 by brian
clean slate
3670
          /*
3671
            In this case we are sure that the column ref will not be created
3672
            because it was already created and stored with the natural join.
3673
          */
3674
          Natural_join_column *nj_col;
3675
          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
3676
            return true;
51.1.48 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
3677
          assert(nj_col->table_field);
1 by brian
clean slate
3678
          field_table= nj_col->table_ref->table;
3679
          if (field_table)
3680
          {
520.1.22 by Brian Aker
Second pass of thd cleanup
3681
            session->used_tables|= field_table->map;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3682
            field_table->covering_keys&= field->part_of_key;
3683
            field_table->merge_keys|= field->part_of_key;
1 by brian
clean slate
3684
            field_table->used_fields++;
3685
          }
3686
        }
3687
      }
3688
      else
520.1.22 by Brian Aker
Second pass of thd cleanup
3689
        session->used_tables|= item->used_tables();
3690
      session->lex->current_select->cur_pos_in_select_list++;
1 by brian
clean slate
3691
    }
3692
    /*
3693
      In case of stored tables, all fields are considered as used,
3694
      while in the case of views, the fields considered as used are the
3695
      ones marked in setup_tables during fix_fields of view columns.
3696
      For NATURAL joins, used_tables is updated in the IF above.
3697
    */
3698
    if (table)
1578.2.10 by Brian Aker
keys and fields partial encapsulation.
3699
      table->used_fields= table->getShare()->sizeFields();
1 by brian
clean slate
3700
  }
3701
  if (found)
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
3702
    return false;
1 by brian
clean slate
3703
3704
  /*
1273.19.1 by Brian Aker
Update for show fields.
3705
    @TODO in the case when we skipped all columns because there was a
3706
    qualified '*', and all columns were coalesced, we have to give a more
3707
    meaningful message than ER_BAD_TABLE_ERROR.
1 by brian
clean slate
3708
  */
3709
  if (!table_name)
3710
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3711
  else
3712
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3713
1046.1.9 by Brian Aker
Remove caller that wasn't correctly locking, and reverted code to 5.1
3714
  return true;
1 by brian
clean slate
3715
}
3716
3717
3718
/*
3719
  Fix all conditions and outer join expressions.
3720
3721
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3722
  setup_conds()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3723
  session     thread Cursor
1046 by Brian Aker
Merge Jay.
3724
  tables  list of tables for name resolving (select_lex->table_list)
3725
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
3726
  conds   WHERE clause
1 by brian
clean slate
3727
3728
  DESCRIPTION
1046 by Brian Aker
Merge Jay.
3729
  TODO
1 by brian
clean slate
3730
3731
  RETURN
1046 by Brian Aker
Merge Jay.
3732
  true  if some error occured (e.g. out of memory)
3733
  false if all is OK
1 by brian
clean slate
3734
*/
3735
1109.1.5 by Brian Aker
More extraction from sql_base
3736
int Session::setup_conds(TableList *leaves, COND **conds)
1 by brian
clean slate
3737
{
1109.1.5 by Brian Aker
More extraction from sql_base
3738
  Session *session= this;
846 by Brian Aker
Removing on typedeffed class.
3739
  Select_Lex *select_lex= session->lex->current_select;
327.2.4 by Brian Aker
Refactoring table.h
3740
  TableList *table= NULL;	// For HP compilers
520.1.22 by Brian Aker
Second pass of thd cleanup
3741
  void *save_session_marker= session->session_marker;
1 by brian
clean slate
3742
  /*
846 by Brian Aker
Removing on typedeffed class.
3743
    it_is_update set to true when tables of primary Select_Lex (Select_Lex
1 by brian
clean slate
3744
    which belong to LEX, i.e. most up SELECT) will be updated by
3745
    INSERT/UPDATE/LOAD
1046.1.10 by Brian Aker
Formatting around return (style)
3746
    NOTE-> using this condition helps to prevent call of prepare_check_option()
3747
    from subquery of VIEW, because tables of subquery belongs to VIEW
3748
    (see condition before prepare_check_option() call)
1 by brian
clean slate
3749
  */
3750
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
3751
  select_lex->is_item_list_lookup= 0;
3752
520.1.22 by Brian Aker
Second pass of thd cleanup
3753
  session->mark_used_columns= MARK_COLUMNS_READ;
1 by brian
clean slate
3754
  select_lex->cond_count= 0;
3755
  select_lex->between_count= 0;
3756
  select_lex->max_equal_elems= 0;
3757
520.1.22 by Brian Aker
Second pass of thd cleanup
3758
  session->session_marker= (void*)1;
1 by brian
clean slate
3759
  if (*conds)
3760
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
3761
    session->where="where clause";
3762
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
1046 by Brian Aker
Merge Jay.
3763
        (*conds)->check_cols(1))
1 by brian
clean slate
3764
      goto err_no_arena;
3765
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3766
  session->session_marker= save_session_marker;
1 by brian
clean slate
3767
3768
  /*
3769
    Apply fix_fields() to all ON clauses at all levels of nesting,
3770
    including the ones inside view definitions.
3771
  */
3772
  for (table= leaves; table; table= table->next_leaf)
3773
  {
327.2.4 by Brian Aker
Refactoring table.h
3774
    TableList *embedded; /* The table at the current level of nesting. */
3775
    TableList *embedding= table; /* The parent nested table reference. */
1 by brian
clean slate
3776
    do
3777
    {
3778
      embedded= embedding;
3779
      if (embedded->on_expr)
3780
      {
3781
        /* Make a join an a expression */
520.1.22 by Brian Aker
Second pass of thd cleanup
3782
        session->session_marker= (void*)embedded;
3783
        session->where="on clause";
3784
        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
3785
            embedded->on_expr->check_cols(1))
3786
          goto err_no_arena;
1 by brian
clean slate
3787
        select_lex->cond_count++;
3788
      }
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3789
      embedding= embedded->getEmbedding();
1 by brian
clean slate
3790
    }
3791
    while (embedding &&
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
3792
           embedding->getNestedJoin()->join_list.head() == embedded);
1 by brian
clean slate
3793
3794
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3795
  session->session_marker= save_session_marker;
1 by brian
clean slate
3796
520.1.22 by Brian Aker
Second pass of thd cleanup
3797
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3798
  return(test(session->is_error()));
1 by brian
clean slate
3799
3800
err_no_arena:
3801
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
1046.1.10 by Brian Aker
Formatting around return (style)
3802
3803
  return 1;
1 by brian
clean slate
3804
}
3805
3806
3807
/******************************************************************************
1046 by Brian Aker
Merge Jay.
3808
 ** Fill a record with data (for INSERT or UPDATE)
3809
 ** Returns : 1 if some field has wrong type
3810
 ******************************************************************************/
1 by brian
clean slate
3811
3812
3813
/*
3814
  Fill fields with given items.
3815
3816
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3817
  fill_record()
3818
  fields        Item_fields list to be filled
3819
  values        values to fill with
3820
  ignore_errors true if we should ignore errors
1 by brian
clean slate
3821
3822
  NOTE
1046 by Brian Aker
Merge Jay.
3823
  fill_record() may set table->auto_increment_field_not_null and a
3824
  caller should make sure that it is reset after their last call to this
3825
  function.
1 by brian
clean slate
3826
3827
  RETURN
1046 by Brian Aker
Merge Jay.
3828
  false   OK
3829
  true    error occured
1 by brian
clean slate
3830
*/
3831
3832
bool
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3833
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
1 by brian
clean slate
3834
{
3835
  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
3836
  Item *value;
1 by brian
clean slate
3837
  Item_field *field;
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3838
  Table *table;
1 by brian
clean slate
3839
3840
  /*
3841
    Reset the table->auto_increment_field_not_null as it is valid for
3842
    only one row.
3843
  */
3844
  if (fields.elements)
3845
  {
3846
    /*
3847
      On INSERT or UPDATE fields are checked to be from the same table,
3848
      thus we safely can take table from the first field.
3849
    */
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3850
    field= static_cast<Item_field *>(f++);
1660.1.3 by Brian Aker
Encapsulate Table in field
3851
    table= field->field->getTable();
55 by brian
Update for using real bool types.
3852
    table->auto_increment_field_not_null= false;
1 by brian
clean slate
3853
    f.rewind();
3854
  }
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3855
3856
  while ((field= static_cast<Item_field *>(f++)))
1 by brian
clean slate
3857
  {
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3858
    value= v++;
3859
1 by brian
clean slate
3860
    Field *rfield= field->field;
1660.1.3 by Brian Aker
Encapsulate Table in field
3861
    table= rfield->getTable();
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3862
1 by brian
clean slate
3863
    if (rfield == table->next_number_field)
55 by brian
Update for using real bool types.
3864
      table->auto_increment_field_not_null= true;
1 by brian
clean slate
3865
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
    {
3867
      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
3868
      if (table)
3869
        table->auto_increment_field_not_null= false;
3870
3871
      return true;
1 by brian
clean slate
3872
    }
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3873
  }
3874
3875
  return session->is_error();
1 by brian
clean slate
3876
}
3877
3878
3879
/*
3880
  Fill field buffer with values from Field list
3881
3882
  SYNOPSIS
1046 by Brian Aker
Merge Jay.
3883
  fill_record()
3884
  ptr           pointer on pointer to record
3885
  values        list of fields
3886
  ignore_errors true if we should ignore errors
1 by brian
clean slate
3887
3888
  NOTE
1046 by Brian Aker
Merge Jay.
3889
  fill_record() may set table->auto_increment_field_not_null and a
3890
  caller should make sure that it is reset after their last call to this
3891
  function.
1 by brian
clean slate
3892
3893
  RETURN
1046 by Brian Aker
Merge Jay.
3894
  false   OK
3895
  true    error occured
1 by brian
clean slate
3896
*/
3897
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3898
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
1 by brian
clean slate
3899
{
3900
  List_iterator_fast<Item> v(values);
3901
  Item *value;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3902
  Table *table= 0;
1 by brian
clean slate
3903
  Field *field;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3904
1 by brian
clean slate
3905
  /*
3906
    Reset the table->auto_increment_field_not_null as it is valid for
3907
    only one row.
3908
  */
3909
  if (*ptr)
3910
  {
3911
    /*
3912
      On INSERT or UPDATE fields are checked to be from the same table,
3913
      thus we safely can take table from the first field.
3914
    */
1660.1.3 by Brian Aker
Encapsulate Table in field
3915
    table= (*ptr)->getTable();
55 by brian
Update for using real bool types.
3916
    table->auto_increment_field_not_null= false;
1 by brian
clean slate
3917
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3918
  while ((field = *ptr++) && ! session->is_error())
1 by brian
clean slate
3919
  {
3920
    value=v++;
1660.1.3 by Brian Aker
Encapsulate Table in field
3921
    table= field->getTable();
1 by brian
clean slate
3922
    if (field == table->next_number_field)
55 by brian
Update for using real bool types.
3923
      table->auto_increment_field_not_null= true;
1 by brian
clean slate
3924
    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
3925
    {
3926
      if (table)
3927
        table->auto_increment_field_not_null= false;
3928
3929
      return true;
3930
    }
1235.1.10 by Brian Aker
Cleaned up the update call (I noticed that there were still update view code
3931
  }
3932
520.1.22 by Brian Aker
Second pass of thd cleanup
3933
  return(session->is_error());
1 by brian
clean slate
3934
}
3935
3936
1130.1.12 by Monty Taylor
Moved service stuff into plugin/
3937
bool drizzle_rm_tmp_tables()
1 by brian
clean slate
3938
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3939
  Session *session;
1 by brian
clean slate
3940
1556.1.1 by Brian Aker
Updates for moving temporary directory.
3941
  assert(drizzle_tmpdir.size());
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3942
1130.1.12 by Monty Taylor
Moved service stuff into plugin/
3943
  if (!(session= new Session(plugin::Listen::getNullClient())))
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3944
    return true;
520.1.22 by Brian Aker
Second pass of thd cleanup
3945
  session->thread_stack= (char*) &session;
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.
3946
  session->storeGlobals();
1 by brian
clean slate
3947
1556.1.1 by Brian Aker
Updates for moving temporary directory.
3948
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3949
520.1.22 by Brian Aker
Second pass of thd cleanup
3950
  delete session;
680 by Brian Aker
Remove locks around temp tables for searching tmp directory path.
3951
3952
  return false;
1 by brian
clean slate
3953
}
3954
3955
3956
3957
/*****************************************************************************
1046 by Brian Aker
Merge Jay.
3958
  unireg support functions
3959
 *****************************************************************************/
1 by brian
clean slate
3960
1877.2.8 by Brian Aker
Additional encapsulation
3961
1 by brian
clean slate
3962
3963
3964
/**
3965
  @} (end of group Data_Dictionary)
3966
*/
575.4.7 by Monty Taylor
More header cleanup.
3967
3968
void kill_drizzle(void)
3969
{
3970
  pthread_kill(signal_thread, SIGTERM);
929.1.6 by Brian Aker
Pushing thread attribute for threads down to engine.
3971
  shutdown_in_progress= 1;			// Safety if kill didn't work
575.4.7 by Monty Taylor
More header cleanup.
3972
}
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
3973
3974
} /* namespace drizzled */