~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Brian Aker
  • Date: 2008-10-18 15:43:20 UTC
  • mto: (492.3.20 drizzle-clean-code)
  • mto: This revision was merged to the branch mainline in revision 530.
  • Revision ID: brian@tangent.org-20081018154320-jc9jyij3mdf08abp
Updating tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Some general useful functions */
18
18
 
19
 
#include <config.h>
20
 
 
21
 
#include <float.h>
22
 
#include <fcntl.h>
23
 
 
24
 
#include <string>
25
 
#include <vector>
26
 
#include <algorithm>
27
 
 
28
 
#include <drizzled/error.h>
29
 
#include <drizzled/gettext.h>
30
 
 
31
 
#include <drizzled/plugin/transactional_storage_engine.h>
32
 
#include <drizzled/plugin/authorization.h>
33
 
#include <drizzled/nested_join.h>
34
 
#include <drizzled/sql_parse.h>
35
 
#include <drizzled/item/sum.h>
36
 
#include <drizzled/table_list.h>
37
 
#include <drizzled/session.h>
38
 
#include <drizzled/sql_base.h>
39
 
#include <drizzled/sql_select.h>
40
 
#include <drizzled/field/blob.h>
41
 
#include <drizzled/field/varstring.h>
42
 
#include <drizzled/field/double.h>
43
 
#include <drizzled/unireg.h>
44
 
#include <drizzled/message/table.pb.h>
45
 
#include <drizzled/sql_table.h>
46
 
#include <drizzled/charset.h>
47
 
#include <drizzled/internal/m_string.h>
48
 
#include <plugin/myisam/myisam.h>
49
 
#include <drizzled/plugin/storage_engine.h>
50
 
 
51
 
#include <drizzled/item/string.h>
52
 
#include <drizzled/item/int.h>
53
 
#include <drizzled/item/decimal.h>
54
 
#include <drizzled/item/float.h>
55
 
#include <drizzled/item/null.h>
56
 
#include <drizzled/temporal.h>
57
 
 
58
 
#include <drizzled/refresh_version.h>
59
 
 
60
 
#include <drizzled/table/singular.h>
61
 
 
62
 
#include <drizzled/table_proto.h>
63
 
#include <drizzled/typelib.h>
64
 
 
65
 
using namespace std;
66
 
 
67
 
namespace drizzled
68
 
{
69
 
 
70
 
extern plugin::StorageEngine *heap_engine;
71
 
extern plugin::StorageEngine *myisam_engine;
72
 
 
73
 
/* Functions defined in this cursor */
 
19
#include <drizzled/server_includes.h>
 
20
#include <drizzled/drizzled_error_messages.h>
 
21
 
 
22
#include "tmp_table.h"
 
23
#include "sj_tmp_table.h"
 
24
 
 
25
/* INFORMATION_SCHEMA name */
 
26
LEX_STRING INFORMATION_SCHEMA_NAME= {C_STRING_WITH_LEN("information_schema")};
 
27
 
 
28
/* Keyword for parsing virtual column functions */
 
29
LEX_STRING parse_vcol_keyword= { C_STRING_WITH_LEN("PARSE_VCOL_EXPR ") };
 
30
 
 
31
/* Functions defined in this file */
 
32
 
 
33
void open_table_error(TABLE_SHARE *share, int error, int db_errno,
 
34
                      myf errortype, int errarg);
 
35
static int open_binary_frm(THD *thd, TABLE_SHARE *share,
 
36
                           unsigned char *head, File file);
 
37
static void fix_type_pointers(const char ***array, TYPELIB *point_to_type,
 
38
                              uint32_t types, char **names);
 
39
static uint32_t find_field(Field **fields, unsigned char *record, uint32_t start, uint32_t length);
74
40
 
75
41
/*************************************************************************/
76
42
 
77
 
// @note this should all be the destructor
78
 
int Table::delete_table(bool free_share)
79
 
{
80
 
  int error= 0;
81
 
 
82
 
  if (db_stat)
83
 
    error= cursor->close();
84
 
  _alias.clear();
85
 
 
86
 
  if (field)
87
 
  {
88
 
    for (Field **ptr=field ; *ptr ; ptr++)
89
 
    {
 
43
/* Get column name from column hash */
 
44
 
 
45
static unsigned char *get_field_name(Field **buff, size_t *length,
 
46
                             bool not_used __attribute__((unused)))
 
47
{
 
48
  *length= (uint) strlen((*buff)->field_name);
 
49
  return (unsigned char*) (*buff)->field_name;
 
50
}
 
51
 
 
52
 
 
53
/*
 
54
  Returns pointer to '.frm' extension of the file name.
 
55
 
 
56
  SYNOPSIS
 
57
    fn_rext()
 
58
    name       file name
 
59
 
 
60
  DESCRIPTION
 
61
    Checks file name part starting with the rightmost '.' character,
 
62
    and returns it if it is equal to '.frm'. 
 
63
 
 
64
  TODO
 
65
    It is a good idea to get rid of this function modifying the code
 
66
    to garantee that the functions presently calling fn_rext() always
 
67
    get arguments in the same format: either with '.frm' or without '.frm'.
 
68
 
 
69
  RETURN VALUES
 
70
    Pointer to the '.frm' extension. If there is no extension,
 
71
    or extension is not '.frm', pointer at the end of file name.
 
72
*/
 
73
 
 
74
char *fn_rext(char *name)
 
75
{
 
76
  char *res= strrchr(name, '.');
 
77
  if (res && !strcmp(res, reg_ext))
 
78
    return res;
 
79
  return name + strlen(name);
 
80
}
 
81
 
 
82
TABLE_CATEGORY get_table_category(const LEX_STRING *db, const LEX_STRING *name)
 
83
{
 
84
  assert(db != NULL);
 
85
  assert(name != NULL);
 
86
 
 
87
  if ((db->length == INFORMATION_SCHEMA_NAME.length) &&
 
88
      (my_strcasecmp(system_charset_info,
 
89
                    INFORMATION_SCHEMA_NAME.str,
 
90
                    db->str) == 0))
 
91
  {
 
92
    return TABLE_CATEGORY_INFORMATION;
 
93
  }
 
94
 
 
95
  return TABLE_CATEGORY_USER;
 
96
}
 
97
 
 
98
 
 
99
/*
 
100
  Allocate a setup TABLE_SHARE structure
 
101
 
 
102
  SYNOPSIS
 
103
    alloc_table_share()
 
104
    TableList           Take database and table name from there
 
105
    key                 Table cache key (db \0 table_name \0...)
 
106
    key_length          Length of key
 
107
 
 
108
  RETURN
 
109
    0  Error (out of memory)
 
110
    #  Share
 
111
*/
 
112
 
 
113
TABLE_SHARE *alloc_table_share(TableList *table_list, char *key,
 
114
                               uint32_t key_length)
 
115
{
 
116
  MEM_ROOT mem_root;
 
117
  TABLE_SHARE *share;
 
118
  char *key_buff, *path_buff;
 
119
  char path[FN_REFLEN];
 
120
  uint32_t path_length;
 
121
 
 
122
  path_length= build_table_filename(path, sizeof(path) - 1,
 
123
                                    table_list->db,
 
124
                                    table_list->table_name, "", 0);
 
125
  init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
126
  if (multi_alloc_root(&mem_root,
 
127
                       &share, sizeof(*share),
 
128
                       &key_buff, key_length,
 
129
                       &path_buff, path_length + 1,
 
130
                       NULL))
 
131
  {
 
132
    memset(share, 0, sizeof(*share));
 
133
 
 
134
    share->set_table_cache_key(key_buff, key, key_length);
 
135
 
 
136
    share->path.str= path_buff;
 
137
    share->path.length= path_length;
 
138
    my_stpcpy(share->path.str, path);
 
139
    share->normalized_path.str=    share->path.str;
 
140
    share->normalized_path.length= path_length;
 
141
 
 
142
    share->version=       refresh_version;
 
143
 
 
144
    /*
 
145
      This constant is used to mark that no table map version has been
 
146
      assigned.  No arithmetic is done on the value: it will be
 
147
      overwritten with a value taken from DRIZZLE_BIN_LOG.
 
148
    */
 
149
    share->table_map_version= UINT64_MAX;
 
150
 
 
151
    /*
 
152
      Since alloc_table_share() can be called without any locking (for
 
153
      example, ha_create_table... functions), we do not assign a table
 
154
      map id here.  Instead we assign a value that is not used
 
155
      elsewhere, and then assign a table map id inside open_table()
 
156
      under the protection of the LOCK_open mutex.
 
157
    */
 
158
    share->table_map_id= UINT32_MAX;
 
159
    share->cached_row_logging_check= -1;
 
160
 
 
161
    memcpy(&share->mem_root, &mem_root, sizeof(mem_root));
 
162
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
 
163
    pthread_cond_init(&share->cond, NULL);
 
164
  }
 
165
  return(share);
 
166
}
 
167
 
 
168
 
 
169
/*
 
170
  Initialize share for temporary tables
 
171
 
 
172
  SYNOPSIS
 
173
    init_tmp_table_share()
 
174
    thd         thread handle
 
175
    share       Share to fill
 
176
    key         Table_cache_key, as generated from create_table_def_key.
 
177
                must start with db name.    
 
178
    key_length  Length of key
 
179
    table_name  Table name
 
180
    path        Path to file (possible in lower case) without .frm
 
181
 
 
182
  NOTES
 
183
    This is different from alloc_table_share() because temporary tables
 
184
    don't have to be shared between threads or put into the table def
 
185
    cache, so we can do some things notable simpler and faster
 
186
 
 
187
    If table is not put in thd->temporary_tables (happens only when
 
188
    one uses OPEN TEMPORARY) then one can specify 'db' as key and
 
189
    use key_length= 0 as neither table_cache_key or key_length will be used).
 
190
*/
 
191
 
 
192
void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
 
193
                          uint32_t key_length, const char *table_name,
 
194
                          const char *path)
 
195
{
 
196
 
 
197
  memset(share, 0, sizeof(*share));
 
198
  init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
199
  share->table_category=         TABLE_CATEGORY_TEMPORARY;
 
200
  share->tmp_table=              INTERNAL_TMP_TABLE;
 
201
  share->db.str=                 (char*) key;
 
202
  share->db.length=              strlen(key);
 
203
  share->table_cache_key.str=    (char*) key;
 
204
  share->table_cache_key.length= key_length;
 
205
  share->table_name.str=         (char*) table_name;
 
206
  share->table_name.length=      strlen(table_name);
 
207
  share->path.str=               (char*) path;
 
208
  share->normalized_path.str=    (char*) path;
 
209
  share->path.length= share->normalized_path.length= strlen(path);
 
210
  share->frm_version=            FRM_VER_TRUE_VARCHAR;
 
211
  /*
 
212
    Temporary tables are not replicated, but we set up these fields
 
213
    anyway to be able to catch errors.
 
214
   */
 
215
  share->table_map_version= ~(uint64_t)0;
 
216
  share->cached_row_logging_check= -1;
 
217
 
 
218
  /*
 
219
    table_map_id is also used for MERGE tables to suppress repeated
 
220
    compatibility checks.
 
221
  */
 
222
  share->table_map_id= (ulong) thd->query_id;
 
223
 
 
224
  return;
 
225
}
 
226
 
 
227
 
 
228
/*
 
229
  Free table share and memory used by it
 
230
 
 
231
  SYNOPSIS
 
232
    free_table_share()
 
233
    share               Table share
 
234
 
 
235
  NOTES
 
236
    share->mutex must be locked when we come here if it's not a temp table
 
237
*/
 
238
 
 
239
void free_table_share(TABLE_SHARE *share)
 
240
{
 
241
  MEM_ROOT mem_root;
 
242
  assert(share->ref_count == 0);
 
243
 
 
244
  /*
 
245
    If someone is waiting for this to be deleted, inform it about this.
 
246
    Don't do a delete until we know that no one is refering to this anymore.
 
247
  */
 
248
  if (share->tmp_table == NO_TMP_TABLE)
 
249
  {
 
250
    /* share->mutex is locked in release_table_share() */
 
251
    while (share->waiting_on_cond)
 
252
    {
 
253
      pthread_cond_broadcast(&share->cond);
 
254
      pthread_cond_wait(&share->cond, &share->mutex);
 
255
    }
 
256
    /* No thread refers to this anymore */
 
257
    pthread_mutex_unlock(&share->mutex);
 
258
    pthread_mutex_destroy(&share->mutex);
 
259
    pthread_cond_destroy(&share->cond);
 
260
  }
 
261
  hash_free(&share->name_hash);
 
262
  
 
263
  plugin_unlock(NULL, share->db_plugin);
 
264
  share->db_plugin= NULL;
 
265
 
 
266
  /* We must copy mem_root from share because share is allocated through it */
 
267
  memcpy(&mem_root, &share->mem_root, sizeof(mem_root));
 
268
  free_root(&mem_root, MYF(0));                 // Free's share
 
269
  return;
 
270
}
 
271
 
 
272
/*
 
273
  Read table definition from a binary / text based .frm file
 
274
  
 
275
  SYNOPSIS
 
276
  open_table_def()
 
277
  thd           Thread handler
 
278
  share         Fill this with table definition
 
279
  db_flags      Bit mask of the following flags: OPEN_VIEW
 
280
 
 
281
  NOTES
 
282
    This function is called when the table definition is not cached in
 
283
    table_def_cache
 
284
    The data is returned in 'share', which is alloced by
 
285
    alloc_table_share().. The code assumes that share is initialized.
 
286
 
 
287
  RETURN VALUES
 
288
   0    ok
 
289
   1    Error (see open_table_error)
 
290
   2    Error (see open_table_error)
 
291
   3    Wrong data in .frm file
 
292
   4    Error (see open_table_error)
 
293
   5    Error (see open_table_error: charset unavailable)
 
294
   6    Unknown .frm version
 
295
*/
 
296
 
 
297
int open_table_def(THD *thd, TABLE_SHARE *share, uint32_t db_flags  __attribute__((unused)))
 
298
{
 
299
  int error, table_type;
 
300
  bool error_given;
 
301
  File file;
 
302
  unsigned char head[64], *disk_buff;
 
303
  char  path[FN_REFLEN];
 
304
  MEM_ROOT **root_ptr, *old_root;
 
305
 
 
306
  error= 1;
 
307
  error_given= 0;
 
308
  disk_buff= NULL;
 
309
 
 
310
  strxmov(path, share->normalized_path.str, reg_ext, NULL);
 
311
  if ((file= open(path, O_RDONLY)) < 0)
 
312
  {
 
313
    /*
 
314
      We don't try to open 5.0 unencoded name, if
 
315
      - non-encoded name contains '@' signs, 
 
316
        because '@' can be misinterpreted.
 
317
        It is not clear if '@' is escape character in 5.1,
 
318
        or a normal character in 5.0.
 
319
        
 
320
      - non-encoded db or table name contain "#mysql50#" prefix.
 
321
        This kind of tables must have been opened only by the
 
322
        open() above.
 
323
    */
 
324
    if (strchr(share->table_name.str, '@') ||
 
325
        !strncmp(share->db.str, MYSQL50_TABLE_NAME_PREFIX,
 
326
                 MYSQL50_TABLE_NAME_PREFIX_LENGTH) ||
 
327
        !strncmp(share->table_name.str, MYSQL50_TABLE_NAME_PREFIX,
 
328
                 MYSQL50_TABLE_NAME_PREFIX_LENGTH))
 
329
      goto err_not_open;
 
330
 
 
331
    /* Try unencoded 5.0 name */
 
332
    uint32_t length;
 
333
    strxnmov(path, sizeof(path)-1,
 
334
             mysql_data_home, "/", share->db.str, "/",
 
335
             share->table_name.str, reg_ext, NULL);
 
336
    length= unpack_filename(path, path) - reg_ext_length;
 
337
    /*
 
338
      The following is a safety test and should never fail
 
339
      as the old file name should never be longer than the new one.
 
340
    */
 
341
    assert(length <= share->normalized_path.length);
 
342
    /*
 
343
      If the old and the new names have the same length,
 
344
      then table name does not have tricky characters,
 
345
      so no need to check the old file name.
 
346
    */
 
347
    if (length == share->normalized_path.length ||
 
348
        ((file= open(path, O_RDONLY)) < 0))
 
349
      goto err_not_open;
 
350
 
 
351
    /* Unencoded 5.0 table name found */
 
352
    path[length]= '\0'; // Remove .frm extension
 
353
    my_stpcpy(share->normalized_path.str, path);
 
354
    share->normalized_path.length= length;
 
355
  }
 
356
 
 
357
  error= 4;
 
358
  if (my_read(file, head, 64, MYF(MY_NABP)))
 
359
    goto err;
 
360
 
 
361
  if (head[0] == (unsigned char) 254 && head[1] == 1)
 
362
  {
 
363
    if (head[2] == FRM_VER || head[2] == FRM_VER+1 ||
 
364
        (head[2] >= FRM_VER+3 && head[2] <= FRM_VER+4))
 
365
    {
 
366
      table_type= 1;
 
367
    }
 
368
    else
 
369
    {
 
370
      error= 6;                                 // Unkown .frm version
 
371
      goto err;
 
372
    }
 
373
  }
 
374
  else
 
375
    goto err;
 
376
 
 
377
  /* No handling of text based files yet */
 
378
  if (table_type == 1)
 
379
  {
 
380
    root_ptr= (MEM_ROOT **)pthread_getspecific(THR_MALLOC);
 
381
    old_root= *root_ptr;
 
382
    *root_ptr= &share->mem_root;
 
383
    error= open_binary_frm(thd, share, head, file);
 
384
    *root_ptr= old_root;
 
385
    error_given= 1;
 
386
  }
 
387
  else
 
388
    assert(1);
 
389
 
 
390
  share->table_category= get_table_category(& share->db, & share->table_name);
 
391
 
 
392
  if (!error)
 
393
    thd->status_var.opened_shares++;
 
394
 
 
395
err:
 
396
  my_close(file, MYF(MY_WME));
 
397
 
 
398
err_not_open:
 
399
  if (error && !error_given)
 
400
  {
 
401
    share->error= error;
 
402
    open_table_error(share, error, (share->open_errno= my_errno), 0);
 
403
  }
 
404
 
 
405
  return(error);
 
406
}
 
407
 
 
408
 
 
409
/*
 
410
  Read data from a binary .frm file from MySQL 3.23 - 5.0 into TABLE_SHARE
 
411
*/
 
412
 
 
413
static int open_binary_frm(THD *thd, TABLE_SHARE *share, unsigned char *head,
 
414
                           File file)
 
415
{
 
416
  int error, errarg= 0;
 
417
  uint32_t new_frm_ver, field_pack_length, new_field_pack_flag;
 
418
  uint32_t interval_count, interval_parts, read_length, int_length;
 
419
  uint32_t db_create_options, keys, key_parts, n_length;
 
420
  uint32_t key_info_length, com_length, null_bit_pos=0;
 
421
  uint32_t vcol_screen_length;
 
422
  uint32_t extra_rec_buf_length;
 
423
  uint32_t i,j;
 
424
  bool use_hash;
 
425
  unsigned char forminfo[288];
 
426
  char *keynames, *names, *comment_pos, *vcol_screen_pos;
 
427
  unsigned char *record;
 
428
  unsigned char *disk_buff, *strpos, *null_flags=NULL, *null_pos=NULL;
 
429
  ulong pos, record_offset, *rec_per_key, rec_buff_length;
 
430
  handler *handler_file= 0;
 
431
  KEY   *keyinfo;
 
432
  KEY_PART_INFO *key_part;
 
433
  Field  **field_ptr, *reg_field;
 
434
  const char **interval_array;
 
435
  enum legacy_db_type legacy_db_type;
 
436
  my_bitmap_map *bitmaps;
 
437
  unsigned char *buff= 0;
 
438
  unsigned char *field_extra_info= 0;
 
439
 
 
440
  new_field_pack_flag= head[27];
 
441
  new_frm_ver= (head[2] - FRM_VER);
 
442
  field_pack_length= new_frm_ver < 2 ? 11 : 17;
 
443
  disk_buff= 0;
 
444
 
 
445
  error= 3;
 
446
  if (!(pos=get_form_pos(file,head,(TYPELIB*) 0)))
 
447
    goto err;                                   /* purecov: inspected */
 
448
  my_seek(file,pos,MY_SEEK_SET,MYF(0));
 
449
  if (my_read(file,forminfo,288,MYF(MY_NABP)))
 
450
    goto err;
 
451
 
 
452
  share->frm_version= head[2];
 
453
  /*
 
454
    Check if .frm file created by MySQL 5.0. In this case we want to
 
455
    display CHAR fields as CHAR and not as VARCHAR.
 
456
    We do it this way as we want to keep the old frm version to enable
 
457
    MySQL 4.1 to read these files.
 
458
  */
 
459
  if (share->frm_version == FRM_VER_TRUE_VARCHAR -1 && head[33] == 5)
 
460
    share->frm_version= FRM_VER_TRUE_VARCHAR;
 
461
 
 
462
  legacy_db_type= DB_TYPE_FIRST_DYNAMIC;
 
463
  assert(share->db_plugin == NULL);
 
464
  /*
 
465
    if the storage engine is dynamic, no point in resolving it by its
 
466
    dynamically allocated legacy_db_type. We will resolve it later by name.
 
467
  */
 
468
  if (legacy_db_type > DB_TYPE_UNKNOWN && 
 
469
      legacy_db_type < DB_TYPE_FIRST_DYNAMIC)
 
470
    share->db_plugin= ha_lock_engine(NULL, 
 
471
                                     ha_checktype(thd, legacy_db_type, 0, 0));
 
472
  share->db_create_options= db_create_options= uint2korr(head+30);
 
473
  share->db_options_in_use= share->db_create_options;
 
474
  share->mysql_version= uint4korr(head+51);
 
475
  share->null_field_first= 0;
 
476
  if (!head[32])                                // New frm file in 3.23
 
477
  {
 
478
    share->avg_row_length= uint4korr(head+34);
 
479
    share->transactional= (ha_choice) (head[39] & 3);
 
480
    share->page_checksum= (ha_choice) ((head[39] >> 2) & 3);
 
481
    share->row_type= (row_type) head[40];
 
482
    share->block_size= uint4korr(head+43);
 
483
    share->table_charset= get_charset((uint) head[38],MYF(0));
 
484
    share->null_field_first= 1;
 
485
  }
 
486
  if (!share->table_charset)
 
487
  {
 
488
    /* unknown charset in head[38] or pre-3.23 frm */
 
489
    if (use_mb(default_charset_info))
 
490
    {
 
491
      /* Warn that we may be changing the size of character columns */
 
492
      sql_print_warning(_("'%s' had no or invalid character set, "
 
493
                        "and default character set is multi-byte, "
 
494
                        "so character column sizes may have changed"),
 
495
                        share->path.str);
 
496
    }
 
497
    share->table_charset= default_charset_info;
 
498
  }
 
499
  share->db_record_offset= 1;
 
500
  if (db_create_options & HA_OPTION_LONG_BLOB_PTR)
 
501
    share->blob_ptr_size= portable_sizeof_char_ptr;
 
502
  /* Set temporarily a good value for db_low_byte_first */
 
503
  share->db_low_byte_first= true;
 
504
  error=4;
 
505
  share->max_rows= uint4korr(head+18);
 
506
  share->min_rows= uint4korr(head+22);
 
507
 
 
508
  /* Read keyinformation */
 
509
  key_info_length= (uint) uint2korr(head+28);
 
510
  my_seek(file,(ulong) uint2korr(head+6),MY_SEEK_SET,MYF(0));
 
511
  if (read_string(file,(unsigned char**) &disk_buff,key_info_length))
 
512
    goto err;                                   /* purecov: inspected */
 
513
  if (disk_buff[0] & 0x80)
 
514
  {
 
515
    share->keys=      keys=      (disk_buff[1] << 7) | (disk_buff[0] & 0x7f);
 
516
    share->key_parts= key_parts= uint2korr(disk_buff+2);
 
517
  }
 
518
  else
 
519
  {
 
520
    share->keys=      keys=      disk_buff[0];
 
521
    share->key_parts= key_parts= disk_buff[1];
 
522
  }
 
523
  share->keys_for_keyread.init(0);
 
524
  share->keys_in_use.init(keys);
 
525
 
 
526
  n_length=keys*sizeof(KEY)+key_parts*sizeof(KEY_PART_INFO);
 
527
  if (!(keyinfo = (KEY*) alloc_root(&share->mem_root,
 
528
                                    n_length + uint2korr(disk_buff+4))))
 
529
    goto err;                                   /* purecov: inspected */
 
530
  memset(keyinfo, 0, n_length);
 
531
  share->key_info= keyinfo;
 
532
  key_part= reinterpret_cast<KEY_PART_INFO*> (keyinfo+keys);
 
533
  strpos=disk_buff+6;
 
534
 
 
535
  if (!(rec_per_key= (ulong*) alloc_root(&share->mem_root,
 
536
                                         sizeof(ulong*)*key_parts)))
 
537
    goto err;
 
538
 
 
539
  for (i=0 ; i < keys ; i++, keyinfo++)
 
540
  {
 
541
    keyinfo->table= 0;                           // Updated in open_frm
 
542
    if (new_frm_ver >= 3)
 
543
    {
 
544
      keyinfo->flags=      (uint) uint2korr(strpos) ^ HA_NOSAME;
 
545
      keyinfo->key_length= (uint) uint2korr(strpos+2);
 
546
      keyinfo->key_parts=  (uint) strpos[4];
 
547
      keyinfo->algorithm=  (enum ha_key_alg) strpos[5];
 
548
      keyinfo->block_size= uint2korr(strpos+6);
 
549
      strpos+=8;
 
550
    }
 
551
 
 
552
    keyinfo->key_part=   key_part;
 
553
    keyinfo->rec_per_key= rec_per_key;
 
554
    for (j=keyinfo->key_parts ; j-- ; key_part++)
 
555
    {
 
556
      *rec_per_key++=0;
 
557
      key_part->fieldnr=        (uint16_t) (uint2korr(strpos) & FIELD_NR_MASK);
 
558
      key_part->offset= (uint) uint2korr(strpos+2)-1;
 
559
      key_part->key_type=       (uint) uint2korr(strpos+5);
 
560
      // key_part->field=       (Field*) 0;     // Will be fixed later
 
561
      if (new_frm_ver >= 1)
 
562
      {
 
563
        key_part->key_part_flag= *(strpos+4);
 
564
        key_part->length=       (uint) uint2korr(strpos+7);
 
565
        strpos+=9;
 
566
      }
 
567
      else
 
568
      {
 
569
        key_part->length=       *(strpos+4);
 
570
        key_part->key_part_flag=0;
 
571
        if (key_part->length > 128)
 
572
        {
 
573
          key_part->length&=127;                /* purecov: inspected */
 
574
          key_part->key_part_flag=HA_REVERSE_SORT; /* purecov: inspected */
 
575
        }
 
576
        strpos+=7;
 
577
      }
 
578
      key_part->store_length=key_part->length;
 
579
    }
 
580
  }
 
581
  keynames=(char*) key_part;
 
582
  strpos+= (my_stpcpy(keynames, (char *) strpos) - keynames)+1;
 
583
 
 
584
  //reading index comments
 
585
  for (keyinfo= share->key_info, i=0; i < keys; i++, keyinfo++)
 
586
  {
 
587
    if (keyinfo->flags & HA_USES_COMMENT)
 
588
    {
 
589
      keyinfo->comment.length= uint2korr(strpos);
 
590
      keyinfo->comment.str= strmake_root(&share->mem_root, (char*) strpos+2,
 
591
                                         keyinfo->comment.length);
 
592
      strpos+= 2 + keyinfo->comment.length;
 
593
    } 
 
594
    assert(test(keyinfo->flags & HA_USES_COMMENT) == 
 
595
               (keyinfo->comment.length > 0));
 
596
  }
 
597
 
 
598
  share->reclength = uint2korr((head+16));
 
599
  share->stored_rec_length= share->reclength;
 
600
 
 
601
  record_offset= (ulong) (uint2korr(head+6)+
 
602
                          ((uint2korr(head+14) == 0xffff ?
 
603
                            uint4korr(head+47) : uint2korr(head+14))));
 
604
 
 
605
  if ((n_length= uint4korr(head+55)))
 
606
  {
 
607
    /* Read extra data segment */
 
608
    unsigned char *next_chunk, *buff_end;
 
609
    if (!(next_chunk= buff= (unsigned char*) my_malloc(n_length, MYF(MY_WME))))
 
610
      goto err;
 
611
    if (pread(file, buff, n_length, record_offset + share->reclength) == 0)
 
612
    {
 
613
      goto err;
 
614
    }
 
615
    share->connect_string.length= uint2korr(buff);
 
616
    if (!(share->connect_string.str= strmake_root(&share->mem_root,
 
617
                                                  (char*) next_chunk + 2,
 
618
                                                  share->connect_string.
 
619
                                                  length)))
 
620
    {
 
621
      goto err;
 
622
    }
 
623
    next_chunk+= share->connect_string.length + 2;
 
624
    buff_end= buff + n_length;
 
625
    if (next_chunk + 2 < buff_end)
 
626
    {
 
627
      uint32_t str_db_type_length= uint2korr(next_chunk);
 
628
      LEX_STRING name;
 
629
      name.str= (char*) next_chunk + 2;
 
630
      name.length= str_db_type_length;
 
631
 
 
632
      plugin_ref tmp_plugin= ha_resolve_by_name(thd, &name);
 
633
      if (tmp_plugin != NULL && !plugin_equals(tmp_plugin, share->db_plugin))
 
634
      {
 
635
        if (legacy_db_type > DB_TYPE_UNKNOWN &&
 
636
            legacy_db_type < DB_TYPE_FIRST_DYNAMIC &&
 
637
            legacy_db_type != ha_legacy_type(
 
638
                plugin_data(tmp_plugin, handlerton *)))
 
639
        {
 
640
          /* bad file, legacy_db_type did not match the name */
 
641
          free(buff);
 
642
          goto err;
 
643
        }
 
644
        /*
 
645
          tmp_plugin is locked with a local lock.
 
646
          we unlock the old value of share->db_plugin before
 
647
          replacing it with a globally locked version of tmp_plugin
 
648
        */
 
649
        plugin_unlock(NULL, share->db_plugin);
 
650
        share->db_plugin= my_plugin_lock(NULL, &tmp_plugin);
 
651
      }
 
652
      else if (!tmp_plugin)
 
653
      {
 
654
        /* purecov: begin inspected */
 
655
        error= 8;
 
656
        my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
 
657
        free(buff);
 
658
        goto err;
 
659
        /* purecov: end */
 
660
      }
 
661
      next_chunk+= str_db_type_length + 2;
 
662
    }
 
663
    if (share->mysql_version >= 50110)
 
664
    {
 
665
      /* New auto_partitioned indicator introduced in 5.1.11 */
 
666
      next_chunk++;
 
667
    }
 
668
    if (forminfo[46] == (unsigned char)255)
 
669
    {
 
670
      //reading long table comment
 
671
      if (next_chunk + 2 > buff_end)
 
672
      {
 
673
          free(buff);
 
674
          goto err;
 
675
      }
 
676
      share->comment.length = uint2korr(next_chunk);
 
677
      if (! (share->comment.str= strmake_root(&share->mem_root,
 
678
                               (char*)next_chunk + 2, share->comment.length)))
 
679
      {
 
680
          free(buff);
 
681
          goto err;
 
682
      }
 
683
      next_chunk+= 2 + share->comment.length;
 
684
    }
 
685
    assert(next_chunk <= buff_end);
 
686
    if (share->mysql_version >= DRIZZLE_VERSION_TABLESPACE_IN_FRM_CGE)
 
687
    {
 
688
      /*
 
689
       New frm format in mysql_version 5.2.5 (originally in
 
690
       mysql-5.1.22-ndb-6.2.5)
 
691
       New column properties added:
 
692
       COLUMN_FORMAT DYNAMIC|FIXED and STORAGE DISK|MEMORY
 
693
       TABLESPACE name is now stored in frm
 
694
      */
 
695
      if (next_chunk >= buff_end)
 
696
      {
 
697
        if (share->mysql_version >= DRIZZLE_VERSION_TABLESPACE_IN_FRM)
 
698
        {
 
699
          goto err;
 
700
        }
 
701
      }
 
702
      else
 
703
      {
 
704
        const uint32_t format_section_header_size= 8;
 
705
        uint32_t format_section_len= uint2korr(next_chunk+0);
 
706
 
 
707
        field_extra_info= next_chunk + format_section_header_size + 1;
 
708
        next_chunk+= format_section_len;
 
709
      }
 
710
    }
 
711
    assert (next_chunk <= buff_end);
 
712
    if (next_chunk > buff_end)
 
713
    {
 
714
      goto err;
 
715
    }
 
716
  }
 
717
  share->key_block_size= uint2korr(head+62);
 
718
 
 
719
  error=4;
 
720
  extra_rec_buf_length= uint2korr(head+59);
 
721
  rec_buff_length= ALIGN_SIZE(share->reclength + 1 + extra_rec_buf_length);
 
722
  share->rec_buff_length= rec_buff_length;
 
723
  if (!(record= (unsigned char *) alloc_root(&share->mem_root,
 
724
                                     rec_buff_length)))
 
725
    goto err;                                   /* purecov: inspected */
 
726
  share->default_values= record;
 
727
  if (pread(file, record, (size_t) share->reclength, record_offset) == 0)
 
728
    goto err;                                   /* purecov: inspected */
 
729
 
 
730
  my_seek(file,pos+288,MY_SEEK_SET,MYF(0));
 
731
 
 
732
  share->fields= uint2korr(forminfo+258);
 
733
  pos= uint2korr(forminfo+260);                 /* Length of all screens */
 
734
  n_length= uint2korr(forminfo+268);
 
735
  interval_count= uint2korr(forminfo+270);
 
736
  interval_parts= uint2korr(forminfo+272);
 
737
  int_length= uint2korr(forminfo+274);
 
738
  share->null_fields= uint2korr(forminfo+282);
 
739
  com_length= uint2korr(forminfo+284);
 
740
  vcol_screen_length= uint2korr(forminfo+286);
 
741
  share->vfields= 0;
 
742
  share->stored_fields= share->fields;
 
743
  if (forminfo[46] != (unsigned char)255)
 
744
  {
 
745
    share->comment.length=  (int) (forminfo[46]);
 
746
    share->comment.str= strmake_root(&share->mem_root, (char*) forminfo+47,
 
747
                                     share->comment.length);
 
748
  }
 
749
 
 
750
 
 
751
  if (!(field_ptr = (Field **)
 
752
        alloc_root(&share->mem_root,
 
753
                   (uint) ((share->fields+1)*sizeof(Field*)+
 
754
                           interval_count*sizeof(TYPELIB)+
 
755
                           (share->fields+interval_parts+
 
756
                            keys+3)*sizeof(char *)+
 
757
                           (n_length+int_length+com_length+
 
758
                               vcol_screen_length)))))
 
759
    goto err;                                   /* purecov: inspected */
 
760
 
 
761
  share->field= field_ptr;
 
762
  read_length=(uint) (share->fields * field_pack_length +
 
763
                      pos+ (uint) (n_length+int_length+com_length+
 
764
                                   vcol_screen_length));
 
765
  if (read_string(file,(unsigned char**) &disk_buff,read_length))
 
766
    goto err;                                   /* purecov: inspected */
 
767
  strpos= disk_buff+pos;
 
768
 
 
769
  share->intervals= (TYPELIB*) (field_ptr+share->fields+1);
 
770
  interval_array= (const char **) (share->intervals+interval_count);
 
771
  names= (char*) (interval_array+share->fields+interval_parts+keys+3);
 
772
  if (!interval_count)
 
773
    share->intervals= 0;                        // For better debugging
 
774
  memcpy(names, strpos+(share->fields*field_pack_length),
 
775
         (uint) (n_length+int_length));
 
776
  comment_pos= names+(n_length+int_length);
 
777
  memcpy(comment_pos, disk_buff+read_length-com_length-vcol_screen_length, 
 
778
         com_length);
 
779
  vcol_screen_pos= names+(n_length+int_length+com_length);
 
780
  memcpy(vcol_screen_pos, disk_buff+read_length-vcol_screen_length, 
 
781
         vcol_screen_length);
 
782
 
 
783
  fix_type_pointers(&interval_array, &share->fieldnames, 1, &names);
 
784
  if (share->fieldnames.count != share->fields)
 
785
    goto err;
 
786
  fix_type_pointers(&interval_array, share->intervals, interval_count,
 
787
                    &names);
 
788
 
 
789
  {
 
790
    /* Set ENUM and SET lengths */
 
791
    TYPELIB *interval;
 
792
    for (interval= share->intervals;
 
793
         interval < share->intervals + interval_count;
 
794
         interval++)
 
795
    {
 
796
      uint32_t count= (uint) (interval->count + 1) * sizeof(uint);
 
797
      if (!(interval->type_lengths= (uint32_t *) alloc_root(&share->mem_root,
 
798
                                                        count)))
 
799
        goto err;
 
800
      for (count= 0; count < interval->count; count++)
 
801
      {
 
802
        char *val= (char*) interval->type_names[count];
 
803
        interval->type_lengths[count]= strlen(val);
 
804
      }
 
805
      interval->type_lengths[count]= 0;
 
806
    }
 
807
  }
 
808
 
 
809
  if (keynames)
 
810
    fix_type_pointers(&interval_array, &share->keynames, 1, &keynames);
 
811
 
 
812
 /* Allocate handler */
 
813
  if (!(handler_file= get_new_handler(share, thd->mem_root,
 
814
                                      share->db_type())))
 
815
    goto err;
 
816
 
 
817
  record= share->default_values-1;              /* Fieldstart = 1 */
 
818
  if (share->null_field_first)
 
819
  {
 
820
    null_flags= null_pos= (unsigned char*) record+1;
 
821
    null_bit_pos= (db_create_options & HA_OPTION_PACK_RECORD) ? 0 : 1;
 
822
    /*
 
823
      null_bytes below is only correct under the condition that
 
824
      there are no bit fields.  Correct values is set below after the
 
825
      table struct is initialized
 
826
    */
 
827
    share->null_bytes= (share->null_fields + null_bit_pos + 7) / 8;
 
828
  }
 
829
 
 
830
  use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
 
831
  if (use_hash)
 
832
    use_hash= !hash_init(&share->name_hash,
 
833
                         system_charset_info,
 
834
                         share->fields,0,0,
 
835
                         (hash_get_key) get_field_name,0,0);
 
836
 
 
837
  for (i=0 ; i < share->fields; i++, strpos+=field_pack_length, field_ptr++)
 
838
  {
 
839
    uint32_t pack_flag, interval_nr, unireg_type, recpos, field_length;
 
840
    uint32_t vcol_info_length=0;
 
841
    enum_field_types field_type;
 
842
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
 
843
    const CHARSET_INFO *charset= NULL;
 
844
    LEX_STRING comment;
 
845
    virtual_column_info *vcol_info= NULL;
 
846
    bool fld_is_stored= true;
 
847
 
 
848
    if (field_extra_info)
 
849
    {
 
850
      char tmp= field_extra_info[i];
 
851
      column_format= (enum column_format_type)
 
852
                    ((tmp >> COLUMN_FORMAT_SHIFT) & COLUMN_FORMAT_MASK);
 
853
    }
 
854
    if (new_frm_ver >= 3)
 
855
    {
 
856
      /* new frm file in 4.1 */
 
857
      field_length= uint2korr(strpos+3);
 
858
      recpos=       uint3korr(strpos+5);
 
859
      pack_flag=    uint2korr(strpos+8);
 
860
      unireg_type=  (uint) strpos[10];
 
861
      interval_nr=  (uint) strpos[12];
 
862
      uint32_t comment_length=uint2korr(strpos+15);
 
863
      field_type=(enum_field_types) (uint) strpos[13];
 
864
 
 
865
      {
 
866
        if (!strpos[14])
 
867
          charset= &my_charset_bin;
 
868
        else if (!(charset=get_charset((uint) strpos[14], MYF(0))))
 
869
        {
 
870
          error= 5; // Unknown or unavailable charset
 
871
          errarg= (int) strpos[14];
 
872
          goto err;
 
873
        }
 
874
      }
 
875
      if (field_type == DRIZZLE_TYPE_VIRTUAL)
 
876
      {
 
877
        assert(interval_nr); // Expect non-null expression
 
878
        /* 
 
879
          The interval_id byte in the .frm file stores the length of the
 
880
          expression statement for a virtual column.
 
881
        */
 
882
        vcol_info_length= interval_nr;
 
883
        interval_nr= 0;
 
884
      }
 
885
      if (!comment_length)
 
886
      {
 
887
        comment.str= (char*) "";
 
888
        comment.length=0;
 
889
      }
 
890
      else
 
891
      {
 
892
        comment.str=    (char*) comment_pos;
 
893
        comment.length= comment_length;
 
894
        comment_pos+=   comment_length;
 
895
      }
 
896
      if (vcol_info_length)
 
897
      {
 
898
        /*
 
899
          Get virtual column data stored in the .frm file as follows:
 
900
          byte 1      = 1 (always 1 to allow for future extensions)
 
901
          byte 2      = sql_type
 
902
          byte 3      = flags (as of now, 0 - no flags, 1 - field is physically stored)
 
903
          byte 4-...  = virtual column expression (text data)
 
904
        */
 
905
        vcol_info= new virtual_column_info();
 
906
        if ((uint)vcol_screen_pos[0] != 1)
 
907
        {
 
908
          error= 4;
 
909
          goto err;
 
910
        }
 
911
        field_type= (enum_field_types) (unsigned char) vcol_screen_pos[1];
 
912
        fld_is_stored= (bool) (uint) vcol_screen_pos[2];
 
913
        vcol_info->expr_str.str= (char *)memdup_root(&share->mem_root,
 
914
                                                     vcol_screen_pos+
 
915
                                                       (uint)FRM_VCOL_HEADER_SIZE,
 
916
                                                     vcol_info_length-
 
917
                                                       (uint)FRM_VCOL_HEADER_SIZE);
 
918
        vcol_info->expr_str.length= vcol_info_length-(uint)FRM_VCOL_HEADER_SIZE;
 
919
        vcol_screen_pos+= vcol_info_length;
 
920
        share->vfields++;
 
921
      }
 
922
    }
 
923
    else
 
924
    {
 
925
      field_length= (uint) strpos[3];
 
926
      recpos=       uint2korr(strpos+4),
 
927
      pack_flag=    uint2korr(strpos+6);
 
928
      pack_flag&=   ~FIELDFLAG_NO_DEFAULT;     // Safety for old files
 
929
      unireg_type=  (uint) strpos[8];
 
930
      interval_nr=  (uint) strpos[10];
 
931
 
 
932
      /* old frm file */
 
933
      field_type= (enum_field_types) f_packtype(pack_flag);
 
934
      if (f_is_binary(pack_flag))
 
935
      {
 
936
        /*
 
937
          Try to choose the best 4.1 type:
 
938
          - for 4.0 "CHAR(N) BINARY" or "VARCHAR(N) BINARY" 
 
939
            try to find a binary collation for character set.
 
940
          - for other types (e.g. BLOB) just use my_charset_bin. 
 
941
        */
 
942
        if (!f_is_blob(pack_flag))
 
943
        {
 
944
          // 3.23 or 4.0 string
 
945
          if (!(charset= get_charset_by_csname(share->table_charset->csname,
 
946
                                               MY_CS_BINSORT, MYF(0))))
 
947
            charset= &my_charset_bin;
 
948
        }
 
949
        else
 
950
          charset= &my_charset_bin;
 
951
      }
 
952
      else
 
953
        charset= share->table_charset;
 
954
      memset(&comment, 0, sizeof(comment));
 
955
    }
 
956
 
 
957
    if (interval_nr && charset->mbminlen > 1)
 
958
    {
 
959
      /* Unescape UCS2 intervals from HEX notation */
 
960
      TYPELIB *interval= share->intervals + interval_nr - 1;
 
961
      unhex_type2(interval);
 
962
    }
 
963
 
 
964
    *field_ptr= reg_field=
 
965
      make_field(share, record+recpos,
 
966
                 (uint32_t) field_length,
 
967
                 null_pos, null_bit_pos,
 
968
                 pack_flag,
 
969
                 field_type,
 
970
                 charset,
 
971
                 (Field::utype) MTYP_TYPENR(unireg_type),
 
972
                 (interval_nr ?
 
973
                  share->intervals+interval_nr-1 :
 
974
                  (TYPELIB*) 0),
 
975
                 share->fieldnames.type_names[i]);
 
976
    if (!reg_field)                             // Not supported field type
 
977
    {
 
978
      error= 4;
 
979
      goto err;                 /* purecov: inspected */
 
980
    }
 
981
 
 
982
    reg_field->flags|= ((uint)column_format << COLUMN_FORMAT_FLAGS);
 
983
    reg_field->field_index= i;
 
984
    reg_field->comment=comment;
 
985
    reg_field->vcol_info= vcol_info;
 
986
    reg_field->is_stored= fld_is_stored;
 
987
    if (!(reg_field->flags & NOT_NULL_FLAG))
 
988
    {
 
989
      if (!(null_bit_pos= (null_bit_pos + 1) & 7))
 
990
        null_pos++;
 
991
    }
 
992
    if (f_no_default(pack_flag))
 
993
      reg_field->flags|= NO_DEFAULT_VALUE_FLAG;
 
994
 
 
995
    if (reg_field->unireg_check == Field::NEXT_NUMBER)
 
996
      share->found_next_number_field= field_ptr;
 
997
    if (share->timestamp_field == reg_field)
 
998
      share->timestamp_field_offset= i;
 
999
 
 
1000
    if (use_hash)
 
1001
      (void) my_hash_insert(&share->name_hash,
 
1002
                            (unsigned char*) field_ptr); // never fail
 
1003
    if (!reg_field->is_stored)
 
1004
    {
 
1005
      share->stored_fields--;
 
1006
      if (share->stored_rec_length>=recpos)
 
1007
        share->stored_rec_length= recpos-1;
 
1008
    }
 
1009
  }
 
1010
  *field_ptr=0;                                 // End marker
 
1011
  /* Sanity checks: */
 
1012
  assert(share->fields>=share->stored_fields);
 
1013
  assert(share->reclength>=share->stored_rec_length);
 
1014
 
 
1015
  /* Fix key->name and key_part->field */
 
1016
  if (key_parts)
 
1017
  {
 
1018
    uint32_t primary_key=(uint) (find_type((char*) primary_key_name,
 
1019
                                       &share->keynames, 3) - 1);
 
1020
    int64_t ha_option= handler_file->ha_table_flags();
 
1021
    keyinfo= share->key_info;
 
1022
    key_part= keyinfo->key_part;
 
1023
 
 
1024
    for (uint32_t key=0 ; key < share->keys ; key++,keyinfo++)
 
1025
    {
 
1026
      uint32_t usable_parts= 0;
 
1027
      keyinfo->name=(char*) share->keynames.type_names[key];
 
1028
 
 
1029
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
 
1030
      {
 
1031
        /*
 
1032
          If the UNIQUE key doesn't have NULL columns and is not a part key
 
1033
          declare this as a primary key.
 
1034
        */
 
1035
        primary_key=key;
 
1036
        for (i=0 ; i < keyinfo->key_parts ;i++)
 
1037
        {
 
1038
          uint32_t fieldnr= key_part[i].fieldnr;
 
1039
          if (!fieldnr ||
 
1040
              share->field[fieldnr-1]->null_ptr ||
 
1041
              share->field[fieldnr-1]->key_length() !=
 
1042
              key_part[i].length)
 
1043
          {
 
1044
            primary_key=MAX_KEY;                // Can't be used
 
1045
            break;
 
1046
          }
 
1047
        }
 
1048
      }
 
1049
 
 
1050
      for (i=0 ; i < keyinfo->key_parts ; key_part++,i++)
 
1051
      {
 
1052
        Field *field;
 
1053
        if (new_field_pack_flag <= 1)
 
1054
          key_part->fieldnr= (uint16_t) find_field(share->field,
 
1055
                                                 share->default_values,
 
1056
                                                 (uint) key_part->offset,
 
1057
                                                 (uint) key_part->length);
 
1058
        if (!key_part->fieldnr)
 
1059
        {
 
1060
          error= 4;                             // Wrong file
 
1061
          goto err;
 
1062
        }
 
1063
        field= key_part->field= share->field[key_part->fieldnr-1];
 
1064
        key_part->type= field->key_type();
 
1065
        if (field->null_ptr)
 
1066
        {
 
1067
          key_part->null_offset=(uint) ((unsigned char*) field->null_ptr -
 
1068
                                        share->default_values);
 
1069
          key_part->null_bit= field->null_bit;
 
1070
          key_part->store_length+=HA_KEY_NULL_LENGTH;
 
1071
          keyinfo->flags|=HA_NULL_PART_KEY;
 
1072
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
 
1073
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
 
1074
        }
 
1075
        if (field->type() == DRIZZLE_TYPE_BLOB ||
 
1076
            field->real_type() == DRIZZLE_TYPE_VARCHAR)
 
1077
        {
 
1078
          if (field->type() == DRIZZLE_TYPE_BLOB)
 
1079
            key_part->key_part_flag|= HA_BLOB_PART;
 
1080
          else
 
1081
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
 
1082
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
 
1083
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
 
1084
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
 
1085
        }
 
1086
        if (i == 0 && key != primary_key)
 
1087
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
 
1088
                           (keyinfo->key_parts == 1)) ?
 
1089
                           UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
 
1090
        if (i == 0)
 
1091
          field->key_start.set_bit(key);
 
1092
        if (field->key_length() == key_part->length &&
 
1093
            !(field->flags & BLOB_FLAG))
 
1094
        {
 
1095
          if (handler_file->index_flags(key, i, 0) & HA_KEYREAD_ONLY)
 
1096
          {
 
1097
            share->keys_for_keyread.set_bit(key);
 
1098
            field->part_of_key.set_bit(key);
 
1099
            field->part_of_key_not_clustered.set_bit(key);
 
1100
          }
 
1101
          if (handler_file->index_flags(key, i, 1) & HA_READ_ORDER)
 
1102
            field->part_of_sortkey.set_bit(key);
 
1103
        }
 
1104
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
 
1105
            usable_parts == i)
 
1106
          usable_parts++;                       // For FILESORT
 
1107
        field->flags|= PART_KEY_FLAG;
 
1108
        if (key == primary_key)
 
1109
        {
 
1110
          field->flags|= PRI_KEY_FLAG;
 
1111
          /*
 
1112
            If this field is part of the primary key and all keys contains
 
1113
            the primary key, then we can use any key to find this column
 
1114
          */
 
1115
          if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
 
1116
          {
 
1117
            field->part_of_key= share->keys_in_use;
 
1118
            if (field->part_of_sortkey.is_set(key))
 
1119
              field->part_of_sortkey= share->keys_in_use;
 
1120
          }
 
1121
        }
 
1122
        if (field->key_length() != key_part->length)
 
1123
        {
 
1124
          key_part->key_part_flag|= HA_PART_KEY_SEG;
 
1125
        }
 
1126
      }
 
1127
      keyinfo->usable_key_parts= usable_parts; // Filesort
 
1128
 
 
1129
      set_if_bigger(share->max_key_length,keyinfo->key_length+
 
1130
                    keyinfo->key_parts);
 
1131
      share->total_key_length+= keyinfo->key_length;
 
1132
      /*
 
1133
        MERGE tables do not have unique indexes. But every key could be
 
1134
        an unique index on the underlying MyISAM table. (Bug #10400)
 
1135
      */
 
1136
      if ((keyinfo->flags & HA_NOSAME) ||
 
1137
          (ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
 
1138
        set_if_bigger(share->max_unique_length,keyinfo->key_length);
 
1139
    }
 
1140
    if (primary_key < MAX_KEY &&
 
1141
        (share->keys_in_use.is_set(primary_key)))
 
1142
    {
 
1143
      share->primary_key= primary_key;
 
1144
      /*
 
1145
        If we are using an integer as the primary key then allow the user to
 
1146
        refer to it as '_rowid'
 
1147
      */
 
1148
      if (share->key_info[primary_key].key_parts == 1)
 
1149
      {
 
1150
        Field *field= share->key_info[primary_key].key_part[0].field;
 
1151
        if (field && field->result_type() == INT_RESULT)
 
1152
        {
 
1153
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
 
1154
          share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
 
1155
                                      fieldnr);
 
1156
        }
 
1157
      }
 
1158
    }
 
1159
    else
 
1160
      share->primary_key = MAX_KEY; // we do not have a primary key
 
1161
  }
 
1162
  else
 
1163
    share->primary_key= MAX_KEY;
 
1164
  if (disk_buff)
 
1165
    free(disk_buff);
 
1166
  disk_buff= NULL;
 
1167
  if (new_field_pack_flag <= 1)
 
1168
  {
 
1169
    /* Old file format with default as not null */
 
1170
    uint32_t null_length= (share->null_fields+7)/8;
 
1171
    memset(share->default_values + (null_flags - (unsigned char*) record), 
 
1172
          null_length, 255);
 
1173
  }
 
1174
 
 
1175
  if (share->found_next_number_field)
 
1176
  {
 
1177
    reg_field= *share->found_next_number_field;
 
1178
    if ((int) (share->next_number_index= (uint)
 
1179
               find_ref_key(share->key_info, share->keys,
 
1180
                            share->default_values, reg_field,
 
1181
                            &share->next_number_key_offset,
 
1182
                            &share->next_number_keypart)) < 0)
 
1183
    {
 
1184
      /* Wrong field definition */
 
1185
      error= 4;
 
1186
      goto err;
 
1187
    }
 
1188
    else
 
1189
      reg_field->flags |= AUTO_INCREMENT_FLAG;
 
1190
  }
 
1191
 
 
1192
  if (share->blob_fields)
 
1193
  {
 
1194
    Field **ptr;
 
1195
    uint32_t k, *save;
 
1196
 
 
1197
    /* Store offsets to blob fields to find them fast */
 
1198
    if (!(share->blob_field= save=
 
1199
          (uint*) alloc_root(&share->mem_root,
 
1200
                             (uint) (share->blob_fields* sizeof(uint)))))
 
1201
      goto err;
 
1202
    for (k=0, ptr= share->field ; *ptr ; ptr++, k++)
 
1203
    {
 
1204
      if ((*ptr)->flags & BLOB_FLAG)
 
1205
        (*save++)= k;
 
1206
    }
 
1207
  }
 
1208
 
 
1209
  /*
 
1210
    the correct null_bytes can now be set, since bitfields have been taken
 
1211
    into account
 
1212
  */
 
1213
  share->null_bytes= (null_pos - (unsigned char*) null_flags +
 
1214
                      (null_bit_pos + 7) / 8);
 
1215
  share->last_null_bit_pos= null_bit_pos;
 
1216
 
 
1217
  share->db_low_byte_first= handler_file->low_byte_first();
 
1218
  share->column_bitmap_size= bitmap_buffer_size(share->fields);
 
1219
 
 
1220
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
 
1221
                                             share->column_bitmap_size)))
 
