~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

Merged in latest plugin-slot-reorg.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Some general useful functions */
18
18
 
19
 
#include "config.h"
20
 
 
21
 
#include <float.h>
22
 
#include <fcntl.h>
23
 
 
24
 
#include <string>
25
 
#include <vector>
26
 
#include <algorithm>
27
 
 
 
19
#include <drizzled/server_includes.h>
28
20
#include <drizzled/error.h>
29
21
#include <drizzled/gettext.h>
30
22
 
31
 
#include "drizzled/plugin/transactional_storage_engine.h"
32
 
#include "drizzled/plugin/authorization.h"
33
23
#include <drizzled/nested_join.h>
34
24
#include <drizzled/sql_parse.h>
35
25
#include <drizzled/item/sum.h>
42
32
#include <drizzled/field/double.h>
43
33
#include <drizzled/unireg.h>
44
34
#include <drizzled/message/table.pb.h>
45
 
#include "drizzled/sql_table.h"
46
 
#include "drizzled/charset.h"
47
 
#include "drizzled/internal/m_string.h"
48
 
#include "plugin/myisam/myisam.h"
49
35
 
50
36
#include <drizzled/item/string.h>
51
37
#include <drizzled/item/int.h>
52
38
#include <drizzled/item/decimal.h>
53
39
#include <drizzled/item/float.h>
54
40
#include <drizzled/item/null.h>
55
 
#include <drizzled/temporal.h>
56
 
 
57
 
#include "drizzled/table/instance.h"
58
 
 
59
 
#include "drizzled/table_proto.h"
 
41
 
 
42
#include <drizzled/table_proto.h>
 
43
 
 
44
#include <string>
 
45
#include <vector>
 
46
#include <algorithm>
 
47
 
60
48
 
61
49
using namespace std;
62
 
 
63
 
namespace drizzled
64
 
