~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/table.cc

  • Committer: Monty Taylor
  • Date: 2009-03-08 23:45:12 UTC
  • mto: (923.2.1 mordred)
  • mto: This revision was merged to the branch mainline in revision 921.
  • Revision ID: mordred@inaugust.com-20090308234512-tqkygxtu1iaig23s
Removed C99 isnan() usage, which allows us to remove the util/math.{cc,h} workarounds. Yay for standards!

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>
 
23
#include <drizzled/sj_tmp_table.h>
33
24
#include <drizzled/nested_join.h>
 
25
#include <drizzled/data_home.h>
34
26
#include <drizzled/sql_parse.h>
35
27
#include <drizzled/item/sum.h>
 
28
#include <drizzled/virtual_column_info.h>
36
29
#include <drizzled/table_list.h>
37
30
#include <drizzled/session.h>
38
31
#include <drizzled/sql_base.h>
39
 
#include <drizzled/sql_select.h>
40
32
#include <drizzled/field/blob.h>
41
33
#include <drizzled/field/varstring.h>
42
34
#include <drizzled/field/double.h>
 
35
#include <string>
 
36
 
43
37
#include <drizzled/unireg.h>
44
 
#include <drizzled/message/table.pb.h>
45
 
#include <drizzled/sql_table.h>
46
 
#include <drizzled/charset.h>
47
 
#include <drizzled/internal/m_string.h>
48
 
#include <plugin/myisam/myisam.h>
49
 
#include <drizzled/plugin/storage_engine.h>
 
38
#include <drizzled/serialize/table.pb.h>
50
39
 
51
40
#include <drizzled/item/string.h>
52
41
#include <drizzled/item/int.h>
53
42
#include <drizzled/item/decimal.h>
54
43
#include <drizzled/item/float.h>
55
44
#include <drizzled/item/null.h>
56
 
#include <drizzled/temporal.h>
57
 
 
58
 
#include <drizzled/refresh_version.h>
59
 
 
60
 
#include <drizzled/table/singular.h>
61
 
 
62
 
#include <drizzled/table_proto.h>
63
 
#include <drizzled/typelib.h>
 
45
 
64
46
 
65
47
using namespace std;
66
48
 
67
 
namespace drizzled
68
 
