~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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
 
 
35
 
#include <drizzled/sql_select.h>
36
 
#include <drizzled/error.h>
37
 
#include <drizzled/gettext.h>
38
 
#include <drizzled/nested_join.h>
39
 
#include <drizzled/sql_base.h>
40
 
#include <drizzled/show.h>
41
 
#include <drizzled/item/cmpfunc.h>
42
 
#include <drizzled/replication_services.h>
43
 
#include <drizzled/check_stack_overrun.h>
44
 
#include <drizzled/lock.h>
45
 
#include <drizzled/plugin/listen.h>
46
 
#include "drizzled/cached_directory.h"
47
 
#include <drizzled/field/timestamp.h>
48
 
#include <drizzled/field/null.h>
49
 
#include "drizzled/memory/multi_malloc.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
 
 
55
 
using namespace std;
56
 
 
57
 
namespace drizzled
58
 
{
59
 
 
60
 
extern bool volatile shutdown_in_progress;
61
 
 
62
 
bool drizzle_rm_tmp_tables();
 
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 " " : "")
63
26
 
64
27
/**
65
28
  @defgroup Data_Dictionary Data Dictionary
66
29
  @{
67
30
*/
68
 
Table *unused_tables;                           /* Used by mysql_test */
 
31
TABLE *unused_tables;                           /* Used by mysql_test */
69
32
HASH open_cache;                                /* Used by mysql_test */
70
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
71
 
                             const char *alias,
72
 
                             char *cache_key, uint32_t cache_key_length);
73
 
void free_cache_entry(void *entry);
74
 
unsigned char *table_cache_key(const unsigned char *record,
75
 
                               size_t *length,
76
 
                               bool );
77
 
 
78
 
 
79
 
unsigned char *table_cache_key(const unsigned char *record,
80
 
                               size_t *length,
81
 
                               bool )
 
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)))
82
49
{
83
 
  Table *entry=(Table*) record;
 
50
  TABLE *entry=(TABLE*) record;
84
51
  *length= entry->s->table_cache_key.length;
85
 
  return (unsigned char*) entry->s->table_cache_key.str;
 
52
  return (uchar*) entry->s->table_cache_key.str;
86
53
}
87
54
 
88
55
 
89
56
bool table_cache_init(void)
90
57
{
91
 
  return hash_init(&open_cache, &my_charset_bin,
92
 
                   (size_t) table_cache_size+16,
93
 
                   0, 0, table_cache_key,
94
 
                   free_cache_entry, 0);
 
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;
95
61
}
96
62
 
97
63
void table_cache_free(void)
98
64
{
99
 
  refresh_version++;                            // Force close of open tables
100
 
 
101
 
  while (unused_tables)
102
 
    hash_delete(&open_cache,(unsigned char*) unused_tables);
103
 
 
104
 
  if (!open_cache.records)                      // Safety first
105
 
    hash_free(&open_cache);
 
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;
106
73
}
107
74
 
108
 
uint32_t cached_open_tables(void)
 
75
uint cached_open_tables(void)
109
76
{
110
77
  return open_cache.records;
111
78
}
112
79
 
113
80
 
114
 
/*
115
 
  Close cursor handle, but leave the table in the table cache
116
 
 
117
 
  SYNOPSIS
118
 
  close_handle_and_leave_table_as_lock()
119
 
  table         Table Cursor
120
 
 
121
 
  NOTES
122
 
  By leaving the table in the table cache, it disallows any other thread
123
 
  to open the table
124
 
 
125
 
  session->killed will be set if we run out of memory
126
 
 
127
 
  If closing a MERGE child, the calling function has to take care for
128
 
  closing the parent too, if necessary.
129
 
*/
130
 
 
131
 
 
132
 
void close_handle_and_leave_table_as_lock(Table *table)
133
 
{
134
 
  TableShare *share, *old_share= table->s;
 
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;
135
561
  char *key_buff;
136
 
  memory::Root *mem_root= &table->mem_root;
 
562
  MEM_ROOT *mem_root= &table->mem_root;
 
563
  DBUG_ENTER("close_handle_and_leave_table_as_lock");
137
564
 
138
 
  assert(table->db_stat);
 
565
  DBUG_ASSERT(table->db_stat);
139
566
 
140
567
  /*
141
568
    Make a local copy of the table share and free the current one.
147
574
                       &key_buff, old_share->table_cache_key.length,
148
575
                       NULL))
149
576
  {
150
 
    memset(share, 0, sizeof(*share));
 
577
    bzero((char*) share, sizeof(*share));
151
578
    share->set_table_cache_key(key_buff, old_share->table_cache_key.str,
152
579
                               old_share->table_cache_key.length);
153
580
    share->tmp_table= INTERNAL_TMP_TABLE;       // for intern_close_table()
154
581
  }
155
582
 
156
 
  table->cursor->close();
157
 
  table->db_stat= 0;                            // Mark cursor closed
158
 
  TableShare::release(table->s);
 
583
  table->file->close();
 
584
  table->db_stat= 0;                            // Mark file closed
 
585
  release_table_share(table->s, RELEASE_NORMAL);
159
586
  table->s= share;
160
 
  table->cursor->change_table_ptr(table, table->s);
 
587
  table->file->change_table_ptr(table, table->s);
 
588
 
 
589
  DBUG_VOID_RETURN;
161
590
}
162
591
 
163
592
 
166
595
  Create a list for all open tables matching SQL expression
167
596
 
168
597
  SYNOPSIS
169
 
  list_open_tables()
170
 
  wild          SQL like expression
 
598
    list_open_tables()
 
599
    thd                 Thread THD
 
600
    wild                SQL like expression
171
601
 
172
602
  NOTES
173
 
  One gets only a list of tables for which one has any kind of privilege.
174
 
  db and table names are allocated in result struct, so one doesn't need
175
 
  a lock on LOCK_open when traversing the return list.
 
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.
176
606
 
177
607
  RETURN VALUES
178
 
  true  Error 
 
608
    NULL        Error (Probably OOM)
 
609
    #           Pointer to list of names of open tables.
179
610
*/
180
611
 
181
 
bool list_open_tables(const char *db, 
182
 
                      const char *wild, 
183
 
                      bool(*func)(Table *table, 
184
 
                                  open_table_list_st& open_list,
185
 
                                  plugin::InfoSchemaTable *schema_table), 
186
 
                      Table *display,
187
 
                      plugin::InfoSchemaTable *schema_table)
 
612
OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
188
613
{
189
 
  vector<open_table_list_st> open_list;
190
 
  vector<open_table_list_st>::iterator it;
191
 
  open_table_list_st table;
192
 
 
193
 
  /* What we really need is an optimization for knowing unique tables */
194
 
  if (db && wild)
195
 
    open_list.reserve(sizeof(open_table_list_st) * (open_cache.records % 2));
196
 
  else
197
 
    open_list.reserve(sizeof(open_table_list_st) * open_cache.records);
198
 
 
199
 
  pthread_mutex_lock(&LOCK_open); /* List all open tables */
200
 
 
201
 
  for (uint32_t idx= 0; idx < open_cache.records; idx++)
 
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++)
202
625
  {
203
 
    bool found= false;
204
 
    Table *entry=(Table*) hash_element(&open_cache,idx);
205
 
 
206
 
    if (db && my_strcasecmp(system_charset_info, db, entry->s->db.str))
207
 
      continue;
208
 
    if (wild && internal::wild_compare(entry->s->table_name.str, wild, 0))
209
 
      continue;
210
 
 
211
 
    for (it= open_list.begin(); it < open_list.end(); it++)
 
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)
212
641
    {
213
 
      if (!(*it).table.compare(entry->s->table_name.str) &&
214
 
          !(*it).db.compare(entry->s->db.str))
 
642
      if (!strcmp(table->table, share->table_name.str) &&
 
643
          !strcmp(table->db,    share->db.str))
215
644
      {
216
 
        if (entry->in_use)
217
 
          (*it).in_use++;
218
 
        if (entry->locked_by_name)
219
 
          (*it).locked++;
220
 
 
221
 
        found= true;
222
 
 
223
 
        break;
 
645
        if (entry->in_use)
 
646
          table->in_use++;
 
647
        if (entry->locked_by_name)
 
648
          table->locked++;
 
649
        break;
224
650
      }
225
651
    }
226
 
 
227
 
    if (found)
 
652
    if (table)
228
653
      continue;
229
 
 
230
 
    table.db= entry->s->db.str;
231
 
    table.table= entry->s->table_name.str;
232
 
    open_list.push_back(table);
233
 
  }
234
 
  pthread_mutex_unlock(&LOCK_open);
235
 
 
236
 
  for (it= open_list.begin(); it < open_list.end(); it++)
237
 
  {
238
 
    if (func(display, *it, schema_table))
239
 
      return true;
240
 
  }
241
 
 
242
 
  return false;
 
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);
243
671
}
244
672
 
245
673
/*****************************************************************************
247
675
 ****************************************************************************/
248
676
 
249
677
 
250
 
void Table::intern_close_table()
 
678
void intern_close_table(TABLE *table)
251
679
{                                               // Free all structures
252
 
  free_io_cache();
253
 
  if (cursor)                              // Not true if name lock
254
 
    closefrm(true);                     // close cursor
 
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;
255
690
}
256
691
 
257
692
/*
258
693
  Remove table from the open table cache
259
694
 
260
695
  SYNOPSIS
261
 
  free_cache_entry()
262
 
  entry         Table to remove
 
696
    free_cache_entry()
 
697
    table               Table to remove
263
698
 
264
699
  NOTE
265
 
  We need to have a lock on LOCK_open when calling this
 
700
    We need to have a lock on LOCK_open when calling this
266
701
*/
267
702
 
268
 
void free_cache_entry(void *entry)
 
703
static void free_cache_entry(TABLE *table)
269
704
{
270
 
  Table *table= static_cast<Table *>(entry);
271
 
  table->intern_close_table();
 
705
  DBUG_ENTER("free_cache_entry");
 
706
 
 
707
  intern_close_table(table);
272
708
  if (!table->in_use)
273
709
  {
274
710
    table->next->prev=table->prev;              /* remove from used chain */
277
713
    {
278
714
      unused_tables=unused_tables->next;
279
715
      if (table == unused_tables)
280
 
        unused_tables= NULL;
 
716
        unused_tables=0;
281
717
    }
 
718
    check_unused();                             // consisty check
282
719
  }
283
 
  free(table);
 
720
  my_free((uchar*) table,MYF(0));
 
721
  DBUG_VOID_RETURN;
284
722
}
285
723
 
286
724
/* Free resources allocated by filesort() and read_record() */
287
725
 
288
 
void Table::free_io_cache()
 
726
void free_io_cache(TABLE *table)
289
727
{
290
 
  if (sort.io_cache)
 
728
  DBUG_ENTER("free_io_cache");
 
729
  if (table->sort.io_cache)
291
730
  {
292
 
    close_cached_file(sort.io_cache);
293
 
    delete sort.io_cache;
294
 
    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;
295
734
  }
 
735
  DBUG_VOID_RETURN;
296
736
}
297
737
 
298
738
 
299
739
/*
300
740
  Close all tables which aren't in use by any thread
301
741
 
302
 
  @param session Thread context (may be NULL)
 
742
  @param thd Thread context
303
743
  @param tables List of tables to remove from the cache
304
744
  @param have_lock If LOCK_open is locked
305
745
  @param wait_for_refresh Wait for a impending flush
306
746
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
307
 
  won't proceed while write-locked tables are being reopened by other
308
 
  threads.
 
747
         won't proceed while write-locked tables are being reopened by other
 
748
         threads.
309
749
 
310
 
  @remark Session can be NULL, but then wait_for_refresh must be false
311
 
  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.
312
752
*/
313
753
 
314
 
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)
315
756
{
316
 
  bool result= false;
317
 
  Session *session= this;
318
 
 
319
 
  pthread_mutex_lock(&LOCK_open); /* Optionally lock for remove tables from open_cahe if not in use */
320
 
 
321
 
  if (tables == NULL)
 
757
  bool result=0;
 
758
  DBUG_ENTER("close_cached_tables");
 
759
  DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
 
760
 
 
761
  if (!have_lock)
 
762
    VOID(pthread_mutex_lock(&LOCK_open));
 
763
  if (!tables)
322
764
  {
323
765
    refresh_version++;                          // Force close of open tables
324
766
    while (unused_tables)
325
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
326
 
 
 
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));
327
783
    if (wait_for_refresh)
328
784
    {
329
785
      /*
334
790
        request is aborted. They loop in open_and_lock_tables() and
335
791
        enter open_table(). Here they notice the table is refreshed and
336
792
        wait for COND_refresh. Then they loop again in
337
 
        openTablesLock() and this time open_table() succeeds. At
 
793
        open_and_lock_tables() and this time open_table() succeeds. At
338
794
        this moment, if we (the FLUSH TABLES thread) are scheduled and
339
795
        on another FLUSH TABLES enter close_cached_tables(), they could
340
796
        awake while we sleep below, waiting for others threads (us) to
349
805
        The fix for this problem is to set some_tables_deleted for all
350
806
        threads with open tables. These threads can still get their
351
807
        locks, but will immediately release them again after checking
352
 
        this variable. They will then loop in openTablesLock()
 
808
        this variable. They will then loop in open_and_lock_tables()
353
809
        again. There they will wait until we update all tables version
354
810
        below.
355
811
 
360
816
        some_tables_deleted for the case when table was opened and all
361
817
        related checks were passed before incrementing refresh_version
362
818
        (which you already have) but attempt to lock the table happened
363
 
        after the call to Session::close_old_data_files() i.e. after removal of
 
819
        after the call to close_old_data_files() i.e. after removal of
364
820
        current thread locks.
365
821
      */
366
 
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
822
      for (uint idx=0 ; idx < open_cache.records ; idx++)
367
823
      {
368
 
        Table *table=(Table*) hash_element(&open_cache,idx);
 
824
        TABLE *table=(TABLE*) hash_element(&open_cache,idx);
369
825
        if (table->in_use)
370
 
          table->in_use->some_tables_deleted= false;
 
826
          table->in_use->some_tables_deleted= 1;
371
827
      }
372
828
    }
373
829
  }
374
830
  else
375
831
  {
376
 
    bool found= false;
377
 
    for (TableList *table= tables; table; table= table->next_local)
 
832
    bool found=0;
 
833
    for (TABLE_LIST *table= tables; table; table= table->next_local)
378
834
    {
379
 
      if (remove_table_from_cache(session, table->db, table->table_name,
380
 
                                  RTFC_OWNED_BY_Session_FLAG))
381
 
        found= true;
 
835
      if (remove_table_from_cache(thd, table->db, table->table_name,
 
836
                                  RTFC_OWNED_BY_THD_FLAG))
 
837
        found=1;
382
838
    }
383
839
    if (!found)
384
 
      wait_for_refresh= false;                  // Nothing to wait for
 
840
      wait_for_refresh=0;                       // Nothing to wait for
385
841
  }
386
842
 
387
843
  if (wait_for_refresh)
390
846
      If there is any table that has a lower refresh_version, wait until
391
847
      this is closed (or this thread is killed) before returning
392
848
    */
393
 
    session->mysys_var->current_mutex= &LOCK_open;
394
 
    session->mysys_var->current_cond= &COND_refresh;
395
 
    session->set_proc_info("Flushing tables");
396
 
 
397
 
    session->close_old_data_files();
398
 
 
399
 
    bool found= true;
 
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;
400
857
    /* Wait until all threads has closed all the tables we had locked */
401
 
    while (found && ! session->killed)
 
858
    DBUG_PRINT("info",
 
859
               ("Waiting for other threads to close their open tables"));
 
860
    while (found && ! thd->killed)
402
861
    {
403
 
      found= false;
404
 
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
862
      found=0;
 
863
      for (uint idx=0 ; idx < open_cache.records ; idx++)
405
864
      {
406
 
        Table *table=(Table*) hash_element(&open_cache,idx);
 
865
        TABLE *table=(TABLE*) hash_element(&open_cache,idx);
407
866
        /* Avoid a self-deadlock. */
408
 
        if (table->in_use == session)
 
867
        if (table->in_use == thd)
409
868
          continue;
410
869
        /*
411
870
          Note that we wait here only for tables which are actually open, and
412
 
          not for placeholders with Table::open_placeholder set. Waiting for
 
871
          not for placeholders with TABLE::open_placeholder set. Waiting for
413
872
          latter will cause deadlock in the following scenario, for example:
414
873
 
415
 
conn1: lock table t1 write;
416
 
conn2: lock table t2 write;
417
 
conn1: flush tables;
418
 
conn2: flush tables;
 
874
          conn1: lock table t1 write;
 
875
          conn2: lock table t2 write;
 
876
          conn1: flush tables;
 
877
          conn2: flush tables;
419
878
 
420
 
It also does not make sense to wait for those of placeholders that
421
 
are employed by CREATE TABLE as in this case table simply does not
422
 
exist yet.
 
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.
423
882
        */
424
 
        if (table->needs_reopen_or_name_lock() && (table->db_stat ||
425
 
                                                   (table->open_placeholder && wait_for_placeholders)))
426
 
        {
427
 
          found= true;
428
 
          pthread_cond_wait(&COND_refresh,&LOCK_open);
429
 
          break;
430
 
        }
 
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
        }
431
891
      }
432
892
    }
433
893
    /*
435
895
      old locks. This should always succeed (unless some external process
436
896
      has removed the tables)
437
897
    */
438
 
    result= session->reopen_tables(true, true);
439
 
 
 
898
    thd->in_lock_tables=1;
 
899
    result=reopen_tables(thd,1,1);
 
900
    thd->in_lock_tables=0;
440
901
    /* Set version for table */
441
 
    for (Table *table= session->open_tables; table ; table= table->next)
 
902
    for (TABLE *table=thd->open_tables; table ; table= table->next)
442
903
    {
443
904
      /*
444
905
        Preserve the version (0) of write locked tables so that a impending
448
909
        table->s->version= refresh_version;
449
910
    }
450
911
  }
451
 
 
452
 
  pthread_mutex_unlock(&LOCK_open);
453
 
 
 
912
  if (!have_lock)
 
913
    VOID(pthread_mutex_unlock(&LOCK_open));
454
914
  if (wait_for_refresh)
455
915
  {
456
 
    pthread_mutex_lock(&session->mysys_var->mutex);
457
 
    session->mysys_var->current_mutex= 0;
458
 
    session->mysys_var->current_cond= 0;
459
 
    session->set_proc_info(0);
460
 
    pthread_mutex_unlock(&session->mysys_var->mutex);
461
 
  }
462
 
 
463
 
  return result;
 
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);
464
988
}
465
989
 
466
990
 
467
991
/**
468
 
  move one table to free list 
469
 
*/
470
 
 
471
 
bool Session::free_cached_table()
472
 
{
473
 
  bool found_old_table= false;
474
 
  Table *table= open_tables;
475
 
 
476
 
  safe_mutex_assert_owner(&LOCK_open);
477
 
  assert(table->key_read == 0);
478
 
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
479
 
 
480
 
  open_tables= table->next;
481
 
 
482
 
  if (table->needs_reopen_or_name_lock() ||
483
 
      version != refresh_version || !table->db_stat)
484
 
  {
485
 
    hash_delete(&open_cache,(unsigned char*) table);
486
 
    found_old_table= true;
487
 
  }
488
 
  else
489
 
  {
490
 
    /*
491
 
      Open placeholders have Table::db_stat set to 0, so they should be
492
 
      handled by the first alternative.
493
 
    */
494
 
    assert(!table->open_placeholder);
495
 
 
496
 
    /* Free memory and reset for next loop */
497
 
    table->cursor->ha_reset();
498
 
    table->in_use= false;
499
 
 
500
 
    if (unused_tables)
501
 
    {
502
 
      table->next= unused_tables;               /* Link in last */
503
 
      table->prev= unused_tables->prev;
504
 
      unused_tables->prev= table;
505
 
      table->prev->next= table;
506
 
    }
507
 
    else
508
 
      unused_tables= table->next=table->prev=table;
509
 
  }
510
 
 
511
 
  return found_old_table;
 
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
  }
512
1047
}
513
1048
 
514
1049
 
515
1050
/**
516
1051
  Auxiliary function to close all tables in the open_tables list.
517
1052
 
518
 
  @param session Thread context.
 
1053
  @param thd Thread context.
519
1054
 
520
1055
  @remark It should not ordinarily be called directly.
521
1056
*/
522
1057
 
523
 
void Session::close_open_tables()
 
1058
static void close_open_tables(THD *thd)
524
1059
{
525
 
  bool found_old_table= false;
 
1060
  bool found_old_table= 0;
526
1061
 
527
1062
  safe_mutex_assert_not_owner(&LOCK_open);
528
1063
 
529
 
  pthread_mutex_lock(&LOCK_open); /* Close all open tables on Session */
530
 
 
531
 
  while (open_tables)
532
 
    found_old_table|= free_cached_table();
533
 
  some_tables_deleted= false;
534
 
 
 
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();
535
1076
  if (found_old_table)
536
1077
  {
537
1078
    /* Tell threads waiting for refresh that something has happened */
538
1079
    broadcast_refresh();
539
1080
  }
540
1081
 
541
 
  pthread_mutex_unlock(&LOCK_open);
 
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;
542
1389
}
543
1390
 
544
1391
/*
545
1392
  Find table in list.
546
1393
 
547
1394
  SYNOPSIS
548
 
  find_table_in_list()
549
 
  table         Pointer to table list
550
 
  offset                Offset to which list in table structure to use
551
 
  db_name               Data base name
552
 
  table_name            Table name
553
 
 
554
 
NOTES:
555
 
This is called by find_table_in_global_list().
556
 
 
557
 
RETURN VALUES
558
 
NULL    Table not found
559
 
#               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.
560
1408
*/
561
1409
 
562
 
TableList *find_table_in_list(TableList *table,
563
 
                              TableList *TableList::*link,
564
 
                              const char *db_name,
565
 
                              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)
566
1414
{
567
1415
  for (; table; table= table->*link )
568
1416
  {
579
1427
  Test that table is unique (It's only exists once in the table list)
580
1428
 
581
1429
  SYNOPSIS
582
 
  unique_table()
583
 
  session                   thread handle
584
 
  table                 table which should be checked
585
 
  table_list            list of tables
586
 
  check_alias           whether to check tables' aliases
587
 
 
588
 
NOTE: to exclude derived tables from check we use following mechanism:
589
 
a) during derived table processing set Session::derived_tables_processing
590
 
b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
591
 
Session::derived_tables_processing set. (we can't use JOIN::execute
592
 
because for PS we perform only JOIN::prepare, but we can't set this
593
 
flag in JOIN::prepare if we are not sure that we are in derived table
594
 
processing loop, because multi-update call fix_fields() for some its
595
 
items (which mean JOIN::prepare for subqueries) before unique_table
596
 
call to detect which tables should be locked for write).
597
 
c) unique_table skip all tables which belong to SELECT with
598
 
SELECT::exclude_from_table_unique_test set.
599
 
Also SELECT::exclude_from_table_unique_test used to exclude from check
600
 
tables of main SELECT of multi-delete and multi-update
601
 
 
602
 
We also skip tables with TableList::prelocking_placeholder set,
603
 
because we want to allow SELECTs from them, and their modification
604
 
will rise the error anyway.
605
 
 
606
 
TODO: when we will have table/view change detection we can do this check
607
 
only once for PS/SP
608
 
 
609
 
RETURN
610
 
found duplicate
611
 
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
612
1460
*/
613
1461
 
614
 
TableList* unique_table(TableList *table, TableList *table_list,
615
 
                        bool check_alias)
 
1462
TABLE_LIST* unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
 
1463
                         bool check_alias)