{
65
 
 
66
 
extern pid_t current_pid;
67
 
extern plugin::StorageEngine *heap_engine;
68
 
extern plugin::StorageEngine *myisam_engine;
69
 
 
70
 
/* Functions defined in this cursor */
 
50
using namespace drizzled;
 
51
 
 
52
/* Functions defined in this file */
71
53
 
72
54
void open_table_error(TableShare *share, int error, int db_errno,
73
55
                      myf errortype, int errarg);
74
56
 
75
57
/*************************************************************************/
76
58
 
77
 
// @note this should all be the destructor
78
 
int Table::delete_table(bool free_share)
 
59
/* Get column name from column hash */
 
60
 
 
61
static unsigned char *get_field_name(Field **buff, size_t *length, bool)
 
62
{
 
63
  *length= (uint32_t) strlen((*buff)->field_name);
 
64
  return (unsigned char*) (*buff)->field_name;
 
65
}
 
66
 
 
67
 
 
68
/*
 
69
  Returns pointer to '.frm' extension of the file name.
 
70
 
 
71
  SYNOPSIS
 
72
    fn_rext()
 
73
    name       file name
 
74
 
 
75
  DESCRIPTION
 
76
    Checks file name part starting with the rightmost '.' character,
 
77
    and returns it if it is equal to '.dfe'.
 
78
 
 
79
  TODO
 
80
    It is a good idea to get rid of this function modifying the code
 
81
    to garantee that the functions presently calling fn_rext() always
 
82
    get arguments in the same format: either with '.frm' or without '.frm'.
 
83
 
 
84
  RETURN VALUES
 
85
    Pointer to the '.frm' extension. If there is no extension,
 
86
    or extension is not '.frm', pointer at the end of file name.
 
87
*/
 
88
 
 
89
char *fn_rext(char *name)
 
90
{
 
91
  char *res= strrchr(name, '.');
 
92
  if (res && !strcmp(res, ".dfe"))
 
93
    return res;
 
94
  return name + strlen(name);
 
95
}
 
96
 
 
97
static TABLE_CATEGORY get_table_category(const LEX_STRING *db)
 
98
{
 
99
  assert(db != NULL);
 
100
 
 
101
  if ((db->length == INFORMATION_SCHEMA_NAME.length()) &&
 
102
      (my_strcasecmp(system_charset_info,
 
103
                    INFORMATION_SCHEMA_NAME.c_str(),
 
104
                    db->str) == 0))
 
105
  {
 
106
    return TABLE_CATEGORY_INFORMATION;
 
107
  }
 
108
 
 
109
  return TABLE_CATEGORY_USER;
 
110
}
 
111
 
 
112
 
 
113
/*
 
114
  Allocate a setup TableShare structure
 
115
 
 
116
  SYNOPSIS
 
117
    alloc_table_share()
 
118
    TableList           Take database and table name from there
 
119
    key                 Table cache key (db \0 table_name \0...)
 
120
    key_length          Length of key
 
121
 
 
122
  RETURN
 
123
    0  Error (out of memory)
 
124
    #  Share
 
125
*/
 
126
 
 
127
TableShare *alloc_table_share(TableList *table_list, char *key,
 
128
                               uint32_t key_length)
 
129
{
 
130
  MEM_ROOT mem_root;
 
131
  TableShare *share;
 
132
  char *key_buff, *path_buff;
 
133
  char path[FN_REFLEN];
 
134
  uint32_t path_length;
 
135
 
 
136
  path_length= build_table_filename(path, sizeof(path) - 1,
 
137
                                    table_list->db,
 
138
                                    table_list->table_name, false);
 
139
  init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
140
  if (multi_alloc_root(&mem_root,
 
141
                       &share, sizeof(*share),
 
142
                       &key_buff, key_length,
 
143
                       &path_buff, path_length + 1,
 
144
                       NULL))
 
145
  {
 
146
    memset(share, 0, sizeof(*share));
 
147
 
 
148
    share->set_table_cache_key(key_buff, key, key_length);
 
149
 
 
150
    share->path.str= path_buff;
 
151
    share->path.length= path_length;
 
152
    strcpy(share->path.str, path);
 
153
    share->normalized_path.str=    share->path.str;
 
154
    share->normalized_path.length= path_length;
 
155
 
 
156
    share->version=       refresh_version;
 
157
 
 
158
    memcpy(&share->mem_root, &mem_root, sizeof(mem_root));
 
159
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
 
160
    pthread_cond_init(&share->cond, NULL);
 
161
  }
 
162
  return(share);
 
163
}
 
164
 
 
165
 
 
166
static enum_field_types proto_field_type_to_drizzle_type(uint32_t proto_field_type)
 
167
{
 
168
  enum_field_types field_type;
 
169
 
 
170
  switch(proto_field_type)
 
171
  {
 
172
  case message::Table::Field::TINYINT:
 
173
    field_type= DRIZZLE_TYPE_TINY;
 
174
    break;
 
175
  case message::Table::Field::INTEGER:
 
176
    field_type= DRIZZLE_TYPE_LONG;
 
177
    break;
 
178
  case message::Table::Field::DOUBLE:
 
179
    field_type= DRIZZLE_TYPE_DOUBLE;
 
180
    break;
 
181
  case message::Table::Field::TIMESTAMP:
 
182
    field_type= DRIZZLE_TYPE_TIMESTAMP;
 
183
    break;
 
184
  case message::Table::Field::BIGINT:
 
185
    field_type= DRIZZLE_TYPE_LONGLONG;
 
186
    break;
 
187
  case message::Table::Field::DATETIME:
 
188
    field_type= DRIZZLE_TYPE_DATETIME;
 
189
    break;
 
190
  case message::Table::Field::DATE:
 
191
    field_type= DRIZZLE_TYPE_DATE;
 
192
    break;
 
193
  case message::Table::Field::VARCHAR:
 
194
    field_type= DRIZZLE_TYPE_VARCHAR;
 
195
    break;
 
196
  case message::Table::Field::DECIMAL:
 
197
    field_type= DRIZZLE_TYPE_NEWDECIMAL;
 
198
    break;
 
199
  case message::Table::Field::ENUM:
 
200
    field_type= DRIZZLE_TYPE_ENUM;
 
201
    break;
 
202
  case message::Table::Field::BLOB:
 
203
    field_type= DRIZZLE_TYPE_BLOB;
 
204
    break;
 
205
  default:
 
206
    field_type= DRIZZLE_TYPE_TINY; /* Set value to kill GCC warning */
 
207
    assert(1);
 
208
  }
 
209
 
 
210
  return field_type;
 
211
}
 
212
 
 
213
static Item *default_value_item(enum_field_types field_type,
 
214
                                const CHARSET_INFO *charset,
 
215
                                bool default_null, const string *default_value,
 
216
                                const string *default_bin_value)
 
217
{
 
218
  Item *default_item= NULL;
 
219
  int error= 0;
 
220
 
 
221
  if (default_null)
 
222
  {
 
223
    return new Item_null();
 
224
  }
 
225
 
 
226
  switch(field_type)
 
227
  {
 
228
  case DRIZZLE_TYPE_TINY:
 
229
  case DRIZZLE_TYPE_LONG:
 
230
  case DRIZZLE_TYPE_LONGLONG:
 
231
    default_item= new Item_int(default_value->c_str(),
 
232
                               (int64_t) my_strtoll10(default_value->c_str(),
 
233
                                                      NULL,
 
234
                                                      &error),
 
235
                               default_value->length());
 
236
    break;
 
237
  case DRIZZLE_TYPE_DOUBLE:
 
238
    default_item= new Item_float(default_value->c_str(),
 
239
                                 default_value->length());
 
240
    break;
 
241
  case DRIZZLE_TYPE_NULL:
 
242
    assert(false);
 
243
  case DRIZZLE_TYPE_TIMESTAMP:
 
244
  case DRIZZLE_TYPE_DATETIME:
 
245
  case DRIZZLE_TYPE_DATE:
 
246
    if (default_value->compare("NOW()") == 0)
 
247
      break;
 
248
  case DRIZZLE_TYPE_ENUM:
 
249
    default_item= new Item_string(default_value->c_str(),
 
250
                                  default_value->length(),
 
251
                                  system_charset_info);
 
252
    break;
 
253
  case DRIZZLE_TYPE_VARCHAR:
 
254
  case DRIZZLE_TYPE_BLOB: /* Blob is here due to TINYTEXT. Feel the hate. */
 
255
    if (charset==&my_charset_bin)
 
256
    {
 
257
      default_item= new Item_string(default_bin_value->c_str(),
 
258
                                    default_bin_value->length(),
 
259
                                    &my_charset_bin);
 
260
    }
 
261
    else
 
262
    {
 
263
      default_item= new Item_string(default_value->c_str(),
 
264
                                    default_value->length(),
 
265
                                    system_charset_info);
 
266
    }
 
267
    break;
 
268
  case DRIZZLE_TYPE_NEWDECIMAL:
 
269
    default_item= new Item_decimal(default_value->c_str(),
 
270
                                   default_value->length(),
 
271
                                   system_charset_info);
 
272
    break;
 
273
  }
 
274
 
 
275
  return default_item;
 
276
}
 
277
 
 
278
int parse_table_proto(Session *session,
 
279
                      message::Table &table,
 
280
                      TableShare *share)
 
281
{
 
282
  int error= 0;
 
283
  handler *handler_file= NULL;
 
284
 
 
285
  share->setTableProto(new(std::nothrow) message::Table(table));
 
286
 
 
287
  share->storage_engine= plugin::StorageEngine::findByName(session, table.engine().name());
 
288
 
 
289
  message::Table::TableOptions table_options;
 
290
 
 
291
  if (table.has_options())
 
292
    table_options= table.options();
 
293
 
 
294
  uint32_t db_create_options= 0;
 
295
 
 
296
  if (table_options.has_pack_keys())
 
297
  {
 
298
    if (table_options.pack_keys())
 
299
      db_create_options|= HA_OPTION_PACK_KEYS;
 
300
    else
 
301
      db_create_options|= HA_OPTION_NO_PACK_KEYS;
 
302
  }
 
303
 
 
304
  if (table_options.pack_record())
 
305
    db_create_options|= HA_OPTION_PACK_RECORD;
 
306
 
 
307
  /* db_create_options was stored as 2 bytes in FRM
 
308
     Any HA_OPTION_ that doesn't fit into 2 bytes was silently truncated away.
 
309
   */
 
310
  share->db_create_options= (db_create_options & 0x0000FFFF);
 
311
  share->db_options_in_use= share->db_create_options;
 
312
 
 
313
  share->row_type= table_options.has_row_type() ?
 
314
    (enum row_type) table_options.row_type() : ROW_TYPE_DEFAULT;
 
315
 
 
316
  share->block_size= table_options.has_block_size() ?
 
317
    table_options.block_size() : 0;
 
318
 
 
319
  share->table_charset= get_charset(table_options.has_collation_id()?
 
320
                                    table_options.collation_id() : 0);
 
321
 
 
322
  if (!share->table_charset)
 
323
  {
 
324
    /* unknown charset in head[38] or pre-3.23 frm */
 
325
    if (use_mb(default_charset_info))
 
326
    {
 
327
      /* Warn that we may be changing the size of character columns */
 
328
      errmsg_printf(ERRMSG_LVL_WARN,
 
329
                    _("'%s' had no or invalid character set, "
 
330
                      "and default character set is multi-byte, "
 
331
                      "so character column sizes may have changed"),
 
332
                    share->path.str);
 
333
    }
 
334
    share->table_charset= default_charset_info;
 
335
  }
 
336
 
 
337
  share->db_record_offset= 1;
 
338
 
 
339
  share->blob_ptr_size= portable_sizeof_char_ptr; // more bonghits.
 
340
 
 
341
  share->db_low_byte_first= true;
 
342
 
 
343
  share->keys= table.indexes_size();
 
344
 
 
345
  share->key_parts= 0;
 
346
  for (int indx= 0; indx < table.indexes_size(); indx++)
 
347
    share->key_parts+= table.indexes(indx).index_part_size();
 
348
 
 
349
  share->key_info= (KEY*) alloc_root(&share->mem_root,
 
350
                                     table.indexes_size() * sizeof(KEY)
 
351
                                     +share->key_parts*sizeof(KEY_PART_INFO));
 
352
 
 
353
  KEY_PART_INFO *key_part;
 
354
 
 
355
  key_part= reinterpret_cast<KEY_PART_INFO*>
 
356
    (share->key_info+table.indexes_size());
 
357
 
 
358
 
 
359
  ulong *rec_per_key= (ulong*) alloc_root(&share->mem_root,
 
360
                                            sizeof(ulong*)*share->key_parts);
 
361
 
 
362
  share->keynames.count= table.indexes_size();
 
363
  share->keynames.name= NULL;
 
364
  share->keynames.type_names= (const char**)
 
365
    alloc_root(&share->mem_root, sizeof(char*) * (table.indexes_size()+1));
 
366
 
 
367
  share->keynames.type_lengths= (unsigned int*)
 
368
    alloc_root(&share->mem_root,
 
369
               sizeof(unsigned int) * (table.indexes_size()+1));
 
370
 
 
371
  share->keynames.type_names[share->keynames.count]= NULL;
 
372
  share->keynames.type_lengths[share->keynames.count]= 0;
 
373
 
 
374
  KEY* keyinfo= share->key_info;
 
375
  for (int keynr= 0; keynr < table.indexes_size(); keynr++, keyinfo++)
 
376
  {
 
377
    message::Table::Index indx= table.indexes(keynr);
 
378
 
 
379
    keyinfo->table= 0;
 
380
    keyinfo->flags= 0;
 
381
 
 
382
    if (indx.is_unique())
 
383
      keyinfo->flags|= HA_NOSAME;
 
384
 
 
385
    if (indx.has_options())
 
386
    {
 
387
      message::Table::Index::IndexOptions indx_options= indx.options();
 
388
      if (indx_options.pack_key())
 
389
        keyinfo->flags|= HA_PACK_KEY;
 
390
 
 
391
      if (indx_options.var_length_key())
 
392
        keyinfo->flags|= HA_VAR_LENGTH_PART;
 
393
 
 
394
      if (indx_options.null_part_key())
 
395
        keyinfo->flags|= HA_NULL_PART_KEY;
 
396
 
 
397
      if (indx_options.binary_pack_key())
 
398
        keyinfo->flags|= HA_BINARY_PACK_KEY;
 
399
 
 
400
      if (indx_options.has_partial_segments())
 
401
        keyinfo->flags|= HA_KEY_HAS_PART_KEY_SEG;
 
402
 
 
403
      if (indx_options.auto_generated_key())
 
404
        keyinfo->flags|= HA_GENERATED_KEY;
 
405
 
 
406
      if (indx_options.has_key_block_size())
 
407
      {
 
408
        keyinfo->flags|= HA_USES_BLOCK_SIZE;
 
409
        keyinfo->block_size= indx_options.key_block_size();
 
410
      }
 
411
      else
 
412
      {
 
413
        keyinfo->block_size= 0;
 
414
      }
 
415
 
 
416
    }
 
417
 
 
418
    switch(indx.type())
 
419
    {
 
420
    case message::Table::Index::UNKNOWN_INDEX:
 
421
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
422
      break;
 
423
    case message::Table::Index::BTREE:
 
424
      keyinfo->algorithm= HA_KEY_ALG_BTREE;
 
425
      break;
 
426
    case message::Table::Index::RTREE:
 
427
      keyinfo->algorithm= HA_KEY_ALG_RTREE;
 
428
      break;
 
429
    case message::Table::Index::HASH:
 
430
      keyinfo->algorithm= HA_KEY_ALG_HASH;
 
431
      break;
 
432
    case message::Table::Index::FULLTEXT:
 
433
      keyinfo->algorithm= HA_KEY_ALG_FULLTEXT;
 
434
 
 
435
    default:
 
436
      /* TODO: suitable warning ? */
 
437
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
438
      break;
 
439
    }
 
440
 
 
441
    keyinfo->key_length= indx.key_length();
 
442
 
 
443
    keyinfo->key_parts= indx.index_part_size();
 
444
 
 
445
    keyinfo->key_part= key_part;
 
446
    keyinfo->rec_per_key= rec_per_key;
 
447
 
 
448
    for (unsigned int partnr= 0;
 
449
        partnr < keyinfo->key_parts;
 
450
        partnr++, key_part++)
 
451
    {
 
452
      message::Table::Index::IndexPart part;
 
453
      part= indx.index_part(partnr);
 
454
 
 
455
      *rec_per_key++= 0;
 
456
 
 
457
      key_part->field= NULL;
 
458
      key_part->fieldnr= part.fieldnr() + 1; // start from 1.
 
459
      key_part->null_bit= 0;
 
460
      /* key_part->null_offset is only set if null_bit (see later) */
 
461
      /* key_part->key_type= */ /* I *THINK* this may be okay.... */
 
462
      /* key_part->type ???? */
 
463
      key_part->key_part_flag= 0;
 
464
      if (part.has_in_reverse_order())
 
465
        key_part->key_part_flag= part.in_reverse_order()? HA_REVERSE_SORT : 0;
 
466
 
 
467
      key_part->length= part.compare_length();
 
468
 
 
469
      key_part->store_length= key_part->length;
 
470
 
 
471
      /* key_part->offset is set later */
 
472
      key_part->key_type= part.key_type();
 
473
 
 
474
    }
 
475
 
 
476
    if (!indx.has_comment())
 
477
    {
 
478
      keyinfo->comment.length= 0;
 
479
      keyinfo->comment.str= NULL;
 
480
    }
 
481
    else
 
482
    {
 
483
      keyinfo->flags|= HA_USES_COMMENT;
 
484
      keyinfo->comment.length= indx.comment().length();
 
485
      keyinfo->comment.str= strmake_root(&share->mem_root,
 
486
                                         indx.comment().c_str(),
 
487
                                         keyinfo->comment.length);
 
488
    }
 
489
 
 
490
    keyinfo->name= strmake_root(&share->mem_root,
 
491
                                indx.name().c_str(),
 
492
                                indx.name().length());
 
493
 
 
494
    share->keynames.type_names[keynr]= keyinfo->name;
 
495
    share->keynames.type_lengths[keynr]= indx.name().length();
 
496
  }
 
497
 
 
498
  share->keys_for_keyread.reset();
 
499
  set_prefix(share->keys_in_use, share->keys);
 
500
 
 
501
  if (table_options.has_connect_string())
 
502
  {
 
503
    size_t len= table_options.connect_string().length();
 
504
    const char* str= table_options.connect_string().c_str();
 
505
 
 
506
    share->connect_string.length= len;
 
507
    share->connect_string.str= strmake_root(&share->mem_root, str, len);
 
508
  }
 
509
 
 
510
  share->key_block_size= table_options.has_key_block_size() ?
 
511
    table_options.key_block_size() : 0;
 
512
 
 
513
  share->fields= table.field_size();
 
514
 
 
515
  share->field= (Field**) alloc_root(&share->mem_root,
 
516
                                     ((share->fields+1) * sizeof(Field*)));
 
517
  share->field[share->fields]= NULL;
 
518
 
 
519
  uint32_t null_fields= 0;
 
520
  share->reclength= 0;
 
521
 
 
522
  uint32_t *field_offsets= (uint32_t*)malloc(share->fields * sizeof(uint32_t));
 
523
  uint32_t *field_pack_length=(uint32_t*)malloc(share->fields*sizeof(uint32_t));
 
524
 
 
525
  assert(field_offsets && field_pack_length); // TODO: fixme
 
526
 
 
527
  uint32_t interval_count= 0;
 
528
  uint32_t interval_parts= 0;
 
529
 
 
530
  uint32_t stored_columns_reclength= 0;
 
531
 
 
532
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
 
533
  {
 
534
    message::Table::Field pfield= table.field(fieldnr);
 
535
    if (pfield.has_constraints() && pfield.constraints().is_nullable())
 
536
      null_fields++;
 
537
 
 
538
    enum_field_types drizzle_field_type=
 
539
      proto_field_type_to_drizzle_type(pfield.type());
 
540
 
 
541
    field_offsets[fieldnr]= stored_columns_reclength;
 
542
 
 
543
    /* the below switch is very similar to
 
544
       CreateField::create_length_to_internal_length in field.cc
 
545
       (which should one day be replace by just this code)
 
546
    */
 
547
    switch(drizzle_field_type)
 
548
    {
 
549
    case DRIZZLE_TYPE_BLOB:
 
550
    case DRIZZLE_TYPE_VARCHAR:
 
551
      {
 
552
        message::Table::Field::StringFieldOptions field_options=
 
553
          pfield.string_options();
 
554
 
 
555
        const CHARSET_INFO *cs= get_charset(field_options.has_collation_id()?
 
556
                                            field_options.collation_id() : 0);
 
557
 
 
558
        if (!cs)
 
559
          cs= default_charset_info;
 
560
 
 
561
        field_pack_length[fieldnr]=
 
562
          calc_pack_length(drizzle_field_type,
 
563
                           field_options.length() * cs->mbmaxlen);
 
564
 
 
565
      }
 
566
      break;
 
567
    case DRIZZLE_TYPE_ENUM:
 
568
      {
 
569
        message::Table::Field::SetFieldOptions field_options=
 
570
          pfield.set_options();
 
571
 
 
572
        field_pack_length[fieldnr]=
 
573
          get_enum_pack_length(field_options.field_value_size());
 
574
 
 
575
        interval_count++;
 
576
        interval_parts+= field_options.field_value_size();
 
577
      }
 
578
      break;
 
579
    case DRIZZLE_TYPE_NEWDECIMAL:
 
580
      {
 
581
        message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
 
582
        field_pack_length[fieldnr]=
 
583
          my_decimal_get_binary_size(fo.precision(), fo.scale());
 
584
      }
 
585
      break;
 
586
    default:
 
587
      /* Zero is okay here as length is fixed for other types. */
 
588
      field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type, 0);
 
589
    }
 
590
 
 
591
    share->reclength+= field_pack_length[fieldnr];
 
592
    stored_columns_reclength+= field_pack_length[fieldnr];
 
593
 
 
594
  }
 
595
 
 
596
  /* data_offset added to stored_rec_length later */
 
597
  share->stored_rec_length= stored_columns_reclength;
 
598
 
 
599
  share->null_fields= null_fields;
 
600
 
 
601
  ulong null_bits= null_fields;
 
602
  if (!table_options.pack_record())
 
603
    null_bits++;
 
604
  ulong data_offset= (null_bits + 7)/8;
 
605
 
 
606
 
 
607
  share->reclength+= data_offset;
 
608
  share->stored_rec_length+= data_offset;
 
609
 
 
610
  ulong rec_buff_length;
 
611
 
 
612
  rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
613
  share->rec_buff_length= rec_buff_length;
 
614
 
 
615
  unsigned char* record= NULL;
 
616
 
 
617
  if (!(record= (unsigned char *) alloc_root(&share->mem_root,
 
618
                                     rec_buff_length)))
 
619
    abort();
 
620
 
 
621
  memset(record, 0, rec_buff_length);
 
622
 
 
623
  int null_count= 0;
 
624
 
 
625
  if (!table_options.pack_record())
 
626
  {
 
627
    null_count++; // one bit for delete mark.
 
628
    *record|= 1;
 
629
  }
 
630
 
 
631
  share->default_values= record;
 
632
 
 
633
  if (interval_count)
 
634
  {
 
635
    share->intervals= (TYPELIB*)alloc_root(&share->mem_root,
 
636
                                           interval_count*sizeof(TYPELIB));
 
637
  }
 
638
  else
 
639
    share->intervals= NULL;
 
640
 
 
641
  share->fieldnames.type_names= (const char**)alloc_root(&share->mem_root,
 
642
                                  (share->fields+1)*sizeof(char*));
 
643
 
 
644
  share->fieldnames.type_lengths= (unsigned int*) alloc_root(&share->mem_root,
 
645
                                  (share->fields+1)*sizeof(unsigned int));
 
646
 
 
647
  share->fieldnames.type_names[share->fields]= NULL;
 
648
  share->fieldnames.type_lengths[share->fields]= 0;
 
649
  share->fieldnames.count= share->fields;
 
650
 
 
651
 
 
652
  /* Now fix the TYPELIBs for the intervals (enum values)
 
653
     and field names.
 
654
   */
 
655
 
 
656
  uint32_t interval_nr= 0;
 
657
 
 
658
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
 
659
  {
 
660
    message::Table::Field pfield= table.field(fieldnr);
 
661
 
 
662
    /* field names */
 
663
    share->fieldnames.type_names[fieldnr]= strmake_root(&share->mem_root,
 
664
                                                        pfield.name().c_str(),
 
665
                                                        pfield.name().length());
 
666
 
 
667
    share->fieldnames.type_lengths[fieldnr]= pfield.name().length();
 
668
 
 
669
    /* enum typelibs */
 
670
    if (pfield.type() != message::Table::Field::ENUM)
 
671
      continue;
 
672
 
 
673
    message::Table::Field::SetFieldOptions field_options= pfield.set_options();
 
674
 
 
675
    const CHARSET_INFO *charset= get_charset(field_options.has_collation_id()?
 
676
                                             field_options.collation_id() : 0);
 
677
 
 
678
    if (!charset)
 
679
      charset= default_charset_info;
 
680
 
 
681
    TYPELIB *t= &(share->intervals[interval_nr]);
 
682
 
 
683
    t->type_names= (const char**)alloc_root(&share->mem_root,
 
684
                           (field_options.field_value_size()+1)*sizeof(char*));
 
685
 
 
686
    t->type_lengths= (unsigned int*) alloc_root(&share->mem_root,
 
687
                     (field_options.field_value_size()+1)*sizeof(unsigned int));
 
688
 
 
689
    t->type_names[field_options.field_value_size()]= NULL;
 
690
    t->type_lengths[field_options.field_value_size()]= 0;
 
691
 
 
692
    t->count= field_options.field_value_size();
 
693
    t->name= NULL;
 
694
 
 
695
    for (int n= 0; n < field_options.field_value_size(); n++)
 
696
    {
 
697
      t->type_names[n]= strmake_root(&share->mem_root,
 
698
                                     field_options.field_value(n).c_str(),
 
699
                                     field_options.field_value(n).length());
 
700
 
 
701
      /* Go ask the charset what the length is as for "" length=1
 
702
         and there's stripping spaces or some other crack going on.
 
703
       */
 
704
      uint32_t lengthsp;
 
705
      lengthsp= charset->cset->lengthsp(charset, t->type_names[n],
 
706
                                        field_options.field_value(n).length());
 
707
      t->type_lengths[n]= lengthsp;
 
708
    }
 
709
    interval_nr++;
 
710
  }
 
711
 
 
712
 
 
713
  /* and read the fields */
 
714
  interval_nr= 0;
 
715
 
 
716
  bool use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
 
717
 
 
718
  if (use_hash)
 
719
    use_hash= !hash_init(&share->name_hash,
 
720
                         system_charset_info,
 
721
                         share->fields, 0, 0,
 
722
                         (hash_get_key) get_field_name, 0, 0);
 
723
 
 
724
  unsigned char* null_pos= record;;
 
725
  int null_bit_pos= (table_options.pack_record()) ? 0 : 1;
 
726
 
 
727
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
 
728
  {
 
729
    message::Table::Field pfield= table.field(fieldnr);
 
730
 
 
731
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
 
732
 
 
733
    switch(pfield.format())
 
734
    {
 
735
    case message::Table::Field::DefaultFormat:
 
736
      column_format= COLUMN_FORMAT_TYPE_DEFAULT;
 
737
      break;
 
738
    case message::Table::Field::FixedFormat:
 
739
      column_format= COLUMN_FORMAT_TYPE_FIXED;
 
740
      break;
 
741
    case message::Table::Field::DynamicFormat:
 
742
      column_format= COLUMN_FORMAT_TYPE_DYNAMIC;
 
743
      break;
 
744
    default:
 
745
      assert(1);
 
746
    }
 
747
 
 
748
    Field::utype unireg_type= Field::NONE;
 
749
 
 
750
    if (pfield.has_numeric_options()
 
751
       && pfield.numeric_options().is_autoincrement())
 
752
    {
 
753
      unireg_type= Field::NEXT_NUMBER;
 
754
    }
 
755
 
 
756
    if (pfield.has_options()
 
757
       && pfield.options().has_default_value()
 
758
       && pfield.options().default_value().compare("NOW()") == 0)
 
759
    {
 
760
      if (pfield.options().has_update_value()
 
761
         && pfield.options().update_value().compare("NOW()") == 0)
 
762
      {
 
763
        unireg_type= Field::TIMESTAMP_DNUN_FIELD;
 
764
      }
 
765
      else if (!pfield.options().has_update_value())
 
766
      {
 
767
        unireg_type= Field::TIMESTAMP_DN_FIELD;
 
768
      }
 
769
      else
 
770
        assert(1); // Invalid update value.
 
771
    }
 
772
    else if (pfield.has_options()
 
773
             && pfield.options().has_update_value()
 
774
             && pfield.options().update_value().compare("NOW()") == 0)
 
775
    {
 
776
      unireg_type= Field::TIMESTAMP_UN_FIELD;
 
777
    }
 
778
 
 
779
    LEX_STRING comment;
 
780
    if (!pfield.has_comment())
 
781
    {
 
782
      comment.str= (char*)"";
 
783
      comment.length= 0;
 
784
    }
 
785
    else
 
786
    {
 
787
      size_t len= pfield.comment().length();
 
788
      const char* str= pfield.comment().c_str();
 
789
 
 
790
      comment.str= strmake_root(&share->mem_root, str, len);
 
791
      comment.length= len;
 
792
    }
 
793
 
 
794
    enum_field_types field_type;
 
795
 
 
796
    field_type= proto_field_type_to_drizzle_type(pfield.type());
 
797
 
 
798
    const CHARSET_INFO *charset= &my_charset_bin;
 
799
 
 
800
    if (field_type==DRIZZLE_TYPE_BLOB
 
801
       || field_type==DRIZZLE_TYPE_VARCHAR)
 
802
    {
 
803
      message::Table::Field::StringFieldOptions field_options=
 
804
        pfield.string_options();
 
805
 
 
806
      charset= get_charset(field_options.has_collation_id()?
 
807
                           field_options.collation_id() : 0);
 
808
 
 
809
      if (!charset)
 
810
        charset= default_charset_info;
 
811
 
 
812
    }
 
813
 
 
814
    if (field_type==DRIZZLE_TYPE_ENUM)
 
815
    {
 
816
      message::Table::Field::SetFieldOptions field_options=
 
817
        pfield.set_options();
 
818
 
 
819
      charset= get_charset(field_options.has_collation_id()?
 
820
                           field_options.collation_id() : 0);
 
821
 
 
822
      if (!charset)
 
823
        charset= default_charset_info;
 
824
 
 
825
    }
 
826
 
 
827
    Item *default_value= NULL;
 
828
 
 
829
    if (pfield.options().has_default_value()
 
830
       || pfield.options().has_default_null()
 
831
       || pfield.options().has_default_bin_value())
 
832
    {
 
833
      default_value= default_value_item(field_type,
 
834
                                        charset,
 
835
                                        pfield.options().default_null(),
 
836
                                        &pfield.options().default_value(),
 
837
                                        &pfield.options().default_bin_value());
 
838
    }
 
839
 
 
840
    uint32_t pack_flag= pfield.pack_flag(); /* TODO: MUST DIE */
 
841
 
 
842
    Table temp_table; /* Use this so that BLOB DEFAULT '' works */
 
843
    memset(&temp_table, 0, sizeof(temp_table));
 
844
    temp_table.s= share;
 
845
    temp_table.in_use= session;
 
846
    temp_table.s->db_low_byte_first= 1; //handler->low_byte_first();
 
847
    temp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
 
848
 
 
849
    Field* f= make_field(share, &share->mem_root,
 
850
                         record+field_offsets[fieldnr]+data_offset,
 
851
                         pfield.options().length(),
 
852
                         null_pos,
 
853
                         null_bit_pos,
 
854
                         pack_flag,
 
855
                         field_type,
 
856
                         charset,
 
857
                         (Field::utype) MTYP_TYPENR(unireg_type),
 
858
                         ((field_type==DRIZZLE_TYPE_ENUM)?
 
859
                         share->intervals+(interval_nr++)
 
860
                         : (TYPELIB*) 0),
 
861
                        share->fieldnames.type_names[fieldnr]);
 
862
 
 
863
    share->field[fieldnr]= f;
 
864
 
 
865
    f->init(&temp_table); /* blob default values need table obj */
 
866
 
 
867
    if (!(f->flags & NOT_NULL_FLAG))
 
868
    {
 
869
      *f->null_ptr|= f->null_bit;
 
870
      if (!(null_bit_pos= (null_bit_pos + 1) & 7))
 
871
        null_pos++;
 
872
      null_count++;
 
873
    }
 
874
 
 
875
    if (default_value)
 
876
    {
 
877
      enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
 
878
      session->count_cuted_fields= CHECK_FIELD_WARN;
 
879
      int res= default_value->save_in_field(f, 1);
 
880
      session->count_cuted_fields= old_count_cuted_fields;
 
881
      if (res != 0 && res != 3)
 
882
      {
 
883
        my_error(ER_INVALID_DEFAULT, MYF(0), f->field_name);
 
884
        error= 1;
 
885
        goto err;
 
886
      }
 
887
    }
 
888
    else if (f->real_type() == DRIZZLE_TYPE_ENUM &&
 
889
            (f->flags & NOT_NULL_FLAG))
 
890
    {
 
891
      f->set_notnull();
 
892
      f->store((int64_t) 1, true);
 
893
    }
 
894
    else
 
895
      f->reset();
 
896
 
 
897
    /* hack to undo f->init() */
 
898
    f->table= NULL;
 
899
    f->orig_table= NULL;
 
900
 
 
901
    f->field_index= fieldnr;
 
902
    f->comment= comment;
 
903
    if (!default_value
 
904
       && !(f->unireg_check==Field::NEXT_NUMBER)
 
905
       && (f->flags & NOT_NULL_FLAG)
 
906
       && (f->real_type() != DRIZZLE_TYPE_TIMESTAMP))
 
907
      f->flags|= NO_DEFAULT_VALUE_FLAG;
 
908
 
 
909
    if (f->unireg_check == Field::NEXT_NUMBER)
 
910
      share->found_next_number_field= &(share->field[fieldnr]);
 
911
 
 
912
    if (share->timestamp_field == f)
 
913
      share->timestamp_field_offset= fieldnr;
 
914
 
 
915
    if (use_hash) /* supposedly this never fails... but comments lie */
 
916
      (void) my_hash_insert(&share->name_hash,
 
917
                            (unsigned char*)&(share->field[fieldnr]));
 
918
 
 
919
  }
 
920
 
 
921
  keyinfo= share->key_info;
 
922
  for (unsigned int keynr= 0; keynr < share->keys; keynr++, keyinfo++)
 
923
  {
 
924
    key_part= keyinfo->key_part;
 
925
 
 
926
    for (unsigned int partnr= 0;
 
927
         partnr < keyinfo->key_parts;
 
928
         partnr++, key_part++)
 
929
    {
 
930
      /* Fix up key_part->offset by adding data_offset.
 
931
         We really should compute offset as well.
 
932
         But at least this way we are a little better. */
 
933
      key_part->offset= field_offsets[key_part->fieldnr-1] + data_offset;
 
934
    }
 
935
  }
 
936
 
 
937
  /*
 
938
    We need to set the unused bits to 1. If the number of bits is a multiple
 
939
    of 8 there are no unused bits.
 
940
  */
 
941
 
 
942
  if (null_count & 7)
 
943
    *(record + null_count / 8)|= ~(((unsigned char) 1 << (null_count & 7)) - 1);
 
944
 
 
945
  share->null_bytes= (null_pos - (unsigned char*) record +
 
946
                      (null_bit_pos + 7) / 8);
 
947
 
 
948
  share->last_null_bit_pos= null_bit_pos;
 
949
 
 
950
  free(field_offsets);
 
951
  free(field_pack_length);
 
952
 
 
953
  if (!(handler_file= get_new_handler(share, session->mem_root,
 
954
                                     share->db_type())))
 
955
    abort(); // FIXME
 
956
 
 
957
  /* Fix key stuff */
 
958
  if (share->key_parts)
 
959
  {
 
960
    uint32_t primary_key=(uint32_t) (find_type((char*) "PRIMARY",
 
961
                                       &share->keynames, 3) - 1);
 
962
 
 
963
    int64_t ha_option= handler_file->ha_table_flags();
 
964
 
 
965
    keyinfo= share->key_info;
 
966
    key_part= keyinfo->key_part;
 
967
 
 
968
    for (uint32_t key= 0 ; key < share->keys ; key++,keyinfo++)
 
969
    {
 
970
      uint32_t usable_parts= 0;
 
971
 
 
972
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
 
973
      {
 
974
        /*
 
975
          If the UNIQUE key doesn't have NULL columns and is not a part key
 
976
          declare this as a primary key.
 
977
        */
 
978
        primary_key=key;
 
979
        for (uint32_t i= 0 ; i < keyinfo->key_parts ;i++)
 
980
        {
 
981
          uint32_t fieldnr= key_part[i].fieldnr;
 
982
          if (!fieldnr ||
 
983
              share->field[fieldnr-1]->null_ptr ||
 
984
              share->field[fieldnr-1]->key_length() !=
 
985
              key_part[i].length)
 
986
          {
 
987
            primary_key=MAX_KEY;                // Can't be used
 
988
            break;
 
989
          }
 
990
        }
 
991
      }
 
992
 
 
993
      for (uint32_t i= 0 ; i < keyinfo->key_parts ; key_part++,i++)
 
994
      {
 
995
        Field *field;
 
996
        if (!key_part->fieldnr)
 
997
        {
 
998
//          error= 4;                             // Wrong file
 
999
          abort(); // goto err;
 
1000
        }
 
1001
        field= key_part->field= share->field[key_part->fieldnr-1];
 
1002
        key_part->type= field->key_type();
 
1003
        if (field->null_ptr)
 
1004
        {
 
1005
          key_part->null_offset=(uint32_t) ((unsigned char*) field->null_ptr -
 
1006
                                        share->default_values);
 
1007
          key_part->null_bit= field->null_bit;
 
1008
          key_part->store_length+=HA_KEY_NULL_LENGTH;
 
1009
          keyinfo->flags|=HA_NULL_PART_KEY;
 
1010
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
 
1011
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
 
1012
        }
 
1013
        if (field->type() == DRIZZLE_TYPE_BLOB ||
 
1014
            field->real_type() == DRIZZLE_TYPE_VARCHAR)
 
1015
        {
 
1016
          if (field->type() == DRIZZLE_TYPE_BLOB)
 
1017
            key_part->key_part_flag|= HA_BLOB_PART;
 
1018
          else
 
1019
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
 
1020
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
 
1021
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
 
1022
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
 
1023
        }
 
1024
        if (i == 0 && key != primary_key)
 
1025
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
 
1026
                           (keyinfo->key_parts == 1)) ?
 
1027
                           UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
 
1028
        if (i == 0)
 
1029
          field->key_start.set(key);
 
1030
        if (field->key_length() == key_part->length &&
 
1031
            !(field->flags & BLOB_FLAG))
 
1032
        {
 
1033
          if (handler_file->index_flags(key, i, 0) & HA_KEYREAD_ONLY)
 
1034
          {
 
1035
            share->keys_for_keyread.set(key);
 
1036
            field->part_of_key.set(key);
 
1037
            field->part_of_key_not_clustered.set(key);
 
1038
          }
 
1039
          if (handler_file->index_flags(key, i, 1) & HA_READ_ORDER)
 
1040
            field->part_of_sortkey.set(key);
 
1041
        }
 
1042
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
 
1043
            usable_parts == i)
 
1044
          usable_parts++;                       // For FILESORT
 
1045
        field->flags|= PART_KEY_FLAG;
 
1046
        if (key == primary_key)
 
1047
        {
 
1048
          field->flags|= PRI_KEY_FLAG;
 
1049
          /*
 
1050
            If this field is part of the primary key and all keys contains
 
1051
            the primary key, then we can use any key to find this column
 
1052
          */
 
1053
          if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
 
1054
          {
 
1055
            field->part_of_key= share->keys_in_use;
 
1056
            if (field->part_of_sortkey.test(key))
 
1057
              field->part_of_sortkey= share->keys_in_use;
 
1058
          }
 
1059
        }
 
1060
        if (field->key_length() != key_part->length)
 
1061
        {
 
1062
          key_part->key_part_flag|= HA_PART_KEY_SEG;
 
1063
        }
 
1064
      }
 
1065
      keyinfo->usable_key_parts= usable_parts; // Filesort
 
1066
 
 
1067
      set_if_bigger(share->max_key_length,keyinfo->key_length+
 
1068
                    keyinfo->key_parts);
 
1069
      share->total_key_length+= keyinfo->key_length;
 
1070
      /*
 
1071
        MERGE tables do not have unique indexes. But every key could be
 
1072
        an unique index on the underlying MyISAM table. (Bug #10400)
 
1073
      */
 
1074
      if ((keyinfo->flags & HA_NOSAME) ||
 
1075
          (ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
 
1076
        set_if_bigger(share->max_unique_length,keyinfo->key_length);
 
1077
    }
 
1078
    if (primary_key < MAX_KEY &&
 
1079
        (share->keys_in_use.test(primary_key)))
 
1080
    {
 
1081
      share->primary_key= primary_key;
 
1082
      /*
 
1083
        If we are using an integer as the primary key then allow the user to
 
1084
        refer to it as '_rowid'
 
1085
      */
 
1086
      if (share->key_info[primary_key].key_parts == 1)
 
1087
      {
 
1088
        Field *field= share->key_info[primary_key].key_part[0].field;
 
1089
        if (field && field->result_type() == INT_RESULT)
 
1090
        {
 
1091
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
 
1092
          share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
 
1093
                                      fieldnr);
 
1094
        }
 
1095
      }
 
1096
 
 
1097
    }
 
1098
    else
 
1099
      share->primary_key = MAX_KEY; // we do not have a primary key
 
1100
  }
 