1222
    goto err;
 
1223
  bitmap_init(&share->all_set, bitmaps, share->fields, false);
 
1224
  bitmap_set_all(&share->all_set);
 
1225
 
 
1226
  delete handler_file;
 
1227
  if (buff)
 
1228
    free(buff);
 
1229
  return (0);
 
1230
 
 
1231
 err:
 
1232
  if (buff)
 
1233
    free(buff);
 
1234
  share->error= error;
 
1235
  share->open_errno= my_errno;
 
1236
  share->errarg= errarg;
 
1237
  if (disk_buff)
 
1238
    free(disk_buff);
 
1239
  delete handler_file;
 
1240
  hash_free(&share->name_hash);
 
1241
 
 
1242
  open_table_error(share, error, share->open_errno, errarg);
 
1243
  return(error);
 
1244
} /* open_binary_frm */
 
1245
 
 
1246
 
 
1247
/*
 
1248
  Clear flag GET_FIXED_FIELDS_FLAG in all fields of the table.
 
1249
  This routine is used for error handling purposes.
 
1250
 
 
1251
  SYNOPSIS
 
1252
    clear_field_flag()
 
1253
    table                Table object for which virtual columns are set-up
 
1254
 
 
1255
  RETURN VALUE
 
1256
    NONE
 
1257
*/
 
1258
static void clear_field_flag(Table *table)
 
1259
{
 
1260
  Field **ptr;
 
1261
 
 
1262
  for (ptr= table->field; *ptr; ptr++)
 
1263
    (*ptr)->flags&= (~GET_FIXED_FIELDS_FLAG);
 
1264
}
 
1265
 
 
1266
/*
 
1267
  The function uses the feature in fix_fields where the flag 
 
1268
  GET_FIXED_FIELDS_FLAG is set for all fields in the item tree.
 
1269
  This field must always be reset before returning from the function
 
1270
  since it is used for other purposes as well.
 
1271
 
 
1272
  SYNOPSIS
 
1273
    fix_fields_vcol_func()
 
1274
    thd                  The thread object
 
1275
    func_item            The item tree reference of the virtual columnfunction
 
1276
    table                The table object
 
1277
    field_name           The name of the processed field
 
1278
 
 
1279
  RETURN VALUE
 
1280
    true                 An error occurred, something was wrong with the
 
1281
                         function.
 
1282
    false                Ok, a partition field array was created
 
1283
*/
 