616
1464
{
617
 
  TableList *res;
 
1465
  TABLE_LIST *res;
618
1466
  const char *d_name, *t_name, *t_alias;
 
1467
  DBUG_ENTER("unique_table");
 
1468
  DBUG_PRINT("enter", ("table alias: %s", table->alias));
619
1469
 
620
1470
  /*
621
1471
    If this function called for query which update table (INSERT/UPDATE/...)
622
 
    then we have in table->table pointer to Table object which we are
623
 
    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
624
1474
    to get right names (even if lower_case_table_names used).
625
1475
 
626
1476
    If this function called for CREATE command that we have not opened table
627
 
    (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
628
1478
    object.
629
1479
  */
630
1480
  if (table->table)
631
1481
  {
632
1482
    /* temporary table is always unique */
633
1483
    if (table->table && table->table->s->tmp_table != NO_TMP_TABLE)
634
 
      return 0;
 
1484
      DBUG_RETURN(0);
635
1485
    table= table->find_underlying_table(table->table);
636
1486
    /*
637
 
      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
638
1488
      it in underlying tables
639
1489
    */
640
 
    assert(table);
 
1490
    DBUG_ASSERT(table);
641
1491
  }
642
1492
  d_name= table->db;
643
1493
  t_name= table->table_name;
644
1494
  t_alias= table->alias;
645
1495
 
 
1496
  DBUG_PRINT("info", ("real table: %s.%s", d_name, t_name));
646
1497
  for (;;)
647
1498
  {
648
 
    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)))) ||
649
1501
        ((!res->table || res->table != table->table) &&
650
 
         (!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))) &&
651
1505
         res->select_lex && !res->select_lex->exclude_from_table_unique_test))
652
1506
      break;
653
1507
    /*
656
1510
      (exclude_from_table_unique_test) or prelocking placeholder.
657
1511
    */
658
1512
    table_list= res->next_global;
 
1513
    DBUG_PRINT("info",
 
1514
               ("found same copy of table or table which we should skip"));
659
1515
  }
660
 
  return(res);
661
 
}
662
 
 
663
 
 
664
 
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
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)
665
1553
{
666
1554
  char  key[MAX_DBKEY_LENGTH];
667
1555
  uint  key_length;
668
 
  Table *table;
669
 
 
670
 
  key_length= TableShare::createKey(key, new_db, table_name);
671
 
 
672
 
  for (table= temporary_tables ; table ; table= table->next)
 
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)
673
1563
  {
674
1564
    if (table->s->table_cache_key.length == key_length &&
675
 
        !memcmp(table->s->table_cache_key.str, key, key_length))
676
 
      return table;
 
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
    }
677
1573
  }
678
 
  return NULL;                               // Not a temporary table
679
 
}
680
 
 
681
 
Table *Session::find_temporary_table(TableList *table_list)
682
 
{
683
 
  return find_temporary_table(table_list->db, table_list->table_name);
 
1574
  DBUG_RETURN(0);                               // Not a temporary table
684
1575
}
685
1576
 
686
1577
 
687
1578
/**
688
1579
  Drop a temporary table.
689
1580
 
690
 
  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.
691
1582
  If the table is found:
692
 
  - if the table is being used by some outer statement, fail.
693
 
  - if the table is in session->locked_tables, unlock it and
694
 
  remove it from the list of locked tables. Currently only transactional
695
 
  temporary tables are present in the locked_tables list.
696
 
  - Close the temporary table, remove its .FRM
697
 
  - 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
698
1589
 
699
1590
  This function is used to drop user temporary tables, as well as
700
1591
  internal tables created in CREATE TEMPORARY TABLE ... SELECT
701
 
  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
702
1593
  is redundant when the table is internal, as long as we
703
1594
  link both internal and user temporary tables into the same
704
 
  session->temporary_tables list, it's impossible to tell here whether
 
1595
  thd->temporary_tables list, it's impossible to tell here whether
705
1596
  we're dealing with an internal or a user temporary table.
706
1597
 
707
1598
  @retval  0  the table was found and dropped successfully.
708
1599
  @retval  1  the table was not found in the list of temporary tables
709
 
  of this thread
 
1600
              of this thread
710
1601
  @retval -1  the table is in use by a outer query
711
1602
*/
712
1603
 
713
 
int Session::drop_temporary_table(TableList *table_list)
 
1604
int drop_temporary_table(THD *thd, TABLE_LIST *table_list)
714
1605
{
715
 
  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));
716
1610
 
717
 
  if (!(table= find_temporary_table(table_list)))
718
 
    return 1;
 
1611
  if (!(table= find_temporary_table(thd, table_list)))
 
1612
    DBUG_RETURN(1);
719
1613
 
720
1614
  /* Table might be in use by some outer statement. */
721
 
  if (table->query_id && table->query_id != query_id)
 
1615
  if (table->query_id && table->query_id != thd->query_id)
722
1616
  {
723
1617
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
724
 
    return -1;
725
 
  }
726
 
 
727
 
  close_temporary_table(table);
728
 
 
729
 
  return 0;
730
 
}
731
 
 
732
 
 
733
 
/* move table first in unused links */
734
 
 
735
 
static void relink_unused(Table *table)
 
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)
736
1736
{
737
1737
  if (table != unused_tables)
738
1738
  {
743
1743
    unused_tables->prev->next=table;
744
1744
    unused_tables->prev=table;
745
1745
    unused_tables=table;
 
1746
    check_unused();
746
1747
  }
747
1748
}
748
1749
 
749
1750
 
750
1751
/**
751
 
  Remove all instances of table from thread's open list and
752
 
  table cache.
753
 
 
754
 
  @param  session     Thread context
755
 
  @param  find    Table to remove
 
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).
756
1764
*/
757
1765
 
758
 
void Session::unlink_open_table(Table *find)
 
1766
void unlink_open_table(THD *thd, TABLE *find, bool unlock)
759
1767
{
760
1768
  char key[MAX_DBKEY_LENGTH];
761
 
  uint32_t key_length= find->s->table_cache_key.length;
762
 
  Table *list, **prev;
 
1769
  uint key_length= find->s->table_cache_key.length;
 
1770
  TABLE *list, **prev;
 
1771
  DBUG_ENTER("unlink_open_table");
763
1772
 
764
1773
  safe_mutex_assert_owner(&LOCK_open);
765
1774
 
771
1780
    Closing a MERGE child before the parent would be fatal if the
772
1781
    other thread tries to abort the MERGE lock in between.
773
1782
  */
774
 
  for (prev= &open_tables; *prev; )
 
1783
  for (prev= &thd->open_tables; *prev; )
775
1784
  {
776
1785
    list= *prev;
777
1786
 
778
1787
    if (list->s->table_cache_key.length == key_length &&
779
 
        !memcmp(list->s->table_cache_key.str, key, key_length))
 
1788
        !memcmp(list->s->table_cache_key.str, key, key_length))
780
1789
    {
 
1790
      if (unlock && thd->locked_tables)
 
1791
        mysql_lock_remove(thd, thd->locked_tables, list, TRUE);
 
1792
 
781
1793
      /* Remove table from open_tables list. */
782
1794
      *prev= list->next;
783
1795
      /* Close table. */
784
 
      hash_delete(&open_cache,(unsigned char*) list); // Close table
 
1796
      VOID(hash_delete(&open_cache,(uchar*) list)); // Close table
785
1797
    }
786
1798
    else
787
1799
    {
792
1804
 
793
1805
  // Notify any 'refresh' threads
794
1806
  broadcast_refresh();
 
1807
  DBUG_VOID_RETURN;
795
1808
}
796
1809
 
797
1810
 
798
1811
/**
799
 
  Auxiliary routine which closes and drops open table.
800
 
 
801
 
  @param  session         Thread handle
802
 
  @param  table       Table object for table to be dropped
803
 
  @param  db_name     Name of database for this table
804
 
  @param  table_name  Name of this table
805
 
 
806
 
  @note This routine assumes that table to be closed is open only
807
 
  by calling thread so we needn't wait until other threads
808
 
  will close the table. Also unless called under implicit or
809
 
  explicit LOCK TABLES mode it assumes that table to be
810
 
  dropped is already unlocked. In the former case it will
811
 
  also remove lock on the table. But one should not rely on
812
 
  this behaviour as it may change in future.
813
 
  Currently, however, this function is never called for a
814
 
  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.
815
1828
*/
816
1829
 
817
 
void Session::drop_open_table(Table *table, const char *db_name,
818
 
                              const char *table_name)
 
1830
void drop_open_table(THD *thd, TABLE *table, const char *db_name,
 
1831
                     const char *table_name)
819
1832
{
820
1833
  if (table->s->tmp_table)
821
 
  {
822
 
    close_temporary_table(table);
823
 
  }
 
1834
    close_temporary_table(thd, table, 1, 1);
824
1835
  else
825
1836
  {
826
 
    pthread_mutex_lock(&LOCK_open); /* Close and drop a table (AUX routine) */
 
1837
    handlerton *table_type= table->s->db_type();
 
1838
    VOID(pthread_mutex_lock(&LOCK_open));
827
1839
    /*
828
1840
      unlink_open_table() also tells threads waiting for refresh or close
829
1841
      that something has happened.
830
1842
    */
831
 
    unlink_open_table(table);
832
 
    TableIdentifier identifier(db_name, table_name, NO_TMP_TABLE);
833
 
    quick_rm_table(*this, identifier);
834
 
    pthread_mutex_unlock(&LOCK_open);
 
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));
835
1846
  }
836
1847
}
837
1848
 
838
1849
 
839
1850
/*
840
 
  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
841
1852
 
842
 
  SYNOPSIS
843
 
  wait_for_condition()
844
 
  session       Thread Cursor
845
 
  mutex mutex that is currently hold that is associated with condition
846
 
  Will be unlocked on return
847
 
  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
848
1859
*/
849
1860
 
850
 
void Session::wait_for_condition(pthread_mutex_t *mutex, pthread_cond_t *cond)
 
1861
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
851
1862
{
852
1863
  /* Wait until the current table is up to date */
853
 
  const char *saved_proc_info;
854
 
  mysys_var->current_mutex= mutex;
855
 
  mysys_var->current_cond= cond;
856
 
  saved_proc_info= get_proc_info();
857
 
  set_proc_info("Waiting for table");
858
 
  if (!killed)
 
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)
859
1871
    (void) pthread_cond_wait(cond, mutex);
860
1872
 
861
1873
  /*
868
1880
    condition variables that are guranteed to not disapper (freed) even if this
869
1881
    mutex is unlocked
870
1882
  */
871
 
 
 
1883
    
872
1884
  pthread_mutex_unlock(mutex);
873
 
  pthread_mutex_lock(&mysys_var->mutex);
874
 
  mysys_var->current_mutex= 0;
875
 
  mysys_var->current_cond= 0;
876
 
  set_proc_info(saved_proc_info);
877
 
  pthread_mutex_unlock(&mysys_var->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);
878
1926
}
879
1927
 
880
1928
 
882
1930
  Open table which is already name-locked by this thread.
883
1931
 
884
1932
  SYNOPSIS
885
 
  reopen_name_locked_table()
886
 
  session         Thread handle
887
 
  table_list  TableList object for table to be open, TableList::table
888
 
  member should point to Table object which was used for
889
 
  name-locking.
890
 
  link_in     true  - if Table object for table to be opened should be
891
 
  linked into Session::open_tables list.
892
 
  false - placeholder used for name-locking is already in
893
 
  this list so we only need to preserve Table::next
894
 
  pointer.
 
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.
895
1943
 
896
1944
  NOTE
897
 
  This function assumes that its caller already acquired LOCK_open mutex.
 
1945
    This function assumes that its caller already acquired LOCK_open mutex.
898
1946
 
899
1947
  RETURN VALUE
900
 
  false - Success
901
 
  true  - Error
 
1948
    FALSE - Success
 
1949
    TRUE  - Error
902
1950
*/
903
1951
 
904
 
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
1952
bool reopen_name_locked_table(THD* thd, TABLE_LIST* table_list, bool link_in)
905
1953
{
906
 
  Table *table= table_list->table;
907
 
  TableShare *share;
 
1954
  TABLE *table= table_list->table;
 
1955
  TABLE_SHARE *share;
908
1956
  char *table_name= table_list->table_name;
909
 
  Table orig_table;
 
1957
  TABLE orig_table;
 
1958
  DBUG_ENTER("reopen_name_locked_table");
910
1959
 
911
1960
  safe_mutex_assert_owner(&LOCK_open);
912
1961
 
913
 
  if (killed || !table)
914
 
    return true;
 
1962
  if (thd->killed || !table)
 
1963
    DBUG_RETURN(TRUE);
915
1964
 
916
1965
  orig_table= *table;
917
1966
 
918
 
  if (open_unireg_entry(this, table, table_list, table_name,
 
1967
  if (open_unireg_entry(thd, table, table_list, table_name,
919
1968
                        table->s->table_cache_key.str,
920
 
                        table->s->table_cache_key.length))
 
1969
                        table->s->table_cache_key.length, thd->mem_root, 0))
921
1970
  {
922
 
    table->intern_close_table();
 
1971
    intern_close_table(table);
923
1972
    /*
924
1973
      If there was an error during opening of table (for example if it
925
1974
      does not exist) '*table' object can be wiped out. To be able
927
1976
      object to its original state.
928
1977
    */
929
1978
    *table= orig_table;
930
 
    return true;
 
1979
    DBUG_RETURN(TRUE);
931
1980
  }
932
1981
 
933
1982
  share= table->s;
934
1983
  /*
935
1984
    We want to prevent other connections from opening this table until end
936
1985
    of statement as it is likely that modifications of table's metadata are
937
 
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1986
    not yet finished (for example CREATE TRIGGER have to change .TRG file,
938
1987
    or we might want to drop table if CREATE TABLE ... SELECT fails).
939
1988
    This also allows us to assume that no other connection will sneak in
940
1989
    before we will get table-level lock on this table.
941
1990
  */
942
1991
  share->version=0;
943
 
  table->in_use = this;
 
1992
  table->in_use = thd;
 
1993
  check_unused();
944
1994
 
945
1995
  if (link_in)
946
1996
  {
947
 
    table->next= open_tables;
948
 
    open_tables= table;
 
1997
    table->next= thd->open_tables;
 
1998
    thd->open_tables= table;
949
1999
  }
950
2000
  else
951
2001
  {
952
2002
    /*
953
 
      Table object should be already in Session::open_tables list so we just
954
 
      need to set Table::next correctly.
 
2003
      TABLE object should be already in THD::open_tables list so we just
 
2004
      need to set TABLE::next correctly.
955
2005
    */
956
2006
    table->next= orig_table.next;
957
2007
  }
958
2008
 
959
 
  table->tablenr= current_tablenr++;
960
 
  table->used_fields= 0;
961
 
  table->const_table= 0;
962
 
  table->null_row= false;
963
 
  table->maybe_null= false;
964
 
  table->force_index= false;
965
 
  table->status= STATUS_NO_RECORD;
966
 
 
967
 
  return false;
 
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);
968
2015
}
969
2016
 
970
2017
 
971
2018
/**
972
 
  Create and insert into table cache placeholder for table
973
 
  which will prevent its opening (or creation) (a.k.a lock
974
 
  table name).
975
 
 
976
 
  @param session         Thread context
977
 
  @param key         Table cache key for name to be locked
978
 
  @param key_length  Table cache key length
979
 
 
980
 
  @return Pointer to Table object used for name locking or 0 in
981
 
  case of failure.
 
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.
982
2029
*/
983
2030
 
984
 
Table *Session::table_cache_insert_placeholder(const char *key, uint32_t key_length)
 
2031
TABLE *table_cache_insert_placeholder(THD *thd, const char *key,
 
2032
                                      uint key_length)
985
2033
{
986
 
  Table *table;
987
 
  TableShare *share;
 
2034
  TABLE *table;
 
2035
  TABLE_SHARE *share;
988
2036
  char *key_buff;
 
2037
  DBUG_ENTER("table_cache_insert_placeholder");
989
2038
 
990
2039
  safe_mutex_assert_owner(&LOCK_open);
991
2040
 
992
2041
  /*
993
2042
    Create a table entry with the right key and with an old refresh version
994
 
    Note that we must use multi_malloc() here as this is freed by the
 
2043
    Note that we must use my_multi_malloc() here as this is freed by the
995
2044
    table cache
996
2045
  */
997
 
  if (! memory::multi_malloc(true,
998
 
                             &table, sizeof(*table),
999
 
                             &share, sizeof(*share),
1000
 
                             &key_buff, key_length,
1001
 
                             NULL))
1002
 
    return NULL;
 
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);
1003
2052
 
1004
2053
  table->s= share;
1005
2054
  share->set_table_cache_key(key_buff, key, key_length);
1006
2055
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
1007
 
  table->in_use= this;
 
2056
  table->in_use= thd;
1008
2057
  table->locked_by_name=1;
1009
2058
 
1010
 
  if (my_hash_insert(&open_cache, (unsigned char*)table))
 
2059
  if (my_hash_insert(&open_cache, (uchar*)table))
1011
2060
  {
1012
 
    free((unsigned char*) table);
1013
 
    return NULL;
 
2061
    my_free((uchar*) table, MYF(0));
 
2062
    DBUG_RETURN(NULL);
1014
2063
  }
1015
2064
 
1016
 
  return table;
 
2065
  DBUG_RETURN(table);
1017
2066
}
1018
2067
 
1019
2068
 
1020
2069
/**
1021
 
  Obtain an exclusive name lock on the table if it is not cached
1022
 
  in the table cache.
1023
 
 
1024
 
  @param      session         Thread context
1025
 
  @param      db          Name of database
1026
 
  @param      table_name  Name of table
1027
 
  @param[out] table       Out parameter which is either:
1028
 
  - set to NULL if table cache contains record for
1029
 
  the table or
1030
 
  - set to point to the Table instance used for
1031
 
  name-locking.
1032
 
 
1033
 
  @note This function takes into account all records for table in table
1034
 
  cache, even placeholders used for name-locking. This means that
1035
 
  'table' parameter can be set to NULL for some situations when
1036
 
  table does not really exist.
1037
 
 
1038
 
  @retval  true   Error occured (OOM)
1039
 
  @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.
1040
2089
*/
1041
2090
 
1042
 
bool Session::lock_table_name_if_not_cached(const char *new_db,
1043
 
                                            const char *table_name, Table **table)
 
2091
bool lock_table_name_if_not_cached(THD *thd, const char *db,
 
2092
                                   const char *table_name, TABLE **table)
1044
2093
{
1045
2094
  char key[MAX_DBKEY_LENGTH];
1046
 
  char *key_pos= key;
1047
 
  uint32_t key_length;
1048
 
 
1049
 
  key_pos= strcpy(key_pos, new_db) + strlen(new_db);
1050
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1051
 
  key_length= (uint32_t) (key_pos-key)+1;
1052
 
 
1053
 
  pthread_mutex_lock(&LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
1054
 
 
1055
 
  if (hash_search(&open_cache, (unsigned char *)key, key_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))
1056
2102
  {
1057
 
    pthread_mutex_unlock(&LOCK_open);
 
2103
    VOID(pthread_mutex_unlock(&LOCK_open));
 
2104
    DBUG_PRINT("info", ("Table is cached, name-lock is not obtained"));
1058
2105
    *table= 0;
1059
 
    return false;
1060
 
  }
1061
 
  if (!(*table= table_cache_insert_placeholder(key, key_length)))
1062
 
  {
1063
 
    pthread_mutex_unlock(&LOCK_open);
1064
 
    return true;
1065
 
  }
1066
 
  (*table)->open_placeholder= true;
1067
 
  (*table)->next= open_tables;
1068
 
  open_tables= *table;
1069
 
  pthread_mutex_unlock(&LOCK_open);
1070
 
 
1071
 
  return false;
1072
 
}
 
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
 
1073
2184
 
1074
2185
/*
1075
2186
  Open a table.
1076
2187
 
1077
2188
  SYNOPSIS
1078
 
  open_table()
1079
 
  session                 Thread context.
1080
 
  table_list          Open first table in list.
1081
 
  refresh      INOUT  Pointer to memory that will be set to 1 if
1082
 
  we need to close all tables and reopen them.
1083
 
  If this is a NULL pointer, then the table is not
1084
 
  put in the thread-open-list.
1085
 
  flags               Bitmap of flags to modify how open works:
1086
 
  DRIZZLE_LOCK_IGNORE_FLUSH - Open table even if
1087
 
  someone has done a flush or namelock on it.
1088
 
  No version number checking is done.
1089
 
  DRIZZLE_OPEN_TEMPORARY_ONLY - Open only temporary
1090
 
  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.
1091
2202
 
1092
2203
  IMPLEMENTATION
1093
 
  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.
1094
2205
 
1095
 
  If table list element for the table to be opened has "create" flag
1096
 
  set and table does not exist, this function will automatically insert
1097
 
  a placeholder for exclusive name lock into the open tables cache and
1098
 
  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.
1099
2210
 
1100
2211
  RETURN
1101
 
  NULL  Open failed.  If refresh is set then one should close
1102
 
  all other tables and retry the open.
1103
 
#     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.
1104
2215
*/
1105
2216
 
1106
2217
 
1107
 
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)
1108
2220
{
1109
 
  Table *table;
 
2221
  register TABLE *table;
1110
2222
  char key[MAX_DBKEY_LENGTH];
1111
2223
  unsigned int key_length;
1112
 
  const char *alias= table_list->alias;
 
2224
  char *alias= table_list->alias;
1113
2225
  HASH_SEARCH_STATE state;
 
2226
  DBUG_ENTER("open_table");
1114
2227
 
1115
 
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1116
 
  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);
1117
2230
 
1118
2231
  /* find a unused table in the open table cache */
1119
2232
  if (refresh)
1120
 
    *refresh= false;
 
2233
    *refresh=0;
1121
2234
 
1122
2235
  /* an open table operation needs a lot of the stack space */
1123
 
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1124
 
    return NULL;
1125
 
 
1126
 
  if (killed)
1127
 
    return NULL;
1128
 
 
1129
 
  key_length= table_list->create_table_def_key(key);
 
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);
1130
2244
 
1131
2245
  /*
1132
2246
    Unless requested otherwise, try to resolve this table in the list
1133
2247
    of temporary tables of this thread. In MySQL temporary tables
1134
2248
    are always thread-local and "shadow" possible base tables with the
1135
2249
    same name. This block implements the behaviour.
1136
 
    TODO -> move this block into a separate function.
1137
 
  */
1138
 
  for (table= temporary_tables; table ; table=table->next)
1139
 
  {
1140
 
    if (table->s->table_cache_key.length == key_length && !memcmp(table->s->table_cache_key.str, key, key_length))
1141
 
    {
1142
 
      /*
1143
 
        We're trying to use the same temporary table twice in a query.
1144
 
        Right now we don't support this because a temporary table
1145
 
        is always represented by only one Table object in Session, and
1146
 
        it can not be cloned. Emit an error for an unsupported behaviour.
1147
 
      */
1148
 
      if (table->query_id)
1149
 
      {
1150
 
        my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1151
 
        return NULL;
1152
 
      }
1153
 
      table->query_id= getQueryId();
 
2250
    TODO: move this block into a separate function.
 
2251
  */
 
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
      {
 
2260
        /*
 
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.
 
2265
        */
 
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)
 
2308
        {
 
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);
 
2318
        }
 
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 */
 
2325
        {
 
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.
 
2335
 
 
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))
 
