~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/table.cc

  • Committer: Monty Taylor
  • Date: 2008-07-05 11:20:18 UTC
  • mto: This revision was merged to the branch mainline in revision 62.
  • Revision ID: monty@inaugust.com-20080705112018-fr12kkmgphtu7m29
Changes so that removal of duplicate curr_dir from my_sys.h work.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
/* Some general useful functions */
18
18
 
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"
 
19
#include "mysql_priv.h"
 
20
#include <m_ctype.h>
 
21
#include "my_md5.h"
24
22
 
25
23
/* INFORMATION_SCHEMA name */
26
24
LEX_STRING INFORMATION_SCHEMA_NAME= {C_STRING_WITH_LEN("information_schema")};
27
25
 
28
 
/* Keyword for parsing virtual column functions */
29
 
LEX_STRING parse_vcol_keyword= { C_STRING_WITH_LEN("PARSE_VCOL_EXPR ") };
 
26
/* MYSQL_SCHEMA name */
 
27
LEX_STRING MYSQL_SCHEMA_NAME= {C_STRING_WITH_LEN("mysql")};
30
28
 
31
29
/* Functions defined in this file */
32
30
 
33
31
void open_table_error(TABLE_SHARE *share, int error, int db_errno,
34
32
                      myf errortype, int errarg);
35
33
static int open_binary_frm(THD *thd, TABLE_SHARE *share,
36
 
                           unsigned char *head, File file);
 
34
                           uchar *head, File file);
37
35
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);
 
36
                              uint types, char **names);
 
37
static uint find_field(Field **fields, uchar *record, uint start, uint length);
 
38
 
 
39
inline bool is_system_table_name(const char *name, uint length);
 
40
 
 
41
/**************************************************************************
 
42
  Object_creation_ctx implementation.
 
43
**************************************************************************/
 
44
 
 
45
Object_creation_ctx *Object_creation_ctx::set_n_backup(THD *thd)
 
46
{
 
47
  Object_creation_ctx *backup_ctx;
 
48
  DBUG_ENTER("Object_creation_ctx::set_n_backup");
 
49
 
 
50
  backup_ctx= create_backup_ctx(thd);
 
51
  change_env(thd);
 
52
 
 
53
  DBUG_RETURN(backup_ctx);
 
54
}
 
55
 
 
56
void Object_creation_ctx::restore_env(THD *thd, Object_creation_ctx *backup_ctx)
 
57
{
 
58
  if (!backup_ctx)
 
59
    return;
 
60
 
 
61
  backup_ctx->change_env(thd);
 
62
 
 
63
  delete backup_ctx;
 
64
}
 
65
 
 
66
/**************************************************************************
 
67
  Default_object_creation_ctx implementation.
 
68
**************************************************************************/
 
69
 
 
70
Default_object_creation_ctx::Default_object_creation_ctx(THD *thd)
 
71
  : m_client_cs(thd->variables.character_set_client),
 
72
    m_connection_cl(thd->variables.collation_connection)
 
73
{ }
 
74
 
 
75
Default_object_creation_ctx::Default_object_creation_ctx(
 
76
  CHARSET_INFO *client_cs, CHARSET_INFO *connection_cl)
 
77
  : m_client_cs(client_cs),
 
78
    m_connection_cl(connection_cl)
 
79
{ }
 
80
 
 
81
Object_creation_ctx *
 
82
Default_object_creation_ctx::create_backup_ctx(THD *thd) const
 
83
{
 
84
  return new Default_object_creation_ctx(thd);
 
85
}
 
86
 
 
87
void Default_object_creation_ctx::change_env(THD *thd) const
 
88
{
 
89
  thd->variables.character_set_client= m_client_cs;
 
90
  thd->variables.collation_connection= m_connection_cl;
 
91
 
 
92
  thd->update_charset();
 
93
}
40
94
 
41
95
/*************************************************************************/
42
96
 
43
97
/* Get column name from column hash */
44
98
 
45
 
static unsigned char *get_field_name(Field **buff, size_t *length,
46
 
                             bool not_used __attribute__((unused)))
 
99
static uchar *get_field_name(Field **buff, size_t *length,
 
100
                             my_bool not_used __attribute__((unused)))
47
101
{
48
102
  *length= (uint) strlen((*buff)->field_name);
49
 
  return (unsigned char*) (*buff)->field_name;
 
103
  return (uchar*) (*buff)->field_name;
50
104
}
51
105
 
52
106
 
81
135
 
82
136
TABLE_CATEGORY get_table_category(const LEX_STRING *db, const LEX_STRING *name)
83
137
{
84
 
  assert(db != NULL);
85
 
  assert(name != NULL);
 
138
  DBUG_ASSERT(db != NULL);
 
139
  DBUG_ASSERT(name != NULL);
86
140
 
87
141
  if ((db->length == INFORMATION_SCHEMA_NAME.length) &&
88
142
      (my_strcasecmp(system_charset_info,
92
146
    return TABLE_CATEGORY_INFORMATION;
93
147
  }
94
148
 
 
149
  if ((db->length == MYSQL_SCHEMA_NAME.length) &&
 
150
      (my_strcasecmp(system_charset_info,
 
151
                    MYSQL_SCHEMA_NAME.str,
 
152
                    db->str) == 0))
 
153
  {
 
154
    if (is_system_table_name(name->str, name->length))
 
155
    {
 
156
      return TABLE_CATEGORY_SYSTEM;
 
157
    }
 
158
  }
 
159
 
95
160
  return TABLE_CATEGORY_USER;
96
161
}
97
162
 
101
166
 
102
167
  SYNOPSIS
103
168
    alloc_table_share()
104
 
    TableList           Take database and table name from there
 
169
    TABLE_LIST          Take database and table name from there
105
170
    key                 Table cache key (db \0 table_name \0...)
106
171
    key_length          Length of key
107
172
 
110
175
    #  Share
111
176
*/
112
177
 
113
 
TABLE_SHARE *alloc_table_share(TableList *table_list, char *key,
114
 
                               uint32_t key_length)
 
178
TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key,
 
179
                               uint key_length)
115
180
{
116
181
  MEM_ROOT mem_root;
117
182
  TABLE_SHARE *share;
118
183
  char *key_buff, *path_buff;
119
184
  char path[FN_REFLEN];
120
 
  uint32_t path_length;
 
185
  uint path_length;
 
186
  DBUG_ENTER("alloc_table_share");
 
187
  DBUG_PRINT("enter", ("table: '%s'.'%s'",
 
188
                       table_list->db, table_list->table_name));
121
189
 
122
190
  path_length= build_table_filename(path, sizeof(path) - 1,
123
191
                                    table_list->db,
129
197
                       &path_buff, path_length + 1,
130
198
                       NULL))
131
199
  {
132
 
    memset(share, 0, sizeof(*share));
 
200
    bzero((char*) share, sizeof(*share));
133
201
 
134
202
    share->set_table_cache_key(key_buff, key, key_length);
135
203
 
136
204
    share->path.str= path_buff;
137
205
    share->path.length= path_length;
138
 
    my_stpcpy(share->path.str, path);
 
206
    strmov(share->path.str, path);
139
207
    share->normalized_path.str=    share->path.str;
140
208
    share->normalized_path.length= path_length;
141
209
 
142
210
    share->version=       refresh_version;
143
211
 
 
212
    share->tablespace=    NULL;
 
213
 
144
214
    /*
145
215
      This constant is used to mark that no table map version has been
146
216
      assigned.  No arithmetic is done on the value: it will be
147
 
      overwritten with a value taken from DRIZZLE_BIN_LOG.
 
217
      overwritten with a value taken from MYSQL_BIN_LOG.
148
218
    */
149
 
    share->table_map_version= UINT64_MAX;
 
219
    share->table_map_version= ~(uint64_t)0;
150
220
 
151
221
    /*
152
222
      Since alloc_table_share() can be called without any locking (for
155
225
      elsewhere, and then assign a table map id inside open_table()
156
226
      under the protection of the LOCK_open mutex.
157
227
    */
158
 
    share->table_map_id= UINT32_MAX;
 
228
    share->table_map_id= ~0UL;
159
229
    share->cached_row_logging_check= -1;
160
230
 
161
 
    memcpy(&share->mem_root, &mem_root, sizeof(mem_root));
 
231
    memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root));
162
232
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
163
233
    pthread_cond_init(&share->cond, NULL);
164
234
  }
165
 
  return(share);
 
235
  DBUG_RETURN(share);
166
236
}
167
237
 
168
238
 
190
260
*/
191
261
 
192
262
void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
193
 
                          uint32_t key_length, const char *table_name,
 
263
                          uint key_length, const char *table_name,
194
264
                          const char *path)
195
265
{
 
266
  DBUG_ENTER("init_tmp_table_share");
 
267
  DBUG_PRINT("enter", ("table: '%s'.'%s'", key, table_name));
196
268
 
197
 
  memset(share, 0, sizeof(*share));
 
269
  bzero((char*) share, sizeof(*share));
198
270
  init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
199
271
  share->table_category=         TABLE_CATEGORY_TEMPORARY;
200
272
  share->tmp_table=              INTERNAL_TMP_TABLE;
208
280
  share->normalized_path.str=    (char*) path;
209
281
  share->path.length= share->normalized_path.length= strlen(path);
210
282
  share->frm_version=            FRM_VER_TRUE_VARCHAR;
 
283
  share->tablespace=             NULL;
211
284
  /*
212
285
    Temporary tables are not replicated, but we set up these fields
213
286
    anyway to be able to catch errors.
221
294
  */
222
295
  share->table_map_id= (ulong) thd->query_id;
223
296
 
224
 
  return;
 
297
  DBUG_VOID_RETURN;
225
298
}
226
299
 
227
300
 
239
312
void free_table_share(TABLE_SHARE *share)
240
313
{
241
314
  MEM_ROOT mem_root;
242
 
  assert(share->ref_count == 0);
 
315
  DBUG_ENTER("free_table_share");
 
316
  DBUG_PRINT("enter", ("table: %s.%s", share->db.str, share->table_name.str));
 
317
  DBUG_ASSERT(share->ref_count == 0);
243
318
 
244
319
  /*
245
320
    If someone is waiting for this to be deleted, inform it about this.
264
339
  share->db_plugin= NULL;
265
340
 
266
341
  /* We must copy mem_root from share because share is allocated through it */
267
 
  memcpy(&mem_root, &share->mem_root, sizeof(mem_root));
 
342
  memcpy((char*) &mem_root, (char*) &share->mem_root, sizeof(mem_root));
268
343
  free_root(&mem_root, MYF(0));                 // Free's share
269
 
  return;
270
 
}
 
344
  DBUG_VOID_RETURN;
 
345
}
 
346
 
 
347
 
 
348
/**
 
349
  Return TRUE if a table name matches one of the system table names.
 
350
  Currently these are:
 
351
 
 
352
  help_category, help_keyword, help_relation, help_topic,
 
353
  proc, event
 
354
  time_zone, time_zone_leap_second, time_zone_name, time_zone_transition,
 
355
  time_zone_transition_type
 
356
 
 
357
  This function trades accuracy for speed, so may return false
 
358
  positives. Presumably mysql.* database is for internal purposes only
 
359
  and should not contain user tables.
 
360
*/
 
361
 
 
362
inline bool is_system_table_name(const char *name, uint length)
 
363
{
 
364
  CHARSET_INFO *ci= system_charset_info;
 
365
 
 
366
  return (
 
367
          /* mysql.proc table */
 
368
          (
 
369
           length == 4 &&
 
370
           my_tolower(ci, name[0]) == 'p' && 
 
371
           my_tolower(ci, name[1]) == 'r' &&
 
372
           my_tolower(ci, name[2]) == 'o' &&
 
373
           my_tolower(ci, name[3]) == 'c'
 
374
          ) ||
 
375
 
 
376
          /* one of mysql.help* tables */
 
377
          (
 
378
           length > 4 &&
 
379
           my_tolower(ci, name[0]) == 'h' &&
 
380
           my_tolower(ci, name[1]) == 'e' &&
 
381
           my_tolower(ci, name[2]) == 'l' &&
 
382
           my_tolower(ci, name[3]) == 'p'
 
383
          ) ||
 
384
 
 
385
          /* one of mysql.time_zone* tables */
 
386
          (
 
387
           my_tolower(ci, name[0]) == 't' &&
 
388
           my_tolower(ci, name[1]) == 'i' &&
 
389
           my_tolower(ci, name[2]) == 'm' &&
 
390
           my_tolower(ci, name[3]) == 'e'
 
391
          )
 
392
          );
 
393
}
 
394
 
271
395
 
272
396
/*
273
397
  Read table definition from a binary / text based .frm file
294
418
   6    Unknown .frm version
295
419
*/
296
420
 
297
 
int open_table_def(THD *thd, TABLE_SHARE *share, uint32_t db_flags  __attribute__((unused)))
 
421
int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags)
298
422
{
299
423
  int error, table_type;
300
424
  bool error_given;
301
425
  File file;
302
 
  unsigned char head[64], *disk_buff;
 
426
  uchar head[64], *disk_buff;
303
427
  char  path[FN_REFLEN];
304
428
  MEM_ROOT **root_ptr, *old_root;
 
429
  DBUG_ENTER("open_table_def");
 
430
  DBUG_PRINT("enter", ("table: '%s'.'%s'  path: '%s'", share->db.str,
 
431
                       share->table_name.str, share->normalized_path.str));
305
432
 
306
433
  error= 1;
307
434
  error_given= 0;
308
435
  disk_buff= NULL;
309
436
 
310
 
  strxmov(path, share->normalized_path.str, reg_ext, NULL);
311
 
  if ((file= open(path, O_RDONLY)) < 0)
 
437
  strxmov(path, share->normalized_path.str, reg_ext, NullS);
 
438
  if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
312
439
  {
313
440
    /*
314
441
      We don't try to open 5.0 unencoded name, if
319
446
        
320
447
      - non-encoded db or table name contain "#mysql50#" prefix.
321
448
        This kind of tables must have been opened only by the
322
 
        open() above.
 
449
        my_open() above.
323
450
    */
324
451
    if (strchr(share->table_name.str, '@') ||
325
452
        !strncmp(share->db.str, MYSQL50_TABLE_NAME_PREFIX,
329
456
      goto err_not_open;
330
457
 
331
458
    /* Try unencoded 5.0 name */
332
 
    uint32_t length;
 
459
    uint length;
333
460
    strxnmov(path, sizeof(path)-1,
334
461
             mysql_data_home, "/", share->db.str, "/",
335
 
             share->table_name.str, reg_ext, NULL);
 
462
             share->table_name.str, reg_ext, NullS);
336
463
    length= unpack_filename(path, path) - reg_ext_length;
337
464
    /*
338
465
      The following is a safety test and should never fail
339
466
      as the old file name should never be longer than the new one.
340
467
    */
341
 
    assert(length <= share->normalized_path.length);
 
468
    DBUG_ASSERT(length <= share->normalized_path.length);
342
469
    /*
343
470
      If the old and the new names have the same length,
344
471
      then table name does not have tricky characters,
345
472
      so no need to check the old file name.
346
473
    */
347
474
    if (length == share->normalized_path.length ||
348
 
        ((file= open(path, O_RDONLY)) < 0))
 
475
        ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0))
349
476
      goto err_not_open;
350
477
 
351
478
    /* Unencoded 5.0 table name found */
352
479
    path[length]= '\0'; // Remove .frm extension
353
 
    my_stpcpy(share->normalized_path.str, path);
 
480
    strmov(share->normalized_path.str, path);
354
481
    share->normalized_path.length= length;
355
482
  }
356
483
 
358
485
  if (my_read(file, head, 64, MYF(MY_NABP)))
359
486
    goto err;
360
487
 
361
 
  if (head[0] == (unsigned char) 254 && head[1] == 1)
 
488
  if (head[0] == (uchar) 254 && head[1] == 1)
362
489
  {
363
490
    if (head[2] == FRM_VER || head[2] == FRM_VER+1 ||
364
491
        (head[2] >= FRM_VER+3 && head[2] <= FRM_VER+4))
365
492
    {
 
493
      /* Open view only */
 
494
      if (db_flags & OPEN_VIEW_ONLY)
 
495
      {
 
496
        error_given= 1;
 
497
        goto err;
 
498
      }
366
499
      table_type= 1;
367
500
    }
368
501
    else
384
517
    *root_ptr= old_root;
385
518
    error_given= 1;
386
519
  }
387
 
  else
388
 
    assert(1);
389
520
 
390
521
  share->table_category= get_table_category(& share->db, & share->table_name);
391
522
 
402
533
    open_table_error(share, error, (share->open_errno= my_errno), 0);
403
534
  }
404
535
 
405
 
  return(error);
 
536
  DBUG_RETURN(error);
406
537
}
407
538
 
408
539
 
410
541
  Read data from a binary .frm file from MySQL 3.23 - 5.0 into TABLE_SHARE
411
542
*/
412
543
 
413
 
static int open_binary_frm(THD *thd, TABLE_SHARE *share, unsigned char *head,
 
544
static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
414
545
                           File file)
415
546
{
416
547
  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;
 
548
  uint new_frm_ver, field_pack_length, new_field_pack_flag;
 
549
  uint interval_count, interval_parts, read_length, int_length;
 
550
  uint db_create_options, keys, key_parts, n_length;
 
551
  uint key_info_length, com_length, null_bit_pos;
 
552
  uint extra_rec_buf_length;
 
553
  uint i,j;
424
554
  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;
 
555
  uchar forminfo[288];
 
556
  char *keynames, *names, *comment_pos;
 
557
  uchar *record;
 
558
  uchar *disk_buff, *strpos, *null_flags, *null_pos;
429
559
  ulong pos, record_offset, *rec_per_key, rec_buff_length;
430
560
  handler *handler_file= 0;
431
561
  KEY   *keyinfo;
432
562
  KEY_PART_INFO *key_part;
 
563
  SQL_CRYPT *crypted=0;
433
564
  Field  **field_ptr, *reg_field;
434
565
  const char **interval_array;
435
566
  enum legacy_db_type legacy_db_type;
436
567
  my_bitmap_map *bitmaps;
437
 
  unsigned char *buff= 0;
438
 
  unsigned char *field_extra_info= 0;
 
568
  uchar *buff= 0;
 
569
  uchar *field_extra_info= 0;
 
570
  DBUG_ENTER("open_binary_frm");
439
571
 
440
572
  new_field_pack_flag= head[27];
441
573
  new_frm_ver= (head[2] - FRM_VER);
445
577
  error= 3;
446
578
  if (!(pos=get_form_pos(file,head,(TYPELIB*) 0)))
447
579
    goto err;                                   /* purecov: inspected */
448
 
  my_seek(file,pos,MY_SEEK_SET,MYF(0));
 
580
  VOID(my_seek(file,pos,MY_SEEK_SET,MYF(0)));
449
581
  if (my_read(file,forminfo,288,MYF(MY_NABP)))
450
582
    goto err;
451
583
 
459
591
  if (share->frm_version == FRM_VER_TRUE_VARCHAR -1 && head[33] == 5)
460
592
    share->frm_version= FRM_VER_TRUE_VARCHAR;
461
593
 
462
 
  legacy_db_type= DB_TYPE_FIRST_DYNAMIC;
463
 
  assert(share->db_plugin == NULL);
 
594
  legacy_db_type= (enum legacy_db_type) (uint) *(head+3);
 
595
  DBUG_ASSERT(share->db_plugin == NULL);
464
596
  /*
465
597
    if the storage engine is dynamic, no point in resolving it by its
466
598
    dynamically allocated legacy_db_type. We will resolve it later by name.
479
611
    share->transactional= (ha_choice) (head[39] & 3);
480
612
    share->page_checksum= (ha_choice) ((head[39] >> 2) & 3);
481
613
    share->row_type= (row_type) head[40];
482
 
    share->block_size= uint4korr(head+43);
483
614
    share->table_charset= get_charset((uint) head[38],MYF(0));
484
615
    share->null_field_first= 1;
485
616
  }
489
620
    if (use_mb(default_charset_info))
490
621
    {
491
622
      /* Warn that we may be changing the size of character columns */
492
 
      sql_print_warning(_("'%s' had no or invalid character set, "
 
623
      sql_print_warning("'%s' had no or invalid character set, "
493
624
                        "and default character set is multi-byte, "
494
 
                        "so character column sizes may have changed"),
 
625
                        "so character column sizes may have changed",
495
626
                        share->path.str);
496
627
    }
497
628
    share->table_charset= default_charset_info;
500
631
  if (db_create_options & HA_OPTION_LONG_BLOB_PTR)
501
632
    share->blob_ptr_size= portable_sizeof_char_ptr;
502
633
  /* Set temporarily a good value for db_low_byte_first */
503
 
  share->db_low_byte_first= true;
 
634
  share->db_low_byte_first= test(legacy_db_type != DB_TYPE_ISAM);
504
635
  error=4;
505
636
  share->max_rows= uint4korr(head+18);
506
637
  share->min_rows= uint4korr(head+22);
507
638
 
508
639
  /* Read keyinformation */
509
640
  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))
 
641
  VOID(my_seek(file,(ulong) uint2korr(head+6),MY_SEEK_SET,MYF(0)));
 
642
  if (read_string(file,(uchar**) &disk_buff,key_info_length))
512
643
    goto err;                                   /* purecov: inspected */
513
644
  if (disk_buff[0] & 0x80)
514
645
  {
527
658
  if (!(keyinfo = (KEY*) alloc_root(&share->mem_root,
528
659
                                    n_length + uint2korr(disk_buff+4))))
529
660
    goto err;                                   /* purecov: inspected */
530
 
  memset(keyinfo, 0, n_length);
 
661
  bzero((char*) keyinfo,n_length);
531
662
  share->key_info= keyinfo;
532
 
  key_part= reinterpret_cast<KEY_PART_INFO*> (keyinfo+keys);
 
663
  key_part= my_reinterpret_cast(KEY_PART_INFO*) (keyinfo+keys);
533
664
  strpos=disk_buff+6;
534
665
 
535
666
  if (!(rec_per_key= (ulong*) alloc_root(&share->mem_root,
548
679
      keyinfo->block_size= uint2korr(strpos+6);
549
680
      strpos+=8;
550
681
    }
 
682
    else
 
683
    {
 
684
      keyinfo->flags=    ((uint) strpos[0]) ^ HA_NOSAME;
 
685
      keyinfo->key_length= (uint) uint2korr(strpos+1);
 
686
      keyinfo->key_parts=  (uint) strpos[3];
 
687
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
688
      strpos+=4;
 
689
    }
551
690
 
552
691
    keyinfo->key_part=   key_part;
553
692
    keyinfo->rec_per_key= rec_per_key;
554
693
    for (j=keyinfo->key_parts ; j-- ; key_part++)
555
694
    {
556
695
      *rec_per_key++=0;
557
 
      key_part->fieldnr=        (uint16_t) (uint2korr(strpos) & FIELD_NR_MASK);
 
696
      key_part->fieldnr=        (uint16) (uint2korr(strpos) & FIELD_NR_MASK);
558
697
      key_part->offset= (uint) uint2korr(strpos+2)-1;
559
698
      key_part->key_type=       (uint) uint2korr(strpos+5);
560
699
      // key_part->field=       (Field*) 0;     // Will be fixed later
579
718
    }
580
719
  }
581
720
  keynames=(char*) key_part;
582
 
  strpos+= (my_stpcpy(keynames, (char *) strpos) - keynames)+1;
 
721
  strpos+= (strmov(keynames, (char *) strpos) - keynames)+1;
583
722
 
584
723
  //reading index comments
585
724
  for (keyinfo= share->key_info, i=0; i < keys; i++, keyinfo++)
591
730
                                         keyinfo->comment.length);
592
731
      strpos+= 2 + keyinfo->comment.length;
593
732
    } 