1284
 
 
1285
bool fix_fields_vcol_func(THD *thd,
 
1286
                          Item* func_expr,
 
1287
                          Table *table,
 
1288
                          const char *field_name)
 
1289
{
 
1290
  uint dir_length, home_dir_length;
 
1291
  bool result= true;
 
1292
  TableList tables;
 
1293
  TableList *save_table_list, *save_first_table, *save_last_table;
 
1294
  int error;
 
1295
  Name_resolution_context *context;
 
1296
  const char *save_where;
 
1297
  char* db_name;
 
1298
  char db_name_string[FN_REFLEN];
 
1299
  bool save_use_only_table_context;
 
1300
  Field **ptr, *field;
 
1301
  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
 
1302
  assert(func_expr);
 
1303
 
 
1304
  /*
 
1305
    Set-up the TABLE_LIST object to be a list with a single table
 
1306
    Set the object to zero to create NULL pointers and set alias
 
1307
    and real name to table name and get database name from file name.
 
1308
  */
 
1309
 
 
1310
  bzero((void*)&tables, sizeof(TableList));
 
1311
  tables.alias= tables.table_name= (char*) table->s->table_name.str;
 
1312
  tables.table= table;
 
1313
  tables.next_local= NULL;
 
1314
  tables.next_name_resolution_table= NULL;
 
1315
  memcpy(db_name_string,
 
1316
         table->s->normalized_path.str,
 
1317
         table->s->normalized_path.length);
 
1318
  dir_length= dirname_length(db_name_string);
 
1319
  db_name_string[dir_length - 1]= 0;
 
1320
  home_dir_length= dirname_length(db_name_string);
 
1321
  db_name= &db_name_string[home_dir_length];
 
1322
  tables.db= db_name;
 
1323
 
 
1324
  thd->mark_used_columns= MARK_COLUMNS_NONE;
 
1325
 
 
1326
  context= thd->lex->current_context();
 
1327
  table->map= 1; //To ensure correct calculation of const item
 
1328
  table->get_fields_in_item_tree= true;
 
1329
  save_table_list= context->table_list;
 
1330
  save_first_table= context->first_name_resolution_table;
 
1331
  save_last_table= context->last_name_resolution_table;
 
1332
  context->table_list= &tables;
 
1333
  context->first_name_resolution_table= &tables;
 
1334
  context->last_name_resolution_table= NULL;
 
1335
  func_expr->walk(&Item::change_context_processor, 0, (unsigned char*) context);
 
1336
  save_where= thd->where;
 
1337
  thd->where= "virtual column function";
 
1338
 
 
1339
  /* Save the context before fixing the fields*/
 
1340
  save_use_only_table_context= thd->lex->use_only_table_context;
 
1341
  thd->lex->use_only_table_context= true;
 
1342
  /* Fix fields referenced to by the virtual column function */
 
1343
  error= func_expr->fix_fields(thd, (Item**)0);
 
1344
  /* Restore the original context*/
 
1345
  thd->lex->use_only_table_context= save_use_only_table_context;
 
1346
  context->table_list= save_table_list;
 
1347
  context->first_name_resolution_table= save_first_table;
 
1348
  context->last_name_resolution_table= save_last_table;
 
1349
 
 
1350
  if (unlikely(error))
 
1351
  {
 
1352
    clear_field_flag(table);
 
1353
    goto end;
 
1354
  }
 
1355
  thd->where= save_where;
 
1356
  /* 
 
1357
    Walk through the Item tree checking if all items are valid 
 
1358
   to be part of the virtual column
 
1359
 */
 
1360
  error= func_expr->walk(&Item::check_vcol_func_processor, 0, NULL);
 
1361
  if (error)
 
1362
  {
 
1363
    my_error(ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0), field_name);
 
1364
    clear_field_flag(table);
 
1365
    goto end;
 
1366
  }
 
1367
  if (unlikely(func_expr->const_item()))
 
1368
  {
 
1369
    my_error(ER_CONST_EXPR_IN_VCOL, MYF(0));
 
1370
    clear_field_flag(table);
 
1371
    goto end;
 
1372
  }
 
1373
  /* Ensure that this virtual column is not based on another virtual field. */
 
1374
  ptr= table->field;
 
1375
  while ((field= *(ptr++))) 
 
1376
  {
 
1377
    if ((field->flags & GET_FIXED_FIELDS_FLAG) &&
 
1378
        (field->vcol_info))
 
1379
    {
 
1380
      my_error(ER_VCOL_BASED_ON_VCOL, MYF(0));
 
1381
      clear_field_flag(table);
 
1382
      goto end;
 
1383
    }
 
1384
  }
 
1385
  /*
 
1386
    Cleanup the fields marked with flag GET_FIXED_FIELDS_FLAG
 
1387
    when calling fix_fields.
 
1388
  */
 
1389
  clear_field_flag(table);
 
1390
  result= false;
 
1391
 
 
1392
end:
 
1393
  table->get_fields_in_item_tree= false;
 
1394
  thd->mark_used_columns= save_mark_used_columns;
 
1395
  table->map= 0; //Restore old value
 
1396
  return(result);
 
1397
}
 
1398
 
 
1399
/*
 
1400
  Unpack the definition of a virtual column
 
1401
 
 
1402
  SYNOPSIS
 
1403
    unpack_vcol_info_from_frm()
 
1404
    thd                  Thread handler
 
1405
    table                Table with the checked field
 
1406
    field                Pointer to Field object
 
1407
    open_mode            Open table mode needed to determine
 
1408
                         which errors need to be generated in a failure
 
1409
    error_reported       updated flag for the caller that no other error
 
1410
                         messages are to be generated.
 
1411
 
 
1412
  RETURN VALUES
 
1413
    true            Failure
 
1414
    false           Success
 
1415
*/
 
1416
bool unpack_vcol_info_from_frm(THD *thd,
 
1417
                               Table *table,
 
1418
                               Field *field,
 
1419
                               LEX_STRING *vcol_expr,
 
1420
                               open_table_mode open_mode,
 
1421
                               bool *error_reported)
 
1422
{
 
1423
  assert(vcol_expr);
 
1424
 
 
1425
  /* 
 
1426
    Step 1: Construct a statement for the parser.
 
1427
    The parsed string needs to take the following format:
 
1428
    "PARSE_VCOL_EXPR (<expr_string_from_frm>)"
 
1429
  */
 
1430
  char *vcol_expr_str;
 
1431
  int str_len= 0;
 
1432
  
 
1433
  if (!(vcol_expr_str= (char*) alloc_root(&table->mem_root,
 
1434
                                          vcol_expr->length + 
 
1435
                                            parse_vcol_keyword.length + 3)))
 
1436
  {
 
1437
    return(true);
 
1438
  }
 
1439
  memcpy(vcol_expr_str,
 
1440
         (char*) parse_vcol_keyword.str,
 
1441
         parse_vcol_keyword.length);
 
1442
  str_len= parse_vcol_keyword.length;
 
1443
  memcpy(vcol_expr_str + str_len, "(", 1);
 
1444
  str_len++;
 
1445
  memcpy(vcol_expr_str + str_len, 
 
1446
         (char*) vcol_expr->str, 
 
1447
         vcol_expr->length);
 
1448
  str_len+= vcol_expr->length;
 
1449
  memcpy(vcol_expr_str + str_len, ")", 1);
 
1450
  str_len++;
 
1451
  memcpy(vcol_expr_str + str_len, "\0", 1);
 
1452
  str_len++;
 
1453
  Lex_input_stream lip(thd, vcol_expr_str, str_len);
 
1454
 
 
1455
  /* 
 
1456
    Step 2: Setup thd for parsing.
 
1457
    1) make Item objects be created in the memory allocated for the Table
 
1458
       object (not TABLE_SHARE)
 
1459
    2) ensure that created Item's are not put on to thd->free_list 
 
1460
       (which is associated with the parsed statement and hence cleared after 
 
1461
       the parsing)
 
1462
    3) setup a flag in the LEX structure to allow "PARSE_VCOL_EXPR" 
 
1463
       to be parsed as a SQL command.
 
1464
  */
 
1465
  MEM_ROOT **root_ptr, *old_root;
 
1466
  Item *backup_free_list= thd->free_list;
 
1467
  root_ptr= (MEM_ROOT **)pthread_getspecific(THR_MALLOC);
 
1468
  old_root= *root_ptr;
 
1469
  *root_ptr= &table->mem_root;
 
1470
  thd->free_list= NULL;
 
1471
  thd->lex->parse_vcol_expr= true;
 
1472
 
 
1473
  /* 
 
1474
    Step 3: Use the parser to build an Item object from.
 
1475
  */
 
1476
  if (parse_sql(thd, &lip))
 
1477
  {
 
1478
    goto parse_err;
 
1479
  }
 
1480
  /* From now on use vcol_info generated by the parser. */
 
1481
  field->vcol_info= thd->lex->vcol_info;
 
1482
 
 
1483
  /* Validate the Item tree. */
 
1484
  if (fix_fields_vcol_func(thd,
 
1485
                           field->vcol_info->expr_item,
 
1486
                           table,
 
1487
                           field->field_name))
 
1488
  {
 
1489
    if (open_mode == OTM_CREATE)
 
1490
    {
 
1491
      /*
 
1492
        During CREATE/ALTER TABLE it is ok to receive errors here.
 
1493
        It is not ok if it happens during the opening of an frm
 
1494
        file as part of a normal query.
 
1495
      */
 
1496
      *error_reported= true;
 
1497
    }
 
1498
    field->vcol_info= NULL;
 
1499
    goto parse_err;
 
1500
  }
 
1501
  field->vcol_info->item_free_list= thd->free_list;
 
1502
  thd->free_list= backup_free_list;
 
1503
  *root_ptr= old_root;
 
1504
 
 
1505
  return(false);
 
1506
 
 
1507
parse_err:
 
1508
  thd->lex->parse_vcol_expr= false;
 
1509
  thd->free_items();
 
1510
  *root_ptr= old_root;
 
1511
  thd->free_list= backup_free_list;
 
1512
  return(true);
 
1513
}
 
1514
 
 
1515
 
 
1516
/*
 
1517
  Open a table based on a TABLE_SHARE
 
1518
 
 
1519
  SYNOPSIS
 
1520
    open_table_from_share()
 
1521
    thd                 Thread handler
 
1522
    share               Table definition
 
1523
    alias               Alias for table
 
1524
    db_stat             open flags (for example HA_OPEN_KEYFILE|
 
1525
                        HA_OPEN_RNDFILE..) can be 0 (example in
 
1526
                        ha_example_table)
 
1527
    prgflag             READ_ALL etc..
 
1528
    ha_open_flags       HA_OPEN_ABORT_IF_LOCKED etc..
 
1529
    outparam            result table
 
1530
    open_mode           One of OTM_OPEN|OTM_CREATE|OTM_ALTER
 
1531
                        if OTM_CREATE some errors are ignore
 
1532
                        if OTM_ALTER HA_OPEN is not called
 
1533
 
 
1534
  RETURN VALUES
 
1535
   0    ok
 
1536
   1    Error (see open_table_error)
 
1537
   2    Error (see open_table_error)
 
1538
   3    Wrong data in .frm file
 
1539
   4    Error (see open_table_error)
 
1540
   5    Error (see open_table_error: charset unavailable)
 
1541
   7    Table definition has changed in engine
 
1542
*/
 
1543
 
 
1544
int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
 
1545
                          uint32_t db_stat, uint32_t prgflag, uint32_t ha_open_flags,
 
1546
                          Table *outparam, open_table_mode open_mode)
 
1547
{
 
1548
  int error;
 
1549
  uint32_t records, i, bitmap_size;
 
1550
  bool error_reported= false;
 
1551
  unsigned char *record, *bitmaps;
 
1552
  Field **field_ptr, **vfield_ptr;
 
1553
 
 
1554
  /* Parsing of partitioning information from .frm needs thd->lex set up. */
 
1555
  assert(thd->lex->is_lex_started);
 
1556
 
 
1557
  error= 1;
 
1558
  memset(outparam, 0, sizeof(*outparam));
 
1559
  outparam->in_use= thd;
 
1560
  outparam->s= share;
 
1561
  outparam->db_stat= db_stat;
 
1562
  outparam->write_row_record= NULL;
 
1563
 
 
1564
  init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
1565
 
 
1566
  if (!(outparam->alias= my_strdup(alias, MYF(MY_WME))))
 
1567
    goto err;
 
1568
  outparam->quick_keys.init();
 
1569
  outparam->covering_keys.init();
 
1570
  outparam->keys_in_use_for_query.init();
 
1571
 
 
1572
  /* Allocate handler */
 
1573
  outparam->file= 0;
 
1574
  if (!(prgflag & OPEN_FRM_FILE_ONLY))
 
1575
  {
 
1576
    if (!(outparam->file= get_new_handler(share, &outparam->mem_root,
 
1577
                                          share->db_type())))
 
1578
      goto err;
 
1579
  }
 
1580
  else
 
1581
  {
 
1582
    assert(!db_stat);
 
1583
  }
 
1584
 
 
1585
  error= 4;
 
1586
  outparam->reginfo.lock_type= TL_UNLOCK;
 
1587
  outparam->current_lock= F_UNLCK;
 
1588
  records=0;
 
1589
  if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
 
1590
    records=1;
 
1591
  if (prgflag & (READ_ALL+EXTRA_RECORD))
 
1592
    records++;
 
1593
 
 
1594
  if (!(record= (unsigned char*) alloc_root(&outparam->mem_root,
 
1595
                                   share->rec_buff_length * records)))
 
1596
    goto err;                                   /* purecov: inspected */
 
1597
 
 
1598
  if (records == 0)
 
1599
  {
 
1600
    /* We are probably in hard repair, and the buffers should not be used */
 
1601
    outparam->record[0]= outparam->record[1]= share->default_values;
 
1602
  }
 
1603
  else
 
1604
  {
 
1605
    outparam->record[0]= record;
 
1606
    if (records > 1)
 
1607
      outparam->record[1]= record+ share->rec_buff_length;
 
1608
    else
 
1609
      outparam->record[1]= outparam->record[0];   // Safety
 
1610
  }
 
1611
 
 
1612
#ifdef HAVE_purify
 
1613
  /*
 
1614
    We need this because when we read var-length rows, we are not updating
 
1615
    bytes after end of varchar
 
1616
  */
 
1617
  if (records > 1)
 
1618
  {
 
1619
    memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
 
1620
    memcpy(outparam->record[1], share->default_values, share->null_bytes);
 
1621
    if (records > 2)
 
1622
      memcpy(outparam->record[1], share->default_values,
 
1623
             share->rec_buff_length);
 
1624
  }
 
1625
#endif
 
1626
 
 
1627
  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
 
1628
                                          (uint) ((share->fields+1)*
 
1629
                                                  sizeof(Field*)))))
 
1630
    goto err;                                   /* purecov: inspected */
 
1631
 
 
1632
  outparam->field= field_ptr;
 
1633
 
 
1634
  record= (unsigned char*) outparam->record[0]-1;       /* Fieldstart = 1 */
 
1635
  if (share->null_field_first)
 
1636
    outparam->null_flags= (unsigned char*) record+1;
 
1637
  else
 
1638
    outparam->null_flags= (unsigned char*) (record+ 1+ share->reclength -
 
1639
                                    share->null_bytes);
 
1640
 
 
1641
  /* Setup copy of fields from share, but use the right alias and record */
 
1642
  for (i=0 ; i < share->fields; i++, field_ptr++)
 
1643
  {
 
1644
    if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
 
1645
      goto err;
 
1646
  }
 
1647
  (*field_ptr)= 0;                              // End marker
 
1648
 
 
1649
  if (share->found_next_number_field)
 
1650
    outparam->found_next_number_field=
 
1651
      outparam->field[(uint) (share->found_next_number_field - share->field)];
 
1652
  if (share->timestamp_field)
 
1653
    outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
 
1654
 
 
1655
 
 
1656
  /* Fix key->name and key_part->field */
 
1657
  if (share->key_parts)
 
1658
  {
 
1659
    KEY *key_info, *key_info_end;
 
1660
    KEY_PART_INFO *key_part;
 
1661
    uint32_t n_length;
 
1662
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
 
1663
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
 
1664
      goto err;
 
1665
    outparam->key_info= key_info;
 
1666
    key_part= (reinterpret_cast<KEY_PART_INFO*> (key_info+share->keys));
 
1667
    
 
1668
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
 
1669
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
 
1670
                                                   share->key_parts));
 
1671
 
 
1672
    for (key_info_end= key_info + share->keys ;
 
1673
         key_info < key_info_end ;
 
1674
         key_info++)
 
1675
    {
 
1676
      KEY_PART_INFO *key_part_end;
 
1677
 
 
1678
      key_info->table= outparam;
 
1679
      key_info->key_part= key_part;
 
1680
 
 
1681
      for (key_part_end= key_part+ key_info->key_parts ;
 
1682
           key_part < key_part_end ;
 
1683
           key_part++)
 
1684
      {
 
1685
        Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
 
1686
 
 
1687
        if (field->key_length() != key_part->length &&
 
1688
            !(field->flags & BLOB_FLAG))
 
1689
        {
 
1690
          /*
 
1691
            We are using only a prefix of the column as a key:
 
1692
            Create a new field for the key part that matches the index
 
1693
          */
 
1694
          field= key_part->field=field->new_field(&outparam->mem_root,
 
1695
                                                  outparam, 0);
 
1696
          field->field_length= key_part->length;
 
1697
        }
 
1698
      }
 
1699
    }
 
1700
  }
 
1701
 
 
1702
  /*
 
1703
    Process virtual columns, if any.
 
1704
  */
 
1705
  if (not (vfield_ptr = (Field **) alloc_root(&outparam->mem_root,
 
1706
                                              (uint) ((share->vfields+1)*
 
1707
                                                      sizeof(Field*)))))
 
1708
    goto err;
 
1709
 
 
1710
  outparam->vfield= vfield_ptr;
 
1711
  
 
1712
  for (field_ptr= outparam->field; *field_ptr; field_ptr++)
 
1713
  {
 
1714
    if ((*field_ptr)->vcol_info)
 
1715
    {
 
1716
      if (unpack_vcol_info_from_frm(thd,
 
1717
                                    outparam,
 
1718
                                    *field_ptr,
 
1719
                                    &(*field_ptr)->vcol_info->expr_str,
 
1720
                                    open_mode,
 
1721
                                    &error_reported))
 
1722
      {
 
1723
        error= 4; // in case no error is reported
 
1724
        goto err;
 
1725
      }
 
1726
      *(vfield_ptr++)= *field_ptr;
 
1727
    }
 
1728
  }
 
1729
  *vfield_ptr= NULL;                              // End marker
 
1730
  /* Check virtual columns against table's storage engine. */
 
1731
  if ((share->vfields && outparam->file) && 
 
1732
        (not outparam->file->check_if_supported_virtual_columns()))
 
1733
  {
 
1734
    my_error(ER_UNSUPPORTED_ACTION_ON_VIRTUAL_COLUMN,
 
1735
             MYF(0), 
 
1736
             "Specified storage engine");
 
1737
    error_reported= true;
 
1738
    goto err;
 
1739
  }
 
1740
 
 
1741
  /* Allocate bitmaps */
 
1742
 
 
1743
  bitmap_size= share->column_bitmap_size;
 
1744
  if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
 
1745
    goto err;
 
1746
  bitmap_init(&outparam->def_read_set,
 
1747
              (my_bitmap_map*) bitmaps, share->fields, false);
 
1748
  bitmap_init(&outparam->def_write_set,
 
1749
              (my_bitmap_map*) (bitmaps+bitmap_size), share->fields, false);
 
1750
  bitmap_init(&outparam->tmp_set,
 
1751
              (my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, false);
 
1752
  outparam->default_column_bitmaps();
 
1753
 
 
1754
  /* The table struct is now initialized;  Open the table */
 
1755
  error= 2;
 
1756
  if (db_stat && open_mode != OTM_ALTER)
 
1757
  {
 
1758
    int ha_err;
 
1759
    if ((ha_err= (outparam->file->
 
1760
                  ha_open(outparam, share->normalized_path.str,
 
1761
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
 
1762
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
 
1763
                           (db_stat & HA_WAIT_IF_LOCKED) ?  HA_OPEN_WAIT_IF_LOCKED :
 
1764
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
 
1765
                          HA_OPEN_ABORT_IF_LOCKED :
 
1766
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
 
1767
    {
 
1768
      /* Set a flag if the table is crashed and it can be auto. repaired */
 
1769
      share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
 
1770
                       outparam->file->auto_repair() &&
 
1771
                       !(ha_open_flags & HA_OPEN_FOR_REPAIR));
 
1772
 
 
1773
      switch (ha_err)
 
1774
      {
 
1775
        case HA_ERR_NO_SUCH_TABLE:
 
1776
          /*
 
1777
            The table did not exists in storage engine, use same error message
 
1778
            as if the .frm file didn't exist
 
1779
          */
 
1780
          error= 1;
 
1781
          my_errno= ENOENT;
 
1782
          break;
 
1783
        case EMFILE:
 
1784
          /*
 
1785
            Too many files opened, use same error message as if the .frm
 
1786
            file can't open
 
1787
           */
 
1788
          error= 1;
 
1789
          my_errno= EMFILE;
 
1790
          break;
 
1791
        default:
 
1792
          outparam->file->print_error(ha_err, MYF(0));
 
1793
          error_reported= true;
 
1794
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
 
1795
            error= 7;
 
1796
          break;
 
1797
      }
 
1798
      goto err;                                 /* purecov: inspected */
 
1799
    }
 
1800
  }
 
1801
 
 
1802
#if defined(HAVE_purify) 
 
1803
  memset(bitmaps, 0, bitmap_size*3);
 
1804
#endif
 
1805
 
 
1806
  outparam->no_replicate= outparam->file;
 
1807
  thd->status_var.opened_tables++;
 
1808
 
 
1809
  return (0);
 
1810
 
 
1811
 err:
 
1812
  if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
 
1813
    open_table_error(share, error, my_errno, 0);
 
1814
  delete outparam->file;
 
1815
  outparam->file= 0;                            // For easier error checking
 
1816
  outparam->db_stat=0;
 
1817
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on zeroed root
 
1818
  free((char*) outparam->alias);
 
1819
  return (error);
 
1820
}
 
1821
 
 
1822
 
 
1823
/*
 
1824
  Free information allocated by openfrm
 
1825
 
 
1826
  SYNOPSIS
 
1827
    closefrm()
 
1828
    table               Table object to free
 
1829
    free_share          Is 1 if we also want to free table_share
 
1830
*/
 
1831
 
 
1832
int closefrm(register Table *table, bool free_share)
 
1833
{
 
1834
  int error=0;
 
1835
 
 
1836
  if (table->db_stat)
 
1837
    error=table->file->close();
 
1838
  free((char*) table->alias);
 
1839
  table->alias= 0;
 
1840
  if (table->field)
 
1841
  {
 
1842
    for (Field **ptr=table->field ; *ptr ; ptr++)
90
1843
      delete *ptr;
91
 
    }
92
 
    field= 0;
 
1844
    table->field= 0;
93
1845
  }
94
 
  safe_delete(cursor);
95
 
 
 
1846
  delete table->file;
 
1847
  table->file= 0;                               /* For easier errorchecking */
96
1848
  if (free_share)
97
1849
  {
98
 
    release();
 
1850
    if (table->s->tmp_table == NO_TMP_TABLE)
 
1851
      release_table_share(table->s, RELEASE_NORMAL);
 
1852
    else
 
1853
      free_table_share(table->s);
99
1854
  }
100
 
 
101
 
  return error;
102
 
}
103
 
 
104
 
Table::~Table()
105
 
{
106
 
  mem_root.free_root(MYF(0));
107
 
}
108
 
 
109
 
 
110
 
void Table::resetTable(Session *session,
111
 
                       TableShare *share,
112
 
                       uint32_t db_stat_arg)
113
 
{
114
 
  setShare(share);
115
 
  in_use= session;
116
 
 
117
 
  field= NULL;
118
 
 
119
 
  cursor= NULL;
120
 
  next= NULL;
121
 
  prev= NULL;
122
 
 
123
 
  read_set= NULL;
124
 
  write_set= NULL;
125
 
 
126
 
  tablenr= 0;
127
 
  db_stat= db_stat_arg;
128
 
 
129
 
  record[0]= (unsigned char *) NULL;
130
 
  record[1]= (unsigned char *) NULL;
131
 
 
132
 
  insert_values.clear();
133
 
  key_info= NULL;
134
 
  next_number_field= NULL;
135
 
  found_next_number_field= NULL;
136
 
  timestamp_field= NULL;
137
 
 
138
 
  pos_in_table_list= NULL;
139
 
  group= NULL;
140
 
  _alias.clear();
141
 
  null_flags= NULL;
142
 
 
143
 
  lock_position= 0;
144
 
  lock_data_start= 0;
145
 
  lock_count= 0;
146
 
  used_fields= 0;
147
 
  status= 0;
148
 
  derived_select_number= 0;
149
 
  current_lock= F_UNLCK;
150
 
  copy_blobs= false;
151
 
 
152
 
  maybe_null= false;
153
 
 
154
 
  null_row= false;
155
 
 
156
 
  force_index= false;
157
 
  distinct= false;
158
 
  const_table= false;
159
 
  no_rows= false;
160
 
  key_read= false;
161
 
  no_keyread= false;
162
 
 
163
 
  open_placeholder= false;
164
 
  locked_by_name= false;
165
 
  no_cache= false;
166
 
 
167
 
  auto_increment_field_not_null= false;
168
 
  alias_name_used= false;
169
 
 
170
 
  query_id= 0;
171
 
  quick_condition_rows= 0;
172
 
 
173
 
  timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
174
 
  map= 0;
175
 
 
176
 
  reginfo.reset();
177
 
 
178
 
  covering_keys.reset();
179
 
 
180
 
  quick_keys.reset();
181
 
  merge_keys.reset();
182
 
 
183
 
  keys_in_use_for_query.reset();
184
 
  keys_in_use_for_group_by.reset();
185
 
  keys_in_use_for_order_by.reset();
186
 
 
187
 
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
188
 
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
189
 
 
190
 
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
191
 
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
192
 
 
193
 
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
194
 
}
195
 
 
 
1855
  free_root(&table->mem_root, MYF(0));
 
1856
  return(error);
 
1857
}
196
1858
 
197
1859
 
198
1860
/* Deallocate temporary blob storage */
199
1861
 
200
 
void free_blobs(Table *table)
 
1862
void free_blobs(register Table *table)
201
1863
{
202
1864
  uint32_t *ptr, *end;
203
1865
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
204
1866
       ptr != end ;
205
1867
       ptr++)
206
 
  {
207
 
    ((Field_blob*) table->getField(*ptr))->free();
208
 
  }
209
 
}
210
 
 
211
 
 
212
 
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
213
 
{
214
 
  TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
 
1868
    ((Field_blob*) table->field[*ptr])->free();
 
1869
}
 
1870
 
 
1871
 
 
1872
        /* Find where a form starts */
 
1873
        /* if formname is NULL then only formnames is read */
 
1874
 
 
1875
ulong get_form_pos(File file, unsigned char *head, TYPELIB *save_names)
 
1876
{
 
1877
  uint32_t a_length,names,length;
 
1878
  unsigned char *pos,*buf;
 
1879
  ulong ret_value=0;
 
1880
 
 
1881
  names=uint2korr(head+8);
 
1882
  a_length=(names+2)*sizeof(char *);            /* Room for two extra */
 
1883
 
 
1884
  if (!save_names)
 
1885
    a_length=0;
 
1886
  else
 
1887
    save_names->type_names=0;                   /* Clear if error */
 
1888
 
 
1889
  if (names)
 
1890
  {
 
1891
    length=uint2korr(head+4);
 
1892
    my_seek(file,64L,MY_SEEK_SET,MYF(0));
 
1893
    if (!(buf= (unsigned char*) my_malloc((size_t) length+a_length+names*4,
 
1894
                                  MYF(MY_WME))) ||
 
1895
        my_read(file, buf+a_length, (size_t) (length+names*4),
 
1896
                MYF(MY_NABP)))
 
1897
    {                                           /* purecov: inspected */
 
1898
      if (buf)
 
1899
        free(buf);
 
1900
      return(0L);                               /* purecov: inspected */
 
1901
    }
 
1902
    pos= buf+a_length+length;
 
1903
    ret_value=uint4korr(pos);
 
1904
  }
 
1905
  if (! save_names)
 
1906
  {
 
1907
    if (names)
 
1908
      free((unsigned char*) buf);
 
1909
  }
 
1910
  else if (!names)
 
1911
    memset(save_names, 0, sizeof(save_names));
 
1912
  else
 
1913
  {
 
1914
    char *str;
 
1915
    str=(char *) (buf+a_length);
 
1916
    fix_type_pointers((const char ***) &buf,save_names,1,&str);
 
1917
  }
 
1918
  return(ret_value);
 
1919
}
 