1101
  else
 
1102
    share->primary_key= MAX_KEY;
 
1103
 
 
1104
  if (share->found_next_number_field)
 
1105
  {
 
1106
    Field *reg_field= *share->found_next_number_field;
 
1107
    if ((int) (share->next_number_index= (uint32_t)
 
1108
               find_ref_key(share->key_info, share->keys,
 
1109
                            share->default_values, reg_field,
 
1110
                            &share->next_number_key_offset,
 
1111
                            &share->next_number_keypart)) < 0)
 
1112
    {
 
1113
      /* Wrong field definition */
 
1114
      error= 4;
 
1115
      goto err;
 
1116
    }
 
1117
    else
 
1118
      reg_field->flags |= AUTO_INCREMENT_FLAG;
 
1119
  }
 
1120
 
 
1121
  if (share->blob_fields)
 
1122
  {
 
1123
    Field **ptr;
 
1124
    uint32_t k, *save;
 
1125
 
 
1126
    /* Store offsets to blob fields to find them fast */
 
1127
    if (!(share->blob_field= save=
 
1128
          (uint*) alloc_root(&share->mem_root,
 
1129
                             (uint32_t) (share->blob_fields* sizeof(uint32_t)))))
 
1130
      goto err;
 
1131
    for (k= 0, ptr= share->field ; *ptr ; ptr++, k++)
 
1132
    {
 
1133
      if ((*ptr)->flags & BLOB_FLAG)
 
1134
        (*save++)= k;
 
1135
    }
 
1136
  }
 
1137
 
 
1138
  share->db_low_byte_first= handler_file->low_byte_first();
 
1139
  share->column_bitmap_size= bitmap_buffer_size(share->fields);
 
1140
 
 
1141
  my_bitmap_map *bitmaps;
 
1142
 
 
1143
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
 
1144
                                             share->column_bitmap_size)))
 
1145
    goto err;
 
1146
  share->all_set.init(bitmaps, share->fields);
 
1147
  share->all_set.setAll();
 
1148
 
 
1149
  if (handler_file)
 
1150
    delete handler_file;
 
1151
  return (0);
 
1152
 
 
1153
err:
 
1154
  share->error= error;
 
1155
  share->open_errno= my_errno;
 
1156
  share->errarg= 0;
 
1157
  hash_free(&share->name_hash);
 
1158
  if (handler_file)
 
1159
    delete handler_file;
 
1160
  share->open_table_error(error, share->open_errno, 0);
 
1161
 
 
1162
  return error;
 
1163
}
 
1164
 
 
1165
/*
 
1166
  Read table definition from a binary / text based .frm file
 
1167
 
 
1168
  SYNOPSIS
 
1169
  open_table_def()
 
1170
  session               Thread handler
 
1171
  share         Fill this with table definition
 
1172
 
 
1173
  NOTES
 
1174
    This function is called when the table definition is not cached in
 
1175
    table_def_cache
 
1176
    The data is returned in 'share', which is alloced by
 
1177
    alloc_table_share().. The code assumes that share is initialized.
 
1178
 
 
1179
  RETURN VALUES
 
1180
   0    ok
 
1181
   1    Error (see open_table_error)
 
1182
   2    Error (see open_table_error)
 
1183
   3    Wrong data in .frm file
 
1184
   4    Error (see open_table_error)
 
1185
   5    Error (see open_table_error: charset unavailable)
 
1186
   6    Unknown .frm version
 
1187
*/
 
1188
 
 
1189
int open_table_def(Session *session, TableShare *share)
 
1190
{
 
1191
  int error;
 
1192
  bool error_given;
 
1193
 
 
1194
  error= 1;
 
1195
  error_given= 0;
 
1196
 
 
1197
  message::Table table;
 
1198
 
 
1199
  error= plugin::StorageEngine::getTableProto(share->normalized_path.str,
 
1200
                                              &table);
 
1201
 
 
1202
  if (error != EEXIST)
 
1203
  {
 
1204
    if (error>0)
 
1205
    {
 
1206
      my_errno= error;
 
1207
      error= 1;
 
1208
    }
 
1209
    else
 
1210
    {
 
1211
      if (!table.IsInitialized())
 
1212
      {
 
1213
        error= 4;
 
1214
      }
 
1215
    }
 
1216
    goto err_not_open;
 
1217
  }
 
1218
 
 
1219
  error= parse_table_proto(session, table, share);
 
1220
 
 
1221
  share->table_category= get_table_category(& share->db);
 
1222
 
 
1223
  if (!error)
 
1224
    session->status_var.opened_shares++;
 
1225
 
 
1226
err_not_open:
 
1227
  if (error && !error_given)
 
1228
  {
 
1229
    share->error= error;
 
1230
    share->open_table_error(error, (share->open_errno= my_errno), 0);
 
1231
  }
 
1232
 
 
1233
  return(error);
 
1234
}
 
