~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Jay Pipes
  • Date: 2008-09-11 16:03:22 UTC
  • mto: (383.5.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 386.
  • Revision ID: jay@mysql.com-20080911160322-vrl0k1djo6q6ytv1
Removed SQL_MODE variances from comment_table.test and ensured correct error thrown when a comment that is too long was input.  After moving to proto buffer definition for table, the 2048 length will go away.

Show diffs side-by-side

added added

removed removed

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