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