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