~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Mark Atwood
  • Date: 2008-10-16 11:33:16 UTC
  • mto: (520.1.13 drizzle)
  • mto: This revision was merged to the branch mainline in revision 530.
  • Revision ID: mark@fallenpegasus.com-20081016113316-ff6jdt31ck90sjdh
an implemention of the errmsg plugin

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