1235
 
 
1236
 
 
1237
/*
 
1238
  Open a table based on a TableShare
 
1239
 
 
1240
  SYNOPSIS
 
1241
    open_table_from_share()
 
1242
    session                     Thread handler
 
1243
    share               Table definition
 
1244
    alias               Alias for table
 
1245
    db_stat             open flags (for example HA_OPEN_KEYFILE|
 
1246
                        HA_OPEN_RNDFILE..) can be 0 (example in
 
1247
                        ha_example_table)
 
1248
    prgflag             READ_ALL etc..
 
1249
    ha_open_flags       HA_OPEN_ABORT_IF_LOCKED etc..
 
1250
    outparam            result table
 
1251
    open_mode           One of OTM_OPEN|OTM_CREATE|OTM_ALTER
 
1252
                        if OTM_CREATE some errors are ignore
 
1253
                        if OTM_ALTER HA_OPEN is not called
 
1254
 
 
1255
  RETURN VALUES
 
1256
   0    ok
 
1257
   1    Error (see open_table_error)
 
1258
   2    Error (see open_table_error)
 
1259
   3    Wrong data in .frm file
 
1260
   4    Error (see open_table_error)
 
1261
   5    Error (see open_table_error: charset unavailable)
 
1262
   7    Table definition has changed in engine
 
1263
*/
 
1264
 
 
1265
int open_table_from_share(Session *session, TableShare *share, const char *alias,
 
1266
                          uint32_t db_stat, uint32_t prgflag, uint32_t ha_open_flags,
 
1267
                          Table *outparam, open_table_mode open_mode)
 
1268
{
 
1269
  int error;
 
1270
  uint32_t records, i, bitmap_size;
 
1271
  bool error_reported= false;
 
1272
  unsigned char *record, *bitmaps;
 
1273
  Field **field_ptr;
 
1274
 
 
1275
  /* Parsing of partitioning information from .frm needs session->lex set up. */
 
1276
  assert(session->lex->is_lex_started);
 
1277
 
 
1278
  error= 1;
 
1279
  outparam->resetTable(session, share, db_stat);
 
1280
 
 
1281
 
 
1282
  if (!(outparam->alias= strdup(alias)))
 
1283
    goto err;
 
1284
 
 
1285
  /* Allocate handler */
 
1286
  if (!(prgflag & OPEN_FRM_FILE_ONLY))
 
1287
  {
 
1288
    if (!(outparam->file= get_new_handler(share, &outparam->mem_root,
 
1289
                                          share->db_type())))
 
1290
      goto err;
 
1291
  }
 
1292
  else
 
1293
  {
 
1294
    assert(!db_stat);
 
1295
  }
 
1296
 
 
1297
  error= 4;
 
1298
  records= 0;
 
1299
  if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
 
1300
    records=1;
 
1301
  if (prgflag & (READ_ALL+EXTRA_RECORD))
 
1302
    records++;
 
1303
 
 
1304
  if (!(record= (unsigned char*) alloc_root(&outparam->mem_root,
 
1305
                                   share->rec_buff_length * records)))
 
1306
    goto err;
 
1307
 
 
1308
  if (records == 0)
 
1309
  {
 
1310
    /* We are probably in hard repair, and the buffers should not be used */
 
1311
    outparam->record[0]= outparam->record[1]= share->default_values;
 
1312
  }
 
1313
  else
 
1314
  {
 
1315
    outparam->record[0]= record;
 
1316
    if (records > 1)
 
1317
      outparam->record[1]= record+ share->rec_buff_length;
 
1318
    else
 
1319
      outparam->record[1]= outparam->record[0];   // Safety
 
1320
  }
 
1321
 
 
1322
#ifdef HAVE_purify
 
1323
  /*
 
1324
    We need this because when we read var-length rows, we are not updating
 
1325
    bytes after end of varchar
 
1326
  */
 
1327
  if (records > 1)
 
1328
  {
 
1329
    memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
 
1330
    memcpy(outparam->record[1], share->default_values, share->null_bytes);
 
1331
    if (records > 2)
 
1332
      memcpy(outparam->record[1], share->default_values,
 
1333
             share->rec_buff_length);
 
1334
  }
 
1335
#endif
 
1336
 
 
1337
  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
 
1338
                                          (uint32_t) ((share->fields+1)*
 
1339
                                                  sizeof(Field*)))))
 
1340
    goto err;
 
1341
 
 
1342
  outparam->field= field_ptr;
 
1343
 
 
1344
  record= (unsigned char*) outparam->record[0]-1;       /* Fieldstart = 1 */
 
1345
 
 
1346
  outparam->null_flags= (unsigned char*) record+1;
 
1347
 
 
1348
  /* Setup copy of fields from share, but use the right alias and record */
 
1349
  for (i= 0 ; i < share->fields; i++, field_ptr++)
 
1350
  {
 
1351
    if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
 
1352
      goto err;
 
1353
  }
 
1354
  (*field_ptr)= 0;                              // End marker
 
1355
 
 
1356
  if (share->found_next_number_field)
 
1357
    outparam->found_next_number_field=
 
1358
      outparam->field[(uint32_t) (share->found_next_number_field - share->field)];
 
1359
  if (share->timestamp_field)
 
1360
    outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
 
1361
 
 
1362
 
 
1363
  /* Fix key->name and key_part->field */
 
1364
  if (share->key_parts)
 
1365
  {
 
1366
    KEY *key_info, *key_info_end;
 
1367
    KEY_PART_INFO *key_part;
 
1368
    uint32_t n_length;
 
1369
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
 
1370
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
 
1371
      goto err;
 
1372
    outparam->key_info= key_info;
 
1373
    key_part= (reinterpret_cast<KEY_PART_INFO*> (key_info+share->keys));
 
1374
 
 
1375
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
 
1376
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
 
1377
                                                   share->key_parts));
 
1378
 
 
1379
    for (key_info_end= key_info + share->keys ;
 
1380
         key_info < key_info_end ;
 
1381
         key_info++)
 
1382
    {
 
1383
      KEY_PART_INFO *key_part_end;
 
1384
 
 
1385
      key_info->table= outparam;
 
1386
      key_info->key_part= key_part;
 
1387
 
 
1388
      for (key_part_end= key_part+ key_info->key_parts ;
 
1389
           key_part < key_part_end ;
 
1390
           key_part++)
 
1391
      {
 
1392
        Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
 
1393
 
 
1394
        if (field->key_length() != key_part->length &&
 
1395
            !(field->flags & BLOB_FLAG))
 
1396
        {
 
1397
          /*
 
1398
            We are using only a prefix of the column as a key:
 
1399
            Create a new field for the key part that matches the index
 
1400
          */
 
1401
          field= key_part->field=field->new_field(&outparam->mem_root,
 
1402
                                                  outparam, 0);
 
1403
          field->field_length= key_part->length;
 
1404
        }
 
1405
      }
 
1406
    }
 
1407
  }
 
1408
 
 
1409
  /* Allocate bitmaps */
 
1410
 
 
1411
  bitmap_size= share->column_bitmap_size;
 
1412
  if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
 
1413
    goto err;
 
1414
  outparam->def_read_set.init((my_bitmap_map*) bitmaps, share->fields);
 
1415
  outparam->def_write_set.init((my_bitmap_map*) (bitmaps+bitmap_size), share->fields);
 
1416
  outparam->tmp_set.init((my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields);
 
1417
  outparam->default_column_bitmaps();
 
1418
 
 
1419
  /* The table struct is now initialized;  Open the table */
 
1420
  error= 2;
 
1421
  if (db_stat && open_mode != OTM_ALTER)
 
1422
  {
 
1423
    int ha_err;
 
1424
    if ((ha_err= (outparam->file->
 
1425
                  ha_open(outparam, share->normalized_path.str,
 
1426
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
 
1427
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
 
1428
                           (db_stat & HA_WAIT_IF_LOCKED) ?  HA_OPEN_WAIT_IF_LOCKED :
 
1429
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
 
1430
                          HA_OPEN_ABORT_IF_LOCKED :
 
1431
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
 
1432
    {
 
1433
      /* Set a flag if the table is crashed and it can be auto. repaired */
 
1434
      share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
 
1435
                       outparam->file->auto_repair() &&
 
1436
                       !(ha_open_flags & HA_OPEN_FOR_REPAIR));
 
1437
 
 
1438
      switch (ha_err)
 
1439
      {
 
1440
        case HA_ERR_NO_SUCH_TABLE:
 
1441
          /*
 
1442
            The table did not exists in storage engine, use same error message
 
1443
            as if the .frm file didn't exist
 
1444
          */
 
1445
          error= 1;
 
1446
          my_errno= ENOENT;
 
1447
          break;
 
1448
        case EMFILE:
 
1449
          /*
 
1450
            Too many files opened, use same error message as if the .frm
 
1451
            file can't open
 
1452
           */
 
1453
          error= 1;
 
1454
          my_errno= EMFILE;
 
1455
          break;
 
1456
        default:
 
1457
          outparam->file->print_error(ha_err, MYF(0));
 
1458
          error_reported= true;
 
1459
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
 
1460
            error= 7;
 
1461
          break;
 
1462
      }
 
1463
      goto err;
 
1464
    }
 
1465
  }
 
1466
 
 
1467
#if defined(HAVE_purify)
 
1468
  memset(bitmaps, 0, bitmap_size*3);
 
1469
#endif
 
1470
 
 
1471
  session->status_var.opened_tables++;
 
1472
 
 
1473
  return (0);
 
1474
 
 
1475
 err:
 
1476
  if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
 
1477
    share->open_table_error(error, my_errno, 0);
 
1478
  delete outparam->file;
 
1479
  outparam->file= 0;                            // For easier error checking
 
1480
  outparam->db_stat= 0;
 
1481
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on zeroed root
 
1482
  free((char*) outparam->alias);
 
1483
  return (error);
 
1484
}
 
1485
 
 
1486
/*
 
1487
  Free information allocated by openfrm
 
1488
 
 
1489
  SYNOPSIS
 
1490
    closefrm()
 
1491
    table               Table object to free
 
1492
    free_share          Is 1 if we also want to free table_share
 
1493
*/
 
1494
 
 
1495
int Table::closefrm(bool free_share)
79
1496
{
80
1497
  int error= 0;
81
1498
 
82
1499
  if (db_stat)
83
 
    error= cursor->close();
84
 
  _alias.clear();
 
1500
    error= file->close();
 
1501
  free((char*) alias);
 
1502
  alias= NULL;
85
1503
  if (field)
86
1504
  {
87
1505
    for (Field **ptr=field ; *ptr ; ptr++)
88
 
    {
89
1506
      delete *ptr;
90
 
    }
91
1507
    field= 0;
92
1508
  }
93
 
  delete cursor;
94
 
  cursor= 0;                            /* For easier errorchecking */
95
 
 
 
1509
  delete file;
 
1510
  file= 0;                              /* For easier errorchecking */
96
1511
  if (free_share)
97
1512
  {
98
 
    release();
 
1513
    if (s->tmp_table == NO_TMP_TABLE)
 
1514
      TableShare::release(s);
 
1515
    else
 
1516
      s->free_table_share();
99
1517
  }
 
1518
  free_root(&mem_root, MYF(0));
100
1519
 
101
1520
  return error;
102
1521
}
103
1522
 
104
 
Table::~Table()
105
 
{
106
 
  mem_root.free_root(MYF(0));
107
 
}
108
 
 
109
 
 
110
 
void Table::resetTable(Session *session,
111
 
                       TableShare *share,
112
 
                       uint32_t db_stat_arg)
113
 
{
114
 
  setShare(share);
115
 
  field= NULL;
116
 
 
117
 
  cursor= NULL;
118
 
  next= NULL;
119
 
  prev= NULL;
120
 
 
121
 
  read_set= NULL;
122
 
  write_set= NULL;
123
 
 
124
 
  tablenr= 0;
125
 
  db_stat= db_stat_arg;
126
 
 
127
 
  in_use= session;
128
 
  record[0]= (unsigned char *) NULL;
129
 
  record[1]= (unsigned char *) NULL;
130
 
 
131
 
  insert_values.clear();
132
 
  key_info= NULL;
133
 
  next_number_field= NULL;
134
 
  found_next_number_field= NULL;
135
 
  timestamp_field= NULL;
136
 
 
137
 
  pos_in_table_list= NULL;
138
 
  group= NULL;
139
 
  _alias.clear();
140
 
  null_flags= NULL;
141
 
 
142
 
  lock_position= 0;
143
 
  lock_data_start= 0;
144
 
  lock_count= 0;
145
 
  used_fields= 0;
146
 
  status= 0;
147
 
  derived_select_number= 0;
148
 
  current_lock= F_UNLCK;
149
 
  copy_blobs= false;
150
 
 
151
 
  maybe_null= false;
152
 
 
153
 
  null_row= false;
154
 
 
155
 
  force_index= false;
156
 
  distinct= false;
157
 
  const_table= false;
158
 
  no_rows= false;
159
 
  key_read= false;
160
 
  no_keyread= false;
161
 
 
162
 
  open_placeholder= false;
163
 
  locked_by_name= false;
164
 
  no_cache= false;
165
 
 
166
 
  auto_increment_field_not_null= false;
167
 
  alias_name_used= false;
168
 
 
169
 
  query_id= 0;
170
 
  quick_condition_rows= 0;
171
 
 
172
 
  timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
173
 
  map= 0;
174
 
 
175
 
  reginfo.reset();
176
 
 
177
 
  covering_keys.reset();
178
 
 
179
 
  quick_keys.reset();
180
 
  merge_keys.reset();
181
 
 
182
 
  keys_in_use_for_query.reset();
183
 
  keys_in_use_for_group_by.reset();
184
 
  keys_in_use_for_order_by.reset();
185
 
 
186
 
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
187
 
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
188
 
 
189
 
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
190
 
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
191
 
 
192
 
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
193
 
}
194
 
 
195
 
 
196
1523
 
197
1524
/* Deallocate temporary blob storage */
198
1525
 
202
1529
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
203
1530
       ptr != end ;
204
1531
       ptr++)
205
 
  {
206
 
    ((Field_blob*) table->getField(*ptr))->free();
207
 
  }
 
1532
    ((Field_blob*) table->field[*ptr])->free();
208
1533
}
209
1534
 
210
1535
 
211
 
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
212
 
{
213
 
  TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
 
1536
        /* error message when opening a form file */
 
1537
 
 
1538
void TableShare::open_table_error(int pass_error, int db_errno, int pass_errarg)
 
1539
{
 
1540
  int err_no;
 
1541
  char buff[FN_REFLEN];
 
1542
  myf errortype= ME_ERROR+ME_WAITTANG;
 
1543
 
 
1544
  switch (pass_error) {
 
1545
  case 7:
 
1546
  case 1:
 
1547
    if (db_errno == ENOENT)
 
1548
      my_error(ER_NO_SUCH_TABLE, MYF(0), db.str, table_name.str);
 
1549
    else
 
1550
    {
 
1551
      sprintf(buff,"%s",normalized_path.str);
 
1552
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
 
1553
               errortype, buff, db_errno);
 
1554
    }
 
1555
    break;
 
1556
  case 2:
 
1557
  {
 
1558
    handler *file= 0;
 
1559
    const char *datext= "";
 
1560
 
 
1561
    if (db_type() != NULL)
 
1562
    {
 
1563
      if ((file= get_new_handler(this, current_session->mem_root,
 
1564
                                 db_type())))
 
1565
      {
 
1566
        if (!(datext= *db_type()->bas_ext()))
 
1567
          datext= "";
 
1568
      }
 
1569
    }
 
1570
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
 
1571
      ER_FILE_USED : ER_CANT_OPEN_FILE;
 
1572
    sprintf(buff,"%s%s", normalized_path.str,datext);
 
1573
    my_error(err_no,errortype, buff, db_errno);
 
1574
    delete file;
 
1575
    break;
 
1576
  }
 
1577
  case 5:
 
1578
  {
 
1579
    const char *csname= get_charset_name((uint32_t) pass_errarg);
 
1580
    char tmp[10];
 
1581
    if (!csname || csname[0] =='?')
 
1582
    {
 
1583
      snprintf(tmp, sizeof(tmp), "#%d", pass_errarg);
 
1584
      csname= tmp;
 
1585
    }
 
1586
    my_printf_error(ER_UNKNOWN_COLLATION,
 
1587
                    _("Unknown collation '%s' in table '%-.64s' definition"),
 
1588
                    MYF(0), csname, table_name.str);
 
1589
    break;
 
1590
  }
 
1591
  case 6:
 
1592
    sprintf(buff,"%s", normalized_path.str);
 
1593
    my_printf_error(ER_NOT_FORM_FILE,
 
1594
                    _("Table '%-.64s' was created with a different version "
 
1595
                    "of Drizzle and cannot be read"),
 
1596
                    MYF(0), buff);
 
1597
    break;
 
1598
  case 8:
 
1599
    break;
 
1600
  default:                              /* Better wrong error than none */
 
1601
  case 4:
 
1602
    sprintf(buff,"%s", normalized_path.str);
 
1603
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
 
1604
    break;
 
1605
  }
 
1606
  return;
 
1607
} /* open_table_error */
 
1608
 
 
1609
 
 
1610
TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
 
1611
{
 
1612
  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
214
1613
  if (!result)
215
1614
    return 0;
216
1615
  result->count= strings.elements;
217
1616
  result->name= "";
218
1617
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
219
1618
  
220
 
  if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
 
1619
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
221
1620
    return 0;
222
1621
    
223
1622
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
247
1646
  return (nr);
248
1647
} /* set_zone */
249
1648
 
 
1649
        /* Adjust number to next larger disk buffer */
 
1650
 
 
1651
ulong next_io_size(register ulong pos)
 
1652
{
 
1653
  register ulong offset;
 
1654
  if ((offset= pos & (IO_SIZE-1)))
 
1655
    return pos-offset+IO_SIZE;
 
1656
  return pos;
 
1657
} /* next_io_size */
 
1658
 
250
1659
 
251
1660
/*
252
1661
  Store an SQL quoted string.
274
1683
        (mblen= my_ismbchar(default_charset_info, pos, end)))
275
1684
    {
276
1685
      res->append(pos, mblen);
277
 
      pos+= mblen - 1;
 
1686
      pos+= mblen;
278
1687
      if (pos >= end)
279
1688
        break;
280
1689
      continue;
310
1719
}
311
1720
 
312
1721
 
 
1722
/*
 
1723
  Set up column usage bitmaps for a temporary table
 
1724
 
 
1725
  IMPLEMENTATION
 
1726
    For temporary tables, we need one bitmap with all columns set and
 
1727
    a tmp_set bitmap to be used by things like filesort.
 
1728
*/
 
1729
 
 
1730
void Table::setup_tmp_table_column_bitmaps(unsigned char *bitmaps)
 
1731
{
 
1732
  uint32_t field_count= s->fields;
 
1733
 
 
1734
  this->def_read_set.init((my_bitmap_map*) bitmaps, field_count);
 
1735
  this->tmp_set.init((my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)), field_count);
 
1736
 
 
1737
  /* write_set and all_set are copies of read_set */
 
1738
  def_write_set= def_read_set;
 
1739
  s->all_set= def_read_set;
 
1740
  this->s->all_set.setAll();
 
1741
  default_column_bitmaps();
 
1742
}
 