1920
 
 
1921
 
 
1922
/*
 
1923
  Read string from a file with malloc
 
1924
 
 
1925
  NOTES:
 
1926
    We add an \0 at end of the read string to make reading of C strings easier
 
1927
*/
 
1928
 
 
1929
int read_string(File file, unsigned char**to, size_t length)
 
1930
{
 
1931
 
 
1932
  if (*to)
 
1933
    free(*to);
 
1934
  if (!(*to= (unsigned char*) my_malloc(length+1,MYF(MY_WME))) ||
 
1935
      my_read(file, *to, length,MYF(MY_NABP)))
 
1936
  {
 
1937
    if (*to)
 
1938
      free(*to);
 
1939
    *to= NULL;
 
1940
    return(1);                           /* purecov: inspected */
 
1941
  }
 
1942
  *((char*) *to+length)= '\0';
 
1943
  return (0);
 
1944
} /* read_string */
 
1945
 
 
1946
 
 
1947
        /* Add a new form to a form file */
 
1948
 
 
1949
ulong make_new_entry(File file, unsigned char *fileinfo, TYPELIB *formnames,
 
1950
                     const char *newname)
 
1951
{
 
1952
  uint32_t i,bufflength,maxlength,n_length,length,names;
 
1953
  ulong endpos,newpos;
 
1954
  unsigned char buff[IO_SIZE];
 
1955
  unsigned char *pos;
 
1956
 
 
1957
  length=(uint) strlen(newname)+1;
 
1958
  n_length=uint2korr(fileinfo+4);
 
1959
  maxlength=uint2korr(fileinfo+6);
 
1960
  names=uint2korr(fileinfo+8);
 
1961
  newpos=uint4korr(fileinfo+10);
 
1962
 
 
1963
  if (64+length+n_length+(names+1)*4 > maxlength)
 
1964
  {                                             /* Expand file */
 
1965
    newpos+=IO_SIZE;
 
1966
    int4store(fileinfo+10,newpos);
 
1967
    endpos=(ulong) my_seek(file,0L,MY_SEEK_END,MYF(0));/* Copy from file-end */
 
1968
    bufflength= (uint) (endpos & (IO_SIZE-1));  /* IO_SIZE is a power of 2 */
 
1969
 
 
1970
    while (endpos > maxlength)
 
1971
    {
 
1972
      my_seek(file,(ulong) (endpos-bufflength),MY_SEEK_SET,MYF(0));
 
1973
      if (my_read(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
 
1974
        return(0L);
 
1975
      my_seek(file,(ulong) (endpos-bufflength+IO_SIZE),MY_SEEK_SET,
 
1976
                   MYF(0));
 
1977
      if ((my_write(file, buff,bufflength,MYF(MY_NABP+MY_WME))))
 
1978
        return(0);
 
1979
      endpos-=bufflength; bufflength=IO_SIZE;
 
1980
    }
 
1981
    memset(buff, 0, IO_SIZE);                   /* Null new block */
 
1982
    my_seek(file,(ulong) maxlength,MY_SEEK_SET,MYF(0));
 
1983
    if (my_write(file,buff,bufflength,MYF(MY_NABP+MY_WME)))
 
1984
        return(0L);
 
1985
    maxlength+=IO_SIZE;                         /* Fix old ref */
 
1986
    int2store(fileinfo+6,maxlength);
 
1987
    for (i=names, pos= (unsigned char*) *formnames->type_names+n_length-1; i-- ;
 
1988
         pos+=4)
 
1989
    {
 
1990
      endpos=uint4korr(pos)+IO_SIZE;
 
1991
      int4store(pos,endpos);
 
1992
    }
 
1993
  }
 
1994
 
 
1995
  if (n_length == 1 )
 
1996
  {                                             /* First name */
 
1997
    length++;
 
1998
    strxmov((char*) buff,"/",newname,"/",NULL);
 
1999
  }
 
2000
  else
 
2001
    strxmov((char*) buff,newname,"/",NULL); /* purecov: inspected */
 
2002
  my_seek(file,63L+(ulong) n_length,MY_SEEK_SET,MYF(0));
 
2003
  if (my_write(file, buff, (size_t) length+1,MYF(MY_NABP+MY_WME)) ||
 
2004
      (names && my_write(file,(unsigned char*) (*formnames->type_names+n_length-1),
 
2005
                         names*4, MYF(MY_NABP+MY_WME))) ||
 
2006
      my_write(file, fileinfo+10, 4,MYF(MY_NABP+MY_WME)))
 
2007
    return(0L); /* purecov: inspected */
 
2008
 
 
2009
  int2store(fileinfo+8,names+1);
 
2010
  int2store(fileinfo+4,n_length+length);
 
2011
  assert(ftruncate(file, newpos)==0);/* Append file with '\0' */
 
2012
  return(newpos);
 
2013
} /* make_new_entry */
 
2014
 
 
2015
 
 
2016
        /* error message when opening a form file */
 
2017
 
 
2018
void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
 
2019
{
 
2020
  int err_no;
 
2021
  char buff[FN_REFLEN];
 
2022
  myf errortype= ME_ERROR+ME_WAITTANG;
 
2023
 
 
2024
  switch (error) {
 
2025
  case 7:
 
2026
  case 1:
 
2027
    if (db_errno == ENOENT)
 
2028
      my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
 
2029
    else
 
2030
    {
 
2031
      strxmov(buff, share->normalized_path.str, reg_ext, NULL);
 
2032
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
 
2033
               errortype, buff, db_errno);
 
2034
    }
 
2035
    break;
 
2036
  case 2:
 
2037
  {
 
2038
    handler *file= 0;
 
2039
    const char *datext= "";
 
2040
    
 
2041
    if (share->db_type() != NULL)
 
2042
    {
 
2043
      if ((file= get_new_handler(share, current_thd->mem_root,
 
2044
                                 share->db_type())))
 
2045
      {
 
2046
        if (!(datext= *file->bas_ext()))
 
2047
          datext= "";
 
2048
      }
 
2049
    }
 
2050
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
 
2051
      ER_FILE_USED : ER_CANT_OPEN_FILE;
 
2052
    strxmov(buff, share->normalized_path.str, datext, NULL);
 
2053
    my_error(err_no,errortype, buff, db_errno);
 
2054
    delete file;
 
2055
    break;
 
2056
  }
 
2057
  case 5:
 
2058
  {
 
2059
    const char *csname= get_charset_name((uint) errarg);
 
2060
    char tmp[10];
 
2061
    if (!csname || csname[0] =='?')
 
2062
    {
 
2063
      snprintf(tmp, sizeof(tmp), "#%d", errarg);
 
2064
      csname= tmp;
 
2065
    }
 
2066
    my_printf_error(ER_UNKNOWN_COLLATION,
 
2067
                    _("Unknown collation '%s' in table '%-.64s' definition"), 
 
2068
                    MYF(0), csname, share->table_name.str);
 
2069
    break;
 
2070
  }
 
2071
  case 6:
 
2072
    strxmov(buff, share->normalized_path.str, reg_ext, NULL);
 
2073
    my_printf_error(ER_NOT_FORM_FILE,
 
2074
                    _("Table '%-.64s' was created with a different version "
 
2075
                    "of MySQL and cannot be read"), 
 
2076
                    MYF(0), buff);
 
2077
    break;
 
2078
  case 8:
 
2079
    break;
 
2080
  default:                              /* Better wrong error than none */
 
2081
  case 4:
 
2082
    strxmov(buff, share->normalized_path.str, reg_ext, NULL);
 
2083
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
 
2084
    break;
 
2085
  }
 
2086
  return;
 
2087
} /* open_table_error */
 
2088
 
 
2089
 
 
2090
        /*
 
2091
        ** fix a str_type to a array type
 
2092
        ** typeparts separated with some char. differents types are separated
 
2093
        ** with a '\0'
 
2094
        */
 
2095
 
 
2096
static void
 
2097
fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint32_t types,
 
2098
                  char **names)
 
2099
{
 
2100
  char *type_name, *ptr;
 
2101
  char chr;
 
2102
 
 
2103
  ptr= *names;
 
2104
  while (types--)
 
2105
  {
 
2106
    point_to_type->name=0;
 
2107
    point_to_type->type_names= *array;
 
2108
 
 
2109
    if ((chr= *ptr))                    /* Test if empty type */
 
2110
    {
 
2111
      while ((type_name=strchr(ptr+1,chr)) != NULL)
 
2112
      {
 
2113
        *((*array)++) = ptr+1;
 
2114
        *type_name= '\0';               /* End string */
 
2115
        ptr=type_name;
 
2116
      }
 
2117
      ptr+=2;                           /* Skip end mark and last 0 */
 
2118
    }
 
2119
    else
 
2120
      ptr++;
 
2121
    point_to_type->count= (uint) (*array - point_to_type->type_names);
 
2122
    point_to_type++;
 
2123
    *((*array)++)= NULL;                /* End of type */
 
2124
  }
 
2125
  *names=ptr;                           /* Update end */
 
2126
  return;
 
2127
} /* fix_type_pointers */
 
2128
 
 
2129
 
 
2130
TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
 
2131
{
 
2132
  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
215
2133
  if (!result)
216
2134
    return 0;
217
 
  result->count= strings.elements;
218
 
  result->name= "";
219
 
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
220
 
  
221
 
  if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
 
2135
  result->count=strings.elements;
 
2136
  result->name="";
 
2137
  uint32_t nbytes= (sizeof(char*) + sizeof(uint)) * (result->count + 1);
 
2138
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
222
2139
    return 0;
223
 
    
224
2140
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
225
 
 
226
 
  List<String>::iterator it(strings.begin());
 
2141
  List_iterator<String> it(strings);
227
2142
  String *tmp;
228
 
  for (uint32_t i= 0; (tmp= it++); i++)
 
2143
  for (uint32_t i=0; (tmp=it++) ; i++)
229
2144
  {
230
2145
    result->type_names[i]= tmp->ptr();
231
2146
    result->type_lengths[i]= tmp->length();
232
2147
  }
233
 
 
234
 
  result->type_names[result->count]= 0;   // End marker
 
2148
  result->type_names[result->count]= 0;         // End marker
235
2149
  result->type_lengths[result->count]= 0;
236
 
 
237
2150
  return result;
238
2151
}
239
2152
 
 
2153
 
 
2154
/*
 
2155
 Search after a field with given start & length
 
2156
 If an exact field isn't found, return longest field with starts
 
2157
 at right position.
 
2158
 
 
2159
 NOTES
 
2160
   This is needed because in some .frm fields 'fieldnr' was saved wrong
 
2161
 
 
2162
 RETURN
 
2163
   0  error
 
2164
   #  field number +1
 
2165
*/
 
2166
 
 
2167
static uint32_t find_field(Field **fields, unsigned char *record, uint32_t start, uint32_t length)
 
2168
{
 
2169
  Field **field;
 
2170
  uint32_t i, pos;
 
2171
 
 
2172
  pos= 0;
 
2173
  for (field= fields, i=1 ; *field ; i++,field++)
 
2174
  {
 
2175
    if ((*field)->offset(record) == start)
 
2176
    {
 
2177
      if ((*field)->key_length() == length)
 
2178
        return (i);
 
2179
      if (!pos || fields[pos-1]->pack_length() <
 
2180
          (*field)->pack_length())
 
2181
        pos= i;
 
2182
    }
 
2183
  }
 
2184
  return (pos);
 
2185
}
 
2186
 
 
2187
 
240
2188
        /* Check that the integer is in the internal */
241
2189
 
242
 
int set_zone(int nr, int min_zone, int max_zone)
 
2190
int set_zone(register int nr, int min_zone, int max_zone)
243
2191
{
244
2192
  if (nr<=min_zone)
245
2193
    return (min_zone);
248
2196
  return (nr);
249
2197
} /* set_zone */
250
2198
 
 
2199
        /* Adjust number to next larger disk buffer */
 
2200
 
 
2201
ulong next_io_size(register ulong pos)
 
2202
{
 
2203
  register ulong offset;
 
2204
  if ((offset= pos & (IO_SIZE-1)))
 
2205
    return pos-offset+IO_SIZE;
 
2206
  return pos;
 
2207
} /* next_io_size */
 
2208
 
251
2209
 
252
2210
/*
253
2211
  Store an SQL quoted string.
254
2212
 
255
 
  SYNOPSIS
 
2213
  SYNOPSIS  
256
2214
    append_unescaped()
257
2215
    res         result String
258
2216
    pos         string to be quoted
270
2228
 
271
2229
  for (; pos != end ; pos++)
272
2230
  {
 
2231
#if defined(USE_MB)
273
2232
    uint32_t mblen;
274
2233
    if (use_mb(default_charset_info) &&
275
2234
        (mblen= my_ismbchar(default_charset_info, pos, end)))
276
2235
    {
277
2236
      res->append(pos, mblen);
278
 
      pos+= mblen - 1;
279
 
      if (pos >= end)
280
 
        break;
 
2237
      pos+= mblen;
281
2238
      continue;
282
2239
    }
 
2240
#endif
283
2241
 
284
2242
    switch (*pos) {
285
2243
    case 0:                             /* Must be escaped for 'mysql' */
311
2269
}
312
2270
 
313
2271
 
314
 
int rename_file_ext(const char * from,const char * to,const char * ext)
315
 
{
316
 
  string from_s, to_s;
317
 
 
318
 
  from_s.append(from);
319
 
  from_s.append(ext);
320
 
  to_s.append(to);
321
 
  to_s.append(ext);
322
 
  return (internal::my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
323
 
}
 
2272
        /* Create a .frm file */
 
2273
 
 
2274
File create_frm(THD *thd, const char *name, const char *db,
 
2275
                const char *table, uint32_t reclength, unsigned char *fileinfo,
 
2276
                HA_CREATE_INFO *create_info, uint32_t keys, KEY *key_info)
 
2277
{
 
2278
  register File file;
 
2279
  ulong length;
 
2280
  unsigned char fill[IO_SIZE];
 
2281
  int create_flags= O_RDWR | O_TRUNC;
 
2282
  ulong key_comment_total_bytes= 0;
 
2283
  uint32_t i;
 
2284
 
 
2285
  if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
 
2286
    create_flags|= O_EXCL;
 
2287
 
 
2288
  /* Fix this when we have new .frm files;  Current limit is 4G rows (QQ) */
 
2289
  if (create_info->max_rows > UINT32_MAX)
 
2290
    create_info->max_rows= UINT32_MAX;
 
2291
  if (create_info->min_rows > UINT32_MAX)
 
2292
    create_info->min_rows= UINT32_MAX;
 
2293
 
 
2294
  if ((file= my_create(name, CREATE_MODE, create_flags, MYF(0))) >= 0)
 
2295
  {
 
2296
    uint32_t key_length, tmp_key_length;
 
2297
    uint32_t tmp;
 
2298
    memset(fileinfo, 0, 64);
 
2299
    /* header */
 
2300
    fileinfo[0]=(unsigned char) 254;
 
2301
    fileinfo[1]= 1;
 
2302
    fileinfo[2]= FRM_VER+3+ test(create_info->varchar);
 
2303
 
 
2304
    fileinfo[3]= (unsigned char) ha_legacy_type(
 
2305
          ha_checktype(thd,ha_legacy_type(create_info->db_type),0,0));
 
2306
    fileinfo[4]=1;
 
2307
    int2store(fileinfo+6,IO_SIZE);              /* Next block starts here */
 
2308
    for (i= 0; i < keys; i++)
 
2309
    {
 
2310
      assert(test(key_info[i].flags & HA_USES_COMMENT) == 
 
2311
                 (key_info[i].comment.length > 0));
 
2312
      if (key_info[i].flags & HA_USES_COMMENT)
 
2313
        key_comment_total_bytes += 2 + key_info[i].comment.length;
 
2314
    }
 
2315
    /*
 
2316
      Keep in sync with pack_keys() in unireg.cc
 
2317
      For each key:
 
2318
      8 bytes for the key header
 
2319
      9 bytes for each key-part (MAX_REF_PARTS)
 
2320
      NAME_LEN bytes for the name
 
2321
      1 byte for the NAMES_SEP_CHAR (before the name)
 
2322
      For all keys:
 
2323
      6 bytes for the header
 
2324
      1 byte for the NAMES_SEP_CHAR (after the last name)
 
2325
      9 extra bytes (padding for safety? alignment?)
 
2326
      comments
 
2327
    */
 
2328
    key_length= (keys * (8 + MAX_REF_PARTS * 9 + NAME_LEN + 1) + 16 +
 
2329
                 key_comment_total_bytes);
 
2330
    length= next_io_size((ulong) (IO_SIZE+key_length+reclength+
 
2331
                                  create_info->extra_size));
 
2332
    int4store(fileinfo+10,length);
 
2333
    tmp_key_length= (key_length < 0xffff) ? key_length : 0xffff;
 
2334
    int2store(fileinfo+14,tmp_key_length);
 
2335
    int2store(fileinfo+16,reclength);
 
2336
    int4store(fileinfo+18,create_info->max_rows);
 
2337
    int4store(fileinfo+22,create_info->min_rows);
 
2338
    /* fileinfo[26] is set in mysql_create_frm() */
 
2339
    fileinfo[27]=2;                             // Use long pack-fields
 
2340
    /* fileinfo[28 & 29] is set to key_info_length in mysql_create_frm() */
 
2341
    create_info->table_options|=HA_OPTION_LONG_BLOB_PTR; // Use portable blob pointers
 
2342
    int2store(fileinfo+30,create_info->table_options);
 
2343
    fileinfo[32]=0;                             // No filename anymore
 
2344
    fileinfo[33]=5;                             // Mark for 5.0 frm file
 
2345
    int4store(fileinfo+34,create_info->avg_row_length);
 
2346
    fileinfo[38]= (create_info->default_table_charset ?
 
2347
                   create_info->default_table_charset->number : 0);
 
2348
    fileinfo[39]= (unsigned char) create_info->page_checksum;
 
2349
    fileinfo[40]= (unsigned char) create_info->row_type;
 
2350
    /* Next few bytes were for RAID support */
 
2351
    fileinfo[41]= 0;
 
2352
    fileinfo[42]= 0;
 
2353
    int4store(fileinfo+43,create_info->block_size);
 
2354
 
 
2355
    fileinfo[44]= 0;
 
2356
    fileinfo[45]= 0;
 
2357
    fileinfo[46]= 0;
 
2358
    int4store(fileinfo+47, key_length);
 
2359
    tmp= DRIZZLE_VERSION_ID;          // Store to avoid warning from int4store
 
2360
    int4store(fileinfo+51, tmp);
 
2361
    int4store(fileinfo+55, create_info->extra_size);
 
2362
    /*
 
2363
      59-60 is reserved for extra_rec_buf_length,
 
2364
      61 for default_part_db_type
 
2365
    */
 
2366
    int2store(fileinfo+62, create_info->key_block_size);
 
2367
    memset(fill, 0, IO_SIZE);
 
2368
    for (; length > IO_SIZE ; length-= IO_SIZE)
 
2369
    {
 
2370
      if (my_write(file,fill, IO_SIZE, MYF(MY_WME | MY_NABP)))
 
2371
      {
 
2372
        my_close(file,MYF(0));
 
2373
        my_delete(name,MYF(0));
 
2374
        return(-1);
 
2375
      }
 
2376
    }
 
2377
  }
 
2378
  else
 
2379
  {
 
2380
    if (my_errno == ENOENT)
 
2381
      my_error(ER_BAD_DB_ERROR,MYF(0),db);
 
2382
    else
 
2383
      my_error(ER_CANT_CREATE_TABLE,MYF(0),table,my_errno);
 
2384
  }
 
2385
  return (file);
 
2386
} /* create_frm */
 
2387
 
 
2388
/*
 
2389
  Set up column usage bitmaps for a temporary table
 
2390
 
 
2391
  IMPLEMENTATION
 
2392
    For temporary tables, we need one bitmap with all columns set and
 
2393
    a tmp_set bitmap to be used by things like filesort.
 
2394
*/
 
2395
 
 
2396
void Table::setup_tmp_table_column_bitmaps(unsigned char *bitmaps)
 
2397
{
 
2398
  uint32_t field_count= s->fields;
 
2399
 
 
2400
  bitmap_init(&this->def_read_set, (my_bitmap_map*) bitmaps, field_count, false);
 
2401
  bitmap_init(&this->tmp_set, (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)), field_count, false);
 
2402
 
 
2403
  /* write_set and all_set are copies of read_set */
 
2404
  def_write_set= def_read_set;
 
2405
  s->all_set= def_read_set;
 
2406
  bitmap_set_all(&this->s->all_set);
 
2407
  default_column_bitmaps();
 
2408
}
 
2409
 
 
2410
 
 
2411
 
 
2412
void Table::updateCreateInfo(HA_CREATE_INFO *create_info)
 
2413
{
 
2414
  create_info->max_rows= s->max_rows;
 
2415
  create_info->min_rows= s->min_rows;
 
2416
  create_info->table_options= s->db_create_options;
 
2417
  create_info->avg_row_length= s->avg_row_length;
 
2418
  create_info->block_size= s->block_size;
 
2419
  create_info->row_type= s->row_type;
 
2420
  create_info->default_table_charset= s->table_charset;
 
2421
  create_info->table_charset= 0;
 
2422
  create_info->comment= s->comment;
 
2423
 
 
2424
  return;
 
2425
}
 
2426
 
 
2427
int
 
2428
rename_file_ext(const char * from,const char * to,const char * ext)
 
2429
{
 
2430
  char from_b[FN_REFLEN],to_b[FN_REFLEN];
 
2431
  strxmov(from_b,from,ext,NULL);
 
2432
  strxmov(to_b,to,ext,NULL);
 
2433
  return (my_rename(from_b,to_b,MYF(MY_WME)));
 
2434
}
 
2435
 
 
2436
 
 
2437
/*
 
2438
  Allocate string field in MEM_ROOT and return it as String
 
2439
 
 
2440
  SYNOPSIS
 
2441
    get_field()
 
2442
    mem         MEM_ROOT for allocating
 
2443
    field       Field for retrieving of string
 
2444
    res         result String
 
2445
 
 
2446
  RETURN VALUES
 
2447
    1   string is empty
 
2448
    0   all ok
 
2449
*/
 
2450
 
 
2451
bool get_field(MEM_ROOT *mem, Field *field, String *res)
 
2452
{
 
2453
  char buff[MAX_FIELD_WIDTH], *to;
 
2454
  String str(buff,sizeof(buff),&my_charset_bin);
 
2455
  uint32_t length;
 
2456
 
 
2457
  field->val_str(&str);
 
2458
  if (!(length= str.length()))
 
2459
  {
 
2460
    res->length(0);
 
2461
    return 1;
 
2462
  }
 
2463
  if (!(to= strmake_root(mem, str.ptr(), length)))
 
2464
    length= 0;                                  // Safety fix
 
2465
  res->set(to, length, ((Field_str*)field)->charset());
 
2466
  return 0;
 
2467
}
 
2468
 
 
2469
 
 
2470
/*
 
2471
  Allocate string field in MEM_ROOT and return it as NULL-terminated string
 
2472
 
 
2473
  SYNOPSIS
 
2474
    get_field()
 
2475
    mem         MEM_ROOT for allocating
 
2476
    field       Field for retrieving of string
 
2477
 
 
2478
  RETURN VALUES
 
2479
    NULL  string is empty
 
2480
    #      pointer to NULL-terminated string value of field
 
2481
*/
 
2482
 
 
2483
char *get_field(MEM_ROOT *mem, Field *field)
 
2484
{
 
2485
  char buff[MAX_FIELD_WIDTH], *to;
 
2486
  String str(buff,sizeof(buff),&my_charset_bin);
 
2487
  uint32_t length;
 
2488
 
 
2489
  field->val_str(&str);
 
2490
  length= str.length();
 
2491
  if (!length || !(to= (char*) alloc_root(mem,length+1)))
 
2492
    return NULL;
 
2493
  memcpy(to,str.ptr(),(uint) length);
 
2494
  to[length]=0;
 
2495
  return to;
 
2496
}
 
2497
 
 
2498
/*
 
2499
  DESCRIPTION
 
2500
    given a buffer with a key value, and a map of keyparts
 
2501
    that are present in this value, returns the length of the value
 
2502
*/
 
2503
uint32_t calculate_key_len(Table *table, uint32_t key,
 
2504
                       const unsigned char *buf __attribute__((unused)),
 
2505
                       key_part_map keypart_map)
 
2506
{
 
2507
  /* works only with key prefixes */
 
2508
  assert(((keypart_map + 1) & keypart_map) == 0);
 
2509
 
 
2510
  KEY *key_info= table->s->key_info+key;
 
2511
  KEY_PART_INFO *key_part= key_info->key_part;
 
2512
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
 
2513
  uint32_t length= 0;
 
2514
 
 
2515
  while (key_part < end_key_part && keypart_map)
 
2516
  {
 
2517
    length+= key_part->store_length;
 
2518
    keypart_map >>= 1;
 
2519
    key_part++;
 
2520
  }
 
2521
  return length;
 
2522
}
 
2523
 
 
2524
/*
 
2525
  Check if database name is valid
 
2526
 
 
2527
  SYNPOSIS
 
2528
    check_db_name()
 
2529
    org_name            Name of database and length
 
2530
 
 
2531
  NOTES
 
2532
    If lower_case_table_names is set then database is converted to lower case
 
2533
 
 
2534
  RETURN
 
2535
    0   ok
 
2536
    1   error
 
2537
*/
 
2538
 
 
2539
bool check_db_name(LEX_STRING *org_name)
 
2540
{
 
2541
  char *name= org_name->str;
 
2542
  uint32_t name_length= org_name->length;
 
2543
 
 
2544
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
 
2545
    return 1;
 
2546
 
 
2547
  if (lower_case_table_names && name != any_db)
 
2548
    my_casedn_str(files_charset_info, name);
 
2549
 
 
2550
  return check_identifier_name(org_name);
 
2551
}
 
2552
 
324
2553
 
325
2554
/*
326
2555
  Allow anything as a table name, as long as it doesn't contain an
327
2556
  ' ' at the end
328
2557
  returns 1 on error
329
2558
*/
 
2559
 
 
2560
 
330
2561
bool check_table_name(const char *name, uint32_t length)
331
2562
{
332
2563
  if (!length || length > NAME_LEN || name[length - 1] == ' ')
347
2578
{
348
2579
  uint32_t name_length= 0;  // name length in symbols
349
2580
  bool last_char_is_space= true;
350
 
 
 
2581
  
351
2582
  while (*name)
352
2583
  {
 
2584
#if defined(USE_MB) && defined(USE_MB_IDENT)
353
2585
    last_char_is_space= my_isspace(system_charset_info, *name);
354
2586
    if (use_mb(system_charset_info))
355
2587
    {
356
 
      int len=my_ismbchar(system_charset_info, name,
 
2588
      int len=my_ismbchar(system_charset_info, name, 
357
2589
                          name+system_charset_info->mbmaxlen);
358
2590
      if (len)
359
2591
      {
364
2596
        continue;
365
2597
      }
366
2598
    }
 
2599
#else
 
2600
    last_char_is_space= *name==' ';
 
2601
#endif
367
2602
    /*
368
2603
      NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
369
2604
      It is defined as 0xFF, which is a not valid byte in utf8.
375
2610
    name_length++;
376
2611
  }
377
2612
  /* Error if empty or too long column name */
378
 
  return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
 
2613
  return last_char_is_space || (uint) name_length > NAME_CHAR_LEN;
 
2614
}
 
2615
 
 
2616
 
 
2617
/**
 
2618
  Checks whether a table is intact. Should be done *just* after the table has
 
2619
  been opened.
 
2620
 
 
2621
  @param[in] table             The table to check
 
2622
  @param[in] table_f_count     Expected number of columns in the table
 
2623
  @param[in] table_def         Expected structure of the table (column name
 
2624
                               and type)
 
2625
 
 
2626
  @retval  false  OK
 
2627
  @retval  TRUE   There was an error. An error message is output
 
2628
                  to the error log.  We do not push an error
 
2629
                  message into the error stack because this
 
2630
                  function is currently only called at start up,
 
2631
                  and such errors never reach the user.
 
2632
*/
 
2633
 
 
2634
bool
 
2635
Table::table_check_intact(const uint32_t table_f_count,
 
2636
                          const TABLE_FIELD_W_TYPE *table_def)
 
2637
{
 
2638
  uint32_t i;
 
2639
  bool error= false;
 
2640
  bool fields_diff_count;
 
2641
 
 
2642
  fields_diff_count= (s->fields != table_f_count);
 
2643
  if (fields_diff_count)
 
2644
  {
 
2645
 
 
2646
    /* previous MySQL version */
 
2647
    if (DRIZZLE_VERSION_ID > s->mysql_version)
 
2648
    {
 
2649
      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
 
2650
                      alias, table_f_count, s->fields,
 
2651
                      s->mysql_version, DRIZZLE_VERSION_ID);
 
2652
      return(true);
 
2653
    }
 
2654
    else if (DRIZZLE_VERSION_ID == s->mysql_version)
 
2655
    {
 
2656
      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), alias,
 
2657
                      table_f_count, s->fields);
 
2658
      return(true);
 
2659
    }
 
2660
    /*
 
2661
      Something has definitely changed, but we're running an older
 
2662
      version of MySQL with new system tables.
 
2663
      Let's check column definitions. If a column was added at
 
2664
      the end of the table, then we don't care much since such change
 
2665
      is backward compatible.
 
2666
    */
 
2667
  }
 
2668
  char buffer[STRING_BUFFER_USUAL_SIZE];
 
2669
  for (i=0 ; i < table_f_count; i++, table_def++)
 
2670
  {
 
2671
    String sql_type(buffer, sizeof(buffer), system_charset_info);
 
2672
    sql_type.length(0);
 
2673
    if (i < s->fields)
 
2674
    {
 
2675
      Field *field= this->field[i];
 
2676
 
 
2677
      if (strncmp(field->field_name, table_def->name.str,
 
2678
                  table_def->name.length))
 
2679
      {
 
2680
        /*
 
2681
          Name changes are not fatal, we use ordinal numbers to access columns.
 
2682
          Still this can be a sign of a tampered table, output an error
 
2683
          to the error log.
 
2684
        */
 
2685
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2686
                        "expected column '%s' at position %d, found '%s'."),
 
2687
                        s->db.str, alias, table_def->name.str, i,
 
2688
                        field->field_name);
 
2689
      }
 
2690
      field->sql_type(sql_type);
 
2691
      /*
 
2692
        Generally, if column types don't match, then something is
 
2693
        wrong.
 
2694
 
 
2695
        However, we only compare column definitions up to the
 
2696
        length of the original definition, since we consider the
 
2697
        following definitions compatible:
 
2698
 
 
2699
        1. DATETIME and DATETIM
 
2700
        2. INT(11) and INT(11
 
2701
        3. SET('one', 'two') and SET('one', 'two', 'more')
 
2702
 
 
2703
        For SETs or ENUMs, if the same prefix is there it's OK to
 
2704
        add more elements - they will get higher ordinal numbers and
 
2705
        the new table definition is backward compatible with the
 
2706
        original one.
 
2707
       */
 
2708
      if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
 
2709
                  table_def->type.length - 1))
 
