~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Monty Taylor
  • Date: 2010-12-27 19:58:09 UTC
  • mto: This revision was merged to the branch mainline in revision 2038.
  • Revision ID: mordred@inaugust.com-20101227195809-1k7a4ge19l3u1o1h
Updated pandora-build files to version 0.171

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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
14
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
15
15
 
16
16
 
17
17
/* Some general useful functions */
28
28
#include <drizzled/error.h>
29
29
#include <drizzled/gettext.h>
30
30
 
31
 
#include "drizzled/plugin/info_schema_table.h"
32
31
#include "drizzled/plugin/transactional_storage_engine.h"
 
32
#include "drizzled/plugin/authorization.h"
33
33
#include <drizzled/nested_join.h>
34
34
#include <drizzled/sql_parse.h>
35
35
#include <drizzled/item/sum.h>
54
54
#include <drizzled/item/null.h>
55
55
#include <drizzled/temporal.h>
56
56
 
 
57
#include "drizzled/table/instance.h"
 
58
 
57
59
#include "drizzled/table_proto.h"
58
60
 
59
61
using namespace std;
72
74
 
73
75
/*************************************************************************/
74
76
 
75
 
/* Get column name from column hash */
76
 
 
77
 
static unsigned char *get_field_name(Field **buff, size_t *length, bool)
78
 
{
79
 
  *length= (uint32_t) strlen((*buff)->field_name);
80
 
  return (unsigned char*) (*buff)->field_name;
81
 
}
82
 
 
83
 
static TABLE_CATEGORY get_table_category(const LEX_STRING *db)
84
 
{
85
 
  assert(db != NULL);
86
 
 
87
 
  if ((db->length == INFORMATION_SCHEMA_NAME.length()) &&
88
 
      (my_strcasecmp(system_charset_info,
89
 
                    INFORMATION_SCHEMA_NAME.c_str(),
90
 
                    db->str) == 0))
91
 
  {
92
 
    return TABLE_CATEGORY_INFORMATION;
93
 
  }
94
 
 
95
 
  return TABLE_CATEGORY_USER;
96
 
}
97
 
 
98
 
 
99
 
/*
100
 
  Allocate a setup TableShare structure
101
 
 
102
 
  SYNOPSIS
103
 
    alloc_table_share()
104
 
    TableList           Take database and table name from there
105
 
    key                 Table cache key (db \0 table_name \0...)
106
 
    key_length          Length of key
107
 
 
108
 
  RETURN
109
 
    0  Error (out of memory)
110
 
    #  Share
111
 
*/
112
 
 
113
 
TableShare *alloc_table_share(TableList *table_list, char *key,
114
 
                               uint32_t key_length)
115
 
{
116
 
  memory::Root mem_root;
117
 
  TableShare *share;
118
 
  char *key_buff, *path_buff;
119
 
  char path[FN_REFLEN];
120
 
  uint32_t path_length;
121
 
 
122
 
  path_length= build_table_filename(path, sizeof(path) - 1,
123
 
                                    table_list->db,
124
 
                                    table_list->table_name, false);
125
 
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
126
 
  if (multi_alloc_root(&mem_root,
127
 
                       &share, sizeof(*share),
128
 
                       &key_buff, key_length,
129
 
                       &path_buff, path_length + 1,
130
 
                       NULL))
131
 
  {
132
 
    memset(share, 0, sizeof(*share));
133
 
 
134
 
    share->set_table_cache_key(key_buff, key, key_length);
135
 
 
136
 
    share->path.str= path_buff;
137
 
    share->path.length= path_length;
138
 
    strcpy(share->path.str, path);
139
 
    share->normalized_path.str=    share->path.str;
140
 
    share->normalized_path.length= path_length;
141
 
 
142
 
    share->version=       refresh_version;
143
 
 
144
 
    memcpy(&share->mem_root, &mem_root, sizeof(mem_root));
145
 
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
146
 
    pthread_cond_init(&share->cond, NULL);
147
 
  }
148
 
  return(share);
149
 
}
150
 
 
151
 
 
152
 
static enum_field_types proto_field_type_to_drizzle_type(uint32_t proto_field_type)
153
 
{
154
 
  enum_field_types field_type;
155
 
 
156
 
  switch(proto_field_type)
157
 
  {
158
 
  case message::Table::Field::INTEGER:
159
 
    field_type= DRIZZLE_TYPE_LONG;
160
 
    break;
161
 
  case message::Table::Field::DOUBLE:
162
 
    field_type= DRIZZLE_TYPE_DOUBLE;
163
 
    break;
164
 
  case message::Table::Field::TIMESTAMP:
165
 
    field_type= DRIZZLE_TYPE_TIMESTAMP;
166
 
    break;
167
 
  case message::Table::Field::BIGINT:
168
 
    field_type= DRIZZLE_TYPE_LONGLONG;
169
 
    break;
170
 
  case message::Table::Field::DATETIME:
171
 
    field_type= DRIZZLE_TYPE_DATETIME;
172
 
    break;
173
 
  case message::Table::Field::DATE:
174
 
    field_type= DRIZZLE_TYPE_DATE;
175
 
    break;
176
 
  case message::Table::Field::VARCHAR:
177
 
    field_type= DRIZZLE_TYPE_VARCHAR;
178
 
    break;
179
 
  case message::Table::Field::DECIMAL:
180
 
    field_type= DRIZZLE_TYPE_DECIMAL;
181
 
    break;
182
 
  case message::Table::Field::ENUM:
183
 
    field_type= DRIZZLE_TYPE_ENUM;
184
 
    break;
185
 
  case message::Table::Field::BLOB:
186
 
    field_type= DRIZZLE_TYPE_BLOB;
187
 
    break;
188
 
  default:
189
 
    field_type= DRIZZLE_TYPE_LONG; /* Set value to kill GCC warning */
190
 
    assert(1);
191
 
  }
192
 
 
193
 
  return field_type;
194
 
}
195
 
 
196
 
static Item *default_value_item(enum_field_types field_type,
197
 
                                const CHARSET_INFO *charset,
198
 
                                bool default_null, const string *default_value,
199
 
                                const string *default_bin_value)
200
 
{
201
 
  Item *default_item= NULL;
202
 
  int error= 0;
203
 
 
204
 
  if (default_null)
205
 
  {
206
 
    return new Item_null();
207
 
  }
208
 
 
209
 
  switch(field_type)
210
 
  {
211
 
  case DRIZZLE_TYPE_LONG:
212
 
  case DRIZZLE_TYPE_LONGLONG:
213
 
    default_item= new Item_int(default_value->c_str(),
214
 
                               (int64_t) internal::my_strtoll10(default_value->c_str(),
215
 
                                                                NULL,
216
 
                                                                &error),
217
 
                               default_value->length());
218
 
    break;
219
 
  case DRIZZLE_TYPE_DOUBLE:
220
 
    default_item= new Item_float(default_value->c_str(),
221
 
                                 default_value->length());
222
 
    break;
223
 
  case DRIZZLE_TYPE_NULL:
224
 
    assert(false);
225
 
  case DRIZZLE_TYPE_TIMESTAMP:
226
 
  case DRIZZLE_TYPE_DATETIME:
227
 
  case DRIZZLE_TYPE_DATE:
228
 
    if (default_value->compare("NOW()") == 0)
229
 
      break;
230
 
  case DRIZZLE_TYPE_ENUM:
231
 
    default_item= new Item_string(default_value->c_str(),
232
 
                                  default_value->length(),
233
 
                                  system_charset_info);
234
 
    break;
235
 
  case DRIZZLE_TYPE_VARCHAR:
236
 
  case DRIZZLE_TYPE_BLOB: /* Blob is here due to TINYTEXT. Feel the hate. */
237
 
    if (charset==&my_charset_bin)
238
 
    {
239
 
      default_item= new Item_string(default_bin_value->c_str(),
240
 
                                    default_bin_value->length(),
241
 
                                    &my_charset_bin);
242
 
    }
243
 
    else
244
 
    {
245
 
      default_item= new Item_string(default_value->c_str(),
246
 
                                    default_value->length(),
247
 
                                    system_charset_info);
248
 
    }
249
 
    break;
250
 
  case DRIZZLE_TYPE_DECIMAL:
251
 
    default_item= new Item_decimal(default_value->c_str(),
252
 
                                   default_value->length(),
253
 
                                   system_charset_info);
254
 
    break;
255
 
  }
256
 
 
257
 
  return default_item;
258
 
}
259
 
 
260
 
int parse_table_proto(Session& session,
261
 
                      message::Table &table,
262
 
                      TableShare *share)
263
 
{
264
 
  int error= 0;
265
 
 
266
 
  if (! table.IsInitialized())
267
 
  {
268
 
    my_error(ER_CORRUPT_TABLE_DEFINITION, MYF(0), table.InitializationErrorString().c_str());
269
 
    return ER_CORRUPT_TABLE_DEFINITION;
270
 
  }
271
 
 
272
 
  share->setTableProto(new(nothrow) message::Table(table));
273
 
 
274
 
  share->storage_engine= plugin::StorageEngine::findByName(session, table.engine().name());
275
 
  assert(share->storage_engine); // We use an assert() here because we should never get this far and still have no suitable engine.
276
 
 
277
 
  message::Table::TableOptions table_options;
278
 
 
279
 
  if (table.has_options())
280
 
    table_options= table.options();
281
 
 
282
 
  uint32_t db_create_options= 0;
283
 
 
284
 
  if (table_options.has_pack_keys())
285
 
  {
286
 
    if (table_options.pack_keys())
287
 
      db_create_options|= HA_OPTION_PACK_KEYS;
288
 
    else
289
 
      db_create_options|= HA_OPTION_NO_PACK_KEYS;
290
 
  }
291
 
 
292
 
  if (table_options.pack_record())
293
 
    db_create_options|= HA_OPTION_PACK_RECORD;
294
 
 
295
 
  /* db_create_options was stored as 2 bytes in FRM
296
 
     Any HA_OPTION_ that doesn't fit into 2 bytes was silently truncated away.
297
 
   */
298
 
  share->db_create_options= (db_create_options & 0x0000FFFF);
299
 
  share->db_options_in_use= share->db_create_options;
300
 
 
301
 
  share->row_type= table_options.has_row_type() ?
302
 
    (enum row_type) table_options.row_type() : ROW_TYPE_DEFAULT;
303
 
 
304
 
  share->block_size= table_options.has_block_size() ?
305
 
    table_options.block_size() : 0;
306
 
 
307
 
  share->table_charset= get_charset(table_options.has_collation_id()?
308
 
                                    table_options.collation_id() : 0);
309
 
 
310
 
  if (!share->table_charset)
311
 
  {
312
 
    /* unknown charset in head[38] or pre-3.23 frm */
313
 
    if (use_mb(default_charset_info))
314
 
    {
315
 
      /* Warn that we may be changing the size of character columns */
316
 
      errmsg_printf(ERRMSG_LVL_WARN,
317
 
                    _("'%s' had no or invalid character set, "
318
 
                      "and default character set is multi-byte, "
319
 
                      "so character column sizes may have changed"),
320
 
                    share->path.str);
321
 
    }
322
 
    share->table_charset= default_charset_info;
323
 
  }
324
 
 
325
 
  share->db_record_offset= 1;
326
 
 
327
 
  share->blob_ptr_size= portable_sizeof_char_ptr; // more bonghits.
328
 
 
329
 
  share->keys= table.indexes_size();
330
 
 
331
 
  share->key_parts= 0;
332
 
  for (int indx= 0; indx < table.indexes_size(); indx++)
333
 
    share->key_parts+= table.indexes(indx).index_part_size();
334
 
 
335
 
  share->key_info= (KEY*) alloc_root(&share->mem_root,
336
 
                                     table.indexes_size() * sizeof(KEY)
337
 
                                     +share->key_parts*sizeof(KEY_PART_INFO));
338
 
 
339
 
  KEY_PART_INFO *key_part;
340
 
 
341
 
  key_part= reinterpret_cast<KEY_PART_INFO*>
342
 
    (share->key_info+table.indexes_size());
343
 
 
344
 
 
345
 
  ulong *rec_per_key= (ulong*) alloc_root(&share->mem_root,
346
 
                                            sizeof(ulong*)*share->key_parts);
347
 
 
348
 
  share->keynames.count= table.indexes_size();
349
 
  share->keynames.name= NULL;
350
 
  share->keynames.type_names= (const char**)
351
 
    alloc_root(&share->mem_root, sizeof(char*) * (table.indexes_size()+1));
352
 
 
353
 
  share->keynames.type_lengths= (unsigned int*)
354
 
    alloc_root(&share->mem_root,
355
 
               sizeof(unsigned int) * (table.indexes_size()+1));
356
 
 
357
 
  share->keynames.type_names[share->keynames.count]= NULL;
358
 
  share->keynames.type_lengths[share->keynames.count]= 0;
359
 
 
360
 
  KEY* keyinfo= share->key_info;
361
 
  for (int keynr= 0; keynr < table.indexes_size(); keynr++, keyinfo++)
362
 
  {
363
 
    message::Table::Index indx= table.indexes(keynr);
364
 
 
365
 
    keyinfo->table= 0;
366
 
    keyinfo->flags= 0;
367
 
 
368
 
    if (indx.is_unique())
369
 
      keyinfo->flags|= HA_NOSAME;
370
 
 
371
 
    if (indx.has_options())
372
 
    {
373
 
      message::Table::Index::IndexOptions indx_options= indx.options();
374
 
      if (indx_options.pack_key())
375
 
        keyinfo->flags|= HA_PACK_KEY;
376
 
 
377
 
      if (indx_options.var_length_key())
378
 
        keyinfo->flags|= HA_VAR_LENGTH_PART;
379
 
 
380
 
      if (indx_options.null_part_key())
381
 
        keyinfo->flags|= HA_NULL_PART_KEY;
382
 
 
383
 
      if (indx_options.binary_pack_key())
384
 
        keyinfo->flags|= HA_BINARY_PACK_KEY;
385
 
 
386
 
      if (indx_options.has_partial_segments())
387
 
        keyinfo->flags|= HA_KEY_HAS_PART_KEY_SEG;
388
 
 
389
 
      if (indx_options.auto_generated_key())
390
 
        keyinfo->flags|= HA_GENERATED_KEY;
391
 
 
392
 
      if (indx_options.has_key_block_size())
393
 
      {
394
 
        keyinfo->flags|= HA_USES_BLOCK_SIZE;
395
 
        keyinfo->block_size= indx_options.key_block_size();
396
 
      }
397
 
      else
398
 
      {
399
 
        keyinfo->block_size= 0;
400
 
      }
401
 
    }
402
 
 
403
 
    switch (indx.type())
404
 
    {
405
 
    case message::Table::Index::UNKNOWN_INDEX:
406
 
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
407
 
      break;
408
 
    case message::Table::Index::BTREE:
409
 
      keyinfo->algorithm= HA_KEY_ALG_BTREE;
410
 
      break;
411
 
    case message::Table::Index::HASH:
412
 
      keyinfo->algorithm= HA_KEY_ALG_HASH;
413
 
      break;
414
 
 
415
 
    default:
416
 
      /* TODO: suitable warning ? */
417
 
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
418
 
      break;
419
 
    }
420
 
 
421
 
    keyinfo->key_length= indx.key_length();
422
 
 
423
 
    keyinfo->key_parts= indx.index_part_size();
424
 
 
425
 
    keyinfo->key_part= key_part;
426
 
    keyinfo->rec_per_key= rec_per_key;
427
 
 
428
 
    for (unsigned int partnr= 0;
429
 
         partnr < keyinfo->key_parts;
430
 
         partnr++, key_part++)
431
 
    {
432
 
      message::Table::Index::IndexPart part;
433
 
      part= indx.index_part(partnr);
434
 
 
435
 
      *rec_per_key++= 0;
436
 
 
437
 
      key_part->field= NULL;
438
 
      key_part->fieldnr= part.fieldnr() + 1; // start from 1.
439
 
      key_part->null_bit= 0;
440
 
      /* key_part->null_offset is only set if null_bit (see later) */
441
 
      /* key_part->key_type= */ /* I *THINK* this may be okay.... */
442
 
      /* key_part->type ???? */
443
 
      key_part->key_part_flag= 0;
444
 
      if (part.has_in_reverse_order())
445
 
        key_part->key_part_flag= part.in_reverse_order()? HA_REVERSE_SORT : 0;
446
 
 
447
 
      key_part->length= part.compare_length();
448
 
 
449
 
      key_part->store_length= key_part->length;
450
 
 
451
 
      /* key_part->offset is set later */
452
 
      key_part->key_type= part.key_type();
453
 
    }
454
 
 
455
 
    if (! indx.has_comment())
456
 
    {
457
 
      keyinfo->comment.length= 0;
458
 
      keyinfo->comment.str= NULL;
459
 
    }
460
 
    else
461
 
    {
462
 
      keyinfo->flags|= HA_USES_COMMENT;
463
 
      keyinfo->comment.length= indx.comment().length();
464
 
      keyinfo->comment.str= strmake_root(&share->mem_root,
465
 
                                         indx.comment().c_str(),
466
 
                                         keyinfo->comment.length);
467
 
    }
468
 
 
469
 
    keyinfo->name= strmake_root(&share->mem_root,
470
 
                                indx.name().c_str(),
471
 
                                indx.name().length());
472
 
 
473
 
    share->keynames.type_names[keynr]= keyinfo->name;
474
 
    share->keynames.type_lengths[keynr]= indx.name().length();
475
 
  }
476
 
 
477
 
  share->keys_for_keyread.reset();
478
 
  set_prefix(share->keys_in_use, share->keys);
479
 
 
480
 
  share->fields= table.field_size();
481
 
 
482
 
  share->field= (Field**) alloc_root(&share->mem_root,
483
 
                                     ((share->fields+1) * sizeof(Field*)));
484
 
  share->field[share->fields]= NULL;
485
 
 
486
 
  uint32_t null_fields= 0;
487
 
  share->reclength= 0;
488
 
 
489
 
  uint32_t *field_offsets= (uint32_t*)malloc(share->fields * sizeof(uint32_t));
490
 
  uint32_t *field_pack_length=(uint32_t*)malloc(share->fields*sizeof(uint32_t));
491
 
 
492
 
  assert(field_offsets && field_pack_length); // TODO: fixme
493
 
 
494
 
  uint32_t interval_count= 0;
495
 
  uint32_t interval_parts= 0;
496
 
 
497
 
  uint32_t stored_columns_reclength= 0;
498
 
 
499
 
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
500
 
  {
501
 
    message::Table::Field pfield= table.field(fieldnr);
502
 
    if (pfield.constraints().is_nullable())
503
 
      null_fields++;
504
 
 
505
 
    enum_field_types drizzle_field_type=
506
 
      proto_field_type_to_drizzle_type(pfield.type());
507
 
 
508
 
    field_offsets[fieldnr]= stored_columns_reclength;
509
 
 
510
 
    /* the below switch is very similar to
511
 
       CreateField::create_length_to_internal_length in field.cc
512
 
       (which should one day be replace by just this code)
513
 
    */
514
 
    switch(drizzle_field_type)
515
 
    {
516
 
    case DRIZZLE_TYPE_BLOB:
517
 
    case DRIZZLE_TYPE_VARCHAR:
518
 
      {
519
 
        message::Table::Field::StringFieldOptions field_options= pfield.string_options();
520
 
 
521
 
        const CHARSET_INFO *cs= get_charset(field_options.has_collation_id() ?
522
 
                                            field_options.collation_id() : 0);
523
 
 
524
 
        if (! cs)
525
 
          cs= default_charset_info;
526
 
 
527
 
        field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type,
528
 
                                                     field_options.length() * cs->mbmaxlen);
529
 
      }
530
 
      break;
531
 
    case DRIZZLE_TYPE_ENUM:
532
 
      {
533
 
        message::Table::Field::SetFieldOptions field_options= pfield.set_options();
534
 
 
535
 
        field_pack_length[fieldnr]=
536
 
          get_enum_pack_length(field_options.field_value_size());
537
 
 
538
 
        interval_count++;
539
 
        interval_parts+= field_options.field_value_size();
540
 
      }
541
 
      break;
542
 
    case DRIZZLE_TYPE_DECIMAL:
543
 
      {
544
 
        message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
545
 
 
546
 
        field_pack_length[fieldnr]= my_decimal_get_binary_size(fo.precision(), fo.scale());
547
 
      }
548
 
      break;
549
 
    default:
550
 
      /* Zero is okay here as length is fixed for other types. */
551
 
      field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type, 0);
552
 
    }