{
69
 
 
70
 
extern plugin::StorageEngine *heap_engine;
71
 
extern plugin::StorageEngine *myisam_engine;
72
 
 
73
 
/* Functions defined in this cursor */
 
49
/* Keyword for parsing virtual column functions */
 
50
LEX_STRING parse_vcol_keyword= { C_STRING_WITH_LEN("PARSE_VCOL_EXPR ") };
 
51
 
 
52
/* Functions defined in this file */
 
53
 
 
54
void open_table_error(TABLE_SHARE *share, int error, int db_errno,
 
55
                      myf errortype, int errarg);
 
56
static void fix_type_pointers(const char ***array, TYPELIB *point_to_type,
 
57
                              uint32_t types, char **names);
74
58
 
75
59
/*************************************************************************/
76
60
 
77
 
// @note this should all be the destructor
78
 
int Table::delete_table(bool free_share)
79
 
{
80
 
  int error= 0;
 
61
/* Get column name from column hash */
 
62
 
 
63
static unsigned char *get_field_name(Field **buff, size_t *length, bool)
 
64
{
 
65
  *length= (uint32_t) strlen((*buff)->field_name);
 
66
  return (unsigned char*) (*buff)->field_name;
 
67
}
 
68
 
 
69
 
 
70
/*
 
71
  Returns pointer to '.frm' extension of the file name.
 
72
 
 
73
  SYNOPSIS
 
74
    fn_rext()
 
75
    name       file name
 
76
 
 
77
  DESCRIPTION
 
78
    Checks file name part starting with the rightmost '.' character,
 
79
    and returns it if it is equal to '.frm'.
 
80
 
 
81
  TODO
 
82
    It is a good idea to get rid of this function modifying the code
 
83
    to garantee that the functions presently calling fn_rext() always
 
84
    get arguments in the same format: either with '.frm' or without '.frm'.
 
85
 
 
86
  RETURN VALUES
 
87
    Pointer to the '.frm' extension. If there is no extension,
 
88
    or extension is not '.frm', pointer at the end of file name.
 
89
*/
 
90
 
 
91
char *fn_rext(char *name)
 
92
{
 
93
  char *res= strrchr(name, '.');
 
94
  if (res && !strcmp(res, ".dfe"))
 
95
    return res;
 
96
  return name + strlen(name);
 
97
}
 
98
 
 
99
TABLE_CATEGORY get_table_category(const LEX_STRING *db, const LEX_STRING *name)
 
100
{
 
101
  assert(db != NULL);
 
102
  assert(name != NULL);
 
103
 
 
104
  if ((db->length == INFORMATION_SCHEMA_NAME.length()) &&
 
105
      (my_strcasecmp(system_charset_info,
 
106
                    INFORMATION_SCHEMA_NAME.c_str(),
 
107
                    db->str) == 0))
 
108
  {
 
109
    return TABLE_CATEGORY_INFORMATION;
 
110
  }
 
111
 
 
112
  return TABLE_CATEGORY_USER;
 
113
}
 
114
 
 
115
 
 
116
/*
 
117
  Allocate a setup TABLE_SHARE structure
 
118
 
 
119
  SYNOPSIS
 
120
    alloc_table_share()
 
121
    TableList           Take database and table name from there
 
122
    key                 Table cache key (db \0 table_name \0...)
 
123
    key_length          Length of key
 
124
 
 
125
  RETURN
 
126
    0  Error (out of memory)
 
127
    #  Share
 
128
*/
 
129
 
 
130
TABLE_SHARE *alloc_table_share(TableList *table_list, char *key,
 
131
                               uint32_t key_length)
 
132
{
 
133
  MEM_ROOT mem_root;
 
134
  TABLE_SHARE *share;
 
135
  char *key_buff, *path_buff;
 
136
  char path[FN_REFLEN];
 
137
  uint32_t path_length;
 
138
 
 
139
  path_length= build_table_filename(path, sizeof(path) - 1,
 
140
                                    table_list->db,
 
141
                                    table_list->table_name, "", 0);
 
142
  init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
143
  if (multi_alloc_root(&mem_root,
 
144
                       &share, sizeof(*share),
 
145
                       &key_buff, key_length,
 
146
                       &path_buff, path_length + 1,
 
147
                       NULL))
 
148
  {
 
149
    memset(share, 0, sizeof(*share));
 
150
 
 
151
    share->set_table_cache_key(key_buff, key, key_length);
 
152
 
 
153
    share->path.str= path_buff;
 
154
    share->path.length= path_length;
 
155
    strcpy(share->path.str, path);
 
156
    share->normalized_path.str=    share->path.str;
 
157
    share->normalized_path.length= path_length;
 
158
 
 
159
    share->version=       refresh_version;
 
160
 
 
161
    /*
 
162
      This constant is used to mark that no table map version has been
 
163
      assigned.  No arithmetic is done on the value: it will be
 
164
      overwritten with a value taken from DRIZZLE_BIN_LOG.
 
165
    */
 
166
    share->table_map_version= UINT64_MAX;
 
167
 
 
168
    /*
 
169
      Since alloc_table_share() can be called without any locking (for
 
170
      example, ha_create_table... functions), we do not assign a table
 
171
      map id here.  Instead we assign a value that is not used
 
172
      elsewhere, and then assign a table map id inside open_table()
 
173
      under the protection of the LOCK_open mutex.
 
174
    */
 
175
    share->table_map_id= UINT32_MAX;
 
176
    share->cached_row_logging_check= -1;
 
177
 
 
178
    memcpy(&share->mem_root, &mem_root, sizeof(mem_root));
 
179
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
 
180
    pthread_cond_init(&share->cond, NULL);
 
181
  }
 
182
  return(share);
 
183
}
 
184
 
 
185
 
 
186
/*
 
187
  Initialize share for temporary tables
 
188
 
 
189
  SYNOPSIS
 
190
    init_tmp_table_share()
 
191
    session         thread handle
 
192
    share       Share to fill
 
193
    key         Table_cache_key, as generated from create_table_def_key.
 
194
                must start with db name.
 
195
    key_length  Length of key
 
196
    table_name  Table name
 
197
    path        Path to file (possible in lower case) without .frm
 
198
 
 
199
  NOTES
 
200
    This is different from alloc_table_share() because temporary tables
 
201
    don't have to be shared between threads or put into the table def
 
202
    cache, so we can do some things notable simpler and faster
 
203
 
 
204
    If table is not put in session->temporary_tables (happens only when
 
205
    one uses OPEN TEMPORARY) then one can specify 'db' as key and
 
206
    use key_length= 0 as neither table_cache_key or key_length will be used).
 
207
*/
 
208
 
 
209
void init_tmp_table_share(Session *session, TABLE_SHARE *share, const char *key,
 
210
                          uint32_t key_length, const char *table_name,
 
211
                          const char *path)
 
212
{
 
213
 
 
214
  memset(share, 0, sizeof(*share));
 
215
  init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
216
  share->table_category=         TABLE_CATEGORY_TEMPORARY;
 
217
  share->tmp_table=              INTERNAL_TMP_TABLE;
 
218
  share->db.str=                 (char*) key;
 
219
  share->db.length=              strlen(key);
 
220
  share->table_cache_key.str=    (char*) key;
 
221
  share->table_cache_key.length= key_length;
 
222
  share->table_name.str=         (char*) table_name;
 
223
  share->table_name.length=      strlen(table_name);
 
224
  share->path.str=               (char*) path;
 
225
  share->normalized_path.str=    (char*) path;
 
226
  share->path.length= share->normalized_path.length= strlen(path);
 
227
 
 
228
  /*
 
229
    Temporary tables are not replicated, but we set up these fields
 
230
    anyway to be able to catch errors.
 
231
   */
 
232
  share->table_map_version= ~(uint64_t)0;
 
233
  share->cached_row_logging_check= -1;
 
234
 
 
235
  /*
 
236
    table_map_id is also used for MERGE tables to suppress repeated
 
237
    compatibility checks.
 
238
  */
 
239
  share->table_map_id= (ulong) session->query_id;
 
240
 
 
241
  return;
 
242
}
 
243
 
 
244
 
 
245
/*
 
246
  Free table share and memory used by it
 
247
 
 
248
  SYNOPSIS
 
249
    free_table_share()
 
250
    share               Table share
 
251
 
 
252
  NOTES
 
253
    share->mutex must be locked when we come here if it's not a temp table
 
254
*/
 
255
 
 
256
void free_table_share(TABLE_SHARE *share)
 
257
{
 
258
  MEM_ROOT mem_root;
 
259
  assert(share->ref_count == 0);
 
260
 
 
261
  /*
 
262
    If someone is waiting for this to be deleted, inform it about this.
 
263
    Don't do a delete until we know that no one is refering to this anymore.
 
264
  */
 
265
  if (share->tmp_table == NO_TMP_TABLE)
 
266
  {
 
267
    /* share->mutex is locked in release_table_share() */
 
268
    while (share->waiting_on_cond)
 
269
    {
 
270
      pthread_cond_broadcast(&share->cond);
 
271
      pthread_cond_wait(&share->cond, &share->mutex);
 
272
    }
 
273
    /* No thread refers to this anymore */
 
274
    pthread_mutex_unlock(&share->mutex);
 
275
    pthread_mutex_destroy(&share->mutex);
 
276
    pthread_cond_destroy(&share->cond);
 
277
  }
 
278
  hash_free(&share->name_hash);
 
279
 
 
280
  plugin_unlock(NULL, share->db_plugin);
 
281
  share->db_plugin= NULL;
 
282
 
 
283
  /* We must copy mem_root from share because share is allocated through it */
 
284
  memcpy(&mem_root, &share->mem_root, sizeof(mem_root));
 
285
  free_root(&mem_root, MYF(0));                 // Free's share
 
286
  return;
 
287
}
 
288
 
 
289
enum_field_types proto_field_type_to_drizzle_type(uint32_t proto_field_type)
 
290
{
 
291
  enum_field_types field_type;
 
292
 
 
293
  switch(proto_field_type)
 
294
  {
 
295
  case drizzle::Table::Field::TINYINT:
 
296
    field_type= DRIZZLE_TYPE_TINY;
 
297
    break;
 
298
  case drizzle::Table::Field::INTEGER:
 
299
    field_type= DRIZZLE_TYPE_LONG;
 
300
    break;
 
301
  case drizzle::Table::Field::DOUBLE:
 
302
    field_type= DRIZZLE_TYPE_DOUBLE;
 
303
    break;
 
304
  case drizzle::Table::Field::TIMESTAMP:
 
305
    field_type= DRIZZLE_TYPE_TIMESTAMP;
 
306
    break;
 
307
  case drizzle::Table::Field::BIGINT:
 
308
    field_type= DRIZZLE_TYPE_LONGLONG;
 
309
    break;
 
310
  case drizzle::Table::Field::DATETIME:
 
311
    field_type= DRIZZLE_TYPE_DATETIME;
 
312
    break;
 
313
  case drizzle::Table::Field::DATE:
 
314
    field_type= DRIZZLE_TYPE_DATE;
 
315
    break;
 
316
  case drizzle::Table::Field::VARCHAR:
 
317
    field_type= DRIZZLE_TYPE_VARCHAR;
 
318
    break;
 
319
  case drizzle::Table::Field::DECIMAL:
 
320
    field_type= DRIZZLE_TYPE_NEWDECIMAL;
 
321
    break;
 
322
  case drizzle::Table::Field::ENUM:
 
323
    field_type= DRIZZLE_TYPE_ENUM;
 
324
    break;
 
325
  case drizzle::Table::Field::BLOB:
 
326
    field_type= DRIZZLE_TYPE_BLOB;
 
327
    break;
 
328
  case drizzle::Table::Field::VIRTUAL:
 
329
    field_type= DRIZZLE_TYPE_VIRTUAL;
 
330
    break;
 
331
  default:
 
332
    field_type= DRIZZLE_TYPE_TINY; /* Set value to kill GCC warning */
 
333
    assert(1);
 
334
  }
 
335
 
 
336
  return field_type;
 
337
}
 
338
 
 
339
Item * default_value_item(enum_field_types field_type,
 
340
                          const CHARSET_INFO *charset,
 
341
                          bool default_null, string default_value,
 
342
                          string default_bin_value)
 
343
{
 
344
  Item *default_item= NULL;
 
345
  int error= 0;
 
346
 
 
347
  if(default_null)
 
348
  {
 
349
    return new Item_null();
 
350
  }
 
351
 
 
352
  switch(field_type)
 
353
  {
 
354
  case DRIZZLE_TYPE_TINY:
 
355
  case DRIZZLE_TYPE_LONG:
 
356
  case DRIZZLE_TYPE_LONGLONG:
 
357
    default_item= new Item_int(default_value.c_str(),
 
358
                               (int64_t) my_strtoll10(default_value.c_str(),
 
359
                                                      NULL,
 
360
                                                      &error),
 
361
                               default_value.length());
 
362
    break;
 
363
  case DRIZZLE_TYPE_DOUBLE:
 
364
    default_item= new Item_float(default_value.c_str(), default_value.length());
 
365
    break;
 
366
  case DRIZZLE_TYPE_NULL:
 
367
    assert(false);
 
368
  case DRIZZLE_TYPE_TIMESTAMP:
 
369
  case DRIZZLE_TYPE_DATETIME:
 
370
  case DRIZZLE_TYPE_DATE:
 
371
    if(default_value.compare("NOW()")==0)
 
372
      break;
 
373
  case DRIZZLE_TYPE_ENUM:
 
374
    default_item= new Item_string(default_value.c_str(),
 
375
                                  default_value.length(),
 
376
                                  system_charset_info);
 
377
    break;
 
378
  case DRIZZLE_TYPE_VARCHAR:
 
379
  case DRIZZLE_TYPE_BLOB: /* Blob is here due to TINYTEXT. Feel the hate. */
 
380
    if(charset==&my_charset_bin)
 
381
    {
 
382
      default_item= new Item_string(default_bin_value.c_str(),
 
383
                                    default_bin_value.length(),
 
384
                                    &my_charset_bin);
 
385
    }
 
386
    else
 
387
    {
 
388
      default_item= new Item_string(default_value.c_str(),
 
389
                                    default_value.length(),
 
390
                                    system_charset_info);
 
391
    }
 
392
    break;
 
393
  case DRIZZLE_TYPE_VIRTUAL:
 
394
    break;
 
395
  case DRIZZLE_TYPE_NEWDECIMAL:
 
396
    default_item= new Item_decimal(default_value.c_str(),
 
397
                                   default_value.length(),
 
398
                                   system_charset_info);
 
399
    break;
 
400
  }
 
401
 
 
402
  return default_item;
 
403
}
 
404
 
 
405
int parse_table_proto(Session *session, drizzle::Table &table, TABLE_SHARE *share)
 
406
{
 
407
  int error= 0;
 
408
  handler *handler_file= NULL;
 
409
 
 
410
  {
 
411
    LEX_STRING engine_name= { (char*)table.engine().name().c_str(),
 
412
                              strlen(table.engine().name().c_str()) };
 
413
    share->db_plugin= ha_resolve_by_name(session, &engine_name);
 
414
  }
 
415
 
 
416
  share->mysql_version= DRIZZLE_VERSION_ID; // TODO: remove
 
417
 
 
418
  drizzle::Table::TableOptions table_options;
 
419
 
 
420
  if(table.has_options())
 
421
    table_options= table.options();
 
422
 
 
423
  uint32_t db_create_options= HA_OPTION_LONG_BLOB_PTR;
 
424
 
 
425
  if(table_options.has_pack_keys())
 
426
  {
 
427
    if(table_options.pack_keys())
 
428
      db_create_options|= HA_OPTION_PACK_KEYS;
 
429
    else
 
430
      db_create_options|= HA_OPTION_NO_PACK_KEYS;
 
431
  }
 
432
 
 
433
  if(table_options.pack_record())
 
434
    db_create_options|= HA_OPTION_PACK_RECORD;
 
435
 
 
436
  if(table_options.has_checksum())
 
437
  {
 
438
    if(table_options.checksum())
 
439
      db_create_options|= HA_OPTION_CHECKSUM;
 
440
    else
 
441
      db_create_options|= HA_OPTION_NO_CHECKSUM;
 
442
  }
 
443
 
 
444
  if(table_options.has_delay_key_write())
 
445
  {
 
446
    if(table_options.delay_key_write())
 
447
      db_create_options|= HA_OPTION_DELAY_KEY_WRITE;
 
448
    else
 
449
      db_create_options|= HA_OPTION_NO_DELAY_KEY_WRITE;
 
450
  }
 
451
 
 
452
  /* db_create_options was stored as 2 bytes in FRM
 
453
     Any HA_OPTION_ that doesn't fit into 2 bytes was silently truncated away.
 
454
   */
 
455
  share->db_create_options= (db_create_options & 0x0000FFFF);
 
456
  share->db_options_in_use= share->db_create_options;
 
457
 
 
458
 
 
459
  share->avg_row_length= table_options.has_avg_row_length() ?
 
460
    table_options.avg_row_length() : 0;
 
461
 
 
462
  share->page_checksum= table_options.has_page_checksum() ?
 
463
    (table_options.page_checksum()?HA_CHOICE_YES:HA_CHOICE_NO)
 
464
    : HA_CHOICE_UNDEF;
 
465
 
 
466
  share->row_type= table_options.has_row_type() ?
 
467
    (enum row_type) table_options.row_type() : ROW_TYPE_DEFAULT;
 
468
 
 
469
  share->block_size= table_options.has_block_size() ?
 
470
    table_options.block_size() : 0;
 
471
 
 
472
  share->table_charset= get_charset(table_options.has_collation_id()?
 
473
                                    table_options.collation_id() : 0);
 
474
 
 
475
  if (!share->table_charset)
 
476
  {
 
477
    /* unknown charset in head[38] or pre-3.23 frm */
 
478
    if (use_mb(default_charset_info))
 
479
    {
 
480
      /* Warn that we may be changing the size of character columns */
 
481
      errmsg_printf(ERRMSG_LVL_WARN,
 
482
                    _("'%s' had no or invalid character set, "
 
483
                      "and default character set is multi-byte, "
 
484
                      "so character column sizes may have changed"),
 
485
                    share->path.str);
 
486
    }
 
487
    share->table_charset= default_charset_info;
 
488
  }
 
489
 
 
490
  share->db_record_offset= 1;
 
491
 
 
492
  share->blob_ptr_size= portable_sizeof_char_ptr; // more bonghits.
 
493
 
 
494
  share->db_low_byte_first= true;
 
495
 
 
496
  share->max_rows= table_options.has_max_rows() ?
 
497
    table_options.max_rows() : 0;
 
498
 
 
499
  share->min_rows= table_options.has_min_rows() ?
 
500
    table_options.min_rows() : 0;
 
501
 
 
502
  share->keys= table.indexes_size();
 
503
 
 
504
  share->key_parts= 0;
 
505
  for(int indx= 0; indx < table.indexes_size(); indx++)
 
506
    share->key_parts+= table.indexes(indx).index_part_size();
 
507
 
 
508
  share->key_info= (KEY*) alloc_root(&share->mem_root,
 
509
                                     table.indexes_size() * sizeof(KEY)
 
510
                                     +share->key_parts*sizeof(KEY_PART_INFO));
 
511
 
 
512
  KEY_PART_INFO *key_part;
 
513
 
 
514
  key_part= reinterpret_cast<KEY_PART_INFO*>
 
515
    (share->key_info+table.indexes_size());
 
516
 
 
517
 
 
518
  ulong *rec_per_key= (ulong*) alloc_root(&share->mem_root,
 
519
                                            sizeof(ulong*)*share->key_parts);
 
520
 
 
521
  share->keynames.count= table.indexes_size();
 
522
  share->keynames.name= NULL;
 
523
  share->keynames.type_names= (const char**)
 
524
    alloc_root(&share->mem_root, sizeof(char*) * (table.indexes_size()+1));
 
525
 
 
526
  share->keynames.type_lengths= (unsigned int*)
 
527
    alloc_root(&share->mem_root,
 
528
               sizeof(unsigned int) * (table.indexes_size()+1));
 
529
 
 
530
  share->keynames.type_names[share->keynames.count]= NULL;
 
531
  share->keynames.type_lengths[share->keynames.count]= 0;
 
532
 
 
533
  KEY* keyinfo= share->key_info;
 
534
  for (int keynr=0; keynr < table.indexes_size(); keynr++, keyinfo++)
 
535
  {
 
536
    drizzle::Table::Index indx= table.indexes(keynr);
 
537
 
 
538
    keyinfo->table= 0;
 
539
    keyinfo->flags= 0;
 
540
 
 
541
    if(indx.is_unique())
 
542
      keyinfo->flags|= HA_NOSAME;
 
543
 
 
544
    if(indx.has_options())
 
545
    {
 
546
      drizzle::Table::Index::IndexOptions indx_options= indx.options();
 
547
      if(indx_options.pack_key())
 
548
        keyinfo->flags|= HA_PACK_KEY;
 
549
 
 
550
      if(indx_options.var_length_key())
 
551
        keyinfo->flags|= HA_VAR_LENGTH_PART;
 
552
 
 
553
      if(indx_options.null_part_key())
 
554
        keyinfo->flags|= HA_NULL_PART_KEY;
 
555
 
 
556
      if(indx_options.binary_pack_key())
 
557
        keyinfo->flags|= HA_BINARY_PACK_KEY;
 
558
 
 
559
      if(indx_options.has_partial_segments())
 
560
        keyinfo->flags|= HA_KEY_HAS_PART_KEY_SEG;
 
561
 
 
562
      if(indx_options.auto_generated_key())
 
563
        keyinfo->flags|= HA_GENERATED_KEY;
 
564
 
 
565
      if(indx_options.has_key_block_size())
 
566
      {
 
567
        keyinfo->flags|= HA_USES_BLOCK_SIZE;
 
568
        keyinfo->block_size= indx_options.key_block_size();
 
569
      }
 
570
      else
 
571
      {
 
572
        keyinfo->block_size= 0;
 
573
      }
 
574
 
 
575
    }
 
576
 
 
577
    switch(indx.type())
 
578
    {
 
579
    case drizzle::Table::Index::UNKNOWN_INDEX:
 
580
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
581
      break;
 
582
    case drizzle::Table::Index::BTREE:
 
583
      keyinfo->algorithm= HA_KEY_ALG_BTREE;
 
584
      break;
 
585
    case drizzle::Table::Index::RTREE:
 
586
      keyinfo->algorithm= HA_KEY_ALG_RTREE;
 
587
      break;
 
588
    case drizzle::Table::Index::HASH:
 
589
      keyinfo->algorithm= HA_KEY_ALG_HASH;
 
590
      break;
 
591
    case drizzle::Table::Index::FULLTEXT:
 
592
      keyinfo->algorithm= HA_KEY_ALG_FULLTEXT;
 
593
 
 
594
    default:
 
595
      /* TODO: suitable warning ? */
 
596
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
597
      break;
 
598
    }
 
599
 
 
600
    keyinfo->key_length= indx.key_length();
 
601
 
 
602
    keyinfo->key_parts= indx.index_part_size();
 
603
 
 
604
    keyinfo->key_part= key_part;
 
605
    keyinfo->rec_per_key= rec_per_key;
 
606
 
 
607
    for(unsigned int partnr= 0;
 
608
        partnr < keyinfo->key_parts;
 
609
        partnr++, key_part++)
 
610
    {
 
611
      drizzle::Table::Index::IndexPart part;
 
612
      part= indx.index_part(partnr);
 
613
 
 
614
      *rec_per_key++=0;
 
615
 
 
616
      key_part->field= NULL;
 
617
      key_part->fieldnr= part.fieldnr() + 1; // start from 1.
 
618
      key_part->null_bit= 0;
 
619
      /* key_part->null_offset is only set if null_bit (see later) */
 
620
      /* key_part->key_type= */ /* I *THINK* this may be okay.... */
 
621
      /* key_part->type ???? */
 
622
      key_part->key_part_flag= 0;
 
623
      if(part.has_in_reverse_order())
 
624
        key_part->key_part_flag= part.in_reverse_order()? HA_REVERSE_SORT : 0;
 
625
 
 
626
      key_part->length= part.compare_length();
 
627
 
 
628
      key_part->store_length= key_part->length;
 
629
 
 
630
      /* key_part->offset is set later */
 
631
      key_part->key_type= part.key_type();
 
632
 
 
633
    }
 
634
 
 
635
    if(!indx.has_comment())
 
636
    {
 
637
      keyinfo->comment.length= 0;
 
638
      keyinfo->comment.str= NULL;
 
639
    }
 
640
    else
 
641
    {
 
642
      keyinfo->flags|= HA_USES_COMMENT;
 
643
      keyinfo->comment.length= indx.comment().length();
 
644
      keyinfo->comment.str= strmake_root(&share->mem_root,
 
645
                                         indx.comment().c_str(),
 
646
                                         keyinfo->comment.length);
 
647
    }
 
648
 
 
649
    keyinfo->name= strmake_root(&share->mem_root,
 
650
                                indx.name().c_str(),
 
651
                                indx.name().length());
 
652
 
 
653
    share->keynames.type_names[keynr]= keyinfo->name;
 
654
    share->keynames.type_lengths[keynr]= indx.name().length();
 
655
  }
 
656
 
 
657
  share->keys_for_keyread.init(0);
 
658
  share->keys_in_use.init(share->keys);
 
659
 
 
660
  if(table_options.has_connect_string())
 
661
  {
 
662
    size_t len= table_options.connect_string().length();
 
663
    const char* str= table_options.connect_string().c_str();
 
664
 
 
665
    share->connect_string.length= len;
 
666
    share->connect_string.str= strmake_root(&share->mem_root, str, len);
 
667
  }
 
668
 
 
669
  if(table_options.has_comment())
 
670
  {
 
671
    size_t len= table_options.comment().length();
 
672
    const char* str= table_options.comment().c_str();
 
673
 
 
674
    share->comment.length= len;
 
675
    share->comment.str= strmake_root(&share->mem_root, str, len);
 
676
  }
 
677
 
 
678
  share->key_block_size= table_options.has_key_block_size() ?
 
679
    table_options.key_block_size() : 0;
 
680
 
 
681
  share->fields= table.field_size();
 
682
  share->vfields= 0;
 
683
  share->stored_fields= share->fields;
 
684
 
 
685
  share->field= (Field**) alloc_root(&share->mem_root,
 
686
                                     ((share->fields+1) * sizeof(Field*)));
 
687
  share->field[share->fields]= NULL;
 
688
 
 
689
  uint32_t null_fields= 0;
 
690
  share->reclength= 0;
 
691
 
 
692
  uint32_t *field_offsets= (uint32_t*)malloc(share->fields * sizeof(uint32_t));
 
693
  uint32_t *field_pack_length=(uint32_t*)malloc(share->fields*sizeof(uint32_t));
 
694
 
 
695
  assert(field_offsets && field_pack_length); // TODO: fixme
 
696
 
 
697
  uint32_t interval_count= 0;
 
698
  uint32_t interval_parts= 0;
 
699
 
 
700
  uint32_t stored_columns_reclength= 0;
 
701
 
 
702
  for(unsigned int fieldnr=0; fieldnr < share->fields; fieldnr++)
 
703
  {
 
704
    drizzle::Table::Field pfield= table.field(fieldnr);
 
705
    if(pfield.has_constraints() && pfield.constraints().is_nullable())
 
706
      null_fields++;
 
707
 
 
708
    bool field_is_stored= true;
 
709
 
 
710
    enum_field_types drizzle_field_type=
 
711
      proto_field_type_to_drizzle_type(pfield.type());
 
712
 
 
713
    if(drizzle_field_type==DRIZZLE_TYPE_VIRTUAL)
 
714
    {
 
715
      drizzle::Table::Field::VirtualFieldOptions field_options=
 
716
        pfield.virtual_options();
 
717
 
 
718
      drizzle_field_type=proto_field_type_to_drizzle_type(field_options.type());
 
719
 
 
720
      field_is_stored= field_options.physically_stored();
 
721
    }
 
722
 
 
723
    field_offsets[fieldnr]= stored_columns_reclength;
 
724
 
 
725
    /* the below switch is very similar to
 
726
       Create_field::create_length_to_internal_length in field.cc
 
727
       (which should one day be replace by just this code)
 
728
    */
 
729
    switch(drizzle_field_type)
 
730
    {
 
731
    case DRIZZLE_TYPE_BLOB:
 
732
    case DRIZZLE_TYPE_VARCHAR:
 
733
      {
 
734
        drizzle::Table::Field::StringFieldOptions field_options=
 
735
          pfield.string_options();
 
736
 
 
737
        const CHARSET_INFO *cs= get_charset(field_options.has_collation_id()?
 
738
                                            field_options.collation_id() : 0);
 
739
 
 
740
        if (!cs)
 
741
          cs= default_charset_info;
 
742
 
 
743
        field_pack_length[fieldnr]=
 
744
          calc_pack_length(drizzle_field_type,
 
745
                           field_options.length() * cs->mbmaxlen);
 
746
 
 
747
      }
 
748
      break;
 
749
    case DRIZZLE_TYPE_ENUM:
 
750
      {
 
751
        drizzle::Table::Field::SetFieldOptions field_options=
 
752
          pfield.set_options();
 
753
 
 
754
        field_pack_length[fieldnr]=
 
755
          get_enum_pack_length(field_options.field_value_size());
 
756
 
 
757
        interval_count++;
 
758
        interval_parts+= field_options.field_value_size();
 
759
      }
 
760
      break;
 
761
    case DRIZZLE_TYPE_NEWDECIMAL:
 
762
      {
 
763
        drizzle::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
 
764
 
 
765
        field_pack_length[fieldnr]=
 
766
          my_decimal_get_binary_size(fo.precision(), fo.scale());
 
767
      }
 
768
      break;
 
769
    default:
 
770
      /* Zero is okay here as length is fixed for other types. */
 
771
      field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type, 0);
 
772
    }
 
773
 
 
774
    share->reclength+= field_pack_length[fieldnr];
 
775
 
 
776
    if(field_is_stored)
 
777
      stored_columns_reclength+= field_pack_length[fieldnr];
 
778
  }
 
779
 
 
780
  /* data_offset added to stored_rec_length later */
 
781
  share->stored_rec_length= stored_columns_reclength;
 
782
 
 
783
  /* fix up offsets for non-stored fields (at end of record) */
 
784
  for(unsigned int fieldnr=0; fieldnr < share->fields; fieldnr++)
 
785
  {
 
786
    drizzle::Table::Field pfield= table.field(fieldnr);
 
787
 
 
788
    bool field_is_stored= true;
 
789
 
 
790
    enum_field_types drizzle_field_type=
 
791
      proto_field_type_to_drizzle_type(pfield.type());
 
792
 
 
793
    if(drizzle_field_type==DRIZZLE_TYPE_VIRTUAL)
 
794
    {
 
795
      drizzle::Table::Field::VirtualFieldOptions field_options=
 
796
        pfield.virtual_options();
 
797
 
 
798
      field_is_stored= field_options.physically_stored();
 
799
    }
 
800
 
 
801
    if(!field_is_stored)
 
802
    {
 
803
      field_offsets[fieldnr]= stored_columns_reclength;
 
804
      stored_columns_reclength+= field_pack_length[fieldnr];
 
805
    }
 
806
  }
 
807
  share->null_fields= null_fields;
 
808
 
 
809
  ulong null_bits= null_fields;
 
810
  if(!table_options.pack_record())
 
811
    null_bits++;
 
812
  ulong data_offset= (null_bits + 7)/8;
 
813
 
 
814
 
 
815
  share->reclength+= data_offset;
 
816
  share->stored_rec_length+= data_offset;
 
817
 
 
818
  ulong rec_buff_length;
 
819
 
 
820
  rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
821
  share->rec_buff_length= rec_buff_length;
 
822
 
 
823
  unsigned char* record= NULL;
 
824
 
 
825
  if (!(record= (unsigned char *) alloc_root(&share->mem_root,
 
826
                                     rec_buff_length)))
 
827
    abort();
 
828
 
 
829
  memset(record, 0, rec_buff_length);
 
830
 
 
831
  int null_count= 0;
 
832
 
 
833
  if(!table_options.pack_record())
 
834
  {
 
835
    null_count++; // one bit for delete mark.
 
836
    *record|= 1;
 
837
  }
 
838
 
 
839
  share->default_values= record;
 
840
 
 
841
  if(interval_count)
 
842
  {
 
843
    share->intervals= (TYPELIB*)alloc_root(&share->mem_root,
 
844
                                           interval_count*sizeof(TYPELIB));
 
845
  }
 
846
  else
 
847
    share->intervals= NULL;
 
848
 
 
849
  share->fieldnames.type_names= (const char**)alloc_root(&share->mem_root,
 
850
                                  (share->fields+1)*sizeof(char*));
 
851
 
 
852
  share->fieldnames.type_lengths= (unsigned int*) alloc_root(&share->mem_root,
 
853
                                  (share->fields+1)*sizeof(unsigned int));
 
854
 
 
855
  share->fieldnames.type_names[share->fields]= NULL;
 
856
  share->fieldnames.type_lengths[share->fields]= 0;
 
857
  share->fieldnames.count= share->fields;
 
858
 
 
859
 
 
860
  /* Now fix the TYPELIBs for the intervals (enum values)
 
861
     and field names.
 
862
   */
 
863
 
 
864
  uint32_t interval_nr= 0;
 
865
 
 
866
  for(unsigned int fieldnr=0; fieldnr < share->fields; fieldnr++)
 
867
  {
 
868
    drizzle::Table::Field pfield= table.field(fieldnr);
 
869
 
 
870
    /* field names */
 
871
    share->fieldnames.type_names[fieldnr]= strmake_root(&share->mem_root,
 
872
                                                        pfield.name().c_str(),
 
873
                                                        pfield.name().length());
 
874
 
 
875
    share->fieldnames.type_lengths[fieldnr]= pfield.name().length();
 
876
 
 
877
    /* enum typelibs */
 
878
    if(pfield.type() != drizzle::Table::Field::ENUM)
 
879
      continue;
 
880
 
 
881
    drizzle::Table::Field::SetFieldOptions field_options=
 
882
      pfield.set_options();
 
883
 
 
884
    const CHARSET_INFO *charset= get_charset(field_options.has_collation_id()?
 
885
                                             field_options.collation_id() : 0);
 
886
 
 
887
    if (!charset)
 
888
      charset= default_charset_info;
 
889
 
 
890
    TYPELIB *t= &(share->intervals[interval_nr]);
 
891
 
 
892
    t->type_names= (const char**)alloc_root(&share->mem_root,
 
893
                           (field_options.field_value_size()+1)*sizeof(char*));
 
894
 
 
895
    t->type_lengths= (unsigned int*) alloc_root(&share->mem_root,
 
896
                     (field_options.field_value_size()+1)*sizeof(unsigned int));
 
897
 
 
898
    t->type_names[field_options.field_value_size()]= NULL;
 
899
    t->type_lengths[field_options.field_value_size()]= 0;
 
900
 
 
901
    t->count= field_options.field_value_size();
 
902
    t->name= NULL;
 
903
 
 
904
    for(int n=0; n < field_options.field_value_size(); n++)
 
905
    {
 
906
      t->type_names[n]= strmake_root(&share->mem_root,
 
907
                                     field_options.field_value(n).c_str(),
 
908
                                     field_options.field_value(n).length());
 
909
 
 
910
      /* Go ask the charset what the length is as for "" length=1
 
911
         and there's stripping spaces or some other crack going on.
 
912
       */
 
913
      uint32_t lengthsp;
 
914
      lengthsp= charset->cset->lengthsp(charset, t->type_names[n],
 
915
                                        field_options.field_value(n).length());
 
916
      t->type_lengths[n]= lengthsp;
 
917
    }
 
918
    interval_nr++;
 
919
  }
 
920
 
 
921
 
 
922
  /* and read the fields */
 
923
  interval_nr= 0;
 
924
 
 
925
  bool use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
 
926
 
 
927
  if(use_hash)
 
928
    use_hash= !hash_init(&share->name_hash,
 
929
                         system_charset_info,
 
930
                         share->fields, 0, 0,
 
931
                         (hash_get_key) get_field_name, 0, 0);
 
932
 
 
933
  unsigned char* null_pos= record;;
 
934
  int null_bit_pos= (table_options.pack_record()) ? 0 : 1;
 
935
 
 
936
  for(unsigned int fieldnr=0; fieldnr < share->fields; fieldnr++)
 
937
  {
 
938
    drizzle::Table::Field pfield= table.field(fieldnr);
 
939
 
 
940
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
 
941
 
 
942
    switch(pfield.format())
 
943
    {
 
944
    case drizzle::Table::Field::DefaultFormat:
 
945
      column_format= COLUMN_FORMAT_TYPE_DEFAULT;
 
946
      break;
 
947
    case drizzle::Table::Field::FixedFormat:
 
948
      column_format= COLUMN_FORMAT_TYPE_FIXED;
 
949
      break;
 
950
    case drizzle::Table::Field::DynamicFormat:
 
951
      column_format= COLUMN_FORMAT_TYPE_DYNAMIC;
 
952
      break;
 
953
    default:
 
954
      assert(1);
 
955
    }
 
956
 
 
957
    Field::utype unireg_type= Field::NONE;
 
958
 
 
959
    if(pfield.has_numeric_options()
 
960
       && pfield.numeric_options().is_autoincrement())
 
961
    {
 
962
      unireg_type= Field::NEXT_NUMBER;
 
963
    }
 
964
 
 
965
    if(pfield.has_options()
 
966
       && pfield.options().has_default_value()
 
967
       && pfield.options().default_value().compare("NOW()")==0)
 
968
    {
 
969
      if(pfield.options().has_update_value()
 
970
         && pfield.options().update_value().compare("NOW()")==0)
 
971
      {
 
972
        unireg_type= Field::TIMESTAMP_DNUN_FIELD;
 
973
      }
 
974
      else if (!pfield.options().has_update_value())
 
975
      {
 
976
        unireg_type= Field::TIMESTAMP_DN_FIELD;
 
977
      }
 
978
      else
 
979
        assert(1); // Invalid update value.
 
980
    }
 
981
    else if (pfield.has_options()
 
982
             && pfield.options().has_update_value()
 
983
             && pfield.options().update_value().compare("NOW()")==0)
 
984
    {
 
985
      unireg_type= Field::TIMESTAMP_UN_FIELD;
 
986
    }
 
987
 
 
988
    LEX_STRING comment;
 
989
    if(!pfield.has_comment())
 
990
    {
 
991
      comment.str= (char*)"";
 
992
      comment.length= 0;
 
993
    }
 
994
    else
 
995
    {
 
996
      size_t len= pfield.comment().length();
 
997
      const char* str= pfield.comment().c_str();
 
998
 
 
999
      comment.str= strmake_root(&share->mem_root, str, len);
 
1000
      comment.length= len;
 
1001
    }
 
1002
 
 
1003
    enum_field_types field_type;
 
1004
    virtual_column_info *vcol_info= NULL;
 
1005
    bool field_is_stored= true;
 
1006
 
 
1007
 
 
1008
    field_type= proto_field_type_to_drizzle_type(pfield.type());
 
1009
 
 
1010
    if(field_type==DRIZZLE_TYPE_VIRTUAL)
 
1011
    {
 
1012
      drizzle::Table::Field::VirtualFieldOptions field_options=
 
1013
        pfield.virtual_options();
 
1014
 
 
1015
      vcol_info= new virtual_column_info();
 
1016
      field_type= proto_field_type_to_drizzle_type(field_options.type());
 
1017
      field_is_stored= field_options.physically_stored();
 
1018
 
 
1019
      size_t len= field_options.expression().length();
 
1020
      const char* str= field_options.expression().c_str();
 
1021
 
 
1022
      vcol_info->expr_str.str= strmake_root(&share->mem_root, str, len);
 
1023
      vcol_info->expr_str.length= len;
 
1024
 
 
1025
      share->vfields++;
 
1026
    }
 
1027
 
 
1028
    const CHARSET_INFO *charset= &my_charset_bin;
 
1029
 
 
1030
    if(field_type==DRIZZLE_TYPE_BLOB
 
1031
       || field_type==DRIZZLE_TYPE_VARCHAR)
 
1032
    {
 
1033
      drizzle::Table::Field::StringFieldOptions field_options=
 
1034
        pfield.string_options();
 
1035
 
 
1036
      charset= get_charset(field_options.has_collation_id()?
 
1037
                           field_options.collation_id() : 0);
 
1038
 
 
1039
      if (!charset)
 
1040
        charset= default_charset_info;
 
1041
 
 
1042
    }
 
1043
 
 
1044
    if(field_type==DRIZZLE_TYPE_ENUM)
 
1045
    {
 
1046
      drizzle::Table::Field::SetFieldOptions field_options=
 
1047
        pfield.set_options();
 
1048
 
 
1049
      charset= get_charset(field_options.has_collation_id()?
 
1050
                           field_options.collation_id() : 0);
 
1051
 
 
1052
      if (!charset)
 
1053
        charset= default_charset_info;
 
1054
 
 
1055
    }
 
1056
 
 
1057
    Item *default_value= NULL;
 
1058
 
 
1059
    if(pfield.options().has_default_value()
 
1060
       || pfield.options().has_default_null()
 
1061
       || pfield.options().has_default_bin_value())
 
1062
    {
 
1063
      default_value= default_value_item(field_type,
 
1064
                                        charset,
 
1065
                                        pfield.options().default_null(),
 
1066
                                        pfield.options().default_value(),
 
1067
                                        pfield.options().default_bin_value());
 
1068
    }
 
1069
 
 
1070
    uint32_t pack_flag= pfield.pack_flag(); /* TODO: MUST DIE */
 
1071
 
 
1072
    Table temp_table; /* Use this so that BLOB DEFAULT '' works */
 
1073
    memset(&temp_table, 0, sizeof(temp_table));
 
1074
    temp_table.s= share;
 
1075
    temp_table.in_use= session;
 
1076
    temp_table.s->db_low_byte_first= 1; //handler->low_byte_first();
 
1077
    temp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
 
1078
 
 
1079
    Field* f= make_field(share, &share->mem_root,
 
1080
                         record+field_offsets[fieldnr]+data_offset,
 
1081
                         pfield.options().length(),
 
1082
                         null_pos,
 
1083
                         null_bit_pos,
 
1084
                         pack_flag,
 
1085
                         field_type,
 
1086
                         charset,
 
1087
                         (Field::utype) MTYP_TYPENR(unireg_type),
 
1088
                         ((field_type==DRIZZLE_TYPE_ENUM)?
 
1089
                         share->intervals+(interval_nr++)
 
1090
                         : (TYPELIB*) 0),
 
1091
                        share->fieldnames.type_names[fieldnr]);
 
1092
 
 
1093
    share->field[fieldnr]= f;
 
1094
 
 
1095
    f->init(&temp_table); /* blob default values need table obj */
 
1096
 
 
1097
    if(!(f->flags & NOT_NULL_FLAG))
 
1098
    {
 
1099
      *f->null_ptr|= f->null_bit;
 
1100
      if (!(null_bit_pos= (null_bit_pos + 1) & 7))
 
1101
        null_pos++;
 
1102
      null_count++;
 
1103
    }
 
1104
 
 
1105
    if(default_value)
 
1106
    {
 
1107
      enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
 
1108
      session->count_cuted_fields= CHECK_FIELD_WARN;
 
1109
      int res= default_value->save_in_field(f, 1);
 
1110
      session->count_cuted_fields= old_count_cuted_fields;
 
1111
      if (res != 0 && res != 3)
 
1112
      {
 
1113
        my_error(ER_INVALID_DEFAULT, MYF(0), f->field_name);
 
1114
        error= 1;
 
1115
        goto err;
 
1116
      }
 
1117
    }
 
1118
    else if(f->real_type() == DRIZZLE_TYPE_ENUM &&
 
1119
            (f->flags & NOT_NULL_FLAG))
 
1120
    {
 
1121
      f->set_notnull();
 
1122
      f->store((int64_t) 1, true);
 
1123
    }
 
1124
    else
 
1125
      f->reset();
 
1126
 
 
1127
    /* hack to undo f->init() */
 
1128
    f->table= NULL;
 
1129
    f->orig_table= NULL;
 
1130
 
 
1131
    f->field_index= fieldnr;
 
1132
    f->comment= comment;
 
1133
    f->vcol_info= vcol_info;
 
1134
    f->is_stored= field_is_stored;
 
1135
    if(!default_value
 
1136
       && !(f->unireg_check==Field::NEXT_NUMBER)
 
1137
       && (f->flags & NOT_NULL_FLAG)
 
1138
       && (f->real_type() != DRIZZLE_TYPE_TIMESTAMP))
 
1139
      f->flags|= NO_DEFAULT_VALUE_FLAG;
 
1140
 
 
1141
    if(f->unireg_check == Field::NEXT_NUMBER)
 
1142
      share->found_next_number_field= &(share->field[fieldnr]);
 
1143
 
 
1144
    if(share->timestamp_field == f)
 
1145
      share->timestamp_field_offset= fieldnr;
 
1146
 
 
1147
    if (use_hash) /* supposedly this never fails... but comments lie */
 
1148
      (void) my_hash_insert(&share->name_hash,
 
1149
                            (unsigned char*)&(share->field[fieldnr]));
 
1150
 
 
1151
    if(!f->is_stored)
 
1152
    {
 
1153
      share->stored_fields--;
 
1154
    }
 
1155
  }
 
1156
 
 
1157
  keyinfo= share->key_info;
 
1158
  for (unsigned int keynr=0; keynr < share->keys; keynr++, keyinfo++)
 
1159
  {
 
1160
    key_part= keyinfo->key_part;
 
1161
 
 
1162
    for(unsigned int partnr= 0;
 
1163
        partnr < keyinfo->key_parts;
 
1164
        partnr++, key_part++)
 
1165
    {
 
1166
      /* Fix up key_part->offset by adding data_offset.
 
1167
         We really should compute offset as well.
 
1168
         But at least this way we are a little better. */
 
1169
      key_part->offset= field_offsets[key_part->fieldnr-1] + data_offset;
 
1170
    }
 
1171
  }
 
1172
 
 
1173
  /*
 
1174
    We need to set the unused bits to 1. If the number of bits is a multiple
 
1175
    of 8 there are no unused bits.
 
1176
  */
 
1177
 
 
1178
  if (null_count & 7)
 
1179
    *(record + null_count / 8)|= ~(((unsigned char) 1 << (null_count & 7)) - 1);
 
1180
 
 
1181
  share->null_bytes= (null_pos - (unsigned char*) record +
 
1182
                      (null_bit_pos + 7) / 8);
 
1183
 
 
1184
  share->last_null_bit_pos= null_bit_pos;
 
1185
 
 
1186
  free(field_offsets);
 
1187
  free(field_pack_length);
 
1188
 
 
1189
  if(!(handler_file= get_new_handler(share, session->mem_root,
 
1190
                                     share->db_type())))
 
1191
    abort(); // FIXME
 
1192
 
 
1193
  /* Fix key stuff */
 
1194
  if (share->key_parts)
 
1195
  {
 
1196
    uint32_t primary_key=(uint32_t) (find_type((char*) "PRIMARY",
 
1197
                                       &share->keynames, 3) - 1);
 
1198
 
 
1199
    int64_t ha_option= handler_file->ha_table_flags();
 
1200
 
 
1201
    keyinfo= share->key_info;
 
1202
    key_part= keyinfo->key_part;
 
1203
 
 
1204
    for (uint32_t key=0 ; key < share->keys ; key++,keyinfo++)
 
1205
    {
 
1206
      uint32_t usable_parts= 0;
 
1207
 
 
1208
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
 
1209
      {
 
1210
        /*
 
1211
          If the UNIQUE key doesn't have NULL columns and is not a part key
 
1212
          declare this as a primary key.
 
1213
        */
 
1214
        primary_key=key;
 
1215
        for (uint32_t i=0 ; i < keyinfo->key_parts ;i++)
 
1216
        {
 
1217
          uint32_t fieldnr= key_part[i].fieldnr;
 
1218
          if (!fieldnr ||
 
1219
              share->field[fieldnr-1]->null_ptr ||
 
1220
              share->field[fieldnr-1]->key_length() !=
 
1221
              key_part[i].length)
 
1222
          {
 
1223
            primary_key=MAX_KEY;                // Can't be used
 
1224
            break;
 
1225
          }
 
1226
        }
 
1227
      }
 
1228
 
 
1229
      for (uint32_t i=0 ; i < keyinfo->key_parts ; key_part++,i++)
 
1230
      {
 
1231
        Field *field;
 
1232
        if (!key_part->fieldnr)
 
1233
        {
 
1234
//          error= 4;                             // Wrong file
 
1235
          abort(); // goto err;
 
1236
        }
 
1237
        field= key_part->field= share->field[key_part->fieldnr-1];
 
1238
        key_part->type= field->key_type();
 
1239
        if (field->null_ptr)
 
1240
        {
 
1241
          key_part->null_offset=(uint32_t) ((unsigned char*) field->null_ptr -
 
1242
                                        share->default_values);
 
1243
          key_part->null_bit= field->null_bit;
 
1244
          key_part->store_length+=HA_KEY_NULL_LENGTH;
 
1245
          keyinfo->flags|=HA_NULL_PART_KEY;
 
1246
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
 
1247
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
 
1248
        }
 
1249
        if (field->type() == DRIZZLE_TYPE_BLOB ||
 
1250
            field->real_type() == DRIZZLE_TYPE_VARCHAR)
 
1251
        {
 
1252
          if (field->type() == DRIZZLE_TYPE_BLOB)
 
1253
            key_part->key_part_flag|= HA_BLOB_PART;
 
1254
          else
 
1255
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
 
1256
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
 
1257
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
 
1258
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
 
1259
        }
 
1260
        if (i == 0 && key != primary_key)
 
1261
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
 
1262
                           (keyinfo->key_parts == 1)) ?
 
1263
                           UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
 
1264
        if (i == 0)
 
1265
          field->key_start.set_bit(key);
 
1266
        if (field->key_length() == key_part->length &&
 
1267
            !(field->flags & BLOB_FLAG))
 
1268
        {
 
1269
          if (handler_file->index_flags(key, i, 0) & HA_KEYREAD_ONLY)
 
1270
          {
 
1271
            share->keys_for_keyread.set_bit(key);
 
1272
            field->part_of_key.set_bit(key);
 
1273
            field->part_of_key_not_clustered.set_bit(key);
 
1274
          }
 
1275
          if (handler_file->index_flags(key, i, 1) & HA_READ_ORDER)
 
1276
            field->part_of_sortkey.set_bit(key);
 
1277
        }
 
1278
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
 
1279
            usable_parts == i)
 
1280
          usable_parts++;                       // For FILESORT
 
1281
        field->flags|= PART_KEY_FLAG;
 
1282
        if (key == primary_key)
 
1283
        {
 
1284
          field->flags|= PRI_KEY_FLAG;
 
1285
          /*
 
1286
            If this field is part of the primary key and all keys contains
 
1287
            the primary key, then we can use any key to find this column
 
1288
          */
 
1289
          if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
 
1290
          {
 
1291
            field->part_of_key= share->keys_in_use;
 
1292
            if (field->part_of_sortkey.is_set(key))
 
1293
              field->part_of_sortkey= share->keys_in_use;
 
1294
          }
 
1295
        }
 
1296
        if (field->key_length() != key_part->length)
 
1297
        {
 
1298
          key_part->key_part_flag|= HA_PART_KEY_SEG;
 
1299
        }
 
1300
      }
 
1301
      keyinfo->usable_key_parts= usable_parts; // Filesort
 
1302
 
 
1303
      set_if_bigger(share->max_key_length,keyinfo->key_length+
 
1304
                    keyinfo->key_parts);
 
1305
      share->total_key_length+= keyinfo->key_length;
 
1306
      /*
 
1307
        MERGE tables do not have unique indexes. But every key could be
 
1308
        an unique index on the underlying MyISAM table. (Bug #10400)
 
1309
      */
 
1310
      if ((keyinfo->flags & HA_NOSAME) ||
 
1311
          (ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
 
1312
        set_if_bigger(share->max_unique_length,keyinfo->key_length);
 
1313
    }
 
1314
    if (primary_key < MAX_KEY &&
 
1315
        (share->keys_in_use.is_set(primary_key)))
 
1316
    {
 
1317
      share->primary_key= primary_key;
 
1318
      /*
 
1319
        If we are using an integer as the primary key then allow the user to
 
1320
        refer to it as '_rowid'
 
1321
      */
 
1322
      if (share->key_info[primary_key].key_parts == 1)
 
1323
      {
 
1324
        Field *field= share->key_info[primary_key].key_part[0].field;
 
1325
        if (field && field->result_type() == INT_RESULT)
 
1326
        {
 
1327
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
 
1328
          share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
 
1329
                                      fieldnr);
 
1330
        }
 
1331
      }
 
1332
 
 
1333
    }
 
1334
    else
 
1335
      share->primary_key = MAX_KEY; // we do not have a primary key
 
1336
  }
 
1337
  else
 
1338
    share->primary_key= MAX_KEY;
 
1339
 
 
1340
  if (share->found_next_number_field)
 
1341
  {
 
1342
    Field *reg_field= *share->found_next_number_field;
 
1343
    if ((int) (share->next_number_index= (uint32_t)
 
1344
               find_ref_key(share->key_info, share->keys,
 
1345
                            share->default_values, reg_field,
 
1346
                            &share->next_number_key_offset,
 
1347
                            &share->next_number_keypart)) < 0)
 
1348
    {
 
1349
      /* Wrong field definition */
 
1350
      error= 4;
 
1351
      goto err;
 
1352
    }
 
1353
    else
 
1354
      reg_field->flags |= AUTO_INCREMENT_FLAG;
 
1355
  }
 
1356
 
 
1357
  if (share->blob_fields)
 
1358
  {
 
1359
    Field **ptr;
 
1360
    uint32_t k, *save;
 
1361
 
 
1362
    /* Store offsets to blob fields to find them fast */
 
1363
    if (!(share->blob_field= save=
 
1364
          (uint*) alloc_root(&share->mem_root,
 
1365
                             (uint32_t) (share->blob_fields* sizeof(uint32_t)))))
 
1366
      goto err;
 
1367
    for (k=0, ptr= share->field ; *ptr ; ptr++, k++)
 
1368
    {
 
1369
      if ((*ptr)->flags & BLOB_FLAG)
 
1370
        (*save++)= k;
 
1371
    }
 
1372
  }
 
1373
 
 
1374
  share->db_low_byte_first= handler_file->low_byte_first();
 
1375
  share->column_bitmap_size= bitmap_buffer_size(share->fields);
 
1376
 
 
1377
  my_bitmap_map *bitmaps;
 
1378
 
 
1379
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
 
1380
                                             share->column_bitmap_size)))
 
