~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Jay Pipes
  • Date: 2008-12-19 22:19:30 UTC
  • mto: This revision was merged to the branch mainline in revision 729.
  • Revision ID: jpipes@serialcoder-20081219221930-62lqxsl72kqxhtau
Fixes negation_elimination.test. Differences in EXPLAIN output were simply due to length of column differences

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