2341
          {
 
2342
            best_distance= distance;
 
2343
            best_table= table;
 
2344
            if (best_distance == 0 && !check_if_used)
 
2345
            {
 
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;
 
2353
            }
 
2354
          }
 
2355
        }
 
2356
      }
 
2357
    }
 
2358
    if (best_table)
 
2359
    {
 
2360
      table= best_table;
 
2361
      table->query_id= thd->query_id;
 
2362
      DBUG_PRINT("info",("Using locked table"));
1154
2363
      goto reset;
1155
2364
    }
1156
 
  }
1157
 
 
1158
 
  if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
1159
 
  {
1160
 
    my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
1161
 
    return NULL;
1162
 
  }
1163
 
 
1164
 
  /*
1165
 
    If it's the first table from a list of tables used in a query,
1166
 
    remember refresh_version (the version of open_cache state).
1167
 
    If the version changes while we're opening the remaining tables,
1168
 
    we will have to back off, close all the tables opened-so-far,
1169
 
    and try to reopen them.
1170
 
 
1171
 
    Note-> refresh_version is currently changed only during FLUSH TABLES.
1172
 
  */
1173
 
  if (!open_tables)
1174
 
    version= refresh_version;
1175
 
  else if ((version != refresh_version) &&
1176
 
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
1177
 
  {
1178
 
    /* Someone did a refresh while thread was opening tables */
1179
 
    if (refresh)
1180
 
      *refresh= true;
1181
 
 
1182
 
    return NULL;
1183
 
  }
1184
 
 
1185
 
  /*
1186
 
    Before we test the global cache, we test our local session cache.
1187
 
  */
1188
 
  if (cached_table)
1189
 
  {
1190
 
    assert(false); /* Not implemented yet */
 
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);
1191
2374
  }
1192
2375
 
1193
2376
  /*
1195
2378
    this is the normal use case.
1196
2379
    Now we should:
1197
2380
    - try to find the table in the table cache.
1198
 
    - if one of the discovered Table instances is name-locked
1199
 
    (table->s->version == 0) back off -- we have to wait
1200
 
    until no one holds a name lock on the table.
1201
 
    - if there is no such Table in the name cache, read the table definition
 
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
1202
2386
    and insert it into the cache.
1203
2387
    We perform all of the above under LOCK_open which currently protects
1204
2388
    the open cache (also known as table cache) and table definitions stored
1205
2389
    on disk.
1206
2390
  */
1207
2391
 
1208
 
  pthread_mutex_lock(&LOCK_open); /* Lock for FLUSH TABLES for open table */
 
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 */
 
2408
    if (refresh)
 
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);
1209
2423
 
1210
2424
  /*
1211
2425
    Actually try to find the table in the open_cache.
1212
 
    The cache may contain several "Table" instances for the same
 
2426
    The cache may contain several "TABLE" instances for the same
1213
2427
    physical table. The instances that are currently "in use" by
1214
2428
    some thread have their "in_use" member != NULL.
1215
2429
    There is no good reason for having more than one entry in the
1217
2431
    an implicit "pending locks queue" - see
1218
2432
    wait_for_locked_table_names for details.
1219
2433
  */
1220
 
  for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
2434
  for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
1221
2435
                                  &state);
1222
2436
       table && table->in_use ;
1223
 
       table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
2437
       table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
1224
2438
                                 &state))
1225
2439
  {
 
2440
    DBUG_PRINT("tcache", ("in_use table: '%s'.'%s' 0x%lx", table->s->db.str,
 
2441
                          table->s->table_name.str, (long) table));
1226
2442
    /*
1227
2443
      Here we flush tables marked for flush.
1228
2444
      Normally, table->s->version contains the value of
1230
2446
      (re-)opened and added to the cache.
1231
2447
      If since then we did (or just started) FLUSH TABLES
1232
2448
      statement, refresh_version has been increased.
1233
 
      For "name-locked" Table instances, table->s->version is set
 
2449
      For "name-locked" TABLE instances, table->s->version is set
1234
2450
      to 0 (see lock_table_name for details).
1235
2451
      In case there is a pending FLUSH TABLES or a name lock, we
1236
2452
      need to back off and re-start opening tables.
1237
2453
      If we do not back off now, we may dead lock in case of lock
1238
2454
      order mismatch with some other thread:
1239
 
c1: name lock t1; -- sort of exclusive lock
1240
 
c2: open t2;      -- sort of shared lock
1241
 
c1: name lock t2; -- blocks
1242
 
c2: open t1; -- blocks
 
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
1243
2459
    */
1244
2460
    if (table->needs_reopen_or_name_lock())
1245
2461
    {
1246
 
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
 
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)
1247
2467
      {
1248
2468
        /* Force close at once after usage */
1249
 
        version= table->s->version;
 
2469
        thd->version= table->s->version;
1250
2470
        continue;
1251
2471
      }
1252
2472
 
1253
2473
      /* Avoid self-deadlocks by detecting self-dependencies. */
1254
 
      if (table->open_placeholder && table->in_use == this)
 
2474
      if (table->open_placeholder && table->in_use == thd)
1255
2475
      {
1256
 
        pthread_mutex_unlock(&LOCK_open);
 
2476
        VOID(pthread_mutex_unlock(&LOCK_open));
1257
2477
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
1258
 
        return NULL;
 
2478
        DBUG_RETURN(0);
1259
2479
      }
1260
2480
 
1261
2481
      /*
1266
2486
        table->db_stat == 0 signals wait_for_locked_table_names
1267
2487
        that the tables in question are not used any more. See
1268
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.
1269
2493
      */
1270
 
      close_old_data_files(false, false);
1271
 
 
 
2494
      close_old_data_files(thd,thd->open_tables,0,0);
1272
2495
      /*
1273
2496
        Back-off part 2: try to avoid "busy waiting" on the table:
1274
2497
        if the table is in use by some other thread, we suspend
1278
2501
        If 'old' table we met is in use by current thread we return
1279
2502
        without waiting since in this situation it's this thread
1280
2503
        which is responsible for broadcasting on COND_refresh
1281
 
        (and this was done already in Session::close_old_data_files()).
 
2504
        (and this was done already in close_old_data_files()).
1282
2505
        Good example of such situation is when we have statement
1283
2506
        that needs two instances of table and FLUSH TABLES comes
1284
2507
        after we open first instance but before we open second
1285
2508
        instance.
1286
2509
      */
1287
 
      if (table->in_use != this)
 
2510
      if (table->in_use != thd)
1288
2511
      {
1289
2512
        /* wait_for_conditionwill unlock LOCK_open for us */
1290
 
        wait_for_condition(&LOCK_open, &COND_refresh);
 
2513
        wait_for_condition(thd, &LOCK_open, &COND_refresh);
1291
2514
      }
1292
2515
      else
1293
2516
      {
1294
 
        pthread_mutex_unlock(&LOCK_open);
 
2517
        VOID(pthread_mutex_unlock(&LOCK_open));
1295
2518
      }
1296
2519
      /*
1297
2520
        There is a refresh in progress for this table.
1298
2521
        Signal the caller that it has to try again.
1299
2522
      */
1300
2523
      if (refresh)
1301
 
        *refresh= true;
1302
 
      return NULL;
 
2524
        *refresh=1;
 
2525
      DBUG_RETURN(0);
1303
2526
    }
1304
2527
  }
1305
2528
  if (table)
1306
2529
  {
 
2530
    DBUG_PRINT("tcache", ("unused table: '%s'.'%s' 0x%lx", table->s->db.str,
 
2531
                          table->s->table_name.str, (long) table));
1307
2532
    /* Unlink the table from "unused_tables" list. */
1308
2533
    if (table == unused_tables)
1309
 
    {  // First unused
1310
 
      unused_tables=unused_tables->next; // Remove from link
 
2534
    {                                           // First unused
 
2535
      unused_tables=unused_tables->next;        // Remove from link
1311
2536
      if (table == unused_tables)
1312
 
        unused_tables= NULL;
 
2537
        unused_tables=0;
1313
2538
    }
1314
 
    table->prev->next=table->next; /* Remove from unused list */
 
2539
    table->prev->next=table->next;              /* Remove from unused list */
1315
2540
    table->next->prev=table->prev;
1316
 
    table->in_use= this;
 
2541
    table->in_use= thd;
1317
2542
  }
1318
2543
  else
1319
2544
  {
1320
 
    /* Insert a new Table instance into the open cache */
 
2545
    /* Insert a new TABLE instance into the open cache */
1321
2546
    int error;
 
2547
    DBUG_PRINT("tcache", ("opening new table"));
1322
2548
    /* Free cache if too big */
1323
2549
    while (open_cache.records > table_cache_size && unused_tables)
1324
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
2550
      VOID(hash_delete(&open_cache,(uchar*) unused_tables)); /* purecov: tested */
1325
2551
 
1326
2552
    if (table_list->create)
1327
2553
    {
1328
 
      TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, NO_TMP_TABLE);
1329
 
 
1330
 
      if (plugin::StorageEngine::getTableDefinition(*this, lock_table_identifier) != EEXIST)
 
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)
1331
2563
      {
1332
2564
        /*
1333
2565
          Table to be created, so we need to create placeholder in table-cache.
1334
2566
        */
1335
 
        if (!(table= table_cache_insert_placeholder(key, key_length)))
 
2567
        if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
1336
2568
        {
1337
 
          pthread_mutex_unlock(&LOCK_open);
1338
 
          return NULL;
 
2569
          VOID(pthread_mutex_unlock(&LOCK_open));
 
2570
          DBUG_RETURN(NULL);
1339
2571
        }
1340
2572
        /*
1341
2573
          Link placeholder to the open tables list so it will be automatically
1342
2574
          removed once tables are closed. Also mark it so it won't be ignored
1343
2575
          by other trying to take name-lock.
1344
2576
        */
1345
 
        table->open_placeholder= true;
1346
 
        table->next= open_tables;
1347
 
        open_tables= table;
1348
 
        pthread_mutex_unlock(&LOCK_open);
1349
 
 
1350
 
        return table ;
 
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);
1351
2582
      }
1352
2583
      /* Table exists. Let us try to open it. */
1353
2584
    }
1354
2585
 
1355
2586
    /* make a new table */
1356
 
    table= (Table *)malloc(sizeof(Table));
1357
 
    if (table == NULL)
 
2587
    if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
1358
2588
    {
1359
 
      pthread_mutex_unlock(&LOCK_open);
1360
 
      return NULL;
 
2589
      VOID(pthread_mutex_unlock(&LOCK_open));
 
2590
      DBUG_RETURN(NULL);
1361
2591
    }
1362
2592
 
1363
 
    error= open_unireg_entry(this, table, table_list, alias, key, key_length);
1364
 
    if (error != 0)
1365
 
    {
1366
 
      free(table);
1367
 
      pthread_mutex_unlock(&LOCK_open);
1368
 
      return NULL;
1369
 
    }
1370
 
    my_hash_insert(&open_cache, (unsigned char*) table);
 
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));
1371
2612
  }
1372
2613
 
1373
 
  pthread_mutex_unlock(&LOCK_open);
 
2614
  check_unused();                               // Debugging call
 
2615
 
 
2616
  VOID(pthread_mutex_unlock(&LOCK_open));
1374
2617
  if (refresh)
1375
2618
  {
1376
 
    table->next= open_tables; /* Link into simple list */
1377
 
    open_tables=table;
 
2619
    table->next=thd->open_tables;               /* Link into simple list */
 
2620
    thd->open_tables=table;
1378
2621
  }
1379
 
  table->reginfo.lock_type= TL_READ; /* Assume read */
1380
 
 
1381
 
reset:
1382
 
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
1383
 
 
1384
 
  if (lex->need_correct_ident())
 
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())
1385
2628
    table->alias_name_used= my_strcasecmp(table_alias_charset,
1386
2629
                                          table->s->table_name.str, alias);
1387
2630
  /* Fix alias if table name changes */
1388
2631
  if (strcmp(table->alias, alias))
1389
2632
  {
1390
 
    uint32_t length=(uint32_t) strlen(alias)+1;
1391
 
    table->alias= (char*) realloc((char*) table->alias, length);
1392
 
    memcpy((void*) table->alias, alias, length);
 
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);
1393
2637
  }
1394
 
 
1395
2638
  /* These variables are also set in reopen_table() */
1396
 
  table->tablenr= current_tablenr++;
1397
 
  table->used_fields= 0;
1398
 
  table->const_table= 0;
1399
 
  table->null_row= false;
1400
 
  table->maybe_null= false;
1401
 
  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;
1402
2643
  table->status=STATUS_NO_RECORD;
1403
2644
  table->insert_values= 0;
 
2645
  table->fulltext_searched= 0;
 
2646
  table->file->ft_handler= 0;
1404
2647
  /* Catch wrong handling of the auto_increment_field_not_null. */
1405
 
  assert(!table->auto_increment_field_not_null);
1406
 
  table->auto_increment_field_not_null= false;
 
2648
  DBUG_ASSERT(!table->auto_increment_field_not_null);
 
2649
  table->auto_increment_field_not_null= FALSE;
1407
2650
  if (table->timestamp_field)
1408
2651
    table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
1409
2652
  table->pos_in_table_list= table_list;
1410
2653
  table->clear_column_bitmaps();
1411
 
  assert(table->key_read == 0);
1412
 
 
1413
 
  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);
1414
2671
}
1415
2672
 
1416
2673
 
1418
2675
  Reopen an table because the definition has changed.
1419
2676
 
1420
2677
  SYNOPSIS
1421
 
  reopen_table()
1422
 
  table Table object
 
2678
    reopen_table()
 
2679
    table       Table object
1423
2680
 
1424
2681
  NOTES
1425
 
  The data cursor for the table is already closed and the share is released
1426
 
  The table has a 'dummy' share that mainly contains database and table name.
 
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.
1427
2684
 
1428
 
  RETURN
1429
 
  0  ok
1430
 
  1  error. The old table object is not changed.
 
2685
 RETURN
 
2686
   0  ok
 
2687
   1  error. The old table object is not changed.
1431
2688
*/
1432
2689
 
1433
 
bool reopen_table(Table *table)
 
2690
bool reopen_table(TABLE *table)
1434
2691
{
1435
 
  Table tmp;
 
2692
  TABLE tmp;
1436
2693
  bool error= 1;
1437
2694
  Field **field;
1438
 
  uint32_t key,part;
1439
 
  TableList table_list;
1440
 
  Session *session= table->in_use;
 
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));
1441
2701
 
1442
 
  assert(table->s->ref_count == 0);
1443
 
  assert(!table->sort.io_cache);
 
2702
  DBUG_ASSERT(table->s->ref_count == 0);
 
2703
  DBUG_ASSERT(!table->sort.io_cache);
1444
2704
 
1445
2705
#ifdef EXTRA_DEBUG
1446
2706
  if (table->db_stat)
1447
 
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data Cursor in reopen_table"),
1448
 
                  table->alias);
 
2707
    sql_print_error("Table %s had a open data handler in reopen_table",
 
2708
                    table->alias);
1449
2709
#endif
 
2710
  bzero((char*) &table_list, sizeof(TABLE_LIST));
1450
2711
  table_list.db=         table->s->db.str;
1451
2712
  table_list.table_name= table->s->table_name.str;
1452
2713
  table_list.table=      table;
1453
2714
 
1454
 
  if (wait_for_locked_table_names(session, &table_list))
1455
 
    return true;                             // Thread was killed
 
2715
  if (wait_for_locked_table_names(thd, &table_list))
 
2716
    DBUG_RETURN(1);                             // Thread was killed
1456
2717
 
1457
 
  if (open_unireg_entry(session, &tmp, &table_list,
1458
 
                        table->alias,
 
2718
  if (open_unireg_entry(thd, &tmp, &table_list,
 
2719
                        table->alias,
1459
2720
                        table->s->table_cache_key.str,
1460
 
                        table->s->table_cache_key.length))
 
2721
                        table->s->table_cache_key.length,
 
2722
                        thd->mem_root, 0))
1461
2723
    goto end;
1462
2724
 
1463
2725
  /* This list copies variables set by open_table */
1468
2730
  tmp.maybe_null=       table->maybe_null;
1469
2731
  tmp.status=           table->status;
1470
2732
 
 
2733
  tmp.s->table_map_id=  table->s->table_map_id;
 
2734
 
1471
2735
  /* Get state */
1472
 
  tmp.in_use=           session;
 
2736
  tmp.in_use=           thd;
1473
2737
  tmp.reginfo.lock_type=table->reginfo.lock_type;
1474
2738
 
1475
2739
  /* Replace table in open list */
1476
2740
  tmp.next=             table->next;
1477
2741
  tmp.prev=             table->prev;
1478
2742
 
1479
 
  if (table->cursor)
1480
 
    table->closefrm(true);              // close cursor, free everything
 
2743
  if (table->file)
 
2744
    VOID(closefrm(table, 1));           // close file, free everything
1481
2745
 
1482
2746
  *table= tmp;
1483
2747
  table->default_column_bitmaps();
1484
 
  table->cursor->change_table_ptr(table, table->s);
 
2748
  table->file->change_table_ptr(table, table->s);
1485
2749
 
1486
 
  assert(table->alias != 0);
 
2750
  DBUG_ASSERT(table->alias != 0);
1487
2751
  for (field=table->field ; *field ; field++)
1488
2752
  {
1489
2753
    (*field)->table= (*field)->orig_table= table;
1494
2758
    for (part=0 ; part < table->key_info[key].usable_key_parts ; part++)
1495
2759
      table->key_info[key].key_part[part].field->table= table;
1496
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
  */
1497
2766
 
1498
2767
  broadcast_refresh();
1499
 
  error= false;
 
2768
  error=0;
1500
2769
 
1501
 
end:
1502
 
  return(error);
 
2770
 end:
 
2771
  DBUG_RETURN(error);
1503
2772
}
1504
2773
 
1505
2774
 
1506
2775
/**
1507
 
  Close all instances of a table open by this thread and replace
1508
 
  them with exclusive name-locks.
1509
 
 
1510
 
  @param session        Thread context
1511
 
  @param db         Database name for the table to be closed
1512
 
  @param table_name Name of the table to be closed
1513
 
 
1514
 
  @note This function assumes that if we are not under LOCK TABLES,
1515
 
  then there is only one table open and locked. This means that
1516
 
  the function probably has to be adjusted before it can be used
1517
 
  anywhere outside ALTER Table.
1518
 
 
1519
 
  @note Must not use TableShare::table_name/db of the table being closed,
1520
 
  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.
1521
2790
*/
1522
2791
 
1523
 
void Session::close_data_files_and_morph_locks(const char *new_db, const char *new_table_name)
 
2792
void close_data_files_and_morph_locks(THD *thd, const char *db,
 
2793
                                      const char *table_name)
1524
2794
{
1525
 
  Table *table;
1526
 
 
1527
 
  safe_mutex_assert_owner(&LOCK_open); /* Adjust locks at the end of ALTER TABLEL */
1528
 
 
1529
 
  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)
1530
2801
  {
1531
2802
    /*
1532
2803
      If we are not under LOCK TABLES we should have only one table
1533
2804
      open and locked so it makes sense to remove the lock at once.
1534
2805
    */
1535
 
    mysql_unlock_tables(this, lock);
1536
 
    lock= 0;
 
2806
    mysql_unlock_tables(thd, thd->lock);
 
2807
    thd->lock= 0;
1537
2808
  }
1538
2809
 
1539
2810
  /*
1540
2811
    Note that open table list may contain a name-lock placeholder
1541
 
    for target table name if we process ALTER Table ... RENAME.
 
2812
    for target table name if we process ALTER TABLE ... RENAME.
1542
2813
    So loop below makes sense even if we are not under LOCK TABLES.
1543
2814
  */
1544
 
  for (table= open_tables; table ; table=table->next)
 
2815
  for (table=thd->open_tables; table ; table=table->next)
1545
2816
  {
1546
 
    if (!strcmp(table->s->table_name.str, new_table_name) &&
1547
 
        !strcmp(table->s->db.str, new_db))
 
2817
    if (!strcmp(table->s->table_name.str, table_name) &&
 
2818
        !strcmp(table->s->db.str, db))
1548
2819
    {
1549
 
      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;
1550
2825
      close_handle_and_leave_table_as_lock(table);
1551
2826
    }
1552
2827
  }
 
2828
  DBUG_VOID_RETURN;
1553
2829
}
1554
2830
 
1555
2831
 
1556
2832
/**
1557
 
  Reopen all tables with closed data files.
1558
 
 
1559
 
  @param session         Thread context
1560
 
  @param get_locks   Should we get locks after reopening tables ?
1561
 
  @param mark_share_as_old  Mark share as old to protect from a impending
1562
 
  global read lock.
1563
 
 
1564
 
  @note Since this function can't properly handle prelocking and
1565
 
  create placeholders it should be used in very special
1566
 
  situations like FLUSH TABLES or ALTER Table. In general
1567
 
  case one should just repeat open_tables()/lock_tables()
1568
 
  combination when one needs tables to be reopened (for
1569
 
  example see openTablesLock()).
1570
 
 
1571
 
  @note One should have lock on LOCK_open when calling this.
1572
 
 
1573
 
  @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.
1574
2850
*/
1575
2851
 
1576
 
bool Session::reopen_tables(bool get_locks, bool mark_share_as_old)
 
2852
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
1577
2853
{
1578
 
  Table *table,*next,**prev;
1579
 
  Table **tables,**tables_ptr;                  // For locks
 
2854
  TABLE *table,*next,**prev;
 
2855
  TABLE **tables,**tables_ptr;                  // For locks
1580
2856
  bool error=0, not_used;
1581
 
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1582
 
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1583
 
    DRIZZLE_LOCK_IGNORE_FLUSH;
1584
 
 
1585
 
  if (open_tables == NULL)
1586
 
    return false;
 
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);
1587
2865
 
1588
2866
  safe_mutex_assert_owner(&LOCK_open);
1589
2867
  if (get_locks)
1592
2870
      The ptr is checked later
1593
2871
      Do not handle locks of MERGE children.
1594
2872
    */
1595
 
    uint32_t opens= 0;
1596
 
 
1597
 
    for (table= open_tables; table ; table=table->next)
 
2873
    uint opens=0;
 
2874
    for (table= thd->open_tables; table ; table=table->next)
1598
2875
      opens++;
1599
 
    tables= new Table *[opens];
 
2876
    DBUG_PRINT("tcache", ("open tables to lock: %u", opens));
 
2877
    tables= (TABLE**) my_alloca(sizeof(TABLE*)*opens);
1600
2878
  }
1601
2879
  else
1602
 
    tables= &open_tables;
 
2880
    tables= &thd->open_tables;
1603
2881
  tables_ptr =tables;
1604
2882
 
1605
 
  prev= &open_tables;
1606
 
  for (table= open_tables; table ; table=next)
 
2883
  prev= &thd->open_tables;
 
2884
  for (table=thd->open_tables; table ; table=next)
1607
2885
  {
1608
 
    uint32_t db_stat= table->db_stat;
1609
 
    next= table->next;
 
2886
    uint db_stat=table->db_stat;
 
2887
    next=table->next;
1610
2888
    if (!tables || (!db_stat && reopen_table(table)))
1611
2889
    {
1612
2890
      my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1613
 
      hash_delete(&open_cache,(unsigned char*) table);
1614
 
      error= 1;
 
2891
      VOID(hash_delete(&open_cache,(uchar*) table));
 
2892
      error=1;
1615
2893
    }
1616
2894
    else
1617
2895
    {
1619
2897
      prev= &table->next;
1620
2898
      /* Do not handle locks of MERGE children. */
1621
2899
      if (get_locks && !db_stat)
1622
 
        *tables_ptr++= table;                   // need new lock on this
 
2900
        *tables_ptr++= table;                   // need new lock on this
1623
2901
      if (mark_share_as_old)
1624
2902
      {
1625
 
        table->s->version= 0;
1626
 
        table->open_placeholder= false;
 
2903
        table->s->version=0;
 
2904
        table->open_placeholder= 0;
1627
2905
      }
1628
2906
    }
1629
2907
  }
