167
Initialize share for temporary tables
170
init_tmp_table_share()
173
key Table_cache_key, as generated from create_table_def_key.
174
must start with db name.
175
key_length Length of key
176
table_name Table name
177
path Path to file (possible in lower case) without .frm
180
This is different from alloc_table_share() because temporary tables
181
don't have to be shared between threads or put into the table def
182
cache, so we can do some things notable simpler and faster
184
If table is not put in thd->temporary_tables (happens only when
185
one uses OPEN TEMPORARY) then one can specify 'db' as key and
186
use key_length= 0 as neither table_cache_key or key_length will be used).
189
void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
190
uint key_length, const char *table_name,
194
memset(share, 0, sizeof(*share));
195
init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
196
share->table_category= TABLE_CATEGORY_TEMPORARY;
197
share->tmp_table= INTERNAL_TMP_TABLE;
198
share->db.str= (char*) key;
199
share->db.length= strlen(key);
200
share->table_cache_key.str= (char*) key;
201
share->table_cache_key.length= key_length;
202
share->table_name.str= (char*) table_name;
203
share->table_name.length= strlen(table_name);
204
share->path.str= (char*) path;
205
share->normalized_path.str= (char*) path;
206
share->path.length= share->normalized_path.length= strlen(path);
207
share->frm_version= FRM_VER_TRUE_VARCHAR;
209
Temporary tables are not replicated, but we set up these fields
210
anyway to be able to catch errors.
212
share->table_map_version= ~(uint64_t)0;
213
share->cached_row_logging_check= -1;
216
table_map_id is also used for MERGE tables to suppress repeated
217
compatibility checks.
219
share->table_map_id= (ulong) thd->query_id;
226
Free table share and memory used by it
233
share->mutex must be locked when we come here if it's not a temp table
236
void free_table_share(TABLE_SHARE *share)
239
assert(share->ref_count == 0);
242
If someone is waiting for this to be deleted, inform it about this.
243
Don't do a delete until we know that no one is refering to this anymore.
245
if (share->tmp_table == NO_TMP_TABLE)
247
/* share->mutex is locked in release_table_share() */
248
while (share->waiting_on_cond)
250
pthread_cond_broadcast(&share->cond);
251
pthread_cond_wait(&share->cond, &share->mutex);
253
/* No thread refers to this anymore */
254
pthread_mutex_unlock(&share->mutex);
255
pthread_mutex_destroy(&share->mutex);
256
pthread_cond_destroy(&share->cond);
258
hash_free(&share->name_hash);
260
plugin_unlock(NULL, share->db_plugin);
261
share->db_plugin= NULL;
263
/* We must copy mem_root from share because share is allocated through it */
264
memcpy(&mem_root, &share->mem_root, sizeof(mem_root));
265
free_root(&mem_root, MYF(0)); // Free's share
270
Read table definition from a binary / text based .frm file
275
share Fill this with table definition
276
db_flags Bit mask of the following flags: OPEN_VIEW
279
This function is called when the table definition is not cached in
281
The data is returned in 'share', which is alloced by
282
alloc_table_share().. The code assumes that share is initialized.
286
1 Error (see open_table_error)
287
2 Error (see open_table_error)
288
3 Wrong data in .frm file
289
4 Error (see open_table_error)
290
5 Error (see open_table_error: charset unavailable)
291
6 Unknown .frm version
294
int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags)
296
int error, table_type;
299
uchar head[64], *disk_buff;
300
char path[FN_REFLEN];
301
MEM_ROOT **root_ptr, *old_root;
307
strxmov(path, share->normalized_path.str, reg_ext, NullS);
308
if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
311
We don't try to open 5.0 unencoded name, if
312
- non-encoded name contains '@' signs,
313
because '@' can be misinterpreted.
314
It is not clear if '@' is escape character in 5.1,
315
or a normal character in 5.0.
317
- non-encoded db or table name contain "#mysql50#" prefix.
318
This kind of tables must have been opened only by the
321
if (strchr(share->table_name.str, '@') ||
322
!strncmp(share->db.str, MYSQL50_TABLE_NAME_PREFIX,
323
MYSQL50_TABLE_NAME_PREFIX_LENGTH) ||
324
!strncmp(share->table_name.str, MYSQL50_TABLE_NAME_PREFIX,
325
MYSQL50_TABLE_NAME_PREFIX_LENGTH))
328
/* Try unencoded 5.0 name */
330
strxnmov(path, sizeof(path)-1,
331
mysql_data_home, "/", share->db.str, "/",
332
share->table_name.str, reg_ext, NullS);
333
length= unpack_filename(path, path) - reg_ext_length;
335
The following is a safety test and should never fail
336
as the old file name should never be longer than the new one.
338
assert(length <= share->normalized_path.length);
340
If the old and the new names have the same length,
341
then table name does not have tricky characters,
342
so no need to check the old file name.
344
if (length == share->normalized_path.length ||
345
((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0))
348
/* Unencoded 5.0 table name found */
349
path[length]= '\0'; // Remove .frm extension
350
stpcpy(share->normalized_path.str, path);
351
share->normalized_path.length= length;
355
if (my_read(file, head, 64, MYF(MY_NABP)))
358
if (head[0] == (uchar) 254 && head[1] == 1)
360
if (head[2] == FRM_VER || head[2] == FRM_VER+1 ||
361
(head[2] >= FRM_VER+3 && head[2] <= FRM_VER+4))
364
if (db_flags & OPEN_VIEW_ONLY)
373
error= 6; // Unkown .frm version
380
/* No handling of text based files yet */
383
root_ptr= (MEM_ROOT **)pthread_getspecific(THR_MALLOC);
385
*root_ptr= &share->mem_root;
386
error= open_binary_frm(thd, share, head, file);
149
static enum_field_types proto_field_type_to_drizzle_type(uint32_t proto_field_type)
151
enum_field_types field_type;
153
switch(proto_field_type)
155
case message::Table::Field::INTEGER:
156
field_type= DRIZZLE_TYPE_LONG;
158
case message::Table::Field::DOUBLE:
159
field_type= DRIZZLE_TYPE_DOUBLE;
161
case message::Table::Field::TIMESTAMP:
162
field_type= DRIZZLE_TYPE_TIMESTAMP;
164
case message::Table::Field::BIGINT:
165
field_type= DRIZZLE_TYPE_LONGLONG;
167
case message::Table::Field::DATETIME:
168
field_type= DRIZZLE_TYPE_DATETIME;
170
case message::Table::Field::DATE:
171
field_type= DRIZZLE_TYPE_DATE;
173
case message::Table::Field::VARCHAR:
174
field_type= DRIZZLE_TYPE_VARCHAR;
176
case message::Table::Field::DECIMAL:
177
field_type= DRIZZLE_TYPE_DECIMAL;
179
case message::Table::Field::ENUM:
180
field_type= DRIZZLE_TYPE_ENUM;
182
case message::Table::Field::BLOB:
183
field_type= DRIZZLE_TYPE_BLOB;
186
field_type= DRIZZLE_TYPE_LONG; /* Set value to kill GCC warning */
393
share->table_category= get_table_category(& share->db, & share->table_name);
396
thd->status_var.opened_shares++;
399
my_close(file, MYF(MY_WME));
402
if (error && !error_given)
405
open_table_error(share, error, (share->open_errno= my_errno), 0);
413
Read data from a binary .frm file from MySQL 3.23 - 5.0 into TABLE_SHARE
416
static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
419
int error, errarg= 0;
420
uint new_frm_ver, field_pack_length, new_field_pack_flag;
421
uint interval_count, interval_parts, read_length, int_length;
422
uint db_create_options, keys, key_parts, n_length;
423
uint key_info_length, com_length, null_bit_pos=0;
424
uint extra_rec_buf_length;
428
char *keynames, *names, *comment_pos;
430
uchar *disk_buff, *strpos, *null_flags=NULL, *null_pos=NULL;
431
ulong pos, record_offset, *rec_per_key, rec_buff_length;
432
handler *handler_file= 0;
434
KEY_PART_INFO *key_part;
435
Field **field_ptr, *reg_field;
436
const char **interval_array;
437
enum legacy_db_type legacy_db_type;
438
my_bitmap_map *bitmaps;
440
uchar *field_extra_info= 0;
442
new_field_pack_flag= head[27];
443
new_frm_ver= (head[2] - FRM_VER);
444
field_pack_length= new_frm_ver < 2 ? 11 : 17;
448
if (!(pos=get_form_pos(file,head,(TYPELIB*) 0)))
449
goto err; /* purecov: inspected */
450
VOID(my_seek(file,pos,MY_SEEK_SET,MYF(0)));
451
if (my_read(file,forminfo,288,MYF(MY_NABP)))
454
share->frm_version= head[2];
456
Check if .frm file created by MySQL 5.0. In this case we want to
457
display CHAR fields as CHAR and not as VARCHAR.
458
We do it this way as we want to keep the old frm version to enable
459
MySQL 4.1 to read these files.
461
if (share->frm_version == FRM_VER_TRUE_VARCHAR -1 && head[33] == 5)
462
share->frm_version= FRM_VER_TRUE_VARCHAR;
464
legacy_db_type= DB_TYPE_FIRST_DYNAMIC;
465
assert(share->db_plugin == NULL);
467
if the storage engine is dynamic, no point in resolving it by its
468
dynamically allocated legacy_db_type. We will resolve it later by name.
470
if (legacy_db_type > DB_TYPE_UNKNOWN &&
471
legacy_db_type < DB_TYPE_FIRST_DYNAMIC)
472
share->db_plugin= ha_lock_engine(NULL,
473
ha_checktype(thd, legacy_db_type, 0, 0));
474
share->db_create_options= db_create_options= uint2korr(head+30);
193
static Item *default_value_item(enum_field_types field_type,
194
const CHARSET_INFO *charset,
195
bool default_null, const string *default_value,
196
const string *default_bin_value)
198
Item *default_item= NULL;
203
return new Item_null();
208
case DRIZZLE_TYPE_LONG:
209
case DRIZZLE_TYPE_LONGLONG:
210
default_item= new Item_int(default_value->c_str(),
211
(int64_t) my_strtoll10(default_value->c_str(),
214
default_value->length());
216
case DRIZZLE_TYPE_DOUBLE:
217
default_item= new Item_float(default_value->c_str(),
218
default_value->length());
220
case DRIZZLE_TYPE_NULL:
222
case DRIZZLE_TYPE_TIMESTAMP:
223
case DRIZZLE_TYPE_DATETIME:
224
case DRIZZLE_TYPE_DATE:
225
if (default_value->compare("NOW()") == 0)
227
case DRIZZLE_TYPE_ENUM:
228
default_item= new Item_string(default_value->c_str(),
229
default_value->length(),
230
system_charset_info);
232
case DRIZZLE_TYPE_VARCHAR:
233
case DRIZZLE_TYPE_BLOB: /* Blob is here due to TINYTEXT. Feel the hate. */
234
if (charset==&my_charset_bin)
236
default_item= new Item_string(default_bin_value->c_str(),
237
default_bin_value->length(),
242
default_item= new Item_string(default_value->c_str(),
243
default_value->length(),
244
system_charset_info);
247
case DRIZZLE_TYPE_DECIMAL:
248
default_item= new Item_decimal(default_value->c_str(),
249
default_value->length(),
250
system_charset_info);
257
int drizzled::parse_table_proto(Session& session,
258
message::Table &table,
263
share->setTableProto(new(nothrow) message::Table(table));
265
share->storage_engine= plugin::StorageEngine::findByName(session, table.engine().name());
266
assert(share->storage_engine); // We use an assert() here because we should never get this far and still have no suitable engine.
268
message::Table::TableOptions table_options;
270
if (table.has_options())
271
table_options= table.options();
273
uint32_t db_create_options= 0;
275
if (table_options.has_pack_keys())
277
if (table_options.pack_keys())
278
db_create_options|= HA_OPTION_PACK_KEYS;
280
db_create_options|= HA_OPTION_NO_PACK_KEYS;
283
if (table_options.pack_record())
284
db_create_options|= HA_OPTION_PACK_RECORD;
286
/* db_create_options was stored as 2 bytes in FRM
287
Any HA_OPTION_ that doesn't fit into 2 bytes was silently truncated away.
289
share->db_create_options= (db_create_options & 0x0000FFFF);
475
290
share->db_options_in_use= share->db_create_options;
476
share->mysql_version= uint4korr(head+51);
477
share->null_field_first= 0;
478
if (!head[32]) // New frm file in 3.23
480
share->avg_row_length= uint4korr(head+34);
481
share->transactional= (ha_choice) (head[39] & 3);
482
share->page_checksum= (ha_choice) ((head[39] >> 2) & 3);
483
share->row_type= (row_type) head[40];
484
share->block_size= uint4korr(head+43);
485
share->table_charset= get_charset((uint) head[38],MYF(0));
486
share->null_field_first= 1;
292
share->row_type= table_options.has_row_type() ?
293
(enum row_type) table_options.row_type() : ROW_TYPE_DEFAULT;
295
share->block_size= table_options.has_block_size() ?
296
table_options.block_size() : 0;
298
share->table_charset= get_charset(table_options.has_collation_id()?
299
table_options.collation_id() : 0);
488
301
if (!share->table_charset)
490
303
/* unknown charset in head[38] or pre-3.23 frm */
491
304
if (use_mb(default_charset_info))
493
306
/* Warn that we may be changing the size of character columns */
494
sql_print_warning(_("'%s' had no or invalid character set, "
495
"and default character set is multi-byte, "
496
"so character column sizes may have changed"),
307
errmsg_printf(ERRMSG_LVL_WARN,
308
_("'%s' had no or invalid character set, "
309
"and default character set is multi-byte, "
310
"so character column sizes may have changed"),
499
313
share->table_charset= default_charset_info;
501
316
share->db_record_offset= 1;
502
if (db_create_options & HA_OPTION_LONG_BLOB_PTR)
503
share->blob_ptr_size= portable_sizeof_char_ptr;
504
/* Set temporarily a good value for db_low_byte_first */
505
share->db_low_byte_first= test(legacy_db_type != DB_TYPE_ISAM);
507
share->max_rows= uint4korr(head+18);
508
share->min_rows= uint4korr(head+22);
510
/* Read keyinformation */
511
key_info_length= (uint) uint2korr(head+28);
512
VOID(my_seek(file,(ulong) uint2korr(head+6),MY_SEEK_SET,MYF(0)));
513
if (read_string(file,(uchar**) &disk_buff,key_info_length))
514
goto err; /* purecov: inspected */
515
if (disk_buff[0] & 0x80)
517
share->keys= keys= (disk_buff[1] << 7) | (disk_buff[0] & 0x7f);
518
share->key_parts= key_parts= uint2korr(disk_buff+2);
522
share->keys= keys= disk_buff[0];
523
share->key_parts= key_parts= disk_buff[1];
525
share->keys_for_keyread.init(0);
526
share->keys_in_use.init(keys);
528
n_length=keys*sizeof(KEY)+key_parts*sizeof(KEY_PART_INFO);
529
if (!(keyinfo = (KEY*) alloc_root(&share->mem_root,
530
n_length + uint2korr(disk_buff+4))))
531
goto err; /* purecov: inspected */
532
memset(keyinfo, 0, n_length);
533
share->key_info= keyinfo;
534
key_part= my_reinterpret_cast(KEY_PART_INFO*) (keyinfo+keys);
537
if (!(rec_per_key= (ulong*) alloc_root(&share->mem_root,
538
sizeof(ulong*)*key_parts)))
541
for (i=0 ; i < keys ; i++, keyinfo++)
543
keyinfo->table= 0; // Updated in open_frm
544
if (new_frm_ver >= 3)
546
keyinfo->flags= (uint) uint2korr(strpos) ^ HA_NOSAME;
547
keyinfo->key_length= (uint) uint2korr(strpos+2);
548
keyinfo->key_parts= (uint) strpos[4];
549
keyinfo->algorithm= (enum ha_key_alg) strpos[5];
550
keyinfo->block_size= uint2korr(strpos+6);
554
keyinfo->key_part= key_part;
318
share->blob_ptr_size= portable_sizeof_char_ptr; // more bonghits.
320
share->keys= table.indexes_size();
323
for (int indx= 0; indx < table.indexes_size(); indx++)
324
share->key_parts+= table.indexes(indx).index_part_size();
326
share->key_info= (KEY*) alloc_root(&share->mem_root,
327
table.indexes_size() * sizeof(KEY)
328
+share->key_parts*sizeof(KEY_PART_INFO));
330
KEY_PART_INFO *key_part;
332
key_part= reinterpret_cast<KEY_PART_INFO*>
333
(share->key_info+table.indexes_size());
336
ulong *rec_per_key= (ulong*) alloc_root(&share->mem_root,
337
sizeof(ulong*)*share->key_parts);
339
share->keynames.count= table.indexes_size();
340
share->keynames.name= NULL;
341
share->keynames.type_names= (const char**)
342
alloc_root(&share->mem_root, sizeof(char*) * (table.indexes_size()+1));
344
share->keynames.type_lengths= (unsigned int*)
345
alloc_root(&share->mem_root,
346
sizeof(unsigned int) * (table.indexes_size()+1));
348
share->keynames.type_names[share->keynames.count]= NULL;
349
share->keynames.type_lengths[share->keynames.count]= 0;
351
KEY* keyinfo= share->key_info;
352
for (int keynr= 0; keynr < table.indexes_size(); keynr++, keyinfo++)
354
message::Table::Index indx= table.indexes(keynr);
359
if (indx.is_unique())
360
keyinfo->flags|= HA_NOSAME;
362
if (indx.has_options())
364
message::Table::Index::IndexOptions indx_options= indx.options();
365
if (indx_options.pack_key())
366
keyinfo->flags|= HA_PACK_KEY;
368
if (indx_options.var_length_key())
369
keyinfo->flags|= HA_VAR_LENGTH_PART;
371
if (indx_options.null_part_key())
372
keyinfo->flags|= HA_NULL_PART_KEY;
374
if (indx_options.binary_pack_key())
375
keyinfo->flags|= HA_BINARY_PACK_KEY;
377
if (indx_options.has_partial_segments())
378
keyinfo->flags|= HA_KEY_HAS_PART_KEY_SEG;
380
if (indx_options.auto_generated_key())
381
keyinfo->flags|= HA_GENERATED_KEY;
383
if (indx_options.has_key_block_size())
385
keyinfo->flags|= HA_USES_BLOCK_SIZE;
386
keyinfo->block_size= indx_options.key_block_size();
390
keyinfo->block_size= 0;
396
case message::Table::Index::UNKNOWN_INDEX:
397
keyinfo->algorithm= HA_KEY_ALG_UNDEF;
399
case message::Table::Index::BTREE:
400
keyinfo->algorithm= HA_KEY_ALG_BTREE;
402
case message::Table::Index::HASH:
403
keyinfo->algorithm= HA_KEY_ALG_HASH;
407
/* TODO: suitable warning ? */
408
keyinfo->algorithm= HA_KEY_ALG_UNDEF;
412
keyinfo->key_length= indx.key_length();
414
keyinfo->key_parts= indx.index_part_size();
416
keyinfo->key_part= key_part;
555
417
keyinfo->rec_per_key= rec_per_key;
556
for (j=keyinfo->key_parts ; j-- ; key_part++)
559
key_part->fieldnr= (uint16_t) (uint2korr(strpos) & FIELD_NR_MASK);
560
key_part->offset= (uint) uint2korr(strpos+2)-1;
561
key_part->key_type= (uint) uint2korr(strpos+5);
562
// key_part->field= (Field*) 0; // Will be fixed later
563
if (new_frm_ver >= 1)
565
key_part->key_part_flag= *(strpos+4);
566
key_part->length= (uint) uint2korr(strpos+7);
571
key_part->length= *(strpos+4);
572
key_part->key_part_flag=0;
573
if (key_part->length > 128)
575
key_part->length&=127; /* purecov: inspected */
576
key_part->key_part_flag=HA_REVERSE_SORT; /* purecov: inspected */
580
key_part->store_length=key_part->length;
583
keynames=(char*) key_part;
584
strpos+= (stpcpy(keynames, (char *) strpos) - keynames)+1;
586
//reading index comments
587
for (keyinfo= share->key_info, i=0; i < keys; i++, keyinfo++)
589
if (keyinfo->flags & HA_USES_COMMENT)
591
keyinfo->comment.length= uint2korr(strpos);
592
keyinfo->comment.str= strmake_root(&share->mem_root, (char*) strpos+2,
593
keyinfo->comment.length);
594
strpos+= 2 + keyinfo->comment.length;
596
assert(test(keyinfo->flags & HA_USES_COMMENT) ==
597
(keyinfo->comment.length > 0));
600
share->reclength = uint2korr((head+16));
602
share->system= 1; /* one-record-database */
604
record_offset= (ulong) (uint2korr(head+6)+
605
((uint2korr(head+14) == 0xffff ?
606
uint4korr(head+47) : uint2korr(head+14))));
608
if ((n_length= uint4korr(head+55)))
610
/* Read extra data segment */
611
uchar *next_chunk, *buff_end;
612
if (!(next_chunk= buff= (uchar*) my_malloc(n_length, MYF(MY_WME))))
614
if (pread(file, buff, n_length, record_offset + share->reclength) == 0)
618
share->connect_string.length= uint2korr(buff);
619
if (!(share->connect_string.str= strmake_root(&share->mem_root,
620
(char*) next_chunk + 2,
621
share->connect_string.
626
next_chunk+= share->connect_string.length + 2;
627
buff_end= buff + n_length;
628
if (next_chunk + 2 < buff_end)
630
uint str_db_type_length= uint2korr(next_chunk);
632
name.str= (char*) next_chunk + 2;
633
name.length= str_db_type_length;
635
plugin_ref tmp_plugin= ha_resolve_by_name(thd, &name);
636
if (tmp_plugin != NULL && !plugin_equals(tmp_plugin, share->db_plugin))
638
if (legacy_db_type > DB_TYPE_UNKNOWN &&
639
legacy_db_type < DB_TYPE_FIRST_DYNAMIC &&
640
legacy_db_type != ha_legacy_type(
641
plugin_data(tmp_plugin, handlerton *)))
643
/* bad file, legacy_db_type did not match the name */
644
my_free(buff, MYF(0));
648
tmp_plugin is locked with a local lock.
649
we unlock the old value of share->db_plugin before
650
replacing it with a globally locked version of tmp_plugin
652
plugin_unlock(NULL, share->db_plugin);
653
share->db_plugin= my_plugin_lock(NULL, &tmp_plugin);
655
else if (!tmp_plugin)
657
/* purecov: begin inspected */
659
my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
660
my_free(buff, MYF(0));
664
next_chunk+= str_db_type_length + 2;
666
if (share->mysql_version >= 50110)
668
/* New auto_partitioned indicator introduced in 5.1.11 */
671
if (forminfo[46] == (uchar)255)
673
//reading long table comment
674
if (next_chunk + 2 > buff_end)
676
my_free(buff, MYF(0));
679
share->comment.length = uint2korr(next_chunk);
680
if (! (share->comment.str= strmake_root(&share->mem_root,
681
(char*)next_chunk + 2, share->comment.length)))
683
my_free(buff, MYF(0));
686
next_chunk+= 2 + share->comment.length;
688
assert(next_chunk <= buff_end);
689
if (share->mysql_version >= DRIZZLE_VERSION_TABLESPACE_IN_FRM_CGE)
692
New frm format in mysql_version 5.2.5 (originally in
693
mysql-5.1.22-ndb-6.2.5)
694
New column properties added:
695
COLUMN_FORMAT DYNAMIC|FIXED and STORAGE DISK|MEMORY
696
TABLESPACE name is now stored in frm
698
if (next_chunk >= buff_end)
700
if (share->mysql_version >= DRIZZLE_VERSION_TABLESPACE_IN_FRM)
707
const uint format_section_header_size= 8;
708
uint format_section_len= uint2korr(next_chunk+0);
710
field_extra_info= next_chunk + format_section_header_size + 1;
711
next_chunk+= format_section_len;
714
assert (next_chunk <= buff_end);
715
if (next_chunk > buff_end)
720
share->key_block_size= uint2korr(head+62);
723
extra_rec_buf_length= uint2korr(head+59);
724
rec_buff_length= ALIGN_SIZE(share->reclength + 1 + extra_rec_buf_length);
419
for (unsigned int partnr= 0;
420
partnr < keyinfo->key_parts;
421
partnr++, key_part++)
423
message::Table::Index::IndexPart part;
424
part= indx.index_part(partnr);
428
key_part->field= NULL;
429
key_part->fieldnr= part.fieldnr() + 1; // start from 1.
430
key_part->null_bit= 0;
431
/* key_part->null_offset is only set if null_bit (see later) */
432
/* key_part->key_type= */ /* I *THINK* this may be okay.... */
433
/* key_part->type ???? */
434
key_part->key_part_flag= 0;
435
if (part.has_in_reverse_order())
436
key_part->key_part_flag= part.in_reverse_order()? HA_REVERSE_SORT : 0;
438
key_part->length= part.compare_length();
440
key_part->store_length= key_part->length;
442
/* key_part->offset is set later */
443
key_part->key_type= part.key_type();
446
if (! indx.has_comment())
448
keyinfo->comment.length= 0;
449
keyinfo->comment.str= NULL;
453
keyinfo->flags|= HA_USES_COMMENT;
454
keyinfo->comment.length= indx.comment().length();
455
keyinfo->comment.str= strmake_root(&share->mem_root,
456
indx.comment().c_str(),
457
keyinfo->comment.length);
460
keyinfo->name= strmake_root(&share->mem_root,
462
indx.name().length());
464
share->keynames.type_names[keynr]= keyinfo->name;
465
share->keynames.type_lengths[keynr]= indx.name().length();
468
share->keys_for_keyread.reset();
469
set_prefix(share->keys_in_use, share->keys);
471
share->fields= table.field_size();
473
share->field= (Field**) alloc_root(&share->mem_root,
474
((share->fields+1) * sizeof(Field*)));
475
share->field[share->fields]= NULL;
477
uint32_t null_fields= 0;
480
uint32_t *field_offsets= (uint32_t*)malloc(share->fields * sizeof(uint32_t));
481
uint32_t *field_pack_length=(uint32_t*)malloc(share->fields*sizeof(uint32_t));
483
assert(field_offsets && field_pack_length); // TODO: fixme
485
uint32_t interval_count= 0;
486
uint32_t interval_parts= 0;
488
uint32_t stored_columns_reclength= 0;
490
for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
492
message::Table::Field pfield= table.field(fieldnr);
493
if (pfield.constraints().is_nullable())
496
enum_field_types drizzle_field_type=
497
proto_field_type_to_drizzle_type(pfield.type());
499
field_offsets[fieldnr]= stored_columns_reclength;
501
/* the below switch is very similar to
502
CreateField::create_length_to_internal_length in field.cc
503
(which should one day be replace by just this code)
505
switch(drizzle_field_type)
507
case DRIZZLE_TYPE_BLOB:
508
case DRIZZLE_TYPE_VARCHAR:
510
message::Table::Field::StringFieldOptions field_options= pfield.string_options();
512
const CHARSET_INFO *cs= get_charset(field_options.has_collation_id() ?
513
field_options.collation_id() : 0);
516
cs= default_charset_info;
518
field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type,
519
field_options.length() * cs->mbmaxlen);
522
case DRIZZLE_TYPE_ENUM:
524
message::Table::Field::SetFieldOptions field_options= pfield.set_options();
526
field_pack_length[fieldnr]=
527
get_enum_pack_length(field_options.field_value_size());
530
interval_parts+= field_options.field_value_size();
533
case DRIZZLE_TYPE_DECIMAL:
535
message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
537
field_pack_length[fieldnr]= my_decimal_get_binary_size(fo.precision(), fo.scale());
541
/* Zero is okay here as length is fixed for other types. */
542
field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type, 0);
545
share->reclength+= field_pack_length[fieldnr];
546
stored_columns_reclength+= field_pack_length[fieldnr];
549
/* data_offset added to stored_rec_length later */
550
share->stored_rec_length= stored_columns_reclength;
552
share->null_fields= null_fields;
554
ulong null_bits= null_fields;
555
if (! table_options.pack_record())
557
ulong data_offset= (null_bits + 7)/8;
560
share->reclength+= data_offset;
561
share->stored_rec_length+= data_offset;
563
ulong rec_buff_length;
565
rec_buff_length= ALIGN_SIZE(share->reclength + 1);
725
566
share->rec_buff_length= rec_buff_length;
726
if (!(record= (uchar *) alloc_root(&share->mem_root,
728
goto err; /* purecov: inspected */
568
unsigned char* record= NULL;
570
if (! (record= (unsigned char *) alloc_root(&share->mem_root,
574
memset(record, 0, rec_buff_length);
578
if (! table_options.pack_record())
580
null_count++; // one bit for delete mark.
729
584
share->default_values= record;
730
if (pread(file, record, (size_t) share->reclength, record_offset) == 0)
731
goto err; /* purecov: inspected */
733
VOID(my_seek(file,pos+288,MY_SEEK_SET,MYF(0)));
735
share->fields= uint2korr(forminfo+258);
736
pos= uint2korr(forminfo+260); /* Length of all screens */
737
n_length= uint2korr(forminfo+268);
738
interval_count= uint2korr(forminfo+270);
739
interval_parts= uint2korr(forminfo+272);
740
int_length= uint2korr(forminfo+274);
741
share->null_fields= uint2korr(forminfo+282);
742
com_length= uint2korr(forminfo+284);
743
if (forminfo[46] != (uchar)255)
745
share->comment.length= (int) (forminfo[46]);
746
share->comment.str= strmake_root(&share->mem_root, (char*) forminfo+47,
747
share->comment.length);
588
share->intervals= (TYPELIB *) alloc_root(&share->mem_root,
589
interval_count*sizeof(TYPELIB));
751
if (!(field_ptr = (Field **)
752
alloc_root(&share->mem_root,
753
(uint) ((share->fields+1)*sizeof(Field*)+
754
interval_count*sizeof(TYPELIB)+
755
(share->fields+interval_parts+
756
keys+3)*sizeof(char *)+
757
(n_length+int_length+com_length)))))
758
goto err; /* purecov: inspected */
760
share->field= field_ptr;
761
read_length=(uint) (share->fields * field_pack_length +
762
pos+ (uint) (n_length+int_length+com_length));
763
if (read_string(file,(uchar**) &disk_buff,read_length))
764
goto err; /* purecov: inspected */
765
strpos= disk_buff+pos;
767
share->intervals= (TYPELIB*) (field_ptr+share->fields+1);
768
interval_array= (const char **) (share->intervals+interval_count);
769
names= (char*) (interval_array+share->fields+interval_parts+keys+3);
771
share->intervals= 0; // For better debugging
772
memcpy(names, strpos+(share->fields*field_pack_length),
773
(uint) (n_length+int_length));
774
comment_pos= names+(n_length+int_length);
775
memcpy(comment_pos, disk_buff+read_length-com_length, com_length);
777
fix_type_pointers(&interval_array, &share->fieldnames, 1, &names);
778
if (share->fieldnames.count != share->fields)
780
fix_type_pointers(&interval_array, share->intervals, interval_count,
592
share->intervals= NULL;
594
share->fieldnames.type_names= (const char **) alloc_root(&share->mem_root,
595
(share->fields + 1) * sizeof(char*));
597
share->fieldnames.type_lengths= (unsigned int *) alloc_root(&share->mem_root,
598
(share->fields + 1) * sizeof(unsigned int));
600
share->fieldnames.type_names[share->fields]= NULL;
601
share->fieldnames.type_lengths[share->fields]= 0;
602
share->fieldnames.count= share->fields;
605
/* Now fix the TYPELIBs for the intervals (enum values)
609
uint32_t interval_nr= 0;
611
for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
784
/* Set ENUM and SET lengths */
786
for (interval= share->intervals;
787
interval < share->intervals + interval_count;
613
message::Table::Field pfield= table.field(fieldnr);
616
share->fieldnames.type_names[fieldnr]= strmake_root(&share->mem_root,
617
pfield.name().c_str(),
618
pfield.name().length());
620
share->fieldnames.type_lengths[fieldnr]= pfield.name().length();
623
if (pfield.type() != message::Table::Field::ENUM)
626
message::Table::Field::SetFieldOptions field_options= pfield.set_options();
628
const CHARSET_INFO *charset= get_charset(field_options.has_collation_id() ?
629
field_options.collation_id() : 0);
632
charset= default_charset_info;
634
TYPELIB *t= &(share->intervals[interval_nr]);
636
t->type_names= (const char**)alloc_root(&share->mem_root,
637
(field_options.field_value_size() + 1) * sizeof(char*));
639
t->type_lengths= (unsigned int*) alloc_root(&share->mem_root,
640
(field_options.field_value_size() + 1) * sizeof(unsigned int));
642
t->type_names[field_options.field_value_size()]= NULL;
643
t->type_lengths[field_options.field_value_size()]= 0;
645
t->count= field_options.field_value_size();
648
for (int n= 0; n < field_options.field_value_size(); n++)
790
uint count= (uint) (interval->count + 1) * sizeof(uint);
791
if (!(interval->type_lengths= (uint *) alloc_root(&share->mem_root,
794
for (count= 0; count < interval->count; count++)
796
char *val= (char*) interval->type_names[count];
797
interval->type_lengths[count]= strlen(val);
799
interval->type_lengths[count]= 0;
650
t->type_names[n]= strmake_root(&share->mem_root,
651
field_options.field_value(n).c_str(),
652
field_options.field_value(n).length());
655
* Go ask the charset what the length is as for "" length=1
656
* and there's stripping spaces or some other crack going on.
659
lengthsp= charset->cset->lengthsp(charset,
661
field_options.field_value(n).length());
662
t->type_lengths[n]= lengthsp;
804
fix_type_pointers(&interval_array, &share->keynames, 1, &keynames);
806
/* Allocate handler */
807
if (!(handler_file= get_new_handler(share, thd->mem_root,
811
record= share->default_values-1; /* Fieldstart = 1 */
812
if (share->null_field_first)
814
null_flags= null_pos= (uchar*) record+1;
815
null_bit_pos= (db_create_options & HA_OPTION_PACK_RECORD) ? 0 : 1;
817
null_bytes below is only correct under the condition that
818
there are no bit fields. Correct values is set below after the
819
table struct is initialized
821
share->null_bytes= (share->null_fields + null_bit_pos + 7) / 8;
824
use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
668
/* and read the fields */
671
bool use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
826
use_hash= !hash_init(&share->name_hash,
829
(hash_get_key) get_field_name,0,0);
831
for (i=0 ; i < share->fields; i++, strpos+=field_pack_length, field_ptr++)
674
use_hash= ! hash_init(&share->name_hash,
679
(hash_get_key) get_field_name,
683
unsigned char* null_pos= record;;
684
int null_bit_pos= (table_options.pack_record()) ? 0 : 1;
686
for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
833
uint pack_flag, interval_nr, unireg_type, recpos, field_length;
834
enum_field_types field_type;
688
message::Table::Field pfield= table.field(fieldnr);
835
690
enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
836
const CHARSET_INFO *charset= NULL;
692
switch (pfield.format())
694
case message::Table::Field::DefaultFormat:
695
column_format= COLUMN_FORMAT_TYPE_DEFAULT;
697
case message::Table::Field::FixedFormat:
698
column_format= COLUMN_FORMAT_TYPE_FIXED;
700
case message::Table::Field::DynamicFormat:
701
column_format= COLUMN_FORMAT_TYPE_DYNAMIC;
707
Field::utype unireg_type= Field::NONE;
709
if (pfield.has_numeric_options() &&
710
pfield.numeric_options().is_autoincrement())
712
unireg_type= Field::NEXT_NUMBER;
715
if (pfield.has_options() &&
716
pfield.options().has_default_value() &&
717
pfield.options().default_value().compare("NOW()") == 0)
719
if (pfield.options().has_update_value() &&
720
pfield.options().update_value().compare("NOW()") == 0)
722
unireg_type= Field::TIMESTAMP_DNUN_FIELD;
724
else if (! pfield.options().has_update_value())
726
unireg_type= Field::TIMESTAMP_DN_FIELD;
729
assert(1); // Invalid update value.
731
else if (pfield.has_options() &&
732
pfield.options().has_update_value() &&
733
pfield.options().update_value().compare("NOW()") == 0)
735
unireg_type= Field::TIMESTAMP_UN_FIELD;
837
738
LEX_STRING comment;
839
if (field_extra_info)
841
char tmp= field_extra_info[i];
842
column_format= (enum column_format_type)
843
((tmp >> COLUMN_FORMAT_SHIFT) & COLUMN_FORMAT_MASK);
845
if (new_frm_ver >= 3)
847
/* new frm file in 4.1 */
848
field_length= uint2korr(strpos+3);
849
recpos= uint3korr(strpos+5);
850
pack_flag= uint2korr(strpos+8);
851
unireg_type= (uint) strpos[10];
852
interval_nr= (uint) strpos[12];
853
uint comment_length=uint2korr(strpos+15);
854
field_type=(enum_field_types) (uint) strpos[13];
858
charset= &my_charset_bin;
859
else if (!(charset=get_charset((uint) strpos[14], MYF(0))))
861
error= 5; // Unknown or unavailable charset
862
errarg= (int) strpos[14];
868
comment.str= (char*) "";
873
comment.str= (char*) comment_pos;
874
comment.length= comment_length;
875
comment_pos+= comment_length;
739
if (!pfield.has_comment())
741
comment.str= (char*)"";
880
field_length= (uint) strpos[3];
881
recpos= uint2korr(strpos+4),
882
pack_flag= uint2korr(strpos+6);
883
pack_flag&= ~FIELDFLAG_NO_DEFAULT; // Safety for old files
884
unireg_type= (uint) strpos[8];
885
interval_nr= (uint) strpos[10];
888
field_type= (enum_field_types) f_packtype(pack_flag);
889
if (f_is_binary(pack_flag))
746
size_t len= pfield.comment().length();
747
const char* str= pfield.comment().c_str();
749
comment.str= strmake_root(&share->mem_root, str, len);
753
enum_field_types field_type;
755
field_type= proto_field_type_to_drizzle_type(pfield.type());
757
const CHARSET_INFO *charset= &my_charset_bin;
759
if (field_type == DRIZZLE_TYPE_BLOB ||
760
field_type == DRIZZLE_TYPE_VARCHAR)
762
message::Table::Field::StringFieldOptions field_options= pfield.string_options();
764
charset= get_charset(field_options.has_collation_id() ?
765
field_options.collation_id() : 0);
768
charset= default_charset_info;
771
if (field_type == DRIZZLE_TYPE_ENUM)
773
message::Table::Field::SetFieldOptions field_options= pfield.set_options();
775
charset= get_charset(field_options.has_collation_id()?
776
field_options.collation_id() : 0);
779
charset= default_charset_info;
783
if (field_type == DRIZZLE_TYPE_DECIMAL
784
|| field_type == DRIZZLE_TYPE_DOUBLE)
786
message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
788
if (! pfield.has_numeric_options() || ! fo.has_scale())
892
Try to choose the best 4.1 type:
893
- for 4.0 "CHAR(N) BINARY" or "VARCHAR(N) BINARY"
894
try to find a binary collation for character set.
895
- for other types (e.g. BLOB) just use my_charset_bin.
791
We don't write the default to table proto so
792
if no decimals specified for DOUBLE, we use the default.
897
if (!f_is_blob(pack_flag))
794
decimals= NOT_FIXED_DEC;
798
if (fo.scale() > DECIMAL_MAX_SCALE)
899
// 3.23 or 4.0 string
900
if (!(charset= get_charset_by_csname(share->table_charset->csname,
901
MY_CS_BINSORT, MYF(0))))
902
charset= &my_charset_bin;
905
charset= &my_charset_bin;
803
decimals= static_cast<uint8_t>(fo.scale());
807
Item *default_value= NULL;
809
if (pfield.options().has_default_value() ||
810
pfield.options().has_default_null() ||
811
pfield.options().has_default_bin_value())
813
default_value= default_value_item(field_type,
815
pfield.options().default_null(),
816
&pfield.options().default_value(),
817
&pfield.options().default_bin_value());
821
Table temp_table; /* Use this so that BLOB DEFAULT '' works */
822
memset(&temp_table, 0, sizeof(temp_table));
824
temp_table.in_use= &session;
825
temp_table.s->db_low_byte_first= true; //Cursor->low_byte_first();
826
temp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
828
uint32_t field_length= 0; //Assignment is for compiler complaint.
832
case DRIZZLE_TYPE_BLOB:
833
case DRIZZLE_TYPE_VARCHAR:
835
message::Table::Field::StringFieldOptions field_options= pfield.string_options();
837
charset= get_charset(field_options.has_collation_id() ?
838
field_options.collation_id() : 0);
841
charset= default_charset_info;
843
field_length= field_options.length() * charset->mbmaxlen;
846
case DRIZZLE_TYPE_DOUBLE:
848
message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
849
if (!fo.has_precision() && !fo.has_scale())
851
field_length= DBL_DIG+7;
908
charset= share->table_charset;
909
memset(&comment, 0, sizeof(comment));
912
if (interval_nr && charset->mbminlen > 1)
914
/* Unescape UCS2 intervals from HEX notation */
915
TYPELIB *interval= share->intervals + interval_nr - 1;
916
unhex_type2(interval);
919
*field_ptr= reg_field=
920
make_field(share, record+recpos,
921
(uint32_t) field_length,
922
null_pos, null_bit_pos,
926
(Field::utype) MTYP_TYPENR(unireg_type),
928
share->intervals+interval_nr-1 :
930
share->fieldnames.type_names[i]);
931
if (!reg_field) // Not supported field type
934
goto err; /* purecov: inspected */
937
reg_field->flags|= ((uint)column_format << COLUMN_FORMAT_FLAGS);
938
reg_field->field_index= i;
939
reg_field->comment=comment;
940
if (!(reg_field->flags & NOT_NULL_FLAG))
942
if (!(null_bit_pos= (null_bit_pos + 1) & 7))
855
field_length= fo.precision();
857
if (field_length < decimals &&
858
decimals != NOT_FIXED_DEC)
860
my_error(ER_M_BIGGER_THAN_D, MYF(0), pfield.name().c_str());
866
case DRIZZLE_TYPE_DECIMAL:
868
message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
870
field_length= my_decimal_precision_to_length(fo.precision(), fo.scale(),
874
case DRIZZLE_TYPE_TIMESTAMP:
875
case DRIZZLE_TYPE_DATETIME:
876
field_length= drizzled::DateTime::MAX_STRING_LENGTH;
878
case DRIZZLE_TYPE_DATE:
879
field_length= drizzled::Date::MAX_STRING_LENGTH;
881
case DRIZZLE_TYPE_ENUM:
885
message::Table::Field::SetFieldOptions fo= pfield.set_options();
887
for(int valnr= 0; valnr < fo.field_value_size(); valnr++)
889
if (fo.field_value(valnr).length() > field_length)
890
field_length= charset->cset->numchars(charset,
891
fo.field_value(valnr).c_str(),
892
fo.field_value(valnr).c_str()
893
+ fo.field_value(valnr).length())
898
case DRIZZLE_TYPE_LONG:
900
uint32_t sign_len= pfield.constraints().is_unsigned() ? 0 : 1;
901
field_length= MAX_INT_WIDTH+sign_len;
904
case DRIZZLE_TYPE_LONGLONG:
905
field_length= MAX_BIGINT_WIDTH;
907
case DRIZZLE_TYPE_NULL:
908
abort(); // Programming error
911
Field* f= make_field(share,
913
record + field_offsets[fieldnr] + data_offset,
915
pfield.constraints().is_nullable(),
921
(Field::utype) MTYP_TYPENR(unireg_type),
922
((field_type == DRIZZLE_TYPE_ENUM) ?
923
share->intervals + (interval_nr++)
925
share->fieldnames.type_names[fieldnr]);
927
share->field[fieldnr]= f;
929
f->init(&temp_table); /* blob default values need table obj */
931
if (! (f->flags & NOT_NULL_FLAG))
933
*f->null_ptr|= f->null_bit;
934
if (! (null_bit_pos= (null_bit_pos + 1) & 7)) /* @TODO Ugh. */
945
if (f_no_default(pack_flag))
946
reg_field->flags|= NO_DEFAULT_VALUE_FLAG;
948
if (reg_field->unireg_check == Field::NEXT_NUMBER)
949
share->found_next_number_field= field_ptr;
950
if (share->timestamp_field == reg_field)
951
share->timestamp_field_offset= i;
941
enum_check_fields old_count_cuted_fields= session.count_cuted_fields;
942
session.count_cuted_fields= CHECK_FIELD_WARN;
943
int res= default_value->save_in_field(f, 1);
944
session.count_cuted_fields= old_count_cuted_fields;
945
if (res != 0 && res != 3) /* @TODO Huh? */
947
my_error(ER_INVALID_DEFAULT, MYF(0), f->field_name);
952
else if (f->real_type() == DRIZZLE_TYPE_ENUM &&
953
(f->flags & NOT_NULL_FLAG))
956
f->store((int64_t) 1, true);
961
/* hack to undo f->init() */
965
f->field_index= fieldnr;
967
if (! default_value &&
968
! (f->unireg_check==Field::NEXT_NUMBER) &&
969
(f->flags & NOT_NULL_FLAG) &&
970
(f->real_type() != DRIZZLE_TYPE_TIMESTAMP))
972
f->flags|= NO_DEFAULT_VALUE_FLAG;
975
if (f->unireg_check == Field::NEXT_NUMBER)
976
share->found_next_number_field= &(share->field[fieldnr]);
978
if (share->timestamp_field == f)
979
share->timestamp_field_offset= fieldnr;
981
if (use_hash) /* supposedly this never fails... but comments lie */
954
982
(void) my_hash_insert(&share->name_hash,
955
(uchar*) field_ptr); // never fail
957
*field_ptr=0; // End marker
959
/* Fix key->name and key_part->field */
962
uint primary_key=(uint) (find_type((char*) primary_key_name,
963
&share->keynames, 3) - 1);
964
int64_t ha_option= handler_file->ha_table_flags();
983
(unsigned char*)&(share->field[fieldnr]));
987
keyinfo= share->key_info;
988
for (unsigned int keynr= 0; keynr < share->keys; keynr++, keyinfo++)
990
key_part= keyinfo->key_part;
992
for (unsigned int partnr= 0;
993
partnr < keyinfo->key_parts;
994
partnr++, key_part++)
997
* Fix up key_part->offset by adding data_offset.
998
* We really should compute offset as well.
999
* But at least this way we are a little better.
1001
key_part->offset= field_offsets[key_part->fieldnr-1] + data_offset;
1006
We need to set the unused bits to 1. If the number of bits is a multiple
1007
of 8 there are no unused bits.
1011
*(record + null_count / 8)|= ~(((unsigned char) 1 << (null_count & 7)) - 1);
1013
share->null_bytes= (null_pos - (unsigned char*) record + (null_bit_pos + 7) / 8);
1015
share->last_null_bit_pos= null_bit_pos;
1017
free(field_offsets);
1018
field_offsets= NULL;
1019
free(field_pack_length);
1020
field_pack_length= NULL;
1023
if (share->key_parts)
1025
uint32_t primary_key= (uint32_t) (find_type((char*) "PRIMARY",
1026
&share->keynames, 3) - 1); /* @TODO Huh? */
965
1028
keyinfo= share->key_info;
966
1029
key_part= keyinfo->key_part;
968
for (uint key=0 ; key < share->keys ; key++,keyinfo++)
1031
for (uint32_t key= 0; key < share->keys; key++,keyinfo++)
970
uint usable_parts= 0;
971
keyinfo->name=(char*) share->keynames.type_names[key];
1033
uint32_t usable_parts= 0;
973
1035
if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
976
If the UNIQUE key doesn't have NULL columns and is not a part key
977
declare this as a primary key.
980
for (i=0 ; i < keyinfo->key_parts ;i++)
982
uint fieldnr= key_part[i].fieldnr;
984
share->field[fieldnr-1]->null_ptr ||
985
share->field[fieldnr-1]->key_length() !=
988
primary_key=MAX_KEY; // Can't be used
1038
If the UNIQUE key doesn't have NULL columns and is not a part key
1039
declare this as a primary key.
1042
for (uint32_t i= 0; i < keyinfo->key_parts; i++)
1044
uint32_t fieldnr= key_part[i].fieldnr;
1046
share->field[fieldnr-1]->null_ptr ||
1047
share->field[fieldnr-1]->key_length() != key_part[i].length)
1049
primary_key= MAX_KEY; // Can't be used
994
for (i=0 ; i < keyinfo->key_parts ; key_part++,i++)
1055
for (uint32_t i= 0 ; i < keyinfo->key_parts ; key_part++,i++)
997
if (new_field_pack_flag <= 1)
998
key_part->fieldnr= (uint16_t) find_field(share->field,
999
share->default_values,
1000
(uint) key_part->offset,
1001
(uint) key_part->length);
1002
if (!key_part->fieldnr)
1058
if (! key_part->fieldnr)
1004
error= 4; // Wrong file
1060
abort(); // goto err;
1007
1062
field= key_part->field= share->field[key_part->fieldnr-1];
1008
1063
key_part->type= field->key_type();
1009
1064
if (field->null_ptr)
1011
key_part->null_offset=(uint) ((uchar*) field->null_ptr -
1066
key_part->null_offset=(uint32_t) ((unsigned char*) field->null_ptr -
1012
1067
share->default_values);
1013
1068
key_part->null_bit= field->null_bit;
1014
1069
key_part->store_length+=HA_KEY_NULL_LENGTH;
1375
1460
/* Allocate bitmaps */
1377
1462
bitmap_size= share->column_bitmap_size;
1378
if (!(bitmaps= (uchar*) alloc_root(&outparam->mem_root, bitmap_size*3)))
1463
if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
1380
bitmap_init(&outparam->def_read_set,
1381
(my_bitmap_map*) bitmaps, share->fields, false);
1382
bitmap_init(&outparam->def_write_set,
1383
(my_bitmap_map*) (bitmaps+bitmap_size), share->fields, false);
1384
bitmap_init(&outparam->tmp_set,
1385
(my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, false);
1465
outparam->def_read_set.init((my_bitmap_map*) bitmaps, share->fields);
1466
outparam->def_write_set.init((my_bitmap_map*) (bitmaps+bitmap_size), share->fields);
1467
outparam->tmp_set.init((my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields);
1386
1468
outparam->default_column_bitmaps();
1388
1470
/* The table struct is now initialized; Open the table */
1390
if (db_stat && open_mode != OTM_ALTER)
1393
if ((ha_err= (outparam->file->
1475
if ((ha_err= (outparam->cursor->
1394
1476
ha_open(outparam, share->normalized_path.str,
1395
1477
(db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
1396
1478
(db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
1397
((db_stat & HA_WAIT_IF_LOCKED) ||
1398
(specialflag & SPECIAL_WAIT_IF_LOCKED)) ?
1399
HA_OPEN_WAIT_IF_LOCKED :
1479
(db_stat & HA_WAIT_IF_LOCKED) ? HA_OPEN_WAIT_IF_LOCKED :
1400
1480
(db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
1401
1481
HA_OPEN_ABORT_IF_LOCKED :
1402
1482
HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
1404
/* Set a flag if the table is crashed and it can be auto. repaired */
1405
share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
1406
outparam->file->auto_repair() &&
1407
!(ha_open_flags & HA_OPEN_FOR_REPAIR));
1409
1484
switch (ha_err)
1411
1486
case HA_ERR_NO_SUCH_TABLE:
1413
1488
The table did not exists in storage engine, use same error message
1414
as if the .frm file didn't exist
1489
as if the .frm cursor didn't exist
1421
1496
Too many files opened, use same error message as if the .frm
1428
outparam->file->print_error(ha_err, MYF(0));
1503
outparam->print_error(ha_err, MYF(0));
1429
1504
error_reported= true;
1430
1505
if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
1434
goto err; /* purecov: inspected */
1438
#if defined(HAVE_purify)
1513
#if defined(HAVE_purify)
1439
1514
memset(bitmaps, 0, bitmap_size*3);
1442
outparam->no_replicate= outparam->file &&
1443
test(outparam->file->ha_table_flags() &
1444
HA_HAS_OWN_BINLOGGING);
1445
thd->status_var.opened_tables++;
1517
session->status_var.opened_tables++;
1450
if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
1451
open_table_error(share, error, my_errno, 0);
1452
delete outparam->file;
1453
outparam->file= 0; // For easier error checking
1454
outparam->db_stat=0;
1522
if (!error_reported)
1523
share->open_table_error(error, errno, 0);
1524
delete outparam->cursor;
1525
outparam->cursor= 0; // For easier error checking
1526
outparam->db_stat= 0;
1455
1527
free_root(&outparam->mem_root, MYF(0)); // Safe to call on zeroed root
1456
my_free((char*) outparam->alias, MYF(MY_ALLOW_ZERO_PTR));
1528
free((char*) outparam->alias);
1457
1529
return (error);
1462
Free information allocated by openfrm
1466
table TABLE object to free
1467
free_share Is 1 if we also want to free table_share
1470
int closefrm(register TABLE *table, bool free_share)
1475
error=table->file->close();
1476
my_free((char*) table->alias, MYF(MY_ALLOW_ZERO_PTR));
1480
for (Field **ptr=table->field ; *ptr ; ptr++)
1532
bool Table::fill_item_list(List<Item> *item_list) const
1535
All Item_field's created using a direct pointer to a field
1536
are fixed in Item_field constructor.
1538
for (Field **ptr= field; *ptr; ptr++)
1540
Item_field *item= new Item_field(*ptr);
1541
if (!item || item_list->push_back(item))
1547
int Table::closefrm(bool free_share)
1552
error= cursor->close();
1553
free((char*) alias);
1557
for (Field **ptr=field ; *ptr ; ptr++)
1485
table->file= 0; /* For easier errorchecking */
1562
cursor= 0; /* For easier errorchecking */
1486
1563
if (free_share)
1488
if (table->s->tmp_table == NO_TMP_TABLE)
1489
release_table_share(table->s, RELEASE_NORMAL);
1565
if (s->tmp_table == NO_TMP_TABLE)
1566
TableShare::release(s);
1491
free_table_share(table->s);
1568
s->free_table_share();
1493
free_root(&table->mem_root, MYF(0));
1570
free_root(&mem_root, MYF(0));
1576
void Table::resetTable(Session *session,
1578
uint32_t db_stat_arg)
1591
db_stat= db_stat_arg;
1594
record[0]= (unsigned char *) NULL;
1595
record[1]= (unsigned char *) NULL;
1597
insert_values= NULL;
1599
next_number_field= NULL;
1600
found_next_number_field= NULL;
1601
timestamp_field= NULL;
1603
pos_in_table_list= NULL;
1613
derived_select_number= 0;
1614
current_lock= F_UNLCK;
1628
open_placeholder= false;
1629
locked_by_name= false;
1632
auto_increment_field_not_null= false;
1633
alias_name_used= false;
1636
quick_condition_rows= 0;
1638
timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1643
covering_keys.reset();
1648
keys_in_use_for_query.reset();
1649
keys_in_use_for_group_by.reset();
1650
keys_in_use_for_order_by.reset();
1652
memset(quick_rows, 0, sizeof(query_id_t) * MAX_KEY);
1653
memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
1655
memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
1656
memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
1658
memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
1659
memset(&sort, 0, sizeof(filesort_info_st));
1498
1664
/* Deallocate temporary blob storage */
1500
void free_blobs(register TABLE *table)
1666
void free_blobs(register Table *table)
1503
for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
1668
uint32_t *ptr, *end;
1669
for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
1506
1672
((Field_blob*) table->field[*ptr])->free();
1510
/* Find where a form starts */
1511
/* if formname is NullS then only formnames is read */
1513
ulong get_form_pos(File file, uchar *head, TYPELIB *save_names)
1515
uint a_length,names,length;
1519
names=uint2korr(head+8);
1520
a_length=(names+2)*sizeof(char *); /* Room for two extra */
1525
save_names->type_names=0; /* Clear if error */
1529
length=uint2korr(head+4);
1530
VOID(my_seek(file,64L,MY_SEEK_SET,MYF(0)));
1531
if (!(buf= (uchar*) my_malloc((size_t) length+a_length+names*4,
1533
my_read(file, buf+a_length, (size_t) (length+names*4),
1535
{ /* purecov: inspected */
1536
x_free((uchar*) buf); /* purecov: inspected */
1537
return(0L); /* purecov: inspected */
1539
pos= buf+a_length+length;
1540
ret_value=uint4korr(pos);
1545
my_free((uchar*) buf,MYF(0));
1548
memset(save_names, 0, sizeof(save_names));
1552
str=(char *) (buf+a_length);
1553
fix_type_pointers((const char ***) &buf,save_names,1,&str);
1560
Read string from a file with malloc
1563
We add an \0 at end of the read string to make reading of C strings easier
1566
int read_string(File file, uchar**to, size_t length)
1570
if (!(*to= (uchar*) my_malloc(length+1,MYF(MY_WME))) ||
1571
my_read(file, *to, length,MYF(MY_NABP)))
1573
x_free(*to); /* purecov: inspected */
1574
*to= 0; /* purecov: inspected */
1575
return(1); /* purecov: inspected */
1577
*((char*) *to+length)= '\0';
1582
/* Add a new form to a form file */
1584
ulong make_new_entry(File file, uchar *fileinfo, TYPELIB *formnames,
1585
const char *newname)
1587
uint i,bufflength,maxlength,n_length,length,names;
1588
ulong endpos,newpos;
1589
uchar buff[IO_SIZE];
1592
length=(uint) strlen(newname)+1;
1593
n_length=uint2korr(fileinfo+4);
1594
maxlength=uint2korr(fileinfo+6);
1595
names=uint2korr(fileinfo+8);
1596
newpos=uint4korr(fileinfo+10);
1598
if (64+length+n_length+(names+1)*4 > maxlength)
1601
int4store(fileinfo+10,newpos);
1602
endpos=(ulong) my_seek(file,0L,MY_SEEK_END,MYF(0));/* Copy from file-end */
1603
bufflength= (uint) (endpos & (IO_SIZE-1)); /* IO_SIZE is a power of 2 */
1605
while (endpos > maxlength)
1607
VOID(my_seek(file,(ulong) (endpos-bufflength),MY_SEEK_SET,MYF(0)));
1608
if (my_read(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
1610
VOID(my_seek(file,(ulong) (endpos-bufflength+IO_SIZE),MY_SEEK_SET,
1612
if ((my_write(file, buff,bufflength,MYF(MY_NABP+MY_WME))))
1614
endpos-=bufflength; bufflength=IO_SIZE;
1616
memset(buff, 0, IO_SIZE); /* Null new block */
1617
VOID(my_seek(file,(ulong) maxlength,MY_SEEK_SET,MYF(0)));
1618
if (my_write(file,buff,bufflength,MYF(MY_NABP+MY_WME)))
1620
maxlength+=IO_SIZE; /* Fix old ref */
1621
int2store(fileinfo+6,maxlength);
1622
for (i=names, pos= (uchar*) *formnames->type_names+n_length-1; i-- ;
1625
endpos=uint4korr(pos)+IO_SIZE;
1626
int4store(pos,endpos);
1633
VOID(strxmov((char*) buff,"/",newname,"/",NullS));
1636
VOID(strxmov((char*) buff,newname,"/",NullS)); /* purecov: inspected */
1637
VOID(my_seek(file,63L+(ulong) n_length,MY_SEEK_SET,MYF(0)));
1638
if (my_write(file, buff, (size_t) length+1,MYF(MY_NABP+MY_WME)) ||
1639
(names && my_write(file,(uchar*) (*formnames->type_names+n_length-1),
1640
names*4, MYF(MY_NABP+MY_WME))) ||
1641
my_write(file, fileinfo+10, 4,MYF(MY_NABP+MY_WME)))
1642
return(0L); /* purecov: inspected */
1644
int2store(fileinfo+8,names+1);
1645
int2store(fileinfo+4,n_length+length);
1646
(void)ftruncate(file, newpos);/* Append file with '\0' */
1648
} /* make_new_entry */
1651
/* error message when opening a form file */
1653
void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
1676
/* error message when opening a form cursor */
1678
void TableShare::open_table_error(int pass_error, int db_errno, int pass_errarg)
1656
1681
char buff[FN_REFLEN];
1657
1682
myf errortype= ME_ERROR+ME_WAITTANG;
1684
switch (pass_error) {
1662
1687
if (db_errno == ENOENT)
1663
my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
1688
my_error(ER_NO_SUCH_TABLE, MYF(0), db.str, table_name.str);
1666
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
1691
sprintf(buff,"%s",normalized_path.str);
1667
1692
my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
1668
1693
errortype, buff, db_errno);
1674
1699
const char *datext= "";
1676
if (share->db_type() != NULL)
1701
if (db_type() != NULL)
1678
if ((file= get_new_handler(share, current_thd->mem_root,
1703
if ((cursor= db_type()->getCursor(*this, current_session->mem_root)))
1681
if (!(datext= *file->bas_ext()))
1705
if (!(datext= *db_type()->bas_ext()))
1685
1709
err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
1686
1710
ER_FILE_USED : ER_CANT_OPEN_FILE;
1687
strxmov(buff, share->normalized_path.str, datext, NullS);
1711
sprintf(buff,"%s%s", normalized_path.str,datext);
1688
1712
my_error(err_no,errortype, buff, db_errno);
1694
const char *csname= get_charset_name((uint) errarg);
1718
const char *csname= get_charset_name((uint32_t) pass_errarg);
1696
1720
if (!csname || csname[0] =='?')
1698
snprintf(tmp, sizeof(tmp), "#%d", errarg);
1722
snprintf(tmp, sizeof(tmp), "#%d", pass_errarg);
1701
1725
my_printf_error(ER_UNKNOWN_COLLATION,
1702
_("Unknown collation '%s' in table '%-.64s' definition"),
1703
MYF(0), csname, share->table_name.str);
1726
_("Unknown collation '%s' in table '%-.64s' definition"),
1727
MYF(0), csname, table_name.str);
1707
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
1731
sprintf(buff,"%s", normalized_path.str);
1708
1732
my_printf_error(ER_NOT_FORM_FILE,
1709
1733
_("Table '%-.64s' was created with a different version "
1710
"of MySQL and cannot be read"),
1734
"of Drizzle and cannot be read"),
1715
1739
default: /* Better wrong error than none */
1717
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
1741
sprintf(buff,"%s", normalized_path.str);
1718
1742
my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
2227
2006
/* Error if empty or too long column name */
2228
return last_char_is_space || (uint) name_length > NAME_CHAR_LEN;
2233
Checks whether a table is intact. Should be done *just* after the table has
2236
@param[in] table The table to check
2237
@param[in] table_f_count Expected number of columns in the table
2238
@param[in] table_def Expected structure of the table (column name
2242
@retval TRUE There was an error. An error message is output
2243
to the error log. We do not push an error
2244
message into the error stack because this
2245
function is currently only called at start up,
2246
and such errors never reach the user.
2250
table_check_intact(TABLE *table, const uint table_f_count,
2251
const TABLE_FIELD_W_TYPE *table_def)
2255
bool fields_diff_count;
2257
fields_diff_count= (table->s->fields != table_f_count);
2258
if (fields_diff_count)
2261
/* previous MySQL version */
2262
if (DRIZZLE_VERSION_ID > table->s->mysql_version)
2264
sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
2265
table->alias, table_f_count, table->s->fields,
2266
table->s->mysql_version, DRIZZLE_VERSION_ID);
2269
else if (DRIZZLE_VERSION_ID == table->s->mysql_version)
2271
sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), table->alias,
2272
table_f_count, table->s->fields);
2276
Something has definitely changed, but we're running an older
2277
version of MySQL with new system tables.
2278
Let's check column definitions. If a column was added at
2279
the end of the table, then we don't care much since such change
2280
is backward compatible.
2283
char buffer[STRING_BUFFER_USUAL_SIZE];
2284
for (i=0 ; i < table_f_count; i++, table_def++)
2286
String sql_type(buffer, sizeof(buffer), system_charset_info);
2288
if (i < table->s->fields)
2290
Field *field= table->field[i];
2292
if (strncmp(field->field_name, table_def->name.str,
2293
table_def->name.length))
2296
Name changes are not fatal, we use ordinal numbers to access columns.
2297
Still this can be a sign of a tampered table, output an error
2300
sql_print_error(_("Incorrect definition of table %s.%s: "
2301
"expected column '%s' at position %d, found '%s'."),
2302
table->s->db.str, table->alias, table_def->name.str, i,
2305
field->sql_type(sql_type);
2307
Generally, if column types don't match, then something is
2310
However, we only compare column definitions up to the
2311
length of the original definition, since we consider the
2312
following definitions compatible:
2314
1. DATETIME and DATETIM
2315
2. INT(11) and INT(11
2316
3. SET('one', 'two') and SET('one', 'two', 'more')
2318
For SETs or ENUMs, if the same prefix is there it's OK to
2319
add more elements - they will get higher ordinal numbers and
2320
the new table definition is backward compatible with the
2323
if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
2324
table_def->type.length - 1))
2326
sql_print_error(_("Incorrect definition of table %s.%s: "
2327
"expected column '%s' at position %d to have type "
2328
"%s, found type %s."), table->s->db.str, table->alias,
2329
table_def->name.str, i, table_def->type.str,
2330
sql_type.c_ptr_safe());
2333
else if (table_def->cset.str && !field->has_charset())
2335
sql_print_error(_("Incorrect definition of table %s.%s: "
2336
"expected the type of column '%s' at position %d "
2337
"to have character set '%s' but the type has no "
2338
"character set."), table->s->db.str, table->alias,
2339
table_def->name.str, i, table_def->cset.str);
2342
else if (table_def->cset.str &&
2343
strcmp(field->charset()->csname, table_def->cset.str))
2345
sql_print_error(_("Incorrect definition of table %s.%s: "
2346
"expected the type of column '%s' at position %d "
2347
"to have character set '%s' but found "
2348
"character set '%s'."), table->s->db.str, table->alias,
2349
table_def->name.str, i, table_def->cset.str,
2350
field->charset()->csname);
2356
sql_print_error(_("Incorrect definition of table %s.%s: "
2357
"expected column '%s' at position %d to have type %s "
2358
" but the column is not found."),
2359
table->s->db.str, table->alias,
2360
table_def->name.str, i, table_def->type.str);
2369
Create Item_field for each column in the table.
2372
st_table::fill_item_list()
2373
item_list a pointer to an empty list used to store items
2376
Create Item_field object for each column in the table and
2377
initialize it with the corresponding Field. New items are
2378
created in the current THD memory root.
2385
bool st_table::fill_item_list(List<Item> *item_list) const
2388
All Item_field's created using a direct pointer to a field
2389
are fixed in Item_field constructor.
2391
for (Field **ptr= field; *ptr; ptr++)
2393
Item_field *item= new Item_field(*ptr);
2394
if (!item || item_list->push_back(item))
2401
Reset an existing list of Item_field items to point to the
2402
Fields of this table.
2405
st_table::fill_item_list()
2406
item_list a non-empty list with Item_fields
2409
This is a counterpart of fill_item_list used to redirect
2410
Item_fields to the fields of a newly created table.
2411
The caller must ensure that number of items in the item_list
2412
is the same as the number of columns in the table.
2415
void st_table::reset_item_list(List<Item> *item_list) const
2417
List_iterator_fast<Item> it(*item_list);
2418
for (Field **ptr= field; *ptr; ptr++)
2420
Item_field *item_field= (Item_field*) it++;
2421
assert(item_field != 0);
2422
item_field->reset_field(*ptr);
2428
Merge ON expressions for a view
2433
table table for the VIEW
2434
is_cascaded TRUE <=> merge ON expressions from underlying views
2437
This function returns the result of ANDing the ON expressions
2438
of the given view and all underlying views. The ON expressions
2439
of the underlying views are added only if is_cascaded is TRUE.
2442
Pointer to the built expression if there is any.
2443
Otherwise and in the case of a failure NULL is returned.
2447
merge_on_conds(THD *thd, TABLE_LIST *table, bool is_cascaded)
2452
cond= table->on_expr->copy_andor_structure(thd);
2453
if (!table->nested_join)
2455
List_iterator<TABLE_LIST> li(table->nested_join->join_list);
2456
while (TABLE_LIST *tbl= li++)
2458
cond= and_conds(cond, merge_on_conds(thd, tbl, is_cascaded));
2465
Find underlying base tables (TABLE_LIST) which represent given
2466
table_to_find (TABLE)
2469
TABLE_LIST::find_underlying_table()
2470
table_to_find table to find
2473
0 table is not found
2474
found table reference
2477
TABLE_LIST *TABLE_LIST::find_underlying_table(TABLE *table_to_find)
2479
/* is this real table and table which we are looking for? */
2480
if (table == table_to_find && merge_underlying_list == 0)
2483
for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
2486
if ((result= tbl->find_underlying_table(table_to_find)))
2493
cleunup items belonged to view fields translation table
2496
TABLE_LIST::cleanup_items()
2499
void TABLE_LIST::cleanup_items()
2501
if (!field_translation)
2504
for (Field_translator *transl= field_translation;
2505
transl < field_translation_end;
2507
transl->item->walk(&Item::cleanup_processor, 0, 0);
2512
Set insert_values buffer
2516
mem_root memory pool for allocating
2520
TRUE - out of memory
2523
bool TABLE_LIST::set_insert_values(MEM_ROOT *mem_root)
2527
if (!table->insert_values &&
2528
!(table->insert_values= (uchar *)alloc_root(mem_root,
2529
table->s->rec_buff_length)))
2538
Test if this is a leaf with respect to name resolution.
2541
TABLE_LIST::is_leaf_for_name_resolution()
2544
A table reference is a leaf with respect to name resolution if
2545
it is either a leaf node in a nested join tree (table, view,
2546
schema table, subquery), or an inner node that represents a
2547
NATURAL/USING join, or a nested join with materialized join
2551
TRUE if a leaf, false otherwise.
2553
bool TABLE_LIST::is_leaf_for_name_resolution()
2555
return (is_natural_join || is_join_columns_complete || !nested_join);
2560
Retrieve the first (left-most) leaf in a nested join tree with
2561
respect to name resolution.
2564
TABLE_LIST::first_leaf_for_name_resolution()
2567
Given that 'this' is a nested table reference, recursively walk
2568
down the left-most children of 'this' until we reach a leaf
2569
table reference with respect to name resolution.
2572
The left-most child of a nested table reference is the last element
2573
in the list of children because the children are inserted in
2577
If 'this' is a nested table reference - the left-most child of
2578
the tree rooted in 'this',
2582
TABLE_LIST *TABLE_LIST::first_leaf_for_name_resolution()
2584
TABLE_LIST *cur_table_ref= NULL;
2585
NESTED_JOIN *cur_nested_join;
2587
if (is_leaf_for_name_resolution())
2589
assert(nested_join);
2591
for (cur_nested_join= nested_join;
2593
cur_nested_join= cur_table_ref->nested_join)
2595
List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
2596
cur_table_ref= it++;
2598
If the current nested join is a RIGHT JOIN, the operands in
2599
'join_list' are in reverse order, thus the first operand is
2600
already at the front of the list. Otherwise the first operand
2601
is in the end of the list of join operands.
2603
if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
2606
while ((next= it++))
2607
cur_table_ref= next;
2609
if (cur_table_ref->is_leaf_for_name_resolution())
2612
return cur_table_ref;
2617
Retrieve the last (right-most) leaf in a nested join tree with
2618
respect to name resolution.
2621
TABLE_LIST::last_leaf_for_name_resolution()
2624
Given that 'this' is a nested table reference, recursively walk
2625
down the right-most children of 'this' until we reach a leaf
2626
table reference with respect to name resolution.
2629
The right-most child of a nested table reference is the first
2630
element in the list of children because the children are inserted
2634
- If 'this' is a nested table reference - the right-most child of
2635
the tree rooted in 'this',
2639
TABLE_LIST *TABLE_LIST::last_leaf_for_name_resolution()
2641
TABLE_LIST *cur_table_ref= this;
2642
NESTED_JOIN *cur_nested_join;
2644
if (is_leaf_for_name_resolution())
2646
assert(nested_join);
2648
for (cur_nested_join= nested_join;
2650
cur_nested_join= cur_table_ref->nested_join)
2652
cur_table_ref= cur_nested_join->join_list.head();
2654
If the current nested is a RIGHT JOIN, the operands in
2655
'join_list' are in reverse order, thus the last operand is in the
2658
if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
2660
List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
2662
cur_table_ref= it++;
2663
while ((next= it++))
2664
cur_table_ref= next;
2666
if (cur_table_ref->is_leaf_for_name_resolution())
2669
return cur_table_ref;
2673
Natural_join_column::Natural_join_column(Field_translator *field_param,
2676
assert(tab->field_translation);
2677
view_field= field_param;
2684
Natural_join_column::Natural_join_column(Field *field_param,
2687
assert(tab->table == field_param->table);
2688
table_field= field_param;
2695
const char *Natural_join_column::name()
2699
assert(table_field == NULL);
2700
return view_field->name;
2703
return table_field->field_name;
2707
Item *Natural_join_column::create_item(THD *thd)
2711
assert(table_field == NULL);
2712
return create_view_field(thd, table_ref, &view_field->item,
2715
return new Item_field(thd, &thd->lex->current_select->context, table_field);
2719
Field *Natural_join_column::field()
2723
assert(table_field == NULL);
2730
const char *Natural_join_column::table_name()
2733
return table_ref->alias;
2737
const char *Natural_join_column::db_name()
2740
Test that TABLE_LIST::db is the same as st_table_share::db to
2741
ensure consistency. An exception are I_S schema tables, which
2742
are inconsistent in this respect.
2744
assert(!strcmp(table_ref->db,
2745
table_ref->table->s->db.str) ||
2746
(table_ref->schema_table &&
2747
table_ref->table->s->db.str[0] == 0));
2748
return table_ref->db;
2752
void Field_iterator_view::set(TABLE_LIST *table)
2754
assert(table->field_translation);
2756
ptr= table->field_translation;
2757
array_end= table->field_translation_end;
2761
const char *Field_iterator_table::name()
2763
return (*ptr)->field_name;
2767
Item *Field_iterator_table::create_item(THD *thd)
2769
SELECT_LEX *select= thd->lex->current_select;
2771
Item_field *item= new Item_field(thd, &select->context, *ptr);
2772
if (item && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
2773
!thd->lex->in_sum_func && select->cur_pos_in_select_list != UNDEF_POS)
2775
select->non_agg_fields.push_back(item);
2776
item->marker= select->cur_pos_in_select_list;
2782
const char *Field_iterator_view::name()
2788
Item *Field_iterator_view::create_item(THD *thd)
2790
return create_view_field(thd, view, &ptr->item, ptr->name);
2793
Item *create_view_field(THD *thd __attribute__((unused)),
2794
TABLE_LIST *view, Item **field_ref,
2795
const char *name __attribute__((unused)))
2797
if (view->schema_table_reformed)
2799
Item *field= *field_ref;
2802
Translation table items are always Item_fields and already fixed
2803
('mysql_schema_table' function). So we can return directly the
2804
field. This case happens only for 'show & where' commands.
2806
assert(field && field->fixed);
2814
void Field_iterator_natural_join::set(TABLE_LIST *table_ref)
2816
assert(table_ref->join_columns);
2817
column_ref_it.init(*(table_ref->join_columns));
2818
cur_column_ref= column_ref_it++;
2822
void Field_iterator_natural_join::next()
2824
cur_column_ref= column_ref_it++;
2825
assert(!cur_column_ref || ! cur_column_ref->table_field ||
2826
cur_column_ref->table_ref->table ==
2827
cur_column_ref->table_field->table);
2831
void Field_iterator_table_ref::set_field_iterator()
2834
If the table reference we are iterating over is a natural join, or it is
2835
an operand of a natural join, and TABLE_LIST::join_columns contains all
2836
the columns of the join operand, then we pick the columns from
2837
TABLE_LIST::join_columns, instead of the orginial container of the
2838
columns of the join operator.
2840
if (table_ref->is_join_columns_complete)
2842
/* Necesary, but insufficient conditions. */
2843
assert(table_ref->is_natural_join ||
2844
table_ref->nested_join ||
2845
((table_ref->join_columns && /* This is a merge view. */ (table_ref->field_translation && table_ref->join_columns->elements == (ulong)(table_ref->field_translation_end - table_ref->field_translation))) ||
2846
/* This is stored table or a tmptable view. */
2847
(!table_ref->field_translation && table_ref->join_columns->elements == table_ref->table->s->fields)));
2848
field_it= &natural_join_it;
2850
/* This is a base table or stored view. */
2853
assert(table_ref->table);
2854
field_it= &table_field_it;
2856
field_it->set(table_ref);
2861
void Field_iterator_table_ref::set(TABLE_LIST *table)
2864
first_leaf= table->first_leaf_for_name_resolution();
2865
last_leaf= table->last_leaf_for_name_resolution();
2866
assert(first_leaf && last_leaf);
2867
table_ref= first_leaf;
2868
set_field_iterator();
2872
void Field_iterator_table_ref::next()
2874
/* Move to the next field in the current table reference. */
2877
If all fields of the current table reference are exhausted, move to
2878
the next leaf table reference.
2880
if (field_it->end_of_fields() && table_ref != last_leaf)
2882
table_ref= table_ref->next_name_resolution_table;
2884
set_field_iterator();
2889
const char *Field_iterator_table_ref::table_name()
2891
if (table_ref->is_natural_join)
2892
return natural_join_it.column_ref()->table_name();
2894
assert(!strcmp(table_ref->table_name,
2895
table_ref->table->s->table_name.str));
2896
return table_ref->table_name;
2900
const char *Field_iterator_table_ref::db_name()
2902
if (table_ref->is_natural_join)
2903
return natural_join_it.column_ref()->db_name();
2906
Test that TABLE_LIST::db is the same as st_table_share::db to
2907
ensure consistency. An exception are I_S schema tables, which
2908
are inconsistent in this respect.
2910
assert(!strcmp(table_ref->db, table_ref->table->s->db.str) ||
2911
(table_ref->schema_table &&
2912
table_ref->table->s->db.str[0] == 0));
2914
return table_ref->db;
2919
Create new or return existing column reference to a column of a
2923
Field_iterator_table_ref::get_or_create_column_ref()
2924
parent_table_ref the parent table reference over which the
2925
iterator is iterating
2928
Create a new natural join column for the current field of the
2929
iterator if no such column was created, or return an already
2930
created natural join column. The former happens for base tables or
2931
views, and the latter for natural/using joins. If a new field is
2932
created, then the field is added to 'parent_table_ref' if it is
2933
given, or to the original table referene of the field if
2934
parent_table_ref == NULL.
2937
This method is designed so that when a Field_iterator_table_ref
2938
walks through the fields of a table reference, all its fields
2939
are created and stored as follows:
2940
- If the table reference being iterated is a stored table, view or
2941
natural/using join, store all natural join columns in a list
2942
attached to that table reference.
2943
- If the table reference being iterated is a nested join that is
2944
not natural/using join, then do not materialize its result
2945
fields. This is OK because for such table references
2946
Field_iterator_table_ref iterates over the fields of the nested
2947
table references (recursively). In this way we avoid the storage
2948
of unnecessay copies of result columns of nested joins.
2951
# Pointer to a column of a natural join (or its operand)
2952
NULL No memory to allocate the column
2955
Natural_join_column *
2956
Field_iterator_table_ref::get_or_create_column_ref(TABLE_LIST *parent_table_ref)
2958
Natural_join_column *nj_col;
2959
bool is_created= true;
2961
TABLE_LIST *add_table_ref= parent_table_ref ?
2962
parent_table_ref : table_ref;
2964
if (field_it == &table_field_it)
2966
/* The field belongs to a stored table. */
2967
Field *tmp_field= table_field_it.field();
2968
nj_col= new Natural_join_column(tmp_field, table_ref);
2969
field_count= table_ref->table->s->fields;
2971
else if (field_it == &view_field_it)
2973
/* The field belongs to a merge view or information schema table. */
2974
Field_translator *translated_field= view_field_it.field_translator();
2975
nj_col= new Natural_join_column(translated_field, table_ref);
2976
field_count= table_ref->field_translation_end -
2977
table_ref->field_translation;
2982
The field belongs to a NATURAL join, therefore the column reference was
2983
already created via one of the two constructor calls above. In this case
2984
we just return the already created column reference.
2986
assert(table_ref->is_join_columns_complete);
2988
nj_col= natural_join_it.column_ref();
2991
assert(!nj_col->table_field ||
2992
nj_col->table_ref->table == nj_col->table_field->table);
2995
If the natural join column was just created add it to the list of
2996
natural join columns of either 'parent_table_ref' or to the table
2997
reference that directly contains the original field.
3001
/* Make sure not all columns were materialized. */
3002
assert(!add_table_ref->is_join_columns_complete);
3003
if (!add_table_ref->join_columns)
3005
/* Create a list of natural join columns on demand. */
3006
if (!(add_table_ref->join_columns= new List<Natural_join_column>))
3008
add_table_ref->is_join_columns_complete= false;
3010
add_table_ref->join_columns->push_back(nj_col);
3012
If new fields are added to their original table reference, mark if
3013
all fields were added. We do it here as the caller has no easy way
3014
of knowing when to do it.
3015
If the fields are being added to parent_table_ref, then the caller
3016
must take care to mark when all fields are created/added.
3018
if (!parent_table_ref &&
3019
add_table_ref->join_columns->elements == field_count)
3020
add_table_ref->is_join_columns_complete= true;
3028
Return an existing reference to a column of a natural/using join.
3031
Field_iterator_table_ref::get_natural_column_ref()
3034
The method should be called in contexts where it is expected that
3035
all natural join columns are already created, and that the column
3036
being retrieved is a Natural_join_column.
3039
# Pointer to a column of a natural join (or its operand)
3040
NULL No memory to allocate the column
3043
Natural_join_column *
3044
Field_iterator_table_ref::get_natural_column_ref()
3046
Natural_join_column *nj_col;
3048
assert(field_it == &natural_join_it);
3050
The field belongs to a NATURAL join, therefore the column reference was
3051
already created via one of the two constructor calls above. In this case
3052
we just return the already created column reference.
3054
nj_col= natural_join_it.column_ref();
3056
(!nj_col->table_field ||
3057
nj_col->table_ref->table == nj_col->table_field->table));
2007
return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
3061
2011
/*****************************************************************************
3062
2012
Functions to handle column usage bitmaps (read_set, write_set etc...)
3243
2194
if neeed, either the primary key column or all columns to be read.
3244
2195
(see mark_columns_needed_for_delete() for details)
3246
If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
2197
If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
3247
2198
mark all USED key columns as 'to-be-read'. This allows the engine to
3248
2199
loop over the given record to find all changed keys and doesn't have to
3249
2200
retrieve the row again.
3252
void st_table::mark_columns_needed_for_update()
2203
void Table::mark_columns_needed_for_update()
3254
if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
2206
If the Cursor has no cursor capabilites, or we have row-based
2207
logging active for the current statement, we have to read either
2208
the primary key, the hidden primary key or all columns to be
2209
able to do an update
2211
if (s->primary_key == MAX_KEY)
2213
/* fallback to use all columns in the table to identify row */
2218
mark_columns_used_by_index_no_reset(s->primary_key);
2220
if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
3256
2222
/* Mark all used key columns for read */
3257
2223
Field **reg_field;
3258
2224
for (reg_field= field ; *reg_field ; reg_field++)
3260
2226
/* Merge keys is all keys that had a column refered to in the query */
3261
if (merge_keys.is_overlapping((*reg_field)->part_of_key))
3262
bitmap_set_bit(read_set, (*reg_field)->field_index);
3264
file->column_bitmaps_signal();
3266
if ((file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) ||
3267
(mysql_bin_log.is_open() && in_use && in_use->current_stmt_binlog_row_based))
3270
If the handler has no cursor capabilites, or we have row-based
3271
logging active for the current statement, we have to read either
3272
the primary key, the hidden primary key or all columns to be
3273
able to do an update
3275
if (s->primary_key == MAX_KEY)
3276
file->use_hidden_primary_key();
3279
mark_columns_used_by_index_no_reset(s->primary_key, read_set);
3280
file->column_bitmaps_signal();
2227
if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
2228
setReadSet((*reg_field)->field_index);
3288
Mark columns the handler needs for doing an insert
2236
Mark columns the Cursor needs for doing an insert
3290
2238
For now, this is used to mark fields used by the trigger
3294
void st_table::mark_columns_needed_for_insert()
2242
void Table::mark_columns_needed_for_insert()
3296
2244
if (found_next_number_field)
3297
2245
mark_auto_increment_column();
3301
Cleanup this table for re-execution.
3304
TABLE_LIST::reinit_before_use()
3307
void TABLE_LIST::reinit_before_use(THD *thd)
3310
Reset old pointers to TABLEs: they are not valid since the tables
3311
were closed in the end of previous prepare or execute call.
3314
/* Reset is_schema_table_processed value(needed for I_S tables */
3315
schema_table_state= NOT_PROCESSED;
3317
TABLE_LIST *embedded; /* The table at the current level of nesting. */
3318
TABLE_LIST *parent_embedding= this; /* The parent nested table reference. */
3321
embedded= parent_embedding;
3322
if (embedded->prep_on_expr)
3323
embedded->on_expr= embedded->prep_on_expr->copy_andor_structure(thd);
3324
parent_embedding= embedded->embedding;
3326
while (parent_embedding &&
3327
parent_embedding->nested_join->join_list.head() == embedded);
3331
Return subselect that contains the FROM list this table is taken from
3334
TABLE_LIST::containing_subselect()
3337
Subselect item for the subquery that contains the FROM list
3338
this table is taken from if there is any
3343
Item_subselect *TABLE_LIST::containing_subselect()
3345
return (select_lex ? select_lex->master_unit()->item : 0);
3349
Compiles the tagged hints list and fills up the bitmasks.
3352
process_index_hints()
3353
table the TABLE to operate on.
3356
The parser collects the index hints for each table in a "tagged list"
3357
(TABLE_LIST::index_hints). Using the information in this tagged list
3358
this function sets the members st_table::keys_in_use_for_query,
3359
st_table::keys_in_use_for_group_by, st_table::keys_in_use_for_order_by,
3360
st_table::force_index and st_table::covering_keys.
3362
Current implementation of the runtime does not allow mixing FORCE INDEX
3363
and USE INDEX, so this is checked here. Then the FORCE INDEX list
3364
(if non-empty) is appended to the USE INDEX list and a flag is set.
3366
Multiple hints of the same kind are processed so that each clause
3367
is applied to what is computed in the previous clause.
3369
USE INDEX (i1) USE INDEX (i2)
3372
and means "consider only i1 and i2".
3375
USE INDEX () USE INDEX (i1)
3378
and means "consider only the index i1"
3380
It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is
3383
Different kind of hints (USE/FORCE/IGNORE) are processed in the following
3385
1. All indexes in USE (or FORCE) INDEX are added to the mask.
3388
e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all
3389
as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
3391
As an optimization if there is a covering index, and we have
3392
IGNORE INDEX FOR GROUP/ORDER, and this index is used for the JOIN part,
3393
then we have to ignore the IGNORE INDEX FROM GROUP/ORDER.
3396
false no errors found
3397
TRUE found and reported an error.
3399
bool TABLE_LIST::process_index_hints(TABLE *tbl)
3401
/* initialize the result variables */
3402
tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by=
3403
tbl->keys_in_use_for_order_by= tbl->s->keys_in_use;
3405
/* index hint list processing */
3408
key_map index_join[INDEX_HINT_FORCE + 1];
3409
key_map index_order[INDEX_HINT_FORCE + 1];
3410
key_map index_group[INDEX_HINT_FORCE + 1];
3413
bool have_empty_use_join= false, have_empty_use_order= false,
3414
have_empty_use_group= false;
3415
List_iterator <Index_hint> iter(*index_hints);
3417
/* initialize temporary variables used to collect hints of each kind */
3418
for (type= INDEX_HINT_IGNORE; type <= INDEX_HINT_FORCE; type++)
3420
index_join[type].clear_all();
3421
index_order[type].clear_all();
3422
index_group[type].clear_all();
3425
/* iterate over the hints list */
3426
while ((hint= iter++))
3430
/* process empty USE INDEX () */
3431
if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
3433
if (hint->clause & INDEX_HINT_MASK_JOIN)
3435
index_join[hint->type].clear_all();
3436
have_empty_use_join= true;
3438
if (hint->clause & INDEX_HINT_MASK_ORDER)
3440
index_order[hint->type].clear_all();
3441
have_empty_use_order= true;
3443
if (hint->clause & INDEX_HINT_MASK_GROUP)
3445
index_group[hint->type].clear_all();
3446
have_empty_use_group= true;
3452
Check if an index with the given name exists and get his offset in
3453
the keys bitmask for the table
3455
if (tbl->s->keynames.type_names == 0 ||
3456
(pos= find_type(&tbl->s->keynames, hint->key_name.str,
3457
hint->key_name.length, 1)) <= 0)
3459
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), hint->key_name.str, alias);
3465
/* add to the appropriate clause mask */
3466
if (hint->clause & INDEX_HINT_MASK_JOIN)
3467
index_join[hint->type].set_bit (pos);
3468
if (hint->clause & INDEX_HINT_MASK_ORDER)
3469
index_order[hint->type].set_bit (pos);
3470
if (hint->clause & INDEX_HINT_MASK_GROUP)
3471
index_group[hint->type].set_bit (pos);
3474
/* cannot mix USE INDEX and FORCE INDEX */
3475
if ((!index_join[INDEX_HINT_FORCE].is_clear_all() ||
3476
!index_order[INDEX_HINT_FORCE].is_clear_all() ||
3477
!index_group[INDEX_HINT_FORCE].is_clear_all()) &&
3478
(!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join ||
3479
!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order ||
3480
!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group))
3482
my_error(ER_WRONG_USAGE, MYF(0), index_hint_type_name[INDEX_HINT_USE],
3483
index_hint_type_name[INDEX_HINT_FORCE]);
3487
/* process FORCE INDEX as USE INDEX with a flag */
3488
if (!index_join[INDEX_HINT_FORCE].is_clear_all() ||
3489
!index_order[INDEX_HINT_FORCE].is_clear_all() ||
3490
!index_group[INDEX_HINT_FORCE].is_clear_all())
3492
tbl->force_index= true;
3493
index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
3494
index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
3495
index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
3498
/* apply USE INDEX */
3499
if (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join)
3500
tbl->keys_in_use_for_query.intersect(index_join[INDEX_HINT_USE]);
3501
if (!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order)
3502
tbl->keys_in_use_for_order_by.intersect (index_order[INDEX_HINT_USE]);
3503
if (!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group)
3504
tbl->keys_in_use_for_group_by.intersect (index_group[INDEX_HINT_USE]);
3506
/* apply IGNORE INDEX */
3507
tbl->keys_in_use_for_query.subtract (index_join[INDEX_HINT_IGNORE]);
3508
tbl->keys_in_use_for_order_by.subtract (index_order[INDEX_HINT_IGNORE]);
3509
tbl->keys_in_use_for_group_by.subtract (index_group[INDEX_HINT_IGNORE]);
3512
/* make sure covering_keys don't include indexes disabled with a hint */
3513
tbl->covering_keys.intersect(tbl->keys_in_use_for_query);
3518
size_t max_row_length(TABLE *table, const uchar *data)
3520
TABLE_SHARE *table_s= table->s;
3521
size_t length= table_s->reclength + 2 * table_s->fields;
3522
uint *const beg= table_s->blob_field;
3523
uint *const end= beg + table_s->blob_fields;
3525
for (uint *ptr= beg ; ptr != end ; ++ptr)
3527
Field_blob* const blob= (Field_blob*) table->field[*ptr];
3528
length+= blob->get_length((const uchar*)
3529
(data + blob->offset(table->record[0]))) +
2250
size_t Table::max_row_length(const unsigned char *data)
2252
size_t length= getRecordLength() + 2 * sizeFields();
2253
uint32_t *const beg= getBlobField();
2254
uint32_t *const end= beg + sizeBlobFields();
2256
for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
2258
Field_blob* const blob= (Field_blob*) field[*ptr];
2259
length+= blob->get_length((const unsigned char*)
2260
(data + blob->offset(record[0]))) +
3530
2261
HA_KEY_BLOB_LENGTH;
2266
/****************************************************************************
2267
Functions for creating temporary tables.
2268
****************************************************************************/
2272
void free_tmp_table(Session *session, Table *entry);
2275
Create field for temporary table from given field.
2277
@param session Thread Cursor
2278
@param org_field field from which new field will be created
2279
@param name New field name
2280
@param table Temporary table
2281
@param item !=NULL if item->result_field should point to new field.
2282
This is relevant for how fill_record() is going to work:
2283
If item != NULL then fill_record() will update
2284
the record in the original table.
2285
If item == NULL then fill_record() will update
2287
@param convert_blob_length If >0 create a varstring(convert_blob_length)
2288
field instead of blob.
2296
Field *create_tmp_field_from_field(Session *session, Field *org_field,
2297
const char *name, Table *table,
2298
Item_field *item, uint32_t convert_blob_length)
2303
Make sure that the blob fits into a Field_varstring which has
2306
if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
2307
(org_field->flags & BLOB_FLAG))
2308
new_field= new Field_varstring(convert_blob_length,
2309
org_field->maybe_null(),
2310
org_field->field_name, table->s,
2311
org_field->charset());
2313
new_field= org_field->new_field(session->mem_root, table,
2314
table == org_field->table);
2317
new_field->init(table);
2318
new_field->orig_table= org_field->orig_table;
2320
item->result_field= new_field;
2322
new_field->field_name= name;
2323
new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
2324
if (org_field->maybe_null() || (item && item->maybe_null))
2325
new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join
2326
if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
2327
table->s->db_create_options|= HA_OPTION_PACK_RECORD;
2328
else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
2329
((Field_double *) new_field)->not_fixed= true;
2336
Create a temp table according to a field list.
2338
Given field pointers are changed to point at tmp_table for
2339
send_fields. The table object is self contained: it's
2340
allocated in its own memory root, as well as Field objects
2341
created for table columns.
2342
This function will replace Item_sum items in 'fields' list with
2343
corresponding Item_field items, pointing at the fields in the
2344
temporary table, unless this was prohibited by true
2345
value of argument save_sum_fields. The Item_field objects
2346
are created in Session memory root.
2348
@param session thread handle
2349
@param param a description used as input to create the table
2350
@param fields list of items that will be used to define
2351
column types of the table (also see NOTES)
2352
@param group TODO document
2353
@param distinct should table rows be distinct
2354
@param save_sum_fields see NOTES
2355
@param select_options
2357
@param table_alias possible name of the temporary table that can
2358
be used for name resolving; can be "".
2361
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
2362
#define AVG_STRING_LENGTH_TO_PACK_ROWS 64
2363
#define RATIO_TO_PACK_ROWS 2
2366
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
2367
order_st *group, bool distinct, bool save_sum_fields,
2368
uint64_t select_options, ha_rows rows_limit,
2369
const char *table_alias)
2371
memory::Root *mem_root_save, own_root;
2374
uint i,field_count,null_count,null_pack_length;
2375
uint32_t copy_func_count= param->func_count;
2376
uint32_t hidden_null_count, hidden_null_pack_length, hidden_field_count;
2377
uint32_t blob_count,group_null_items, string_count;
2378
uint32_t fieldnr= 0;
2379
ulong reclength, string_total_length;
2380
bool using_unique_constraint= 0;
2381
bool use_packed_rows= 0;
2382
bool not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
2383
char *tmpname,path[FN_REFLEN];
2384
unsigned char *pos, *group_buff, *bitmaps;
2385
unsigned char *null_flags;
2386
Field **reg_field, **from_field, **default_field;
2387
uint32_t *blob_field;
2390
KEY_PART_INFO *key_part_info;
2392
MI_COLUMNDEF *recinfo;
2393
uint32_t total_uneven_bit_length= 0;
2394
bool force_copy_fields= param->force_copy_fields;
2395
uint64_t max_rows= 0;
2397
status_var_increment(session->status_var.created_tmp_tables);
2399
/* if we run out of slots or we are not using tempool */
2400
snprintf(path, FN_REFLEN, "%s%lx_%"PRIx64"_%x", TMP_FILE_PREFIX, (unsigned long)current_pid,
2401
session->thread_id, session->tmp_table++);
2404
No need to change table name to lower case as we are only creating
2405
MyISAM or HEAP tables here
2407
fn_format(path, path, drizzle_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
2412
if (!param->quick_group)
2413
group= 0; // Can't use group key
2414
else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
2417
marker == 4 means two things:
2418
- store NULLs in the key, and
2419
- convert BIT fields to 64-bit long, needed because MEMORY tables
2420
can't index BIT fields.
2422
(*tmp->item)->marker= 4;
2423
if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
2424
using_unique_constraint=1;
2426
if (param->group_length >= MAX_BLOB_WIDTH)
2427
using_unique_constraint=1;
2429
distinct= 0; // Can't use distinct
2432
field_count=param->field_count+param->func_count+param->sum_func_count;
2433
hidden_field_count=param->hidden_field_count;
2436
When loose index scan is employed as access method, it already
2437
computes all groups and the result of all aggregate functions. We
2438
make space for the items of the aggregate function in the list of
2439
functions Tmp_Table_Param::items_to_copy, so that the values of
2440
these items are stored in the temporary table.
2442
if (param->precomputed_group_by)
2443
copy_func_count+= param->sum_func_count;
2445
memory::init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
2447
if (!multi_alloc_root(&own_root,
2448
&table, sizeof(*table),
2449
&share, sizeof(*share),
2450
®_field, sizeof(Field*) * (field_count+1),
2451
&default_field, sizeof(Field*) * (field_count),
2452
&blob_field, sizeof(uint32_t)*(field_count+1),
2453
&from_field, sizeof(Field*)*field_count,
2454
©_func, sizeof(*copy_func)*(copy_func_count+1),
2455
¶m->keyinfo, sizeof(*param->keyinfo),
2457
sizeof(*key_part_info)*(param->group_parts+1),
2458
¶m->start_recinfo,
2459
sizeof(*param->recinfo)*(field_count*2+4),
2460
&tmpname, (uint32_t) strlen(path)+1,
2461
&group_buff, (group && ! using_unique_constraint ?
2462
param->group_length : 0),
2463
&bitmaps, bitmap_buffer_size(field_count)*2,
2468
/* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
2469
if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
2471
free_root(&own_root, MYF(0));
2474
param->items_to_copy= copy_func;
2475
strcpy(tmpname,path);
2476
/* make table according to fields */
2478
memset(table, 0, sizeof(*table));
2479
memset(reg_field, 0, sizeof(Field*)*(field_count+1));
2480
memset(default_field, 0, sizeof(Field*) * (field_count));
2481
memset(from_field, 0, sizeof(Field*)*field_count);
2483
table->mem_root= own_root;
2484
mem_root_save= session->mem_root;
2485
session->mem_root= &table->mem_root;
2487
table->field=reg_field;
2488
table->alias= table_alias;
2489
table->reginfo.lock_type=TL_WRITE; /* Will be updated */
2490
table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
2492
table->copy_blobs= 1;
2493
table->in_use= session;
2494
table->quick_keys.reset();
2495
table->covering_keys.reset();
2496
table->keys_in_use_for_query.reset();
2498
table->setShare(share);
2499
share->init(tmpname, tmpname);
2500
share->blob_field= blob_field;
2501
share->blob_ptr_size= portable_sizeof_char_ptr;
2502
share->db_low_byte_first=1; // True for HEAP and MyISAM
2503
share->table_charset= param->table_charset;
2504
share->primary_key= MAX_KEY; // Indicate no primary key
2505
share->keys_for_keyread.reset();
2506
share->keys_in_use.reset();
2508
/* Calculate which type of fields we will store in the temporary table */
2510
reclength= string_total_length= 0;
2511
blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
2512
param->using_indirect_summary_function= 0;
2514
List_iterator_fast<Item> li(fields);
2516
Field **tmp_from_field=from_field;
2519
Item::Type type=item->type();
2520
if (not_all_columns)
2522
if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
2524
if (item->used_tables() & OUTER_REF_TABLE_BIT)
2525
item->update_used_tables();
2526
if (type == Item::SUBSELECT_ITEM ||
2527
(item->used_tables() & ~OUTER_REF_TABLE_BIT))
2530
Mark that the we have ignored an item that refers to a summary
2531
function. We need to know this if someone is going to use
2532
DISTINCT on the result.
2534
param->using_indirect_summary_function=1;
2538
if (item->const_item() && (int) hidden_field_count <= 0)
2539
continue; // We don't have to store this
2541
if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
2542
{ /* Can't calc group yet */
2543
((Item_sum*) item)->result_field= 0;
2544
for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
2546
Item **argp= ((Item_sum*) item)->args + i;
2548
if (!arg->const_item())
2551
create_tmp_field(session, table, arg, arg->type(), ©_func,
2552
tmp_from_field, &default_field[fieldnr],
2553
group != 0,not_all_columns,
2555
param->convert_blob_length);
2557
goto err; // Should be OOM
2559
reclength+=new_field->pack_length();
2560
if (new_field->flags & BLOB_FLAG)
2562
*blob_field++= fieldnr;
2565
*(reg_field++)= new_field;
2566
if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
2569
string_total_length+= new_field->pack_length();
2571
session->mem_root= mem_root_save;
2572
session->change_item_tree(argp, new Item_field(new_field));
2573
session->mem_root= &table->mem_root;
2574
if (!(new_field->flags & NOT_NULL_FLAG))
2578
new_field->maybe_null() is still false, it will be
2579
changed below. But we have to setup Item_field correctly
2581
(*argp)->maybe_null=1;
2583
new_field->field_index= fieldnr++;
2590
The last parameter to create_tmp_field() is a bit tricky:
2592
We need to set it to 0 in union, to get fill_record() to modify the
2594
We need to set it to 1 on multi-table-update and in select to
2595
write rows to the temporary table.
2596
We here distinguish between UNION and multi-table-updates by the fact
2597
that in the later case group is set to the row pointer.
2600
create_tmp_field(session, table, item, type, ©_func,
2601
tmp_from_field, &default_field[fieldnr],
2603
!force_copy_fields &&
2604
(not_all_columns || group != 0),
2606
If item->marker == 4 then we force create_tmp_field
2607
to create a 64-bit longs for BIT fields because HEAP
2608
tables can't index BIT fields directly. We do the same
2609
for distinct, as we want the distinct index to be
2610
usable in this case too.
2612
item->marker == 4 || param->bit_fields_as_long,
2614
param->convert_blob_length);
2618
if (session->is_fatal_error)
2619
goto err; // Got OOM
2620
continue; // Some kindf of const item
2622
if (type == Item::SUM_FUNC_ITEM)
2623
((Item_sum *) item)->result_field= new_field;
2625
reclength+=new_field->pack_length();
2626
if (!(new_field->flags & NOT_NULL_FLAG))
2628
if (new_field->flags & BLOB_FLAG)
2630
*blob_field++= fieldnr;
2633
if (item->marker == 4 && item->maybe_null)
2636
new_field->flags|= GROUP_FLAG;
2638
new_field->field_index= fieldnr++;
2639
*(reg_field++)= new_field;
2641
if (!--hidden_field_count)
2644
This was the last hidden field; Remember how many hidden fields could
2647
hidden_null_count=null_count;
2649
We need to update hidden_field_count as we may have stored group
2650
functions with constant arguments
2652
param->hidden_field_count= fieldnr;
2656
assert(fieldnr == (uint32_t) (reg_field - table->field));
2657
assert(field_count >= (uint32_t) (reg_field - table->field));
2658
field_count= fieldnr;
2660
*blob_field= 0; // End marker
2661
share->fields= field_count;
2663
/* If result table is small; use a heap */
2664
/* future: storage engine selection can be made dynamic? */
2665
if (blob_count || using_unique_constraint ||
2666
(select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
2667
OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
2669
share->storage_engine= myisam_engine;
2670
table->cursor= share->db_type()->getCursor(*share, &table->mem_root);
2672
(param->group_parts > table->cursor->getEngine()->max_key_parts() ||
2673
param->group_length > table->cursor->getEngine()->max_key_length()))
2674
using_unique_constraint=1;
2678
share->storage_engine= heap_engine;
2679
table->cursor= share->db_type()->getCursor(*share, &table->mem_root);
2685
if (!using_unique_constraint)
2686
reclength+= group_null_items; // null flag is stored separately
2688
share->blob_fields= blob_count;
2689
if (blob_count == 0)
2691
/* We need to ensure that first byte is not 0 for the delete link */
2692
if (param->hidden_field_count)
2693
hidden_null_count++;
2697
hidden_null_pack_length=(hidden_null_count+7)/8;
2698
null_pack_length= (hidden_null_pack_length +
2699
(null_count + total_uneven_bit_length + 7) / 8);
2700
reclength+=null_pack_length;
2702
reclength=1; // Dummy select
2703
/* Use packed rows if there is blobs or a lot of space to gain */
2704
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)))
2707
share->reclength= reclength;
2709
uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
2710
share->rec_buff_length= alloc_length;
2711
if (!(table->record[0]= (unsigned char*)
2712
alloc_root(&table->mem_root, alloc_length*3)))
2714
table->record[1]= table->record[0]+alloc_length;
2715
share->default_values= table->record[1]+alloc_length;
2717
copy_func[0]= 0; // End marker
2718
param->func_count= copy_func - param->items_to_copy;
2720
table->setup_tmp_table_column_bitmaps(bitmaps);
2722
recinfo=param->start_recinfo;
2723
null_flags=(unsigned char*) table->record[0];
2724
pos=table->record[0]+ null_pack_length;
2725
if (null_pack_length)
2727
memset(recinfo, 0, sizeof(*recinfo));
2728
recinfo->type=FIELD_NORMAL;
2729
recinfo->length=null_pack_length;
2731
memset(null_flags, 255, null_pack_length); // Set null fields
2733
table->null_flags= (unsigned char*) table->record[0];
2734
share->null_fields= null_count+ hidden_null_count;
2735
share->null_bytes= null_pack_length;
2737
null_count= (blob_count == 0) ? 1 : 0;
2738
hidden_field_count=param->hidden_field_count;
2739
for (i= 0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
2741
Field *field= *reg_field;
2743
memset(recinfo, 0, sizeof(*recinfo));
2745
if (!(field->flags & NOT_NULL_FLAG))
2747
if (field->flags & GROUP_FLAG && !using_unique_constraint)
2750
We have to reserve one byte here for NULL bits,
2751
as this is updated by 'end_update()'
2753
*pos++= '\0'; // Null is stored here
2755
recinfo->type=FIELD_NORMAL;
2757
memset(recinfo, 0, sizeof(*recinfo));
2761
recinfo->null_bit= 1 << (null_count & 7);
2762
recinfo->null_pos= null_count/8;
2764
field->move_field(pos,null_flags+null_count/8,
2765
1 << (null_count & 7));
2769
field->move_field(pos,(unsigned char*) 0,0);
2773
Test if there is a default field value. The test for ->ptr is to skip
2774
'offset' fields generated by initalize_tables
2776
if (default_field[i] && default_field[i]->ptr)
2779
default_field[i] is set only in the cases when 'field' can
2780
inherit the default value that is defined for the field referred
2781
by the Item_field object from which 'field' has been created.
2784
Field *orig_field= default_field[i];
2785
/* Get the value from default_values */
2786
diff= (ptrdiff_t) (orig_field->table->s->default_values-
2787
orig_field->table->record[0]);
2788
orig_field->move_field_offset(diff); // Points now at default_values
2789
if (orig_field->is_real_null())
2793
field->set_notnull();
2794
memcpy(field->ptr, orig_field->ptr, field->pack_length());
2796
orig_field->move_field_offset(-diff); // Back to record[0]
2800
{ /* Not a table Item */
2801
copy->set(field,from_field[i],save_sum_fields);
2804
length=field->pack_length();
2807
/* Make entry for create table */
2808
recinfo->length=length;
2809
if (field->flags & BLOB_FLAG)
2810
recinfo->type= (int) FIELD_BLOB;
2812
recinfo->type=FIELD_NORMAL;
2813
if (!--hidden_field_count)
2814
null_count=(null_count+7) & ~7; // move to next byte
2816
// fix table name in field entry
2817
field->table_name= &table->alias;
2820
param->copy_field_end=copy;
2821
param->recinfo=recinfo;
2822
table->storeRecordAsDefault(); // Make empty default record
2824
if (session->variables.tmp_table_size == ~ (uint64_t) 0) // No limit
2825
max_rows= ~(uint64_t) 0;
2827
max_rows= (uint64_t) (((share->db_type() == heap_engine) ?
2828
min(session->variables.tmp_table_size,
2829
session->variables.max_heap_table_size) :
2830
session->variables.tmp_table_size) /
2833
set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
2835
Push the LIMIT clause to the temporary table creation, so that we
2836
materialize only up to 'rows_limit' records instead of all result records.
2838
set_if_smaller(max_rows, rows_limit);
2840
share->setMaxRows(max_rows);
2842
param->end_write_records= rows_limit;
2844
keyinfo= param->keyinfo;
2848
table->group=group; /* Table is grouped by key */
2849
param->group_buff=group_buff;
2851
share->uniques= test(using_unique_constraint);
2852
table->key_info=keyinfo;
2853
keyinfo->key_part=key_part_info;
2854
keyinfo->flags=HA_NOSAME;
2855
keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
2856
keyinfo->key_length= 0;
2857
keyinfo->rec_per_key= 0;
2858
keyinfo->algorithm= HA_KEY_ALG_UNDEF;
2859
keyinfo->name= (char*) "group_key";
2860
order_st *cur_group= group;
2861
for (; cur_group ; cur_group= cur_group->next, key_part_info++)
2863
Field *field=(*cur_group->item)->get_tmp_table_field();
2864
bool maybe_null=(*cur_group->item)->maybe_null;
2865
key_part_info->null_bit= 0;
2866
key_part_info->field= field;
2867
key_part_info->offset= field->offset(table->record[0]);
2868
key_part_info->length= (uint16_t) field->key_length();
2869
key_part_info->type= (uint8_t) field->key_type();
2870
key_part_info->key_type=
2871
((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
2872
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
2873
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
2875
if (!using_unique_constraint)
2877
cur_group->buff=(char*) group_buff;
2878
if (!(cur_group->field= field->new_key_field(session->mem_root,table,
2887
To be able to group on NULL, we reserved place in group_buff
2888
for the NULL flag just before the column. (see above).
2889
The field data is after this flag.
2890
The NULL flag is updated in 'end_update()' and 'end_write()'
2892
keyinfo->flags|= HA_NULL_ARE_EQUAL; // def. that NULL == NULL
2893
key_part_info->null_bit=field->null_bit;
2894
key_part_info->null_offset= (uint32_t) (field->null_ptr -
2895
(unsigned char*) table->record[0]);
2896
cur_group->buff++; // Pointer to field data
2897
group_buff++; // Skipp null flag
2899
/* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
2900
key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
2901
group_buff+= cur_group->field->pack_length();
2903
keyinfo->key_length+= key_part_info->length;
2907
if (distinct && field_count != param->hidden_field_count)
2910
Create an unique key or an unique constraint over all columns
2911
that should be in the result. In the temporary table, there are
2912
'param->hidden_field_count' extra columns, whose null bits are stored
2913
in the first 'hidden_null_pack_length' bytes of the row.
2918
Special mode for index creation in MyISAM used to support unique
2919
indexes on blobs with arbitrary length. Such indexes cannot be
2924
null_pack_length-=hidden_null_pack_length;
2925
keyinfo->key_parts= ((field_count-param->hidden_field_count)+
2926
(share->uniques ? test(null_pack_length) : 0));
2929
if (!(key_part_info= (KEY_PART_INFO*)
2930
alloc_root(&table->mem_root,
2931
keyinfo->key_parts * sizeof(KEY_PART_INFO))))
2933
memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
2934
table->key_info=keyinfo;
2935
keyinfo->key_part=key_part_info;
2936
keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
2937
keyinfo->key_length=(uint16_t) reclength;
2938
keyinfo->name= (char*) "distinct_key";
2939
keyinfo->algorithm= HA_KEY_ALG_UNDEF;
2940
keyinfo->rec_per_key= 0;
2943
Create an extra field to hold NULL bits so that unique indexes on
2944
blobs can distinguish NULL from 0. This extra field is not needed
2945
when we do not use UNIQUE indexes for blobs.
2947
if (null_pack_length && share->uniques)
2949
key_part_info->null_bit= 0;
2950
key_part_info->offset=hidden_null_pack_length;
2951
key_part_info->length=null_pack_length;
2952
key_part_info->field= new Field_varstring(table->record[0],
2953
(uint32_t) key_part_info->length,
2960
if (!key_part_info->field)
2962
key_part_info->field->init(table);
2963
key_part_info->key_type= 1; /* binary comparison */
2964
key_part_info->type= HA_KEYTYPE_BINARY;
2967
/* Create a distinct key over the columns we are going to return */
2968
for (i=param->hidden_field_count, reg_field=table->field + i ;
2970
i++, reg_field++, key_part_info++)
2972
key_part_info->null_bit= 0;
2973
key_part_info->field= *reg_field;
2974
key_part_info->offset= (*reg_field)->offset(table->record[0]);
2975
key_part_info->length= (uint16_t) (*reg_field)->pack_length();
2977
The below method of computing the key format length of the
2978
key part is a copy/paste from optimizer/range.cc, and table.cc.
2979
This should be factored out, e.g. as a method of Field.
2980
In addition it is not clear if any of the Field::*_length
2981
methods is supposed to compute the same length. If so, it
2984
key_part_info->store_length= key_part_info->length;
2986
if ((*reg_field)->real_maybe_null())
2987
key_part_info->store_length+= HA_KEY_NULL_LENGTH;
2988
if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
2989
(*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
2990
key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
2992
key_part_info->type= (uint8_t) (*reg_field)->key_type();
2993
key_part_info->key_type =
2994
((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
2995
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
2996
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
3001
if (session->is_fatal_error) // If end of memory
3003
share->db_record_offset= 1;
3004
if (share->db_type() == myisam_engine)
3006
if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
3007
¶m->recinfo, select_options))
3010
if (table->open_tmp_table())
3013
session->mem_root= mem_root_save;
3018
session->mem_root= mem_root_save;
3019
table->free_tmp_table(session);
3023
/****************************************************************************/
3026
Create a reduced Table object with properly set up Field list from a
3027
list of field definitions.
3029
The created table doesn't have a table Cursor associated with
3030
it, has no keys, no group/distinct, no copy_funcs array.
3031
The sole purpose of this Table object is to use the power of Field
3032
class to read/write data to/from table->record[0]. Then one can store
3033
the record in any container (RB tree, hash, etc).
3034
The table is created in Session mem_root, so are the table's fields.
3035
Consequently, if you don't BLOB fields, you don't need to free it.
3037
@param session connection handle
3038
@param field_list list of column definitions
3041
0 if out of memory, Table object in case of success
3044
Table *create_virtual_tmp_table(Session *session, List<CreateField> &field_list)
3046
uint32_t field_count= field_list.elements;
3047
uint32_t blob_count= 0;
3049
CreateField *cdef; /* column definition */
3050
uint32_t record_length= 0;
3051
uint32_t null_count= 0; /* number of columns which may be null */
3052
uint32_t null_pack_length; /* NULL representation array length */
3053
uint32_t *blob_field;
3054
unsigned char *bitmaps;
3058
if (!multi_alloc_root(session->mem_root,
3059
&table, sizeof(*table),
3060
&share, sizeof(*share),
3061
&field, (field_count + 1) * sizeof(Field*),
3062
&blob_field, (field_count+1) *sizeof(uint32_t),
3063
&bitmaps, bitmap_buffer_size(field_count)*2,
3067
memset(table, 0, sizeof(*table));
3068
memset(share, 0, sizeof(*share));
3069
table->field= field;
3071
share->blob_field= blob_field;
3072
share->fields= field_count;
3073
share->blob_ptr_size= portable_sizeof_char_ptr;
3074
table->setup_tmp_table_column_bitmaps(bitmaps);
3076
/* Create all fields and calculate the total length of record */
3077
List_iterator_fast<CreateField> it(field_list);
3078
while ((cdef= it++))
3080
*field= make_field(share,
3084
(cdef->flags & NOT_NULL_FLAG) ? false : true,
3085
(unsigned char *) ((cdef->flags & NOT_NULL_FLAG) ? 0 : ""),
3086
(cdef->flags & NOT_NULL_FLAG) ? 0 : 1,
3095
(*field)->init(table);
3096
record_length+= (*field)->pack_length();
3097
if (! ((*field)->flags & NOT_NULL_FLAG))
3100
if ((*field)->flags & BLOB_FLAG)
3101
share->blob_field[blob_count++]= (uint32_t) (field - table->field);
3105
*field= NULL; /* mark the end of the list */
3106
share->blob_field[blob_count]= 0; /* mark the end of the list */
3107
share->blob_fields= blob_count;
3109
null_pack_length= (null_count + 7)/8;
3110
share->reclength= record_length + null_pack_length;
3111
share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
3112
table->record[0]= (unsigned char*) session->alloc(share->rec_buff_length);
3113
if (!table->record[0])
3116
if (null_pack_length)
3118
table->null_flags= (unsigned char*) table->record[0];
3119
share->null_fields= null_count;
3120
share->null_bytes= null_pack_length;
3123
table->in_use= session; /* field->reset() may access table->in_use */
3125
/* Set up field pointers */
3126
unsigned char *null_pos= table->record[0];
3127
unsigned char *field_pos= null_pos + share->null_bytes;
3128
uint32_t null_bit= 1;
3130
for (field= table->field; *field; ++field)
3132
Field *cur_field= *field;
3133
if ((cur_field->flags & NOT_NULL_FLAG))
3134
cur_field->move_field(field_pos);
3137
cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
3139
if (null_bit == (1 << 8))
3147
field_pos+= cur_field->pack_length();
3152
for (field= table->field; *field; ++field)
3153
delete *field; /* just invokes field destructor */
3157
bool Table::open_tmp_table()
3160
if ((error=cursor->ha_open(this, s->table_name.str,O_RDWR,
3161
HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
3163
print_error(error, MYF(0));
3167
(void) cursor->extra(HA_EXTRA_QUICK); /* Faster */
3536
Check type of .frm if we are not going to parse it
3173
Create MyISAM temporary table
3176
create_myisam_tmp_table()
3177
keyinfo Description of the index (there is always one index)
3178
start_recinfo MyISAM's column descriptions
3179
recinfo INOUT End of MyISAM's column descriptions
3183
Create a MyISAM temporary table according to passed description. The is
3184
assumed to have one unique index or constraint.
3186
The passed array or MI_COLUMNDEF structures must have this form:
3188
1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
3189
when there are many nullable columns)
3191
3. One free MI_COLUMNDEF element (*recinfo points here)
3193
This function may use the free element to create hash column for unique
3547
frm_type_enum mysql_frm_type(THD *thd __attribute__((unused)),
3548
char *path, enum legacy_db_type *dbt)
3201
bool Table::create_myisam_tmp_table(KEY *keyinfo,
3202
MI_COLUMNDEF *start_recinfo,
3203
MI_COLUMNDEF **recinfo,
3551
uchar header[10]; /* This should be optimized */
3554
*dbt= DB_TYPE_UNKNOWN;
3556
if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
3557
return(FRMTYPE_ERROR);
3558
error= my_read(file, (uchar*) header, sizeof(header), MYF(MY_NABP));
3559
my_close(file, MYF(MY_WME));
3562
return(FRMTYPE_ERROR);
3565
This is just a check for DB_TYPE. We'll return default unknown type
3566
if the following test is true (arg #3). This should not have effect
3567
on return value from this function (default FRMTYPE_TABLE)
3569
if (header[0] != (uchar) 254 || header[1] != 1 ||
3570
(header[2] != FRM_VER && header[2] != FRM_VER+1 &&
3571
(header[2] < FRM_VER+3 || header[2] > FRM_VER+4)))
3572
return(FRMTYPE_TABLE);
3574
*dbt= (enum legacy_db_type) (uint) *(header + 3);
3575
return(FRMTYPE_TABLE); // Is probably a .frm table
3579
/*****************************************************************************
3580
** Instansiate templates
3581
*****************************************************************************/
3583
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
3584
template class List<String>;
3585
template class List_iterator<String>;
3208
MI_UNIQUEDEF uniquedef;
3209
TableShare *share= s;
3212
{ // Get keys for ni_create
3213
bool using_unique_constraint= 0;
3214
HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
3215
sizeof(*seg) * keyinfo->key_parts);
3219
memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
3220
if (keyinfo->key_length >= cursor->getEngine()->max_key_length() ||
3221
keyinfo->key_parts > cursor->getEngine()->max_key_parts() ||
3224
/* Can't create a key; Make a unique constraint instead of a key */
3227
using_unique_constraint=1;
3228
memset(&uniquedef, 0, sizeof(uniquedef));
3229
uniquedef.keysegs=keyinfo->key_parts;
3231
uniquedef.null_are_equal=1;
3233
/* Create extra column for hash value */
3234
memset(*recinfo, 0, sizeof(**recinfo));
3235
(*recinfo)->type= FIELD_CHECK;
3236
(*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
3238
share->reclength+=MI_UNIQUE_HASH_LENGTH;
3242
/* Create an unique key */
3243
memset(&keydef, 0, sizeof(keydef));
3244
keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
3245
keydef.keysegs= keyinfo->key_parts;
3248
for (uint32_t i= 0; i < keyinfo->key_parts ; i++,seg++)
3250
Field *key_field=keyinfo->key_part[i].field;
3252
seg->language= key_field->charset()->number;
3253
seg->length= keyinfo->key_part[i].length;
3254
seg->start= keyinfo->key_part[i].offset;
3255
if (key_field->flags & BLOB_FLAG)
3257
seg->type= ((keyinfo->key_part[i].key_type & 1 /* binary */) ?
3258
HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
3259
seg->bit_start= (uint8_t)(key_field->pack_length()
3260
- share->blob_ptr_size);
3261
seg->flag= HA_BLOB_PART;
3262
seg->length= 0; // Whole blob in unique constraint
3266
seg->type= keyinfo->key_part[i].type;
3268
if (!(key_field->flags & NOT_NULL_FLAG))
3270
seg->null_bit= key_field->null_bit;
3271
seg->null_pos= (uint32_t) (key_field->null_ptr - (unsigned char*) record[0]);
3273
We are using a GROUP BY on something that contains NULL
3274
In this case we have to tell MyISAM that two NULL should
3275
on INSERT be regarded at the same value
3277
if (!using_unique_constraint)
3278
keydef.flag|= HA_NULL_ARE_EQUAL;
3282
MI_CREATE_INFO create_info;
3283
memset(&create_info, 0, sizeof(create_info));
3285
if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
3287
create_info.data_file_length= ~(uint64_t) 0;
3289
if ((error=mi_create(share->table_name.str, share->keys, &keydef,
3290
(uint32_t) (*recinfo-start_recinfo),
3292
share->uniques, &uniquedef,
3294
HA_CREATE_TMP_TABLE)))
3296
print_error(error, MYF(0));
3300
status_var_increment(in_use->status_var.created_tmp_disk_tables);
3301
share->db_record_offset= 1;
3308
void Table::free_tmp_table(Session *session)
3310
memory::Root own_root= mem_root;
3311
const char *save_proc_info;
3313
save_proc_info=session->get_proc_info();
3314
session->set_proc_info("removing tmp table");
3316
// Release latches since this can take a long time
3317
plugin::StorageEngine::releaseTemporaryLatches(session);
3322
cursor->closeMarkForDelete(s->table_name.str);
3324
s->db_type()->doDropTable(*session, s->table_name.str);
3330
for (Field **ptr= field ; *ptr ; ptr++)
3334
free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
3335
session->set_proc_info(save_proc_info);
3339
If a HEAP table gets full, create a MyISAM table and copy all rows
3343
bool create_myisam_from_heap(Session *session, Table *table,
3344
MI_COLUMNDEF *start_recinfo,
3345
MI_COLUMNDEF **recinfo,
3346
int error, bool ignore_last_dupp_key_error)
3350
const char *save_proc_info;
3353
if (table->s->db_type() != heap_engine ||
3354
error != HA_ERR_RECORD_FILE_FULL)
3356
table->print_error(error, MYF(0));
3360
// Release latches since this can take a long time
3361
plugin::StorageEngine::releaseTemporaryLatches(session);
3365
new_table.s= &share;
3366
new_table.s->storage_engine= myisam_engine;
3367
if (!(new_table.cursor= new_table.s->db_type()->getCursor(share, &new_table.mem_root)))
3368
return true; // End of memory
3370
save_proc_info=session->get_proc_info();
3371
session->set_proc_info("converting HEAP to MyISAM");
3373
if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
3374
recinfo, session->lex->select_lex.options |
3377
if (new_table.open_tmp_table())
3379
if (table->cursor->indexes_are_disabled())
3380
new_table.cursor->ha_disable_indexes(HA_KEY_SWITCH_ALL);
3381
table->cursor->ha_index_or_rnd_end();
3382
table->cursor->ha_rnd_init(1);
3385
new_table.cursor->extra(HA_EXTRA_NO_ROWS);
3386
new_table.no_rows=1;
3389
/* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
3390
new_table.cursor->extra(HA_EXTRA_WRITE_CACHE);
3393
copy all old rows from heap table to MyISAM table
3394
This is the only code that uses record[1] to read/write but this
3395
is safe as this is a temporary MyISAM table without timestamp/autoincrement.
3397
while (!table->cursor->rnd_next(new_table.record[1]))
3399
write_err= new_table.cursor->ha_write_row(new_table.record[1]);
3403
/* copy row that filled HEAP table */
3404
if ((write_err=new_table.cursor->ha_write_row(table->record[0])))
3406
if (new_table.cursor->is_fatal_error(write_err, HA_CHECK_DUP) ||
3407
!ignore_last_dupp_key_error)
3411
/* remove heap table and change to use myisam table */
3412
(void) table->cursor->ha_rnd_end();
3413
(void) table->cursor->close(); // This deletes the table !
3414
delete table->cursor;
3415
table->cursor= NULL;
3416
new_table.s= table->s; // Keep old share
3420
table->cursor->change_table_ptr(table, table->s);
3421
table->use_all_columns();
3424
const char *new_proc_info=
3425
(!strcmp(save_proc_info,"Copying to tmp table") ?
3426
"Copying to tmp table on disk" : save_proc_info);
3427
session->set_proc_info(new_proc_info);
3432
table->print_error(write_err, MYF(0));
3433
(void) table->cursor->ha_rnd_end();
3434
(void) new_table.cursor->close();
3436
new_table.s->db_type()->doDropTable(*session, new_table.s->table_name.str);
3438
delete new_table.cursor;
3439
session->set_proc_info(save_proc_info);
3440
table->mem_root= new_table.mem_root;
3444
my_bitmap_map *Table::use_all_columns(MyBitmap *bitmap)
3446
my_bitmap_map *old= bitmap->getBitmap();
3447
bitmap->setBitmap(s->all_set.getBitmap());
3451
void Table::restore_column_map(my_bitmap_map *old)
3453
read_set->setBitmap(old);
3456
uint32_t Table::find_shortest_key(const key_map *usable_keys)
3458
uint32_t min_length= UINT32_MAX;
3459
uint32_t best= MAX_KEY;
3460
if (usable_keys->any())
3462
for (uint32_t nr= 0; nr < s->keys ; nr++)
3464
if (usable_keys->test(nr))
3466
if (key_info[nr].key_length < min_length)
3468
min_length= key_info[nr].key_length;
3477
/*****************************************************************************
3478
Remove duplicates from tmp table
3479
This should be recoded to add a unique index to the table and remove
3481
Table is a locked single thread table
3482
fields is the number of fields to check (from the end)
3483
*****************************************************************************/
3485
bool Table::compare_record(Field **ptr)
3487
for (; *ptr ; ptr++)
3489
if ((*ptr)->cmp_offset(s->rec_buff_length))
3495
/* Return false if row hasn't changed */
3497
bool Table::compare_record()
3499
if (s->blob_fields + s->varchar_fields == 0)
3500
return memcmp(this->record[0], this->record[1], (size_t) s->reclength);
3502
/* Compare null bits */
3503
if (memcmp(null_flags, null_flags + s->rec_buff_length, s->null_bytes))
3504
return true; /* Diff in NULL value */
3506
/* Compare updated fields */
3507
for (Field **ptr= field ; *ptr ; ptr++)
3509
if (isWriteSet((*ptr)->field_index) &&
3510
(*ptr)->cmp_binary_offset(s->rec_buff_length))
3517
* Store a record from previous record into next
3520
void Table::storeRecord()
3522
memcpy(record[1], record[0], (size_t) s->reclength);
3526
* Store a record as an insert
3529
void Table::storeRecordAsInsert()
3531
memcpy(insert_values, record[0], (size_t) s->reclength);
3535
* Store a record with default values
3538
void Table::storeRecordAsDefault()
3540
memcpy(s->default_values, record[0], (size_t) s->reclength);
3544
* Restore a record from previous record into next
3547
void Table::restoreRecord()
3549
memcpy(record[0], record[1], (size_t) s->reclength);
3553
* Restore a record with default values
3556
void Table::restoreRecordAsDefault()
3558
memcpy(record[0], s->default_values, (size_t) s->reclength);
3565
void Table::emptyRecord()
3567
restoreRecordAsDefault();
3568
memset(null_flags, 255, s->null_bytes);
3582
insert_values(NULL),
3584
next_number_field(NULL),
3585
found_next_number_field(NULL),
3586
timestamp_field(NULL),
3587
pos_in_table_list(NULL),
3596
derived_select_number(0),
3597
current_lock(F_UNLCK),
3607
open_placeholder(false),
3608
locked_by_name(false),
3610
auto_increment_field_not_null(false),
3611
alias_name_used(false),
3613
quick_condition_rows(0),
3614
timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
3617
record[0]= (unsigned char *) 0;
3618
record[1]= (unsigned char *) 0;
3620
covering_keys.reset();
3625
keys_in_use_for_query.reset();
3626
keys_in_use_for_group_by.reset();
3627
keys_in_use_for_order_by.reset();
3629
memset(quick_rows, 0, sizeof(query_id_t) * MAX_KEY);
3630
memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
3632
memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
3633
memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
3635
memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
3636
memset(&sort, 0, sizeof(filesort_info_st));
3639
/*****************************************************************************
3640
The different ways to read a record
3641
Returns -1 if row was not found, 0 if row was found and 1 on errors
3642
*****************************************************************************/
3644
/** Help function when we get some an error from the table Cursor. */
3646
int Table::report_error(int error)
3648
if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
3650
status= STATUS_GARBAGE;
3651
return -1; // key not found; ok
3654
Locking reads can legally return also these errors, do not
3655
print them to the .err log
3657
if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
3658
errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
3659
error, s->path.str);
3660
print_error(error, MYF(0));
3666
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
3671
status= STATUS_NO_RECORD;
3672
maybe_null= table_list->outer_join;
3673
TableList *embedding= table_list->embedding;
3674
while (!maybe_null && embedding)
3676
maybe_null= embedding->outer_join;
3677
embedding= embedding->embedding;
3679
tablenr= table_number;
3680
map= (table_map) 1 << table_number;
3681
force_index= table_list->force_index;
3682
covering_keys= s->keys_for_keyread;
3686
Field *Table::find_field_in_table_sef(const char *name)
3689
if (s->name_hash.records)
3691
field_ptr= (Field**)hash_search(&s->name_hash,(unsigned char*) name,
3696
field_ptr points to field in TableShare. Convert it to the matching
3699
field_ptr= (field + (field_ptr - s->field));
3704
if (!(field_ptr= field))
3706
for (; *field_ptr; ++field_ptr)
3707
if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
3718
Used by ALTER Table when the table is a temporary one. It changes something
3719
only if the ALTER contained a RENAME clause (otherwise, table_name is the old
3721
Prepares a table cache key, which is the concatenation of db, table_name and
3722
session->slave_proxy_id, separated by '\0'.
3725
bool Table::rename_temporary_table(const char *db, const char *table_name)
3728
uint32_t key_length;
3729
TableShare *share= s;
3731
if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
3734
key_length= TableShare::createKey(key, db, table_name);
3735
share->set_table_cache_key(key, key_length);