594
 
    assert(test(keyinfo->flags & HA_USES_COMMENT) == 
 
733
    DBUG_ASSERT(test(keyinfo->flags & HA_USES_COMMENT) == 
595
734
               (keyinfo->comment.length > 0));
596
735
  }
597
736
 
598
737
  share->reclength = uint2korr((head+16));
599
 
  share->stored_rec_length= share->reclength;
 
738
  if (*(head+26) == 1)
 
739
    share->system= 1;                           /* one-record-database */
600
740
 
601
741
  record_offset= (ulong) (uint2korr(head+6)+
602
742
                          ((uint2korr(head+14) == 0xffff ?
605
745
  if ((n_length= uint4korr(head+55)))
606
746
  {
607
747
    /* 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))))
 
748
    uchar *next_chunk, *buff_end;
 
749
    DBUG_PRINT("info", ("extra segment size is %u bytes", n_length));
 
750
    if (!(next_chunk= buff= (uchar*) my_malloc(n_length, MYF(MY_WME))))
610
751
      goto err;
611
752
    if (pread(file, buff, n_length, record_offset + share->reclength) == 0)
612
753
    {
624
765
    buff_end= buff + n_length;
625
766
    if (next_chunk + 2 < buff_end)
626
767
    {
627
 
      uint32_t str_db_type_length= uint2korr(next_chunk);
 
768
      uint str_db_type_length= uint2korr(next_chunk);
628
769
      LEX_STRING name;
629
770
      name.str= (char*) next_chunk + 2;
630
771
      name.length= str_db_type_length;
638
779
                plugin_data(tmp_plugin, handlerton *)))
639
780
        {
640
781
          /* bad file, legacy_db_type did not match the name */
641
 
          free(buff);
 
782
          my_free(buff, MYF(0));
642
783
          goto err;
643
784
        }
644
785
        /*
648
789
        */
649
790
        plugin_unlock(NULL, share->db_plugin);
650
791
        share->db_plugin= my_plugin_lock(NULL, &tmp_plugin);
 
792
        DBUG_PRINT("info", ("setting dbtype to '%.*s' (%d)",
 
793
                            str_db_type_length, next_chunk + 2,
 
794
                            ha_legacy_type(share->db_type())));
651
795
      }
652
796
      else if (!tmp_plugin)
653
797
      {
654
798
        /* purecov: begin inspected */
655
799
        error= 8;
656
800
        my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
657
 
        free(buff);
 
801
        my_free(buff, MYF(0));
658
802
        goto err;
659
803
        /* purecov: end */
660
804
      }
661
805
      next_chunk+= str_db_type_length + 2;
662
806
    }
 
807
#if MYSQL_VERSION_ID < 50200
 
808
    if (share->mysql_version >= 50106 && share->mysql_version <= 50109)
 
809
    {
 
810
      /*
 
811
         Partition state array was here in version 5.1.6 to 5.1.9, this code
 
812
         makes it possible to load a 5.1.6 table in later versions. Can most
 
813
         likely be removed at some point in time. Will only be used for
 
814
         upgrades within 5.1 series of versions. Upgrade to 5.2 can only be
 
815
         done from newer 5.1 versions.
 
816
      */
 
817
      next_chunk+= 4;
 
818
    }
 
819
    else
 
820
#endif
663
821
    if (share->mysql_version >= 50110)
664
822
    {
665
823
      /* New auto_partitioned indicator introduced in 5.1.11 */
666
824
      next_chunk++;
667
825
    }
668
 
    if (forminfo[46] == (unsigned char)255)
 
826
    if (forminfo[46] == (uchar)255)
669
827
    {
670
828
      //reading long table comment
671
829
      if (next_chunk + 2 > buff_end)
672
830
      {
673
 
          free(buff);
 
831
          DBUG_PRINT("error",
 
832
                     ("long table comment is not defined in .frm"));
 
833
          my_free(buff, MYF(0));
674
834
          goto err;
675
835
      }
676
836
      share->comment.length = uint2korr(next_chunk);
677
837
      if (! (share->comment.str= strmake_root(&share->mem_root,
678
838
                               (char*)next_chunk + 2, share->comment.length)))
679
839
      {
680
 
          free(buff);
 
840
          my_free(buff, MYF(0));
681
841
          goto err;
682
842
      }
683
843
      next_chunk+= 2 + share->comment.length;
684
844
    }
685
 
    assert(next_chunk <= buff_end);
686
 
    if (share->mysql_version >= DRIZZLE_VERSION_TABLESPACE_IN_FRM_CGE)
 
845
    DBUG_ASSERT (next_chunk <= buff_end);
 
846
    if (share->mysql_version >= MYSQL_VERSION_TABLESPACE_IN_FRM_CGE)
687
847
    {
688
848
      /*
689
849
       New frm format in mysql_version 5.2.5 (originally in
694
854
      */
695
855
      if (next_chunk >= buff_end)
696
856
      {
697
 
        if (share->mysql_version >= DRIZZLE_VERSION_TABLESPACE_IN_FRM)
 
857
        if (share->mysql_version >= MYSQL_VERSION_TABLESPACE_IN_FRM)
698
858
        {
 
859
          DBUG_PRINT("error", ("Found no field extra info"));
699
860
          goto err;
700
861
        }
 
862
        DBUG_PRINT("info", ("Found no field extra info"));
701
863
      }
702
864
      else
703
865
      {
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;
 
866
        DBUG_PRINT("info", ("Found field extra info"));
 
867
        const uint format_section_header_size= 8;
 
868
        uint format_section_len= uint2korr(next_chunk+0);
 
869
        uint flags=              uint4korr(next_chunk+2);
 
870
 
 
871
        share->default_storage_media= (enum ha_storage_media) (flags & 0x7);
 
872
 
 
873
        const char *tablespace= (const char*)next_chunk + format_section_header_size;
 
874
        uint tablespace_len= strlen(tablespace);
 
875
        if (tablespace_len != 0) 
 
876
        {
 
877
          share->tablespace= (char *) alloc_root(&share->mem_root,
 
878
                                                 tablespace_len+1);
 
879
          strxmov(share->tablespace, tablespace, NullS);
 
880
        }
 
881
        else
 
882
          share->tablespace= NULL;
 
883
 
 
884
        field_extra_info= next_chunk + format_section_header_size + tablespace_len + 1;
708
885
        next_chunk+= format_section_len;
709
886
      }
710
887
    }
711
 
    assert (next_chunk <= buff_end);
 
888
    DBUG_ASSERT (next_chunk <= buff_end);
712
889
    if (next_chunk > buff_end)
713
890
    {
 
891
      DBUG_PRINT("error", ("Buffer overflow in field extra info"));
714
892
      goto err;
715
893
    }
716
894
  }
720
898
  extra_rec_buf_length= uint2korr(head+59);
721
899
  rec_buff_length= ALIGN_SIZE(share->reclength + 1 + extra_rec_buf_length);
722
900
  share->rec_buff_length= rec_buff_length;
723
 
  if (!(record= (unsigned char *) alloc_root(&share->mem_root,
 
901
  if (!(record= (uchar *) alloc_root(&share->mem_root,
724
902
                                     rec_buff_length)))
725
903
    goto err;                                   /* purecov: inspected */
726
904
  share->default_values= record;
727
905
  if (pread(file, record, (size_t) share->reclength, record_offset) == 0)
728
906
    goto err;                                   /* purecov: inspected */
729
907
 
730
 
  my_seek(file,pos+288,MY_SEEK_SET,MYF(0));
 
908
  VOID(my_seek(file,pos+288,MY_SEEK_SET,MYF(0)));
731
909
 
732
910
  share->fields= uint2korr(forminfo+258);
733
911
  pos= uint2korr(forminfo+260);                 /* Length of all screens */
737
915
  int_length= uint2korr(forminfo+274);
738
916
  share->null_fields= uint2korr(forminfo+282);
739
917
  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)
 
918
  if (forminfo[46] != (uchar)255)
744
919
  {
745
920
    share->comment.length=  (int) (forminfo[46]);
746
921
    share->comment.str= strmake_root(&share->mem_root, (char*) forminfo+47,
747
922
                                     share->comment.length);
748
923
  }
749
924
 
 
925
  DBUG_PRINT("info",("i_count: %d  i_parts: %d  index: %d  n_length: %d  int_length: %d  com_length: %d", interval_count,interval_parts, share->keys,n_length,int_length, com_length));
750
926
 
751
927
  if (!(field_ptr = (Field **)
752
928
        alloc_root(&share->mem_root,
754
930
                           interval_count*sizeof(TYPELIB)+
755
931
                           (share->fields+interval_parts+
756
932
                            keys+3)*sizeof(char *)+
757
 
                           (n_length+int_length+com_length+
758
 
                               vcol_screen_length)))))
 
933
                           (n_length+int_length+com_length)))))
759
934
    goto err;                                   /* purecov: inspected */
760
935
 
761
936
  share->field= field_ptr;
762
937
  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))
 
938
                      pos+ (uint) (n_length+int_length+com_length));
 
939
  if (read_string(file,(uchar**) &disk_buff,read_length))
766
940
    goto err;                                   /* purecov: inspected */
767
941
  strpos= disk_buff+pos;
768
942
 
771
945
  names= (char*) (interval_array+share->fields+interval_parts+keys+3);
772
946
  if (!interval_count)
773
947
    share->intervals= 0;                        // For better debugging
774
 
  memcpy(names, strpos+(share->fields*field_pack_length),
 
948
  memcpy((char*) names, strpos+(share->fields*field_pack_length),
775
949
         (uint) (n_length+int_length));
776
950
  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);
 
951
  memcpy(comment_pos, disk_buff+read_length-com_length, com_length);
782
952
 
783
953
  fix_type_pointers(&interval_array, &share->fieldnames, 1, &names);
784
954
  if (share->fieldnames.count != share->fields)
793
963
         interval < share->intervals + interval_count;
794
964
         interval++)
795
965
    {
796
 
      uint32_t count= (uint) (interval->count + 1) * sizeof(uint);
797
 
      if (!(interval->type_lengths= (uint32_t *) alloc_root(&share->mem_root,
 
966
      uint count= (uint) (interval->count + 1) * sizeof(uint);
 
967
      if (!(interval->type_lengths= (uint *) alloc_root(&share->mem_root,
798
968
                                                        count)))
799
969
        goto err;
800
970
      for (count= 0; count < interval->count; count++)
817
987
  record= share->default_values-1;              /* Fieldstart = 1 */
818
988
  if (share->null_field_first)
819
989
  {
820
 
    null_flags= null_pos= (unsigned char*) record+1;
 
990
    null_flags= null_pos= (uchar*) record+1;
821
991
    null_bit_pos= (db_create_options & HA_OPTION_PACK_RECORD) ? 0 : 1;
822
992
    /*
823
993
      null_bytes below is only correct under the condition that
826
996
    */
827
997
    share->null_bytes= (share->null_fields + null_bit_pos + 7) / 8;
828
998
  }
 
999
#ifndef WE_WANT_TO_SUPPORT_VERY_OLD_FRM_FILES
 
1000
  else
 
1001
  {
 
1002
    share->null_bytes= (share->null_fields+7)/8;
 
1003
    null_flags= null_pos= (uchar*) (record + 1 +share->reclength -
 
1004
                                    share->null_bytes);
 
1005
    null_bit_pos= 0;
 
1006
  }
 
1007
#endif
829
1008
 
830
1009
  use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
831
1010
  if (use_hash)
836
1015
 
837
1016
  for (i=0 ; i < share->fields; i++, strpos+=field_pack_length, field_ptr++)
838
1017
  {
839
 
    uint32_t pack_flag, interval_nr, unireg_type, recpos, field_length;
840
 
    uint32_t vcol_info_length=0;
 
1018
    uint pack_flag, interval_nr, unireg_type, recpos, field_length;
841
1019
    enum_field_types field_type;
 
1020
    enum ha_storage_media storage_type= HA_SM_DEFAULT;
842
1021
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
843
 
    const CHARSET_INFO *charset= NULL;
 
1022
    CHARSET_INFO *charset=NULL;
844
1023
    LEX_STRING comment;
845
 
    virtual_column_info *vcol_info= NULL;
846
 
    bool fld_is_stored= true;
847
1024
 
848
1025
    if (field_extra_info)
849
1026
    {
850
1027
      char tmp= field_extra_info[i];
 
1028
      storage_type= (enum ha_storage_media)(tmp & STORAGE_TYPE_MASK);
851
1029
      column_format= (enum column_format_type)
852
1030
                    ((tmp >> COLUMN_FORMAT_SHIFT) & COLUMN_FORMAT_MASK);
 
1031
      DBUG_PRINT("info", ("Field extra: storage %u format %u",
 
1032
                          storage_type, column_format));
853
1033
    }
854
1034
    if (new_frm_ver >= 3)
855
1035
    {
859
1039
      pack_flag=    uint2korr(strpos+8);
860
1040
      unireg_type=  (uint) strpos[10];
861
1041
      interval_nr=  (uint) strpos[12];
862
 
      uint32_t comment_length=uint2korr(strpos+15);
 
1042
      uint comment_length=uint2korr(strpos+15);
863
1043
      field_type=(enum_field_types) (uint) strpos[13];
864
1044
 
865
1045
      {
872
1052
          goto err;
873
1053
        }
874
1054
      }
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
1055
      if (!comment_length)
886
1056
      {
887
1057
        comment.str= (char*) "";
893
1063
        comment.length= comment_length;
894
1064
        comment_pos+=   comment_length;
895
1065
      }
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
1066
    }
923
1067
    else
924
1068
    {
951
1095
      }
952
1096
      else
953
1097
        charset= share->table_charset;
954
 
      memset(&comment, 0, sizeof(comment));
 
1098
      bzero((char*) &comment, sizeof(comment));
955
1099
    }
956
1100
 
957
1101
    if (interval_nr && charset->mbminlen > 1)
960
1104
      TYPELIB *interval= share->intervals + interval_nr - 1;
961
1105
      unhex_type2(interval);
962
1106
    }
 
1107
    
 
1108
#ifndef TO_BE_DELETED_ON_PRODUCTION
 
1109
    if (field_type == MYSQL_TYPE_NEWDECIMAL && !share->mysql_version)
 
1110
    {
 
1111
      /*
 
1112
        Fix pack length of old decimal values from 5.0.3 -> 5.0.4
 
1113
        The difference is that in the old version we stored precision
 
1114
        in the .frm table while we now store the display_length
 
1115
      */
 
1116
      uint decimals= f_decimals(pack_flag);
 
1117
      field_length= my_decimal_precision_to_length(field_length,
 
1118
                                                   decimals,
 
1119
                                                   f_is_dec(pack_flag) == 0);
 
1120
      sql_print_error("Found incompatible DECIMAL field '%s' in %s; "
 
1121
                      "Please do \"ALTER TABLE '%s' FORCE\" to fix it!",
 
1122
                      share->fieldnames.type_names[i], share->table_name.str,
 
1123
                      share->table_name.str);
 
1124
      push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
 
1125
                          ER_CRASHED_ON_USAGE,
 
1126
                          "Found incompatible DECIMAL field '%s' in %s; "
 
1127
                          "Please do \"ALTER TABLE '%s' FORCE\" to fix it!",
 
1128
                          share->fieldnames.type_names[i],
 
1129
                          share->table_name.str,
 
1130
                          share->table_name.str);
 
1131
      share->crashed= 1;                        // Marker for CHECK TABLE
 
1132
    }
 
1133
#endif
963
1134
 
964
1135
    *field_ptr= reg_field=
965
1136
      make_field(share, record+recpos,
966
 
                 (uint32_t) field_length,
 
1137
                 (uint32) field_length,
967
1138
                 null_pos, null_bit_pos,
968
1139
                 pack_flag,
969
1140
                 field_type,
979
1150
      goto err;                 /* purecov: inspected */
980
1151
    }
981
1152
 
 
1153
    reg_field->flags|= ((uint)storage_type << FIELD_STORAGE_FLAGS);
982
1154
    reg_field->flags|= ((uint)column_format << COLUMN_FORMAT_FLAGS);
983
1155
    reg_field->field_index= i;
984
1156
    reg_field->comment=comment;
985
 
    reg_field->vcol_info= vcol_info;
986
 
    reg_field->is_stored= fld_is_stored;
 
1157
    if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
 
1158
    {
 
1159
      if ((null_bit_pos+= field_length & 7) > 7)
 
1160
      {
 
1161
        null_pos++;
 
1162
        null_bit_pos-= 8;
 
1163
      }
 
1164
    }
987
1165
    if (!(reg_field->flags & NOT_NULL_FLAG))
988
1166
    {
989
1167
      if (!(null_bit_pos= (null_bit_pos + 1) & 7))
999
1177
 
1000
1178
    if (use_hash)
1001
1179
      (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
 
    }
 
1180
                            (uchar*) field_ptr); // never fail
1009
1181
  }
1010
1182
  *field_ptr=0;                                 // End marker
1011
 
  /* Sanity checks: */
1012
 
  assert(share->fields>=share->stored_fields);
1013
 
  assert(share->reclength>=share->stored_rec_length);
1014
1183
 
1015
1184
  /* Fix key->name and key_part->field */
1016
1185
  if (key_parts)