1381
    goto err;
 
1382
  bitmap_init(&share->all_set, bitmaps, share->fields, false);
 
1383
  bitmap_set_all(&share->all_set);
 
1384
 
 
1385
  if(handler_file)
 
1386
    delete handler_file;
 
1387
  return (0);
 
1388
 
 
1389
err:
 
1390
  share->error= error;
 
1391
  share->open_errno= my_errno;
 
1392
  share->errarg= 0;
 
1393
  hash_free(&share->name_hash);
 
1394
  if(handler_file)
 
1395
    delete handler_file;
 
1396
  open_table_error(share, error, share->open_errno, 0);
 
1397
  return error;
 
1398
}
 
1399
 
 
1400
/*
 
1401
  Read table definition from a binary / text based .frm file
 
1402
 
 
1403
  SYNOPSIS
 
1404
  open_table_def()
 
1405
  session               Thread handler
 
1406
  share         Fill this with table definition
 
1407
  db_flags      Bit mask of the following flags: OPEN_VIEW
 
1408
 
 
1409
  NOTES
 
1410
    This function is called when the table definition is not cached in
 
1411
    table_def_cache
 
1412
    The data is returned in 'share', which is alloced by
 
1413
    alloc_table_share().. The code assumes that share is initialized.
 
1414
 
 
1415
  RETURN VALUES
 
1416
   0    ok
 
1417
   1    Error (see open_table_error)
 
1418
   2    Error (see open_table_error)
 
1419
   3    Wrong data in .frm file
 
1420
   4    Error (see open_table_error)
 
1421
   5    Error (see open_table_error: charset unavailable)
 
1422
   6    Unknown .frm version
 
1423
*/
 
1424
 
 
1425
int open_table_def(Session *session, TABLE_SHARE *share, uint32_t)
 
1426
{
 
1427
  int error;
 
1428
  bool error_given;
 
1429
  string proto_path("");
 
1430
 
 
1431
  error= 1;
 
1432
  error_given= 0;
 
1433
 
 
1434
  proto_path.reserve(FN_REFLEN);
 
1435
  proto_path.append(share->normalized_path.str);
 
1436
 
 
1437
  proto_path.append(".dfe");
 
1438
 
 
1439
  drizzle::Table table;
 
1440
 
 
1441
  if((error= drizzle_read_table_proto(proto_path.c_str(), &table)))
 
1442
  {
 
1443
    if(error>0)
 
1444
    {
 
1445
      my_errno= error;
 
1446
      error= 1;
 
1447
    }
 
1448
    else
 
1449
    {
 
1450
      if(!table.IsInitialized())
 
1451
      {
 
1452
        error= 4;
 
1453
      }
 
1454
    }
 
1455
    goto err_not_open;
 
1456
  }
 
1457
 
 
1458
  error= parse_table_proto(session, table, share);
 
1459
 
 
1460
  share->table_category= get_table_category(& share->db, & share->table_name);
 
1461
 
 
1462
  if (!error)
 
1463
    session->status_var.opened_shares++;
 
1464
 
 
1465
err_not_open:
 
1466
  if (error && !error_given)
 
1467
  {
 
1468
    share->error= error;
 
1469
    open_table_error(share, error, (share->open_errno= my_errno), 0);
 
1470
  }
 
1471
 
 
1472
  return(error);
 
1473
}
 
1474
 
 
1475
/*
 
1476
  Clear flag GET_FIXED_FIELDS_FLAG in all fields of the table.
 
1477
  This routine is used for error handling purposes.
 
1478
 
 
1479
  SYNOPSIS
 
1480
    clear_field_flag()
 
1481
    table                Table object for which virtual columns are set-up
 
1482
 
 
1483
  RETURN VALUE
 
1484
    NONE
 
1485
*/
 
1486
static void clear_field_flag(Table *table)
 
1487
{
 
1488
  Field **ptr;
 
1489
 
 
1490
  for (ptr= table->field; *ptr; ptr++)
 
1491
    (*ptr)->flags&= (~GET_FIXED_FIELDS_FLAG);
 
1492
}
 
1493
 
 
1494
/*
 
1495
  The function uses the feature in fix_fields where the flag
 
1496
  GET_FIXED_FIELDS_FLAG is set for all fields in the item tree.
 
1497
  This field must always be reset before returning from the function
 
1498
  since it is used for other purposes as well.
 
1499
 
 
1500
  SYNOPSIS
 
1501
    fix_fields_vcol_func()
 
1502
    session                  The thread object
 
1503
    func_item            The item tree reference of the virtual columnfunction
 
1504
    table                The table object
 
1505
    field_name           The name of the processed field
 
1506
 
 
1507
  RETURN VALUE
 
1508
    true                 An error occurred, something was wrong with the
 
1509
                         function.
 
1510
    false                Ok, a partition field array was created
 
1511
*/
 
1512
 
 
1513
bool fix_fields_vcol_func(Session *session,
 
1514
                          Item* func_expr,
 
1515
                          Table *table,
 
1516
                          const char *field_name)
 
1517
{
 
1518
  uint32_t dir_length, home_dir_length;
 
1519
  bool result= true;
 
1520
  TableList tables;
 
1521
  TableList *save_table_list, *save_first_table, *save_last_table;
 
1522
  int error;
 
1523
  Name_resolution_context *context;
 
1524
  const char *save_where;
 
1525
  char* db_name;
 
1526
  char db_name_string[FN_REFLEN];
 
1527
  bool save_use_only_table_context;
 
1528
  Field **ptr, *field;
 
1529
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
 
1530
  assert(func_expr);
 
1531
 
 
1532
  /*
 
1533
    Set-up the TABLE_LIST object to be a list with a single table
 
1534
    Set the object to zero to create NULL pointers and set alias
 
1535
    and real name to table name and get database name from file name.
 
1536
  */
 
1537
 
 
1538
  bzero((void*)&tables, sizeof(TableList));
 
1539
  tables.alias= tables.table_name= (char*) table->s->table_name.str;
 
1540
  tables.table= table;
 
1541
  tables.next_local= NULL;
 
1542
  tables.next_name_resolution_table= NULL;
 
1543
  memcpy(db_name_string,
 
1544
         table->s->normalized_path.str,
 
1545
         table->s->normalized_path.length);
 
1546
  db_name_string[table->s->normalized_path.length]= '\0';
 
1547
  dir_length= dirname_length(db_name_string);
 
1548
  db_name_string[dir_length - 1]= 0;
 
1549
  home_dir_length= dirname_length(db_name_string);
 
1550
  db_name= &db_name_string[home_dir_length];
 
1551
  tables.db= db_name;
 
1552
 
 
1553
  session->mark_used_columns= MARK_COLUMNS_NONE;
 
1554
 
 
1555
  context= session->lex->current_context();
 
1556
  table->map= 1; //To ensure correct calculation of const item
 
1557
  table->get_fields_in_item_tree= true;
 
1558
  save_table_list= context->table_list;
 
1559
  save_first_table= context->first_name_resolution_table;
 
1560
  save_last_table= context->last_name_resolution_table;
 
1561
  context->table_list= &tables;
 
1562
  context->first_name_resolution_table= &tables;
 
1563
  context->last_name_resolution_table= NULL;
 
1564
  func_expr->walk(&Item::change_context_processor, 0, (unsigned char*) context);
 
1565
  save_where= session->where;
 
1566
  session->where= "virtual column function";
 
1567
 
 
1568
  /* Save the context before fixing the fields*/
 
1569
  save_use_only_table_context= session->lex->use_only_table_context;
 
1570
  session->lex->use_only_table_context= true;
 
1571
  /* Fix fields referenced to by the virtual column function */
 
1572
  error= func_expr->fix_fields(session, (Item**)0);
 
1573
  /* Restore the original context*/
 
1574
  session->lex->use_only_table_context= save_use_only_table_context;
 
1575
  context->table_list= save_table_list;
 
1576
  context->first_name_resolution_table= save_first_table;
 
1577
  context->last_name_resolution_table= save_last_table;
 
1578
 
 
1579
  if (unlikely(error))
 
1580
  {
 
1581
    clear_field_flag(table);
 
1582
    goto end;
 
1583
  }
 
1584
  session->where= save_where;
 
1585
  /*
 
1586
    Walk through the Item tree checking if all items are valid
 
1587
   to be part of the virtual column
 
1588
 */
 
1589
  error= func_expr->walk(&Item::check_vcol_func_processor, 0, NULL);
 
1590
  if (error)
 
1591
  {
 
1592
    my_error(ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0), field_name);
 
1593
    clear_field_flag(table);
 
1594
    goto end;
 
1595
  }
 
1596
  if (unlikely(func_expr->const_item()))
 
1597
  {
 
1598
    my_error(ER_CONST_EXPR_IN_VCOL, MYF(0));
 
1599
    clear_field_flag(table);
 
1600
    goto end;
 
1601
  }
 
1602
  /* Ensure that this virtual column is not based on another virtual field. */
 
1603
  ptr= table->field;
 
1604
  while ((field= *(ptr++)))
 
1605
  {
 
1606
    if ((field->flags & GET_FIXED_FIELDS_FLAG) &&
 
1607
        (field->vcol_info))
 
1608
    {
 
1609
      my_error(ER_VCOL_BASED_ON_VCOL, MYF(0));
 
1610
      clear_field_flag(table);
 
1611
      goto end;
 
1612
    }
 
1613
  }
 
1614
  /*
 
1615
    Cleanup the fields marked with flag GET_FIXED_FIELDS_FLAG
 
1616
    when calling fix_fields.
 
1617
  */
 
1618
  clear_field_flag(table);
 
1619
  result= false;
 
1620
 
 
1621
end:
 
1622
  table->get_fields_in_item_tree= false;
 
1623
  session->mark_used_columns= save_mark_used_columns;
 
1624
  table->map= 0; //Restore old value
 
1625
  return(result);
 
1626
}
 
1627
 
 
1628
/*
 
1629
  Unpack the definition of a virtual column
 
1630
 
 
1631
  SYNOPSIS
 
1632
    unpack_vcol_info_from_frm()
 
1633
    session                  Thread handler
 
1634
    table                Table with the checked field
 
1635
    field                Pointer to Field object
 
1636
    open_mode            Open table mode needed to determine
 
1637
                         which errors need to be generated in a failure
 
1638
    error_reported       updated flag for the caller that no other error
 
1639
                         messages are to be generated.
 
1640
 
 
1641
  RETURN VALUES
 
1642
    true            Failure
 
1643
    false           Success
 
1644
*/
 
1645
bool unpack_vcol_info_from_frm(Session *session,
 
1646
                               Table *table,
 
1647
                               Field *field,
 
1648
                               LEX_STRING *vcol_expr,
 
1649
                               open_table_mode open_mode,
 
1650
                               bool *error_reported)
 
1651
{
 
1652
  assert(vcol_expr);
 
1653
 
 
1654
  /*
 
1655
    Step 1: Construct a statement for the parser.
 
1656
    The parsed string needs to take the following format:
 
1657
    "PARSE_VCOL_EXPR (<expr_string_from_frm>)"
 
1658
  */
 
1659
  char *vcol_expr_str;
 
1660
  int str_len= 0;
 
1661
 
 
1662
  if (!(vcol_expr_str= (char*) alloc_root(&table->mem_root,
 
1663
                                          vcol_expr->length +
 
1664
                                            parse_vcol_keyword.length + 3)))
 
1665
  {
 
1666
    return(true);
 
1667
  }
 
1668
  memcpy(vcol_expr_str,
 
1669
         (char*) parse_vcol_keyword.str,
 
1670
         parse_vcol_keyword.length);
 
1671
  str_len= parse_vcol_keyword.length;
 
1672
  memcpy(vcol_expr_str + str_len, "(", 1);
 
1673
  str_len++;
 
1674
  memcpy(vcol_expr_str + str_len,
 
1675
         (char*) vcol_expr->str,
 
1676
         vcol_expr->length);
 
1677
  str_len+= vcol_expr->length;
 
1678
  memcpy(vcol_expr_str + str_len, ")", 1);
 
1679
  str_len++;
 
1680
  memcpy(vcol_expr_str + str_len, "\0", 1);
 
1681
  str_len++;
 
1682
  Lex_input_stream lip(session, vcol_expr_str, str_len);
 
1683
 
 
1684
  /*
 
1685
    Step 2: Setup session for parsing.
 
1686
    1) make Item objects be created in the memory allocated for the Table
 
1687
       object (not TABLE_SHARE)
 
1688
    2) ensure that created Item's are not put on to session->free_list
 
1689
       (which is associated with the parsed statement and hence cleared after
 
1690
       the parsing)
 
1691
    3) setup a flag in the LEX structure to allow "PARSE_VCOL_EXPR"
 
1692
       to be parsed as a SQL command.
 
1693
  */
 
1694
  MEM_ROOT **root_ptr, *old_root;
 
1695
  Item *backup_free_list= session->free_list;
 
1696
  root_ptr= current_mem_root_ptr();
 
1697
  old_root= *root_ptr;
 
1698
  *root_ptr= &table->mem_root;
 
1699
  session->free_list= NULL;
 
1700
  session->lex->parse_vcol_expr= true;
 
1701
 
 
1702
  /*
 
1703
    Step 3: Use the parser to build an Item object from.
 
1704
  */
 
1705
  if (parse_sql(session, &lip))
 
1706
  {
 
1707
    goto parse_err;
 
1708
  }
 
1709
  /* From now on use vcol_info generated by the parser. */
 
1710
  field->vcol_info= session->lex->vcol_info;
 
1711
 
 
1712
  /* Validate the Item tree. */
 
1713
  if (fix_fields_vcol_func(session,
 
1714
                           field->vcol_info->expr_item,
 
1715
                           table,
 
1716
                           field->field_name))
 
1717
  {
 
1718
    if (open_mode == OTM_CREATE)
 
1719
    {
 
1720
      /*
 
1721
        During CREATE/ALTER TABLE it is ok to receive errors here.
 
1722
        It is not ok if it happens during the opening of an frm
 
1723
        file as part of a normal query.
 
1724
      */
 
1725
      *error_reported= true;
 
1726
    }
 
1727
    field->vcol_info= NULL;
 
1728
    goto parse_err;
 
1729
  }
 
1730
  field->vcol_info->item_free_list= session->free_list;
 
1731
  session->free_list= backup_free_list;
 
1732
  *root_ptr= old_root;
 
1733
 
 
1734
  return(false);
 
1735
 
 
1736
parse_err:
 
1737
  session->lex->parse_vcol_expr= false;
 
1738
  session->free_items();
 
1739
  *root_ptr= old_root;
 
1740
  session->free_list= backup_free_list;
 
1741
  return(true);
 
1742
}
 
1743
 
 
1744
 
 
1745
/*
 
1746
  Open a table based on a TABLE_SHARE
 
1747
 
 
1748
  SYNOPSIS
 
1749
    open_table_from_share()
 
1750
    session                     Thread handler
 
1751
    share               Table definition
 
1752
    alias               Alias for table
 
1753
    db_stat             open flags (for example HA_OPEN_KEYFILE|
 
1754
                        HA_OPEN_RNDFILE..) can be 0 (example in
 
1755
                        ha_example_table)
 
1756
    prgflag             READ_ALL etc..
 
1757
    ha_open_flags       HA_OPEN_ABORT_IF_LOCKED etc..
 
1758
    outparam            result table
 
1759
    open_mode           One of OTM_OPEN|OTM_CREATE|OTM_ALTER
 
1760
                        if OTM_CREATE some errors are ignore
 
1761
                        if OTM_ALTER HA_OPEN is not called
 
1762
 
 
1763
  RETURN VALUES
 
1764
   0    ok
 
1765
   1    Error (see open_table_error)
 
1766
   2    Error (see open_table_error)
 
1767
   3    Wrong data in .frm file
 
1768
   4    Error (see open_table_error)
 
1769
   5    Error (see open_table_error: charset unavailable)
 
1770
   7    Table definition has changed in engine
 
1771
*/
 
1772
 
 
1773
int open_table_from_share(Session *session, TABLE_SHARE *share, const char *alias,
 
1774
                          uint32_t db_stat, uint32_t prgflag, uint32_t ha_open_flags,
 
1775
                          Table *outparam, open_table_mode open_mode)
 
1776
{
 
1777
  int error;
 
1778
  uint32_t records, i, bitmap_size;
 
1779
  bool error_reported= false;
 
1780
  unsigned char *record, *bitmaps;
 
1781
  Field **field_ptr, **vfield_ptr;
 
1782
 
 
1783
  /* Parsing of partitioning information from .frm needs session->lex set up. */
 
1784
  assert(session->lex->is_lex_started);
 
1785
 
 
1786
  error= 1;
 
1787
  memset(outparam, 0, sizeof(*outparam));
 
1788
  outparam->in_use= session;
 
1789
  outparam->s= share;
 
1790
  outparam->db_stat= db_stat;
 
1791
  outparam->write_row_record= NULL;
 
1792
 
 
1793
  init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
1794
 
 
1795
  if (!(outparam->alias= strdup(alias)))
 
1796
    goto err;
 
1797
  outparam->quick_keys.init();
 
1798
  outparam->covering_keys.init();
 
1799
  outparam->keys_in_use_for_query.init();
 
1800
 
 
1801
  /* Allocate handler */
 
1802
  outparam->file= 0;
 
1803
  if (!(prgflag & OPEN_FRM_FILE_ONLY))
 
1804
  {
 
1805
    if (!(outparam->file= get_new_handler(share, &outparam->mem_root,
 
1806
                                          share->db_type())))
 
1807
      goto err;
 
1808
  }
 
1809
  else
 
1810
  {
 
1811
    assert(!db_stat);
 
1812
  }
 
1813
 
 
1814
  error= 4;
 
1815
  outparam->reginfo.lock_type= TL_UNLOCK;
 
1816
  outparam->current_lock= F_UNLCK;
 
1817
  records=0;
 
1818
  if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
 
1819
    records=1;
 
1820
  if (prgflag & (READ_ALL+EXTRA_RECORD))
 
1821
    records++;
 
1822
 
 
1823
  if (!(record= (unsigned char*) alloc_root(&outparam->mem_root,
 
1824
                                   share->rec_buff_length * records)))
 
1825
    goto err;                                   /* purecov: inspected */
 
1826
 
 
1827
  if (records == 0)
 
1828
  {
 
1829
    /* We are probably in hard repair, and the buffers should not be used */
 
1830
    outparam->record[0]= outparam->record[1]= share->default_values;
 
1831
  }
 
1832
  else
 
1833
  {
 
1834
    outparam->record[0]= record;
 
1835
    if (records > 1)
 
1836
      outparam->record[1]= record+ share->rec_buff_length;
 
1837
    else
 
1838
      outparam->record[1]= outparam->record[0];   // Safety
 
1839
  }
 
1840
 
 
1841
#ifdef HAVE_purify
 
1842
  /*
 
1843
    We need this because when we read var-length rows, we are not updating
 
1844
    bytes after end of varchar
 
1845
  */
 
1846
  if (records > 1)
 
1847
  {
 
1848
    memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
 
1849
    memcpy(outparam->record[1], share->default_values, share->null_bytes);
 
1850
    if (records > 2)
 
1851
      memcpy(outparam->record[1], share->default_values,
 
1852
             share->rec_buff_length);
 
1853
  }
 
1854
#endif
 
1855
 
 
1856
  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
 
1857
                                          (uint32_t) ((share->fields+1)*
 
1858
                                                  sizeof(Field*)))))
 
1859
    goto err;                                   /* purecov: inspected */
 
1860
 
 
1861
  outparam->field= field_ptr;
 
1862
 
 
1863
  record= (unsigned char*) outparam->record[0]-1;       /* Fieldstart = 1 */
 
1864
 
 
1865
  outparam->null_flags= (unsigned char*) record+1;
 
1866
 
 
1867
  /* Setup copy of fields from share, but use the right alias and record */
 
1868
  for (i=0 ; i < share->fields; i++, field_ptr++)
 
1869
  {
 
1870
    if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
 
1871
      goto err;
 
1872
  }
 
1873
  (*field_ptr)= 0;                              // End marker
 
1874
 
 
1875
  if (share->found_next_number_field)
 
1876
    outparam->found_next_number_field=
 
1877
      outparam->field[(uint32_t) (share->found_next_number_field - share->field)];
 
1878
  if (share->timestamp_field)
 
1879
    outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
 
1880
 
 
1881
 
 
1882
  /* Fix key->name and key_part->field */
 
1883
  if (share->key_parts)
 
1884
  {
 
1885
    KEY *key_info, *key_info_end;
 
1886
    KEY_PART_INFO *key_part;
 
1887
    uint32_t n_length;
 
1888
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
 
1889
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
 
1890
      goto err;
 
1891
    outparam->key_info= key_info;
 
1892
    key_part= (reinterpret_cast<KEY_PART_INFO*> (key_info+share->keys));
 
1893
 
 
1894
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
 
1895
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
 
1896
                                                   share->key_parts));
 
1897
 
 
1898
    for (key_info_end= key_info + share->keys ;
 
1899
         key_info < key_info_end ;
 
1900
         key_info++)
 
1901
    {
 
1902
      KEY_PART_INFO *key_part_end;
 
1903
 
 
1904
      key_info->table= outparam;
 
1905
      key_info->key_part= key_part;
 
1906
 
 
1907
      for (key_part_end= key_part+ key_info->key_parts ;
 
1908
           key_part < key_part_end ;
 
1909
           key_part++)
 
1910
      {
 
1911
        Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
 
1912
 
 
1913
        if (field->key_length() != key_part->length &&
 
1914
            !(field->flags & BLOB_FLAG))
 
1915
        {
 
1916
          /*
 
1917
            We are using only a prefix of the column as a key:
 
1918
            Create a new field for the key part that matches the index
 
1919
          */
 
1920
          field= key_part->field=field->new_field(&outparam->mem_root,
 
1921
                                                  outparam, 0);
 
1922
          field->field_length= key_part->length;
 
1923
        }
 
1924
      }
 
1925
    }
 