553
 
 
554
 
    share->reclength+= field_pack_length[fieldnr];
555
 
    stored_columns_reclength+= field_pack_length[fieldnr];
556
 
  }
557
 
 
558
 
  /* data_offset added to stored_rec_length later */
559
 
  share->stored_rec_length= stored_columns_reclength;
560
 
 
561
 
  share->null_fields= null_fields;
562
 
 
563
 
  ulong null_bits= null_fields;
564
 
  if (! table_options.pack_record())
565
 
    null_bits++;
566
 
  ulong data_offset= (null_bits + 7)/8;
567
 
 
568
 
 
569
 
  share->reclength+= data_offset;
570
 
  share->stored_rec_length+= data_offset;
571
 
 
572
 
  ulong rec_buff_length;
573
 
 
574
 
  rec_buff_length= ALIGN_SIZE(share->reclength + 1);
575
 
  share->rec_buff_length= rec_buff_length;
576
 
 
577
 
  unsigned char* record= NULL;
578
 
 
579
 
  if (! (record= (unsigned char *) alloc_root(&share->mem_root,
580
 
                                              rec_buff_length)))
581
 
    abort();
582
 
 
583
 
  memset(record, 0, rec_buff_length);
584
 
 
585
 
  int null_count= 0;
586
 
 
587
 
  if (! table_options.pack_record())
588
 
  {
589
 
    null_count++; // one bit for delete mark.
590
 
    *record|= 1;
591
 
  }
592
 
 
593
 
  share->default_values= record;
594
 
 
595
 
  if (interval_count)
596
 
  {
597
 
    share->intervals= (TYPELIB *) alloc_root(&share->mem_root,
598
 
                                           interval_count*sizeof(TYPELIB));
599
 
  }
600
 
  else
601
 
    share->intervals= NULL;
602
 
 
603
 
  share->fieldnames.type_names= (const char **) alloc_root(&share->mem_root,
604
 
                                                          (share->fields + 1) * sizeof(char*));
605
 
 
606
 
  share->fieldnames.type_lengths= (unsigned int *) alloc_root(&share->mem_root,
607
 
                                                             (share->fields + 1) * sizeof(unsigned int));
608
 
 
609
 
  share->fieldnames.type_names[share->fields]= NULL;
610
 
  share->fieldnames.type_lengths[share->fields]= 0;
611
 
  share->fieldnames.count= share->fields;
612
 
 
613
 
 
614
 
  /* Now fix the TYPELIBs for the intervals (enum values)
615
 
     and field names.
616
 
   */
617
 
 
618
 
  uint32_t interval_nr= 0;
619
 
 
620
 
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
621
 
  {
622
 
    message::Table::Field pfield= table.field(fieldnr);
623
 
 
624
 
    /* field names */
625
 
    share->fieldnames.type_names[fieldnr]= strmake_root(&share->mem_root,
626
 
                                                        pfield.name().c_str(),
627
 
                                                        pfield.name().length());
628
 
 
629
 
    share->fieldnames.type_lengths[fieldnr]= pfield.name().length();
630
 
 
631
 
    /* enum typelibs */
632
 
    if (pfield.type() != message::Table::Field::ENUM)
633
 
      continue;
634
 
 
635
 
    message::Table::Field::SetFieldOptions field_options= pfield.set_options();
636
 
 
637
 
    const CHARSET_INFO *charset= get_charset(field_options.has_collation_id() ?
638
 
                                             field_options.collation_id() : 0);
639
 
 
640
 
    if (! charset)
641
 
      charset= default_charset_info;
642
 
 
643
 
    TYPELIB *t= &(share->intervals[interval_nr]);
644
 
 
645
 
    t->type_names= (const char**)alloc_root(&share->mem_root,
646
 
                                            (field_options.field_value_size() + 1) * sizeof(char*));
647
 
 
648
 
    t->type_lengths= (unsigned int*) alloc_root(&share->mem_root,
649
 
                                                (field_options.field_value_size() + 1) * sizeof(unsigned int));
650
 
 
651
 
    t->type_names[field_options.field_value_size()]= NULL;
652
 
    t->type_lengths[field_options.field_value_size()]= 0;
653
 
 
654
 
    t->count= field_options.field_value_size();
655
 
    t->name= NULL;
656
 
 
657
 
    for (int n= 0; n < field_options.field_value_size(); n++)
658
 
    {
659
 
      t->type_names[n]= strmake_root(&share->mem_root,
660
 
                                     field_options.field_value(n).c_str(),
661
 
                                     field_options.field_value(n).length());
662
 
 
663
 
      /* 
664
 
       * Go ask the charset what the length is as for "" length=1
665
 
       * and there's stripping spaces or some other crack going on.
666
 
       */
667
 
      uint32_t lengthsp;
668
 
      lengthsp= charset->cset->lengthsp(charset,
669
 
                                        t->type_names[n],
670
 
                                        field_options.field_value(n).length());
671
 
      t->type_lengths[n]= lengthsp;
672
 
    }
673
 
    interval_nr++;
674
 
  }
675
 
 
676
 
 
677
 
  /* and read the fields */
678
 
  interval_nr= 0;
679
 
 
680
 
  bool use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
681
 
 
682
 
  if (use_hash)
683
 
    use_hash= ! hash_init(&share->name_hash,
684
 
                          system_charset_info,
685
 
                          share->fields,
686
 
                          0,
687
 
                          0,
688
 
                          (hash_get_key) get_field_name,
689
 
                          0,
690
 
                          0);
691
 
 
692
 
  unsigned char* null_pos= record;;
693
 
  int null_bit_pos= (table_options.pack_record()) ? 0 : 1;