1017
1186
  {
1018
 
    uint32_t primary_key=(uint) (find_type((char*) primary_key_name,
 
1187
    uint primary_key=(uint) (find_type((char*) primary_key_name,
1019
1188
                                       &share->keynames, 3) - 1);
1020
 
    int64_t ha_option= handler_file->ha_table_flags();
 
1189
    longlong ha_option= handler_file->ha_table_flags();
1021
1190
    keyinfo= share->key_info;
1022
1191
    key_part= keyinfo->key_part;
1023
1192
 
1024
 
    for (uint32_t key=0 ; key < share->keys ; key++,keyinfo++)
 
1193
    for (uint key=0 ; key < share->keys ; key++,keyinfo++)
1025
1194
    {
1026
 
      uint32_t usable_parts= 0;
 
1195
      uint usable_parts= 0;
1027
1196
      keyinfo->name=(char*) share->keynames.type_names[key];
1028
1197
 
1029
1198
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
1035
1204
        primary_key=key;
1036
1205
        for (i=0 ; i < keyinfo->key_parts ;i++)
1037
1206
        {
1038
 
          uint32_t fieldnr= key_part[i].fieldnr;
 
1207
          uint fieldnr= key_part[i].fieldnr;
1039
1208
          if (!fieldnr ||
1040
1209
              share->field[fieldnr-1]->null_ptr ||
1041
1210
              share->field[fieldnr-1]->key_length() !=
1051
1220
      {
1052
1221
        Field *field;
1053
1222
        if (new_field_pack_flag <= 1)
1054
 
          key_part->fieldnr= (uint16_t) find_field(share->field,
 
1223
          key_part->fieldnr= (uint16) find_field(share->field,
1055
1224
                                                 share->default_values,
1056
1225
                                                 (uint) key_part->offset,
1057
1226
                                                 (uint) key_part->length);
1064
1233
        key_part->type= field->key_type();
1065
1234
        if (field->null_ptr)
1066
1235
        {
1067
 
          key_part->null_offset=(uint) ((unsigned char*) field->null_ptr -
 
1236
          key_part->null_offset=(uint) ((uchar*) field->null_ptr -
1068
1237
                                        share->default_values);
1069
1238
          key_part->null_bit= field->null_bit;
1070
1239
          key_part->store_length+=HA_KEY_NULL_LENGTH;
1072
1241
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
1073
1242
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
1074
1243
        }
1075
 
        if (field->type() == DRIZZLE_TYPE_BLOB ||
1076
 
            field->real_type() == DRIZZLE_TYPE_VARCHAR)
 
1244
        if (field->type() == MYSQL_TYPE_BLOB ||
 
1245
            field->real_type() == MYSQL_TYPE_VARCHAR)
1077
1246
        {
1078
 
          if (field->type() == DRIZZLE_TYPE_BLOB)
 
1247
          if (field->type() == MYSQL_TYPE_BLOB)
1079
1248
            key_part->key_part_flag|= HA_BLOB_PART;
1080
1249
          else
1081
1250
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
1082
1251
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
1083
1252
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
1084
1253
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
 
1254
          /*
 
1255
            Mark that there may be many matching values for one key
 
1256
            combination ('a', 'a ', 'a  '...)
 
1257
          */
 
1258
          if (!(field->flags & BINARY_FLAG))
 
1259
            keyinfo->flags|= HA_END_SPACE_KEY;
1085
1260
        }
 
1261
        if (field->type() == MYSQL_TYPE_BIT)
 
1262
          key_part->key_part_flag|= HA_BIT_PART;
 
1263
 
1086
1264
        if (i == 0 && key != primary_key)
1087
1265
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
1088
1266
                           (keyinfo->key_parts == 1)) ?
1121
1299
        }
1122
1300
        if (field->key_length() != key_part->length)
1123
1301
        {
 
1302
#ifndef TO_BE_DELETED_ON_PRODUCTION
 
1303
          if (field->type() == MYSQL_TYPE_NEWDECIMAL)
 
1304
          {
 
1305
            /*
 
1306
              Fix a fatal error in decimal key handling that causes crashes
 
1307
              on Innodb. We fix it by reducing the key length so that
 
1308
              InnoDB never gets a too big key when searching.
 
1309
              This allows the end user to do an ALTER TABLE to fix the
 
1310
              error.
 
1311
            */
 
1312
            keyinfo->key_length-= (key_part->length - field->key_length());
 
1313
            key_part->store_length-= (uint16)(key_part->length -
 
1314
                                              field->key_length());
 
1315
            key_part->length= (uint16)field->key_length();
 
1316
            sql_print_error("Found wrong key definition in %s; "
 
1317
                            "Please do \"ALTER TABLE '%s' FORCE \" to fix it!",
 
1318
                            share->table_name.str,
 
1319
                            share->table_name.str);
 
1320
            push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
 
1321
                                ER_CRASHED_ON_USAGE,
 
1322
                                "Found wrong key definition in %s; "
 
1323
                                "Please do \"ALTER TABLE '%s' FORCE\" to fix "
 
1324
                                "it!",
 
1325
                                share->table_name.str,
 
1326
                                share->table_name.str);
 
1327
            share->crashed= 1;                // Marker for CHECK TABLE
 
1328
            continue;
 
1329
          }
 
1330
#endif
1124
1331
          key_part->key_part_flag|= HA_PART_KEY_SEG;
1125
1332
        }
1126
1333
      }
1161
1368
  }
1162
1369
  else
1163
1370
    share->primary_key= MAX_KEY;
1164
 
  if (disk_buff)
1165
 
    free(disk_buff);
1166
 
  disk_buff= NULL;
 
1371
  x_free((uchar*) disk_buff);
 
1372
  disk_buff=0;
1167
1373
  if (new_field_pack_flag <= 1)
1168
1374
  {
1169
1375
    /* 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), 
 
1376
    uint null_length= (share->null_fields+7)/8;
 
1377
    bfill(share->default_values + (null_flags - (uchar*) record),
1172
1378
          null_length, 255);
1173
1379
  }
1174
1380
 
1192
1398
  if (share->blob_fields)
1193
1399
  {
1194
1400
    Field **ptr;
1195
 
    uint32_t k, *save;
 
1401
    uint k, *save;
1196
1402
 
1197
1403
    /* Store offsets to blob fields to find them fast */
1198
1404
    if (!(share->blob_field= save=
1210
1416
    the correct null_bytes can now be set, since bitfields have been taken
1211
1417
    into account
1212
1418
  */
1213
 
  share->null_bytes= (null_pos - (unsigned char*) null_flags +
 
1419
  share->null_bytes= (null_pos - (uchar*) null_flags +
1214
1420
                      (null_bit_pos + 7) / 8);
1215
1421
  share->last_null_bit_pos= null_bit_pos;
1216
1422
 
1220
1426
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
1221
1427
                                             share->column_bitmap_size)))
1222
1428
    goto err;
1223
 
  bitmap_init(&share->all_set, bitmaps, share->fields, false);
 
1429
  bitmap_init(&share->all_set, bitmaps, share->fields, FALSE);
1224
1430
  bitmap_set_all(&share->all_set);
1225
1431
 
1226
1432
  delete handler_file;
 
1433
#ifndef DBUG_OFF
 
1434
  if (use_hash)
 
1435
    (void) hash_check(&share->name_hash);
 
1436
#endif
1227
1437
  if (buff)
1228
 
    free(buff);
1229
 
  return (0);
 
1438
    my_free(buff, MYF(0));
 
1439
  DBUG_RETURN (0);
1230
1440
 
1231
1441
 err:
1232
1442
  if (buff)
1233
 
    free(buff);
 
1443
    my_free(buff, MYF(0));
1234
1444
  share->error= error;
1235
1445
  share->open_errno= my_errno;
1236
1446
  share->errarg= errarg;
1237
 
  if (disk_buff)
1238
 
    free(disk_buff);
 
1447
  x_free((uchar*) disk_buff);
 
1448
  delete crypted;
1239
1449
  delete handler_file;
1240
1450
  hash_free(&share->name_hash);
1241
1451
 
1242
1452
  open_table_error(share, error, share->open_errno, errarg);
1243
 
  return(error);
 
1453
  DBUG_RETURN(error);
1244
1454
} /* open_binary_frm */
1245
1455
 
1246
1456
 
1247
1457
/*
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
1458
  Open a table based on a TABLE_SHARE
1518
1459
 
1519
1460
  SYNOPSIS
1542
1483
*/
1543
1484
 
1544
1485
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)
 
1486
                          uint db_stat, uint prgflag, uint ha_open_flags,
 
1487
                          TABLE *outparam, open_table_mode open_mode)
1547
1488
{
1548
1489
  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;
 
1490
  uint records, i, bitmap_size;
 
1491
  bool error_reported= FALSE;
 
1492
  uchar *record, *bitmaps;
 
1493
  Field **field_ptr;
 
1494
  DBUG_ENTER("open_table_from_share");
 
1495
  DBUG_PRINT("enter",("name: '%s.%s'  form: 0x%lx, open mode:%s",
 
1496
                      share->db.str,
 
1497
                      share->table_name.str,
 
1498
                      (long) outparam,
 
1499
                      (open_mode == OTM_OPEN)?"open":
 
1500
                      ((open_mode == OTM_CREATE)?"create":"alter")));
1553
1501
 
1554
1502
  /* Parsing of partitioning information from .frm needs thd->lex set up. */
1555
 
  assert(thd->lex->is_lex_started);
 
1503
  DBUG_ASSERT(thd->lex->is_lex_started);
1556
1504
 
1557
1505
  error= 1;
1558
 
  memset(outparam, 0, sizeof(*outparam));
 
1506
  bzero((char*) outparam, sizeof(*outparam));
1559
1507
  outparam->in_use= thd;
1560
1508
  outparam->s= share;
1561
1509
  outparam->db_stat= db_stat;
1579
1527
  }
1580
1528
  else
1581
1529
  {
1582
 
    assert(!db_stat);
 
1530
    DBUG_ASSERT(!db_stat);
1583
1531
  }
1584
1532
 
1585
1533
  error= 4;
1591
1539
  if (prgflag & (READ_ALL+EXTRA_RECORD))
1592
1540
    records++;
1593
1541
 
1594
 
  if (!(record= (unsigned char*) alloc_root(&outparam->mem_root,
 
1542
  if (!(record= (uchar*) alloc_root(&outparam->mem_root,
1595
1543
                                   share->rec_buff_length * records)))
1596
1544
    goto err;                                   /* purecov: inspected */
1597
1545
 
1631
1579
 
1632
1580
  outparam->field= field_ptr;
1633
1581
 
1634
 
  record= (unsigned char*) outparam->record[0]-1;       /* Fieldstart = 1 */
 
1582
  record= (uchar*) outparam->record[0]-1;       /* Fieldstart = 1 */
1635
1583
  if (share->null_field_first)
1636
 
    outparam->null_flags= (unsigned char*) record+1;
 
1584
    outparam->null_flags= (uchar*) record+1;
1637
1585
  else
1638
 
    outparam->null_flags= (unsigned char*) (record+ 1+ share->reclength -
 
1586
    outparam->null_flags= (uchar*) (record+ 1+ share->reclength -
1639
1587
                                    share->null_bytes);
1640
1588
 
1641
1589
  /* Setup copy of fields from share, but use the right alias and record */
1658
1606
  {
1659
1607
    KEY *key_info, *key_info_end;
1660
1608
    KEY_PART_INFO *key_part;
1661
 
    uint32_t n_length;
 
1609
    uint n_length;
1662
1610
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
1663
1611
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
1664
1612
      goto err;
1665
1613
    outparam->key_info= key_info;
1666
 
    key_part= (reinterpret_cast<KEY_PART_INFO*> (key_info+share->keys));
 
1614
    key_part= (my_reinterpret_cast(KEY_PART_INFO*) (key_info+share->keys));
1667
1615
    
1668
1616
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
1669
1617
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
1699
1647
    }
1700
1648
  }
1701
1649
 
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
1650
  /* Allocate bitmaps */
1742
1651
 
1743
1652
  bitmap_size= share->column_bitmap_size;
1744
 
  if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
 
1653
  if (!(bitmaps= (uchar*) alloc_root(&outparam->mem_root, bitmap_size*3)))
1745
1654
    goto err;
1746
1655
  bitmap_init(&outparam->def_read_set,
1747
 
              (my_bitmap_map*) bitmaps, share->fields, false);
 
1656
              (my_bitmap_map*) bitmaps, share->fields, FALSE);
1748
1657
  bitmap_init(&outparam->def_write_set,
1749
 
              (my_bitmap_map*) (bitmaps+bitmap_size), share->fields, false);
 
1658
              (my_bitmap_map*) (bitmaps+bitmap_size), share->fields, FALSE);
1750
1659
  bitmap_init(&outparam->tmp_set,
1751
 
              (my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, false);
 
1660
              (my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, FALSE);
1752
1661
  outparam->default_column_bitmaps();
1753
1662
 
1754
1663
  /* The table struct is now initialized;  Open the table */
1760
1669
                  ha_open(outparam, share->normalized_path.str,
1761
1670
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
1762
1671
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
1763
 
                           (db_stat & HA_WAIT_IF_LOCKED) ?  HA_OPEN_WAIT_IF_LOCKED :
 
1672
                           ((db_stat & HA_WAIT_IF_LOCKED) ||
 
1673
                            (specialflag & SPECIAL_WAIT_IF_LOCKED)) ?
 
1674
                           HA_OPEN_WAIT_IF_LOCKED :
1764
1675
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
1765
1676
                          HA_OPEN_ABORT_IF_LOCKED :
1766
1677
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
1785
1696
            Too many files opened, use same error message as if the .frm
1786
1697
            file can't open
1787
1698
           */
 
1699
          DBUG_PRINT("error", ("open file: %s failed, too many files opened (errno: %d)", 
 
1700
                  share->normalized_path.str, ha_err));
1788
1701
          error= 1;
1789
1702
          my_errno= EMFILE;
1790
1703
          break;
1791
1704
        default:
1792
1705
          outparam->file->print_error(ha_err, MYF(0));
1793
 
          error_reported= true;
 
1706
          error_reported= TRUE;
1794
1707
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
1795
1708
            error= 7;
1796
1709
          break;
1799
1712
    }
1800
1713
  }
1801
1714
 
1802
 
#if defined(HAVE_purify) 
1803
 
  memset(bitmaps, 0, bitmap_size*3);
 
1715
#if defined(HAVE_purify) && !defined(DBUG_OFF)
 
1716
  bzero((char*) bitmaps, bitmap_size*3);
1804
1717
#endif
1805
1718
 
1806
 
  outparam->no_replicate= outparam->file;
 
1719
  outparam->no_replicate= outparam->file &&
 
1720
                          test(outparam->file->ha_table_flags() &
 
1721
                               HA_HAS_OWN_BINLOGGING);
1807
1722
  thd->status_var.opened_tables++;
1808
1723
 
1809
 
  return (0);
 
1724
  DBUG_RETURN (0);
1810
1725
 
1811
1726
 err:
1812
1727
  if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
1814
1729
  delete outparam->file;
1815
1730
  outparam->file= 0;                            // For easier error checking
1816
1731
  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);
 
1732
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on bzero'd root
 
1733
  my_free((char*) outparam->alias, MYF(MY_ALLOW_ZERO_PTR));
 
1734
  DBUG_RETURN (error);
1820
1735
}
1821
1736
 
1822
1737
 
1825
1740
 
1826
1741
  SYNOPSIS
1827
1742
    closefrm()
1828
 
    table               Table object to free
 
1743
    table               TABLE object to free
1829
1744
    free_share          Is 1 if we also want to free table_share
1830
1745
*/
1831
1746
 
1832
 
int closefrm(register Table *table, bool free_share)
 
1747
int closefrm(register TABLE *table, bool free_share)
1833
1748
{
1834
1749
  int error=0;
 
1750
  DBUG_ENTER("closefrm");
 
1751
  DBUG_PRINT("enter", ("table: 0x%lx", (long) table));
1835
1752
 
1836
1753
  if (table->db_stat)
1837
1754
    error=table->file->close();
1838
 
  free((char*) table->alias);
 
1755
  my_free((char*) table->alias, MYF(MY_ALLOW_ZERO_PTR));
1839
1756
  table->alias= 0;
1840
1757
  if (table->field)
1841
1758
  {
1853
1770
      free_table_share(table->s);
1854
1771
  }
1855
1772
  free_root(&table->mem_root, MYF(0));
1856
 
  return(error);
 
1773
  DBUG_RETURN(error);
1857
1774
}
1858
1775
 
1859
1776
 
1860
1777
/* Deallocate temporary blob storage */
1861
1778
 
1862
 
void free_blobs(register Table *table)
 
1779
void free_blobs(register TABLE *table)
1863
1780
{
1864
 
  uint32_t *ptr, *end;
1865
 
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
 
1781
  uint *ptr, *end;
 
1782
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
1866
1783
       ptr != end ;
1867
1784
       ptr++)
1868
1785
    ((Field_blob*) table->field[*ptr])->free();
1870
1787
 
1871
1788
 
1872
1789
        /* Find where a form starts */
1873
 
        /* if formname is NULL then only formnames is read */
 
1790
        /* if formname is NullS then only formnames is read */
1874
1791
 
1875
 
ulong get_form_pos(File file, unsigned char *head, TYPELIB *save_names)
 
1792
ulong get_form_pos(File file, uchar *head, TYPELIB *save_names)
1876
1793
{
1877
 
  uint32_t a_length,names,length;
1878
 
  unsigned char *pos,*buf;
 
1794
  uint a_length,names,length;
 
1795
  uchar *pos,*buf;
1879
1796
  ulong ret_value=0;
 
1797
  DBUG_ENTER("get_form_pos");
1880
1798
 
1881
1799
  names=uint2korr(head+8);
1882
1800
  a_length=(names+2)*sizeof(char *);            /* Room for two extra */
1889
1807
  if (names)
1890
1808
  {
1891
1809
    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,
 
1810
    VOID(my_seek(file,64L,MY_SEEK_SET,MYF(0)));
 
1811
    if (!(buf= (uchar*) my_malloc((size_t) length+a_length+names*4,
1894
1812
                                  MYF(MY_WME))) ||
1895
1813
        my_read(file, buf+a_length, (size_t) (length+names*4),
1896
1814
                MYF(MY_NABP)))
1897
1815
    {                                           /* purecov: inspected */
1898
 
      if (buf)
1899
 
        free(buf);
1900
 
      return(0L);                               /* purecov: inspected */
 
1816
      x_free((uchar*) buf);                     /* purecov: inspected */
 
1817
      DBUG_RETURN(0L);                          /* purecov: inspected */
1901
1818
    }
1902
1819
    pos= buf+a_length+length;
1903
1820
    ret_value=uint4korr(pos);
1905
1822
  if (! save_names)
1906
1823
  {
1907
1824
    if (names)
1908
 
      free((unsigned char*) buf);
 
1825
      my_free((uchar*) buf,MYF(0));
1909
1826
  }
1910
1827
  else if (!names)
1911
 
    memset(save_names, 0, sizeof(save_names));
 
1828
    bzero((char*) save_names,sizeof(save_names));
1912
1829
  else
1913
1830
  {
1914
1831
    char *str;
1915
1832
    str=(char *) (buf+a_length);
1916
1833
    fix_type_pointers((const char ***) &buf,save_names,1,&str);
1917
1834
  }
1918
 
  return(ret_value);
 
1835
  DBUG_RETURN(ret_value);
1919
1836
}
1920
1837
 
1921
1838
 
1926
1843
    We add an \0 at end of the read string to make reading of C strings easier
1927
1844
*/
1928
1845
 
1929
 
int read_string(File file, unsigned char**to, size_t length)
 
1846
int read_string(File file, uchar**to, size_t length)
1930
1847
{
 
1848
  DBUG_ENTER("read_string");
1931
1849
 
1932
 
  if (*to)
1933
 
    free(*to);
1934
 
  if (!(*to= (unsigned char*) my_malloc(length+1,MYF(MY_WME))) ||
 
1850
  x_free(*to);
 
1851
  if (!(*to= (uchar*) my_malloc(length+1,MYF(MY_WME))) ||
1935
1852
      my_read(file, *to, length,MYF(MY_NABP)))
1936
1853
  {
1937
 
    if (*to)
1938
 
      free(*to);
1939
 
    *to= NULL;
1940
 
    return(1);                           /* purecov: inspected */
 
1854
    x_free(*to);                              /* purecov: inspected */
 
1855
    *to= 0;                                   /* purecov: inspected */
 
1856
    DBUG_RETURN(1);                           /* purecov: inspected */
1941
1857
  }
1942
1858
  *((char*) *to+length)= '\0';
1943
 
  return (0);
 
1859
  DBUG_RETURN (0);
1944
1860
} /* read_string */
1945
1861
 
1946
1862
 
1947
1863
        /* Add a new form to a form file */
1948
1864
 
1949
 
ulong make_new_entry(File file, unsigned char *fileinfo, TYPELIB *formnames,
 
1865
ulong make_new_entry(File file, uchar *fileinfo, TYPELIB *formnames,
1950
1866
                     const char *newname)
1951
1867
{
1952
 
  uint32_t i,bufflength,maxlength,n_length,length,names;
 
1868
  uint i,bufflength,maxlength,n_length,length,names;
1953
1869
  ulong endpos,newpos;
1954
 
  unsigned char buff[IO_SIZE];
1955
 
  unsigned char *pos;
 
1870
  uchar buff[IO_SIZE];
 
1871
  uchar *pos;
 
1872
  DBUG_ENTER("make_new_entry");
1956
1873
 
1957
1874
  length=(uint) strlen(newname)+1;
1958
1875
  n_length=uint2korr(fileinfo+4);
1969
1886
 
1970
1887
    while (endpos > maxlength)
1971
1888
    {
1972
 
      my_seek(file,(ulong) (endpos-bufflength),MY_SEEK_SET,MYF(0));
 
1889
      VOID(my_seek(file,(ulong) (endpos-bufflength),MY_SEEK_SET,MYF(0)));
1973
1890
      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));
 
1891
        DBUG_RETURN(0L);
 
1892
      VOID(my_seek(file,(ulong) (endpos-bufflength+IO_SIZE),MY_SEEK_SET,
 
1893
                   MYF(0)));
1977
1894
      if ((my_write(file, buff,bufflength,MYF(MY_NABP+MY_WME))))
1978
 
        return(0);
 
1895
        DBUG_RETURN(0);
1979
1896
      endpos-=bufflength; bufflength=IO_SIZE;
1980
1897
    }
1981
 
    memset(buff, 0, IO_SIZE);                   /* Null new block */
1982
 
    my_seek(file,(ulong) maxlength,MY_SEEK_SET,MYF(0));
 
1898
    bzero(buff,IO_SIZE);                        /* Null new block */
 
1899
    VOID(my_seek(file,(ulong) maxlength,MY_SEEK_SET,MYF(0)));
1983
1900
    if (my_write(file,buff,bufflength,MYF(MY_NABP+MY_WME)))
1984
 
        return(0L);
 
1901
        DBUG_RETURN(0L);
1985
1902
    maxlength+=IO_SIZE;                         /* Fix old ref */
1986
1903
    int2store(fileinfo+6,maxlength);
1987
 
    for (i=names, pos= (unsigned char*) *formnames->type_names+n_length-1; i-- ;
 
1904
    for (i=names, pos= (uchar*) *formnames->type_names+n_length-1; i-- ;
1988
1905
         pos+=4)
1989
1906
    {
1990
1907
      endpos=uint4korr(pos)+IO_SIZE;
1995
1912
  if (n_length == 1 )
1996
1913
  {                                             /* First name */
1997
1914
    length++;
1998
 
    strxmov((char*) buff,"/",newname,"/",NULL);
 
1915
    VOID(strxmov((char*) buff,"/",newname,"/",NullS));
1999
1916
  }
2000
1917
  else
2001
 
    strxmov((char*) buff,newname,"/",NULL); /* purecov: inspected */
2002
 
  my_seek(file,63L+(ulong) n_length,MY_SEEK_SET,MYF(0));
 
1918
    VOID(strxmov((char*) buff,newname,"/",NullS)); /* purecov: inspected */
 
1919
  VOID(my_seek(file,63L+(ulong) n_length,MY_SEEK_SET,MYF(0)));
2003
1920
  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),
 
1921
      (names && my_write(file,(uchar*) (*formnames->type_names+n_length-1),
2005
1922
                         names*4, MYF(MY_NABP+MY_WME))) ||
2006
1923
      my_write(file, fileinfo+10, 4,MYF(MY_NABP+MY_WME)))
2007
 
    return(0L); /* purecov: inspected */
 
1924
    DBUG_RETURN(0L); /* purecov: inspected */
2008
1925
 
2009
1926
  int2store(fileinfo+8,names+1);
2010
1927
  int2store(fileinfo+4,n_length+length);
2011
1928
  (void)ftruncate(file, newpos);/* Append file with '\0' */
2012
 
  return(newpos);
 
1929
  DBUG_RETURN(newpos);
2013
1930
} /* make_new_entry */
2014
1931
 
2015
1932
 
2020
1937
  int err_no;
2021
1938
  char buff[FN_REFLEN];
2022
1939
  myf errortype= ME_ERROR+ME_WAITTANG;
 
1940
  DBUG_ENTER("open_table_error");
2023
1941
 
2024
1942
  switch (error) {
2025
1943
  case 7:
2028
1946
      my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
2029
1947
    else
2030
1948
    {
2031
 
      strxmov(buff, share->normalized_path.str, reg_ext, NULL);
 
1949
      strxmov(buff, share->normalized_path.str, reg_ext, NullS);
2032
1950
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
2033
1951
               errortype, buff, db_errno);
2034
1952
    }
2049
1967
    }
2050
1968
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
2051
1969
      ER_FILE_USED : ER_CANT_OPEN_FILE;
2052
 
    strxmov(buff, share->normalized_path.str, datext, NULL);
 
1970
    strxmov(buff, share->normalized_path.str, datext, NullS);
2053
1971
    my_error(err_no,errortype, buff, db_errno);
2054
1972
    delete file;
2055
1973
    break;
2060
1978
    char tmp[10];
2061
1979
    if (!csname || csname[0] =='?')
2062
1980
    {
2063
 
      snprintf(tmp, sizeof(tmp), "#%d", errarg);
 
1981
      my_snprintf(tmp, sizeof(tmp), "#%d", errarg);
2064
1982
      csname= tmp;
2065
1983
    }
2066
1984
    my_printf_error(ER_UNKNOWN_COLLATION,
2067
 
                    _("Unknown collation '%s' in table '%-.64s' definition"), 
 
1985
                    "Unknown collation '%s' in table '%-.64s' definition", 
2068
1986
                    MYF(0), csname, share->table_name.str);
2069
1987
    break;
2070
1988
  }
2071
1989
  case 6:
2072
 
    strxmov(buff, share->normalized_path.str, reg_ext, NULL);
 
1990
    strxmov(buff, share->normalized_path.str, reg_ext, NullS);
2073
1991
    my_printf_error(ER_NOT_FORM_FILE,
2074
 
                    _("Table '%-.64s' was created with a different version "
2075
 
                    "of MySQL and cannot be read"), 
 
1992
                    "Table '%-.64s' was created with a different version "
 
1993
                    "of MySQL and cannot be read", 
2076
1994
                    MYF(0), buff);
2077
1995
    break;
2078
1996
  case 8:
2079
1997
    break;
2080
1998
  default:                              /* Better wrong error than none */
2081
1999
  case 4:
2082
 
    strxmov(buff, share->normalized_path.str, reg_ext, NULL);
 
2000
    strxmov(buff, share->normalized_path.str, reg_ext, NullS);
2083
2001
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
2084
2002
    break;
2085
2003
  }
2086
 
  return;
 
2004
  DBUG_VOID_RETURN;
2087
2005
} /* open_table_error */
2088
2006
 
2089
2007
 
2094
2012
        */
2095
2013
 
2096
2014
static void
2097
 
fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint32_t types,
 
2015
fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint types,
2098
2016
                  char **names)