1743
 
 
1744
 
 
1745
 
 
1746
void Table::updateCreateInfo(HA_CREATE_INFO *create_info,
 
1747
                             message::Table *table_proto)
 
1748
{
 
1749
  message::Table::TableOptions *table_options= table_proto->mutable_options();
 
1750
  create_info->table_options= s->db_create_options;
 
1751
  table_options->set_block_size(s->block_size);
 
1752
  create_info->row_type= s->row_type;
 
1753
  create_info->default_table_charset= s->table_charset;
 
1754
  create_info->table_charset= 0;
 
1755
  table_options->set_comment(s->getComment());
 
1756
}
 
1757
 
313
1758
int rename_file_ext(const char * from,const char * to,const char * ext)
314
1759
{
315
1760
  string from_s, to_s;
318
1763
  from_s.append(ext);
319
1764
  to_s.append(to);
320
1765
  to_s.append(ext);
321
 
  return (internal::my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
 
1766
  return (my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
 
1767
}
 
1768
 
 
1769
/*
 
1770
  DESCRIPTION
 
1771
    given a buffer with a key value, and a map of keyparts
 
1772
    that are present in this value, returns the length of the value
 
1773
*/
 
1774
uint32_t calculate_key_len(Table *table, uint32_t key,
 
1775
                       const unsigned char *,
 
1776
                       key_part_map keypart_map)
 
1777
{
 
1778
  /* works only with key prefixes */
 
1779
  assert(((keypart_map + 1) & keypart_map) == 0);
 
1780
 
 
1781
  KEY *key_info= table->s->key_info+key;
 
1782
  KEY_PART_INFO *key_part= key_info->key_part;
 
1783
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
 
1784
  uint32_t length= 0;
 
1785
 
 
1786
  while (key_part < end_key_part && keypart_map)
 
1787
  {
 
1788
    length+= key_part->store_length;
 
1789
    keypart_map >>= 1;
 
1790
    key_part++;
 
1791
  }
 
1792
  return length;
322
1793
}
323
1794
 
324
1795
/*
329
1800
    org_name            Name of database and length
330
1801
 
331
1802
  RETURN
332
 
    false error
333
 
    true ok
 
1803
    0   ok
 
1804
    1   error
334
1805
*/
335
1806
 
336
 
bool check_db_name(Session *session, SchemaIdentifier &schema_identifier)
 
1807
bool check_db_name(LEX_STRING *org_name)
337
1808
{
338
 
  if (not plugin::Authorization::isAuthorized(session->getSecurityContext(), schema_identifier))
339
 
  {
340
 
    return false;
341
 
  }
342
 
 
343
 
  return schema_identifier.isValid();
 
1809
  char *name= org_name->str;
 
1810
  uint32_t name_length= org_name->length;
 
1811
 
 
1812
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
 
1813
    return 1;
 
1814
 
 
1815
  if (name != any_db)
 
1816
    my_casedn_str(files_charset_info, name);
 
1817
 
 
1818
  return check_identifier_name(org_name);
344
1819
}
345
1820
 
 
1821
 
346
1822
/*
347
1823
  Allow anything as a table name, as long as it doesn't contain an
348
1824
  ' ' at the end
413
1889
    bitmap_clear_all(&table->def_read_set);
414
1890
    bitmap_clear_all(&table->def_write_set);
415
1891
  */
416
 
  def_read_set.reset();
417
 
  def_write_set.reset();
418
 
  column_bitmaps_set(def_read_set, def_write_set);
 
1892
  def_read_set.clearAll();
 
1893
  def_write_set.clearAll();
 
1894
  column_bitmaps_set(&def_read_set, &def_write_set);
419
1895
}
420
1896
 
421
1897
 
422
1898
/*
423
 
  Tell Cursor we are going to call position() and rnd_pos() later.
 
1899
  Tell handler we are going to call position() and rnd_pos() later.
424
1900
 
425
1901
  NOTES:
426
1902
  This is needed for handlers that uses the primary key to find the
431
1907
void Table::prepare_for_position()
432
1908
{
433
1909
 
434
 
  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
435
 
      getShare()->hasPrimaryKey())
 
1910
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
1911
      s->primary_key < MAX_KEY)
436
1912
  {
437
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
 
1913
    mark_columns_used_by_index_no_reset(s->primary_key);
438
1914
  }
439
1915
  return;
440
1916
}
452
1928
 
453
1929
void Table::mark_columns_used_by_index(uint32_t index)
454
1930
{
455
 
  boost::dynamic_bitset<> *bitmap= &tmp_set;
 
1931
  MyBitmap *bitmap= &tmp_set;
456
1932
 
457
 
  (void) cursor->extra(HA_EXTRA_KEYREAD);
458
 
  bitmap->reset();
459
 
  mark_columns_used_by_index_no_reset(index, *bitmap);
460
 
  column_bitmaps_set(*bitmap, *bitmap);
 
1933
  (void) file->extra(HA_EXTRA_KEYREAD);
 
1934
  bitmap->clearAll();
 
1935
  mark_columns_used_by_index_no_reset(index, bitmap);
 
1936
  column_bitmaps_set(bitmap, bitmap);
461
1937
  return;
462
1938
}
463
1939
 
477
1953
{
478
1954
 
479
1955
  key_read= 0;
480
 
  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
 
1956
  (void) file->extra(HA_EXTRA_NO_KEYREAD);
481
1957
  default_column_bitmaps();
482
1958
  return;
483
1959
}
489
1965
 
490
1966
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
491
1967
{
492
 
    mark_columns_used_by_index_no_reset(index, *read_set);
 
1968
    mark_columns_used_by_index_no_reset(index, read_set);
493
1969
}
494
1970
 
495
 
 
496
1971
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
497
 
                                                boost::dynamic_bitset<>& bitmap)
 
1972
                                                MyBitmap *bitmap)
498
1973
{
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
 
  }
 
1974
  KEY_PART_INFO *key_part= key_info[index].key_part;
 
1975
  KEY_PART_INFO *key_part_end= (key_part +
 
1976
                                key_info[index].key_parts);
 
1977
  for (;key_part != key_part_end; key_part++)
 
1978
    bitmap->setBit(key_part->fieldnr-1);
506
1979
}
507
1980
 
508
1981
 
521
1994
    We must set bit in read set as update_auto_increment() is using the
522
1995
    store() to check overflow of auto_increment values
523
1996
  */
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);
 
1997
  setReadSet(found_next_number_field->field_index);
 
1998
  setWriteSet(found_next_number_field->field_index);
 
1999
  if (s->next_number_keypart)
 
2000
    mark_columns_used_by_index_no_reset(s->next_number_index);
528
2001
}
529
2002
 
530
2003
 
549
2022
void Table::mark_columns_needed_for_delete()
550
2023
{
551
2024
  /*
552
 
    If the Cursor has no cursor capabilites, or we have row-based
 
2025
    If the handler has no cursor capabilites, or we have row-based
553
2026
    replication active for the current statement, we have to read
554
2027
    either the primary key, the hidden primary key or all columns to
555
2028
    be able to do an delete
556
2029
 
557
2030
  */
558
 
  if (not getShare()->hasPrimaryKey())
 
2031
  if (s->primary_key == MAX_KEY)
559
2032
  {
560
2033
    /* fallback to use all columns in the table to identify row */
561
2034
    use_all_columns();
562
2035
    return;
563
2036
  }
564
2037
  else
565
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
 
2038
    mark_columns_used_by_index_no_reset(s->primary_key);
566
2039
 
567
2040
  /* If we the engine wants all predicates we mark all keys */
568
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
2041
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
569
2042
  {
570
2043
    Field **reg_field;
571
2044
    for (reg_field= field ; *reg_field ; reg_field++)
572
2045
    {
573
2046
      if ((*reg_field)->flags & PART_KEY_FLAG)
574
 
        setReadSet((*reg_field)->position());
 
2047
        setReadSet((*reg_field)->field_index);
575
2048
    }
576
2049
  }
577
2050
}
589
2062
    if neeed, either the primary key column or all columns to be read.
590
2063
    (see mark_columns_needed_for_delete() for details)
591
2064
 
592
 
    If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
 
2065
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
593
2066
    mark all USED key columns as 'to-be-read'. This allows the engine to
594
2067
    loop over the given record to find all changed keys and doesn't have to
595
2068
    retrieve the row again.
598
2071
void Table::mark_columns_needed_for_update()
599
2072
{
600
2073
  /*
601
 
    If the Cursor has no cursor capabilites, or we have row-based
 
2074
    If the handler has no cursor capabilites, or we have row-based
602
2075
    logging active for the current statement, we have to read either
603
2076
    the primary key, the hidden primary key or all columns to be
604
2077
    able to do an update
605
2078
  */
606
 
  if (not getShare()->hasPrimaryKey())
 
2079
  if (s->primary_key == MAX_KEY)
607
2080
  {
608
2081
    /* fallback to use all columns in the table to identify row */
609
2082
    use_all_columns();
610
2083
    return;
611
2084
  }
612
2085
  else
613
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
 
2086
    mark_columns_used_by_index_no_reset(s->primary_key);
614
2087
 
615
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
2088
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
616
2089
  {
617
2090
    /* Mark all used key columns for read */
618
2091
    Field **reg_field;
620
2093
    {
621
2094
      /* Merge keys is all keys that had a column refered to in the query */
622
2095
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
623
 
        setReadSet((*reg_field)->position());
 
2096
        setReadSet((*reg_field)->field_index);
624
2097
    }
625
2098
  }
626
2099
 
628
2101
 
629
2102
 
630
2103
/*
631
 
  Mark columns the Cursor needs for doing an insert
 
2104
  Mark columns the handler needs for doing an insert
632
2105
 
633
2106
  For now, this is used to mark fields used by the trigger
634
2107
  as changed.
652
2125
  {
653
2126
    Field_blob* const blob= (Field_blob*) field[*ptr];
654
2127
    length+= blob->get_length((const unsigned char*)
655
 
                              (data + blob->offset(getInsertRecord()))) +
 
2128
                              (data + blob->offset(record[0]))) +
656
2129
      HA_KEY_BLOB_LENGTH;
657
2130
  }
658
2131
  return length;
659
2132
}
660
2133
 
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
2134
/****************************************************************************
674
2135
 Functions for creating temporary tables.
675
2136
****************************************************************************/
 
2137
 
 
2138
 
 
2139
/* Prototypes */
 
2140
void free_tmp_table(Session *session, Table *entry);
 
2141
 
676
2142
/**
677
2143
  Create field for temporary table from given field.
678
2144
 
679
 
  @param session               Thread Cursor
 
2145
  @param session               Thread handler
680
2146
  @param org_field    field from which new field will be created
681
2147
  @param name         New field name
682
2148
  @param table         Temporary table
707
2173
  */
708
2174
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
709
2175
      (org_field->flags & BLOB_FLAG))
710
 
  {
711
 
    table->setVariableWidth();
712
2176
    new_field= new Field_varstring(convert_blob_length,
713
2177
                                   org_field->maybe_null(),
714
 
                                   org_field->field_name,
 
2178
                                   org_field->field_name, table->s,
715
2179
                                   org_field->charset());
716
 
  }
717
2180
  else
718
 
  {
719
2181
    new_field= org_field->new_field(session->mem_root, table,
720
 
                                    table == org_field->getTable());
721
 
  }
 
2182
                                    table == org_field->table);
722
2183
  if (new_field)
723
2184
  {
724
2185
    new_field->init(table);
731
2192
    if (org_field->maybe_null() || (item && item->maybe_null))
732
2193
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
733
2194
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
734
 
      table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
 
2195
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
735
2196
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
736
2197
      ((Field_double *) new_field)->not_fixed= true;
737
2198
  }
740
2201
 
741
2202
 
742
2203
/**
 
2204
  Create field for information schema table.
 
2205
 
 
2206
  @param session                Thread handler
 
2207
  @param table          Temporary table
 
2208
  @param item           Item to create a field for
 
2209
 
 
2210
  @retval
 
2211
    0                   on error
 
2212
  @retval
 
2213
    new_created field
 
2214
*/
 
2215
 
 
2216
static Field *create_tmp_field_for_schema(Item *item, Table *table)
 
2217
{
 
2218
  if (item->field_type() == DRIZZLE_TYPE_VARCHAR)
 
2219
  {
 
2220
    Field *field;
 
2221
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
 
2222
      field= new Field_blob(item->max_length, item->maybe_null,
 
2223
                            item->name, item->collation.collation);
 
2224
    else
 
2225
      field= new Field_varstring(item->max_length, item->maybe_null,
 
2226
                                 item->name,
 
2227
                                 table->s, item->collation.collation);
 
2228
    if (field)
 
2229
      field->init(table);
 
2230
    return field;
 
2231
  }
 
2232
  return item->tmp_table_field_from_field_type(table, 0);
 
2233
}
 
2234
 
 
2235
 
 
2236
/**
743
2237
  Create a temp table according to a field list.
744
2238
 
745
2239
  Given field pointers are changed to point at tmp_table for
771
2265
 
772
2266
Table *
773
2267
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
774
 
                 Order *group, bool distinct, bool save_sum_fields,
 
2268
                 order_st *group, bool distinct, bool save_sum_fields,
775
2269
                 uint64_t select_options, ha_rows rows_limit,
776
2270
                 const char *table_alias)
777
2271
{
778
 
  memory::Root *mem_root_save;
 
2272
  MEM_ROOT *mem_root_save, own_root;
 
2273
  Table *table;
 
2274
  TableShare *share;
779
2275
  uint  i,field_count,null_count,null_pack_length;
780
2276
  uint32_t  copy_func_count= param->func_count;
781
2277
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
782
2278
  uint32_t  blob_count,group_null_items, string_count;
783
2279
  uint32_t fieldnr= 0;
784
2280
  ulong reclength, string_total_length;
785
 
  bool  using_unique_constraint= false;
786
 
  bool  use_packed_rows= true;
 
2281
  bool  using_unique_constraint= 0;
 
2282
  bool  use_packed_rows= 0;
787
2283
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
788
 
  unsigned char *pos, *group_buff;
 
2284
  char  *tmpname,path[FN_REFLEN];
 
2285
  unsigned char *pos, *group_buff, *bitmaps;
789
2286
  unsigned char *null_flags;
790
2287
  Field **reg_field, **from_field, **default_field;
 
2288
  uint32_t *blob_field;
791
2289
  CopyField *copy= 0;
792
 
  KeyInfo *keyinfo;
793
 
  KeyPartInfo *key_part_info;
 
2290
  KEY *keyinfo;
 
2291
  KEY_PART_INFO *key_part_info;
794
2292
  Item **copy_func;
795
2293
  MI_COLUMNDEF *recinfo;
796
2294
  uint32_t total_uneven_bit_length= 0;
797
2295
  bool force_copy_fields= param->force_copy_fields;
798
2296
  uint64_t max_rows= 0;
799
2297
 
800
 
  session->status_var.created_tmp_tables++;
 
2298
  status_var_increment(session->status_var.created_tmp_tables);
 
2299
 
 
2300
  /* if we run out of slots or we are not using tempool */
 