694
 
 
695
 
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
696
 
  {
697
 
    message::Table::Field pfield= table.field(fieldnr);
698
 
 
699
 
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
700
 
 
701
 
    switch (pfield.format())
702
 
    {
703
 
    case message::Table::Field::DefaultFormat:
704
 
      column_format= COLUMN_FORMAT_TYPE_DEFAULT;
705
 
      break;
706
 
    case message::Table::Field::FixedFormat:
707
 
      column_format= COLUMN_FORMAT_TYPE_FIXED;
708
 
      break;
709
 
    case message::Table::Field::DynamicFormat:
710
 
      column_format= COLUMN_FORMAT_TYPE_DYNAMIC;
711
 
      break;
712
 
    default:
713
 
      assert(1);
714
 
    }
715
 
 
716
 
    Field::utype unireg_type= Field::NONE;
717
 
 
718
 
    if (pfield.has_numeric_options() &&
719
 
        pfield.numeric_options().is_autoincrement())
720
 
    {
721
 
      unireg_type= Field::NEXT_NUMBER;
722
 
    }
723
 
 
724
 
    if (pfield.has_options() &&
725
 
        pfield.options().has_default_value() &&
726
 
        pfield.options().default_value().compare("NOW()") == 0)
727
 
    {
728
 
      if (pfield.options().has_update_value() &&
729
 
          pfield.options().update_value().compare("NOW()") == 0)
730
 
      {
731
 
        unireg_type= Field::TIMESTAMP_DNUN_FIELD;
732
 
      }
733
 
      else if (! pfield.options().has_update_value())
734
 
      {
735
 
        unireg_type= Field::TIMESTAMP_DN_FIELD;
736
 
      }
737
 
      else
738
 
        assert(1); // Invalid update value.
739
 
    }
740
 
    else if (pfield.has_options() &&
741
 
             pfield.options().has_update_value() &&
742
 
             pfield.options().update_value().compare("NOW()") == 0)
743
 
    {
744
 
      unireg_type= Field::TIMESTAMP_UN_FIELD;
745
 
    }
746
 
 
747
 
    LEX_STRING comment;
748
 
    if (!pfield.has_comment())
749
 
    {
750
 
      comment.str= (char*)"";
751
 
      comment.length= 0;
752
 
    }
753
 
    else
754
 
    {
755
 
      size_t len= pfield.comment().length();
756
 
      const char* str= pfield.comment().c_str();
757
 
 
758
 
      comment.str= strmake_root(&share->mem_root, str, len);
759
 
      comment.length= len;
760
 
    }
761
 
 
762
 
    enum_field_types field_type;
763
 
 
764
 
    field_type= proto_field_type_to_drizzle_type(pfield.type());
765
 
 
766
 
    const CHARSET_INFO *charset= &my_charset_bin;
767
 
 
768
 
    if (field_type == DRIZZLE_TYPE_BLOB ||
769
 
        field_type == DRIZZLE_TYPE_VARCHAR)
770
 
    {
771
 
      message::Table::Field::StringFieldOptions field_options= pfield.string_options();
772
 
 
773
 
      charset= get_charset(field_options.has_collation_id() ?
774
 
                           field_options.collation_id() : 0);
775
 
 
776
 
      if (! charset)
777
 
        charset= default_charset_info;
778
 
    }
779
 
 
780
 
    if (field_type == DRIZZLE_TYPE_ENUM)
781
 
    {
782
 
      message::Table::Field::SetFieldOptions field_options= pfield.set_options();
783
 
 
784
 
      charset= get_charset(field_options.has_collation_id()?
785
 
                           field_options.collation_id() : 0);
786
 
 
787
 
      if (! charset)
788
 
              charset= default_charset_info;
789
 
    }
790
 
 
791
 
    uint8_t decimals= 0;
792
 
    if (field_type == DRIZZLE_TYPE_DECIMAL
793
 
        || field_type == DRIZZLE_TYPE_DOUBLE)
794
 
    {
795
 
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
796
 
 
797
 
      if (! pfield.has_numeric_options() || ! fo.has_scale())
798
 
      {
799
 
        /*
800
 
          We don't write the default to table proto so
801
 
          if no decimals specified for DOUBLE, we use the default.
802
 
        */
803
 
        decimals= NOT_FIXED_DEC;
804
 
      }
805
 
      else
806
 
      {
807
 
        if (fo.scale() > DECIMAL_MAX_SCALE)
808
 
        {
809
 
          error= 4;
810
 
          goto err;
811
 
        }
812
 
        decimals= static_cast<uint8_t>(fo.scale());
813
 
      }
814
 
    }
815
 
 
816
 
    Item *default_value= NULL;
817
 
 
818
 
    if (pfield.options().has_default_value() ||
819
 
        pfield.options().has_default_null()  ||
820
 
        pfield.options().has_default_bin_value())
821
 
    {
822
 
      default_value= default_value_item(field_type,
823
 
                                        charset,
824
 
                                        pfield.options().default_null(),
825
 
                                        &pfield.options().default_value(),
826
 
                                        &pfield.options().default_bin_value());
827
 
    }
828
 
 
829
 
 
830
 
    Table temp_table; /* Use this so that BLOB DEFAULT '' works */
831
 
    memset(&temp_table, 0, sizeof(temp_table));
832
 
    temp_table.s= share;
833
 
    temp_table.in_use= &session;
834
 
    temp_table.s->db_low_byte_first= true; //Cursor->low_byte_first();
835
 
    temp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
836
 
 
837
 
    uint32_t field_length= 0; //Assignment is for compiler complaint.
838
 
 
839
 
    switch (field_type)
840
 
    {
841
 
    case DRIZZLE_TYPE_BLOB:
842
 
    case DRIZZLE_TYPE_VARCHAR:
843
 
    {
844
 
      message::Table::Field::StringFieldOptions field_options= pfield.string_options();
845
 
 
846
 
      charset= get_charset(field_options.has_collation_id() ?
847
 
                           field_options.collation_id() : 0);
848
 
 
849
 
      if (! charset)
850
 
        charset= default_charset_info;
851
 
 
852
 
      field_length= field_options.length() * charset->mbmaxlen;
853
 
    }
854
 
      break;
855
 
    case DRIZZLE_TYPE_DOUBLE:
856
 
    {
857
 
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
858
 
      if (!fo.has_precision() && !fo.has_scale())
859
 
      {
860
 
        field_length= DBL_DIG+7;
861
 
      }
862
 
      else
863
 
      {
864
 
        field_length= fo.precision();
865
 
      }
866
 
      if (field_length < decimals &&
867
 
          decimals != NOT_FIXED_DEC)
868
 
      {
869
 
        my_error(ER_M_BIGGER_THAN_D, MYF(0), pfield.name().c_str());
870
 
        error= 1;
871
 
        goto err;
872
 
      }
873
 
      break;
874
 
    }
875
 
    case DRIZZLE_TYPE_DECIMAL:
876
 
    {
877
 
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
878
 
 
879
 
      field_length= my_decimal_precision_to_length(fo.precision(), fo.scale(),
880
 
                                                   false);
881
 
      break;
882
 
    }
883
 
    case DRIZZLE_TYPE_TIMESTAMP:
884
 
    case DRIZZLE_TYPE_DATETIME:
885
 
      field_length= DateTime::MAX_STRING_LENGTH;
886
 
      break;
887
 
    case DRIZZLE_TYPE_DATE:
888
 
      field_length= Date::MAX_STRING_LENGTH;
889
 
      break;
890
 
    case DRIZZLE_TYPE_ENUM:
891
 
    {
892
 
      field_length= 0;
893
 
 
894
 
      message::Table::Field::SetFieldOptions fo= pfield.set_options();
895
 
 
896
 
      for(int valnr= 0; valnr < fo.field_value_size(); valnr++)
897
 
      {
898
 
        if (fo.field_value(valnr).length() > field_length)
899
 
          field_length= charset->cset->numchars(charset,
900
 
                                                fo.field_value(valnr).c_str(),
901
 
                                                fo.field_value(valnr).c_str()
902
 
                                                + fo.field_value(valnr).length())
903
 
            * charset->mbmaxlen;
904
 
      }
905
 
    }
906
 
      break;
907
 
    case DRIZZLE_TYPE_LONG:
908
 
      {
909
 
        uint32_t sign_len= pfield.constraints().is_unsigned() ? 0 : 1;
910
 
          field_length= MAX_INT_WIDTH+sign_len;
911
 
      }
912
 
      break;
913
 
    case DRIZZLE_TYPE_LONGLONG:
914
 
      field_length= MAX_BIGINT_WIDTH;
915
 
      break;
916
 
    case DRIZZLE_TYPE_NULL:
917
 
      abort(); // Programming error
918
 
    }
919
 
 
920
 
    Field* f= make_field(share,
921
 
                         &share->mem_root,
922
 
                         record + field_offsets[fieldnr] + data_offset,
923
 
                         field_length,
924
 
                         pfield.constraints().is_nullable(),
925
 
                         null_pos,
926
 
                         null_bit_pos,
927
 
                         decimals,
928
 
                         field_type,
929
 
                         charset,
930
 
                         (Field::utype) MTYP_TYPENR(unireg_type),
931
 
                         ((field_type == DRIZZLE_TYPE_ENUM) ?
932
 
                          share->intervals + (interval_nr++)
933
 
                          : (TYPELIB*) 0),
934
 
                         share->fieldnames.type_names[fieldnr]);
935
 
 
936
 
    share->field[fieldnr]= f;
937
 
 
938
 
    f->init(&temp_table); /* blob default values need table obj */
939
 
 
940
 
    if (! (f->flags & NOT_NULL_FLAG))
941
 
    {
942
 
      *f->null_ptr|= f->null_bit;
943
 
      if (! (null_bit_pos= (null_bit_pos + 1) & 7)) /* @TODO Ugh. */
944
 
        null_pos++;
945
 
      null_count++;
946
 
    }
947
 
 
948
 
    if (default_value)
949
 
    {
950
 
      enum_check_fields old_count_cuted_fields= session.count_cuted_fields;
951
 
      session.count_cuted_fields= CHECK_FIELD_WARN;
952
 
      int res= default_value->save_in_field(f, 1);
953
 
      session.count_cuted_fields= old_count_cuted_fields;
954
 
      if (res != 0 && res != 3) /* @TODO Huh? */
955
 
      {
956
 
        my_error(ER_INVALID_DEFAULT, MYF(0), f->field_name);
957
 
        error= 1;
958
 
        goto err;
959
 
      }
960
 
    }
961
 
    else if (f->real_type() == DRIZZLE_TYPE_ENUM &&
962
 
             (f->flags & NOT_NULL_FLAG))
963
 
    {
964
 
      f->set_notnull();
965
 
      f->store((int64_t) 1, true);
966
 
    }
967
 
    else
968
 
      f->reset();
969
 
 
970
 
    /* hack to undo f->init() */
971
 
    f->table= NULL;
972
 
    f->orig_table= NULL;
973
 
 
974
 
    f->field_index= fieldnr;
975
 
    f->comment= comment;
976
 
    if (! default_value &&
977
 
        ! (f->unireg_check==Field::NEXT_NUMBER) &&
978
 
        (f->flags & NOT_NULL_FLAG) &&
979
 
        (f->real_type() != DRIZZLE_TYPE_TIMESTAMP))
980
 
    {
981
 
      f->flags|= NO_DEFAULT_VALUE_FLAG;
982
 
    }
983
 
 
984
 
    if (f->unireg_check == Field::NEXT_NUMBER)
985
 
      share->found_next_number_field= &(share->field[fieldnr]);
986
 
 
987
 
    if (share->timestamp_field == f)
988
 
      share->timestamp_field_offset= fieldnr;
989
 
 
990
 
    if (use_hash) /* supposedly this never fails... but comments lie */
991
 
      (void) my_hash_insert(&share->name_hash,
992
 
                            (unsigned char*)&(share->field[fieldnr]));
993
 
 
994
 
  }
995
 
 
996
 
  keyinfo= share->key_info;
997
 
  for (unsigned int keynr= 0; keynr < share->keys; keynr++, keyinfo++)
998
 
  {
999
 
    key_part= keyinfo->key_part;
1000
 
 
1001
 
    for (unsigned int partnr= 0;
1002
 
         partnr < keyinfo->key_parts;
1003
 
         partnr++, key_part++)
1004
 
    {
1005
 
      /* 
1006
 
       * Fix up key_part->offset by adding data_offset.
1007
 
       * We really should compute offset as well.
1008
 
       * But at least this way we are a little better.
1009
 
       */
1010
 
      key_part->offset= field_offsets[key_part->fieldnr-1] + data_offset;
1011
 
    }
1012
 
  }
1013
 
 
1014
 
  /*
1015
 
    We need to set the unused bits to 1. If the number of bits is a multiple
1016
 
    of 8 there are no unused bits.
1017
 
  */
1018
 
 
1019
 
  if (null_count & 7)
1020
 
    *(record + null_count / 8)|= ~(((unsigned char) 1 << (null_count & 7)) - 1);
1021
 
 
1022
 
  share->null_bytes= (null_pos - (unsigned char*) record + (null_bit_pos + 7) / 8);
1023
 
 
1024
 
  share->last_null_bit_pos= null_bit_pos;
1025
 
 
1026
 
  free(field_offsets);
1027
 
  field_offsets= NULL;
1028
 
  free(field_pack_length);
1029
 
  field_pack_length= NULL;
1030
 
 
1031
 
  /* Fix key stuff */
1032
 
  if (share->key_parts)
1033
 
  {
1034
 
    uint32_t primary_key= (uint32_t) (find_type((char*) "PRIMARY",
1035
 
                                                &share->keynames, 3) - 1); /* @TODO Huh? */
1036
 
 
1037
 
    keyinfo= share->key_info;
1038
 
    key_part= keyinfo->key_part;
1039
 
 
1040
 
    for (uint32_t key= 0; key < share->keys; key++,keyinfo++)
1041
 
    {
1042
 
      uint32_t usable_parts= 0;
1043
 
 
1044
 
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
1045
 
      {
1046
 
        /*
1047
 
          If the UNIQUE key doesn't have NULL columns and is not a part key
1048
 
          declare this as a primary key.
1049
 
        */
1050
 
        primary_key=key;
1051
 
        for (uint32_t i= 0; i < keyinfo->key_parts; i++)
1052
 
        {
1053
 
          uint32_t fieldnr= key_part[i].fieldnr;
1054
 
          if (! fieldnr ||
1055
 
              share->field[fieldnr-1]->null_ptr ||
1056
 
              share->field[fieldnr-1]->key_length() != key_part[i].length)
1057
 
          {
1058
 
            primary_key= MAX_KEY; // Can't be used
1059
 
            break;
1060
 
          }
1061
 
        }
1062
 
      }
1063
 
 
1064
 
      for (uint32_t i= 0 ; i < keyinfo->key_parts ; key_part++,i++)
1065
 
      {
1066
 
        Field *field;
1067
 
        if (! key_part->fieldnr)
1068
 
        {
1069
 
          abort(); // goto err;
1070
 
        }
1071
 
        field= key_part->field= share->field[key_part->fieldnr-1];
1072
 
        key_part->type= field->key_type();
1073
 
        if (field->null_ptr)
1074
 
        {
1075
 
          key_part->null_offset=(uint32_t) ((unsigned char*) field->null_ptr -
1076
 
                                        share->default_values);
1077
 
          key_part->null_bit= field->null_bit;
1078
 
          key_part->store_length+=HA_KEY_NULL_LENGTH;
1079
 
          keyinfo->flags|=HA_NULL_PART_KEY;
1080
 
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
1081
 
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
1082
 
        }
1083
 
        if (field->type() == DRIZZLE_TYPE_BLOB ||
1084
 
            field->real_type() == DRIZZLE_TYPE_VARCHAR)
1085
 
        {
1086
 
          if (field->type() == DRIZZLE_TYPE_BLOB)
1087
 
            key_part->key_part_flag|= HA_BLOB_PART;
1088
 
          else
1089
 
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
1090
 
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
1091
 
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
1092
 
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
1093
 
        }
1094
 
        if (i == 0 && key != primary_key)
1095
 
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
1096
 
                           (keyinfo->key_parts == 1)) ?
1097
 
                           UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
1098
 
        if (i == 0)
1099
 
          field->key_start.set(key);
1100
 
        if (field->key_length() == key_part->length &&
1101
 
            !(field->flags & BLOB_FLAG))
1102
 
        {
1103
 
          enum ha_key_alg algo= share->key_info[key].algorithm;
1104
 
          if (share->db_type()->index_flags(algo) & HA_KEYREAD_ONLY)
1105
 
          {
1106
 
            share->keys_for_keyread.set(key);
1107
 
            field->part_of_key.set(key);
1108
 
            field->part_of_key_not_clustered.set(key);
1109
 
          }
1110
 
          if (share->db_type()->index_flags(algo) & HA_READ_ORDER)
1111
 
            field->part_of_sortkey.set(key);
1112
 
        }
1113
 
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
1114
 
            usable_parts == i)
1115
 
          usable_parts++;                       // For FILESORT
1116
 
        field->flags|= PART_KEY_FLAG;
1117
 
        if (key == primary_key)
1118
 
        {
1119
 
          field->flags|= PRI_KEY_FLAG;
1120
 
          /*
1121
 
            If this field is part of the primary key and all keys contains
1122
 
            the primary key, then we can use any key to find this column
1123
 
          */
1124
 
          if (share->storage_engine->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX))
1125
 
          {
1126
 
            field->part_of_key= share->keys_in_use;
1127
 
            if (field->part_of_sortkey.test(key))
1128
 
              field->part_of_sortkey= share->keys_in_use;
1129
 
          }
1130
 
        }
1131
 
        if (field->key_length() != key_part->length)
1132
 
        {
1133
 
          key_part->key_part_flag|= HA_PART_KEY_SEG;
1134
 
        }
1135
 
      }
1136
 
      keyinfo->usable_key_parts= usable_parts; // Filesort
1137
 
 
1138
 
      set_if_bigger(share->max_key_length,keyinfo->key_length+
1139
 
                    keyinfo->key_parts);
1140
 
      share->total_key_length+= keyinfo->key_length;
1141
 
 
1142
 
      if (keyinfo->flags & HA_NOSAME)
1143
 
      {
1144
 
        set_if_bigger(share->max_unique_length,keyinfo->key_length);
1145
 
      }
1146
 
    }
1147
 
    if (primary_key < MAX_KEY &&
1148
 
        (share->keys_in_use.test(primary_key)))
1149
 
    {
1150
 
      share->primary_key= primary_key;
1151
 
      /*
1152
 
        If we are using an integer as the primary key then allow the user to
1153
 
        refer to it as '_rowid'
1154
 
      */
1155
 
      if (share->key_info[primary_key].key_parts == 1)
1156
 
      {
1157
 
        Field *field= share->key_info[primary_key].key_part[0].field;
1158
 
        if (field && field->result_type() == INT_RESULT)
1159
 
        {
1160
 
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
1161
 
          share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
1162
 
                                      fieldnr);
1163
 
        }
1164
 
      }
1165
 
    }
1166
 
    else
1167
 
      share->primary_key = MAX_KEY; // we do not have a primary key
1168
 
  }
1169
 
  else
1170
 
    share->primary_key= MAX_KEY;
1171
 
 
1172
 
  if (share->found_next_number_field)