1926
  }
 
1927
 
 
1928
  /*
 
1929
    Process virtual columns, if any.
 
1930
  */
 
1931
  if (not (vfield_ptr = (Field **) alloc_root(&outparam->mem_root,
 
1932
                                              (uint32_t) ((share->vfields+1)*
 
1933
                                                      sizeof(Field*)))))
 
1934
    goto err;
 
1935
 
 
1936
  outparam->vfield= vfield_ptr;
 
1937
 
 
1938
  for (field_ptr= outparam->field; *field_ptr; field_ptr++)
 
1939
  {
 
1940
    if ((*field_ptr)->vcol_info)
 
1941
    {
 
1942
      if (unpack_vcol_info_from_frm(session,
 
1943
                                    outparam,
 
1944
                                    *field_ptr,
 
1945
                                    &(*field_ptr)->vcol_info->expr_str,
 
1946
                                    open_mode,
 
1947
                                    &error_reported))
 
1948
      {
 
1949
        error= 4; // in case no error is reported
 
1950
        goto err;
 
1951
      }
 
1952
      *(vfield_ptr++)= *field_ptr;
 
1953
    }
 
1954
  }
 
1955
  *vfield_ptr= NULL;                              // End marker
 
1956
  /* Check virtual columns against table's storage engine. */
 
1957
  if ((share->vfields && outparam->file) &&
 
1958
        (not outparam->file->check_if_supported_virtual_columns()))
 
1959
  {
 
1960
    my_error(ER_UNSUPPORTED_ACTION_ON_VIRTUAL_COLUMN,
 
1961
             MYF(0),
 
1962
             "Specified storage engine");
 
1963
    error_reported= true;
 
1964
    goto err;
 
1965
  }
 
1966
 
 
1967
  /* Allocate bitmaps */
 
1968
 
 
1969
  bitmap_size= share->column_bitmap_size;
 
1970
  if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
 
1971
    goto err;
 
1972
  bitmap_init(&outparam->def_read_set,
 
1973
              (my_bitmap_map*) bitmaps, share->fields, false);
 
1974
  bitmap_init(&outparam->def_write_set,
 
1975
              (my_bitmap_map*) (bitmaps+bitmap_size), share->fields, false);
 
1976
  bitmap_init(&outparam->tmp_set,
 
1977
              (my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, false);
 
1978
  outparam->default_column_bitmaps();
 
1979
 
 
1980
  /* The table struct is now initialized;  Open the table */
 
1981
  error= 2;
 
1982
  if (db_stat && open_mode != OTM_ALTER)
 
1983
  {
 
1984
    int ha_err;
 
1985
    if ((ha_err= (outparam->file->
 
1986
                  ha_open(outparam, share->normalized_path.str,
 
1987
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
 
1988
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
 
1989
                           (db_stat & HA_WAIT_IF_LOCKED) ?  HA_OPEN_WAIT_IF_LOCKED :
 
1990
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
 
1991
                          HA_OPEN_ABORT_IF_LOCKED :
 
1992
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
 
1993
    {
 
1994
      /* Set a flag if the table is crashed and it can be auto. repaired */
 
1995
      share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
 
1996
                       outparam->file->auto_repair() &&
 
1997
                       !(ha_open_flags & HA_OPEN_FOR_REPAIR));
 
1998
 
 
1999
      switch (ha_err)
 
2000
      {
 
2001
        case HA_ERR_NO_SUCH_TABLE:
 
2002
          /*
 
2003
            The table did not exists in storage engine, use same error message
 
2004
            as if the .frm file didn't exist
 
2005
          */
 
2006
          error= 1;
 
2007
          my_errno= ENOENT;
 
2008
          break;
 
2009
        case EMFILE:
 
2010
          /*
 
2011
            Too many files opened, use same error message as if the .frm
 
2012
            file can't open
 
2013
           */
 
2014
          error= 1;
 
2015
          my_errno= EMFILE;
 
2016
          break;
 
2017
        default:
 
2018
          outparam->file->print_error(ha_err, MYF(0));
 
2019
          error_reported= true;
 
2020
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
 
2021
            error= 7;
 
2022
          break;
 
2023
      }
 
2024
      goto err;                                 /* purecov: inspected */
 
2025
    }
 
2026
  }
 
2027
 
 
2028
#if defined(HAVE_purify)
 
2029
  memset(bitmaps, 0, bitmap_size*3);
 
2030
#endif
 
2031
 
 
2032
  outparam->no_replicate= outparam->file;
 
2033
  session->status_var.opened_tables++;
 
2034
 
 
2035
  return (0);
 
2036
 
 
2037
 err:
 
2038
  if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
 
2039
    open_table_error(share, error, my_errno, 0);
 
2040
  delete outparam->file;
 
2041
  outparam->file= 0;                            // For easier error checking
 
2042
  outparam->db_stat=0;
 
2043
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on zeroed root
 
2044
  free((char*) outparam->alias);
 
2045
  return (error);
 
2046
}
 
2047
 
 
2048
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
 
2049
uint32_t  Table::tmpkeyval()
 
2050
{
 
2051
  return uint4korr(s->table_cache_key.str + s->table_cache_key.length - 4);
 
2052
}
 
2053
 
 
2054
/*
 
2055
  Free information allocated by openfrm
 
2056
 
 
2057
  SYNOPSIS
 
2058
    closefrm()
 
2059
    table               Table object to free
 
2060
    free_share          Is 1 if we also want to free table_share
 
2061
*/
 
2062
 
 
2063
int Table::closefrm(bool free_share)
 
2064
{
 
2065
  int error=0;
81
2066
 
82
2067
  if (db_stat)
83
 
    error= cursor->close();
84
 
  _alias.clear();
85
 
 
 
2068
    error= file->close();
 
2069
  free((char*) alias);
 
2070
  alias= NULL;
86
2071
  if (field)
87
2072
  {
88
2073
    for (Field **ptr=field ; *ptr ; ptr++)
89
 
    {
90
2074
      delete *ptr;
91
 
    }
92
2075
    field= 0;
93
2076
  }
94
 
  safe_delete(cursor);
95
 
 
 
2077
  delete file;
 
2078
  file= 0;                              /* For easier errorchecking */
96
2079
  if (free_share)
97
2080
  {
98
 
    release();
 
2081
    if (s->tmp_table == NO_TMP_TABLE)
 
2082
      release_table_share(s, RELEASE_NORMAL);
 
2083
    else
 
2084
      free_table_share(s);
99
2085
  }
 
2086
  free_root(&mem_root, MYF(0));
100
2087
 
101
2088
  return error;
102
2089
}
103
2090
 
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
 
  in_use= session;
116
 
 
117
 
  field= NULL;
118
 
 
119
 
  cursor= NULL;
120
 
  next= NULL;
121
 
  prev= NULL;
122
 
 
123
 
  read_set= NULL;
124
 
  write_set= NULL;
125
 
 
126
 
  tablenr= 0;
127
 
  db_stat= db_stat_arg;
128
 
 
129
 
  record[0]= (unsigned char *) NULL;
130
 
  record[1]= (unsigned char *) NULL;
131
 
 
132
 
  insert_values.clear();
133
 
  key_info= NULL;
134
 
  next_number_field= NULL;
135
 
  found_next_number_field= NULL;
136
 
  timestamp_field= NULL;
137
 
 
138
 
  pos_in_table_list= NULL;
139
 
  group= NULL;
140
 
  _alias.clear();
141
 
  null_flags= NULL;
142
 
 
143
 
  lock_position= 0;
144
 
  lock_data_start= 0;
145
 
  lock_count= 0;
146
 
  used_fields= 0;
147
 
  status= 0;
148
 
  derived_select_number= 0;
149
 
  current_lock= F_UNLCK;
150
 
  copy_blobs= false;
151
 
 
152
 
  maybe_null= false;
153
 
 
154
 
  null_row= false;
155
 
 
156
 
  force_index= false;
157
 
  distinct= false;
158
 
  const_table= false;
159
 
  no_rows= false;
160
 
  key_read= false;
161
 
  no_keyread= false;
162
 
 
163
 
  open_placeholder= false;
164
 
  locked_by_name= false;
165
 
  no_cache= false;
166
 
 
167
 
  auto_increment_field_not_null= false;
168
 
  alias_name_used= false;
169
 
 
170
 
  query_id= 0;
171
 
  quick_condition_rows= 0;
172
 
 
173
 
  timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
174
 
  map= 0;
175
 
 
176
 
  reginfo.reset();
177
 
 
178
 
  covering_keys.reset();
179
 
 
180
 
  quick_keys.reset();
181
 
  merge_keys.reset();
182
 
 
183
 
  keys_in_use_for_query.reset();
184
 
  keys_in_use_for_group_by.reset();
185
 
  keys_in_use_for_order_by.reset();
186
 
 
187
 
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
188
 
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
189
 
 
190
 
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
191
 
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
192
 
 
193
 
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
194
 
}
195
 
 
196
 
 
197
2091
 
198
2092
/* Deallocate temporary blob storage */
199
2093
 
200
 
void free_blobs(Table *table)
 
2094
void free_blobs(register Table *table)
201
2095
{
202
2096
  uint32_t *ptr, *end;
203
2097
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
204
2098
       ptr != end ;
205
2099
       ptr++)
206
 
  {
207
 
    ((Field_blob*) table->getField(*ptr))->free();
208
 
  }
209
 
}
210
 
 
211
 
 
212
 
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
213
 
{
214
 
  TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
 
2100
    ((Field_blob*) table->field[*ptr])->free();
 
2101
}
 
2102
 
 
2103
 
 
2104
        /* Find where a form starts */
 
2105
        /* if formname is NULL then only formnames is read */
 
2106
 
 
2107
ulong get_form_pos(File file, unsigned char *head, TYPELIB *save_names)
 
2108
{
 
2109
  uint32_t a_length,names,length;
 
2110
  unsigned char *pos,*buf;
 
2111
  ulong ret_value=0;
 
2112
 
 
2113
  names=uint2korr(head+8);
 
2114
  a_length=(names+2)*sizeof(char *);            /* Room for two extra */
 
2115
 
 
2116
  if (!save_names)
 
2117
    a_length=0;
 
2118
  else
 
2119
    save_names->type_names=0;                   /* Clear if error */
 
2120
 
 
2121
  if (names)
 
2122
  {
 
2123
    length=uint2korr(head+4);
 
2124
    lseek(file,64,SEEK_SET);
 
2125
    if (!(buf= (unsigned char*) malloc(length+a_length+names*4)) ||
 
2126
        my_read(file, buf+a_length, (size_t) (length+names*4),
 
2127
                MYF(MY_NABP)))
 
2128
    {                                           /* purecov: inspected */
 
2129
      if (buf)
 
2130
        free(buf);
 
2131
      return(0L);                               /* purecov: inspected */
 
2132
    }
 
2133
    pos= buf+a_length+length;
 
2134
    ret_value=uint4korr(pos);
 
2135
  }
 
2136
  if (! save_names)
 
2137
  {
 
2138
    if (names)
 
2139
      free((unsigned char*) buf);
 
2140
  }
 
2141
  else if (!names)
 
2142
    memset(save_names, 0, sizeof(save_names));
 
2143
  else
 
2144
  {
 
2145
    char *str;
 
2146
    str=(char *) (buf+a_length);
 
2147
    fix_type_pointers((const char ***) &buf,save_names,1,&str);
 
2148
  }
 
2149
  return(ret_value);
 
2150
}
 
2151
 
 
2152
 
 
2153
/*
 
2154
  Read string from a file with malloc
 
2155
 
 
2156
  NOTES:
 
2157
    We add an \0 at end of the read string to make reading of C strings easier
 
2158
*/
 
2159
 
 
2160
int read_string(File file, unsigned char**to, size_t length)
 
2161
{
 
2162
 
 
2163
  if (*to)
 
2164
    free(*to);
 
2165
  if (!(*to= (unsigned char*) malloc(length+1)) ||
 
2166
      my_read(file, *to, length,MYF(MY_NABP)))
 
2167
  {
 
2168
    if (*to)
 
2169
      free(*to);
 
2170
    *to= NULL;
 
2171
    return(1);                           /* purecov: inspected */
 
2172
  }
 
2173
  *((char*) *to+length)= '\0';
 
2174
  return (0);
 
2175
} /* read_string */
 
2176
 
 
2177
 
 
2178
        /* Add a new form to a form file */
 
2179
 
 
2180
off_t make_new_entry(File file, unsigned char *fileinfo, TYPELIB *formnames,
 
2181
                     const char *newname)
 
2182
{
 
2183
  uint32_t i,bufflength,maxlength,n_length,length,names;
 
2184
  off_t endpos,newpos;
 
2185
  unsigned char buff[IO_SIZE];
 
2186
  unsigned char *pos;
 
2187
 
 
2188
  length=(uint32_t) strlen(newname)+1;
 
2189
  n_length=uint2korr(fileinfo+4);
 
2190
  maxlength=uint2korr(fileinfo+6);
 
2191
  names=uint2korr(fileinfo+8);
 
2192
  newpos=uint4korr(fileinfo+10);
 
2193
 
 
2194
  if (64+length+n_length+(names+1)*4 > maxlength)
 
2195
  {                                             /* Expand file */
 
2196
    newpos+=IO_SIZE;
 
2197
    int4store(fileinfo+10,newpos);
 
2198
    endpos= lseek(file,0,SEEK_END);/* Copy from file-end */
 
2199
    bufflength= (uint32_t) (endpos & (IO_SIZE-1));      /* IO_SIZE is a power of 2 */
 
2200
 
 
2201
    while (endpos > maxlength)
 
2202
    {
 
2203
      lseek(file,(off_t) (endpos-bufflength),SEEK_SET);
 
2204
      if (my_read(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
 
2205
        return(0L);
 
2206
      lseek(file,(off_t) (endpos-bufflength+IO_SIZE),SEEK_SET);
 
2207
      if ((my_write(file, buff,bufflength,MYF(MY_NABP+MY_WME))))
 
2208
        return(0);
 
2209
      endpos-=bufflength; bufflength=IO_SIZE;
 
2210
    }
 
2211
    memset(buff, 0, IO_SIZE);                   /* Null new block */
 
2212
    lseek(file,(ulong) maxlength,SEEK_SET);
 
2213
    if (my_write(file,buff,bufflength,MYF(MY_NABP+MY_WME)))
 
2214
      return(0L);
 
2215
    maxlength+=IO_SIZE;                         /* Fix old ref */
 
2216
    int2store(fileinfo+6,maxlength);
 
2217
    for (i=names, pos= (unsigned char*) *formnames->type_names+n_length-1; i--;
 
2218
         pos+=4)
 
2219
    {
 
2220
      endpos=uint4korr(pos)+IO_SIZE;
 
2221
      int4store(pos,endpos);
 
2222
    }
 
2223
  }
 
2224
 
 
2225
  if (n_length == 1 )
 
2226
  {                                             /* First name */
 
2227
    length++;
 
2228
    sprintf((char*)buff,"/%s/",newname);
 
2229
  }
 
2230
  else
 
2231
    sprintf((char*)buff,"%s/",newname); /* purecov: inspected */
 
2232
  lseek(file, 63 + n_length,SEEK_SET);
 
2233
  if (my_write(file, buff, (size_t) length+1,MYF(MY_NABP+MY_WME)) ||
 
2234
      (names && my_write(file,(unsigned char*) (*formnames->type_names+n_length-1),
 
2235
                         names*4, MYF(MY_NABP+MY_WME))) ||
 
2236
      my_write(file, fileinfo+10, 4,MYF(MY_NABP+MY_WME)))
 
2237
    return(0L); /* purecov: inspected */
 
2238
 
 
2239
  int2store(fileinfo+8,names+1);
 
2240
  int2store(fileinfo+4,n_length+length);
 
2241
  assert(ftruncate(file, newpos)==0);/* Append file with '\0' */
 
2242
  return(newpos);
 
2243
} /* make_new_entry */
 
2244
 
 
2245
 
 
2246
        /* error message when opening a form file */
 
2247
 
 
2248
void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
 
2249
{
 
2250
  int err_no;
 
2251
  char buff[FN_REFLEN];
 
2252
  myf errortype= ME_ERROR+ME_WAITTANG;
 
2253
 
 
2254
  switch (error) {
 
2255
  case 7:
 
2256
  case 1:
 
2257
    if (db_errno == ENOENT)
 
2258
      my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
 
2259
    else
 
2260
    {
 
2261
      sprintf(buff,"%s",share->normalized_path.str);
 
2262
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
 
2263
               errortype, buff, db_errno);
 
2264
    }
 
2265
    break;
 
2266
  case 2:
 
2267
  {
 
2268
    handler *file= 0;
 
2269
    const char *datext= "";
 
2270
 
 
2271
    if (share->db_type() != NULL)
 
2272
    {
 
2273
      if ((file= get_new_handler(share, current_session->mem_root,
 
2274
                                 share->db_type())))
 
2275
      {
 
2276
        if (!(datext= *file->bas_ext()))
 
2277
          datext= "";
 
2278
      }
 
2279
    }
 
2280
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
 
2281
      ER_FILE_USED : ER_CANT_OPEN_FILE;
 
2282
    sprintf(buff,"%s%s", share->normalized_path.str,datext);
 
2283
    my_error(err_no,errortype, buff, db_errno);
 
2284
    delete file;
 
2285
    break;
 
2286
  }
 
2287
  case 5:
 
2288
  {
 
2289
    const char *csname= get_charset_name((uint32_t) errarg);
 
2290
    char tmp[10];
 
2291
    if (!csname || csname[0] =='?')
 
2292
    {
 
2293
      snprintf(tmp, sizeof(tmp), "#%d", errarg);
 
2294
      csname= tmp;
 
2295
    }
 
2296
    my_printf_error(ER_UNKNOWN_COLLATION,
 
2297
                    _("Unknown collation '%s' in table '%-.64s' definition"),
 
2298
                    MYF(0), csname, share->table_name.str);
 
2299
    break;
 
2300
  }
 
2301
  case 6:
 
2302
    sprintf(buff,"%s",share->normalized_path.str);
 
2303
    my_printf_error(ER_NOT_FORM_FILE,
 
2304
                    _("Table '%-.64s' was created with a different version "
 
2305
                    "of Drizzle and cannot be read"),
 
2306
                    MYF(0), buff);
 
2307
    break;
 
2308
  case 8:
 
2309
    break;
 
2310
  default:                              /* Better wrong error than none */
 
2311
  case 4:
 
2312
    sprintf(buff,"%s",share->normalized_path.str);
 
2313
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
 
2314
    break;
 
2315
  }
 
2316
  return;
 
2317
} /* open_table_error */
 
2318
 
 
2319
 
 
2320
        /*
 
2321
        ** fix a str_type to a array type
 
2322
        ** typeparts separated with some char. differents types are separated
 
2323
        ** with a '\0'
 
2324
        */
 
2325
 
 
2326
static void
 
2327
fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint32_t types,
 
2328
                  char **names)
 
2329
{
 
2330
  char *type_name, *ptr;
 
2331
  char chr;
 
2332
 
 
2333
  ptr= *names;
 
2334
  while (types--)
 
2335
  {
 
2336
    point_to_type->name=0;
 
2337
    point_to_type->type_names= *array;
 
2338
 
 
2339
    if ((chr= *ptr))                    /* Test if empty type */
 
2340
    {
 
2341
      while ((type_name=strchr(ptr+1,chr)) != NULL)
 
2342
      {
 
2343
        *((*array)++) = ptr+1;
 
2344
        *type_name= '\0';               /* End string */
 
2345
        ptr=type_name;
 
2346
      }
 
2347
      ptr+=2;                           /* Skip end mark and last 0 */
 
2348
    }
 
2349
    else
 
2350
      ptr++;
 
2351
    point_to_type->count= (uint32_t) (*array - point_to_type->type_names);
 
2352
    point_to_type++;
 
2353
    *((*array)++)= NULL;                /* End of type */
 
2354
  }
 
2355
  *names=ptr;                           /* Update end */
 
2356
  return;
 
2357
} /* fix_type_pointers */
 
2358
 
 
2359
 
 
2360
TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
 
2361
{
 
2362
  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
215
2363
  if (!result)
216
2364
    return 0;
217
 
  result->count= strings.elements;
218
 
  result->name= "";
 
2365
  result->count=strings.elements;
 
2366
  result->name="";
219
2367
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
220
 
  
221
 
  if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
 
2368
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
222
2369
    return 0;
223
 
    
224
2370
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
225
 
 
226
 
  List<String>::iterator it(strings.begin());
 
2371
  List_iterator<String> it(strings);
227
2372
  String *tmp;
228
 
  for (uint32_t i= 0; (tmp= it++); i++)
 
2373
  for (uint32_t i=0; (tmp=it++) ; i++)
229
2374
  {
230
2375
    result->type_names[i]= tmp->ptr();
231
2376
    result->type_lengths[i]= tmp->length();
232
2377
  }
233
 
 
234
 
  result->type_names[result->count]= 0;   // End marker
 
2378
  result->type_names[result->count]= 0;         // End marker
235
2379
  result->type_lengths[result->count]= 0;
236
 
 
237
2380
  return result;
238
2381
}
239
2382
 
240
2383
        /* Check that the integer is in the internal */
241
2384
 
242
 
int set_zone(int nr, int min_zone, int max_zone)
 
2385
int set_zone(register int nr, int min_zone, int max_zone)
243
2386
{
244
2387
  if (nr<=min_zone)
245
2388
    return (min_zone);
248
2391
  return (nr);
249
2392
} /* set_zone */
250
2393
 
 
2394
        /* Adjust number to next larger disk buffer */
 
2395
 
 
2396
ulong next_io_size(register ulong pos)
 
2397
{
 
2398
  register ulong offset;
 
2399
  if ((offset= pos & (IO_SIZE-1)))
 
2400
    return pos-offset+IO_SIZE;
 
2401
  return pos;
 
2402
} /* next_io_size */
 
2403
 
251
2404
 
252
2405
/*
253
2406
  Store an SQL quoted string.
270
2423
 
271
2424
  for (; pos != end ; pos++)
272
2425
  {
 
2426
#if defined(USE_MB)
273
2427
    uint32_t mblen;
274
2428
    if (use_mb(default_charset_info) &&
275
2429
        (mblen= my_ismbchar(default_charset_info, pos, end)))
276
2430
    {
277
2431
      res->append(pos, mblen);
278
 
      pos+= mblen - 1;
 
2432
      pos+= mblen;
279
2433
      if (pos >= end)
280
2434
        break;
281
2435
      continue;
282
2436
    }
 
2437
#endif
283
2438
 
284
2439
    switch (*pos) {
285
2440
    case 0:                             /* Must be escaped for 'mysql' */
311
2466
}
312
2467
 
313
2468
 
 
2469
/*
 
2470
  Set up column usage bitmaps for a temporary table
 
2471
 
 
2472
  IMPLEMENTATION
 
2473
    For temporary tables, we need one bitmap with all columns set and
 
2474
    a tmp_set bitmap to be used by things like filesort.
 
2475
*/
 
2476
 
 
2477
void Table::setup_tmp_table_column_bitmaps(unsigned char *bitmaps)
 
2478
{
 
2479
  uint32_t field_count= s->fields;
 
2480
 
 
2481
  bitmap_init(&this->def_read_set, (my_bitmap_map*) bitmaps, field_count, false);
 
2482
  bitmap_init(&this->tmp_set, (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)), field_count, false);
 
2483
 
 
2484
  /* write_set and all_set are copies of read_set */
 
2485
  def_write_set= def_read_set;
 
2486
  s->all_set= def_read_set;
 
2487
  bitmap_set_all(&this->s->all_set);
 
2488
  default_column_bitmaps();
 
2489
}
 
2490
 
 
2491
 
 
2492
 
 
2493
void Table::updateCreateInfo(HA_CREATE_INFO *create_info)
 
2494
{
 
2495
  create_info->max_rows= s->max_rows;
 
2496
  create_info->min_rows= s->min_rows;
 
2497
  create_info->table_options= s->db_create_options;
 
2498
  create_info->avg_row_length= s->avg_row_length;
 
2499
  create_info->block_size= s->block_size;
 
2500
  create_info->row_type= s->row_type;
 
2501
  create_info->default_table_charset= s->table_charset;
 
2502
  create_info->table_charset= 0;
 
2503
  create_info->comment= s->comment;
 
2504
 
 
2505
  return;
 
2506
}
 
2507
 
