~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Brian Aker
  • Date: 2009-10-15 00:22:33 UTC
  • mto: (1183.1.11 merge)
  • mto: This revision was merged to the branch mainline in revision 1198.
  • Revision ID: brian@gaz-20091015002233-fa4ao2mbc67wls91
First pass of information engine. OMG, ponies... is it so much easier to
deal with creating and engine.

The list table iterator though... its ass, needs to go. We should also
abstract out share. Very few engines need a custom one. Just say'in

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