2301
  sprintf(path,"%s%lx_%"PRIx64"_%x", TMP_FILE_PREFIX, (unsigned long)current_pid,
 
2302
          session->thread_id, session->tmp_table++);
 
2303
 
 
2304
  /*
 
2305
    No need to change table name to lower case as we are only creating
 
2306
    MyISAM or HEAP tables here
 
2307
  */
 
2308
  fn_format(path, path, drizzle_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
2309
 
801
2310
 
802
2311
  if (group)
803
2312
  {
804
 
    if (! param->quick_group)
805
 
    {
 
2313
    if (!param->quick_group)
806
2314
      group= 0;                                 // Can't use group key
807
 
    }
808
 
    else for (Order *tmp=group ; tmp ; tmp=tmp->next)
 
2315
    else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
809
2316
    {
810
2317
      /*
811
2318
        marker == 4 means two things:
815
2322
      */
816
2323
      (*tmp->item)->marker= 4;
817
2324
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
818
 
        using_unique_constraint= true;
 
2325
        using_unique_constraint=1;
819
2326
    }
820
2327
    if (param->group_length >= MAX_BLOB_WIDTH)
821
 
      using_unique_constraint= true;
 
2328
      using_unique_constraint=1;
822
2329
    if (group)
823
2330
      distinct= 0;                              // Can't use distinct
824
2331
  }
834
2341
    these items are stored in the temporary table.
835
2342
  */
836
2343
  if (param->precomputed_group_by)
837
 
  {
838
2344
    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))
 
2345
 
 
2346
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
2347
 
 
2348
  if (!multi_alloc_root(&own_root,
 
2349
                        &table, sizeof(*table),
 
2350
                        &share, sizeof(*share),
 
2351
                        &reg_field, sizeof(Field*) * (field_count+1),
 
2352
                        &default_field, sizeof(Field*) * (field_count),
 
2353
                        &blob_field, sizeof(uint32_t)*(field_count+1),
 
2354
                        &from_field, sizeof(Field*)*field_count,
 
2355
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
 
2356
                        &param->keyinfo, sizeof(*param->keyinfo),
 
2357
                        &key_part_info,
 
2358
                        sizeof(*key_part_info)*(param->group_parts+1),
 
2359
                        &param->start_recinfo,
 
2360
                        sizeof(*param->recinfo)*(field_count*2+4),
 
2361
                        &tmpname, (uint32_t) strlen(path)+1,
 
2362
                        &group_buff, (group && ! using_unique_constraint ?
 
2363
                                      param->group_length : 0),
 
2364
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
2365
                        NULL))
854
2366
  {
855
2367
    return NULL;
856
2368
  }
857
2369
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
858
2370
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
859
2371
  {
 
2372
    free_root(&own_root, MYF(0));
860
2373
    return NULL;
861
2374
  }
862
2375
  param->items_to_copy= copy_func;
 
2376
  strcpy(tmpname,path);
863
2377
  /* make table according to fields */
864
2378
 
 
2379
  memset(table, 0, sizeof(*table));
 
2380
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
865
2381
  memset(default_field, 0, sizeof(Field*) * (field_count));
866
2382
  memset(from_field, 0, sizeof(Field*)*field_count);
867
2383
 
 
2384
  table->mem_root= own_root;
868
2385
  mem_root_save= session->mem_root;
869
 
  session->mem_root= table->getMemRoot();
 
2386
  session->mem_root= &table->mem_root;
870
2387
 
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);
 
2388
  table->field=reg_field;
 
2389
  table->alias= table_alias;
875
2390
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
876
2391
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
877
2392
  table->map=1;
878
2393
  table->copy_blobs= 1;
879
 
  assert(session);
880
2394
  table->in_use= session;
881
2395
  table->quick_keys.reset();
882
2396
  table->covering_keys.reset();
883
2397
  table->keys_in_use_for_query.reset();
884
2398
 
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();
 
2399
  table->setShare(share);
 
2400
  share->init(tmpname, tmpname);
 
2401
  share->blob_field= blob_field;
 
2402
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
2403
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
2404
  share->table_charset= param->table_charset;
 
2405
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
2406
  share->keys_for_keyread.reset();
 
2407
  share->keys_in_use.reset();
892
2408
 
893
2409
  /* Calculate which type of fields we will store in the temporary table */
894
2410
 
936
2452
            create_tmp_field(session, table, arg, arg->type(), &copy_func,
937
2453
                             tmp_from_field, &default_field[fieldnr],
938
2454
                             group != 0,not_all_columns,
939
 
                             false,
 
2455
                             distinct, 0,
940
2456
                             param->convert_blob_length);
941
2457
          if (!new_field)
942
2458
            goto err;                                   // Should be OOM
955
2471
          }
956
2472
          session->mem_root= mem_root_save;
957
2473
          session->change_item_tree(argp, new Item_field(new_field));
958
 
          session->mem_root= table->getMemRoot();
 
2474
          session->mem_root= &table->mem_root;
959
2475
          if (!(new_field->flags & NOT_NULL_FLAG))
960
2476
          {
961
2477
            null_count++;
965
2481
            */
966
2482
            (*argp)->maybe_null=1;
967
2483
          }
968
 
          new_field->setPosition(fieldnr++);
 
2484
          new_field->field_index= fieldnr++;
969
2485
        }
970
2486
      }
971
2487
    }
981
2497
        We here distinguish between UNION and multi-table-updates by the fact
982
2498
        that in the later case group is set to the row pointer.
983
2499
      */
984
 
      Field *new_field=
 
2500
      Field *new_field= (param->schema_table) ?
 
2501
        create_tmp_field_for_schema(item, table) :
985
2502
        create_tmp_field(session, table, item, type, &copy_func,
986
2503
                         tmp_from_field, &default_field[fieldnr],
987
2504
                         group != 0,
988
2505
                         !force_copy_fields &&
989
2506
                           (not_all_columns || group != 0),
 
2507
                         /*
 
2508
                           If item->marker == 4 then we force create_tmp_field
 
2509
                           to create a 64-bit longs for BIT fields because HEAP
 
2510
                           tables can't index BIT fields directly. We do the same
 
2511
                           for distinct, as we want the distinct index to be
 
2512
                           usable in this case too.
 
2513
                         */
 
2514
                         item->marker == 4 || param->bit_fields_as_long,
990
2515
                         force_copy_fields,
991
2516
                         param->convert_blob_length);
992
2517
 
1012
2537
        group_null_items++;
1013
2538
        new_field->flags|= GROUP_FLAG;
1014
2539
      }
1015
 
      new_field->setPosition(fieldnr++);
 
2540
      new_field->field_index= fieldnr++;
1016
2541
      *(reg_field++)= new_field;
1017
2542
    }
1018
2543
    if (!--hidden_field_count)
1030
2555
      null_count= 0;
1031
2556
    }
1032
2557
  }
1033
 
  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
1034
 
  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
 
2558
  assert(fieldnr == (uint32_t) (reg_field - table->field));
 
2559
  assert(field_count >= (uint32_t) (reg_field - table->field));
1035
2560
  field_count= fieldnr;
1036
2561
  *reg_field= 0;
1037
2562
  *blob_field= 0;                               // End marker
1038
 
  table->getMutableShare()->fields= field_count;
 
2563
  share->fields= field_count;
1039
2564
 
1040
2565
  /* If result table is small; use a heap */
1041
2566
  /* future: storage engine selection can be made dynamic? */
1042
 
  if (blob_count || using_unique_constraint || 
1043
 
      (session->lex->select_lex.options & SELECT_BIG_RESULT) ||
1044
 
      (session->lex->current_select->olap == ROLLUP_TYPE) ||
1045
 
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
 
2567
  if (blob_count || using_unique_constraint ||
 
2568
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
2569
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
1046
2570
  {
1047
 
    table->getMutableShare()->storage_engine= myisam_engine;
1048
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
 
2571
    share->storage_engine= myisam_engine;
 
2572
    table->file= get_new_handler(share, &table->mem_root,
 
2573
                                 share->db_type());
1049
2574
    if (group &&
1050
 
        (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
1051
 
         param->group_length > table->cursor->getEngine()->max_key_length()))
1052
 
    {
1053
 
      using_unique_constraint= true;
1054
 
    }
 
2575
        (param->group_parts > table->file->max_key_parts() ||
 
2576
         param->group_length > table->file->max_key_length()))
 
2577
      using_unique_constraint=1;
1055
2578
  }
1056
2579
  else
1057
2580
  {
1058
 
    table->getMutableShare()->storage_engine= heap_engine;
1059
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
 
2581
    share->storage_engine= heap_engine;
 
2582
    table->file= get_new_handler(share, &table->mem_root,
 
2583
                                 share->db_type());
1060
2584
  }
1061
 
  if (! table->cursor)
 
2585
  if (!table->file)
1062
2586
    goto err;
1063
2587
 
1064
2588
 
1065
 
  if (! using_unique_constraint)
 
2589
  if (!using_unique_constraint)
1066
2590
    reclength+= group_null_items;       // null flag is stored separately
1067
2591
 
1068
 
  table->getMutableShare()->blob_fields= blob_count;
 
2592
  share->blob_fields= blob_count;
1069
2593
  if (blob_count == 0)
1070
2594
  {
1071
2595
    /* We need to ensure that first byte is not 0 for the delete link */
1084
2608
  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
2609
    use_packed_rows= 1;
1086
2610
 
1087
 
  table->getMutableShare()->setRecordLength(reclength);
 
2611
  share->reclength= reclength;
1088
2612
  {
1089
2613
    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
 
    {
 
2614
    share->rec_buff_length= alloc_length;
 
2615
    if (!(table->record[0]= (unsigned char*)
 
2616
                            alloc_root(&table->mem_root, alloc_length*3)))
1093
2617
      goto err;
1094
 
    }
1095
 
    table->record[1]= table->getInsertRecord()+alloc_length;
1096
 
    table->getMutableShare()->resizeDefaultValues(alloc_length);
 
2618
    table->record[1]= table->record[0]+alloc_length;
 
2619
    share->default_values= table->record[1]+alloc_length;
1097
2620
  }
1098
2621
  copy_func[0]= 0;                              // End marker
1099
2622
  param->func_count= copy_func - param->items_to_copy;
1100
2623
 
1101
 
  table->setup_tmp_table_column_bitmaps();
 
2624
  table->setup_tmp_table_column_bitmaps(bitmaps);
1102
2625
 
1103
2626
  recinfo=param->start_recinfo;
1104
 
  null_flags=(unsigned char*) table->getInsertRecord();
1105
 
  pos=table->getInsertRecord()+ null_pack_length;
 
2627
  null_flags=(unsigned char*) table->record[0];
 
2628
  pos=table->record[0]+ null_pack_length;
1106
2629
  if (null_pack_length)
1107
2630
  {
1108
2631
    memset(recinfo, 0, sizeof(*recinfo));
1111
2634
    recinfo++;
1112
2635
    memset(null_flags, 255, null_pack_length);  // Set null fields
1113
2636
 
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;
 
2637
    table->null_flags= (unsigned char*) table->record[0];
 
2638
    share->null_fields= null_count+ hidden_null_count;
 
2639
    share->null_bytes= null_pack_length;
1117
2640
  }
1118
2641
  null_count= (blob_count == 0) ? 1 : 0;
1119
2642
  hidden_field_count=param->hidden_field_count;
1120
 
  for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
 
2643
  for (i= 0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
1121
2644
  {
1122
2645
    Field *field= *reg_field;
1123
2646
    uint32_t length;
1161
2684
         inherit the default value that is defined for the field referred
1162
2685
         by the Item_field object from which 'field' has been created.
1163
2686
      */
1164
 
      ptrdiff_t diff;
 
2687
      my_ptrdiff_t diff;
1165
2688
      Field *orig_field= default_field[i];
1166
2689
      /* Get the value from default_values */
1167
 
      diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
 
2690
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
 
2691
                            orig_field->table->record[0]);
1168
2692
      orig_field->move_field_offset(diff);      // Points now at default_values
1169
2693
      if (orig_field->is_real_null())
1170
2694
        field->set_null();
1173
2697
        field->set_notnull();
1174
2698
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
1175
2699
      }
1176
 
      orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
 
2700
      orig_field->move_field_offset(-diff);     // Back to record[0]
1177
2701
    }
1178
2702
 
1179
2703
    if (from_field[i])
1192
2716
      recinfo->type=FIELD_NORMAL;
1193
2717
    if (!--hidden_field_count)
1194
2718
      null_count=(null_count+7) & ~7;           // move to next byte
 
2719
 
 
2720
    // fix table name in field entry
 
2721
    field->table_name= &table->alias;
1195
2722
  }
1196
2723
 
1197
2724
  param->copy_field_end=copy;
1199
2726
  table->storeRecordAsDefault();        // Make empty default record
1200
2727
 
1201
2728
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)              // No limit
1202
 
  {
1203
2729
    max_rows= ~(uint64_t) 0;
1204
 
  }
1205
2730
  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
 
  }
 
2731
    max_rows= (uint64_t) (((share->db_type() == heap_engine) ?
 
2732
                          min(session->variables.tmp_table_size,
 
2733
                              session->variables.max_heap_table_size) :
 
2734
                          session->variables.tmp_table_size) /
 
2735
                         share->reclength);
1213
2736
 
1214
2737
  set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
1215
2738
  /*
1218
2741
  */
1219
2742
  set_if_smaller(max_rows, rows_limit);
1220
2743
 
1221
 
  table->getMutableShare()->setMaxRows(max_rows);
 
2744
  share->setMaxRows(max_rows);
1222
2745
 
1223
2746
  param->end_write_records= rows_limit;
1224
2747
 
1228
2751
  {
1229
2752
    table->group=group;                         /* Table is grouped by key */
1230
2753
    param->group_buff=group_buff;
1231
 
    table->getMutableShare()->keys=1;
1232
 
    table->getMutableShare()->uniques= test(using_unique_constraint);
 
2754
    share->keys=1;
 
2755
    share->uniques= test(using_unique_constraint);
1233
2756
    table->key_info=keyinfo;
1234
2757
    keyinfo->key_part=key_part_info;
1235
2758
    keyinfo->flags=HA_NOSAME;
1238
2761
    keyinfo->rec_per_key= 0;
1239
2762
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1240
2763
    keyinfo->name= (char*) "group_key";
1241
 
    Order *cur_group= group;
 
2764
    order_st *cur_group= group;
1242
2765
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1243
2766
    {
1244
2767
      Field *field=(*cur_group->item)->get_tmp_table_field();
1245
2768
      bool maybe_null=(*cur_group->item)->maybe_null;
1246
2769
      key_part_info->null_bit= 0;
1247
2770
      key_part_info->field=  field;
1248
 
      key_part_info->offset= field->offset(table->getInsertRecord());
 
2771
      key_part_info->offset= field->offset(table->record[0]);
1249
2772
      key_part_info->length= (uint16_t) field->key_length();
1250
2773
      key_part_info->type=   (uint8_t) field->key_type();
1251
 
      key_part_info->key_type= 
 
2774
      key_part_info->key_type =
1252
2775
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1253
2776
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1254
2777
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1255
 
        0 : 1;
 
2778
        0 : FIELDFLAG_BINARY;
1256
2779
      if (!using_unique_constraint)
1257
2780
      {
1258
2781
        cur_group->buff=(char*) group_buff;
1273
2796
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
1274
2797
          key_part_info->null_bit=field->null_bit;
1275
2798
          key_part_info->null_offset= (uint32_t) (field->null_ptr -
1276
 
                                              (unsigned char*) table->getInsertRecord());
 
2799
                                              (unsigned char*) table->record[0]);
1277
2800
          cur_group->buff++;                        // Pointer to field data
1278
2801
          group_buff++;                         // Skipp null flag
1279
2802
        }
1300
2823
        indexes on blobs with arbitrary length. Such indexes cannot be
1301
2824
        used for lookups.
1302
2825
      */
1303
 
      table->getMutableShare()->uniques= 1;
 
2826
      share->uniques= 1;
1304
2827
    }