1630
2908
  *prev=0;
 
2909
  DBUG_PRINT("tcache", ("open tables to lock: %u",
 
2910
                        (uint) (tables_ptr - tables)));
1631
2911
  if (tables != tables_ptr)                     // Should we get back old locks
1632
2912
  {
1633
 
    DRIZZLE_LOCK *local_lock;
 
2913
    MYSQL_LOCK *lock;
1634
2914
    /*
1635
2915
      We should always get these locks. Anyway, we must not go into
1636
2916
      wait_for_tables() as it tries to acquire LOCK_open, which is
1637
2917
      already locked.
1638
2918
    */
1639
 
    some_tables_deleted= false;
1640
 
 
1641
 
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
2919
    thd->some_tables_deleted=0;
 
2920
    if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
1642
2921
                                 flags, &not_used)))
1643
2922
    {
1644
 
      /* unused */
 
2923
      thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
1645
2924
    }
1646
2925
    else
1647
2926
    {
1654
2933
      error=1;
1655
2934
    }
1656
2935
  }
1657
 
 
1658
2936
  if (get_locks && tables)
1659
 
    delete [] tables;
1660
 
 
 
2937
  {
 
2938
    my_afree((uchar*) tables);
 
2939
  }
1661
2940
  broadcast_refresh();
1662
 
 
1663
 
  return(error);
 
2941
  DBUG_RETURN(error);
1664
2942
}
1665
2943
 
1666
2944
 
1667
2945
/**
1668
 
  Close handlers for tables in list, but leave the Table structure
1669
 
  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.
1670
2948
 
1671
 
  @param session           Thread context
1672
 
  @param table         Head of the list of Table objects
1673
 
  @param morph_locks   true  - remove locks which we have on tables being closed
1674
 
  but ensure that no DML or DDL will sneak in before
1675
 
  we will re-open the table (i.e. temporarily morph
1676
 
  our table-level locks into name-locks).
1677
 
  false - otherwise
1678
 
  @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?
1679
2957
*/
1680
2958
 
1681
 
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)
1682
2961
{
1683
2962
  bool found= send_refresh;
1684
 
 
1685
 
  Table *table= open_tables;
 
2963
  DBUG_ENTER("close_old_data_files");
1686
2964
 
1687
2965
  for (; table ; table=table->next)
1688
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));
1689
2972
    /*
1690
2973
      Reopen marked for flush.
1691
2974
    */
1694
2977
      found=1;
1695
2978
      if (table->db_stat)
1696
2979
      {
1697
 
        if (morph_locks)
1698
 
        {
1699
 
          Table *ulcktbl= table;
 
2980
        if (morph_locks)
 
2981
        {
 
2982
          TABLE *ulcktbl= table;
1700
2983
          if (ulcktbl->lock_count)
1701
2984
          {
1702
2985
            /*
1705
2988
              lock on it. This will also give them a chance to close their
1706
2989
              instances of this table.
1707
2990
            */
1708
 
            mysql_lock_abort(this, ulcktbl);
1709
 
            mysql_lock_remove(this, ulcktbl);
 
2991
            mysql_lock_abort(thd, ulcktbl, TRUE);
 
2992
            mysql_lock_remove(thd, thd->locked_tables, ulcktbl, TRUE);
1710
2993
            ulcktbl->lock_count= 0;
1711
2994
          }
1712
2995
          if ((ulcktbl != table) && ulcktbl->db_stat)
1717
3000
              as a placeholder. When this happens, do not clear the
1718
3001
              placeholder flag. See the branch below ("***").
1719
3002
            */
1720
 
            ulcktbl->open_placeholder= true;
 
3003
            ulcktbl->open_placeholder= 1;
1721
3004
            close_handle_and_leave_table_as_lock(ulcktbl);
1722
3005
          }
1723
3006
          /*
1724
3007
            We want to protect the table from concurrent DDL operations
1725
 
            (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.
1726
3009
          */
1727
 
          table->open_placeholder= true;
1728
 
        }
 
3010
          table->open_placeholder= 1;
 
3011
        }
1729
3012
        close_handle_and_leave_table_as_lock(table);
1730
3013
      }
1731
3014
      else if (table->open_placeholder && !morph_locks)
1734
3017
          We come here only in close-for-back-off scenario. So we have to
1735
3018
          "close" create placeholder here to avoid deadlocks (for example,
1736
3019
          in case of concurrent execution of CREATE TABLE t1 SELECT * FROM t2
1737
 
          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
1738
3021
          probably want to let it stay.
1739
3022
 
1740
3023
          Note "***": We must not enter this branch if the placeholder
1741
3024
          flag has been set because of a former close through a child.
1742
3025
          See above the comment that refers to this note.
1743
3026
        */
1744
 
        table->open_placeholder= false;
 
3027
        table->open_placeholder= 0;
1745
3028
      }
1746
3029
    }
1747
3030
  }
1748
3031
  if (found)
1749
3032
    broadcast_refresh();
 
3033
  DBUG_VOID_RETURN;
1750
3034
}
1751
3035
 
1752
3036
 
1756
3040
  if the table is closed
1757
3041
*/
1758
3042
 
1759
 
bool table_is_used(Table *table, bool wait_for_name_lock)
 
3043
bool table_is_used(TABLE *table, bool wait_for_name_lock)
1760
3044
{
 
3045
  DBUG_ENTER("table_is_used");
1761
3046
  do
1762
3047
  {
1763
3048
    char *key= table->s->table_cache_key.str;
1764
 
    uint32_t key_length= table->s->table_cache_key.length;
 
3049
    uint key_length= table->s->table_cache_key.length;
1765
3050
 
 
3051
    DBUG_PRINT("loop", ("table_name: %s", table->alias));
1766
3052
    HASH_SEARCH_STATE state;
1767
 
    for (Table *search= (Table*) hash_first(&open_cache, (unsigned char*) key,
1768
 
                                            key_length, &state);
1769
 
         search ;
1770
 
         search= (Table*) hash_next(&open_cache, (unsigned char*) key,
 
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,
1771
3057
                                    key_length, &state))
1772
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));
1773
3066
      if (search->in_use == table->in_use)
1774
3067
        continue;                               // Name locked by this thread
1775
3068
      /*
1781
3074
      */
1782
3075
      if ( (search->locked_by_name && wait_for_name_lock) ||
1783
3076
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
1784
 
        return 1;
 
3077
        DBUG_RETURN(1);
1785
3078
    }
1786
3079
  } while ((table=table->next));
1787
 
  return 0;
 
3080
  DBUG_RETURN(0);
1788
3081
}
1789
3082
 
1790
3083
 
1791
3084
/* Wait until all used tables are refreshed */
1792
3085
 
1793
 
bool wait_for_tables(Session *session)
 
3086
bool wait_for_tables(THD *thd)
1794
3087
{
1795
3088
  bool result;
 
3089
  DBUG_ENTER("wait_for_tables");
1796
3090
 
1797
 
  session->set_proc_info("Waiting for tables");
1798
 
  pthread_mutex_lock(&LOCK_open); /* Lock for all tables to be refreshed */
1799
 
  while (!session->killed)
 
3091
  thd_proc_info(thd, "Waiting for tables");
 
3092
  pthread_mutex_lock(&LOCK_open);
 
3093
  while (!thd->killed)
1800
3094
  {
1801
 
    session->some_tables_deleted= false;
1802
 
    session->close_old_data_files(false, dropping_tables != 0);
1803
 
    if (!table_is_used(session->open_tables, 1))
 
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))
1804
3099
      break;
1805
3100
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
1806
3101
  }
1807
 
  if (session->killed)
1808
 
    result= true;                                       // aborted
 
3102
  if (thd->killed)
 
3103
    result= 1;                                  // aborted
1809
3104
  else
1810
3105
  {
1811
3106
    /* Now we can open all tables without any interference */
1812
 
    session->set_proc_info("Reopen tables");
1813
 
    session->version= refresh_version;
1814
 
    result= session->reopen_tables(false, false);
 
3107
    thd_proc_info(thd, "Reopen tables");
 
3108
    thd->version= refresh_version;
 
3109
    result=reopen_tables(thd,0,0);
1815
3110
  }
1816
3111
  pthread_mutex_unlock(&LOCK_open);
1817
 
  session->set_proc_info(0);
1818
 
 
1819
 
  return result;
 
3112
  thd_proc_info(thd, 0);
 
3113
  DBUG_RETURN(result);
1820
3114
}
1821
3115
 
1822
3116
 
1824
3118
  drop tables from locked list
1825
3119
 
1826
3120
  SYNOPSIS
1827
 
  drop_locked_tables()
1828
 
  session                       Thread thandler
1829
 
  db                    Database
1830
 
  table_name            Table name
 
3121
    drop_locked_tables()
 
3122
    thd                 Thread thandler
 
3123
    db                  Database
 
3124
    table_name          Table name
1831
3125
 
1832
3126
  INFORMATION
1833
 
  This is only called on drop tables
 
3127
    This is only called on drop tables
1834
3128
 
1835
 
  The Table object for the dropped table is unlocked but still kept around
1836
 
  as a name lock, which means that the table will be available for other
1837
 
  thread as soon as we call unlock_table_names().
1838
 
  If there is multiple copies of the table locked, all copies except
1839
 
  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.
1840
3134
 
1841
3135
  RETURN
1842
 
#    If table existed, return table
1843
 
0        Table was not locked
 
3136
    #    If table existed, return table
 
3137
    0    Table was not locked
1844
3138
*/
1845
3139
 
1846
3140
 
1847
 
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
 
3141
TABLE *drop_locked_tables(THD *thd,const char *db, const char *table_name)
1848
3142
{
1849
 
  Table *table,*next,**prev, *found= 0;
1850
 
  prev= &session->open_tables;
 
3143
  TABLE *table,*next,**prev, *found= 0;
 
3144
  prev= &thd->open_tables;
 
3145
  DBUG_ENTER("drop_locked_tables");
1851
3146
 
1852
3147
  /*
1853
3148
    Note that we need to hold LOCK_open while changing the
1856
3151
    Closing a MERGE child before the parent would be fatal if the
1857
3152
    other thread tries to abort the MERGE lock in between.
1858
3153
  */
1859
 
  for (table= session->open_tables; table ; table=next)
 
3154
  for (table= thd->open_tables; table ; table=next)
1860
3155
  {
1861
3156
    next=table->next;
1862
3157
    if (!strcmp(table->s->table_name.str, table_name) &&
1863
 
        !strcmp(table->s->db.str, db))
 
3158
        !strcmp(table->s->db.str, db))
1864
3159
    {
1865
 
      mysql_lock_remove(session, table);
 
3160
      mysql_lock_remove(thd, thd->locked_tables, table, TRUE);
1866
3161
 
1867
3162
      if (!found)
1868
3163
      {
1871
3166
        if (table->db_stat)
1872
3167
        {
1873
3168
          table->db_stat= 0;
1874
 
          table->cursor->close();
 
3169
          table->file->close();
1875
3170
        }
1876
3171
      }
1877
3172
      else
1878
3173
      {
1879
3174
        /* We already have a name lock, remove copy */
1880
 
        hash_delete(&open_cache,(unsigned char*) table);
 
3175
        VOID(hash_delete(&open_cache,(uchar*) table));
1881
3176
      }
1882
3177
    }
1883
3178
    else
1889
3184
  *prev=0;
1890
3185
  if (found)
1891
3186
    broadcast_refresh();
1892
 
 
1893
 
  return(found);
 
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);
1894
3193
}
1895
3194
 
1896
3195
 
1897
3196
/*
1898
 
  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
1899
3198
  done on the table, change the lock type to a lock that will abort all
1900
3199
  other threads trying to get the lock.
1901
3200
*/
1902
3201
 
1903
 
void abort_locked_tables(Session *session,const char *db, const char *table_name)
 
3202
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
1904
3203
{
1905
 
  Table *table;
1906
 
  for (table= session->open_tables; table ; table= table->next)
 
3204
  TABLE *table;
 
3205
  for (table= thd->open_tables; table ; table= table->next)
1907
3206
  {
1908
3207
    if (!strcmp(table->s->table_name.str, table_name) &&
1909
 
        !strcmp(table->s->db.str, db))
 
3208
        !strcmp(table->s->db.str, db))
1910
3209
    {
1911
3210
      /* If MERGE child, forward lock handling to parent. */
1912
 
      mysql_lock_abort(session, table);
 
3211
      mysql_lock_abort(thd, table, TRUE);
1913
3212
      break;
1914
3213
    }
1915
3214
  }
1916
3215
}
1917
3216
 
1918
 
/*
1919
 
  Load a table definition from cursor and open unireg table
 
3217
 
 
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
1920
3275
 
1921
3276
  SYNOPSIS
1922
 
  open_unireg_entry()
1923
 
  session                       Thread handle
1924
 
  entry         Store open table definition here
1925
 
  table_list            TableList with db, table_name
1926
 
  alias         Alias name
1927
 
  cache_key             Key for share_cache
1928
 
  cache_key_length      length of cache_key
 
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()
1929
3287
 
1930
3288
  NOTES
1931
 
  Extra argument for open is taken from session->open_options
1932
 
  One must have a lock on LOCK_open when calling this function
 
3289
   Extra argument for open is taken from thd->open_options
 
3290
   One must have a lock on LOCK_open when calling this function
1933
3291
 
1934
3292
  RETURN
1935
 
  0     ok
1936
 
#       Error
 
3293
    0   ok
 
3294
    #   Error
1937
3295
*/
1938
3296
 
1939
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
3297
static int open_unireg_entry(THD *thd, TABLE *entry, TABLE_LIST *table_list,
1940
3298
                             const char *alias,
1941
 
                             char *cache_key, uint32_t cache_key_length)
 
3299
                             char *cache_key, uint cache_key_length,
 
3300
                             MEM_ROOT *mem_root, uint flags)
1942
3301
{
1943
3302
  int error;
1944
 
  TableShare *share;
1945
 
  uint32_t discover_retry_count= 0;
 
3303
  TABLE_SHARE *share;
 
3304
  uint discover_retry_count= 0;
 
3305
  DBUG_ENTER("open_unireg_entry");
1946
3306
 
1947
3307
  safe_mutex_assert_owner(&LOCK_open);
1948
3308
retry:
1949
 
  if (!(share= TableShare::getShare(session, table_list, cache_key,
1950
 
                                    cache_key_length,
1951
 
                                    table_list->i_s_requested_object,
1952
 
                                    &error)))
1953
 
    return 1;
 
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);
1954
3315
 
1955
 
  while ((error= open_table_from_share(session, share, alias,
1956
 
                                       (uint32_t) (HA_OPEN_KEYFILE |
1957
 
                                                   HA_OPEN_RNDFILE |
1958
 
                                                   HA_GET_INDEX |
1959
 
                                                   HA_TRY_READ_ONLY),
1960
 
                                       session->open_options, entry)))
 
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)))
1961
3324
  {
1962
3325
    if (error == 7)                             // Table def changed
1963
3326
    {
1966
3329
        goto err;
1967
3330
 
1968
3331
      /*
1969
 
        TODO->
 
3332
        TODO:
1970
3333
        Here we should wait until all threads has released the table.
1971
3334
        For now we do one retry. This may cause a deadlock if there
1972
3335
        is other threads waiting for other tables used by this thread.
1973
 
 
 
3336
        
1974
3337
        Proper fix would be to if the second retry failed:
1975
3338
        - Mark that table def changed
1976
3339
        - Return from open table
1978
3341
        - Start waiting that the share is released
1979
3342
        - Retry by opening all tables again
1980
3343
      */
1981
 
 
 
3344
      if (ha_create_table_from_engine(thd, table_list->db,
 
3345
                                      table_list->table_name))
 
3346
        goto err;
1982
3347
      /*
1983
3348
        TO BE FIXED
1984
3349
        To avoid deadlock, only wait for release if no one else is
1987
3352
      if (share->ref_count != 1)
1988
3353
        goto err;
1989
3354
      /* Free share and wait until it's released by all threads */
1990
 
      TableShare::release(share);
1991
 
 
1992
 
      if (!session->killed)
 
3355
      release_table_share(share, RELEASE_WAIT_FOR_DROP);
 
3356
      if (!thd->killed)
1993
3357
      {
1994
 
        drizzle_reset_errors(session, 1);         // Clear warnings
1995
 
        session->clear_error();                 // Clear error message
 
3358
        mysql_reset_errors(thd, 1);         // Clear warnings
 
3359
        thd->clear_error();                 // Clear error message
1996
3360
        goto retry;
1997
3361
      }
1998
 
      return 1;
 
3362
      DBUG_RETURN(1);
1999
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
   }
2000
3407
 
2001
 
    goto err;
 
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
    }
2002
3442
  }
2003
 
 
2004
 
  return 0;
 
3443
  DBUG_RETURN(0);
2005
3444
 
2006
3445
err:
2007
 
  TableShare::release(share);
2008
 
 
2009
 
  return 1;
 
3446
  release_table_share(share, RELEASE_NORMAL);
 
3447
  DBUG_RETURN(1);
2010
3448
}
2011
3449
 
2012
3450
 
2014
3452
  Open all tables in list
2015
3453
 
2016
3454
  SYNOPSIS
2017
 
  open_tables()
2018
 
  session - thread Cursor
2019
 
  start - list of tables in/out
2020
 
  counter - number of opened tables will be return using this parameter
2021
 
  flags   - bitmap of flags to modify how the tables will be open:
2022
 
  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
2023
 
  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.
2024
3462
 
2025
3463
  NOTE
2026
 
  Unless we are already in prelocked mode, this function will also precache
2027
 
  all SP/SFs explicitly or implicitly (via views and triggers) used by the
2028
 
  query and add tables needed for their execution to table list. If resulting
2029
 
  tables list will be non empty it will mark query as requiring precaching.
2030
 
  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.
2031
3469
 
2032
 
  If query for which we are opening tables is already marked as requiring
2033
 
  prelocking it won't do such precaching and will simply reuse table list
2034
 
  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.
2035
3473
 
2036
3474
  RETURN
2037
 
  0  - OK
2038
 
  -1 - error
 
3475
    0  - OK
 
3476
    -1 - error
2039
3477
*/
2040
3478
 
2041
 
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)
2042
3480
{
2043
 
  TableList *tables= NULL;
 
3481
  TABLE_LIST *tables= NULL;
2044
3482
  bool refresh;
2045
 
  int result= 0;
 
3483
  int result=0;
 
3484
  MEM_ROOT new_frm_mem;
2046
3485
  /* Also used for indicating that prelocking is need */
2047
3486
  bool safe_to_ignore_table;
2048
3487
 
2049
 
  current_tablenr= 0;
2050
 
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:
2051
3497
  *counter= 0;
2052
 
  set_proc_info("Opening tables");
 
3498
  thd_proc_info(thd, "Opening tables");
2053
3499
 
2054
3500
  /*
2055
3501
    For every table in the list of tables to open, try to find or open
2057
3503
  */
2058
3504
  for (tables= *start; tables ;tables= tables->next_global)
2059
3505
  {
2060
 
    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;
2061
3510
 
2062
3511
    /*
2063
3512
      Ignore placeholders for derived tables. After derived tables
2064
3513
      processing, link to created temporary table will be put here.
2065
3514
      If this is derived table for view then we still want to process
2066
3515
      routines used by this view.
2067
 
    */
 
3516
     */
2068
3517
    if (tables->derived)
2069
3518
    {
2070
3519
      continue;
2071
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
    }
2072
3533
    (*counter)++;
2073
3534
 
2074
3535
    /*
2075
3536
      Not a placeholder: must be a base table or a view, and the table is
2076
3537
      not opened yet. Try to open the table.
2077
3538
    */
2078
 
    if (tables->table == NULL)
2079
 
      tables->table= openTable(tables, &refresh, flags);
2080
 
 
2081
 
    if (tables->table == NULL)
2082
 
    {
 
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
 
2083
3552
      if (refresh)                              // Refresh in progress
2084
3553
      {
2085
3554
        /*
2096
3565
          we pretend that we have finished calculation which we were doing
2097
3566
          currently.
2098
3567
        */
2099
 
        close_tables_for_reopen(start);
2100
 
        goto restart;
 
3568
        close_tables_for_reopen(thd, start);
 
3569
        goto restart;
2101
3570
      }
2102
3571
 
2103
3572
      if (safe_to_ignore_table)
 
3573
      {
 
3574
        DBUG_PRINT("info", ("open_table: ignoring table '%s'.'%s'",
 
3575
                            tables->db, tables->alias));
2104
3576
        continue;
 
3577
      }
2105
3578
 
2106
3579
      result= -1;                               // Fatal error
2107
3580
      break;
2108
3581
    }
2109
 
    if (tables->lock_type != TL_UNLOCK)
 
3582
    if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
2110
3583
    {
2111
3584
      if (tables->lock_type == TL_WRITE_DEFAULT)
2112
 
        tables->table->reginfo.lock_type= update_lock_default;
 
3585
        tables->table->reginfo.lock_type= thd->update_lock_default;
2113
3586
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
2114
3587
        tables->table->reginfo.lock_type= tables->lock_type;
2115
3588
    }
2116
3589
  }
2117
3590
 
2118
 
  set_proc_info(0);
 
3591
  thd_proc_info(thd, 0);
 
3592
  free_root(&new_frm_mem, MYF(0));              // Free pre-alloced block
2119
3593
 
2120
3594
  if (result && tables)
2121
3595
  {
2122
3596
    /*
2123
3597
      Some functions determine success as (tables->table != NULL).
2124
 
      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.
2125
3600
    */
 
3601
    if (tables->parent_l)
 
3602
      tables->parent_l->table= NULL;
2126
3603
    tables->table= NULL;
2127
3604
  }
2128
 
 
2129
 
  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);
2130
3699
}
2131
3700
 
2132
3701
 
2134
3703
  Open and lock one table
2135
3704
 
2136
3705
  SYNOPSIS
2137
 
  openTableLock()
2138
 
  session                       Thread Cursor
2139
 
  table_list            Table to open is first table in this list
2140
 
  lock_type             Lock to use for open
2141
 
  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
2142
3711
 
2143
3712
  NOTE
2144
 
  This function don't do anything like SP/SF/views/triggers analysis done
2145
 
  in open_tables(). It is intended for opening of only one concrete table.
2146
 
  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.
2147
3716
 
2148
3717
  RETURN VALUES
2149
 
  table         Opened table
2150
 
  0                     Error
2151
 
 
2152
 
  If ok, the following are also set:
2153
 
  table_list->lock_type         lock_type
2154
 
  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
2155
3724
*/
2156
3725
 
2157
 
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)
2158
3728
{
2159
 
  Table *table;
 
3729
  TABLE *table;
2160
3730
  bool refresh;
 
3731
  DBUG_ENTER("open_ltable");
2161
3732
 
2162
 
  set_proc_info("Opening table");
2163
 
  current_tablenr= 0;
2164
 
  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)) &&
2165
3738
         refresh)
2166
3739
    ;
2167
3740
 
2169
3742
  {
2170
3743
    table_list->lock_type= lock_type;
2171
3744
    table_list->table=     table;
2172
 
 
2173
 
    assert(lock == 0);  // You must lock everything at once
2174
 
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
2175
 
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
2176
 
        table= 0;
2177
 
  }
