~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2010-02-07 01:33:54 UTC
  • Revision ID: brian@gaz-20100207013354-d2pg1n68u5c09pgo
Remove giant include header to its own file.

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