~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2009-06-05 05:40:36 UTC
  • mfrom: (1046.1.15 merge)
  • Revision ID: brian@gaz-20090605054036-1024tm3gv0oloipw
Merge of Brian

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