2099
2017
{
2100
2018
  char *type_name, *ptr;
2108
2026
 
2109
2027
    if ((chr= *ptr))                    /* Test if empty type */
2110
2028
    {
2111
 
      while ((type_name=strchr(ptr+1,chr)) != NULL)
 
2029
      while ((type_name=strchr(ptr+1,chr)) != NullS)
2112
2030
      {
2113
2031
        *((*array)++) = ptr+1;
2114
2032
        *type_name= '\0';               /* End string */
2120
2038
      ptr++;
2121
2039
    point_to_type->count= (uint) (*array - point_to_type->type_names);
2122
2040
    point_to_type++;
2123
 
    *((*array)++)= NULL;                /* End of type */
 
2041
    *((*array)++)= NullS;               /* End of type */
2124
2042
  }
2125
2043
  *names=ptr;                           /* Update end */
2126
2044
  return;
2134
2052
    return 0;
2135
2053
  result->count=strings.elements;
2136
2054
  result->name="";
2137
 
  uint32_t nbytes= (sizeof(char*) + sizeof(uint)) * (result->count + 1);
 
2055
  uint nbytes= (sizeof(char*) + sizeof(uint)) * (result->count + 1);
2138
2056
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
2139
2057
    return 0;
2140
2058
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
2141
2059
  List_iterator<String> it(strings);
2142
2060
  String *tmp;
2143
 
  for (uint32_t i=0; (tmp=it++) ; i++)
 
2061
  for (uint i=0; (tmp=it++) ; i++)
2144
2062
  {
2145
2063
    result->type_names[i]= tmp->ptr();
2146
2064
    result->type_lengths[i]= tmp->length();
2164
2082
   #  field number +1
2165
2083
*/
2166
2084
 
2167
 
static uint32_t find_field(Field **fields, unsigned char *record, uint32_t start, uint32_t length)
 
2085
static uint find_field(Field **fields, uchar *record, uint start, uint length)
2168
2086
{
2169
2087
  Field **field;
2170
 
  uint32_t i, pos;
 
2088
  uint i, pos;
2171
2089
 
2172
2090
  pos= 0;
2173
2091
  for (field= fields, i=1 ; *field ; i++,field++)
2221
2139
    May fail with some multibyte charsets though.
2222
2140
*/
2223
2141
 
2224
 
void append_unescaped(String *res, const char *pos, uint32_t length)
 
2142
void append_unescaped(String *res, const char *pos, uint length)
2225
2143
{
2226
2144
  const char *end= pos+length;
2227
2145
  res->append('\'');
2228
2146
 
2229
2147
  for (; pos != end ; pos++)
2230
2148
  {
2231
 
#if defined(USE_MB)
2232
 
    uint32_t mblen;
 
2149
#if defined(USE_MB) && MYSQL_VERSION_ID < 40100
 
2150
    uint mblen;
2233
2151
    if (use_mb(default_charset_info) &&
2234
2152
        (mblen= my_ismbchar(default_charset_info, pos, end)))
2235
2153
    {
2272
2190
        /* Create a .frm file */
2273
2191
 
2274
2192
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)
 
2193
                const char *table, uint reclength, uchar *fileinfo,
 
2194
                HA_CREATE_INFO *create_info, uint keys, KEY *key_info)
2277
2195
{
2278
2196
  register File file;
2279
2197
  ulong length;
2280
 
  unsigned char fill[IO_SIZE];
 
2198
  uchar fill[IO_SIZE];
2281
2199
  int create_flags= O_RDWR | O_TRUNC;
2282
2200
  ulong key_comment_total_bytes= 0;
2283
 
  uint32_t i;
 
2201
  uint i;
2284
2202
 
2285
2203
  if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
2286
 
    create_flags|= O_EXCL;
 
2204
    create_flags|= O_EXCL | O_NOFOLLOW;
2287
2205
 
2288
2206
  /* 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;
 
2207
  if (create_info->max_rows > UINT_MAX32)
 
2208
    create_info->max_rows= UINT_MAX32;
 
2209
  if (create_info->min_rows > UINT_MAX32)
 
2210
    create_info->min_rows= UINT_MAX32;
2293
2211
 
2294
2212
  if ((file= my_create(name, CREATE_MODE, create_flags, MYF(0))) >= 0)
2295
2213
  {
2296
 
    uint32_t key_length, tmp_key_length;
2297
 
    uint32_t tmp;
2298
 
    memset(fileinfo, 0, 64);
 
2214
    uint key_length, tmp_key_length;
 
2215
    uint tmp;
 
2216
    bzero((char*) fileinfo,64);
2299
2217
    /* header */
2300
 
    fileinfo[0]=(unsigned char) 254;
 
2218
    fileinfo[0]=(uchar) 254;
2301
2219
    fileinfo[1]= 1;
2302
2220
    fileinfo[2]= FRM_VER+3+ test(create_info->varchar);
2303
2221
 
2304
 
    fileinfo[3]= (unsigned char) ha_legacy_type(
 
2222
    fileinfo[3]= (uchar) ha_legacy_type(
2305
2223
          ha_checktype(thd,ha_legacy_type(create_info->db_type),0,0));
2306
2224
    fileinfo[4]=1;
2307
2225
    int2store(fileinfo+6,IO_SIZE);              /* Next block starts here */
2308
2226
    for (i= 0; i < keys; i++)
2309
2227
    {
2310
 
      assert(test(key_info[i].flags & HA_USES_COMMENT) == 
 
2228
      DBUG_ASSERT(test(key_info[i].flags & HA_USES_COMMENT) == 
2311
2229
                 (key_info[i].comment.length > 0));
2312
2230
      if (key_info[i].flags & HA_USES_COMMENT)
2313
2231
        key_comment_total_bytes += 2 + key_info[i].comment.length;
2345
2263
    int4store(fileinfo+34,create_info->avg_row_length);
2346
2264
    fileinfo[38]= (create_info->default_table_charset ?
2347
2265
                   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 */
 
2266
    fileinfo[39]= (uchar) ((uint) create_info->transactional |
 
2267
                           ((uint) create_info->page_checksum << 2));
 
2268
    fileinfo[40]= (uchar) create_info->row_type;
 
2269
    /* Next few bytes where for RAID support */
2351
2270
    fileinfo[41]= 0;
2352
2271
    fileinfo[42]= 0;
2353
 
    int4store(fileinfo+43,create_info->block_size);
2354
 
 
 
2272
    fileinfo[43]= 0;
2355
2273
    fileinfo[44]= 0;
2356
2274
    fileinfo[45]= 0;
2357
2275
    fileinfo[46]= 0;
2358
2276
    int4store(fileinfo+47, key_length);
2359
 
    tmp= DRIZZLE_VERSION_ID;          // Store to avoid warning from int4store
 
2277
    tmp= MYSQL_VERSION_ID;          // Store to avoid warning from int4store
2360
2278
    int4store(fileinfo+51, tmp);
2361
2279
    int4store(fileinfo+55, create_info->extra_size);
2362
2280
    /*
2364
2282
      61 for default_part_db_type
2365
2283
    */
2366
2284
    int2store(fileinfo+62, create_info->key_block_size);
2367
 
    memset(fill, 0, IO_SIZE);
 
2285
    bzero(fill,IO_SIZE);
2368
2286
    for (; length > IO_SIZE ; length-= IO_SIZE)
2369
2287
    {
2370
2288
      if (my_write(file,fill, IO_SIZE, MYF(MY_WME | MY_NABP)))
2371
2289
      {
2372
 
        my_close(file,MYF(0));
2373
 
        my_delete(name,MYF(0));
 
2290
        VOID(my_close(file,MYF(0)));
 
2291
        VOID(my_delete(name,MYF(0)));
2374
2292
        return(-1);
2375
2293
      }
2376
2294
    }
2385
2303
  return (file);
2386
2304
} /* create_frm */
2387
2305
 
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;
 
2306
 
 
2307
void update_create_info_from_table(HA_CREATE_INFO *create_info, TABLE *table)
 
2308
{
 
2309
  TABLE_SHARE *share= table->s;
 
2310
  DBUG_ENTER("update_create_info_from_table");
 
2311
 
 
2312
  create_info->max_rows= share->max_rows;
 
2313
  create_info->min_rows= share->min_rows;
 
2314
  create_info->table_options= share->db_create_options;
 
2315
  create_info->avg_row_length= share->avg_row_length;
 
2316
  create_info->row_type= share->row_type;
 
2317
  create_info->default_storage_media= share->default_storage_media;
 
2318
  create_info->tablespace= share->tablespace;
 
2319
  create_info->default_table_charset= share->table_charset;
2421
2320
  create_info->table_charset= 0;
2422
 
  create_info->comment= s->comment;
 
2321
  create_info->comment= share->comment;
2423
2322
 
2424
 
  return;
 
2323
  DBUG_VOID_RETURN;
2425
2324
}
2426
2325
 
2427
2326
int
2428
2327
rename_file_ext(const char * from,const char * to,const char * ext)
2429
2328
{
2430
2329
  char from_b[FN_REFLEN],to_b[FN_REFLEN];
2431
 
  strxmov(from_b,from,ext,NULL);
2432
 
  strxmov(to_b,to,ext,NULL);
 
2330
  VOID(strxmov(from_b,from,ext,NullS));
 
2331
  VOID(strxmov(to_b,to,ext,NullS));
2433
2332
  return (my_rename(from_b,to_b,MYF(MY_WME)));
2434
2333
}
2435
2334
 
2452
2351
{
2453
2352
  char buff[MAX_FIELD_WIDTH], *to;
2454
2353
  String str(buff,sizeof(buff),&my_charset_bin);
2455
 
  uint32_t length;
 
2354
  uint length;
2456
2355
 
2457
2356
  field->val_str(&str);
2458
2357
  if (!(length= str.length()))
2476
2375
    field       Field for retrieving of string
2477
2376
 
2478
2377
  RETURN VALUES
2479
 
    NULL  string is empty
 
2378
    NullS  string is empty
2480
2379
    #      pointer to NULL-terminated string value of field
2481
2380
*/
2482
2381
 
2484
2383
{
2485
2384
  char buff[MAX_FIELD_WIDTH], *to;
2486
2385
  String str(buff,sizeof(buff),&my_charset_bin);
2487
 
  uint32_t length;
 
2386
  uint length;
2488
2387
 
2489
2388
  field->val_str(&str);
2490
2389
  length= str.length();
2491
2390
  if (!length || !(to= (char*) alloc_root(mem,length+1)))
2492
 
    return NULL;
 
2391
    return NullS;
2493
2392
  memcpy(to,str.ptr(),(uint) length);
2494
2393
  to[length]=0;
2495
2394
  return to;
2500
2399
    given a buffer with a key value, and a map of keyparts
2501
2400
    that are present in this value, returns the length of the value
2502
2401
*/
2503
 
uint32_t calculate_key_len(Table *table, uint32_t key,
2504
 
                       const unsigned char *buf __attribute__((unused)),
 
2402
uint calculate_key_len(TABLE *table, uint key, const uchar *buf,
2505
2403
                       key_part_map keypart_map)
2506
2404
{
2507
2405
  /* works only with key prefixes */
2508
 
  assert(((keypart_map + 1) & keypart_map) == 0);
 
2406
  DBUG_ASSERT(((keypart_map + 1) & keypart_map) == 0);
2509
2407
 
2510
2408
  KEY *key_info= table->s->key_info+key;
2511
2409
  KEY_PART_INFO *key_part= key_info->key_part;
2512
2410
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
2513
 
  uint32_t length= 0;
 
2411
  uint length= 0;
2514
2412
 
2515
2413
  while (key_part < end_key_part && keypart_map)
2516
2414
  {
2539
2437
bool check_db_name(LEX_STRING *org_name)
2540
2438
{
2541
2439
  char *name= org_name->str;
2542
 
  uint32_t name_length= org_name->length;
 
2440
  uint name_length= org_name->length;
2543
2441
 
2544
2442
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
2545
2443
    return 1;
2558
2456
*/
2559
2457
 
2560
2458
 
2561
 
bool check_table_name(const char *name, uint32_t length)
 
2459
bool check_table_name(const char *name, uint length)
2562
2460
{
2563
2461
  if (!length || length > NAME_LEN || name[length - 1] == ' ')
2564
2462
    return 1;
2576
2474
*/
2577
2475
bool check_column_name(const char *name)
2578
2476
{
2579
 
  uint32_t name_length= 0;  // name length in symbols
2580
 
  bool last_char_is_space= true;
 
2477
  uint name_length= 0;  // name length in symbols
 
2478
  bool last_char_is_space= TRUE;
2581
2479
  
2582
2480
  while (*name)
2583
2481
  {
2605
2503
      This assert is to catch use of this byte if we decide to
2606
2504
      use non-utf8 as system_character_set.
2607
2505
    */
2608
 
    assert(*name != NAMES_SEP_CHAR);
 
2506
    DBUG_ASSERT(*name != NAMES_SEP_CHAR);
2609
2507
    name++;
2610
2508
    name_length++;
2611
2509
  }
2623
2521
  @param[in] table_def         Expected structure of the table (column name
2624
2522
                               and type)
2625
2523
 
2626
 
  @retval  false  OK
 
2524
  @retval  FALSE  OK
2627
2525
  @retval  TRUE   There was an error. An error message is output
2628
2526
                  to the error log.  We do not push an error
2629
2527
                  message into the error stack because this
2631
2529
                  and such errors never reach the user.
2632
2530
*/
2633
2531
 
2634
 
bool
2635
 
Table::table_check_intact(const uint32_t table_f_count,
2636
 
                          const TABLE_FIELD_W_TYPE *table_def)
 
2532
my_bool
 
2533
table_check_intact(TABLE *table, const uint table_f_count,
 
2534
                   const TABLE_FIELD_W_TYPE *table_def)
2637
2535
{
2638
 
  uint32_t i;
2639
 
  bool error= false;
2640
 
  bool fields_diff_count;
 
2536
  uint i;
 
2537
  my_bool error= FALSE;
 
2538
  my_bool fields_diff_count;
 
2539
  DBUG_ENTER("table_check_intact");
 
2540
  DBUG_PRINT("info",("table: %s  expected_count: %d",
 
2541
                     table->alias, table_f_count));
2641
2542
 
2642
 
  fields_diff_count= (s->fields != table_f_count);
 
2543
  fields_diff_count= (table->s->fields != table_f_count);
2643
2544
  if (fields_diff_count)
2644
2545
  {
 
2546
    DBUG_PRINT("info", ("Column count has changed, checking the definition"));
2645
2547
 
2646
2548
    /* previous MySQL version */
2647
 
    if (DRIZZLE_VERSION_ID > s->mysql_version)
 
2549
    if (MYSQL_VERSION_ID > table->s->mysql_version)
2648
2550
    {
2649
2551
      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);
 
2552
                      table->alias, table_f_count, table->s->fields,
 
2553
                      table->s->mysql_version, MYSQL_VERSION_ID);
 
2554
      DBUG_RETURN(TRUE);
2653
2555
    }
2654
 
    else if (DRIZZLE_VERSION_ID == s->mysql_version)
 
2556
    else if (MYSQL_VERSION_ID == table->s->mysql_version)
2655
2557
    {
2656
 
      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), alias,
2657
 
                      table_f_count, s->fields);
2658
 
      return(true);
 
2558
      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), table->alias,
 
2559
                      table_f_count, table->s->fields);
 
2560
      DBUG_RETURN(TRUE);
2659
2561
    }
2660
2562
    /*
2661
2563
      Something has definitely changed, but we're running an older
2670
2572
  {
2671
2573
    String sql_type(buffer, sizeof(buffer), system_charset_info);
2672
2574
    sql_type.length(0);
2673
 
    if (i < s->fields)
 
2575
    if (i < table->s->fields)
2674
2576
    {
2675
 
      Field *field= this->field[i];
 
2577
      Field *field= table->field[i];
2676
2578
 
2677
2579
      if (strncmp(field->field_name, table_def->name.str,
2678
2580
                  table_def->name.length))
2682
2584
          Still this can be a sign of a tampered table, output an error
2683
2585
          to the error log.
2684
2586
        */
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,
 
2587
        sql_print_error("Incorrect definition of table %s.%s: "
 
2588
                        "expected column '%s' at position %d, found '%s'.",
 
2589
                        table->s->db.str, table->alias, table_def->name.str, i,
2688
2590
                        field->field_name);
2689
2591
      }
2690
2592
      field->sql_type(sql_type);
2708
2610
      if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
2709
2611
                  table_def->type.length - 1))
2710
2612
      {
2711
 
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2613
        sql_print_error("Incorrect definition of table %s.%s: "
2712
2614
                        "expected column '%s' at position %d to have type "
2713
 
                        "%s, found type %s."), s->db.str, alias,
 
2615
                        "%s, found type %s.", table->s->db.str, table->alias,
2714
2616
                        table_def->name.str, i, table_def->type.str,
2715
2617
                        sql_type.c_ptr_safe());
2716
 
        error= true;
 
2618
        error= TRUE;
2717
2619
      }
2718
2620
      else if (table_def->cset.str && !field->has_charset())
2719
2621
      {
2720
 
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2622
        sql_print_error("Incorrect definition of table %s.%s: "
2721
2623
                        "expected the type of column '%s' at position %d "
2722
2624
                        "to have character set '%s' but the type has no "
2723
 
                        "character set."), s->db.str, alias,
 
2625
                        "character set.", table->s->db.str, table->alias,
2724
2626
                        table_def->name.str, i, table_def->cset.str);
2725
 
        error= true;
 
2627
        error= TRUE;
2726
2628
      }
2727
2629
      else if (table_def->cset.str &&
2728
2630
               strcmp(field->charset()->csname, table_def->cset.str))
2729
2631
      {
2730
 
        sql_print_error(_("Incorrect definition of table %s.%s: "
 
2632
        sql_print_error("Incorrect definition of table %s.%s: "
2731
2633
                        "expected the type of column '%s' at position %d "
2732
2634
                        "to have character set '%s' but found "
2733
 
                        "character set '%s'."), s->db.str, alias,
 
2635
                        "character set '%s'.", table->s->db.str, table->alias,
2734
2636
                        table_def->name.str, i, table_def->cset.str,
2735
2637
                        field->charset()->csname);
2736
 
        error= true;
 
2638
        error= TRUE;
2737
2639
      }
2738
2640
    }
2739
2641
    else
2740
2642
    {
2741
 
      sql_print_error(_("Incorrect definition of table %s.%s: "
 
2643
      sql_print_error("Incorrect definition of table %s.%s: "
2742
2644
                      "expected column '%s' at position %d to have type %s "
2743
 
                      " but the column is not found."),
2744
 
                      s->db.str, alias,
 
2645
                      " but the column is not found.",
 
2646
                      table->s->db.str, table->alias,
2745
2647
                      table_def->name.str, i, table_def->type.str);
2746
 
      error= true;
 
2648
      error= TRUE;
2747
2649
    }
2748
2650
  }
2749
 
  return(error);
 
2651
  DBUG_RETURN(error);
2750
2652
}
2751
2653
 
2752
2654
 
2754
2656
  Create Item_field for each column in the table.
2755
2657
 
2756
2658
  SYNPOSIS
2757
 
    Table::fill_item_list()
 
2659
    st_table::fill_item_list()
2758
2660
      item_list          a pointer to an empty list used to store items
2759
2661
 
2760
2662
  DESCRIPTION
2767
2669
    1                    out of memory
2768
2670
*/
2769
2671
 
2770
 
bool Table::fill_item_list(List<Item> *item_list) const
 
2672
bool st_table::fill_item_list(List<Item> *item_list) const
2771
2673
{
2772
2674
  /*
2773
2675
    All Item_field's created using a direct pointer to a field
2777
2679
  {
2778
2680
    Item_field *item= new Item_field(*ptr);
2779
2681
    if (!item || item_list->push_back(item))
2780
 
      return true;
 
2682
      return TRUE;
2781
2683
  }
2782
 
  return false;
 
2684
  return FALSE;
2783
2685
}
2784
2686
 
2785
2687
/*
2787
2689
  Fields of this table.
2788
2690
 
2789
2691
  SYNPOSIS
2790
 
    Table::fill_item_list()
 
2692
    st_table::fill_item_list()
2791
2693
      item_list          a non-empty list with Item_fields
2792
2694
 
2793
2695
  DESCRIPTION
2797
2699
    is the same as the number of columns in the table.
2798
2700
*/
2799
2701
 
2800
 
void Table::reset_item_list(List<Item> *item_list) const
 
2702
void st_table::reset_item_list(List<Item> *item_list) const
2801
2703
{
2802
2704
  List_iterator_fast<Item> it(*item_list);
2803
2705
  for (Field **ptr= field; *ptr; ptr++)
2804
2706
  {
2805
2707
    Item_field *item_field= (Item_field*) it++;
2806
 
    assert(item_field != 0);
 
2708
    DBUG_ASSERT(item_field != 0);
2807
2709
    item_field->reset_field(*ptr);
2808
2710
  }
2809
2711
}
2810
2712
 
2811
2713
 
2812
2714
/*
2813
 
  Find underlying base tables (TableList) which represent given
2814
 
  table_to_find (Table)
2815
 
 
2816
 
  SYNOPSIS
2817
 
    TableList::find_underlying_table()
 
2715
  Merge ON expressions for a view
 
2716
 
 
2717
  SYNOPSIS
 
2718
    merge_on_conds()
 
2719
    thd             thread handle
 
2720
    table           table for the VIEW
 
2721
    is_cascaded     TRUE <=> merge ON expressions from underlying views
 
2722
 
 
2723
  DESCRIPTION
 
2724
    This function returns the result of ANDing the ON expressions
 
2725
    of the given view and all underlying views. The ON expressions
 
2726
    of the underlying views are added only if is_cascaded is TRUE.
 
2727
 
 
2728
  RETURN
 
2729
    Pointer to the built expression if there is any.
 
2730
    Otherwise and in the case of a failure NULL is returned.
 
2731
*/
 
2732
 
 
2733
static Item *
 
2734
merge_on_conds(THD *thd, TABLE_LIST *table, bool is_cascaded)
 
2735
{
 
2736
  DBUG_ENTER("merge_on_conds");
 
2737
 
 
2738
  Item *cond= NULL;
 
2739
  DBUG_PRINT("info", ("alias: %s", table->alias));
 
2740
  if (table->on_expr)
 
2741
    cond= table->on_expr->copy_andor_structure(thd);
 
2742
  if (!table->nested_join)
 
2743
    DBUG_RETURN(cond);
 
2744
  List_iterator<TABLE_LIST> li(table->nested_join->join_list);
 
2745
  while (TABLE_LIST *tbl= li++)
 
2746
  {
 
2747
    cond= and_conds(cond, merge_on_conds(thd, tbl, is_cascaded));
 
2748
  }
 
2749
  DBUG_RETURN(cond);
 
2750
}
 
2751
 
 
2752
 
 
2753
/*
 
2754
  Find underlying base tables (TABLE_LIST) which represent given
 
2755
  table_to_find (TABLE)
 
2756
 
 
2757
  SYNOPSIS
 
2758
    TABLE_LIST::find_underlying_table()
2818
2759
    table_to_find table to find
2819
2760
 
2820
2761
  RETURN
2822
2763
    found table reference
2823
2764
*/
2824
2765
 
2825
 
TableList *TableList::find_underlying_table(Table *table_to_find)
 
2766
TABLE_LIST *TABLE_LIST::find_underlying_table(TABLE *table_to_find)
2826
2767
{
2827
2768
  /* is this real table and table which we are looking for? */
2828
2769
  if (table == table_to_find && merge_underlying_list == 0)
2829
2770
    return this;
2830
2771
 
2831
 
  for (TableList *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
 
2772
  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
2832
2773
  {
2833
 
    TableList *result;
 
2774
    TABLE_LIST *result;
2834
2775
    if ((result= tbl->find_underlying_table(table_to_find)))
2835
2776
      return result;
2836
2777
  }
2841
2782
  cleunup items belonged to view fields translation table
2842
2783
 
2843
2784
  SYNOPSIS
2844
 
    TableList::cleanup_items()
 
2785
    TABLE_LIST::cleanup_items()
2845
2786
*/
2846
2787
 
2847
 
void TableList::cleanup_items()
 
2788
void TABLE_LIST::cleanup_items()
2848
2789
{
2849
2790
  if (!field_translation)
2850
2791
    return;
2864
2805
    mem_root   memory pool for allocating
2865
2806
 
2866
2807
  RETURN
2867
 
    false - OK
 
2808
    FALSE - OK
2868
2809
    TRUE  - out of memory
2869
2810
*/
2870
2811
 
2871
 
bool TableList::set_insert_values(MEM_ROOT *mem_root)
 
2812
bool TABLE_LIST::set_insert_values(MEM_ROOT *mem_root)
2872
2813
{
2873
2814
  if (table)
2874
2815
  {
2875
2816
    if (!table->insert_values &&
2876
 
        !(table->insert_values= (unsigned char *)alloc_root(mem_root,
 
2817
        !(table->insert_values= (uchar *)alloc_root(mem_root,
2877
2818
                                                   table->s->rec_buff_length)))
2878
 
      return true;
 
2819
      return TRUE;
2879
2820
  }
2880
2821
 
2881
 
  return false;
 
2822
  return FALSE;
2882
2823
}
2883
2824
 
2884
2825
 
2886
2827
  Test if this is a leaf with respect to name resolution.
2887
2828
 
2888
2829
  SYNOPSIS
2889
 
    TableList::is_leaf_for_name_resolution()
 
2830
    TABLE_LIST::is_leaf_for_name_resolution()
2890
2831
 
2891
2832
  DESCRIPTION
2892
2833
    A table reference is a leaf with respect to name resolution if
2896
2837
    columns.
2897
2838
 
2898
2839
  RETURN
2899
 
    TRUE if a leaf, false otherwise.
 
2840
    TRUE if a leaf, FALSE otherwise.
2900
2841
*/
2901
 
bool TableList::is_leaf_for_name_resolution()
 
2842
bool TABLE_LIST::is_leaf_for_name_resolution()
2902
2843
{
2903
2844
  return (is_natural_join || is_join_columns_complete || !nested_join);
2904
2845
}
2909
2850
  respect to name resolution.
2910
2851
 
2911
2852
  SYNOPSIS
2912
 
    TableList::first_leaf_for_name_resolution()
 
2853
    TABLE_LIST::first_leaf_for_name_resolution()
2913
2854
 
2914
2855
  DESCRIPTION
2915
2856
    Given that 'this' is a nested table reference, recursively walk
2927
2868
    else return 'this'
2928
2869
*/
2929
2870
 
2930
 
TableList *TableList::first_leaf_for_name_resolution()
 
2871
TABLE_LIST *TABLE_LIST::first_leaf_for_name_resolution()
2931
2872
{
2932
 
  TableList *cur_table_ref= NULL;
2933
 
  nested_join_st *cur_nested_join;
 
2873
  TABLE_LIST *cur_table_ref;
 
2874
  NESTED_JOIN *cur_nested_join;
2934
2875
 
2935
2876
  if (is_leaf_for_name_resolution())
2936
2877
    return this;
2937
 
  assert(nested_join);
 
2878
  DBUG_ASSERT(nested_join);
2938
2879
 
2939
2880
  for (cur_nested_join= nested_join;
2940
2881
       cur_nested_join;
2941
2882
       cur_nested_join= cur_table_ref->nested_join)
2942
2883
  {
2943
 
    List_iterator_fast<TableList> it(cur_nested_join->join_list);
 
2884
    List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
2944
2885
    cur_table_ref= it++;
2945
2886
    /*
2946
2887
      If the current nested join is a RIGHT JOIN, the operands in
2950
2891
    */
2951
2892
    if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
2952
2893
    {
2953
 
      TableList *next;
 
2894
      TABLE_LIST *next;
2954
2895
      while ((next= it++))
2955
2896
        cur_table_ref= next;
2956
2897
    }
2966
2907
  respect to name resolution.
2967
2908
 
2968
2909
  SYNOPSIS
2969
 
    TableList::last_leaf_for_name_resolution()
 
2910
    TABLE_LIST::last_leaf_for_name_resolution()
2970
2911
 
2971
2912
  DESCRIPTION
2972
2913
    Given that 'this' is a nested table reference, recursively walk
2984
2925
    - else - 'this'
2985
2926
*/
2986
2927
 
2987
 
TableList *TableList::last_leaf_for_name_resolution()
 
2928
TABLE_LIST *TABLE_LIST::last_leaf_for_name_resolution()
2988
2929
{
2989
 
  TableList *cur_table_ref= this;
2990
 
  nested_join_st *cur_nested_join;
 
2930
  TABLE_LIST *cur_table_ref= this;
 
2931
  NESTED_JOIN *cur_nested_join;
2991
2932
 
2992
2933
  if (is_leaf_for_name_resolution())
2993
2934
    return this;
2994
 
  assert(nested_join);
 
2935
  DBUG_ASSERT(nested_join);
2995
2936
 
2996
2937
  for (cur_nested_join= nested_join;
2997
2938
       cur_nested_join;
3005
2946
    */
3006
2947
    if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
3007
2948
    {
3008
 
      List_iterator_fast<TableList> it(cur_nested_join->join_list);
3009
 
      TableList *next;
 
2949
      List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
 
2950
      TABLE_LIST *next;
3010
2951
      cur_table_ref= it++;
3011
2952
      while ((next= it++))
3012
2953
        cur_table_ref= next;
3018
2959
}
3019
2960
 
3020
2961
 
 
2962
Natural_join_column::Natural_join_column(Field_translator *field_param,
 
2963
                                         TABLE_LIST *tab)
 
2964
{
 
2965
  DBUG_ASSERT(tab->field_translation);
 
2966
  view_field= field_param;
 
2967
  table_field= NULL;
 
2968
  table_ref= tab;
 
2969
  is_common= FALSE;
 
2970
}
 
2971
 
 
2972
 
 
2973
Natural_join_column::Natural_join_column(Field *field_param,
 
2974
                                         TABLE_LIST *tab)
 
2975
{
 
2976
  DBUG_ASSERT(tab->table == field_param->table);
 
2977
  table_field= field_param;
 
2978
  view_field= NULL;
 
2979
  table_ref= tab;
 
2980
  is_common= FALSE;
 
2981
}
 
2982
 
 
2983
 
 
2984
const char *Natural_join_column::name()
 
2985
{
 
2986
  if (view_field)
 
2987
  {
 
2988
    DBUG_ASSERT(table_field == NULL);
 
2989
    return view_field->name;
 
2990
  }
 
2991
 
 
2992
  return table_field->field_name;
 
2993
}
 
2994
 
 
2995
 
 
2996
Item *Natural_join_column::create_item(THD *thd)
 
2997
{
 
2998
  if (view_field)
 
2999
  {
 
3000
    DBUG_ASSERT(table_field == NULL);
 
3001
    return create_view_field(thd, table_ref, &view_field->item,
 
3002
                             view_field->name);
 
3003
  }
 
3004
  return new Item_field(thd, &thd->lex->current_select->context, table_field);
 
3005
}
 
3006
 
 
3007
 
 
3008
Field *Natural_join_column::field()
 
3009
{
 
3010
  if (view_field)
 
3011
  {
 
3012
    DBUG_ASSERT(table_field == NULL);
 
3013
    return NULL;
 
3014
  }
 
3015
  return table_field;
 
3016
}
 
3017
 
 
3018
 
 
3019
const char *Natural_join_column::table_name()
 
3020
{
 
3021
  DBUG_ASSERT(table_ref);
 
3022
  return table_ref->alias;
 
3023
}
 
3024
 
 
3025
 
 
3026
const char *Natural_join_column::db_name()
 
3027
{
 
3028
  /*
 
3029
    Test that TABLE_LIST::db is the same as st_table_share::db to
 
3030
    ensure consistency. An exception are I_S schema tables, which
 
3031
    are inconsistent in this respect.
 
3032
  */
 
3033
  DBUG_ASSERT(!strcmp(table_ref->db,
 
3034
                      table_ref->table->s->db.str) ||
 
3035
              (table_ref->schema_table &&
 
3036
               table_ref->table->s->db.str[0] == 0));
 
3037
  return table_ref->db;
 
3038
}
 
3039
 
 
3040
 
 
3041
void Field_iterator_view::set(TABLE_LIST *table)
 
3042
{
 
3043
  DBUG_ASSERT(table->field_translation);
 
3044
  view= table;
 
3045
  ptr= table->field_translation;
 
3046
  array_end= table->field_translation_end;
 
3047
}
 
3048
 
 
3049
 
 
3050
const char *Field_iterator_table::name()
 
3051
{
 
3052
  return (*ptr)->field_name;
 
3053
}
 
3054
 
 
3055
 
 
3056
Item *Field_iterator_table::create_item(THD *thd)
 
3057
{
 
3058
  SELECT_LEX *select= thd->lex->current_select;
 
3059
 
 
3060
  Item_field *item= new Item_field(thd, &select->context, *ptr);
 
3061
  if (item && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
 
3062
      !thd->lex->in_sum_func && select->cur_pos_in_select_list != UNDEF_POS)
 
3063
  {
 
3064
    select->non_agg_fields.push_back(item);
 
3065
    item->marker= select->cur_pos_in_select_list;
 
3066
  }
 
3067
  return item;
 
3068
}
 
3069
 
 
3070
 
 
3071
const char *Field_iterator_view::name()
 
3072
{
 
3073
  return ptr->name;
 
3074
}
 
3075
 
 
3076
 
 
3077
Item *Field_iterator_view::create_item(THD *thd)
 
3078
{
 
3079
  return create_view_field(thd, view, &ptr->item, ptr->name);
 
3080
}
 
3081
 
 
3082
Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref,
 
3083
                        const char *name)
 
3084
{
 
3085
  DBUG_ENTER("create_view_field");
 
3086
  if (view->schema_table_reformed)
 
3087
  {
 
3088
    Item *field= *field_ref;
 
3089
 
 
3090
    /*
 
3091
      Translation table items are always Item_fields and already fixed
 
3092
      ('mysql_schema_table' function). So we can return directly the
 
3093
      field. This case happens only for 'show & where' commands.
 
3094
    */
 
3095
    DBUG_ASSERT(field && field->fixed);
 
3096
    DBUG_RETURN(field);
 
3097
  }
 
3098
 
 
3099
  DBUG_RETURN(NULL);
 
3100
}
 
3101
 
 
3102
 
 
3103
void Field_iterator_natural_join::set(TABLE_LIST *table_ref)
 
3104
{
 
3105
  DBUG_ASSERT(table_ref->join_columns);
 
3106
  column_ref_it.init(*(table_ref->join_columns));
 
3107
  cur_column_ref= column_ref_it++;
 
3108
}
 
3109
 
 
3110
 
 
3111
void Field_iterator_natural_join::next()
 
3112
{
 
3113
  cur_column_ref= column_ref_it++;
 
3114
  DBUG_ASSERT(!cur_column_ref || ! cur_column_ref->table_field ||
 
3115
              cur_column_ref->table_ref->table ==
 
3116
              cur_column_ref->table_field->table);
 
3117
}
 
3118
 
 
3119
 
 
3120
void Field_iterator_table_ref::set_field_iterator()
 
3121
{
 
3122
  DBUG_ENTER("Field_iterator_table_ref::set_field_iterator");
 
3123
  /*
 
3124
    If the table reference we are iterating over is a natural join, or it is
 
3125
    an operand of a natural join, and TABLE_LIST::join_columns contains all
 
3126
    the columns of the join operand, then we pick the columns from
 
3127
    TABLE_LIST::join_columns, instead of the  orginial container of the
 
3128
    columns of the join operator.
 
3129
  */
 
3130
  if (table_ref->is_join_columns_complete)
 
3131
  {
 
3132
    /* Necesary, but insufficient conditions. */
 
3133
    DBUG_ASSERT(table_ref->is_natural_join ||
 
3134
                table_ref->nested_join ||
 
3135
                table_ref->join_columns &&
 
3136
                /* This is a merge view. */
 
3137
                ((table_ref->field_translation &&
 
3138
                  table_ref->join_columns->elements ==
 
3139
                  (ulong)(table_ref->field_translation_end -
 
3140
                          table_ref->field_translation)) ||
 
3141
                 /* This is stored table or a tmptable view. */
 
3142
                 (!table_ref->field_translation &&
 
3143
                  table_ref->join_columns->elements ==
 
3144
                  table_ref->table->s->fields)));
 
3145
    field_it= &natural_join_it;
 
3146
    DBUG_PRINT("info",("field_it for '%s' is Field_iterator_natural_join",
 
3147
                       table_ref->alias));
 
3148
  }
 
3149
  /* This is a base table or stored view. */
 
3150
  else
 
3151
  {
 
3152
    DBUG_ASSERT(table_ref->table);
 
3153
    field_it= &table_field_it;
 
3154
    DBUG_PRINT("info", ("field_it for '%s' is Field_iterator_table",
 
3155
                        table_ref->alias));
 
3156
  }
 
3157
  field_it->set(table_ref);
 
3158
  DBUG_VOID_RETURN;
 
3159
}
 
3160
 
 
3161
 
 
3162
void Field_iterator_table_ref::set(TABLE_LIST *table)
 
3163
{
 
3164
  DBUG_ASSERT(table);
 
3165
  first_leaf= table->first_leaf_for_name_resolution();
 
3166
  last_leaf=  table->last_leaf_for_name_resolution();
 
3167
  DBUG_ASSERT(first_leaf && last_leaf);
 
3168
  table_ref= first_leaf;
 
3169
  set_field_iterator();
 
3170
}
 
3171
 
 
3172
 
 
3173
void Field_iterator_table_ref::next()
 
3174
{
 
3175
  /* Move to the next field in the current table reference. */
 
3176
  field_it->next();
 
3177
  /*
 
3178
    If all fields of the current table reference are exhausted, move to
 
3179
    the next leaf table reference.
 
3180
  */
 
3181
  if (field_it->end_of_fields() && table_ref != last_leaf)
 
3182
  {
 
3183
    table_ref= table_ref->next_name_resolution_table;
 
3184
    DBUG_ASSERT(table_ref);
 
3185
    set_field_iterator();
 
3186
  }
 
3187
}
 
3188
 
 
3189
 
 
3190
const char *Field_iterator_table_ref::table_name()
 
3191
{
 
3192
  if (table_ref->is_natural_join)
 
3193
    return natural_join_it.column_ref()->table_name();
 
3194
 
 
3195
  DBUG_ASSERT(!strcmp(table_ref->table_name,
 
3196
                      table_ref->table->s->table_name.str));
 
3197
  return table_ref->table_name;
 
3198
}
 
3199
 
 
3200
 
 
3201
const char *Field_iterator_table_ref::db_name()
 
3202
{
 
3203
  if (table_ref->is_natural_join)
 
3204
    return natural_join_it.column_ref()->db_name();
 
3205
 
 
3206
  /*
 
3207
    Test that TABLE_LIST::db is the same as st_table_share::db to
 
3208
    ensure consistency. An exception are I_S schema tables, which
 
3209
    are inconsistent in this respect.
 
3210
  */
 
3211
  DBUG_ASSERT(!strcmp(table_ref->db, table_ref->table->s->db.str) ||
 
3212
              (table_ref->schema_table &&
 
3213
               table_ref->table->s->db.str[0] == 0));
 
3214
 
 
3215
  return table_ref->db;
 
3216
}
 
3217
 
 
3218
 
 
3219
/*
 
3220
  Create new or return existing column reference to a column of a
 
3221
  natural/using join.
 
3222
 
 
3223
  SYNOPSIS
 
3224
    Field_iterator_table_ref::get_or_create_column_ref()
 
3225
    parent_table_ref  the parent table reference over which the
 
3226
                      iterator is iterating
 
3227
 
 
3228
  DESCRIPTION
 
3229
    Create a new natural join column for the current field of the
 
3230
    iterator if no such column was created, or return an already
 
3231
    created natural join column. The former happens for base tables or
 
3232
    views, and the latter for natural/using joins. If a new field is
 
3233
    created, then the field is added to 'parent_table_ref' if it is
 
3234
    given, or to the original table referene of the field if
 
3235
    parent_table_ref == NULL.
 
3236
 
 
3237
  NOTES
 
3238
    This method is designed so that when a Field_iterator_table_ref
 
3239
    walks through the fields of a table reference, all its fields
 
3240
    are created and stored as follows:
 
3241
    - If the table reference being iterated is a stored table, view or
 
3242
      natural/using join, store all natural join columns in a list
 
3243
      attached to that table reference.
 
3244
    - If the table reference being iterated is a nested join that is
 
3245
      not natural/using join, then do not materialize its result
 
3246
      fields. This is OK because for such table references
 
3247
      Field_iterator_table_ref iterates over the fields of the nested
 
3248
      table references (recursively). In this way we avoid the storage
 
3249
      of unnecessay copies of result columns of nested joins.
 
3250
 
 
3251
  RETURN
 
3252
    #     Pointer to a column of a natural join (or its operand)
 
3253
    NULL  No memory to allocate the column
 
3254
*/
 
3255
 
 
3256
Natural_join_column *
 
3257
Field_iterator_table_ref::get_or_create_column_ref(TABLE_LIST *parent_table_ref)
 
3258
{
 
3259
  Natural_join_column *nj_col;
 
3260
  bool is_created= TRUE;
 
3261
  uint field_count;
 
3262
  TABLE_LIST *add_table_ref= parent_table_ref ?
 
3263
                             parent_table_ref : table_ref;
 
3264
 
 
3265
  if (field_it == &table_field_it)
 
3266
  {
 
3267
    /* The field belongs to a stored table. */
 
3268
    Field *tmp_field= table_field_it.field();
 
3269
    nj_col= new Natural_join_column(tmp_field, table_ref);
 
3270
    field_count= table_ref->table->s->fields;
 
3271
  }
 
3272
  else if (field_it == &view_field_it)
 
3273
  {
 
3274
    /* The field belongs to a merge view or information schema table. */
 
3275
    Field_translator *translated_field= view_field_it.field_translator();
 
3276
    nj_col= new Natural_join_column(translated_field, table_ref);
 
3277
    field_count= table_ref->field_translation_end -
 
3278
                 table_ref->field_translation;
 
3279
  }
 
3280
  else
 
3281
  {
 
3282
    /*
 
3283
      The field belongs to a NATURAL join, therefore the column reference was
 
3284
      already created via one of the two constructor calls above. In this case
 
3285
      we just return the already created column reference.
 
3286
    */
 
3287
    DBUG_ASSERT(table_ref->is_join_columns_complete);
 
3288
    is_created= FALSE;
 
3289
    nj_col= natural_join_it.column_ref();
 
3290
    DBUG_ASSERT(nj_col);
 
3291
  }
 
3292
  DBUG_ASSERT(!nj_col->table_field ||
 
3293
              nj_col->table_ref->table == nj_col->table_field->table);
 
3294
 
 
3295
  /*
 
3296
    If the natural join column was just created add it to the list of
 
3297
    natural join columns of either 'parent_table_ref' or to the table
 
3298
    reference that directly contains the original field.
 
3299
  */
 
3300
  if (is_created)
 
3301
  {
 
3302
    /* Make sure not all columns were materialized. */
 
3303
    DBUG_ASSERT(!add_table_ref->is_join_columns_complete);
 
3304
    if (!add_table_ref->join_columns)
 
3305
    {
 
3306
      /* Create a list of natural join columns on demand. */
 
3307
      if (!(add_table_ref->join_columns= new List<Natural_join_column>))
 
3308
        return NULL;
 
3309
      add_table_ref->is_join_columns_complete= FALSE;
 
3310
    }
 
3311
    add_table_ref->join_columns->push_back(nj_col);
 
3312
    /*
 
3313
      If new fields are added to their original table reference, mark if
 
3314
      all fields were added. We do it here as the caller has no easy way
 
3315
      of knowing when to do it.
 
3316
      If the fields are being added to parent_table_ref, then the caller
 
3317
      must take care to mark when all fields are created/added.
 
3318
    */
 
3319
    if (!parent_table_ref &&
 
3320
        add_table_ref->join_columns->elements == field_count)
 
3321
      add_table_ref->is_join_columns_complete= TRUE;
 
3322
  }
 
3323
 
 
3324
  return nj_col;
 
3325
}
 
3326
 
 
3327
 
 
3328
/*
 
3329
  Return an existing reference to a column of a natural/using join.
 
3330
 
 
3331
  SYNOPSIS
 
3332
    Field_iterator_table_ref::get_natural_column_ref()
 
3333
 
 
3334
  DESCRIPTION
 
3335
    The method should be called in contexts where it is expected that
 
3336
    all natural join columns are already created, and that the column
 
3337
    being retrieved is a Natural_join_column.
 
3338
 
 
3339
  RETURN
 
3340
    #     Pointer to a column of a natural join (or its operand)
 
3341
    NULL  No memory to allocate the column
 
3342
*/
 
3343
 
 
3344
Natural_join_column *
 
3345
Field_iterator_table_ref::get_natural_column_ref()
 
3346
{
 
3347
  Natural_join_column *nj_col;
 
3348
 
 
3349
  DBUG_ASSERT(field_it == &natural_join_it);
 
3350
  /*
 
3351
    The field belongs to a NATURAL join, therefore the column reference was
 
3352
    already created via one of the two constructor calls above. In this case
 
3353
    we just return the already created column reference.
 
3354
  */
 
3355
  nj_col= natural_join_it.column_ref();
 
3356
  DBUG_ASSERT(nj_col &&
 
3357
              (!nj_col->table_field ||
 
3358
               nj_col->table_ref->table == nj_col->table_field->table));
 
3359
  return nj_col;
 
3360
}
 
3361
 
3021
3362
/*****************************************************************************
3022
3363
  Functions to handle column usage bitmaps (read_set, write_set etc...)
3023
3364
*****************************************************************************/
3024
3365
 
3025
3366
/* Reset all columns bitmaps */
3026
3367
 
3027
 
void Table::clear_column_bitmaps()
 
3368
void st_table::clear_column_bitmaps()
3028
3369
{
3029
3370
  /*
3030
3371
    Reset column read/write usage. It's identical to:
3031
3372
    bitmap_clear_all(&table->def_read_set);
3032
3373
    bitmap_clear_all(&table->def_write_set);
3033
3374
  */
3034
 
  memset(def_read_set.bitmap, 0, s->column_bitmap_size*2);
 
3375
  bzero((char*) def_read_set.bitmap, s->column_bitmap_size*2);
3035
3376
  column_bitmaps_set(&def_read_set, &def_write_set);
3036
3377
}
3037
3378
 
3045
3386
  key fields.
3046
3387
*/
3047
3388
 
3048
 
void Table::prepare_for_position()
 
3389
void st_table::prepare_for_position()
3049
3390
{
 
3391
  DBUG_ENTER("st_table::prepare_for_position");
3050
3392
 
3051
3393
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
3052
3394
      s->primary_key < MAX_KEY)
3055
3397
    /* signal change */
3056
3398
    file->column_bitmaps_signal();
3057
3399
  }
3058
 
  return;
 
3400
  DBUG_VOID_RETURN;
3059
3401
}
3060
3402
 
3061
3403
 
3065
3407
  NOTE:
3066
3408
    This changes the bitmap to use the tmp bitmap
3067
3409
    After this, you can't access any other columns in the table until
3068
 
    bitmaps are reset, for example with Table::clear_column_bitmaps()
3069
 
    or Table::restore_column_maps_after_mark_index()
 
3410
    bitmaps are reset, for example with st_table::clear_column_bitmaps()
 
3411
    or st_table::restore_column_maps_after_mark_index()
3070
3412
*/
3071
3413
 
3072
 
void Table::mark_columns_used_by_index(uint32_t index)
 
3414
void st_table::mark_columns_used_by_index(uint index)
3073
3415
{
3074
3416
  MY_BITMAP *bitmap= &tmp_set;
 
3417
  DBUG_ENTER("st_table::mark_columns_used_by_index");
3075
3418
 
3076
3419
  (void) file->extra(HA_EXTRA_KEYREAD);
3077
3420
  bitmap_clear_all(bitmap);
3078
3421
  mark_columns_used_by_index_no_reset(index, bitmap);
3079
3422
  column_bitmaps_set(bitmap, bitmap);
3080
 
  return;
 
3423
  DBUG_VOID_RETURN;
3081
3424
}
3082
3425
 
3083
3426
 
3092
3435
    when calling mark_columns_used_by_index
3093
3436
*/
3094
3437
 
3095
 
void Table::restore_column_maps_after_mark_index()
 
3438
void st_table::restore_column_maps_after_mark_index()
3096
3439
{
 
3440
  DBUG_ENTER("st_table::restore_column_maps_after_mark_index");
3097
3441
 
3098
3442
  key_read= 0;
3099
3443
  (void) file->extra(HA_EXTRA_NO_KEYREAD);
3100
3444
  default_column_bitmaps();
3101
3445
  file->column_bitmaps_signal();
3102
 
  return;
 
3446
  DBUG_VOID_RETURN;
3103
3447
}
3104
3448
 
3105
3449
 
3107
3451
  mark columns used by key, but don't reset other fields
3108
3452
*/
3109
3453
 
3110
 
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
 
3454
void st_table::mark_columns_used_by_index_no_reset(uint index,
3111
3455
                                                   MY_BITMAP *bitmap)
3112
3456
{
3113
3457
  KEY_PART_INFO *key_part= key_info[index].key_part;
3114
3458
  KEY_PART_INFO *key_part_end= (key_part +
3115
3459
                                key_info[index].key_parts);
3116
3460
  for (;key_part != key_part_end; key_part++)
3117
 
  {
3118
3461
    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);
3124
 
  }
3125
3462
}
3126
3463
 
3127
3464
 
3133
3470
    always set and sometimes read.
3134
3471
*/
3135
3472
 
3136
 
void Table::mark_auto_increment_column()
 
3473
void st_table::mark_auto_increment_column()
3137
3474
{
3138
 
  assert(found_next_number_field);
 
3475
  DBUG_ASSERT(found_next_number_field);
3139
3476
  /*
3140
3477
    We must set bit in read set as update_auto_increment() is using the
3141
3478
    store() to check overflow of auto_increment values
3166
3503
    retrieve the row again.
3167
3504
*/
3168
3505
 
3169
 
void Table::mark_columns_needed_for_delete()
 
3506
void st_table::mark_columns_needed_for_delete()
3170
3507
{
3171
3508
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
3172
3509
  {
3216
3553
    retrieve the row again.
3217
3554
*/
3218
3555
 
3219
 
void Table::mark_columns_needed_for_update()
 
3556
void st_table::mark_columns_needed_for_update()
3220
3557
{
 
3558
  DBUG_ENTER("mark_columns_needed_for_update");
3221
3559
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
3222
3560
  {
3223
3561
    /* Mark all used key columns for read */
3247
3585
      file->column_bitmaps_signal();
3248
3586
    }
3249
3587
  }
3250
 
  /* Mark all virtual columns as writable */
3251
 
  mark_virtual_columns();
3252
 
  return;
 
3588
  DBUG_VOID_RETURN;
3253
3589
}
3254
3590
 
3255
3591
 
3260
3596
  as changed.
3261
3597
*/
3262
3598
 
3263
 
void Table::mark_columns_needed_for_insert()
 
3599
void st_table::mark_columns_needed_for_insert()
3264
3600
{
3265
3601
  if (found_next_number_field)
3266
3602
    mark_auto_increment_column();
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
 
 
 
3603
}
3303
3604
 
3304
3605
/*
3305
3606
  Cleanup this table for re-execution.
3306
3607
 
3307
3608
  SYNOPSIS
3308
 
    TableList::reinit_before_use()
 
3609
    TABLE_LIST::reinit_before_use()
3309
3610
*/
3310
3611
 
3311
 
void TableList::reinit_before_use(THD *thd)
 
3612
void TABLE_LIST::reinit_before_use(THD *thd)
3312
3613
{
3313
3614
  /*
3314
3615
    Reset old pointers to TABLEs: they are not valid since the tables
3318
3619
  /* Reset is_schema_table_processed value(needed for I_S tables */
3319
3620
  schema_table_state= NOT_PROCESSED;
3320
3621
 
3321
 
  TableList *embedded; /* The table at the current level of nesting. */
3322
 
  TableList *parent_embedding= this; /* The parent nested table reference. */
 
3622
  TABLE_LIST *embedded; /* The table at the current level of nesting. */
 
3623
  TABLE_LIST *parent_embedding= this; /* The parent nested table reference. */
3323
3624
  do
3324
3625
  {
3325
3626
    embedded= parent_embedding;
3335
3636
  Return subselect that contains the FROM list this table is taken from
3336
3637
 
3337
3638
  SYNOPSIS
3338
 
    TableList::containing_subselect()
 
3639
    TABLE_LIST::containing_subselect()
3339
3640
 
3340
3641
  RETURN
3341
3642
    Subselect item for the subquery that contains the FROM list
3344
3645
 
3345
3646
*/
3346
3647
 
3347
 
Item_subselect *TableList::containing_subselect()
 
3648
Item_subselect *TABLE_LIST::containing_subselect()
3348
3649
{    
3349
3650
  return (select_lex ? select_lex->master_unit()->item : 0);
3350
3651
}
3354
3655
 
3355
3656
  SYNOPSIS
3356
3657
    process_index_hints()
3357
 
      table         the Table to operate on.
 
3658
      table         the TABLE to operate on.
3358
3659
 
3359
3660
  DESCRIPTION
3360
3661
    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.
 
3662
    (TABLE_LIST::index_hints). Using the information in this tagged list
 
3663
    this function sets the members st_table::keys_in_use_for_query, 
 
3664
    st_table::keys_in_use_for_group_by, st_table::keys_in_use_for_order_by,
 
3665
    st_table::force_index and st_table::covering_keys.
3365
3666
 
3366
3667
    Current implementation of the runtime does not allow mixing FORCE INDEX
3367
3668
    and USE INDEX, so this is checked here. Then the FORCE INDEX list 
3393
3694
    as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
3394
3695
 
3395
3696
    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.
 
3697
    IGNORE INDEX FOR GROUP/ORDER, and this index is used for the JOIN part, 
 
3698
    then we have to ignore the IGNORE INDEX FROM GROUP/ORDER.
3398
3699
 
3399
3700
  RETURN VALUE
3400
 
    false                no errors found
 
3701
    FALSE                no errors found
3401
3702
    TRUE                 found and reported an error.
3402
3703
*/
3403
 
bool TableList::process_index_hints(Table *tbl)
 
3704
bool TABLE_LIST::process_index_hints(TABLE *tbl)
3404
3705
{
3405
3706
  /* initialize the result variables */
3406
3707
  tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by= 
3414
3715
    key_map index_group[INDEX_HINT_FORCE + 1];
3415
3716
    Index_hint *hint;
3416
3717
    int type;
3417
 
    bool have_empty_use_join= false, have_empty_use_order= false, 
3418
 
         have_empty_use_group= false;
 
3718
    bool have_empty_use_join= FALSE, have_empty_use_order= FALSE, 
 
3719
         have_empty_use_group= FALSE;
3419
3720
    List_iterator <Index_hint> iter(*index_hints);
3420
3721
 
3421
3722
    /* initialize temporary variables used to collect hints of each kind */
3429
3730
    /* iterate over the hints list */
3430
3731
    while ((hint= iter++))
3431
3732
    {
3432
 
      uint32_t pos;
 
3733
      uint pos;
3433
3734
 
3434
3735
      /* process empty USE INDEX () */
3435
3736
      if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
3437
3738
        if (hint->clause & INDEX_HINT_MASK_JOIN)
3438
3739
        {
3439
3740
          index_join[hint->type].clear_all();
3440
 
          have_empty_use_join= true;
 
3741
          have_empty_use_join= TRUE;
3441
3742
        }
3442
3743
        if (hint->clause & INDEX_HINT_MASK_ORDER)
3443
3744
        {
3444
3745
          index_order[hint->type].clear_all();
3445
 
          have_empty_use_order= true;
 
3746
          have_empty_use_order= TRUE;
3446
3747
        }
3447
3748
        if (hint->clause & INDEX_HINT_MASK_GROUP)
3448
3749
        {
3449
3750
          index_group[hint->type].clear_all();
3450
 
          have_empty_use_group= true;
 
3751
          have_empty_use_group= TRUE;
3451
3752
        }
3452
3753
        continue;
3453
3754
      }
3493
3794
        !index_order[INDEX_HINT_FORCE].is_clear_all() ||
3494
3795
        !index_group[INDEX_HINT_FORCE].is_clear_all())
3495
3796
    {
3496
 
      tbl->force_index= true;
 
3797
      tbl->force_index= TRUE;
3497
3798
      index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
3498
3799
      index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
3499
3800
      index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
3519
3820
}
3520
3821
 
3521
3822
 
3522
 
size_t Table::max_row_length(const unsigned char *data)
 
3823
size_t max_row_length(TABLE *table, const uchar *data)
3523
3824
{
3524
 
  size_t length= getRecordLength() + 2 * sizeFields();
3525
 
  uint32_t *const beg= getBlobField();
3526
 
  uint32_t *const end= beg + sizeBlobFields();
 
3825
  TABLE_SHARE *table_s= table->s;
 
3826
  size_t length= table_s->reclength + 2 * table_s->fields;
 
3827
  uint *const beg= table_s->blob_field;
 
3828
  uint *const end= beg + table_s->blob_fields;
3527
3829
 
3528
 
  for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
 
3830
  for (uint *ptr= beg ; ptr != end ; ++ptr)
3529
3831
  {
3530
 
    Field_blob* const blob= (Field_blob*) field[*ptr];
3531
 
    length+= blob->get_length((const unsigned char*)
3532
 
                              (data + blob->offset(record[0]))) +
 
3832
    Field_blob* const blob= (Field_blob*) table->field[*ptr];
 
3833
    length+= blob->get_length((const uchar*)
 
3834
                              (data + blob->offset(table->record[0]))) +
3533
3835
      HA_KEY_BLOB_LENGTH;
3534
3836
  }
3535
3837
  return length;
3543
3845
  path        path to file
3544
3846
 
3545
3847
  RETURN
3546
 
  false       error
3547
 
  true       table
3548
 
*/
 
3848
  FRMTYPE_ERROR       error                
 
3849
  FRMTYPE_TABLE       table                
 
3850
 */    
3549
3851
 
3550
 
bool mysql_frm_type(THD *thd __attribute__((unused)),
3551
 
                    char *path, enum legacy_db_type *dbt)
3552
 
{
 
3852
frm_type_enum mysql_frm_type(THD *thd, char *path, enum legacy_db_type *dbt)
 
3853
{   
3553
3854
  File file;
3554
 
  unsigned char header[10];     /* This should be optimized */
 
3855
  uchar header[10];     /* This should be optimized */
3555
3856
  int error;
 
3857
  DBUG_ENTER("mysql_frm_type");
3556
3858
 
3557
3859
  *dbt= DB_TYPE_UNKNOWN;
3558
3860
 
3559
 
  if ((file= open(path, O_RDONLY)) < 0)
3560
 
    return false;
3561
 
  error= my_read(file, (unsigned char*) header, sizeof(header), MYF(MY_NABP));
 
3861
  if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
 
3862
    DBUG_RETURN(FRMTYPE_ERROR);
 
3863
  error= my_read(file, (uchar*) header, sizeof(header), MYF(MY_NABP));
3562
3864
  my_close(file, MYF(MY_WME));
3563
3865
 
3564
3866
  if (error)
3565
 
    return false;
 
3867
    DBUG_RETURN(FRMTYPE_ERROR);
3566
3868
 
3567
3869
  /*  
3568
3870
    This is just a check for DB_TYPE. We'll return default unknown type
3569
3871
    if the following test is true (arg #3). This should not have effect
3570
3872
    on return value from this function (default FRMTYPE_TABLE)
3571
3873
   */  
3572
 
  if (header[0] != (unsigned char) 254 || header[1] != 1 ||
 
3874
  if (header[0] != (uchar) 254 || header[1] != 1 ||
3573
3875
      (header[2] != FRM_VER && header[2] != FRM_VER+1 &&
3574
3876
       (header[2] < FRM_VER+3 || header[2] > FRM_VER+4)))
3575
 
    return true;
 
3877
    DBUG_RETURN(FRMTYPE_TABLE);
3576
3878
 
3577
3879
  *dbt= (enum legacy_db_type) (uint) *(header + 3);
3578
 
  return true;                   // Is probably a .frm table
3579
 
}
3580
 
 
3581
 
/****************************************************************************
3582
 
 Functions for creating temporary tables.
3583
 
****************************************************************************/
3584
 
 
3585
 
 
3586
 
/* Prototypes */
3587
 
void free_tmp_table(THD *thd, Table *entry);
3588
 
 
3589
 
/**
3590
 
  Create field for temporary table from given field.
3591
 
 
3592
 
  @param thd           Thread handler
3593
 
  @param org_field    field from which new field will be created
3594
 
  @param name         New field name
3595
 
  @param table         Temporary table
3596
 
  @param item          !=NULL if item->result_field should point to new field.
3597
 
                      This is relevant for how fill_record() is going to work:
3598
 
                      If item != NULL then fill_record() will update
3599
 
                      the record in the original table.
3600
 
                      If item == NULL then fill_record() will update
3601
 
                      the temporary table
3602
 
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
3603
 
                               field instead of blob.
3604
 
 
3605
 
  @retval
3606
 
    NULL                on error
3607
 
  @retval
3608
 
    new_created field
3609
 
*/
3610
 
 
3611
 
Field *create_tmp_field_from_field(THD *thd, Field *org_field,
3612
 
                                   const char *name, Table *table,
3613
 
                                   Item_field *item, uint32_t convert_blob_length)
3614
 
{
3615
 
  Field *new_field;
3616
 
 
3617
 
  /* 
3618
 
    Make sure that the blob fits into a Field_varstring which has 
3619
 
    2-byte lenght. 
3620
 
  */
3621
 
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
3622
 
      (org_field->flags & BLOB_FLAG))
3623
 
    new_field= new Field_varstring(convert_blob_length,
3624
 
                                   org_field->maybe_null(),
3625
 
                                   org_field->field_name, table->s,
3626
 
                                   org_field->charset());
3627
 
  else
3628
 
    new_field= org_field->new_field(thd->mem_root, table,
3629
 
                                    table == org_field->table);
3630
 
  if (new_field)
3631
 
  {
3632
 
    new_field->init(table);
3633
 
    new_field->orig_table= org_field->orig_table;
3634
 
    if (item)
3635
 
      item->result_field= new_field;
3636
 
    else
3637
 
      new_field->field_name= name;
3638
 
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
3639
 
    if (org_field->maybe_null() || (item && item->maybe_null))
3640
 
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
3641
 
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
3642
 
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
3643
 
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
3644
 
      ((Field_double *) new_field)->not_fixed= true;
3645
 
  }
3646
 
  return new_field;
3647
 
}
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
 
}
3941
 
 
3942
 
/**
3943
 
  Create a temp table according to a field list.
3944
 
 
3945
 
  Given field pointers are changed to point at tmp_table for
3946
 
  send_fields. The table object is self contained: it's
3947
 
  allocated in its own memory root, as well as Field objects
3948
 
  created for table columns.
3949
 
  This function will replace Item_sum items in 'fields' list with
3950
 
  corresponding Item_field items, pointing at the fields in the
3951
 
  temporary table, unless this was prohibited by true
3952
 
  value of argument save_sum_fields. The Item_field objects
3953
 
  are created in THD memory root.
3954
 
 
3955
 
  @param thd                  thread handle
3956
 
  @param param                a description used as input to create the table
3957
 
  @param fields               list of items that will be used to define
3958
 
                              column types of the table (also see NOTES)
3959
 
  @param group                TODO document
3960
 
  @param distinct             should table rows be distinct
3961
 
  @param save_sum_fields      see NOTES
3962
 
  @param select_options
3963
 
  @param rows_limit
3964
 
  @param table_alias          possible name of the temporary table that can
3965
 
                              be used for name resolving; can be "".
3966
 
*/
3967
 
 
3968
 
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
3969
 
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
3970
 
#define RATIO_TO_PACK_ROWS             2
3971
 
#define MIN_STRING_LENGTH_TO_PACK_ROWS   10
3972
 
 
3973
 
Table *
3974
 
create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
3975
 
                 order_st *group, bool distinct, bool save_sum_fields,
3976
 
                 uint64_t select_options, ha_rows rows_limit,
3977
 
                 char *table_alias)
3978
 
{
3979
 
  MEM_ROOT *mem_root_save, own_root;
3980
 
  Table *table;
3981
 
  TABLE_SHARE *share;
3982
 
  uint  i,field_count,null_count,null_pack_length;
3983
 
  uint32_t  copy_func_count= param->func_count;
3984
 
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
3985
 
  uint32_t  blob_count,group_null_items, string_count;
3986
 
  uint32_t  temp_pool_slot=MY_BIT_NONE;
3987
 
  uint32_t fieldnr= 0;
3988
 
  ulong reclength, string_total_length;
3989
 
  bool  using_unique_constraint= 0;
3990
 
  bool  use_packed_rows= 0;
3991
 
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
3992
 
  char  *tmpname,path[FN_REFLEN];
3993
 
  unsigned char *pos, *group_buff, *bitmaps;
3994
 
  unsigned char *null_flags;
3995
 
  Field **reg_field, **from_field, **default_field;
3996
 
  uint32_t *blob_field;
3997
 
  Copy_field *copy=0;
3998
 
  KEY *keyinfo;
3999
 
  KEY_PART_INFO *key_part_info;
4000
 
  Item **copy_func;
4001
 
  MI_COLUMNDEF *recinfo;
4002
 
  uint32_t total_uneven_bit_length= 0;
4003
 
  bool force_copy_fields= param->force_copy_fields;
4004
 
 
4005
 
  status_var_increment(thd->status_var.created_tmp_tables);
4006
 
 
4007
 
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
4008
 
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
4009
 
 
4010
 
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
4011
 
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
4012
 
            current_pid, temp_pool_slot);
4013
 
  else
4014
 
  {
4015
 
    /* if we run out of slots or we are not using tempool */
4016
 
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
4017
 
            thd->thread_id, thd->tmp_table++);
4018
 
  }
4019
 
 
4020
 
  /*
4021
 
    No need to change table name to lower case as we are only creating
4022
 
    MyISAM or HEAP tables here
4023
 
  */
4024
 
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
4025
 
 
4026
 
 
4027
 
  if (group)
4028
 
  {
4029
 
    if (!param->quick_group)
4030
 
      group=0;                                  // Can't use group key
4031
 
    else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
4032
 
    {
4033
 
      /*
4034
 
        marker == 4 means two things:
4035
 
        - store NULLs in the key, and
4036
 
        - convert BIT fields to 64-bit long, needed because MEMORY tables
4037
 
          can't index BIT fields.
4038
 
      */
4039
 
      (*tmp->item)->marker= 4;
4040
 
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
4041
 
        using_unique_constraint=1;
4042
 
    }
4043
 
    if (param->group_length >= MAX_BLOB_WIDTH)
4044
 
      using_unique_constraint=1;
4045
 
    if (group)
4046
 
      distinct=0;                               // Can't use distinct
4047
 
  }
4048
 
 
4049
 
  field_count=param->field_count+param->func_count+param->sum_func_count;
4050
 
  hidden_field_count=param->hidden_field_count;
4051
 
 
4052
 
  /*
4053
 
    When loose index scan is employed as access method, it already
4054
 
    computes all groups and the result of all aggregate functions. We
4055
 
    make space for the items of the aggregate function in the list of
4056
 
    functions TMP_TABLE_PARAM::items_to_copy, so that the values of
4057
 
    these items are stored in the temporary table.
4058
 
  */
4059
 
  if (param->precomputed_group_by)
4060
 
    copy_func_count+= param->sum_func_count;
4061
 
  
4062
 
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
4063
 
 
4064
 
  if (!multi_alloc_root(&own_root,
4065
 
                        &table, sizeof(*table),
4066
 
                        &share, sizeof(*share),
4067
 
                        &reg_field, sizeof(Field*) * (field_count+1),
4068
 
                        &default_field, sizeof(Field*) * (field_count),
4069
 
                        &blob_field, sizeof(uint)*(field_count+1),
4070
 
                        &from_field, sizeof(Field*)*field_count,
4071
 
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
4072
 
                        &param->keyinfo, sizeof(*param->keyinfo),
4073
 
                        &key_part_info,
4074
 
                        sizeof(*key_part_info)*(param->group_parts+1),
4075
 
                        &param->start_recinfo,
4076
 
                        sizeof(*param->recinfo)*(field_count*2+4),
4077
 
                        &tmpname, (uint) strlen(path)+1,
4078
 
                        &group_buff, (group && ! using_unique_constraint ?
4079
 
                                      param->group_length : 0),
4080
 
                        &bitmaps, bitmap_buffer_size(field_count)*2,
4081
 
                        NULL))
4082
 
  {
4083
 
    if (temp_pool_slot != MY_BIT_NONE)
4084
 
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
4085
 
    return(NULL);                               /* purecov: inspected */
4086
 
  }
4087
 
  /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */
4088
 
  if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count]))
4089
 
  {
4090
 
    if (temp_pool_slot != MY_BIT_NONE)
4091
 
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
4092
 
    free_root(&own_root, MYF(0));               /* purecov: inspected */
4093
 
    return(NULL);                               /* purecov: inspected */
4094
 
  }
4095
 
  param->items_to_copy= copy_func;
4096
 
  my_stpcpy(tmpname,path);
4097
 
  /* make table according to fields */
4098
 
 
4099
 
  memset(table, 0, sizeof(*table));
4100
 
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
4101
 
  memset(default_field, 0, sizeof(Field*) * (field_count));
4102
 
  memset(from_field, 0, sizeof(Field*)*field_count);
4103
 
 
4104
 
  table->mem_root= own_root;
4105
 
  mem_root_save= thd->mem_root;
4106
 
  thd->mem_root= &table->mem_root;
4107
 
 
4108
 
  table->field=reg_field;
4109
 
  table->alias= table_alias;
4110
 
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
4111
 
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
4112
 
  table->map=1;
4113
 
  table->temp_pool_slot = temp_pool_slot;
4114
 
  table->copy_blobs= 1;
4115
 
  table->in_use= thd;
4116
 
  table->quick_keys.init();
4117
 
  table->covering_keys.init();
4118
 
  table->keys_in_use_for_query.init();
4119
 
 
4120
 
  table->setShare(share);
4121
 
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
4122
 
  share->blob_field= blob_field;
4123
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
4124
 
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
4125
 
  share->table_charset= param->table_charset;
4126
 
  share->primary_key= MAX_KEY;               // Indicate no primary key
4127
 
  share->keys_for_keyread.init();
4128
 
  share->keys_in_use.init();
4129
 
 
4130
 
  /* Calculate which type of fields we will store in the temporary table */
4131
 
 
4132
 
  reclength= string_total_length= 0;
4133
 
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
4134
 
  param->using_indirect_summary_function=0;
4135
 
 
4136
 
  List_iterator_fast<Item> li(fields);
4137
 
  Item *item;
4138
 
  Field **tmp_from_field=from_field;
4139
 
  while ((item=li++))
4140
 
  {
4141
 
    Item::Type type=item->type();
4142
 
    if (not_all_columns)
4143
 
    {
4144
 
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
4145
 
      {
4146
 
        if (item->used_tables() & OUTER_REF_TABLE_BIT)
4147
 
          item->update_used_tables();
4148
 
        if (type == Item::SUBSELECT_ITEM ||
4149
 
            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
4150
 
        {
4151
 
          /*
4152
 
            Mark that the we have ignored an item that refers to a summary
4153
 
            function. We need to know this if someone is going to use
4154
 
            DISTINCT on the result.
4155
 
          */
4156
 
          param->using_indirect_summary_function=1;
4157
 
          continue;
4158
 
        }
4159
 
      }
4160
 
      if (item->const_item() && (int) hidden_field_count <= 0)
4161
 
        continue; // We don't have to store this
4162
 
    }
4163
 
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
4164
 
    {                                           /* Can't calc group yet */
4165
 
      ((Item_sum*) item)->result_field=0;
4166
 
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
4167
 
      {
4168
 
        Item **argp= ((Item_sum*) item)->args + i;
4169
 
        Item *arg= *argp;
4170
 
        if (!arg->const_item())
4171
 
        {
4172
 
          Field *new_field=
4173
 
            create_tmp_field(thd, table, arg, arg->type(), &copy_func,
4174
 
                             tmp_from_field, &default_field[fieldnr],
4175
 
                             group != 0,not_all_columns,
4176
 
                             distinct, 0,
4177
 
                             param->convert_blob_length);
4178
 
          if (!new_field)
4179
 
            goto err;                                   // Should be OOM
4180
 
          tmp_from_field++;
4181
 
          reclength+=new_field->pack_length();
4182
 
          if (new_field->flags & BLOB_FLAG)
4183
 
          {
4184
 
            *blob_field++= fieldnr;
4185
 
            blob_count++;
4186
 
          }
4187
 
          *(reg_field++)= new_field;
4188
 
          if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
4189
 
          {
4190
 
            string_count++;
4191
 
            string_total_length+= new_field->pack_length();
4192
 
          }
4193
 
          thd->mem_root= mem_root_save;
4194
 
          thd->change_item_tree(argp, new Item_field(new_field));
4195
 
          thd->mem_root= &table->mem_root;
4196
 
          if (!(new_field->flags & NOT_NULL_FLAG))
4197
 
          {
4198
 
            null_count++;
4199
 
            /*
4200
 
              new_field->maybe_null() is still false, it will be
4201
 
              changed below. But we have to setup Item_field correctly
4202
 
            */
4203
 
            (*argp)->maybe_null=1;
4204
 
          }
4205
 
          new_field->field_index= fieldnr++;
4206
 
        }
4207
 
      }
4208
 
    }
4209
 
    else
4210
 
    {
4211
 
      /*
4212
 
        The last parameter to create_tmp_field() is a bit tricky:
4213
 
 
4214
 
        We need to set it to 0 in union, to get fill_record() to modify the
4215
 
        temporary table.
4216
 
        We need to set it to 1 on multi-table-update and in select to
4217
 
        write rows to the temporary table.
4218
 
        We here distinguish between UNION and multi-table-updates by the fact
4219
 
        that in the later case group is set to the row pointer.
4220
 
      */
4221
 
      Field *new_field= (param->schema_table) ?
4222
 
        create_tmp_field_for_schema(thd, item, table) :
4223
 
        create_tmp_field(thd, table, item, type, &copy_func,
4224
 
                         tmp_from_field, &default_field[fieldnr],
4225
 
                         group != 0,
4226
 
                         !force_copy_fields &&
4227
 
                           (not_all_columns || group !=0),
4228
 
                         /*
4229
 
                           If item->marker == 4 then we force create_tmp_field
4230
 
                           to create a 64-bit longs for BIT fields because HEAP
4231
 
                           tables can't index BIT fields directly. We do the same
4232
 
                           for distinct, as we want the distinct index to be
4233
 
                           usable in this case too.
4234
 
                         */
4235
 
                         item->marker == 4 || param->bit_fields_as_long,
4236
 
                         force_copy_fields,
4237
 
                         param->convert_blob_length);
4238
 
 
4239
 
      if (!new_field)
4240
 
      {
4241
 
        if (thd->is_fatal_error)
4242
 
          goto err;                             // Got OOM
4243
 
        continue;                               // Some kindf of const item
4244
 
      }
4245
 
      if (type == Item::SUM_FUNC_ITEM)
4246
 
        ((Item_sum *) item)->result_field= new_field;
4247
 
      tmp_from_field++;
4248
 
      reclength+=new_field->pack_length();
4249
 
      if (!(new_field->flags & NOT_NULL_FLAG))
4250
 
        null_count++;
4251
 
      if (new_field->flags & BLOB_FLAG)
4252
 
      {
4253
 
        *blob_field++= fieldnr;
4254
 
        blob_count++;
4255
 
      }
4256
 
      if (item->marker == 4 && item->maybe_null)
4257
 
      {
4258
 
        group_null_items++;
4259
 
        new_field->flags|= GROUP_FLAG;
4260
 
      }
4261
 
      new_field->field_index= fieldnr++;
4262
 
      *(reg_field++)= new_field;
4263
 
    }
4264
 
    if (!--hidden_field_count)
4265
 
    {
4266
 
      /*
4267
 
        This was the last hidden field; Remember how many hidden fields could
4268
 
        have null
4269
 
      */
4270
 
      hidden_null_count=null_count;
4271
 
      /*
4272
 
        We need to update hidden_field_count as we may have stored group
4273
 
        functions with constant arguments
4274
 
      */
4275
 
      param->hidden_field_count= fieldnr;
4276
 
      null_count= 0;
4277
 
    }
4278
 
  }
4279
 
  assert(fieldnr == (uint) (reg_field - table->field));
4280
 
  assert(field_count >= (uint) (reg_field - table->field));
4281
 
  field_count= fieldnr;
4282
 
  *reg_field= 0;
4283
 
  *blob_field= 0;                               // End marker
4284
 
  share->fields= field_count;
4285
 
 
4286
 
  /* If result table is small; use a heap */
4287
 
  /* future: storage engine selection can be made dynamic? */
4288
 
  if (blob_count || using_unique_constraint ||
4289
 
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
4290
 
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
4291
 
  {
4292
 
    share->db_plugin= ha_lock_engine(0, myisam_hton);
4293
 
    table->file= get_new_handler(share, &table->mem_root,
4294
 
                                 share->db_type());
4295
 
    if (group &&
4296
 
        (param->group_parts > table->file->max_key_parts() ||
4297
 
         param->group_length > table->file->max_key_length()))
4298
 
      using_unique_constraint=1;
4299
 
  }
4300
 
  else
4301
 
  {
4302
 
    share->db_plugin= ha_lock_engine(0, heap_hton);
4303
 
    table->file= get_new_handler(share, &table->mem_root,
4304
 
                                 share->db_type());
4305
 
  }
4306
 
  if (!table->file)
4307
 
    goto err;
4308
 
 
4309
 
 
4310
 
  if (!using_unique_constraint)
4311
 
    reclength+= group_null_items;       // null flag is stored separately
4312
 
 
4313
 
  share->blob_fields= blob_count;
4314
 
  if (blob_count == 0)
4315
 
  {
4316
 
    /* We need to ensure that first byte is not 0 for the delete link */
4317
 
    if (param->hidden_field_count)
4318
 
      hidden_null_count++;
4319
 
    else
4320
 
      null_count++;
4321
 
  }
4322
 
  hidden_null_pack_length=(hidden_null_count+7)/8;
4323
 
  null_pack_length= (hidden_null_pack_length +
4324
 
                     (null_count + total_uneven_bit_length + 7) / 8);
4325
 
  reclength+=null_pack_length;
4326
 
  if (!reclength)
4327
 
    reclength=1;                                // Dummy select
4328
 
  /* Use packed rows if there is blobs or a lot of space to gain */
4329
 
  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)))
4330
 
    use_packed_rows= 1;
4331
 
 
4332
 
  share->reclength= reclength;
4333
 
  {
4334
 
    uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
4335
 
    share->rec_buff_length= alloc_length;
4336
 
    if (!(table->record[0]= (unsigned char*)
4337
 
                            alloc_root(&table->mem_root, alloc_length*3)))
4338
 
      goto err;
4339
 
    table->record[1]= table->record[0]+alloc_length;
4340
 
    share->default_values= table->record[1]+alloc_length;
4341
 
  }
4342
 
  copy_func[0]=0;                               // End marker
4343
 
  param->func_count= copy_func - param->items_to_copy; 
4344
 
 
4345
 
  table->setup_tmp_table_column_bitmaps(bitmaps);
4346
 
 
4347
 
  recinfo=param->start_recinfo;
4348
 
  null_flags=(unsigned char*) table->record[0];
4349
 
  pos=table->record[0]+ null_pack_length;
4350
 
  if (null_pack_length)
4351
 
  {
4352
 
    memset(recinfo, 0, sizeof(*recinfo));
4353
 
    recinfo->type=FIELD_NORMAL;
4354
 
    recinfo->length=null_pack_length;
4355
 
    recinfo++;
4356
 
    memset(null_flags, 255, null_pack_length);  // Set null fields
4357
 
 
4358
 
    table->null_flags= (unsigned char*) table->record[0];
4359
 
    share->null_fields= null_count+ hidden_null_count;
4360
 
    share->null_bytes= null_pack_length;
4361
 
  }
4362
 
  null_count= (blob_count == 0) ? 1 : 0;
4363
 
  hidden_field_count=param->hidden_field_count;
4364
 
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
4365
 
  {
4366
 
    Field *field= *reg_field;
4367
 
    uint32_t length;
4368
 
    memset(recinfo, 0, sizeof(*recinfo));
4369
 
 
4370
 
    if (!(field->flags & NOT_NULL_FLAG))
4371
 
    {
4372
 
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
4373
 
      {
4374
 
        /*
4375
 
          We have to reserve one byte here for NULL bits,
4376
 
          as this is updated by 'end_update()'
4377
 
        */
4378
 
        *pos++=0;                               // Null is stored here
4379
 
        recinfo->length=1;
4380
 
        recinfo->type=FIELD_NORMAL;
4381
 
        recinfo++;
4382
 
        memset(recinfo, 0, sizeof(*recinfo));
4383
 
      }
4384
 
      else
4385
 
      {
4386
 
        recinfo->null_bit= 1 << (null_count & 7);
4387
 
        recinfo->null_pos= null_count/8;
4388
 
      }
4389
 
      field->move_field(pos,null_flags+null_count/8,
4390
 
                        1 << (null_count & 7));
4391
 
      null_count++;
4392
 
    }
4393
 
    else
4394
 
      field->move_field(pos,(unsigned char*) 0,0);
4395
 
    field->reset();
4396
 
 
4397
 
    /*
4398
 
      Test if there is a default field value. The test for ->ptr is to skip
4399
 
      'offset' fields generated by initalize_tables
4400
 
    */
4401
 
    if (default_field[i] && default_field[i]->ptr)
4402
 
    {
4403
 
      /* 
4404
 
         default_field[i] is set only in the cases  when 'field' can
4405
 
         inherit the default value that is defined for the field referred
4406
 
         by the Item_field object from which 'field' has been created.
4407
 
      */
4408
 
      my_ptrdiff_t diff;
4409
 
      Field *orig_field= default_field[i];
4410
 
      /* Get the value from default_values */
4411
 
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
4412
 
                            orig_field->table->record[0]);
4413
 
      orig_field->move_field_offset(diff);      // Points now at default_values
4414
 
      if (orig_field->is_real_null())
4415
 
        field->set_null();
4416
 
      else
4417
 
      {
4418
 
        field->set_notnull();
4419
 
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
4420
 
      }
4421
 
      orig_field->move_field_offset(-diff);     // Back to record[0]
4422
 
    } 
4423
 
 
4424
 
    if (from_field[i])
4425
 
    {                                           /* Not a table Item */
4426
 
      copy->set(field,from_field[i],save_sum_fields);
4427
 
      copy++;
4428
 
    }
4429
 
    length=field->pack_length();
4430
 
    pos+= length;
4431
 
 
4432
 
    /* Make entry for create table */
4433
 
    recinfo->length=length;
4434
 
    if (field->flags & BLOB_FLAG)
4435
 
      recinfo->type= (int) FIELD_BLOB;
4436
 
    else
4437
 
      recinfo->type=FIELD_NORMAL;
4438
 
    if (!--hidden_field_count)
4439
 
      null_count=(null_count+7) & ~7;           // move to next byte
4440
 
 
4441
 
    // fix table name in field entry
4442
 
    field->table_name= &table->alias;
4443
 
  }
4444
 
 
4445
 
  param->copy_field_end=copy;
4446
 
  param->recinfo=recinfo;
4447
 
  store_record(table,s->default_values);        // Make empty default record
4448
 
 
4449
 
  if (thd->variables.tmp_table_size == ~ (uint64_t) 0)          // No limit
4450
 
    share->max_rows= ~(ha_rows) 0;
4451
 
  else
4452
 
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
4453
 
                                 cmin(thd->variables.tmp_table_size,
4454
 
                                     thd->variables.max_heap_table_size) :
4455
 
                                 thd->variables.tmp_table_size) /
4456
 
                                 share->reclength);
4457
 
  set_if_bigger(share->max_rows,1);             // For dummy start options
4458
 
  /*
4459
 
    Push the LIMIT clause to the temporary table creation, so that we
4460
 
    materialize only up to 'rows_limit' records instead of all result records.
4461
 
  */
4462
 
  set_if_smaller(share->max_rows, rows_limit);
4463
 
  param->end_write_records= rows_limit;
4464
 
 
4465
 
  keyinfo= param->keyinfo;
4466
 
 
4467
 
  if (group)
4468
 
  {
4469
 
    table->group=group;                         /* Table is grouped by key */
4470
 
    param->group_buff=group_buff;
4471
 
    share->keys=1;
4472
 
    share->uniques= test(using_unique_constraint);
4473
 
    table->key_info=keyinfo;
4474
 
    keyinfo->key_part=key_part_info;
4475
 
    keyinfo->flags=HA_NOSAME;
4476
 
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
4477
 
    keyinfo->key_length=0;
4478
 
    keyinfo->rec_per_key=0;
4479
 
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
4480
 
    keyinfo->name= (char*) "group_key";
4481
 
    order_st *cur_group= group;
4482
 
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
4483
 
    {
4484
 
      Field *field=(*cur_group->item)->get_tmp_table_field();
4485
 
      bool maybe_null=(*cur_group->item)->maybe_null;
4486
 
      key_part_info->null_bit=0;
4487
 
      key_part_info->field=  field;
4488
 
      key_part_info->offset= field->offset(table->record[0]);
4489
 
      key_part_info->length= (uint16_t) field->key_length();
4490
 
      key_part_info->type=   (uint8_t) field->key_type();
4491
 
      key_part_info->key_type =
4492
 
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
4493
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
4494
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
4495
 
        0 : FIELDFLAG_BINARY;
4496
 
      if (!using_unique_constraint)
4497
 
      {
4498
 
        cur_group->buff=(char*) group_buff;
4499
 
        if (!(cur_group->field= field->new_key_field(thd->mem_root,table,
4500
 
                                                     group_buff +
4501
 
                                                     test(maybe_null),
4502
 
                                                     field->null_ptr,
4503
 
                                                     field->null_bit)))
4504
 
          goto err; /* purecov: inspected */
4505
 
        if (maybe_null)
4506
 
        {
4507
 
          /*
4508
 
            To be able to group on NULL, we reserved place in group_buff
4509
 
            for the NULL flag just before the column. (see above).
4510
 
            The field data is after this flag.
4511
 
            The NULL flag is updated in 'end_update()' and 'end_write()'
4512
 
          */
4513
 
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
4514
 
          key_part_info->null_bit=field->null_bit;
4515
 
          key_part_info->null_offset= (uint) (field->null_ptr -
4516
 
                                              (unsigned char*) table->record[0]);
4517
 
          cur_group->buff++;                        // Pointer to field data
4518
 
          group_buff++;                         // Skipp null flag
4519
 
        }
4520
 
        /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
4521
 
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
4522
 
        group_buff+= cur_group->field->pack_length();
4523
 
      }
4524
 
      keyinfo->key_length+=  key_part_info->length;
4525
 
    }
4526
 
  }
4527
 
 
4528
 
  if (distinct && field_count != param->hidden_field_count)
4529
 
  {
4530
 
    /*
4531
 
      Create an unique key or an unique constraint over all columns
4532
 
      that should be in the result.  In the temporary table, there are
4533
 
      'param->hidden_field_count' extra columns, whose null bits are stored
4534
 
      in the first 'hidden_null_pack_length' bytes of the row.
4535
 
    */
4536
 
    if (blob_count)
4537
 
    {
4538
 
      /*
4539
 
        Special mode for index creation in MyISAM used to support unique
4540
 
        indexes on blobs with arbitrary length. Such indexes cannot be
4541
 
        used for lookups.
4542
 
      */
4543
 
      share->uniques= 1;
4544
 
    }
4545
 
    null_pack_length-=hidden_null_pack_length;
4546
 
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
4547
 
                         (share->uniques ? test(null_pack_length) : 0));
4548
 
    table->distinct= 1;
4549
 
    share->keys= 1;
4550
 
    if (!(key_part_info= (KEY_PART_INFO*)
4551
 
          alloc_root(&table->mem_root,
4552
 
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
4553
 
      goto err;
4554
 
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
4555
 
    table->key_info=keyinfo;
4556
 
    keyinfo->key_part=key_part_info;
4557
 
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
4558
 
    keyinfo->key_length=(uint16_t) reclength;
4559
 
    keyinfo->name= (char*) "distinct_key";
4560
 
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
4561
 
    keyinfo->rec_per_key=0;
4562
 
 
4563
 
    /*
4564
 
      Create an extra field to hold NULL bits so that unique indexes on
4565
 
      blobs can distinguish NULL from 0. This extra field is not needed
4566
 
      when we do not use UNIQUE indexes for blobs.
4567
 
    */
4568
 
    if (null_pack_length && share->uniques)
4569
 
    {
4570
 
      key_part_info->null_bit=0;
4571
 
      key_part_info->offset=hidden_null_pack_length;
4572
 
      key_part_info->length=null_pack_length;
4573
 
      key_part_info->field= new Field_varstring(table->record[0],
4574
 
                                                (uint32_t) key_part_info->length,
4575
 
                                                0,
4576
 
                                                (unsigned char*) 0,
4577
 
                                                (uint) 0,
4578
 
                                                Field::NONE,
4579
 
                                                NULL, 
4580
 
                                                table->s,
4581
 
                                                &my_charset_bin);
4582
 
      if (!key_part_info->field)
4583
 
        goto err;
4584
 
      key_part_info->field->init(table);
4585
 
      key_part_info->key_type=FIELDFLAG_BINARY;
4586
 
      key_part_info->type=    HA_KEYTYPE_BINARY;
4587
 
      key_part_info++;
4588
 
    }
4589
 
    /* Create a distinct key over the columns we are going to return */
4590
 
    for (i=param->hidden_field_count, reg_field=table->field + i ;
4591
 
         i < field_count;
4592
 
         i++, reg_field++, key_part_info++)
4593
 
    {
4594
 
      key_part_info->null_bit=0;
4595
 
      key_part_info->field=    *reg_field;
4596
 
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
4597
 
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
4598
 
      /* TODO:
4599
 
        The below method of computing the key format length of the
4600
 
        key part is a copy/paste from opt_range.cc, and table.cc.
4601
 
        This should be factored out, e.g. as a method of Field.
4602
 
        In addition it is not clear if any of the Field::*_length
4603
 
        methods is supposed to compute the same length. If so, it
4604
 
        might be reused.
4605
 
      */
4606
 
      key_part_info->store_length= key_part_info->length;
4607
 
 
4608
 
      if ((*reg_field)->real_maybe_null())
4609
 
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
4610
 
      if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB || 
4611
 
          (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
4612
 
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
4613
 
 
4614
 
      key_part_info->type=     (uint8_t) (*reg_field)->key_type();
4615
 
      key_part_info->key_type =
4616
 
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
4617
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
4618
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
4619
 
        0 : FIELDFLAG_BINARY;
4620
 
    }
4621
 
  }
4622
 
 
4623
 
  if (thd->is_fatal_error)                              // If end of memory
4624
 
    goto err;                                    /* purecov: inspected */
4625
 
  share->db_record_offset= 1;
4626
 
  if (share->db_type() == myisam_hton)
4627
 
  {
4628
 
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
4629
 
                                       &param->recinfo, select_options))
4630
 
      goto err;
4631
 
  }
4632
 
  if (table->open_tmp_table())
4633
 
    goto err;
4634
 
 
4635
 
  thd->mem_root= mem_root_save;
4636
 
 
4637
 
  return(table);
4638
 
 
4639
 
err:
4640
 
  thd->mem_root= mem_root_save;
4641
 
  table->free_tmp_table(thd);                    /* purecov: inspected */
4642
 
  if (temp_pool_slot != MY_BIT_NONE)
4643
 
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
4644
 
  return(NULL);                         /* purecov: inspected */
4645
 
}
4646
 
 
4647
 
/****************************************************************************/
4648
 
 
4649
 
/**
4650
 
  Create a reduced Table object with properly set up Field list from a
4651
 
  list of field definitions.
4652
 
 
4653
 
    The created table doesn't have a table handler associated with
4654
 
    it, has no keys, no group/distinct, no copy_funcs array.
4655
 
    The sole purpose of this Table object is to use the power of Field
4656
 
    class to read/write data to/from table->record[0]. Then one can store
4657
 
    the record in any container (RB tree, hash, etc).
4658
 
    The table is created in THD mem_root, so are the table's fields.
4659
 
    Consequently, if you don't BLOB fields, you don't need to free it.
4660
 
 
4661
 
  @param thd         connection handle
4662
 
  @param field_list  list of column definitions
4663
 
 
4664
 
  @return
4665
 
    0 if out of memory, Table object in case of success
4666
 
*/
4667
 
 
4668
 
Table *create_virtual_tmp_table(THD *thd, List<Create_field> &field_list)
4669
 
{
4670
 
  uint32_t field_count= field_list.elements;
4671
 
  uint32_t blob_count= 0;
4672
 
  Field **field;
4673
 
  Create_field *cdef;                           /* column definition */
4674
 
  uint32_t record_length= 0;
4675
 
  uint32_t null_count= 0;                 /* number of columns which may be null */
4676
 
  uint32_t null_pack_length;              /* NULL representation array length */
4677
 
  uint32_t *blob_field;
4678
 
  unsigned char *bitmaps;
4679
 
  Table *table;
4680
 
  TABLE_SHARE *share;
4681
 
 
4682
 
  if (!multi_alloc_root(thd->mem_root,
4683
 
                        &table, sizeof(*table),
4684
 
                        &share, sizeof(*share),
4685
 
                        &field, (field_count + 1) * sizeof(Field*),
4686
 
                        &blob_field, (field_count+1) *sizeof(uint),
4687
 
                        &bitmaps, bitmap_buffer_size(field_count)*2,
4688
 
                        NULL))
4689
 
    return 0;
4690
 
 
4691
 
  memset(table, 0, sizeof(*table));
4692
 
  memset(share, 0, sizeof(*share));
4693
 
  table->field= field;
4694
 
  table->s= share;
4695
 
  share->blob_field= blob_field;
4696
 
  share->fields= field_count;
4697
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
4698
 
  table->setup_tmp_table_column_bitmaps(bitmaps);
4699
 
 
4700
 
  /* Create all fields and calculate the total length of record */
4701
 
  List_iterator_fast<Create_field> it(field_list);
4702
 
  while ((cdef= it++))
4703
 
  {
4704
 
    *field= make_field(share, 0, cdef->length,
4705
 
                       (unsigned char*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
4706
 
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
4707
 
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
4708
 
                       cdef->unireg_check,
4709
 
                       cdef->interval, cdef->field_name);
4710
 
    if (!*field)
4711
 
      goto error;
4712
 
    (*field)->init(table);
4713
 
    record_length+= (*field)->pack_length();
4714
 
    if (! ((*field)->flags & NOT_NULL_FLAG))
4715
 
      null_count++;
4716
 
 
4717
 
    if ((*field)->flags & BLOB_FLAG)
4718
 
      share->blob_field[blob_count++]= (uint) (field - table->field);
4719
 
 
4720
 
    field++;
4721
 
  }
4722
 
  *field= NULL;                             /* mark the end of the list */
4723
 
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
4724
 
  share->blob_fields= blob_count;
4725
 
 
4726
 
  null_pack_length= (null_count + 7)/8;
4727
 
  share->reclength= record_length + null_pack_length;
4728
 
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
4729
 
  table->record[0]= (unsigned char*) thd->alloc(share->rec_buff_length);
4730
 
  if (!table->record[0])
4731
 
    goto error;
4732
 
 
4733
 
  if (null_pack_length)
4734
 
  {
4735
 
    table->null_flags= (unsigned char*) table->record[0];
4736
 
    share->null_fields= null_count;
4737
 
    share->null_bytes= null_pack_length;
4738
 
  }
4739
 
 
4740
 
  table->in_use= thd;           /* field->reset() may access table->in_use */
4741
 
  {
4742
 
    /* Set up field pointers */
4743
 
    unsigned char *null_pos= table->record[0];
4744
 
    unsigned char *field_pos= null_pos + share->null_bytes;
4745
 
    uint32_t null_bit= 1;
4746
 
 
4747
 
    for (field= table->field; *field; ++field)
4748
 
    {
4749
 
      Field *cur_field= *field;
4750
 
      if ((cur_field->flags & NOT_NULL_FLAG))
4751
 
        cur_field->move_field(field_pos);
4752
 
      else
4753
 
      {
4754
 
        cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
4755
 
        null_bit<<= 1;
4756
 
        if (null_bit == (1 << 8))
4757
 
        {
4758
 
          ++null_pos;
4759
 
          null_bit= 1;
4760
 
        }
4761
 
      }
4762
 
      cur_field->reset();
4763
 
 
4764
 
      field_pos+= cur_field->pack_length();
4765
 
    }
4766
 
  }
4767
 
  return table;
4768
 
error:
4769
 
  for (field= table->field; *field; ++field)
4770
 
    delete *field;                         /* just invokes field destructor */
4771
 
  return 0;
4772
 
}
4773
 
 
4774
 
 
4775
 
bool Table::open_tmp_table()
4776
 
{
4777
 
  int error;
4778
 
  if ((error=file->ha_open(this, s->table_name.str,O_RDWR,
4779
 
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
4780
 
  {
4781
 
    file->print_error(error,MYF(0)); /* purecov: inspected */
4782
 
    db_stat=0;
4783
 
    return(1);
4784
 
  }
4785
 
  (void) file->extra(HA_EXTRA_QUICK);           /* Faster */
4786
 
  return(0);
4787
 
}
4788
 
 
4789
 
 
4790
 
/*
4791
 
  Create MyISAM temporary table
4792
 
 
4793
 
  SYNOPSIS
4794
 
    create_myisam_tmp_table()
4795
 
      keyinfo         Description of the index (there is always one index)
4796
 
      start_recinfo   MyISAM's column descriptions
4797
 
      recinfo INOUT   End of MyISAM's column descriptions
4798
 
      options         Option bits
4799
 
   
4800
 
  DESCRIPTION
4801
 
    Create a MyISAM temporary table according to passed description. The is
4802
 
    assumed to have one unique index or constraint.
4803
 
 
4804
 
    The passed array or MI_COLUMNDEF structures must have this form:
4805
 
 
4806
 
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
4807
 
         when there are many nullable columns)
4808
 
      2. Table columns
4809
 
      3. One free MI_COLUMNDEF element (*recinfo points here)
4810
 
   
4811
 
    This function may use the free element to create hash column for unique
4812
 
    constraint.
4813
 
 
4814
 
   RETURN
4815
 
     false - OK
4816
 
     true  - Error
4817
 
*/
4818
 
 
4819
 
bool Table::create_myisam_tmp_table(KEY *keyinfo, 
4820
 
                                    MI_COLUMNDEF *start_recinfo,
4821
 
                                    MI_COLUMNDEF **recinfo, 
4822
 
                                    uint64_t options)
4823
 
{
4824
 
  int error;
4825
 
  MI_KEYDEF keydef;
4826
 
  MI_UNIQUEDEF uniquedef;
4827
 
  TABLE_SHARE *share= s;
4828
 
 
4829
 
  if (share->keys)
4830
 
  {                                             // Get keys for ni_create
4831
 
    bool using_unique_constraint=0;
4832
 
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
4833
 
                                            sizeof(*seg) * keyinfo->key_parts);
4834
 
    if (!seg)
4835
 
      goto err;
4836
 
 
4837
 
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
4838
 
    if (keyinfo->key_length >= file->max_key_length() ||
4839
 
        keyinfo->key_parts > file->max_key_parts() ||
4840
 
        share->uniques)
4841
 
    {
4842
 
      /* Can't create a key; Make a unique constraint instead of a key */
4843
 
      share->keys=    0;
4844
 
      share->uniques= 1;
4845
 
      using_unique_constraint=1;
4846
 
      memset(&uniquedef, 0, sizeof(uniquedef));
4847
 
      uniquedef.keysegs=keyinfo->key_parts;
4848
 
      uniquedef.seg=seg;
4849
 
      uniquedef.null_are_equal=1;
4850
 
 
4851
 
      /* Create extra column for hash value */
4852
 
      memset(*recinfo, 0, sizeof(**recinfo));
4853
 
      (*recinfo)->type= FIELD_CHECK;
4854
 
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
4855
 
      (*recinfo)++;
4856
 
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
4857
 
    }
4858
 
    else
4859
 
    {
4860
 
      /* Create an unique key */
4861
 
      memset(&keydef, 0, sizeof(keydef));
4862
 
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
4863
 
      keydef.keysegs=  keyinfo->key_parts;
4864
 
      keydef.seg= seg;
4865
 
    }
4866
 
    for (uint32_t i=0; i < keyinfo->key_parts ; i++,seg++)
4867
 
    {
4868
 
      Field *field=keyinfo->key_part[i].field;
4869
 
      seg->flag=     0;
4870
 
      seg->language= field->charset()->number;
4871
 
      seg->length=   keyinfo->key_part[i].length;
4872
 
      seg->start=    keyinfo->key_part[i].offset;
4873
 
      if (field->flags & BLOB_FLAG)
4874
 
      {
4875
 
        seg->type=
4876
 
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
4877
 
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
4878
 
        seg->bit_start= (uint8_t)(field->pack_length() - share->blob_ptr_size);
4879
 
        seg->flag= HA_BLOB_PART;
4880
 
        seg->length=0;                  // Whole blob in unique constraint
4881
 
      }
4882
 
      else
4883
 
      {
4884
 
        seg->type= keyinfo->key_part[i].type;
4885
 
      }
4886
 
      if (!(field->flags & NOT_NULL_FLAG))
4887
 
      {
4888
 
        seg->null_bit= field->null_bit;
4889
 
        seg->null_pos= (uint) (field->null_ptr - (unsigned char*) record[0]);
4890
 
        /*
4891
 
          We are using a GROUP BY on something that contains NULL
4892
 
          In this case we have to tell MyISAM that two NULL should
4893
 
          on INSERT be regarded at the same value
4894
 
        */
4895
 
        if (!using_unique_constraint)
4896
 
          keydef.flag|= HA_NULL_ARE_EQUAL;
4897
 
      }
4898
 
    }
4899
 
  }
4900
 
  MI_CREATE_INFO create_info;
4901
 
  memset(&create_info, 0, sizeof(create_info));
4902
 
 
4903
 
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
4904
 
      OPTION_BIG_TABLES)
4905
 
    create_info.data_file_length= ~(uint64_t) 0;
4906
 
 
4907
 
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
4908
 
                       (uint) (*recinfo-start_recinfo),
4909
 
                       start_recinfo,
4910
 
                       share->uniques, &uniquedef,
4911
 
                       &create_info,
4912
 
                       HA_CREATE_TMP_TABLE)))
4913
 
  {
4914
 
    file->print_error(error,MYF(0));    /* purecov: inspected */
4915
 
    db_stat=0;
4916
 
    goto err;
4917
 
  }
4918
 
  status_var_increment(in_use->status_var.created_tmp_disk_tables);
4919
 
  share->db_record_offset= 1;
4920
 
  return false;
4921
 
 err:
4922
 
  return true;
4923
 
}
4924
 
 
4925
 
 
4926
 
void Table::free_tmp_table(THD *thd)
4927
 
{
4928
 
  MEM_ROOT own_root= mem_root;
4929
 
  const char *save_proc_info;
4930
 
 
4931
 
  save_proc_info=thd->get_proc_info();
4932
 
  thd->set_proc_info("removing tmp table");
4933
 
 
4934
 
  if (file)
4935
 
  {
4936
 
    if (db_stat)
4937
 
      file->ha_drop_table(s->table_name.str);
4938
 
    else
4939
 
      file->ha_delete_table(s->table_name.str);
4940
 
    delete file;
4941
 
  }
4942
 
 
4943
 
  /* free blobs */
4944
 
  for (Field **ptr= field ; *ptr ; ptr++)
4945
 
    (*ptr)->free();
4946
 
  free_io_cache(this);
4947
 
 
4948
 
  if (temp_pool_slot != MY_BIT_NONE)
4949
 
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
4950
 
 
4951
 
  plugin_unlock(0, s->db_plugin);
4952
 
 
4953
 
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
4954
 
  thd->set_proc_info(save_proc_info);
4955
 
 
4956
 
  return;
4957
 
}
4958
 
 
4959
 
/**
4960
 
  If a HEAP table gets full, create a MyISAM table and copy all rows
4961
 
  to this.
4962
 
*/
4963
 
 
4964
 
bool create_myisam_from_heap(THD *thd, Table *table,
4965
 
                             MI_COLUMNDEF *start_recinfo,
4966
 
                             MI_COLUMNDEF **recinfo, 
4967
 
                             int error, bool ignore_last_dupp_key_error)
4968
 
{
4969
 
  Table new_table;
4970
 
  TABLE_SHARE share;
4971
 
  const char *save_proc_info;
4972
 
  int write_err;
4973
 
 
4974
 
  if (table->s->db_type() != heap_hton || 
4975
 
      error != HA_ERR_RECORD_FILE_FULL)
4976
 
  {
4977
 
    table->file->print_error(error,MYF(0));
4978
 
    return(1);
4979
 
  }
4980
 
  new_table= *table;
4981
 
  share= *table->s;
4982
 
  new_table.s= &share;
4983
 
  new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton);
4984
 
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
4985
 
                                        new_table.s->db_type())))
4986
 
    return(1);                          // End of memory
4987
 
 
4988
 
  save_proc_info=thd->get_proc_info();
4989
 
  thd->set_proc_info("converting HEAP to MyISAM");
4990
 
 
4991
 
  if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
4992
 
                                        recinfo, thd->lex->select_lex.options | 
4993
 
                                        thd->options))
4994
 
    goto err2;
4995
 
  if (new_table.open_tmp_table())
4996
 
    goto err1;
4997
 
  if (table->file->indexes_are_disabled())
4998
 
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
4999
 
  table->file->ha_index_or_rnd_end();
5000
 
  table->file->ha_rnd_init(1);
5001
 
  if (table->no_rows)
5002
 
  {
5003
 
    new_table.file->extra(HA_EXTRA_NO_ROWS);
5004
 
    new_table.no_rows=1;
5005
 
  }
5006
 
 
5007
 
#ifdef TO_BE_DONE_LATER_IN_4_1
5008
 
  /*
5009
 
    To use start_bulk_insert() (which is new in 4.1) we need to find
5010
 
    all places where a corresponding end_bulk_insert() should be put.
5011
 
  */
5012
 
  table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */
5013
 
  new_table.file->ha_start_bulk_insert(table->file->stats.records);
5014
 
#else
5015
 
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
5016
 
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
5017
 
#endif
5018
 
 
5019
 
  /*
5020
 
    copy all old rows from heap table to MyISAM table
5021
 
    This is the only code that uses record[1] to read/write but this
5022
 
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
5023
 
  */
5024
 
  while (!table->file->rnd_next(new_table.record[1]))
5025
 
  {
5026
 
    write_err= new_table.file->ha_write_row(new_table.record[1]);
5027
 
    if (write_err)
5028
 
      goto err;
5029
 
  }
5030
 
  /* copy row that filled HEAP table */
5031
 
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
5032
 
  {
5033
 
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
5034
 
        !ignore_last_dupp_key_error)
5035
 
      goto err;
5036
 
  }
5037
 
 
5038
 
  /* remove heap table and change to use myisam table */
5039
 
  (void) table->file->ha_rnd_end();
5040
 
  (void) table->file->close();                  // This deletes the table !
5041
 
  delete table->file;
5042
 
  table->file=0;
5043
 
  plugin_unlock(0, table->s->db_plugin);
5044
 
  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
5045
 
  new_table.s= table->s;                       // Keep old share
5046
 
  *table= new_table;
5047
 
  *table->s= share;
5048
 
  
5049
 
  table->file->change_table_ptr(table, table->s);
5050
 
  table->use_all_columns();
5051
 
  if (save_proc_info)
5052
 
  {
5053
 
    const char *new_proc_info=
5054
 
      (!strcmp(save_proc_info,"Copying to tmp table") ?
5055
 
      "Copying to tmp table on disk" : save_proc_info);
5056
 
    thd->set_proc_info(new_proc_info);
5057
 
  }
5058
 
  return(0);
5059
 
 
5060
 
 err:
5061
 
  table->file->print_error(write_err, MYF(0));
5062
 
  (void) table->file->ha_rnd_end();
5063
 
  (void) new_table.file->close();
5064
 
 err1:
5065
 
  new_table.file->ha_delete_table(new_table.s->table_name.str);
5066
 
 err2:
5067
 
  delete new_table.file;
5068
 
  thd->set_proc_info(save_proc_info);
5069
 
  table->mem_root= new_table.mem_root;
5070
 
  return(1);
5071
 
}
5072
 
 
5073
 
my_bitmap_map *Table::use_all_columns(MY_BITMAP *bitmap)
5074
 
{
5075
 
  my_bitmap_map *old= bitmap->bitmap;
5076
 
  bitmap->bitmap= s->all_set.bitmap;
5077
 
  return old;
5078
 
}
5079
 
 
5080
 
void Table::restore_column_map(my_bitmap_map *old)
5081
 
{
5082
 
  read_set->bitmap= old;
5083
 
}
5084
 
 
5085
 
uint32_t Table::find_shortest_key(const key_map *usable_keys)
5086
 
{
5087
 
  uint32_t min_length= UINT32_MAX;
5088
 
  uint32_t best= MAX_KEY;
5089
 
  if (!usable_keys->is_clear_all())
5090
 
  {
5091
 
    for (uint32_t nr=0; nr < s->keys ; nr++)
5092
 
    {
5093
 
      if (usable_keys->is_set(nr))
5094
 
      {
5095
 
        if (key_info[nr].key_length < min_length)
5096
 
        {
5097
 
          min_length= key_info[nr].key_length;
5098
 
          best=nr;
5099
 
        }
5100
 
      }
5101
 
    }
5102
 
  }
5103
 
  return best;
5104
 
}
5105
 
 
5106
 
/*****************************************************************************
5107
 
  Remove duplicates from tmp table
5108
 
  This should be recoded to add a unique index to the table and remove
5109
 
  duplicates
5110
 
  Table is a locked single thread table
5111
 
  fields is the number of fields to check (from the end)
5112
 
*****************************************************************************/
5113
 
 
5114
 
bool Table::compare_record(Field **ptr)
5115
 
{
5116
 
  for (; *ptr ; ptr++)
5117
 
  {
5118
 
    if ((*ptr)->cmp_offset(s->rec_buff_length))
5119
 
      return true;
5120
 
  }
5121
 
  return false;
5122
 
}
5123
 
 
5124
 
/* Return false if row hasn't changed */
5125
 
 
5126
 
bool Table::compare_record()
5127
 
{
5128
 
  if (s->blob_fields + s->varchar_fields == 0)
5129
 
    return cmp_record(this, record[1]);
5130
 
  /* Compare null bits */
5131
 
  if (memcmp(null_flags,
5132
 
             null_flags + s->rec_buff_length,
5133
 
             s->null_bytes))
5134
 
    return true;                                // Diff in NULL value
5135
 
  /* Compare updated fields */
5136
 
  for (Field **ptr= field ; *ptr ; ptr++)
5137
 
  {
5138
 
    if (bitmap_is_set(write_set, (*ptr)->field_index) &&
5139
 
        (*ptr)->cmp_binary_offset(s->rec_buff_length))
5140
 
      return true;
5141
 
  }
5142
 
  return false;
5143
 
}
5144
 
 
5145
 
 
5146
 
 
5147
 
 
5148
 
 
5149
 
/*****************************************************************************
5150
 
  The different ways to read a record
5151
 
  Returns -1 if row was not found, 0 if row was found and 1 on errors
5152
 
*****************************************************************************/
5153
 
 
5154
 
/** Help function when we get some an error from the table handler. */
5155
 
 
5156
 
int Table::report_error(int error)
5157
 
{
5158
 
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
5159
 
  {
5160
 
    status= STATUS_GARBAGE;
5161
 
    return -1;                                  // key not found; ok
5162
 
  }
5163
 
  /*
5164
 
    Locking reads can legally return also these errors, do not
5165
 
    print them to the .err log
5166
 
  */
5167
 
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
5168
 
    sql_print_error(_("Got error %d when reading table '%s'"),
5169
 
                    error, s->path.str);
5170
 
  file->print_error(error,MYF(0));
5171
 
 
5172
 
  return 1;
5173
 
}
5174
 
 
5175
 
 
5176
 
/*
5177
 
  Calculate data for each virtual field marked for write in the
5178
 
  corresponding column map.
5179
 
 
5180
 
  SYNOPSIS
5181
 
    update_virtual_fields_marked_for_write()
5182
 
    table                  The Table object
5183
 
    ignore_stored          Indication whether physically stored virtual
5184
 
                           fields do not need updating.
5185
 
                           This value is false when during INSERT and UPDATE
5186
 
                           and true in all other cases.
5187
 
 
5188
 
  RETURN
5189
 
    0  - Success
5190
 
    >0 - Error occurred during the generation/calculation of a virtual field value
5191
 
 
5192
 
*/
5193
 
 
5194
 
int update_virtual_fields_marked_for_write(Table *table,
5195
 
                                           bool ignore_stored)
5196
 
{
5197
 
  Field **vfield_ptr, *vfield;
5198
 
  int error= 0;
5199
 
  if ((not table) or (not table->vfield))
5200
 
    return(0);
5201
 
 
5202
 
  /* Iterate over virtual fields in the table */
5203
 
  for (vfield_ptr= table->vfield; *vfield_ptr; vfield_ptr++)
5204
 
  {
5205
 
    vfield= (*vfield_ptr);
5206
 
    assert(vfield->vcol_info && vfield->vcol_info->expr_item);
5207
 
    /*
5208
 
      Only update those fields that are marked in the write_set bitmap
5209
 
      and not _already_ physically stored in the database.
5210
 
    */
5211
 
    if (bitmap_is_set(table->write_set, vfield->field_index) &&
5212
 
        (not (ignore_stored && vfield->is_stored))
5213
 
       )
5214
 
    {
5215
 
      /* Generate the actual value of the virtual fields */
5216
 
      error= vfield->vcol_info->expr_item->save_in_field(vfield, 0);
5217
 
    }
5218
 
  }
5219
 
  return(0);
 
3880
  DBUG_RETURN(FRMTYPE_TABLE);                   // Is probably a .frm table
5220
3881
}
5221
3882
 
5222
3883