~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/sql_base.cc

  • Committer: brian
  • Date: 2008-06-25 05:29:13 UTC
  • Revision ID: brian@localhost.localdomain-20080625052913-6upwo0jsrl4lnapl
clean slate

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* Copyright (C) 2000-2006 MySQL AB
2
2
 
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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
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 */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
18
 
#include "config.h"
19
 
#include <assert.h>
20
 
 
21
 
#include <signal.h>
22
 
 
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
33
 
#include "drizzled/internal/my_pthread.h"
34
 
#include "drizzled/internal/thread_var.h"
35
 
 
36
 
#include <drizzled/sql_select.h>
37
 
#include <drizzled/error.h>
38
 
#include <drizzled/gettext.h>
39
 
#include <drizzled/nested_join.h>
40
 
#include <drizzled/sql_base.h>
41
 
#include <drizzled/show.h>
42
 
#include <drizzled/item/cmpfunc.h>
43
 
#include <drizzled/replication_services.h>
44
 
#include <drizzled/check_stack_overrun.h>
45
 
#include <drizzled/lock.h>
46
 
#include <drizzled/plugin/listen.h>
47
 
#include "drizzled/cached_directory.h"
48
 
#include <drizzled/field/timestamp.h>
49
 
#include <drizzled/field/null.h>
50
 
#include "drizzled/sql_table.h"
51
 
#include "drizzled/global_charset_info.h"
52
 
#include "drizzled/pthread_globals.h"
53
 
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
 
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
59
 
 
60
 
using namespace std;
61
 
 
62
 
namespace drizzled
 
18
 
 
19
#include "mysql_priv.h"
 
20
#include "sql_select.h"
 
21
#include <m_ctype.h>
 
22
#include <my_dir.h>
 
23
#include <hash.h>
 
24
 
 
25
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
 
26
 
 
27
/**
 
28
  @defgroup Data_Dictionary Data Dictionary
 
29
  @{
 
30
*/
 
31
TABLE *unused_tables;                           /* Used by mysql_test */
 
32
HASH open_cache;                                /* Used by mysql_test */
 
33
static HASH table_def_cache;
 
34
static TABLE_SHARE *oldest_unused_share, end_of_unused_share;
 
35
static pthread_mutex_t LOCK_table_share;
 
36
static bool table_def_inited= 0;
 
37
 
 
38
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
 
39
                             const char *alias,
 
40
                             char *cache_key, uint cache_key_length,
 
41
                             MEM_ROOT *mem_root, uint flags);
 
42
static void free_cache_entry(TABLE *entry);
 
43
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
 
44
                                 bool send_refresh);
 
45
 
 
46
 
 
47
extern "C" uchar *table_cache_key(const uchar *record, size_t *length,
 
48
                                 my_bool not_used __attribute__((unused)))
63
49
{
 
50
  TABLE *entry=(TABLE*) record;
 
51
  *length= entry->s->table_cache_key.length;
 
52
  return (uchar*) entry->s->table_cache_key.str;
 
53
}
64
54
 
65
 
extern bool volatile shutdown_in_progress;
66
55
 
67
56
bool table_cache_init(void)
68
57
{
69
 
  return false;
70
 
}
71
 
 
72
 
uint32_t cached_open_tables(void)
73
 
{
74
 
  return table::getCache().size();
 
58
  return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
 
59
                   0, 0, table_cache_key,
 
60
                   (hash_free_key) free_cache_entry, 0) != 0;
75
61
}
76
62
 
77
63
void table_cache_free(void)
78
64
{
79
 
  refresh_version++;                            // Force close of open tables
80
 
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
83
 
}
84
 
 
85
 
/*
86
 
  Close cursor handle, but leave the table in the table cache
87
 
 
88
 
  SYNOPSIS
89
 
  close_handle_and_leave_table_as_lock()
90
 
  table         Table Cursor
91
 
 
92
 
  NOTES
93
 
  By leaving the table in the table cache, it disallows any other thread
94
 
  to open the table
95
 
 
96
 
  session->getKilled() will be set if we run out of memory
97
 
 
98
 
  If closing a MERGE child, the calling function has to take care for
99
 
  closing the parent too, if necessary.
100
 
*/
101
 
 
102
 
 
103
 
void close_handle_and_leave_table_as_lock(Table *table)
104
 
{
105
 
  assert(table->db_stat);
106
 
  assert(table->getShare()->getType() == message::Table::STANDARD);
 
65
  DBUG_ENTER("table_cache_free");
 
66
  if (table_def_inited)
 
67
  {
 
68
    close_cached_tables(NULL, NULL, FALSE, FALSE, FALSE);
 
69
    if (!open_cache.records)                    // Safety first
 
70
      hash_free(&open_cache);
 
71
  }
 
72
  DBUG_VOID_RETURN;
 
73
}
 
74
 
 
75
uint cached_open_tables(void)
 
76
{
 
77
  return open_cache.records;
 
78
}
 
79
 
 
80
 
 
81
#ifdef EXTRA_DEBUG
 
82
static void check_unused(void)
 
83
{
 
84
  uint count= 0, open_files= 0, idx= 0;
 
85
  TABLE *cur_link,*start_link;
 
86
 
 
87
  if ((start_link=cur_link=unused_tables))
 
88
  {
 
89
    do
 
90
    {
 
91
      if (cur_link != cur_link->next->prev || cur_link != cur_link->prev->next)
 
92
      {
 
93
        DBUG_PRINT("error",("Unused_links aren't linked properly")); /* purecov: inspected */
 
94
        return; /* purecov: inspected */
 
95
      }
 
96
    } while (count++ < open_cache.records &&
 
97
             (cur_link=cur_link->next) != start_link);
 
98
    if (cur_link != start_link)
 
99
    {
 
100
      DBUG_PRINT("error",("Unused_links aren't connected")); /* purecov: inspected */
 
101
    }
 
102
  }
 
103
  for (idx=0 ; idx < open_cache.records ; idx++)
 
104
  {
 
105
    TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
 
106
    if (!entry->in_use)
 
107
      count--;
 
108
    if (entry->file)
 
109
      open_files++;
 
110
  }
 
111
  if (count != 0)
 
112
  {
 
113
    DBUG_PRINT("error",("Unused_links doesn't match open_cache: diff: %d", /* purecov: inspected */
 
114
                        count)); /* purecov: inspected */
 
115
  }
 
116
 
 
117
#ifdef NOT_SAFE_FOR_REPAIR
 
118
  /*
 
119
    check that open cache and table definition cache has same number of
 
120
    aktive tables
 
121
  */
 
122
  count= 0;
 
123
  for (idx=0 ; idx < table_def_cache.records ; idx++)
 
124
  {
 
125
    TABLE_SHARE *entry= (TABLE_SHARE*) hash_element(&table_def_cache,idx);
 
126
    count+= entry->ref_count;
 
127
  }
 
128
  if (count != open_files)
 
129
  {
 
130
    DBUG_PRINT("error", ("table_def ref_count: %u  open_cache: %u",
 
131
                         count, open_files));
 
132
    DBUG_ASSERT(count == open_files);
 
133
  }
 
134
#endif
 
135
}
 
136
#else
 
137
#define check_unused()
 
138
#endif
 
139
 
 
140
 
 
141
/*
 
142
  Create a table cache key
 
143
 
 
144
  SYNOPSIS
 
145
    create_table_def_key()
 
146
    thd                 Thread handler
 
147
    key                 Create key here (must be of size MAX_DBKEY_LENGTH)
 
148
    table_list          Table definition
 
149
    tmp_table           Set if table is a tmp table
 
150
 
 
151
 IMPLEMENTATION
 
152
    The table cache_key is created from:
 
153
    db_name + \0
 
154
    table_name + \0
 
155
 
 
156
    if the table is a tmp table, we add the following to make each tmp table
 
157
    unique on the slave:
 
158
 
 
159
    4 bytes for master thread id
 
160
    4 bytes pseudo thread id
 
161
 
 
162
  RETURN
 
163
    Length of key
 
164
*/
 
165
 
 
166
uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
 
167
                          bool tmp_table)
 
168
{
 
169
  uint key_length= (uint) (strmov(strmov(key, table_list->db)+1,
 
170
                                  table_list->table_name)-key)+1;
 
171
  if (tmp_table)
 
172
  {
 
173
    int4store(key + key_length, thd->server_id);
 
174
    int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
 
175
    key_length+= TMP_TABLE_KEY_EXTRA;
 
176
  }
 
177
  return key_length;
 
178
}
 
179
 
 
180
 
 
181
 
 
182
/*****************************************************************************
 
183
  Functions to handle table definition cach (TABLE_SHARE)
 
184
*****************************************************************************/
 
185
 
 
186
extern "C" uchar *table_def_key(const uchar *record, size_t *length,
 
187
                               my_bool not_used __attribute__((unused)))
 
188
{
 
189
  TABLE_SHARE *entry=(TABLE_SHARE*) record;
 
190
  *length= entry->table_cache_key.length;
 
191
  return (uchar*) entry->table_cache_key.str;
 
192
}
 
193
 
 
194
 
 
195
static void table_def_free_entry(TABLE_SHARE *share)
 
196
{
 
197
  DBUG_ENTER("table_def_free_entry");
 
198
  if (share->prev)
 
199
  {
 
200
    /* remove from old_unused_share list */
 
201
    pthread_mutex_lock(&LOCK_table_share);
 
202
    *share->prev= share->next;
 
203
    share->next->prev= share->prev;
 
204
    pthread_mutex_unlock(&LOCK_table_share);
 
205
  }
 
206
  free_table_share(share);
 
207
  DBUG_VOID_RETURN;
 
208
}
 
209
 
 
210
 
 
211
bool table_def_init(void)
 
212
{
 
213
  table_def_inited= 1;
 
214
  pthread_mutex_init(&LOCK_table_share, MY_MUTEX_INIT_FAST);
 
215
  oldest_unused_share= &end_of_unused_share;
 
216
  end_of_unused_share.prev= &oldest_unused_share;
 
217
 
 
218
  return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
 
219
                   0, 0, table_def_key,
 
220
                   (hash_free_key) table_def_free_entry, 0) != 0;
 
221
}
 
222
 
 
223
 
 
224
void table_def_free(void)
 
225
{
 
226
  DBUG_ENTER("table_def_free");
 
227
  if (table_def_inited)
 
228
  {
 
229
    table_def_inited= 0;
 
230
    pthread_mutex_destroy(&LOCK_table_share);
 
231
    hash_free(&table_def_cache);
 
232
  }
 
233
  DBUG_VOID_RETURN;
 
234
}
 
235
 
 
236
 
 
237
uint cached_table_definitions(void)
 
238
{
 
239
  return table_def_cache.records;
 
240
}
 
241
 
 
242
 
 
243
/*
 
244
  Get TABLE_SHARE for a table.
 
245
 
 
246
  get_table_share()
 
247
  thd                   Thread handle
 
248
  table_list            Table that should be opened
 
249
  key                   Table cache key
 
250
  key_length            Length of key
 
251
  db_flags              Flags to open_table_def():
 
252
                        OPEN_VIEW
 
253
  error                 out: Error code from open_table_def()
 
254
 
 
255
  IMPLEMENTATION
 
256
    Get a table definition from the table definition cache.
 
257
    If it doesn't exist, create a new from the table definition file.
 
258
 
 
259
  NOTES
 
260
    We must have wrlock on LOCK_open when we come here
 
261
    (To be changed later)
 
262
 
 
263
  RETURN
 
264
   0  Error
 
265
   #  Share for table
 
266
*/
 
267
 
 
268
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
 
269
                             uint key_length, uint db_flags, int *error)
 
270
{
 
271
  TABLE_SHARE *share;
 
272
  DBUG_ENTER("get_table_share");
 
273
 
 
274
  *error= 0;
 
275
 
 
276
  /* Read table definition from cache */
 
277
  if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
 
278
                                         key_length)))
 
279
    goto found;
 
280
 
 
281
  if (!(share= alloc_table_share(table_list, key, key_length)))
 
282
  {
 
283
    DBUG_RETURN(0);
 
284
  }
 
285
 
 
286
  /*
 
287
    Lock mutex to be able to read table definition from file without
 
288
    conflicts
 
289
  */
 
290
  (void) pthread_mutex_lock(&share->mutex);
 
291
 
 
292
  /*
 
293
    We assign a new table id under the protection of the LOCK_open and
 
294
    the share's own mutex.  We do this insted of creating a new mutex
 
295
    and using it for the sole purpose of serializing accesses to a
 
296
    static variable, we assign the table id here.  We assign it to the
 
297
    share before inserting it into the table_def_cache to be really
 
298
    sure that it cannot be read from the cache without having a table
 
299
    id assigned.
 
300
 
 
301
    CAVEAT. This means that the table cannot be used for
 
302
    binlogging/replication purposes, unless get_table_share() has been
 
303
    called directly or indirectly.
 
304
   */
 
305
  assign_new_table_id(share);
 
306
 
 
307
  if (my_hash_insert(&table_def_cache, (uchar*) share))
 
308
  {
 
309
    free_table_share(share);
 
310
    DBUG_RETURN(0);                             // return error
 
311
  }
 
312
  if (open_table_def(thd, share, db_flags))
 
313
  {
 
314
    *error= share->error;
 
315
    (void) hash_delete(&table_def_cache, (uchar*) share);
 
316
    DBUG_RETURN(0);
 
317
  }
 
318
  share->ref_count++;                           // Mark in use
 
319
  DBUG_PRINT("exit", ("share: 0x%lx  ref_count: %u",
 
320
                      (ulong) share, share->ref_count));
 
321
  (void) pthread_mutex_unlock(&share->mutex);
 
322
  DBUG_RETURN(share);
 
323
 
 
324
found:
 
325
  /* 
 
326
     We found an existing table definition. Return it if we didn't get
 
327
     an error when reading the table definition from file.
 
328
  */
 
329
 
 
330
  /* We must do a lock to ensure that the structure is initialized */
 
331
  (void) pthread_mutex_lock(&share->mutex);
 
332
  if (share->error)
 
333
  {
 
334
    /* Table definition contained an error */
 
335
    open_table_error(share, share->error, share->open_errno, share->errarg);
 
336
    (void) pthread_mutex_unlock(&share->mutex);
 
337
    DBUG_RETURN(0);
 
338
  }
 
339
 
 
340
  if (!share->ref_count++ && share->prev)
 
341
  {
 
342
    /*
 
343
      Share was not used before and it was in the old_unused_share list
 
344
      Unlink share from this list
 
345
    */
 
346
    DBUG_PRINT("info", ("Unlinking from not used list"));
 
347
    pthread_mutex_lock(&LOCK_table_share);
 
348
    *share->prev= share->next;
 
349
    share->next->prev= share->prev;
 
350
    share->next= 0;
 
351
    share->prev= 0;
 
352
    pthread_mutex_unlock(&LOCK_table_share);
 
353
  }
 
354
  (void) pthread_mutex_unlock(&share->mutex);
 
355
 
 
356
   /* Free cache if too big */
 
357
  while (table_def_cache.records > table_def_size &&
 
358
         oldest_unused_share->next)
 
359
  {
 
360
    pthread_mutex_lock(&oldest_unused_share->mutex);
 
361
    VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
 
362
  }
 
363
 
 
364
  DBUG_PRINT("exit", ("share: 0x%lx  ref_count: %u",
 
365
                      (ulong) share, share->ref_count));
 
366
  DBUG_RETURN(share);
 
367
}
 
368
 
 
369
 
 
370
/*
 
371
  Get a table share. If it didn't exist, try creating it from engine
 
372
 
 
373
  For arguments and return values, see get_table_from_share()
 
374
*/
 
375
 
 
376
static TABLE_SHARE
 
377
*get_table_share_with_create(THD *thd, TABLE_LIST *table_list,
 
378
                             char *key, uint key_length,
 
379
                             uint db_flags, int *error)
 
380
{
 
381
  TABLE_SHARE *share;
 
382
  int tmp;
 
383
  DBUG_ENTER("get_table_share_with_create");
 
384
 
 
385
  share= get_table_share(thd, table_list, key, key_length, db_flags, error);
 
386
  /*
 
387
    If share is not NULL, we found an existing share.
 
388
 
 
389
    If share is NULL, and there is no error, we're inside
 
390
    pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
 
391
    with the intention to silently drop non-existing tables 
 
392
    from the pre-locking list. In this case we still need to try
 
393
    auto-discover before returning a NULL share.
 
394
 
 
395
    If share is NULL and the error is ER_NO_SUCH_TABLE, this is
 
396
    the same as above, only that the error was not silenced by 
 
397
    pre-locking. Once again, we need to try to auto-discover
 
398
    the share.
 
399
 
 
400
    Finally, if share is still NULL, it's a real error and we need
 
401
    to abort.
 
402
 
 
403
    @todo Rework alternative ways to deal with ER_NO_SUCH TABLE.
 
404
  */
 
405
  if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
 
406
 
 
407
    DBUG_RETURN(share);
 
408
 
 
409
  /* Table didn't exist. Check if some engine can provide it */
 
410
  if ((tmp= ha_create_table_from_engine(thd, table_list->db,
 
411
                                        table_list->table_name)) < 0)
 
412
  {
 
413
    /*
 
414
      No such table in any engine.
 
415
      Hide "Table doesn't exist" errors if the table belongs to a view.
 
416
      The check for thd->is_error() is necessary to not push an
 
417
      unwanted error in case of pre-locking, which silences
 
418
      "no such table" errors.
 
419
      @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
 
420
    */
 
421
    if (thd->is_error() && table_list->belong_to_view)
 
422
    {
 
423
      thd->clear_error();
 
424
      my_error(ER_VIEW_INVALID, MYF(0), "", "");
 
425
    }
 
426
    DBUG_RETURN(0);
 
427
  }
 
428
  if (tmp)
 
429
  {
 
430
    /* Give right error message */
 
431
    thd->clear_error();
 
432
    DBUG_PRINT("error", ("Discovery of %s/%s failed", table_list->db,
 
433
                         table_list->table_name));
 
434
    my_printf_error(ER_UNKNOWN_ERROR,
 
435
                    "Failed to open '%-.64s', error while "
 
436
                    "unpacking from engine",
 
437
                    MYF(0), table_list->table_name);
 
438
    DBUG_RETURN(0);
 
439
  }
 
440
  /* Table existed in engine. Let's open it */
 
441
  mysql_reset_errors(thd, 1);                   // Clear warnings
 
442
  thd->clear_error();                           // Clear error message
 
443
  DBUG_RETURN(get_table_share(thd, table_list, key, key_length,
 
444
                              db_flags, error));
 
445
}
 
446
 
 
447
 
 
448
/* 
 
449
   Mark that we are not using table share anymore.
 
450
 
 
451
   SYNOPSIS
 
452
     release_table_share()
 
453
     share              Table share
 
454
     release_type       How the release should be done:
 
455
                        RELEASE_NORMAL
 
456
                         - Release without checking
 
457
                        RELEASE_WAIT_FOR_DROP
 
458
                         - Don't return until we get a signal that the
 
459
                           table is deleted or the thread is killed.
 
460
 
 
461
   IMPLEMENTATION
 
462
     If ref_count goes to zero and (we have done a refresh or if we have
 
463
     already too many open table shares) then delete the definition.
 
464
 
 
465
     If type == RELEASE_WAIT_FOR_DROP then don't return until we get a signal
 
466
     that the table is deleted or the thread is killed.
 
467
*/
 
468
 
 
469
void release_table_share(TABLE_SHARE *share, enum release_type type)
 
470
{
 
471
  bool to_be_deleted= 0;
 
472
  DBUG_ENTER("release_table_share");
 
473
  DBUG_PRINT("enter",
 
474
             ("share: 0x%lx  table: %s.%s  ref_count: %u  version: %lu",
 
475
              (ulong) share, share->db.str, share->table_name.str,
 
476
              share->ref_count, share->version));
 
477
 
 
478
  safe_mutex_assert_owner(&LOCK_open);
 
479
 
 
480
  pthread_mutex_lock(&share->mutex);
 
481
  if (!--share->ref_count)
 
482
  {
 
483
    if (share->version != refresh_version)
 
484
      to_be_deleted=1;
 
485
    else
 
486
    {
 
487
      /* Link share last in used_table_share list */
 
488
      DBUG_PRINT("info",("moving share to unused list"));
 
489
 
 
490
      DBUG_ASSERT(share->next == 0);
 
491
      pthread_mutex_lock(&LOCK_table_share);
 
492
      share->prev= end_of_unused_share.prev;
 
493
      *end_of_unused_share.prev= share;
 
494
      end_of_unused_share.prev= &share->next;
 
495
      share->next= &end_of_unused_share;
 
496
      pthread_mutex_unlock(&LOCK_table_share);
 
497
 
 
498
      to_be_deleted= (table_def_cache.records > table_def_size);
 
499
    }
 
500
  }
 
501
 
 
502
  if (to_be_deleted)
 
503
  {
 
504
    DBUG_PRINT("info", ("Deleting share"));
 
505
    hash_delete(&table_def_cache, (uchar*) share);
 
506
    DBUG_VOID_RETURN;
 
507
  }
 
508
  pthread_mutex_unlock(&share->mutex);
 
509
  DBUG_VOID_RETURN;
 
510
}
 
511
 
 
512
 
 
513
/*
 
514
  Check if table definition exits in cache
 
515
 
 
516
  SYNOPSIS
 
517
    get_cached_table_share()
 
518
    db                  Database name
 
519
    table_name          Table name
 
520
 
 
521
  RETURN
 
522
    0  Not cached
 
523
    #  TABLE_SHARE for table
 
524
*/
 
525
 
 
526
TABLE_SHARE *get_cached_table_share(const char *db, const char *table_name)
 
527
{
 
528
  char key[NAME_LEN*2+2];
 
529
  TABLE_LIST table_list;
 
530
  uint key_length;
 
531
  safe_mutex_assert_owner(&LOCK_open);
 
532
 
 
533
  table_list.db= (char*) db;
 
534
  table_list.table_name= (char*) table_name;
 
535
  key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
 
536
  return (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key, key_length);
 
537
}  
 
538
 
 
539
 
 
540
/*
 
541
  Close file handle, but leave the table in the table cache
 
542
 
 
543
  SYNOPSIS
 
544
    close_handle_and_leave_table_as_lock()
 
545
    table               Table handler
 
546
 
 
547
  NOTES
 
548
    By leaving the table in the table cache, it disallows any other thread
 
549
    to open the table
 
550
 
 
551
    thd->killed will be set if we run out of memory
 
552
 
 
553
    If closing a MERGE child, the calling function has to take care for
 
554
    closing the parent too, if necessary.
 
555
*/
 
556
 
 
557
 
 
558
void close_handle_and_leave_table_as_lock(TABLE *table)
 
559
{
 
560
  TABLE_SHARE *share, *old_share= table->s;
 
561
  char *key_buff;
 
562
  MEM_ROOT *mem_root= &table->mem_root;
 
563
  DBUG_ENTER("close_handle_and_leave_table_as_lock");
 
564
 
 
565
  DBUG_ASSERT(table->db_stat);
107
566
 
108
567
  /*
109
568
    Make a local copy of the table share and free the current one.
110
569
    This has to be done to ensure that the table share is removed from
111
570
    the table defintion cache as soon as the last instance is removed
112
571
  */
113
 
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
 
  const TableIdentifier::Key &key(identifier.getKey());
115
 
  TableShare *share= new TableShare(identifier.getType(),
116
 
                                    identifier,
117
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
118
 
 
119
 
  table->cursor->close();
120
 
  table->db_stat= 0;                            // Mark cursor closed
121
 
  TableShare::release(table->getMutableShare());
122
 
  table->setShare(share);
123
 
}
124
 
 
 
572
  if (multi_alloc_root(mem_root,
 
573
                       &share, sizeof(*share),
 
574
                       &key_buff, old_share->table_cache_key.length,
 
575
                       NULL))
 
576
  {
 
577
    bzero((char*) share, sizeof(*share));
 
578
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
 
579
                               old_share->table_cache_key.length);
 
580
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
 
581
  }
 
582
 
 
583
  table->file->close();
 
584
  table->db_stat= 0;                            // Mark file closed
 
585
  release_table_share(table->s, RELEASE_NORMAL);
 
586
  table->s= share;
 
587
  table->file->change_table_ptr(table, table->s);
 
588
 
 
589
  DBUG_VOID_RETURN;
 
590
}
 
591
 
 
592
 
 
593
 
 
594
/*
 
595
  Create a list for all open tables matching SQL expression
 
596
 
 
597
  SYNOPSIS
 
598
    list_open_tables()
 
599
    thd                 Thread THD
 
600
    wild                SQL like expression
 
601
 
 
602
  NOTES
 
603
    One gets only a list of tables for which one has any kind of privilege.
 
604
    db and table names are allocated in result struct, so one doesn't need
 
605
    a lock on LOCK_open when traversing the return list.
 
606
 
 
607
  RETURN VALUES
 
608
    NULL        Error (Probably OOM)
 
609
    #           Pointer to list of names of open tables.
 
610
*/
 
611
 
 
612
OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
 
613
{
 
614
  int result = 0;
 
615
  OPEN_TABLE_LIST **start_list, *open_list;
 
616
  TABLE_LIST table_list;
 
617
  DBUG_ENTER("list_open_tables");
 
618
 
 
619
  VOID(pthread_mutex_lock(&LOCK_open));
 
620
  bzero((char*) &table_list,sizeof(table_list));
 
621
  start_list= &open_list;
 
622
  open_list=0;
 
623
 
 
624
  for (uint idx=0 ; result == 0 && idx < open_cache.records; idx++)
 
625
  {
 
626
    OPEN_TABLE_LIST *table;
 
627
    TABLE *entry=(TABLE*) hash_element(&open_cache,idx);
 
628
    TABLE_SHARE *share= entry->s;
 
629
 
 
630
    if (db && my_strcasecmp(system_charset_info, db, share->db.str))
 
631
      continue;
 
632
    if (wild && wild_compare(share->table_name.str, wild, 0))
 
633
      continue;
 
634
 
 
635
    /* Check if user has SELECT privilege for any column in the table */
 
636
    table_list.db=         share->db.str;
 
637
    table_list.table_name= share->table_name.str;
 
638
 
 
639
    /* need to check if we haven't already listed it */
 
640
    for (table= open_list  ; table ; table=table->next)
 
641
    {
 
642
      if (!strcmp(table->table, share->table_name.str) &&
 
643
          !strcmp(table->db,    share->db.str))
 
644
      {
 
645
        if (entry->in_use)
 
646
          table->in_use++;
 
647
        if (entry->locked_by_name)
 
648
          table->locked++;
 
649
        break;
 
650
      }
 
651
    }
 
652
    if (table)
 
653
      continue;
 
654
    if (!(*start_list = (OPEN_TABLE_LIST *)
 
655
          sql_alloc(sizeof(**start_list)+share->table_cache_key.length)))
 
656
    {
 
657
      open_list=0;                              // Out of memory
 
658
      break;
 
659
    }
 
660
    strmov((*start_list)->table=
 
661
           strmov(((*start_list)->db= (char*) ((*start_list)+1)),
 
662
                  share->db.str)+1,
 
663
           share->table_name.str);
 
664
    (*start_list)->in_use= entry->in_use ? 1 : 0;
 
665
    (*start_list)->locked= entry->locked_by_name ? 1 : 0;
 
666
    start_list= &(*start_list)->next;
 
667
    *start_list=0;
 
668
  }
 
669
  VOID(pthread_mutex_unlock(&LOCK_open));
 
670
  DBUG_RETURN(open_list);
 
671
}
125
672
 
126
673
/*****************************************************************************
127
674
 *       Functions to free open table cache
128
675
 ****************************************************************************/
129
676
 
130
677
 
131
 
void Table::intern_close_table()
 
678
void intern_close_table(TABLE *table)
132
679
{                                               // Free all structures
133
 
  free_io_cache();
134
 
  if (cursor)                              // Not true if name lock
 
680
  DBUG_ENTER("intern_close_table");
 
681
  DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx",
 
682
                        table->s ? table->s->db.str : "?",
 
683
                        table->s ? table->s->table_name.str : "?",
 
684
                        (long) table));
 
685
 
 
686
  free_io_cache(table);
 
687
  if (table->file)                              // Not true if name lock
 
688
    VOID(closefrm(table, 1));                   // close file
 
689
  DBUG_VOID_RETURN;
 
690
}
 
691
 
 
692
/*
 
693
  Remove table from the open table cache
 
694
 
 
695
  SYNOPSIS
 
696
    free_cache_entry()
 
697
    table               Table to remove
 
698
 
 
699
  NOTE
 
700
    We need to have a lock on LOCK_open when calling this
 
701
*/
 
702
 
 
703
static void free_cache_entry(TABLE *table)
 
704
{
 
705
  DBUG_ENTER("free_cache_entry");
 
706
 
 
707
  intern_close_table(table);
 
708
  if (!table->in_use)
135
709
  {
136
 
    delete_table(true);                 // close cursor
 
710
    table->next->prev=table->prev;              /* remove from used chain */
 
711
    table->prev->next=table->next;
 
712
    if (table == unused_tables)
 
713
    {
 
714
      unused_tables=unused_tables->next;
 
715
      if (table == unused_tables)
 
716
        unused_tables=0;
 
717
    }
 
718
    check_unused();                             // consisty check
137
719
  }
 
720
  my_free((uchar*) table,MYF(0));
 
721
  DBUG_VOID_RETURN;
138
722
}
139
723
 
140
724
/* Free resources allocated by filesort() and read_record() */
141
725
 
142
 
void Table::free_io_cache()
 
726
void free_io_cache(TABLE *table)
143
727
{
144
 
  if (sort.io_cache)
 
728
  DBUG_ENTER("free_io_cache");
 
729
  if (table->sort.io_cache)
145
730
  {
146
 
    sort.io_cache->close_cached_file();
147
 
    delete sort.io_cache;
148
 
    sort.io_cache= 0;
 
731
    close_cached_file(table->sort.io_cache);
 
732
    my_free((uchar*) table->sort.io_cache,MYF(0));
 
733
    table->sort.io_cache=0;
149
734
  }
 
735
  DBUG_VOID_RETURN;
150
736
}
151
737
 
152
738
 
153
739
/*
154
740
  Close all tables which aren't in use by any thread
155
741
 
156
 
  @param session Thread context (may be NULL)
 
742
  @param thd Thread context
157
743
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
744
  @param have_lock If LOCK_open is locked
159
745
  @param wait_for_refresh Wait for a impending flush
160
746
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
 
  won't proceed while write-locked tables are being reopened by other
162
 
  threads.
 
747
         won't proceed while write-locked tables are being reopened by other
 
748
         threads.
163
749
 
164
 
  @remark Session can be NULL, but then wait_for_refresh must be false
165
 
  and tables must be NULL.
 
750
  @remark THD can be NULL, but then wait_for_refresh must be FALSE
 
751
          and tables must be NULL.
166
752
*/
167
753
 
168
 
bool Session::close_cached_tables(TableList *tables, bool wait_for_refresh, bool wait_for_placeholders)
 
754
bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool have_lock,
 
755
                         bool wait_for_refresh, bool wait_for_placeholders)
169
756
{
170
 
  bool result= false;
171
 
  Session *session= this;
 
757
  bool result=0;
 
758
  DBUG_ENTER("close_cached_tables");
 
759
  DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
172
760
 
 
761
  if (!have_lock)
 
762
    VOID(pthread_mutex_lock(&LOCK_open));
 
763
  if (!tables)
173
764
  {
174
 
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
175
 
 
176
 
    if (tables == NULL)
177
 
    {
178
 
      refresh_version++;                                // Force close of open tables
179
 
 
180
 
      table::getUnused().clear();
181
 
 
182
 
      if (wait_for_refresh)
183
 
      {
184
 
        /*
185
 
          Other threads could wait in a loop in open_and_lock_tables(),
186
 
          trying to lock one or more of our tables.
187
 
 
188
 
          If they wait for the locks in thr_multi_lock(), their lock
189
 
          request is aborted. They loop in open_and_lock_tables() and
190
 
          enter open_table(). Here they notice the table is refreshed and
191
 
          wait for COND_refresh. Then they loop again in
192
 
          openTablesLock() and this time open_table() succeeds. At
193
 
          this moment, if we (the FLUSH TABLES thread) are scheduled and
194
 
          on another FLUSH TABLES enter close_cached_tables(), they could
195
 
          awake while we sleep below, waiting for others threads (us) to
196
 
          close their open tables. If this happens, the other threads
197
 
          would find the tables unlocked. They would get the locks, one
198
 
          after the other, and could do their destructive work. This is an
199
 
          issue if we have LOCK TABLES in effect.
200
 
 
201
 
          The problem is that the other threads passed all checks in
202
 
          open_table() before we refresh the table.
203
 
 
204
 
          The fix for this problem is to set some_tables_deleted for all
205
 
          threads with open tables. These threads can still get their
206
 
          locks, but will immediately release them again after checking
207
 
          this variable. They will then loop in openTablesLock()
208
 
          again. There they will wait until we update all tables version
209
 
          below.
210
 
 
211
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
212
 
          in the other branch.
213
 
 
214
 
          In other words (reviewer suggestion): You need this setting of
215
 
          some_tables_deleted for the case when table was opened and all
216
 
          related checks were passed before incrementing refresh_version
217
 
          (which you already have) but attempt to lock the table happened
218
 
          after the call to Session::close_old_data_files() i.e. after removal of
219
 
          current thread locks.
220
 
        */
221
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
 
             iter != table::getCache().end();
223
 
             iter++)
224
 
        {
225
 
          Table *table= (*iter).second;
226
 
          if (table->in_use)
227
 
            table->in_use->some_tables_deleted= false;
228
 
        }
229
 
      }
230
 
    }
231
 
    else
232
 
    {
233
 
      bool found= false;
234
 
      for (TableList *table= tables; table; table= table->next_local)
235
 
      {
236
 
        TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
 
        if (table::Cache::singleton().removeTable(session, identifier,
238
 
                                    RTFC_OWNED_BY_Session_FLAG))
239
 
        {
240
 
          found= true;
241
 
        }
242
 
      }
243
 
      if (!found)
244
 
        wait_for_refresh= false;                        // Nothing to wait for
245
 
    }
246
 
 
 
765
    refresh_version++;                          // Force close of open tables
 
766
    while (unused_tables)
 
767
    {
 
768
#ifdef EXTRA_DEBUG
 
769
      if (hash_delete(&open_cache,(uchar*) unused_tables))
 
770
        printf("Warning: Couldn't delete open table from hash\n");
 
771
#else
 
772
      VOID(hash_delete(&open_cache,(uchar*) unused_tables));
 
773
#endif
 
774
    }
 
775
    /* Free table shares */
 
776
    while (oldest_unused_share->next)
 
777
    {
 
778
      pthread_mutex_lock(&oldest_unused_share->mutex);
 
779
      VOID(hash_delete(&table_def_cache, (uchar*) oldest_unused_share));
 
780
    }
 
781
    DBUG_PRINT("tcache", ("incremented global refresh_version to: %lu",
 
782
                          refresh_version));
247
783
    if (wait_for_refresh)
248
784
    {
249
785
      /*
250
 
        If there is any table that has a lower refresh_version, wait until
251
 
        this is closed (or this thread is killed) before returning
 
786
        Other threads could wait in a loop in open_and_lock_tables(),
 
787
        trying to lock one or more of our tables.
 
788
 
 
789
        If they wait for the locks in thr_multi_lock(), their lock
 
790
        request is aborted. They loop in open_and_lock_tables() and
 
791
        enter open_table(). Here they notice the table is refreshed and
 
792
        wait for COND_refresh. Then they loop again in
 
793
        open_and_lock_tables() and this time open_table() succeeds. At
 
794
        this moment, if we (the FLUSH TABLES thread) are scheduled and
 
795
        on another FLUSH TABLES enter close_cached_tables(), they could
 
796
        awake while we sleep below, waiting for others threads (us) to
 
797
        close their open tables. If this happens, the other threads
 
798
        would find the tables unlocked. They would get the locks, one
 
799
        after the other, and could do their destructive work. This is an
 
800
        issue if we have LOCK TABLES in effect.
 
801
 
 
802
        The problem is that the other threads passed all checks in
 
803
        open_table() before we refresh the table.
 
804
 
 
805
        The fix for this problem is to set some_tables_deleted for all
 
806
        threads with open tables. These threads can still get their
 
807
        locks, but will immediately release them again after checking
 
808
        this variable. They will then loop in open_and_lock_tables()
 
809
        again. There they will wait until we update all tables version
 
810
        below.
 
811
 
 
812
        Setting some_tables_deleted is done by remove_table_from_cache()
 
813
        in the other branch.
 
814
 
 
815
        In other words (reviewer suggestion): You need this setting of
 
816
        some_tables_deleted for the case when table was opened and all
 
817
        related checks were passed before incrementing refresh_version
 
818
        (which you already have) but attempt to lock the table happened
 
819
        after the call to close_old_data_files() i.e. after removal of
 
820
        current thread locks.
252
821
      */
253
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
254
 
      session->mysys_var->current_cond= &COND_refresh;
255
 
      session->set_proc_info("Flushing tables");
256
 
 
257
 
      session->close_old_data_files();
258
 
 
259
 
      bool found= true;
260
 
      /* Wait until all threads has closed all the tables we had locked */
261
 
      while (found && ! session->getKilled())
 
822
      for (uint idx=0 ; idx < open_cache.records ; idx++)
262
823
      {
263
 
        found= false;
264
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
 
             iter != table::getCache().end();
266
 
             iter++)
267
 
        {
268
 
          Table *table= (*iter).second;
269
 
          /* Avoid a self-deadlock. */
270
 
          if (table->in_use == session)
271
 
            continue;
272
 
          /*
273
 
            Note that we wait here only for tables which are actually open, and
274
 
            not for placeholders with Table::open_placeholder set. Waiting for
275
 
            latter will cause deadlock in the following scenario, for example:
276
 
 
277
 
            conn1-> lock table t1 write;
278
 
            conn2-> lock table t2 write;
279
 
            conn1-> flush tables;
280
 
            conn2-> flush tables;
281
 
 
282
 
            It also does not make sense to wait for those of placeholders that
283
 
            are employed by CREATE TABLE as in this case table simply does not
284
 
            exist yet.
285
 
          */
286
 
          if (table->needs_reopen_or_name_lock() && (table->db_stat ||
287
 
                                                     (table->open_placeholder && wait_for_placeholders)))
288
 
          {
289
 
            found= true;
290
 
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
291
 
            COND_refresh.wait(scoped);
292
 
            scoped.release();
293
 
            break;
294
 
          }
295
 
        }
 
824
        TABLE *table=(TABLE*) hash_element(&open_cache,idx);
 
825
        if (table->in_use)
 
826
          table->in_use->some_tables_deleted= 1;
296
827
      }
297
 
      /*
298
 
        No other thread has the locked tables open; reopen them and get the
299
 
        old locks. This should always succeed (unless some external process
300
 
        has removed the tables)
301
 
      */
302
 
      result= session->reopen_tables(true, true);
303
 
 
304
 
      /* Set version for table */
305
 
      for (Table *table= session->open_tables; table ; table= table->getNext())
 
828
    }
 
829
  }
 
830
  else
 
831
  {
 
832
    bool found=0;
 
833
    for (TABLE_LIST *table= tables; table; table= table->next_local)
 
834
    {
 
835
      if (remove_table_from_cache(thd, table->db, table->table_name,
 
836
                                  RTFC_OWNED_BY_THD_FLAG))
 
837
        found=1;
 
838
    }
 
839
    if (!found)
 
840
      wait_for_refresh=0;                       // Nothing to wait for
 
841
  }
 
842
 
 
843
  if (wait_for_refresh)
 
844
  {
 
845
    /*
 
846
      If there is any table that has a lower refresh_version, wait until
 
847
      this is closed (or this thread is killed) before returning
 
848
    */
 
849
    thd->mysys_var->current_mutex= &LOCK_open;
 
850
    thd->mysys_var->current_cond= &COND_refresh;
 
851
    thd_proc_info(thd, "Flushing tables");
 
852
 
 
853
    close_old_data_files(thd,thd->open_tables,1,1);
 
854
    mysql_ha_flush(thd);
 
855
 
 
856
    bool found=1;
 
857
    /* Wait until all threads has closed all the tables we had locked */
 
858
    DBUG_PRINT("info",
 
859
               ("Waiting for other threads to close their open tables"));
 
860
    while (found && ! thd->killed)
 
861
    {
 
862
      found=0;
 
863
      for (uint idx=0 ; idx < open_cache.records ; idx++)
306
864
      {
 
865
        TABLE *table=(TABLE*) hash_element(&open_cache,idx);
 
866
        /* Avoid a self-deadlock. */
 
867
        if (table->in_use == thd)
 
868
          continue;
307
869
        /*
308
 
          Preserve the version (0) of write locked tables so that a impending
309
 
          global read lock won't sneak in.
 
870
          Note that we wait here only for tables which are actually open, and
 
871
          not for placeholders with TABLE::open_placeholder set. Waiting for
 
872
          latter will cause deadlock in the following scenario, for example:
 
873
 
 
874
          conn1: lock table t1 write;
 
875
          conn2: lock table t2 write;
 
876
          conn1: flush tables;
 
877
          conn2: flush tables;
 
878
 
 
879
          It also does not make sense to wait for those of placeholders that
 
880
          are employed by CREATE TABLE as in this case table simply does not
 
881
          exist yet.
310
882
        */
311
 
        if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
312
 
          table->getMutableShare()->refreshVersion();
 
883
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
 
884
            (table->open_placeholder && wait_for_placeholders)))
 
885
        {
 
886
          found=1;
 
887
          DBUG_PRINT("signal", ("Waiting for COND_refresh"));
 
888
          pthread_cond_wait(&COND_refresh,&LOCK_open);
 
889
          break;
 
890
        }
313
891
      }
314
892
    }
315
 
 
316
 
    table::Cache::singleton().mutex().unlock();
317
 
  }
318
 
 
319
 
  if (wait_for_refresh)
320
 
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
322
 
    session->mysys_var->current_mutex= 0;
323
 
    session->mysys_var->current_cond= 0;
324
 
    session->set_proc_info(0);
325
 
  }
326
 
 
327
 
  return result;
328
 
}
329
 
 
330
 
 
331
 
/**
332
 
  move one table to free list 
333
 
*/
334
 
 
335
 
bool Session::free_cached_table()
336
 
{
337
 
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
339
 
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
341
 
  assert(table->key_read == 0);
342
 
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
 
 
344
 
  open_tables= table->getNext();
345
 
 
346
 
  if (table->needs_reopen_or_name_lock() ||
347
 
      version != refresh_version || !table->db_stat)
348
 
  {
349
 
    table::remove_table(table);
350
 
    found_old_table= true;
351
 
  }
352
 
  else
353
 
  {
354
893
    /*
355
 
      Open placeholders have Table::db_stat set to 0, so they should be
356
 
      handled by the first alternative.
 
894
      No other thread has the locked tables open; reopen them and get the
 
895
      old locks. This should always succeed (unless some external process
 
896
      has removed the tables)
357
897
    */
358
 
    assert(not table->open_placeholder);
359
 
 
360
 
    /* Free memory and reset for next loop */
361
 
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
363
 
 
364
 
    table::getUnused().link(table);
365
 
  }
366
 
 
367
 
  return found_old_table;
 
898
    thd->in_lock_tables=1;
 
899
    result=reopen_tables(thd,1,1);
 
900
    thd->in_lock_tables=0;
 
901
    /* Set version for table */
 
902
    for (TABLE *table=thd->open_tables; table ; table= table->next)
 
903
    {
 
904
      /*
 
905
        Preserve the version (0) of write locked tables so that a impending
 
906
        global read lock won't sneak in.
 
907
      */
 
908
      if (table->reginfo.lock_type < TL_WRITE_ALLOW_WRITE)
 
909
        table->s->version= refresh_version;
 
910
    }
 
911
  }
 
912
  if (!have_lock)
 
913
    VOID(pthread_mutex_unlock(&LOCK_open));
 
914
  if (wait_for_refresh)
 
915
  {
 
916
    pthread_mutex_lock(&thd->mysys_var->mutex);
 
917
    thd->mysys_var->current_mutex= 0;
 
918
    thd->mysys_var->current_cond= 0;
 
919
    thd_proc_info(thd, 0);
 
920
    pthread_mutex_unlock(&thd->mysys_var->mutex);
 
921
  }
 
922
  DBUG_RETURN(result);
 
923
}
 
924
 
 
925
 
 
926
/*
 
927
  Close all tables which match specified connection string or
 
928
  if specified string is NULL, then any table with a connection string.
 
929
*/
 
930
 
 
931
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
 
932
                                    LEX_STRING *connection, bool have_lock)
 
933
{
 
934
  uint idx;
 
935
  TABLE_LIST tmp, *tables= NULL;
 
936
  bool result= FALSE;
 
937
  DBUG_ENTER("close_cached_connections");
 
938
  DBUG_ASSERT(thd);
 
939
 
 
940
  bzero(&tmp, sizeof(TABLE_LIST));
 
941
 
 
942
  if (!have_lock)
 
943
    VOID(pthread_mutex_lock(&LOCK_open));
 
944
 
 
945
  for (idx= 0; idx < table_def_cache.records; idx++)
 
946
  {
 
947
    TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
 
948
 
 
949
    /* Ignore if table is not open or does not have a connect_string */
 
950
    if (!share->connect_string.length || !share->ref_count)
 
951
      continue;
 
952
 
 
953
    /* Compare the connection string */
 
954
    if (connection &&
 
955
        (connection->length > share->connect_string.length ||
 
956
         (connection->length < share->connect_string.length &&
 
957
          (share->connect_string.str[connection->length] != '/' &&
 
958
           share->connect_string.str[connection->length] != '\\')) ||
 
959
         strncasecmp(connection->str, share->connect_string.str,
 
960
                     connection->length)))
 
961
      continue;
 
962
 
 
963
    /* close_cached_tables() only uses these elements */
 
964
    tmp.db= share->db.str;
 
965
    tmp.table_name= share->table_name.str;
 
966
    tmp.next_local= tables;
 
967
 
 
968
    tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp, 
 
969
                                       sizeof(TABLE_LIST));
 
970
  }
 
971
 
 
972
  if (tables)
 
973
    result= close_cached_tables(thd, tables, TRUE, FALSE, FALSE);
 
974
 
 
975
  if (!have_lock)
 
976
    VOID(pthread_mutex_unlock(&LOCK_open));
 
977
 
 
978
  if (if_wait_for_refresh)
 
979
  {
 
980
    pthread_mutex_lock(&thd->mysys_var->mutex);
 
981
    thd->mysys_var->current_mutex= 0;
 
982
    thd->mysys_var->current_cond= 0;
 
983
    thd->proc_info=0;
 
984
    pthread_mutex_unlock(&thd->mysys_var->mutex);
 
985
  }
 
986
 
 
987
  DBUG_RETURN(result);
 
988
}
 
989
 
 
990
 
 
991
/**
 
992
  Mark all temporary tables which were used by the current statement or
 
993
  substatement as free for reuse, but only if the query_id can be cleared.
 
994
 
 
995
  @param thd thread context
 
996
 
 
997
  @remark For temp tables associated with a open SQL HANDLER the query_id
 
998
          is not reset until the HANDLER is closed.
 
999
*/
 
1000
 
 
1001
static void mark_temp_tables_as_free_for_reuse(THD *thd)
 
1002
{
 
1003
  for (TABLE *table= thd->temporary_tables ; table ; table= table->next)
 
1004
  {
 
1005
    if ((table->query_id == thd->query_id) && ! table->open_by_handler)
 
1006
    {
 
1007
      table->query_id= 0;
 
1008
      table->file->ha_reset();
 
1009
    }
 
1010
  }
 
1011
}
 
1012
 
 
1013
 
 
1014
/*
 
1015
  Mark all tables in the list which were used by current substatement
 
1016
  as free for reuse.
 
1017
 
 
1018
  SYNOPSIS
 
1019
    mark_used_tables_as_free_for_reuse()
 
1020
      thd   - thread context
 
1021
      table - head of the list of tables
 
1022
 
 
1023
  DESCRIPTION
 
1024
    Marks all tables in the list which were used by current substatement
 
1025
    (they are marked by its query_id) as free for reuse.
 
1026
 
 
1027
  NOTE
 
1028
    The reason we reset query_id is that it's not enough to just test
 
1029
    if table->query_id != thd->query_id to know if a table is in use.
 
1030
 
 
1031
    For example
 
1032
    SELECT f1_that_uses_t1() FROM t1;
 
1033
    In f1_that_uses_t1() we will see one instance of t1 where query_id is
 
1034
    set to query_id of original query.
 
1035
*/
 
1036
 
 
1037
static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
 
1038
{
 
1039
  for (; table ; table= table->next)
 
1040
  {
 
1041
    if (table->query_id == thd->query_id)
 
1042
    {
 
1043
      table->query_id= 0;
 
1044
      table->file->ha_reset();
 
1045
    }
 
1046
  }
368
1047
}
369
1048
 
370
1049
 
371
1050
/**
372
1051
  Auxiliary function to close all tables in the open_tables list.
373
1052
 
374
 
  @param session Thread context.
 
1053
  @param thd Thread context.
375
1054
 
376
1055
  @remark It should not ordinarily be called directly.
377
1056
*/
378
1057
 
379
 
void Session::close_open_tables()
 
1058
static void close_open_tables(THD *thd)
380
1059
{
381
 
  bool found_old_table= false;
382
 
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
384
 
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
386
 
 
387
 
  while (open_tables)
388
 
  {
389
 
    found_old_table|= free_cached_table();
390
 
  }
391
 
  some_tables_deleted= false;
392
 
 
 
1060
  bool found_old_table= 0;
 
1061
 
 
1062
  safe_mutex_assert_not_owner(&LOCK_open);
 
1063
 
 
1064
  VOID(pthread_mutex_lock(&LOCK_open));
 
1065
 
 
1066
  DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables));
 
1067
 
 
1068
  while (thd->open_tables)
 
1069
    found_old_table|= close_thread_table(thd, &thd->open_tables);
 
1070
  thd->some_tables_deleted= 0;
 
1071
 
 
1072
  /* Free tables to hold down open files */
 
1073
  while (open_cache.records > table_cache_size && unused_tables)
 
1074
    VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
 
1075
  check_unused();
393
1076
  if (found_old_table)
394
1077
  {
395
1078
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
397
 
  }
 
1079
    broadcast_refresh();
 
1080
  }
 
1081
 
 
1082
  VOID(pthread_mutex_unlock(&LOCK_open));
 
1083
}
 
1084
 
 
1085
 
 
1086
/*
 
1087
  Close all tables used by the current substatement, or all tables
 
1088
  used by this thread if we are on the upper level.
 
1089
 
 
1090
  SYNOPSIS
 
1091
    close_thread_tables()
 
1092
    thd                 Thread handler
 
1093
 
 
1094
  IMPLEMENTATION
 
1095
    Unlocks tables and frees derived tables.
 
1096
    Put all normal tables used by thread in free list.
 
1097
 
 
1098
    It will only close/mark as free for reuse tables opened by this
 
1099
    substatement, it will also check if we are closing tables after
 
1100
    execution of complete query (i.e. we are on upper level) and will
 
1101
    leave prelocked mode if needed.
 
1102
*/
 
1103
 
 
1104
void close_thread_tables(THD *thd)
 
1105
{
 
1106
  TABLE *table;
 
1107
  DBUG_ENTER("close_thread_tables");
 
1108
 
 
1109
  /*
 
1110
    We are assuming here that thd->derived_tables contains ONLY derived
 
1111
    tables for this substatement. i.e. instead of approach which uses
 
1112
    query_id matching for determining which of the derived tables belong
 
1113
    to this substatement we rely on the ability of substatements to
 
1114
    save/restore thd->derived_tables during their execution.
 
1115
 
 
1116
    TODO: Probably even better approach is to simply associate list of
 
1117
          derived tables with (sub-)statement instead of thread and destroy
 
1118
          them at the end of its execution.
 
1119
  */
 
1120
  if (thd->derived_tables)
 
1121
  {
 
1122
    TABLE *next;
 
1123
    /*
 
1124
      Close all derived tables generated in queries like
 
1125
      SELECT * FROM (SELECT * FROM t1)
 
1126
    */
 
1127
    for (table= thd->derived_tables ; table ; table= next)
 
1128
    {
 
1129
      next= table->next;
 
1130
      free_tmp_table(thd, table);
 
1131
    }
 
1132
    thd->derived_tables= 0;
 
1133
  }
 
1134
 
 
1135
  /*
 
1136
    Mark all temporary tables used by this statement as free for reuse.
 
1137
  */
 
1138
  mark_temp_tables_as_free_for_reuse(thd);
 
1139
  /*
 
1140
    Let us commit transaction for statement. Since in 5.0 we only have
 
1141
    one statement transaction and don't allow several nested statement
 
1142
    transactions this call will do nothing if we are inside of stored
 
1143
    function or trigger (i.e. statement transaction is already active and
 
1144
    does not belong to statement for which we do close_thread_tables()).
 
1145
    TODO: This should be fixed in later releases.
 
1146
   */
 
1147
  if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
 
1148
  {
 
1149
    thd->main_da.can_overwrite_status= TRUE;
 
1150
    ha_autocommit_or_rollback(thd, thd->is_error());
 
1151
    thd->main_da.can_overwrite_status= FALSE;
 
1152
    thd->transaction.stmt.reset();
 
1153
  }
 
1154
 
 
1155
  if (thd->locked_tables)
 
1156
  {
 
1157
 
 
1158
    /* Ensure we are calling ha_reset() for all used tables */
 
1159
    mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
 
1160
 
 
1161
    /*
 
1162
      We are under simple LOCK TABLES so should not do anything else.
 
1163
    */
 
1164
    DBUG_VOID_RETURN;
 
1165
  }
 
1166
 
 
1167
  if (thd->lock)
 
1168
  {
 
1169
    /*
 
1170
      For RBR we flush the pending event just before we unlock all the
 
1171
      tables.  This means that we are at the end of a topmost
 
1172
      statement, so we ensure that the STMT_END_F flag is set on the
 
1173
      pending event.  For statements that are *inside* stored
 
1174
      functions, the pending event will not be flushed: that will be
 
1175
      handled either before writing a query log event (inside
 
1176
      binlog_query()) or when preparing a pending event.
 
1177
     */
 
1178
    thd->binlog_flush_pending_rows_event(TRUE);
 
1179
    mysql_unlock_tables(thd, thd->lock);
 
1180
    thd->lock=0;
 
1181
  }
 
1182
  /*
 
1183
    Note that we need to hold LOCK_open while changing the
 
1184
    open_tables list. Another thread may work on it.
 
1185
    (See: remove_table_from_cache(), mysql_wait_completed_table())
 
1186
    Closing a MERGE child before the parent would be fatal if the
 
1187
    other thread tries to abort the MERGE lock in between.
 
1188
  */
 
1189
  if (thd->open_tables)
 
1190
    close_open_tables(thd);
 
1191
 
 
1192
  DBUG_VOID_RETURN;
 
1193
}
 
1194
 
 
1195
 
 
1196
/* move one table to free list */
 
1197
 
 
1198
bool close_thread_table(THD *thd, TABLE **table_ptr)
 
1199
{
 
1200
  bool found_old_table= 0;
 
1201
  TABLE *table= *table_ptr;
 
1202
  DBUG_ENTER("close_thread_table");
 
1203
  DBUG_ASSERT(table->key_read == 0);
 
1204
  DBUG_ASSERT(!table->file || table->file->inited == handler::NONE);
 
1205
  DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
 
1206
                        table->s->table_name.str, (long) table));
 
1207
 
 
1208
  *table_ptr=table->next;
 
1209
 
 
1210
  if (table->needs_reopen_or_name_lock() ||
 
1211
      thd->version != refresh_version || !table->db_stat)
 
1212
  {
 
1213
    VOID(hash_delete(&open_cache,(uchar*) table));
 
1214
    found_old_table=1;
 
1215
  }
 
1216
  else
 
1217
  {
 
1218
    /*
 
1219
      Open placeholders have TABLE::db_stat set to 0, so they should be
 
1220
      handled by the first alternative.
 
1221
    */
 
1222
    DBUG_ASSERT(!table->open_placeholder);
 
1223
 
 
1224
    /* Free memory and reset for next loop */
 
1225
    table->file->ha_reset();
 
1226
    table->in_use=0;
 
1227
    if (unused_tables)
 
1228
    {
 
1229
      table->next=unused_tables;                /* Link in last */
 
1230
      table->prev=unused_tables->prev;
 
1231
      unused_tables->prev=table;
 
1232
      table->prev->next=table;
 
1233
    }
 
1234
    else
 
1235
      unused_tables=table->next=table->prev=table;
 
1236
  }
 
1237
  DBUG_RETURN(found_old_table);
 
1238
}
 
1239
 
 
1240
 
 
1241
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
 
1242
static inline uint  tmpkeyval(THD *thd, TABLE *table)
 
1243
{
 
1244
  return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
 
1245
}
 
1246
 
 
1247
 
 
1248
/*
 
1249
  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
 
1250
  creates one DROP TEMPORARY TABLE binlog event for each pseudo-thread 
 
1251
*/
 
1252
 
 
1253
void close_temporary_tables(THD *thd)
 
1254
{
 
1255
  TABLE *table;
 
1256
  TABLE *next= NULL;
 
1257
  TABLE *prev_table;
 
1258
  /* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
 
1259
  bool was_quote_show= TRUE;
 
1260
 
 
1261
  if (!thd->temporary_tables)
 
1262
    return;
 
1263
 
 
1264
  if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
 
1265
  {
 
1266
    TABLE *tmp_next;
 
1267
    for (table= thd->temporary_tables; table; table= tmp_next)
 
1268
    {
 
1269
      tmp_next= table->next;
 
1270
      close_temporary(table, 1, 1);
 
1271
    }
 
1272
    thd->temporary_tables= 0;
 
1273
    return;
 
1274
  }
 
1275
 
 
1276
  /* Better add "if exists", in case a RESET MASTER has been done */
 
1277
  const char stub[]= "DROP /*!40005 TEMPORARY */ TABLE IF EXISTS ";
 
1278
  uint stub_len= sizeof(stub) - 1;
 
1279
  char buf[256];
 
1280
  String s_query= String(buf, sizeof(buf), system_charset_info);
 
1281
  bool found_user_tables= FALSE;
 
1282
 
 
1283
  memcpy(buf, stub, stub_len);
 
1284
 
 
1285
  /*
 
1286
    Insertion sort of temp tables by pseudo_thread_id to build ordered list
 
1287
    of sublists of equal pseudo_thread_id
 
1288
  */
 
1289
 
 
1290
  for (prev_table= thd->temporary_tables, table= prev_table->next;
 
1291
       table;
 
1292
       prev_table= table, table= table->next)
 
1293
  {
 
1294
    TABLE *prev_sorted /* same as for prev_table */, *sorted;
 
1295
    if (is_user_table(table))
 
1296
    {
 
1297
      if (!found_user_tables)
 
1298
        found_user_tables= true;
 
1299
      for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
 
1300
           prev_sorted= sorted, sorted= sorted->next)
 
1301
      {
 
1302
        if (!is_user_table(sorted) ||
 
1303
            tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
 
1304
        {
 
1305
          /* move into the sorted part of the list from the unsorted */
 
1306
          prev_table->next= table->next;
 
1307
          table->next= sorted;
 
1308
          if (prev_sorted)
 
1309
          {
 
1310
            prev_sorted->next= table;
 
1311
          }
 
1312
          else
 
1313
          {
 
1314
            thd->temporary_tables= table;
 
1315
          }
 
1316
          table= prev_table;
 
1317
          break;
 
1318
        }
 
1319
      }
 
1320
    }
 
1321
  }
 
1322
 
 
1323
  /* We always quote db,table names though it is slight overkill */
 
1324
  if (found_user_tables &&
 
1325
      !(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
 
1326
  {
 
1327
    thd->options |= OPTION_QUOTE_SHOW_CREATE;
 
1328
  }
 
1329
 
 
1330
  /* scan sorted tmps to generate sequence of DROP */
 
1331
  for (table= thd->temporary_tables; table; table= next)
 
1332
  {
 
1333
    if (is_user_table(table))
 
1334
    {
 
1335
      my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
 
1336
      /* Set pseudo_thread_id to be that of the processed table */
 
1337
      thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
 
1338
      /*
 
1339
        Loop forward through all tables within the sublist of
 
1340
        common pseudo_thread_id to create single DROP query.
 
1341
      */
 
1342
      for (s_query.length(stub_len);
 
1343
           table && is_user_table(table) &&
 
1344
             tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
 
1345
           table= next)
 
1346
      {
 
1347
        /*
 
1348
          We are going to add 4 ` around the db/table names and possible more
 
1349
          due to special characters in the names
 
1350
        */
 
1351
        append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
 
1352
        s_query.append('.');
 
1353
        append_identifier(thd, &s_query, table->s->table_name.str,
 
1354
                          strlen(table->s->table_name.str));
 
1355
        s_query.append(',');
 
1356
        next= table->next;
 
1357
        close_temporary(table, 1, 1);
 
1358
      }
 
1359
      thd->clear_error();
 
1360
      CHARSET_INFO *cs_save= thd->variables.character_set_client;
 
1361
      thd->variables.character_set_client= system_charset_info;
 
1362
      Query_log_event qinfo(thd, s_query.ptr(),
 
1363
                            s_query.length() - 1 /* to remove trailing ',' */,
 
1364
                            0, FALSE);
 
1365
      thd->variables.character_set_client= cs_save;
 
1366
      /*
 
1367
        Imagine the thread had created a temp table, then was doing a
 
1368
        SELECT, and the SELECT was killed. Then it's not clever to
 
1369
        mark the statement above as "killed", because it's not really
 
1370
        a statement updating data, and there are 99.99% chances it
 
1371
        will succeed on slave.  If a real update (one updating a
 
1372
        persistent table) was killed on the master, then this real
 
1373
        update will be logged with error_code=killed, rightfully
 
1374
        causing the slave to stop.
 
1375
      */
 
1376
      qinfo.error_code= 0;
 
1377
      mysql_bin_log.write(&qinfo);
 
1378
      thd->variables.pseudo_thread_id= save_pseudo_thread_id;
 
1379
    }
 
1380
    else
 
1381
    {
 
1382
      next= table->next;
 
1383
      close_temporary(table, 1, 1);
 
1384
    }
 
1385
  }
 
1386
  if (!was_quote_show)
 
1387
    thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
 
1388
  thd->temporary_tables=0;
398
1389
}
399
1390
 
400
1391
/*
401
1392
  Find table in list.
402
1393
 
403
1394
  SYNOPSIS
404
 
  find_table_in_list()
405
 
  table         Pointer to table list
406
 
  offset                Offset to which list in table structure to use
407
 
  db_name               Data base name
408
 
  table_name            Table name
409
 
 
410
 
NOTES:
411
 
This is called by find_table_in_global_list().
412
 
 
413
 
RETURN VALUES
414
 
NULL    Table not found
415
 
#               Pointer to found table.
 
1395
    find_table_in_list()
 
1396
    table               Pointer to table list
 
1397
    offset              Offset to which list in table structure to use
 
1398
    db_name             Data base name
 
1399
    table_name          Table name
 
1400
 
 
1401
  NOTES:
 
1402
    This is called by find_table_in_local_list() and
 
1403
    find_table_in_global_list().
 
1404
 
 
1405
  RETURN VALUES
 
1406
    NULL        Table not found
 
1407
    #           Pointer to found table.
416
1408
*/
417
1409
 
418
 
TableList *find_table_in_list(TableList *table,
419
 
                              TableList *TableList::*link,
420
 
                              const char *db_name,
421
 
                              const char *table_name)
 
1410
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
 
1411
                               TABLE_LIST *TABLE_LIST::*link,
 
1412
                               const char *db_name,
 
1413
                               const char *table_name)
422
1414
{
423
1415
  for (; table; table= table->*link )
424
1416
  {
425
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
426
 
        strcasecmp(table->getSchemaName(), db_name) == 0 &&
427
 
        strcasecmp(table->getTableName(), table_name) == 0)
 
1417
    if ((table->table == 0 || table->table->s->tmp_table == NO_TMP_TABLE) &&
 
1418
        strcmp(table->db, db_name) == 0 &&
 
1419
        strcmp(table->table_name, table_name) == 0)
428
1420
      break;
429
1421
  }
430
1422
  return table;
435
1427
  Test that table is unique (It's only exists once in the table list)
436
1428
 
437
1429
  SYNOPSIS
438
 
  unique_table()
439
 
  session                   thread handle
440
 
  table                 table which should be checked
441
 
  table_list            list of tables
442
 
  check_alias           whether to check tables' aliases
443
 
 
444
 
NOTE: to exclude derived tables from check we use following mechanism:
445
 
a) during derived table processing set Session::derived_tables_processing
446
 
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
447
 
Session::derived_tables_processing set. (we can't use JOIN::execute
448
 
because for PS we perform only JOIN::prepare, but we can't set this
449
 
flag in JOIN::prepare if we are not sure that we are in derived table
450
 
processing loop, because multi-update call fix_fields() for some its
451
 
items (which mean JOIN::prepare for subqueries) before unique_table
452
 
call to detect which tables should be locked for write).
453
 
c) unique_table skip all tables which belong to SELECT with
454
 
SELECT::exclude_from_table_unique_test set.
455
 
Also SELECT::exclude_from_table_unique_test used to exclude from check
456
 
tables of main SELECT of multi-delete and multi-update
457
 
 
458
 
We also skip tables with TableList::prelocking_placeholder set,
459
 
because we want to allow SELECTs from them, and their modification
460
 
will rise the error anyway.
461
 
 
462
 
TODO: when we will have table/view change detection we can do this check
463
 
only once for PS/SP
464
 
 
465
 
RETURN
466
 
found duplicate
467
 
0 if table is unique
 
1430
    unique_table()
 
1431
    thd                   thread handle
 
1432
    table                 table which should be checked
 
1433
    table_list            list of tables
 
1434
    check_alias           whether to check tables' aliases
 
1435
 
 
1436
  NOTE: to exclude derived tables from check we use following mechanism:
 
1437
    a) during derived table processing set THD::derived_tables_processing
 
1438
    b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
 
1439
       THD::derived_tables_processing set. (we can't use JOIN::execute
 
1440
       because for PS we perform only JOIN::prepare, but we can't set this
 
1441
       flag in JOIN::prepare if we are not sure that we are in derived table
 
1442
       processing loop, because multi-update call fix_fields() for some its
 
1443
       items (which mean JOIN::prepare for subqueries) before unique_table
 
1444
       call to detect which tables should be locked for write).
 
1445
    c) unique_table skip all tables which belong to SELECT with
 
1446
       SELECT::exclude_from_table_unique_test set.
 
1447
    Also SELECT::exclude_from_table_unique_test used to exclude from check
 
1448
    tables of main SELECT of multi-delete and multi-update
 
1449
 
 
1450
    We also skip tables with TABLE_LIST::prelocking_placeholder set,
 
1451
    because we want to allow SELECTs from them, and their modification
 
1452
    will rise the error anyway.
 
1453
 
 
1454
    TODO: when we will have table/view change detection we can do this check
 
1455
          only once for PS/SP
 
1456
 
 
1457
  RETURN
 
1458
    found duplicate
 
1459
    0 if table is unique
468
1460
*/
469
1461
 
470
 
TableList* unique_table(TableList *table, TableList *table_list,
471
 
                        bool check_alias)
 
1462
TABLE_LIST* unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
 
1463
                         bool check_alias)
472
1464
{
473
 
  TableList *res;
 
1465
  TABLE_LIST *res;
474
1466
  const char *d_name, *t_name, *t_alias;
 
1467
  DBUG_ENTER("unique_table");
 
1468
  DBUG_PRINT("enter", ("table alias: %s", table->alias));
475
1469
 
476
1470
  /*
477
1471
    If this function called for query which update table (INSERT/UPDATE/...)
478
 
    then we have in table->table pointer to Table object which we are
479
 
    updating even if it is VIEW so we need TableList of this Table object
 
1472
    then we have in table->table pointer to TABLE object which we are
 
1473
    updating even if it is VIEW so we need TABLE_LIST of this TABLE object
480
1474
    to get right names (even if lower_case_table_names used).
481
1475
 
482
1476
    If this function called for CREATE command that we have not opened table
483
 
    (table->table equal to 0) and right names is in current TableList
 
1477
    (table->table equal to 0) and right names is in current TABLE_LIST
484
1478
    object.
485
1479
  */
486
1480
  if (table->table)
487
1481
  {
488
1482
    /* temporary table is always unique */
489
 
    if (table->table && table->table->getShare()->getType() != message::Table::STANDARD)
490
 
      return 0;
 
1483
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
 
1484
      DBUG_RETURN(0);
491
1485
    table= table->find_underlying_table(table->table);
492
1486
    /*
493
 
      as far as we have table->table we have to find real TableList of
 
1487
      as far as we have table->table we have to find real TABLE_LIST of
494
1488
      it in underlying tables
495
1489
    */
496
 
    assert(table);
 
1490
    DBUG_ASSERT(table);
497
1491
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
1492
  d_name= table->db;
 
1493
  t_name= table->table_name;
500
1494
  t_alias= table->alias;
501
1495
 
 
1496
  DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name));
502
1497
  for (;;)
503
1498
  {
504
 
    if ((! (res= find_table_in_global_list(table_list, d_name, t_name))) ||
 
1499
    if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
 
1500
         (! (res= mysql_lock_have_duplicate(thd, table, table_list)))) ||
505
1501
        ((!res->table || res->table != table->table) &&
506
 
         (!check_alias || !(my_strcasecmp(files_charset_info, t_alias, res->alias))) &&
 
1502
         (!check_alias || !(lower_case_table_names ?
 
1503
          my_strcasecmp(files_charset_info, t_alias, res->alias) :
 
1504
          strcmp(t_alias, res->alias))) &&
507
1505
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
508
1506
      break;
509
1507
    /*
512
1510
      (exclude_from_table_unique_test) or prelocking placeholder.
513
1511
    */
514
1512
    table_list= res->next_global;
515
 
  }
516
 
  return(res);
517
 
}
518
 
 
519
 
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
522
 
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
524
 
  {
525
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
 
    {
527
 
      set_of_names.insert(table->getShare()->getTableName());
528
 
    }
529
 
  }
530
 
}
531
 
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
535
 
{
536
 
  doGetTableNames(schema_identifier, set_of_names);
537
 
}
538
 
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
541
 
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
543
 
  {
544
 
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
 
    {
546
 
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
547
 
                                                   table->getShare()->getTableName(),
548
 
                                                   table->getShare()->getPath()));
549
 
    }
550
 
  }
551
 
}
552
 
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
556
 
{
557
 
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
 
}
559
 
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
561
 
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
563
 
  {
564
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
 
    {
566
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
567
 
      {
568
 
        return true;
569
 
      }
570
 
    }
571
 
  }
572
 
 
573
 
  return false;
574
 
}
575
 
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
577
 
                                  message::Table &table_proto)
578
 
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
580
 
  {
581
 
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
 
    {
583
 
      if (identifier.getKey() == table->getShare()->getCacheKey())
584
 
      {
585
 
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
586
 
 
587
 
        return EEXIST;
588
 
      }
589
 
    }
590
 
  }
591
 
 
592
 
  return ENOENT;
593
 
}
594
 
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
596
 
{
597
 
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
 
  {
599
 
    if (identifier.getKey() == table->getShare()->getCacheKey())
600
 
      return table;
601
 
  }
602
 
 
603
 
  return NULL;                               // Not a temporary table
 
1513
    DBUG_PRINT("info",
 
1514
               ("found same copy of table or table which we should skip"));
 
1515
  }
 
1516
  DBUG_RETURN(res);
 
1517
}
 
1518
 
 
1519
 
 
1520
/*
 
1521
  Issue correct error message in case we found 2 duplicate tables which
 
1522
  prevent some update operation
 
1523
 
 
1524
  SYNOPSIS
 
1525
    update_non_unique_table_error()
 
1526
    update      table which we try to update
 
1527
    operation   name of update operation
 
1528
    duplicate   duplicate table which we found
 
1529
 
 
1530
  NOTE:
 
1531
    here we hide view underlying tables if we have them
 
1532
*/
 
1533
 
 
1534
void update_non_unique_table_error(TABLE_LIST *update,
 
1535
                                   const char *operation,
 
1536
                                   TABLE_LIST *duplicate)
 
1537
{
 
1538
  my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
 
1539
}
 
1540
 
 
1541
 
 
1542
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
 
1543
{
 
1544
  TABLE_LIST table_list;
 
1545
 
 
1546
  table_list.db= (char*) db;
 
1547
  table_list.table_name= (char*) table_name;
 
1548
  return find_temporary_table(thd, &table_list);
 
1549
}
 
1550
 
 
1551
 
 
1552
TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
 
1553
{
 
1554
  char  key[MAX_DBKEY_LENGTH];
 
1555
  uint  key_length;
 
1556
  TABLE *table;
 
1557
  DBUG_ENTER("find_temporary_table");
 
1558
  DBUG_PRINT("enter", ("table: '%s'.'%s'",
 
1559
                       table_list->db, table_list->table_name));
 
1560
 
 
1561
  key_length= create_table_def_key(thd, key, table_list, 1);
 
1562
  for (table=thd->temporary_tables ; table ; table= table->next)
 
1563
  {
 
1564
    if (table->s->table_cache_key.length == key_length &&
 
1565
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
1566
    {
 
1567
      DBUG_PRINT("info",
 
1568
                 ("Found table. server_id: %u  pseudo_thread_id: %lu",
 
1569
                  (uint) thd->server_id,
 
1570
                  (ulong) thd->variables.pseudo_thread_id));
 
1571
      DBUG_RETURN(table);
 
1572
    }
 
1573
  }
 
1574
  DBUG_RETURN(0);                               // Not a temporary table
604
1575
}
605
1576
 
606
1577
 
607
1578
/**
608
1579
  Drop a temporary table.
609
1580
 
610
 
  Try to locate the table in the list of session->temporary_tables.
 
1581
  Try to locate the table in the list of thd->temporary_tables.
611
1582
  If the table is found:
612
 
  - if the table is being used by some outer statement, fail.
613
 
  - if the table is in session->locked_tables, unlock it and
614
 
  remove it from the list of locked tables. Currently only transactional
615
 
  temporary tables are present in the locked_tables list.
616
 
  - Close the temporary table, remove its .FRM
617
 
  - remove the table from the list of temporary tables
 
1583
   - if the table is being used by some outer statement, fail.
 
1584
   - if the table is in thd->locked_tables, unlock it and
 
1585
     remove it from the list of locked tables. Currently only transactional
 
1586
     temporary tables are present in the locked_tables list.
 
1587
   - Close the temporary table, remove its .FRM
 
1588
   - remove the table from the list of temporary tables
618
1589
 
619
1590
  This function is used to drop user temporary tables, as well as
620
1591
  internal tables created in CREATE TEMPORARY TABLE ... SELECT
621
 
  or ALTER Table. Even though part of the work done by this function
 
1592
  or ALTER TABLE. Even though part of the work done by this function
622
1593
  is redundant when the table is internal, as long as we
623
1594
  link both internal and user temporary tables into the same
624
 
  session->temporary_tables list, it's impossible to tell here whether
 
1595
  thd->temporary_tables list, it's impossible to tell here whether
625
1596
  we're dealing with an internal or a user temporary table.
626
1597
 
627
1598
  @retval  0  the table was found and dropped successfully.
628
1599
  @retval  1  the table was not found in the list of temporary tables
629
 
  of this thread
 
1600
              of this thread
630
1601
  @retval -1  the table is in use by a outer query
631
1602
*/
632
1603
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
1604
int drop_temporary_table(THD *thd, TABLE_LIST *table_list)
634
1605
{
635
 
  Table *table;
 
1606
  TABLE *table;
 
1607
  DBUG_ENTER("drop_temporary_table");
 
1608
  DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
 
1609
                          table_list->db, table_list->table_name));
636
1610
 
637
 
  if (not (table= find_temporary_table(identifier)))
638
 
    return 1;
 
1611
  if (!(table= find_temporary_table(thd, table_list)))
 
1612
    DBUG_RETURN(1);
639
1613
 
640
1614
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
642
 
  {
643
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
644
 
    return -1;
645
 
  }
646
 
 
647
 
  close_temporary_table(table);
648
 
 
649
 
  return 0;
 
1615
  if (table->query_id && table->query_id != thd->query_id)
 
1616
  {
 
1617
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
1618
    DBUG_RETURN(-1);
 
1619
  }
 
1620
 
 
1621
  /*
 
1622
    If LOCK TABLES list is not empty and contains this table,
 
1623
    unlock the table and remove the table from this list.
 
1624
  */
 
1625
  mysql_lock_remove(thd, thd->locked_tables, table, FALSE);
 
1626
  close_temporary_table(thd, table, 1, 1);
 
1627
  DBUG_RETURN(0);
 
1628
}
 
1629
 
 
1630
/*
 
1631
  unlink from thd->temporary tables and close temporary table
 
1632
*/
 
1633
 
 
1634
void close_temporary_table(THD *thd, TABLE *table,
 
1635
                           bool free_share, bool delete_table)
 
1636
{
 
1637
  DBUG_ENTER("close_temporary_table");
 
1638
  DBUG_PRINT("tmptable", ("closing table: '%s'.'%s' 0x%lx  alias: '%s'",
 
1639
                          table->s->db.str, table->s->table_name.str,
 
1640
                          (long) table, table->alias));
 
1641
 
 
1642
  if (table->prev)
 
1643
  {
 
1644
    table->prev->next= table->next;
 
1645
    if (table->prev->next)
 
1646
      table->next->prev= table->prev;
 
1647
  }
 
1648
  else
 
1649
  {
 
1650
    /* removing the item from the list */
 
1651
    DBUG_ASSERT(table == thd->temporary_tables);
 
1652
    /*
 
1653
      slave must reset its temporary list pointer to zero to exclude
 
1654
      passing non-zero value to end_slave via rli->save_temporary_tables
 
1655
      when no temp tables opened, see an invariant below.
 
1656
    */
 
1657
    thd->temporary_tables= table->next;
 
1658
    if (thd->temporary_tables)
 
1659
      table->next->prev= 0;
 
1660
  }
 
1661
  if (thd->slave_thread)
 
1662
  {
 
1663
    /* natural invariant of temporary_tables */
 
1664
    DBUG_ASSERT(slave_open_temp_tables || !thd->temporary_tables);
 
1665
    slave_open_temp_tables--;
 
1666
  }
 
1667
  close_temporary(table, free_share, delete_table);
 
1668
  DBUG_VOID_RETURN;
 
1669
}
 
1670
 
 
1671
 
 
1672
/*
 
1673
  Close and delete a temporary table
 
1674
 
 
1675
  NOTE
 
1676
    This dosn't unlink table from thd->temporary
 
1677
    If this is needed, use close_temporary_table()
 
1678
*/
 
1679
 
 
1680
void close_temporary(TABLE *table, bool free_share, bool delete_table)
 
1681
{
 
1682
  handlerton *table_type= table->s->db_type();
 
1683
  DBUG_ENTER("close_temporary");
 
1684
  DBUG_PRINT("tmptable", ("closing table: '%s'.'%s'",
 
1685
                          table->s->db.str, table->s->table_name.str));
 
1686
 
 
1687
  free_io_cache(table);
 
1688
  closefrm(table, 0);
 
1689
  /*
 
1690
     Check that temporary table has not been created with
 
1691
     frm_only because it has then not been created in any storage engine
 
1692
   */
 
1693
  if (delete_table)
 
1694
    rm_temporary_table(table_type, table->s->path.str, 
 
1695
                       table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
 
1696
  if (free_share)
 
1697
  {
 
1698
    free_table_share(table->s);
 
1699
    my_free((char*) table,MYF(0));
 
1700
  }
 
1701
  DBUG_VOID_RETURN;
 
1702
}
 
1703
 
 
1704
 
 
1705
/*
 
1706
  Used by ALTER TABLE when the table is a temporary one. It changes something
 
1707
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
 
1708
  name).
 
1709
  Prepares a table cache key, which is the concatenation of db, table_name and
 
1710
  thd->slave_proxy_id, separated by '\0'.
 
1711
*/
 
1712
 
 
1713
bool rename_temporary_table(THD* thd, TABLE *table, const char *db,
 
1714
                            const char *table_name)
 
1715
{
 
1716
  char *key;
 
1717
  uint key_length;
 
1718
  TABLE_SHARE *share= table->s;
 
1719
  TABLE_LIST table_list;
 
1720
  DBUG_ENTER("rename_temporary_table");
 
1721
 
 
1722
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
 
1723
    DBUG_RETURN(1);                             /* purecov: inspected */
 
1724
 
 
1725
  table_list.db= (char*) db;
 
1726
  table_list.table_name= (char*) table_name;
 
1727
  key_length= create_table_def_key(thd, key, &table_list, 1);
 
1728
  share->set_table_cache_key(key, key_length);
 
1729
  DBUG_RETURN(0);
 
1730
}
 
1731
 
 
1732
 
 
1733
        /* move table first in unused links */
 
1734
 
 
1735
static void relink_unused(TABLE *table)
 
1736
{
 
1737
  if (table != unused_tables)
 
1738
  {
 
1739
    table->prev->next=table->next;              /* Remove from unused list */
 
1740
    table->next->prev=table->prev;
 
1741
    table->next=unused_tables;                  /* Link in unused tables */
 
1742
    table->prev=unused_tables->prev;
 
1743
    unused_tables->prev->next=table;
 
1744
    unused_tables->prev=table;
 
1745
    unused_tables=table;
 
1746
    check_unused();
 
1747
  }
650
1748
}
651
1749
 
652
1750
 
653
1751
/**
654
 
  Remove all instances of table from thread's open list and
655
 
  table cache.
656
 
 
657
 
  @param  session     Thread context
658
 
  @param  find    Table to remove
659
 
 
660
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
 
1752
    Remove all instances of table from thread's open list and
 
1753
    table cache.
 
1754
 
 
1755
    @param  thd     Thread context
 
1756
    @param  find    Table to remove
 
1757
    @param  unlock  TRUE  - free all locks on tables removed that are
 
1758
                            done with LOCK TABLES
 
1759
                    FALSE - otherwise
 
1760
 
 
1761
    @note When unlock parameter is FALSE or current thread doesn't have
 
1762
          any tables locked with LOCK TABLES, tables are assumed to be
 
1763
          not locked (for example already unlocked).
661
1764
*/
662
1765
 
663
 
void Session::unlink_open_table(Table *find)
 
1766
void unlink_open_table(THD *thd, TABLE *find, bool unlock)
664
1767
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
668
 
 
 
1768
  char key[MAX_DBKEY_LENGTH];
 
1769
  uint key_length= find->s->table_cache_key.length;
 
1770
  TABLE *list, **prev;
 
1771
  DBUG_ENTER("unlink_open_table");
 
1772
 
 
1773
  safe_mutex_assert_owner(&LOCK_open);
 
1774
 
 
1775
  memcpy(key, find->s->table_cache_key.str, key_length);
669
1776
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1777
    Note that we need to hold LOCK_open while changing the
671
1778
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1779
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
1780
    Closing a MERGE child before the parent would be fatal if the
674
1781
    other thread tries to abort the MERGE lock in between.
675
1782
  */
676
 
  for (prev= &open_tables; *prev; )
 
1783
  for (prev= &thd->open_tables; *prev; )
677
1784
  {
678
 
    Table *list= *prev;
 
1785
    list= *prev;
679
1786
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
1787
    if (list->s->table_cache_key.length == key_length &&
 
1788
        !memcmp(list->s->table_cache_key.str, key, key_length))
681
1789
    {
 
1790
      if (unlock && thd->locked_tables)
 
1791
        mysql_lock_remove(thd, thd->locked_tables, list, TRUE);
 
1792
 
682
1793
      /* Remove table from open_tables list. */
683
 
      *prev= list->getNext();
684
 
 
 
1794
      *prev= list->next;
685
1795
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
1796
      VOID(hash_delete(&open_cache,(uchar*) list)); // Close table
687
1797
    }
688
1798
    else
689
1799
    {
690
1800
      /* Step to next entry in open_tables list. */
691
 
      prev= list->getNextPtr();
 
1801
      prev= &list->next;
692
1802
    }
693
1803
  }
694
1804
 
695
1805
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
1806
  broadcast_refresh();
 
1807
  DBUG_VOID_RETURN;
697
1808
}
698
1809
 
699
1810
 
700
1811
/**
701
 
  Auxiliary routine which closes and drops open table.
702
 
 
703
 
  @param  session         Thread handle
704
 
  @param  table       Table object for table to be dropped
705
 
  @param  db_name     Name of database for this table
706
 
  @param  table_name  Name of this table
707
 
 
708
 
  @note This routine assumes that table to be closed is open only
709
 
  by calling thread so we needn't wait until other threads
710
 
  will close the table. Also unless called under implicit or
711
 
  explicit LOCK TABLES mode it assumes that table to be
712
 
  dropped is already unlocked. In the former case it will
713
 
  also remove lock on the table. But one should not rely on
714
 
  this behaviour as it may change in future.
715
 
  Currently, however, this function is never called for a
716
 
  table that was locked with LOCK TABLES.
 
1812
    Auxiliary routine which closes and drops open table.
 
1813
 
 
1814
    @param  thd         Thread handle
 
1815
    @param  table       TABLE object for table to be dropped
 
1816
    @param  db_name     Name of database for this table
 
1817
    @param  table_name  Name of this table
 
1818
 
 
1819
    @note This routine assumes that table to be closed is open only
 
1820
          by calling thread so we needn't wait until other threads
 
1821
          will close the table. Also unless called under implicit or
 
1822
          explicit LOCK TABLES mode it assumes that table to be
 
1823
          dropped is already unlocked. In the former case it will
 
1824
          also remove lock on the table. But one should not rely on
 
1825
          this behaviour as it may change in future.
 
1826
          Currently, however, this function is never called for a
 
1827
          table that was locked with LOCK TABLES.
717
1828
*/
718
1829
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
1830
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
 
1831
                     const char *table_name)
720
1832
{
721
 
  if (table->getShare()->getType())
722
 
  {
723
 
    close_temporary_table(table);
724
 
  }
 
1833
  if (table->s->tmp_table)
 
1834
    close_temporary_table(thd, table, 1, 1);
725
1835
  else
726
1836
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
1837
    handlerton *table_type= table->s->db_type();
 
1838
    VOID(pthread_mutex_lock(&LOCK_open));
728
1839
    /*
729
1840
      unlink_open_table() also tells threads waiting for refresh or close
730
1841
      that something has happened.
731
1842
    */
732
 
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
1843
    unlink_open_table(thd, table, FALSE);
 
1844
    quick_rm_table(table_type, db_name, table_name, 0);
 
1845
    VOID(pthread_mutex_unlock(&LOCK_open));
734
1846
  }
735
1847
}
736
1848
 
737
1849
 
738
1850
/*
739
 
  Wait for condition but allow the user to send a kill to mysqld
 
1851
   Wait for condition but allow the user to send a kill to mysqld
740
1852
 
741
 
  SYNOPSIS
742
 
  wait_for_condition()
743
 
  session       Thread Cursor
744
 
  mutex mutex that is currently hold that is associated with condition
745
 
  Will be unlocked on return
746
 
  cond  Condition to wait for
 
1853
   SYNOPSIS
 
1854
     wait_for_condition()
 
1855
     thd        Thread handler
 
1856
     mutex      mutex that is currently hold that is associated with condition
 
1857
                Will be unlocked on return     
 
1858
     cond       Condition to wait for
747
1859
*/
748
1860
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
1861
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
750
1862
{
751
1863
  /* Wait until the current table is up to date */
752
 
  const char *saved_proc_info;
753
 
  mysys_var->current_mutex= &mutex;
754
 
  mysys_var->current_cond= &cond;
755
 
  saved_proc_info= get_proc_info();
756
 
  set_proc_info("Waiting for table");
757
 
  {
758
 
    /*
759
 
      We must unlock mutex first to avoid deadlock becasue conditions are
760
 
      sent to this thread by doing locks in the following order:
761
 
      lock(mysys_var->mutex)
762
 
      lock(mysys_var->current_mutex)
763
 
 
764
 
      One by effect of this that one can only use wait_for_condition with
765
 
      condition variables that are guranteed to not disapper (freed) even if this
766
 
      mutex is unlocked
767
 
    */
768
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
770
 
    {
771
 
      cond.wait(scopedLock);
772
 
    }
773
 
  }
774
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
775
 
  mysys_var->current_mutex= 0;
776
 
  mysys_var->current_cond= 0;
777
 
  set_proc_info(saved_proc_info);
778
 
}
779
 
 
780
 
 
781
 
/**
782
 
  Create and insert into table cache placeholder for table
783
 
  which will prevent its opening (or creation) (a.k.a lock
784
 
  table name).
785
 
 
786
 
  @param session         Thread context
787
 
  @param key         Table cache key for name to be locked
788
 
  @param key_length  Table cache key length
789
 
 
790
 
  @return Pointer to Table object used for name locking or 0 in
791
 
  case of failure.
792
 
*/
793
 
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
795
 
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1864
  const char *proc_info;
 
1865
  thd->mysys_var->current_mutex= mutex;
 
1866
  thd->mysys_var->current_cond= cond;
 
1867
  proc_info=thd->proc_info;
 
1868
  thd_proc_info(thd, "Waiting for table");
 
1869
  DBUG_ENTER("wait_for_condition");
 
1870
  if (!thd->killed)
 
1871
    (void) pthread_cond_wait(cond, mutex);
 
1872
 
 
1873
  /*
 
1874
    We must unlock mutex first to avoid deadlock becasue conditions are
 
1875
    sent to this thread by doing locks in the following order:
 
1876
    lock(mysys_var->mutex)
 
1877
    lock(mysys_var->current_mutex)
 
1878
 
 
1879
    One by effect of this that one can only use wait_for_condition with
 
1880
    condition variables that are guranteed to not disapper (freed) even if this
 
1881
    mutex is unlocked
 
1882
  */
 
1883
    
 
1884
  pthread_mutex_unlock(mutex);
 
1885
  pthread_mutex_lock(&thd->mysys_var->mutex);
 
1886
  thd->mysys_var->current_mutex= 0;
 
1887
  thd->mysys_var->current_cond= 0;
 
1888
  thd_proc_info(thd, proc_info);
 
1889
  pthread_mutex_unlock(&thd->mysys_var->mutex);
 
1890
  DBUG_VOID_RETURN;
 
1891
}
 
1892
 
 
1893
 
 
1894
/**
 
1895
  Exclusively name-lock a table that is already write-locked by the
 
1896
  current thread.
 
1897
 
 
1898
  @param thd current thread context
 
1899
  @param tables table list containing one table to open.
 
1900
 
 
1901
  @return FALSE on success, TRUE otherwise.
 
1902
*/
 
1903
 
 
1904
bool name_lock_locked_table(THD *thd, TABLE_LIST *tables)
 
1905
{
 
1906
  DBUG_ENTER("name_lock_locked_table");
 
1907
 
 
1908
  /* Under LOCK TABLES we must only accept write locked tables. */
 
1909
  tables->table= find_locked_table(thd, tables->db, tables->table_name);
 
1910
 
 
1911
  if (!tables->table)
 
1912
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
 
1913
  else if (tables->table->reginfo.lock_type < TL_WRITE_LOW_PRIORITY)
 
1914
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), tables->alias);
 
1915
  else
 
1916
  {
 
1917
    /*
 
1918
      Ensures that table is opened only by this thread and that no
 
1919
      other statement will open this table.
 
1920
    */
 
1921
    wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN);
 
1922
    DBUG_RETURN(FALSE);
 
1923
  }
 
1924
 
 
1925
  DBUG_RETURN(TRUE);
 
1926
}
 
1927
 
 
1928
 
 
1929
/*
 
1930
  Open table which is already name-locked by this thread.
 
1931
 
 
1932
  SYNOPSIS
 
1933
    reopen_name_locked_table()
 
1934
      thd         Thread handle
 
1935
      table_list  TABLE_LIST object for table to be open, TABLE_LIST::table
 
1936
                  member should point to TABLE object which was used for
 
1937
                  name-locking.
 
1938
      link_in     TRUE  - if TABLE object for table to be opened should be
 
1939
                          linked into THD::open_tables list.
 
1940
                  FALSE - placeholder used for name-locking is already in
 
1941
                          this list so we only need to preserve TABLE::next
 
1942
                          pointer.
 
1943
 
 
1944
  NOTE
 
1945
    This function assumes that its caller already acquired LOCK_open mutex.
 
1946
 
 
1947
  RETURN VALUE
 
1948
    FALSE - Success
 
1949
    TRUE  - Error
 
1950
*/
 
1951
 
 
1952
bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in)
 
1953
{
 
1954
  TABLE *table= table_list->table;
 
1955
  TABLE_SHARE *share;
 
1956
  char *table_name= table_list->table_name;
 
1957
  TABLE orig_table;
 
1958
  DBUG_ENTER("reopen_name_locked_table");
 
1959
 
 
1960
  safe_mutex_assert_owner(&LOCK_open);
 
1961
 
 
1962
  if (thd->killed || !table)
 
1963
    DBUG_RETURN(TRUE);
 
1964
 
 
1965
  orig_table= *table;
 
1966
 
 
1967
  if (open_unireg_entry(thd, table, table_list, table_name,
 
1968
                        table->s->table_cache_key.str,
 
1969
                        table->s->table_cache_key.length, thd->mem_root, 0))
 
1970
  {
 
1971
    intern_close_table(table);
 
1972
    /*
 
1973
      If there was an error during opening of table (for example if it
 
1974
      does not exist) '*table' object can be wiped out. To be able
 
1975
      properly release name-lock in this case we should restore this
 
1976
      object to its original state.
 
1977
    */
 
1978
    *table= orig_table;
 
1979
    DBUG_RETURN(TRUE);
 
1980
  }
 
1981
 
 
1982
  share= table->s;
 
1983
  /*
 
1984
    We want to prevent other connections from opening this table until end
 
1985
    of statement as it is likely that modifications of table's metadata are
 
1986
    not yet finished (for example CREATE TRIGGER have to change .TRG file,
 
1987
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1988
    This also allows us to assume that no other connection will sneak in
 
1989
    before we will get table-level lock on this table.
 
1990
  */
 
1991
  share->version=0;
 
1992
  table->in_use = thd;
 
1993
  check_unused();
 
1994
 
 
1995
  if (link_in)
 
1996
  {
 
1997
    table->next= thd->open_tables;
 
1998
    thd->open_tables= table;
 
1999
  }
 
2000
  else
 
2001
  {
 
2002
    /*
 
2003
      TABLE object should be already in THD::open_tables list so we just
 
2004
      need to set TABLE::next correctly.
 
2005
    */
 
2006
    table->next= orig_table.next;
 
2007
  }
 
2008
 
 
2009
  table->tablenr=thd->current_tablenr++;
 
2010
  table->used_fields=0;
 
2011
  table->const_table=0;
 
2012
  table->null_row= table->maybe_null= table->force_index= 0;
 
2013
  table->status=STATUS_NO_RECORD;
 
2014
  DBUG_RETURN(FALSE);
 
2015
}
 
2016
 
 
2017
 
 
2018
/**
 
2019
    Create and insert into table cache placeholder for table
 
2020
    which will prevent its opening (or creation) (a.k.a lock
 
2021
    table name).
 
2022
 
 
2023
    @param thd         Thread context
 
2024
    @param key         Table cache key for name to be locked
 
2025
    @param key_length  Table cache key length
 
2026
 
 
2027
    @return Pointer to TABLE object used for name locking or 0 in
 
2028
            case of failure.
 
2029
*/
 
2030
 
 
2031
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
 
2032
                                      uint key_length)
 
2033
{
 
2034
  TABLE *table;
 
2035
  TABLE_SHARE *share;
 
2036
  char *key_buff;
 
2037
  DBUG_ENTER("table_cache_insert_placeholder");
 
2038
 
 
2039
  safe_mutex_assert_owner(&LOCK_open);
797
2040
 
798
2041
  /*
799
2042
    Create a table entry with the right key and with an old refresh version
 
2043
    Note that we must use my_multi_malloc() here as this is freed by the
 
2044
    table cache
800
2045
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
803
 
 
804
 
  if (not table::Cache::singleton().insert(table))
 
2046
  if (!my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
 
2047
                       &table, sizeof(*table),
 
2048
                       &share, sizeof(*share),
 
2049
                       &key_buff, key_length,
 
2050
                       NULL))
 
2051
    DBUG_RETURN(NULL);
 
2052
 
 
2053
  table->s= share;
 
2054
  share->set_table_cache_key(key_buff, key, key_length);
 
2055
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
 
2056
  table->in_use= thd;
 
2057
  table->locked_by_name=1;
 
2058
 
 
2059
  if (my_hash_insert(&open_cache, (uchar*)table))
805
2060
  {
806
 
    delete table;
807
 
 
808
 
    return NULL;
 
2061
    my_free((uchar*) table, MYF(0));
 
2062
    DBUG_RETURN(NULL);
809
2063
  }
810
2064
 
811
 
  return table;
 
2065
  DBUG_RETURN(table);
812
2066
}
813
2067
 
814
2068
 
815
2069
/**
816
 
  Obtain an exclusive name lock on the table if it is not cached
817
 
  in the table cache.
818
 
 
819
 
  @param      session         Thread context
820
 
  @param      db          Name of database
821
 
  @param      table_name  Name of table
822
 
  @param[out] table       Out parameter which is either:
823
 
  - set to NULL if table cache contains record for
824
 
  the table or
825
 
  - set to point to the Table instance used for
826
 
  name-locking.
827
 
 
828
 
  @note This function takes into account all records for table in table
829
 
  cache, even placeholders used for name-locking. This means that
830
 
  'table' parameter can be set to NULL for some situations when
831
 
  table does not really exist.
832
 
 
833
 
  @retval  true   Error occured (OOM)
834
 
  @retval  false  Success. 'table' parameter set according to above rules.
 
2070
    Obtain an exclusive name lock on the table if it is not cached
 
2071
    in the table cache.
 
2072
 
 
2073
    @param      thd         Thread context
 
2074
    @param      db          Name of database
 
2075
    @param      table_name  Name of table
 
2076
    @param[out] table       Out parameter which is either:
 
2077
                            - set to NULL if table cache contains record for
 
2078
                              the table or
 
2079
                            - set to point to the TABLE instance used for
 
2080
                              name-locking.
 
2081
 
 
2082
    @note This function takes into account all records for table in table
 
2083
          cache, even placeholders used for name-locking. This means that
 
2084
          'table' parameter can be set to NULL for some situations when
 
2085
          table does not really exist.
 
2086
 
 
2087
    @retval  TRUE   Error occured (OOM)
 
2088
    @retval  FALSE  Success. 'table' parameter set according to above rules.
835
2089
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
2090
 
 
2091
bool lock_table_name_if_not_cached(THD *thd, const char *db,
 
2092
                                   const char *table_name, TABLE **table)
837
2093
{
838
 
  const TableIdentifier::Key &key(identifier.getKey());
839
 
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
2094
  char key[MAX_DBKEY_LENGTH];
 
2095
  uint key_length;
 
2096
  DBUG_ENTER("lock_table_name_if_not_cached");
 
2097
 
 
2098
  key_length= (uint)(strmov(strmov(key, db) + 1, table_name) - key) + 1;
 
2099
  VOID(pthread_mutex_lock(&LOCK_open));
 
2100
 
 
2101
  if (hash_search(&open_cache, (uchar *)key, key_length))
847
2102
  {
 
2103
    VOID(pthread_mutex_unlock(&LOCK_open));
 
2104
    DBUG_PRINT("info", ("Table is cached, name-lock is not obtained"));
848
2105
    *table= 0;
849
 
    return false;
850
 
  }
851
 
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
853
 
  {
854
 
    return true;
855
 
  }
856
 
  (*table)->open_placeholder= true;
857
 
  (*table)->setNext(open_tables);
858
 
  open_tables= *table;
859
 
 
860
 
  return false;
861
 
}
 
2106
    DBUG_RETURN(FALSE);
 
2107
  }
 
2108
  if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
 
2109
  {
 
2110
    VOID(pthread_mutex_unlock(&LOCK_open));
 
2111
    DBUG_RETURN(TRUE);
 
2112
  }
 
2113
  (*table)->open_placeholder= 1;
 
2114
  (*table)->next= thd->open_tables;
 
2115
  thd->open_tables= *table;
 
2116
  VOID(pthread_mutex_unlock(&LOCK_open));
 
2117
  DBUG_RETURN(FALSE);
 
2118
}
 
2119
 
 
2120
 
 
2121
/**
 
2122
    Check that table exists in table definition cache, on disk
 
2123
    or in some storage engine.
 
2124
 
 
2125
    @param       thd     Thread context
 
2126
    @param       table   Table list element
 
2127
    @param[out]  exists  Out parameter which is set to TRUE if table
 
2128
                         exists and to FALSE otherwise.
 
2129
 
 
2130
    @note This function assumes that caller owns LOCK_open mutex.
 
2131
          It also assumes that the fact that there are no name-locks
 
2132
          on the table was checked beforehand.
 
2133
 
 
2134
    @note If there is no .FRM file for the table but it exists in one
 
2135
          of engines (e.g. it was created on another node of NDB cluster)
 
2136
          this function will fetch and create proper .FRM file for it.
 
2137
 
 
2138
    @retval  TRUE   Some error occured
 
2139
    @retval  FALSE  No error. 'exists' out parameter set accordingly.
 
2140
*/
 
2141
 
 
2142
bool check_if_table_exists(THD *thd, TABLE_LIST *table, bool *exists)
 
2143
{
 
2144
  char path[FN_REFLEN];
 
2145
  int rc;
 
2146
  DBUG_ENTER("check_if_table_exists");
 
2147
 
 
2148
  safe_mutex_assert_owner(&LOCK_open);
 
2149
 
 
2150
  *exists= TRUE;
 
2151
 
 
2152
  if (get_cached_table_share(table->db, table->table_name))
 
2153
    DBUG_RETURN(FALSE);
 
2154
 
 
2155
  build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
 
2156
                       reg_ext, 0);
 
2157
 
 
2158
  if (!access(path, F_OK))
 
2159
    DBUG_RETURN(FALSE);
 
2160
 
 
2161
  /* .FRM file doesn't exist. Check if some engine can provide it. */
 
2162
 
 
2163
  rc= ha_create_table_from_engine(thd, table->db, table->table_name);
 
2164
 
 
2165
  if (rc < 0)
 
2166
  {
 
2167
    /* Table does not exists in engines as well. */
 
2168
    *exists= FALSE;
 
2169
    DBUG_RETURN(FALSE);
 
2170
  }
 
2171
  else if (!rc)
 
2172
  {
 
2173
    /* Table exists in some engine and .FRM for it was created. */
 
2174
    DBUG_RETURN(FALSE);
 
2175
  }
 
2176
  else /* (rc > 0) */
 
2177
  {
 
2178
    my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
 
2179
                    "unpacking from engine", MYF(0), table->table_name);
 
2180
    DBUG_RETURN(TRUE);
 
2181
  }
 
2182
}
 
2183
 
862
2184
 
863
2185
/*
864
2186
  Open a table.
865
2187
 
866
2188
  SYNOPSIS
867
 
  open_table()
868
 
  session                 Thread context.
869
 
  table_list          Open first table in list.
870
 
  refresh      INOUT  Pointer to memory that will be set to 1 if
871
 
  we need to close all tables and reopen them.
872
 
  If this is a NULL pointer, then the table is not
873
 
  put in the thread-open-list.
874
 
  flags               Bitmap of flags to modify how open works:
875
 
  DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
876
 
  someone has done a flush or namelock on it.
877
 
  No version number checking is done.
878
 
  DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
879
 
  table not the base table or view.
 
2189
    open_table()
 
2190
    thd                 Thread context.
 
2191
    table_list          Open first table in list.
 
2192
    refresh      INOUT  Pointer to memory that will be set to 1 if
 
2193
                        we need to close all tables and reopen them.
 
2194
                        If this is a NULL pointer, then the table is not
 
2195
                        put in the thread-open-list.
 
2196
    flags               Bitmap of flags to modify how open works:
 
2197
                          MYSQL_LOCK_IGNORE_FLUSH - Open table even if
 
2198
                          someone has done a flush or namelock on it.
 
2199
                          No version number checking is done.
 
2200
                          MYSQL_OPEN_TEMPORARY_ONLY - Open only temporary
 
2201
                          table not the base table or view.
880
2202
 
881
2203
  IMPLEMENTATION
882
 
  Uses a cache of open tables to find a table not in use.
 
2204
    Uses a cache of open tables to find a table not in use.
883
2205
 
884
 
  If table list element for the table to be opened has "create" flag
885
 
  set and table does not exist, this function will automatically insert
886
 
  a placeholder for exclusive name lock into the open tables cache and
887
 
  will return the Table instance that corresponds to this placeholder.
 
2206
    If table list element for the table to be opened has "create" flag
 
2207
    set and table does not exist, this function will automatically insert
 
2208
    a placeholder for exclusive name lock into the open tables cache and
 
2209
    will return the TABLE instance that corresponds to this placeholder.
888
2210
 
889
2211
  RETURN
890
 
  NULL  Open failed.  If refresh is set then one should close
891
 
  all other tables and retry the open.
892
 
#     Success. Pointer to Table object for open table.
 
2212
    NULL  Open failed.  If refresh is set then one should close
 
2213
          all other tables and retry the open.
 
2214
    #     Success. Pointer to TABLE object for open table.
893
2215
*/
894
2216
 
895
2217
 
896
 
Table *Session::openTable(TableList *table_list, bool *refresh, uint32_t flags)
 
2218
TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
 
2219
                  bool *refresh, uint flags)
897
2220
{
898
 
  Table *table;
899
 
  const char *alias= table_list->alias;
 
2221
  register TABLE *table;
 
2222
  char key[MAX_DBKEY_LENGTH];
 
2223
  unsigned int key_length;
 
2224
  char *alias= table_list->alias;
 
2225
  HASH_SEARCH_STATE state;
 
2226
  DBUG_ENTER("open_table");
900
2227
 
901
 
  /* Parsing of partitioning information from .frm needs session->lex set up. */
902
 
  assert(lex->is_lex_started);
 
2228
  /* Parsing of partitioning information from .frm needs thd->lex set up. */
 
2229
  DBUG_ASSERT(thd->lex->is_lex_started);
903
2230
 
904
2231
  /* find a unused table in the open table cache */
905
2232
  if (refresh)
906
 
    *refresh= false;
 
2233
    *refresh=0;
907
2234
 
908
2235
  /* an open table operation needs a lot of the stack space */
909
 
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
 
    return NULL;
911
 
 
912
 
  if (getKilled())
913
 
    return NULL;
914
 
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
916
 
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
2236
  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
 
2237
    DBUG_RETURN(0);
 
2238
 
 
2239
  if (thd->killed)
 
2240
    DBUG_RETURN(0);
 
2241
 
 
2242
  key_length= (create_table_def_key(thd, key, table_list, 1) -
 
2243
               TMP_TABLE_KEY_EXTRA);
918
2244
 
919
2245
  /*
920
2246
    Unless requested otherwise, try to resolve this table in the list
921
2247
    of temporary tables of this thread. In MySQL temporary tables
922
2248
    are always thread-local and "shadow" possible base tables with the
923
2249
    same name. This block implements the behaviour.
924
 
    TODO -> move this block into a separate function.
 
2250
    TODO: move this block into a separate function.
925
2251
  */
926
 
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
928
 
  {
929
 
    if (table->getShare()->getCacheKey() == key)
930
 
    {
931
 
      /*
932
 
        We're trying to use the same temporary table twice in a query.
933
 
        Right now we don't support this because a temporary table
934
 
        is always represented by only one Table object in Session, and
935
 
        it can not be cloned. Emit an error for an unsupported behaviour.
936
 
      */
937
 
      if (table->query_id)
938
 
      {
939
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
940
 
        return NULL;
941
 
      }
942
 
      table->query_id= getQueryId();
943
 
      reset= true;
944
 
      break;
945
 
    }
946
 
  }
947
 
 
948
 
  if (not reset)
949
 
  {
950
 
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
 
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
953
 
      return NULL;
954
 
    }
955
 
 
956
 
    /*
957
 
      If it's the first table from a list of tables used in a query,
958
 
      remember refresh_version (the version of open_cache state).
959
 
      If the version changes while we're opening the remaining tables,
960
 
      we will have to back off, close all the tables opened-so-far,
961
 
      and try to reopen them.
962
 
 
963
 
      Note-> refresh_version is currently changed only during FLUSH TABLES.
964
 
    */
965
 
    if (!open_tables)
966
 
    {
967
 
      version= refresh_version;
968
 
    }
969
 
    else if ((version != refresh_version) &&
970
 
             ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
971
 
    {
972
 
      /* Someone did a refresh while thread was opening tables */
973
 
      if (refresh)
974
 
        *refresh= true;
975
 
 
976
 
      return NULL;
977
 
    }
978
 
 
979
 
    /*
980
 
      Before we test the global cache, we test our local session cache.
981
 
    */
982
 
    if (cached_table)
983
 
    {
984
 
      assert(false); /* Not implemented yet */
985
 
    }
986
 
 
987
 
    /*
988
 
      Non pre-locked/LOCK TABLES mode, and the table is not temporary:
989
 
      this is the normal use case.
990
 
      Now we should:
991
 
      - try to find the table in the table cache.
992
 
      - if one of the discovered Table instances is name-locked
993
 
      (table->getShare()->version == 0) back off -- we have to wait
994
 
      until no one holds a name lock on the table.
995
 
      - if there is no such Table in the name cache, read the table definition
996
 
      and insert it into the cache.
997
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
998
 
      the open cache (also known as table cache) and table definitions stored
999
 
      on disk.
1000
 
    */
1001
 
 
1002
 
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
1004
 
 
1005
 
      /*
1006
 
        Actually try to find the table in the open_cache.
1007
 
        The cache may contain several "Table" instances for the same
1008
 
        physical table. The instances that are currently "in use" by
1009
 
        some thread have their "in_use" member != NULL.
1010
 
        There is no good reason for having more than one entry in the
1011
 
        hash for the same physical table, except that we use this as
1012
 
        an implicit "pending locks queue" - see
1013
 
        wait_for_locked_table_names for details.
1014
 
      */
1015
 
      ppp= table::getCache().equal_range(key);
1016
 
 
1017
 
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
1019
 
           iter != ppp.second; ++iter, table= NULL)
1020
 
      {
1021
 
        table= (*iter).second;
1022
 
 
1023
 
        if (not table->in_use)
1024
 
          break;
 
2252
  {
 
2253
    for (table= thd->temporary_tables; table ; table=table->next)
 
2254
    {
 
2255
      if (table->s->table_cache_key.length == key_length +
 
2256
          TMP_TABLE_KEY_EXTRA &&
 
2257
          !memcmp(table->s->table_cache_key.str, key,
 
2258
                  key_length + TMP_TABLE_KEY_EXTRA))
 
2259
      {
1025
2260
        /*
1026
 
          Here we flush tables marked for flush.
1027
 
          Normally, table->getShare()->version contains the value of
1028
 
          refresh_version from the moment when this table was
1029
 
          (re-)opened and added to the cache.
1030
 
          If since then we did (or just started) FLUSH TABLES
1031
 
          statement, refresh_version has been increased.
1032
 
          For "name-locked" Table instances, table->getShare()->version is set
1033
 
          to 0 (see lock_table_name for details).
1034
 
          In case there is a pending FLUSH TABLES or a name lock, we
1035
 
          need to back off and re-start opening tables.
1036
 
          If we do not back off now, we may dead lock in case of lock
1037
 
          order mismatch with some other thread:
1038
 
          c1-> name lock t1; -- sort of exclusive lock
1039
 
          c2-> open t2;      -- sort of shared lock
1040
 
          c1-> name lock t2; -- blocks
1041
 
          c2-> open t1; -- blocks
 
2261
          We're trying to use the same temporary table twice in a query.
 
2262
          Right now we don't support this because a temporary table
 
2263
          is always represented by only one TABLE object in THD, and
 
2264
          it can not be cloned. Emit an error for an unsupported behaviour.
1042
2265
        */
1043
 
        if (table->needs_reopen_or_name_lock())
 
2266
        if (table->query_id)
 
2267
        {
 
2268
          DBUG_PRINT("error",
 
2269
                     ("query_id: %lu  server_id: %u  pseudo_thread_id: %lu",
 
2270
                      (ulong) table->query_id, (uint) thd->server_id,
 
2271
                      (ulong) thd->variables.pseudo_thread_id));
 
2272
          my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
2273
          DBUG_RETURN(0);
 
2274
        }
 
2275
        table->query_id= thd->query_id;
 
2276
        thd->thread_specific_used= TRUE;
 
2277
        DBUG_PRINT("info",("Using temporary table"));
 
2278
        goto reset;
 
2279
      }
 
2280
    }
 
2281
  }
 
2282
 
 
2283
  if (flags & MYSQL_OPEN_TEMPORARY_ONLY)
 
2284
  {
 
2285
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
 
2286
    DBUG_RETURN(0);
 
2287
  }
 
2288
 
 
2289
  /*
 
2290
    The table is not temporary - if we're in pre-locked or LOCK TABLES
 
2291
    mode, let's try to find the requested table in the list of pre-opened
 
2292
    and locked tables. If the table is not there, return an error - we can't
 
2293
    open not pre-opened tables in pre-locked/LOCK TABLES mode.
 
2294
    TODO: move this block into a separate function.
 
2295
  */
 
2296
  if (thd->locked_tables)
 
2297
  {                                             // Using table locks
 
2298
    TABLE *best_table= 0;
 
2299
    int best_distance= INT_MIN;
 
2300
    bool check_if_used= false;
 
2301
    for (table=thd->open_tables; table ; table=table->next)
 
2302
    {
 
2303
      if (table->s->table_cache_key.length == key_length &&
 
2304
          !memcmp(table->s->table_cache_key.str, key, key_length))
 
2305
      {
 
2306
        if (check_if_used && table->query_id &&
 
2307
            table->query_id != thd->query_id)
1044
2308
        {
1045
 
          if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
1046
 
          {
1047
 
            /* Force close at once after usage */
1048
 
            version= table->getShare()->getVersion();
1049
 
            continue;
1050
 
          }
1051
 
 
1052
 
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
 
          if (table->open_placeholder && table->in_use == this)
1054
 
          {
1055
 
            table::Cache::singleton().mutex().unlock();
1056
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1057
 
            return NULL;
1058
 
          }
1059
 
 
1060
 
          /*
1061
 
            Back off, part 1: mark the table as "unused" for the
1062
 
            purpose of name-locking by setting table->db_stat to 0. Do
1063
 
            that only for the tables in this thread that have an old
1064
 
            table->getShare()->version (this is an optimization (?)).
1065
 
            table->db_stat == 0 signals wait_for_locked_table_names
1066
 
            that the tables in question are not used any more. See
1067
 
            table_is_used call for details.
1068
 
          */
1069
 
          close_old_data_files(false, false);
1070
 
 
1071
 
          /*
1072
 
            Back-off part 2: try to avoid "busy waiting" on the table:
1073
 
            if the table is in use by some other thread, we suspend
1074
 
            and wait till the operation is complete: when any
1075
 
            operation that juggles with table->getShare()->version completes,
1076
 
            it broadcasts COND_refresh condition variable.
1077
 
            If 'old' table we met is in use by current thread we return
1078
 
            without waiting since in this situation it's this thread
1079
 
            which is responsible for broadcasting on COND_refresh
1080
 
            (and this was done already in Session::close_old_data_files()).
1081
 
            Good example of such situation is when we have statement
1082
 
            that needs two instances of table and FLUSH TABLES comes
1083
 
            after we open first instance but before we open second
1084
 
            instance.
1085
 
          */
1086
 
          if (table->in_use != this)
1087
 
          {
1088
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1090
 
          }
1091
 
          else
1092
 
          {
1093
 
            table::Cache::singleton().mutex().unlock();
1094
 
          }
1095
 
          /*
1096
 
            There is a refresh in progress for this table.
1097
 
            Signal the caller that it has to try again.
1098
 
          */
1099
 
          if (refresh)
1100
 
            *refresh= true;
1101
 
          return NULL;
 
2309
          /*
 
2310
            If we are in stored function or trigger we should ensure that
 
2311
            we won't change table that is already used by calling statement.
 
2312
            So if we are opening table for writing, we should check that it
 
2313
            is not already open by some calling stamement.
 
2314
          */
 
2315
          my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
 
2316
                   table->s->table_name.str);
 
2317
          DBUG_RETURN(0);
1102
2318
        }
1103
 
      }
1104
 
      if (table)
1105
 
      {
1106
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
1107
 
        table->in_use= this;
1108
 
      }
1109
 
      else
1110
 
      {
1111
 
        /* Insert a new Table instance into the open cache */
1112
 
        int error;
1113
 
        /* Free cache if too big */
1114
 
        table::getUnused().cull();
1115
 
 
1116
 
        if (table_list->isCreate())
 
2319
        /*
 
2320
          When looking for a usable TABLE, ignore MERGE children, as they
 
2321
          belong to their parent and cannot be used explicitly.
 
2322
        */
 
2323
        if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
 
2324
            table->query_id != thd->query_id)  /* skip tables already used */
1117
2325
        {
1118
 
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
 
2326
          int distance= ((int) table->reginfo.lock_type -
 
2327
                         (int) table_list->lock_type);
 
2328
          /*
 
2329
            Find a table that either has the exact lock type requested,
 
2330
            or has the best suitable lock. In case there is no locked
 
2331
            table that has an equal or higher lock than requested,
 
2332
            we us the closest matching lock to be able to produce an error
 
2333
            message about wrong lock mode on the table. The best_table
 
2334
            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
1119
2335
 
1120
 
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
 
2336
            distance <  0 - No suitable lock found
 
2337
            distance >  0 - we have lock mode higher then we require
 
2338
            distance == 0 - we have lock mode exactly which we need
 
2339
          */
 
2340
          if ((best_distance < 0 && distance > best_distance) || (distance >= 0 && distance < best_distance))
1121
2341
          {
1122
 
            /*
1123
 
              Table to be created, so we need to create placeholder in table-cache.
1124
 
            */
1125
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
 
2342
            best_distance= distance;
 
2343
            best_table= table;
 
2344
            if (best_distance == 0 && !check_if_used)
1126
2345
            {
1127
 
              table::Cache::singleton().mutex().unlock();
1128
 
              return NULL;
 
2346
              /*
 
2347
                If we have found perfect match and we don't need to check that
 
2348
                table is not used by one of calling statements (assuming that
 
2349
                we are inside of function or trigger) we can finish iterating
 
2350
                through open tables list.
 
2351
              */
 
2352
              break;
1129
2353
            }
1130
 
            /*
1131
 
              Link placeholder to the open tables list so it will be automatically
1132
 
              removed once tables are closed. Also mark it so it won't be ignored
1133
 
              by other trying to take name-lock.
1134
 
            */
1135
 
            table->open_placeholder= true;
1136
 
            table->setNext(open_tables);
1137
 
            open_tables= table;
1138
 
            table::Cache::singleton().mutex().unlock();
1139
 
 
1140
 
            return table ;
1141
 
          }
1142
 
          /* Table exists. Let us try to open it. */
1143
 
        }
1144
 
 
1145
 
        /* make a new table */
1146
 
        {
1147
 
          table::Concurrent *new_table= new table::Concurrent;
1148
 
          table= new_table;
1149
 
          if (new_table == NULL)
1150
 
          {
1151
 
            table::Cache::singleton().mutex().unlock();
1152
 
            return NULL;
1153
 
          }
1154
 
 
1155
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1156
 
          if (error != 0)
1157
 
          {
1158
 
            delete new_table;
1159
 
            table::Cache::singleton().mutex().unlock();
1160
 
            return NULL;
1161
 
          }
1162
 
          (void)table::Cache::singleton().insert(new_table);
 
2354
          }
1163
2355
        }
1164
2356
      }
1165
 
 
1166
 
      table::Cache::singleton().mutex().unlock();
1167
 
    }
 
2357
    }
 
2358
    if (best_table)
 
2359
    {
 
2360
      table= best_table;
 
2361
      table->query_id= thd->query_id;
 
2362
      DBUG_PRINT("info",("Using locked table"));
 
2363
      goto reset;
 
2364
    }
 
2365
    /*
 
2366
      No table in the locked tables list. In case of explicit LOCK TABLES
 
2367
      this can happen if a user did not include the able into the list.
 
2368
      In case of pre-locked mode locked tables list is generated automatically,
 
2369
      so we may only end up here if the table did not exist when
 
2370
      locked tables list was created.
 
2371
    */
 
2372
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
 
2373
    DBUG_RETURN(0);
 
2374
  }
 
2375
 
 
2376
  /*
 
2377
    Non pre-locked/LOCK TABLES mode, and the table is not temporary:
 
2378
    this is the normal use case.
 
2379
    Now we should:
 
2380
    - try to find the table in the table cache.
 
2381
    - if one of the discovered TABLE instances is name-locked
 
2382
      (table->s->version == 0) or some thread has started FLUSH TABLES
 
2383
      (refresh_version > table->s->version), back off -- we have to wait
 
2384
      until no one holds a name lock on the table.
 
2385
    - if there is no such TABLE in the name cache, read the table definition
 
2386
    and insert it into the cache.
 
2387
    We perform all of the above under LOCK_open which currently protects
 
2388
    the open cache (also known as table cache) and table definitions stored
 
2389
    on disk.
 
2390
  */
 
2391
 
 
2392
  VOID(pthread_mutex_lock(&LOCK_open));
 
2393
 
 
2394
  /*
 
2395
    If it's the first table from a list of tables used in a query,
 
2396
    remember refresh_version (the version of open_cache state).
 
2397
    If the version changes while we're opening the remaining tables,
 
2398
    we will have to back off, close all the tables opened-so-far,
 
2399
    and try to reopen them.
 
2400
    Note: refresh_version is currently changed only during FLUSH TABLES.
 
2401
  */
 
2402
  if (!thd->open_tables)
 
2403
    thd->version=refresh_version;
 
2404
  else if ((thd->version != refresh_version) &&
 
2405
           ! (flags & MYSQL_LOCK_IGNORE_FLUSH))
 
2406
  {
 
2407
    /* Someone did a refresh while thread was opening tables */
1168
2408
    if (refresh)
1169
 
    {
1170
 
      table->setNext(open_tables); /* Link into simple list */
1171
 
      open_tables= table;
1172
 
    }
1173
 
    table->reginfo.lock_type= TL_READ; /* Assume read */
1174
 
 
1175
 
  }
1176
 
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
 
 
 
2409
      *refresh=1;
 
2410
    VOID(pthread_mutex_unlock(&LOCK_open));
 
2411
    DBUG_RETURN(0);
 
2412
  }
 
2413
 
 
2414
  /*
 
2415
    In order for the back off and re-start process to work properly,
 
2416
    handler tables having old versions (due to FLUSH TABLES or pending
 
2417
    name-lock) MUST be closed. This is specially important if a name-lock
 
2418
    is pending for any table of the handler_tables list, otherwise a
 
2419
    deadlock may occur.
 
2420
  */
 
2421
  if (thd->handler_tables)
 
2422
    mysql_ha_flush(thd);
 
2423
 
 
2424
  /*
 
2425
    Actually try to find the table in the open_cache.
 
2426
    The cache may contain several "TABLE" instances for the same
 
2427
    physical table. The instances that are currently "in use" by
 
2428
    some thread have their "in_use" member != NULL.
 
2429
    There is no good reason for having more than one entry in the
 
2430
    hash for the same physical table, except that we use this as
 
2431
    an implicit "pending locks queue" - see
 
2432
    wait_for_locked_table_names for details.
 
2433
  */
 
2434
  for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
 
2435
                                  &state);
 
2436
       table && table->in_use ;
 
2437
       table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
 
2438
                                 &state))
 
2439
  {
 
2440
    DBUG_PRINT("tcache", ("in_use table: '%s'.'%s' 0x%lx", table->s->db.str,
 
2441
                          table->s->table_name.str, (long) table));
 
2442
    /*
 
2443
      Here we flush tables marked for flush.
 
2444
      Normally, table->s->version contains the value of
 
2445
      refresh_version from the moment when this table was
 
2446
      (re-)opened and added to the cache.
 
2447
      If since then we did (or just started) FLUSH TABLES
 
2448
      statement, refresh_version has been increased.
 
2449
      For "name-locked" TABLE instances, table->s->version is set
 
2450
      to 0 (see lock_table_name for details).
 
2451
      In case there is a pending FLUSH TABLES or a name lock, we
 
2452
      need to back off and re-start opening tables.
 
2453
      If we do not back off now, we may dead lock in case of lock
 
2454
      order mismatch with some other thread:
 
2455
      c1: name lock t1; -- sort of exclusive lock 
 
2456
      c2: open t2;      -- sort of shared lock
 
2457
      c1: name lock t2; -- blocks
 
2458
      c2: open t1; -- blocks
 
2459
    */
 
2460
    if (table->needs_reopen_or_name_lock())
 
2461
    {
 
2462
      DBUG_PRINT("note",
 
2463
                 ("Found table '%s.%s' with different refresh version",
 
2464
                  table_list->db, table_list->table_name));
 
2465
 
 
2466
      if (flags & MYSQL_LOCK_IGNORE_FLUSH)
 
2467
      {
 
2468
        /* Force close at once after usage */
 
2469
        thd->version= table->s->version;
 
2470
        continue;
 
2471
      }
 
2472
 
 
2473
      /* Avoid self-deadlocks by detecting self-dependencies. */
 
2474
      if (table->open_placeholder && table->in_use == thd)
 
2475
      {
 
2476
        VOID(pthread_mutex_unlock(&LOCK_open));
 
2477
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
 
2478
        DBUG_RETURN(0);
 
2479
      }
 
2480
 
 
2481
      /*
 
2482
        Back off, part 1: mark the table as "unused" for the
 
2483
        purpose of name-locking by setting table->db_stat to 0. Do
 
2484
        that only for the tables in this thread that have an old
 
2485
        table->s->version (this is an optimization (?)).
 
2486
        table->db_stat == 0 signals wait_for_locked_table_names
 
2487
        that the tables in question are not used any more. See
 
2488
        table_is_used call for details.
 
2489
 
 
2490
        Notice that HANDLER tables were already taken care of by
 
2491
        the earlier call to mysql_ha_flush() in this same critical
 
2492
        section.
 
2493
      */
 
2494
      close_old_data_files(thd,thd->open_tables,0,0);
 
2495
      /*
 
2496
        Back-off part 2: try to avoid "busy waiting" on the table:
 
2497
        if the table is in use by some other thread, we suspend
 
2498
        and wait till the operation is complete: when any
 
2499
        operation that juggles with table->s->version completes,
 
2500
        it broadcasts COND_refresh condition variable.
 
2501
        If 'old' table we met is in use by current thread we return
 
2502
        without waiting since in this situation it's this thread
 
2503
        which is responsible for broadcasting on COND_refresh
 
2504
        (and this was done already in close_old_data_files()).
 
2505
        Good example of such situation is when we have statement
 
2506
        that needs two instances of table and FLUSH TABLES comes
 
2507
        after we open first instance but before we open second
 
2508
        instance.
 
2509
      */
 
2510
      if (table->in_use != thd)
 
2511
      {
 
2512
        /* wait_for_conditionwill unlock LOCK_open for us */
 
2513
        wait_for_condition(thd, &LOCK_open, &COND_refresh);
 
2514
      }
 
2515
      else
 
2516
      {
 
2517
        VOID(pthread_mutex_unlock(&LOCK_open));
 
2518
      }
 
2519
      /*
 
2520
        There is a refresh in progress for this table.
 
2521
        Signal the caller that it has to try again.
 
2522
      */
 
2523
      if (refresh)
 
2524
        *refresh=1;
 
2525
      DBUG_RETURN(0);
 
2526
    }
 
2527
  }
 
2528
  if (table)
 
2529
  {
 
2530
    DBUG_PRINT("tcache", ("unused table: '%s'.'%s' 0x%lx", table->s->db.str,
 
2531
                          table->s->table_name.str, (long) table));
 
2532
    /* Unlink the table from "unused_tables" list. */
 
2533
    if (table == unused_tables)
 
2534
    {                                           // First unused
 
2535
      unused_tables=unused_tables->next;        // Remove from link
 
2536
      if (table == unused_tables)
 
2537
        unused_tables=0;
 
2538
    }
 
2539
    table->prev->next=table->next;              /* Remove from unused list */
 
2540
    table->next->prev=table->prev;
 
2541
    table->in_use= thd;
 
2542
  }
 
2543
  else
 
2544
  {
 
2545
    /* Insert a new TABLE instance into the open cache */
 
2546
    int error;
 
2547
    DBUG_PRINT("tcache", ("opening new table"));
 
2548
    /* Free cache if too big */
 
2549
    while (open_cache.records > table_cache_size && unused_tables)
 
2550
      VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
 
2551
 
 
2552
    if (table_list->create)
 
2553
    {
 
2554
      bool exists;
 
2555
 
 
2556
      if (check_if_table_exists(thd, table_list, &exists))
 
2557
      {
 
2558
        VOID(pthread_mutex_unlock(&LOCK_open));
 
2559
        DBUG_RETURN(NULL);
 
2560
      }
 
2561
 
 
2562
      if (!exists)
 
2563
      {
 
2564
        /*
 
2565
          Table to be created, so we need to create placeholder in table-cache.
 
2566
        */
 
2567
        if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
 
2568
        {
 
2569
          VOID(pthread_mutex_unlock(&LOCK_open));
 
2570
          DBUG_RETURN(NULL);
 
2571
        }
 
2572
        /*
 
2573
          Link placeholder to the open tables list so it will be automatically
 
2574
          removed once tables are closed. Also mark it so it won't be ignored
 
2575
          by other trying to take name-lock.
 
2576
        */
 
2577
        table->open_placeholder= 1;
 
2578
        table->next= thd->open_tables;
 
2579
        thd->open_tables= table;
 
2580
        VOID(pthread_mutex_unlock(&LOCK_open));
 
2581
        DBUG_RETURN(table);
 
2582
      }
 
2583
      /* Table exists. Let us try to open it. */
 
2584
    }
 
2585
 
 
2586
    /* make a new table */
 
2587
    if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
 
2588
    {
 
2589
      VOID(pthread_mutex_unlock(&LOCK_open));
 
2590
      DBUG_RETURN(NULL);
 
2591
    }
 
2592
 
 
2593
    error= open_unireg_entry(thd, table, table_list, alias, key, key_length,
 
2594
                             mem_root, (flags & OPEN_VIEW_NO_PARSE));
 
2595
    /* Combine the follow two */
 
2596
    if (error > 0)
 
2597
    {
 
2598
      my_free((uchar*)table, MYF(0));
 
2599
      VOID(pthread_mutex_unlock(&LOCK_open));
 
2600
      DBUG_RETURN(NULL);
 
2601
    }
 
2602
    if (error < 0)
 
2603
    {
 
2604
      my_free((uchar*)table, MYF(0));
 
2605
      VOID(pthread_mutex_unlock(&LOCK_open));
 
2606
      DBUG_RETURN(0); // VIEW
 
2607
    }
 
2608
    DBUG_PRINT("info", ("inserting table '%s'.'%s' 0x%lx into the cache",
 
2609
                        table->s->db.str, table->s->table_name.str,
 
2610
                        (long) table));
 
2611
    VOID(my_hash_insert(&open_cache,(uchar*) table));
 
2612
  }
 
2613
 
 
2614
  check_unused();                               // Debugging call
 
2615
 
 
2616
  VOID(pthread_mutex_unlock(&LOCK_open));
 
2617
  if (refresh)
 
2618
  {
 
2619
    table->next=thd->open_tables;               /* Link into simple list */
 
2620
    thd->open_tables=table;
 
2621
  }
 
2622
  table->reginfo.lock_type=TL_READ;             /* Assume read */
 
2623
 
 
2624
 reset:
 
2625
  DBUG_ASSERT(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
 
2626
 
 
2627
  if (thd->lex->need_correct_ident())
 
2628
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
2629
                                          table->s->table_name.str, alias);
1178
2630
  /* Fix alias if table name changes */
1179
 
  if (strcmp(table->getAlias(), alias))
 
2631
  if (strcmp(table->alias, alias))
1180
2632
  {
1181
 
    table->setAlias(alias);
 
2633
    uint length=(uint) strlen(alias)+1;
 
2634
    table->alias= (char*) my_realloc((char*) table->alias, length,
 
2635
                                     MYF(MY_WME));
 
2636
    memcpy((char*) table->alias, alias, length);
1182
2637
  }
1183
 
 
1184
2638
  /* These variables are also set in reopen_table() */
1185
 
  table->tablenr= current_tablenr++;
1186
 
  table->used_fields= 0;
1187
 
  table->const_table= 0;
1188
 
  table->null_row= false;
1189
 
  table->maybe_null= false;
1190
 
  table->force_index= false;
 
2639
  table->tablenr=thd->current_tablenr++;
 
2640
  table->used_fields=0;
 
2641
  table->const_table=0;
 
2642
  table->null_row= table->maybe_null= table->force_index= 0;
1191
2643
  table->status=STATUS_NO_RECORD;
1192
 
  table->insert_values.clear();
 
2644
  table->insert_values= 0;
 
2645
  table->fulltext_searched= 0;
 
2646
  table->file->ft_handler= 0;
1193
2647
  /* Catch wrong handling of the auto_increment_field_not_null. */
1194
 
  assert(!table->auto_increment_field_not_null);
1195
 
  table->auto_increment_field_not_null= false;
 
2648
  DBUG_ASSERT(!table->auto_increment_field_not_null);
 
2649
  table->auto_increment_field_not_null= FALSE;
1196
2650
  if (table->timestamp_field)
1197
 
  {
1198
2651
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1199
 
  }
1200
2652
  table->pos_in_table_list= table_list;
1201
2653
  table->clear_column_bitmaps();
1202
 
  assert(table->key_read == 0);
1203
 
 
1204
 
  return table;
 
2654
  DBUG_ASSERT(table->key_read == 0);
 
2655
  DBUG_RETURN(table);
 
2656
}
 
2657
 
 
2658
 
 
2659
TABLE *find_locked_table(THD *thd, const char *db,const char *table_name)
 
2660
{
 
2661
  char  key[MAX_DBKEY_LENGTH];
 
2662
  uint key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
 
2663
 
 
2664
  for (TABLE *table=thd->open_tables; table ; table=table->next)
 
2665
  {
 
2666
    if (table->s->table_cache_key.length == key_length &&
 
2667
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
2668
      return table;
 
2669
  }
 
2670
  return(0);
 
2671
}
 
2672
 
 
2673
 
 
2674
/*
 
2675
  Reopen an table because the definition has changed.
 
2676
 
 
2677
  SYNOPSIS
 
2678
    reopen_table()
 
2679
    table       Table object
 
2680
 
 
2681
  NOTES
 
2682
   The data file for the table is already closed and the share is released
 
2683
   The table has a 'dummy' share that mainly contains database and table name.
 
2684
 
 
2685
 RETURN
 
2686
   0  ok
 
2687
   1  error. The old table object is not changed.
 
2688
*/
 
2689
 
 
2690
bool reopen_table(TABLE *table)
 
2691
{
 
2692
  TABLE tmp;
 
2693
  bool error= 1;
 
2694
  Field **field;
 
2695
  uint key,part;
 
2696
  TABLE_LIST table_list;
 
2697
  THD *thd= table->in_use;
 
2698
  DBUG_ENTER("reopen_table");
 
2699
  DBUG_PRINT("tcache", ("table: '%s'.'%s' 0x%lx", table->s->db.str,
 
2700
                        table->s->table_name.str, (long) table));
 
2701
 
 
2702
  DBUG_ASSERT(table->s->ref_count == 0);
 
2703
  DBUG_ASSERT(!table->sort.io_cache);
 
2704
 
 
2705
#ifdef EXTRA_DEBUG
 
2706
  if (table->db_stat)
 
2707
    sql_print_error("Table %s had a open data handler in reopen_table",
 
2708
                    table->alias);
 
2709
#endif
 
2710
  bzero((char*) &table_list, sizeof(TABLE_LIST));
 
2711
  table_list.db=         table->s->db.str;
 
2712
  table_list.table_name= table->s->table_name.str;
 
2713
  table_list.table=      table;
 
2714
 
 
2715
  if (wait_for_locked_table_names(thd, &table_list))
 
2716
    DBUG_RETURN(1);                             // Thread was killed
 
2717
 
 
2718
  if (open_unireg_entry(thd, &tmp, &table_list,
 
2719
                        table->alias,
 
2720
                        table->s->table_cache_key.str,
 
2721
                        table->s->table_cache_key.length,
 
2722
                        thd->mem_root, 0))
 
2723
    goto end;
 
2724
 
 
2725
  /* This list copies variables set by open_table */
 
2726
  tmp.tablenr=          table->tablenr;
 
2727
  tmp.used_fields=      table->used_fields;
 
2728
  tmp.const_table=      table->const_table;
 
2729
  tmp.null_row=         table->null_row;
 
2730
  tmp.maybe_null=       table->maybe_null;
 
2731
  tmp.status=           table->status;
 
2732
 
 
2733
  tmp.s->table_map_id=  table->s->table_map_id;
 
2734
 
 
2735
  /* Get state */
 
2736
  tmp.in_use=           thd;
 
2737
  tmp.reginfo.lock_type=table->reginfo.lock_type;
 
2738
 
 
2739
  /* Replace table in open list */
 
2740
  tmp.next=             table->next;
 
2741
  tmp.prev=             table->prev;
 
2742
 
 
2743
  if (table->file)
 
2744
    VOID(closefrm(table, 1));           // close file, free everything
 
2745
 
 
2746
  *table= tmp;
 
2747
  table->default_column_bitmaps();
 
2748
  table->file->change_table_ptr(table, table->s);
 
2749
 
 
2750
  DBUG_ASSERT(table->alias != 0);
 
2751
  for (field=table->field ; *field ; field++)
 
2752
  {
 
2753
    (*field)->table= (*field)->orig_table= table;
 
2754
    (*field)->table_name= &table->alias;
 
2755
  }
 
2756
  for (key=0 ; key < table->s->keys ; key++)
 
2757
  {
 
2758
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
 
2759
      table->key_info[key].key_part[part].field->table= table;
 
2760
  }
 
2761
  /*
 
2762
    Do not attach MERGE children here. The children might be reopened
 
2763
    after the parent. Attach children after reopening all tables that
 
2764
    require reopen. See for example reopen_tables().
 
2765
  */
 
2766
 
 
2767
  broadcast_refresh();
 
2768
  error=0;
 
2769
 
 
2770
 end:
 
2771
  DBUG_RETURN(error);
1205
2772
}
1206
2773
 
1207
2774
 
1208
2775
/**
1209
 
  Close all instances of a table open by this thread and replace
1210
 
  them with exclusive name-locks.
1211
 
 
1212
 
  @param session        Thread context
1213
 
  @param db         Database name for the table to be closed
1214
 
  @param table_name Name of the table to be closed
1215
 
 
1216
 
  @note This function assumes that if we are not under LOCK TABLES,
1217
 
  then there is only one table open and locked. This means that
1218
 
  the function probably has to be adjusted before it can be used
1219
 
  anywhere outside ALTER Table.
1220
 
 
1221
 
  @note Must not use TableShare::table_name/db of the table being closed,
1222
 
  the strings are used in a loop even after the share may be freed.
 
2776
    Close all instances of a table open by this thread and replace
 
2777
    them with exclusive name-locks.
 
2778
 
 
2779
    @param thd        Thread context
 
2780
    @param db         Database name for the table to be closed
 
2781
    @param table_name Name of the table to be closed
 
2782
 
 
2783
    @note This function assumes that if we are not under LOCK TABLES,
 
2784
          then there is only one table open and locked. This means that
 
2785
          the function probably has to be adjusted before it can be used
 
2786
          anywhere outside ALTER TABLE.
 
2787
 
 
2788
    @note Must not use TABLE_SHARE::table_name/db of the table being closed,
 
2789
          the strings are used in a loop even after the share may be freed.
1223
2790
*/
1224
2791
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
2792
void close_data_files_and_morph_locks(THD *thd, const char *db,
 
2793
                                      const char *table_name)
1226
2794
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1228
 
 
1229
 
  if (lock)
 
2795
  TABLE *table;
 
2796
  DBUG_ENTER("close_data_files_and_morph_locks");
 
2797
 
 
2798
  safe_mutex_assert_owner(&LOCK_open);
 
2799
 
 
2800
  if (thd->lock)
1230
2801
  {
1231
2802
    /*
1232
2803
      If we are not under LOCK TABLES we should have only one table
1233
2804
      open and locked so it makes sense to remove the lock at once.
1234
2805
    */
1235
 
    unlockTables(lock);
1236
 
    lock= 0;
 
2806
    mysql_unlock_tables(thd, thd->lock);
 
2807
    thd->lock= 0;
1237
2808
  }
1238
2809
 
1239
2810
  /*
1240
2811
    Note that open table list may contain a name-lock placeholder
1241
 
    for target table name if we process ALTER Table ... RENAME.
 
2812
    for target table name if we process ALTER TABLE ... RENAME.
1242
2813
    So loop below makes sense even if we are not under LOCK TABLES.
1243
2814
  */
1244
 
  for (Table *table= open_tables; table ; table=table->getNext())
 
2815
  for (table=thd->open_tables; table ; table=table->next)
1245
2816
  {
1246
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
2817
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2818
        !strcmp(table->s->db.str, db))
1247
2819
    {
1248
 
      table->open_placeholder= true;
 
2820
      if (thd->locked_tables)
 
2821
      {
 
2822
        mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
 
2823
      }
 
2824
      table->open_placeholder= 1;
1249
2825
      close_handle_and_leave_table_as_lock(table);
1250
2826
    }
1251
2827
  }
 
2828
  DBUG_VOID_RETURN;
1252
2829
}
1253
2830
 
1254
2831
 
1255
2832
/**
1256
 
  Reopen all tables with closed data files.
1257
 
 
1258
 
  @param session         Thread context
1259
 
  @param get_locks   Should we get locks after reopening tables ?
1260
 
  @param mark_share_as_old  Mark share as old to protect from a impending
1261
 
  global read lock.
1262
 
 
1263
 
  @note Since this function can't properly handle prelocking and
1264
 
  create placeholders it should be used in very special
1265
 
  situations like FLUSH TABLES or ALTER Table. In general
1266
 
  case one should just repeat open_tables()/lock_tables()
1267
 
  combination when one needs tables to be reopened (for
1268
 
  example see openTablesLock()).
1269
 
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
1271
 
 
1272
 
  @return false in case of success, true - otherwise.
 
2833
    Reopen all tables with closed data files.
 
2834
 
 
2835
    @param thd         Thread context
 
2836
    @param get_locks   Should we get locks after reopening tables ?
 
2837
    @param mark_share_as_old  Mark share as old to protect from a impending
 
2838
                              global read lock.
 
2839
 
 
2840
    @note Since this function can't properly handle prelocking and
 
2841
          create placeholders it should be used in very special
 
2842
          situations like FLUSH TABLES or ALTER TABLE. In general
 
2843
          case one should just repeat open_tables()/lock_tables()
 
2844
          combination when one needs tables to be reopened (for
 
2845
          example see open_and_lock_tables()).
 
2846
 
 
2847
    @note One should have lock on LOCK_open when calling this.
 
2848
 
 
2849
    @return FALSE in case of success, TRUE - otherwise.
1273
2850
*/
1274
2851
 
1275
 
bool Session::reopen_tables(bool get_locks, bool)
 
2852
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1276
2853
{
1277
 
  Table *table,*next,**prev;
1278
 
  Table **tables,**tables_ptr;                  // For locks
 
2854
  TABLE *table,*next,**prev;
 
2855
  TABLE **tables,**tables_ptr;                  // For locks
1279
2856
  bool error=0, not_used;
1280
 
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1281
 
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1282
 
    DRIZZLE_LOCK_IGNORE_FLUSH;
1283
 
 
1284
 
  if (open_tables == NULL)
1285
 
    return false;
1286
 
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
2857
  const uint flags= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN |
 
2858
                    MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK |
 
2859
                    MYSQL_LOCK_IGNORE_FLUSH;
 
2860
 
 
2861
  DBUG_ENTER("reopen_tables");
 
2862
 
 
2863
  if (!thd->open_tables)
 
2864
    DBUG_RETURN(0);
 
2865
 
 
2866
  safe_mutex_assert_owner(&LOCK_open);
1288
2867
  if (get_locks)
1289
2868
  {
1290
2869
    /*
1291
2870
      The ptr is checked later
1292
2871
      Do not handle locks of MERGE children.
1293
2872
    */
1294
 
    uint32_t opens= 0;
1295
 
 
1296
 
    for (table= open_tables; table ; table=table->getNext())
1297
 
    {
 
2873
    uint opens=0;
 
2874
    for (table= thd->open_tables; table ; table=table->next)
1298
2875
      opens++;
1299
 
    }
1300
 
    tables= new Table *[opens];
 
2876
    DBUG_PRINT("tcache", ("open tables to lock: %u", opens));
 
2877
    tables= (TABLE**) my_alloca(sizeof(TABLE*)*opens);
1301
2878
  }
1302
2879
  else
1303
 
  {
1304
 
    tables= &open_tables;
1305
 
  }
 
2880
    tables= &thd->open_tables;
1306
2881
  tables_ptr =tables;
1307
2882
 
1308
 
  prev= &open_tables;
1309
 
  for (table= open_tables; table ; table=next)
 
2883
  prev= &thd->open_tables;
 
2884
  for (table=thd->open_tables; table ; table=next)
1310
2885
  {
1311
 
    next= table->getNext();
1312
 
 
1313
 
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
1315
 
    error= 1;
 
2886
    uint db_stat=table->db_stat;
 
2887
    next=table->next;
 
2888
    if (!tables || (!db_stat && reopen_table(table)))
 
2889
    {
 
2890
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
2891
      VOID(hash_delete(&open_cache,(uchar*) table));
 
2892
      error=1;
 
2893
    }
 
2894
    else
 
2895
    {
 
2896
      *prev= table;
 
2897
      prev= &table->next;
 
2898
      /* Do not handle locks of MERGE children. */
 
2899
      if (get_locks && !db_stat)
 
2900
        *tables_ptr++= table;                   // need new lock on this
 
2901
      if (mark_share_as_old)
 
2902
      {
 
2903
        table->s->version=0;
 
2904
        table->open_placeholder= 0;
 
2905
      }
 
2906
    }
1316
2907
  }
1317
2908
  *prev=0;
 
2909
  DBUG_PRINT("tcache", ("open tables to lock: %u",
 
2910
                        (uint) (tables_ptr - tables)));
1318
2911
  if (tables != tables_ptr)                     // Should we get back old locks
1319
2912
  {
1320
 
    DrizzleLock *local_lock;
 
2913
    MYSQL_LOCK *lock;
1321
2914
    /*
1322
2915
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
2916
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
2917
      already locked.
1325
2918
    */
1326
 
    some_tables_deleted= false;
1327
 
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
2919
    thd->some_tables_deleted=0;
 
2920
    if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
 
2921
                                 flags, &not_used)))
1330
2922
    {
1331
 
      /* unused */
 
2923
      thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
1332
2924
    }
1333
2925
    else
1334
2926
    {
1341
2933
      error=1;
1342
2934
    }
1343
2935
  }
1344
 
 
1345
2936
  if (get_locks && tables)
1346
 
    delete [] tables;
1347
 
 
1348
 
  locking::broadcast_refresh();
1349
 
 
1350
 
  return(error);
 
2937
  {
 
2938
    my_afree((uchar*) tables);
 
2939
  }
 
2940
  broadcast_refresh();
 
2941
  DBUG_RETURN(error);
1351
2942
}
1352
2943
 
1353
2944
 
1354
2945
/**
1355
 
  Close handlers for tables in list, but leave the Table structure
1356
 
  intact so that we can re-open these quickly.
 
2946
    Close handlers for tables in list, but leave the TABLE structure
 
2947
    intact so that we can re-open these quickly.
1357
2948
 
1358
 
  @param session           Thread context
1359
 
  @param table         Head of the list of Table objects
1360
 
  @param morph_locks   true  - remove locks which we have on tables being closed
1361
 
  but ensure that no DML or DDL will sneak in before
1362
 
  we will re-open the table (i.e. temporarily morph
1363
 
  our table-level locks into name-locks).
1364
 
  false - otherwise
1365
 
  @param send_refresh  Should we awake waiters even if we didn't close any tables?
 
2949
    @param thd           Thread context
 
2950
    @param table         Head of the list of TABLE objects
 
2951
    @param morph_locks   TRUE  - remove locks which we have on tables being closed
 
2952
                                 but ensure that no DML or DDL will sneak in before
 
2953
                                 we will re-open the table (i.e. temporarily morph
 
2954
                                 our table-level locks into name-locks).
 
2955
                         FALSE - otherwise
 
2956
    @param send_refresh  Should we awake waiters even if we didn't close any tables?
1366
2957
*/
1367
2958
 
1368
 
void Session::close_old_data_files(bool morph_locks, bool send_refresh)
 
2959
static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
 
2960
                                 bool send_refresh)
1369
2961
{
1370
2962
  bool found= send_refresh;
1371
 
 
1372
 
  Table *table= open_tables;
1373
 
 
1374
 
  for (; table ; table=table->getNext())
 
2963
  DBUG_ENTER("close_old_data_files");
 
2964
 
 
2965
  for (; table ; table=table->next)
1375
2966
  {
 
2967
    DBUG_PRINT("tcache", ("checking table: '%s'.'%s' 0x%lx",
 
2968
                          table->s->db.str, table->s->table_name.str,
 
2969
                          (long) table));
 
2970
    DBUG_PRINT("tcache", ("needs refresh: %d  is open: %u",
 
2971
                          table->needs_reopen_or_name_lock(), table->db_stat));
1376
2972
    /*
1377
2973
      Reopen marked for flush.
1378
2974
    */
1381
2977
      found=1;
1382
2978
      if (table->db_stat)
1383
2979
      {
1384
 
        if (morph_locks)
1385
 
        {
1386
 
          Table *ulcktbl= table;
 
2980
        if (morph_locks)
 
2981
        {
 
2982
          TABLE *ulcktbl= table;
1387
2983
          if (ulcktbl->lock_count)
1388
2984
          {
1389
2985
            /*
1392
2988
              lock on it. This will also give them a chance to close their
1393
2989
              instances of this table.
1394
2990
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
2991
            mysql_lock_abort(thd, ulcktbl, TRUE);
 
2992
            mysql_lock_remove(thd, thd->locked_tables, ulcktbl, TRUE);
1397
2993
            ulcktbl->lock_count= 0;
1398
2994
          }
1399
2995
          if ((ulcktbl != table) && ulcktbl->db_stat)
1404
3000
              as a placeholder. When this happens, do not clear the
1405
3001
              placeholder flag. See the branch below ("***").
1406
3002
            */
1407
 
            ulcktbl->open_placeholder= true;
 
3003
            ulcktbl->open_placeholder= 1;
1408
3004
            close_handle_and_leave_table_as_lock(ulcktbl);
1409
3005
          }
1410
3006
          /*
1411
3007
            We want to protect the table from concurrent DDL operations
1412
 
            (like RENAME Table) until we will re-open and re-lock it.
 
3008
            (like RENAME TABLE) until we will re-open and re-lock it.
1413
3009
          */
1414
 
          table->open_placeholder= true;
1415
 
        }
 
3010
          table->open_placeholder= 1;
 
3011
        }
1416
3012
        close_handle_and_leave_table_as_lock(table);
1417
3013
      }
1418
3014
      else if (table->open_placeholder && !morph_locks)
1421
3017
          We come here only in close-for-back-off scenario. So we have to
1422
3018
          "close" create placeholder here to avoid deadlocks (for example,
1423
3019
          in case of concurrent execution of CREATE TABLE t1 SELECT * FROM t2
1424
 
          and RENAME Table t2 TO t1). In close-for-re-open scenario we will
 
3020
          and RENAME TABLE t2 TO t1). In close-for-re-open scenario we will
1425
3021
          probably want to let it stay.
1426
3022
 
1427
3023
          Note "***": We must not enter this branch if the placeholder
1428
3024
          flag has been set because of a former close through a child.
1429
3025
          See above the comment that refers to this note.
1430
3026
        */
1431
 
        table->open_placeholder= false;
 
3027
        table->open_placeholder= 0;
1432
3028
      }
1433
3029
    }
1434
3030
  }
1435
3031
  if (found)
1436
 
    locking::broadcast_refresh();
 
3032
    broadcast_refresh();
 
3033
  DBUG_VOID_RETURN;
 
3034
}
 
3035
 
 
3036
 
 
3037
/*
 
3038
  Wait until all threads has closed the tables in the list
 
3039
  We have also to wait if there is thread that has a lock on this table even
 
3040
  if the table is closed
 
3041
*/
 
3042
 
 
3043
bool table_is_used(TABLE *table, bool wait_for_name_lock)
 
3044
{
 
3045
  DBUG_ENTER("table_is_used");
 
3046
  do
 
3047
  {
 
3048
    char *key= table->s->table_cache_key.str;
 
3049
    uint key_length= table->s->table_cache_key.length;
 
3050
 
 
3051
    DBUG_PRINT("loop", ("table_name: %s", table->alias));
 
3052
    HASH_SEARCH_STATE state;
 
3053
    for (TABLE *search= (TABLE*) hash_first(&open_cache, (uchar*) key,
 
3054
                                             key_length, &state);
 
3055
         search ;
 
3056
         search= (TABLE*) hash_next(&open_cache, (uchar*) key,
 
3057
                                    key_length, &state))
 
3058
    {
 
3059
      DBUG_PRINT("info", ("share: 0x%lx  "
 
3060
                          "open_placeholder: %d  locked_by_name: %d "
 
3061
                          "db_stat: %u  version: %lu",
 
3062
                          (ulong) search->s,
 
3063
                          search->open_placeholder, search->locked_by_name,
 
3064
                          search->db_stat,
 
3065
                          search->s->version));
 
3066
      if (search->in_use == table->in_use)
 
3067
        continue;                               // Name locked by this thread
 
3068
      /*
 
3069
        We can't use the table under any of the following conditions:
 
3070
        - There is an name lock on it (Table is to be deleted or altered)
 
3071
        - If we are in flush table and we didn't execute the flush
 
3072
        - If the table engine is open and it's an old version
 
3073
        (We must wait until all engines are shut down to use the table)
 
3074
      */
 
3075
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
3076
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
3077
        DBUG_RETURN(1);
 
3078
    }
 
3079
  } while ((table=table->next));
 
3080
  DBUG_RETURN(0);
1437
3081
}
1438
3082
 
1439
3083
 
1440
3084
/* Wait until all used tables are refreshed */
1441
3085
 
1442
 
bool wait_for_tables(Session *session)
 
3086
bool wait_for_tables(THD *thd)
1443
3087
{
1444
3088
  bool result;
1445
 
 
1446
 
  session->set_proc_info("Waiting for tables");
1447
 
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
1450
 
    {
1451
 
      session->some_tables_deleted= false;
1452
 
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
1455
 
        break;
1456
 
      }
1457
 
      COND_refresh.wait(lock);
1458
 
    }
1459
 
    if (session->getKilled())
1460
 
      result= true;                                     // aborted
1461
 
    else
1462
 
    {
1463
 
      /* Now we can open all tables without any interference */
1464
 
      session->set_proc_info("Reopen tables");
1465
 
      session->version= refresh_version;
1466
 
      result= session->reopen_tables(false, false);
1467
 
    }
1468
 
  }
1469
 
  session->set_proc_info(0);
1470
 
 
1471
 
  return result;
 
3089
  DBUG_ENTER("wait_for_tables");
 
3090
 
 
3091
  thd_proc_info(thd, "Waiting for tables");
 
3092
  pthread_mutex_lock(&LOCK_open);
 
3093
  while (!thd->killed)
 
3094
  {
 
3095
    thd->some_tables_deleted=0;
 
3096
    close_old_data_files(thd,thd->open_tables,0,dropping_tables != 0);
 
3097
    mysql_ha_flush(thd);
 
3098
    if (!table_is_used(thd->open_tables,1))
 
3099
      break;
 
3100
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
 
3101
  }
 
3102
  if (thd->killed)
 
3103
    result= 1;                                  // aborted
 
3104
  else
 
3105
  {
 
3106
    /* Now we can open all tables without any interference */
 
3107
    thd_proc_info(thd, "Reopen tables");
 
3108
    thd->version= refresh_version;
 
3109
    result=reopen_tables(thd,0,0);
 
3110
  }
 
3111
  pthread_mutex_unlock(&LOCK_open);
 
3112
  thd_proc_info(thd, 0);
 
3113
  DBUG_RETURN(result);
1472
3114
}
1473
3115
 
1474
3116
 
1476
3118
  drop tables from locked list
1477
3119
 
1478
3120
  SYNOPSIS
1479
 
  drop_locked_tables()
1480
 
  session                       Thread thandler
1481
 
  db                    Database
1482
 
  table_name            Table name
 
3121
    drop_locked_tables()
 
3122
    thd                 Thread thandler
 
3123
    db                  Database
 
3124
    table_name          Table name
1483
3125
 
1484
3126
  INFORMATION
1485
 
  This is only called on drop tables
 
3127
    This is only called on drop tables
1486
3128
 
1487
 
  The Table object for the dropped table is unlocked but still kept around
1488
 
  as a name lock, which means that the table will be available for other
1489
 
  thread as soon as we call unlock_table_names().
1490
 
  If there is multiple copies of the table locked, all copies except
1491
 
  the first, which acts as a name lock, is removed.
 
3129
    The TABLE object for the dropped table is unlocked but still kept around
 
3130
    as a name lock, which means that the table will be available for other
 
3131
    thread as soon as we call unlock_table_names().
 
3132
    If there is multiple copies of the table locked, all copies except
 
3133
    the first, which acts as a name lock, is removed.
1492
3134
 
1493
3135
  RETURN
1494
 
#    If table existed, return table
1495
 
0        Table was not locked
 
3136
    #    If table existed, return table
 
3137
    0    Table was not locked
1496
3138
*/
1497
3139
 
1498
3140
 
1499
 
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
3141
TABLE *drop_locked_tables(THD *thd,const char *db, const char *table_name)
1500
3142
{
1501
 
  Table *table,*next,**prev, *found= 0;
1502
 
  prev= &session->open_tables;
 
3143
  TABLE *table,*next,**prev, *found= 0;
 
3144
  prev= &thd->open_tables;
 
3145
  DBUG_ENTER("drop_locked_tables");
1503
3146
 
1504
3147
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
3148
    Note that we need to hold LOCK_open while changing the
1506
3149
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
3150
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
3151
    Closing a MERGE child before the parent would be fatal if the
1509
3152
    other thread tries to abort the MERGE lock in between.
1510
3153
  */
1511
 
  for (table= session->open_tables; table ; table=next)
 
3154
  for (table= thd->open_tables; table ; table=next)
1512
3155
  {
1513
 
    next=table->getNext();
1514
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
3156
    next=table->next;
 
3157
    if (!strcmp(table->s->table_name.str, table_name) &&
 
3158
        !strcmp(table->s->db.str, db))
1515
3159
    {
1516
 
      session->removeLock(table);
 
3160
      mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
1517
3161
 
1518
3162
      if (!found)
1519
3163
      {
1522
3166
        if (table->db_stat)
1523
3167
        {
1524
3168
          table->db_stat= 0;
1525
 
          table->cursor->close();
 
3169
          table->file->close();
1526
3170
        }
1527
3171
      }
1528
3172
      else
1529
3173
      {
1530
3174
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
3175
        VOID(hash_delete(&open_cache,(uchar*) table));
1532
3176
      }
1533
3177
    }
1534
3178
    else
1535
3179
    {
1536
3180
      *prev=table;
1537
 
      prev= table->getNextPtr();
 
3181
      prev= &table->next;
1538
3182
    }
1539
3183
  }
1540
3184
  *prev=0;
1541
3185
  if (found)
1542
 
    locking::broadcast_refresh();
1543
 
 
1544
 
  return(found);
 
3186
    broadcast_refresh();
 
3187
  if (thd->locked_tables && thd->locked_tables->table_count == 0)
 
3188
  {
 
3189
    my_free((uchar*) thd->locked_tables,MYF(0));
 
3190
    thd->locked_tables=0;
 
3191
  }
 
3192
  DBUG_RETURN(found);
1545
3193
}
1546
3194
 
1547
3195
 
1548
3196
/*
1549
 
  If we have the table open, which only happens when a LOCK Table has been
 
3197
  If we have the table open, which only happens when a LOCK TABLE has been
1550
3198
  done on the table, change the lock type to a lock that will abort all
1551
3199
  other threads trying to get the lock.
1552
3200
*/
1553
3201
 
1554
 
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
 
3202
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
1555
3203
{
1556
 
  Table *table;
1557
 
  for (table= session->open_tables; table ; table= table->getNext())
 
3204
  TABLE *table;
 
3205
  for (table= thd->open_tables; table ; table= table->next)
1558
3206
  {
1559
 
    if (table->getShare()->getCacheKey() == identifier.getKey())
 
3207
    if (!strcmp(table->s->table_name.str, table_name) &&
 
3208
        !strcmp(table->s->db.str, db))
1560
3209
    {
1561
3210
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
3211
      mysql_lock_abort(thd, table, TRUE);
1563
3212
      break;
1564
3213
    }
1565
3214
  }
1567
3216
 
1568
3217
 
1569
3218
/*
 
3219
  Function to assign a new table map id to a table share.
 
3220
 
 
3221
  PARAMETERS
 
3222
 
 
3223
    share - Pointer to table share structure
 
3224
 
 
3225
  DESCRIPTION
 
3226
 
 
3227
    We are intentionally not checking that share->mutex is locked
 
3228
    since this function should only be called when opening a table
 
3229
    share and before it is entered into the table_def_cache (meaning
 
3230
    that it cannot be fetched by another thread, even accidentally).
 
3231
 
 
3232
  PRE-CONDITION(S)
 
3233
 
 
3234
    share is non-NULL
 
3235
    The LOCK_open mutex is locked
 
3236
 
 
3237
  POST-CONDITION(S)
 
3238
 
 
3239
    share->table_map_id is given a value that with a high certainty is
 
3240
    not used by any other table (the only case where a table id can be
 
3241
    reused is on wrap-around, which means more than 4 billion table
 
3242
    share opens have been executed while one table was open all the
 
3243
    time).
 
3244
 
 
3245
    share->table_map_id is not ~0UL.
 
3246
 */
 
3247
void assign_new_table_id(TABLE_SHARE *share)
 
3248
{
 
3249
  static ulong last_table_id= ~0UL;
 
3250
 
 
3251
  DBUG_ENTER("assign_new_table_id");
 
3252
 
 
3253
  /* Preconditions */
 
3254
  DBUG_ASSERT(share != NULL);
 
3255
  safe_mutex_assert_owner(&LOCK_open);
 
3256
 
 
3257
  ulong tid= ++last_table_id;                   /* get next id */
 
3258
  /*
 
3259
    There is one reserved number that cannot be used.  Remember to
 
3260
    change this when 6-byte global table id's are introduced.
 
3261
  */
 
3262
  if (unlikely(tid == ~0UL))
 
3263
    tid= ++last_table_id;
 
3264
  share->table_map_id= tid;
 
3265
  DBUG_PRINT("info", ("table_id=%lu", tid));
 
3266
 
 
3267
  /* Post conditions */
 
3268
  DBUG_ASSERT(share->table_map_id != ~0UL);
 
3269
 
 
3270
  DBUG_VOID_RETURN;
 
3271
}
 
3272
 
 
3273
/*
 
3274
  Load a table definition from file and open unireg table
 
3275
 
 
3276
  SYNOPSIS
 
3277
    open_unireg_entry()
 
3278
    thd                 Thread handle
 
3279
    entry               Store open table definition here
 
3280
    table_list          TABLE_LIST with db, table_name & belong_to_view
 
3281
    alias               Alias name
 
3282
    cache_key           Key for share_cache
 
3283
    cache_key_length    length of cache_key
 
3284
    mem_root            temporary mem_root for parsing
 
3285
    flags               the OPEN_VIEW_NO_PARSE flag to be passed to
 
3286
                        openfrm()/open_new_frm()
 
3287
 
 
3288
  NOTES
 
3289
   Extra argument for open is taken from thd->open_options
 
3290
   One must have a lock on LOCK_open when calling this function
 
3291
 
 
3292
  RETURN
 
3293
    0   ok
 
3294
    #   Error
 
3295
*/
 
3296
 
 
3297
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
 
3298
                             const char *alias,
 
3299
                             char *cache_key, uint cache_key_length,
 
3300
                             MEM_ROOT *mem_root, uint flags)
 
3301
{
 
3302
  int error;
 
3303
  TABLE_SHARE *share;
 
3304
  uint discover_retry_count= 0;
 
3305
  DBUG_ENTER("open_unireg_entry");
 
3306
 
 
3307
  safe_mutex_assert_owner(&LOCK_open);
 
3308
retry:
 
3309
  if (!(share= get_table_share_with_create(thd, table_list, cache_key,
 
3310
                                           cache_key_length, 
 
3311
                                           OPEN_VIEW |
 
3312
                                           table_list->i_s_requested_object,
 
3313
                                           &error)))
 
3314
    DBUG_RETURN(1);
 
3315
 
 
3316
  while ((error= open_table_from_share(thd, share, alias,
 
3317
                                       (uint) (HA_OPEN_KEYFILE |
 
3318
                                               HA_OPEN_RNDFILE |
 
3319
                                               HA_GET_INDEX |
 
3320
                                               HA_TRY_READ_ONLY),
 
3321
                                       (READ_KEYINFO | COMPUTE_TYPES |
 
3322
                                        EXTRA_RECORD),
 
3323
                                       thd->open_options, entry, OTM_OPEN)))
 
3324
  {
 
3325
    if (error == 7)                             // Table def changed
 
3326
    {
 
3327
      share->version= 0;                        // Mark share as old
 
3328
      if (discover_retry_count++)               // Retry once
 
3329
        goto err;
 
3330
 
 
3331
      /*
 
3332
        TODO:
 
3333
        Here we should wait until all threads has released the table.
 
3334
        For now we do one retry. This may cause a deadlock if there
 
3335
        is other threads waiting for other tables used by this thread.
 
3336
        
 
3337
        Proper fix would be to if the second retry failed:
 
3338
        - Mark that table def changed
 
3339
        - Return from open table
 
3340
        - Close all tables used by this thread
 
3341
        - Start waiting that the share is released
 
3342
        - Retry by opening all tables again
 
3343
      */
 
3344
      if (ha_create_table_from_engine(thd, table_list->db,
 
3345
                                      table_list->table_name))
 
3346
        goto err;
 
3347
      /*
 
3348
        TO BE FIXED
 
3349
        To avoid deadlock, only wait for release if no one else is
 
3350
        using the share.
 
3351
      */
 
3352
      if (share->ref_count != 1)
 
3353
        goto err;
 
3354
      /* Free share and wait until it's released by all threads */
 
3355
      release_table_share(share, RELEASE_WAIT_FOR_DROP);
 
3356
      if (!thd->killed)
 
3357
      {
 
3358
        mysql_reset_errors(thd, 1);         // Clear warnings
 
3359
        thd->clear_error();                 // Clear error message
 
3360
        goto retry;
 
3361
      }
 
3362
      DBUG_RETURN(1);
 
3363
    }
 
3364
    if (!entry->s || !entry->s->crashed)
 
3365
      goto err;
 
3366
     // Code below is for repairing a crashed file
 
3367
     if ((error= lock_table_name(thd, table_list, TRUE)))
 
3368
     {
 
3369
       if (error < 0)
 
3370
        goto err;
 
3371
       if (wait_for_locked_table_names(thd, table_list))
 
3372
       {
 
3373
        unlock_table_name(thd, table_list);
 
3374
        goto err;
 
3375
       }
 
3376
     }
 
3377
     pthread_mutex_unlock(&LOCK_open);
 
3378
     thd->clear_error();                                // Clear error message
 
3379
     error= 0;
 
3380
     if (open_table_from_share(thd, share, alias,
 
3381
                               (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
3382
                                       HA_GET_INDEX |
 
3383
                                       HA_TRY_READ_ONLY),
 
3384
                               READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD,
 
3385
                               ha_open_options | HA_OPEN_FOR_REPAIR,
 
3386
                               entry, OTM_OPEN) || ! entry->file ||
 
3387
        (entry->file->is_crashed() && entry->file->ha_check_and_repair(thd)))
 
3388
     {
 
3389
       /* Give right error message */
 
3390
       thd->clear_error();
 
3391
       my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
 
3392
       sql_print_error("Couldn't repair table: %s.%s", share->db.str,
 
3393
                       share->table_name.str);
 
3394
       if (entry->file)
 
3395
        closefrm(entry, 0);
 
3396
       error=1;
 
3397
     }
 
3398
     else
 
3399
       thd->clear_error();                      // Clear error message
 
3400
     pthread_mutex_lock(&LOCK_open);
 
3401
     unlock_table_name(thd, table_list);
 
3402
 
 
3403
     if (error)
 
3404
       goto err;
 
3405
     break;
 
3406
   }
 
3407
 
 
3408
  /*
 
3409
    If we are here, there was no fatal error (but error may be still
 
3410
    unitialized).
 
3411
  */
 
3412
  if (unlikely(entry->file->implicit_emptied))
 
3413
  {
 
3414
    entry->file->implicit_emptied= 0;
 
3415
    if (mysql_bin_log.is_open())
 
3416
    {
 
3417
      char *query, *end;
 
3418
      uint query_buf_size= 20 + share->db.length + share->table_name.length +1;
 
3419
      if ((query= (char*) my_malloc(query_buf_size,MYF(MY_WME))))
 
3420
      {
 
3421
        /* this DELETE FROM is needed even with row-based binlogging */
 
3422
        end = strxmov(strmov(query, "DELETE FROM `"),
 
3423
                      share->db.str,"`.`",share->table_name.str,"`", NullS);
 
3424
        thd->binlog_query(THD::STMT_QUERY_TYPE,
 
3425
                          query, (ulong)(end-query), FALSE, FALSE);
 
3426
        my_free(query, MYF(0));
 
3427
      }
 
3428
      else
 
3429
      {
 
3430
        /*
 
3431
          As replication is maybe going to be corrupted, we need to warn the
 
3432
          DBA on top of warning the client (which will automatically be done
 
3433
          because of MYF(MY_WME) in my_malloc() above).
 
3434
        */
 
3435
        sql_print_error("When opening HEAP table, could not allocate memory "
 
3436
                        "to write 'DELETE FROM `%s`.`%s`' to the binary log",
 
3437
                        table_list->db, table_list->table_name);
 
3438
        closefrm(entry, 0);
 
3439
        goto err;
 
3440
      }
 
3441
    }
 
3442
  }
 
3443
  DBUG_RETURN(0);
 
3444
 
 
3445
err:
 
3446
  release_table_share(share, RELEASE_NORMAL);
 
3447
  DBUG_RETURN(1);
 
3448
}
 
3449
 
 
3450
 
 
3451
/*
1570
3452
  Open all tables in list
1571
3453
 
1572
3454
  SYNOPSIS
1573
 
  open_tables()
1574
 
  session - thread Cursor
1575
 
  start - list of tables in/out
1576
 
  counter - number of opened tables will be return using this parameter
1577
 
  flags   - bitmap of flags to modify how the tables will be open:
1578
 
  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
1579
 
  done a flush or namelock on it.
 
3455
    open_tables()
 
3456
    thd - thread handler
 
3457
    start - list of tables in/out
 
3458
    counter - number of opened tables will be return using this parameter
 
3459
    flags   - bitmap of flags to modify how the tables will be open:
 
3460
              MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
 
3461
              done a flush or namelock on it.
1580
3462
 
1581
3463
  NOTE
1582
 
  Unless we are already in prelocked mode, this function will also precache
1583
 
  all SP/SFs explicitly or implicitly (via views and triggers) used by the
1584
 
  query and add tables needed for their execution to table list. If resulting
1585
 
  tables list will be non empty it will mark query as requiring precaching.
1586
 
  Prelocked mode will be enabled for such query during lock_tables() call.
 
3464
    Unless we are already in prelocked mode, this function will also precache
 
3465
    all SP/SFs explicitly or implicitly (via views and triggers) used by the
 
3466
    query and add tables needed for their execution to table list. If resulting
 
3467
    tables list will be non empty it will mark query as requiring precaching.
 
3468
    Prelocked mode will be enabled for such query during lock_tables() call.
1587
3469
 
1588
 
  If query for which we are opening tables is already marked as requiring
1589
 
  prelocking it won't do such precaching and will simply reuse table list
1590
 
  which is already built.
 
3470
    If query for which we are opening tables is already marked as requiring
 
3471
    prelocking it won't do such precaching and will simply reuse table list
 
3472
    which is already built.
1591
3473
 
1592
3474
  RETURN
1593
 
  0  - OK
1594
 
  -1 - error
 
3475
    0  - OK
 
3476
    -1 - error
1595
3477
*/
1596
3478
 
1597
 
int Session::open_tables_from_list(TableList **start, uint32_t *counter, uint32_t flags)
 
3479
int open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags)
1598
3480
{
1599
 
  TableList *tables= NULL;
 
3481
  TABLE_LIST *tables= NULL;
1600
3482
  bool refresh;
1601
 
  int result= 0;
 
3483
  int result=0;
 
3484
  MEM_ROOT new_frm_mem;
1602
3485
  /* Also used for indicating that prelocking is need */
1603
3486
  bool safe_to_ignore_table;
1604
3487
 
1605
 
  current_tablenr= 0;
1606
 
restart:
 
3488
  DBUG_ENTER("open_tables");
 
3489
  /*
 
3490
    temporary mem_root for new .frm parsing.
 
3491
    TODO: variables for size
 
3492
  */
 
3493
  init_sql_alloc(&new_frm_mem, 8024, 8024);
 
3494
 
 
3495
  thd->current_tablenr= 0;
 
3496
 restart:
1607
3497
  *counter= 0;
1608
 
  set_proc_info("Opening tables");
 
3498
  thd_proc_info(thd, "Opening tables");
1609
3499
 
1610
3500
  /*
1611
3501
    For every table in the list of tables to open, try to find or open
1613
3503
  */
1614
3504
  for (tables= *start; tables ;tables= tables->next_global)
1615
3505
  {
1616
 
    safe_to_ignore_table= false;
 
3506
    DBUG_PRINT("tcache", ("opening table: '%s'.'%s'  item: 0x%lx",
 
3507
                          tables->db, tables->table_name, (long) tables));
 
3508
 
 
3509
    safe_to_ignore_table= FALSE;
1617
3510
 
1618
3511
    /*
1619
3512
      Ignore placeholders for derived tables. After derived tables
1620
3513
      processing, link to created temporary table will be put here.
1621
3514
      If this is derived table for view then we still want to process
1622
3515
      routines used by this view.
1623
 
    */
 
3516
     */
1624
3517
    if (tables->derived)
1625
3518
    {
1626
3519
      continue;
1627
3520
    }
 
3521
    /*
 
3522
      If this TABLE_LIST object is a placeholder for an information_schema
 
3523
      table, create a temporary table to represent the information_schema
 
3524
      table in the query. Do not fill it yet - will be filled during
 
3525
      execution.
 
3526
    */
 
3527
    if (tables->schema_table)
 
3528
    {
 
3529
      if (!mysql_schema_table(thd, thd->lex, tables))
 
3530
        continue;
 
3531
      DBUG_RETURN(-1);
 
3532
    }
1628
3533
    (*counter)++;
1629
3534
 
1630
3535
    /*
1631
 
     * Is the user authorized to see this table? Do this before we check
1632
 
     * to see if it exists so that an unauthorized user cannot phish for
1633
 
     * table/schema information via error messages
1634
 
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
1636
 
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
 
                                                the_table))
1638
 
    {
1639
 
      result= -1;                               // Fatal error
1640
 
      break;
1641
 
    }
1642
 
 
1643
 
 
1644
 
    /*
1645
3536
      Not a placeholder: must be a base table or a view, and the table is
1646
3537
      not opened yet. Try to open the table.
1647
3538
    */
1648
 
    if (tables->table == NULL)
1649
 
      tables->table= openTable(tables, &refresh, flags);
1650
 
 
1651
 
    if (tables->table == NULL)
1652
 
    {
 
3539
    if (!tables->table)
 
3540
    {
 
3541
      tables->table= open_table(thd, tables, &new_frm_mem, &refresh, flags);
 
3542
    }
 
3543
    else
 
3544
      DBUG_PRINT("tcache", ("referenced table: '%s'.'%s' 0x%lx",
 
3545
                            tables->db, tables->table_name,
 
3546
                            (long) tables->table));
 
3547
 
 
3548
    if (!tables->table)
 
3549
    {
 
3550
      free_root(&new_frm_mem, MYF(MY_KEEP_PREALLOC));
 
3551
 
1653
3552
      if (refresh)                              // Refresh in progress
1654
3553
      {
1655
3554
        /*
1666
3565
          we pretend that we have finished calculation which we were doing
1667
3566
          currently.
1668
3567
        */
1669
 
        close_tables_for_reopen(start);
1670
 
        goto restart;
 
3568
        close_tables_for_reopen(thd, start);
 
3569
        goto restart;
1671
3570
      }
1672
3571
 
1673
3572
      if (safe_to_ignore_table)
 
3573
      {
 
3574
        DBUG_PRINT("info", ("open_table: ignoring table '%s'.'%s'",
 
3575
                            tables->db, tables->alias));
1674
3576
        continue;
 
3577
      }
1675
3578
 
1676
3579
      result= -1;                               // Fatal error
1677
3580
      break;
1678
3581
    }
1679
 
    if (tables->lock_type != TL_UNLOCK)
 
3582
    if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
1680
3583
    {
1681
3584
      if (tables->lock_type == TL_WRITE_DEFAULT)
1682
 
        tables->table->reginfo.lock_type= update_lock_default;
1683
 
      else if (tables->table->getShare()->getType() == message::Table::STANDARD)
 
3585
        tables->table->reginfo.lock_type= thd->update_lock_default;
 
3586
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
1684
3587
        tables->table->reginfo.lock_type= tables->lock_type;
1685
3588
    }
1686
3589
  }
1687
3590
 
1688
 
  set_proc_info(0);
 
3591
  thd_proc_info(thd, 0);
 
3592
  free_root(&new_frm_mem, MYF(0));              // Free pre-alloced block
1689
3593
 
1690
3594
  if (result && tables)
1691
3595
  {
1692
3596
    /*
1693
3597
      Some functions determine success as (tables->table != NULL).
1694
 
      tables->table is in session->open_tables.
 
3598
      tables->table is in thd->open_tables. It won't go lost. If the
 
3599
      error happens on a MERGE child, clear the parents TABLE reference.
1695
3600
    */
 
3601
    if (tables->parent_l)
 
3602
      tables->parent_l->table= NULL;
1696
3603
    tables->table= NULL;
1697
3604
  }
1698
 
 
1699
 
  return(result);
 
3605
  DBUG_PRINT("tcache", ("returning: %d", result));
 
3606
  DBUG_RETURN(result);
 
3607
}
 
3608
 
 
3609
 
 
3610
/*
 
3611
  Check that lock is ok for tables; Call start stmt if ok
 
3612
 
 
3613
  SYNOPSIS
 
3614
    check_lock_and_start_stmt()
 
3615
    thd                 Thread handle
 
3616
    table_list          Table to check
 
3617
    lock_type           Lock used for table
 
3618
 
 
3619
  RETURN VALUES
 
3620
  0     ok
 
3621
  1     error
 
3622
*/
 
3623
 
 
3624
static bool check_lock_and_start_stmt(THD *thd, TABLE *table,
 
3625
                                      thr_lock_type lock_type)
 
3626
{
 
3627
  int error;
 
3628
  DBUG_ENTER("check_lock_and_start_stmt");
 
3629
 
 
3630
  if ((int) lock_type >= (int) TL_WRITE_ALLOW_READ &&
 
3631
      (int) table->reginfo.lock_type < (int) TL_WRITE_ALLOW_READ)
 
3632
  {
 
3633
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
 
3634
    DBUG_RETURN(1);
 
3635
  }
 
3636
  if ((error=table->file->start_stmt(thd, lock_type)))
 
3637
  {
 
3638
    table->file->print_error(error,MYF(0));
 
3639
    DBUG_RETURN(1);
 
3640
  }
 
3641
  DBUG_RETURN(0);
 
3642
}
 
3643
 
 
3644
 
 
3645
/**
 
3646
  @brief Open and lock one table
 
3647
 
 
3648
  @param[in]    thd             thread handle
 
3649
  @param[in]    table_l         table to open is first table in this list
 
3650
  @param[in]    lock_type       lock to use for table
 
3651
 
 
3652
  @return       table
 
3653
    @retval     != NULL         OK, opened table returned
 
3654
    @retval     NULL            Error
 
3655
 
 
3656
  @note
 
3657
    If ok, the following are also set:
 
3658
      table_list->lock_type     lock_type
 
3659
      table_list->table         table
 
3660
 
 
3661
  @note
 
3662
    If table_l is a list, not a single table, the list is temporarily
 
3663
    broken.
 
3664
 
 
3665
  @detail
 
3666
    This function is meant as a replacement for open_ltable() when
 
3667
    MERGE tables can be opened. open_ltable() cannot open MERGE tables.
 
3668
 
 
3669
    There may be more differences between open_n_lock_single_table() and
 
3670
    open_ltable(). One known difference is that open_ltable() does
 
3671
    neither call decide_logging_format() nor handle some other logging
 
3672
    and locking issues because it does not call lock_tables().
 
3673
*/
 
3674
 
 
3675
TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
 
3676
                                thr_lock_type lock_type)
 
3677
{
 
3678
  TABLE_LIST *save_next_global;
 
3679
  DBUG_ENTER("open_n_lock_single_table");
 
3680
 
 
3681
  /* Remember old 'next' pointer. */
 
3682
  save_next_global= table_l->next_global;
 
3683
  /* Break list. */
 
3684
  table_l->next_global= NULL;
 
3685
 
 
3686
  /* Set requested lock type. */
 
3687
  table_l->lock_type= lock_type;
 
3688
  /* Allow to open real tables only. */
 
3689
  table_l->required_type= FRMTYPE_TABLE;
 
3690
 
 
3691
  /* Open the table. */
 
3692
  if (simple_open_n_lock_tables(thd, table_l))
 
3693
    table_l->table= NULL; /* Just to be sure. */
 
3694
 
 
3695
  /* Restore list. */
 
3696
  table_l->next_global= save_next_global;
 
3697
 
 
3698
  DBUG_RETURN(table_l->table);
1700
3699
}
1701
3700
 
1702
3701
 
1704
3703
  Open and lock one table
1705
3704
 
1706
3705
  SYNOPSIS
1707
 
  openTableLock()
1708
 
  session                       Thread Cursor
1709
 
  table_list            Table to open is first table in this list
1710
 
  lock_type             Lock to use for open
1711
 
  lock_flags          Flags passed to mysql_lock_table
 
3706
    open_ltable()
 
3707
    thd                 Thread handler
 
3708
    table_list          Table to open is first table in this list
 
3709
    lock_type           Lock to use for open
 
3710
    lock_flags          Flags passed to mysql_lock_table
1712
3711
 
1713
3712
  NOTE
1714
 
  This function don't do anything like SP/SF/views/triggers analysis done
1715
 
  in open_tables(). It is intended for opening of only one concrete table.
1716
 
  And used only in special contexts.
 
3713
    This function don't do anything like SP/SF/views/triggers analysis done
 
3714
    in open_tables(). It is intended for opening of only one concrete table.
 
3715
    And used only in special contexts.
1717
3716
 
1718
3717
  RETURN VALUES
1719
 
  table         Opened table
1720
 
  0                     Error
1721
 
 
1722
 
  If ok, the following are also set:
1723
 
  table_list->lock_type         lock_type
1724
 
  table_list->table             table
 
3718
    table               Opened table
 
3719
    0                   Error
 
3720
  
 
3721
    If ok, the following are also set:
 
3722
      table_list->lock_type     lock_type
 
3723
      table_list->table         table
1725
3724
*/
1726
3725
 
1727
 
Table *Session::openTableLock(TableList *table_list, thr_lock_type lock_type)
 
3726
TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
 
3727
                   uint lock_flags)
1728
3728
{
1729
 
  Table *table;
 
3729
  TABLE *table;
1730
3730
  bool refresh;
 
3731
  DBUG_ENTER("open_ltable");
1731
3732
 
1732
 
  set_proc_info("Opening table");
1733
 
  current_tablenr= 0;
1734
 
  while (!(table= openTable(table_list, &refresh)) &&
 
3733
  thd_proc_info(thd, "Opening table");
 
3734
  thd->current_tablenr= 0;
 
3735
  /* open_ltable can be used only for BASIC TABLEs */
 
3736
  table_list->required_type= FRMTYPE_TABLE;
 
3737
  while (!(table= open_table(thd, table_list, thd->mem_root, &refresh, 0)) &&
1735
3738
         refresh)
1736
3739
    ;
1737
3740
 
1739
3742
  {
1740
3743
    table_list->lock_type= lock_type;
1741
3744
    table_list->table=     table;
1742
 
 
1743
 
    assert(lock == 0);  // You must lock everything at once
1744
 
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
1746
 
        table= 0;
1747
 
  }
1748
 
 
1749
 
  set_proc_info(0);
1750
 
 
1751
 
  return table;
 
3745
    if (thd->locked_tables)
 
3746
    {
 
3747
      if (check_lock_and_start_stmt(thd, table, lock_type))
 
3748
        table= 0;
 
3749
    }
 
3750
    else
 
3751
    {
 
3752
      DBUG_ASSERT(thd->lock == 0);      // You must lock everything at once
 
3753
      if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
 
3754
        if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
 
3755
                                            lock_flags, &refresh)))
 
3756
          table= 0;
 
3757
    }
 
3758
  }
 
3759
 
 
3760
  thd_proc_info(thd, 0);
 
3761
  DBUG_RETURN(table);
 
3762
}
 
3763
 
 
3764
 
 
3765
/*
 
3766
  Open all tables in list, locks them and optionally process derived tables.
 
3767
 
 
3768
  SYNOPSIS
 
3769
    open_and_lock_tables_derived()
 
3770
    thd         - thread handler
 
3771
    tables      - list of tables for open&locking
 
3772
    derived     - if to handle derived tables
 
3773
 
 
3774
  RETURN
 
3775
    FALSE - ok
 
3776
    TRUE  - error
 
3777
 
 
3778
  NOTE
 
3779
    The lock will automaticaly be freed by close_thread_tables()
 
3780
 
 
3781
  NOTE
 
3782
    There are two convenience functions:
 
3783
    - simple_open_n_lock_tables(thd, tables)  without derived handling
 
3784
    - open_and_lock_tables(thd, tables)       with derived handling
 
3785
    Both inline functions call open_and_lock_tables_derived() with
 
3786
    the third argument set appropriately.
 
3787
*/
 
3788
 
 
3789
int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived)
 
3790
{
 
3791
  uint counter;
 
3792
  bool need_reopen;
 
3793
  DBUG_ENTER("open_and_lock_tables_derived");
 
3794
  DBUG_PRINT("enter", ("derived handling: %d", derived));
 
3795
 
 
3796
  for ( ; ; ) 
 
3797
  {
 
3798
    if (open_tables(thd, &tables, &counter, 0))
 
3799
      DBUG_RETURN(-1);
 
3800
 
 
3801
    DBUG_EXECUTE_IF("sleep_open_and_lock_after_open", {
 
3802
      const char *old_proc_info= thd->proc_info;
 
3803
      thd->proc_info= "DBUG sleep";
 
3804
      my_sleep(6000000);
 
3805
      thd->proc_info= old_proc_info;});
 
3806
 
 
3807
    if (!lock_tables(thd, tables, counter, &need_reopen))
 
3808
      break;
 
3809
    if (!need_reopen)
 
3810
      DBUG_RETURN(-1);
 
3811
    close_tables_for_reopen(thd, &tables);
 
3812
  }
 
3813
  if (derived &&
 
3814
      (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
 
3815
       (thd->fill_derived_tables() &&
 
3816
        mysql_handle_derived(thd->lex, &mysql_derived_filling))))
 
3817
    DBUG_RETURN(TRUE); /* purecov: inspected */
 
3818
  DBUG_RETURN(0);
 
3819
}
 
3820
 
 
3821
 
 
3822
/*
 
3823
  Open all tables in list and process derived tables
 
3824
 
 
3825
  SYNOPSIS
 
3826
    open_normal_and_derived_tables
 
3827
    thd         - thread handler
 
3828
    tables      - list of tables for open
 
3829
    flags       - bitmap of flags to modify how the tables will be open:
 
3830
                  MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
 
3831
                  done a flush or namelock on it.
 
3832
 
 
3833
  RETURN
 
3834
    FALSE - ok
 
3835
    TRUE  - error
 
3836
 
 
3837
  NOTE 
 
3838
    This is to be used on prepare stage when you don't read any
 
3839
    data from the tables.
 
3840
*/
 
3841
 
 
3842
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
 
3843
{
 
3844
  uint counter;
 
3845
  DBUG_ENTER("open_normal_and_derived_tables");
 
3846
  DBUG_ASSERT(!thd->fill_derived_tables());
 
3847
  if (open_tables(thd, &tables, &counter, flags) ||
 
3848
      mysql_handle_derived(thd->lex, &mysql_derived_prepare))
 
3849
    DBUG_RETURN(TRUE); /* purecov: inspected */
 
3850
  DBUG_RETURN(0);
 
3851
}
 
3852
 
 
3853
 
 
3854
/**
 
3855
   Decide on logging format to use for the statement.
 
3856
 
 
3857
   Compute the capabilities vector for the involved storage engines
 
3858
   and mask out the flags for the binary log. Right now, the binlog
 
3859
   flags only include the capabilities of the storage engines, so this
 
3860
   is safe.
 
3861
 
 
3862
   We now have three alternatives that prevent the statement from
 
3863
   being loggable:
 
3864
 
 
3865
   1. If there are no capabilities left (all flags are clear) it is
 
3866
      not possible to log the statement at all, so we roll back the
 
3867
      statement and report an error.
 
3868
 
 
3869
   2. Statement mode is set, but the capabilities indicate that
 
3870
      statement format is not possible.
 
3871
 
 
3872
   3. Row mode is set, but the capabilities indicate that row
 
3873
      format is not possible.
 
3874
 
 
3875
   4. Statement is unsafe, but the capabilities indicate that row
 
3876
      format is not possible.
 
3877
 
 
3878
   If we are in MIXED mode, we then decide what logging format to use:
 
3879
 
 
3880
   1. If the statement is unsafe, row-based logging is used.
 
3881
 
 
3882
   2. If statement-based logging is not possible, row-based logging is
 
3883
      used.
 
3884
 
 
3885
   3. Otherwise, statement-based logging is used.
 
3886
 
 
3887
   @param thd    Client thread
 
3888
   @param tables Tables involved in the query
 
3889
 */
 
3890
 
 
3891
int decide_logging_format(THD *thd, TABLE_LIST *tables)
 
3892
{
 
3893
  if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
 
3894
  {
 
3895
    handler::Table_flags flags_some_set= handler::Table_flags();
 
3896
    handler::Table_flags flags_all_set= ~handler::Table_flags();
 
3897
    my_bool multi_engine= FALSE;
 
3898
    void* prev_ht= NULL;
 
3899
    for (TABLE_LIST *table= tables; table; table= table->next_global)
 
3900
    {
 
3901
      if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
 
3902
      {
 
3903
        ulonglong const flags= table->table->file->ha_table_flags();
 
3904
        DBUG_PRINT("info", ("table: %s; ha_table_flags: %s%s",
 
3905
                            table->table_name,
 
3906
                            FLAGSTR(flags, HA_BINLOG_STMT_CAPABLE),
 
3907
                            FLAGSTR(flags, HA_BINLOG_ROW_CAPABLE)));
 
3908
        if (prev_ht && prev_ht != table->table->file->ht)
 
3909
          multi_engine= TRUE;
 
3910
        prev_ht= table->table->file->ht;
 
3911
        flags_all_set &= flags;
 
3912
        flags_some_set |= flags;
 
3913
      }
 
3914
    }
 
3915
 
 
3916
    DBUG_PRINT("info", ("flags_all_set: %s%s",
 
3917
                        FLAGSTR(flags_all_set, HA_BINLOG_STMT_CAPABLE),
 
3918
                        FLAGSTR(flags_all_set, HA_BINLOG_ROW_CAPABLE)));
 
3919
    DBUG_PRINT("info", ("flags_some_set: %s%s",
 
3920
                        FLAGSTR(flags_some_set, HA_BINLOG_STMT_CAPABLE),
 
3921
                        FLAGSTR(flags_some_set, HA_BINLOG_ROW_CAPABLE)));
 
3922
    DBUG_PRINT("info", ("thd->variables.binlog_format: %ld",
 
3923
                        thd->variables.binlog_format));
 
3924
    DBUG_PRINT("info", ("multi_engine: %s",
 
3925
                        multi_engine ? "TRUE" : "FALSE"));
 
3926
 
 
3927
    int error= 0;
 
3928
    if (flags_all_set == 0)
 
3929
    {
 
3930
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3931
               "Statement cannot be logged to the binary log in"
 
3932
               " row-based nor statement-based format");
 
3933
    }
 
3934
    else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
 
3935
             (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
 
3936
    {
 
3937
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3938
                "Statement-based format required for this statement,"
 
3939
                " but not allowed by this combination of engines");
 
3940
    }
 
3941
    else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
 
3942
              thd->lex->is_stmt_unsafe()) &&
 
3943
             (flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
 
3944
    {
 
3945
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3946
                "Row-based format required for this statement,"
 
3947
                " but not allowed by this combination of engines");
 
3948
    }
 
3949
 
 
3950
    /*
 
3951
      If more than one engine is involved in the statement and at
 
3952
      least one is doing it's own logging (is *self-logging*), the
 
3953
      statement cannot be logged atomically, so we generate an error
 
3954
      rather than allowing the binlog to become corrupt.
 
3955
     */
 
3956
    if (multi_engine &&
 
3957
        (flags_some_set & HA_HAS_OWN_BINLOGGING))
 
3958
    {
 
3959
      error= ER_BINLOG_LOGGING_IMPOSSIBLE;
 
3960
      my_error(error, MYF(0),
 
3961
               "Statement cannot be written atomically since more"
 
3962
               " than one engine involved and at least one engine"
 
3963
               " is self-logging");
 
3964
    }
 
3965
 
 
3966
    DBUG_PRINT("info", ("error: %d", error));
 
3967
 
 
3968
    if (error)
 
3969
      return -1;
 
3970
 
 
3971
    /*
 
3972
      We switch to row-based format if we are in mixed mode and one of
 
3973
      the following are true:
 
3974
 
 
3975
      1. If the statement is unsafe
 
3976
      2. If statement format cannot be used
 
3977
 
 
3978
      Observe that point to cannot be decided before the tables
 
3979
      involved in a statement has been checked, i.e., we cannot put
 
3980
      this code in reset_current_stmt_binlog_row_based(), it has to be
 
3981
      here.
 
3982
    */
 
3983
    if (thd->lex->is_stmt_unsafe() ||
 
3984
        (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
 
3985
    {
 
3986
      thd->set_current_stmt_binlog_row_based_if_mixed();
 
3987
    }
 
3988
  }
 
3989
 
 
3990
  return 0;
1752
3991
}
1753
3992
 
1754
3993
/*
1755
3994
  Lock all tables in list
1756
3995
 
1757
3996
  SYNOPSIS
1758
 
  lock_tables()
1759
 
  session                       Thread Cursor
1760
 
  tables                Tables to lock
1761
 
  count         Number of opened tables
1762
 
  need_reopen         Out parameter which if true indicates that some
1763
 
  tables were dropped or altered during this call
1764
 
  and therefore invoker should reopen tables and
1765
 
  try to lock them once again (in this case
1766
 
  lock_tables() will also return error).
 
3997
    lock_tables()
 
3998
    thd                 Thread handler
 
3999
    tables              Tables to lock
 
4000
    count               Number of opened tables
 
4001
    need_reopen         Out parameter which if TRUE indicates that some
 
4002
                        tables were dropped or altered during this call
 
4003
                        and therefore invoker should reopen tables and
 
4004
                        try to lock them once again (in this case
 
4005
                        lock_tables() will also return error).
1767
4006
 
1768
4007
  NOTES
1769
 
  You can't call lock_tables twice, as this would break the dead-lock-free
1770
 
  handling thr_lock gives us.  You most always get all needed locks at
1771
 
  once.
 
4008
    You can't call lock_tables twice, as this would break the dead-lock-free
 
4009
    handling thr_lock gives us.  You most always get all needed locks at
 
4010
    once.
1772
4011
 
1773
 
  If query for which we are calling this function marked as requring
1774
 
  prelocking, this function will do implicit LOCK TABLES and change
1775
 
  session::prelocked_mode accordingly.
 
4012
    If query for which we are calling this function marked as requring
 
4013
    prelocking, this function will do implicit LOCK TABLES and change
 
4014
    thd::prelocked_mode accordingly.
1776
4015
 
1777
4016
  RETURN VALUES
1778
 
  0     ok
1779
 
  -1    Error
 
4017
   0    ok
 
4018
   -1   Error
1780
4019
*/
1781
4020
 
1782
 
int Session::lock_tables(TableList *tables, uint32_t count, bool *need_reopen)
 
4021
int lock_tables(THD *thd, TABLE_LIST *tables, uint count, bool *need_reopen)
1783
4022
{
1784
 
  TableList *table;
1785
 
  Session *session= this;
 
4023
  TABLE_LIST *table;
1786
4024
 
 
4025
  DBUG_ENTER("lock_tables");
1787
4026
  /*
1788
4027
    We can't meet statement requiring prelocking if we already
1789
4028
    in prelocked mode.
1790
4029
  */
1791
 
  *need_reopen= false;
1792
 
 
1793
 
  if (tables == NULL)
1794
 
    return 0;
1795
 
 
1796
 
  assert(session->lock == 0);   // You must lock everything at once
1797
 
  Table **start,**ptr;
1798
 
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1799
 
 
1800
 
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1801
 
    return -1;
1802
 
  for (table= tables; table; table= table->next_global)
1803
 
  {
1804
 
    if (!table->placeholder())
1805
 
      *(ptr++)= table->table;
1806
 
  }
1807
 
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
1809
 
  {
1810
 
    return -1;
1811
 
  }
1812
 
 
1813
 
  return 0;
 
4030
  *need_reopen= FALSE;
 
4031
 
 
4032
  if (!tables)
 
4033
    DBUG_RETURN(decide_logging_format(thd, tables));
 
4034
 
 
4035
  if (!thd->locked_tables)
 
4036
  {
 
4037
    DBUG_ASSERT(thd->lock == 0);        // You must lock everything at once
 
4038
    TABLE **start,**ptr;
 
4039
    uint lock_flag= MYSQL_LOCK_NOTIFY_IF_NEED_REOPEN;
 
4040
 
 
4041
    if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count)))
 
4042
      DBUG_RETURN(-1);
 
4043
    for (table= tables; table; table= table->next_global)
 
4044
    {
 
4045
      if (!table->placeholder())
 
4046
        *(ptr++)= table->table;
 
4047
    }
 
4048
 
 
4049
    if (!(thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
 
4050
                                       lock_flag, need_reopen)))
 
4051
    {
 
4052
      DBUG_RETURN(-1);
 
4053
    }
 
4054
  }
 
4055
  else
 
4056
  {
 
4057
    TABLE_LIST *first_not_own= thd->lex->first_not_own_table();
 
4058
    /*
 
4059
      When open_and_lock_tables() is called for a single table out of
 
4060
      a table list, the 'next_global' chain is temporarily broken. We
 
4061
      may not find 'first_not_own' before the end of the "list".
 
4062
      Look for example at those places where open_n_lock_single_table()
 
4063
      is called. That function implements the temporary breaking of
 
4064
      a table list for opening a single table.
 
4065
    */
 
4066
    for (table= tables;
 
4067
         table && table != first_not_own;
 
4068
         table= table->next_global)
 
4069
    {
 
4070
      if (!table->placeholder() &&
 
4071
          check_lock_and_start_stmt(thd, table->table, table->lock_type))
 
4072
      {
 
4073
        DBUG_RETURN(-1);
 
4074
      }
 
4075
    }
 
4076
  }
 
4077
 
 
4078
  DBUG_RETURN(decide_logging_format(thd, tables));
 
4079
}
 
4080
 
 
4081
 
 
4082
/*
 
4083
  Prepare statement for reopening of tables and recalculation of set of
 
4084
  prelocked tables.
 
4085
 
 
4086
  SYNOPSIS
 
4087
    close_tables_for_reopen()
 
4088
      thd    in     Thread context
 
4089
      tables in/out List of tables which we were trying to open and lock
 
4090
 
 
4091
*/
 
4092
 
 
4093
void close_tables_for_reopen(THD *thd, TABLE_LIST **tables)
 
4094
{
 
4095
  /*
 
4096
    If table list consists only from tables from prelocking set, table list
 
4097
    for new attempt should be empty, so we have to update list's root pointer.
 
4098
  */
 
4099
  if (thd->lex->first_not_own_table() == *tables)
 
4100
    *tables= 0;
 
4101
  thd->lex->chop_off_not_own_tables();
 
4102
  for (TABLE_LIST *tmp= *tables; tmp; tmp= tmp->next_global)
 
4103
    tmp->table= 0;
 
4104
  close_thread_tables(thd);
1814
4105
}
1815
4106
 
1816
4107
 
1818
4109
  Open a single table without table caching and don't set it in open_list
1819
4110
 
1820
4111
  SYNPOSIS
1821
 
  open_temporary_table()
1822
 
  session                 Thread object
1823
 
  path    Path (without .frm)
1824
 
  db              database
1825
 
  table_name      Table name
1826
 
  link_in_list  1 if table should be linked into session->temporary_tables
1827
 
 
1828
 
NOTES:
1829
 
Used by alter_table to open a temporary table and when creating
1830
 
a temporary table with CREATE TEMPORARY ...
1831
 
 
1832
 
RETURN
1833
 
0  Error
1834
 
#  Table object
 
4112
    open_temporary_table()
 
4113
    thd           Thread object
 
4114
    path          Path (without .frm)
 
4115
    db            database
 
4116
    table_name    Table name
 
4117
    link_in_list  1 if table should be linked into thd->temporary_tables
 
4118
 
 
4119
 NOTES:
 
4120
    Used by alter_table to open a temporary table and when creating
 
4121
    a temporary table with CREATE TEMPORARY ...
 
4122
 
 
4123
 RETURN
 
4124
   0  Error
 
4125
   #  TABLE object
1835
4126
*/
1836
4127
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
4128
TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
 
4129
                            const char *table_name, bool link_in_list,
 
4130
                            open_table_mode open_mode)
1839
4131
{
1840
 
  assert(identifier.isTmp());
1841
 
 
1842
 
 
1843
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1844
 
                                                        identifier,
1845
 
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1846
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
1847
 
  if (not new_tmp_table)
1848
 
    return NULL;
1849
 
 
1850
 
  /*
1851
 
    First open the share, and then open the table from the share we just opened.
1852
 
  */
1853
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1855
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1856
 
                                                                          HA_GET_INDEX),
1857
 
                                                              ha_open_options,
1858
 
                                                              *new_tmp_table))
 
4132
  TABLE *tmp_table;
 
4133
  TABLE_SHARE *share;
 
4134
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
 
4135
  uint key_length;
 
4136
  TABLE_LIST table_list;
 
4137
  DBUG_ENTER("open_temporary_table");
 
4138
  DBUG_PRINT("enter",
 
4139
             ("table: '%s'.'%s'  path: '%s'  server_id: %u  "
 
4140
              "pseudo_thread_id: %lu",
 
4141
              db, table_name, path,
 
4142
              (uint) thd->server_id, (ulong) thd->variables.pseudo_thread_id));
 
4143
 
 
4144
  table_list.db=         (char*) db;
 
4145
  table_list.table_name= (char*) table_name;
 
4146
  /* Create the cache_key for temporary tables */
 
4147
  key_length= create_table_def_key(thd, cache_key, &table_list, 1);
 
4148
 
 
4149
  if (!(tmp_table= (TABLE*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
 
4150
                                      strlen(path)+1 + key_length,
 
4151
                                      MYF(MY_WME))))
 
4152
    DBUG_RETURN(0);                             /* purecov: inspected */
 
4153
 
 
4154
  share= (TABLE_SHARE*) (tmp_table+1);
 
4155
  tmp_path= (char*) (share+1);
 
4156
  saved_cache_key= strmov(tmp_path, path)+1;
 
4157
  memcpy(saved_cache_key, cache_key, key_length);
 
4158
 
 
4159
  init_tmp_table_share(thd, share, saved_cache_key, key_length,
 
4160
                       strend(saved_cache_key)+1, tmp_path);
 
4161
 
 
4162
  if (open_table_def(thd, share, 0) ||
 
4163
      open_table_from_share(thd, share, table_name,
 
4164
                            (open_mode == OTM_ALTER) ? 0 :
 
4165
                            (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
4166
                                    HA_GET_INDEX),
 
4167
                            (open_mode == OTM_ALTER) ?
 
4168
                              (READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD |
 
4169
                               OPEN_FRM_FILE_ONLY)
 
4170
                            : (READ_KEYINFO | COMPUTE_TYPES | EXTRA_RECORD),
 
4171
                            ha_open_options,
 
4172
                            tmp_table, open_mode))
1859
4173
  {
1860
4174
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
1862
 
    delete new_tmp_table;
1863
 
 
1864
 
    return 0;
1865
 
  }
1866
 
 
1867
 
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
 
4175
    free_table_share(share);
 
4176
    my_free((char*) tmp_table,MYF(0));
 
4177
    DBUG_RETURN(0);
 
4178
  }
 
4179
 
 
4180
  tmp_table->reginfo.lock_type= TL_WRITE;        // Simulate locked
 
4181
  if (open_mode == OTM_ALTER)
 
4182
  {
 
4183
    /*
 
4184
       Temporary table has been created with frm_only
 
4185
       and has not been created in any storage engine
 
4186
    */
 
4187
    share->tmp_table= TMP_TABLE_FRM_FILE_ONLY;
 
4188
  }
 
4189
  else
 
4190
    share->tmp_table= (tmp_table->file->has_transactions() ?
 
4191
                       TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
1868
4192
 
1869
4193
  if (link_in_list)
1870
4194
  {
1871
4195
    /* growing temp list at the head */
1872
 
    new_tmp_table->setNext(this->temporary_tables);
1873
 
    if (new_tmp_table->getNext())
1874
 
    {
1875
 
      new_tmp_table->getNext()->setPrev(new_tmp_table);
1876
 
    }
1877
 
    this->temporary_tables= new_tmp_table;
1878
 
    this->temporary_tables->setPrev(0);
1879
 
  }
1880
 
  new_tmp_table->pos_in_table_list= 0;
1881
 
 
1882
 
  return new_tmp_table;
 
4196
    tmp_table->next= thd->temporary_tables;
 
4197
    if (tmp_table->next)
 
4198
      tmp_table->next->prev= tmp_table;
 
4199
    thd->temporary_tables= tmp_table;
 
4200
    thd->temporary_tables->prev= 0;
 
4201
    if (thd->slave_thread)
 
4202
      slave_open_temp_tables++;
 
4203
  }
 
4204
  tmp_table->pos_in_table_list= 0;
 
4205
  DBUG_PRINT("tmptable", ("opened table: '%s'.'%s' 0x%lx", tmp_table->s->db.str,
 
4206
                          tmp_table->s->table_name.str, (long) tmp_table));
 
4207
  DBUG_RETURN(tmp_table);
 
4208
}
 
4209
 
 
4210
 
 
4211
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
 
4212
{
 
4213
  bool error=0;
 
4214
  handler *file;
 
4215
  char *ext;
 
4216
  DBUG_ENTER("rm_temporary_table");
 
4217
 
 
4218
  strmov(ext= strend(path), reg_ext);
 
4219
  if (my_delete(path,MYF(0)))
 
4220
    error=1; /* purecov: inspected */
 
4221
  *ext= 0;                              // remove extension
 
4222
  file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
 
4223
  if (!frm_only && file && file->ha_delete_table(path))
 
4224
  {
 
4225
    error=1;
 
4226
    sql_print_warning("Could not remove temporary table: '%s', error: %d",
 
4227
                      path, my_errno);
 
4228
  }
 
4229
  delete file;
 
4230
  DBUG_RETURN(error);
1883
4231
}
1884
4232
 
1885
4233
 
1886
4234
/*****************************************************************************
1887
 
 * The following find_field_in_XXX procedures implement the core of the
1888
 
 * name resolution functionality. The entry point to resolve a column name in a
1889
 
 * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
1890
 
 * for each table reference. In turn, depending on the type of table reference,
1891
 
 * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
1892
 
 * below specific for the type of table reference.
1893
 
 ******************************************************************************/
 
4235
* The following find_field_in_XXX procedures implement the core of the
 
4236
* name resolution functionality. The entry point to resolve a column name in a
 
4237
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
 
4238
* for each table reference. In turn, depending on the type of table reference,
 
4239
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
 
4240
* below specific for the type of table reference.
 
4241
******************************************************************************/
1894
4242
 
1895
4243
/* Special Field pointers as return values of find_field_in_XXX functions. */
1896
4244
Field *not_found_field= (Field*) 0x1;
1897
 
Field *view_ref_found= (Field*) 0x2;
1898
 
 
1899
 
static void update_field_dependencies(Session *session, Field *field, Table *table)
 
4245
Field *view_ref_found= (Field*) 0x2; 
 
4246
 
 
4247
#define WRONG_GRANT (Field*) -1
 
4248
 
 
4249
static void update_field_dependencies(THD *thd, Field *field, TABLE *table)
1900
4250
{
1901
 
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
 
4251
  DBUG_ENTER("update_field_dependencies");
 
4252
  if (thd->mark_used_columns != MARK_COLUMNS_NONE)
1902
4253
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
4254
    MY_BITMAP *current_bitmap, *other_bitmap;
1904
4255
 
1905
4256
    /*
1906
4257
      We always want to register the used keys, as the column bitmap may have
1907
4258
      been set for all fields (for example for view).
1908
4259
    */
1909
 
 
1910
 
    table->covering_keys&= field->part_of_key;
1911
 
    table->merge_keys|= field->part_of_key;
1912
 
 
1913
 
    if (session->mark_used_columns == MARK_COLUMNS_READ)
 
4260
      
 
4261
    table->covering_keys.intersect(field->part_of_key);
 
4262
    table->merge_keys.merge(field->part_of_key);
 
4263
 
 
4264
    if (thd->mark_used_columns == MARK_COLUMNS_READ)
1914
4265
    {
1915
4266
      current_bitmap= table->read_set;
 
4267
      other_bitmap=   table->write_set;
1916
4268
    }
1917
4269
    else
1918
4270
    {
1919
4271
      current_bitmap= table->write_set;
 
4272
      other_bitmap=   table->read_set;
1920
4273
    }
1921
4274
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
4275
    if (bitmap_fast_test_and_set(current_bitmap, field->field_index))
1924
4276
    {
1925
 
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
 
        session->dup_field= field;
1927
 
      return;
 
4277
      if (thd->mark_used_columns == MARK_COLUMNS_WRITE)
 
4278
      {
 
4279
        DBUG_PRINT("warning", ("Found duplicated field"));
 
4280
        thd->dup_field= field;
 
4281
      }
 
4282
      else
 
4283
      {
 
4284
        DBUG_PRINT("note", ("Field found before"));
 
4285
      }
 
4286
      DBUG_VOID_RETURN;
1928
4287
    }
 
4288
    if (table->get_fields_in_item_tree)
 
4289
      field->flags|= GET_FIXED_FIELDS_FLAG;
1929
4290
    table->used_fields++;
1930
4291
  }
 
4292
  else if (table->get_fields_in_item_tree)
 
4293
    field->flags|= GET_FIXED_FIELDS_FLAG;
 
4294
  DBUG_VOID_RETURN;
 
4295
}
 
4296
 
 
4297
 
 
4298
/*
 
4299
  Find a field by name in a view that uses merge algorithm.
 
4300
 
 
4301
  SYNOPSIS
 
4302
    find_field_in_view()
 
4303
    thd                         thread handler
 
4304
    table_list                  view to search for 'name'
 
4305
    name                        name of field
 
4306
    length                      length of name
 
4307
    item_name                   name of item if it will be created (VIEW)
 
4308
    ref                         expression substituted in VIEW should be passed
 
4309
                                using this reference (return view_ref_found)
 
4310
    register_tree_change        TRUE if ref is not stack variable and we
 
4311
                                need register changes in item tree
 
4312
 
 
4313
  RETURN
 
4314
    0                   field is not found
 
4315
    view_ref_found      found value in VIEW (real result is in *ref)
 
4316
    #                   pointer to field - only for schema table fields
 
4317
*/
 
4318
 
 
4319
static Field *
 
4320
find_field_in_view(THD *thd, TABLE_LIST *table_list,
 
4321
                   const char *name, uint length,
 
4322
                   const char *item_name, Item **ref,
 
4323
                   bool register_tree_change)
 
4324
{
 
4325
  DBUG_ENTER("find_field_in_view");
 
4326
  DBUG_PRINT("enter",
 
4327
             ("view: '%s', field name: '%s', item name: '%s', ref 0x%lx",
 
4328
              table_list->alias, name, item_name, (ulong) ref));
 
4329
  Field_iterator_view field_it;
 
4330
  field_it.set(table_list);
 
4331
  
 
4332
  DBUG_ASSERT(table_list->schema_table_reformed ||
 
4333
              (ref != 0 && (0) != 0));
 
4334
  for (; !field_it.end_of_fields(); field_it.next())
 
4335
  {
 
4336
    if (!my_strcasecmp(system_charset_info, field_it.name(), name))
 
4337
    {
 
4338
      /*
 
4339
        create_item() may, or may not create a new Item, depending on
 
4340
        the column reference. See create_view_field() for details.
 
4341
      */
 
4342
      Item *item= field_it.create_item(thd);
 
4343
      
 
4344
      if (!item)
 
4345
        DBUG_RETURN(0);
 
4346
      /*
 
4347
       *ref != NULL means that *ref contains the item that we need to
 
4348
       replace. If the item was aliased by the user, set the alias to
 
4349
       the replacing item.
 
4350
       We need to set alias on both ref itself and on ref real item.
 
4351
      */
 
4352
      if (*ref && !(*ref)->is_autogenerated_name)
 
4353
      {
 
4354
        item->set_name((*ref)->name, (*ref)->name_length,
 
4355
                       system_charset_info);
 
4356
        item->real_item()->set_name((*ref)->name, (*ref)->name_length,
 
4357
                       system_charset_info);
 
4358
      }
 
4359
      if (register_tree_change)
 
4360
        thd->change_item_tree(ref, item);
 
4361
      else
 
4362
        *ref= item;
 
4363
      DBUG_RETURN((Field*) view_ref_found);
 
4364
    }
 
4365
  }
 
4366
  DBUG_RETURN(0);
1931
4367
}
1932
4368
 
1933
4369
 
1935
4371
  Find field by name in a NATURAL/USING join table reference.
1936
4372
 
1937
4373
  SYNOPSIS
1938
 
  find_field_in_natural_join()
1939
 
  session                        [in]  thread Cursor
1940
 
  table_ref            [in]  table reference to search
1941
 
  name           [in]  name of field
1942
 
  length                 [in]  length of name
1943
 
  ref                  [in/out] if 'name' is resolved to a view field, ref is
1944
 
  set to point to the found view field
1945
 
  register_tree_change [in]  true if ref is not stack variable and we
1946
 
  need register changes in item tree
1947
 
  actual_table         [out] the original table reference where the field
1948
 
  belongs - differs from 'table_list' only for
1949
 
  NATURAL/USING joins
 
4374
    find_field_in_natural_join()
 
4375
    thd                  [in]  thread handler
 
4376
    table_ref            [in]  table reference to search
 
4377
    name                 [in]  name of field
 
4378
    length               [in]  length of name
 
4379
    ref                  [in/out] if 'name' is resolved to a view field, ref is
 
4380
                               set to point to the found view field
 
4381
    register_tree_change [in]  TRUE if ref is not stack variable and we
 
4382
                               need register changes in item tree
 
4383
    actual_table         [out] the original table reference where the field
 
4384
                               belongs - differs from 'table_list' only for
 
4385
                               NATURAL/USING joins
1950
4386
 
1951
4387
  DESCRIPTION
1952
 
  Search for a field among the result fields of a NATURAL/USING join.
1953
 
  Notice that this procedure is called only for non-qualified field
1954
 
  names. In the case of qualified fields, we search directly the base
1955
 
  tables of a natural join.
 
4388
    Search for a field among the result fields of a NATURAL/USING join.
 
4389
    Notice that this procedure is called only for non-qualified field
 
4390
    names. In the case of qualified fields, we search directly the base
 
4391
    tables of a natural join.
1956
4392
 
1957
4393
  RETURN
1958
 
  NULL        if the field was not found
1959
 
  PTR         Pointer to the found Field
 
4394
    NULL        if the field was not found
 
4395
    WRONG_GRANT if no access rights to the found field
 
4396
    #           Pointer to the found Field
1960
4397
*/
1961
4398
 
1962
4399
static Field *
1963
 
find_field_in_natural_join(Session *session, TableList *table_ref,
1964
 
                           const char *name, uint32_t , Item **,
1965
 
                           bool, TableList **actual_table)
 
4400
find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name,
 
4401
                           uint length, Item **ref, bool register_tree_change,
 
4402
                           TABLE_LIST **actual_table)
1966
4403
{
1967
4404
  List_iterator_fast<Natural_join_column>
1968
4405
    field_it(*(table_ref->join_columns));
1969
4406
  Natural_join_column *nj_col, *curr_nj_col;
1970
4407
  Field *found_field;
1971
 
 
1972
 
  assert(table_ref->is_natural_join && table_ref->join_columns);
1973
 
  assert(*actual_table == NULL);
1974
 
 
1975
 
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
 
4408
  DBUG_ENTER("find_field_in_natural_join");
 
4409
  DBUG_PRINT("enter", ("field name: '%s', ref 0x%lx",
 
4410
                       name, (ulong) ref));
 
4411
  DBUG_ASSERT(table_ref->is_natural_join && table_ref->join_columns);
 
4412
  DBUG_ASSERT(*actual_table == NULL);
 
4413
 
 
4414
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col; 
1976
4415
       curr_nj_col= field_it++)
1977
4416
  {
1978
4417
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
1979
4418
    {
1980
4419
      if (nj_col)
1981
4420
      {
1982
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1983
 
        return NULL;
 
4421
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
 
4422
        DBUG_RETURN(NULL);
1984
4423
      }
1985
4424
      nj_col= curr_nj_col;
1986
4425
    }
1987
4426
  }
1988
4427
  if (!nj_col)
1989
 
    return NULL;
 
4428
    DBUG_RETURN(NULL);
 
4429
 
 
4430
  if (nj_col->view_field)
 
4431
  {
 
4432
    Item *item;
 
4433
    /*
 
4434
      create_item() may, or may not create a new Item, depending on the
 
4435
      column reference. See create_view_field() for details.
 
4436
    */
 
4437
    item= nj_col->create_item(thd);
 
4438
    /*
 
4439
     *ref != NULL means that *ref contains the item that we need to
 
4440
     replace. If the item was aliased by the user, set the alias to
 
4441
     the replacing item.
 
4442
     We need to set alias on both ref itself and on ref real item.
 
4443
     */
 
4444
    if (*ref && !(*ref)->is_autogenerated_name)
 
4445
    {
 
4446
      item->set_name((*ref)->name, (*ref)->name_length,
 
4447
                     system_charset_info);
 
4448
      item->real_item()->set_name((*ref)->name, (*ref)->name_length,
 
4449
                                  system_charset_info);
 
4450
    }
 
4451
 
 
4452
    if (!item)
 
4453
      DBUG_RETURN(NULL);
 
4454
    DBUG_ASSERT(nj_col->table_field == NULL);
 
4455
    if (nj_col->table_ref->schema_table_reformed)
 
4456
    {
 
4457
      /*
 
4458
        Translation table items are always Item_fields and fixed
 
4459
        already('mysql_schema_table' function). So we can return
 
4460
        ->field. It is used only for 'show & where' commands.
 
4461
      */
 
4462
      DBUG_RETURN(((Item_field*) (nj_col->view_field->item))->field);
 
4463
    }
 
4464
    if (register_tree_change)
 
4465
      thd->change_item_tree(ref, item);
 
4466
    else
 
4467
      *ref= item;
 
4468
    found_field= (Field*) view_ref_found;
 
4469
  }
 
4470
  else
1990
4471
  {
1991
4472
    /* This is a base table. */
1992
 
    assert(nj_col->table_ref->table == nj_col->table_field->getTable());
 
4473
    DBUG_ASSERT(nj_col->view_field == NULL);
 
4474
    DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->table);
1993
4475
    found_field= nj_col->table_field;
1994
 
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
 
4476
    update_field_dependencies(thd, found_field, nj_col->table_ref->table);
1995
4477
  }
1996
4478
 
1997
4479
  *actual_table= nj_col->table_ref;
1998
 
 
1999
 
  return(found_field);
 
4480
  
 
4481
  DBUG_RETURN(found_field);
2000
4482
}
2001
4483
 
2002
4484
 
2004
4486
  Find field by name in a base table or a view with temp table algorithm.
2005
4487
 
2006
4488
  SYNOPSIS
2007
 
  find_field_in_table()
2008
 
  session                               thread Cursor
2009
 
  table                 table where to search for the field
2010
 
  name                  name of field
2011
 
  length                        length of name
2012
 
  allow_rowid                   do allow finding of "_rowid" field?
2013
 
  cached_field_index_ptr        cached position in field list (used to speedup
2014
 
  lookup for fields in prepared tables)
 
4489
    find_field_in_table()
 
4490
    thd                         thread handler
 
4491
    table                       table where to search for the field
 
4492
    name                        name of field
 
4493
    length                      length of name
 
4494
    allow_rowid                 do allow finding of "_rowid" field?
 
4495
    cached_field_index_ptr      cached position in field list (used to speedup
 
4496
                                lookup for fields in prepared tables)
2015
4497
 
2016
4498
  RETURN
2017
 
  0     field is not found
2018
 
#       pointer to field
 
4499
    0   field is not found
 
4500
    #   pointer to field
2019
4501
*/
2020
4502
 
2021
4503
Field *
2022
 
find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
2023
 
                    bool allow_rowid, uint32_t *cached_field_index_ptr)
 
4504
find_field_in_table(THD *thd, TABLE *table, const char *name, uint length,
 
4505
                    bool allow_rowid, uint *cached_field_index_ptr)
2024
4506
{
2025
4507
  Field **field_ptr, *field;
2026
 
  uint32_t cached_field_index= *cached_field_index_ptr;
 
4508
  uint cached_field_index= *cached_field_index_ptr;
 
4509
  DBUG_ENTER("find_field_in_table");
 
4510
  DBUG_PRINT("enter", ("table: '%s', field name: '%s'", table->alias, name));
2027
4511
 
2028
4512
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2029
 
  if (cached_field_index < table->getShare()->sizeFields() &&
 
4513
  if (cached_field_index < table->s->fields &&
2030
4514
      !my_strcasecmp(system_charset_info,
2031
 
                     table->getField(cached_field_index)->field_name, name))
2032
 
  {
2033
 
    field_ptr= table->getFields() + cached_field_index;
2034
 
  }
2035
 
  else if (table->getShare()->getNamedFieldSize())
2036
 
  {
2037
 
    field_ptr= table->getMutableShare()->getNamedField(std::string(name, length));
 
4515
                     table->field[cached_field_index]->field_name, name))
 
4516
    field_ptr= table->field + cached_field_index;
 
4517
  else if (table->s->name_hash.records)
 
4518
  {
 
4519
    field_ptr= (Field**) hash_search(&table->s->name_hash, (uchar*) name,
 
4520
                                     length);
2038
4521
    if (field_ptr)
2039
4522
    {
2040
4523
      /*
2041
 
        field_ptr points to field in TableShare. Convert it to the matching
 
4524
        field_ptr points to field in TABLE_SHARE. Convert it to the matching
2042
4525
        field in table
2043
4526
      */
2044
 
      field_ptr= (table->getFields() + table->getShare()->positionFields(field_ptr));
 
4527
      field_ptr= (table->field + (field_ptr - table->s->field));
2045
4528
    }
2046
4529
  }
2047
4530
  else
2048
4531
  {
2049
 
    if (!(field_ptr= table->getFields()))
2050
 
      return((Field *)0);
 
4532
    if (!(field_ptr= table->field))
 
4533
      DBUG_RETURN((Field *)0);
2051
4534
    for (; *field_ptr; ++field_ptr)
2052
4535
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2053
4536
        break;
2055
4538
 
2056
4539
  if (field_ptr && *field_ptr)
2057
4540
  {
2058
 
    *cached_field_index_ptr= field_ptr - table->getFields();
 
4541
    *cached_field_index_ptr= field_ptr - table->field;
2059
4542
    field= *field_ptr;
2060
4543
  }
2061
4544
  else
2062
4545
  {
2063
4546
    if (!allow_rowid ||
2064
4547
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2065
 
        table->getShare()->rowid_field_offset == 0)
2066
 
      return((Field*) 0);
2067
 
    field= table->getField(table->getShare()->rowid_field_offset-1);
 
4548
        table->s->rowid_field_offset == 0)
 
4549
      DBUG_RETURN((Field*) 0);
 
4550
    field= table->field[table->s->rowid_field_offset-1];
2068
4551
  }
2069
4552
 
2070
 
  update_field_dependencies(session, field, table);
 
4553
  update_field_dependencies(thd, field, table);
2071
4554
 
2072
 
  return field;
 
4555
  DBUG_RETURN(field);
2073
4556
}
2074
4557
 
2075
4558
 
2077
4560
  Find field in a table reference.
2078
4561
 
2079
4562
  SYNOPSIS
2080
 
  find_field_in_table_ref()
2081
 
  session                          [in]  thread Cursor
2082
 
  table_list               [in]  table reference to search
2083
 
  name             [in]  name of field
2084
 
  length                   [in]  field length of name
2085
 
  item_name              [in]  name of item if it will be created (VIEW)
2086
 
  db_name                [in]  optional database name that qualifies the
2087
 
  table_name             [in]  optional table name that qualifies the field
2088
 
  ref                  [in/out] if 'name' is resolved to a view field, ref
2089
 
  is set to point to the found view field
2090
 
  allow_rowid              [in]  do allow finding of "_rowid" field?
2091
 
  cached_field_index_ptr [in]  cached position in field list (used to
2092
 
  speedup lookup for fields in prepared tables)
2093
 
  register_tree_change   [in]  true if ref is not stack variable and we
2094
 
  need register changes in item tree
2095
 
  actual_table           [out] the original table reference where the field
2096
 
  belongs - differs from 'table_list' only for
2097
 
  NATURAL_USING joins.
 
4563
    find_field_in_table_ref()
 
4564
    thd                    [in]  thread handler
 
4565
    table_list             [in]  table reference to search
 
4566
    name                   [in]  name of field
 
4567
    length                 [in]  field length of name
 
4568
    item_name              [in]  name of item if it will be created (VIEW)
 
4569
    db_name                [in]  optional database name that qualifies the
 
4570
    table_name             [in]  optional table name that qualifies the field
 
4571
    ref                [in/out] if 'name' is resolved to a view field, ref
 
4572
                                 is set to point to the found view field
 
4573
    check_privileges       [in]  check privileges
 
4574
    allow_rowid            [in]  do allow finding of "_rowid" field?
 
4575
    cached_field_index_ptr [in]  cached position in field list (used to
 
4576
                                 speedup lookup for fields in prepared tables)
 
4577
    register_tree_change   [in]  TRUE if ref is not stack variable and we
 
4578
                                 need register changes in item tree
 
4579
    actual_table           [out] the original table reference where the field
 
4580
                                 belongs - differs from 'table_list' only for
 
4581
                                 NATURAL_USING joins.
2098
4582
 
2099
4583
  DESCRIPTION
2100
 
  Find a field in a table reference depending on the type of table
2101
 
  reference. There are three types of table references with respect
2102
 
  to the representation of their result columns:
2103
 
  - an array of Field_translator objects for MERGE views and some
2104
 
  information_schema tables,
2105
 
  - an array of Field objects (and possibly a name hash) for stored
2106
 
  tables,
2107
 
  - a list of Natural_join_column objects for NATURAL/USING joins.
2108
 
  This procedure detects the type of the table reference 'table_list'
2109
 
  and calls the corresponding search routine.
 
4584
    Find a field in a table reference depending on the type of table
 
4585
    reference. There are three types of table references with respect
 
4586
    to the representation of their result columns:
 
4587
    - an array of Field_translator objects for MERGE views and some
 
4588
      information_schema tables,
 
4589
    - an array of Field objects (and possibly a name hash) for stored
 
4590
      tables,
 
4591
    - a list of Natural_join_column objects for NATURAL/USING joins.
 
4592
    This procedure detects the type of the table reference 'table_list'
 
4593
    and calls the corresponding search routine.
2110
4594
 
2111
4595
  RETURN
2112
 
  0                     field is not found
2113
 
  view_ref_found        found value in VIEW (real result is in *ref)
2114
 
#                       pointer to field
 
4596
    0                   field is not found
 
4597
    view_ref_found      found value in VIEW (real result is in *ref)
 
4598
    #                   pointer to field
2115
4599
*/
2116
4600
 
2117
4601
Field *
2118
 
find_field_in_table_ref(Session *session, TableList *table_list,
2119
 
                        const char *name, uint32_t length,
 
4602
find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
 
4603
                        const char *name, uint length,
2120
4604
                        const char *item_name, const char *db_name,
2121
4605
                        const char *table_name, Item **ref,
2122
 
                        bool allow_rowid,
2123
 
                        uint32_t *cached_field_index_ptr,
2124
 
                        bool register_tree_change, TableList **actual_table)
 
4606
                        bool check_privileges, bool allow_rowid,
 
4607
                        uint *cached_field_index_ptr,
 
4608
                        bool register_tree_change, TABLE_LIST **actual_table)
2125
4609
{
2126
 
  Field *fld= NULL;
2127
 
 
2128
 
  assert(table_list->alias);
2129
 
  assert(name);
2130
 
  assert(item_name);
 
4610
  Field *fld;
 
4611
  DBUG_ENTER("find_field_in_table_ref");
 
4612
  DBUG_ASSERT(table_list->alias);
 
4613
  DBUG_ASSERT(name);
 
4614
  DBUG_ASSERT(item_name);
 
4615
  DBUG_PRINT("enter",
 
4616
             ("table: '%s'  field name: '%s'  item name: '%s'  ref 0x%lx",
 
4617
              table_list->alias, name, item_name, (ulong) ref));
2131
4618
 
2132
4619
  /*
2133
4620
    Check that the table and database that qualify the current field name
2143
4630
    inside the view, but we want to search directly in the view columns
2144
4631
    which are represented as a 'field_translation'.
2145
4632
 
2146
 
    TODO-> Ensure that table_name, db_name and tables->db always points to something !
 
4633
    TODO: Ensure that table_name, db_name and tables->db always points to
 
4634
          something !
2147
4635
  */
2148
4636
  if (/* Exclude nested joins. */
2149
 
      (!table_list->getNestedJoin()) &&
2150
 
      /* Include merge views and information schema tables. */
 
4637
      (!table_list->nested_join ||
 
4638
       /* Include merge views and information schema tables. */
 
4639
       table_list->field_translation) &&
2151
4640
      /*
2152
4641
        Test if the field qualifiers match the table reference we plan
2153
4642
        to search.
2154
4643
      */
2155
4644
      table_name && table_name[0] &&
2156
4645
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2157
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
 
        strcmp(db_name, table_list->getSchemaName()))))
2159
 
    return 0;
 
4646
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
4647
        strcmp(db_name, table_list->db))))
 
4648
    DBUG_RETURN(0);
2160
4649
 
2161
4650
  *actual_table= NULL;
2162
4651
 
2163
 
  if (!table_list->getNestedJoin())
 
4652
  if (table_list->field_translation)
 
4653
  {
 
4654
    /* 'table_list' is a view or an information schema table. */
 
4655
    if ((fld= find_field_in_view(thd, table_list, name, length, item_name, ref,
 
4656
                                 register_tree_change)))
 
4657
      *actual_table= table_list;
 
4658
  }
 
4659
  else if (!table_list->nested_join)
2164
4660
  {
2165
4661
    /* 'table_list' is a stored table. */
2166
 
    assert(table_list->table);
2167
 
    if ((fld= find_field_in_table(session, table_list->table, name, length,
 
4662
    DBUG_ASSERT(table_list->table);
 
4663
    if ((fld= find_field_in_table(thd, table_list->table, name, length,
2168
4664
                                  allow_rowid,
2169
4665
                                  cached_field_index_ptr)))
2170
4666
      *actual_table= table_list;
2180
4676
    */
2181
4677
    if (table_name && table_name[0])
2182
4678
    {
2183
 
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
2184
 
      TableList *table;
 
4679
      List_iterator<TABLE_LIST> it(table_list->nested_join->join_list);
 
4680
      TABLE_LIST *table;
2185
4681
      while ((table= it++))
2186
4682
      {
2187
 
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
 
4683
        if ((fld= find_field_in_table_ref(thd, table, name, length, item_name,
2188
4684
                                          db_name, table_name, ref,
2189
 
                                          allow_rowid,
 
4685
                                          check_privileges, allow_rowid,
2190
4686
                                          cached_field_index_ptr,
2191
4687
                                          register_tree_change, actual_table)))
2192
 
          return fld;
 
4688
          DBUG_RETURN(fld);
2193
4689
      }
2194
 
      return NULL;
 
4690
      DBUG_RETURN(0);
2195
4691
    }
2196
4692
    /*
2197
4693
      Non-qualified field, search directly in the result columns of the
2199
4695
      natural join, thus if the field is not qualified, we will search
2200
4696
      directly the top-most NATURAL/USING join.
2201
4697
    */
2202
 
    fld= find_field_in_natural_join(session, table_list, name, length, ref,
 
4698
    fld= find_field_in_natural_join(thd, table_list, name, length, ref,
2203
4699
                                    register_tree_change, actual_table);
2204
4700
  }
2205
4701
 
2206
4702
  if (fld)
2207
4703
  {
2208
 
    if (session->mark_used_columns != MARK_COLUMNS_NONE)
 
4704
      if (thd->mark_used_columns != MARK_COLUMNS_NONE)
 
4705
      {
 
4706
        /*
 
4707
          Get rw_set correct for this field so that the handler
 
4708
          knows that this field is involved in the query and gets
 
4709
          retrieved/updated
 
4710
         */
 
4711
        Field *field_to_set= NULL;
 
4712
        if (fld == view_ref_found)
 
4713
        {
 
4714
          Item *it= (*ref)->real_item();
 
4715
          if (it->type() == Item::FIELD_ITEM)
 
4716
            field_to_set= ((Item_field*)it)->field;
 
4717
          else
 
4718
          {
 
4719
            if (thd->mark_used_columns == MARK_COLUMNS_READ)
 
4720
              it->walk(&Item::register_field_in_read_map, 1, (uchar *) 0);
 
4721
          }
 
4722
        }
 
4723
        else
 
4724
          field_to_set= fld;
 
4725
        if (field_to_set)
 
4726
        {
 
4727
          TABLE *table= field_to_set->table;
 
4728
          if (thd->mark_used_columns == MARK_COLUMNS_READ)
 
4729
            bitmap_set_bit(table->read_set, field_to_set->field_index);
 
4730
          else
 
4731
            bitmap_set_bit(table->write_set, field_to_set->field_index);
 
4732
        }
 
4733
      }
 
4734
  }
 
4735
  DBUG_RETURN(fld);
 
4736
}
 
4737
 
 
4738
 
 
4739
/*
 
4740
  Find field in table, no side effects, only purpose is to check for field
 
4741
  in table object and get reference to the field if found.
 
4742
 
 
4743
  SYNOPSIS
 
4744
  find_field_in_table_sef()
 
4745
 
 
4746
  table                         table where to find
 
4747
  name                          Name of field searched for
 
4748
 
 
4749
  RETURN
 
4750
    0                   field is not found
 
4751
    #                   pointer to field
 
4752
*/
 
4753
 
 
4754
Field *find_field_in_table_sef(TABLE *table, const char *name)
 
4755
{
 
4756
  Field **field_ptr;
 
4757
  if (table->s->name_hash.records)
 
4758
  {
 
4759
    field_ptr= (Field**)hash_search(&table->s->name_hash,(uchar*) name,
 
4760
                                    strlen(name));
 
4761
    if (field_ptr)
2209
4762
    {
2210
4763
      /*
2211
 
        Get rw_set correct for this field so that the Cursor
2212
 
        knows that this field is involved in the query and gets
2213
 
        retrieved/updated
 
4764
        field_ptr points to field in TABLE_SHARE. Convert it to the matching
 
4765
        field in table
2214
4766
      */
2215
 
      Field *field_to_set= NULL;
2216
 
      if (fld == view_ref_found)
2217
 
      {
2218
 
        Item *it= (*ref)->real_item();
2219
 
        if (it->type() == Item::FIELD_ITEM)
2220
 
          field_to_set= ((Item_field*)it)->field;
2221
 
        else
2222
 
        {
2223
 
          if (session->mark_used_columns == MARK_COLUMNS_READ)
2224
 
            it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
2225
 
        }
2226
 
      }
2227
 
      else
2228
 
        field_to_set= fld;
2229
 
      if (field_to_set)
2230
 
      {
2231
 
        Table *table= field_to_set->getTable();
2232
 
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
2234
 
        else
2235
 
          table->setWriteSet(field_to_set->position());
2236
 
      }
 
4767
      field_ptr= (table->field + (field_ptr - table->s->field));
2237
4768
    }
2238
4769
  }
2239
 
  return(fld);
 
4770
  else
 
4771
  {
 
4772
    if (!(field_ptr= table->field))
 
4773
      return (Field *)0;
 
4774
    for (; *field_ptr; ++field_ptr)
 
4775
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
 
4776
        break;
 
4777
  }
 
4778
  if (field_ptr)
 
4779
    return *field_ptr;
 
4780
  else
 
4781
    return (Field *)0;
2240
4782
}
2241
4783
 
2242
4784
 
2244
4786
  Find field in table list.
2245
4787
 
2246
4788
  SYNOPSIS
2247
 
  find_field_in_tables()
2248
 
  session                         pointer to current thread structure
2249
 
  item            field item that should be found
2250
 
  first_table           list of tables to be searched for item
2251
 
  last_table            end of the list of tables to search for item. If NULL
2252
 
  then search to the end of the list 'first_table'.
2253
 
  ref                     if 'item' is resolved to a view field, ref is set to
2254
 
  point to the found view field
2255
 
  report_error    Degree of error reporting:
2256
 
  - IGNORE_ERRORS then do not report any error
2257
 
  - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2258
 
  fields, suppress all other errors
2259
 
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2260
 
  except when non-unique fields were found
2261
 
  - REPORT_ALL_ERRORS
2262
 
  register_tree_change  true if ref is not a stack variable and we
2263
 
  to need register changes in item tree
 
4789
    find_field_in_tables()
 
4790
    thd                   pointer to current thread structure
 
4791
    item                  field item that should be found
 
4792
    first_table           list of tables to be searched for item
 
4793
    last_table            end of the list of tables to search for item. If NULL
 
4794
                          then search to the end of the list 'first_table'.
 
4795
    ref                   if 'item' is resolved to a view field, ref is set to
 
4796
                          point to the found view field
 
4797
    report_error          Degree of error reporting:
 
4798
                          - IGNORE_ERRORS then do not report any error
 
4799
                          - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
 
4800
                            fields, suppress all other errors
 
4801
                          - REPORT_EXCEPT_NON_UNIQUE report all other errors
 
4802
                            except when non-unique fields were found
 
4803
                          - REPORT_ALL_ERRORS
 
4804
    check_privileges      need to check privileges
 
4805
    register_tree_change  TRUE if ref is not a stack variable and we
 
4806
                          to need register changes in item tree
2264
4807
 
2265
4808
  RETURN VALUES
2266
 
  0                     If error: the found field is not unique, or there are
2267
 
  no sufficient access priviliges for the found field,
2268
 
  or the field is qualified with non-existing table.
2269
 
  not_found_field       The function was called with report_error ==
2270
 
  (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2271
 
  field was not found.
2272
 
  view_ref_found        View field is found, item passed through ref parameter
2273
 
  found field         If a item was resolved to some field
 
4809
    0                   If error: the found field is not unique, or there are
 
4810
                        no sufficient access priviliges for the found field,
 
4811
                        or the field is qualified with non-existing table.
 
4812
    not_found_field     The function was called with report_error ==
 
4813
                        (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
 
4814
                        field was not found.
 
4815
    view_ref_found      View field is found, item passed through ref parameter
 
4816
    found field         If a item was resolved to some field
2274
4817
*/
2275
4818
 
2276
4819
Field *
2277
 
find_field_in_tables(Session *session, Item_ident *item,
2278
 
                     TableList *first_table, TableList *last_table,
2279
 
                     Item **ref, find_item_error_report_type report_error,
2280
 
                     bool register_tree_change)
 
4820
find_field_in_tables(THD *thd, Item_ident *item,
 
4821
                     TABLE_LIST *first_table, TABLE_LIST *last_table,
 
4822
                     Item **ref, find_item_error_report_type report_error,
 
4823
                     bool check_privileges, bool register_tree_change)
2281
4824
{
2282
4825
  Field *found=0;
2283
4826
  const char *db= item->db_name;
2284
4827
  const char *table_name= item->table_name;
2285
4828
  const char *name= item->field_name;
2286
 
  uint32_t length=(uint32_t) strlen(name);
 
4829
  uint length=(uint) strlen(name);
2287
4830
  char name_buff[NAME_LEN+1];
2288
 
  TableList *cur_table= first_table;
2289
 
  TableList *actual_table;
 
4831
  TABLE_LIST *cur_table= first_table;
 
4832
  TABLE_LIST *actual_table;
2290
4833
  bool allow_rowid;
2291
4834
 
2292
4835
  if (!table_name || !table_name[0])
2301
4844
  {
2302
4845
    /*
2303
4846
      This shortcut is used by prepared statements. We assume that
2304
 
      TableList *first_table is not changed during query execution (which
 
4847
      TABLE_LIST *first_table is not changed during query execution (which
2305
4848
      is true for all queries except RENAME but luckily RENAME doesn't
2306
4849
      use fields...) so we can rely on reusing pointer to its member.
2307
4850
      With this optimization we also miss case when addition of one more
2308
4851
      field makes some prepared query ambiguous and so erroneous, but we
2309
4852
      accept this trade off.
2310
4853
    */
2311
 
    TableList *table_ref= item->cached_table;
 
4854
    TABLE_LIST *table_ref= item->cached_table;
2312
4855
    /*
2313
4856
      The condition (table_ref->view == NULL) ensures that we will call
2314
4857
      find_field_in_table even in the case of information schema tables
2315
4858
      when table_ref->field_translation != NULL.
2316
 
    */
 
4859
      */
2317
4860
    if (table_ref->table)
2318
 
      found= find_field_in_table(session, table_ref->table, name, length,
2319
 
                                 true, &(item->cached_field_index));
 
4861
      found= find_field_in_table(thd, table_ref->table, name, length,
 
4862
                                 TRUE, &(item->cached_field_index));
2320
4863
    else
2321
 
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
2322
 
                                     NULL, NULL, ref,
2323
 
                                     true, &(item->cached_field_index),
 
4864
      found= find_field_in_table_ref(thd, table_ref, name, length, item->name,
 
4865
                                     NULL, NULL, ref, check_privileges,
 
4866
                                     TRUE, &(item->cached_field_index),
2324
4867
                                     register_tree_change,
2325
4868
                                     &actual_table);
2326
4869
    if (found)
2327
4870
    {
 
4871
      if (found == WRONG_GRANT)
 
4872
        return (Field*) 0;
 
4873
 
2328
4874
      /*
2329
4875
        Only views fields should be marked as dependent, not an underlying
2330
4876
        fields.
2331
4877
      */
 
4878
      if (!table_ref->belong_to_view)
2332
4879
      {
2333
 
        Select_Lex *current_sel= session->lex->current_select;
2334
 
        Select_Lex *last_select= table_ref->select_lex;
 
4880
        SELECT_LEX *current_sel= thd->lex->current_select;
 
4881
        SELECT_LEX *last_select= table_ref->select_lex;
2335
4882
        /*
2336
4883
          If the field was an outer referencee, mark all selects using this
2337
4884
          sub query as dependent on the outer query
2338
4885
        */
2339
4886
        if (current_sel != last_select)
2340
 
          mark_select_range_as_dependent(session, last_select, current_sel,
 
4887
          mark_select_range_as_dependent(thd, last_select, current_sel,
2341
4888
                                         found, *ref, item);
2342
4889
      }
2343
4890
      return found;
2344
4891
    }
2345
4892
  }
2346
4893
 
2347
 
  if (db)
 
4894
  if (db && lower_case_table_names)
2348
4895
  {
2349
4896
    /*
2350
4897
      convert database to lower case for comparison.
2351
4898
      We can't do this in Item_field as this would change the
2352
4899
      'name' of the item which may be used in the select list
2353
4900
    */
2354
 
    strncpy(name_buff, db, sizeof(name_buff)-1);
 
4901
    strmake(name_buff, db, sizeof(name_buff)-1);
2355
4902
    my_casedn_str(files_charset_info, name_buff);
2356
4903
    db= name_buff;
2357
4904
  }
2362
4909
  for (; cur_table != last_table ;
2363
4910
       cur_table= cur_table->next_name_resolution_table)
2364
4911
  {
2365
 
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
 
4912
    Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,
2366
4913
                                              item->name, db, table_name, ref,
 
4914
                                              (thd->lex->sql_command ==
 
4915
                                               SQLCOM_SHOW_FIELDS)
 
4916
                                              ? false : check_privileges,
2367
4917
                                              allow_rowid,
2368
4918
                                              &(item->cached_field_index),
2369
4919
                                              register_tree_change,
2370
4920
                                              &actual_table);
2371
4921
    if (cur_field)
2372
4922
    {
 
4923
      if (cur_field == WRONG_GRANT)
 
4924
      {
 
4925
        if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)
 
4926
          return (Field*) 0;
 
4927
 
 
4928
        thd->clear_error();
 
4929
        cur_field= find_field_in_table_ref(thd, cur_table, name, length,
 
4930
                                           item->name, db, table_name, ref,
 
4931
                                           false,
 
4932
                                           allow_rowid,
 
4933
                                           &(item->cached_field_index),
 
4934
                                           register_tree_change,
 
4935
                                           &actual_table);
 
4936
        if (cur_field)
 
4937
        {
 
4938
          Field *nf=new Field_null(NULL,0,Field::NONE,
 
4939
                                   cur_field->field_name,
 
4940
                                   &my_charset_bin);
 
4941
          nf->init(cur_table->table);
 
4942
          cur_field= nf;
 
4943
        }
 
4944
      }
 
4945
 
2373
4946
      /*
2374
4947
        Store the original table of the field, which may be different from
2375
4948
        cur_table in the case of NATURAL/USING join.
2376
4949
      */
2377
 
      item->cached_table= found ?  0 : actual_table;
 
4950
      item->cached_table= (!actual_table->cacheable_table || found) ?
 
4951
                          0 : actual_table;
2378
4952
 
2379
 
      assert(session->where);
 
4953
      DBUG_ASSERT(thd->where);
2380
4954
      /*
2381
4955
        If we found a fully qualified field we return it directly as it can't
2382
4956
        have duplicates.
2383
 
      */
 
4957
       */
2384
4958
      if (db)
2385
4959
        return cur_field;
2386
4960
 
2389
4963
        if (report_error == REPORT_ALL_ERRORS ||
2390
4964
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2391
4965
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2392
 
                   table_name ? item->full_name() : name, session->where);
 
4966
                   table_name ? item->full_name() : name, thd->where);
2393
4967
        return (Field*) 0;
2394
4968
      }
2395
4969
      found= cur_field;
2413
4987
    char buff[NAME_LEN*2+1];
2414
4988
    if (db && db[0])
2415
4989
    {
2416
 
      /* We're in an error condition, two extra strlen's aren't going
2417
 
       * to kill us */
2418
 
      assert(strlen(db) <= NAME_LEN);
2419
 
      assert(strlen(table_name) <= NAME_LEN);
2420
 
      strcpy(buff, db);
2421
 
      strcat(buff,".");
2422
 
      strcat(buff, table_name);
 
4990
      strxnmov(buff,sizeof(buff)-1,db,".",table_name,NullS);
2423
4991
      table_name=buff;
2424
4992
    }
2425
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
 
4993
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
2426
4994
  }
2427
4995
  else
2428
4996
  {
2429
4997
    if (report_error == REPORT_ALL_ERRORS ||
2430
4998
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2431
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
 
4999
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);
2432
5000
    else
2433
5001
      found= not_found_field;
2434
5002
  }
2440
5008
  Find Item in list of items (find_field_in_tables analog)
2441
5009
 
2442
5010
  TODO
2443
 
  is it better return only counter?
 
5011
    is it better return only counter?
2444
5012
 
2445
5013
  SYNOPSIS
2446
 
  find_item_in_list()
2447
 
  find                  Item to find
2448
 
  items                 List of items
2449
 
  counter                       To return number of found item
2450
 
  report_error
2451
 
  REPORT_ALL_ERRORS             report errors, return 0 if error
2452
 
  REPORT_EXCEPT_NOT_FOUND       Do not report 'not found' error and
2453
 
  return not_found_item, report other errors,
2454
 
  return 0
2455
 
  IGNORE_ERRORS         Do not report errors, return 0 if error
2456
 
  resolution                  Set to the resolution type if the item is found
2457
 
  (it says whether the item is resolved
2458
 
  against an alias name,
2459
 
  or as a field name without alias,
2460
 
  or as a field hidden by alias,
2461
 
  or ignoring alias)
2462
 
 
 
5014
    find_item_in_list()
 
5015
    find                        Item to find
 
5016
    items                       List of items
 
5017
    counter                     To return number of found item
 
5018
    report_error
 
5019
      REPORT_ALL_ERRORS         report errors, return 0 if error
 
5020
      REPORT_EXCEPT_NOT_FOUND   Do not report 'not found' error and
 
5021
                                return not_found_item, report other errors,
 
5022
                                return 0
 
5023
      IGNORE_ERRORS             Do not report errors, return 0 if error
 
5024
    resolution                  Set to the resolution type if the item is found 
 
5025
                                (it says whether the item is resolved 
 
5026
                                 against an alias name,
 
5027
                                 or as a field name without alias,
 
5028
                                 or as a field hidden by alias,
 
5029
                                 or ignoring alias)
 
5030
                                
2463
5031
  RETURN VALUES
2464
 
  0                     Item is not found or item is not unique,
2465
 
  error message is reported
2466
 
  not_found_item        Function was called with
2467
 
  report_error == REPORT_EXCEPT_NOT_FOUND and
2468
 
  item was not found. No error message was reported
2469
 
  found field
 
5032
    0                   Item is not found or item is not unique,
 
5033
                        error message is reported
 
5034
    not_found_item      Function was called with
 
5035
                        report_error == REPORT_EXCEPT_NOT_FOUND and
 
5036
                        item was not found. No error message was reported
 
5037
                        found field
2470
5038
*/
2471
5039
 
2472
5040
/* Special Item pointer to serve as a return value from find_item_in_list(). */
2474
5042
 
2475
5043
 
2476
5044
Item **
2477
 
find_item_in_list(Session *session,
2478
 
                  Item *find, List<Item> &items, uint32_t *counter,
 
5045
find_item_in_list(Item *find, List<Item> &items, uint *counter,
2479
5046
                  find_item_error_report_type report_error,
2480
5047
                  enum_resolution_type *resolution)
2481
5048
{
2490
5057
    (and not an item that happens to have a name).
2491
5058
  */
2492
5059
  bool is_ref_by_name= 0;
2493
 
  uint32_t unaliased_counter= 0;
 
5060
  uint unaliased_counter= 0;
2494
5061
 
2495
5062
  *resolution= NOT_RESOLVED;
2496
5063
 
2497
 
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
 
5064
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  || 
2498
5065
                   find->type() == Item::REF_ITEM);
2499
5066
  if (is_ref_by_name)
2500
5067
  {
2503
5070
    db_name=    ((Item_ident*) find)->db_name;
2504
5071
  }
2505
5072
 
2506
 
  for (uint32_t i= 0; (item=li++); i++)
 
5073
  for (uint i= 0; (item=li++); i++)
2507
5074
  {
2508
5075
    if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
2509
5076
    {
2510
5077
      Item_ident *item_field= (Item_ident*) item;
2511
5078
 
2512
5079
      /*
2513
 
        In case of group_concat() with ORDER BY condition in the QUERY
2514
 
        item_field can be field of temporary table without item name
2515
 
        (if this field created from expression argument of group_concat()),
2516
 
        => we have to check presence of name before compare
2517
 
      */
 
5080
        In case of group_concat() with ORDER BY condition in the QUERY
 
5081
        item_field can be field of temporary table without item name 
 
5082
        (if this field created from expression argument of group_concat()),
 
5083
        => we have to check presence of name before compare
 
5084
      */ 
2518
5085
      if (!item_field->name)
2519
5086
        continue;
2520
5087
 
2533
5100
          case sensitive. In cases where they are not case sensitive, they
2534
5101
          are always in lower case.
2535
5102
 
2536
 
          item_field->field_name and item_field->table_name can be 0x0 if
2537
 
          item is not fix_field()'ed yet.
 
5103
          item_field->field_name and item_field->table_name can be 0x0 if
 
5104
          item is not fix_field()'ed yet.
2538
5105
        */
2539
5106
        if (item_field->field_name && item_field->table_name &&
2540
 
            !my_strcasecmp(system_charset_info, item_field->field_name,
 
5107
            !my_strcasecmp(system_charset_info, item_field->field_name,
2541
5108
                           field_name) &&
2542
 
            !my_strcasecmp(table_alias_charset, item_field->table_name,
 
5109
            !my_strcasecmp(table_alias_charset, item_field->table_name, 
2543
5110
                           table_name) &&
2544
5111
            (!db_name || (item_field->db_name &&
2545
5112
                          !strcmp(item_field->db_name, db_name))))
2555
5122
            */
2556
5123
            if (report_error != IGNORE_ERRORS)
2557
5124
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2558
 
                       find->full_name(), session->where);
 
5125
                       find->full_name(), current_thd->where);
2559
5126
            return (Item**) 0;
2560
5127
          }
2561
5128
          found_unaliased= li.ref();
2586
5153
              continue;                           // Same field twice
2587
5154
            if (report_error != IGNORE_ERRORS)
2588
5155
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2589
 
                       find->full_name(), session->where);
 
5156
                       find->full_name(), current_thd->where);
2590
5157
            return (Item**) 0;
2591
5158
          }
2592
5159
          found= li.ref();
2593
5160
          *counter= i;
2594
5161
          *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
2595
 
            RESOLVED_WITH_NO_ALIAS;
 
5162
                                   RESOLVED_WITH_NO_ALIAS;
2596
5163
        }
2597
5164
        else if (!fname_cmp)
2598
5165
        {
2614
5181
      }
2615
5182
    }
2616
5183
    else if (!table_name)
2617
 
    {
 
5184
    { 
2618
5185
      if (is_ref_by_name && find->name && item->name &&
2619
 
          !my_strcasecmp(system_charset_info,item->name,find->name))
 
5186
          !my_strcasecmp(system_charset_info,item->name,find->name))
2620
5187
      {
2621
5188
        found= li.ref();
2622
5189
        *counter= i;
2631
5198
        break;
2632
5199
      }
2633
5200
    }
 
5201
    else if (table_name && item->type() == Item::REF_ITEM &&
 
5202
             ((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF)
 
5203
    {
 
5204
      /*
 
5205
        TODO:Here we process prefixed view references only. What we should 
 
5206
        really do is process all types of Item_refs. But this will currently 
 
5207
        lead to a clash with the way references to outer SELECTs (from the 
 
5208
        HAVING clause) are handled in e.g. :
 
5209
        SELECT 1 FROM t1 AS t1_o GROUP BY a
 
5210
          HAVING (SELECT t1_o.a FROM t1 AS t1_i GROUP BY t1_i.a LIMIT 1).
 
5211
        Processing all Item_refs here will cause t1_o.a to resolve to itself.
 
5212
        We still need to process the special case of Item_direct_view_ref 
 
5213
        because in the context of views they have the same meaning as 
 
5214
        Item_field for tables.
 
5215
      */
 
5216
      Item_ident *item_ref= (Item_ident *) item;
 
5217
      if (item_ref->name && item_ref->table_name &&
 
5218
          !my_strcasecmp(system_charset_info, item_ref->name, field_name) &&
 
5219
          !my_strcasecmp(table_alias_charset, item_ref->table_name,
 
5220
                         table_name) &&
 
5221
          (!db_name || (item_ref->db_name && 
 
5222
                        !strcmp (item_ref->db_name, db_name))))
 
5223
      {
 
5224
        found= li.ref();
 
5225
        *counter= i;
 
5226
        *resolution= RESOLVED_IGNORING_ALIAS;
 
5227
        break;
 
5228
      }
 
5229
    }
2634
5230
  }
2635
5231
  if (!found)
2636
5232
  {
2638
5234
    {
2639
5235
      if (report_error != IGNORE_ERRORS)
2640
5236
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2641
 
                 find->full_name(), session->where);
 
5237
                 find->full_name(), current_thd->where);
2642
5238
      return (Item **) 0;
2643
5239
    }
2644
5240
    if (found_unaliased)
2654
5250
  {
2655
5251
    if (report_error == REPORT_ALL_ERRORS)
2656
5252
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2657
 
               find->full_name(), session->where);
 
5253
               find->full_name(), current_thd->where);
2658
5254
    return (Item **) 0;
2659
5255
  }
2660
5256
  else
2666
5262
  Test if a string is a member of a list of strings.
2667
5263
 
2668
5264
  SYNOPSIS
2669
 
  test_if_string_in_list()
2670
 
  find      the string to look for
2671
 
  str_list  a list of strings to be searched
 
5265
    test_if_string_in_list()
 
5266
    find      the string to look for
 
5267
    str_list  a list of strings to be searched
2672
5268
 
2673
5269
  DESCRIPTION
2674
 
  Sequentially search a list of strings for a string, and test whether
2675
 
  the list contains the same string.
 
5270
    Sequentially search a list of strings for a string, and test whether
 
5271
    the list contains the same string.
2676
5272
 
2677
5273
  RETURN
2678
 
  true  if find is in str_list
2679
 
  false otherwise
 
5274
    TRUE  if find is in str_list
 
5275
    FALSE otherwise
2680
5276
*/
2681
5277
 
2682
5278
static bool
2690
5286
    if (find_length != curr_str->length())
2691
5287
      continue;
2692
5288
    if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
2693
 
      return true;
 
5289
      return TRUE;
2694
5290
  }
2695
 
  return false;
 
5291
  return FALSE;
2696
5292
}
2697
5293
 
2698
5294
 
2701
5297
  being resolved in a specific table reference.
2702
5298
 
2703
5299
  SYNOPSIS
2704
 
  set_new_item_local_context()
2705
 
  session        pointer to current thread
2706
 
  item       item for which new context is created and set
2707
 
  table_ref  table ref where an item showld be resolved
 
5300
    set_new_item_local_context()
 
5301
    thd        pointer to current thread
 
5302
    item       item for which new context is created and set
 
5303
    table_ref  table ref where an item showld be resolved
2708
5304
 
2709
5305
  DESCRIPTION
2710
 
  Create a new name resolution context for an item, so that the item
2711
 
  is resolved only the supplied 'table_ref'.
 
5306
    Create a new name resolution context for an item, so that the item
 
5307
    is resolved only the supplied 'table_ref'.
2712
5308
 
2713
5309
  RETURN
2714
 
  false  if all OK
2715
 
  true   otherwise
 
5310
    FALSE  if all OK
 
5311
    TRUE   otherwise
2716
5312
*/
2717
5313
 
2718
5314
static bool
2719
 
set_new_item_local_context(Session *session, Item_ident *item, TableList *table_ref)
 
5315
set_new_item_local_context(THD *thd, Item_ident *item, TABLE_LIST *table_ref)
2720
5316
{
2721
5317
  Name_resolution_context *context;
2722
 
  if (!(context= new (session->mem_root) Name_resolution_context))
2723
 
    return true;
 
5318
  if (!(context= new (thd->mem_root) Name_resolution_context))
 
5319
    return TRUE;
2724
5320
  context->init();
2725
5321
  context->first_name_resolution_table=
2726
5322
    context->last_name_resolution_table= table_ref;
2727
5323
  item->context= context;
2728
 
  return false;
 
5324
  return FALSE;
2729
5325
}
2730
5326
 
2731
5327
 
2733
5329
  Find and mark the common columns of two table references.
2734
5330
 
2735
5331
  SYNOPSIS
2736
 
  mark_common_columns()
2737
 
  session                [in] current thread
2738
 
  table_ref_1        [in] the first (left) join operand
2739
 
  table_ref_2        [in] the second (right) join operand
2740
 
  using_fields       [in] if the join is JOIN...USING - the join columns,
2741
 
  if NATURAL join, then NULL
2742
 
  found_using_fields [out] number of fields from the USING clause that were
2743
 
  found among the common fields
 
5332
    mark_common_columns()
 
5333
    thd                [in] current thread
 
5334
    table_ref_1        [in] the first (left) join operand
 
5335
    table_ref_2        [in] the second (right) join operand
 
5336
    using_fields       [in] if the join is JOIN...USING - the join columns,
 
5337
                            if NATURAL join, then NULL
 
5338
    found_using_fields [out] number of fields from the USING clause that were
 
5339
                             found among the common fields
2744
5340
 
2745
5341
  DESCRIPTION
2746
 
  The procedure finds the common columns of two relations (either
2747
 
  tables or intermediate join results), and adds an equi-join condition
2748
 
  to the ON clause of 'table_ref_2' for each pair of matching columns.
2749
 
  If some of table_ref_XXX represents a base table or view, then we
2750
 
  create new 'Natural_join_column' instances for each column
2751
 
  reference and store them in the 'join_columns' of the table
2752
 
  reference.
 
5342
    The procedure finds the common columns of two relations (either
 
5343
    tables or intermediate join results), and adds an equi-join condition
 
5344
    to the ON clause of 'table_ref_2' for each pair of matching columns.
 
5345
    If some of table_ref_XXX represents a base table or view, then we
 
5346
    create new 'Natural_join_column' instances for each column
 
5347
    reference and store them in the 'join_columns' of the table
 
5348
    reference.
2753
5349
 
2754
5350
  IMPLEMENTATION
2755
 
  The procedure assumes that store_natural_using_join_columns() was
2756
 
  called for the previous level of NATURAL/USING joins.
 
5351
    The procedure assumes that store_natural_using_join_columns() was
 
5352
    called for the previous level of NATURAL/USING joins.
2757
5353
 
2758
5354
  RETURN
2759
 
  true   error when some common column is non-unique, or out of memory
2760
 
  false  OK
 
5355
    TRUE   error when some common column is non-unique, or out of memory
 
5356
    FALSE  OK
2761
5357
*/
2762
5358
 
2763
5359
static bool
2764
 
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
2765
 
                    List<String> *using_fields, uint32_t *found_using_fields)
 
5360
mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2,
 
5361
                    List<String> *using_fields, uint *found_using_fields)
2766
5362
{
2767
5363
  Field_iterator_table_ref it_1, it_2;
2768
5364
  Natural_join_column *nj_col_1, *nj_col_2;
2769
 
  bool result= true;
2770
 
  bool first_outer_loop= true;
 
5365
  bool result= TRUE;
 
5366
  bool first_outer_loop= TRUE;
2771
5367
  /*
2772
5368
    Leaf table references to which new natural join columns are added
2773
5369
    if the leaves are != NULL.
2774
5370
  */
2775
 
  TableList *leaf_1= (table_ref_1->getNestedJoin() &&
2776
 
                      ! table_ref_1->is_natural_join) ?
2777
 
    NULL : table_ref_1;
2778
 
  TableList *leaf_2= (table_ref_2->getNestedJoin() &&
2779
 
                      ! table_ref_2->is_natural_join) ?
2780
 
    NULL : table_ref_2;
 
5371
  TABLE_LIST *leaf_1= (table_ref_1->nested_join &&
 
5372
                       !table_ref_1->is_natural_join) ?
 
5373
                      NULL : table_ref_1;
 
5374
  TABLE_LIST *leaf_2= (table_ref_2->nested_join &&
 
5375
                       !table_ref_2->is_natural_join) ?
 
5376
                      NULL : table_ref_2;
 
5377
 
 
5378
  DBUG_ENTER("mark_common_columns");
 
5379
  DBUG_PRINT("info", ("operand_1: %s  operand_2: %s",
 
5380
                      table_ref_1->alias, table_ref_2->alias));
2781
5381
 
2782
5382
  *found_using_fields= 0;
2783
5383
 
2784
5384
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
2785
5385
  {
2786
 
    bool found= false;
 
5386
    bool found= FALSE;
2787
5387
    const char *field_name_1;
2788
5388
    /* true if field_name_1 is a member of using_fields */
2789
5389
    bool is_using_column_1;
2790
5390
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
5391
      goto err;
2792
5392
    field_name_1= nj_col_1->name();
2793
 
    is_using_column_1= using_fields &&
 
5393
    is_using_column_1= using_fields && 
2794
5394
      test_if_string_in_list(field_name_1, using_fields);
 
5395
    DBUG_PRINT ("info", ("field_name_1=%s.%s", 
 
5396
                         nj_col_1->table_name() ? nj_col_1->table_name() : "", 
 
5397
                         field_name_1));
2795
5398
 
2796
5399
    /*
2797
5400
      Find a field with the same name in table_ref_2.
2806
5409
      Natural_join_column *cur_nj_col_2;
2807
5410
      const char *cur_field_name_2;
2808
5411
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
5412
        goto err;
2810
5413
      cur_field_name_2= cur_nj_col_2->name();
 
5414
      DBUG_PRINT ("info", ("cur_field_name_2=%s.%s", 
 
5415
                           cur_nj_col_2->table_name() ? 
 
5416
                             cur_nj_col_2->table_name() : "", 
 
5417
                           cur_field_name_2));
2811
5418
 
2812
5419
      /*
2813
5420
        Compare the two columns and check for duplicate common fields.
2814
5421
        A common field is duplicate either if it was already found in
2815
 
        table_ref_2 (then found == true), or if a field in table_ref_2
 
5422
        table_ref_2 (then found == TRUE), or if a field in table_ref_2
2816
5423
        was already matched by some previous field in table_ref_1
2817
 
        (then cur_nj_col_2->is_common == true).
 
5424
        (then cur_nj_col_2->is_common == TRUE).
2818
5425
        Note that it is too early to check the columns outside of the
2819
5426
        USING list for ambiguity because they are not actually "referenced"
2820
 
        here. These columns must be checked only on unqualified reference
 
5427
        here. These columns must be checked only on unqualified reference 
2821
5428
        by name (e.g. in SELECT list).
2822
5429
      */
2823
5430
      if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
2824
5431
      {
 
5432
        DBUG_PRINT ("info", ("match c1.is_common=%d", nj_col_1->is_common));
2825
5433
        if (cur_nj_col_2->is_common ||
2826
5434
            (found && (!using_fields || is_using_column_1)))
2827
5435
        {
2828
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
5436
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where);
 
5437
          goto err;
2830
5438
        }
2831
5439
        nj_col_2= cur_nj_col_2;
2832
 
        found= true;
 
5440
        found= TRUE;
2833
5441
      }
2834
5442
    }
2835
5443
    if (first_outer_loop && leaf_2)
2838
5446
        Make sure that the next inner loop "knows" that all columns
2839
5447
        are materialized already.
2840
5448
      */
2841
 
      leaf_2->is_join_columns_complete= true;
2842
 
      first_outer_loop= false;
 
5449
      leaf_2->is_join_columns_complete= TRUE;
 
5450
      first_outer_loop= FALSE;
2843
5451
    }
2844
5452
    if (!found)
2845
5453
      continue;                                 // No matching field
2851
5459
    */
2852
5460
    if (nj_col_2 && (!using_fields ||is_using_column_1))
2853
5461
    {
2854
 
      Item *item_1=   nj_col_1->create_item(session);
2855
 
      Item *item_2=   nj_col_2->create_item(session);
 
5462
      Item *item_1=   nj_col_1->create_item(thd);
 
5463
      Item *item_2=   nj_col_2->create_item(thd);
2856
5464
      Field *field_1= nj_col_1->field();
2857
5465
      Field *field_2= nj_col_2->field();
2858
5466
      Item_ident *item_ident_1, *item_ident_2;
2859
5467
      Item_func_eq *eq_cond;
2860
5468
 
2861
5469
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
5470
        goto err;                               // out of memory
2863
5471
 
2864
5472
      /*
 
5473
        The following assert checks that the two created items are of
 
5474
        type Item_ident.
 
5475
      */
 
5476
      DBUG_ASSERT(!thd->lex->current_select->no_wrap_view_item);
 
5477
      /*
2865
5478
        In the case of no_wrap_view_item == 0, the created items must be
2866
5479
        of sub-classes of Item_ident.
2867
5480
      */
2868
 
      assert(item_1->type() == Item::FIELD_ITEM ||
2869
 
             item_1->type() == Item::REF_ITEM);
2870
 
      assert(item_2->type() == Item::FIELD_ITEM ||
2871
 
             item_2->type() == Item::REF_ITEM);
 
5481
      DBUG_ASSERT(item_1->type() == Item::FIELD_ITEM ||
 
5482
                  item_1->type() == Item::REF_ITEM);
 
5483
      DBUG_ASSERT(item_2->type() == Item::FIELD_ITEM ||
 
5484
                  item_2->type() == Item::REF_ITEM);
2872
5485
 
2873
5486
      /*
2874
5487
        We need to cast item_1,2 to Item_ident, because we need to hook name
2882
5495
        resolution of these items, and to enable proper name resolution of
2883
5496
        the items during the execute phase of PS.
2884
5497
      */
2885
 
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
 
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
5498
      if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) ||
 
5499
          set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref))
 
5500
        goto err;
2888
5501
 
2889
5502
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
5503
        goto err;                               /* Out of memory. */
2891
5504
 
2892
5505
      /*
2893
5506
        Add the new equi-join condition to the ON clause. Notice that
2894
5507
        fix_fields() is applied to all ON conditions in setup_conds()
2895
5508
        so we don't do it here.
2896
 
      */
 
5509
       */
2897
5510
      add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
2898
5511
                   table_ref_1 : table_ref_2),
2899
5512
                  eq_cond);
2900
5513
 
2901
 
      nj_col_1->is_common= nj_col_2->is_common= true;
 
5514
      nj_col_1->is_common= nj_col_2->is_common= TRUE;
 
5515
      DBUG_PRINT ("info", ("%s.%s and %s.%s are common", 
 
5516
                           nj_col_1->table_name() ? 
 
5517
                             nj_col_1->table_name() : "", 
 
5518
                           nj_col_1->name(),
 
5519
                           nj_col_2->table_name() ? 
 
5520
                             nj_col_2->table_name() : "", 
 
5521
                           nj_col_2->name()));
2902
5522
 
2903
5523
      if (field_1)
2904
5524
      {
2905
 
        Table *table_1= nj_col_1->table_ref->table;
 
5525
        TABLE *table_1= nj_col_1->table_ref->table;
2906
5526
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
2908
 
        table_1->covering_keys&= field_1->part_of_key;
2909
 
        table_1->merge_keys|= field_1->part_of_key;
 
5527
        bitmap_set_bit(table_1->read_set, field_1->field_index);
 
5528
        table_1->covering_keys.intersect(field_1->part_of_key);
 
5529
        table_1->merge_keys.merge(field_1->part_of_key);
2910
5530
      }
2911
5531
      if (field_2)
2912
5532
      {
2913
 
        Table *table_2= nj_col_2->table_ref->table;
 
5533
        TABLE *table_2= nj_col_2->table_ref->table;
2914
5534
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
2916
 
        table_2->covering_keys&= field_2->part_of_key;
2917
 
        table_2->merge_keys|= field_2->part_of_key;
 
5535
        bitmap_set_bit(table_2->read_set, field_2->field_index);
 
5536
        table_2->covering_keys.intersect(field_2->part_of_key);
 
5537
        table_2->merge_keys.merge(field_2->part_of_key);
2918
5538
      }
2919
5539
 
2920
5540
      if (using_fields != NULL)
2922
5542
    }
2923
5543
  }
2924
5544
  if (leaf_1)
2925
 
    leaf_1->is_join_columns_complete= true;
 
5545
    leaf_1->is_join_columns_complete= TRUE;
2926
5546
 
2927
5547
  /*
2928
5548
    Everything is OK.
2931
5551
    we check for this error in store_natural_using_join_columns() when
2932
5552
    (found_using_fields < length(join_using_fields)).
2933
5553
  */
2934
 
  result= false;
 
5554
  result= FALSE;
2935
5555
 
2936
 
  return(result);
 
5556
err:
 
5557
  DBUG_RETURN(result);
2937
5558
}
2938
5559
 
2939
5560
 
2942
5563
  Materialize and store the row type of NATURAL/USING join.
2943
5564
 
2944
5565
  SYNOPSIS
2945
 
  store_natural_using_join_columns()
2946
 
  session                current thread
2947
 
  natural_using_join the table reference of the NATURAL/USING join
2948
 
  table_ref_1        the first (left) operand (of a NATURAL/USING join).
2949
 
  table_ref_2        the second (right) operand (of a NATURAL/USING join).
2950
 
  using_fields       if the join is JOIN...USING - the join columns,
2951
 
  if NATURAL join, then NULL
2952
 
  found_using_fields number of fields from the USING clause that were
2953
 
  found among the common fields
 
5566
    store_natural_using_join_columns()
 
5567
    thd                current thread
 
5568
    natural_using_join the table reference of the NATURAL/USING join
 
5569
    table_ref_1        the first (left) operand (of a NATURAL/USING join).
 
5570
    table_ref_2        the second (right) operand (of a NATURAL/USING join).
 
5571
    using_fields       if the join is JOIN...USING - the join columns,
 
5572
                       if NATURAL join, then NULL
 
5573
    found_using_fields number of fields from the USING clause that were
 
5574
                       found among the common fields
2954
5575
 
2955
5576
  DESCRIPTION
2956
 
  Iterate over the columns of both join operands and sort and store
2957
 
  all columns into the 'join_columns' list of natural_using_join
2958
 
  where the list is formed by three parts:
2959
 
part1: The coalesced columns of table_ref_1 and table_ref_2,
2960
 
sorted according to the column order of the first table.
2961
 
part2: The other columns of the first table, in the order in
2962
 
which they were defined in CREATE TABLE.
2963
 
part3: The other columns of the second table, in the order in
2964
 
which they were defined in CREATE TABLE.
2965
 
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
2966
 
 
2967
 
IMPLEMENTATION
2968
 
The procedure assumes that mark_common_columns() has been called
2969
 
for the join that is being processed.
2970
 
 
2971
 
RETURN
2972
 
true    error: Some common column is ambiguous
2973
 
false   OK
 
5577
    Iterate over the columns of both join operands and sort and store
 
5578
    all columns into the 'join_columns' list of natural_using_join
 
5579
    where the list is formed by three parts:
 
5580
      part1: The coalesced columns of table_ref_1 and table_ref_2,
 
5581
             sorted according to the column order of the first table.
 
5582
      part2: The other columns of the first table, in the order in
 
5583
             which they were defined in CREATE TABLE.
 
5584
      part3: The other columns of the second table, in the order in
 
5585
             which they were defined in CREATE TABLE.
 
5586
    Time complexity - O(N1+N2), where Ni = length(table_ref_i).
 
5587
 
 
5588
  IMPLEMENTATION
 
5589
    The procedure assumes that mark_common_columns() has been called
 
5590
    for the join that is being processed.
 
5591
 
 
5592
  RETURN
 
5593
    TRUE    error: Some common column is ambiguous
 
5594
    FALSE   OK
2974
5595
*/
2975
5596
 
2976
5597
static bool
2977
 
store_natural_using_join_columns(Session *session,
2978
 
                                 TableList *natural_using_join,
2979
 
                                 TableList *table_ref_1,
2980
 
                                 TableList *table_ref_2,
 
5598
store_natural_using_join_columns(THD *thd, TABLE_LIST *natural_using_join,
 
5599
                                 TABLE_LIST *table_ref_1,
 
5600
                                 TABLE_LIST *table_ref_2,
2981
5601
                                 List<String> *using_fields,
2982
 
                                 uint32_t found_using_fields)
 
5602
                                 uint found_using_fields)
2983
5603
{
2984
5604
  Field_iterator_table_ref it_1, it_2;
2985
5605
  Natural_join_column *nj_col_1, *nj_col_2;
2986
 
  bool result= true;
 
5606
  bool result= TRUE;
2987
5607
  List<Natural_join_column> *non_join_columns;
 
5608
  DBUG_ENTER("store_natural_using_join_columns");
2988
5609
 
2989
 
  assert(!natural_using_join->join_columns);
 
5610
  DBUG_ASSERT(!natural_using_join->join_columns);
2990
5611
 
2991
5612
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
5613
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
5614
    goto err;
2996
5615
 
2997
5616
  /* Append the columns of the first join operand. */
2998
5617
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3002
5621
    {
3003
5622
      natural_using_join->join_columns->push_back(nj_col_1);
3004
5623
      /* Reset the common columns for the next call to mark_common_columns. */
3005
 
      nj_col_1->is_common= false;
 
5624
      nj_col_1->is_common= FALSE;
3006
5625
    }
3007
5626
    else
3008
5627
      non_join_columns->push_back(nj_col_1);
3030
5649
        if (!(common_field= it++))
3031
5650
        {
3032
5651
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
 
                   session->where);
3034
 
          return(result);
 
5652
                   current_thd->where);
 
5653
          goto err;
3035
5654
        }
3036
5655
        if (!my_strcasecmp(system_charset_info,
3037
5656
                           common_field->name(), using_field_name_ptr))
3049
5668
    else
3050
5669
    {
3051
5670
      /* Reset the common columns for the next call to mark_common_columns. */
3052
 
      nj_col_2->is_common= false;
 
5671
      nj_col_2->is_common= FALSE;
3053
5672
    }
3054
5673
  }
3055
5674
 
3056
5675
  if (non_join_columns->elements > 0)
3057
5676
    natural_using_join->join_columns->concat(non_join_columns);
3058
 
  natural_using_join->is_join_columns_complete= true;
3059
 
 
3060
 
  result= false;
3061
 
 
3062
 
  return(result);
 
5677
  natural_using_join->is_join_columns_complete= TRUE;
 
5678
 
 
5679
  result= FALSE;
 
5680
 
 
5681
err:
 
5682
  DBUG_RETURN(result);
3063
5683
}
3064
5684
 
3065
5685
 
3067
5687
  Precompute and store the row types of the top-most NATURAL/USING joins.
3068
5688
 
3069
5689
  SYNOPSIS
3070
 
  store_top_level_join_columns()
3071
 
  session            current thread
3072
 
  table_ref      nested join or table in a FROM clause
3073
 
  left_neighbor  neighbor table reference to the left of table_ref at the
3074
 
  same level in the join tree
3075
 
  right_neighbor neighbor table reference to the right of table_ref at the
3076
 
  same level in the join tree
 
5690
    store_top_level_join_columns()
 
5691
    thd            current thread
 
5692
    table_ref      nested join or table in a FROM clause
 
5693
    left_neighbor  neighbor table reference to the left of table_ref at the
 
5694
                   same level in the join tree
 
5695
    right_neighbor neighbor table reference to the right of table_ref at the
 
5696
                   same level in the join tree
3077
5697
 
3078
5698
  DESCRIPTION
3079
 
  The procedure performs a post-order traversal of a nested join tree
3080
 
  and materializes the row types of NATURAL/USING joins in a
3081
 
  bottom-up manner until it reaches the TableList elements that
3082
 
  represent the top-most NATURAL/USING joins. The procedure should be
3083
 
  applied to each element of Select_Lex::top_join_list (i.e. to each
3084
 
  top-level element of the FROM clause).
 
5699
    The procedure performs a post-order traversal of a nested join tree
 
5700
    and materializes the row types of NATURAL/USING joins in a
 
5701
    bottom-up manner until it reaches the TABLE_LIST elements that
 
5702
    represent the top-most NATURAL/USING joins. The procedure should be
 
5703
    applied to each element of SELECT_LEX::top_join_list (i.e. to each
 
5704
    top-level element of the FROM clause).
3085
5705
 
3086
5706
  IMPLEMENTATION
3087
 
  Notice that the table references in the list nested_join->join_list
3088
 
  are in reverse order, thus when we iterate over it, we are moving
3089
 
  from the right to the left in the FROM clause.
 
5707
    Notice that the table references in the list nested_join->join_list
 
5708
    are in reverse order, thus when we iterate over it, we are moving
 
5709
    from the right to the left in the FROM clause.
3090
5710
 
3091
5711
  RETURN
3092
 
  true   Error
3093
 
  false  OK
 
5712
    TRUE   Error
 
5713
    FALSE  OK
3094
5714
*/
3095
5715
 
3096
5716
static bool
3097
 
store_top_level_join_columns(Session *session, TableList *table_ref,
3098
 
                             TableList *left_neighbor,
3099
 
                             TableList *right_neighbor)
 
5717
store_top_level_join_columns(THD *thd, TABLE_LIST *table_ref,
 
5718
                             TABLE_LIST *left_neighbor,
 
5719
                             TABLE_LIST *right_neighbor)
3100
5720
{
3101
 
  bool result= true;
 
5721
  bool result= TRUE;
 
5722
 
 
5723
  DBUG_ENTER("store_top_level_join_columns");
3102
5724
 
3103
5725
  /* Call the procedure recursively for each nested table reference. */
3104
 
  if (table_ref->getNestedJoin())
 
5726
  if (table_ref->nested_join)
3105
5727
  {
3106
 
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
3107
 
    TableList *same_level_left_neighbor= nested_it++;
3108
 
    TableList *same_level_right_neighbor= NULL;
 
5728
    List_iterator_fast<TABLE_LIST> nested_it(table_ref->nested_join->join_list);
 
5729
    TABLE_LIST *same_level_left_neighbor= nested_it++;
 
5730
    TABLE_LIST *same_level_right_neighbor= NULL;
3109
5731
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3110
 
    TableList *real_left_neighbor, *real_right_neighbor;
 
5732
    TABLE_LIST *real_left_neighbor, *real_right_neighbor;
3111
5733
 
3112
5734
    while (same_level_left_neighbor)
3113
5735
    {
3114
 
      TableList *cur_table_ref= same_level_left_neighbor;
 
5736
      TABLE_LIST *cur_table_ref= same_level_left_neighbor;
3115
5737
      same_level_left_neighbor= nested_it++;
3116
5738
      /*
3117
5739
        The order of RIGHT JOIN operands is reversed in 'join list' to
3128
5750
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3129
5751
      {
3130
5752
        /* This can happen only for JOIN ... ON. */
3131
 
        assert(table_ref->getNestedJoin()->join_list.elements == 2);
3132
 
        std::swap(same_level_left_neighbor, cur_table_ref);
 
5753
        DBUG_ASSERT(table_ref->nested_join->join_list.elements == 2);
 
5754
        swap_variables(TABLE_LIST*, same_level_left_neighbor, cur_table_ref);
3133
5755
      }
3134
5756
 
3135
5757
      /*
3137
5759
        neighbors at the same level.
3138
5760
      */
3139
5761
      real_left_neighbor=  (same_level_left_neighbor) ?
3140
 
        same_level_left_neighbor : left_neighbor;
 
5762
                           same_level_left_neighbor : left_neighbor;
3141
5763
      real_right_neighbor= (same_level_right_neighbor) ?
3142
 
        same_level_right_neighbor : right_neighbor;
 
5764
                           same_level_right_neighbor : right_neighbor;
3143
5765
 
3144
 
      if (cur_table_ref->getNestedJoin() &&
3145
 
          store_top_level_join_columns(session, cur_table_ref,
 
5766
      if (cur_table_ref->nested_join &&
 
5767
          store_top_level_join_columns(thd, cur_table_ref,
3146
5768
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
5769
        goto err;
3148
5770
      same_level_right_neighbor= cur_table_ref;
3149
5771
    }
3150
5772
  }
3155
5777
  */
3156
5778
  if (table_ref->is_natural_join)
3157
5779
  {
3158
 
    assert(table_ref->getNestedJoin() &&
3159
 
           table_ref->getNestedJoin()->join_list.elements == 2);
3160
 
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
 
5780
    DBUG_ASSERT(table_ref->nested_join &&
 
5781
                table_ref->nested_join->join_list.elements == 2);
 
5782
    List_iterator_fast<TABLE_LIST> operand_it(table_ref->nested_join->join_list);
3161
5783
    /*
3162
5784
      Notice that the order of join operands depends on whether table_ref
3163
5785
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3164
5786
      in inverted order.
3165
 
    */
3166
 
    TableList *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
3167
 
    TableList *table_ref_1= operand_it++; /* First NATURAL join operand. */
 
5787
     */
 
5788
    TABLE_LIST *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
 
5789
    TABLE_LIST *table_ref_1= operand_it++; /* First NATURAL join operand. */
3168
5790
    List<String> *using_fields= table_ref->join_using_fields;
3169
 
    uint32_t found_using_fields;
 
5791
    uint found_using_fields;
3170
5792
 
3171
5793
    /*
3172
5794
      The two join operands were interchanged in the parser, change the order
3173
5795
      back for 'mark_common_columns'.
3174
5796
    */
3175
5797
    if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
3176
 
      std::swap(table_ref_1, table_ref_2);
3177
 
    if (mark_common_columns(session, table_ref_1, table_ref_2,
 
5798
      swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
 
5799
    if (mark_common_columns(thd, table_ref_1, table_ref_2,
3178
5800
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
5801
      goto err;
3180
5802
 
3181
5803
    /*
3182
5804
      Swap the join operands back, so that we pick the columns of the second
3184
5806
      same as of an equivalent LEFT JOIN.
3185
5807
    */
3186
5808
    if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
3187
 
      std::swap(table_ref_1, table_ref_2);
3188
 
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
 
5809
      swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
 
5810
    if (store_natural_using_join_columns(thd, table_ref, table_ref_1,
3189
5811
                                         table_ref_2, using_fields,
3190
5812
                                         found_using_fields))
3191
 
      return(result);
 
5813
      goto err;
3192
5814
 
3193
5815
    /*
3194
5816
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3198
5820
    */
3199
5821
    table_ref_1->natural_join= table_ref_2->natural_join= NULL;
3200
5822
 
3201
 
    /* Add a true condition to outer joins that have no common columns. */
 
5823
    /* Add a TRUE condition to outer joins that have no common columns. */
3202
5824
    if (table_ref_2->outer_join &&
3203
5825
        !table_ref_1->on_expr && !table_ref_2->on_expr)
3204
 
      table_ref_2->on_expr= new Item_int((int64_t) 1,1);   /* Always true. */
 
5826
      table_ref_2->on_expr= new Item_int((longlong) 1,1);   /* Always true. */
3205
5827
 
3206
5828
    /* Change this table reference to become a leaf for name resolution. */
3207
5829
    if (left_neighbor)
3208
5830
    {
3209
 
      TableList *last_leaf_on_the_left;
 
5831
      TABLE_LIST *last_leaf_on_the_left;
3210
5832
      last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
3211
5833
      last_leaf_on_the_left->next_name_resolution_table= table_ref;
3212
5834
    }
3213
5835
    if (right_neighbor)
3214
5836
    {
3215
 
      TableList *first_leaf_on_the_right;
 
5837
      TABLE_LIST *first_leaf_on_the_right;
3216
5838
      first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
3217
5839
      table_ref->next_name_resolution_table= first_leaf_on_the_right;
3218
5840
    }
3219
5841
    else
3220
5842
      table_ref->next_name_resolution_table= NULL;
3221
5843
  }
3222
 
  result= false; /* All is OK. */
 
5844
  result= FALSE; /* All is OK. */
3223
5845
 
3224
 
  return(result);
 
5846
err:
 
5847
  DBUG_RETURN(result);
3225
5848
}
3226
5849
 
3227
5850
 
3230
5853
  in a FROM clause.
3231
5854
 
3232
5855
  SYNOPSIS
3233
 
  setup_natural_join_row_types()
3234
 
  session          current thread
3235
 
  from_clause  list of top-level table references in a FROM clause
 
5856
    setup_natural_join_row_types()
 
5857
    thd          current thread
 
5858
    from_clause  list of top-level table references in a FROM clause
3236
5859
 
3237
5860
  DESCRIPTION
3238
 
  Apply the procedure 'store_top_level_join_columns' to each of the
3239
 
  top-level table referencs of the FROM clause. Adjust the list of tables
3240
 
  for name resolution - context->first_name_resolution_table to the
3241
 
  top-most, lef-most NATURAL/USING join.
 
5861
    Apply the procedure 'store_top_level_join_columns' to each of the
 
5862
    top-level table referencs of the FROM clause. Adjust the list of tables
 
5863
    for name resolution - context->first_name_resolution_table to the
 
5864
    top-most, lef-most NATURAL/USING join.
3242
5865
 
3243
5866
  IMPLEMENTATION
3244
 
  Notice that the table references in 'from_clause' are in reverse
3245
 
  order, thus when we iterate over it, we are moving from the right
3246
 
  to the left in the FROM clause.
 
5867
    Notice that the table references in 'from_clause' are in reverse
 
5868
    order, thus when we iterate over it, we are moving from the right
 
5869
    to the left in the FROM clause.
3247
5870
 
3248
5871
  RETURN
3249
 
  true   Error
3250
 
  false  OK
 
5872
    TRUE   Error
 
5873
    FALSE  OK
3251
5874
*/
3252
 
static bool setup_natural_join_row_types(Session *session,
3253
 
                                         List<TableList> *from_clause,
 
5875
static bool setup_natural_join_row_types(THD *thd,
 
5876
                                         List<TABLE_LIST> *from_clause,
3254
5877
                                         Name_resolution_context *context)
3255
5878
{
3256
 
  session->where= "from clause";
 
5879
  thd->where= "from clause";
3257
5880
  if (from_clause->elements == 0)
3258
 
    return false; /* We come here in the case of UNIONs. */
 
5881
    return FALSE; /* We come here in the case of UNIONs. */
3259
5882
 
3260
 
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3261
 
  TableList *table_ref; /* Current table reference. */
 
5883
  List_iterator_fast<TABLE_LIST> table_ref_it(*from_clause);
 
5884
  TABLE_LIST *table_ref; /* Current table reference. */
3262
5885
  /* Table reference to the left of the current. */
3263
 
  TableList *left_neighbor;
 
5886
  TABLE_LIST *left_neighbor;
3264
5887
  /* Table reference to the right of the current. */
3265
 
  TableList *right_neighbor= NULL;
 
5888
  TABLE_LIST *right_neighbor= NULL;
3266
5889
 
3267
5890
  /* Note that tables in the list are in reversed order */
3268
5891
  for (left_neighbor= table_ref_it++; left_neighbor ; )
3269
5892
  {
3270
5893
    table_ref= left_neighbor;
3271
5894
    left_neighbor= table_ref_it++;
3272
 
    if (store_top_level_join_columns(session, table_ref,
3273
 
                                     left_neighbor, right_neighbor))
3274
 
      return true;
3275
 
    if (left_neighbor)
 
5895
    /* For stored procedures do not redo work if already done. */
 
5896
    if (context->select_lex->first_execution)
3276
5897
    {
3277
 
      TableList *first_leaf_on_the_right;
3278
 
      first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
3279
 
      left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
 
5898
      if (store_top_level_join_columns(thd, table_ref,
 
5899
                                       left_neighbor, right_neighbor))
 
5900
        return TRUE;
 
5901
      if (left_neighbor)
 
5902
      {
 
5903
        TABLE_LIST *first_leaf_on_the_right;
 
5904
        first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
 
5905
        left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
 
5906
      }
3280
5907
    }
3281
5908
    right_neighbor= table_ref;
3282
5909
  }
3287
5914
    right_neighbor points to the left-most top-level table reference in the
3288
5915
    FROM clause.
3289
5916
  */
3290
 
  assert(right_neighbor);
 
5917
  DBUG_ASSERT(right_neighbor);
3291
5918
  context->first_name_resolution_table=
3292
5919
    right_neighbor->first_leaf_for_name_resolution();
3293
5920
 
3294
 
  return false;
 
5921
  return FALSE;
3295
5922
}
3296
5923
 
3297
5924
 
3298
5925
/****************************************************************************
3299
 
 ** Expand all '*' in given fields
3300
 
 ****************************************************************************/
 
5926
** Expand all '*' in given fields
 
5927
****************************************************************************/
3301
5928
 
3302
 
int setup_wild(Session *session, List<Item> &fields,
3303
 
               List<Item> *sum_func_list,
3304
 
               uint32_t wild_num)
 
5929
int setup_wild(THD *thd, TABLE_LIST *tables, List<Item> &fields,
 
5930
               List<Item> *sum_func_list,
 
5931
               uint wild_num)
3305
5932
{
3306
5933
  if (!wild_num)
3307
 
    return 0;
 
5934
    return(0);
3308
5935
 
3309
5936
  Item *item;
3310
5937
  List_iterator<Item> it(fields);
 
5938
  DBUG_ENTER("setup_wild");
3311
5939
 
3312
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
5940
  thd->lex->current_select->cur_pos_in_select_list= 0;
3313
5941
  while (wild_num && (item= it++))
3314
5942
  {
3315
5943
    if (item->type() == Item::FIELD_ITEM &&
3316
5944
        ((Item_field*) item)->field_name &&
3317
 
        ((Item_field*) item)->field_name[0] == '*' &&
3318
 
        !((Item_field*) item)->field)
 
5945
        ((Item_field*) item)->field_name[0] == '*' &&
 
5946
        !((Item_field*) item)->field)
3319
5947
    {
3320
 
      uint32_t elem= fields.elements;
 
5948
      uint elem= fields.elements;
3321
5949
      bool any_privileges= ((Item_field *) item)->any_privileges;
3322
 
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
 
5950
      Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
3323
5951
      if (subsel &&
3324
5952
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3325
5953
      {
3328
5956
 
3329
5957
          Item_int do not need fix_fields() because it is basic constant.
3330
5958
        */
3331
 
        it.replace(new Item_int("Not_used", (int64_t) 1,
 
5959
        it.replace(new Item_int("Not_used", (longlong) 1,
3332
5960
                                MY_INT64_NUM_DECIMAL_DIGITS));
3333
5961
      }
3334
 
      else if (insert_fields(session, ((Item_field*) item)->context,
 
5962
      else if (insert_fields(thd, ((Item_field*) item)->context,
3335
5963
                             ((Item_field*) item)->db_name,
3336
5964
                             ((Item_field*) item)->table_name, &it,
3337
5965
                             any_privileges))
3338
5966
      {
3339
 
        return -1;
 
5967
        DBUG_RETURN(-1);
3340
5968
      }
3341
5969
      if (sum_func_list)
3342
5970
      {
3343
 
        /*
3344
 
          sum_func_list is a list that has the fields list as a tail.
3345
 
          Because of this we have to update the element count also for this
3346
 
          list after expanding the '*' entry.
3347
 
        */
3348
 
        sum_func_list->elements+= fields.elements - elem;
 
5971
        /*
 
5972
          sum_func_list is a list that has the fields list as a tail.
 
5973
          Because of this we have to update the element count also for this
 
5974
          list after expanding the '*' entry.
 
5975
        */
 
5976
        sum_func_list->elements+= fields.elements - elem;
3349
5977
      }
3350
5978
      wild_num--;
3351
5979
    }
3352
5980
    else
3353
 
      session->lex->current_select->cur_pos_in_select_list++;
 
5981
      thd->lex->current_select->cur_pos_in_select_list++;
3354
5982
  }
3355
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3356
 
 
3357
 
  return 0;
 
5983
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
5984
  DBUG_RETURN(0);
3358
5985
}
3359
5986
 
3360
5987
/****************************************************************************
3361
 
 ** Check that all given fields exists and fill struct with current data
3362
 
 ****************************************************************************/
 
5988
** Check that all given fields exists and fill struct with current data
 
5989
****************************************************************************/
3363
5990
 
3364
 
bool setup_fields(Session *session, Item **ref_pointer_array,
 
5991
bool setup_fields(THD *thd, Item **ref_pointer_array,
3365
5992
                  List<Item> &fields, enum_mark_columns mark_used_columns,
3366
5993
                  List<Item> *sum_func_list, bool allow_sum_func)
3367
5994
{
3368
5995
  register Item *item;
3369
 
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3370
 
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
5996
  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
 
5997
  nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
3371
5998
  List_iterator<Item> it(fields);
3372
5999
  bool save_is_item_list_lookup;
 
6000
  DBUG_ENTER("setup_fields");
3373
6001
 
3374
 
  session->mark_used_columns= mark_used_columns;
 
6002
  thd->mark_used_columns= mark_used_columns;
 
6003
  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
3375
6004
  if (allow_sum_func)
3376
 
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3377
 
  session->where= Session::DEFAULT_WHERE;
3378
 
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3379
 
  session->lex->current_select->is_item_list_lookup= 0;
 
6005
    thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
 
6006
  thd->where= THD::DEFAULT_WHERE;
 
6007
  save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup;
 
6008
  thd->lex->current_select->is_item_list_lookup= 0;
3380
6009
 
3381
6010
  /*
3382
6011
    To prevent fail on forward lookup we fill it with zerows,
3386
6015
    There is other way to solve problem: fill array with pointers to list,
3387
6016
    but it will be slower.
3388
6017
 
3389
 
TODO: remove it when (if) we made one list for allfields and
3390
 
ref_pointer_array
 
6018
    TODO: remove it when (if) we made one list for allfields and
 
6019
    ref_pointer_array
3391
6020
  */
3392
6021
  if (ref_pointer_array)
3393
 
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
 
6022
    bzero(ref_pointer_array, sizeof(Item *) * fields.elements);
3394
6023
 
3395
6024
  Item **ref= ref_pointer_array;
3396
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
6025
  thd->lex->current_select->cur_pos_in_select_list= 0;
3397
6026
  while ((item= it++))
3398
6027
  {
3399
 
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
 
6028
    if ((!item->fixed && item->fix_fields(thd, it.ref())) || (item= *(it.ref()))->check_cols(1))
3400
6029
    {
3401
 
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3402
 
      session->lex->allow_sum_func= save_allow_sum_func;
3403
 
      session->mark_used_columns= save_mark_used_columns;
3404
 
      return true;
 
6030
      thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
6031
      thd->lex->allow_sum_func= save_allow_sum_func;
 
6032
      thd->mark_used_columns= save_mark_used_columns;
 
6033
      DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
 
6034
      DBUG_RETURN(TRUE); /* purecov: inspected */
3405
6035
    }
3406
6036
    if (ref)
3407
6037
      *(ref++)= item;
3408
6038
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
3409
 
        sum_func_list)
3410
 
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3411
 
    session->used_tables|= item->used_tables();
3412
 
    session->lex->current_select->cur_pos_in_select_list++;
 
6039
        sum_func_list)
 
6040
      item->split_sum_func(thd, ref_pointer_array, *sum_func_list);
 
6041
    thd->used_tables|= item->used_tables();
 
6042
    thd->lex->current_select->cur_pos_in_select_list++;
3413
6043
  }
3414
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3415
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
6044
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
6045
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3416
6046
 
3417
 
  session->lex->allow_sum_func= save_allow_sum_func;
3418
 
  session->mark_used_columns= save_mark_used_columns;
3419
 
  return(test(session->is_error()));
 
6047
  thd->lex->allow_sum_func= save_allow_sum_func;
 
6048
  thd->mark_used_columns= save_mark_used_columns;
 
6049
  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
 
6050
  DBUG_RETURN(test(thd->is_error()));
3420
6051
}
3421
6052
 
3422
6053
 
3424
6055
  make list of leaves of join table tree
3425
6056
 
3426
6057
  SYNOPSIS
3427
 
  make_leaves_list()
3428
 
  list    pointer to pointer on list first element
3429
 
  tables  table list
 
6058
    make_leaves_list()
 
6059
    list    pointer to pointer on list first element
 
6060
    tables  table list
3430
6061
 
3431
6062
  RETURN pointer on pointer to next_leaf of last element
3432
6063
*/
3433
6064
 
3434
 
static TableList **make_leaves_list(TableList **list, TableList *tables)
 
6065
TABLE_LIST **make_leaves_list(TABLE_LIST **list, TABLE_LIST *tables)
3435
6066
{
3436
 
  for (TableList *table= tables; table; table= table->next_local)
 
6067
  for (TABLE_LIST *table= tables; table; table= table->next_local)
3437
6068
  {
3438
6069
    {
3439
6070
      *list= table;
3447
6078
  prepare tables
3448
6079
 
3449
6080
  SYNOPSIS
3450
 
  setup_tables()
3451
 
  session                 Thread Cursor
3452
 
  context       name resolution contest to setup table list there
3453
 
  from_clause   Top-level list of table references in the FROM clause
3454
 
  tables          Table list (select_lex->table_list)
3455
 
  leaves        List of join table leaves list (select_lex->leaf_tables)
3456
 
  refresh       It is onle refresh for subquery
3457
 
  select_insert It is SELECT ... INSERT command
 
6081
    setup_tables()
 
6082
    thd           Thread handler
 
6083
    context       name resolution contest to setup table list there
 
6084
    from_clause   Top-level list of table references in the FROM clause
 
6085
    tables        Table list (select_lex->table_list)
 
6086
    leaves        List of join table leaves list (select_lex->leaf_tables)
 
6087
    refresh       It is onle refresh for subquery
 
6088
    select_insert It is SELECT ... INSERT command
3458
6089
 
3459
6090
  NOTE
3460
 
  Check also that the 'used keys' and 'ignored keys' exists and set up the
3461
 
  table structure accordingly.
3462
 
  Create a list of leaf tables. For queries with NATURAL/USING JOINs,
3463
 
  compute the row types of the top most natural/using join table references
3464
 
  and link these into a list of table references for name resolution.
 
6091
    Check also that the 'used keys' and 'ignored keys' exists and set up the
 
6092
    table structure accordingly.
 
6093
    Create a list of leaf tables. For queries with NATURAL/USING JOINs,
 
6094
    compute the row types of the top most natural/using join table references
 
6095
    and link these into a list of table references for name resolution.
3465
6096
 
3466
 
  This has to be called for all tables that are used by items, as otherwise
3467
 
  table->map is not set and all Item_field will be regarded as const items.
 
6097
    This has to be called for all tables that are used by items, as otherwise
 
6098
    table->map is not set and all Item_field will be regarded as const items.
3468
6099
 
3469
6100
  RETURN
3470
 
  false ok;  In this case *map will includes the chosen index
3471
 
  true  error
 
6101
    FALSE ok;  In this case *map will includes the chosen index
 
6102
    TRUE  error
3472
6103
*/
3473
6104
 
3474
 
bool setup_tables(Session *session, Name_resolution_context *context,
3475
 
                  List<TableList> *from_clause, TableList *tables,
3476
 
                  TableList **leaves, bool select_insert)
 
6105
bool setup_tables(THD *thd, Name_resolution_context *context,
 
6106
                  List<TABLE_LIST> *from_clause, TABLE_LIST *tables,
 
6107
                  TABLE_LIST **leaves, bool select_insert)
3477
6108
{
3478
 
  uint32_t tablenr= 0;
 
6109
  uint tablenr= 0;
 
6110
  DBUG_ENTER("setup_tables");
3479
6111
 
3480
 
  assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
3481
 
          (context->table_list && context->first_name_resolution_table));
 
6112
  DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables || 
 
6113
               (context->table_list && context->first_name_resolution_table));
3482
6114
  /*
3483
6115
    this is used for INSERT ... SELECT.
3484
6116
    For select we setup tables except first (and its underlying tables)
3485
6117
  */
3486
 
  TableList *first_select_table= (select_insert ?  tables->next_local: NULL);
3487
 
 
 
6118
  TABLE_LIST *first_select_table= (select_insert ?
 
6119
                                   tables->next_local:
 
6120
                                   0);
3488
6121
  if (!(*leaves))
3489
6122
    make_leaves_list(leaves, tables);
3490
6123
 
3491
 
  TableList *table_list;
 
6124
  TABLE_LIST *table_list;
3492
6125
  for (table_list= *leaves;
3493
6126
       table_list;
3494
6127
       table_list= table_list->next_leaf, tablenr++)
3495
6128
  {
3496
 
    Table *table= table_list->table;
 
6129
    TABLE *table= table_list->table;
3497
6130
    table->pos_in_table_list= table_list;
3498
6131
    if (first_select_table &&
3499
6132
        table_list->top_table() == first_select_table)
3502
6135
      first_select_table= 0;
3503
6136
      tablenr= 0;
3504
6137
    }
3505
 
    table->setup_table_map(table_list, tablenr);
 
6138
    setup_table_map(table, table_list, tablenr);
3506
6139
    if (table_list->process_index_hints(table))
3507
 
      return 1;
 
6140
      DBUG_RETURN(1);
3508
6141
  }
3509
6142
  if (tablenr > MAX_TABLES)
3510
6143
  {
3511
6144
    my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
3512
 
    return 1;
 
6145
    DBUG_RETURN(1);
3513
6146
  }
3514
6147
 
3515
6148
  /* Precompute and store the row types of NATURAL/USING joins. */
3516
 
  if (setup_natural_join_row_types(session, from_clause, context))
3517
 
    return 1;
 
6149
  if (setup_natural_join_row_types(thd, from_clause, context))
 
6150
    DBUG_RETURN(1);
3518
6151
 
3519
 
  return 0;
 
6152
  DBUG_RETURN(0);
3520
6153
}
3521
6154
 
3522
6155
 
3524
6157
  prepare tables and check access for the view tables
3525
6158
 
3526
6159
  SYNOPSIS
3527
 
  setup_tables_and_check_view_access()
3528
 
  session                 Thread Cursor
3529
 
  context       name resolution contest to setup table list there
3530
 
  from_clause   Top-level list of table references in the FROM clause
3531
 
  tables          Table list (select_lex->table_list)
3532
 
  conds   Condition of current SELECT (can be changed by VIEW)
3533
 
  leaves        List of join table leaves list (select_lex->leaf_tables)
3534
 
  refresh       It is onle refresh for subquery
3535
 
  select_insert It is SELECT ... INSERT command
3536
 
  want_access   what access is needed
 
6160
    setup_tables_and_check_view_access()
 
6161
    thd           Thread handler
 
6162
    context       name resolution contest to setup table list there
 
6163
    from_clause   Top-level list of table references in the FROM clause
 
6164
    tables        Table list (select_lex->table_list)
 
6165
    conds         Condition of current SELECT (can be changed by VIEW)
 
6166
    leaves        List of join table leaves list (select_lex->leaf_tables)
 
6167
    refresh       It is onle refresh for subquery
 
6168
    select_insert It is SELECT ... INSERT command
 
6169
    want_access   what access is needed
3537
6170
 
3538
6171
  NOTE
3539
 
  a wrapper for check_tables that will also check the resulting
3540
 
  table leaves list for access to all the tables that belong to a view
 
6172
    a wrapper for check_tables that will also check the resulting
 
6173
    table leaves list for access to all the tables that belong to a view
3541
6174
 
3542
6175
  RETURN
3543
 
  false ok;  In this case *map will include the chosen index
3544
 
  true  error
 
6176
    FALSE ok;  In this case *map will include the chosen index
 
6177
    TRUE  error
3545
6178
*/
3546
 
bool setup_tables_and_check_access(Session *session,
 
6179
bool setup_tables_and_check_access(THD *thd, 
3547
6180
                                   Name_resolution_context *context,
3548
 
                                   List<TableList> *from_clause,
3549
 
                                   TableList *tables,
3550
 
                                   TableList **leaves,
 
6181
                                   List<TABLE_LIST> *from_clause,
 
6182
                                   TABLE_LIST *tables,
 
6183
                                   TABLE_LIST **leaves,
3551
6184
                                   bool select_insert)
3552
6185
{
3553
 
  TableList *leaves_tmp= NULL;
 
6186
  TABLE_LIST *leaves_tmp= NULL;
 
6187
  bool first_table= true;
3554
6188
 
3555
 
  if (setup_tables(session, context, from_clause, tables,
 
6189
  if (setup_tables(thd, context, from_clause, tables,
3556
6190
                   &leaves_tmp, select_insert))
3557
 
    return true;
 
6191
    return TRUE;
3558
6192
 
3559
6193
  if (leaves)
3560
6194
    *leaves= leaves_tmp;
3561
6195
 
3562
 
  return false;
 
6196
  for (; leaves_tmp; leaves_tmp= leaves_tmp->next_leaf)
 
6197
  {
 
6198
    if (leaves_tmp->belong_to_view)
 
6199
    {
 
6200
      return TRUE;
 
6201
    }
 
6202
    first_table= 0;
 
6203
  }
 
6204
  return FALSE;
 
6205
}
 
6206
 
 
6207
 
 
6208
/*
 
6209
   Create a key_map from a list of index names
 
6210
 
 
6211
   SYNOPSIS
 
6212
     get_key_map_from_key_list()
 
6213
     map                key_map to fill in
 
6214
     table              Table
 
6215
     index_list         List of index names
 
6216
 
 
6217
   RETURN
 
6218
     0  ok;  In this case *map will includes the choosed index
 
6219
     1  error
 
6220
*/
 
6221
 
 
6222
bool get_key_map_from_key_list(key_map *map, TABLE *table,
 
6223
                               List<String> *index_list)
 
6224
{
 
6225
  List_iterator_fast<String> it(*index_list);
 
6226
  String *name;
 
6227
  uint pos;
 
6228
 
 
6229
  map->clear_all();
 
6230
  while ((name=it++))
 
6231
  {
 
6232
    if (table->s->keynames.type_names == 0 ||
 
6233
        (pos= find_type(&table->s->keynames, name->ptr(),
 
6234
                        name->length(), 1)) <=
 
6235
        0)
 
6236
    {
 
6237
      my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name->c_ptr(),
 
6238
               table->pos_in_table_list->alias);
 
6239
      map->set_all();
 
6240
      return 1;
 
6241
    }
 
6242
    map->set_bit(pos-1);
 
6243
  }
 
6244
  return 0;
3563
6245
}
3564
6246
 
3565
6247
 
3567
6249
  Drops in all fields instead of current '*' field
3568
6250
 
3569
6251
  SYNOPSIS
3570
 
  insert_fields()
3571
 
  session                       Thread Cursor
3572
 
  context             Context for name resolution
3573
 
  db_name               Database name in case of 'database_name.table_name.*'
3574
 
  table_name            Table name in case of 'table_name.*'
3575
 
  it                    Pointer to '*'
3576
 
  any_privileges        0 If we should ensure that we have SELECT privileges
3577
 
  for all columns
3578
 
  1 If any privilege is ok
 
6252
    insert_fields()
 
6253
    thd                 Thread handler
 
6254
    context             Context for name resolution
 
6255
    db_name             Database name in case of 'database_name.table_name.*'
 
6256
    table_name          Table name in case of 'table_name.*'
 
6257
    it                  Pointer to '*'
 
6258
    any_privileges      0 If we should ensure that we have SELECT privileges
 
6259
                          for all columns
 
6260
                        1 If any privilege is ok
3579
6261
  RETURN
3580
 
  0     ok     'it' is updated to point at last inserted
3581
 
  1     error.  Error message is generated but not sent to client
 
6262
    0   ok     'it' is updated to point at last inserted
 
6263
    1   error.  Error message is generated but not sent to client
3582
6264
*/
3583
6265
 
3584
6266
bool
3585
 
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
3586
 
              const char *table_name, List_iterator<Item> *it,
3587
 
              bool )
 
6267
insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
 
6268
              const char *table_name, List_iterator<Item> *it,
 
6269
              bool any_privileges)
3588
6270
{
3589
6271
  Field_iterator_table_ref field_iterator;
3590
6272
  bool found;
3591
6273
  char name_buff[NAME_LEN+1];
 
6274
  DBUG_ENTER("insert_fields");
3592
6275
 
3593
 
  if (db_name)
 
6276
  if (db_name && lower_case_table_names)
3594
6277
  {
3595
6278
    /*
3596
6279
      convert database to lower case for comparison
3597
6280
      We can't do this in Item_field as this would change the
3598
6281
      'name' of the item which may be used in the select list
3599
6282
    */
3600
 
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
 
6283
    strmake(name_buff, db_name, sizeof(name_buff)-1);
3601
6284
    my_casedn_str(files_charset_info, name_buff);
3602
6285
    db_name= name_buff;
3603
6286
  }
3604
6287
 
3605
 
  found= false;
 
6288
  found= FALSE;
3606
6289
 
3607
6290
  /*
3608
6291
    If table names are qualified, then loop over all tables used in the query,
3609
6292
    else treat natural joins as leaves and do not iterate over their underlying
3610
6293
    tables.
3611
6294
  */
3612
 
  for (TableList *tables= (table_name ? context->table_list :
3613
 
                           context->first_name_resolution_table);
 
6295
  for (TABLE_LIST *tables= (table_name ? context->table_list :
 
6296
                            context->first_name_resolution_table);
3614
6297
       tables;
3615
6298
       tables= (table_name ? tables->next_local :
3616
6299
                tables->next_name_resolution_table)
3617
 
      )
 
6300
       )
3618
6301
  {
3619
6302
    Field *field;
3620
 
    Table *table= tables->table;
3621
 
 
3622
 
    assert(tables->is_leaf_for_name_resolution());
3623
 
 
3624
 
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
6303
    TABLE *table= tables->table;
 
6304
 
 
6305
    DBUG_ASSERT(tables->is_leaf_for_name_resolution());
 
6306
 
 
6307
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) || 
 
6308
        (db_name && strcmp(tables->db,db_name)))
3626
6309
      continue;
3627
6310
 
3628
6311
    /*
3630
6313
      views and natural joins this update is performed inside the loop below.
3631
6314
    */
3632
6315
    if (table)
3633
 
      session->used_tables|= table->map;
 
6316
      thd->used_tables|= table->map;
3634
6317
 
3635
6318
    /*
3636
6319
      Initialize a generic field iterator for the current table reference.
3644
6327
    {
3645
6328
      Item *item;
3646
6329
 
3647
 
      if (!(item= field_iterator.create_item(session)))
3648
 
        return true;
 
6330
      if (!(item= field_iterator.create_item(thd)))
 
6331
        DBUG_RETURN(TRUE);
3649
6332
 
3650
6333
      if (!found)
3651
6334
      {
3652
 
        found= true;
 
6335
        found= TRUE;
3653
6336
        it->replace(item); /* Replace '*' with the first found item. */
3654
6337
      }
3655
6338
      else
3658
6341
      if ((field= field_iterator.field()))
3659
6342
      {
3660
6343
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
6344
        bitmap_set_bit(field->table->read_set, field->field_index);
3662
6345
        if (table)
3663
6346
        {
3664
 
          table->covering_keys&= field->part_of_key;
3665
 
          table->merge_keys|= field->part_of_key;
 
6347
          table->covering_keys.intersect(field->part_of_key);
 
6348
          table->merge_keys.merge(field->part_of_key);
3666
6349
        }
3667
6350
        if (tables->is_natural_join)
3668
6351
        {
3669
 
          Table *field_table;
 
6352
          TABLE *field_table;
3670
6353
          /*
3671
6354
            In this case we are sure that the column ref will not be created
3672
6355
            because it was already created and stored with the natural join.
3673
6356
          */
3674
6357
          Natural_join_column *nj_col;
3675
6358
          if (!(nj_col= field_iterator.get_natural_column_ref()))
3676
 
            return true;
3677
 
          assert(nj_col->table_field);
 
6359
            DBUG_RETURN(TRUE);
 
6360
          DBUG_ASSERT(nj_col->table_field);
3678
6361
          field_table= nj_col->table_ref->table;
3679
6362
          if (field_table)
3680
6363
          {
3681
 
            session->used_tables|= field_table->map;
3682
 
            field_table->covering_keys&= field->part_of_key;
3683
 
            field_table->merge_keys|= field->part_of_key;
 
6364
            thd->used_tables|= field_table->map;
 
6365
            field_table->covering_keys.intersect(field->part_of_key);
 
6366
            field_table->merge_keys.merge(field->part_of_key);
3684
6367
            field_table->used_fields++;
3685
6368
          }
3686
6369
        }
3687
6370
      }
3688
6371
      else
3689
 
        session->used_tables|= item->used_tables();
3690
 
      session->lex->current_select->cur_pos_in_select_list++;
 
6372
        thd->used_tables|= item->used_tables();
 
6373
      thd->lex->current_select->cur_pos_in_select_list++;
3691
6374
    }
3692
6375
    /*
3693
6376
      In case of stored tables, all fields are considered as used,
3696
6379
      For NATURAL joins, used_tables is updated in the IF above.
3697
6380
    */
3698
6381
    if (table)
3699
 
      table->used_fields= table->getShare()->sizeFields();
 
6382
      table->used_fields= table->s->fields;
3700
6383
  }
3701
6384
  if (found)
3702
 
    return false;
 
6385
    DBUG_RETURN(FALSE);
3703
6386
 
3704
6387
  /*
3705
 
    @TODO in the case when we skipped all columns because there was a
 
6388
    TODO: in the case when we skipped all columns because there was a
3706
6389
    qualified '*', and all columns were coalesced, we have to give a more
3707
6390
    meaningful message than ER_BAD_TABLE_ERROR.
3708
6391
  */
3711
6394
  else
3712
6395
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3713
6396
 
3714
 
  return true;
 
6397
  DBUG_RETURN(TRUE);
3715
6398
}
3716
6399
 
3717
6400
 
3719
6402
  Fix all conditions and outer join expressions.
3720
6403
 
3721
6404
  SYNOPSIS
3722
 
  setup_conds()
3723
 
  session     thread Cursor
3724
 
  tables  list of tables for name resolving (select_lex->table_list)
3725
 
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
3726
 
  conds   WHERE clause
 
6405
    setup_conds()
 
6406
    thd     thread handler
 
6407
    tables  list of tables for name resolving (select_lex->table_list)
 
6408
    leaves  list of leaves of join table tree (select_lex->leaf_tables)
 
6409
    conds   WHERE clause
3727
6410
 
3728
6411
  DESCRIPTION
3729
 
  TODO
 
6412
    TODO
3730
6413
 
3731
6414
  RETURN
3732
 
  true  if some error occured (e.g. out of memory)
3733
 
  false if all is OK
 
6415
    TRUE  if some error occured (e.g. out of memory)
 
6416
    FALSE if all is OK
3734
6417
*/
3735
6418
 
3736
 
int Session::setup_conds(TableList *leaves, COND **conds)
 
6419
int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves,
 
6420
                COND **conds)
3737
6421
{
3738
 
  Session *session= this;
3739
 
  Select_Lex *select_lex= session->lex->current_select;
3740
 
  TableList *table= NULL;       // For HP compilers
3741
 
  void *save_session_marker= session->session_marker;
 
6422
  SELECT_LEX *select_lex= thd->lex->current_select;
 
6423
  TABLE_LIST *table= NULL;      // For HP compilers
 
6424
  void *save_thd_marker= thd->thd_marker;
3742
6425
  /*
3743
 
    it_is_update set to true when tables of primary Select_Lex (Select_Lex
 
6426
    it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX
3744
6427
    which belong to LEX, i.e. most up SELECT) will be updated by
3745
6428
    INSERT/UPDATE/LOAD
3746
 
    NOTE-> using this condition helps to prevent call of prepare_check_option()
 
6429
    NOTE: using this condition helps to prevent call of prepare_check_option()
3747
6430
    from subquery of VIEW, because tables of subquery belongs to VIEW
3748
6431
    (see condition before prepare_check_option() call)
3749
6432
  */
3750
6433
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
3751
6434
  select_lex->is_item_list_lookup= 0;
 
6435
  DBUG_ENTER("setup_conds");
3752
6436
 
3753
 
  session->mark_used_columns= MARK_COLUMNS_READ;
 
6437
  thd->mark_used_columns= MARK_COLUMNS_READ;
 
6438
  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
3754
6439
  select_lex->cond_count= 0;
3755
6440
  select_lex->between_count= 0;
3756
6441
  select_lex->max_equal_elems= 0;
3757
6442
 
3758
 
  session->session_marker= (void*)1;
 
6443
  thd->thd_marker= (void*)1;
3759
6444
  if (*conds)
3760
6445
  {
3761
 
    session->where="where clause";
3762
 
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3763
 
        (*conds)->check_cols(1))
 
6446
    thd->where="where clause";
 
6447
    if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) ||
 
6448
        (*conds)->check_cols(1))
3764
6449
      goto err_no_arena;
3765
6450
  }
3766
 
  session->session_marker= save_session_marker;
 
6451
  thd->thd_marker= save_thd_marker;
3767
6452
 
3768
6453
  /*
3769
6454
    Apply fix_fields() to all ON clauses at all levels of nesting,
3771
6456
  */
3772
6457
  for (table= leaves; table; table= table->next_leaf)
3773
6458
  {
3774
 
    TableList *embedded; /* The table at the current level of nesting. */
3775
 
    TableList *embedding= table; /* The parent nested table reference. */
 
6459
    TABLE_LIST *embedded; /* The table at the current level of nesting. */
 
6460
    TABLE_LIST *embedding= table; /* The parent nested table reference. */
3776
6461
    do
3777
6462
    {
3778
6463
      embedded= embedding;
3779
6464
      if (embedded->on_expr)
3780
6465
      {
3781
6466
        /* Make a join an a expression */
3782
 
        session->session_marker= (void*)embedded;
3783
 
        session->where="on clause";
3784
 
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3785
 
            embedded->on_expr->check_cols(1))
3786
 
          goto err_no_arena;
 
6467
        thd->thd_marker= (void*)embedded;
 
6468
        thd->where="on clause";
 
6469
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(thd, &embedded->on_expr)) ||
 
6470
            embedded->on_expr->check_cols(1))
 
6471
          goto err_no_arena;
3787
6472
        select_lex->cond_count++;
3788
6473
      }
3789
 
      embedding= embedded->getEmbedding();
 
6474
      embedding= embedded->embedding;
3790
6475
    }
3791
6476
    while (embedding &&
3792
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
6477
           embedding->nested_join->join_list.head() == embedded);
3793
6478
 
3794
6479
  }
3795
 
  session->session_marker= save_session_marker;
 
6480
  thd->thd_marker= save_thd_marker;
3796
6481
 
3797
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3798
 
  return(test(session->is_error()));
 
6482
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
6483
  DBUG_RETURN(test(thd->is_error()));
3799
6484
 
3800
6485
err_no_arena:
3801
6486
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
3802
 
 
3803
 
  return 1;
 
6487
  DBUG_RETURN(1);
3804
6488
}
3805
6489
 
3806
6490
 
3807
6491
/******************************************************************************
3808
 
 ** Fill a record with data (for INSERT or UPDATE)
3809
 
 ** Returns : 1 if some field has wrong type
3810
 
 ******************************************************************************/
 
6492
** Fill a record with data (for INSERT or UPDATE)
 
6493
** Returns : 1 if some field has wrong type
 
6494
******************************************************************************/
3811
6495
 
3812
6496
 
3813
6497
/*
3814
6498
  Fill fields with given items.
3815
6499
 
3816
6500
  SYNOPSIS
3817
 
  fill_record()
3818
 
  fields        Item_fields list to be filled
3819
 
  values        values to fill with
3820
 
  ignore_errors true if we should ignore errors
 
6501
    fill_record()
 
6502
    thd           thread handler
 
6503
    fields        Item_fields list to be filled
 
6504
    values        values to fill with
 
6505
    ignore_errors TRUE if we should ignore errors
3821
6506
 
3822
6507
  NOTE
3823
 
  fill_record() may set table->auto_increment_field_not_null and a
3824
 
  caller should make sure that it is reset after their last call to this
3825
 
  function.
 
6508
    fill_record() may set table->auto_increment_field_not_null and a
 
6509
    caller should make sure that it is reset after their last call to this
 
6510
    function.
3826
6511
 
3827
6512
  RETURN
3828
 
  false   OK
3829
 
  true    error occured
 
6513
    FALSE   OK
 
6514
    TRUE    error occured
3830
6515
*/
3831
6516
 
3832
6517
bool
3833
 
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
6518
fill_record(THD * thd, List<Item> &fields, List<Item> &values, bool ignore_errors)
3834
6519
{
3835
6520
  List_iterator_fast<Item> f(fields),v(values);
3836
 
  Item *value;
 
6521
  Item *value, *fld;
3837
6522
  Item_field *field;
3838
 
  Table *table;
 
6523
  TABLE *table= 0;
 
6524
  DBUG_ENTER("fill_record");
3839
6525
 
3840
6526
  /*
3841
6527
    Reset the table->auto_increment_field_not_null as it is valid for
3847
6533
      On INSERT or UPDATE fields are checked to be from the same table,
3848
6534
      thus we safely can take table from the first field.
3849
6535
    */
3850
 
    field= static_cast<Item_field *>(f++);
3851
 
    table= field->field->getTable();
3852
 
    table->auto_increment_field_not_null= false;
 
6536
    fld= (Item_field*)f++;
 
6537
    if (!(field= fld->filed_for_view_update()))
 
6538
    {
 
6539
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
6540
      goto err;
 
6541
    }
 
6542
    table= field->field->table;
 
6543
    table->auto_increment_field_not_null= FALSE;
3853
6544
    f.rewind();
3854
6545
  }
3855
 
 
3856
 
  while ((field= static_cast<Item_field *>(f++)))
 
6546
  while ((fld= f++))
3857
6547
  {
3858
 
    value= v++;
3859
 
 
 
6548
    if (!(field= fld->filed_for_view_update()))
 
6549
    {
 
6550
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
 
6551
      goto err;
 
6552
    }
 
6553
    value=v++;
3860
6554
    Field *rfield= field->field;
3861
 
    table= rfield->getTable();
3862
 
 
 
6555
    table= rfield->table;
3863
6556
    if (rfield == table->next_number_field)
3864
 
      table->auto_increment_field_not_null= true;
 
6557
      table->auto_increment_field_not_null= TRUE;
3865
6558
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
6559
    {
3867
6560
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3868
 
      if (table)
3869
 
        table->auto_increment_field_not_null= false;
3870
 
 
3871
 
      return true;
 
6561
      goto err;
3872
6562
    }
3873
6563
  }
3874
 
 
3875
 
  return session->is_error();
 
6564
  DBUG_RETURN(thd->is_error());
 
6565
err:
 
6566
  if (table)
 
6567
    table->auto_increment_field_not_null= FALSE;
 
6568
  DBUG_RETURN(TRUE);
3876
6569
}
3877
6570
 
3878
6571
 
3880
6573
  Fill field buffer with values from Field list
3881
6574
 
3882
6575
  SYNOPSIS
3883
 
  fill_record()
3884
 
  ptr           pointer on pointer to record
3885
 
  values        list of fields
3886
 
  ignore_errors true if we should ignore errors
 
6576
    fill_record()
 
6577
    thd           thread handler
 
6578
    ptr           pointer on pointer to record
 
6579
    values        list of fields
 
6580
    ignore_errors TRUE if we should ignore errors
3887
6581
 
3888
6582
  NOTE
3889
 
  fill_record() may set table->auto_increment_field_not_null and a
3890
 
  caller should make sure that it is reset after their last call to this
3891
 
  function.
 
6583
    fill_record() may set table->auto_increment_field_not_null and a
 
6584
    caller should make sure that it is reset after their last call to this
 
6585
    function.
3892
6586
 
3893
6587
  RETURN
3894
 
  false   OK
3895
 
  true    error occured
 
6588
    FALSE   OK
 
6589
    TRUE    error occured
3896
6590
*/
3897
6591
 
3898
 
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
 
6592
bool
 
6593
fill_record(THD *thd, Field **ptr, List<Item> &values, bool ignore_errors)
3899
6594
{
3900
6595
  List_iterator_fast<Item> v(values);
3901
6596
  Item *value;
3902
 
  Table *table= 0;
 
6597
  TABLE *table= 0;
 
6598
  DBUG_ENTER("fill_record");
 
6599
 
3903
6600
  Field *field;
3904
 
 
3905
6601
  /*
3906
6602
    Reset the table->auto_increment_field_not_null as it is valid for
3907
6603
    only one row.
3912
6608
      On INSERT or UPDATE fields are checked to be from the same table,
3913
6609
      thus we safely can take table from the first field.
3914
6610
    */
3915
 
    table= (*ptr)->getTable();
3916
 
    table->auto_increment_field_not_null= false;
 
6611
    table= (*ptr)->table;
 
6612
    table->auto_increment_field_not_null= FALSE;
3917
6613
  }
3918
 
  while ((field = *ptr++) && ! session->is_error())
 
6614
  while ((field = *ptr++) && ! thd->is_error())
3919
6615
  {
3920
6616
    value=v++;
3921
 
    table= field->getTable();
 
6617
    table= field->table;
3922
6618
    if (field == table->next_number_field)
3923
 
      table->auto_increment_field_not_null= true;
 
6619
      table->auto_increment_field_not_null= TRUE;
3924
6620
    if (value->save_in_field(field, 0) < 0)
 
6621
      goto err;
 
6622
  }
 
6623
  DBUG_RETURN(thd->is_error());
 
6624
 
 
6625
err:
 
6626
  if (table)
 
6627
    table->auto_increment_field_not_null= FALSE;
 
6628
  DBUG_RETURN(TRUE);
 
6629
}
 
6630
 
 
6631
 
 
6632
my_bool mysql_rm_tmp_tables(void)
 
6633
{
 
6634
  uint i, idx;
 
6635
  char  filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
 
6636
  MY_DIR *dirp;
 
6637
  FILEINFO *file;
 
6638
  TABLE_SHARE share;
 
6639
  THD *thd;
 
6640
  DBUG_ENTER("mysql_rm_tmp_tables");
 
6641
 
 
6642
  if (!(thd= new THD))
 
6643
    DBUG_RETURN(1);
 
6644
  thd->thread_stack= (char*) &thd;
 
6645
  thd->store_globals();
 
6646
 
 
6647
  for (i=0; i<=mysql_tmpdir_list.max; i++)
 
6648
  {
 
6649
    tmpdir=mysql_tmpdir_list.list[i];
 
6650
    /* See if the directory exists */
 
6651
    if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
 
6652
      continue;
 
6653
 
 
6654
    /* Remove all SQLxxx tables from directory */
 
6655
 
 
6656
    for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
3925
6657
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
 
6658
      file=dirp->dir_entry+idx;
 
6659
 
 
6660
      /* skiping . and .. */
 
6661
      if (file->name[0] == '.' && (!file->name[1] ||
 
6662
                                   (file->name[1] == '.' &&  !file->name[2])))
 
6663
        continue;
 
6664
 
 
6665
      if (!bcmp((uchar*) file->name, (uchar*) tmp_file_prefix,
 
6666
                tmp_file_prefix_length))
 
6667
      {
 
6668
        char *ext= fn_ext(file->name);
 
6669
        uint ext_len= strlen(ext);
 
6670
        uint filePath_len= my_snprintf(filePath, sizeof(filePath),
 
6671
                                       "%s%c%s", tmpdir, FN_LIBCHAR,
 
6672
                                       file->name);
 
6673
        if (!bcmp((uchar*) reg_ext, (uchar*) ext, ext_len))
 
6674
        {
 
6675
          handler *handler_file= 0;
 
6676
          /* We should cut file extention before deleting of table */
 
6677
          memcpy(filePathCopy, filePath, filePath_len - ext_len);
 
6678
          filePathCopy[filePath_len - ext_len]= 0;
 
6679
          init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
 
6680
          if (!open_table_def(thd, &share, 0) &&
 
6681
              ((handler_file= get_new_handler(&share, thd->mem_root,
 
6682
                                              share.db_type()))))
 
6683
          {
 
6684
            handler_file->ha_delete_table(filePathCopy);
 
6685
            delete handler_file;
 
6686
          }
 
6687
          free_table_share(&share);
 
6688
        }
 
6689
        /*
 
6690
          File can be already deleted by tmp_table.file->delete_table().
 
6691
          So we hide error messages which happnes during deleting of these
 
6692
          files(MYF(0)).
 
6693
        */
 
6694
        VOID(my_delete(filePath, MYF(0))); 
 
6695
      }
3930
6696
    }
 
6697
    my_dirend(dirp);
3931
6698
  }
3932
 
 
3933
 
  return(session->is_error());
3934
 
}
3935
 
 
3936
 
 
3937
 
bool drizzle_rm_tmp_tables()
3938
 
{
3939
 
  Session *session;
3940
 
 
3941
 
  assert(drizzle_tmpdir.size());
3942
 
 
3943
 
  if (!(session= new Session(plugin::Listen::getNullClient())))
3944
 
    return true;
3945
 
  session->thread_stack= (char*) &session;
3946
 
  session->storeGlobals();
3947
 
 
3948
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3949
 
 
3950
 
  delete session;
3951
 
 
3952
 
  return false;
 
6699
  delete thd;
 
6700
  my_pthread_setspecific_ptr(THR_THD,  0);
 
6701
  DBUG_RETURN(0);
3953
6702
}
3954
6703
 
3955
6704
 
3956
6705
 
3957
6706
/*****************************************************************************
3958
 
  unireg support functions
3959
 
 *****************************************************************************/
3960
 
 
3961
 
 
3962
 
 
 
6707
        unireg support functions
 
6708
*****************************************************************************/
 
6709
 
 
6710
/*
 
6711
  Invalidate any cache entries that are for some DB
 
6712
 
 
6713
  SYNOPSIS
 
6714
    remove_db_from_cache()
 
6715
    db          Database name. This will be in lower case if
 
6716
                lower_case_table_name is set
 
6717
 
 
6718
  NOTE:
 
6719
  We can't use hash_delete when looping hash_elements. We mark them first
 
6720
  and afterwards delete those marked unused.
 
6721
*/
 
6722
 
 
6723
void remove_db_from_cache(const char *db)
 
6724
{
 
6725
  for (uint idx=0 ; idx < open_cache.records ; idx++)
 
6726
  {
 
6727
    TABLE *table=(TABLE*) hash_element(&open_cache,idx);
 
6728
    if (!strcmp(table->s->db.str, db))
 
6729
    {
 
6730
      table->s->version= 0L;                    /* Free when thread is ready */
 
6731
      if (!table->in_use)
 
6732
        relink_unused(table);
 
6733
    }
 
6734
  }
 
6735
  while (unused_tables && !unused_tables->s->version)
 
6736
    VOID(hash_delete(&open_cache,(uchar*) unused_tables));
 
6737
}
 
6738
 
 
6739
 
 
6740
/*
 
6741
  free all unused tables
 
6742
 
 
6743
  NOTE
 
6744
    This is called by 'handle_manager' when one wants to periodicly flush
 
6745
    all not used tables.
 
6746
*/
 
6747
 
 
6748
void flush_tables()
 
6749
{
 
6750
  (void) pthread_mutex_lock(&LOCK_open);
 
6751
  while (unused_tables)
 
6752
    hash_delete(&open_cache,(uchar*) unused_tables);
 
6753
  (void) pthread_mutex_unlock(&LOCK_open);
 
6754
}
 
6755
 
 
6756
 
 
6757
/*
 
6758
  Mark all entries with the table as deleted to force an reopen of the table
 
6759
 
 
6760
  The table will be closed (not stored in cache) by the current thread when
 
6761
  close_thread_tables() is called.
 
6762
 
 
6763
  PREREQUISITES
 
6764
    Lock on LOCK_open()
 
6765
 
 
6766
  RETURN
 
6767
    0  This thread now have exclusive access to this table and no other thread
 
6768
       can access the table until close_thread_tables() is called.
 
6769
    1  Table is in use by another thread
 
6770
*/
 
6771
 
 
6772
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
 
6773
                             uint flags)
 
6774
{
 
6775
  char key[MAX_DBKEY_LENGTH];
 
6776
  uint key_length;
 
6777
  TABLE *table;
 
6778
  TABLE_SHARE *share;
 
6779
  bool result= 0, signalled= 0;
 
6780
  DBUG_ENTER("remove_table_from_cache");
 
6781
  DBUG_PRINT("enter", ("table: '%s'.'%s'  flags: %u", db, table_name, flags));
 
6782
 
 
6783
  key_length=(uint) (strmov(strmov(key,db)+1,table_name)-key)+1;
 
6784
  for (;;)
 
6785
  {
 
6786
    HASH_SEARCH_STATE state;
 
6787
    result= signalled= 0;
 
6788
 
 
6789
    for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
 
6790
                                    &state);
 
6791
         table;
 
6792
         table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
 
6793
                                   &state))
 
6794
    {
 
6795
      THD *in_use;
 
6796
      DBUG_PRINT("tcache", ("found table: '%s'.'%s' 0x%lx", table->s->db.str,
 
6797
                            table->s->table_name.str, (long) table));
 
6798
 
 
6799
      table->s->version=0L;             /* Free when thread is ready */
 
6800
      if (!(in_use=table->in_use))
 
6801
      {
 
6802
        DBUG_PRINT("info",("Table was not in use"));
 
6803
        relink_unused(table);
 
6804
      }
 
6805
      else if (in_use != thd)
 
6806
      {
 
6807
        DBUG_PRINT("info", ("Table was in use by other thread"));
 
6808
        /*
 
6809
          Mark that table is going to be deleted from cache. This will
 
6810
          force threads that are in mysql_lock_tables() (but not yet
 
6811
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
6812
        */
 
6813
        in_use->some_tables_deleted= 1;
 
6814
        if (table->is_name_opened())
 
6815
        {
 
6816
          DBUG_PRINT("info", ("Found another active instance of the table"));
 
6817
          result=1;
 
6818
        }
 
6819
        /* Kill delayed insert threads */
 
6820
        if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
 
6821
            ! in_use->killed)
 
6822
        {
 
6823
          in_use->killed= THD::KILL_CONNECTION;
 
6824
          pthread_mutex_lock(&in_use->mysys_var->mutex);
 
6825
          if (in_use->mysys_var->current_cond)
 
6826
          {
 
6827
            pthread_mutex_lock(in_use->mysys_var->current_mutex);
 
6828
            signalled= 1;
 
6829
            pthread_cond_broadcast(in_use->mysys_var->current_cond);
 
6830
            pthread_mutex_unlock(in_use->mysys_var->current_mutex);
 
6831
          }
 
6832
          pthread_mutex_unlock(&in_use->mysys_var->mutex);
 
6833
        }
 
6834
        /*
 
6835
          Now we must abort all tables locks used by this thread
 
6836
          as the thread may be waiting to get a lock for another table.
 
6837
          Note that we need to hold LOCK_open while going through the
 
6838
          list. So that the other thread cannot change it. The other
 
6839
          thread must also hold LOCK_open whenever changing the
 
6840
          open_tables list. Aborting the MERGE lock after a child was
 
6841
          closed and before the parent is closed would be fatal.
 
6842
        */
 
6843
        for (TABLE *thd_table= in_use->open_tables;
 
6844
             thd_table ;
 
6845
             thd_table= thd_table->next)
 
6846
        {
 
6847
          /* Do not handle locks of MERGE children. */
 
6848
          if (thd_table->db_stat)       // If table is open
 
6849
            signalled|= mysql_lock_abort_for_thread(thd, thd_table);
 
6850
        }
 
6851
      }
 
6852
      else
 
6853
      {
 
6854
        DBUG_PRINT("info", ("Table was in use by current thread. db_stat: %u",
 
6855
                            table->db_stat));
 
6856
        result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
 
6857
      }
 
6858
    }
 
6859
    while (unused_tables && !unused_tables->s->version)
 
6860
      VOID(hash_delete(&open_cache,(uchar*) unused_tables));
 
6861
 
 
6862
    DBUG_PRINT("info", ("Removing table from table_def_cache"));
 
6863
    /* Remove table from table definition cache if it's not in use */
 
6864
    if ((share= (TABLE_SHARE*) hash_search(&table_def_cache,(uchar*) key,
 
6865
                                           key_length)))
 
6866
    {
 
6867
      DBUG_PRINT("info", ("share version: %lu  ref_count: %u",
 
6868
                          share->version, share->ref_count));
 
6869
      share->version= 0;                          // Mark for delete
 
6870
      if (share->ref_count == 0)
 
6871
      {
 
6872
        pthread_mutex_lock(&share->mutex);
 
6873
        VOID(hash_delete(&table_def_cache, (uchar*) share));
 
6874
      }
 
6875
    }
 
6876
 
 
6877
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
6878
    {
 
6879
      /*
 
6880
        Signal any thread waiting for tables to be freed to
 
6881
        reopen their tables
 
6882
      */
 
6883
      broadcast_refresh();
 
6884
      DBUG_PRINT("info", ("Waiting for refresh signal"));
 
6885
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed)
 
6886
      {
 
6887
        dropping_tables++;
 
6888
        if (likely(signalled))
 
6889
          (void) pthread_cond_wait(&COND_refresh, &LOCK_open);
 
6890
        else
 
6891
        {
 
6892
          struct timespec abstime;
 
6893
          /*
 
6894
            It can happen that another thread has opened the
 
6895
            table but has not yet locked any table at all. Since
 
6896
            it can be locked waiting for a table that our thread
 
6897
            has done LOCK TABLE x WRITE on previously, we need to
 
6898
            ensure that the thread actually hears our signal
 
6899
            before we go to sleep. Thus we wait for a short time
 
6900
            and then we retry another loop in the
 
6901
            remove_table_from_cache routine.
 
6902
          */
 
6903
          set_timespec(abstime, 10);
 
6904
          pthread_cond_timedwait(&COND_refresh, &LOCK_open, &abstime);
 
6905
        }
 
6906
        dropping_tables--;
 
6907
        continue;
 
6908
      }
 
6909
    }
 
6910
    break;
 
6911
  }
 
6912
  DBUG_RETURN(result);
 
6913
}
 
6914
 
 
6915
 
 
6916
bool is_equal(const LEX_STRING *a, const LEX_STRING *b)
 
6917
{
 
6918
  return a->length == b->length && !strncmp(a->str, b->str, a->length);
 
6919
}
 
6920
 
 
6921
 
 
6922
/*
 
6923
  Open and lock system tables for read.
 
6924
 
 
6925
  SYNOPSIS
 
6926
    open_system_tables_for_read()
 
6927
      thd         Thread context.
 
6928
      table_list  List of tables to open.
 
6929
      backup      Pointer to Open_tables_state instance where
 
6930
                  information about currently open tables will be
 
6931
                  saved, and from which will be restored when we will
 
6932
                  end work with system tables.
 
6933
 
 
6934
  NOTES
 
6935
    Thanks to restrictions which we put on opening and locking of
 
6936
    system tables for writing, we can open and lock them for reading
 
6937
    even when we already have some other tables open and locked.  One
 
6938
    must call close_system_tables() to close systems tables opened
 
6939
    with this call.
 
6940
 
 
6941
  RETURN
 
6942
    FALSE   Success
 
6943
    TRUE    Error
 
6944
*/
 
6945
 
 
6946
bool
 
6947
open_system_tables_for_read(THD *thd, TABLE_LIST *table_list,
 
6948
                            Open_tables_state *backup)
 
6949
{
 
6950
  DBUG_ENTER("open_system_tables_for_read");
 
6951
 
 
6952
  thd->reset_n_backup_open_tables_state(backup);
 
6953
 
 
6954
  uint count= 0;
 
6955
  bool not_used;
 
6956
  for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
 
6957
  {
 
6958
    TABLE *table= open_table(thd, tables, thd->mem_root, &not_used,
 
6959
                             MYSQL_LOCK_IGNORE_FLUSH);
 
6960
    if (!table)
 
6961
      goto error;
 
6962
 
 
6963
    DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
 
6964
 
 
6965
    table->use_all_columns();
 
6966
    table->reginfo.lock_type= tables->lock_type;
 
6967
    tables->table= table;
 
6968
    count++;
 
6969
  }
 
6970
 
 
6971
  {
 
6972
    TABLE **list= (TABLE**) thd->alloc(sizeof(TABLE*) * count);
 
6973
    TABLE **ptr= list;
 
6974
    for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
 
6975
      *(ptr++)= tables->table;
 
6976
 
 
6977
    thd->lock= mysql_lock_tables(thd, list, count,
 
6978
                                 MYSQL_LOCK_IGNORE_FLUSH, &not_used);
 
6979
  }
 
6980
  if (thd->lock)
 
6981
    DBUG_RETURN(FALSE);
 
6982
 
 
6983
error:
 
6984
  close_system_tables(thd, backup);
 
6985
 
 
6986
  DBUG_RETURN(TRUE);
 
6987
}
 
6988
 
 
6989
 
 
6990
/*
 
6991
  Close system tables, opened with open_system_tables_for_read().
 
6992
 
 
6993
  SYNOPSIS
 
6994
    close_system_tables()
 
6995
      thd     Thread context
 
6996
      backup  Pointer to Open_tables_state instance which holds
 
6997
              information about tables which were open before we
 
6998
              decided to access system tables.
 
6999
*/
 
7000
 
 
7001
void
 
7002
close_system_tables(THD *thd, Open_tables_state *backup)
 
7003
{
 
7004
  close_thread_tables(thd);
 
7005
  thd->restore_backup_open_tables_state(backup);
 
7006
}
 
7007
 
 
7008
 
 
7009
/*
 
7010
  Open and lock one system table for update.
 
7011
 
 
7012
  SYNOPSIS
 
7013
    open_system_table_for_update()
 
7014
      thd        Thread context.
 
7015
      one_table  Table to open.
 
7016
 
 
7017
  NOTES
 
7018
    Table opened with this call should closed using close_thread_tables().
 
7019
 
 
7020
  RETURN
 
7021
    0   Error
 
7022
    #   Pointer to TABLE object of system table
 
7023
*/
 
7024
 
 
7025
TABLE *
 
7026
open_system_table_for_update(THD *thd, TABLE_LIST *one_table)
 
7027
{
 
7028
  DBUG_ENTER("open_system_table_for_update");
 
7029
 
 
7030
  TABLE *table= open_ltable(thd, one_table, one_table->lock_type, 0);
 
7031
  if (table)
 
7032
  {
 
7033
    DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
 
7034
    table->use_all_columns();
 
7035
  }
 
7036
 
 
7037
  DBUG_RETURN(table);
 
7038
}
3963
7039
 
3964
7040
/**
3965
7041
  @} (end of group Data_Dictionary)
3966
7042
*/
3967
 
 
3968
 
void kill_drizzle(void)
3969
 
{
3970
 
  pthread_kill(signal_thread, SIGTERM);
3971
 
  shutdown_in_progress= 1;                      // Safety if kill didn't work
3972
 
}
3973
 
 
3974
 
} /* namespace drizzled */