1173
 
  {
1174
 
    Field *reg_field= *share->found_next_number_field;
1175
 
    if ((int) (share->next_number_index= (uint32_t)
1176
 
               find_ref_key(share->key_info, share->keys,
1177
 
                            share->default_values, reg_field,
1178
 
                            &share->next_number_key_offset,
1179
 
                            &share->next_number_keypart)) < 0)
1180
 
    {
1181
 
      /* Wrong field definition */
1182
 
      error= 4;
1183
 
      goto err;
1184
 
    }
1185
 
    else
1186
 
      reg_field->flags |= AUTO_INCREMENT_FLAG;
1187
 
  }
1188
 
 
1189
 
  if (share->blob_fields)
1190
 
  {
1191
 
    Field **ptr;
1192
 
    uint32_t k, *save;
1193
 
 
1194
 
    /* Store offsets to blob fields to find them fast */
1195
 
    if (!(share->blob_field= save=
1196
 
          (uint*) alloc_root(&share->mem_root,
1197
 
                             (uint32_t) (share->blob_fields* sizeof(uint32_t)))))
1198
 
      goto err;
1199
 
    for (k= 0, ptr= share->field ; *ptr ; ptr++, k++)
1200
 
    {
1201
 
      if ((*ptr)->flags & BLOB_FLAG)
1202
 
        (*save++)= k;
1203
 
    }
1204
 
  }
1205
 
 
1206
 
  share->db_low_byte_first= true; // @todo Question this.
1207
 
  share->column_bitmap_size= bitmap_buffer_size(share->fields);
1208
 
 
1209
 
  my_bitmap_map *bitmaps;
1210
 
 
1211
 
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
1212
 
                                             share->column_bitmap_size)))
1213
 
    goto err;
1214
 
  share->all_set.init(bitmaps, share->fields);
1215
 
  share->all_set.setAll();
1216
 
 
1217
 
  return (0);
1218
 
 
1219
 
err:
1220
 
  if (field_offsets)
1221
 
    free(field_offsets);
1222
 
  if (field_pack_length)
1223
 
    free(field_pack_length);
1224
 
 
1225
 
  share->error= error;
1226
 
  share->open_errno= errno;
1227
 
  share->errarg= 0;
1228
 
  hash_free(&share->name_hash);
1229
 
  share->open_table_error(error, share->open_errno, 0);
1230
 
 
1231
 
  return error;
1232
 
}
1233
 
 
1234
 
/*
1235
 
  Read table definition from a binary / text based .frm cursor
1236
 
 
1237
 
  SYNOPSIS
1238
 
  open_table_def()
1239
 
  session               Thread Cursor
1240
 
  share         Fill this with table definition
1241
 
 
1242
 
  NOTES
1243
 
    This function is called when the table definition is not cached in
1244
 
    table_def_cache
1245
 
    The data is returned in 'share', which is alloced by
1246
 
    alloc_table_share().. The code assumes that share is initialized.
1247
 
 
1248
 
  RETURN VALUES
1249
 
   0    ok
1250
 
   1    Error (see open_table_error)
1251
 
   2    Error (see open_table_error)
1252
 
   3    Wrong data in .frm cursor
1253
 
   4    Error (see open_table_error)
1254
 
   5    Error (see open_table_error: charset unavailable)
1255
 
   6    Unknown .frm version
1256
 
*/
1257
 
 
1258
 
int open_table_def(Session& session, TableShare *share)
1259
 
{
1260
 
  int error;
1261
 
  bool error_given;
1262
 
 
1263
 
  error= 1;
1264
 
  error_given= 0;
1265
 
 
1266
 
  message::Table table;
1267
 
 
1268
 
  error= plugin::StorageEngine::getTableDefinition(session, share->normalized_path.str,
1269
 
                                                   share->db.str,
1270
 
                                                   share->table_name.str,
1271
 
                                                   false,
1272
 
                                                   &table);
1273
 
 
1274
 
  if (error != EEXIST)
1275
 
  {
1276
 
    if (error>0)
1277
 
    {
1278
 
      errno= error;
1279
 
      error= 1;
1280
 
    }
1281
 
    else
1282
 
    {
1283
 
      if (!table.IsInitialized())
1284
 
      {
1285
 
        error= 4;
1286
 
      }
1287
 
    }
1288
 
    goto err_not_open;
1289
 
  }
1290
 
 
1291
 
  error= parse_table_proto(session, table, share);
1292
 
 
1293
 
  share->table_category= get_table_category(& share->db);
1294
 
 
1295
 
  if (!error)
1296
 
    session.status_var.opened_shares++;
1297
 
 
1298
 
err_not_open:
1299
 
  if (error && !error_given)
1300
 
  {
1301
 
    share->error= error;
1302
 
    share->open_table_error(error, (share->open_errno= errno), 0);
1303
 
  }
1304
 
 
1305
 
  return(error);
1306
 
}
1307
 
 
1308
 
 
1309
 
/*
1310
 
  Open a table based on a TableShare
1311
 
 
1312
 
  SYNOPSIS
1313
 
    open_table_from_share()
1314
 
    session                     Thread Cursor
1315
 
    share               Table definition
1316
 
    alias               Alias for table
1317
 
    db_stat             open flags (for example HA_OPEN_KEYFILE|
1318
 
                        HA_OPEN_RNDFILE..) can be 0 (example in
1319
 
                        ha_example_table)
1320
 
    ha_open_flags       HA_OPEN_ABORT_IF_LOCKED etc..
1321
 
    outparam            result table
1322
 
 
1323
 
  RETURN VALUES
1324
 
   0    ok
1325
 
   1    Error (see open_table_error)
1326
 
   2    Error (see open_table_error)
1327
 
   3    Wrong data in .frm cursor
1328
 
   4    Error (see open_table_error)
1329
 
   5    Error (see open_table_error: charset unavailable)
1330
 
   7    Table definition has changed in engine
1331
 
*/
1332
 
 
1333
 
int open_table_from_share(Session *session, TableShare *share, const char *alias,
1334
 
                          uint32_t db_stat, uint32_t ha_open_flags,
1335
 
                          Table *outparam)
1336
 
{
1337
 
  int error;
1338
 
  uint32_t records, i, bitmap_size;
1339
 
  bool error_reported= false;
1340
 
  unsigned char *record, *bitmaps;
1341
 
  Field **field_ptr;
1342
 
 
1343
 
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1344
 
  assert(session->lex->is_lex_started);
1345
 
 
1346
 
  error= 1;
1347
 
  outparam->resetTable(session, share, db_stat);
1348
 
 
1349
 
 
1350
 
  if (!(outparam->alias= strdup(alias)))
1351
 
    goto err;
1352
 
 
1353
 
  /* Allocate Cursor */
1354
 
  if (!(outparam->cursor= share->db_type()->getCursor(*share, &outparam->mem_root)))
1355
 
    goto err;
1356
 
 
1357
 
  error= 4;
1358
 
  records= 0;
1359
 
  if ((db_stat & HA_OPEN_KEYFILE))
1360
 
    records=1;
1361
 
 
1362
 
  records++;
1363
 
 
1364
 
  if (!(record= (unsigned char*) alloc_root(&outparam->mem_root,
1365
 
                                   share->rec_buff_length * records)))
1366
 
    goto err;
1367
 
 
1368
 
  if (records == 0)
1369
 
  {
1370
 
    /* We are probably in hard repair, and the buffers should not be used */
1371
 
    outparam->record[0]= outparam->record[1]= share->default_values;
1372
 
  }
1373
 
  else
1374
 
  {
1375
 
    outparam->record[0]= record;
1376
 
    if (records > 1)
1377
 
      outparam->record[1]= record+ share->rec_buff_length;
1378
 
    else
1379
 
      outparam->record[1]= outparam->record[0];   // Safety
1380
 
  }
1381
 
 
1382
 
#ifdef HAVE_purify
1383
 
  /*
1384
 
    We need this because when we read var-length rows, we are not updating
1385
 
    bytes after end of varchar
1386
 
  */
1387
 
  if (records > 1)
1388
 
  {
1389
 
    memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
1390
 
    memcpy(outparam->record[1], share->default_values, share->null_bytes);
1391
 
    if (records > 2)
1392
 
      memcpy(outparam->record[1], share->default_values,
1393
 
             share->rec_buff_length);
1394
 
  }
1395
 
#endif
1396
 
 
1397
 
  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
1398
 
                                          (uint32_t) ((share->fields+1)*
1399
 
                                                  sizeof(Field*)))))
1400
 
    goto err;
1401
 
 
1402
 
  outparam->field= field_ptr;
1403
 
 
1404
 
  record= (unsigned char*) outparam->record[0]-1;       /* Fieldstart = 1 */
1405
 
 
1406
 
  outparam->null_flags= (unsigned char*) record+1;
1407
 
 
1408
 
  /* Setup copy of fields from share, but use the right alias and record */
1409
 
  for (i= 0 ; i < share->fields; i++, field_ptr++)
1410
 
  {
1411
 
    if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
1412
 
      goto err;
1413
 
  }
1414
 
  (*field_ptr)= 0;                              // End marker
1415
 
 
1416
 
  if (share->found_next_number_field)
1417
 
    outparam->found_next_number_field=
1418
 
      outparam->field[(uint32_t) (share->found_next_number_field - share->field)];
1419
 
  if (share->timestamp_field)
1420
 
    outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
1421
 
 
1422
 
 
1423
 
  /* Fix key->name and key_part->field */
1424
 
  if (share->key_parts)
1425
 
  {
1426
 
    KEY *key_info, *key_info_end;
1427
 
    KEY_PART_INFO *key_part;
1428
 
    uint32_t n_length;
1429
 
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
1430
 
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
1431
 
      goto err;
1432
 
    outparam->key_info= key_info;
1433
 
    key_part= (reinterpret_cast<KEY_PART_INFO*> (key_info+share->keys));
1434
 
 
1435
 
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
1436
 
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
1437
 
                                                   share->key_parts));
1438
 
 
1439
 
    for (key_info_end= key_info + share->keys ;
1440
 
         key_info < key_info_end ;
1441
 
         key_info++)
1442
 
    {
1443
 
      KEY_PART_INFO *key_part_end;
1444
 
 
1445
 
      key_info->table= outparam;
1446
 
      key_info->key_part= key_part;
1447
 
 
1448
 
      for (key_part_end= key_part+ key_info->key_parts ;
1449
 
           key_part < key_part_end ;
1450
 
           key_part++)
1451
 
      {
1452
 
        Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
1453
 
 
1454
 
        if (field->key_length() != key_part->length &&
1455
 
            !(field->flags & BLOB_FLAG))
1456
 
        {
1457
 
          /*
1458
 
            We are using only a prefix of the column as a key:
1459
 
            Create a new field for the key part that matches the index
1460
 
          */
1461
 
          field= key_part->field=field->new_field(&outparam->mem_root,
1462
 
                                                  outparam, 0);
1463
 
          field->field_length= key_part->length;
1464
 
        }
1465
 
      }
1466
 
    }
1467
 
  }
1468
 
 
1469
 
  /* Allocate bitmaps */
1470
 
 
1471
 
  bitmap_size= share->column_bitmap_size;
1472
 
  if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
1473
 
    goto err;
1474
 
  outparam->def_read_set.init((my_bitmap_map*) bitmaps, share->fields);
1475
 
  outparam->def_write_set.init((my_bitmap_map*) (bitmaps+bitmap_size), share->fields);