2178
 
 
2179
 
  set_proc_info(0);
2180
 
 
2181
 
  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;
2182
3991
}
2183
3992
 
2184
3993
/*
2185
3994
  Lock all tables in list
2186
3995
 
2187
3996
  SYNOPSIS
2188
 
  lock_tables()
2189
 
  session                       Thread Cursor
2190
 
  tables                Tables to lock
2191
 
  count         Number of opened tables
2192
 
  need_reopen         Out parameter which if true indicates that some
2193
 
  tables were dropped or altered during this call
2194
 
  and therefore invoker should reopen tables and
2195
 
  try to lock them once again (in this case
2196
 
  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).
2197
4006
 
2198
4007
  NOTES
2199
 
  You can't call lock_tables twice, as this would break the dead-lock-free
2200
 
  handling thr_lock gives us.  You most always get all needed locks at
2201
 
  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.
2202
4011
 
2203
 
  If query for which we are calling this function marked as requring
2204
 
  prelocking, this function will do implicit LOCK TABLES and change
2205
 
  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.
2206
4015
 
2207
4016
  RETURN VALUES
2208
 
  0     ok
2209
 
  -1    Error
 
4017
   0    ok
 
4018
   -1   Error
2210
4019
*/
2211
4020
 
2212
 
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)
2213
4022
{
2214
 
  TableList *table;
2215
 
  Session *session= this;
 
4023
  TABLE_LIST *table;
2216
4024
 
 
4025
  DBUG_ENTER("lock_tables");
2217
4026
  /*
2218
4027
    We can't meet statement requiring prelocking if we already
2219
4028
    in prelocked mode.
2220
4029
  */
2221
 
  *need_reopen= false;
2222
 
 
2223
 
  if (tables == NULL)
2224
 
    return 0;
2225
 
 
2226
 
  assert(session->lock == 0);   // You must lock everything at once
2227
 
  Table **start,**ptr;
2228
 
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
2229
 
 
2230
 
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
2231
 
    return -1;
2232
 
  for (table= tables; table; table= table->next_global)
2233
 
  {
2234
 
    if (!table->placeholder())
2235
 
      *(ptr++)= table->table;
2236
 
  }
2237
 
 
2238
 
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
2239
 
                                         lock_flag, need_reopen)))
2240
 
  {
2241
 
    return -1;
2242
 
  }
2243
 
 
2244
 
  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);
2245
4105
}
2246
4106
 
2247
4107
 
2249
4109
  Open a single table without table caching and don't set it in open_list
2250
4110
 
2251
4111
  SYNPOSIS
2252
 
  open_temporary_table()
2253
 
  session                 Thread object
2254
 
  path    Path (without .frm)
2255
 
  db              database
2256
 
  table_name      Table name
2257
 
  link_in_list  1 if table should be linked into session->temporary_tables
2258
 
 
2259
 
NOTES:
2260
 
Used by alter_table to open a temporary table and when creating
2261
 
a temporary table with CREATE TEMPORARY ...
2262
 
 
2263
 
RETURN
2264
 
0  Error
2265
 
#  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
2266
4126
*/
2267
4127
 
2268
 
Table *Session::open_temporary_table(TableIdentifier &identifier,
2269
 
                                     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)
2270
4131
{
2271
 
  Table *new_tmp_table;
2272
 
  TableShare *share;
 
4132
  TABLE *tmp_table;
 
4133
  TABLE_SHARE *share;
2273
4134
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
2274
 
  uint32_t key_length, path_length;
2275
 
  TableList table_list;
 
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));
2276
4143
 
2277
 
  table_list.db=         (char*) identifier.getDBName();
2278
 
  table_list.table_name= (char*) identifier.getTableName();
 
4144
  table_list.db=         (char*) db;
 
4145
  table_list.table_name= (char*) table_name;
2279
4146
  /* Create the cache_key for temporary tables */
2280
 
  key_length= table_list.create_table_def_key(cache_key);
2281
 
  path_length= strlen(identifier.getPath());
2282
 
 
2283
 
  if (!(new_tmp_table= (Table*) malloc(sizeof(*new_tmp_table) + sizeof(*share) +
2284
 
                                       path_length + 1 + key_length)))
2285
 
    return NULL;
2286
 
 
2287
 
  share= (TableShare*) (new_tmp_table+1);
 
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);
2288
4155
  tmp_path= (char*) (share+1);
2289
 
  saved_cache_key= strcpy(tmp_path, identifier.getPath())+path_length+1;
 
4156
  saved_cache_key= strmov(tmp_path, path)+1;
2290
4157
  memcpy(saved_cache_key, cache_key, key_length);
2291
4158
 
2292
 
  share->init(saved_cache_key, key_length, strchr(saved_cache_key, '\0')+1, tmp_path);
 
4159
  init_tmp_table_share(thd, share, saved_cache_key, key_length,
 
4160
                       strend(saved_cache_key)+1, tmp_path);
2293
4161
 
2294
 
  /*
2295
 
    First open the share, and then open the table from the share we just opened.
2296
 
  */
2297
 
  if (open_table_def(*this, share) ||
2298
 
      open_table_from_share(this, share, identifier.getTableName(),
2299
 
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2300
 
                                        HA_GET_INDEX),
 
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),
2301
4171
                            ha_open_options,
2302
 
                            new_tmp_table))
 
4172
                            tmp_table, open_mode))
2303
4173
  {
2304
4174
    /* No need to lock share->mutex as this is not needed for tmp tables */
2305
 
    share->free_table_share();
2306
 
    free((char*) new_tmp_table);
2307
 
    return 0;
 
4175
    free_table_share(share);
 
4176
    my_free((char*) tmp_table,MYF(0));
 
4177
    DBUG_RETURN(0);
2308
4178
  }
2309
4179
 
2310
 
  new_tmp_table->reginfo.lock_type= TL_WRITE;    // Simulate locked
2311
 
  share->tmp_table= TEMP_TABLE;
 
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);
2312
4192
 
2313
4193
  if (link_in_list)
2314
4194
  {
2315
4195
    /* growing temp list at the head */
2316
 
    new_tmp_table->next= this->temporary_tables;
2317
 
    if (new_tmp_table->next)
2318
 
      new_tmp_table->next->prev= new_tmp_table;
2319
 
    this->temporary_tables= new_tmp_table;
2320
 
    this->temporary_tables->prev= 0;
2321
 
  }
2322
 
  new_tmp_table->pos_in_table_list= 0;
2323
 
 
2324
 
  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);
2325
4231
}
2326
4232
 
2327
4233
 
2328
4234
/*****************************************************************************
2329
 
 * The following find_field_in_XXX procedures implement the core of the
2330
 
 * name resolution functionality. The entry point to resolve a column name in a
2331
 
 * list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
2332
 
 * for each table reference. In turn, depending on the type of table reference,
2333
 
 * 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
2334
 
 * below specific for the type of table reference.
2335
 
 ******************************************************************************/
 
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
******************************************************************************/
2336
4242
 
2337
4243
/* Special Field pointers as return values of find_field_in_XXX functions. */
2338
4244
Field *not_found_field= (Field*) 0x1;
2339
 
Field *view_ref_found= (Field*) 0x2;
2340
 
 
2341
 
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)
2342
4250
{
2343
 
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
 
4251
  DBUG_ENTER("update_field_dependencies");
 
4252
  if (thd->mark_used_columns != MARK_COLUMNS_NONE)
2344
4253
  {
2345
 
    MyBitmap *current_bitmap, *other_bitmap;
 
4254
    MY_BITMAP *current_bitmap, *other_bitmap;
2346
4255
 
2347
4256
    /*
2348
4257
      We always want to register the used keys, as the column bitmap may have
2349
4258
      been set for all fields (for example for view).
2350
4259
    */
2351
 
 
2352
 
    table->covering_keys&= field->part_of_key;
2353
 
    table->merge_keys|= field->part_of_key;
2354
 
 
2355
 
    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)
2356
4265
    {
2357
4266
      current_bitmap= table->read_set;
2358
4267
      other_bitmap=   table->write_set;
2363
4272
      other_bitmap=   table->read_set;
2364
4273
    }
2365
4274
 
2366
 
    if (current_bitmap->testAndSet(field->field_index))
 
4275
    if (bitmap_fast_test_and_set(current_bitmap, field->field_index))
2367
4276
    {
2368
 
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
2369
 
        session->dup_field= field;
2370
 
      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;
2371
4287
    }
 
4288
    if (table->get_fields_in_item_tree)
 
4289
      field->flags|= GET_FIXED_FIELDS_FLAG;
2372
4290
    table->used_fields++;
2373
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);
2374
4367
}
2375
4368
 
2376
4369
 
2378
4371
  Find field by name in a NATURAL/USING join table reference.
2379
4372
 
2380
4373
  SYNOPSIS
2381
 
  find_field_in_natural_join()
2382
 
  session                        [in]  thread Cursor
2383
 
  table_ref            [in]  table reference to search
2384
 
  name           [in]  name of field
2385
 
  length                 [in]  length of name
2386
 
  ref                  [in/out] if 'name' is resolved to a view field, ref is
2387
 
  set to point to the found view field
2388
 
  register_tree_change [in]  true if ref is not stack variable and we
2389
 
  need register changes in item tree
2390
 
  actual_table         [out] the original table reference where the field
2391
 
  belongs - differs from 'table_list' only for
2392
 
  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
2393
4386
 
2394
4387
  DESCRIPTION
2395
 
  Search for a field among the result fields of a NATURAL/USING join.
2396
 
  Notice that this procedure is called only for non-qualified field
2397
 
  names. In the case of qualified fields, we search directly the base
2398
 
  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.
2399
4392
 
2400
4393
  RETURN
2401
 
  NULL        if the field was not found
2402
 
  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
2403
4397
*/
2404
4398
 
2405
4399
static Field *
2406
 
find_field_in_natural_join(Session *session, TableList *table_ref,
2407
 
                           const char *name, uint32_t , Item **,
2408
 
                           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)
2409
4403
{
2410
4404
  List_iterator_fast<Natural_join_column>
2411
4405
    field_it(*(table_ref->join_columns));
2412
4406
  Natural_join_column *nj_col, *curr_nj_col;
2413
4407
  Field *found_field;
2414
 
 
2415
 
  assert(table_ref->is_natural_join && table_ref->join_columns);
2416
 
  assert(*actual_table == NULL);
2417
 
 
2418
 
  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; 
2419
4415
       curr_nj_col= field_it++)
2420
4416
  {
2421
4417
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
2422
4418
    {
2423
4419
      if (nj_col)
2424
4420
      {
2425
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
2426
 
        return NULL;
 
4421
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
 
4422
        DBUG_RETURN(NULL);
2427
4423
      }
2428
4424
      nj_col= curr_nj_col;
2429
4425
    }
2430
4426
  }
2431
4427
  if (!nj_col)
2432
 
    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
2433
4471
  {
2434
4472
    /* This is a base table. */
2435
 
    assert(nj_col->table_ref->table == nj_col->table_field->table);
 
4473
    DBUG_ASSERT(nj_col->view_field == NULL);
 
4474
    DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->table);
2436
4475
    found_field= nj_col->table_field;
2437
 
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
 
4476
    update_field_dependencies(thd, found_field, nj_col->table_ref->table);
2438
4477
  }
2439
4478
 
2440
4479
  *actual_table= nj_col->table_ref;
2441
 
 
2442
 
  return(found_field);
 
4480
  
 
4481
  DBUG_RETURN(found_field);
2443
4482
}
2444
4483
 
2445
4484
 
2447
4486
  Find field by name in a base table or a view with temp table algorithm.
2448
4487
 
2449
4488
  SYNOPSIS
2450
 
  find_field_in_table()
2451
 
  session                               thread Cursor
2452
 
  table                 table where to search for the field
2453
 
  name                  name of field
2454
 
  length                        length of name
2455
 
  allow_rowid                   do allow finding of "_rowid" field?
2456
 
  cached_field_index_ptr        cached position in field list (used to speedup
2457
 
  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)
2458
4497
 
2459
4498
  RETURN
2460
 
  0     field is not found
2461
 
#       pointer to field
 
4499
    0   field is not found
 
4500
    #   pointer to field
2462
4501
*/
2463
4502
 
2464
4503
Field *
2465
 
find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
2466
 
                    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)
2467
4506
{
2468
4507
  Field **field_ptr, *field;
2469
 
  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));
2470
4511
 
2471
4512
  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
2472
4513
  if (cached_field_index < table->s->fields &&
2475
4516
    field_ptr= table->field + cached_field_index;
2476
4517
  else if (table->s->name_hash.records)
2477
4518
  {
2478
 
    field_ptr= (Field**) hash_search(&table->s->name_hash, (unsigned char*) name,
 
4519
    field_ptr= (Field**) hash_search(&table->s->name_hash, (uchar*) name,
2479
4520
                                     length);
2480
4521
    if (field_ptr)
2481
4522
    {
2482
4523
      /*
2483
 
        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
2484
4525
        field in table
2485
4526
      */
2486
4527
      field_ptr= (table->field + (field_ptr - table->s->field));
2489
4530
  else
2490
4531
  {
2491
4532
    if (!(field_ptr= table->field))
2492
 
      return((Field *)0);
 
4533
      DBUG_RETURN((Field *)0);
2493
4534
    for (; *field_ptr; ++field_ptr)
2494
4535
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
2495
4536
        break;
2505
4546
    if (!allow_rowid ||
2506
4547
        my_strcasecmp(system_charset_info, name, "_rowid") ||
2507
4548
        table->s->rowid_field_offset == 0)
2508
 
      return((Field*) 0);
 
4549
      DBUG_RETURN((Field*) 0);
2509
4550
    field= table->field[table->s->rowid_field_offset-1];
2510
4551
  }
2511
4552
 
2512
 
  update_field_dependencies(session, field, table);
 
4553
  update_field_dependencies(thd, field, table);
2513
4554
 
2514
 
  return field;
 
4555
  DBUG_RETURN(field);
2515
4556
}
2516
4557
 
2517
4558
 
2519
4560
  Find field in a table reference.
2520
4561
 
2521
4562
  SYNOPSIS
2522
 
  find_field_in_table_ref()
2523
 
  session                          [in]  thread Cursor
2524
 
  table_list               [in]  table reference to search
2525
 
  name             [in]  name of field
2526
 
  length                   [in]  field length of name
2527
 
  item_name              [in]  name of item if it will be created (VIEW)
2528
 
  db_name                [in]  optional database name that qualifies the
2529
 
  table_name             [in]  optional table name that qualifies the field
2530
 
  ref                  [in/out] if 'name' is resolved to a view field, ref
2531
 
  is set to point to the found view field
2532
 
  allow_rowid              [in]  do allow finding of "_rowid" field?
2533
 
  cached_field_index_ptr [in]  cached position in field list (used to
2534
 
  speedup lookup for fields in prepared tables)
2535
 
  register_tree_change   [in]  true if ref is not stack variable and we
2536
 
  need register changes in item tree
2537
 
  actual_table           [out] the original table reference where the field
2538
 
  belongs - differs from 'table_list' only for
2539
 
  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.
2540
4582
 
2541
4583
  DESCRIPTION
2542
 
  Find a field in a table reference depending on the type of table
2543
 
  reference. There are three types of table references with respect
2544
 
  to the representation of their result columns:
2545
 
  - an array of Field_translator objects for MERGE views and some
2546
 
  information_schema tables,
2547
 
  - an array of Field objects (and possibly a name hash) for stored
2548
 
  tables,
2549
 
  - a list of Natural_join_column objects for NATURAL/USING joins.
2550
 
  This procedure detects the type of the table reference 'table_list'
2551
 
  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.
2552
4594
 
2553
4595
  RETURN
2554
 
  0                     field is not found
2555
 
  view_ref_found        found value in VIEW (real result is in *ref)
2556
 
#                       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
2557
4599
*/
2558
4600
 
2559
4601
Field *
2560
 
find_field_in_table_ref(Session *session, TableList *table_list,
2561
 
                        const char *name, uint32_t length,
 
4602
find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
 
4603
                        const char *name, uint length,
2562
4604
                        const char *item_name, const char *db_name,
2563
4605
                        const char *table_name, Item **ref,
2564
 
                        bool allow_rowid,
2565
 
                        uint32_t *cached_field_index_ptr,
2566
 
                        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)
2567
4609
{
2568
 
  Field *fld= NULL;
2569
 
 
2570
 
  assert(table_list->alias);
2571
 
  assert(name);
2572
 
  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));
2573
4618
 
2574
4619
  /*
2575
4620
    Check that the table and database that qualify the current field name
2585
4630
    inside the view, but we want to search directly in the view columns
2586
4631
    which are represented as a 'field_translation'.
2587
4632
 
2588
 
TODO: Ensure that table_name, db_name and tables->db always points to
2589
 
something !
 
4633
    TODO: Ensure that table_name, db_name and tables->db always points to
 
4634
          something !
2590
4635
  */
2591
4636
  if (/* Exclude nested joins. */
2592
 
      (!table_list->nested_join) &&
2593
 
      /* 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) &&
2594
4640
      /*
2595
4641
        Test if the field qualifiers match the table reference we plan
2596
4642
        to search.
2599
4645
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2600
4646
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
2601
4647
        strcmp(db_name, table_list->db))))
2602
 
    return 0;
 
4648
    DBUG_RETURN(0);
2603
4649
 
2604
4650
  *actual_table= NULL;
2605
4651
 
2606
 
  if (!table_list->nested_join)
 
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)
2607
4660
  {
2608
4661
    /* 'table_list' is a stored table. */
2609
 
    assert(table_list->table);
2610
 
    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,
2611
4664
                                  allow_rowid,
2612
4665
                                  cached_field_index_ptr)))
2613
4666
      *actual_table= table_list;
2623
4676
    */
2624
4677
    if (table_name && table_name[0])
2625
4678
    {
2626
 
      List_iterator<TableList> it(table_list->nested_join->join_list);
2627
 
      TableList *table;
 
4679
      List_iterator<TABLE_LIST> it(table_list->nested_join->join_list);
 
4680
      TABLE_LIST *table;
2628
4681
      while ((table= it++))
2629
4682
      {
2630
 
        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,
2631
4684
                                          db_name, table_name, ref,
2632
 
                                          allow_rowid,
 
4685
                                          check_privileges, allow_rowid,
2633
4686
                                          cached_field_index_ptr,
2634
4687
                                          register_tree_change, actual_table)))
2635
 
          return fld;
 
4688
          DBUG_RETURN(fld);
2636
4689
      }
2637
 
      return NULL;
 
4690
      DBUG_RETURN(0);
2638
4691
    }
2639
4692
    /*
2640
4693
      Non-qualified field, search directly in the result columns of the
2642
4695
      natural join, thus if the field is not qualified, we will search
2643
4696
      directly the top-most NATURAL/USING join.
2644
4697
    */
2645
 
    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,
2646
4699
                                    register_tree_change, actual_table);
2647
4700
  }
2648
4701
 
2649
4702
  if (fld)
2650
4703
  {
2651
 
    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)
2652
4762
    {
2653
4763
      /*
2654
 
        Get rw_set correct for this field so that the Cursor
2655
 
        knows that this field is involved in the query and gets
2656
 
        retrieved/updated
 
4764
        field_ptr points to field in TABLE_SHARE. Convert it to the matching
 
4765
        field in table
2657
4766
      */
2658
 
      Field *field_to_set= NULL;
2659
 
      if (fld == view_ref_found)
2660
 
      {
2661
 
        Item *it= (*ref)->real_item();
2662
 
        if (it->type() == Item::FIELD_ITEM)
2663
 
          field_to_set= ((Item_field*)it)->field;
2664
 
        else
2665
 
        {
2666
 
          if (session->mark_used_columns == MARK_COLUMNS_READ)
2667
 
            it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
2668
 
        }
2669
 
      }
2670
 
      else
2671
 
        field_to_set= fld;
2672
 
      if (field_to_set)
2673
 
      {
2674
 
        Table *table= field_to_set->table;
2675
 
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2676
 
          table->setReadSet(field_to_set->field_index);
2677
 
        else
2678
 
          table->setWriteSet(field_to_set->field_index);
2679
 
      }
 
4767
      field_ptr= (table->field + (field_ptr - table->s->field));
2680
4768
    }
2681
4769
  }
2682
 
  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;
2683
4782
}
2684
4783
 
2685
4784
 
2687
4786
  Find field in table list.
2688
4787
 
2689
4788
  SYNOPSIS
2690
 
  find_field_in_tables()
2691
 
  session                         pointer to current thread structure
2692
 
  item            field item that should be found
2693
 
  first_table           list of tables to be searched for item
2694
 
  last_table            end of the list of tables to search for item. If NULL
2695
 
  then search to the end of the list 'first_table'.
2696
 
  ref                     if 'item' is resolved to a view field, ref is set to
2697
 
  point to the found view field
2698
 
  report_error    Degree of error reporting:
2699
 
  - IGNORE_ERRORS then do not report any error
2700
 
  - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
2701
 
  fields, suppress all other errors
2702
 
  - REPORT_EXCEPT_NON_UNIQUE report all other errors
2703
 
  except when non-unique fields were found
2704
 
  - REPORT_ALL_ERRORS
2705
 
  register_tree_change  true if ref is not a stack variable and we
2706
 
  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
2707
4807
 
2708
4808
  RETURN VALUES
2709
 
  0                     If error: the found field is not unique, or there are
2710
 
  no sufficient access priviliges for the found field,
2711
 
  or the field is qualified with non-existing table.
2712
 
  not_found_field       The function was called with report_error ==