314
2508
int rename_file_ext(const char * from,const char * to,const char * ext)
315
2509
{
316
2510
  string from_s, to_s;
319
2513
  from_s.append(ext);
320
2514
  to_s.append(to);
321
2515
  to_s.append(ext);
322
 
  return (internal::my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
323
 
}
 
2516
  return (my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
 
2517
}
 
2518
 
 
2519
 
 
2520
/*
 
2521
  Allocate string field in MEM_ROOT and return it as String
 
2522
 
 
2523
  SYNOPSIS
 
2524
    get_field()
 
2525
    mem         MEM_ROOT for allocating
 
2526
    field       Field for retrieving of string
 
2527
    res         result String
 
2528
 
 
2529
  RETURN VALUES
 
2530
    1   string is empty
 
2531
    0   all ok
 
2532
*/
 
2533
 
 
2534
bool get_field(MEM_ROOT *mem, Field *field, String *res)
 
2535
{
 
2536
  char buff[MAX_FIELD_WIDTH], *to;
 
2537
  String str(buff,sizeof(buff),&my_charset_bin);
 
2538
  uint32_t length;
 
2539
 
 
2540
  field->val_str(&str);
 
2541
  if (!(length= str.length()))
 
2542
  {
 
2543
    res->length(0);
 
2544
    return 1;
 
2545
  }
 
2546
  if (!(to= strmake_root(mem, str.ptr(), length)))
 
2547
    length= 0;                                  // Safety fix
 
2548
  res->set(to, length, ((Field_str*)field)->charset());
 
2549
  return 0;
 
2550
}
 
2551
 
 
2552
 
 
2553
/*
 
2554
  Allocate string field in MEM_ROOT and return it as NULL-terminated string
 
2555
 
 
2556
  SYNOPSIS
 
2557
    get_field()
 
2558
    mem         MEM_ROOT for allocating
 
2559
    field       Field for retrieving of string
 
2560
 
 
2561
  RETURN VALUES
 
2562
    NULL  string is empty
 
2563
    #      pointer to NULL-terminated string value of field
 
2564
*/
 
2565
 
 
2566
char *get_field(MEM_ROOT *mem, Field *field)
 
2567
{
 
2568
  char buff[MAX_FIELD_WIDTH], *to;
 
2569
  String str(buff,sizeof(buff),&my_charset_bin);
 
2570
  uint32_t length;
 
2571
 
 
2572
  field->val_str(&str);
 
2573
  length= str.length();
 
2574
  if (!length || !(to= (char*) alloc_root(mem,length+1)))
 
2575
    return NULL;
 
2576
  memcpy(to,str.ptr(),(uint32_t) length);
 
2577
  to[length]=0;
 
2578
  return to;
 
2579
}
 
2580
 
 
2581
/*
 
2582
  DESCRIPTION
 
2583
    given a buffer with a key value, and a map of keyparts
 
2584
    that are present in this value, returns the length of the value
 
2585
*/
 
2586
uint32_t calculate_key_len(Table *table, uint32_t key,
 
2587
                       const unsigned char *,
 
2588
                       key_part_map keypart_map)
 
2589
{
 
2590
  /* works only with key prefixes */
 
2591
  assert(((keypart_map + 1) & keypart_map) == 0);
 
2592
 
 
2593
  KEY *key_info= table->s->key_info+key;
 
2594
  KEY_PART_INFO *key_part= key_info->key_part;
 
2595
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
 
2596
  uint32_t length= 0;
 
2597
 
 
2598
  while (key_part < end_key_part && keypart_map)
 
2599
  {
 
2600
    length+= key_part->store_length;
 
2601
    keypart_map >>= 1;
 
2602
    key_part++;
 
2603
  }
 
2604
  return length;
 
2605
}
 
2606
 
 
2607
/*
 
2608
  Check if database name is valid
 
2609
 
 
2610
  SYNPOSIS
 
2611
    check_db_name()
 
2612
    org_name            Name of database and length
 
2613
 
 
2614
  NOTES
 
2615
    If lower_case_table_names is set then database is converted to lower case
 
2616
 
 
2617
  RETURN
 
2618
    0   ok
 
2619
    1   error
 
2620
*/
 
2621
 
 
2622
bool check_db_name(LEX_STRING *org_name)
 
2623
{
 
2624
  char *name= org_name->str;
 
2625
  uint32_t name_length= org_name->length;
 
2626
 
 
2627
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
 
2628
    return 1;
 
2629
 
 
2630
  if (lower_case_table_names && name != any_db)
 
2631
    my_casedn_str(files_charset_info, name);
 
2632
 
 
2633
  return check_identifier_name(org_name);
 
2634
}
 
2635
 
324
2636
 
325
2637
/*
326
2638
  Allow anything as a table name, as long as it doesn't contain an
327
2639
  ' ' at the end
328
2640
  returns 1 on error
329
2641
*/
 
2642
 
 
2643
 
330
2644
bool check_table_name(const char *name, uint32_t length)
331
2645
{
332
2646
  if (!length || length > NAME_LEN || name[length - 1] == ' ')
350
2664
 
351
2665
  while (*name)
352
2666
  {
 
2667
#if defined(USE_MB) && defined(USE_MB_IDENT)
353
2668
    last_char_is_space= my_isspace(system_charset_info, *name);
354
2669
    if (use_mb(system_charset_info))
355
2670
    {
364
2679
        continue;
365
2680
      }
366
2681
    }
 
2682
#else
 
2683
    last_char_is_space= *name==' ';
 
2684
#endif
367
2685
    /*
368
2686
      NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
369
2687
      It is defined as 0xFF, which is a not valid byte in utf8.
379
2697
}
380
2698
 
381
2699
 
 
2700
/**
 
2701
  Checks whether a table is intact. Should be done *just* after the table has
 
2702
  been opened.
 
2703
 
 
2704
  @param[in] table             The table to check
 
2705
  @param[in] table_f_count     Expected number of columns in the table
 
2706
  @param[in] table_def         Expected structure of the table (column name
 
2707
                               and type)
 
2708
 
 
2709
  @retval  false  OK
 
2710
  @retval  TRUE   There was an error. An error message is output
 
2711
                  to the error log.  We do not push an error
 
2712
                  message into the error stack because this
 
2713
                  function is currently only called at start up,
 
2714
                  and such errors never reach the user.
 
2715
*/
 
2716
 
 
2717
bool
 
2718
Table::table_check_intact(const uint32_t table_f_count,
 
2719
                          const TABLE_FIELD_W_TYPE *table_def)
 
2720
{
 
2721
  uint32_t i;
 
2722
  bool error= false;
 
2723
  bool fields_diff_count;
 
2724
 
 
2725
  fields_diff_count= (s->fields != table_f_count);
 
2726
  if (fields_diff_count)
 
2727
  {
 
2728
 
 
2729
    /* previous MySQL version */
 
2730
    if (DRIZZLE_VERSION_ID > s->mysql_version)
 
2731
    {
 
2732
      errmsg_printf(ERRMSG_LVL_ERROR, ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
 
2733
                      alias, table_f_count, s->fields,
 
2734
                      s->mysql_version, DRIZZLE_VERSION_ID);
 
2735
      return(true);
 
2736
    }
 
2737
    else if (DRIZZLE_VERSION_ID == s->mysql_version)
 
2738
    {
 
2739
      errmsg_printf(ERRMSG_LVL_ERROR, ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), alias,
 
2740
                      table_f_count, s->fields);
 
2741
      return(true);
 
2742
    }
 
2743
    /*
 
2744
      Something has definitely changed, but we're running an older
 
2745
      version of MySQL with new system tables.
 
2746
      Let's check column definitions. If a column was added at
 
2747
      the end of the table, then we don't care much since such change
 
2748
      is backward compatible.
 
2749
    */
 
2750
  }
 
2751
  char buffer[STRING_BUFFER_USUAL_SIZE];
 
2752
  for (i=0 ; i < table_f_count; i++, table_def++)
 
2753
  {
 
2754
    String sql_type(buffer, sizeof(buffer), system_charset_info);
 
2755
    sql_type.length(0);
 
2756
    if (i < s->fields)
 
2757
    {
 
2758
      Field *cur_field= this->field[i];
 
2759
 
 
2760
      if (strncmp(cur_field->field_name, table_def->name.str,
 
2761
                  table_def->name.length))
 
2762
      {
 
2763
        /*
 
2764
          Name changes are not fatal, we use ordinal numbers to access columns.
 
2765
          Still this can be a sign of a tampered table, output an error
 
2766
          to the error log.
 
2767
        */
 
2768
        errmsg_printf(ERRMSG_LVL_ERROR, _("Incorrect definition of table %s.%s: "
 
2769
                        "expected column '%s' at position %d, found '%s'."),
 
2770
                        s->db.str, alias, table_def->name.str, i,
 
2771
                        cur_field->field_name);
 
2772
      }
 
2773
      cur_field->sql_type(sql_type);
 
2774
      /*
 
2775
        Generally, if column types don't match, then something is
 
2776
        wrong.
 
2777
 
 
2778
        However, we only compare column definitions up to the
 
2779
        length of the original definition, since we consider the
 
2780
        following definitions compatible:
 
2781
 
 
2782
        1. DATETIME and DATETIM
 
2783
        2. INT(11) and INT(11
 
2784
        3. SET('one', 'two') and SET('one', 'two', 'more')
 
2785
 
 
2786
        For SETs or ENUMs, if the same prefix is there it's OK to
 
2787
        add more elements - they will get higher ordinal numbers and
 
2788
        the new table definition is backward compatible with the
 
2789
        original one.
 
2790
       */
 
2791
      if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
 
2792
                  table_def->type.length - 1))
 
2793
      {
 
2794
        errmsg_printf(ERRMSG_LVL_ERROR,
 
2795
                      _("Incorrect definition of table %s.%s: "
 
2796
                        "expected column '%s' at position %d to have type "
 
2797
                        "%s, found type %s."),
 
2798
                      s->db.str, alias,
 
2799
                      table_def->name.str, i, table_def->type.str,
 
2800
                      sql_type.c_ptr_safe());
 
2801
        error= true;
 
2802
      }
 
2803
      else if (table_def->cset.str && !cur_field->has_charset())
 
2804
      {
 
2805
        errmsg_printf(ERRMSG_LVL_ERROR,
 
2806
                      _("Incorrect definition of table %s.%s: "
 
2807
                        "expected the type of column '%s' at position %d "
 
2808
                        "to have character set '%s' but the type has no "
 
2809
                        "character set."),
 
2810
                      s->db.str, alias,
 
2811
                      table_def->name.str, i, table_def->cset.str);
 
2812
        error= true;
 
2813
      }
 
2814
      else if (table_def->cset.str &&
 
2815
               strcmp(cur_field->charset()->csname, table_def->cset.str))
 
2816
      {
 
2817
        errmsg_printf(ERRMSG_LVL_ERROR,
 
2818
                      _("Incorrect definition of table %s.%s: "
 
2819
                        "expected the type of column '%s' at position %d "
 
2820
                        "to have character set '%s' but found "
 
2821
                        "character set '%s'."),
 
2822
                      s->db.str, alias,
 
2823
                      table_def->name.str, i, table_def->cset.str,
 
2824
                      cur_field->charset()->csname);
 
2825
        error= true;
 
2826
      }
 
2827
    }
 
2828
    else
 
2829
    {
 
2830
      errmsg_printf(ERRMSG_LVL_ERROR,
 
2831
                    _("Incorrect definition of table %s.%s: "
 
2832
                      "expected column '%s' at position %d to have type %s "
 
2833
                      " but the column is not found."),
 
2834
                    s->db.str, alias,
 
2835
                    table_def->name.str, i, table_def->type.str);
 
2836
      error= true;
 
2837
    }
 
2838
  }
 
2839
  return(error);
 
2840
}
 
2841
 
 
2842
 
 
2843
/*
 
2844
  Create Item_field for each column in the table.
 
2845
 
 
2846
  SYNPOSIS
 
2847
    Table::fill_item_list()
 
2848
      item_list          a pointer to an empty list used to store items
 
2849
 
 
2850
  DESCRIPTION
 
2851
    Create Item_field object for each column in the table and
 
2852
    initialize it with the corresponding Field. New items are
 
2853
    created in the current Session memory root.
 
2854
 
 
2855
  RETURN VALUE
 
2856
    0                    success
 
2857
    1                    out of memory
 
2858
*/
 
2859
 
 
2860
bool Table::fill_item_list(List<Item> *item_list) const
 
2861
{
 
2862
  /*
 
2863
    All Item_field's created using a direct pointer to a field
 
2864
    are fixed in Item_field constructor.
 
2865
  */
 
2866
  for (Field **ptr= field; *ptr; ptr++)
 
2867
  {
 
2868
    Item_field *item= new Item_field(*ptr);
 
2869
    if (!item || item_list->push_back(item))
 
2870
      return true;
 
2871
  }
 
2872
  return false;
 
2873
}
 
2874
 
 
2875
/*
 
2876
  Reset an existing list of Item_field items to point to the
 
2877
  Fields of this table.
 
2878
 
 
2879
  SYNPOSIS
 
2880
    Table::fill_item_list()
 
2881
      item_list          a non-empty list with Item_fields
 
2882
 
 
2883
  DESCRIPTION
 
2884
    This is a counterpart of fill_item_list used to redirect
 
2885
    Item_fields to the fields of a newly created table.
 
2886
    The caller must ensure that number of items in the item_list
 
2887
    is the same as the number of columns in the table.
 
2888
*/
 
2889
 
 
2890
void Table::reset_item_list(List<Item> *item_list) const
 
2891
{
 
2892
  List_iterator_fast<Item> it(*item_list);
 
2893
  for (Field **ptr= field; *ptr; ptr++)
 
2894
  {
 
2895
    Item_field *item_field= (Item_field*) it++;
 
2896
    assert(item_field != 0);
 
2897
    item_field->reset_field(*ptr);
 
2898
  }
 
2899
}
 
2900
 
 
2901
 
 
2902
/*
 
2903
  Find underlying base tables (TableList) which represent given
 
2904
  table_to_find (Table)
 
2905
 
 
2906
  SYNOPSIS
 
2907
    TableList::find_underlying_table()
 
2908
    table_to_find table to find
 
2909
 
 
2910
  RETURN
 
2911
    0  table is not found
 
2912
    found table reference
 
2913
*/
 
2914
 
 
2915
TableList *TableList::find_underlying_table(Table *table_to_find)
 
2916
{
 
2917
  /* is this real table and table which we are looking for? */
 
2918
  if (table == table_to_find && merge_underlying_list == 0)
 
2919
    return this;
 
2920
 
 
2921
  for (TableList *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
 
2922
  {
 
2923
    TableList *result;
 
2924
    if ((result= tbl->find_underlying_table(table_to_find)))
 
2925
      return result;
 
2926
  }
 
2927
  return 0;
 
2928
}
 
2929
 
 
2930
/*
 
2931
  cleunup items belonged to view fields translation table
 
2932
 
 
2933
  SYNOPSIS
 
2934
    TableList::cleanup_items()
 
2935
*/
 
2936
 
 
2937
void TableList::cleanup_items()
 
2938
{
 
2939
}
 
2940
 
 
2941
 
 
2942
bool TableList::placeholder()
 
2943
{
 
2944
  return derived || schema_table || (create && !table->getDBStat()) || !table;
 
2945
}
 
2946
 
 
2947
 
 
2948
/*
 
2949
  Set insert_values buffer
 
2950
 
 
2951
  SYNOPSIS
 
2952
    set_insert_values()
 
2953
    mem_root   memory pool for allocating
 
2954
 
 
2955
  RETURN
 
2956
    false - OK
 
2957
    TRUE  - out of memory
 
2958
*/
 
2959
 
 
2960
bool TableList::set_insert_values(MEM_ROOT *mem_root)
 
2961
{
 
2962
  if (table)
 
2963
  {
 
2964
    if (!table->insert_values &&
 
2965
        !(table->insert_values= (unsigned char *)alloc_root(mem_root,
 
2966
                                                   table->s->rec_buff_length)))
 
2967
      return true;
 
2968
  }
 
2969
 
 
2970
  return false;
 
2971
}
 
2972
 
 
2973
 
 
2974
/*
 
2975
  Test if this is a leaf with respect to name resolution.
 
2976
 
 
2977
  SYNOPSIS
 
2978
    TableList::is_leaf_for_name_resolution()
 
2979
 
 
2980
  DESCRIPTION
 
2981
    A table reference is a leaf with respect to name resolution if
 
2982
    it is either a leaf node in a nested join tree (table, view,
 
2983
    schema table, subquery), or an inner node that represents a
 
2984
    NATURAL/USING join, or a nested join with materialized join
 
2985
    columns.
 
2986
 
 
2987
  RETURN
 
2988
    TRUE if a leaf, false otherwise.
 
2989
*/
 
2990
bool TableList::is_leaf_for_name_resolution()
 
2991
{
 
2992
  return (is_natural_join || is_join_columns_complete || !nested_join);
 
2993
}
 
2994
 
 
2995
 
 
2996
/*
 
2997
  Retrieve the first (left-most) leaf in a nested join tree with
 
2998
  respect to name resolution.
 
2999
 
 
3000
  SYNOPSIS
 
3001
    TableList::first_leaf_for_name_resolution()
 
3002
 
 
3003
  DESCRIPTION
 
3004
    Given that 'this' is a nested table reference, recursively walk
 
3005
    down the left-most children of 'this' until we reach a leaf
 
3006
    table reference with respect to name resolution.
 
3007
 
 
3008
  IMPLEMENTATION
 
3009
    The left-most child of a nested table reference is the last element
 
3010
    in the list of children because the children are inserted in
 
3011
    reverse order.
 
3012
 
 
3013
  RETURN
 
3014
    If 'this' is a nested table reference - the left-most child of
 
3015
      the tree rooted in 'this',
 
3016
    else return 'this'
 
3017
*/
 
3018
 
 
3019
TableList *TableList::first_leaf_for_name_resolution()
 
3020
{
 
3021
  TableList *cur_table_ref= NULL;
 
3022
  nested_join_st *cur_nested_join;
 
3023
 
 
3024
  if (is_leaf_for_name_resolution())
 
3025
    return this;
 
3026
  assert(nested_join);
 
3027
 
 
3028
  for (cur_nested_join= nested_join;
 
3029
       cur_nested_join;
 
3030
       cur_nested_join= cur_table_ref->nested_join)
 
3031
  {
 
3032
    List_iterator_fast<TableList> it(cur_nested_join->join_list);
 
3033
    cur_table_ref= it++;
 
3034
    /*
 
3035
      If the current nested join is a RIGHT JOIN, the operands in
 
3036
      'join_list' are in reverse order, thus the first operand is
 
3037
      already at the front of the list. Otherwise the first operand
 
3038
      is in the end of the list of join operands.
 
3039
    */
 
3040
    if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
 
3041
    {
 
3042
      TableList *next;
 
3043
      while ((next= it++))
 
3044
        cur_table_ref= next;
 
3045
    }
 
3046
    if (cur_table_ref->is_leaf_for_name_resolution())
 
3047
      break;
 
3048
  }
 
3049
  return cur_table_ref;
 
3050
}
 
3051
 
 
3052
 
 
3053
/*
 
3054
  Retrieve the last (right-most) leaf in a nested join tree with
 
3055
  respect to name resolution.
 
3056
 
 
3057
  SYNOPSIS
 
3058
    TableList::last_leaf_for_name_resolution()
 
3059
 
 
3060
  DESCRIPTION
 
3061
    Given that 'this' is a nested table reference, recursively walk
 
3062
    down the right-most children of 'this' until we reach a leaf
 
3063
    table reference with respect to name resolution.
 
3064
 
 
3065
  IMPLEMENTATION
 
3066
    The right-most child of a nested table reference is the first
 
3067
    element in the list of children because the children are inserted
 
3068
    in reverse order.
 
3069
 
 
3070
  RETURN
 
3071
    - If 'this' is a nested table reference - the right-most child of
 
3072
      the tree rooted in 'this',
 
3073
    - else - 'this'
 
3074
*/
 
3075
 
 
3076
TableList *TableList::last_leaf_for_name_resolution()
 
3077
{
 
3078
  TableList *cur_table_ref= this;
 
3079
  nested_join_st *cur_nested_join;
 
3080
 
 
3081
  if (is_leaf_for_name_resolution())
 
3082
    return this;
 
3083
  assert(nested_join);
 
3084
 
 
3085
  for (cur_nested_join= nested_join;
 
3086
       cur_nested_join;
 
3087
       cur_nested_join= cur_table_ref->nested_join)
 
3088
  {
 
3089
    cur_table_ref= cur_nested_join->join_list.head();
 
3090
    /*
 
3091
      If the current nested is a RIGHT JOIN, the operands in
 
3092
      'join_list' are in reverse order, thus the last operand is in the
 
3093
      end of the list.
 
3094
    */
 
3095
    if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
 
3096
    {
 
3097
      List_iterator_fast<TableList> it(cur_nested_join->join_list);
 
3098
      TableList *next;
 
3099
      cur_table_ref= it++;
 
3100
      while ((next= it++))
 
3101
        cur_table_ref= next;
 
3102
    }
 
3103
    if (cur_table_ref->is_leaf_for_name_resolution())
 
3104
      break;
 
3105
  }
 
3106
  return cur_table_ref;
 
3107
}
 
3108
 
 
3109
 
382
3110
/*****************************************************************************
383
3111
  Functions to handle column usage bitmaps (read_set, write_set etc...)
384
3112
*****************************************************************************/
392
3120
    bitmap_clear_all(&table->def_read_set);
393
3121
    bitmap_clear_all(&table->def_write_set);
394
3122
  */
395
 
  def_read_set.reset();
396
 
  def_write_set.reset();
397
 
  column_bitmaps_set(def_read_set, def_write_set);
 
3123
  memset(def_read_set.bitmap, 0, s->column_bitmap_size*2);
 
3124
  column_bitmaps_set(&def_read_set, &def_write_set);
398
3125
}
399
3126
 
400
3127
 
401
3128
/*
402
 
  Tell Cursor we are going to call position() and rnd_pos() later.
 
3129
  Tell handler we are going to call position() and rnd_pos() later.
403
3130
 
404
3131
  NOTES:
405
3132
  This is needed for handlers that uses the primary key to find the
410
3137
void Table::prepare_for_position()
411
3138
{
412
3139
 
413
 
  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
414
 
      getShare()->hasPrimaryKey())
 
3140
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
3141
      s->primary_key < MAX_KEY)
415
3142
  {
416
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
 
3143
    mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3144
    /* signal change */
 
3145
    file->column_bitmaps_signal();
417
3146
  }
418
3147
  return;
419
3148
}
431
3160
 
432
3161
void Table::mark_columns_used_by_index(uint32_t index)
433
3162
{
434
 
  boost::dynamic_bitset<> *bitmap= &tmp_set;
 
3163
  MY_BITMAP *bitmap= &tmp_set;
435
3164
 
436
 
  (void) cursor->extra(HA_EXTRA_KEYREAD);
437
 
  bitmap->reset();
438
 
  mark_columns_used_by_index_no_reset(index, *bitmap);
439
 
  column_bitmaps_set(*bitmap, *bitmap);
 
3165
  (void) file->extra(HA_EXTRA_KEYREAD);
 
3166
  bitmap_clear_all(bitmap);
 
3167
  mark_columns_used_by_index_no_reset(index, bitmap);
 
3168
  column_bitmaps_set(bitmap, bitmap);
440
3169
  return;
441
3170
}
442
3171
 
456
3185
{
457
3186
 
458
3187
  key_read= 0;
459
 
  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
 
3188
  (void) file->extra(HA_EXTRA_NO_KEYREAD);
460
3189
  default_column_bitmaps();
 
3190
  file->column_bitmaps_signal();
461
3191
  return;
462
3192
}
463
3193
 
466
3196
  mark columns used by key, but don't reset other fields
467
3197
*/
468
3198
 
469
 
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
470
 
{
471
 
    mark_columns_used_by_index_no_reset(index, *read_set);
472
 
}
473
 
 
474
 
 
475
3199
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
476
 
                                                boost::dynamic_bitset<>& bitmap)
 
3200
                                                   MY_BITMAP *bitmap)
477
3201
{
478
 
  KeyPartInfo *key_part= key_info[index].key_part;
479
 
  KeyPartInfo *key_part_end= (key_part + key_info[index].key_parts);
480
 
  for (; key_part != key_part_end; key_part++)
 
3202
  KEY_PART_INFO *key_part= key_info[index].key_part;
 
3203
  KEY_PART_INFO *key_part_end= (key_part +
 
3204
                                key_info[index].key_parts);
 
3205
  for (;key_part != key_part_end; key_part++)
481
3206
  {
482
 
    if (! bitmap.empty())
483
 
      bitmap.set(key_part->fieldnr-1);
 
3207
    bitmap_set_bit(bitmap, key_part->fieldnr-1);
 
3208
    if (key_part->field->vcol_info &&
 
3209
        key_part->field->vcol_info->expr_item)
 
3210
      key_part->field->vcol_info->
 
3211
               expr_item->walk(&Item::register_field_in_bitmap,
 
3212
                               1, (unsigned char *) bitmap);
484
3213
  }
485
3214
}
486
3215
 
500
3229
    We must set bit in read set as update_auto_increment() is using the
501
3230
    store() to check overflow of auto_increment values
502
3231
  */
503
 
  setReadSet(found_next_number_field->position());
504
 
  setWriteSet(found_next_number_field->position());
505
 
  if (getShare()->next_number_keypart)
506
 
    mark_columns_used_by_index_no_reset(getShare()->next_number_index);
 
3232
  bitmap_set_bit(read_set, found_next_number_field->field_index);
 
3233
  bitmap_set_bit(write_set, found_next_number_field->field_index);
 
3234
  if (s->next_number_keypart)
 
3235
    mark_columns_used_by_index_no_reset(s->next_number_index, read_set);
 
3236
  file->column_bitmaps_signal();
507
3237
}
508
3238
 
509
3239
 
527
3257
 
528
3258
void Table::mark_columns_needed_for_delete()
529
3259
{
530
 
  /*
531
 
    If the Cursor has no cursor capabilites, or we have row-based
532
 
    replication active for the current statement, we have to read
533
 
    either the primary key, the hidden primary key or all columns to
534
 
    be able to do an delete
535
 
 
536
 
  */
537
 
  if (not getShare()->hasPrimaryKey())
538
 
  {
539
 
    /* fallback to use all columns in the table to identify row */
540
 
    use_all_columns();
541
 
    return;
542
 
  }
543
 
  else
544
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
545
 
 
546
 
  /* If we the engine wants all predicates we mark all keys */
547
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
3260
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
548
3261
  {
549
3262
    Field **reg_field;
550
3263
    for (reg_field= field ; *reg_field ; reg_field++)
551
3264
    {
552
3265
      if ((*reg_field)->flags & PART_KEY_FLAG)
553
 
        setReadSet((*reg_field)->position());
 
3266
        bitmap_set_bit(read_set, (*reg_field)->field_index);
 
3267
    }
 
3268
    file->column_bitmaps_signal();
 
3269
  }
 
3270
 
 
3271
  {
 
3272
    /*
 
3273
      If the handler has no cursor capabilites, or we have row-based
 
3274
      replication active for the current statement, we have to read
 
3275
      either the primary key, the hidden primary key or all columns to
 
3276
      be able to do an delete
 
3277
    */
 
3278
    if (s->primary_key == MAX_KEY)
 
3279
      file->use_hidden_primary_key();
 
3280
    else
 
3281
    {
 
3282
      mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3283
      file->column_bitmaps_signal();
554
3284
    }
555
3285
  }
556
3286
}
568
3298
    if neeed, either the primary key column or all columns to be read.
569
3299
    (see mark_columns_needed_for_delete() for details)
570
3300
 
571
 
    If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
 
3301
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
572
3302
    mark all USED key columns as 'to-be-read'. This allows the engine to
573
3303
    loop over the given record to find all changed keys and doesn't have to
574
3304
    retrieve the row again.
576
3306
 
