~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty Taylor
  • Date: 2009-04-14 19:16:51 UTC
  • mto: (997.2.5 mordred)
  • mto: This revision was merged to the branch mainline in revision 994.
  • Revision ID: mordred@inaugust.com-20090414191651-ltbww6hpqks8k7qk
Clarified instructions in README.

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