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