~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty Taylor
  • Date: 2009-10-06 19:37:52 UTC
  • mto: This revision was merged to the branch mainline in revision 1184.
  • Revision ID: mordred@inaugust.com-20091006193752-4dx2c8u35j4em79g
Removed more server_includes.h from headers.

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