1305
2828
    null_pack_length-=hidden_null_pack_length;
1306
2829
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
1307
 
                         (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
 
2830
                         (share->uniques ? test(null_pack_length) : 0));
1308
2831
    table->distinct= 1;
1309
 
    table->getMutableShare()->keys= 1;
1310
 
    if (!(key_part_info= (KeyPartInfo*)
1311
 
         table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
 
2832
    share->keys= 1;
 
2833
    if (!(key_part_info= (KEY_PART_INFO*)
 
2834
          alloc_root(&table->mem_root,
 
2835
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
1312
2836
      goto err;
1313
 
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
 
2837
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
1314
2838
    table->key_info=keyinfo;
1315
2839
    keyinfo->key_part=key_part_info;
1316
2840
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
1324
2848
      blobs can distinguish NULL from 0. This extra field is not needed
1325
2849
      when we do not use UNIQUE indexes for blobs.
1326
2850
    */
1327
 
    if (null_pack_length && table->getMutableShare()->uniques)
 
2851
    if (null_pack_length && share->uniques)
1328
2852
    {
1329
2853
      key_part_info->null_bit= 0;
1330
2854
      key_part_info->offset=hidden_null_pack_length;
1331
2855
      key_part_info->length=null_pack_length;
1332
 
      table->setVariableWidth();
1333
 
      key_part_info->field= new Field_varstring(table->getInsertRecord(),
 
2856
      key_part_info->field= new Field_varstring(table->record[0],
1334
2857
                                                (uint32_t) key_part_info->length,
1335
2858
                                                0,
1336
2859
                                                (unsigned char*) 0,
1337
2860
                                                (uint32_t) 0,
 
2861
                                                Field::NONE,
1338
2862
                                                NULL,
 
2863
                                                table->s,
1339
2864
                                                &my_charset_bin);
1340
2865
      if (!key_part_info->field)
1341
2866
        goto err;
1342
2867
      key_part_info->field->init(table);
1343
 
      key_part_info->key_type= 1; /* binary comparison */
 
2868
      key_part_info->key_type=FIELDFLAG_BINARY;
1344
2869
      key_part_info->type=    HA_KEYTYPE_BINARY;
1345
2870
      key_part_info++;
1346
2871
    }
1347
2872
    /* Create a distinct key over the columns we are going to return */
1348
 
    for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
 
2873
    for (i=param->hidden_field_count, reg_field=table->field + i ;
1349
2874
         i < field_count;
1350
2875
         i++, reg_field++, key_part_info++)
1351
2876
    {
1352
2877
      key_part_info->null_bit= 0;
1353
2878
      key_part_info->field=    *reg_field;
1354
 
      key_part_info->offset=   (*reg_field)->offset(table->getInsertRecord());
 
2879
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
1355
2880
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
1356
 
      /* @todo The below method of computing the key format length of the
1357
 
        key part is a copy/paste from optimizer/range.cc, and table.cc.
 
2881
      /* TODO:
 
2882
        The below method of computing the key format length of the
 
2883
        key part is a copy/paste from opt_range.cc, and table.cc.
1358
2884
        This should be factored out, e.g. as a method of Field.
1359
2885
        In addition it is not clear if any of the Field::*_length
1360
2886
        methods is supposed to compute the same length. If so, it
1373
2899
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1374
2900
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1375
2901
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1376
 
        0 : 1;
 
2902
        0 : FIELDFLAG_BINARY;
1377
2903
    }
1378
2904
  }
1379
2905
 
1380
2906
  if (session->is_fatal_error)                          // If end of memory
1381
2907
    goto err;
1382
 
  table->getMutableShare()->db_record_offset= 1;
1383
 
  if (table->getShare()->db_type() == myisam_engine)
 
2908
  share->db_record_offset= 1;
 
2909
  if (share->db_type() == myisam_engine)
1384
2910
  {
1385
2911
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1386
2912
                                       &param->recinfo, select_options))
1387
2913
      goto err;
1388
2914
  }
1389
 
  assert(table->in_use);
1390
2915
  if (table->open_tmp_table())
1391
2916
    goto err;
1392
2917
 
1396
2921
 
1397
2922
err:
1398
2923
  session->mem_root= mem_root_save;
1399
 
  table= NULL;
1400
 
 
 
2924
  table->free_tmp_table(session);
1401
2925
  return NULL;
1402
2926
}
1403
2927
 
1404
2928
/****************************************************************************/
1405
2929
 
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;
 
2930
/**
 
2931
  Create a reduced Table object with properly set up Field list from a
 
2932
  list of field definitions.
 
2933
 
 
2934
    The created table doesn't have a table handler associated with
 
2935
    it, has no keys, no group/distinct, no copy_funcs array.
 
2936
    The sole purpose of this Table object is to use the power of Field
 
2937
    class to read/write data to/from table->record[0]. Then one can store
 
2938
    the record in any container (RB tree, hash, etc).
 
2939
    The table is created in Session mem_root, so are the table's fields.
 
2940
    Consequently, if you don't BLOB fields, you don't need to free it.
 
2941
 
 
2942
  @param session         connection handle
 
2943
  @param field_list  list of column definitions
 
2944
 
 
2945
  @return
 
2946
    0 if out of memory, Table object in case of success
 
2947
*/
 
2948
 
 
2949
Table *create_virtual_tmp_table(Session *session, List<CreateField> &field_list)
 
2950
{
 
2951
  uint32_t field_count= field_list.elements;
 
2952
  uint32_t blob_count= 0;
 
2953
  Field **field;
 
2954
  CreateField *cdef;                           /* column definition */
 
2955
  uint32_t record_length= 0;
 
2956
  uint32_t null_count= 0;                 /* number of columns which may be null */
 
2957
  uint32_t null_pack_length;              /* NULL representation array length */
 
2958
  uint32_t *blob_field;
 
2959
  unsigned char *bitmaps;
 
2960
  Table *table;
 
2961
  TableShare *share;
 
2962
 
 
2963
  if (!multi_alloc_root(session->mem_root,
 
2964
                        &table, sizeof(*table),
 
2965
                        &share, sizeof(*share),
 
2966
                        &field, (field_count + 1) * sizeof(Field*),
 
2967
                        &blob_field, (field_count+1) *sizeof(uint32_t),
 
2968
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
2969
                        NULL))
 
2970
    return NULL;
 
2971
 
 
2972
  memset(table, 0, sizeof(*table));
 
2973
  memset(share, 0, sizeof(*share));
 
2974
  table->field= field;
 
2975
  table->s= share;
 
2976
  share->blob_field= blob_field;
 
2977
  share->fields= field_count;
 
2978
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
2979
  table->setup_tmp_table_column_bitmaps(bitmaps);
 
2980
 
 
2981
  /* Create all fields and calculate the total length of record */
 
2982
  List_iterator_fast<CreateField> it(field_list);
 
2983
  while ((cdef= it++))
 
2984
  {
 
2985
    *field= make_field(share, NULL, 0, cdef->length,
 
2986
                       (unsigned char*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
 
2987
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
 
2988
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
 
2989
                       cdef->unireg_check,
 
2990
                       cdef->interval, cdef->field_name);
 
2991
    if (!*field)
 
2992
      goto error;
 
2993
    (*field)->init(table);
 
2994
    record_length+= (*field)->pack_length();
 
2995
    if (! ((*field)->flags & NOT_NULL_FLAG))
 
2996
      null_count++;
 
2997
 
 
2998
    if ((*field)->flags & BLOB_FLAG)
 
2999
      share->blob_field[blob_count++]= (uint32_t) (field - table->field);
 
3000
 
 
3001
    field++;
 
3002
  }
 
3003
  *field= NULL;                             /* mark the end of the list */
 
3004
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
 
3005
  share->blob_fields= blob_count;
 
3006
 
 
3007
  null_pack_length= (null_count + 7)/8;
 
3008
  share->reclength= record_length + null_pack_length;
 
3009
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
3010
  table->record[0]= (unsigned char*) session->alloc(share->rec_buff_length);
 
3011
  if (!table->record[0])
 
3012
    goto error;
 
3013
 
 
3014
  if (null_pack_length)
 
3015
  {
 
3016
    table->null_flags= (unsigned char*) table->record[0];
 
3017
    share->null_fields= null_count;
 
3018
    share->null_bytes= null_pack_length;
 
3019
  }
 
3020
 
 
3021
  table->in_use= session;           /* field->reset() may access table->in_use */
 
3022
  {
 
3023
    /* Set up field pointers */
 
3024
    unsigned char *null_pos= table->record[0];
 
3025
    unsigned char *field_pos= null_pos + share->null_bytes;
 
3026
    uint32_t null_bit= 1;
 
3027
 
 
3028
    for (field= table->field; *field; ++field)
 
3029
    {
 
3030
      Field *cur_field= *field;
 
3031
      if ((cur_field->flags & NOT_NULL_FLAG))
 
3032
        cur_field->move_field(field_pos);
 
3033
      else
 
3034
      {
 
3035
        cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
 
3036
        null_bit<<= 1;
 
3037
        if (null_bit == (1 << 8))
 
3038
        {
 
3039
          ++null_pos;
 
3040
          null_bit= 1;
 
3041
        }
 
3042
      }
 
3043
      cur_field->reset();
 
3044
 
 
3045
      field_pos+= cur_field->pack_length();
 
3046
    }
 
3047
  }
 
3048
  return table;
 
3049
error:
 
3050
  for (field= table->field; *field; ++field)
 
3051
    delete *field;                         /* just invokes field destructor */
 
3052
  return 0;
 
3053
}
 
3054
 
 
3055
bool Table::open_tmp_table()
 
3056
{
 
3057
  int error;
 
3058
  if ((error=file->ha_open(this, s->table_name.str,O_RDWR,
 
3059
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
 
3060
  {
 
3061
    file->print_error(error,MYF(0));
 
3062
    db_stat= 0;
 
3063
    return true;
 
3064
  }
 
3065
  (void) file->extra(HA_EXTRA_QUICK);           /* Faster */
 
3066
  return false;
 
3067
}
 
3068
 
 
3069
 
 
3070
/*
 
3071
  Create MyISAM temporary table
 
3072
 
 
3073
  SYNOPSIS
 
3074
    create_myisam_tmp_table()
 
3075
      keyinfo         Description of the index (there is always one index)
 
3076
      start_recinfo   MyISAM's column descriptions
 
3077
      recinfo INOUT   End of MyISAM's column descriptions
 
3078
      options         Option bits
 
3079
 
 
3080
  DESCRIPTION
 
3081
    Create a MyISAM temporary table according to passed description. The is
 
3082
    assumed to have one unique index or constraint.
 
3083
 
 
3084
    The passed array or MI_COLUMNDEF structures must have this form:
 
3085
 
 
3086
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
 
3087
         when there are many nullable columns)
 
3088
      2. Table columns
 
3089
      3. One free MI_COLUMNDEF element (*recinfo points here)
 
3090
 
 
3091
    This function may use the free element to create hash column for unique
 
3092
    constraint.
 
3093
 
 
3094
   RETURN
 
3095
     false - OK
 
3096
     true  - Error
 
3097
*/
 
3098
 
 
3099
bool Table::create_myisam_tmp_table(KEY *keyinfo,
 
3100
                                    MI_COLUMNDEF *start_recinfo,
 
3101
                                    MI_COLUMNDEF **recinfo,
 
3102
                                    uint64_t options)
 
3103
{
 
3104
  int error;
 
3105
  MI_KEYDEF keydef;
 
3106
  MI_UNIQUEDEF uniquedef;
 
3107
  TableShare *share= s;
 
3108
 
 
3109
  if (share->keys)
 
3110
  {                                             // Get keys for ni_create
 
3111
    bool using_unique_constraint= 0;
 
3112
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
 
3113
                                            sizeof(*seg) * keyinfo->key_parts);
 
3114
    if (!seg)
 
3115
      goto err;
 
3116
 
 
3117
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
 
3118
    if (keyinfo->key_length >= file->max_key_length() ||
 
3119
        keyinfo->key_parts > file->max_key_parts() ||
 
3120
        share->uniques)
 
3121
    {
 
3122
      /* Can't create a key; Make a unique constraint instead of a key */
 
3123
      share->keys=    0;
 
3124
      share->uniques= 1;
 
3125
      using_unique_constraint=1;
 
3126
      memset(&uniquedef, 0, sizeof(uniquedef));
 
3127
      uniquedef.keysegs=keyinfo->key_parts;
 
3128
      uniquedef.seg=seg;
 
3129
      uniquedef.null_are_equal=1;
 
3130
 
 
3131
      /* Create extra column for hash value */
 
3132
      memset(*recinfo, 0, sizeof(**recinfo));
 
3133
      (*recinfo)->type= FIELD_CHECK;
 
3134
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
 
3135
      (*recinfo)++;
 
3136
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
 
3137
    }
 
3138
    else
 
3139
    {
 
3140
      /* Create an unique key */
 
3141
      memset(&keydef, 0, sizeof(keydef));
 
3142
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
 
3143
      keydef.keysegs=  keyinfo->key_parts;
 
3144
      keydef.seg= seg;
 
3145
    }
 
3146
    for (uint32_t i= 0; i < keyinfo->key_parts ; i++,seg++)
 
3147
    {
 
3148
      Field *key_field=keyinfo->key_part[i].field;
 
3149
      seg->flag=     0;
 
3150
      seg->language= key_field->charset()->number;
 
3151
      seg->length=   keyinfo->key_part[i].length;
 
3152
      seg->start=    keyinfo->key_part[i].offset;
 
3153
      if (key_field->flags & BLOB_FLAG)
 
3154
      {
 
3155
        seg->type=
 
3156
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
 
3157
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
 
3158
        seg->bit_start= (uint8_t)(key_field->pack_length()
 
3159
                                  - share->blob_ptr_size);
 
3160
        seg->flag= HA_BLOB_PART;
 
3161
        seg->length= 0;                 // Whole blob in unique constraint
 
3162
      }
 
3163
      else
 
3164
      {
 
3165
        seg->type= keyinfo->key_part[i].type;
 
3166
      }
 
3167
      if (!(key_field->flags & NOT_NULL_FLAG))
 
3168
      {
 
3169
        seg->null_bit= key_field->null_bit;
 
3170
        seg->null_pos= (uint32_t) (key_field->null_ptr - (unsigned char*) record[0]);
 
3171
        /*
 
3172
          We are using a GROUP BY on something that contains NULL
 
3173
          In this case we have to tell MyISAM that two NULL should
 
3174
          on INSERT be regarded at the same value
 
3175
        */
 
3176
        if (!using_unique_constraint)
 
3177
          keydef.flag|= HA_NULL_ARE_EQUAL;
 
3178
      }
 
3179
    }
 
3180
  }
 
3181
  MI_CREATE_INFO create_info;
 
3182
  memset(&create_info, 0, sizeof(create_info));
 
3183
 
 
3184
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
3185
      OPTION_BIG_TABLES)
 
3186
    create_info.data_file_length= ~(uint64_t) 0;
 
3187
 
 
3188
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
 
3189
                       (uint32_t) (*recinfo-start_recinfo),
 
3190
                       start_recinfo,
 
3191
                       share->uniques, &uniquedef,
 
3192
                       &create_info,
 
3193
                       HA_CREATE_TMP_TABLE)))
 
3194
  {
 
3195
    file->print_error(error,MYF(0));
 
3196
    db_stat= 0;
 
3197
    goto err;
 
3198
  }
 
3199
  status_var_increment(in_use->status_var.created_tmp_disk_tables);
 
3200
  share->db_record_offset= 1;
 
3201
  return false;
 
3202
 err:
 
3203
  return true;
 
3204
}
 
3205
 
 
3206
 
 
3207
void Table::free_tmp_table(Session *session)
 
3208
{
 
3209
  MEM_ROOT own_root= mem_root;
 
3210
  const char *save_proc_info;
 
3211
 
 
3212
  save_proc_info=session->get_proc_info();
 
3213
  session->set_proc_info("removing tmp table");
 
3214
 
 
3215
  // Release latches since this can take a long time
 
3216
  ha_release_temporary_latches(session);
 
3217
 
 
3218
  if (file)
 
3219
  {
 
3220
    if (db_stat)
 
3221
      file->ha_drop_table(s->table_name.str);
 
3222
    else
 
3223
      s->db_type()->deleteTable(session, s->table_name.str);
 
3224
    delete file;
 
3225
  }
 
3226
 
 
3227
  /* free blobs */
 
3228
  for (Field **ptr= field ; *ptr ; ptr++)
 
3229
    (*ptr)->free();
 
3230
  free_io_cache();
 
3231
 
 
3232
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
 
3233
  session->set_proc_info(save_proc_info);
 
3234
}
 
3235
 
 
3236
/**
 
3237
  If a HEAP table gets full, create a MyISAM table and copy all rows
 
3238
  to this.
 
3239
*/
 
3240
 
 
3241
bool create_myisam_from_heap(Session *session, Table *table,
 
3242
                             MI_COLUMNDEF *start_recinfo,
 
3243
                             MI_COLUMNDEF **recinfo,
 
3244
                             int error, bool ignore_last_dupp_key_error)
 
3245
{
 
3246
  Table new_table;
 
3247
  TableShare share;
 
3248
  const char *save_proc_info;
 
3249
  int write_err;
 
3250
 
 
3251
  if (table->s->db_type() != heap_engine ||
 
3252
      error != HA_ERR_RECORD_FILE_FULL)
 
3253
  {
 
3254
    table->file->print_error(error,MYF(0));
 
3255
    return true;
 
3256
  }
 
3257
 
 
3258
  // Release latches since this can take a long time
 
3259
  ha_release_temporary_latches(session);
 
3260
 
 
3261
  new_table= *table;
 
3262
  share= *table->s;
 
3263
  new_table.s= &share;
 
3264
  new_table.s->storage_engine= myisam_engine;
 
3265
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
 
3266
                                        new_table.s->db_type())))
 
3267
    return true;                                // End of memory
 
3268
 
 
3269
  save_proc_info=session->get_proc_info();
 
3270
  session->set_proc_info("converting HEAP to MyISAM");
 
3271
 
 
3272
  if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
 
3273
                                        recinfo, session->lex->select_lex.options |
 
3274
                                        session->options))
 
3275
    goto err2;
 
3276
  if (new_table.open_tmp_table())
 
3277
    goto err1;
 
3278
  if (table->file->indexes_are_disabled())
 
3279
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
 
3280
  table->file->ha_index_or_rnd_end();
 
3281
  table->file->ha_rnd_init(1);
 
3282
  if (table->no_rows)
 
3283
  {
 
3284
    new_table.file->extra(HA_EXTRA_NO_ROWS);
 
3285
    new_table.no_rows=1;
 
3286
  }
 
3287
 
 
3288
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
 
3289
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
 
3290
 
 
3291
  /*
 
3292
    copy all old rows from heap table to MyISAM table
 
3293
    This is the only code that uses record[1] to read/write but this
 
3294
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
 
3295
  */
 
3296
  while (!table->file->rnd_next(new_table.record[1]))
 
3297
  {
 
3298
    write_err= new_table.file->ha_write_row(new_table.record[1]);
 
3299
    if (write_err)
 
3300
      goto err;
 
3301
  }
 
3302
  /* copy row that filled HEAP table */
 
3303
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
 
3304
  {
 
3305
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
 
3306
        !ignore_last_dupp_key_error)
 
3307
      goto err;
 
3308
  }
 
3309
 
 
3310
  /* remove heap table and change to use myisam table */
 
3311
  (void) table->file->ha_rnd_end();
 
3312
  (void) table->file->close();                  // This deletes the table !
 
3313
  delete table->file;
 
3314
  table->file= NULL;
 
3315
  new_table.s= table->s;                       // Keep old share
 
3316
  *table= new_table;
 
3317
  *table->s= share;
 
3318
 
 
3319
  table->file->change_table_ptr(table, table->s);
 
3320
  table->use_all_columns();
 
3321
  if (save_proc_info)
 
3322
  {
 
3323
    const char *new_proc_info=
 
3324
      (!strcmp(save_proc_info,"Copying to tmp table") ?
 
3325
      "Copying to tmp table on disk" : save_proc_info);
 
3326
    session->set_proc_info(new_proc_info);
 
3327
  }
 
3328
  return false;
 
3329
 
 
3330
 err:
 
3331
  table->file->print_error(write_err, MYF(0));
 
3332
  (void) table->file->ha_rnd_end();
 
3333
  (void) new_table.file->close();
 
3334
 err1:
 
3335
  new_table.s->db_type()->deleteTable(session, new_table.s->table_name.str);
 
3336
 err2:
 
3337
  delete new_table.file;
 
3338
  session->set_proc_info(save_proc_info);
 
3339
  table->mem_root= new_table.mem_root;
 
3340
  return true;
 
3341
}
 