1476
 
  outparam->tmp_set.init((my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields);
1477
 
  outparam->default_column_bitmaps();
1478
 
 
1479
 
  /* The table struct is now initialized;  Open the table */
1480
 
  error= 2;
1481
 
  if (db_stat)
1482
 
  {
1483
 
    int ha_err;
1484
 
    if ((ha_err= (outparam->cursor->
1485
 
                  ha_open(outparam, share->normalized_path.str,
1486
 
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
1487
 
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
1488
 
                           (db_stat & HA_WAIT_IF_LOCKED) ?  HA_OPEN_WAIT_IF_LOCKED :
1489
 
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
1490
 
                          HA_OPEN_ABORT_IF_LOCKED :
1491
 
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
1492
 
    {
1493
 
      switch (ha_err)
1494
 
      {
1495
 
        case HA_ERR_NO_SUCH_TABLE:
1496
 
          /*
1497
 
            The table did not exists in storage engine, use same error message
1498
 
            as if the .frm cursor didn't exist
1499
 
          */
1500
 
          error= 1;
1501
 
          errno= ENOENT;
1502
 
          break;
1503
 
        case EMFILE:
1504
 
          /*
1505
 
            Too many files opened, use same error message as if the .frm
1506
 
            cursor can't open
1507
 
           */
1508
 
          error= 1;
1509
 
          errno= EMFILE;
1510
 
          break;
1511
 
        default:
1512
 
          outparam->print_error(ha_err, MYF(0));
1513
 
          error_reported= true;
1514
 
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
1515
 
            error= 7;
1516
 
          break;
1517
 
      }
1518
 
      goto err;
1519
 
    }
1520
 
  }
1521
 
 
1522
 
#if defined(HAVE_purify)
1523
 
  memset(bitmaps, 0, bitmap_size*3);
1524
 
#endif
1525
 
 
1526
 
  session->status_var.opened_tables++;
1527
 
 
1528
 
  return (0);
1529
 
 
1530
 
 err:
1531
 
  if (!error_reported)
1532
 
    share->open_table_error(error, errno, 0);
1533
 
  delete outparam->cursor;
1534
 
  outparam->cursor= 0;                          // For easier error checking
1535
 
  outparam->db_stat= 0;
1536
 
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on zeroed root
1537
 
  free((char*) outparam->alias);
1538
 
  return (error);
1539
 
}
1540
 
 
1541
 
bool Table::fill_item_list(List<Item> *item_list) const
1542
 
{
1543
 
  /*
1544
 
    All Item_field's created using a direct pointer to a field
1545
 
    are fixed in Item_field constructor.
1546
 
  */
1547
 
  for (Field **ptr= field; *ptr; ptr++)
1548
 
  {
1549
 
    Item_field *item= new Item_field(*ptr);
1550
 
    if (!item || item_list->push_back(item))
1551
 
      return true;
1552
 
  }
1553
 
  return false;
1554
 
}
1555
 
 
1556
 
int Table::closefrm(bool free_share)
 
77
// @note this should all be the destructor
 
78
int Table::delete_table(bool free_share)
1557
79
{
1558
80
  int error= 0;
1559
81
 
1560
82
  if (db_stat)
1561
83
    error= cursor->close();
1562
 
  free((char*) alias);
1563
 
  alias= NULL;
 
84
  _alias.clear();
1564
85
  if (field)
1565
86
  {
1566
87
    for (Field **ptr=field ; *ptr ; ptr++)
 
88
    {
1567
89
      delete *ptr;
 
90
    }
1568
91
    field= 0;
1569
92
  }
1570
93
  delete cursor;
1571
94
  cursor= 0;                            /* For easier errorchecking */
 
95
 
1572
96
  if (free_share)
1573
97
  {
1574
 
    if (s->tmp_table == NO_TMP_TABLE)
1575
 
      TableShare::release(s);
1576
 
    else
1577
 
      s->free_table_share();
 
98
    release();
1578
99
  }
1579
 
  free_root(&mem_root, MYF(0));
1580
100
 
1581
101
  return error;
1582
102
}
1583
103
 
 
104
Table::~Table()
 
105
{
 
106
  mem_root.free_root(MYF(0));
 
107
}
 
108
 
1584
109
 
1585
110
void Table::resetTable(Session *session,
1586
111
                       TableShare *share,
1587
112
                       uint32_t db_stat_arg)
1588
113
{
1589
 
  s= share;
 
114
  setShare(share);
1590
115
  field= NULL;
1591
116
 
1592
117
  cursor= NULL;
1603
128
  record[0]= (unsigned char *) NULL;
1604
129
  record[1]= (unsigned char *) NULL;
1605
130
 
1606
 
  insert_values= NULL;
 
131
  insert_values.clear();
1607
132
  key_info= NULL;
1608
133
  next_number_field= NULL;
1609
134
  found_next_number_field= NULL;
1611
136
 
1612
137
  pos_in_table_list= NULL;
1613
138
  group= NULL;
1614
 
  alias= NULL;
 
139
  _alias.clear();
1615
140
  null_flags= NULL;
1616
141
 
1617
142
  lock_position= 0;
1665
190
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
1666
191
 
1667
192
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
1668
 
  memset(&sort, 0, sizeof(filesort_info_st));
1669
193
}
1670
194
 
1671
195
 
1678
202
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
1679
203
       ptr != end ;
1680
204
       ptr++)
1681
 
    ((Field_blob*) table->field[*ptr])->free();
 
205
  {
 
206
    ((Field_blob*) table->getField(*ptr))->free();
 
207
  }
1682
208
}
1683
209
 
1684
210
 
1685
 
        /* error message when opening a form cursor */
1686
 
 
1687
 
void TableShare::open_table_error(int pass_error, int db_errno, int pass_errarg)
1688
 
{
1689
 
  int err_no;
1690
 
  char buff[FN_REFLEN];
1691
 
  myf errortype= ME_ERROR+ME_WAITTANG;
1692
 
 
1693
 
  switch (pass_error) {
1694
 
  case 7:
1695
 
  case 1:
1696
 
    if (db_errno == ENOENT)
1697
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), db.str, table_name.str);
1698
 
    else
1699
 
    {
1700
 
      sprintf(buff,"%s",normalized_path.str);
1701
 
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
1702
 
               errortype, buff, db_errno);
1703
 
    }
1704
 
    break;
1705
 
  case 2:
1706
 
  {
1707
 
    Cursor *cursor= 0;
1708
 
    const char *datext= "";
1709
 
 
1710
 
    if (db_type() != NULL)
1711
 
    {
1712
 
      if ((cursor= db_type()->getCursor(*this, current_session->mem_root)))
1713
 
      {
1714
 
        if (!(datext= *db_type()->bas_ext()))
1715
 
          datext= "";
1716
 
      }
1717
 
    }
1718
 
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
1719
 
      ER_FILE_USED : ER_CANT_OPEN_FILE;
1720
 
    sprintf(buff,"%s%s", normalized_path.str,datext);
1721
 
    my_error(err_no,errortype, buff, db_errno);
1722
 
    delete cursor;
1723
 
    break;
1724
 
  }
1725
 
  case 5:
1726
 
  {
1727
 
    const char *csname= get_charset_name((uint32_t) pass_errarg);
1728
 
    char tmp[10];
1729
 
    if (!csname || csname[0] =='?')
1730
 
    {
1731
 
      snprintf(tmp, sizeof(tmp), "#%d", pass_errarg);
1732
 
      csname= tmp;
1733
 
    }
1734
 
    my_printf_error(ER_UNKNOWN_COLLATION,
1735
 
                    _("Unknown collation '%s' in table '%-.64s' definition"),
1736
 
                    MYF(0), csname, table_name.str);
1737
 
    break;
1738
 
  }
1739
 
  case 6:
1740
 
    sprintf(buff,"%s", normalized_path.str);
1741
 
    my_printf_error(ER_NOT_FORM_FILE,
1742
 
                    _("Table '%-.64s' was created with a different version "
1743
 
                    "of Drizzle and cannot be read"),
1744
 
                    MYF(0), buff);
1745
 
    break;
1746
 
  case 8:
1747
 
    break;
1748
 
  default:                              /* Better wrong error than none */
1749
 
  case 4:
1750
 
    sprintf(buff,"%s", normalized_path.str);
1751
 
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
1752
 
    break;
1753
 
  }
1754
 
  return;
1755
 
} /* open_table_error */
1756
 
 
1757
 
 
1758
211
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
1759
212
{
1760
 
  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
 
213
  TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
1761
214
  if (!result)
1762
215
    return 0;
1763
216
  result->count= strings.elements;
1764
217
  result->name= "";
1765
218
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
1766
219
  
1767
 
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
 
220
  if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
1768
221
    return 0;
1769
222
    
1770
223
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
1794
247
  return (nr);
1795
248
} /* set_zone */
1796
249
 
1797
 
        /* Adjust number to next larger disk buffer */
1798
 
 
1799
 
ulong next_io_size(register ulong pos)
1800
 
{
1801
 
  register ulong offset;
1802
 
  if ((offset= pos & (IO_SIZE-1)))
1803
 
    return pos-offset+IO_SIZE;
1804
 
  return pos;
1805
 
} /* next_io_size */
1806
 
 
1807
250
 
1808
251
/*
1809
252
  Store an SQL quoted string.
1831
274
        (mblen= my_ismbchar(default_charset_info, pos, end)))
1832
275
    {
1833
276
      res->append(pos, mblen);
1834
 
      pos+= mblen;
 
277
      pos+= mblen - 1;
1835
278
      if (pos >= end)
1836
279
        break;
1837
280
      continue;
1867
310
}
1868
311
 
1869
312
 
1870
 
/*
1871
 
  Set up column usage bitmaps for a temporary table
1872
 
 
1873
 
  IMPLEMENTATION
1874
 
    For temporary tables, we need one bitmap with all columns set and
1875
 
    a tmp_set bitmap to be used by things like filesort.
1876
 
*/
1877
 
 
1878
 
void Table::setup_tmp_table_column_bitmaps(unsigned char *bitmaps)
1879
 
{
1880
 
  uint32_t field_count= s->fields;
1881
 
 
1882
 
  this->def_read_set.init((my_bitmap_map*) bitmaps, field_count);
1883
 
  this->tmp_set.init((my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)), field_count);
1884
 
 
1885
 
  /* write_set and all_set are copies of read_set */
1886
 
  def_write_set= def_read_set;
1887
 
  s->all_set= def_read_set;
1888
 
  this->s->all_set.setAll();
1889
 
  default_column_bitmaps();
1890
 
}
1891
 
 
1892
 
 
1893
 
 
1894
 
void Table::updateCreateInfo(message::Table *table_proto)
1895
 
{
1896
 
  message::Table::TableOptions *table_options= table_proto->mutable_options();
1897
 
  table_options->set_block_size(s->block_size);
1898
 
  table_options->set_comment(s->getComment());
1899
 
}
1900
 
 
1901
313
int rename_file_ext(const char * from,const char * to,const char * ext)
1902
314
{
1903
315
  string from_s, to_s;
1910
322
}
1911
323
 
1912
324
/*
1913
 
  DESCRIPTION
1914
 
    given a buffer with a key value, and a map of keyparts
1915
 
    that are present in this value, returns the length of the value
1916
 
*/
1917
 
uint32_t calculate_key_len(Table *table, uint32_t key,
1918
 
                       const unsigned char *,
1919
 
                       key_part_map keypart_map)
1920
 
{
1921
 
  /* works only with key prefixes */
1922
 
  assert(((keypart_map + 1) & keypart_map) == 0);
1923
 
 
1924
 
  KEY *key_info= table->s->key_info+key;
1925
 
  KEY_PART_INFO *key_part= key_info->key_part;
1926
 
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
1927
 
  uint32_t length= 0;
1928
 
 
1929
 
  while (key_part < end_key_part && keypart_map)
1930
 
  {
1931
 
    length+= key_part->store_length;
1932
 
    keypart_map >>= 1;
1933
 
    key_part++;
1934
 
  }
1935
 
  return length;
1936
 
}
1937
 
 
1938
 
/*
1939
325
  Check if database name is valid
1940
326
 
1941
327
  SYNPOSIS
1943
329
    org_name            Name of database and length
1944
330
 
1945
331
  RETURN
1946
 
    0   ok
1947
 
    1   error
 
332
    false error
 
333
    true ok
1948
334
*/
1949
335
 
1950
 
bool check_db_name(LEX_STRING *org_name)
 
336
bool check_db_name(Session *session, SchemaIdentifier &schema_identifier)
1951
337
{
1952
 
  char *name= org_name->str;
1953
 
  uint32_t name_length= org_name->length;
1954
 
 
1955
 
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
1956
 
    return 1;
1957
 
 
1958
 
  my_casedn_str(files_charset_info, name);
1959
 
 
1960
 
  return check_identifier_name(org_name);
 
338
  if (not plugin::Authorization::isAuthorized(session->user(), schema_identifier))
 
339
  {
 
340
    return false;
 
341
  }
 
342
 
 
343
  return schema_identifier.isValid();
1961
344
}
1962
345
 
1963
346
/*
2030
413
    bitmap_clear_all(&table->def_read_set);
2031
414
    bitmap_clear_all(&table->def_write_set);
2032
415
  */
2033
 
  def_read_set.clearAll();
2034
 
  def_write_set.clearAll();
2035
 
  column_bitmaps_set(&def_read_set, &def_write_set);
 
416
  def_read_set.reset();
 
417
  def_write_set.reset();
 
418
  column_bitmaps_set(def_read_set, def_write_set);
2036
419
}
2037
420
 
2038
421
 
2049
432
{
2050
433
 
2051
434
  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
2052
 
      s->primary_key < MAX_KEY)
 
435
      getShare()->hasPrimaryKey())
2053
436
  {
2054
 
    mark_columns_used_by_index_no_reset(s->primary_key);
 
437
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
2055
438
  }
2056
439
  return;
2057
440
}
2069
452
 
2070
453
void Table::mark_columns_used_by_index(uint32_t index)
2071
454
{
2072
 
  MyBitmap *bitmap= &tmp_set;
 
455
  boost::dynamic_bitset<> *bitmap= &tmp_set;
2073
456
 
2074
457
  (void) cursor->extra(HA_EXTRA_KEYREAD);
2075
 
  bitmap->clearAll();
2076
 
  mark_columns_used_by_index_no_reset(index, bitmap);
2077
 
  column_bitmaps_set(bitmap, bitmap);
 
458
  bitmap->reset();
 
459
  mark_columns_used_by_index_no_reset(index, *bitmap);
 
460
  column_bitmaps_set(*bitmap, *bitmap);
2078
461
  return;
2079
462
}
2080
463
 
2106
489
 
2107
490
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
2108
491
{
2109
 
    mark_columns_used_by_index_no_reset(index, read_set);
 
492
    mark_columns_used_by_index_no_reset(index, *read_set);
2110
493
}
2111
494
 
 
495
 
2112
496
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
2113
 
                                                MyBitmap *bitmap)
 
497
                                                boost::dynamic_bitset<>& bitmap)
2114
498
{
2115
 
  KEY_PART_INFO *key_part= key_info[index].key_part;
2116
 
  KEY_PART_INFO *key_part_end= (key_part +
2117
 
                                key_info[index].key_parts);
2118
 
  for (;key_part != key_part_end; key_part++)
2119
 
    bitmap->setBit(key_part->fieldnr-1);
 
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
  }
2120
506
}
2121
507
 
2122
508
 
2135
521
    We must set bit in read set as update_auto_increment() is using the
2136
522
    store() to check overflow of auto_increment values
2137
523
  */
2138
 
  setReadSet(found_next_number_field->field_index);
2139
 
  setWriteSet(found_next_number_field->field_index);
2140
 
  if (s->next_number_keypart)
2141
 
    mark_columns_used_by_index_no_reset(s->next_number_index);
 
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);
2142
528
}
2143
529
 
2144
530
 
2169
555
    be able to do an delete
2170
556
 
2171
557
  */
2172
 
  if (s->primary_key == MAX_KEY)
 
558
  if (not getShare()->hasPrimaryKey())
2173
559
  {
2174
560
    /* fallback to use all columns in the table to identify row */
2175
561
    use_all_columns();
2176
562
    return;
2177
563
  }
2178
564
  else
2179
 
    mark_columns_used_by_index_no_reset(s->primary_key);
 
565
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
2180
566
 
2181
567
  /* If we the engine wants all predicates we mark all keys */
2182
568
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
2185
571
    for (reg_field= field ; *reg_field ; reg_field++)
2186
572
    {
2187
573
      if ((*reg_field)->flags & PART_KEY_FLAG)
2188
 
        setReadSet((*reg_field)->field_index);
 
574
        setReadSet((*reg_field)->position());
2189
575
    }
2190
576
  }
2191
577
}
2217
603
    the primary key, the hidden primary key or all columns to be
2218
604
    able to do an update
2219
605
  */
2220
 
  if (s->primary_key == MAX_KEY)
 
606
  if (not getShare()->hasPrimaryKey())
2221
607
  {
2222
608
    /* fallback to use all columns in the table to identify row */
2223
609
    use_all_columns();
2224
610
    return;
2225
611
  }
2226
612
  else
2227
 
    mark_columns_used_by_index_no_reset(s->primary_key);
 
613
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
2228
614
 
2229
615
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
2230
616
  {
2234
620
    {
2235
621
      /* Merge keys is all keys that had a column refered to in the query */
2236
622
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
2237
 
        setReadSet((*reg_field)->field_index);
 
623
        setReadSet((*reg_field)->position());
2238
624
    }
2239
625
  }
2240
626
 
2266
652
  {
2267
653
    Field_blob* const blob= (Field_blob*) field[*ptr];
2268
654
    length+= blob->get_length((const unsigned char*)
2269
 
                              (data + blob->offset(record[0]))) +
 
655
                              (data + blob->offset(getInsertRecord()))) +
2270
656
      HA_KEY_BLOB_LENGTH;
2271
657
  }
2272
658
  return length;
2273
659
}
2274
660
 
 
661
void Table::setVariableWidth(void)
 
662
{
 
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.
 
671
}
 
672
 
2275
673
/****************************************************************************
2276
674
 Functions for creating temporary tables.
2277
675
****************************************************************************/
2278
 
 
2279
 
 
2280
 
/* Prototypes */
2281
 
void free_tmp_table(Session *session, Table *entry);
2282
 
 
2283
676
/**
2284
677
  Create field for temporary table from given field.
2285
678
 
2314
707
  */
2315
708
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
2316
709
      (org_field->flags & BLOB_FLAG))
 
710
  {
 
711
    table->setVariableWidth();
2317
712
    new_field= new Field_varstring(convert_blob_length,
2318
713
                                   org_field->maybe_null(),
2319
 
                                   org_field->field_name, table->s,
 
714
                                   org_field->field_name,
2320
715
                                   org_field->charset());
 
716
  }
2321
717
  else
 