2710
      {
 
2711
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2712
                        "expected column '%s' at position %d to have type "
 
2713
                        "%s, found type %s."), s->db.str, alias,
 
2714
                        table_def->name.str, i, table_def->type.str,
 
2715
                        sql_type.c_ptr_safe());
 
2716
        error= true;
 
2717
      }
 
2718
      else if (table_def->cset.str && !field->has_charset())
 
2719
      {
 
2720
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2721
                        "expected the type of column '%s' at position %d "
 
2722
                        "to have character set '%s' but the type has no "
 
2723
                        "character set."), s->db.str, alias,
 
2724
                        table_def->name.str, i, table_def->cset.str);
 
2725
        error= true;
 
2726
      }
 
2727
      else if (table_def->cset.str &&
 
2728
               strcmp(field->charset()->csname, table_def->cset.str))
 
2729
      {
 
2730
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2731
                        "expected the type of column '%s' at position %d "
 
2732
                        "to have character set '%s' but found "
 
2733
                        "character set '%s'."), s->db.str, alias,
 
2734
                        table_def->name.str, i, table_def->cset.str,
 
2735
                        field->charset()->csname);
 
2736
        error= true;
 
2737
      }
 
2738
    }
 
2739
    else
 
2740
    {
 
2741
      sql_print_error(_("Incorrect definition of table %s.%s: "
 
2742
                      "expected column '%s' at position %d to have type %s "
 
2743
                      " but the column is not found."),
 
2744
                      s->db.str, alias,
 
2745
                      table_def->name.str, i, table_def->type.str);
 
2746
      error= true;
 
2747
    }
 
2748
  }
 
2749
  return(error);
 
2750
}
 
2751
 
 
2752
 
 
2753
/*
 
2754
  Create Item_field for each column in the table.
 
2755
 
 
2756
  SYNPOSIS
 
2757
    Table::fill_item_list()
 
2758
      item_list          a pointer to an empty list used to store items
 
2759
 
 
2760
  DESCRIPTION
 
2761
    Create Item_field object for each column in the table and
 
2762
    initialize it with the corresponding Field. New items are
 
2763
    created in the current THD memory root.
 
2764
 
 
2765
  RETURN VALUE
 
2766
    0                    success
 
2767
    1                    out of memory
 
2768
*/
 
2769
 
 
2770
bool Table::fill_item_list(List<Item> *item_list) const
 
2771
{
 
2772
  /*
 
2773
    All Item_field's created using a direct pointer to a field
 
2774
    are fixed in Item_field constructor.
 
2775
  */
 
2776
  for (Field **ptr= field; *ptr; ptr++)
 
2777
  {
 
2778
    Item_field *item= new Item_field(*ptr);
 
2779
    if (!item || item_list->push_back(item))
 
2780
      return true;
 
2781
  }
 
2782
  return false;
 
2783
}
 
2784
 
 
2785
/*
 
2786
  Reset an existing list of Item_field items to point to the
 
2787
  Fields of this table.
 
2788
 
 
2789
  SYNPOSIS
 
2790
    Table::fill_item_list()
 
2791
      item_list          a non-empty list with Item_fields
 
2792
 
 
2793
  DESCRIPTION
 
2794
    This is a counterpart of fill_item_list used to redirect
 
2795
    Item_fields to the fields of a newly created table.
 
2796
    The caller must ensure that number of items in the item_list
 
2797
    is the same as the number of columns in the table.
 
2798
*/
 
2799
 
 
2800
void Table::reset_item_list(List<Item> *item_list) const
 
2801
{
 
2802
  List_iterator_fast<Item> it(*item_list);
 
2803
  for (Field **ptr= field; *ptr; ptr++)
 
2804
  {
 
2805
    Item_field *item_field= (Item_field*) it++;
 
2806
    assert(item_field != 0);
 
2807
    item_field->reset_field(*ptr);
 
2808
  }
 
2809
}
 
2810
 
 
2811
 
 
2812
/*
 
2813
  Find underlying base tables (TableList) which represent given
 
2814
  table_to_find (Table)
 
2815
 
 
2816
  SYNOPSIS
 
2817
    TableList::find_underlying_table()
 
2818
    table_to_find table to find
 
2819
 
 
2820
  RETURN
 
2821
    0  table is not found
 
2822
    found table reference
 
2823
*/
 
2824
 
 
2825
TableList *TableList::find_underlying_table(Table *table_to_find)
 
2826
{
 
2827
  /* is this real table and table which we are looking for? */
 
2828
  if (table == table_to_find && merge_underlying_list == 0)
 
2829
    return this;
 
2830
 
 
2831
  for (TableList *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
 
2832
  {
 
2833
    TableList *result;
 
2834
    if ((result= tbl->find_underlying_table(table_to_find)))
 
2835
      return result;
 
2836
  }
 
2837
  return 0;
 
2838
}
 
2839
 
 
2840
/*
 
2841
  cleunup items belonged to view fields translation table
 
2842
 
 
2843
  SYNOPSIS
 
2844
    TableList::cleanup_items()
 
2845
*/
 
2846
 
 
2847
void TableList::cleanup_items()
 
2848
{
 
2849
  if (!field_translation)
 
2850
    return;
 
2851
 
 
2852
  for (Field_translator *transl= field_translation;
 
2853
       transl < field_translation_end;
 
2854
       transl++)
 
2855
    transl->item->walk(&Item::cleanup_processor, 0, 0);
 
2856
}
 
2857
 
 
2858
 
 
2859
/*
 
2860
  Set insert_values buffer
 
2861
 
 
2862
  SYNOPSIS
 
2863
    set_insert_values()
 
2864
    mem_root   memory pool for allocating
 
2865
 
 
2866
  RETURN
 
2867
    false - OK
 
2868
    TRUE  - out of memory
 
2869
*/
 
2870
 
 
2871
bool TableList::set_insert_values(MEM_ROOT *mem_root)
 
2872
{
 
2873
  if (table)
 
2874
  {
 
2875
    if (!table->insert_values &&
 
2876
        !(table->insert_values= (unsigned char *)alloc_root(mem_root,
 
2877
                                                   table->s->rec_buff_length)))
 
2878
      return true;
 
2879
  }
 
2880
 
 
2881
  return false;
 
2882
}
 
2883
 
 
2884
 
 
2885
/*
 
2886
  Test if this is a leaf with respect to name resolution.
 
2887
 
 
2888
  SYNOPSIS
 
2889
    TableList::is_leaf_for_name_resolution()
 
2890
 
 
2891
  DESCRIPTION
 
2892
    A table reference is a leaf with respect to name resolution if
 
2893
    it is either a leaf node in a nested join tree (table, view,
 
2894
    schema table, subquery), or an inner node that represents a
 
2895
    NATURAL/USING join, or a nested join with materialized join
 
2896
    columns.
 
2897
 
 
2898
  RETURN
 
2899
    TRUE if a leaf, false otherwise.
 
2900
*/
 
2901
bool TableList::is_leaf_for_name_resolution()
 
2902
{
 
2903
  return (is_natural_join || is_join_columns_complete || !nested_join);
 
2904
}
 
2905
 
 
2906
 
 
2907
/*
 
2908
  Retrieve the first (left-most) leaf in a nested join tree with
 
2909
  respect to name resolution.
 
2910
 
 
2911
  SYNOPSIS
 
2912
    TableList::first_leaf_for_name_resolution()
 
2913
 
 
2914
  DESCRIPTION
 
2915
    Given that 'this' is a nested table reference, recursively walk
 
2916
    down the left-most children of 'this' until we reach a leaf
 
2917
    table reference with respect to name resolution.
 
2918
 
 
2919
  IMPLEMENTATION
 
2920
    The left-most child of a nested table reference is the last element
 
2921
    in the list of children because the children are inserted in
 
2922
    reverse order.
 
2923
 
 
2924
  RETURN
 
2925
    If 'this' is a nested table reference - the left-most child of
 
2926
      the tree rooted in 'this',
 
2927
    else return 'this'
 
2928
*/
 
2929
 
 
2930
TableList *TableList::first_leaf_for_name_resolution()
 
2931
{
 
2932
  TableList *cur_table_ref= NULL;
 
2933
  nested_join_st *cur_nested_join;
 
2934
 
 
2935
  if (is_leaf_for_name_resolution())
 
2936
    return this;
 
2937
  assert(nested_join);
 
2938
 
 
2939
  for (cur_nested_join= nested_join;
 
2940
       cur_nested_join;
 
2941
       cur_nested_join= cur_table_ref->nested_join)
 
2942
  {
 
2943
    List_iterator_fast<TableList> it(cur_nested_join->join_list);
 
2944
    cur_table_ref= it++;
 
2945
    /*
 
2946
      If the current nested join is a RIGHT JOIN, the operands in
 
2947
      'join_list' are in reverse order, thus the first operand is
 
2948
      already at the front of the list. Otherwise the first operand
 
2949
      is in the end of the list of join operands.
 
2950
    */
 
2951
    if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
 
2952
    {
 
2953
      TableList *next;
 
2954
      while ((next= it++))
 
2955
        cur_table_ref= next;
 
2956
    }
 
2957
    if (cur_table_ref->is_leaf_for_name_resolution())
 
2958
      break;
 
2959
  }
 
2960
  return cur_table_ref;
 
2961
}
 
2962
 
 
2963
 
 
2964
/*
 
2965
  Retrieve the last (right-most) leaf in a nested join tree with
 
2966
  respect to name resolution.
 
2967
 
 
2968
  SYNOPSIS
 
2969
    TableList::last_leaf_for_name_resolution()
 
2970
 
 
2971
  DESCRIPTION
 
2972
    Given that 'this' is a nested table reference, recursively walk
 
2973
    down the right-most children of 'this' until we reach a leaf
 
2974
    table reference with respect to name resolution.
 
2975
 
 
2976
  IMPLEMENTATION
 
2977
    The right-most child of a nested table reference is the first
 
2978
    element in the list of children because the children are inserted
 
2979
    in reverse order.
 
2980
 
 
2981
  RETURN
 
2982
    - If 'this' is a nested table reference - the right-most child of
 
2983
      the tree rooted in 'this',
 
2984
    - else - 'this'
 
2985
*/
 
2986
 
 
2987
TableList *TableList::last_leaf_for_name_resolution()
 
2988
{
 
2989
  TableList *cur_table_ref= this;
 
2990
  nested_join_st *cur_nested_join;
 
2991
 
 
2992
  if (is_leaf_for_name_resolution())
 
2993
    return this;
 
2994
  assert(nested_join);
 
2995
 
 
2996
  for (cur_nested_join= nested_join;
 
2997
       cur_nested_join;
 
2998
       cur_nested_join= cur_table_ref->nested_join)
 
2999
  {
 
3000
    cur_table_ref= cur_nested_join->join_list.head();
 
3001
    /*
 
3002
      If the current nested is a RIGHT JOIN, the operands in
 
3003
      'join_list' are in reverse order, thus the last operand is in the
 
3004
      end of the list.
 
3005
    */
 
3006
    if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
 
3007
    {
 
3008
      List_iterator_fast<TableList> it(cur_nested_join->join_list);
 
3009
      TableList *next;
 
3010
      cur_table_ref= it++;
 
3011
      while ((next= it++))
 
3012
        cur_table_ref= next;
 
3013
    }
 
3014
    if (cur_table_ref->is_leaf_for_name_resolution())
 
3015
      break;
 
3016
  }
 
3017
  return cur_table_ref;
379
3018
}
380
3019
 
381
3020
 
392
3031
    bitmap_clear_all(&table->def_read_set);
393
3032
    bitmap_clear_all(&table->def_write_set);
394
3033
  */
395
 
  def_read_set.reset();
396
 
  def_write_set.reset();
397
 
  column_bitmaps_set(def_read_set, def_write_set);
 
3034
  memset(def_read_set.bitmap, 0, s->column_bitmap_size*2);
 
3035
  column_bitmaps_set(&def_read_set, &def_write_set);
398
3036
}
399
3037
 
400
3038
 
401
3039
/*
402
 
  Tell Cursor we are going to call position() and rnd_pos() later.
403
 
 
 
3040
  Tell handler we are going to call position() and rnd_pos() later.
 
3041
  
404
3042
  NOTES:
405
3043
  This is needed for handlers that uses the primary key to find the
406
3044
  row. In this case we have to extend the read bitmap with the primary
410
3048
void Table::prepare_for_position()
411
3049
{
412
3050
 
413
 
  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
414
 
      getShare()->hasPrimaryKey())
 
3051
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
3052
      s->primary_key < MAX_KEY)
415
3053
  {
416
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
 
3054
    mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3055
    /* signal change */
 
3056
    file->column_bitmaps_signal();
417
3057
  }
418
3058
  return;
419
3059
}
431
3071
 
432
3072
void Table::mark_columns_used_by_index(uint32_t index)
433
3073
{
434
 
  boost::dynamic_bitset<> *bitmap= &tmp_set;
 
3074
  MY_BITMAP *bitmap= &tmp_set;
435
3075
 
436
 
  (void) cursor->extra(HA_EXTRA_KEYREAD);
437
 
  bitmap->reset();
438
 
  mark_columns_used_by_index_no_reset(index, *bitmap);
439
 
  column_bitmaps_set(*bitmap, *bitmap);
 
3076
  (void) file->extra(HA_EXTRA_KEYREAD);
 
3077
  bitmap_clear_all(bitmap);
 
3078
  mark_columns_used_by_index_no_reset(index, bitmap);
 
3079
  column_bitmaps_set(bitmap, bitmap);
440
3080
  return;
441
3081
}
442
3082
 
456
3096
{
457
3097
 
458
3098
  key_read= 0;
459
 
  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
 
3099
  (void) file->extra(HA_EXTRA_NO_KEYREAD);
460
3100
  default_column_bitmaps();
 
3101
  file->column_bitmaps_signal();
461
3102
  return;
462
3103
}
463
3104
 
466
3107
  mark columns used by key, but don't reset other fields
467
3108
*/
468
3109
 
469
 
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
470
 
{
471
 
    mark_columns_used_by_index_no_reset(index, *read_set);
472
 
}
473
 
 
474
 
 
475
3110
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
476
 
                                                boost::dynamic_bitset<>& bitmap)
 
3111
                                                   MY_BITMAP *bitmap)
477
3112
{
478
 
  KeyPartInfo *key_part= key_info[index].key_part;
479
 
  KeyPartInfo *key_part_end= (key_part + key_info[index].key_parts);
480
 
  for (; key_part != key_part_end; key_part++)
 
3113
  KEY_PART_INFO *key_part= key_info[index].key_part;
 
3114
  KEY_PART_INFO *key_part_end= (key_part +
 
3115
                                key_info[index].key_parts);
 
3116
  for (;key_part != key_part_end; key_part++)
481
3117
  {
482
 
    if (! bitmap.empty())
483
 
      bitmap.set(key_part->fieldnr-1);
 
3118
    bitmap_set_bit(bitmap, key_part->fieldnr-1);
 
3119
    if (key_part->field->vcol_info &&
 
3120
        key_part->field->vcol_info->expr_item)
 
3121
      key_part->field->vcol_info->
 
3122
               expr_item->walk(&Item::register_field_in_bitmap, 
 
3123
                               1, (unsigned char *) bitmap);
484
3124
  }
485
3125
}
486
3126
 
500
3140
    We must set bit in read set as update_auto_increment() is using the
501
3141
    store() to check overflow of auto_increment values
502
3142
  */
503
 
  setReadSet(found_next_number_field->position());
504
 
  setWriteSet(found_next_number_field->position());
505
 
  if (getShare()->next_number_keypart)
506
 
    mark_columns_used_by_index_no_reset(getShare()->next_number_index);
 
3143
  bitmap_set_bit(read_set, found_next_number_field->field_index);
 
3144
  bitmap_set_bit(write_set, found_next_number_field->field_index);
 
3145
  if (s->next_number_keypart)
 
3146
    mark_columns_used_by_index_no_reset(s->next_number_index, read_set);
 
3147
  file->column_bitmaps_signal();
507
3148
}
508
3149
 
509
3150
 
527
3168
 
528
3169
void Table::mark_columns_needed_for_delete()
529
3170
{
530
 
  /*
531
 
    If the Cursor has no cursor capabilites, or we have row-based
532
 
    replication active for the current statement, we have to read
533
 
    either the primary key, the hidden primary key or all columns to
534
 
    be able to do an delete
535
 
 
536
 
  */
537
 
  if (not getShare()->hasPrimaryKey())
538
 
  {
539
 
    /* fallback to use all columns in the table to identify row */
540
 
    use_all_columns();
541
 
    return;
542
 
  }
543
 
  else
544
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
545
 
 
546
 
  /* If we the engine wants all predicates we mark all keys */
547
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
3171
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
548
3172
  {
549
3173
    Field **reg_field;
550
3174
    for (reg_field= field ; *reg_field ; reg_field++)
551
3175
    {
552
3176
      if ((*reg_field)->flags & PART_KEY_FLAG)
553
 
        setReadSet((*reg_field)->position());
 
3177
        bitmap_set_bit(read_set, (*reg_field)->field_index);
 
3178
    }
 
3179
    file->column_bitmaps_signal();
 
3180
  }
 
3181
  if (file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE ||
 
3182
      (mysql_bin_log.is_open() && in_use && in_use->current_stmt_binlog_row_based))
 
3183
  {
 
3184
    /*
 
3185
      If the handler has no cursor capabilites, or we have row-based
 
3186
      replication active for the current statement, we have to read
 
3187
      either the primary key, the hidden primary key or all columns to
 
3188
      be able to do an delete
 
3189
    */
 
3190
    if (s->primary_key == MAX_KEY)
 
3191
      file->use_hidden_primary_key();
 
3192
    else
 
3193
    {
 
3194
      mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3195
      file->column_bitmaps_signal();
554
3196
    }
555
3197
  }
556
3198
}
568
3210
    if neeed, either the primary key column or all columns to be read.
569
3211
    (see mark_columns_needed_for_delete() for details)
570
3212
 
571
 
    If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
 
3213
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
572
3214
    mark all USED key columns as 'to-be-read'. This allows the engine to
573
3215
    loop over the given record to find all changed keys and doesn't have to
574
3216
    retrieve the row again.
576
3218
 
577
3219
void Table::mark_columns_needed_for_update()
578
3220
{
579
 
  /*
580
 
    If the Cursor has no cursor capabilites, or we have row-based
581
 
    logging active for the current statement, we have to read either
582
 
    the primary key, the hidden primary key or all columns to be
583
 
    able to do an update
584
 
  */
585
 
  if (not getShare()->hasPrimaryKey())
586
 
  {
587
 
    /* fallback to use all columns in the table to identify row */
588
 
    use_all_columns();
589
 
    return;
590
 
  }
591
 
  else
592
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
593
 
 
594
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
3221
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
595
3222
  {
596
3223
    /* Mark all used key columns for read */
597
3224
    Field **reg_field;
598
3225
    for (reg_field= field ; *reg_field ; reg_field++)
599
3226
    {
600
3227
      /* Merge keys is all keys that had a column refered to in the query */
601
 
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
602
 
        setReadSet((*reg_field)->position());
603
 
    }
604
 
  }
605
 
 
 
3228
      if (merge_keys.is_overlapping((*reg_field)->part_of_key))
 
3229
        bitmap_set_bit(read_set, (*reg_field)->field_index);
 
3230
    }
 
3231
    file->column_bitmaps_signal();
 
3232
  }
 
3233
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) ||
 
3234
      (mysql_bin_log.is_open() && in_use && in_use->current_stmt_binlog_row_based))
 
3235
  {
 
3236
    /*
 
3237
      If the handler has no cursor capabilites, or we have row-based
 
3238
      logging active for the current statement, we have to read either
 
3239
      the primary key, the hidden primary key or all columns to be
 
3240
      able to do an update
 
3241
    */
 
3242
    if (s->primary_key == MAX_KEY)
 
3243
      file->use_hidden_primary_key();
 
3244
    else
 
3245
    {
 
3246
      mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3247
      file->column_bitmaps_signal();
 
3248
    }
 
3249
  }
 
3250
  /* Mark all virtual columns as writable */
 
3251
  mark_virtual_columns();
 
3252
  return;
606
3253
}
607
3254
 
608
3255
 
609
3256
/*
610
 
  Mark columns the Cursor needs for doing an insert
 
3257
  Mark columns the handler needs for doing an insert
611
3258
 
612
3259
  For now, this is used to mark fields used by the trigger
613
3260
  as changed.
617
3264
{
618
3265
  if (found_next_number_field)
619
3266
    mark_auto_increment_column();
620
 
}
621
 
 
 
3267
  /* Mark all virtual columns as writable */
 
3268
  mark_virtual_columns();
 
3269
}
 
3270
 
 
3271
/* 
 
3272
  @brief Update the write and read table bitmap to allow
 
3273
         using procedure save_in_field for all virtual columns
 
3274
         in the table.
 
3275
 
 
3276
  @return       void
 
3277
 
 
3278
  @detail
 
3279
    Each virtual field is set in the write column map.
 
3280
    All fields that the virtual columns are based on are set in the
 
3281
    read bitmap.
 
3282
*/
 
3283
 
 
3284
void Table::mark_virtual_columns(void)
 
3285
{
 
3286
  Field **vfield_ptr, *tmp_vfield;
 
3287
  bool bitmap_updated= false;
 
3288
 
 
3289
  for (vfield_ptr= vfield; *vfield_ptr; vfield_ptr++)
 
3290
  {
 
3291
    tmp_vfield= *vfield_ptr;
 
3292
    assert(tmp_vfield->vcol_info && tmp_vfield->vcol_info->expr_item);
 
3293
    tmp_vfield->vcol_info->expr_item->walk(&Item::register_field_in_read_map, 
 
3294
                                           1, (unsigned char *) 0);
 
3295
    bitmap_set_bit(read_set, tmp_vfield->field_index);
 
3296
    bitmap_set_bit(write_set, tmp_vfield->field_index);
 
3297
    bitmap_updated= true;
 
3298
  }
 
3299
  if (bitmap_updated)
 
3300
    file->column_bitmaps_signal();
 
3301
}
 
3302
 
 
3303
 
 
3304
/*
 
3305
  Cleanup this table for re-execution.
 
3306
 
 
3307
  SYNOPSIS
 
3308
    TableList::reinit_before_use()
 
3309
*/
 
3310
 
 
3311
void TableList::reinit_before_use(THD *thd)
 
3312
{
 
3313
  /*
 
3314
    Reset old pointers to TABLEs: they are not valid since the tables
 
3315
    were closed in the end of previous prepare or execute call.
 
3316
  */
 
3317
  table= 0;
 
3318
  /* Reset is_schema_table_processed value(needed for I_S tables */
 
3319
  schema_table_state= NOT_PROCESSED;
 
3320
 
 
3321
  TableList *embedded; /* The table at the current level of nesting. */
 
3322
  TableList *parent_embedding= this; /* The parent nested table reference. */
 
3323
  do
 
3324
  {
 
3325
    embedded= parent_embedding;
 
3326
    if (embedded->prep_on_expr)
 
3327
      embedded->on_expr= embedded->prep_on_expr->copy_andor_structure(thd);
 
3328
    parent_embedding= embedded->embedding;
 
3329
  }
 
3330
  while (parent_embedding &&
 
3331
         parent_embedding->nested_join->join_list.head() == embedded);
 
3332
}
 
3333
 
 
3334
/*
 
3335
  Return subselect that contains the FROM list this table is taken from
 
3336
 
 
3337
  SYNOPSIS
 
3338
    TableList::containing_subselect()
 
3339
 
 
3340
  RETURN
 
3341
    Subselect item for the subquery that contains the FROM list
 
3342
    this table is taken from if there is any
 
3343
    0 - otherwise
 
3344
 
 
3345
*/
 
3346
 
 
3347
Item_subselect *TableList::containing_subselect()
 
3348
{    
 
3349
  return (select_lex ? select_lex->master_unit()->item : 0);
 
3350
}
 
3351
 
 
3352
/*
 
3353
  Compiles the tagged hints list and fills up the bitmasks.
 
3354
 
 
3355
  SYNOPSIS
 
3356
    process_index_hints()
 
3357
      table         the Table to operate on.
 
3358
 
 
3359
  DESCRIPTION
 
3360
    The parser collects the index hints for each table in a "tagged list" 
 
3361
    (TableList::index_hints). Using the information in this tagged list
 
3362
    this function sets the members Table::keys_in_use_for_query, 
 
3363
    Table::keys_in_use_for_group_by, Table::keys_in_use_for_order_by,
 
3364
    Table::force_index and Table::covering_keys.
 
3365
 
 
3366
    Current implementation of the runtime does not allow mixing FORCE INDEX
 
3367
    and USE INDEX, so this is checked here. Then the FORCE INDEX list 
 
3368
    (if non-empty) is appended to the USE INDEX list and a flag is set.
 
3369
 
 
3370
    Multiple hints of the same kind are processed so that each clause 
 
3371
    is applied to what is computed in the previous clause.
 
3372
    For example:
 
3373
        USE INDEX (i1) USE INDEX (i2)
 
3374
    is equivalent to
 
3375
        USE INDEX (i1,i2)
 
3376
    and means "consider only i1 and i2".
 
3377
        
 
3378
    Similarly
 
3379
        USE INDEX () USE INDEX (i1)
 
3380
    is equivalent to
 
3381
        USE INDEX (i1)
 
3382
    and means "consider only the index i1"
 
3383
 
 
3384
    It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is
 
3385
    not an error.
 
3386
        
 
3387
    Different kind of hints (USE/FORCE/IGNORE) are processed in the following
 
3388
    order:
 
3389
      1. All indexes in USE (or FORCE) INDEX are added to the mask.
 
3390
      2. All IGNORE INDEX
 
3391
 
 
3392
    e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all
 
3393
    as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
 
3394
 
 
3395
    As an optimization if there is a covering index, and we have 
 
3396
    IGNORE INDEX FOR GROUP/order_st, and this index is used for the JOIN part, 
 
3397
    then we have to ignore the IGNORE INDEX FROM GROUP/order_st.
 
3398
 
 
3399
  RETURN VALUE
 
3400
    false                no errors found
 
3401
    TRUE                 found and reported an error.
 
3402
*/
 
3403
bool TableList::process_index_hints(Table *tbl)
 
