~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-02-21 00:18:15 UTC
  • Revision ID: brian@tangent.org-20090221001815-x20e8h71e984lvs1
Completion (?) of uint conversion.

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