3342
 
 
3343
my_bitmap_map *Table::use_all_columns(MyBitmap *bitmap)
 
3344
{
 
3345
  my_bitmap_map *old= bitmap->getBitmap();
 
3346
  bitmap->setBitmap(s->all_set.getBitmap());
1418
3347
  return old;
1419
3348
}
1420
3349
 
1421
 
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
 
3350
void Table::restore_column_map(my_bitmap_map *old)
1422
3351
{
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
 
  }
 
3352
  read_set->setBitmap(old);
1434
3353
}
1435
3354
 
1436
3355
uint32_t Table::find_shortest_key(const key_map *usable_keys)
1439
3358
  uint32_t best= MAX_KEY;
1440
3359
  if (usable_keys->any())
1441
3360
  {
1442
 
    for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
 
3361
    for (uint32_t nr= 0; nr < s->keys ; nr++)
1443
3362
    {
1444
3363
      if (usable_keys->test(nr))
1445
3364
      {
1466
3385
{
1467
3386
  for (; *ptr ; ptr++)
1468
3387
  {
1469
 
    if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
 
3388
    if ((*ptr)->cmp_offset(s->rec_buff_length))
1470
3389
      return true;
1471
3390
  }
1472
3391
  return false;
1473
3392
}
1474
3393
 
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
 
 
 
3394
/* Return false if row hasn't changed */
 
3395
 
 
3396
bool Table::compare_record()
 
3397
{
 
3398
  if (s->blob_fields + s->varchar_fields == 0)
 
3399
    return memcmp(this->record[0], this->record[1], (size_t) s->reclength);
1536
3400
  /* Compare null bits */
1537
 
  if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
1538
 
    return true; /* Diff in NULL value */
1539
 
 
 
3401
  if (memcmp(null_flags,
 
3402
             null_flags + s->rec_buff_length,
 
3403
             s->null_bytes))
 
3404
    return true;                                // Diff in NULL value
1540
3405
  /* Compare updated fields */
1541
3406
  for (Field **ptr= field ; *ptr ; ptr++)
1542
3407
  {
1543
 
    if (isWriteSet((*ptr)->position()) &&
1544
 
        (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
 
3408
    if (isWriteSet((*ptr)->field_index) &&
 
3409
        (*ptr)->cmp_binary_offset(s->rec_buff_length))
1545
3410
      return true;
1546
3411
  }
1547
3412
  return false;
1553
3418
 */
1554
3419
void Table::storeRecord()
1555
3420
{
1556
 
  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
 
3421
  memcpy(record[1], record[0], (size_t) s->reclength);
1557
3422
}
1558
3423
 
1559
3424
/*
1562
3427
 */
1563
3428
void Table::storeRecordAsInsert()
1564
3429
{
1565
 
  assert(insert_values.size() >= getShare()->getRecordLength());
1566
 
  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
 
3430
  memcpy(insert_values, record[0], (size_t) s->reclength);
1567
3431
}
1568
3432
 
1569
3433
/*
1572
3436
 */
1573
3437
void Table::storeRecordAsDefault()
1574
3438
{
1575
 
  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
 
3439
  memcpy(s->default_values, record[0], (size_t) s->reclength);
1576
3440
}
1577
3441
 
1578
3442
/*
1581
3445
 */
1582
3446
void Table::restoreRecord()
1583
3447
{
1584
 
  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
 
3448
  memcpy(record[0], record[1], (size_t) s->reclength);
1585
3449
}
1586
3450
 
1587
3451
/*
1590
3454
 */
1591
3455
void Table::restoreRecordAsDefault()
1592
3456
{
1593
 
  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
 
3457
  memcpy(record[0], s->default_values, (size_t) s->reclength);
1594
3458
}
1595
3459
 
1596
3460
/*
1600
3464
void Table::emptyRecord()
1601
3465
{
1602
3466
  restoreRecordAsDefault();
1603
 
  memset(null_flags, 255, getShare()->null_bytes);
1604
 
}
1605
 
 
1606
 
Table::Table() : 
1607
 
  field(NULL),
1608
 
  cursor(NULL),
1609
 
  next(NULL),
1610
 
  prev(NULL),
1611
 
  read_set(NULL),
1612
 
  write_set(NULL),
1613
 
  tablenr(0),
1614
 
  db_stat(0),
1615
 
  def_read_set(),
1616
 
  def_write_set(),
1617
 
  tmp_set(),
1618
 
  in_use(NULL),
1619
 
  key_info(NULL),
1620
 
  next_number_field(NULL),
1621
 
  found_next_number_field(NULL),
1622
 
  timestamp_field(NULL),
1623
 
  pos_in_table_list(NULL),
1624
 
  group(NULL),
1625
 
  null_flags(NULL),
1626
 
  lock_position(0),
1627
 
  lock_data_start(0),
1628
 
  lock_count(0),
1629
 
  used_fields(0),
1630
 
  status(0),
1631
 
  derived_select_number(0),
1632
 
  current_lock(F_UNLCK),
1633
 
  copy_blobs(false),
1634
 
  maybe_null(false),
1635
 
  null_row(false),
1636
 
  force_index(false),
1637
 
  distinct(false),
1638
 
  const_table(false),
1639
 
  no_rows(false),
1640
 
  key_read(false),
1641
 
  no_keyread(false),
1642
 
  open_placeholder(false),
1643
 
  locked_by_name(false),
1644
 
  no_cache(false),
1645
 
  auto_increment_field_not_null(false),
1646
 
  alias_name_used(false),
1647
 
  query_id(0),
1648
 
  quick_condition_rows(0),
1649
 
  timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1650
 
  map(0)
1651
 
{
1652
 
  record[0]= (unsigned char *) 0;
1653
 
  record[1]= (unsigned char *) 0;
1654
 
 
1655
 
  reginfo.reset();
1656
 
  covering_keys.reset();
1657
 
  quick_keys.reset();
1658
 
  merge_keys.reset();
1659
 
 
1660
 
  keys_in_use_for_query.reset();
1661
 
  keys_in_use_for_group_by.reset();
1662
 
  keys_in_use_for_order_by.reset();
1663
 
 
1664
 
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
1665
 
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
1666
 
 
1667
 
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
1668
 
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
 
3467
  memset(null_flags, 255, s->null_bytes);
1669
3468
}
1670
3469
 
1671
3470
/*****************************************************************************
1673
3472
  Returns -1 if row was not found, 0 if row was found and 1 on errors
1674
3473
*****************************************************************************/
1675
3474
 
1676
 
/** Help function when we get some an error from the table Cursor. */
 
3475
/** Help function when we get some an error from the table handler. */
1677
3476
 
1678
3477
int Table::report_error(int error)
1679
3478
{
1688
3487
  */
1689
3488
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
1690
3489
    errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
1691
 
                  error, getShare()->getPath());
1692
 
  print_error(error, MYF(0));
 
3490
                    error, s->path.str);
 
3491
  file->print_error(error,MYF(0));
1693
3492
 
1694
3493
  return 1;
1695
3494
}
1702
3501
  null_row= 0;
1703
3502
  status= STATUS_NO_RECORD;
1704
3503
  maybe_null= table_list->outer_join;
1705
 
  TableList *embedding= table_list->getEmbedding();
 
3504
  TableList *embedding= table_list->embedding;
1706
3505
  while (!maybe_null && embedding)
1707
3506
  {
1708
3507
    maybe_null= embedding->outer_join;
1709
 
    embedding= embedding->getEmbedding();
 
3508
    embedding= embedding->embedding;
1710
3509
  }
1711
3510
  tablenr= table_number;
1712
3511
  map= (table_map) 1 << table_number;
1713
3512
  force_index= table_list->force_index;
1714
 
  covering_keys= getShare()->keys_for_keyread;
 
3513
  covering_keys= s->keys_for_keyread;
1715
3514
  merge_keys.reset();
1716
3515
}
1717
3516
 
1718
 
 
1719
 
bool Table::fill_item_list(List<Item> *item_list) const
1720
 
{
1721
 
  /*
1722
 
    All Item_field's created using a direct pointer to a field
1723
 
    are fixed in Item_field constructor.
1724
 
  */
1725
 
  for (Field **ptr= field; *ptr; ptr++)
1726
 
  {
1727
 
    Item_field *item= new Item_field(*ptr);
1728
 
    if (!item || item_list->push_back(item))
1729
 
      return true;
1730
 
  }
 
3517
Field *Table::find_field_in_table_sef(const char *name)
 
3518
{
 
3519
  Field **field_ptr;
 
3520
  if (s->name_hash.records)
 
3521
  {
 
3522
    field_ptr= (Field**)hash_search(&s->name_hash,(unsigned char*) name,
 
3523
                                    strlen(name));
 
3524
    if (field_ptr)
 
3525
    {
 
3526
      /*
 
3527
        field_ptr points to field in TableShare. Convert it to the matching
 
3528
        field in table
 
3529
      */
 
3530
      field_ptr= (field + (field_ptr - s->field));
 
3531
    }
 
3532
  }
 
3533
  else
 
3534
  {
 
3535
    if (!(field_ptr= field))
 
3536
      return (Field *)0;
 
3537
    for (; *field_ptr; ++field_ptr)
 
3538
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
 
3539
        break;
 
3540
  }
 
3541
  if (field_ptr)
 
3542
    return *field_ptr;
 
3543
  else
 
3544
    return (Field *)0;
 
3545
}
 
3546
 
 
3547
 
 
3548
/*
 
3549
  Used by ALTER Table when the table is a temporary one. It changes something
 
3550
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
 
3551
  name).
 
3552
  Prepares a table cache key, which is the concatenation of db, table_name and
 
3553
  session->slave_proxy_id, separated by '\0'.
 
3554
*/
 
3555
 
 
3556
bool Table::rename_temporary_table(const char *db, const char *table_name)
 
3557
{
 
3558
  char *key;
 
3559
  uint32_t key_length;
 
3560
  TableShare *share= s;
 
3561
 
 
3562
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
 
3563
    return true;
 
3564
 
 
3565
  key_length= TableShare::createKey(key, db, table_name);
 
3566
  share->set_table_cache_key(key, key_length);
 
3567
 
1731
3568
  return false;
1732
3569
}
1733
3570
 
1734
 
 
1735
 
void Table::filesort_free_buffers(bool full)
1736
 
{
1737
 
  if (sort.record_pointers)
1738
 
  {
1739
 
    free((unsigned char*) sort.record_pointers);
1740
 
    sort.record_pointers=0;
1741
 
  }
1742
 
  if (full)
1743
 
  {
1744
 
    if (sort.sort_keys )
1745
 
    {
1746
 
      if ((unsigned char*) sort.sort_keys)
1747
 
        free((unsigned char*) sort.sort_keys);
1748
 
      sort.sort_keys= 0;
1749
 
    }
1750
 
    if (sort.buffpek)
1751
 
    {
1752
 
      if ((unsigned char*) sort.buffpek)
1753
 
        free((unsigned char*) sort.buffpek);
1754
 
      sort.buffpek= 0;
1755
 
      sort.buffpek_len= 0;
1756
 
    }
1757
 
  }
1758
 
 
1759
 
  if (sort.addon_buf)
1760
 
  {
1761
 
    free((char *) sort.addon_buf);
1762
 
    free((char *) sort.addon_field);
1763
 
    sort.addon_buf=0;
1764
 
    sort.addon_field=0;
1765
 
  }
1766
 
}
1767
 
 
1768
 
} /* namespace drizzled */
 
3571
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
3572
template class List<String>;
 
3573
template class List_iterator<String>;
 
3574
#endif