3404
{
 
3405
  /* initialize the result variables */
 
3406
  tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by= 
 
3407
    tbl->keys_in_use_for_order_by= tbl->s->keys_in_use;
 
3408
 
 
3409
  /* index hint list processing */
 
3410
  if (index_hints)
 
3411
  {
 
3412
    key_map index_join[INDEX_HINT_FORCE + 1];
 
3413
    key_map index_order[INDEX_HINT_FORCE + 1];
 
3414
    key_map index_group[INDEX_HINT_FORCE + 1];
 
3415
    Index_hint *hint;
 
3416
    int type;
 
3417
    bool have_empty_use_join= false, have_empty_use_order= false, 
 
3418
         have_empty_use_group= false;
 
3419
    List_iterator <Index_hint> iter(*index_hints);
 
3420
 
 
3421
    /* initialize temporary variables used to collect hints of each kind */
 
3422
    for (type= INDEX_HINT_IGNORE; type <= INDEX_HINT_FORCE; type++)
 
3423
    {
 
3424
      index_join[type].clear_all();
 
3425
      index_order[type].clear_all();
 
3426
      index_group[type].clear_all();
 
3427
    }
 
3428
 
 
3429
    /* iterate over the hints list */
 
3430
    while ((hint= iter++))
 
3431
    {
 
3432
      uint32_t pos;
 
3433
 
 
3434
      /* process empty USE INDEX () */
 
3435
      if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
 
3436
      {
 
3437
        if (hint->clause & INDEX_HINT_MASK_JOIN)
 
3438
        {
 
3439
          index_join[hint->type].clear_all();
 
3440
          have_empty_use_join= true;
 
3441
        }
 
3442
        if (hint->clause & INDEX_HINT_MASK_ORDER)
 
3443
        {
 
3444
          index_order[hint->type].clear_all();
 
3445
          have_empty_use_order= true;
 
3446
        }
 
3447
        if (hint->clause & INDEX_HINT_MASK_GROUP)
 
3448
        {
 
3449
          index_group[hint->type].clear_all();
 
3450
          have_empty_use_group= true;
 
3451
        }
 
3452
        continue;
 
3453
      }
 
3454
 
 
3455
      /* 
 
3456
        Check if an index with the given name exists and get his offset in 
 
3457
        the keys bitmask for the table 
 
3458
      */
 
3459
      if (tbl->s->keynames.type_names == 0 ||
 
3460
          (pos= find_type(&tbl->s->keynames, hint->key_name.str,
 
3461
                          hint->key_name.length, 1)) <= 0)
 
3462
      {
 
3463
        my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), hint->key_name.str, alias);
 
3464
        return 1;
 
3465
      }
 
3466
 
 
3467
      pos--;
 
3468
 
 
3469
      /* add to the appropriate clause mask */
 
3470
      if (hint->clause & INDEX_HINT_MASK_JOIN)
 
3471
        index_join[hint->type].set_bit (pos);
 
3472
      if (hint->clause & INDEX_HINT_MASK_ORDER)
 
3473
        index_order[hint->type].set_bit (pos);
 
3474
      if (hint->clause & INDEX_HINT_MASK_GROUP)
 
3475
        index_group[hint->type].set_bit (pos);
 
3476
    }
 
3477
 
 
3478
    /* cannot mix USE INDEX and FORCE INDEX */
 
3479
    if ((!index_join[INDEX_HINT_FORCE].is_clear_all() ||
 
3480
         !index_order[INDEX_HINT_FORCE].is_clear_all() ||
 
3481
         !index_group[INDEX_HINT_FORCE].is_clear_all()) &&
 
3482
        (!index_join[INDEX_HINT_USE].is_clear_all() ||  have_empty_use_join ||
 
3483
         !index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order ||
 
3484
         !index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group))
 
3485
    {
 
3486
      my_error(ER_WRONG_USAGE, MYF(0), index_hint_type_name[INDEX_HINT_USE],
 
3487
               index_hint_type_name[INDEX_HINT_FORCE]);
 
3488
      return 1;
 
3489
    }
 
3490
 
 
3491
    /* process FORCE INDEX as USE INDEX with a flag */
 
3492
    if (!index_join[INDEX_HINT_FORCE].is_clear_all() ||
 
3493
        !index_order[INDEX_HINT_FORCE].is_clear_all() ||
 
3494
        !index_group[INDEX_HINT_FORCE].is_clear_all())
 
3495
    {
 
3496
      tbl->force_index= true;
 
3497
      index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
 
3498
      index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
 
3499
      index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
 
3500
    }
 
3501
 
 
3502
    /* apply USE INDEX */
 
3503
    if (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join)
 
3504
      tbl->keys_in_use_for_query.intersect(index_join[INDEX_HINT_USE]);
 
3505
    if (!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order)
 
3506
      tbl->keys_in_use_for_order_by.intersect (index_order[INDEX_HINT_USE]);
 
3507
    if (!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group)
 
3508
      tbl->keys_in_use_for_group_by.intersect (index_group[INDEX_HINT_USE]);
 
3509
 
 
3510
    /* apply IGNORE INDEX */
 
3511
    tbl->keys_in_use_for_query.subtract (index_join[INDEX_HINT_IGNORE]);
 
3512
    tbl->keys_in_use_for_order_by.subtract (index_order[INDEX_HINT_IGNORE]);
 
3513
    tbl->keys_in_use_for_group_by.subtract (index_group[INDEX_HINT_IGNORE]);
 
3514
  }
 
3515
 
 
3516
  /* make sure covering_keys don't include indexes disabled with a hint */
 
3517
  tbl->covering_keys.intersect(tbl->keys_in_use_for_query);
 
3518
  return 0;
 
3519
}
622
3520
 
623
3521
 
624
3522
size_t Table::max_row_length(const unsigned char *data)
631
3529
  {
632
3530
    Field_blob* const blob= (Field_blob*) field[*ptr];
633
3531
    length+= blob->get_length((const unsigned char*)
634
 
                              (data + blob->offset(getInsertRecord()))) +
 
3532
                              (data + blob->offset(record[0]))) +
635
3533
      HA_KEY_BLOB_LENGTH;
636
3534
  }
637
3535
  return length;
638
3536
}
639
3537
 
640
 
void Table::setVariableWidth(void)
 
3538
/*
 
3539
  Check type of .frm if we are not going to parse it
 
3540
 
 
3541
  SYNOPSIS
 
3542
  mysql_frm_type()
 
3543
  path        path to file
 
3544
 
 
3545
  RETURN
 
3546
  false       error
 
3547
  true       table
 
3548
*/
 
3549
 
 
3550
bool mysql_frm_type(THD *thd __attribute__((unused)),
 
3551
                    char *path, enum legacy_db_type *dbt)
641
3552
{
642
 
  assert(in_use);
643
 
  if (in_use && in_use->getLex()->sql_command == SQLCOM_CREATE_TABLE)
644
 
  {
645
 
    getMutableShare()->setVariableWidth();
646
 
    return;
647
 
  }
648
 
 
649
 
  assert(0); // Programming error, you can't set this on a plain old Table.
 
3553
  File file;
 
3554
  unsigned char header[10];     /* This should be optimized */
 
3555
  int error;
 
3556
 
 
3557
  *dbt= DB_TYPE_UNKNOWN;
 
3558
 
 
3559
  if ((file= open(path, O_RDONLY)) < 0)
 
3560
    return false;
 
3561
  error= my_read(file, (unsigned char*) header, sizeof(header), MYF(MY_NABP));
 
3562
  my_close(file, MYF(MY_WME));
 
3563
 
 
3564
  if (error)
 
3565
    return false;
 
3566
 
 
3567
  /*  
 
3568
    This is just a check for DB_TYPE. We'll return default unknown type
 
3569
    if the following test is true (arg #3). This should not have effect
 
3570
    on return value from this function (default FRMTYPE_TABLE)
 
3571
   */  
 
3572
  if (header[0] != (unsigned char) 254 || header[1] != 1 ||
 
3573
      (header[2] != FRM_VER && header[2] != FRM_VER+1 &&
 
3574
       (header[2] < FRM_VER+3 || header[2] > FRM_VER+4)))
 
3575
    return true;
 
3576
 
 
3577
  *dbt= (enum legacy_db_type) (uint) *(header + 3);
 
3578
  return true;                   // Is probably a .frm table
650
3579
}
651
3580
 
652
3581
/****************************************************************************
653
3582
 Functions for creating temporary tables.
654
3583
****************************************************************************/
 
3584
 
 
3585
 
 
3586
/* Prototypes */
 
3587
void free_tmp_table(THD *thd, Table *entry);
 
3588
 
655
3589
/**
656
3590
  Create field for temporary table from given field.
657
3591
 
658
 
  @param session               Thread Cursor
 
3592
  @param thd           Thread handler
659
3593
  @param org_field    field from which new field will be created
660
3594
  @param name         New field name
661
3595
  @param table         Temporary table
674
3608
    new_created field
675
3609
*/
676
3610
 
677
 
Field *create_tmp_field_from_field(Session *session, Field *org_field,
 
3611
Field *create_tmp_field_from_field(THD *thd, Field *org_field,
678
3612
                                   const char *name, Table *table,
679
3613
                                   Item_field *item, uint32_t convert_blob_length)
680
3614
{
681
3615
  Field *new_field;
682
3616
 
683
 
  /*
684
 
    Make sure that the blob fits into a Field_varstring which has
685
 
    2-byte lenght.
 
3617
  /* 
 
3618
    Make sure that the blob fits into a Field_varstring which has 
 
3619
    2-byte lenght. 
686
3620
  */
687
3621
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
688
3622
      (org_field->flags & BLOB_FLAG))
689
 
  {
690
 
    table->setVariableWidth();
691
3623
    new_field= new Field_varstring(convert_blob_length,
692
3624
                                   org_field->maybe_null(),
693
 
                                   org_field->field_name,
 
3625
                                   org_field->field_name, table->s,
694
3626
                                   org_field->charset());
695
 
  }
696
3627
  else
697
 
  {
698
 
    new_field= org_field->new_field(session->mem_root, table,
699
 
                                    table == org_field->getTable());
700
 
  }
 
3628
    new_field= org_field->new_field(thd->mem_root, table,
 
3629
                                    table == org_field->table);
701
3630
  if (new_field)
702
3631
  {
703
3632
    new_field->init(table);
710
3639
    if (org_field->maybe_null() || (item && item->maybe_null))
711
3640
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
712
3641
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
713
 
      table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
 
3642
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
714
3643
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
715
3644
      ((Field_double *) new_field)->not_fixed= true;
716
3645
  }
717
3646
  return new_field;
718
3647
}
719
3648
 
 
3649
/**
 
3650
  Create field for temporary table using type of given item.
 
3651
 
 
3652
  @param thd                   Thread handler
 
3653
  @param item                  Item to create a field for
 
3654
  @param table                 Temporary table
 
3655
  @param copy_func             If set and item is a function, store copy of
 
3656
                               item in this array
 
3657
  @param modify_item           1 if item->result_field should point to new
 
3658
                               item. This is relevent for how fill_record()
 
3659
                               is going to work:
 
3660
                               If modify_item is 1 then fill_record() will
 
3661
                               update the record in the original table.
 
3662
                               If modify_item is 0 then fill_record() will
 
3663
                               update the temporary table
 
3664
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
 
3665
                               field instead of blob.
 
3666
 
 
3667
  @retval
 
3668
    0  on error
 
3669
  @retval
 
3670
    new_created field
 
3671
*/
 
3672
 
 
3673
static Field *create_tmp_field_from_item(THD *thd __attribute__((unused)),
 
3674
                                         Item *item, Table *table,
 
3675
                                         Item ***copy_func, bool modify_item,
 
3676
                                         uint32_t convert_blob_length)
 
3677
{
 
3678
  bool maybe_null= item->maybe_null;
 
3679
  Field *new_field;
 
3680
 
 
3681
  switch (item->result_type()) {
 
3682
  case REAL_RESULT:
 
3683
    new_field= new Field_double(item->max_length, maybe_null,
 
3684
                                item->name, item->decimals, true);
 
3685
    break;
 
3686
  case INT_RESULT:
 
3687
    /* 
 
3688
      Select an integer type with the minimal fit precision.
 
3689
      MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
 
3690
      Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into 
 
3691
      Field_long : make them Field_int64_t.  
 
3692
    */
 
3693
    if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
 
3694
      new_field=new Field_int64_t(item->max_length, maybe_null,
 
3695
                                   item->name, item->unsigned_flag);
 
3696
    else
 
3697
      new_field=new Field_long(item->max_length, maybe_null,
 
3698
                               item->name, item->unsigned_flag);
 
3699
    break;
 
3700
  case STRING_RESULT:
 
3701
    assert(item->collation.collation);
 
3702
  
 
3703
    enum enum_field_types type;
 
3704
    /*
 
3705
      DATE/TIME fields have STRING_RESULT result type. 
 
3706
      To preserve type they needed to be handled separately.
 
3707
    */
 
3708
    if ((type= item->field_type()) == DRIZZLE_TYPE_DATETIME ||
 
3709
        type == DRIZZLE_TYPE_TIME || type == DRIZZLE_TYPE_NEWDATE ||
 
3710
        type == DRIZZLE_TYPE_TIMESTAMP)
 
3711
      new_field= item->tmp_table_field_from_field_type(table, 1);
 
3712
    /* 
 
3713
      Make sure that the blob fits into a Field_varstring which has 
 
3714
      2-byte lenght. 
 
3715
    */
 
3716
    else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
 
3717
             convert_blob_length <= Field_varstring::MAX_SIZE && 
 
3718
             convert_blob_length)
 
3719
      new_field= new Field_varstring(convert_blob_length, maybe_null,
 
3720
                                     item->name, table->s,
 
3721
                                     item->collation.collation);
 
3722
    else
 
3723
      new_field= item->make_string_field(table);
 
3724
    new_field->set_derivation(item->collation.derivation);
 
3725
    break;
 
3726
  case DECIMAL_RESULT:
 
3727
  {
 
3728
    uint8_t dec= item->decimals;
 
3729
    uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
 
3730
    uint32_t len= item->max_length;
 
3731
 
 
3732
    /*
 
3733
      Trying to put too many digits overall in a DECIMAL(prec,dec)
 
3734
      will always throw a warning. We must limit dec to
 
3735
      DECIMAL_MAX_SCALE however to prevent an assert() later.
 
3736
    */
 
3737
 
 
3738
    if (dec > 0)
 
3739
    {
 
3740
      signed int overflow;
 
3741
 
 
3742
      dec= cmin(dec, (uint8_t)DECIMAL_MAX_SCALE);
 
3743
 
 
3744
      /*
 
3745
        If the value still overflows the field with the corrected dec,
 
3746
        we'll throw out decimals rather than integers. This is still
 
3747
        bad and of course throws a truncation warning.
 
3748
        +1: for decimal point
 
3749
      */
 
3750
 
 
3751
      overflow= my_decimal_precision_to_length(intg + dec, dec,
 
3752
                                               item->unsigned_flag) - len;
 
3753
 
 
3754
      if (overflow > 0)
 
3755
        dec= cmax(0, dec - overflow);            // too long, discard fract
 
3756
      else
 
3757
        len -= item->decimals - dec;            // corrected value fits
 
3758
    }
 
3759
 
 
3760
    new_field= new Field_new_decimal(len, maybe_null, item->name,
 
3761
                                     dec, item->unsigned_flag);
 
3762
    break;
 
3763
  }
 
3764
  case ROW_RESULT:
 
3765
  default:
 
3766
    // This case should never be choosen
 
3767
    assert(0);
 
3768
    new_field= 0;
 
3769
    break;
 
3770
  }
 
3771
  if (new_field)
 
3772
    new_field->init(table);
 
3773
    
 
3774
  if (copy_func && item->is_result_field())
 
3775
    *((*copy_func)++) = item;                   // Save for copy_funcs
 
3776
  if (modify_item)
 
3777
    item->set_result_field(new_field);
 
3778
  if (item->type() == Item::NULL_ITEM)
 
3779
    new_field->is_created_from_null_item= true;
 
3780
  return new_field;
 
3781
}
 
3782
 
 
3783
 
 
3784
/**
 
3785
  Create field for information schema table.
 
3786
 
 
3787
  @param thd            Thread handler
 
3788
  @param table          Temporary table
 
3789
  @param item           Item to create a field for
 
3790
 
 
3791
  @retval
 
3792
    0                   on error
 
3793
  @retval
 
3794
    new_created field
 
3795
*/
 
3796
 
 
3797
Field *create_tmp_field_for_schema(THD *thd __attribute__((unused)),
 
3798
                                   Item *item, Table *table)
 
3799
{
 
3800
  if (item->field_type() == DRIZZLE_TYPE_VARCHAR)
 
3801
  {
 
3802
    Field *field;
 
3803
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
 
3804
      field= new Field_blob(item->max_length, item->maybe_null,
 
3805
                            item->name, item->collation.collation);
 
3806
    else
 
3807
      field= new Field_varstring(item->max_length, item->maybe_null,
 
3808
                                 item->name,
 
3809
                                 table->s, item->collation.collation);
 
3810
    if (field)
 
3811
      field->init(table);
 
3812
    return field;
 
3813
  }
 
3814
  return item->tmp_table_field_from_field_type(table, 0);
 
3815
}
 
3816
 
 
3817
 
 
3818
/**
 
3819
  Create field for temporary table.
 
3820
 
 
3821
  @param thd            Thread handler
 
3822
  @param table          Temporary table
 
3823
  @param item           Item to create a field for
 
3824
  @param type           Type of item (normally item->type)
 
3825
  @param copy_func      If set and item is a function, store copy of item
 
3826
                       in this array
 
3827
  @param from_field    if field will be created using other field as example,
 
3828
                       pointer example field will be written here
 
3829
  @param default_field  If field has a default value field, store it here
 
3830
  @param group          1 if we are going to do a relative group by on result
 
3831
  @param modify_item    1 if item->result_field should point to new item.
 
3832
                       This is relevent for how fill_record() is going to
 
3833
                       work:
 
3834
                       If modify_item is 1 then fill_record() will update
 
3835
                       the record in the original table.
 
3836
                       If modify_item is 0 then fill_record() will update
 
3837
                       the temporary table
 
3838
  @param convert_blob_length If >0 create a varstring(convert_blob_length)
 
3839
                             field instead of blob.
 
3840
 
 
3841
  @retval
 
3842
    0                   on error
 
3843
  @retval
 
3844
    new_created field
 
3845
*/
 
3846
 
 
3847
Field *create_tmp_field(THD *thd, Table *table,Item *item, Item::Type type,
 
3848
                        Item ***copy_func, Field **from_field,
 
3849
                        Field **default_field,
 
3850
                        bool group, bool modify_item,
 
3851
                        bool table_cant_handle_bit_fields __attribute__((unused)),
 
3852
                        bool make_copy_field,
 
3853
                        uint32_t convert_blob_length)
 
3854
{
 
3855
  Field *result;
 
3856
  Item::Type orig_type= type;
 
3857
  Item *orig_item= 0;
 
3858
 
 
3859
  if (type != Item::FIELD_ITEM &&
 
3860
      item->real_item()->type() == Item::FIELD_ITEM)
 
3861
  {
 
3862
    orig_item= item;
 
3863
    item= item->real_item();
 
3864
    type= Item::FIELD_ITEM;
 
3865
  }
 
3866
 
 
3867
  switch (type) {
 
3868
  case Item::SUM_FUNC_ITEM:
 
3869
  {
 
3870
    Item_sum *item_sum=(Item_sum*) item;
 
3871
    result= item_sum->create_tmp_field(group, table, convert_blob_length);
 
3872
    if (!result)
 
3873
      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
 
3874
    return result;
 
3875
  }
 
3876
  case Item::FIELD_ITEM:
 
3877
  case Item::DEFAULT_VALUE_ITEM:
 
3878
  {
 
3879
    Item_field *field= (Item_field*) item;
 
3880
    bool orig_modify= modify_item;
 
3881
    if (orig_type == Item::REF_ITEM)
 
3882
      modify_item= 0;
 
3883
    /*
 
3884
      If item have to be able to store NULLs but underlaid field can't do it,
 
3885
      create_tmp_field_from_field() can't be used for tmp field creation.
 
3886
    */
 
3887
    if (field->maybe_null && !field->field->maybe_null())
 
3888
    {
 
3889
      result= create_tmp_field_from_item(thd, item, table, NULL,
 
3890
                                         modify_item, convert_blob_length);
 
3891
      *from_field= field->field;
 
3892
      if (result && modify_item)
 
3893
        field->result_field= result;
 
3894
    } 
 
3895
    else
 
3896
      result= create_tmp_field_from_field(thd, (*from_field= field->field),
 
3897
                                          orig_item ? orig_item->name :
 
3898
                                          item->name,
 
3899
                                          table,
 
3900
                                          modify_item ? field :
 
3901
                                          NULL,
 
3902
                                          convert_blob_length);
 
3903
    if (orig_type == Item::REF_ITEM && orig_modify)
 
3904
      ((Item_ref*)orig_item)->set_result_field(result);
 
3905
    if (field->field->eq_def(result))
 
3906
      *default_field= field->field;
 
3907
    return result;
 
3908
  }
 
3909
  /* Fall through */
 
3910
  case Item::FUNC_ITEM:
 
3911
    /* Fall through */
 
3912
  case Item::COND_ITEM:
 
3913
  case Item::FIELD_AVG_ITEM:
 
3914
  case Item::FIELD_STD_ITEM:
 
3915
  case Item::SUBSELECT_ITEM:
 
3916
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
 
3917
  case Item::PROC_ITEM:
 
3918
  case Item::INT_ITEM:
 
3919
  case Item::REAL_ITEM:
 
3920
  case Item::DECIMAL_ITEM:
 
3921
  case Item::STRING_ITEM:
 
3922
  case Item::REF_ITEM:
 
3923
  case Item::NULL_ITEM:
 
3924
  case Item::VARBIN_ITEM:
 
3925
    if (make_copy_field)
 
3926
    {
 
3927
      assert(((Item_result_field*)item)->result_field);
 
3928
      *from_field= ((Item_result_field*)item)->result_field;
 
3929
    }
 
3930
    return create_tmp_field_from_item(thd, item, table,
 
3931
                                      (make_copy_field ? 0 : copy_func),
 
3932
                                       modify_item, convert_blob_length);
 
3933
  case Item::TYPE_HOLDER:  
 
3934
    result= ((Item_type_holder *)item)->make_field_by_type(table);
 
3935
    result->set_derivation(item->collation.derivation);
 
3936
    return result;
 
3937
  default:                                      // Dosen't have to be stored
 
3938
    return 0;
 
3939
  }
 
3940
}
720
3941
 
721
3942
/**
722
3943
  Create a temp table according to a field list.
729
3950
  corresponding Item_field items, pointing at the fields in the
730
3951
  temporary table, unless this was prohibited by true
731
3952
  value of argument save_sum_fields. The Item_field objects
732
 
  are created in Session memory root.
 
3953
  are created in THD memory root.
733
3954
 
734
 
  @param session                  thread handle
 
3955
  @param thd                  thread handle
735
3956
  @param param                a description used as input to create the table
736
3957
  @param fields               list of items that will be used to define
737
3958
                              column types of the table (also see NOTES)
749
3970
#define RATIO_TO_PACK_ROWS             2
750
3971
 
751
3972
Table *
752
 
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
753
 
                 Order *group, bool distinct, bool save_sum_fields,
 
3973
create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
 
3974
                 order_st *group, bool distinct, bool save_sum_fields,
754
3975
                 uint64_t select_options, ha_rows rows_limit,
755
 
                 const char *table_alias)
 
3976
                 char *table_alias)
756
3977
{
757
 
  memory::Root *mem_root_save;
 
3978
  MEM_ROOT *mem_root_save, own_root;
 
3979
  Table *table;
 
3980
  TABLE_SHARE *share;
758
3981
  uint  i,field_count,null_count,null_pack_length;
759
3982
  uint32_t  copy_func_count= param->func_count;
760
3983
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
761
3984
  uint32_t  blob_count,group_null_items, string_count;
 
3985
  uint32_t  temp_pool_slot=MY_BIT_NONE;
762
3986
  uint32_t fieldnr= 0;
763
3987
  ulong reclength, string_total_length;
764
 
  bool  using_unique_constraint= false;
765
 
  bool  use_packed_rows= true;
 
3988
  bool  using_unique_constraint= 0;
 
3989
  bool  use_packed_rows= 0;
766
3990
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
767
 
  unsigned char *pos, *group_buff;
 
3991
  char  *tmpname,path[FN_REFLEN];
 
3992
  unsigned char *pos, *group_buff, *bitmaps;
768
3993
  unsigned char *null_flags;
769
3994
  Field **reg_field, **from_field, **default_field;
770
 
  CopyField *copy= 0;
771
 
  KeyInfo *keyinfo;
772
 
  KeyPartInfo *key_part_info;
 
3995
  uint32_t *blob_field;
 
3996
  Copy_field *copy=0;
 
3997
  KEY *keyinfo;
 
3998
  KEY_PART_INFO *key_part_info;
773
3999
  Item **copy_func;
774
4000
  MI_COLUMNDEF *recinfo;
775
4001
  uint32_t total_uneven_bit_length= 0;
776
4002
  bool force_copy_fields= param->force_copy_fields;
777
 
  uint64_t max_rows= 0;
778
 
 
779
 
  session->status_var.created_tmp_tables++;
 
4003
 
 
4004
  status_var_increment(thd->status_var.created_tmp_tables);
 
4005
 
 
4006
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
 
4007
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
 
4008
 
 
4009
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
 
4010
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
 
4011
            current_pid, temp_pool_slot);
 
4012
  else
 
4013
  {
 
4014
    /* if we run out of slots or we are not using tempool */
 
4015
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
 
4016
            thd->thread_id, thd->tmp_table++);
 
4017
  }
 
4018
 
 
4019
  /*
 
4020
    No need to change table name to lower case as we are only creating
 
4021
    MyISAM or HEAP tables here
 
4022
  */
 
4023
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
4024
 
780
4025
 
781
4026
  if (group)
782
4027
  {
783
 
    if (! param->quick_group)
784
 
    {
785
 
      group= 0;                                 // Can't use group key
786
 
    }
787
 
    else for (Order *tmp=group ; tmp ; tmp=tmp->next)
 
4028
    if (!param->quick_group)
 
4029
      group=0;                                  // Can't use group key
 
4030
    else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
788
4031
    {
789
4032
      /*
790
4033
        marker == 4 means two things:
794
4037
      */
795
4038
      (*tmp->item)->marker= 4;
796
4039
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
797
 
        using_unique_constraint= true;
 
4040
        using_unique_constraint=1;
798
4041
    }
799
4042
    if (param->group_length >= MAX_BLOB_WIDTH)
800
 
      using_unique_constraint= true;
 
4043
      using_unique_constraint=1;
801
4044
    if (group)
802
 
      distinct= 0;                              // Can't use distinct
 
4045
      distinct=0;                               // Can't use distinct
803
4046
  }
804
4047
 
805
4048
  field_count=param->field_count+param->func_count+param->sum_func_count;
809
4052
    When loose index scan is employed as access method, it already
810
4053
    computes all groups and the result of all aggregate functions. We
811
4054
    make space for the items of the aggregate function in the list of
812
 
    functions Tmp_Table_Param::items_to_copy, so that the values of
 
4055
    functions TMP_TABLE_PARAM::items_to_copy, so that the values of
813
4056
    these items are stored in the temporary table.
814
4057
  */
815
4058
  if (param->precomputed_group_by)
816
 
  {
817
4059
    copy_func_count+= param->sum_func_count;
818
 
  }
819
 
 
820
 
  table::Singular *table;
821
 
  table= session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
822
 
 
823
 
  if (not table->getMemRoot()->multi_alloc_root(0,
824
 
                                                &default_field, sizeof(Field*) * (field_count),
825
 
                                                &from_field, sizeof(Field*)*field_count,
826
 
                                                &copy_func, sizeof(*copy_func)*(copy_func_count+1),
827
 
                                                &param->keyinfo, sizeof(*param->keyinfo),
828
 
                                                &key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
829
 
                                                &param->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
830
 
                                                &group_buff, (group && ! using_unique_constraint ?
831
 
                                                              param->group_length : 0),
832
 
                                                NULL))
833
 
  {
834
 
    return NULL;
835
 
  }
