~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Monty Taylor
  • Date: 2008-10-09 22:38:27 UTC
  • mto: This revision was merged to the branch mainline in revision 497.
  • Revision ID: monty@inaugust.com-20081009223827-bc9gvpiplsmvpwyq
Moved test() to its own file.
Made a new function to possibly replace int10_to_str.

Show diffs side-by-side

added added

removed removed

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