718
  {
2322
719
    new_field= org_field->new_field(session->mem_root, table,
2323
 
                                    table == org_field->table);
 
720
                                    table == org_field->getTable());
 
721
  }
2324
722
  if (new_field)
2325
723
  {
2326
724
    new_field->init(table);
2333
731
    if (org_field->maybe_null() || (item && item->maybe_null))
2334
732
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
2335
733
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
2336
 
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
 
734
      table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
2337
735
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
2338
736
      ((Field_double *) new_field)->not_fixed= true;
2339
737
  }
2371
769
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
2372
770
#define RATIO_TO_PACK_ROWS             2
2373
771
 
2374
 
static void make_internal_temporary_table_path(Session *session, char *path)
2375
 
{
2376
 
  snprintf(path, FN_REFLEN, "%s%lx_%"PRIx64"_%x", TMP_FILE_PREFIX, (unsigned long)current_pid,
2377
 
           session->thread_id, session->tmp_table++);
2378
 
 
2379
 
  internal::fn_format(path, path, drizzle_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
2380
 
}
2381
 
 
2382
772
Table *
2383
773
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
2384
 
                 order_st *group, bool distinct, bool save_sum_fields,
 
774
                 Order *group, bool distinct, bool save_sum_fields,
2385
775
                 uint64_t select_options, ha_rows rows_limit,
2386
776
                 const char *table_alias)
2387
777
{
2388
 
  memory::Root *mem_root_save, own_root;
2389
 
  Table *table;
2390
 
  TableShare *share;
 
778
  memory::Root *mem_root_save;
2391
779
  uint  i,field_count,null_count,null_pack_length;
2392
780
  uint32_t  copy_func_count= param->func_count;
2393
781
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
2397
785
  bool  using_unique_constraint= false;
2398
786
  bool  use_packed_rows= true;
2399
787
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
2400
 
  char  *tmpname;
2401
 
  char  path[FN_REFLEN];
2402
 
  unsigned char *pos, *group_buff, *bitmaps;
 
788
  unsigned char *pos, *group_buff;
2403
789
  unsigned char *null_flags;
2404
790
  Field **reg_field, **from_field, **default_field;
2405
 
  uint32_t *blob_field;
2406
791
  CopyField *copy= 0;
2407
 
  KEY *keyinfo;
2408
 
  KEY_PART_INFO *key_part_info;
 
792
  KeyInfo *keyinfo;
 
793
  KeyPartInfo *key_part_info;
2409
794
  Item **copy_func;
2410
795
  MI_COLUMNDEF *recinfo;
2411
796
  uint32_t total_uneven_bit_length= 0;
2412
797
  bool force_copy_fields= param->force_copy_fields;
2413
798
  uint64_t max_rows= 0;
2414
799
 
2415
 
  status_var_increment(session->status_var.created_tmp_tables);
2416
 
 
2417
 
  make_internal_temporary_table_path(session, path);
 
800
  session->status_var.created_tmp_tables++;
2418
801
 
2419
802
  if (group)
2420
803
  {
2421
804
    if (! param->quick_group)
 
805
    {
2422
806
      group= 0;                                 // Can't use group key
2423
 
    else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
 
807
    }
 
808
    else for (Order *tmp=group ; tmp ; tmp=tmp->next)
2424
809
    {
2425
810
      /*
2426
811
        marker == 4 means two things:
2449
834
    these items are stored in the temporary table.
2450
835
  */
2451
836
  if (param->precomputed_group_by)
 
837
  {
2452
838
    copy_func_count+= param->sum_func_count;
2453
 
 
2454
 
  memory::init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
2455
 
 
2456
 
  if (!multi_alloc_root(&own_root,
2457
 
                        &table, sizeof(*table),
2458
 
                        &share, sizeof(*share),
2459
 
                        &reg_field, sizeof(Field*) * (field_count+1),
2460
 
                        &default_field, sizeof(Field*) * (field_count),
2461
 
                        &blob_field, sizeof(uint32_t)*(field_count+1),
2462
 
                        &from_field, sizeof(Field*)*field_count,
2463
 
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
2464
 
                        &param->keyinfo, sizeof(*param->keyinfo),
2465
 
                        &key_part_info,
2466
 
                        sizeof(*key_part_info)*(param->group_parts+1),
2467
 
                        &param->start_recinfo,
2468
 
                        sizeof(*param->recinfo)*(field_count*2+4),
2469
 
                        &tmpname, (uint32_t) strlen(path)+1,
2470
 
                        &group_buff, (group && ! using_unique_constraint ?
2471
 
                                      param->group_length : 0),
2472
 
                        &bitmaps, bitmap_buffer_size(field_count)*2,
2473
 
                        NULL))
 
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))
2474
854
  {
2475
855
    return NULL;
2476
856
  }
2477
857
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
2478
858
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
2479
859
  {
2480
 
    free_root(&own_root, MYF(0));
2481
860
    return NULL;
2482
861
  }
2483
862
  param->items_to_copy= copy_func;
2484
 
  strcpy(tmpname,path);
2485
863
  /* make table according to fields */
2486
864
 
2487
 
  memset(table, 0, sizeof(*table));
2488
 
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
2489
865
  memset(default_field, 0, sizeof(Field*) * (field_count));
2490
866
  memset(from_field, 0, sizeof(Field*)*field_count);
2491
867
 
2492
 
  table->mem_root= own_root;
2493
868
  mem_root_save= session->mem_root;
2494
 
  session->mem_root= &table->mem_root;
 
869
  session->mem_root= table->getMemRoot();
2495
870
 
2496
 
  table->field=reg_field;
2497
 
  table->alias= table_alias;
 
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);
2498
875
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
2499
876
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
2500
877
  table->map=1;
2501
878
  table->copy_blobs= 1;
 
879
  assert(session);
2502
880
  table->in_use= session;
2503
881
  table->quick_keys.reset();
2504
882
  table->covering_keys.reset();
2505
883
  table->keys_in_use_for_query.reset();
2506
884
 
2507
 
  table->setShare(share);
2508
 
  share->init(tmpname, tmpname);
2509
 
  share->blob_field= blob_field;
2510
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
2511
 
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
2512
 
  share->table_charset= param->table_charset;
2513
 
  share->primary_key= MAX_KEY;               // Indicate no primary key
2514
 
  share->keys_for_keyread.reset();
2515
 
  share->keys_in_use.reset();
 
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();
2516
892
 
2517
893
  /* Calculate which type of fields we will store in the temporary table */
2518
894
 
2579
955
          }
2580
956
          session->mem_root= mem_root_save;
2581
957
          session->change_item_tree(argp, new Item_field(new_field));
2582
 
          session->mem_root= &table->mem_root;
 
958
          session->mem_root= table->getMemRoot();
2583
959
          if (!(new_field->flags & NOT_NULL_FLAG))
2584
960
          {
2585
961
            null_count++;
2589
965
            */
2590
966
            (*argp)->maybe_null=1;
2591
967
          }
2592
 
          new_field->field_index= fieldnr++;
 
968
          new_field->setPosition(fieldnr++);
2593
969
        }
2594
970
      }
2595
971
    }
2636
1012
        group_null_items++;
2637
1013
        new_field->flags|= GROUP_FLAG;
2638
1014
      }
2639
 
      new_field->field_index= fieldnr++;
 
1015
      new_field->setPosition(fieldnr++);
2640
1016
      *(reg_field++)= new_field;
2641
1017
    }
2642
1018
    if (!--hidden_field_count)
2654
1030
      null_count= 0;
2655
1031
    }
2656
1032
  }
2657
 
  assert(fieldnr == (uint32_t) (reg_field - table->field));
2658
 
  assert(field_count >= (uint32_t) (reg_field - table->field));
 
1033
  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
 
1034
  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
2659
1035
  field_count= fieldnr;
2660
1036
  *reg_field= 0;
2661
1037
  *blob_field= 0;                               // End marker
2662
 
  share->fields= field_count;
 
1038
  table->getMutableShare()->fields= field_count;
2663
1039
 
2664
1040
  /* If result table is small; use a heap */
2665
1041
  /* future: storage engine selection can be made dynamic? */
2666
 
  if (blob_count || using_unique_constraint ||
 
1042
  if (blob_count || using_unique_constraint || 
 
1043
      (session->lex->select_lex.options & SELECT_BIG_RESULT) ||
 
1044
      (session->lex->current_select->olap == ROLLUP_TYPE) ||
2667
1045
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
2668
1046
  {
2669
 
    share->storage_engine= myisam_engine;
2670
 
    table->cursor= share->db_type()->getCursor(*share, &table->mem_root);
 
1047
    table->getMutableShare()->storage_engine= myisam_engine;
 
1048
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
2671
1049
    if (group &&
2672
1050
        (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
2673
1051
         param->group_length > table->cursor->getEngine()->max_key_length()))
 
1052
    {
2674
1053
      using_unique_constraint= true;
 
1054
    }
2675
1055
  }
2676
1056
  else
2677
1057
  {
2678
 
    share->storage_engine= heap_engine;
2679
 
    table->cursor= share->db_type()->getCursor(*share, &table->mem_root);
 
1058
    table->getMutableShare()->storage_engine= heap_engine;
 
1059
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
2680
1060
  }
2681
1061
  if (! table->cursor)
2682
1062
    goto err;
2685
1065
  if (! using_unique_constraint)
2686
1066
    reclength+= group_null_items;       // null flag is stored separately
2687
1067
 
2688
 
  share->blob_fields= blob_count;
 
1068
  table->getMutableShare()->blob_fields= blob_count;
2689
1069
  if (blob_count == 0)
2690
1070
  {
2691
1071
    /* We need to ensure that first byte is not 0 for the delete link */
2704
1084
  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)))
2705
1085
    use_packed_rows= 1;
2706
1086
 
2707
 
  share->reclength= reclength;
 
1087
  table->getMutableShare()->setRecordLength(reclength);
2708
1088
  {
2709
1089
    uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
2710
 
    share->rec_buff_length= alloc_length;
2711
 
    if (!(table->record[0]= (unsigned char*)
2712
 
                            alloc_root(&table->mem_root, alloc_length*3)))
 
1090
    table->getMutableShare()->rec_buff_length= alloc_length;
 
1091
    if (!(table->record[0]= (unsigned char*) table->alloc_root(alloc_length*2)))
 
1092
    {
2713
1093
      goto err;
2714
 
    table->record[1]= table->record[0]+alloc_length;
2715
 
    share->default_values= table->record[1]+alloc_length;
 
1094
    }
 
1095
    table->record[1]= table->getInsertRecord()+alloc_length;
 
1096
    table->getMutableShare()->resizeDefaultValues(alloc_length);
2716
1097
  }
2717
1098
  copy_func[0]= 0;                              // End marker
2718
1099
  param->func_count= copy_func - param->items_to_copy;
2719
1100
 
2720
 
  table->setup_tmp_table_column_bitmaps(bitmaps);
 
1101
  table->setup_tmp_table_column_bitmaps();
2721
1102
 
2722
1103
  recinfo=param->start_recinfo;
2723
 
  null_flags=(unsigned char*) table->record[0];
2724
 
  pos=table->record[0]+ null_pack_length;
 
1104
  null_flags=(unsigned char*) table->getInsertRecord();
 
1105
  pos=table->getInsertRecord()+ null_pack_length;
2725
1106
  if (null_pack_length)
2726
1107
  {
2727
1108
    memset(recinfo, 0, sizeof(*recinfo));
2730
1111
    recinfo++;
2731
1112
    memset(null_flags, 255, null_pack_length);  // Set null fields
2732
1113
 
2733
 
    table->null_flags= (unsigned char*) table->record[0];
2734
 
    share->null_fields= null_count+ hidden_null_count;
2735
 
    share->null_bytes= null_pack_length;
 
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;
2736
1117
  }
2737
1118
  null_count= (blob_count == 0) ? 1 : 0;
2738
1119
  hidden_field_count=param->hidden_field_count;
2739
 
  for (i= 0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
 
1120
  for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
2740
1121
  {
2741
1122
    Field *field= *reg_field;
2742
1123
    uint32_t length;
2783
1164
      ptrdiff_t diff;
2784
1165
      Field *orig_field= default_field[i];
2785
1166
      /* Get the value from default_values */
2786
 
      diff= (ptrdiff_t) (orig_field->table->s->default_values-
2787
 
                            orig_field->table->record[0]);
 
1167
      diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
2788
1168
      orig_field->move_field_offset(diff);      // Points now at default_values
2789
1169
      if (orig_field->is_real_null())
2790
1170
        field->set_null();
2793
1173
        field->set_notnull();
2794
1174
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
2795
1175
      }
2796
 
      orig_field->move_field_offset(-diff);     // Back to record[0]
 
1176
      orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
2797
1177
    }
2798
1178
 
2799
1179
    if (from_field[i])
2812
1192
      recinfo->type=FIELD_NORMAL;
2813
1193
    if (!--hidden_field_count)
2814
1194
      null_count=(null_count+7) & ~7;           // move to next byte
2815
 
 
2816
 
    // fix table name in field entry
2817
 
    field->table_name= &table->alias;
2818
1195
  }
2819
1196
 
2820
1197
  param->copy_field_end=copy;
2822
1199
  table->storeRecordAsDefault();        // Make empty default record
2823
1200
 
2824
1201
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)              // No limit
 
1202
  {
2825
1203
    max_rows= ~(uint64_t) 0;
 
1204
  }
2826
1205
  else
2827
 
    max_rows= (uint64_t) (((share->db_type() == heap_engine) ?
2828
 
                          min(session->variables.tmp_table_size,
2829
 
                              session->variables.max_heap_table_size) :
2830
 
                          session->variables.tmp_table_size) /
2831
 
                         share->reclength);
 
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
  }
2832
1213
 
2833
1214
  set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
2834
1215
  /*
2837
1218
  */
2838
1219
  set_if_smaller(max_rows, rows_limit);
2839
1220
 
2840
 
  share->setMaxRows(max_rows);
 
1221
  table->getMutableShare()->setMaxRows(max_rows);
2841
1222
 
2842
1223
  param->end_write_records= rows_limit;
2843
1224
 
2847
1228
  {
2848
1229
    table->group=group;                         /* Table is grouped by key */
2849
1230
    param->group_buff=group_buff;
2850
 
    share->keys=1;
2851
 
    share->uniques= test(using_unique_constraint);
 
1231
    table->getMutableShare()->keys=1;
 
1232
    table->getMutableShare()->uniques= test(using_unique_constraint);
2852
1233
    table->key_info=keyinfo;
2853
1234
    keyinfo->key_part=key_part_info;
2854
1235
    keyinfo->flags=HA_NOSAME;
2857
1238
    keyinfo->rec_per_key= 0;
2858
1239
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
2859
1240
    keyinfo->name= (char*) "group_key";
2860
 
    order_st *cur_group= group;
 
1241
    Order *cur_group= group;
2861
1242
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
2862
1243
    {
2863
1244
      Field *field=(*cur_group->item)->get_tmp_table_field();
2864
1245
      bool maybe_null=(*cur_group->item)->maybe_null;
2865
1246
      key_part_info->null_bit= 0;
2866
1247
      key_part_info->field=  field;
2867
 
      key_part_info->offset= field->offset(table->record[0]);
 
1248
      key_part_info->offset= field->offset(table->getInsertRecord());
2868
1249
      key_part_info->length= (uint16_t) field->key_length();
2869
1250
      key_part_info->type=   (uint8_t) field->key_type();
2870
1251
      key_part_info->key_type= 
2892
1273
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
2893
1274
          key_part_info->null_bit=field->null_bit;
2894
1275
          key_part_info->null_offset= (uint32_t) (field->null_ptr -
2895
 
                                              (unsigned char*) table->record[0]);
 
1276
                                              (unsigned char*) table->getInsertRecord());
2896
1277
          cur_group->buff++;                        // Pointer to field data
2897
1278
          group_buff++;                         // Skipp null flag
2898
1279
        }