836
 
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
837
 
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
838
 
  {
839
 
    return NULL;
 
4060
  
 
4061
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
4062
 
 
4063
  if (!multi_alloc_root(&own_root,
 
4064
                        &table, sizeof(*table),
 
4065
                        &share, sizeof(*share),
 
4066
                        &reg_field, sizeof(Field*) * (field_count+1),
 
4067
                        &default_field, sizeof(Field*) * (field_count),
 
4068
                        &blob_field, sizeof(uint)*(field_count+1),
 
4069
                        &from_field, sizeof(Field*)*field_count,
 
4070
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
 
4071
                        &param->keyinfo, sizeof(*param->keyinfo),
 
4072
                        &key_part_info,
 
4073
                        sizeof(*key_part_info)*(param->group_parts+1),
 
4074
                        &param->start_recinfo,
 
4075
                        sizeof(*param->recinfo)*(field_count*2+4),
 
4076
                        &tmpname, (uint) strlen(path)+1,
 
4077
                        &group_buff, (group && ! using_unique_constraint ?
 
4078
                                      param->group_length : 0),
 
4079
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
4080
                        NULL))
 
4081
  {
 
4082
    if (temp_pool_slot != MY_BIT_NONE)
 
4083
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
4084
    return(NULL);                               /* purecov: inspected */
 
4085
  }
 
4086
  /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */
 
4087
  if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count]))
 
4088
  {
 
4089
    if (temp_pool_slot != MY_BIT_NONE)
 
4090
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
4091
    free_root(&own_root, MYF(0));               /* purecov: inspected */
 
4092
    return(NULL);                               /* purecov: inspected */
840
4093
  }
841
4094
  param->items_to_copy= copy_func;
 
4095
  my_stpcpy(tmpname,path);
842
4096
  /* make table according to fields */
843
4097
 
 
4098
  memset(table, 0, sizeof(*table));
 
4099
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
844
4100
  memset(default_field, 0, sizeof(Field*) * (field_count));
845
4101
  memset(from_field, 0, sizeof(Field*)*field_count);
846
4102
 
847
 
  mem_root_save= session->mem_root;
848
 
  session->mem_root= table->getMemRoot();
 
4103
  table->mem_root= own_root;
 
4104
  mem_root_save= thd->mem_root;
 
4105
  thd->mem_root= &table->mem_root;
849
4106
 
850
 
  table->getMutableShare()->setFields(field_count+1);
851
 
  table->setFields(table->getMutableShare()->getFields(true));
852
 
  reg_field= table->getMutableShare()->getFields(true);
853
 
  table->setAlias(table_alias);
 
4107
  table->field=reg_field;
 
4108
  table->alias= table_alias;
854
4109
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
855
4110
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
856
4111
  table->map=1;
 
4112
  table->temp_pool_slot = temp_pool_slot;
857
4113
  table->copy_blobs= 1;
858
 
  assert(session);
859
 
  table->in_use= session;
860
 
  table->quick_keys.reset();
861
 
  table->covering_keys.reset();
862
 
  table->keys_in_use_for_query.reset();
 
4114
  table->in_use= thd;
 
4115
  table->quick_keys.init();
 
4116
  table->covering_keys.init();
 
4117
  table->keys_in_use_for_query.init();
863
4118
 
864
 
  table->getMutableShare()->blob_field.resize(field_count+1);
865
 
  uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
866
 
  table->getMutableShare()->db_low_byte_first=1;                // True for HEAP and MyISAM
867
 
  table->getMutableShare()->table_charset= param->table_charset;
868
 
  table->getMutableShare()->keys_for_keyread.reset();
869
 
  table->getMutableShare()->keys_in_use.reset();
 
4119
  table->setShare(share);
 
4120
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
 
4121
  share->blob_field= blob_field;
 
4122
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
4123
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
4124
  share->table_charset= param->table_charset;
 
4125
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
4126
  share->keys_for_keyread.init();
 
4127
  share->keys_in_use.init();
870
4128
 
871
4129
  /* Calculate which type of fields we will store in the temporary table */
872
4130
 
873
4131
  reclength= string_total_length= 0;
874
4132
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
875
 
  param->using_indirect_summary_function= 0;
 
4133
  param->using_indirect_summary_function=0;
876
4134
 
877
 
  List<Item>::iterator li(fields.begin());
 
4135
  List_iterator_fast<Item> li(fields);
878
4136
  Item *item;
879
4137
  Field **tmp_from_field=from_field;
880
4138
  while ((item=li++))
903
4161
    }
904
4162
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
905
4163
    {                                           /* Can't calc group yet */
906
 
      ((Item_sum*) item)->result_field= 0;
907
 
      for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
 
4164
      ((Item_sum*) item)->result_field=0;
 
4165
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
908
4166
      {
909
4167
        Item **argp= ((Item_sum*) item)->args + i;
910
4168
        Item *arg= *argp;
911
4169
        if (!arg->const_item())
912
4170
        {
913
4171
          Field *new_field=
914
 
            create_tmp_field(session, table, arg, arg->type(), &copy_func,
 
4172
            create_tmp_field(thd, table, arg, arg->type(), &copy_func,
915
4173
                             tmp_from_field, &default_field[fieldnr],
916
4174
                             group != 0,not_all_columns,
917
 
                             false,
 
4175
                             distinct, 0,
918
4176
                             param->convert_blob_length);
919
4177
          if (!new_field)
920
4178
            goto err;                                   // Should be OOM
931
4189
            string_count++;
932
4190
            string_total_length+= new_field->pack_length();
933
4191
          }
934
 
          session->mem_root= mem_root_save;
935
 
          session->change_item_tree(argp, new Item_field(new_field));
936
 
          session->mem_root= table->getMemRoot();
 
4192
          thd->mem_root= mem_root_save;
 
4193
          thd->change_item_tree(argp, new Item_field(new_field));
 
4194
          thd->mem_root= &table->mem_root;
937
4195
          if (!(new_field->flags & NOT_NULL_FLAG))
938
4196
          {
939
4197
            null_count++;
943
4201
            */
944
4202
            (*argp)->maybe_null=1;
945
4203
          }
946
 
          new_field->setPosition(fieldnr++);
 
4204
          new_field->field_index= fieldnr++;
947
4205
        }
948
4206
      }
949
4207
    }
959
4217
        We here distinguish between UNION and multi-table-updates by the fact
960
4218
        that in the later case group is set to the row pointer.
961
4219
      */
962
 
      Field *new_field=
963
 
        create_tmp_field(session, table, item, type, &copy_func,
 
4220
      Field *new_field= (param->schema_table) ?
 
4221
        create_tmp_field_for_schema(thd, item, table) :
 
4222
        create_tmp_field(thd, table, item, type, &copy_func,
964
4223
                         tmp_from_field, &default_field[fieldnr],
965
4224
                         group != 0,
966
4225
                         !force_copy_fields &&
967
 
                           (not_all_columns || group != 0),
 
4226
                           (not_all_columns || group !=0),
 
4227
                         /*
 
4228
                           If item->marker == 4 then we force create_tmp_field
 
4229
                           to create a 64-bit longs for BIT fields because HEAP
 
4230
                           tables can't index BIT fields directly. We do the same
 
4231
                           for distinct, as we want the distinct index to be
 
4232
                           usable in this case too.
 
4233
                         */
 
4234
                         item->marker == 4 || param->bit_fields_as_long,
968
4235
                         force_copy_fields,
969
4236
                         param->convert_blob_length);
970
4237
 
971
4238
      if (!new_field)
972
4239
      {
973
 
        if (session->is_fatal_error)
 
4240
        if (thd->is_fatal_error)
974
4241
          goto err;                             // Got OOM
975
4242
        continue;                               // Some kindf of const item
976
4243
      }
990
4257
        group_null_items++;
991
4258
        new_field->flags|= GROUP_FLAG;
992
4259
      }
993
 
      new_field->setPosition(fieldnr++);
 
4260
      new_field->field_index= fieldnr++;
994
4261
      *(reg_field++)= new_field;
995
4262
    }
996
4263
    if (!--hidden_field_count)
1008
4275
      null_count= 0;
1009
4276
    }
1010
4277
  }
1011
 
  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
1012
 
  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
 
4278
  assert(fieldnr == (uint) (reg_field - table->field));
 
4279
  assert(field_count >= (uint) (reg_field - table->field));
1013
4280
  field_count= fieldnr;
1014
4281
  *reg_field= 0;
1015
4282
  *blob_field= 0;                               // End marker
1016
 
  table->getMutableShare()->setFieldSize(field_count);
 
4283
  share->fields= field_count;
1017
4284
 
1018
4285
  /* If result table is small; use a heap */
1019
4286
  /* future: storage engine selection can be made dynamic? */
1020
 
  if (blob_count || using_unique_constraint || 
1021
 
      (session->getLex()->select_lex.options & SELECT_BIG_RESULT) ||
1022
 
      (session->getLex()->current_select->olap == ROLLUP_TYPE) ||
1023
 
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
 
4287
  if (blob_count || using_unique_constraint ||
 
4288
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
4289
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
1024
4290
  {
1025
 
    table->getMutableShare()->storage_engine= myisam_engine;
1026
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
 
4291
    share->db_plugin= ha_lock_engine(0, myisam_hton);
 
4292
    table->file= get_new_handler(share, &table->mem_root,
 
4293
                                 share->db_type());
1027
4294
    if (group &&
1028
 
        (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
1029
 
         param->group_length > table->cursor->getEngine()->max_key_length()))
1030
 
    {
1031
 
      using_unique_constraint= true;
1032
 
    }
 
4295
        (param->group_parts > table->file->max_key_parts() ||
 
4296
         param->group_length > table->file->max_key_length()))
 
4297
      using_unique_constraint=1;
1033
4298
  }
1034
4299
  else
1035
4300
  {
1036
 
    table->getMutableShare()->storage_engine= heap_engine;
1037
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
 
4301
    share->db_plugin= ha_lock_engine(0, heap_hton);
 
4302
    table->file= get_new_handler(share, &table->mem_root,
 
4303
                                 share->db_type());
1038
4304
  }
1039
 
  if (! table->cursor)
 
4305
  if (!table->file)
1040
4306
    goto err;
1041
4307
 
1042
4308
 
1043
 
  if (! using_unique_constraint)
 
4309
  if (!using_unique_constraint)
1044
4310
    reclength+= group_null_items;       // null flag is stored separately
1045
4311
 
1046
 
  table->getMutableShare()->blob_fields= blob_count;
 
4312
  share->blob_fields= blob_count;
1047
4313
  if (blob_count == 0)
1048
4314
  {
1049
4315
    /* We need to ensure that first byte is not 0 for the delete link */
1062
4328
  if (blob_count || ((string_total_length >= STRING_TOTAL_LENGTH_TO_PACK_ROWS) && (reclength / string_total_length <= RATIO_TO_PACK_ROWS || (string_total_length / string_count) >= AVG_STRING_LENGTH_TO_PACK_ROWS)))
1063
4329
    use_packed_rows= 1;
1064
4330
 
1065
 
  table->getMutableShare()->setRecordLength(reclength);
 
4331
  share->reclength= reclength;
1066
4332
  {
1067
4333
    uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
1068
 
    table->getMutableShare()->rec_buff_length= alloc_length;
1069
 
    if (!(table->record[0]= (unsigned char*) table->alloc_root(alloc_length*2)))
1070
 
    {
 
4334
    share->rec_buff_length= alloc_length;
 
4335
    if (!(table->record[0]= (unsigned char*)
 
4336
                            alloc_root(&table->mem_root, alloc_length*3)))
1071
4337
      goto err;
1072
 
    }
1073
 
    table->record[1]= table->getInsertRecord()+alloc_length;
1074
 
    table->getMutableShare()->resizeDefaultValues(alloc_length);
 
4338
    table->record[1]= table->record[0]+alloc_length;
 
4339
    share->default_values= table->record[1]+alloc_length;
1075
4340
  }
1076
 
  copy_func[0]= 0;                              // End marker
1077
 
  param->func_count= copy_func - param->items_to_copy;
 
4341
  copy_func[0]=0;                               // End marker
 
4342
  param->func_count= copy_func - param->items_to_copy; 
1078
4343
 
1079
 
  table->setup_tmp_table_column_bitmaps();
 
4344
  table->setup_tmp_table_column_bitmaps(bitmaps);
1080
4345
 
1081
4346
  recinfo=param->start_recinfo;
1082
 
  null_flags=(unsigned char*) table->getInsertRecord();
1083
 
  pos=table->getInsertRecord()+ null_pack_length;
 
4347
  null_flags=(unsigned char*) table->record[0];
 
4348
  pos=table->record[0]+ null_pack_length;
1084
4349
  if (null_pack_length)
1085
4350
  {
1086
4351
    memset(recinfo, 0, sizeof(*recinfo));
1089
4354
    recinfo++;
1090
4355
    memset(null_flags, 255, null_pack_length);  // Set null fields
1091
4356
 
1092
 
    table->null_flags= (unsigned char*) table->getInsertRecord();
1093
 
    table->getMutableShare()->null_fields= null_count+ hidden_null_count;
1094
 
    table->getMutableShare()->null_bytes= null_pack_length;
 
4357
    table->null_flags= (unsigned char*) table->record[0];
 
4358
    share->null_fields= null_count+ hidden_null_count;
 
4359
    share->null_bytes= null_pack_length;
1095
4360
  }
1096
4361
  null_count= (blob_count == 0) ? 1 : 0;
1097
4362
  hidden_field_count=param->hidden_field_count;
1098
 
  for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
 
4363
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
1099
4364
  {
1100
4365
    Field *field= *reg_field;
1101
4366
    uint32_t length;
1109
4374
          We have to reserve one byte here for NULL bits,
1110
4375
          as this is updated by 'end_update()'
1111
4376
        */
1112
 
        *pos++= '\0';                           // Null is stored here
1113
 
        recinfo->length= 1;
 
4377
        *pos++=0;                               // Null is stored here
 
4378
        recinfo->length=1;
1114
4379
        recinfo->type=FIELD_NORMAL;
1115
4380
        recinfo++;
1116
4381
        memset(recinfo, 0, sizeof(*recinfo));
1134
4399
    */
1135
4400
    if (default_field[i] && default_field[i]->ptr)
1136
4401
    {
1137
 
      /*
 
4402
      /* 
1138
4403
         default_field[i] is set only in the cases  when 'field' can
1139
4404
         inherit the default value that is defined for the field referred
1140
4405
         by the Item_field object from which 'field' has been created.
1141
4406
      */
1142
 
      ptrdiff_t diff;
 
4407
      my_ptrdiff_t diff;
1143
4408
      Field *orig_field= default_field[i];
1144
4409
      /* Get the value from default_values */
1145
 
      diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
 
4410
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
 
4411
                            orig_field->table->record[0]);
1146
4412
      orig_field->move_field_offset(diff);      // Points now at default_values
1147
4413
      if (orig_field->is_real_null())
1148
4414
        field->set_null();
1151
4417
        field->set_notnull();
1152
4418
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
1153
4419
      }
1154
 
      orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
1155
 
    }
 
4420
      orig_field->move_field_offset(-diff);     // Back to record[0]
 
4421
    } 
1156
4422
 
1157
4423
    if (from_field[i])
1158
4424
    {                                           /* Not a table Item */
1170
4436
      recinfo->type=FIELD_NORMAL;
1171
4437
    if (!--hidden_field_count)
1172
4438
      null_count=(null_count+7) & ~7;           // move to next byte
 
4439
 
 
4440
    // fix table name in field entry
 
4441
    field->table_name= &table->alias;
1173
4442
  }
1174
4443
 
1175
4444
  param->copy_field_end=copy;
1176
4445
  param->recinfo=recinfo;
1177
 
  table->storeRecordAsDefault();        // Make empty default record
 
4446
  store_record(table,s->default_values);        // Make empty default record
1178
4447
 
1179
 
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)              // No limit
1180
 
  {
1181
 
    max_rows= ~(uint64_t) 0;
1182
 
  }
 
4448
  if (thd->variables.tmp_table_size == ~ (uint64_t) 0)          // No limit
 
4449
    share->max_rows= ~(ha_rows) 0;
1183
4450
  else
1184
 
  {
1185
 
    max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
1186
 
                           min(session->variables.tmp_table_size,
1187
 
                               session->variables.max_heap_table_size) :
1188
 
                           session->variables.tmp_table_size) /
1189
 
                          table->getMutableShare()->getRecordLength());
1190
 
  }
1191
 
 
1192
 
  set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
 
4451
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
 
4452
                                 cmin(thd->variables.tmp_table_size,
 
4453
                                     thd->variables.max_heap_table_size) :
 
4454
                                 thd->variables.tmp_table_size) /
 
4455
                                 share->reclength);
 
4456
  set_if_bigger(share->max_rows,1);             // For dummy start options
1193
4457
  /*
1194
4458
    Push the LIMIT clause to the temporary table creation, so that we
1195
4459
    materialize only up to 'rows_limit' records instead of all result records.
1196
4460
  */
1197
 
  set_if_smaller(max_rows, rows_limit);
1198
 
 
1199
 
  table->getMutableShare()->setMaxRows(max_rows);
1200
 
 
 
4461
  set_if_smaller(share->max_rows, rows_limit);
1201
4462
  param->end_write_records= rows_limit;
1202
4463
 
1203
4464
  keyinfo= param->keyinfo;