577
3307
void Table::mark_columns_needed_for_update()
578
3308
{
579
 
  /*
580
 
    If the Cursor has no cursor capabilites, or we have row-based
581
 
    logging active for the current statement, we have to read either
582
 
    the primary key, the hidden primary key or all columns to be
583
 
    able to do an update
584
 
  */
585
 
  if (not getShare()->hasPrimaryKey())
586
 
  {
587
 
    /* fallback to use all columns in the table to identify row */
588
 
    use_all_columns();
589
 
    return;
590
 
  }
591
 
  else
592
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
593
 
 
594
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
3309
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
595
3310
  {
596
3311
    /* Mark all used key columns for read */
597
3312
    Field **reg_field;
598
3313
    for (reg_field= field ; *reg_field ; reg_field++)
599
3314
    {
600
3315
      /* Merge keys is all keys that had a column refered to in the query */
601
 
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
602
 
        setReadSet((*reg_field)->position());
 
3316
      if (merge_keys.is_overlapping((*reg_field)->part_of_key))
 
3317
        bitmap_set_bit(read_set, (*reg_field)->field_index);
603
3318
    }
 
3319
    file->column_bitmaps_signal();
604
3320
  }
605
3321
 
 
3322
  {
 
3323
    /*
 
3324
      If the handler has no cursor capabilites, or we have row-based
 
3325
      logging active for the current statement, we have to read either
 
3326
      the primary key, the hidden primary key or all columns to be
 
3327
      able to do an update
 
3328
    */
 
3329
    if (s->primary_key == MAX_KEY)
 
3330
      file->use_hidden_primary_key();
 
3331
    else
 
3332
    {
 
3333
      mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3334
      file->column_bitmaps_signal();
 
3335
    }
 
3336
  }
 
3337
  /* Mark all virtual columns as writable */
 
3338
  mark_virtual_columns();
 
3339
  return;
606
3340
}
607
3341
 
608
3342
 
609
3343
/*
610
 
  Mark columns the Cursor needs for doing an insert
 
3344
  Mark columns the handler needs for doing an insert
611
3345
 
612
3346
  For now, this is used to mark fields used by the trigger
613
3347
  as changed.
617
3351
{
618
3352
  if (found_next_number_field)
619
3353
    mark_auto_increment_column();
620
 
}
621
 
 
 
3354
  /* Mark all virtual columns as writable */
 
3355
  mark_virtual_columns();
 
3356
}
 
3357
 
 
3358
/*
 
3359
  @brief Update the write and read table bitmap to allow
 
3360
         using procedure save_in_field for all virtual columns
 
3361
         in the table.
 
3362
 
 
3363
  @return       void
 
3364
 
 
3365
  @detail
 
3366
    Each virtual field is set in the write column map.
 
3367
    All fields that the virtual columns are based on are set in the
 
3368
    read bitmap.
 
3369
*/
 
3370
 
 
3371
void Table::mark_virtual_columns(void)
 
3372
{
 
3373
  Field **vfield_ptr, *tmp_vfield;
 
3374
  bool bitmap_updated= false;
 
3375
 
 
3376
  for (vfield_ptr= vfield; *vfield_ptr; vfield_ptr++)
 
3377
  {
 
3378
    tmp_vfield= *vfield_ptr;
 
3379
    assert(tmp_vfield->vcol_info && tmp_vfield->vcol_info->expr_item);
 
3380
    tmp_vfield->vcol_info->expr_item->walk(&Item::register_field_in_read_map,
 
3381
                                           1, (unsigned char *) 0);
 
3382
    bitmap_set_bit(read_set, tmp_vfield->field_index);
 
3383
    bitmap_set_bit(write_set, tmp_vfield->field_index);
 
3384
    bitmap_updated= true;
 
3385
  }
 
3386
  if (bitmap_updated)
 
3387
    file->column_bitmaps_signal();
 
3388
}
 
3389
 
 
3390
 
 
3391
/*
 
3392
  Cleanup this table for re-execution.
 
3393
 
 
3394
  SYNOPSIS
 
3395
    TableList::reinit_before_use()
 
3396
*/
 
3397
 
 
3398
void TableList::reinit_before_use(Session *session)
 
3399
{
 
3400
  /*
 
3401
    Reset old pointers to TABLEs: they are not valid since the tables
 
3402
    were closed in the end of previous prepare or execute call.
 
3403
  */
 
3404
  table= 0;
 
3405
  /* Reset is_schema_table_processed value(needed for I_S tables */
 
3406
  schema_table_state= NOT_PROCESSED;
 
3407
 
 
3408
  TableList *embedded; /* The table at the current level of nesting. */
 
3409
  TableList *parent_embedding= this; /* The parent nested table reference. */
 
3410
  do
 
3411
  {
 
3412
    embedded= parent_embedding;
 
3413
    if (embedded->prep_on_expr)
 
3414
      embedded->on_expr= embedded->prep_on_expr->copy_andor_structure(session);
 
3415
    parent_embedding= embedded->embedding;
 
3416
  }
 
3417
  while (parent_embedding &&
 
3418
         parent_embedding->nested_join->join_list.head() == embedded);
 
3419
}
 
3420
 
 
3421
/*
 
3422
  Return subselect that contains the FROM list this table is taken from
 
3423
 
 
3424
  SYNOPSIS
 
3425
    TableList::containing_subselect()
 
3426
 
 
3427
  RETURN
 
3428
    Subselect item for the subquery that contains the FROM list
 
3429
    this table is taken from if there is any
 
3430
    0 - otherwise
 
3431
 
 
3432
*/
 
3433
 
 
3434
Item_subselect *TableList::containing_subselect()
 
3435
{
 
3436
  return (select_lex ? select_lex->master_unit()->item : 0);
 
3437
}
 
3438
 
 
3439
/*
 
3440
  Compiles the tagged hints list and fills up the bitmasks.
 
3441
 
 
3442
  SYNOPSIS
 
3443
    process_index_hints()
 
3444
      table         the Table to operate on.
 
3445
 
 
3446
  DESCRIPTION
 
3447
    The parser collects the index hints for each table in a "tagged list"
 
3448
    (TableList::index_hints). Using the information in this tagged list
 
3449
    this function sets the members Table::keys_in_use_for_query,
 
3450
    Table::keys_in_use_for_group_by, Table::keys_in_use_for_order_by,
 
3451
    Table::force_index and Table::covering_keys.
 
3452
 
 
3453
    Current implementation of the runtime does not allow mixing FORCE INDEX
 
3454
    and USE INDEX, so this is checked here. Then the FORCE INDEX list
 
3455
    (if non-empty) is appended to the USE INDEX list and a flag is set.
 
3456
 
 
3457
    Multiple hints of the same kind are processed so that each clause
 
3458
    is applied to what is computed in the previous clause.
 
3459
    For example:
 
3460
        USE INDEX (i1) USE INDEX (i2)
 
3461
    is equivalent to
 
3462
        USE INDEX (i1,i2)
 
3463
    and means "consider only i1 and i2".
 
3464
 
 
3465
    Similarly
 
3466
        USE INDEX () USE INDEX (i1)
 
3467
    is equivalent to
 
3468
        USE INDEX (i1)
 
3469
    and means "consider only the index i1"
 
3470
 
 
3471
    It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is
 
3472
    not an error.
 
3473
 
 
3474
    Different kind of hints (USE/FORCE/IGNORE) are processed in the following
 
3475
    order:
 
3476
      1. All indexes in USE (or FORCE) INDEX are added to the mask.
 
3477
      2. All IGNORE INDEX
 
3478
 
 
3479
    e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all
 
3480
    as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
 
3481
 
 
3482
    As an optimization if there is a covering index, and we have
 
3483
    IGNORE INDEX FOR GROUP/order_st, and this index is used for the JOIN part,
 
3484
    then we have to ignore the IGNORE INDEX FROM GROUP/order_st.
 
3485
 
 
3486
  RETURN VALUE
 
3487
    false                no errors found
 
3488
    TRUE                 found and reported an error.
 
3489
*/
 
3490
bool TableList::process_index_hints(Table *tbl)
 
3491
{
 
3492
  /* initialize the result variables */
 
3493
  tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by=
 
3494
    tbl->keys_in_use_for_order_by= tbl->s->keys_in_use;
 
3495
 
 
3496
  /* index hint list processing */
 
3497
  if (index_hints)
 
3498
  {
 
3499
    key_map index_join[INDEX_HINT_FORCE + 1];
 
3500
    key_map index_order[INDEX_HINT_FORCE + 1];
 
3501
    key_map index_group[INDEX_HINT_FORCE + 1];
 
3502
    Index_hint *hint;
 
3503
    int type;
 
3504
    bool have_empty_use_join= false, have_empty_use_order= false,
 
3505
         have_empty_use_group= false;
 
3506
    List_iterator <Index_hint> iter(*index_hints);
 
3507
 
 
3508
    /* initialize temporary variables used to collect hints of each kind */
 
3509
    for (type= INDEX_HINT_IGNORE; type <= INDEX_HINT_FORCE; type++)
 
3510
    {
 
3511
      index_join[type].clear_all();
 
3512
      index_order[type].clear_all();
 
3513
      index_group[type].clear_all();
 
3514
    }
 
3515
 
 
3516
    /* iterate over the hints list */
 
3517
    while ((hint= iter++))
 
3518
    {
 
3519
      uint32_t pos;
 
3520
 
 
3521
      /* process empty USE INDEX () */
 
3522
      if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
 
3523
      {
 
3524
        if (hint->clause & INDEX_HINT_MASK_JOIN)
 
3525
        {
 
3526
          index_join[hint->type].clear_all();
 
3527
          have_empty_use_join= true;
 
3528
        }
 
3529
        if (hint->clause & INDEX_HINT_MASK_ORDER)
 
3530
        {
 
3531
          index_order[hint->type].clear_all();
 
3532
          have_empty_use_order= true;
 
3533
        }
 
3534
        if (hint->clause & INDEX_HINT_MASK_GROUP)
 
3535
        {
 
3536
          index_group[hint->type].clear_all();
 
3537
          have_empty_use_group= true;
 
3538
        }
 
3539
        continue;
 
3540
      }
 
3541
 
 
3542
      /*
 
3543
        Check if an index with the given name exists and get his offset in
 
3544
        the keys bitmask for the table
 
3545
      */
 
3546
      if (tbl->s->keynames.type_names == 0 ||
 
3547
          (pos= find_type(&tbl->s->keynames, hint->key_name.str,
 
3548
                          hint->key_name.length, 1)) <= 0)
 
3549
      {
 
3550
        my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), hint->key_name.str, alias);
 
3551
        return 1;
 
3552
      }
 
3553
 
 
3554
      pos--;
 
3555
 
 
3556
      /* add to the appropriate clause mask */
 
3557
      if (hint->clause & INDEX_HINT_MASK_JOIN)
 
3558
        index_join[hint->type].set_bit (pos);
 
3559
      if (hint->clause & INDEX_HINT_MASK_ORDER)
 
3560
        index_order[hint->type].set_bit (pos);
 
3561
      if (hint->clause & INDEX_HINT_MASK_GROUP)
 
3562
        index_group[hint->type].set_bit (pos);
 
3563
    }
 
3564
 
 
3565
    /* cannot mix USE INDEX and FORCE INDEX */
 
3566
    if ((!index_join[INDEX_HINT_FORCE].is_clear_all() ||
 
3567
         !index_order[INDEX_HINT_FORCE].is_clear_all() ||
 
3568
         !index_group[INDEX_HINT_FORCE].is_clear_all()) &&
 
3569
        (!index_join[INDEX_HINT_USE].is_clear_all() ||  have_empty_use_join ||
 
3570
         !index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order ||
 
3571
         !index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group))
 
3572
    {
 
3573
      my_error(ER_WRONG_USAGE, MYF(0), index_hint_type_name[INDEX_HINT_USE],
 
3574
               index_hint_type_name[INDEX_HINT_FORCE]);
 
3575
      return 1;
 
3576
    }
 
3577
 
 
3578
    /* process FORCE INDEX as USE INDEX with a flag */
 
3579
    if (!index_join[INDEX_HINT_FORCE].is_clear_all() ||
 
3580
        !index_order[INDEX_HINT_FORCE].is_clear_all() ||
 
3581
        !index_group[INDEX_HINT_FORCE].is_clear_all())
 
3582
    {
 
3583
      tbl->force_index= true;
 
3584
      index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
 
3585
      index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
 
3586
      index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
 
3587
    }
 
3588
 
 
3589
    /* apply USE INDEX */
 
3590
    if (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join)
 
3591
      tbl->keys_in_use_for_query.intersect(index_join[INDEX_HINT_USE]);
 
3592
    if (!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order)
 
3593
      tbl->keys_in_use_for_order_by.intersect (index_order[INDEX_HINT_USE]);
 
3594
    if (!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group)
 
3595
      tbl->keys_in_use_for_group_by.intersect (index_group[INDEX_HINT_USE]);
 
3596
 
 
3597
    /* apply IGNORE INDEX */
 
3598
    tbl->keys_in_use_for_query.subtract (index_join[INDEX_HINT_IGNORE]);
 
3599
    tbl->keys_in_use_for_order_by.subtract (index_order[INDEX_HINT_IGNORE]);
 
3600
    tbl->keys_in_use_for_group_by.subtract (index_group[INDEX_HINT_IGNORE]);
 
3601
  }
 
3602
 
 
3603
  /* make sure covering_keys don't include indexes disabled with a hint */
 
3604
  tbl->covering_keys.intersect(tbl->keys_in_use_for_query);
 
3605
  return 0;
 
3606
}
622
3607
 
623
3608
 
624
3609
size_t Table::max_row_length(const unsigned char *data)
631
3616
  {
632
3617
    Field_blob* const blob= (Field_blob*) field[*ptr];
633
3618
    length+= blob->get_length((const unsigned char*)
634
 
                              (data + blob->offset(getInsertRecord()))) +
 
3619
                              (data + blob->offset(record[0]))) +
635
3620
      HA_KEY_BLOB_LENGTH;
636
3621
  }
637
3622
  return length;
638
3623
}
639
3624
 
640
 
void Table::setVariableWidth(void)
641
 
{
642
 
  assert(in_use);
643
 
  if (in_use && in_use->getLex()->sql_command == SQLCOM_CREATE_TABLE)
644
 
  {
645
 
    getMutableShare()->setVariableWidth();
646
 
    return;
647
 
  }
648
 
 
649
 
  assert(0); // Programming error, you can't set this on a plain old Table.
650
 
}
651
 
 
652
3625
/****************************************************************************
653
3626
 Functions for creating temporary tables.
654
3627
****************************************************************************/
 
3628
 
 
3629
 
 
3630
/* Prototypes */
 
3631
void free_tmp_table(Session *session, Table *entry);
 
3632
 
655
3633
/**
656
3634
  Create field for temporary table from given field.
657
3635
 
658
 
  @param session               Thread Cursor
 
3636
  @param session               Thread handler
659
3637
  @param org_field    field from which new field will be created
660
3638
  @param name         New field name
661
3639
  @param table         Temporary table
686
3664
  */
687
3665
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
688
3666
      (org_field->flags & BLOB_FLAG))
689
 
  {
690
 
    table->setVariableWidth();
691
3667
    new_field= new Field_varstring(convert_blob_length,
692
3668
                                   org_field->maybe_null(),
693
 
                                   org_field->field_name,
 
3669
                                   org_field->field_name, table->s,
694
3670
                                   org_field->charset());
695
 
  }
696
3671
  else
697
 
  {
698
3672
    new_field= org_field->new_field(session->mem_root, table,
699
 
                                    table == org_field->getTable());
700
 
  }
 
3673
                                    table == org_field->table);
701
3674
  if (new_field)
702
3675
  {
703
3676
    new_field->init(table);
710
3683
    if (org_field->maybe_null() || (item && item->maybe_null))
711
3684
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
712
3685
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
713
 
      table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
 
3686
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
714
3687
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
715
3688
      ((Field_double *) new_field)->not_fixed= true;
716
3689
  }
719
3692
 
720
3693
 
721
3694
/**
 
3695
  Create field for information schema table.
 
3696
 
 
3697
  @param session                Thread handler
 
3698
  @param table          Temporary table
 
3699
  @param item           Item to create a field for
 
3700
 
 
3701
  @retval
 
3702
    0                   on error
 
3703
  @retval
 
3704
    new_created field
 
3705
*/
 
3706
 
 
3707
Field *create_tmp_field_for_schema(Session *, Item *item, Table *table)
 
3708
{
 
3709
  if (item->field_type() == DRIZZLE_TYPE_VARCHAR)
 
3710
  {
 
3711
    Field *field;
 
3712
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
 
3713
      field= new Field_blob(item->max_length, item->maybe_null,
 
3714
                            item->name, item->collation.collation);
 
3715
    else
 
3716
      field= new Field_varstring(item->max_length, item->maybe_null,
 
3717
                                 item->name,
 
3718
                                 table->s, item->collation.collation);
 
3719
    if (field)
 
3720
      field->init(table);
 
3721
    return field;
 
3722
  }
 
3723
  return item->tmp_table_field_from_field_type(table, 0);
 
3724
}
 
3725
 
 
3726
 
 
3727
/**
722
3728
  Create a temp table according to a field list.
723
3729
 
724
3730
  Given field pointers are changed to point at tmp_table for
750
3756
 
751
3757
Table *
752
3758
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
753
 
                 Order *group, bool distinct, bool save_sum_fields,
 
3759
                 order_st *group, bool distinct, bool save_sum_fields,
754
3760
                 uint64_t select_options, ha_rows rows_limit,
755
 
                 const char *table_alias)
 
3761
                 char *table_alias)
756
3762
{
757
 
  memory::Root *mem_root_save;
 
3763
  MEM_ROOT *mem_root_save, own_root;
 
3764
  Table *table;
 
3765
  TABLE_SHARE *share;
758
3766
  uint  i,field_count,null_count,null_pack_length;
759
3767
  uint32_t  copy_func_count= param->func_count;
760
3768
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
761
3769
  uint32_t  blob_count,group_null_items, string_count;
 
3770
  uint32_t  temp_pool_slot=MY_BIT_NONE;
762
3771
  uint32_t fieldnr= 0;
763
3772
  ulong reclength, string_total_length;
764
 
  bool  using_unique_constraint= false;
765
 
  bool  use_packed_rows= true;
 
3773
  bool  using_unique_constraint= 0;
 
3774
  bool  use_packed_rows= 0;
766
3775
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
767
 
  unsigned char *pos, *group_buff;
 
3776
  char  *tmpname,path[FN_REFLEN];
 
3777
  unsigned char *pos, *group_buff, *bitmaps;
768
3778
  unsigned char *null_flags;
769
3779
  Field **reg_field, **from_field, **default_field;
770
 
  CopyField *copy= 0;
771
 
  KeyInfo *keyinfo;
772
 
  KeyPartInfo *key_part_info;
 
3780
  uint32_t *blob_field;
 
3781
  Copy_field *copy=0;
 
3782
  KEY *keyinfo;
 
3783
  KEY_PART_INFO *key_part_info;
773
3784
  Item **copy_func;
774
3785
  MI_COLUMNDEF *recinfo;
775
3786
  uint32_t total_uneven_bit_length= 0;
776
3787
  bool force_copy_fields= param->force_copy_fields;
777
 
  uint64_t max_rows= 0;
778
 
 
779
 
  session->status_var.created_tmp_tables++;
 
3788
 
 
3789
  status_var_increment(session->status_var.created_tmp_tables);
 
3790
 
 
3791
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
 
3792
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
 
3793
 
 
3794
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
 
3795
    sprintf(path, "%s_%lx_%i", TMP_FILE_PREFIX,
 
3796
            (unsigned long)current_pid, temp_pool_slot);
 
3797
  else
 
3798
  {
 
3799
    /* if we run out of slots or we are not using tempool */
 
3800
    sprintf(path,"%s%lx_%"PRIx64"_%x", TMP_FILE_PREFIX, (unsigned long)current_pid,
 
3801
            session->thread_id, session->tmp_table++);
 
3802
  }
 
3803
 
 
3804
  /*
 
3805
    No need to change table name to lower case as we are only creating
 
3806
    MyISAM or HEAP tables here
 
3807
  */
 
3808
  fn_format(path, path, drizzle_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
3809
 
780
3810
 
781
3811
  if (group)
782
3812
  {
783
 
    if (! param->quick_group)
784
 
    {
785
 
      group= 0;                                 // Can't use group key
786
 
    }
787
 
    else for (Order *tmp=group ; tmp ; tmp=tmp->next)
 
3813
    if (!param->quick_group)
 
3814
      group=0;                                  // Can't use group key
 
3815
    else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
788
3816
    {
789
3817
      /*
790
3818
        marker == 4 means two things:
794
3822
      */
795
3823
      (*tmp->item)->marker= 4;
796
3824
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
797
 
        using_unique_constraint= true;
 
3825
        using_unique_constraint=1;
798
3826
    }
799
3827
    if (param->group_length >= MAX_BLOB_WIDTH)
800
 
      using_unique_constraint= true;
 
3828
      using_unique_constraint=1;
801
3829
    if (group)
802
 
      distinct= 0;                              // Can't use distinct
 
3830
      distinct=0;                               // Can't use distinct
803
3831
  }
804
3832
 
805
3833
  field_count=param->field_count+param->func_count+param->sum_func_count;
813
3841
    these items are stored in the temporary table.
814
3842
  */
815
3843
  if (param->precomputed_group_by)
816
 
  {
817
3844
    copy_func_count+= param->sum_func_count;
818
 
  }
819
 
 
820
 
  table::Singular *table;
821
 
  table= session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
822
 
 
823
 
  if (not table->getMemRoot()->multi_alloc_root(0,
824
 
                                                &default_field, sizeof(Field*) * (field_count),
825
 
                                                &from_field, sizeof(Field*)*field_count,
826
 
                                                &copy_func, sizeof(*copy_func)*(copy_func_count+1),
827
 
                                                &param->keyinfo, sizeof(*param->keyinfo),
828
 
                                                &key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
829
 
                                                &param->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
830
 
                                                &group_buff, (group && ! using_unique_constraint ?
831
 
                                                              param->group_length : 0),
832
 
                                                NULL))
833
 
  {
834
 
    return NULL;
835
 
  }
836
 
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
837
 
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
838
 
  {
839
 
    return NULL;
 
3845
 
 
3846
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
3847
 
 
3848
  if (!multi_alloc_root(&own_root,
 
3849
                        &table, sizeof(*table),
 
3850
                        &share, sizeof(*share),
 
3851
                        &reg_field, sizeof(Field*) * (field_count+1),
 
3852
                        &default_field, sizeof(Field*) * (field_count),
 
3853
                        &blob_field, sizeof(uint32_t)*(field_count+1),
 
3854
                        &from_field, sizeof(Field*)*field_count,
 
3855
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
 
3856
                        &param->keyinfo, sizeof(*param->keyinfo),
 
3857
                        &key_part_info,
 
3858
                        sizeof(*key_part_info)*(param->group_parts+1),
 
3859
                        &param->start_recinfo,
 
3860
                        sizeof(*param->recinfo)*(field_count*2+4),
 
3861
                        &tmpname, (uint32_t) strlen(path)+1,
 
3862
                        &group_buff, (group && ! using_unique_constraint ?
 
3863
                                      param->group_length : 0),
 
3864
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
3865
                        NULL))
 
3866
  {
 
3867
    if (temp_pool_slot != MY_BIT_NONE)
 
3868
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
3869
    return(NULL);                               /* purecov: inspected */
 
3870
  }
 
3871
  /* Copy_field belongs to Tmp_Table_Param, allocate it in Session mem_root */
 
3872
  if (!(param->copy_field= copy= new (session->mem_root) Copy_field[field_count]))
 
3873
  {
 
3874
    if (temp_pool_slot != MY_BIT_NONE)
 
3875
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
3876
    free_root(&own_root, MYF(0));               /* purecov: inspected */
 
3877
    return(NULL);                               /* purecov: inspected */
840
3878
  }
841
3879
  param->items_to_copy= copy_func;
 
3880
  strcpy(tmpname,path);
842
3881
  /* make table according to fields */
843
3882
 
 
3883
  memset(table, 0, sizeof(*table));
 
3884
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
844
3885
  memset(default_field, 0, sizeof(Field*) * (field_count));
845
3886
  memset(from_field, 0, sizeof(Field*)*field_count);
846
3887
 
 
3888
  table->mem_root= own_root;
847
3889
  mem_root_save= session->mem_root;
848
 
  session->mem_root= table->getMemRoot();
 
3890
  session->mem_root= &table->mem_root;
849
3891
 
850
 
  table->getMutableShare()->setFields(field_count+1);
851
 
  table->setFields(table->getMutableShare()->getFields(true));
852
 
  reg_field= table->getMutableShare()->getFields(true);
853
 
  table->setAlias(table_alias);
 
3892
  table->field=reg_field;
 
3893
  table->alias= table_alias;
854
3894
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
855
3895
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
856
3896
  table->map=1;
 
3897
  table->temp_pool_slot = temp_pool_slot;
857
3898
  table->copy_blobs= 1;
858
 
  assert(session);
859
3899
  table->in_use= session;
860
 
  table->quick_keys.reset();
861
 
  table->covering_keys.reset();
862
 
  table->keys_in_use_for_query.reset();
 
3900
  table->quick_keys.init();
 
3901
  table->covering_keys.init();
 
3902
  table->keys_in_use_for_query.init();
863
3903
 
864
 
  table->getMutableShare()->blob_field.resize(field_count+1);
865
 
  uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
866
 
  table->getMutableShare()->db_low_byte_first=1;                // True for HEAP and MyISAM
867
 
  table->getMutableShare()->table_charset= param->table_charset;
868
 
  table->getMutableShare()->keys_for_keyread.reset();
869
 
  table->getMutableShare()->keys_in_use.reset();
 
3904
  table->setShare(share);
 
3905
  init_tmp_table_share(session, share, "", 0, tmpname, tmpname);
 
3906
  share->blob_field= blob_field;
 
3907
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
3908
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
3909
  share->table_charset= param->table_charset;
 
3910
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
3911
  share->keys_for_keyread.init();
 
3912
  share->keys_in_use.init();
870
3913
 
871
3914
  /* Calculate which type of fields we will store in the temporary table */
872
3915
 
873
3916
  reclength= string_total_length= 0;
874
3917
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
875
 
  param->using_indirect_summary_function= 0;
 
3918
  param->using_indirect_summary_function=0;
876
3919
 
877
 
  List<Item>::iterator li(fields.begin());
 
3920
  List_iterator_fast<Item> li(fields);
878
3921
  Item *item;
879
3922
  Field **tmp_from_field=from_field;
880
3923
  while ((item=li++))
903
3946
    }
904
3947
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
905
3948
    {                                           /* Can't calc group yet */
906
 
      ((Item_sum*) item)->result_field= 0;
907
 
      for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
 
3949
      ((Item_sum*) item)->result_field=0;
 
3950
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
908
3951
      {
909
3952
        Item **argp= ((Item_sum*) item)->args + i;
910
3953
        Item *arg= *argp;
914
3957
            create_tmp_field(session, table, arg, arg->type(), &copy_func,
915
3958
                             tmp_from_field, &default_field[fieldnr],
916
3959
                             group != 0,not_all_columns,
917
 
                             false,
 
3960
                             distinct, 0,
918
3961
                             param->convert_blob_length);
919
3962
          if (!new_field)
920
3963
            goto err;                                   // Should be OOM
933
3976
          }
934
3977
          session->mem_root= mem_root_save;
935
3978
          session->change_item_tree(argp, new Item_field(new_field));
936
 
          session->mem_root= table->getMemRoot();
 
3979
          session->mem_root= &table->mem_root;
937
3980
          if (!(new_field->flags & NOT_NULL_FLAG))
938
3981
          {
939
3982
            null_count++;
943
3986
            */
944
3987
            (*argp)->maybe_null=1;
945
3988
          }
946
 
          new_field->setPosition(fieldnr++);
 
3989
          new_field->field_index= fieldnr++;
947
3990
        }
948
3991
      }