2713
 
  (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
2714
 
  field was not found.
2715
 
  view_ref_found        View field is found, item passed through ref parameter
2716
 
  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
2717
4817
*/
2718
4818
 
2719
4819
Field *
2720
 
find_field_in_tables(Session *session, Item_ident *item,
2721
 
                     TableList *first_table, TableList *last_table,
2722
 
                     Item **ref, find_item_error_report_type report_error,
2723
 
                     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)
2724
4824
{
2725
4825
  Field *found=0;
2726
4826
  const char *db= item->db_name;
2727
4827
  const char *table_name= item->table_name;
2728
4828
  const char *name= item->field_name;
2729
 
  uint32_t length=(uint32_t) strlen(name);
 
4829
  uint length=(uint) strlen(name);
2730
4830
  char name_buff[NAME_LEN+1];
2731
 
  TableList *cur_table= first_table;
2732
 
  TableList *actual_table;
 
4831
  TABLE_LIST *cur_table= first_table;
 
4832
  TABLE_LIST *actual_table;
2733
4833
  bool allow_rowid;
2734
4834
 
2735
4835
  if (!table_name || !table_name[0])
2744
4844
  {
2745
4845
    /*
2746
4846
      This shortcut is used by prepared statements. We assume that
2747
 
      TableList *first_table is not changed during query execution (which
 
4847
      TABLE_LIST *first_table is not changed during query execution (which
2748
4848
      is true for all queries except RENAME but luckily RENAME doesn't
2749
4849
      use fields...) so we can rely on reusing pointer to its member.
2750
4850
      With this optimization we also miss case when addition of one more
2751
4851
      field makes some prepared query ambiguous and so erroneous, but we
2752
4852
      accept this trade off.
2753
4853
    */
2754
 
    TableList *table_ref= item->cached_table;
 
4854
    TABLE_LIST *table_ref= item->cached_table;
2755
4855
    /*
2756
4856
      The condition (table_ref->view == NULL) ensures that we will call
2757
4857
      find_field_in_table even in the case of information schema tables
2758
4858
      when table_ref->field_translation != NULL.
2759
 
    */
 
4859
      */
2760
4860
    if (table_ref->table)
2761
 
      found= find_field_in_table(session, table_ref->table, name, length,
2762
 
                                 true, &(item->cached_field_index));
 
4861
      found= find_field_in_table(thd, table_ref->table, name, length,
 
4862
                                 TRUE, &(item->cached_field_index));
2763
4863
    else
2764
 
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
2765
 
                                     NULL, NULL, ref,
2766
 
                                     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),
2767
4867
                                     register_tree_change,
2768
4868
                                     &actual_table);
2769
4869
    if (found)
2770
4870
    {
 
4871
      if (found == WRONG_GRANT)
 
4872
        return (Field*) 0;
 
4873
 
2771
4874
      /*
2772
4875
        Only views fields should be marked as dependent, not an underlying
2773
4876
        fields.
2774
4877
      */
 
4878
      if (!table_ref->belong_to_view)
2775
4879
      {
2776
 
        Select_Lex *current_sel= session->lex->current_select;
2777
 
        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;
2778
4882
        /*
2779
4883
          If the field was an outer referencee, mark all selects using this
2780
4884
          sub query as dependent on the outer query
2781
4885
        */
2782
4886
        if (current_sel != last_select)
2783
 
          mark_select_range_as_dependent(session, last_select, current_sel,
 
4887
          mark_select_range_as_dependent(thd, last_select, current_sel,
2784
4888
                                         found, *ref, item);
2785
4889
      }
2786
4890
      return found;
2787
4891
    }
2788
4892
  }
2789
4893
 
2790
 
  if (db)
 
4894
  if (db && lower_case_table_names)
2791
4895
  {
2792
4896
    /*
2793
4897
      convert database to lower case for comparison.
2794
4898
      We can't do this in Item_field as this would change the
2795
4899
      'name' of the item which may be used in the select list
2796
4900
    */
2797
 
    strncpy(name_buff, db, sizeof(name_buff)-1);
 
4901
    strmake(name_buff, db, sizeof(name_buff)-1);
2798
4902
    my_casedn_str(files_charset_info, name_buff);
2799
4903
    db= name_buff;
2800
4904
  }
2805
4909
  for (; cur_table != last_table ;
2806
4910
       cur_table= cur_table->next_name_resolution_table)
2807
4911
  {
2808
 
    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,
2809
4913
                                              item->name, db, table_name, ref,
 
4914
                                              (thd->lex->sql_command ==
 
4915
                                               SQLCOM_SHOW_FIELDS)
 
4916
                                              ? false : check_privileges,
2810
4917
                                              allow_rowid,
2811
4918
                                              &(item->cached_field_index),
2812
4919
                                              register_tree_change,
2813
4920
                                              &actual_table);
2814
4921
    if (cur_field)
2815
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
 
2816
4946
      /*
2817
4947
        Store the original table of the field, which may be different from
2818
4948
        cur_table in the case of NATURAL/USING join.
2819
4949
      */
2820
 
      item->cached_table= found ?  0 : actual_table;
 
4950
      item->cached_table= (!actual_table->cacheable_table || found) ?
 
4951
                          0 : actual_table;
2821
4952
 
2822
 
      assert(session->where);
 
4953
      DBUG_ASSERT(thd->where);
2823
4954
      /*
2824
4955
        If we found a fully qualified field we return it directly as it can't
2825
4956
        have duplicates.
2826
 
      */
 
4957
       */
2827
4958
      if (db)
2828
4959
        return cur_field;
2829
4960
 
2832
4963
        if (report_error == REPORT_ALL_ERRORS ||
2833
4964
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2834
4965
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2835
 
                   table_name ? item->full_name() : name, session->where);
 
4966
                   table_name ? item->full_name() : name, thd->where);
2836
4967
        return (Field*) 0;
2837
4968
      }
2838
4969
      found= cur_field;
2856
4987
    char buff[NAME_LEN*2+1];
2857
4988
    if (db && db[0])
2858
4989
    {
2859
 
      /* We're in an error condition, two extra strlen's aren't going
2860
 
       * to kill us */
2861
 
      assert(strlen(db) <= NAME_LEN);
2862
 
      assert(strlen(table_name) <= NAME_LEN);
2863
 
      strcpy(buff, db);
2864
 
      strcat(buff,".");
2865
 
      strcat(buff, table_name);
 
4990
      strxnmov(buff,sizeof(buff)-1,db,".",table_name,NullS);
2866
4991
      table_name=buff;
2867
4992
    }
2868
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
 
4993
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
2869
4994
  }
2870
4995
  else
2871
4996
  {
2872
4997
    if (report_error == REPORT_ALL_ERRORS ||
2873
4998
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2874
 
      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);
2875
5000
    else
2876
5001
      found= not_found_field;
2877
5002
  }
2883
5008
  Find Item in list of items (find_field_in_tables analog)
2884
5009
 
2885
5010
  TODO
2886
 
  is it better return only counter?
 
5011
    is it better return only counter?
2887
5012
 
2888
5013
  SYNOPSIS
2889
 
  find_item_in_list()
2890
 
  find                  Item to find
2891
 
  items                 List of items
2892
 
  counter                       To return number of found item
2893
 
  report_error
2894
 
  REPORT_ALL_ERRORS             report errors, return 0 if error
2895
 
  REPORT_EXCEPT_NOT_FOUND       Do not report 'not found' error and
2896
 
  return not_found_item, report other errors,
2897
 
  return 0
2898
 
  IGNORE_ERRORS         Do not report errors, return 0 if error
2899
 
  resolution                  Set to the resolution type if the item is found
2900
 
  (it says whether the item is resolved
2901
 
  against an alias name,
2902
 
  or as a field name without alias,
2903
 
  or as a field hidden by alias,
2904
 
  or ignoring alias)
2905
 
 
 
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
                                
2906
5031
  RETURN VALUES
2907
 
  0                     Item is not found or item is not unique,
2908
 
  error message is reported
2909
 
  not_found_item        Function was called with
2910
 
  report_error == REPORT_EXCEPT_NOT_FOUND and
2911
 
  item was not found. No error message was reported
2912
 
  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
2913
5038
*/
2914
5039
 
2915
5040
/* Special Item pointer to serve as a return value from find_item_in_list(). */
2917
5042
 
2918
5043
 
2919
5044
Item **
2920
 
find_item_in_list(Item *find, List<Item> &items, uint32_t *counter,
 
5045
find_item_in_list(Item *find, List<Item> &items, uint *counter,
2921
5046
                  find_item_error_report_type report_error,
2922
5047
                  enum_resolution_type *resolution)
2923
5048
{
2932
5057
    (and not an item that happens to have a name).
2933
5058
  */
2934
5059
  bool is_ref_by_name= 0;
2935
 
  uint32_t unaliased_counter= 0;
 
5060
  uint unaliased_counter= 0;
2936
5061
 
2937
5062
  *resolution= NOT_RESOLVED;
2938
5063
 
2939
 
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
 
5064
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  || 
2940
5065
                   find->type() == Item::REF_ITEM);
2941
5066
  if (is_ref_by_name)
2942
5067
  {
2945
5070
    db_name=    ((Item_ident*) find)->db_name;
2946
5071
  }
2947
5072
 
2948
 
  for (uint32_t i= 0; (item=li++); i++)
 
5073
  for (uint i= 0; (item=li++); i++)
2949
5074
  {
2950
5075
    if (field_name && item->real_item()->type() == Item::FIELD_ITEM)
2951
5076
    {
2952
5077
      Item_ident *item_field= (Item_ident*) item;
2953
5078
 
2954
5079
      /*
2955
 
        In case of group_concat() with ORDER BY condition in the QUERY
2956
 
        item_field can be field of temporary table without item name
2957
 
        (if this field created from expression argument of group_concat()),
2958
 
        => we have to check presence of name before compare
2959
 
      */
 
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
      */ 
2960
5085
      if (!item_field->name)
2961
5086
        continue;
2962
5087
 
2975
5100
          case sensitive. In cases where they are not case sensitive, they
2976
5101
          are always in lower case.
2977
5102
 
2978
 
          item_field->field_name and item_field->table_name can be 0x0 if
2979
 
          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.
2980
5105
        */
2981
5106
        if (item_field->field_name && item_field->table_name &&
2982
 
            !my_strcasecmp(system_charset_info, item_field->field_name,
 
5107
            !my_strcasecmp(system_charset_info, item_field->field_name,
2983
5108
                           field_name) &&
2984
 
            !my_strcasecmp(table_alias_charset, item_field->table_name,
 
5109
            !my_strcasecmp(table_alias_charset, item_field->table_name, 
2985
5110
                           table_name) &&
2986
5111
            (!db_name || (item_field->db_name &&
2987
5112
                          !strcmp(item_field->db_name, db_name))))
2997
5122
            */
2998
5123
            if (report_error != IGNORE_ERRORS)
2999
5124
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3000
 
                       find->full_name(), current_session->where);
 
5125
                       find->full_name(), current_thd->where);
3001
5126
            return (Item**) 0;
3002
5127
          }
3003
5128
          found_unaliased= li.ref();
3028
5153
              continue;                           // Same field twice
3029
5154
            if (report_error != IGNORE_ERRORS)
3030
5155
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
3031
 
                       find->full_name(), current_session->where);
 
5156
                       find->full_name(), current_thd->where);
3032
5157
            return (Item**) 0;
3033
5158
          }
3034
5159
          found= li.ref();
3035
5160
          *counter= i;
3036
5161
          *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
3037
 
            RESOLVED_WITH_NO_ALIAS;
 
5162
                                   RESOLVED_WITH_NO_ALIAS;
3038
5163
        }
3039
5164
        else if (!fname_cmp)
3040
5165
        {
3056
5181
      }
3057
5182
    }
3058
5183
    else if (!table_name)
3059
 
    {
 
5184
    { 
3060
5185
      if (is_ref_by_name && find->name && item->name &&
3061
 
          !my_strcasecmp(system_charset_info,item->name,find->name))
 
5186
          !my_strcasecmp(system_charset_info,item->name,find->name))
3062
5187
      {
3063
5188
        found= li.ref();
3064
5189
        *counter= i;
3073
5198
        break;
3074
5199
      }
3075
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
    }
3076
5230
  }
3077
5231
  if (!found)
3078
5232
  {
3080
5234
    {
3081
5235
      if (report_error != IGNORE_ERRORS)
3082
5236
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
3083
 
                 find->full_name(), current_session->where);
 
5237
                 find->full_name(), current_thd->where);
3084
5238
      return (Item **) 0;
3085
5239
    }
3086
5240
    if (found_unaliased)
3096
5250
  {
3097
5251
    if (report_error == REPORT_ALL_ERRORS)
3098
5252
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
3099
 
               find->full_name(), current_session->where);
 
5253
               find->full_name(), current_thd->where);
3100
5254
    return (Item **) 0;
3101
5255
  }
3102
5256
  else
3108
5262
  Test if a string is a member of a list of strings.
3109
5263
 
3110
5264
  SYNOPSIS
3111
 
  test_if_string_in_list()
3112
 
  find      the string to look for
3113
 
  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
3114
5268
 
3115
5269
  DESCRIPTION
3116
 
  Sequentially search a list of strings for a string, and test whether
3117
 
  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.
3118
5272
 
3119
5273
  RETURN
3120
 
  true  if find is in str_list
3121
 
  false otherwise
 
5274
    TRUE  if find is in str_list
 
5275
    FALSE otherwise
3122
5276
*/
3123
5277
 
3124
5278
static bool
3132
5286
    if (find_length != curr_str->length())
3133
5287
      continue;
3134
5288
    if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
3135
 
      return true;
 
5289
      return TRUE;
3136
5290
  }
3137
 
  return false;
 
5291
  return FALSE;
3138
5292
}
3139
5293
 
3140
5294
 
3143
5297
  being resolved in a specific table reference.
3144
5298
 
3145
5299
  SYNOPSIS
3146
 
  set_new_item_local_context()
3147
 
  session        pointer to current thread
3148
 
  item       item for which new context is created and set
3149
 
  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
3150
5304
 
3151
5305
  DESCRIPTION
3152
 
  Create a new name resolution context for an item, so that the item
3153
 
  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'.
3154
5308
 
3155
5309
  RETURN
3156
 
  false  if all OK
3157
 
  true   otherwise
 
5310
    FALSE  if all OK
 
5311
    TRUE   otherwise
3158
5312
*/
3159
5313
 
3160
5314
static bool
3161
 
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)
3162
5316
{
3163
5317
  Name_resolution_context *context;
3164
 
  if (!(context= new (session->mem_root) Name_resolution_context))
3165
 
    return true;
 
5318
  if (!(context= new (thd->mem_root) Name_resolution_context))
 
5319
    return TRUE;
3166
5320
  context->init();
3167
5321
  context->first_name_resolution_table=
3168
5322
    context->last_name_resolution_table= table_ref;
3169
5323
  item->context= context;
3170
 
  return false;
 
5324
  return FALSE;
3171
5325
}
3172
5326
 
3173
5327
 
3175
5329
  Find and mark the common columns of two table references.
3176
5330
 
3177
5331
  SYNOPSIS
3178
 
  mark_common_columns()
3179
 
  session                [in] current thread
3180
 
  table_ref_1        [in] the first (left) join operand
3181
 
  table_ref_2        [in] the second (right) join operand
3182
 
  using_fields       [in] if the join is JOIN...USING - the join columns,
3183
 
  if NATURAL join, then NULL
3184
 
  found_using_fields [out] number of fields from the USING clause that were
3185
 
  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
3186
5340
 
3187
5341
  DESCRIPTION
3188
 
  The procedure finds the common columns of two relations (either
3189
 
  tables or intermediate join results), and adds an equi-join condition
3190
 
  to the ON clause of 'table_ref_2' for each pair of matching columns.
3191
 
  If some of table_ref_XXX represents a base table or view, then we
3192
 
  create new 'Natural_join_column' instances for each column
3193
 
  reference and store them in the 'join_columns' of the table
3194
 
  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.
3195
5349
 
3196
5350
  IMPLEMENTATION
3197
 
  The procedure assumes that store_natural_using_join_columns() was
3198
 
  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.
3199
5353
 
3200
5354
  RETURN
3201
 
  true   error when some common column is non-unique, or out of memory
3202
 
  false  OK
 
5355
    TRUE   error when some common column is non-unique, or out of memory
 
5356
    FALSE  OK
3203
5357
*/
3204
5358
 
3205
5359
static bool
3206
 
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
3207
 
                    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)
3208
5362
{
3209
5363
  Field_iterator_table_ref it_1, it_2;
3210
5364
  Natural_join_column *nj_col_1, *nj_col_2;
3211
 
  bool result= true;
3212
 
  bool first_outer_loop= true;
 
5365
  bool result= TRUE;
 
5366
  bool first_outer_loop= TRUE;
3213
5367
  /*
3214
5368
    Leaf table references to which new natural join columns are added
3215
5369
    if the leaves are != NULL.
3216
5370
  */
3217
 
  TableList *leaf_1= (table_ref_1->nested_join &&
3218
 
                      !table_ref_1->is_natural_join) ?
3219
 
    NULL : table_ref_1;
3220
 
  TableList *leaf_2= (table_ref_2->nested_join &&
3221
 
                      !table_ref_2->is_natural_join) ?
3222
 
    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));
3223
5381
 
3224
5382
  *found_using_fields= 0;
3225
5383
 
3226
5384
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3227
5385
  {
3228
 
    bool found= false;
 
5386
    bool found= FALSE;
3229
5387
    const char *field_name_1;
3230
5388
    /* true if field_name_1 is a member of using_fields */
3231
5389
    bool is_using_column_1;
3232
5390
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
3233
5391
      goto err;
3234
5392
    field_name_1= nj_col_1->name();
3235
 
    is_using_column_1= using_fields &&
 
5393
    is_using_column_1= using_fields && 
3236
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));
3237
5398
 
3238
5399
    /*
3239
5400
      Find a field with the same name in table_ref_2.
3250
5411
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
3251
5412
        goto err;
3252
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));
3253
5418
 
3254
5419
      /*
3255
5420
        Compare the two columns and check for duplicate common fields.
3256
5421
        A common field is duplicate either if it was already found in
3257
 
        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
3258
5423
        was already matched by some previous field in table_ref_1
3259
 
        (then cur_nj_col_2->is_common == true).
 
5424
        (then cur_nj_col_2->is_common == TRUE).
3260
5425
        Note that it is too early to check the columns outside of the
3261
5426
        USING list for ambiguity because they are not actually "referenced"
3262
 
        here. These columns must be checked only on unqualified reference
 
5427
        here. These columns must be checked only on unqualified reference 
3263
5428
        by name (e.g. in SELECT list).
3264
5429
      */
3265
5430
      if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
3266
5431
      {
 
5432
        DBUG_PRINT ("info", ("match c1.is_common=%d", nj_col_1->is_common));
3267
5433
        if (cur_nj_col_2->is_common ||
3268
5434
            (found && (!using_fields || is_using_column_1)))
3269
5435
        {
3270
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
5436
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where);
3271
5437
          goto err;
3272
5438
        }
3273
5439
        nj_col_2= cur_nj_col_2;
3274
 
        found= true;
 
5440
        found= TRUE;
3275
5441
      }
3276
5442
    }
3277
5443
    if (first_outer_loop && leaf_2)
3280
5446
        Make sure that the next inner loop "knows" that all columns
3281
5447
        are materialized already.
3282
5448
      */
3283
 
      leaf_2->is_join_columns_complete= true;
3284
 
      first_outer_loop= false;
 
5449
      leaf_2->is_join_columns_complete= TRUE;
 
5450
      first_outer_loop= FALSE;
3285
5451
    }
3286
5452
    if (!found)
3287
5453
      continue;                                 // No matching field
3293
5459
    */
3294
5460
    if (nj_col_2 && (!using_fields ||is_using_column_1))
3295
5461
    {
3296
 
      Item *item_1=   nj_col_1->create_item(session);
3297
 
      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);
3298
5464
      Field *field_1= nj_col_1->field();
3299
5465
      Field *field_2= nj_col_2->field();
3300
5466
      Item_ident *item_ident_1, *item_ident_2;
3304
5470
        goto err;                               // out of memory
3305
5471
 
3306
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
      /*
3307
5478
        In the case of no_wrap_view_item == 0, the created items must be
3308
5479
        of sub-classes of Item_ident.
3309
5480
      */
3310
 
      assert(item_1->type() == Item::FIELD_ITEM ||
3311
 
             item_1->type() == Item::REF_ITEM);
3312
 
      assert(item_2->type() == Item::FIELD_ITEM ||
3313
 
             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);
3314
5485
 
3315
5486
      /*
3316
5487
        We need to cast item_1,2 to Item_ident, because we need to hook name
3324
5495
        resolution of these items, and to enable proper name resolution of
3325
5496
        the items during the execute phase of PS.
3326
5497
      */
3327
 
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
3328
 
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
 
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))
3329
5500
        goto err;
3330
5501
 
3331
5502
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
3335
5506
        Add the new equi-join condition to the ON clause. Notice that
3336
5507
        fix_fields() is applied to all ON conditions in setup_conds()
3337
5508
        so we don't do it here.
3338
 
      */
 
5509
       */
3339
5510
      add_join_on((table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
3340
5511
                   table_ref_1 : table_ref_2),
3341
5512
                  eq_cond);
3342
5513
 
3343
 
      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()));
3344
5522
 
3345
5523
      if (field_1)
3346
5524
      {
3347
 
        Table *table_1= nj_col_1->table_ref->table;
 
5525
        TABLE *table_1= nj_col_1->table_ref->table;
3348
5526
        /* Mark field_1 used for table cache. */
3349
 
        table_1->setReadSet(field_1->field_index);
3350
 
        table_1->covering_keys&= field_1->part_of_key;
3351
 
        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);
3352
5530
      }
3353
5531
      if (field_2)
3354
5532
      {
3355
 
        Table *table_2= nj_col_2->table_ref->table;
 
5533
        TABLE *table_2= nj_col_2->table_ref->table;
3356
5534
        /* Mark field_2 used for table cache. */
3357
 
        table_2->setReadSet(field_2->field_index);
3358
 
        table_2->covering_keys&= field_2->part_of_key;
3359
 
        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);
3360
5538
      }
3361
5539
 
3362
5540
      if (using_fields != NULL)
3364
5542
    }
3365
5543
  }
3366
5544
  if (leaf_1)
3367
 
    leaf_1->is_join_columns_complete= true;
 
5545
    leaf_1->is_join_columns_complete= TRUE;
3368
5546
 
3369
5547
  /*
3370
5548
    Everything is OK.
3373
5551
    we check for this error in store_natural_using_join_columns() when
3374
5552
    (found_using_fields < length(join_using_fields)).
3375
5553
  */
3376
 
  result= false;
 
5554
  result= FALSE;
3377
5555
 
3378
5556
err:
3379
 
  return(result);
 
5557
  DBUG_RETURN(result);
3380
5558
}
3381
5559
 
3382
5560
 
3385
5563
  Materialize and store the row type of NATURAL/USING join.
3386
5564
 
3387
5565
  SYNOPSIS
3388
 
  store_natural_using_join_columns()
3389
 
  session                current thread
3390
 
  natural_using_join the table reference of the NATURAL/USING join
3391
 
  table_ref_1        the first (left) operand (of a NATURAL/USING join).
3392
 
  table_ref_2        the second (right) operand (of a NATURAL/USING join).
3393
 
  using_fields       if the join is JOIN...USING - the join columns,
3394
 
  if NATURAL join, then NULL
3395
 
  found_using_fields number of fields from the USING clause that were
3396
 
  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
3397
5575
 
3398
5576
  DESCRIPTION
3399
 
  Iterate over the columns of both join operands and sort and store
3400
 
  all columns into the 'join_columns' list of natural_using_join
3401
 
  where the list is formed by three parts:
3402
 
part1: The coalesced columns of table_ref_1 and table_ref_2,
3403
 
sorted according to the column order of the first table.
3404
 
part2: The other columns of the first table, in the order in
3405
 
which they were defined in CREATE TABLE.
3406
 
part3: The other columns of the second table, in the order in
3407
 
which they were defined in CREATE TABLE.
3408
 
Time complexity - O(N1+N2), where Ni = length(table_ref_i).
3409
 
 
3410
 
IMPLEMENTATION
3411
 
The procedure assumes that mark_common_columns() has been called
3412
 
for the join that is being processed.
3413
 
 
3414
 
RETURN
3415
 
true    error: Some common column is ambiguous
3416
 
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
3417
5595
*/
3418
5596
 
3419
5597
static bool
3420
 
store_natural_using_join_columns(Session *,
3421
 
                                 TableList *natural_using_join,
3422
 
                                 TableList *table_ref_1,
3423
 
                                 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,
3424
5601
                                 List<String> *using_fields,
3425
 
                                 uint32_t found_using_fields)
 
5602
                                 uint found_using_fields)
3426
5603
{
3427
5604
  Field_iterator_table_ref it_1, it_2;
3428
5605
  Natural_join_column *nj_col_1, *nj_col_2;
3429
 
  bool result= true;
 
5606
  bool result= TRUE;
3430
5607
  List<Natural_join_column> *non_join_columns;
 
5608
  DBUG_ENTER("store_natural_using_join_columns");
3431
5609
 
3432
 
  assert(!natural_using_join->join_columns);
 
5610
  DBUG_ASSERT(!natural_using_join->join_columns);
3433
5611
 
3434
5612
  if (!(non_join_columns= new List<Natural_join_column>) ||
3435
5613
      !(natural_using_join->join_columns= new List<Natural_join_column>))
3443
5621
    {
3444
5622
      natural_using_join->join_columns->push_back(nj_col_1);
3445
5623
      /* Reset the common columns for the next call to mark_common_columns. */
3446
 
      nj_col_1->is_common= false;
 
5624
      nj_col_1->is_common= FALSE;
3447
5625
    }
3448
5626
    else
3449
5627
      non_join_columns->push_back(nj_col_1);
3471
5649
        if (!(common_field= it++))
3472
5650
        {
3473
5651
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3474
 
                   current_session->where);
 
5652
                   current_thd->where);
