~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Padraig O'Sullivan
  • Date: 2010-02-11 16:22:34 UTC
  • mto: (1300.3.1 query-as-string)
  • mto: This revision was merged to the branch mainline in revision 1307.
  • Revision ID: osullivan.padraig@gmail.com-20100211162234-tkk64v4vdqkb9syv
Removed the found_semicolon member from the parsing stage

Show diffs side-by-side

added added

removed removed

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