~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-01-24 09:43:35 UTC
  • Revision ID: brian@gir-3.local-20090124094335-6qdtvc35gl5fvivz
Adding in an example singe thread scheduler

Show diffs side-by-side

added added

removed removed

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