3475
5653
          goto err;
3476
5654
        }
3477
5655
        if (!my_strcasecmp(system_charset_info,
3490
5668
    else
3491
5669
    {
3492
5670
      /* Reset the common columns for the next call to mark_common_columns. */
3493
 
      nj_col_2->is_common= false;
 
5671
      nj_col_2->is_common= FALSE;
3494
5672
    }
3495
5673
  }
3496
5674
 
3497
5675
  if (non_join_columns->elements > 0)
3498
5676
    natural_using_join->join_columns->concat(non_join_columns);
3499
 
  natural_using_join->is_join_columns_complete= true;
 
5677
  natural_using_join->is_join_columns_complete= TRUE;
3500
5678
 
3501
 
  result= false;
 
5679
  result= FALSE;
3502
5680
 
3503
5681
err:
3504
 
  return(result);
 
5682
  DBUG_RETURN(result);
3505
5683
}
3506
5684
 
3507
5685
 
3509
5687
  Precompute and store the row types of the top-most NATURAL/USING joins.
3510
5688
 
3511
5689
  SYNOPSIS
3512
 
  store_top_level_join_columns()
3513
 
  session            current thread
3514
 
  table_ref      nested join or table in a FROM clause
3515
 
  left_neighbor  neighbor table reference to the left of table_ref at the
3516
 
  same level in the join tree
3517
 
  right_neighbor neighbor table reference to the right of table_ref at the
3518
 
  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
3519
5697
 
3520
5698
  DESCRIPTION
3521
 
  The procedure performs a post-order traversal of a nested join tree
3522
 
  and materializes the row types of NATURAL/USING joins in a
3523
 
  bottom-up manner until it reaches the TableList elements that
3524
 
  represent the top-most NATURAL/USING joins. The procedure should be
3525
 
  applied to each element of Select_Lex::top_join_list (i.e. to each
3526
 
  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).
3527
5705
 
3528
5706
  IMPLEMENTATION
3529
 
  Notice that the table references in the list nested_join->join_list
3530
 
  are in reverse order, thus when we iterate over it, we are moving
3531
 
  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.
3532
5710
 
3533
5711
  RETURN
3534
 
  true   Error
3535
 
  false  OK
 
5712
    TRUE   Error
 
5713
    FALSE  OK
3536
5714
*/
3537
5715
 
3538
5716
static bool
3539
 
store_top_level_join_columns(Session *session, TableList *table_ref,
3540
 
                             TableList *left_neighbor,
3541
 
                             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)
3542
5720
{
3543
 
  bool result= true;
 
5721
  bool result= TRUE;
 
5722
 
 
5723
  DBUG_ENTER("store_top_level_join_columns");
3544
5724
 
3545
5725
  /* Call the procedure recursively for each nested table reference. */
3546
5726
  if (table_ref->nested_join)
3547
5727
  {
3548
 
    List_iterator_fast<TableList> nested_it(table_ref->nested_join->join_list);
3549
 
    TableList *same_level_left_neighbor= nested_it++;
3550
 
    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;
3551
5731
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3552
 
    TableList *real_left_neighbor, *real_right_neighbor;
 
5732
    TABLE_LIST *real_left_neighbor, *real_right_neighbor;
3553
5733
 
3554
5734
    while (same_level_left_neighbor)
3555
5735
    {
3556
 
      TableList *cur_table_ref= same_level_left_neighbor;
 
5736
      TABLE_LIST *cur_table_ref= same_level_left_neighbor;
3557
5737
      same_level_left_neighbor= nested_it++;
3558
5738
      /*
3559
5739
        The order of RIGHT JOIN operands is reversed in 'join list' to
3570
5750
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
3571
5751
      {
3572
5752
        /* This can happen only for JOIN ... ON. */
3573
 
        assert(table_ref->nested_join->join_list.elements == 2);
3574
 
        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);
3575
5755
      }
3576
5756
 
3577
5757
      /*
3579
5759
        neighbors at the same level.
3580
5760
      */
3581
5761
      real_left_neighbor=  (same_level_left_neighbor) ?
3582
 
        same_level_left_neighbor : left_neighbor;
 
5762
                           same_level_left_neighbor : left_neighbor;
3583
5763
      real_right_neighbor= (same_level_right_neighbor) ?
3584
 
        same_level_right_neighbor : right_neighbor;
 
5764
                           same_level_right_neighbor : right_neighbor;
3585
5765
 
3586
5766
      if (cur_table_ref->nested_join &&
3587
 
          store_top_level_join_columns(session, cur_table_ref,
 
5767
          store_top_level_join_columns(thd, cur_table_ref,
3588
5768
                                       real_left_neighbor, real_right_neighbor))
3589
5769
        goto err;
3590
5770
      same_level_right_neighbor= cur_table_ref;
3597
5777
  */
3598
5778
  if (table_ref->is_natural_join)
3599
5779
  {
3600
 
    assert(table_ref->nested_join &&
3601
 
           table_ref->nested_join->join_list.elements == 2);
3602
 
    List_iterator_fast<TableList> operand_it(table_ref->nested_join->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);
3603
5783
    /*
3604
5784
      Notice that the order of join operands depends on whether table_ref
3605
5785
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3606
5786
      in inverted order.
3607
 
    */
3608
 
    TableList *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
3609
 
    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. */
3610
5790
    List<String> *using_fields= table_ref->join_using_fields;
3611
 
    uint32_t found_using_fields;
 
5791
    uint found_using_fields;
3612
5792
 
3613
5793
    /*
3614
5794
      The two join operands were interchanged in the parser, change the order
3615
5795
      back for 'mark_common_columns'.
3616
5796
    */
3617
5797
    if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
3618
 
      std::swap(table_ref_1, table_ref_2);
3619
 
    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,
3620
5800
                            using_fields, &found_using_fields))
3621
5801
      goto err;
3622
5802
 
3626
5806
      same as of an equivalent LEFT JOIN.
3627
5807
    */
3628
5808
    if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
3629
 
      std::swap(table_ref_1, table_ref_2);
3630
 
    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,
3631
5811
                                         table_ref_2, using_fields,
3632
5812
                                         found_using_fields))
3633
5813
      goto err;
3640
5820
    */
3641
5821
    table_ref_1->natural_join= table_ref_2->natural_join= NULL;
3642
5822
 
3643
 
    /* 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. */
3644
5824
    if (table_ref_2->outer_join &&
3645
5825
        !table_ref_1->on_expr && !table_ref_2->on_expr)
3646
 
      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. */
3647
5827
 
3648
5828
    /* Change this table reference to become a leaf for name resolution. */
3649
5829
    if (left_neighbor)
3650
5830
    {
3651
 
      TableList *last_leaf_on_the_left;
 
5831
      TABLE_LIST *last_leaf_on_the_left;
3652
5832
      last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
3653
5833
      last_leaf_on_the_left->next_name_resolution_table= table_ref;
3654
5834
    }
3655
5835
    if (right_neighbor)
3656
5836
    {
3657
 
      TableList *first_leaf_on_the_right;
 
5837
      TABLE_LIST *first_leaf_on_the_right;
3658
5838
      first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
3659
5839
      table_ref->next_name_resolution_table= first_leaf_on_the_right;
3660
5840
    }
3661
5841
    else
3662
5842
      table_ref->next_name_resolution_table= NULL;
3663
5843
  }
3664
 
  result= false; /* All is OK. */
 
5844
  result= FALSE; /* All is OK. */
3665
5845
 
3666
5846
err:
3667
 
  return(result);
 
5847
  DBUG_RETURN(result);
3668
5848
}
3669
5849
 
3670
5850
 
3673
5853
  in a FROM clause.
3674
5854
 
3675
5855
  SYNOPSIS
3676
 
  setup_natural_join_row_types()
3677
 
  session          current thread
3678
 
  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
3679
5859
 
3680
5860
  DESCRIPTION
3681
 
  Apply the procedure 'store_top_level_join_columns' to each of the
3682
 
  top-level table referencs of the FROM clause. Adjust the list of tables
3683
 
  for name resolution - context->first_name_resolution_table to the
3684
 
  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.
3685
5865
 
3686
5866
  IMPLEMENTATION
3687
 
  Notice that the table references in 'from_clause' are in reverse
3688
 
  order, thus when we iterate over it, we are moving from the right
3689
 
  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.
3690
5870
 
3691
5871
  RETURN
3692
 
  true   Error
3693
 
  false  OK
 
5872
    TRUE   Error
 
5873
    FALSE  OK
3694
5874
*/
3695
 
static bool setup_natural_join_row_types(Session *session,
3696
 
                                         List<TableList> *from_clause,
 
5875
static bool setup_natural_join_row_types(THD *thd,
 
5876
                                         List<TABLE_LIST> *from_clause,
3697
5877
                                         Name_resolution_context *context)
3698
5878
{
3699
 
  session->where= "from clause";
 
5879
  thd->where= "from clause";
3700
5880
  if (from_clause->elements == 0)
3701
 
    return false; /* We come here in the case of UNIONs. */
 
5881
    return FALSE; /* We come here in the case of UNIONs. */
3702
5882
 
3703
 
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3704
 
  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. */
3705
5885
  /* Table reference to the left of the current. */
3706
 
  TableList *left_neighbor;
 
5886
  TABLE_LIST *left_neighbor;
3707
5887
  /* Table reference to the right of the current. */
3708
 
  TableList *right_neighbor= NULL;
 
5888
  TABLE_LIST *right_neighbor= NULL;
3709
5889
 
3710
5890
  /* Note that tables in the list are in reversed order */
3711
5891
  for (left_neighbor= table_ref_it++; left_neighbor ; )
3712
5892
  {
3713
5893
    table_ref= left_neighbor;
3714
5894
    left_neighbor= table_ref_it++;
3715
 
    if (store_top_level_join_columns(session, table_ref,
3716
 
                                     left_neighbor, right_neighbor))
3717
 
      return true;
3718
 
    if (left_neighbor)
 
5895
    /* For stored procedures do not redo work if already done. */
 
5896
    if (context->select_lex->first_execution)
3719
5897
    {
3720
 
      TableList *first_leaf_on_the_right;
3721
 
      first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
3722
 
      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
      }
3723
5907
    }
3724
5908
    right_neighbor= table_ref;
3725
5909
  }
3730
5914
    right_neighbor points to the left-most top-level table reference in the
3731
5915
    FROM clause.
3732
5916
  */
3733
 
  assert(right_neighbor);
 
5917
  DBUG_ASSERT(right_neighbor);
3734
5918
  context->first_name_resolution_table=
3735
5919
    right_neighbor->first_leaf_for_name_resolution();
3736
5920
 
3737
 
  return false;
 
5921
  return FALSE;
3738
5922
}
3739
5923
 
3740
5924
 
3741
5925
/****************************************************************************
3742
 
 ** Expand all '*' in given fields
3743
 
 ****************************************************************************/
 
5926
** Expand all '*' in given fields
 
5927
****************************************************************************/
3744
5928
 
3745
 
int setup_wild(Session *session, List<Item> &fields,
3746
 
               List<Item> *sum_func_list,
3747
 
               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)
3748
5932
{
3749
5933
  if (!wild_num)
3750
 
    return 0;
 
5934
    return(0);
3751
5935
 
3752
5936
  Item *item;
3753
5937
  List_iterator<Item> it(fields);
 
5938
  DBUG_ENTER("setup_wild");
3754
5939
 
3755
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
5940
  thd->lex->current_select->cur_pos_in_select_list= 0;
3756
5941
  while (wild_num && (item= it++))
3757
5942
  {
3758
5943
    if (item->type() == Item::FIELD_ITEM &&
3759
5944
        ((Item_field*) item)->field_name &&
3760
 
        ((Item_field*) item)->field_name[0] == '*' &&
3761
 
        !((Item_field*) item)->field)
 
5945
        ((Item_field*) item)->field_name[0] == '*' &&
 
5946
        !((Item_field*) item)->field)
3762
5947
    {
3763
 
      uint32_t elem= fields.elements;
 
5948
      uint elem= fields.elements;
3764
5949
      bool any_privileges= ((Item_field *) item)->any_privileges;
3765
 
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
 
5950
      Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
3766
5951
      if (subsel &&
3767
5952
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3768
5953
      {
3771
5956
 
3772
5957
          Item_int do not need fix_fields() because it is basic constant.
3773
5958
        */
3774
 
        it.replace(new Item_int("Not_used", (int64_t) 1,
 
5959
        it.replace(new Item_int("Not_used", (longlong) 1,
3775
5960
                                MY_INT64_NUM_DECIMAL_DIGITS));
3776
5961
      }
3777
 
      else if (insert_fields(session, ((Item_field*) item)->context,
 
5962
      else if (insert_fields(thd, ((Item_field*) item)->context,
3778
5963
                             ((Item_field*) item)->db_name,
3779
5964
                             ((Item_field*) item)->table_name, &it,
3780
5965
                             any_privileges))
3781
5966
      {
3782
 
        return -1;
 
5967
        DBUG_RETURN(-1);
3783
5968
      }
3784
5969
      if (sum_func_list)
3785
5970
      {
3786
 
        /*
3787
 
          sum_func_list is a list that has the fields list as a tail.
3788
 
          Because of this we have to update the element count also for this
3789
 
          list after expanding the '*' entry.
3790
 
        */
3791
 
        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;
3792
5977
      }
3793
5978
      wild_num--;
3794
5979
    }
3795
5980
    else
3796
 
      session->lex->current_select->cur_pos_in_select_list++;
 
5981
      thd->lex->current_select->cur_pos_in_select_list++;
3797
5982
  }
3798
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3799
 
 
3800
 
  return 0;
 
5983
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
5984
  DBUG_RETURN(0);
3801
5985
}
3802
5986
 
3803
5987
/****************************************************************************
3804
 
 ** Check that all given fields exists and fill struct with current data
3805
 
 ****************************************************************************/
 
5988
** Check that all given fields exists and fill struct with current data
 
5989
****************************************************************************/
3806
5990
 
3807
 
bool setup_fields(Session *session, Item **ref_pointer_array,
 
5991
bool setup_fields(THD *thd, Item **ref_pointer_array,
3808
5992
                  List<Item> &fields, enum_mark_columns mark_used_columns,
3809
5993
                  List<Item> *sum_func_list, bool allow_sum_func)
3810
5994
{
3811
5995
  register Item *item;
3812
 
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3813
 
  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;
3814
5998
  List_iterator<Item> it(fields);
3815
5999
  bool save_is_item_list_lookup;
 
6000
  DBUG_ENTER("setup_fields");
3816
6001
 
3817
 
  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));
3818
6004
  if (allow_sum_func)
3819
 
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
3820
 
  session->where= Session::DEFAULT_WHERE;
3821
 
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
3822
 
  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;
3823
6009
 
3824
6010
  /*
3825
6011
    To prevent fail on forward lookup we fill it with zerows,
3829
6015
    There is other way to solve problem: fill array with pointers to list,
3830
6016
    but it will be slower.
3831
6017
 
3832
 
TODO: remove it when (if) we made one list for allfields and
3833
 
ref_pointer_array
 
6018
    TODO: remove it when (if) we made one list for allfields and
 
6019
    ref_pointer_array
3834
6020
  */
3835
6021
  if (ref_pointer_array)
3836
 
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
 
6022
    bzero(ref_pointer_array, sizeof(Item *) * fields.elements);
3837
6023
 
3838
6024
  Item **ref= ref_pointer_array;
3839
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
6025
  thd->lex->current_select->cur_pos_in_select_list= 0;
3840
6026
  while ((item= it++))
3841
6027
  {
3842
 
    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))
3843
6029
    {
3844
 
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3845
 
      session->lex->allow_sum_func= save_allow_sum_func;
3846
 
      session->mark_used_columns= save_mark_used_columns;
3847
 
      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 */
3848
6035
    }
3849
6036
    if (ref)
3850
6037
      *(ref++)= item;
3851
6038
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
3852
 
        sum_func_list)
3853
 
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3854
 
    session->used_tables|= item->used_tables();
3855
 
    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++;
3856
6043
  }
3857
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3858
 
  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;
3859
6046
 
3860
 
  session->lex->allow_sum_func= save_allow_sum_func;
3861
 
  session->mark_used_columns= save_mark_used_columns;
3862
 
  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()));
3863
6051
}
3864
6052
 
3865
6053
 
3867
6055
  make list of leaves of join table tree
3868
6056
 
3869
6057
  SYNOPSIS
3870
 
  make_leaves_list()
3871
 
  list    pointer to pointer on list first element
3872
 
  tables  table list
 
6058
    make_leaves_list()
 
6059
    list    pointer to pointer on list first element
 
6060
    tables  table list
3873
6061
 
3874
6062
  RETURN pointer on pointer to next_leaf of last element
3875
6063
*/
3876
6064
 
3877
 
static TableList **make_leaves_list(TableList **list, TableList *tables)
 
6065
TABLE_LIST **make_leaves_list(TABLE_LIST **list, TABLE_LIST *tables)
3878
6066
{
3879
 
  for (TableList *table= tables; table; table= table->next_local)
 
6067
  for (TABLE_LIST *table= tables; table; table= table->next_local)
3880
6068
  {
3881
6069
    {
3882
6070
      *list= table;
3890
6078
  prepare tables
3891
6079
 
3892
6080
  SYNOPSIS
3893
 
  setup_tables()
3894
 
  session                 Thread Cursor
3895
 
  context       name resolution contest to setup table list there
3896
 
  from_clause   Top-level list of table references in the FROM clause
3897
 
  tables          Table list (select_lex->table_list)
3898
 
  leaves        List of join table leaves list (select_lex->leaf_tables)
3899
 
  refresh       It is onle refresh for subquery
3900
 
  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
3901
6089
 
3902
6090
  NOTE
3903
 
  Check also that the 'used keys' and 'ignored keys' exists and set up the
3904
 
  table structure accordingly.
3905
 
  Create a list of leaf tables. For queries with NATURAL/USING JOINs,
3906
 
  compute the row types of the top most natural/using join table references
3907
 
  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.
3908
6096
 
3909
 
  This has to be called for all tables that are used by items, as otherwise
3910
 
  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.
3911
6099
 
3912
6100
  RETURN
3913
 
  false ok;  In this case *map will includes the chosen index
3914
 
  true  error
 
6101
    FALSE ok;  In this case *map will includes the chosen index
 
6102
    TRUE  error
3915
6103
*/
3916
6104
 
3917
 
bool setup_tables(Session *session, Name_resolution_context *context,
3918
 
                  List<TableList> *from_clause, TableList *tables,
3919
 
                  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)
3920
6108
{
3921
 
  uint32_t tablenr= 0;
 
6109
  uint tablenr= 0;
 
6110
  DBUG_ENTER("setup_tables");
3922
6111
 
3923
 
  assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
3924
 
          (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));
3925
6114
  /*
3926
6115
    this is used for INSERT ... SELECT.
3927
6116
    For select we setup tables except first (and its underlying tables)
3928
6117
  */
3929
 
  TableList *first_select_table= (select_insert ?  tables->next_local: NULL);
3930
 
 
 
6118
  TABLE_LIST *first_select_table= (select_insert ?
 
6119
                                   tables->next_local:
 
6120
                                   0);
3931
6121
  if (!(*leaves))
3932
6122
    make_leaves_list(leaves, tables);
3933
6123
 
3934
 
  TableList *table_list;
 
6124
  TABLE_LIST *table_list;
3935
6125
  for (table_list= *leaves;
3936
6126
       table_list;
3937
6127
       table_list= table_list->next_leaf, tablenr++)
3938
6128
  {
3939
 
    Table *table= table_list->table;
 
6129
    TABLE *table= table_list->table;
3940
6130
    table->pos_in_table_list= table_list;
3941
6131
    if (first_select_table &&
3942
6132
        table_list->top_table() == first_select_table)
3945
6135
      first_select_table= 0;
3946
6136
      tablenr= 0;
3947
6137
    }
3948
 
    table->setup_table_map(table_list, tablenr);
 
6138
    setup_table_map(table, table_list, tablenr);
3949
6139
    if (table_list->process_index_hints(table))
3950
 
      return 1;
 
6140
      DBUG_RETURN(1);
3951
6141
  }
3952
6142
  if (tablenr > MAX_TABLES)
3953
6143
  {
3954
6144
    my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
3955
 
    return 1;
 
6145
    DBUG_RETURN(1);
3956
6146
  }
3957
6147
 
3958
6148
  /* Precompute and store the row types of NATURAL/USING joins. */
3959
 
  if (setup_natural_join_row_types(session, from_clause, context))
3960
 
    return 1;
 
6149
  if (setup_natural_join_row_types(thd, from_clause, context))
 
6150
    DBUG_RETURN(1);
3961
6151
 
3962
 
  return 0;
 
6152
  DBUG_RETURN(0);
3963
6153
}
3964
6154
 
3965
6155
 
3967
6157
  prepare tables and check access for the view tables
3968
6158
 
3969
6159
  SYNOPSIS
3970
 
  setup_tables_and_check_view_access()
3971
 
  session                 Thread Cursor
3972
 
  context       name resolution contest to setup table list there
3973
 
  from_clause   Top-level list of table references in the FROM clause
3974
 
  tables          Table list (select_lex->table_list)
3975
 
  conds   Condition of current SELECT (can be changed by VIEW)
3976
 
  leaves        List of join table leaves list (select_lex->leaf_tables)
3977
 
  refresh       It is onle refresh for subquery
3978
 
  select_insert It is SELECT ... INSERT command
3979
 
  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
3980
6170
 
3981
6171
  NOTE
3982
 
  a wrapper for check_tables that will also check the resulting
3983
 
  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
3984
6174
 
3985
6175
  RETURN
3986
 
  false ok;  In this case *map will include the chosen index
3987
 
  true  error
 
6176
    FALSE ok;  In this case *map will include the chosen index
 
6177
    TRUE  error
3988
6178
*/
3989
 
bool setup_tables_and_check_access(Session *session,
 
6179
bool setup_tables_and_check_access(THD *thd, 
3990
6180
                                   Name_resolution_context *context,
3991
 
                                   List<TableList> *from_clause,
3992
 
                                   TableList *tables,
3993
 
                                   TableList **leaves,
 
6181
                                   List<TABLE_LIST> *from_clause,
 
6182
                                   TABLE_LIST *tables,
 
6183
                                   TABLE_LIST **leaves,
3994
6184
                                   bool select_insert)
3995
6185
{
3996
 
  TableList *leaves_tmp= NULL;
 
6186
  TABLE_LIST *leaves_tmp= NULL;
 
6187
  bool first_table= true;
3997
6188
 
3998
 
  if (setup_tables(session, context, from_clause, tables,
 
6189
  if (setup_tables(thd, context, from_clause, tables,
3999
6190
                   &leaves_tmp, select_insert))
4000
 
    return true;
 
6191
    return TRUE;
4001
6192
 
4002
6193
  if (leaves)
4003
6194
    *leaves= leaves_tmp;
4004
6195
 
4005
 
  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;
4006
6245
}
4007
6246
 
4008
6247
 
4010
6249
  Drops in all fields instead of current '*' field
4011
6250
 
4012
6251
  SYNOPSIS
4013
 
  insert_fields()
4014
 
  session                       Thread Cursor
4015
 
  context             Context for name resolution
4016
 
  db_name               Database name in case of 'database_name.table_name.*'
4017
 
  table_name            Table name in case of 'table_name.*'
4018
 
  it                    Pointer to '*'
4019
 
  any_privileges        0 If we should ensure that we have SELECT privileges
4020
 
  for all columns
4021
 
  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
4022
6261
  RETURN
4023
 
  0     ok     'it' is updated to point at last inserted
4024
 
  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
4025
6264
*/
4026
6265
 
4027
6266
bool
4028
 
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
4029
 
              const char *table_name, List_iterator<Item> *it,
4030
 
              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)
4031
6270
{
4032
6271
  Field_iterator_table_ref field_iterator;
4033
6272
  bool found;
4034
6273
  char name_buff[NAME_LEN+1];
 
6274
  DBUG_ENTER("insert_fields");
4035
6275
 
4036
 
  if (db_name)
 
6276
  if (db_name && lower_case_table_names)
4037
6277
  {
4038
6278
    /*
4039
6279
      convert database to lower case for comparison
4040
6280
      We can't do this in Item_field as this would change the
4041
6281
      'name' of the item which may be used in the select list
4042
6282
    */
4043
 
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
 
6283
    strmake(name_buff, db_name, sizeof(name_buff)-1);
4044
6284
    my_casedn_str(files_charset_info, name_buff);
4045
6285
    db_name= name_buff;
4046
6286
  }
4047
6287
 
4048
 
  found= false;
 
6288
  found= FALSE;
4049
6289
 
4050
6290
  /*
4051
6291
    If table names are qualified, then loop over all tables used in the query,
4052
6292
    else treat natural joins as leaves and do not iterate over their underlying
4053
6293
    tables.
4054
6294
  */
4055
 
  for (TableList *tables= (table_name ? context->table_list :
4056
 
                           context->first_name_resolution_table);
 
6295
  for (TABLE_LIST *tables= (table_name ? context->table_list :
 
6296
                            context->first_name_resolution_table);
4057
6297
       tables;
4058
6298
       tables= (table_name ? tables->next_local :
4059
6299
                tables->next_name_resolution_table)
4060
 
      )
 
6300
       )
4061
6301
  {
4062
6302
    Field *field;
4063
 
    Table *table= tables->table;
4064
 
 
4065
 
    assert(tables->is_leaf_for_name_resolution());
4066
 
 
4067
 
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
 
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)) || 
4068
6308
        (db_name && strcmp(tables->db,db_name)))
4069
6309
      continue;
4070
6310
 
4073
6313
      views and natural joins this update is performed inside the loop below.
4074
6314
    */
4075
6315
    if (table)
4076
 
      session->used_tables|= table->map;
 
6316
      thd->used_tables|= table->map;
4077
6317
 
4078
6318
    /*
4079
6319
      Initialize a generic field iterator for the current table reference.
4087
6327
    {
4088
6328
      Item *item;
4089
6329
 
4090
 
      if (!(item= field_iterator.create_item(session)))
4091
 
        return true;
 
6330
      if (!(item= field_iterator.create_item(thd)))
 
6331
        DBUG_RETURN(TRUE);
4092
6332
 
4093
6333
      if (!found)
4094
6334
      {
4095
 
        found= true;
 
6335
        found= TRUE;
4096
6336
        it->replace(item); /* Replace '*' with the first found item. */
4097
6337
      }
4098
6338
      else
4101
6341
      if ((field= field_iterator.field()))
4102
6342
      {
4103
6343
        /* Mark fields as used to allow storage engine to optimze access */
4104
 
        field->table->setReadSet(field->field_index);
 
6344
        bitmap_set_bit(field->table->read_set, field->field_index);
4105
6345
        if (table)
4106
6346
        {
4107
 
          table->covering_keys&= field->part_of_key;
4108
 
          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);
4109
6349
        }
4110
6350
        if (tables->is_natural_join)
4111
6351
        {
4112
 
          Table *field_table;
 
6352
          TABLE *field_table;
4113
6353
          /*
4114
6354
            In this case we are sure that the column ref will not be created
4115
6355
            because it was already created and stored with the natural join.
4116
6356
          */
4117
6357
          Natural_join_column *nj_col;
4118
6358
          if (!(nj_col= field_iterator.get_natural_column_ref()))
4119
 
            return true;
4120
 
          assert(nj_col->table_field);
 
6359
            DBUG_RETURN(TRUE);
 
6360
          DBUG_ASSERT(nj_col->table_field);
4121
6361
          field_table= nj_col->table_ref->table;
4122
6362
          if (field_table)
4123
6363
          {
4124
 
            session->used_tables|= field_table->map;
4125
 
            field_table->covering_keys&= field->part_of_key;
4126
 
            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);
4127
6367
            field_table->used_fields++;
4128
6368
          }
4129
6369
        }