2919
1300
        indexes on blobs with arbitrary length. Such indexes cannot be
2920
1301
        used for lookups.
2921
1302
      */
2922
 
      share->uniques= 1;
 
1303
      table->getMutableShare()->uniques= 1;
2923
1304
    }
2924
1305
    null_pack_length-=hidden_null_pack_length;
2925
1306
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
2926
 
                         (share->uniques ? test(null_pack_length) : 0));
 
1307
                         (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
2927
1308
    table->distinct= 1;
2928
 
    share->keys= 1;
2929
 
    if (!(key_part_info= (KEY_PART_INFO*)
2930
 
          alloc_root(&table->mem_root,
2931
 
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
 
1309
    table->getMutableShare()->keys= 1;
 
1310
    if (!(key_part_info= (KeyPartInfo*)
 
1311
         table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
2932
1312
      goto err;
2933
 
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
 
1313
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
2934
1314
    table->key_info=keyinfo;
2935
1315
    keyinfo->key_part=key_part_info;
2936
1316
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
2944
1324
      blobs can distinguish NULL from 0. This extra field is not needed
2945
1325
      when we do not use UNIQUE indexes for blobs.
2946
1326
    */
2947
 
    if (null_pack_length && share->uniques)
 
1327
    if (null_pack_length && table->getMutableShare()->uniques)
2948
1328
    {
2949
1329
      key_part_info->null_bit= 0;
2950
1330
      key_part_info->offset=hidden_null_pack_length;
2951
1331
      key_part_info->length=null_pack_length;
2952
 
      key_part_info->field= new Field_varstring(table->record[0],
 
1332
      table->setVariableWidth();
 
1333
      key_part_info->field= new Field_varstring(table->getInsertRecord(),
2953
1334
                                                (uint32_t) key_part_info->length,
2954
1335
                                                0,
2955
1336
                                                (unsigned char*) 0,
2956
1337
                                                (uint32_t) 0,
2957
1338
                                                NULL,
2958
 
                                                table->s,
2959
1339
                                                &my_charset_bin);
2960
1340
      if (!key_part_info->field)
2961
1341
        goto err;
2965
1345
      key_part_info++;
2966
1346
    }
2967
1347
    /* Create a distinct key over the columns we are going to return */
2968
 
    for (i=param->hidden_field_count, reg_field=table->field + i ;
 
1348
    for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
2969
1349
         i < field_count;
2970
1350
         i++, reg_field++, key_part_info++)
2971
1351
    {
2972
1352
      key_part_info->null_bit= 0;
2973
1353
      key_part_info->field=    *reg_field;
2974
 
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
 
1354
      key_part_info->offset=   (*reg_field)->offset(table->getInsertRecord());
2975
1355
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
2976
 
      /* TODO:
2977
 
        The below method of computing the key format length of the
 
1356
      /* @todo The below method of computing the key format length of the
2978
1357
        key part is a copy/paste from optimizer/range.cc, and table.cc.
2979
1358
        This should be factored out, e.g. as a method of Field.
2980
1359
        In addition it is not clear if any of the Field::*_length
3000
1379
 
3001
1380
  if (session->is_fatal_error)                          // If end of memory
3002
1381
    goto err;
3003
 
  share->db_record_offset= 1;
3004
 
  if (share->db_type() == myisam_engine)
 
1382
  table->getMutableShare()->db_record_offset= 1;
 
1383
  if (table->getShare()->db_type() == myisam_engine)
3005
1384
  {
3006
1385
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
3007
1386
                                       &param->recinfo, select_options))
3008
1387
      goto err;
3009
1388
  }
 
1389
  assert(table->in_use);
3010
1390
  if (table->open_tmp_table())
3011
1391
    goto err;
3012
1392
 
3016
1396
 
3017
1397
err:
3018
1398
  session->mem_root= mem_root_save;
3019
 
  table->free_tmp_table(session);
 
1399
  table= NULL;
 
1400
 
3020
1401
  return NULL;
3021
1402
}
3022
1403
 
3023
1404
/****************************************************************************/
3024
1405
 
3025
 
/**
3026
 
  Create a reduced Table object with properly set up Field list from a
3027
 
  list of field definitions.
3028
 
 
3029
 
    The created table doesn't have a table Cursor associated with
3030
 
    it, has no keys, no group/distinct, no copy_funcs array.
3031
 
    The sole purpose of this Table object is to use the power of Field
3032
 
    class to read/write data to/from table->record[0]. Then one can store
3033
 
    the record in any container (RB tree, hash, etc).
3034
 
    The table is created in Session mem_root, so are the table's fields.
3035
 
    Consequently, if you don't BLOB fields, you don't need to free it.
3036
 
 
3037
 
  @param session         connection handle
3038
 
  @param field_list  list of column definitions
3039
 
 
3040
 
  @return
3041
 
    0 if out of memory, Table object in case of success
3042
 
*/
3043
 
 
3044
 
Table *create_virtual_tmp_table(Session *session, List<CreateField> &field_list)
3045
 
{
3046
 
  uint32_t field_count= field_list.elements;
3047
 
  uint32_t blob_count= 0;
3048
 
  Field **field;
3049
 
  CreateField *cdef;                           /* column definition */
3050
 
  uint32_t record_length= 0;
3051
 
  uint32_t null_count= 0;                 /* number of columns which may be null */
3052
 
  uint32_t null_pack_length;              /* NULL representation array length */
3053
 
  uint32_t *blob_field;
3054
 
  unsigned char *bitmaps;
3055
 
  Table *table;
3056
 
  TableShare *share;
3057
 
 
3058
 
  if (!multi_alloc_root(session->mem_root,
3059
 
                        &table, sizeof(*table),
3060
 
                        &share, sizeof(*share),
3061
 
                        &field, (field_count + 1) * sizeof(Field*),
3062
 
                        &blob_field, (field_count+1) *sizeof(uint32_t),
3063
 
                        &bitmaps, bitmap_buffer_size(field_count)*2,
3064
 
                        NULL))
3065
 
    return NULL;
3066
 
 
3067
 
  memset(table, 0, sizeof(*table));
3068
 
  memset(share, 0, sizeof(*share));
3069
 
  table->field= field;
3070
 
  table->s= share;
3071
 
  share->blob_field= blob_field;
3072
 
  share->fields= field_count;
3073
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
3074
 
  table->setup_tmp_table_column_bitmaps(bitmaps);
3075
 
 
3076
 
  /* Create all fields and calculate the total length of record */
3077
 
  List_iterator_fast<CreateField> it(field_list);
3078
 
  while ((cdef= it++))
3079
 
  {
3080
 
    *field= make_field(share,
3081
 
                       NULL,
3082
 
                       0,
3083
 
                       cdef->length,
3084
 
                       (cdef->flags & NOT_NULL_FLAG) ? false : true,
3085
 
                       (unsigned char *) ((cdef->flags & NOT_NULL_FLAG) ? 0 : ""),
3086
 
                       (cdef->flags & NOT_NULL_FLAG) ? 0 : 1,
3087
 
                       cdef->decimals,
3088
 
                       cdef->sql_type,
3089
 
                       cdef->charset,
3090
 
                       cdef->unireg_check,
3091
 
                       cdef->interval,
3092
 
                       cdef->field_name);
3093
 
    if (!*field)
3094
 
      goto error;
3095
 
    (*field)->init(table);
3096
 
    record_length+= (*field)->pack_length();
3097
 
    if (! ((*field)->flags & NOT_NULL_FLAG))
3098
 
      null_count++;
3099
 
 
3100
 
    if ((*field)->flags & BLOB_FLAG)
3101
 
      share->blob_field[blob_count++]= (uint32_t) (field - table->field);
3102
 
 
3103
 
    field++;
3104
 
  }
3105
 
  *field= NULL;                             /* mark the end of the list */
3106
 
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
3107
 
  share->blob_fields= blob_count;
3108
 
 
3109
 
  null_pack_length= (null_count + 7)/8;
3110
 
  share->reclength= record_length + null_pack_length;
3111
 
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
3112
 
  table->record[0]= (unsigned char*) session->alloc(share->rec_buff_length);
3113
 
  if (!table->record[0])
3114
 
    goto error;
3115
 
 
3116
 
  if (null_pack_length)
3117
 
  {
3118
 
    table->null_flags= (unsigned char*) table->record[0];
3119
 
    share->null_fields= null_count;
3120
 
    share->null_bytes= null_pack_length;
3121
 
  }
3122
 
 
3123
 
  table->in_use= session;           /* field->reset() may access table->in_use */
3124
 
  {
3125
 
    /* Set up field pointers */
3126
 
    unsigned char *null_pos= table->record[0];
3127
 
    unsigned char *field_pos= null_pos + share->null_bytes;
3128
 
    uint32_t null_bit= 1;
3129
 
 
3130
 
    for (field= table->field; *field; ++field)
3131
 
    {
3132
 
      Field *cur_field= *field;
3133
 
      if ((cur_field->flags & NOT_NULL_FLAG))
3134
 
        cur_field->move_field(field_pos);
3135
 
      else
3136
 
      {
3137
 
        cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
3138
 
        null_bit<<= 1;
3139
 
        if (null_bit == (1 << 8))
3140
 
        {
3141
 
          ++null_pos;
3142
 
          null_bit= 1;
3143
 
        }
3144
 
      }
3145
 
      cur_field->reset();
3146
 
 
3147
 
      field_pos+= cur_field->pack_length();
3148
 
    }
3149
 
  }
3150
 
  return table;
3151
 
error:
3152
 
  for (field= table->field; *field; ++field)
3153
 
    delete *field;                         /* just invokes field destructor */
3154
 
  return 0;
3155
 
}
3156
 
 
3157
 
bool Table::open_tmp_table()
3158
 
{
3159
 
  int error;
3160
 
  if ((error=cursor->ha_open(this, s->table_name.str,O_RDWR,
3161
 
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
3162
 
  {
3163
 
    print_error(error, MYF(0));
3164
 
    db_stat= 0;
3165
 
    return true;
3166
 
  }
3167
 
  (void) cursor->extra(HA_EXTRA_QUICK);         /* Faster */
3168
 
  return false;
3169
 
}
3170
 
 
3171
 
 
3172
 
/*
3173
 
  Create MyISAM temporary table
3174
 
 
3175
 
  SYNOPSIS
3176
 
    create_myisam_tmp_table()
3177
 
      keyinfo         Description of the index (there is always one index)
3178
 
      start_recinfo   MyISAM's column descriptions
3179
 
      recinfo INOUT   End of MyISAM's column descriptions
3180
 
      options         Option bits
3181
 
 
3182
 
  DESCRIPTION
3183
 
    Create a MyISAM temporary table according to passed description. The is
3184
 
    assumed to have one unique index or constraint.
3185
 
 
3186
 
    The passed array or MI_COLUMNDEF structures must have this form:
3187
 
 
3188
 
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
3189
 
         when there are many nullable columns)
3190
 
      2. Table columns
3191
 
      3. One free MI_COLUMNDEF element (*recinfo points here)
3192
 
 
3193
 
    This function may use the free element to create hash column for unique
3194
 
    constraint.
3195
 
 
3196
 
   RETURN
3197
 
     false - OK
3198
 
     true  - Error
3199
 
*/
3200
 
 
3201
 
bool Table::create_myisam_tmp_table(KEY *keyinfo,
3202
 
                                    MI_COLUMNDEF *start_recinfo,
3203
 
                                    MI_COLUMNDEF **recinfo,
3204
 
                                    uint64_t options)
3205
 
{
3206
 
  int error;
3207
 
  MI_KEYDEF keydef;
3208
 
  MI_UNIQUEDEF uniquedef;
3209
 
  TableShare *share= s;
3210
 
 
3211
 
  if (share->keys)
3212
 
  {                                             // Get keys for ni_create
3213
 
    bool using_unique_constraint= false;
3214
 
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
3215
 
                                            sizeof(*seg) * keyinfo->key_parts);
3216
 
    if (!seg)
3217
 
      goto err;
3218
 
 
3219
 
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
3220
 
    if (keyinfo->key_length >= cursor->getEngine()->max_key_length() ||
3221
 
        keyinfo->key_parts > cursor->getEngine()->max_key_parts() ||
3222
 
        share->uniques)
3223
 
    {
3224
 
      /* Can't create a key; Make a unique constraint instead of a key */
3225
 
      share->keys=    0;
3226
 
      share->uniques= 1;
3227
 
      using_unique_constraint= true;
3228
 
      memset(&uniquedef, 0, sizeof(uniquedef));
3229
 
      uniquedef.keysegs=keyinfo->key_parts;
3230
 
      uniquedef.seg=seg;
3231
 
      uniquedef.null_are_equal=1;
3232
 
 
3233
 
      /* Create extra column for hash value */
3234
 
      memset(*recinfo, 0, sizeof(**recinfo));
3235
 
      (*recinfo)->type= FIELD_CHECK;
3236
 
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
3237
 
      (*recinfo)++;
3238
 
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
3239
 
    }
3240
 
    else
3241
 
    {
3242
 
      /* Create an unique key */
3243
 
      memset(&keydef, 0, sizeof(keydef));
3244
 
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
3245
 
      keydef.keysegs=  keyinfo->key_parts;
3246
 
      keydef.seg= seg;
3247
 
    }
3248
 
    for (uint32_t i= 0; i < keyinfo->key_parts ; i++,seg++)
3249
 
    {
3250
 
      Field *key_field=keyinfo->key_part[i].field;
3251
 
      seg->flag=     0;
3252
 
      seg->language= key_field->charset()->number;
3253
 
      seg->length=   keyinfo->key_part[i].length;
3254
 
      seg->start=    keyinfo->key_part[i].offset;
3255
 
      if (key_field->flags & BLOB_FLAG)
3256
 
      {
3257
 
        seg->type= ((keyinfo->key_part[i].key_type & 1 /* binary */) ?
3258
 
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
3259
 
        seg->bit_start= (uint8_t)(key_field->pack_length()
3260
 
                                  - share->blob_ptr_size);
3261
 
        seg->flag= HA_BLOB_PART;
3262
 
        seg->length= 0;                 // Whole blob in unique constraint
3263
 
      }
3264
 
      else
3265
 
      {
3266
 
        seg->type= keyinfo->key_part[i].type;
3267
 
      }
3268
 
      if (!(key_field->flags & NOT_NULL_FLAG))
3269
 
      {
3270
 
        seg->null_bit= key_field->null_bit;
3271
 
        seg->null_pos= (uint32_t) (key_field->null_ptr - (unsigned char*) record[0]);
3272
 
        /*
3273
 
          We are using a GROUP BY on something that contains NULL
3274
 
          In this case we have to tell MyISAM that two NULL should
3275
 
          on INSERT be regarded at the same value
3276
 
        */
3277
 
        if (! using_unique_constraint)
3278
 
          keydef.flag|= HA_NULL_ARE_EQUAL;
3279
 
      }
3280
 
    }
3281
 
  }
3282
 
  MI_CREATE_INFO create_info;
3283
 
  memset(&create_info, 0, sizeof(create_info));
3284
 
 
3285
 
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
3286
 
      OPTION_BIG_TABLES)
3287
 
    create_info.data_file_length= ~(uint64_t) 0;
3288
 
 
3289
 
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
3290
 
                       (uint32_t) (*recinfo-start_recinfo),
3291
 
                       start_recinfo,
3292
 
                       share->uniques, &uniquedef,
3293
 
                       &create_info,
3294
 
                       HA_CREATE_TMP_TABLE)))
3295
 
  {
3296
 
    print_error(error, MYF(0));
3297
 
    db_stat= 0;
3298
 
    goto err;
3299
 
  }
3300
 
  status_var_increment(in_use->status_var.created_tmp_disk_tables);
3301
 
  share->db_record_offset= 1;
3302
 
  return false;
3303
 
 err:
3304
 
  return true;
3305
 
}
3306
 
 
3307
 
 
3308
 
void Table::free_tmp_table(Session *session)
3309
 
{
3310
 
  memory::Root own_root= mem_root;
3311
 
  const char *save_proc_info;
3312
 
 
3313
 
  save_proc_info=session->get_proc_info();
3314
 
  session->set_proc_info("removing tmp table");
3315
 
 
3316
 
  // Release latches since this can take a long time
3317
 
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
3318
 
 
3319
 
  if (cursor)
3320
 
  {
3321
 
    if (db_stat)
3322
 
      cursor->closeMarkForDelete(s->table_name.str);
3323
 
 
3324
 
    s->db_type()->doDropTable(*session, s->table_name.str);
3325
 
 
3326
 
    delete cursor;
3327
 
  }
3328
 
 
3329
 
  /* free blobs */
3330
 
  for (Field **ptr= field ; *ptr ; ptr++)
3331
 
    (*ptr)->free();
3332
 
  free_io_cache();
3333
 
 
3334
 
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
3335
 
  session->set_proc_info(save_proc_info);
3336
 
}
3337
 
 
3338
 
/**
3339
 
  If a HEAP table gets full, create a MyISAM table and copy all rows
3340
 
  to this.
3341
 
*/
3342
 
 
3343
 
bool create_myisam_from_heap(Session *session, Table *table,
3344
 
                             MI_COLUMNDEF *start_recinfo,
3345
 
                             MI_COLUMNDEF **recinfo,
3346
 
                             int error, bool ignore_last_dupp_key_error)
3347
 
{
3348
 
  Table new_table;
3349
 
  TableShare share;
3350
 
  const char *save_proc_info;
3351
 
  int write_err;
3352
 
 
3353
 
  if (table->s->db_type() != heap_engine ||
3354
 
      error != HA_ERR_RECORD_FILE_FULL)
3355
 
  {
3356
 
    table->print_error(error, MYF(0));
3357
 
    return true;
3358
 
  }
3359
 
 
3360
 
  // Release latches since this can take a long time
3361
 
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
3362
 
 
3363
 
  new_table= *table;
3364
 
  share= *table->s;
3365
 
  new_table.s= &share;
3366
 
  new_table.s->storage_engine= myisam_engine;
3367
 
  if (!(new_table.cursor= new_table.s->db_type()->getCursor(share, &new_table.mem_root)))
3368
 
    return true;                                // End of memory
3369
 
 
3370
 
  save_proc_info=session->get_proc_info();
3371
 
  session->set_proc_info("converting HEAP to MyISAM");
3372
 
 
3373
 
  if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
3374
 
                                        recinfo, session->lex->select_lex.options |
3375
 
                                        session->options))
3376
 
    goto err2;
3377
 
  if (new_table.open_tmp_table())
3378
 
    goto err1;
3379
 
  if (table->cursor->indexes_are_disabled())
3380
 
    new_table.cursor->ha_disable_indexes(HA_KEY_SWITCH_ALL);
3381
 
  table->cursor->ha_index_or_rnd_end();
3382
 
  table->cursor->ha_rnd_init(1);
3383
 
  if (table->no_rows)
3384
 
  {
3385
 
    new_table.cursor->extra(HA_EXTRA_NO_ROWS);
3386
 
    new_table.no_rows=1;
3387
 
  }
3388
 
 
3389
 
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
3390
 
  new_table.cursor->extra(HA_EXTRA_WRITE_CACHE);
3391
 
 
3392
 
  /*
3393
 
    copy all old rows from heap table to MyISAM table
3394
 
    This is the only code that uses record[1] to read/write but this
3395
 
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
3396
 
  */
3397
 
  while (!table->cursor->rnd_next(new_table.record[1]))
3398
 
  {
3399
 
    write_err= new_table.cursor->ha_write_row(new_table.record[1]);
3400
 
    if (write_err)
3401
 
      goto err;
3402
 
  }
3403
 
  /* copy row that filled HEAP table */
3404
 
  if ((write_err=new_table.cursor->ha_write_row(table->record[0])))
3405
 
  {
3406
 
    if (new_table.cursor->is_fatal_error(write_err, HA_CHECK_DUP) ||
3407
 
        !ignore_last_dupp_key_error)
3408
 
      goto err;
3409
 
  }
3410
 
 
3411
 
  /* remove heap table and change to use myisam table */
3412
 
  (void) table->cursor->ha_rnd_end();
3413
 
  (void) table->cursor->close();                  // This deletes the table !
3414
 
  delete table->cursor;
3415
 
  table->cursor= NULL;
3416
 
  new_table.s= table->s;                       // Keep old share
3417
 
  *table= new_table;
3418
 
  *table->s= share;
3419
 
 
3420
 
  table->cursor->change_table_ptr(table, table->s);
3421
 
  table->use_all_columns();
3422
 
  if (save_proc_info)
3423
 
  {
3424
 
    const char *new_proc_info=
3425
 
      (!strcmp(save_proc_info,"Copying to tmp table") ?
3426
 
      "Copying to tmp table on disk" : save_proc_info);
3427
 
    session->set_proc_info(new_proc_info);
3428
 
  }
3429
 
  return false;
3430
 
 
3431
 
 err:
3432
 
  table->print_error(write_err, MYF(0));
3433
 
  (void) table->cursor->ha_rnd_end();
3434
 
  (void) new_table.cursor->close();
3435
 
 err1:
3436
 
  new_table.s->db_type()->doDropTable(*session, new_table.s->table_name.str);
3437
 
 err2:
3438
 
  delete new_table.cursor;
3439
 
  session->set_proc_info(save_proc_info);
3440
 
  table->mem_root= new_table.mem_root;
3441
 
  return true;
3442
 
}
3443
 
 
3444
 
my_bitmap_map *Table::use_all_columns(MyBitmap *bitmap)
3445
 
{
3446
 
  my_bitmap_map *old= bitmap->getBitmap();
3447
 
  bitmap->setBitmap(s->all_set.getBitmap());
 
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;
3448
1418
  return old;
3449
1419
}
3450
1420
 
3451
 
void Table::restore_column_map(my_bitmap_map *old)
 
1421
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
3452
1422
{
3453
 
  read_set->setBitmap(old);
 
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
  }
3454
1434
}
3455
1435
 
3456
1436
uint32_t Table::find_shortest_key(const key_map *usable_keys)
3459
1439
  uint32_t best= MAX_KEY;
3460
1440
  if (usable_keys->any())
3461
1441
  {
3462
 
    for (uint32_t nr= 0; nr < s->keys ; nr++)
 
1442
    for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
3463
1443
    {
3464
1444
      if (usable_keys->test(nr))
3465
1445
      {
3486
1466
{
3487
1467
  for (; *ptr ; ptr++)
3488
1468
  {
3489
 
    if ((*ptr)->cmp_offset(s->rec_buff_length))
 
1469
    if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
3490
1470
      return true;
3491
1471
  }
3492
1472
  return false;
3493
1473
}
3494
1474
 
3495
 
/* Return false if row hasn't changed */
3496
 
 
3497
 
bool Table::compare_record()
3498
 
{
3499
 
  if (s->blob_fields + s->varchar_fields == 0)
3500
 
    return memcmp(this->record[0], this->record[1], (size_t) s->reclength);
3501
 
  
 
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
 
3502
1536
  /* Compare null bits */
3503
 
  if (memcmp(null_flags, null_flags + s->rec_buff_length, s->null_bytes))
 
1537
  if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
3504
1538
    return true; /* Diff in NULL value */
3505
1539
 
3506
1540
  /* Compare updated fields */
3507
1541
  for (Field **ptr= field ; *ptr ; ptr++)
3508
1542
  {
3509
 
    if (isWriteSet((*ptr)->field_index) &&
3510
 
        (*ptr)->cmp_binary_offset(s->rec_buff_length))
 
1543
    if (isWriteSet((*ptr)->position()) &&
 
1544
        (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
3511
1545
      return true;
3512
1546
  }
3513
1547
  return false;
3519
1553
 */
3520
1554
void Table::storeRecord()
3521
1555
{
3522
 
  memcpy(record[1], record[0], (size_t) s->reclength);
 
1556
  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
3523
1557
}
3524
1558
 
3525
1559
/*
3528
1562
 */
3529
1563
void Table::storeRecordAsInsert()
3530
1564
{
3531
 
  memcpy(insert_values, record[0], (size_t) s->reclength);
 
1565
  assert(insert_values.size() >= getShare()->getRecordLength());
 
1566
  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
3532
1567
}
3533
1568
 
3534
1569
/*
3537
1572
 */
3538
1573
void Table::storeRecordAsDefault()
3539
1574
{
3540
 
  memcpy(s->default_values, record[0], (size_t) s->reclength);
 
1575
  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
3541
1576
}
3542
1577
 
3543
1578
/*
3546
1581
 */
3547
1582
void Table::restoreRecord()
3548
1583
{
3549
 
  memcpy(record[0], record[1], (size_t) s->reclength);
 
1584
  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
3550
1585
}
3551
1586
 
3552
1587
/*
3555
1590
 */
3556
1591
void Table::restoreRecordAsDefault()
3557
1592
{
3558
 
  memcpy(record[0], s->default_values, (size_t) s->reclength);
 
1593
  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
3559
1594
}
3560
1595
 
3561
1596
/*
3565
1600
void Table::emptyRecord()
3566
1601
{
3567
1602
  restoreRecordAsDefault();
3568
 
  memset(null_flags, 255, s->null_bytes);
 
1603
  memset(null_flags, 255, getShare()->null_bytes);
3569
1604
}
3570
1605
 
3571
 
Table::Table()
3572
 
  : s(NULL),
3573
 
    field(NULL),
3574
 
    cursor(NULL),
3575
 
    next(NULL),
3576
 
    prev(NULL),
3577
 
    read_set(NULL),
3578
 
    write_set(NULL),
3579
 
    tablenr(0),
3580
 
    db_stat(0),
3581
 
    in_use(NULL),
3582
 
    insert_values(NULL),
3583
 
    key_info(NULL),
3584
 
    next_number_field(NULL),
3585
 
    found_next_number_field(NULL),
3586
 
    timestamp_field(NULL),
3587
 
    pos_in_table_list(NULL),
3588
 
    group(NULL),
3589
 
    alias(NULL),
3590
 
    null_flags(NULL),
3591
 
    lock_position(0),
3592
 
    lock_data_start(0),
3593
 
    lock_count(0),
3594
 
    used_fields(0),
3595
 
    status(0),
3596
 
    derived_select_number(0),
3597
 
    current_lock(F_UNLCK),
3598
 
    copy_blobs(false),
3599
 
    maybe_null(false),
3600
 
    null_row(false),
3601
 
    force_index(false),
3602
 
    distinct(false),
3603
 
    const_table(false),
3604
 
    no_rows(false),
3605
 
    key_read(false),
3606
 
    no_keyread(false),
3607
 
    open_placeholder(false),
3608
 
    locked_by_name(false),
3609
 
    no_cache(false),
3610
 
    auto_increment_field_not_null(false),
3611
 
    alias_name_used(false),
3612
 
    query_id(0),
3613
 
    quick_condition_rows(0),
3614
 
    timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
3615
 
    map(0)
 
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)
3616
1651
{
3617
1652
  record[0]= (unsigned char *) 0;
3618
1653
  record[1]= (unsigned char *) 0;
3619
1654
 
 
1655
  reginfo.reset();
3620
1656
  covering_keys.reset();
3621
 
 
3622
1657
  quick_keys.reset();
3623
1658
  merge_keys.reset();
3624
1659
 
3631
1666
 
3632
1667
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
3633
1668
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
3634
 
 
3635
 
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
3636
 
  memset(&sort, 0, sizeof(filesort_info_st));
3637
1669
}
3638
1670
 
3639
1671
/*****************************************************************************
3656
1688
  */
3657
1689
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
3658
1690
    errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
3659
 
                    error, s->path.str);
 
1691
                  error, getShare()->getPath());
3660
1692
  print_error(error, MYF(0));
3661
1693
 
3662
1694
  return 1;
3670
1702
  null_row= 0;
3671
1703
  status= STATUS_NO_RECORD;
3672
1704
  maybe_null= table_list->outer_join;
3673
 
  TableList *embedding= table_list->embedding;
 
1705
  TableList *embedding= table_list->getEmbedding();
3674
1706
  while (!maybe_null && embedding)
3675
1707
  {
3676
1708
    maybe_null= embedding->outer_join;
3677
 
    embedding= embedding->embedding;
 
1709
    embedding= embedding->getEmbedding();
3678
1710
  }
3679
1711
  tablenr= table_number;
3680
1712
  map= (table_map) 1 << table_number;
3681
1713
  force_index= table_list->force_index;
3682
 
  covering_keys= s->keys_for_keyread;
 
1714
  covering_keys= getShare()->keys_for_keyread;
3683
1715
  merge_keys.reset();
3684
1716
}
3685
1717
 
3686
1718
 
3687
 
/*
3688
 
  Used by ALTER Table when the table is a temporary one. It changes something
3689
 
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
3690
 
  name).
3691
 
  Prepares a table cache key, which is the concatenation of db, table_name and
3692
 
  session->slave_proxy_id, separated by '\0'.
3693
 
*/
3694
 
 
3695
 
bool Table::rename_temporary_table(const char *db, const char *table_name)
 
1719
bool Table::fill_item_list(List<Item> *item_list) const
3696
1720
{
3697
 
  char *key;
3698
 
  uint32_t key_length;
3699
 
  TableShare *share= s;
3700
 
 
3701
 
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
3702
 
    return true;
3703
 
 
3704
 
  key_length= TableShare::createKey(key, db, table_name);
3705
 
  share->set_table_cache_key(key, key_length);
3706
 
 
 
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
  }
3707
1731
  return false;
3708
1732
}
3709
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
 
3710
1768
} /* namespace drizzled */