~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty
  • Date: 2008-10-02 05:41:33 UTC
  • mfrom: (398.1.10 codestyle)
  • Revision ID: mordred@scylla.inaugust.com-20081002054133-tyxv5bmqpazfaqqi
Merged up to 408 of stdint-includes-fix.

Show diffs side-by-side

added added

removed removed

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