1206
4467
  {
1207
4468
    table->group=group;                         /* Table is grouped by key */
1208
4469
    param->group_buff=group_buff;
1209
 
    table->getMutableShare()->keys=1;
1210
 
    table->getMutableShare()->uniques= test(using_unique_constraint);
 
4470
    share->keys=1;
 
4471
    share->uniques= test(using_unique_constraint);
1211
4472
    table->key_info=keyinfo;
1212
4473
    keyinfo->key_part=key_part_info;
1213
4474
    keyinfo->flags=HA_NOSAME;
1214
4475
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
1215
 
    keyinfo->key_length= 0;
1216
 
    keyinfo->rec_per_key= 0;
 
4476
    keyinfo->key_length=0;
 
4477
    keyinfo->rec_per_key=0;
1217
4478
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1218
4479
    keyinfo->name= (char*) "group_key";
1219
 
    Order *cur_group= group;
 
4480
    order_st *cur_group= group;
1220
4481
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1221
4482
    {
1222
4483
      Field *field=(*cur_group->item)->get_tmp_table_field();
1223
4484
      bool maybe_null=(*cur_group->item)->maybe_null;
1224
 
      key_part_info->null_bit= 0;
 
4485
      key_part_info->null_bit=0;
1225
4486
      key_part_info->field=  field;
1226
 
      key_part_info->offset= field->offset(table->getInsertRecord());
 
4487
      key_part_info->offset= field->offset(table->record[0]);
1227
4488
      key_part_info->length= (uint16_t) field->key_length();
1228
4489
      key_part_info->type=   (uint8_t) field->key_type();
1229
 
      key_part_info->key_type= 
 
4490
      key_part_info->key_type =
1230
4491
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1231
4492
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1232
4493
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1233
 
        0 : 1;
 
4494
        0 : FIELDFLAG_BINARY;
1234
4495
      if (!using_unique_constraint)
1235
4496
      {
1236
4497
        cur_group->buff=(char*) group_buff;
1237
 
        if (!(cur_group->field= field->new_key_field(session->mem_root,table,
 
4498
        if (!(cur_group->field= field->new_key_field(thd->mem_root,table,
1238
4499
                                                     group_buff +
1239
4500
                                                     test(maybe_null),
1240
4501
                                                     field->null_ptr,
1241
4502
                                                     field->null_bit)))
1242
 
          goto err;
 
4503
          goto err; /* purecov: inspected */
1243
4504
        if (maybe_null)
1244
4505
        {
1245
4506
          /*
1250
4511
          */
1251
4512
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
1252
4513
          key_part_info->null_bit=field->null_bit;
1253
 
          key_part_info->null_offset= (uint32_t) (field->null_ptr -
1254
 
                                              (unsigned char*) table->getInsertRecord());
 
4514
          key_part_info->null_offset= (uint) (field->null_ptr -
 
4515
                                              (unsigned char*) table->record[0]);
1255
4516
          cur_group->buff++;                        // Pointer to field data
1256
4517
          group_buff++;                         // Skipp null flag
1257
4518
        }
1278
4539
        indexes on blobs with arbitrary length. Such indexes cannot be
1279
4540
        used for lookups.
1280
4541
      */
1281
 
      table->getMutableShare()->uniques= 1;
 
4542
      share->uniques= 1;
1282
4543
    }
1283
4544
    null_pack_length-=hidden_null_pack_length;
1284
4545
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
1285
 
                         (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
 
4546
                         (share->uniques ? test(null_pack_length) : 0));
1286
4547
    table->distinct= 1;
1287
 
    table->getMutableShare()->keys= 1;
1288
 
    if (!(key_part_info= (KeyPartInfo*)
1289
 
         table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
 
4548
    share->keys= 1;
 
4549
    if (!(key_part_info= (KEY_PART_INFO*)
 
4550
          alloc_root(&table->mem_root,
 
4551
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
1290
4552
      goto err;
1291
 
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
 
4553
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
1292
4554
    table->key_info=keyinfo;
1293
4555
    keyinfo->key_part=key_part_info;
1294
4556
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
1295
4557
    keyinfo->key_length=(uint16_t) reclength;
1296
4558
    keyinfo->name= (char*) "distinct_key";
1297
4559
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1298
 
    keyinfo->rec_per_key= 0;
 
4560
    keyinfo->rec_per_key=0;
1299
4561
 
1300
4562
    /*
1301
4563
      Create an extra field to hold NULL bits so that unique indexes on
1302
4564
      blobs can distinguish NULL from 0. This extra field is not needed
1303
4565
      when we do not use UNIQUE indexes for blobs.
1304
4566
    */
1305
 
    if (null_pack_length && table->getMutableShare()->uniques)
 
4567
    if (null_pack_length && share->uniques)
1306
4568
    {
1307
 
      key_part_info->null_bit= 0;
 
4569
      key_part_info->null_bit=0;
1308
4570
      key_part_info->offset=hidden_null_pack_length;
1309
4571
      key_part_info->length=null_pack_length;
1310
 
      table->setVariableWidth();
1311
 
      key_part_info->field= new Field_varstring(table->getInsertRecord(),
 
4572
      key_part_info->field= new Field_varstring(table->record[0],
1312
4573
                                                (uint32_t) key_part_info->length,
1313
4574
                                                0,
1314
4575
                                                (unsigned char*) 0,
1315
 
                                                (uint32_t) 0,
1316
 
                                                NULL,
 
4576
                                                (uint) 0,
 
4577
                                                Field::NONE,
 
4578
                                                NULL, 
 
4579
                                                table->s,
1317
4580
                                                &my_charset_bin);
1318
4581
      if (!key_part_info->field)
1319
4582
        goto err;
1320
4583
      key_part_info->field->init(table);
1321
 
      key_part_info->key_type= 1; /* binary comparison */
 
4584
      key_part_info->key_type=FIELDFLAG_BINARY;
1322
4585
      key_part_info->type=    HA_KEYTYPE_BINARY;
1323
4586
      key_part_info++;
1324
4587
    }
1325
4588
    /* Create a distinct key over the columns we are going to return */
1326
 
    for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
 
4589
    for (i=param->hidden_field_count, reg_field=table->field + i ;
1327
4590
         i < field_count;
1328
4591
         i++, reg_field++, key_part_info++)
1329
4592
    {
1330
 
      key_part_info->null_bit= 0;
 
4593
      key_part_info->null_bit=0;
1331
4594
      key_part_info->field=    *reg_field;
1332
 
      key_part_info->offset=   (*reg_field)->offset(table->getInsertRecord());
 
4595
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
1333
4596
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
1334
 
      /* @todo The below method of computing the key format length of the
1335
 
        key part is a copy/paste from optimizer/range.cc, and table.cc.
 
4597
      /* TODO:
 
4598
        The below method of computing the key format length of the
 
4599
        key part is a copy/paste from opt_range.cc, and table.cc.
1336
4600
        This should be factored out, e.g. as a method of Field.
1337
4601
        In addition it is not clear if any of the Field::*_length
1338
4602
        methods is supposed to compute the same length. If so, it
1342
4606
 
1343
4607
      if ((*reg_field)->real_maybe_null())
1344
4608
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
1345
 
      if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
 
4609
      if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB || 
1346
4610
          (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
1347
4611
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
1348
4612
 
1351
4615
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1352
4616
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1353
4617
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1354
 
        0 : 1;
 
4618
        0 : FIELDFLAG_BINARY;
1355
4619
    }
1356
4620
  }
1357
4621
 
1358
 
  if (session->is_fatal_error)                          // If end of memory
1359
 
    goto err;
1360
 
  table->getMutableShare()->db_record_offset= 1;
1361
 
  if (table->getShare()->db_type() == myisam_engine)
 
4622
  if (thd->is_fatal_error)                              // If end of memory
 
4623
    goto err;                                    /* purecov: inspected */
 
4624
  share->db_record_offset= 1;
 
4625
  if (share->db_type() == myisam_hton)
1362
4626
  {
1363
4627
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1364
4628
                                       &param->recinfo, select_options))
1365
4629
      goto err;
1366
4630
  }
1367
 
  assert(table->in_use);
1368
4631
  if (table->open_tmp_table())
1369
4632
    goto err;
1370
4633
 
1371
 
  session->mem_root= mem_root_save;
 
4634
  thd->mem_root= mem_root_save;
1372
4635
 
1373
4636
  return(table);
1374
4637
 
1375
4638
err:
1376
 
  session->mem_root= mem_root_save;
1377
 
  table= NULL;
1378
 
 
1379
 
  return NULL;
 
4639
  thd->mem_root= mem_root_save;
 
4640
  table->free_tmp_table(thd);                    /* purecov: inspected */
 
4641
  if (temp_pool_slot != MY_BIT_NONE)
 
4642
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
4643
  return(NULL);                         /* purecov: inspected */
1380
4644
}
1381
4645
 
1382
4646
/****************************************************************************/
1383
4647
 
1384
 
void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
1385
 
                               boost::dynamic_bitset<>& write_set_arg)
1386
 
{
1387
 
  read_set= &read_set_arg;
1388
 
  write_set= &write_set_arg;
1389
 
}
1390
 
 
1391
 
 
1392
 
const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
1393
 
{
1394
 
  const boost::dynamic_bitset<> old= in_map;
1395
 
  in_map= getShare()->all_set;
 
4648
/**
 
4649
  Create a reduced Table object with properly set up Field list from a
 
4650
  list of field definitions.
 
4651
 
 
4652
    The created table doesn't have a table handler associated with
 
4653
    it, has no keys, no group/distinct, no copy_funcs array.
 
4654
    The sole purpose of this Table object is to use the power of Field
 
4655
    class to read/write data to/from table->record[0]. Then one can store
 
4656
    the record in any container (RB tree, hash, etc).
 
4657
    The table is created in THD mem_root, so are the table's fields.
 
4658
    Consequently, if you don't BLOB fields, you don't need to free it.
 
4659
 
 
4660
  @param thd         connection handle
 
4661
  @param field_list  list of column definitions
 
4662
 
 
4663
  @return
 
4664
    0 if out of memory, Table object in case of success
 
4665
*/
 
4666
 
 
4667
Table *create_virtual_tmp_table(THD *thd, List<Create_field> &field_list)
 
4668
{
 
4669
  uint32_t field_count= field_list.elements;
 
4670
  uint32_t blob_count= 0;
 
4671
  Field **field;
 
4672
  Create_field *cdef;                           /* column definition */
 
4673
  uint32_t record_length= 0;
 
4674
  uint32_t null_count= 0;                 /* number of columns which may be null */
 
4675
  uint32_t null_pack_length;              /* NULL representation array length */
 
4676
  uint32_t *blob_field;
 
4677
  unsigned char *bitmaps;
 
4678
  Table *table;
 
4679
  TABLE_SHARE *share;
 
4680
 
 
4681
  if (!multi_alloc_root(thd->mem_root,
 
4682
                        &table, sizeof(*table),
 
4683
                        &share, sizeof(*share),
 
4684
                        &field, (field_count + 1) * sizeof(Field*),
 
4685
                        &blob_field, (field_count+1) *sizeof(uint),
 
4686
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
4687
                        NULL))
 
4688
    return 0;
 
4689
 
 
4690
  memset(table, 0, sizeof(*table));
 
4691
  memset(share, 0, sizeof(*share));
 
4692
  table->field= field;
 
4693
  table->s= share;
 
4694
  share->blob_field= blob_field;
 
4695
  share->fields= field_count;
 
4696
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
4697
  table->setup_tmp_table_column_bitmaps(bitmaps);
 
4698
 
 
4699
  /* Create all fields and calculate the total length of record */
 
4700
  List_iterator_fast<Create_field> it(field_list);
 
4701
  while ((cdef= it++))
 
4702
  {
 
4703
    *field= make_field(share, 0, cdef->length,
 
4704
                       (unsigned char*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
 
4705
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
 
4706
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
 
4707
                       cdef->unireg_check,
 
4708
                       cdef->interval, cdef->field_name);
 
4709
    if (!*field)
 
4710
      goto error;
 
4711
    (*field)->init(table);
 
4712
    record_length+= (*field)->pack_length();
 
4713
    if (! ((*field)->flags & NOT_NULL_FLAG))
 
4714
      null_count++;
 
4715
 
 
4716
    if ((*field)->flags & BLOB_FLAG)
 
4717
      share->blob_field[blob_count++]= (uint) (field - table->field);
 
4718
 
 
4719
    field++;
 
4720
  }
 
4721
  *field= NULL;                             /* mark the end of the list */
 
4722
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
 
4723
  share->blob_fields= blob_count;
 
4724
 
 
4725
  null_pack_length= (null_count + 7)/8;
 
4726
  share->reclength= record_length + null_pack_length;
 
4727
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
4728
  table->record[0]= (unsigned char*) thd->alloc(share->rec_buff_length);
 
4729
  if (!table->record[0])
 
4730
    goto error;
 
4731
 
 
4732
  if (null_pack_length)
 
4733
  {
 
4734
    table->null_flags= (unsigned char*) table->record[0];
 
4735
    share->null_fields= null_count;
 
4736
    share->null_bytes= null_pack_length;
 
4737
  }
 
4738
 
 
4739
  table->in_use= thd;           /* field->reset() may access table->in_use */
 
4740
  {
 
4741
    /* Set up field pointers */
 
4742
    unsigned char *null_pos= table->record[0];
 
4743
    unsigned char *field_pos= null_pos + share->null_bytes;
 
4744
    uint32_t null_bit= 1;
 
4745
 
 
4746
    for (field= table->field; *field; ++field)
 
4747
    {
 
4748
      Field *cur_field= *field;
 
4749
      if ((cur_field->flags & NOT_NULL_FLAG))
 
4750
        cur_field->move_field(field_pos);
 
4751
      else
 
4752
      {
 
4753
        cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
 
4754
        null_bit<<= 1;
 
4755
        if (null_bit == (1 << 8))
 
4756
        {
 
4757
          ++null_pos;
 
4758
          null_bit= 1;
 
4759
        }
 
4760
      }
 
4761
      cur_field->reset();
 
4762
 
 
4763
      field_pos+= cur_field->pack_length();
 
4764
    }
 
4765
  }
 
4766
  return table;
 
4767
error:
 
4768
  for (field= table->field; *field; ++field)
 
4769
    delete *field;                         /* just invokes field destructor */
 
4770
  return 0;
 
4771
}
 
4772
 
 
4773
 
 
4774
bool Table::open_tmp_table()
 
4775
{
 
4776
  int error;
 
4777
  if ((error=file->ha_open(this, s->table_name.str,O_RDWR,
 
4778
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
 
4779
  {
 
4780
    file->print_error(error,MYF(0)); /* purecov: inspected */
 
4781
    db_stat=0;
 
4782
    return(1);
 
4783
  }
 
4784
  (void) file->extra(HA_EXTRA_QUICK);           /* Faster */
 
4785
  return(0);
 
4786
}
 
4787
 
 
4788
 
 
4789
/*
 
4790
  Create MyISAM temporary table
 
4791
 
 
4792
  SYNOPSIS
 
4793
    create_myisam_tmp_table()
 
4794
      keyinfo         Description of the index (there is always one index)
 
4795
      start_recinfo   MyISAM's column descriptions
 
4796
      recinfo INOUT   End of MyISAM's column descriptions
 
4797
      options         Option bits
 
4798
   
 
4799
  DESCRIPTION
 
4800
    Create a MyISAM temporary table according to passed description. The is
 
4801
    assumed to have one unique index or constraint.
 
4802
 
 
4803
    The passed array or MI_COLUMNDEF structures must have this form:
 
4804
 
 
4805
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
 
4806
         when there are many nullable columns)
 
4807
      2. Table columns
 
4808
      3. One free MI_COLUMNDEF element (*recinfo points here)
 
4809
   
 
4810
    This function may use the free element to create hash column for unique
 
4811
    constraint.
 
4812
 
 
4813
   RETURN
 
4814
     false - OK
 
4815
     true  - Error
 
4816
*/
 
4817
 
 
4818
bool Table::create_myisam_tmp_table(KEY *keyinfo, 
 
4819
                                    MI_COLUMNDEF *start_recinfo,
 
4820
                                    MI_COLUMNDEF **recinfo, 
 
4821
                                    uint64_t options)
 
4822
{
 
4823
  int error;
 
4824
  MI_KEYDEF keydef;
 
4825
  MI_UNIQUEDEF uniquedef;
 
4826
  TABLE_SHARE *share= s;
 
4827
 
 
4828
  if (share->keys)
 
4829
  {                                             // Get keys for ni_create
 
4830
    bool using_unique_constraint=0;
 
4831
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
 
4832
                                            sizeof(*seg) * keyinfo->key_parts);
 
4833
    if (!seg)
 
4834
      goto err;
 
4835
 
 
4836
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
 
4837
    if (keyinfo->key_length >= file->max_key_length() ||
 
4838
        keyinfo->key_parts > file->max_key_parts() ||
 
4839
        share->uniques)
 
4840
    {
 
4841
      /* Can't create a key; Make a unique constraint instead of a key */
 
4842
      share->keys=    0;
 
4843
      share->uniques= 1;
 
4844
      using_unique_constraint=1;
 
4845
      memset(&uniquedef, 0, sizeof(uniquedef));
 
4846
      uniquedef.keysegs=keyinfo->key_parts;
 
4847
      uniquedef.seg=seg;
 
4848
      uniquedef.null_are_equal=1;
 
4849
 
 
4850
      /* Create extra column for hash value */
 
4851
      memset(*recinfo, 0, sizeof(**recinfo));
 
4852
      (*recinfo)->type= FIELD_CHECK;
 
4853
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
 
4854
      (*recinfo)++;
 
4855
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
 
4856
    }
 
4857
    else
 
4858
    {
 
4859
      /* Create an unique key */
 
4860
      memset(&keydef, 0, sizeof(keydef));
 
4861
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
 
4862
      keydef.keysegs=  keyinfo->key_parts;
 
4863
      keydef.seg= seg;
 
4864
    }
 
4865
    for (uint32_t i=0; i < keyinfo->key_parts ; i++,seg++)
 
4866
    {
 
4867
      Field *field=keyinfo->key_part[i].field;
 
4868
      seg->flag=     0;
 
4869
      seg->language= field->charset()->number;
 
4870
      seg->length=   keyinfo->key_part[i].length;
 
4871
      seg->start=    keyinfo->key_part[i].offset;
 
4872
      if (field->flags & BLOB_FLAG)
 
4873
      {
 
4874
        seg->type=
 
4875
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
 
4876
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
 
4877
        seg->bit_start= (uint8_t)(field->pack_length() - share->blob_ptr_size);
 
4878
        seg->flag= HA_BLOB_PART;
 
4879
        seg->length=0;                  // Whole blob in unique constraint
 
4880
      }
 
4881
      else
 
4882
      {
 
4883
        seg->type= keyinfo->key_part[i].type;
 
4884
      }
 
4885
      if (!(field->flags & NOT_NULL_FLAG))
 
4886
      {
 
4887
        seg->null_bit= field->null_bit;
 
4888
        seg->null_pos= (uint) (field->null_ptr - (unsigned char*) record[0]);
 
4889
        /*
 
4890
          We are using a GROUP BY on something that contains NULL
 
4891
          In this case we have to tell MyISAM that two NULL should
 
4892
          on INSERT be regarded at the same value
 
4893
        */
 
4894
        if (!using_unique_constraint)
 
4895
          keydef.flag|= HA_NULL_ARE_EQUAL;
 
4896
      }
 
4897
    }
 
4898
  }
 
4899
  MI_CREATE_INFO create_info;
 
4900
  memset(&create_info, 0, sizeof(create_info));
 
4901
 
 
4902
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
4903
      OPTION_BIG_TABLES)
 
4904
    create_info.data_file_length= ~(uint64_t) 0;
 
4905
 
 
4906
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
 
4907
                       (uint) (*recinfo-start_recinfo),
 
4908
                       start_recinfo,
 
4909
                       share->uniques, &uniquedef,
 
4910
                       &create_info,
 
4911
                       HA_CREATE_TMP_TABLE)))
 
4912
  {
 
4913
    file->print_error(error,MYF(0));    /* purecov: inspected */
 
4914
    db_stat=0;
 
4915
    goto err;
 
4916
  }
 
4917
  status_var_increment(in_use->status_var.created_tmp_disk_tables);
 
4918
  share->db_record_offset= 1;
 
4919
  return false;
 
4920
 err:
 
4921
  return true;
 
4922
}
 
4923
 
 
4924
 
 
4925
void Table::free_tmp_table(THD *thd)
 
4926
{
 
4927
  MEM_ROOT own_root= mem_root;
 
4928
  const char *save_proc_info;
 
4929
 
 
4930
  save_proc_info=thd->get_proc_info();
 
4931
  thd->set_proc_info("removing tmp table");
 
4932
 
 
4933
  if (file)
 
4934
  {
 
4935
    if (db_stat)
 
4936
      file->ha_drop_table(s->table_name.str);
 
4937
    else
 
4938
      file->ha_delete_table(s->table_name.str);
 
4939
    delete file;
 
4940
  }
 
4941
 
 
4942
  /* free blobs */
 
4943
  for (Field **ptr= field ; *ptr ; ptr++)
 
4944
    (*ptr)->free();
 
4945
  free_io_cache(this);
 
4946
 
 
4947
  if (temp_pool_slot != MY_BIT_NONE)
 
4948
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
4949
 
 
4950
  plugin_unlock(0, s->db_plugin);
 
4951
 
 
4952
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
 
4953
  thd->set_proc_info(save_proc_info);
 
4954
 
 
4955
  return;
 
4956
}
 
4957
 
 
4958
/**
 
4959
  If a HEAP table gets full, create a MyISAM table and copy all rows
 
4960
  to this.
 
4961
*/
 
4962
 
 
4963
bool create_myisam_from_heap(THD *thd, Table *table,
 
4964
                             MI_COLUMNDEF *start_recinfo,
 
4965
                             MI_COLUMNDEF **recinfo, 
 
4966
                             int error, bool ignore_last_dupp_key_error)
 
4967
{
 
4968
  Table new_table;
 
4969
  TABLE_SHARE share;
 
4970
  const char *save_proc_info;
 
4971
  int write_err;
 
4972
 
 
4973
  if (table->s->db_type() != heap_hton || 
 
4974
      error != HA_ERR_RECORD_FILE_FULL)
 
4975
  {
 
4976
    table->file->print_error(error,MYF(0));
 
4977
    return(1);
 
4978
  }
 
4979
  new_table= *table;
 
4980
  share= *table->s;
 
4981
  new_table.s= &share;
 
4982
  new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton);
 
4983
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
 
4984
                                        new_table.s->db_type())))
 
4985
    return(1);                          // End of memory
 
4986
 
 
4987
  save_proc_info=thd->get_proc_info();
 
4988
  thd->set_proc_info("converting HEAP to MyISAM");
 
4989
 
 
4990
  if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
 
4991
                                        recinfo, thd->lex->select_lex.options | 
 
4992
                                        thd->options))
 
4993
    goto err2;
 
4994
  if (new_table.open_tmp_table())
 
4995
    goto err1;
 
4996
  if (table->file->indexes_are_disabled())
 
4997
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
 
4998
  table->file->ha_index_or_rnd_end();
 
4999
  table->file->ha_rnd_init(1);
 
5000
  if (table->no_rows)
 
5001
  {
 
5002
    new_table.file->extra(HA_EXTRA_NO_ROWS);
 
5003
    new_table.no_rows=1;
 
5004
  }
 
5005
 
 
5006
#ifdef TO_BE_DONE_LATER_IN_4_1
 
5007
  /*
 
5008
    To use start_bulk_insert() (which is new in 4.1) we need to find
 
5009
    all places where a corresponding end_bulk_insert() should be put.
 
5010
  */
 
5011
  table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */
 
5012
  new_table.file->ha_start_bulk_insert(table->file->stats.records);
 
5013
#else
 
5014
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
 
5015
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
 
5016
#endif
 
5017
 
 
5018
  /*
 
5019
    copy all old rows from heap table to MyISAM table
 
5020
    This is the only code that uses record[1] to read/write but this
 
5021
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
 
5022
  */
 
5023
  while (!table->file->rnd_next(new_table.record[1]))
 
5024
  {
 
5025
    write_err= new_table.file->ha_write_row(new_table.record[1]);
 
5026
    if (write_err)
 
5027
      goto err;
 
5028
  }
 
5029
  /* copy row that filled HEAP table */
 
5030
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
 
5031
  {
 
5032
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
 
5033
        !ignore_last_dupp_key_error)
 
5034
      goto err;
 
5035
  }
 
5036
 
 
5037
  /* remove heap table and change to use myisam table */
 
5038
  (void) table->file->ha_rnd_end();
 
5039
  (void) table->file->close();                  // This deletes the table !
 
5040
  delete table->file;
 
5041
  table->file=0;
 
5042
  plugin_unlock(0, table->s->db_plugin);
 
5043
  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
 
5044
  new_table.s= table->s;                       // Keep old share
 
5045
  *table= new_table;
 
5046
  *table->s= share;
 
5047
  
 
5048
  table->file->change_table_ptr(table, table->s);
 
5049
  table->use_all_columns();
 
5050
  if (save_proc_info)
 
5051
  {
 
5052
    const char *new_proc_info=
 
5053
      (!strcmp(save_proc_info,"Copying to tmp table") ?
 
5054
      "Copying to tmp table on disk" : save_proc_info);
 
5055
    thd->set_proc_info(new_proc_info);
 
5056
  }
 
5057
  return(0);
 
5058
 
 
5059
 err:
 
5060
  table->file->print_error(write_err, MYF(0));
 
5061
  (void) table->file->ha_rnd_end();
 
5062
  (void) new_table.file->close();
 
5063
 err1:
 
5064
  new_table.file->ha_delete_table(new_table.s->table_name.str);
 
5065
 err2:
 
5066
  delete new_table.file;
 
5067
  thd->set_proc_info(save_proc_info);
 
5068
  table->mem_root= new_table.mem_root;
 
5069
  return(1);
 
5070
}
 
5071
 
 
5072
my_bitmap_map *Table::use_all_columns(MY_BITMAP *bitmap)
 
5073
{
 
5074
  my_bitmap_map *old= bitmap->bitmap;
 
5075
  bitmap->bitmap= s->all_set.bitmap;
1396
5076
  return old;
1397
5077
}
1398
5078
 
1399
 
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
 
5079
void Table::restore_column_map(my_bitmap_map *old)
1400
5080
{
1401
 
  for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
1402
 
  {
1403
 
    if (old.test(i))
1404
 
    {
1405
 
      read_set->set(i);
1406
 
    }
1407
 
    else
1408
 
    {
1409
 
      read_set->reset(i);
1410
 
    }
1411
 
  }
 
5081
  read_set->bitmap= old;
1412
5082
}
1413
5083
 
1414
5084
uint32_t Table::find_shortest_key(const key_map *usable_keys)
1415
5085
{
1416
5086
  uint32_t min_length= UINT32_MAX;
1417
5087
  uint32_t best= MAX_KEY;
1418
 
  if (usable_keys->any())
 
5088
  if (!usable_keys->is_clear_all())
1419
5089
  {
1420
 
    for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
 
5090
    for (uint32_t nr=0; nr < s->keys ; nr++)
1421
5091
    {
1422
 
      if (usable_keys->test(nr))
 
5092
      if (usable_keys->is_set(nr))
1423
5093
      {
1424
5094
        if (key_info[nr].key_length < min_length)
1425
5095
        {
1444
5114
{
1445
5115
  for (; *ptr ; ptr++)
1446
5116
  {
1447
 
    if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
 
5117
    if ((*ptr)->cmp_offset(s->rec_buff_length))
1448
5118
      return true;
1449
5119
  }
1450
5120
  return false;
1451
5121
}
1452
5122
 
1453
 
/**
1454
 
   True if the table's input and output record buffers are comparable using
1455
 
   compare_records(TABLE*).
1456
 
 */
1457
 
bool Table::records_are_comparable()
1458
 
{
1459
 
  return ((getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) == 0) ||
1460
 
          write_set->is_subset_of(*read_set));
1461
 
}
1462
 
 
1463
 
/**
1464
 
   Compares the input and outbut record buffers of the table to see if a row
1465
 
   has changed. The algorithm iterates over updated columns and if they are
1466
 
   nullable compares NULL bits in the buffer before comparing actual
1467
 
   data. Special care must be taken to compare only the relevant NULL bits and
1468
 
   mask out all others as they may be undefined. The storage engine will not
1469
 
   and should not touch them.
1470
 
 
1471
 
   @param table The table to evaluate.
1472
 
 
1473
 
   @return true if row has changed.
1474
 
   @return false otherwise.
1475
 
*/
1476
 
bool Table::compare_records()
1477
 
{
1478
 
  if (getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) != 0)
1479
 
  {
1480
 
    /*
1481
 
      Storage engine may not have read all columns of the record.  Fields
1482
 
      (including NULL bits) not in the write_set may not have been read and
1483
 
      can therefore not be compared.
1484
 
    */
1485
 
    for (Field **ptr= this->field ; *ptr != NULL; ptr++)
1486
 
    {
1487
 
      Field *f= *ptr;
1488
 
      if (write_set->test(f->position()))
1489
 
      {
1490
 
        if (f->real_maybe_null())
1491
 
        {
1492
 
          unsigned char null_byte_index= f->null_ptr - record[0];
1493
 
 
1494
 
          if (((record[0][null_byte_index]) & f->null_bit) !=
1495
 
              ((record[1][null_byte_index]) & f->null_bit))
1496
 
            return true;
1497
 
        }
1498
 
        if (f->cmp_binary_offset(getShare()->rec_buff_length))
1499
 
          return true;
1500
 
      }
1501
 
    }
1502
 
    return false;
1503
 
  }
1504
 
 
1505
 
  /*
1506
 
    The storage engine has read all columns, so it's safe to compare all bits
1507
 
    including those not in the write_set. This is cheaper than the
1508
 
    field-by-field comparison done above.
1509
 
  */
1510
 
  if (not getShare()->blob_fields + getShare()->hasVariableWidth())
1511
 
    // Fixed-size record: do bitwise comparison of the records
1512
 
    return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
1513
 
 
 
5123
/* Return false if row hasn't changed */
 
5124
 
 
5125
bool Table::compare_record()
 
5126
{
 
5127
  if (s->blob_fields + s->varchar_fields == 0)
 
5128
    return cmp_record(this, record[1]);
1514
5129
  /* Compare null bits */
1515
 
  if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
1516
 
    return true; /* Diff in NULL value */
1517
 
 
 
5130
  if (memcmp(null_flags,
 
5131
             null_flags + s->rec_buff_length,
 
5132
             s->null_bytes))
 
5133
    return true;                                // Diff in NULL value
1518
5134
  /* Compare updated fields */
1519
5135
  for (Field **ptr= field ; *ptr ; ptr++)
1520
5136
  {
1521
 
    if (isWriteSet((*ptr)->position()) &&
1522
 
        (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
 
5137
    if (bitmap_is_set(write_set, (*ptr)->field_index) &&
 
5138
        (*ptr)->cmp_binary_offset(s->rec_buff_length))
1523
5139
      return true;
1524
5140
  }
1525
5141
  return false;
1526
5142
}
1527
5143
 
1528
 
/*
1529
 
 * Store a record from previous record into next
1530
 
 *
1531
 
 */
1532
 
void Table::storeRecord()
1533
 
{
1534
 
  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1535
 
}
1536
 
 
1537
 
/*
1538
 
 * Store a record as an insert
1539
 
 *
1540
 
 */
1541
 
void Table::storeRecordAsInsert()
1542
 
{
1543
 
  assert(insert_values.size() >= getShare()->getRecordLength());
1544
 
  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
1545
 
}
1546
 
 
1547
 
/*
1548
 
 * Store a record with default values
1549
 
 *
1550
 
 */
1551
 
void Table::storeRecordAsDefault()
1552
 
{
1553
 
  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1554
 
}
1555
 
 
1556
 
/*
1557
 
 * Restore a record from previous record into next
1558
 
 *
1559
 
 */
1560
 
void Table::restoreRecord()
1561
 
{
1562
 
  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
1563
 
}
1564
 
 
1565
 
/*
1566
 
 * Restore a record with default values
1567
 
 *
1568
 
 */
1569
 
void Table::restoreRecordAsDefault()
1570
 
{
1571
 
  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
1572
 
}
1573
 
 
1574
 
/*
1575
 
 * Empty a record
1576
 
 *
1577
 
 */
1578
 
void Table::emptyRecord()
1579
 
{
1580
 
  restoreRecordAsDefault();
1581
 
  memset(null_flags, 255, getShare()->null_bytes);
1582
 
}
1583
 
 
1584
 
Table::Table() : 
1585
 
  field(NULL),
1586
 
  cursor(NULL),
1587
 
  next(NULL),
1588
 
  prev(NULL),
1589
 
  read_set(NULL),
1590
 
  write_set(NULL),
1591
 
  tablenr(0),
1592
 
  db_stat(0),
1593
 
  def_read_set(),
1594
 
  def_write_set(),
1595
 
  tmp_set(),
1596
 
  in_use(NULL),
1597
 
  key_info(NULL),
1598
 
  next_number_field(NULL),
1599
 
  found_next_number_field(NULL),
1600
 
  timestamp_field(NULL),
1601
 
  pos_in_table_list(NULL),
1602
 
  group(NULL),
1603
 
  null_flags(NULL),
1604
 
  lock_position(0),
1605
 
  lock_data_start(0),
1606
 
  lock_count(0),
1607
 
  used_fields(0),
1608
 
  status(0),
1609
 
  derived_select_number(0),
1610
 
  current_lock(F_UNLCK),
1611
 
  copy_blobs(false),
1612
 
  maybe_null(false),
1613
 
  null_row(false),
1614
 
  force_index(false),
1615
 
  distinct(false),
1616
 
  const_table(false),
1617
 
  no_rows(false),
1618
 
  key_read(false),
1619
 
  no_keyread(false),
1620
 
  open_placeholder(false),
1621
 
  locked_by_name(false),
1622
 
  no_cache(false),
1623
 
  auto_increment_field_not_null(false),
1624
 
  alias_name_used(false),
1625
 
  query_id(0),
1626
 
  quick_condition_rows(0),
1627
 
  timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1628
 
  map(0),
1629
 
  quick_rows(),
1630
 
  const_key_parts(),
1631
 
  quick_key_parts(),
1632
 
  quick_n_ranges()
1633
 
{
1634
 
  record[0]= (unsigned char *) 0;
1635
 
  record[1]= (unsigned char *) 0;
1636
 
}
 
5144
 
 
5145
 
 
5146
 
1637
5147
 
1638
5148
/*****************************************************************************
1639
5149
  The different ways to read a record
1640
5150
  Returns -1 if row was not found, 0 if row was found and 1 on errors
1641
5151
*****************************************************************************/
1642
5152
 
1643
 
/** Help function when we get some an error from the table Cursor. */
 
5153
/** Help function when we get some an error from the table handler. */
1644
5154
 
1645
5155
int Table::report_error(int error)
1646
5156
{
1654
5164
    print them to the .err log
1655
5165
  */
1656
5166
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
1657
 
    errmsg_printf(error::ERROR, _("Got error %d when reading table '%s'"),
1658
 
                  error, getShare()->getPath());
1659
 
  print_error(error, MYF(0));
 
5167
    sql_print_error(_("Got error %d when reading table '%s'"),
 
5168
                    error, s->path.str);
 
5169
  file->print_error(error,MYF(0));
1660
5170
 
1661
5171
  return 1;
1662
5172
}
1663
5173
 
1664
5174
 
1665
 
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
1666
 
{
1667
 
  used_fields= 0;
1668
 
  const_table= 0;
1669
 
  null_row= 0;
1670
 
  status= STATUS_NO_RECORD;
1671
 
  maybe_null= table_list->outer_join;
1672
 
  TableList *embedding= table_list->getEmbedding();
1673
 
  while (!maybe_null && embedding)
1674
 
  {
1675
 
    maybe_null= embedding->outer_join;
1676
 
    embedding= embedding->getEmbedding();
1677
 
  }
1678
 
  tablenr= table_number;
1679
 
  map= (table_map) 1 << table_number;
1680
 
  force_index= table_list->force_index;
1681
 
  covering_keys= getShare()->keys_for_keyread;
1682
 
  merge_keys.reset();
1683
 
}
1684
 
 
1685
 
 
1686
 
bool Table::fill_item_list(List<Item> *item_list) const
1687
 
{
1688
 
  /*
1689
 
    All Item_field's created using a direct pointer to a field
1690
 
    are fixed in Item_field constructor.
1691
 
  */
1692
 
  for (Field **ptr= field; *ptr; ptr++)
1693
 
  {
1694
 
    Item_field *item= new Item_field(*ptr);
1695
 
    if (!item || item_list->push_back(item))
1696
 
      return true;
1697
 
  }
1698
 
  return false;
1699
 
}
1700
 
 
1701
 
 
1702
 
void Table::filesort_free_buffers(bool full)
1703
 
{
1704
 
  if (sort.record_pointers)
1705
 
  {
1706
 
    free((unsigned char*) sort.record_pointers);
1707
 
    sort.record_pointers=0;
1708
 
  }
1709
 
  if (full)
1710
 
  {
1711
 
    if (sort.sort_keys )
1712
 
    {
1713
 
      if ((unsigned char*) sort.sort_keys)
1714
 
        free((unsigned char*) sort.sort_keys);
1715
 
      sort.sort_keys= 0;
1716
 
    }
1717
 
    if (sort.buffpek)
1718
 
    {
1719
 
      if ((unsigned char*) sort.buffpek)
1720
 
        free((unsigned char*) sort.buffpek);
1721
 
      sort.buffpek= 0;
1722
 
      sort.buffpek_len= 0;
1723
 
    }
1724
 
  }
1725
 
 
1726
 
  if (sort.addon_buf)
1727
 
  {
1728
 
    free((char *) sort.addon_buf);
1729
 
    free((char *) sort.addon_field);
1730
 
    sort.addon_buf=0;
1731
 
    sort.addon_field=0;
1732
 
  }
1733
 
}
1734
 
 
1735
5175
/*
1736
 
  Is this instance of the table should be reopen or represents a name-lock?
 
5176
  Calculate data for each virtual field marked for write in the
 
5177
  corresponding column map.
 
5178
 
 
5179
  SYNOPSIS
 
5180
    update_virtual_fields_marked_for_write()
 
5181
    table                  The Table object
 
5182
    ignore_stored          Indication whether physically stored virtual
 
5183
                           fields do not need updating.
 
5184
                           This value is false when during INSERT and UPDATE
 
5185
                           and true in all other cases.
 
5186
 
 
5187
  RETURN
 
5188
    0  - Success
 
5189
    >0 - Error occurred during the generation/calculation of a virtual field value
 
5190
 
1737
5191
*/
1738
 
bool Table::needs_reopen_or_name_lock() const
1739
 
1740
 
  return getShare()->getVersion() != refresh_version;
1741
 
}
1742
 
 
1743
 
uint32_t Table::index_flags(uint32_t idx) const
1744
 
{
1745
 
  return getShare()->getEngine()->index_flags(getShare()->getKeyInfo(idx).algorithm);
1746
 
}
1747
 
 
1748
 
void Table::print_error(int error, myf errflag) const
1749
 
{
1750
 
  getShare()->getEngine()->print_error(error, errflag, *this);
1751
 
}
1752
 
 
1753
 
} /* namespace drizzled */
 
5192
 
 
5193
int update_virtual_fields_marked_for_write(Table *table,
 
5194
                                           bool ignore_stored)
 
5195
{
 
5196
  Field **vfield_ptr, *vfield;
 
5197
  int error= 0;
 
5198
  if ((not table) or (not table->vfield))
 
5199
    return(0);
 
5200
 
 
5201
  /* Iterate over virtual fields in the table */
 
5202
  for (vfield_ptr= table->vfield; *vfield_ptr; vfield_ptr++)
 
5203
  {
 
5204
    vfield= (*vfield_ptr);
 
5205
    assert(vfield->vcol_info && vfield->vcol_info->expr_item);
 
5206
    /*
 
5207
      Only update those fields that are marked in the write_set bitmap
 
5208
      and not _already_ physically stored in the database.
 
5209
    */
 
5210
    if (bitmap_is_set(table->write_set, vfield->field_index) &&
 
5211
        (not (ignore_stored && vfield->is_stored))
 
5212
       )
 
5213
    {
 
5214
      /* Generate the actual value of the virtual fields */
 
5215
      error= vfield->vcol_info->expr_item->save_in_field(vfield, 0);
 
5216
    }
 
5217
  }
 
5218
  return(0);
 
5219
}
 
5220
 
 
5221
 
 
5222
/*****************************************************************************
 
5223
** Instansiate templates
 
5224
*****************************************************************************/
 
5225
 
 
5226
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
5227
template class List<String>;
 
5228
template class List_iterator<String>;
 
5229
#endif