4130
6370
      }
4131
6371
      else
4132
 
        session->used_tables|= item->used_tables();
4133
 
      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++;
4134
6374
    }
4135
6375
    /*
4136
6376
      In case of stored tables, all fields are considered as used,
4142
6382
      table->used_fields= table->s->fields;
4143
6383
  }
4144
6384
  if (found)
4145
 
    return false;
 
6385
    DBUG_RETURN(FALSE);
4146
6386
 
4147
6387
  /*
4148
 
TODO: in the case when we skipped all columns because there was a
4149
 
qualified '*', and all columns were coalesced, we have to give a more
4150
 
meaningful message than ER_BAD_TABLE_ERROR.
 
6388
    TODO: in the case when we skipped all columns because there was a
 
6389
    qualified '*', and all columns were coalesced, we have to give a more
 
6390
    meaningful message than ER_BAD_TABLE_ERROR.
4151
6391
  */
4152
6392
  if (!table_name)
4153
6393
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
4154
6394
  else
4155
6395
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
4156
6396
 
4157
 
  return true;
 
6397
  DBUG_RETURN(TRUE);
4158
6398
}
4159
6399
 
4160
6400
 
4162
6402
  Fix all conditions and outer join expressions.
4163
6403
 
4164
6404
  SYNOPSIS
4165
 
  setup_conds()
4166
 
  session     thread Cursor
4167
 
  tables  list of tables for name resolving (select_lex->table_list)
4168
 
  leaves  list of leaves of join table tree (select_lex->leaf_tables)
4169
 
  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
4170
6410
 
4171
6411
  DESCRIPTION
4172
 
  TODO
 
6412
    TODO
4173
6413
 
4174
6414
  RETURN
4175
 
  true  if some error occured (e.g. out of memory)
4176
 
  false if all is OK
 
6415
    TRUE  if some error occured (e.g. out of memory)
 
6416
    FALSE if all is OK
4177
6417
*/
4178
6418
 
4179
 
int Session::setup_conds(TableList *leaves, COND **conds)
 
6419
int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves,
 
6420
                COND **conds)
4180
6421
{
4181
 
  Session *session= this;
4182
 
  Select_Lex *select_lex= session->lex->current_select;
4183
 
  TableList *table= NULL;       // For HP compilers
4184
 
  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;
4185
6425
  /*
4186
 
    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
4187
6427
    which belong to LEX, i.e. most up SELECT) will be updated by
4188
6428
    INSERT/UPDATE/LOAD
4189
 
    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()
4190
6430
    from subquery of VIEW, because tables of subquery belongs to VIEW
4191
6431
    (see condition before prepare_check_option() call)
4192
6432
  */
4193
6433
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
4194
6434
  select_lex->is_item_list_lookup= 0;
 
6435
  DBUG_ENTER("setup_conds");
4195
6436
 
4196
 
  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));
4197
6439
  select_lex->cond_count= 0;
4198
6440
  select_lex->between_count= 0;
4199
6441
  select_lex->max_equal_elems= 0;
4200
6442
 
4201
 
  session->session_marker= (void*)1;
 
6443
  thd->thd_marker= (void*)1;
4202
6444
  if (*conds)
4203
6445
  {
4204
 
    session->where="where clause";
4205
 
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
4206
 
        (*conds)->check_cols(1))
 
6446
    thd->where="where clause";
 
6447
    if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) ||
 
6448
        (*conds)->check_cols(1))
4207
6449
      goto err_no_arena;
4208
6450
  }
4209
 
  session->session_marker= save_session_marker;
 
6451
  thd->thd_marker= save_thd_marker;
4210
6452
 
4211
6453
  /*
4212
6454
    Apply fix_fields() to all ON clauses at all levels of nesting,
4214
6456
  */
4215
6457
  for (table= leaves; table; table= table->next_leaf)
4216
6458
  {
4217
 
    TableList *embedded; /* The table at the current level of nesting. */
4218
 
    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. */
4219
6461
    do
4220
6462
    {
4221
6463
      embedded= embedding;
4222
6464
      if (embedded->on_expr)
4223
6465
      {
4224
6466
        /* Make a join an a expression */
4225
 
        session->session_marker= (void*)embedded;
4226
 
        session->where="on clause";
4227
 
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
4228
 
            embedded->on_expr->check_cols(1))
4229
 
          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;
4230
6472
        select_lex->cond_count++;
4231
6473
      }
4232
6474
      embedding= embedded->embedding;
4235
6477
           embedding->nested_join->join_list.head() == embedded);
4236
6478
 
4237
6479
  }
4238
 
  session->session_marker= save_session_marker;
 
6480
  thd->thd_marker= save_thd_marker;
4239
6481
 
4240
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
4241
 
  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()));
4242
6484
 
4243
6485
err_no_arena:
4244
6486
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
4245
 
 
4246
 
  return 1;
 
6487
  DBUG_RETURN(1);
4247
6488
}
4248
6489
 
4249
6490
 
4250
6491
/******************************************************************************
4251
 
 ** Fill a record with data (for INSERT or UPDATE)
4252
 
 ** Returns : 1 if some field has wrong type
4253
 
 ******************************************************************************/
 
6492
** Fill a record with data (for INSERT or UPDATE)
 
6493
** Returns : 1 if some field has wrong type
 
6494
******************************************************************************/
4254
6495
 
4255
6496
 
4256
6497
/*
4257
6498
  Fill fields with given items.
4258
6499
 
4259
6500
  SYNOPSIS
4260
 
  fill_record()
4261
 
  fields        Item_fields list to be filled
4262
 
  values        values to fill with
4263
 
  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
4264
6506
 
4265
6507
  NOTE
4266
 
  fill_record() may set table->auto_increment_field_not_null and a
4267
 
  caller should make sure that it is reset after their last call to this
4268
 
  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.
4269
6511
 
4270
6512
  RETURN
4271
 
  false   OK
4272
 
  true    error occured
 
6513
    FALSE   OK
 
6514
    TRUE    error occured
4273
6515
*/
4274
6516
 
4275
6517
bool
4276
 
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)
4277
6519
{
4278
6520
  List_iterator_fast<Item> f(fields),v(values);
4279
 
  Item *value;
 
6521
  Item *value, *fld;
4280
6522
  Item_field *field;
4281
 
  Table *table;
 
6523
  TABLE *table= 0;
 
6524
  DBUG_ENTER("fill_record");
4282
6525
 
4283
6526
  /*
4284
6527
    Reset the table->auto_increment_field_not_null as it is valid for
4290
6533
      On INSERT or UPDATE fields are checked to be from the same table,
4291
6534
      thus we safely can take table from the first field.
4292
6535
    */
4293
 
    field= static_cast<Item_field *>(f++);
 
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
    }
4294
6542
    table= field->field->table;
4295
 
    table->auto_increment_field_not_null= false;
 
6543
    table->auto_increment_field_not_null= FALSE;
4296
6544
    f.rewind();
4297
6545
  }
4298
 
 
4299
 
  while ((field= static_cast<Item_field *>(f++)))
 
6546
  while ((fld= f++))
4300
6547
  {
4301
 
    value= v++;
4302
 
 
 
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++;
4303
6554
    Field *rfield= field->field;
4304
6555
    table= rfield->table;
4305
 
 
4306
6556
    if (rfield == table->next_number_field)
4307
 
      table->auto_increment_field_not_null= true;
 
6557
      table->auto_increment_field_not_null= TRUE;
4308
6558
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
4309
6559
    {
4310
6560
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
4311
6561
      goto err;
4312
6562
    }
4313
6563
  }
4314
 
 
4315
 
  return session->is_error();
4316
 
 
 
6564
  DBUG_RETURN(thd->is_error());
4317
6565
err:
4318
6566
  if (table)
4319
 
    table->auto_increment_field_not_null= false;
4320
 
 
4321
 
  return true;
 
6567
    table->auto_increment_field_not_null= FALSE;
 
6568
  DBUG_RETURN(TRUE);
4322
6569
}
4323
6570
 
4324
6571
 
4326
6573
  Fill field buffer with values from Field list
4327
6574
 
4328
6575
  SYNOPSIS
4329
 
  fill_record()
4330
 
  ptr           pointer on pointer to record
4331
 
  values        list of fields
4332
 
  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
4333
6581
 
4334
6582
  NOTE
4335
 
  fill_record() may set table->auto_increment_field_not_null and a
4336
 
  caller should make sure that it is reset after their last call to this
4337
 
  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.
4338
6586
 
4339
6587
  RETURN
4340
 
  false   OK
4341
 
  true    error occured
 
6588
    FALSE   OK
 
6589
    TRUE    error occured
4342
6590
*/
4343
6591
 
4344
 
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)
4345
6594
{
4346
6595
  List_iterator_fast<Item> v(values);
4347
6596
  Item *value;
4348
 
  Table *table= 0;
 
6597
  TABLE *table= 0;
 
6598
  DBUG_ENTER("fill_record");
 
6599
 
4349
6600
  Field *field;
4350
 
 
4351
6601
  /*
4352
6602
    Reset the table->auto_increment_field_not_null as it is valid for
4353
6603
    only one row.
4359
6609
      thus we safely can take table from the first field.
4360
6610
    */
4361
6611
    table= (*ptr)->table;
4362
 
    table->auto_increment_field_not_null= false;
 
6612
    table->auto_increment_field_not_null= FALSE;
4363
6613
  }
4364
 
  while ((field = *ptr++) && ! session->is_error())
 
6614
  while ((field = *ptr++) && ! thd->is_error())
4365
6615
  {
4366
6616
    value=v++;
4367
6617
    table= field->table;
4368
6618
    if (field == table->next_number_field)
4369
 
      table->auto_increment_field_not_null= true;
 
6619
      table->auto_increment_field_not_null= TRUE;
4370
6620
    if (value->save_in_field(field, 0) < 0)
4371
6621
      goto err;
4372
6622
  }
4373
 
 
4374
 
  return(session->is_error());
 
6623
  DBUG_RETURN(thd->is_error());
4375
6624
 
4376
6625
err:
4377
6626
  if (table)
4378
 
    table->auto_increment_field_not_null= false;
4379
 
 
4380
 
  return true;
 
6627
    table->auto_increment_field_not_null= FALSE;
 
6628
  DBUG_RETURN(TRUE);
4381
6629
}
4382
6630
 
4383
6631
 
4384
 
bool drizzle_rm_tmp_tables()
 
6632
my_bool mysql_rm_tmp_tables(void)
4385
6633
{
4386
 
  Session *session;
4387
 
 
4388
 
  assert(drizzle_tmpdir);
4389
 
 
4390
 
  if (!(session= new Session(plugin::Listen::getNullClient())))
4391
 
    return true;
4392
 
  session->thread_stack= (char*) &session;
4393
 
  session->storeGlobals();
4394
 
 
4395
 
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir);
4396
 
 
4397
 
  delete session;
4398
 
 
4399
 
  return false;
 
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++)
 
6657
    {
 
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
      }
 
6696
    }
 
6697
    my_dirend(dirp);
 
6698
  }
 
6699
  delete thd;
 
6700
  my_pthread_setspecific_ptr(THR_THD,  0);
 
6701
  DBUG_RETURN(0);
4400
6702
}
4401
6703
 
4402
6704
 
4403
6705
 
4404
6706
/*****************************************************************************
4405
 
  unireg support functions
4406
 
 *****************************************************************************/
 
6707
        unireg support functions
 
6708
*****************************************************************************/
4407
6709
 
4408
6710
/*
4409
6711
  Invalidate any cache entries that are for some DB
4410
6712
 
4411
6713
  SYNOPSIS
4412
 
  remove_db_from_cache()
4413
 
  db            Database name. This will be in lower case if
4414
 
  lower_case_table_name is set
 
6714
    remove_db_from_cache()
 
6715
    db          Database name. This will be in lower case if
 
6716
                lower_case_table_name is set
4415
6717
 
4416
 
NOTE:
4417
 
We can't use hash_delete when looping hash_elements. We mark them first
4418
 
and afterwards delete those marked unused.
 
6718
  NOTE:
 
6719
  We can't use hash_delete when looping hash_elements. We mark them first
 
6720
  and afterwards delete those marked unused.
4419
6721
*/
4420
6722
 
4421
6723
void remove_db_from_cache(const char *db)
4422
6724
{
4423
 
  safe_mutex_assert_owner(&LOCK_open);
4424
 
 
4425
 
  for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
 
6725
  for (uint idx=0 ; idx < open_cache.records ; idx++)
4426
6726
  {
4427
 
    Table *table=(Table*) hash_element(&open_cache,idx);
 
6727
    TABLE *table=(TABLE*) hash_element(&open_cache,idx);
4428
6728
    if (!strcmp(table->s->db.str, db))
4429
6729
    {
4430
6730
      table->s->version= 0L;                    /* Free when thread is ready */
4431
6731
      if (!table->in_use)
4432
 
        relink_unused(table);
 
6732
        relink_unused(table);
4433
6733
    }
4434
6734
  }
4435
6735
  while (unused_tables && !unused_tables->s->version)
4436
 
    hash_delete(&open_cache,(unsigned char*) unused_tables);
 
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);
4437
6754
}
4438
6755
 
4439
6756
 
4444
6761
  close_thread_tables() is called.
4445
6762
 
4446
6763
  PREREQUISITES
4447
 
  Lock on LOCK_open()
 
6764
    Lock on LOCK_open()
4448
6765
 
4449
6766
  RETURN
4450
 
  0  This thread now have exclusive access to this table and no other thread
4451
 
  can access the table until close_thread_tables() is called.
4452
 
  1  Table is in use by another thread
 
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
4453
6770
*/
4454
6771
 
4455
 
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
4456
 
                             uint32_t flags)
 
6772
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
 
6773
                             uint flags)
4457
6774
{
4458
6775
  char key[MAX_DBKEY_LENGTH];
4459
 
  char *key_pos= key;
4460
 
  uint32_t key_length;
4461
 
  Table *table;
4462
 
  bool result= false; 
4463
 
  bool signalled= false;
4464
 
 
4465
 
  key_pos= strcpy(key_pos, db) + strlen(db);
4466
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
4467
 
  key_length= (uint32_t) (key_pos-key)+1;
4468
 
 
 
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;
4469
6784
  for (;;)
4470
6785
  {
4471
6786
    HASH_SEARCH_STATE state;
4472
 
    result= signalled= false;
 
6787
    result= signalled= 0;
4473
6788
 
4474
 
    for (table= (Table*) hash_first(&open_cache, (unsigned char*) key, key_length,
 
6789
    for (table= (TABLE*) hash_first(&open_cache, (uchar*) key, key_length,
4475
6790
                                    &state);
4476
6791
         table;
4477
 
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
 
6792
         table= (TABLE*) hash_next(&open_cache, (uchar*) key, key_length,
4478
6793
                                   &state))
4479
6794
    {
4480
 
      Session *in_use;
 
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));
4481
6798
 
4482
6799
      table->s->version=0L;             /* Free when thread is ready */
4483
6800
      if (!(in_use=table->in_use))
4484
6801
      {
 
6802
        DBUG_PRINT("info",("Table was not in use"));
4485
6803
        relink_unused(table);
4486
6804
      }
4487
 
      else if (in_use != session)
 
6805
      else if (in_use != thd)
4488
6806
      {
 
6807
        DBUG_PRINT("info", ("Table was in use by other thread"));
4489
6808
        /*
4490
6809
          Mark that table is going to be deleted from cache. This will
4491
6810
          force threads that are in mysql_lock_tables() (but not yet
4492
6811
          in thr_multi_lock()) to abort it's locks, close all tables and retry
4493
6812
        */
4494
 
        in_use->some_tables_deleted= true;
 
6813
        in_use->some_tables_deleted= 1;
4495
6814
        if (table->is_name_opened())
4496
6815
        {
4497
 
          result= true;
 
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);
4498
6833
        }
4499
6834
        /*
4500
 
          Now we must abort all tables locks used by this thread
4501
 
          as the thread may be waiting to get a lock for another table.
 
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.
4502
6837
          Note that we need to hold LOCK_open while going through the
4503
6838
          list. So that the other thread cannot change it. The other
4504
6839
          thread must also hold LOCK_open whenever changing the
4505
6840
          open_tables list. Aborting the MERGE lock after a child was
4506
6841
          closed and before the parent is closed would be fatal.
4507
6842
        */
4508
 
        for (Table *session_table= in_use->open_tables;
4509
 
             session_table ;
4510
 
             session_table= session_table->next)
 
6843
        for (TABLE *thd_table= in_use->open_tables;
 
6844
             thd_table ;
 
6845
             thd_table= thd_table->next)
4511
6846
        {
4512
6847
          /* Do not handle locks of MERGE children. */
4513
 
          if (session_table->db_stat)   // If table is open
4514
 
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
6848
          if (thd_table->db_stat)       // If table is open
 
6849
            signalled|= mysql_lock_abort_for_thread(thd, thd_table);
4515
6850
        }
4516
6851
      }
4517
6852
      else
4518
 
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
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
      }
4519
6858
    }
4520
6859
    while (unused_tables && !unused_tables->s->version)
4521
 
      hash_delete(&open_cache,(unsigned char*) unused_tables);
 
6860
      VOID(hash_delete(&open_cache,(uchar*) unused_tables));
4522
6861
 
 
6862
    DBUG_PRINT("info", ("Removing table from table_def_cache"));
4523
6863
    /* Remove table from table definition cache if it's not in use */
4524
 
    TableShare::release(key, key_length);
 
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
    }
4525
6876
 
4526
6877
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
4527
6878
    {
4530
6881
        reopen their tables
4531
6882
      */
4532
6883
      broadcast_refresh();
4533
 
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
6884
      DBUG_PRINT("info", ("Waiting for refresh signal"));
 
6885
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed)
4534
6886
      {
4535
6887
        dropping_tables++;
4536
6888
        if (likely(signalled))
4542
6894
            It can happen that another thread has opened the
4543
6895
            table but has not yet locked any table at all. Since
4544
6896
            it can be locked waiting for a table that our thread
4545
 
            has done LOCK Table x WRITE on previously, we need to
 
6897
            has done LOCK TABLE x WRITE on previously, we need to
4546
6898
            ensure that the thread actually hears our signal
4547
6899
            before we go to sleep. Thus we wait for a short time
4548
6900
            and then we retry another loop in the
4557
6909
    }
4558
6910
    break;
4559
6911
  }
4560
 
  return result;
4561
 
}
4562
 
 
 
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
}
4563
7039
 
4564
7040
/**
4565
7041
  @} (end of group Data_Dictionary)
4566
7042
*/
4567
 
 
4568
 
void kill_drizzle(void)
4569
 
{
4570
 
  pthread_kill(signal_thread, SIGTERM);
4571
 
  shutdown_in_progress= 1;                      // Safety if kill didn't work
4572
 
}
4573
 
 
4574
 
} /* namespace drizzled */