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