949
3992
    }
959
4002
        We here distinguish between UNION and multi-table-updates by the fact
960
4003
        that in the later case group is set to the row pointer.
961
4004
      */
962
 
      Field *new_field=
 
4005
      Field *new_field= (param->schema_table) ?
 
4006
        create_tmp_field_for_schema(session, item, table) :
963
4007
        create_tmp_field(session, table, item, type, &copy_func,
964
4008
                         tmp_from_field, &default_field[fieldnr],
965
4009
                         group != 0,
966
4010
                         !force_copy_fields &&
967
 
                           (not_all_columns || group != 0),
 
4011
                           (not_all_columns || group !=0),
 
4012
                         /*
 
4013
                           If item->marker == 4 then we force create_tmp_field
 
4014
                           to create a 64-bit longs for BIT fields because HEAP
 
4015
                           tables can't index BIT fields directly. We do the same
 
4016
                           for distinct, as we want the distinct index to be
 
4017
                           usable in this case too.
 
4018
                         */
 
4019
                         item->marker == 4 || param->bit_fields_as_long,
968
4020
                         force_copy_fields,
969
4021
                         param->convert_blob_length);
970
4022
 
990
4042
        group_null_items++;
991
4043
        new_field->flags|= GROUP_FLAG;
992
4044
      }
993
 
      new_field->setPosition(fieldnr++);
 
4045
      new_field->field_index= fieldnr++;
994
4046
      *(reg_field++)= new_field;
995
4047
    }
996
4048
    if (!--hidden_field_count)
1008
4060
      null_count= 0;
1009
4061
    }
1010
4062
  }
1011
 
  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
1012
 
  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
 
4063
  assert(fieldnr == (uint32_t) (reg_field - table->field));
 
4064
  assert(field_count >= (uint32_t) (reg_field - table->field));
1013
4065
  field_count= fieldnr;
1014
4066
  *reg_field= 0;
1015
4067
  *blob_field= 0;                               // End marker
1016
 
  table->getMutableShare()->setFieldSize(field_count);
 
4068
  share->fields= field_count;
1017
4069
 
1018
4070
  /* If result table is small; use a heap */
1019
4071
  /* future: storage engine selection can be made dynamic? */
1020
 
  if (blob_count || using_unique_constraint || 
1021
 
      (session->getLex()->select_lex.options & SELECT_BIG_RESULT) ||
1022
 
      (session->getLex()->current_select->olap == ROLLUP_TYPE) ||
1023
 
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
 
4072
  if (blob_count || using_unique_constraint ||
 
4073
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
4074
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
1024
4075
  {
1025
 
    table->getMutableShare()->storage_engine= myisam_engine;
1026
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
 
4076
    share->db_plugin= ha_lock_engine(0, myisam_hton);
 
4077
    table->file= get_new_handler(share, &table->mem_root,
 
4078
                                 share->db_type());
1027
4079
    if (group &&
1028
 
        (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
1029
 
         param->group_length > table->cursor->getEngine()->max_key_length()))
1030
 
    {
1031
 
      using_unique_constraint= true;
1032
 
    }
 
4080
        (param->group_parts > table->file->max_key_parts() ||
 
4081
         param->group_length > table->file->max_key_length()))
 
4082
      using_unique_constraint=1;
1033
4083
  }
1034
4084
  else
1035
4085
  {
1036
 
    table->getMutableShare()->storage_engine= heap_engine;
1037
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
 
4086
    share->db_plugin= ha_lock_engine(0, heap_hton);
 
4087
    table->file= get_new_handler(share, &table->mem_root,
 
4088
                                 share->db_type());
1038
4089
  }
1039
 
  if (! table->cursor)
 
4090
  if (!table->file)
1040
4091
    goto err;
1041
4092
 
1042
4093
 
1043
 
  if (! using_unique_constraint)
 
4094
  if (!using_unique_constraint)
1044
4095
    reclength+= group_null_items;       // null flag is stored separately
1045
4096
 
1046
 
  table->getMutableShare()->blob_fields= blob_count;
 
4097
  share->blob_fields= blob_count;
1047
4098
  if (blob_count == 0)
1048
4099
  {
1049
4100
    /* We need to ensure that first byte is not 0 for the delete link */
1062
4113
  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)))
1063
4114
    use_packed_rows= 1;
1064
4115
 
1065
 
  table->getMutableShare()->setRecordLength(reclength);
 
4116
  share->reclength= reclength;
1066
4117
  {
1067
4118
    uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
1068
 
    table->getMutableShare()->rec_buff_length= alloc_length;
1069
 
    if (!(table->record[0]= (unsigned char*) table->alloc_root(alloc_length*2)))
1070
 
    {
 
4119
    share->rec_buff_length= alloc_length;
 
4120
    if (!(table->record[0]= (unsigned char*)
 
4121
                            alloc_root(&table->mem_root, alloc_length*3)))
1071
4122
      goto err;
1072
 
    }
1073
 
    table->record[1]= table->getInsertRecord()+alloc_length;
1074
 
    table->getMutableShare()->resizeDefaultValues(alloc_length);
 
4123
    table->record[1]= table->record[0]+alloc_length;
 
4124
    share->default_values= table->record[1]+alloc_length;
1075
4125
  }
1076
 
  copy_func[0]= 0;                              // End marker
 
4126
  copy_func[0]=0;                               // End marker
1077
4127
  param->func_count= copy_func - param->items_to_copy;
1078
4128
 
1079
 
  table->setup_tmp_table_column_bitmaps();
 
4129
  table->setup_tmp_table_column_bitmaps(bitmaps);
1080
4130
 
1081
4131
  recinfo=param->start_recinfo;
1082
 
  null_flags=(unsigned char*) table->getInsertRecord();
1083
 
  pos=table->getInsertRecord()+ null_pack_length;
 
4132
  null_flags=(unsigned char*) table->record[0];
 
4133
  pos=table->record[0]+ null_pack_length;
1084
4134
  if (null_pack_length)
1085
4135
  {
1086
4136
    memset(recinfo, 0, sizeof(*recinfo));
1089
4139
    recinfo++;
1090
4140
    memset(null_flags, 255, null_pack_length);  // Set null fields
1091
4141
 
1092
 
    table->null_flags= (unsigned char*) table->getInsertRecord();
1093
 
    table->getMutableShare()->null_fields= null_count+ hidden_null_count;
1094
 
    table->getMutableShare()->null_bytes= null_pack_length;
 
4142
    table->null_flags= (unsigned char*) table->record[0];
 
4143
    share->null_fields= null_count+ hidden_null_count;
 
4144
    share->null_bytes= null_pack_length;
1095
4145
  }
1096
4146
  null_count= (blob_count == 0) ? 1 : 0;
1097
4147
  hidden_field_count=param->hidden_field_count;
1098
 
  for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
 
4148
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
1099
4149
  {
1100
4150
    Field *field= *reg_field;
1101
4151
    uint32_t length;
1109
4159
          We have to reserve one byte here for NULL bits,
1110
4160
          as this is updated by 'end_update()'
1111
4161
        */
1112
 
        *pos++= '\0';                           // Null is stored here
1113
 
        recinfo->length= 1;
 
4162
        *pos++=0;                               // Null is stored here
 
4163
        recinfo->length=1;
1114
4164
        recinfo->type=FIELD_NORMAL;
1115
4165
        recinfo++;
1116
4166
        memset(recinfo, 0, sizeof(*recinfo));
1139
4189
         inherit the default value that is defined for the field referred
1140
4190
         by the Item_field object from which 'field' has been created.
1141
4191
      */
1142
 
      ptrdiff_t diff;
 
4192
      my_ptrdiff_t diff;
1143
4193
      Field *orig_field= default_field[i];
1144
4194
      /* Get the value from default_values */
1145
 
      diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
 
4195
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
 
4196
                            orig_field->table->record[0]);
1146
4197
      orig_field->move_field_offset(diff);      // Points now at default_values
1147
4198
      if (orig_field->is_real_null())
1148
4199
        field->set_null();
1151
4202
        field->set_notnull();
1152
4203
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
1153
4204
      }
1154
 
      orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
 
4205
      orig_field->move_field_offset(-diff);     // Back to record[0]
1155
4206
    }
1156
4207
 
1157
4208
    if (from_field[i])
1170
4221
      recinfo->type=FIELD_NORMAL;
1171
4222
    if (!--hidden_field_count)
1172
4223
      null_count=(null_count+7) & ~7;           // move to next byte
 
4224
 
 
4225
    // fix table name in field entry
 
4226
    field->table_name= &table->alias;
1173
4227
  }
1174
4228
 
1175
4229
  param->copy_field_end=copy;
1176
4230
  param->recinfo=recinfo;
1177
 
  table->storeRecordAsDefault();        // Make empty default record
 
4231
  store_record(table,s->default_values);        // Make empty default record
1178
4232
 
1179
4233
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)              // No limit
1180
 
  {
1181
 
    max_rows= ~(uint64_t) 0;
1182
 
  }
 
4234
    share->max_rows= ~(ha_rows) 0;
1183
4235
  else
1184
 
  {
1185
 
    max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
1186
 
                           min(session->variables.tmp_table_size,
1187
 
                               session->variables.max_heap_table_size) :
1188
 
                           session->variables.tmp_table_size) /
1189
 
                          table->getMutableShare()->getRecordLength());
1190
 
  }
1191
 
 
1192
 
  set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
 
4236
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
 
4237
                                 cmin(session->variables.tmp_table_size,
 
4238
                                     session->variables.max_heap_table_size) :
 
4239
                                 session->variables.tmp_table_size) /
 
4240
                                 share->reclength);
 
4241
  set_if_bigger(share->max_rows,1);             // For dummy start options
1193
4242
  /*
1194
4243
    Push the LIMIT clause to the temporary table creation, so that we
1195
4244
    materialize only up to 'rows_limit' records instead of all result records.
1196
4245
  */
1197
 
  set_if_smaller(max_rows, rows_limit);
1198
 
 
1199
 
  table->getMutableShare()->setMaxRows(max_rows);
1200
 
 
 
4246
  set_if_smaller(share->max_rows, rows_limit);
1201
4247
  param->end_write_records= rows_limit;
1202
4248
 
1203
4249
  keyinfo= param->keyinfo;
1206
4252
  {
1207
4253
    table->group=group;                         /* Table is grouped by key */
1208
4254
    param->group_buff=group_buff;
1209
 
    table->getMutableShare()->keys=1;
1210
 
    table->getMutableShare()->uniques= test(using_unique_constraint);
 
4255
    share->keys=1;
 
4256
    share->uniques= test(using_unique_constraint);
1211
4257
    table->key_info=keyinfo;
1212
4258
    keyinfo->key_part=key_part_info;
1213
4259
    keyinfo->flags=HA_NOSAME;
1214
4260
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
1215
 
    keyinfo->key_length= 0;
1216
 
    keyinfo->rec_per_key= 0;
 
4261
    keyinfo->key_length=0;
 
4262
    keyinfo->rec_per_key=0;
1217
4263
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1218
4264
    keyinfo->name= (char*) "group_key";
1219
 
    Order *cur_group= group;
 
4265
    order_st *cur_group= group;
1220
4266
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1221
4267
    {
1222
4268
      Field *field=(*cur_group->item)->get_tmp_table_field();
1223
4269
      bool maybe_null=(*cur_group->item)->maybe_null;
1224
 
      key_part_info->null_bit= 0;
 
4270
      key_part_info->null_bit=0;
1225
4271
      key_part_info->field=  field;
1226
 
      key_part_info->offset= field->offset(table->getInsertRecord());
 
4272
      key_part_info->offset= field->offset(table->record[0]);
1227
4273
      key_part_info->length= (uint16_t) field->key_length();
1228
4274
      key_part_info->type=   (uint8_t) field->key_type();
1229
 
      key_part_info->key_type= 
 
4275
      key_part_info->key_type =
1230
4276
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1231
4277
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1232
4278
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1233
 
        0 : 1;
 
4279
        0 : FIELDFLAG_BINARY;
1234
4280
      if (!using_unique_constraint)
1235
4281
      {
1236
4282
        cur_group->buff=(char*) group_buff;
1239
4285
                                                     test(maybe_null),
1240
4286
                                                     field->null_ptr,
1241
4287
                                                     field->null_bit)))
1242
 
          goto err;
 
4288
          goto err; /* purecov: inspected */
1243
4289
        if (maybe_null)
1244
4290
        {
1245
4291
          /*
1251
4297
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
1252
4298
          key_part_info->null_bit=field->null_bit;
1253
4299
          key_part_info->null_offset= (uint32_t) (field->null_ptr -
1254
 
                                              (unsigned char*) table->getInsertRecord());
 
4300
                                              (unsigned char*) table->record[0]);
1255
4301
          cur_group->buff++;                        // Pointer to field data
1256
4302
          group_buff++;                         // Skipp null flag
1257
4303
        }
1278
4324
        indexes on blobs with arbitrary length. Such indexes cannot be
1279
4325
        used for lookups.
1280
4326
      */
1281
 
      table->getMutableShare()->uniques= 1;
 
4327
      share->uniques= 1;
1282
4328
    }
1283
4329
    null_pack_length-=hidden_null_pack_length;
1284
4330
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
1285
 
                         (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
 
4331
                         (share->uniques ? test(null_pack_length) : 0));
1286
4332
    table->distinct= 1;
1287
 
    table->getMutableShare()->keys= 1;
1288
 
    if (!(key_part_info= (KeyPartInfo*)
1289
 
         table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
 
4333
    share->keys= 1;
 
4334
    if (!(key_part_info= (KEY_PART_INFO*)
 
4335
          alloc_root(&table->mem_root,
 
4336
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
1290
4337
      goto err;
1291
 
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
 
4338
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
1292
4339
    table->key_info=keyinfo;
1293
4340
    keyinfo->key_part=key_part_info;
1294
4341
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
1295
4342
    keyinfo->key_length=(uint16_t) reclength;
1296
4343
    keyinfo->name= (char*) "distinct_key";
1297
4344
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1298
 
    keyinfo->rec_per_key= 0;
 
4345
    keyinfo->rec_per_key=0;
1299
4346
 
1300
4347
    /*
1301
4348
      Create an extra field to hold NULL bits so that unique indexes on
1302
4349
      blobs can distinguish NULL from 0. This extra field is not needed
1303
4350
      when we do not use UNIQUE indexes for blobs.
1304
4351
    */
1305
 
    if (null_pack_length && table->getMutableShare()->uniques)
 
4352
    if (null_pack_length && share->uniques)
1306
4353
    {
1307
 
      key_part_info->null_bit= 0;
 
4354
      key_part_info->null_bit=0;
1308
4355
      key_part_info->offset=hidden_null_pack_length;
1309
4356
      key_part_info->length=null_pack_length;
1310
 
      table->setVariableWidth();
1311
 
      key_part_info->field= new Field_varstring(table->getInsertRecord(),
 
4357
      key_part_info->field= new Field_varstring(table->record[0],
1312
4358
                                                (uint32_t) key_part_info->length,
1313
4359
                                                0,
1314
4360
                                                (unsigned char*) 0,
1315
4361
                                                (uint32_t) 0,
 
4362
                                                Field::NONE,
1316
4363
                                                NULL,
 
4364
                                                table->s,
1317
4365
                                                &my_charset_bin);
1318
4366
      if (!key_part_info->field)
1319
4367
        goto err;
1320
4368
      key_part_info->field->init(table);
1321
 
      key_part_info->key_type= 1; /* binary comparison */
 
4369
      key_part_info->key_type=FIELDFLAG_BINARY;
1322
4370
      key_part_info->type=    HA_KEYTYPE_BINARY;
1323
4371
      key_part_info++;
1324
4372
    }
1325
4373
    /* Create a distinct key over the columns we are going to return */
1326
 
    for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
 
4374
    for (i=param->hidden_field_count, reg_field=table->field + i ;
1327
4375
         i < field_count;
1328
4376
         i++, reg_field++, key_part_info++)
1329
4377
    {
1330
 
      key_part_info->null_bit= 0;
 
4378
      key_part_info->null_bit=0;
1331
4379
      key_part_info->field=    *reg_field;
1332
 
      key_part_info->offset=   (*reg_field)->offset(table->getInsertRecord());
 
4380
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
1333
4381
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
1334
 
      /* @todo The below method of computing the key format length of the
1335
 
        key part is a copy/paste from optimizer/range.cc, and table.cc.
 
4382
      /* TODO:
 
4383
        The below method of computing the key format length of the
 
4384
        key part is a copy/paste from opt_range.cc, and table.cc.
1336
4385
        This should be factored out, e.g. as a method of Field.
1337
4386
        In addition it is not clear if any of the Field::*_length
1338
4387
        methods is supposed to compute the same length. If so, it
1351
4400
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1352
4401
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1353
4402
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1354
 
        0 : 1;
 
4403
        0 : FIELDFLAG_BINARY;
1355
4404
    }
1356
4405
  }
1357
4406
 
1358
4407
  if (session->is_fatal_error)                          // If end of memory
1359
 
    goto err;
1360
 
  table->getMutableShare()->db_record_offset= 1;
1361
 
  if (table->getShare()->db_type() == myisam_engine)
 
4408
    goto err;                                    /* purecov: inspected */
 
4409
  share->db_record_offset= 1;
 
4410
  if (share->db_type() == myisam_hton)
1362
4411
  {
1363
4412
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1364
4413
                                       &param->recinfo, select_options))
1365
4414
      goto err;
1366
4415
  }
1367
 
  assert(table->in_use);
1368
4416
  if (table->open_tmp_table())
1369
4417
    goto err;
1370
4418
 
1374
4422
 
1375
4423
err:
1376
4424
  session->mem_root= mem_root_save;
1377
 
  table= NULL;
1378
 
 
1379
 
  return NULL;
 
4425
  table->free_tmp_table(session);                    /* purecov: inspected */
 
4426
  if (temp_pool_slot != MY_BIT_NONE)
 
4427
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
4428
  return(NULL);                         /* purecov: inspected */
1380
4429
}
1381
4430
 
1382
4431
/****************************************************************************/
1383
4432
 
1384
 
void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
1385
 
                               boost::dynamic_bitset<>& write_set_arg)
1386
 
{
1387
 
  read_set= &read_set_arg;
1388
 
  write_set= &write_set_arg;
1389
 
}
1390
 
 
1391
 
 
1392
 
const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
1393
 
{
1394
 
  const boost::dynamic_bitset<> old= in_map;
1395
 
  in_map= getShare()->all_set;
 
4433
/**
 
4434
  Create a reduced Table object with properly set up Field list from a
 
4435
  list of field definitions.
 
4436
 
 
4437
    The created table doesn't have a table handler associated with
 
4438
    it, has no keys, no group/distinct, no copy_funcs array.
 
4439
    The sole purpose of this Table object is to use the power of Field
 
4440
    class to read/write data to/from table->record[0]. Then one can store
 
4441
    the record in any container (RB tree, hash, etc).
 
4442
    The table is created in Session mem_root, so are the table's fields.
 
4443
    Consequently, if you don't BLOB fields, you don't need to free it.
 
4444
 
 
4445
  @param session         connection handle
 
4446
  @param field_list  list of column definitions
 
4447
 
 
4448
  @return
 
4449
    0 if out of memory, Table object in case of success
 
4450
*/
 
4451
 
 
4452
Table *create_virtual_tmp_table(Session *session, List<Create_field> &field_list)
 
4453
{
 
4454
  uint32_t field_count= field_list.elements;
 
4455
  uint32_t blob_count= 0;
 
4456
  Field **field;
 
4457
  Create_field *cdef;                           /* column definition */
 
4458
  uint32_t record_length= 0;
 
4459
  uint32_t null_count= 0;                 /* number of columns which may be null */
 
4460
  uint32_t null_pack_length;              /* NULL representation array length */
 
4461
  uint32_t *blob_field;
 
4462
  unsigned char *bitmaps;
 
4463
  Table *table;
 
4464
  TABLE_SHARE *share;
 
4465
 
 
4466
  if (!multi_alloc_root(session->mem_root,
 
4467
                        &table, sizeof(*table),
 
4468
                        &share, sizeof(*share),
 
4469
                        &field, (field_count + 1) * sizeof(Field*),
 
4470
                        &blob_field, (field_count+1) *sizeof(uint32_t),
 
4471
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
4472
                        NULL))
 
4473
    return 0;
 
4474
 
 
4475
  memset(table, 0, sizeof(*table));
 
4476
  memset(share, 0, sizeof(*share));
 
4477
  table->field= field;
 
4478
  table->s= share;
 
4479
  share->blob_field= blob_field;
 
4480
  share->fields= field_count;
 
4481
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
4482
  table->setup_tmp_table_column_bitmaps(bitmaps);
 
4483
 
 
4484
  /* Create all fields and calculate the total length of record */
 
4485
  List_iterator_fast<Create_field> it(field_list);
 
4486
  while ((cdef= it++))
 
4487
  {
 
4488
    *field= make_field(share, NULL, 0, cdef->length,
 
4489
                       (unsigned char*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
 
4490
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
 
4491
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
 
4492
                       cdef->unireg_check,
 
4493
                       cdef->interval, cdef->field_name);
 
4494
    if (!*field)
 
4495
      goto error;
 
4496
    (*field)->init(table);
 
4497
    record_length+= (*field)->pack_length();
 
4498
    if (! ((*field)->flags & NOT_NULL_FLAG))
 
4499
      null_count++;
 
4500
 
 
4501
    if ((*field)->flags & BLOB_FLAG)
 
4502
      share->blob_field[blob_count++]= (uint32_t) (field - table->field);
 
4503
 
 
4504
    field++;
 
4505
  }
 
4506
  *field= NULL;                             /* mark the end of the list */
 
4507
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
 
4508
  share->blob_fields= blob_count;
 
4509
 
 
4510
  null_pack_length= (null_count + 7)/8;
 
4511
  share->reclength= record_length + null_pack_length;
 
4512
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
4513
  table->record[0]= (unsigned char*) session->alloc(share->rec_buff_length);
 
4514
  if (!table->record[0])
 
4515
    goto error;
 
4516
 
 
4517
  if (null_pack_length)
 
4518
  {
 
4519
    table->null_flags= (unsigned char*) table->record[0];
 
4520
    share->null_fields= null_count;
 
4521
    share->null_bytes= null_pack_length;
 
4522
  }
 
4523
 
 
4524
  table->in_use= session;           /* field->reset() may access table->in_use */
 
4525
  {
 
4526
    /* Set up field pointers */
 
4527
    unsigned char *null_pos= table->record[0];
 
4528
    unsigned char *field_pos= null_pos + share->null_bytes;
 
4529
    uint32_t null_bit= 1;
 
4530
 
 
4531
    for (field= table->field; *field; ++field)
 
4532
    {
 
4533
      Field *cur_field= *field;
 
4534
      if ((cur_field->flags & NOT_NULL_FLAG))
 
4535
        cur_field->move_field(field_pos);
 
4536
      else
 
4537
      {
 
4538
        cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
 
4539
        null_bit<<= 1;
 
4540
        if (null_bit == (1 << 8))
 
4541
        {
 
4542
          ++null_pos;
 
4543
          null_bit= 1;
 
4544
        }
 
4545
      }
 
4546
      cur_field->reset();
 
4547
 
 
4548
      field_pos+= cur_field->pack_length();
 
4549
    }
 
4550
  }
 
4551
  return table;
 
4552
error:
 
4553
  for (field= table->field; *field; ++field)
 
4554
    delete *field;                         /* just invokes field destructor */
 
4555
  return 0;
 
4556
}
 
4557
 
 
4558
 
 
4559
bool Table::open_tmp_table()
 
4560
{
 
4561
  int error;
 
4562
  if ((error=file->ha_open(this, s->table_name.str,O_RDWR,
 
4563
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
 
4564
  {
 
4565
    file->print_error(error,MYF(0)); /* purecov: inspected */
 
4566
    db_stat=0;
 
4567
    return(1);
 
4568
  }
 
4569
  (void) file->extra(HA_EXTRA_QUICK);           /* Faster */
 
4570
  return(0);
 
4571
}
 
4572
 
 
4573
 
 
4574
/*
 
4575
  Create MyISAM temporary table
 
4576
 
 
4577
  SYNOPSIS
 
4578
    create_myisam_tmp_table()
 
4579
      keyinfo         Description of the index (there is always one index)
 
4580
      start_recinfo   MyISAM's column descriptions
 
4581
      recinfo INOUT   End of MyISAM's column descriptions
 
4582
      options         Option bits
 
4583
 
 
4584
  DESCRIPTION
 
4585
    Create a MyISAM temporary table according to passed description. The is
 
4586
    assumed to have one unique index or constraint.
 
4587
 
 
4588
    The passed array or MI_COLUMNDEF structures must have this form:
 
4589
 
 
4590
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
 
4591
         when there are many nullable columns)
 
4592
      2. Table columns
 
4593
      3. One free MI_COLUMNDEF element (*recinfo points here)
 
4594
 
 
4595
    This function may use the free element to create hash column for unique
 
4596
    constraint.
 
4597
 
 
4598
   RETURN
 
4599
     false - OK
 
4600
     true  - Error
 
4601
*/
 
4602
 
 
4603
bool Table::create_myisam_tmp_table(KEY *keyinfo,
 
4604
                                    MI_COLUMNDEF *start_recinfo,
 
4605
                                    MI_COLUMNDEF **recinfo,
 
4606
                                    uint64_t options)
 
4607
{
 
4608
  int error;
 
4609
  MI_KEYDEF keydef;
 
4610
  MI_UNIQUEDEF uniquedef;
 
4611
  TABLE_SHARE *share= s;
 
4612
 
 
4613
  if (share->keys)
 
4614
  {                                             // Get keys for ni_create
 
4615
    bool using_unique_constraint=0;
 
4616
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
 
4617
                                            sizeof(*seg) * keyinfo->key_parts);
 
4618
    if (!seg)
 
4619
      goto err;
 
4620
 
 
4621
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
 
4622
    if (keyinfo->key_length >= file->max_key_length() ||
 
4623
        keyinfo->key_parts > file->max_key_parts() ||
 
4624
        share->uniques)
 
4625
    {
 
4626
      /* Can't create a key; Make a unique constraint instead of a key */
 
4627
      share->keys=    0;
 
4628
      share->uniques= 1;
 
4629
      using_unique_constraint=1;
 
4630
      memset(&uniquedef, 0, sizeof(uniquedef));
 
4631
      uniquedef.keysegs=keyinfo->key_parts;
 
4632
      uniquedef.seg=seg;
 
4633
      uniquedef.null_are_equal=1;
 
4634
 
 
4635
      /* Create extra column for hash value */
 
4636
      memset(*recinfo, 0, sizeof(**recinfo));
 
4637
      (*recinfo)->type= FIELD_CHECK;
 
4638
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
 
4639
      (*recinfo)++;
 
4640
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
 
4641
    }
 
4642
    else
 
4643
    {
 
4644
      /* Create an unique key */
 
4645
      memset(&keydef, 0, sizeof(keydef));
 
4646
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
 
4647
      keydef.keysegs=  keyinfo->key_parts;
 
4648
      keydef.seg= seg;
 
4649
    }
 
4650
    for (uint32_t i=0; i < keyinfo->key_parts ; i++,seg++)
 
4651
    {
 
4652
      Field *key_field=keyinfo->key_part[i].field;
 
4653
      seg->flag=     0;
 
4654
      seg->language= key_field->charset()->number;
 
4655
      seg->length=   keyinfo->key_part[i].length;
 
4656
      seg->start=    keyinfo->key_part[i].offset;
 
4657
      if (key_field->flags & BLOB_FLAG)
 
4658
      {
 
4659
        seg->type=
 
4660
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
 
4661
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
 
4662
        seg->bit_start= (uint8_t)(key_field->pack_length()
 
4663
                                  - share->blob_ptr_size);
 
4664
        seg->flag= HA_BLOB_PART;
 
4665
        seg->length=0;                  // Whole blob in unique constraint
 
4666
      }
 
4667
      else
 
4668
      {
 
4669
        seg->type= keyinfo->key_part[i].type;
 
4670
      }
 
4671
      if (!(key_field->flags & NOT_NULL_FLAG))
 
4672
      {
 
4673
        seg->null_bit= key_field->null_bit;
 
4674
        seg->null_pos= (uint32_t) (key_field->null_ptr - (unsigned char*) record[0]);
 
4675
        /*
 
4676
          We are using a GROUP BY on something that contains NULL
 
4677
          In this case we have to tell MyISAM that two NULL should
 
4678
          on INSERT be regarded at the same value
 
4679
        */
 
4680
        if (!using_unique_constraint)
 
4681
          keydef.flag|= HA_NULL_ARE_EQUAL;
 
4682
      }
 
4683
    }
 
4684
  }
 
4685
  MI_CREATE_INFO create_info;
 
4686
  memset(&create_info, 0, sizeof(create_info));
 
4687
 
 
4688
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
4689
      OPTION_BIG_TABLES)
 
4690
    create_info.data_file_length= ~(uint64_t) 0;
 
4691
 
 
4692
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
 
4693
                       (uint32_t) (*recinfo-start_recinfo),
 
4694
                       start_recinfo,
 
4695
                       share->uniques, &uniquedef,
 
4696
                       &create_info,
 
4697
                       HA_CREATE_TMP_TABLE)))
 
4698
  {
 
4699
    file->print_error(error,MYF(0));    /* purecov: inspected */
 
4700
    db_stat=0;
 
4701
    goto err;
 
4702
  }
 
4703
  status_var_increment(in_use->status_var.created_tmp_disk_tables);
 
4704
  share->db_record_offset= 1;
 
4705
  return false;
 
4706
 err:
 
4707
  return true;
 
4708
}
 
4709
 
 
4710
 
 
4711
void Table::free_tmp_table(Session *session)
 
4712
{
 
4713
  MEM_ROOT own_root= mem_root;
 
4714
  const char *save_proc_info;
 
4715
 
 
4716
  save_proc_info=session->get_proc_info();
 
4717
  session->set_proc_info("removing tmp table");
 
4718
 
 
4719
  // Release latches since this can take a long time
 
4720
  ha_release_temporary_latches(session);
 
4721
 
 
4722
  if (file)
 
4723
  {
 
4724
    if (db_stat)
 
4725
      file->ha_drop_table(s->table_name.str);
 
4726
    else
 
4727
      file->ha_delete_table(s->table_name.str);
 
4728
    delete file;
 
4729
  }
 
4730
 
 
4731
  /* free blobs */
 
4732
  for (Field **ptr= field ; *ptr ; ptr++)
 
4733
    (*ptr)->free();
 
4734
  free_io_cache(this);
 
4735
 
 
4736
  if (temp_pool_slot != MY_BIT_NONE)
 
4737
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
4738
 
 
4739
  plugin_unlock(0, s->db_plugin);
 
4740
 
 
4741
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
 
4742
  session->set_proc_info(save_proc_info);
 
4743
 
 
4744
  return;
 
4745
}
 
4746
 
 
4747
/**
 
4748
  If a HEAP table gets full, create a MyISAM table and copy all rows
 
4749
  to this.
 
4750
*/
 
4751
 
 
4752
bool create_myisam_from_heap(Session *session, Table *table,
 
4753
                             MI_COLUMNDEF *start_recinfo,
 
4754
                             MI_COLUMNDEF **recinfo,
 
4755
                             int error, bool ignore_last_dupp_key_error)
 
4756
{
 
4757
  Table new_table;
 
4758
  TABLE_SHARE share;
 
4759
  const char *save_proc_info;
 
4760
  int write_err;
 
4761
 
 
4762
  if (table->s->db_type() != heap_hton ||
 
4763
      error != HA_ERR_RECORD_FILE_FULL)
 
4764
  {
 
4765
    table->file->print_error(error,MYF(0));
 
4766
    return(1);
 
4767
  }
 
4768
 
 
4769
  // Release latches since this can take a long time
 
4770
  ha_release_temporary_latches(session);
 
4771
 
 
4772
  new_table= *table;
 
4773
  share= *table->s;
 
4774
  new_table.s= &share;
 
4775
  new_table.s->db_plugin= ha_lock_engine(session, myisam_hton);
 
4776
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
 
4777
                                        new_table.s->db_type())))
 
4778
    return(1);                          // End of memory
 
4779
 
 
4780
  save_proc_info=session->get_proc_info();
 
4781
  session->set_proc_info("converting HEAP to MyISAM");
 
4782
 
 
4783
  if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
 
4784
                                        recinfo, session->lex->select_lex.options |
 
4785
                                        session->options))
 
