~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-10-16 10:27:33 UTC
  • mfrom: (1183.1.4 merge)
  • Revision ID: brian@gaz-20091016102733-b10po5oup0hjlilh
MergeĀ EngineĀ changes.

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