4786
    goto err2;
 
4787
  if (new_table.open_tmp_table())
 
4788
    goto err1;
 
4789
  if (table->file->indexes_are_disabled())
 
4790
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
 
4791
  table->file->ha_index_or_rnd_end();
 
4792
  table->file->ha_rnd_init(1);
 
4793
  if (table->no_rows)
 
4794
  {
 
4795
    new_table.file->extra(HA_EXTRA_NO_ROWS);
 
4796
    new_table.no_rows=1;
 
4797
  }
 
4798
 
 
4799
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
 
4800
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
 
4801
 
 
4802
  /*
 
4803
    copy all old rows from heap table to MyISAM table
 
4804
    This is the only code that uses record[1] to read/write but this
 
4805
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
 
4806
  */
 
4807
  while (!table->file->rnd_next(new_table.record[1]))
 
4808
  {
 
4809
    write_err= new_table.file->ha_write_row(new_table.record[1]);
 
4810
    if (write_err)
 
4811
      goto err;
 
4812
  }
 
4813
  /* copy row that filled HEAP table */
 
4814
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
 
4815
  {
 
4816
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
 
4817
        !ignore_last_dupp_key_error)
 
4818
      goto err;
 
4819
  }
 
4820
 
 
4821
  /* remove heap table and change to use myisam table */
 
4822
  (void) table->file->ha_rnd_end();
 
4823
  (void) table->file->close();                  // This deletes the table !
 
4824
  delete table->file;
 
4825
  table->file=0;
 
4826
  plugin_unlock(0, table->s->db_plugin);
 
4827
  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
 
4828
  new_table.s= table->s;                       // Keep old share
 
4829
  *table= new_table;
 
4830
  *table->s= share;
 
4831
 
 
4832
  table->file->change_table_ptr(table, table->s);
 
4833
  table->use_all_columns();
 
4834
  if (save_proc_info)
 
4835
  {
 
4836
    const char *new_proc_info=
 
4837
      (!strcmp(save_proc_info,"Copying to tmp table") ?
 
4838
      "Copying to tmp table on disk" : save_proc_info);
 
4839
    session->set_proc_info(new_proc_info);
 
4840
  }
 
4841
  return(0);
 
4842
 
 
4843
 err:
 
4844
  table->file->print_error(write_err, MYF(0));
 
4845
  (void) table->file->ha_rnd_end();
 
4846
  (void) new_table.file->close();
 
4847
 err1:
 
4848
  new_table.file->ha_delete_table(new_table.s->table_name.str);
 
4849
 err2:
 
4850
  delete new_table.file;
 
4851
  session->set_proc_info(save_proc_info);
 
4852
  table->mem_root= new_table.mem_root;
 
4853
  return(1);
 
4854
}
 
4855
 
 
4856
my_bitmap_map *Table::use_all_columns(MY_BITMAP *bitmap)
 
4857
{
 
4858
  my_bitmap_map *old= bitmap->bitmap;
 
4859
  bitmap->bitmap= s->all_set.bitmap;
1396
4860
  return old;
1397
4861
}
1398
4862
 
1399
 
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
 
4863
void Table::restore_column_map(my_bitmap_map *old)
1400
4864
{
1401
 
  for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
1402
 
  {
1403
 
    if (old.test(i))
1404
 
    {
1405
 
      read_set->set(i);
1406
 
    }
1407
 
    else
1408
 
    {
1409
 
      read_set->reset(i);
1410
 
    }
1411
 
  }
 
4865
  read_set->bitmap= old;
1412
4866
}
1413
4867
 
1414
4868
uint32_t Table::find_shortest_key(const key_map *usable_keys)
1415
4869
{
1416
4870
  uint32_t min_length= UINT32_MAX;
1417
4871
  uint32_t best= MAX_KEY;
1418
 
  if (usable_keys->any())
 
4872
  if (!usable_keys->is_clear_all())
1419
4873
  {
1420
 
    for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
 
4874
    for (uint32_t nr=0; nr < s->keys ; nr++)
1421
4875
    {
1422
 
      if (usable_keys->test(nr))
 
4876
      if (usable_keys->is_set(nr))
1423
4877
      {
1424
4878
        if (key_info[nr].key_length < min_length)
1425
4879
        {
1444
4898
{
1445
4899
  for (; *ptr ; ptr++)
1446
4900
  {
1447
 
    if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
 
4901
    if ((*ptr)->cmp_offset(s->rec_buff_length))
1448
4902
      return true;
1449
4903
  }
1450
4904
  return false;
1451
4905
}
1452
4906
 
1453
 
/**
1454
 
   True if the table's input and output record buffers are comparable using
1455
 
   compare_records(TABLE*).
1456
 
 */
1457
 
bool Table::records_are_comparable()
1458
 
{
1459
 
  return ((getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) == 0) ||
1460
 
          write_set->is_subset_of(*read_set));
1461
 
}
1462
 
 
1463
 
/**
1464
 
   Compares the input and outbut record buffers of the table to see if a row
1465
 
   has changed. The algorithm iterates over updated columns and if they are
1466
 
   nullable compares NULL bits in the buffer before comparing actual
1467
 
   data. Special care must be taken to compare only the relevant NULL bits and
1468
 
   mask out all others as they may be undefined. The storage engine will not
1469
 
   and should not touch them.
1470
 
 
1471
 
   @param table The table to evaluate.
1472
 
 
1473
 
   @return true if row has changed.
1474
 
   @return false otherwise.
1475
 
*/
1476
 
bool Table::compare_records()
1477
 
{
1478
 
  if (getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) != 0)
1479
 
  {
1480
 
    /*
1481
 
      Storage engine may not have read all columns of the record.  Fields
1482
 
      (including NULL bits) not in the write_set may not have been read and
1483
 
      can therefore not be compared.
1484
 
    */
1485
 
    for (Field **ptr= this->field ; *ptr != NULL; ptr++)
1486
 
    {
1487
 
      Field *f= *ptr;
1488
 
      if (write_set->test(f->position()))
1489
 
      {
1490
 
        if (f->real_maybe_null())
1491
 
        {
1492
 
          unsigned char null_byte_index= f->null_ptr - record[0];
1493
 
 
1494
 
          if (((record[0][null_byte_index]) & f->null_bit) !=
1495
 
              ((record[1][null_byte_index]) & f->null_bit))
1496
 
            return true;
1497
 
        }
1498
 
        if (f->cmp_binary_offset(getShare()->rec_buff_length))
1499
 
          return true;
1500
 
      }
1501
 
    }
1502
 
    return false;
1503
 
  }
1504
 
 
1505
 
  /*
1506
 
    The storage engine has read all columns, so it's safe to compare all bits
1507
 
    including those not in the write_set. This is cheaper than the
1508
 
    field-by-field comparison done above.
1509
 
  */
1510
 
  if (not getShare()->blob_fields + getShare()->hasVariableWidth())
1511
 
    // Fixed-size record: do bitwise comparison of the records
1512
 
    return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
1513
 
 
 
4907
/* Return false if row hasn't changed */
 
4908
 
 
4909
bool Table::compare_record()
 
4910
{
 
4911
  if (s->blob_fields + s->varchar_fields == 0)
 
4912
    return cmp_record(this, record[1]);
1514
4913
  /* Compare null bits */
1515
 
  if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
1516
 
    return true; /* Diff in NULL value */
1517
 
 
 
4914
  if (memcmp(null_flags,
 
4915
             null_flags + s->rec_buff_length,
 
4916
             s->null_bytes))
 
4917
    return true;                                // Diff in NULL value
1518
4918
  /* Compare updated fields */
1519
4919
  for (Field **ptr= field ; *ptr ; ptr++)
1520
4920
  {
1521
 
    if (isWriteSet((*ptr)->position()) &&
1522
 
        (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
 
4921
    if (bitmap_is_set(write_set, (*ptr)->field_index) &&
 
4922
        (*ptr)->cmp_binary_offset(s->rec_buff_length))
1523
4923
      return true;
1524
4924
  }
1525
4925
  return false;
1526
4926
}
1527
4927
 
1528
 
/*
1529
 
 * Store a record from previous record into next
1530
 
 *
1531
 
 */
1532
 
void Table::storeRecord()
1533
 
{
1534
 
  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1535
 
}
1536
 
 
1537
 
/*
1538
 
 * Store a record as an insert
1539
 
 *
1540
 
 */
1541
 
void Table::storeRecordAsInsert()
1542
 
{
1543
 
  assert(insert_values.size() >= getShare()->getRecordLength());
1544
 
  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
1545
 
}
1546
 
 
1547
 
/*
1548
 
 * Store a record with default values
1549
 
 *
1550
 
 */
1551
 
void Table::storeRecordAsDefault()
1552
 
{
1553
 
  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1554
 
}
1555
 
 
1556
 
/*
1557
 
 * Restore a record from previous record into next
1558
 
 *
1559
 
 */
1560
 
void Table::restoreRecord()
1561
 
{
1562
 
  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
1563
 
}
1564
 
 
1565
 
/*
1566
 
 * Restore a record with default values
1567
 
 *
1568
 
 */
1569
 
void Table::restoreRecordAsDefault()
1570
 
{
1571
 
  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
1572
 
}
1573
 
 
1574
 
/*
1575
 
 * Empty a record
1576
 
 *
1577
 
 */
1578
 
void Table::emptyRecord()
1579
 
{
1580
 
  restoreRecordAsDefault();
1581
 
  memset(null_flags, 255, getShare()->null_bytes);
1582
 
}
1583
 
 
1584
 
Table::Table() : 
1585
 
  field(NULL),
1586
 
  cursor(NULL),
1587
 
  next(NULL),
1588
 
  prev(NULL),
1589
 
  read_set(NULL),
1590
 
  write_set(NULL),
1591
 
  tablenr(0),
1592
 
  db_stat(0),
1593
 
  def_read_set(),
1594
 
  def_write_set(),
1595
 
  tmp_set(),
1596
 
  in_use(NULL),
1597
 
  key_info(NULL),
1598
 
  next_number_field(NULL),
1599
 
  found_next_number_field(NULL),
1600
 
  timestamp_field(NULL),
1601
 
  pos_in_table_list(NULL),
1602
 
  group(NULL),
1603
 
  null_flags(NULL),
1604
 
  lock_position(0),
1605
 
  lock_data_start(0),
1606
 
  lock_count(0),
1607
 
  used_fields(0),
1608
 
  status(0),
1609
 
  derived_select_number(0),
1610
 
  current_lock(F_UNLCK),
1611
 
  copy_blobs(false),
1612
 
  maybe_null(false),
1613
 
  null_row(false),
1614
 
  force_index(false),
1615
 
  distinct(false),
1616
 
  const_table(false),
1617
 
  no_rows(false),
1618
 
  key_read(false),
1619
 
  no_keyread(false),
1620
 
  open_placeholder(false),
1621
 
  locked_by_name(false),
1622
 
  no_cache(false),
1623
 
  auto_increment_field_not_null(false),
1624
 
  alias_name_used(false),
1625
 
  query_id(0),
1626
 
  quick_condition_rows(0),
1627
 
  timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1628
 
  map(0),
1629
 
  quick_rows(),
1630
 
  const_key_parts(),
1631
 
  quick_key_parts(),
1632
 
  quick_n_ranges()
1633
 
{
1634
 
  record[0]= (unsigned char *) 0;
1635
 
  record[1]= (unsigned char *) 0;
1636
 
}
 
4928
 
 
4929
 
 
4930
 
1637
4931
 
1638
4932
/*****************************************************************************
1639
4933
  The different ways to read a record
1640
4934
  Returns -1 if row was not found, 0 if row was found and 1 on errors
1641
4935
*****************************************************************************/
1642
4936
 
1643
 
/** Help function when we get some an error from the table Cursor. */
 
4937
/** Help function when we get some an error from the table handler. */
1644
4938
 
1645
4939
int Table::report_error(int error)
1646
4940
{
1654
4948
    print them to the .err log
1655
4949
  */
1656
4950
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
1657
 
    errmsg_printf(error::ERROR, _("Got error %d when reading table '%s'"),
1658
 
                  error, getShare()->getPath());
1659
 
  print_error(error, MYF(0));
 
4951
    errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
 
4952
                    error, s->path.str);
 
4953
  file->print_error(error,MYF(0));
1660
4954
 
1661
4955
  return 1;
1662
4956
}
1663
4957
 
1664
4958
 
1665
 
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
1666
 
{
1667
 
  used_fields= 0;
1668
 
  const_table= 0;
1669
 
  null_row= 0;
1670
 
  status= STATUS_NO_RECORD;
1671
 
  maybe_null= table_list->outer_join;
1672
 
  TableList *embedding= table_list->getEmbedding();
1673
 
  while (!maybe_null && embedding)
1674
 
  {
1675
 
    maybe_null= embedding->outer_join;
1676
 
    embedding= embedding->getEmbedding();
1677
 
  }
1678
 
  tablenr= table_number;
1679
 
  map= (table_map) 1 << table_number;
1680
 
  force_index= table_list->force_index;
1681
 
  covering_keys= getShare()->keys_for_keyread;
1682
 
  merge_keys.reset();
1683
 
}
1684
 
 
1685
 
 
1686
 
bool Table::fill_item_list(List<Item> *item_list) const
1687
 
{
1688
 
  /*
1689
 
    All Item_field's created using a direct pointer to a field
1690
 
    are fixed in Item_field constructor.
1691
 
  */
1692
 
  for (Field **ptr= field; *ptr; ptr++)
1693
 
  {
1694
 
    Item_field *item= new Item_field(*ptr);
1695
 
    if (!item || item_list->push_back(item))
1696
 
      return true;
1697
 
  }
1698
 
  return false;
1699
 
}
1700
 
 
1701
 
 
1702
 
void Table::filesort_free_buffers(bool full)
1703
 
{
1704
 
  if (sort.record_pointers)
1705
 
  {
1706
 
    free((unsigned char*) sort.record_pointers);
1707
 
    sort.record_pointers=0;
1708
 
  }
1709
 
  if (full)
1710
 
  {
1711
 
    if (sort.sort_keys )
1712
 
    {
1713
 
      if ((unsigned char*) sort.sort_keys)
1714
 
        free((unsigned char*) sort.sort_keys);
1715
 
      sort.sort_keys= 0;
1716
 
    }
1717
 
    if (sort.buffpek)
1718
 
    {
1719
 
      if ((unsigned char*) sort.buffpek)
1720
 
        free((unsigned char*) sort.buffpek);
1721
 
      sort.buffpek= 0;
1722
 
      sort.buffpek_len= 0;
1723
 
    }
1724
 
  }
1725
 
 
1726
 
  if (sort.addon_buf)
1727
 
  {
1728
 
    free((char *) sort.addon_buf);
1729
 
    free((char *) sort.addon_field);
1730
 
    sort.addon_buf=0;
1731
 
    sort.addon_field=0;
1732
 
  }
1733
 
}
1734
 
 
1735
4959
/*
1736
 
  Is this instance of the table should be reopen or represents a name-lock?
 
4960
  Calculate data for each virtual field marked for write in the
 
4961
  corresponding column map.
 
4962
 
 
4963
  SYNOPSIS
 
4964
    update_virtual_fields_marked_for_write()
 
4965
    table                  The Table object
 
4966
    ignore_stored          Indication whether physically stored virtual
 
4967
                           fields do not need updating.
 
4968
                           This value is false when during INSERT and UPDATE
 
4969
                           and true in all other cases.
 
4970
 
 
4971
  RETURN
 
4972
    0  - Success
 
4973
    >0 - Error occurred during the generation/calculation of a virtual field value
 
4974
 
1737
4975
*/
1738
 
bool Table::needs_reopen_or_name_lock() const
1739
 
1740
 
  return getShare()->getVersion() != refresh_version;
1741
 
}
1742
 
 
1743
 
uint32_t Table::index_flags(uint32_t idx) const
1744
 
{
1745
 
  return getShare()->getEngine()->index_flags(getShare()->getKeyInfo(idx).algorithm);
1746
 
}
1747
 
 
1748
 
void Table::print_error(int error, myf errflag) const
1749
 
{
1750
 
  getShare()->getEngine()->print_error(error, errflag, *this);
1751
 
}
1752
 
 
1753
 
} /* namespace drizzled */
 
4976
 
 
4977
int update_virtual_fields_marked_for_write(Table *table,
 
4978
                                           bool ignore_stored)
 
4979
{
 
4980
  Field **vfield_ptr, *vfield;
 
4981
  int error= 0;
 
4982
  if ((not table) or (not table->vfield))
 
4983
    return(0);
 
4984
 
 
4985
  /* Iterate over virtual fields in the table */
 
4986
  for (vfield_ptr= table->vfield; *vfield_ptr; vfield_ptr++)
 
4987
  {
 
4988
    vfield= (*vfield_ptr);
 
4989
    assert(vfield->vcol_info && vfield->vcol_info->expr_item);
 
4990
    /*
 
4991
      Only update those fields that are marked in the write_set bitmap
 
4992
      and not _already_ physically stored in the database.
 
4993
    */
 
4994
    if (bitmap_is_set(table->write_set, vfield->field_index) &&
 
4995
        (not (ignore_stored && vfield->is_stored))
 
4996
       )
 
4997
    {
 
4998
      /* Generate the actual value of the virtual fields */
 
4999
      error= vfield->vcol_info->expr_item->save_in_field(vfield, 0);
 
5000
    }
 
5001
  }
 
5002
  return(0);
 
5003
}
 
5004
 
 
5005
 
 
5006
void setup_table_map(Table *table, TableList *table_list, uint32_t tablenr)
 
5007
{
 
5008
  table->used_fields= 0;
 
5009
  table->const_table= 0;
 
5010
  table->null_row= 0;
 
5011
  table->status= STATUS_NO_RECORD;
 
5012
  table->maybe_null= table_list->outer_join;
 
5013
  TableList *embedding= table_list->embedding;
 
5014
  while (!table->maybe_null && embedding)
 
5015
  {
 
5016
    table->maybe_null= embedding->outer_join;
 
5017
    embedding= embedding->embedding;
 
5018
  }
 
5019
  table->tablenr= tablenr;
 
5020
  table->map= (table_map) 1 << tablenr;
 
5021
  table->force_index= table_list->force_index;
 
5022
  table->covering_keys= table->s->keys_for_keyread;
 
5023
  table->merge_keys.clear_all();
 
5024
}
 
5025
 
 
5026
 
 
5027
/*****************************************************************************
 
5028
** Instansiate templates
 
5029
*****************************************************************************/
 
5030
 
 
5031
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
5032
template class List<String>;
 
5033
template class List_iterator<String>;
 
5034
#endif