12
12
You should have received a copy of the GNU General Public License
13
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
17
17
/* Some general useful functions */
28
#include <drizzled/error.h>
29
#include <drizzled/gettext.h>
31
#include "drizzled/plugin/transactional_storage_engine.h"
32
#include "drizzled/plugin/authorization.h"
33
#include <drizzled/nested_join.h>
34
#include <drizzled/sql_parse.h>
35
#include <drizzled/item/sum.h>
36
#include <drizzled/table_list.h>
37
#include <drizzled/session.h>
38
#include <drizzled/sql_base.h>
39
#include <drizzled/sql_select.h>
40
#include <drizzled/field/blob.h>
41
#include <drizzled/field/varstring.h>
42
#include <drizzled/field/double.h>
43
#include <drizzled/unireg.h>
44
#include <drizzled/message/table.pb.h>
45
#include "drizzled/sql_table.h"
46
#include "drizzled/charset.h"
47
#include "drizzled/internal/m_string.h"
48
#include "plugin/myisam/myisam.h"
50
#include <drizzled/item/string.h>
51
#include <drizzled/item/int.h>
52
#include <drizzled/item/decimal.h>
53
#include <drizzled/item/float.h>
54
#include <drizzled/item/null.h>
55
#include <drizzled/temporal.h>
57
#include "drizzled/table/instance.h"
59
#include "drizzled/table_proto.h"
66
extern pid_t current_pid;
67
extern plugin::StorageEngine *heap_engine;
68
extern plugin::StorageEngine *myisam_engine;
70
/* Functions defined in this cursor */
72
void open_table_error(TableShare *share, int error, int db_errno,
19
#include "mysql_priv.h"
23
/* INFORMATION_SCHEMA name */
24
LEX_STRING INFORMATION_SCHEMA_NAME= {C_STRING_WITH_LEN("information_schema")};
26
/* MYSQL_SCHEMA name */
27
LEX_STRING MYSQL_SCHEMA_NAME= {C_STRING_WITH_LEN("mysql")};
29
/* Functions defined in this file */
31
void open_table_error(TABLE_SHARE *share, int error, int db_errno,
73
32
myf errortype, int errarg);
33
static int open_binary_frm(THD *thd, TABLE_SHARE *share,
34
uchar *head, File file);
35
static void fix_type_pointers(const char ***array, TYPELIB *point_to_type,
36
uint types, char **names);
37
static uint find_field(Field **fields, uchar *record, uint start, uint length);
39
/**************************************************************************
40
Object_creation_ctx implementation.
41
**************************************************************************/
43
Object_creation_ctx *Object_creation_ctx::set_n_backup(THD *thd)
45
Object_creation_ctx *backup_ctx;
47
backup_ctx= create_backup_ctx(thd);
53
void Object_creation_ctx::restore_env(THD *thd, Object_creation_ctx *backup_ctx)
58
backup_ctx->change_env(thd);
63
/**************************************************************************
64
Default_object_creation_ctx implementation.
65
**************************************************************************/
67
Default_object_creation_ctx::Default_object_creation_ctx(THD *thd)
68
: m_client_cs(thd->variables.character_set_client),
69
m_connection_cl(thd->variables.collation_connection)
72
Default_object_creation_ctx::Default_object_creation_ctx(
73
CHARSET_INFO *client_cs, CHARSET_INFO *connection_cl)
74
: m_client_cs(client_cs),
75
m_connection_cl(connection_cl)
79
Default_object_creation_ctx::create_backup_ctx(THD *thd) const
81
return new Default_object_creation_ctx(thd);
84
void Default_object_creation_ctx::change_env(THD *thd) const
86
thd->variables.character_set_client= m_client_cs;
87
thd->variables.collation_connection= m_connection_cl;
89
thd->update_charset();
75
92
/*************************************************************************/
77
// @note this should all be the destructor
78
int Table::delete_table(bool free_share)
83
error= cursor->close();
87
for (Field **ptr=field ; *ptr ; ptr++)
94
/* Get column name from column hash */
96
static uchar *get_field_name(Field **buff, size_t *length,
97
my_bool not_used __attribute__((unused)))
99
*length= (uint) strlen((*buff)->field_name);
100
return (uchar*) (*buff)->field_name;
105
Returns pointer to '.frm' extension of the file name.
112
Checks file name part starting with the rightmost '.' character,
113
and returns it if it is equal to '.frm'.
116
It is a good idea to get rid of this function modifying the code
117
to garantee that the functions presently calling fn_rext() always
118
get arguments in the same format: either with '.frm' or without '.frm'.
121
Pointer to the '.frm' extension. If there is no extension,
122
or extension is not '.frm', pointer at the end of file name.
125
char *fn_rext(char *name)
127
char *res= strrchr(name, '.');
128
if (res && !strcmp(res, reg_ext))
130
return name + strlen(name);
133
TABLE_CATEGORY get_table_category(const LEX_STRING *db, const LEX_STRING *name)
136
assert(name != NULL);
138
if ((db->length == INFORMATION_SCHEMA_NAME.length) &&
139
(my_strcasecmp(system_charset_info,
140
INFORMATION_SCHEMA_NAME.str,
143
return TABLE_CATEGORY_INFORMATION;
146
return TABLE_CATEGORY_USER;
151
Allocate a setup TABLE_SHARE structure
155
TABLE_LIST Take database and table name from there
156
key Table cache key (db \0 table_name \0...)
157
key_length Length of key
160
0 Error (out of memory)
164
TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key,
169
char *key_buff, *path_buff;
170
char path[FN_REFLEN];
173
path_length= build_table_filename(path, sizeof(path) - 1,
175
table_list->table_name, "", 0);
176
init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
177
if (multi_alloc_root(&mem_root,
178
&share, sizeof(*share),
179
&key_buff, key_length,
180
&path_buff, path_length + 1,
183
bzero((char*) share, sizeof(*share));
185
share->set_table_cache_key(key_buff, key, key_length);
187
share->path.str= path_buff;
188
share->path.length= path_length;
189
strmov(share->path.str, path);
190
share->normalized_path.str= share->path.str;
191
share->normalized_path.length= path_length;
193
share->version= refresh_version;
196
This constant is used to mark that no table map version has been
197
assigned. No arithmetic is done on the value: it will be
198
overwritten with a value taken from MYSQL_BIN_LOG.
200
share->table_map_version= ~(uint64_t)0;
203
Since alloc_table_share() can be called without any locking (for
204
example, ha_create_table... functions), we do not assign a table
205
map id here. Instead we assign a value that is not used
206
elsewhere, and then assign a table map id inside open_table()
207
under the protection of the LOCK_open mutex.
209
share->table_map_id= ~0UL;
210
share->cached_row_logging_check= -1;
212
memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root));
213
pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
214
pthread_cond_init(&share->cond, NULL);
221
Initialize share for temporary tables
224
init_tmp_table_share()
227
key Table_cache_key, as generated from create_table_def_key.
228
must start with db name.
229
key_length Length of key
230
table_name Table name
231
path Path to file (possible in lower case) without .frm
234
This is different from alloc_table_share() because temporary tables
235
don't have to be shared between threads or put into the table def
236
cache, so we can do some things notable simpler and faster
238
If table is not put in thd->temporary_tables (happens only when
239
one uses OPEN TEMPORARY) then one can specify 'db' as key and
240
use key_length= 0 as neither table_cache_key or key_length will be used).
243
void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
244
uint key_length, const char *table_name,
248
bzero((char*) share, sizeof(*share));
249
init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
250
share->table_category= TABLE_CATEGORY_TEMPORARY;
251
share->tmp_table= INTERNAL_TMP_TABLE;
252
share->db.str= (char*) key;
253
share->db.length= strlen(key);
254
share->table_cache_key.str= (char*) key;
255
share->table_cache_key.length= key_length;
256
share->table_name.str= (char*) table_name;
257
share->table_name.length= strlen(table_name);
258
share->path.str= (char*) path;
259
share->normalized_path.str= (char*) path;
260
share->path.length= share->normalized_path.length= strlen(path);
261
share->frm_version= FRM_VER_TRUE_VARCHAR;
263
Temporary tables are not replicated, but we set up these fields
264
anyway to be able to catch errors.
266
share->table_map_version= ~(uint64_t)0;
267
share->cached_row_logging_check= -1;
270
table_map_id is also used for MERGE tables to suppress repeated
271
compatibility checks.
273
share->table_map_id= (ulong) thd->query_id;
280
Free table share and memory used by it
287
share->mutex must be locked when we come here if it's not a temp table
290
void free_table_share(TABLE_SHARE *share)
293
assert(share->ref_count == 0);
296
If someone is waiting for this to be deleted, inform it about this.
297
Don't do a delete until we know that no one is refering to this anymore.
299
if (share->tmp_table == NO_TMP_TABLE)
301
/* share->mutex is locked in release_table_share() */
302
while (share->waiting_on_cond)
304
pthread_cond_broadcast(&share->cond);
305
pthread_cond_wait(&share->cond, &share->mutex);
307
/* No thread refers to this anymore */
308
pthread_mutex_unlock(&share->mutex);
309
pthread_mutex_destroy(&share->mutex);
310
pthread_cond_destroy(&share->cond);
312
hash_free(&share->name_hash);
314
plugin_unlock(NULL, share->db_plugin);
315
share->db_plugin= NULL;
317
/* We must copy mem_root from share because share is allocated through it */
318
memcpy((char*) &mem_root, (char*) &share->mem_root, sizeof(mem_root));
319
free_root(&mem_root, MYF(0)); // Free's share
324
Read table definition from a binary / text based .frm file
329
share Fill this with table definition
330
db_flags Bit mask of the following flags: OPEN_VIEW
333
This function is called when the table definition is not cached in
335
The data is returned in 'share', which is alloced by
336
alloc_table_share().. The code assumes that share is initialized.
340
1 Error (see open_table_error)
341
2 Error (see open_table_error)
342
3 Wrong data in .frm file
343
4 Error (see open_table_error)
344
5 Error (see open_table_error: charset unavailable)
345
6 Unknown .frm version
348
int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags)
350
int error, table_type;
353
uchar head[64], *disk_buff;
354
char path[FN_REFLEN];
355
MEM_ROOT **root_ptr, *old_root;
361
strxmov(path, share->normalized_path.str, reg_ext, NullS);
362
if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
365
We don't try to open 5.0 unencoded name, if
366
- non-encoded name contains '@' signs,
367
because '@' can be misinterpreted.
368
It is not clear if '@' is escape character in 5.1,
369
or a normal character in 5.0.
371
- non-encoded db or table name contain "#mysql50#" prefix.
372
This kind of tables must have been opened only by the
375
if (strchr(share->table_name.str, '@') ||
376
!strncmp(share->db.str, MYSQL50_TABLE_NAME_PREFIX,
377
MYSQL50_TABLE_NAME_PREFIX_LENGTH) ||
378
!strncmp(share->table_name.str, MYSQL50_TABLE_NAME_PREFIX,
379
MYSQL50_TABLE_NAME_PREFIX_LENGTH))
382
/* Try unencoded 5.0 name */
384
strxnmov(path, sizeof(path)-1,
385
mysql_data_home, "/", share->db.str, "/",
386
share->table_name.str, reg_ext, NullS);
387
length= unpack_filename(path, path) - reg_ext_length;
389
The following is a safety test and should never fail
390
as the old file name should never be longer than the new one.
392
assert(length <= share->normalized_path.length);
394
If the old and the new names have the same length,
395
then table name does not have tricky characters,
396
so no need to check the old file name.
398
if (length == share->normalized_path.length ||
399
((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0))
402
/* Unencoded 5.0 table name found */
403
path[length]= '\0'; // Remove .frm extension
404
strmov(share->normalized_path.str, path);
405
share->normalized_path.length= length;
409
if (my_read(file, head, 64, MYF(MY_NABP)))
412
if (head[0] == (uchar) 254 && head[1] == 1)
414
if (head[2] == FRM_VER || head[2] == FRM_VER+1 ||
415
(head[2] >= FRM_VER+3 && head[2] <= FRM_VER+4))
418
if (db_flags & OPEN_VIEW_ONLY)
427
error= 6; // Unkown .frm version
434
/* No handling of text based files yet */
437
root_ptr= (MEM_ROOT **)pthread_getspecific(THR_MALLOC);
439
*root_ptr= &share->mem_root;
440
error= open_binary_frm(thd, share, head, file);
447
share->table_category= get_table_category(& share->db, & share->table_name);
450
thd->status_var.opened_shares++;
453
my_close(file, MYF(MY_WME));
456
if (error && !error_given)
459
open_table_error(share, error, (share->open_errno= my_errno), 0);
467
Read data from a binary .frm file from MySQL 3.23 - 5.0 into TABLE_SHARE
470
static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
473
int error, errarg= 0;
474
uint new_frm_ver, field_pack_length, new_field_pack_flag;
475
uint interval_count, interval_parts, read_length, int_length;
476
uint db_create_options, keys, key_parts, n_length;
477
uint key_info_length, com_length, null_bit_pos=0;
478
uint extra_rec_buf_length;
482
char *keynames, *names, *comment_pos;
484
uchar *disk_buff, *strpos, *null_flags=NULL, *null_pos=NULL;
485
ulong pos, record_offset, *rec_per_key, rec_buff_length;
486
handler *handler_file= 0;
488
KEY_PART_INFO *key_part;
489
SQL_CRYPT *crypted=0;
490
Field **field_ptr, *reg_field;
491
const char **interval_array;
492
enum legacy_db_type legacy_db_type;
493
my_bitmap_map *bitmaps;
495
uchar *field_extra_info= 0;
497
new_field_pack_flag= head[27];
498
new_frm_ver= (head[2] - FRM_VER);
499
field_pack_length= new_frm_ver < 2 ? 11 : 17;
503
if (!(pos=get_form_pos(file,head,(TYPELIB*) 0)))
504
goto err; /* purecov: inspected */
505
VOID(my_seek(file,pos,MY_SEEK_SET,MYF(0)));
506
if (my_read(file,forminfo,288,MYF(MY_NABP)))
509
share->frm_version= head[2];
511
Check if .frm file created by MySQL 5.0. In this case we want to
512
display CHAR fields as CHAR and not as VARCHAR.
513
We do it this way as we want to keep the old frm version to enable
514
MySQL 4.1 to read these files.
516
if (share->frm_version == FRM_VER_TRUE_VARCHAR -1 && head[33] == 5)
517
share->frm_version= FRM_VER_TRUE_VARCHAR;
519
legacy_db_type= DB_TYPE_FIRST_DYNAMIC;
520
assert(share->db_plugin == NULL);
522
if the storage engine is dynamic, no point in resolving it by its
523
dynamically allocated legacy_db_type. We will resolve it later by name.
525
if (legacy_db_type > DB_TYPE_UNKNOWN &&
526
legacy_db_type < DB_TYPE_FIRST_DYNAMIC)
527
share->db_plugin= ha_lock_engine(NULL,
528
ha_checktype(thd, legacy_db_type, 0, 0));
529
share->db_create_options= db_create_options= uint2korr(head+30);
530
share->db_options_in_use= share->db_create_options;
531
share->mysql_version= uint4korr(head+51);
532
share->null_field_first= 0;
533
if (!head[32]) // New frm file in 3.23
535
share->avg_row_length= uint4korr(head+34);
536
share->transactional= (ha_choice) (head[39] & 3);
537
share->page_checksum= (ha_choice) ((head[39] >> 2) & 3);
538
share->row_type= (row_type) head[40];
539
share->table_charset= get_charset((uint) head[38],MYF(0));
540
share->null_field_first= 1;
542
if (!share->table_charset)
544
/* unknown charset in head[38] or pre-3.23 frm */
545
if (use_mb(default_charset_info))
547
/* Warn that we may be changing the size of character columns */
548
sql_print_warning("'%s' had no or invalid character set, "
549
"and default character set is multi-byte, "
550
"so character column sizes may have changed",
553
share->table_charset= default_charset_info;
555
share->db_record_offset= 1;
556
if (db_create_options & HA_OPTION_LONG_BLOB_PTR)
557
share->blob_ptr_size= portable_sizeof_char_ptr;
558
/* Set temporarily a good value for db_low_byte_first */
559
share->db_low_byte_first= test(legacy_db_type != DB_TYPE_ISAM);
561
share->max_rows= uint4korr(head+18);
562
share->min_rows= uint4korr(head+22);
564
/* Read keyinformation */
565
key_info_length= (uint) uint2korr(head+28);
566
VOID(my_seek(file,(ulong) uint2korr(head+6),MY_SEEK_SET,MYF(0)));
567
if (read_string(file,(uchar**) &disk_buff,key_info_length))
568
goto err; /* purecov: inspected */
569
if (disk_buff[0] & 0x80)
571
share->keys= keys= (disk_buff[1] << 7) | (disk_buff[0] & 0x7f);
572
share->key_parts= key_parts= uint2korr(disk_buff+2);
576
share->keys= keys= disk_buff[0];
577
share->key_parts= key_parts= disk_buff[1];
579
share->keys_for_keyread.init(0);
580
share->keys_in_use.init(keys);
582
n_length=keys*sizeof(KEY)+key_parts*sizeof(KEY_PART_INFO);
583
if (!(keyinfo = (KEY*) alloc_root(&share->mem_root,
584
n_length + uint2korr(disk_buff+4))))
585
goto err; /* purecov: inspected */
586
bzero((char*) keyinfo,n_length);
587
share->key_info= keyinfo;
588
key_part= my_reinterpret_cast(KEY_PART_INFO*) (keyinfo+keys);
591
if (!(rec_per_key= (ulong*) alloc_root(&share->mem_root,
592
sizeof(ulong*)*key_parts)))
595
for (i=0 ; i < keys ; i++, keyinfo++)
597
keyinfo->table= 0; // Updated in open_frm
598
if (new_frm_ver >= 3)
600
keyinfo->flags= (uint) uint2korr(strpos) ^ HA_NOSAME;
601
keyinfo->key_length= (uint) uint2korr(strpos+2);
602
keyinfo->key_parts= (uint) strpos[4];
603
keyinfo->algorithm= (enum ha_key_alg) strpos[5];
604
keyinfo->block_size= uint2korr(strpos+6);
608
keyinfo->key_part= key_part;
609
keyinfo->rec_per_key= rec_per_key;
610
for (j=keyinfo->key_parts ; j-- ; key_part++)
613
key_part->fieldnr= (uint16) (uint2korr(strpos) & FIELD_NR_MASK);
614
key_part->offset= (uint) uint2korr(strpos+2)-1;
615
key_part->key_type= (uint) uint2korr(strpos+5);
616
// key_part->field= (Field*) 0; // Will be fixed later
617
if (new_frm_ver >= 1)
619
key_part->key_part_flag= *(strpos+4);
620
key_part->length= (uint) uint2korr(strpos+7);
625
key_part->length= *(strpos+4);
626
key_part->key_part_flag=0;
627
if (key_part->length > 128)
629
key_part->length&=127; /* purecov: inspected */
630
key_part->key_part_flag=HA_REVERSE_SORT; /* purecov: inspected */
634
key_part->store_length=key_part->length;
637
keynames=(char*) key_part;
638
strpos+= (strmov(keynames, (char *) strpos) - keynames)+1;
640
//reading index comments
641
for (keyinfo= share->key_info, i=0; i < keys; i++, keyinfo++)
643
if (keyinfo->flags & HA_USES_COMMENT)
645
keyinfo->comment.length= uint2korr(strpos);
646
keyinfo->comment.str= strmake_root(&share->mem_root, (char*) strpos+2,
647
keyinfo->comment.length);
648
strpos+= 2 + keyinfo->comment.length;
650
assert(test(keyinfo->flags & HA_USES_COMMENT) ==
651
(keyinfo->comment.length > 0));
654
share->reclength = uint2korr((head+16));
656
share->system= 1; /* one-record-database */
658
record_offset= (ulong) (uint2korr(head+6)+
659
((uint2korr(head+14) == 0xffff ?
660
uint4korr(head+47) : uint2korr(head+14))));
662
if ((n_length= uint4korr(head+55)))
664
/* Read extra data segment */
665
uchar *next_chunk, *buff_end;
666
if (!(next_chunk= buff= (uchar*) my_malloc(n_length, MYF(MY_WME))))
668
if (pread(file, buff, n_length, record_offset + share->reclength) == 0)
672
share->connect_string.length= uint2korr(buff);
673
if (!(share->connect_string.str= strmake_root(&share->mem_root,
674
(char*) next_chunk + 2,
675
share->connect_string.
680
next_chunk+= share->connect_string.length + 2;
681
buff_end= buff + n_length;
682
if (next_chunk + 2 < buff_end)
684
uint str_db_type_length= uint2korr(next_chunk);
686
name.str= (char*) next_chunk + 2;
687
name.length= str_db_type_length;
689
plugin_ref tmp_plugin= ha_resolve_by_name(thd, &name);
690
if (tmp_plugin != NULL && !plugin_equals(tmp_plugin, share->db_plugin))
692
if (legacy_db_type > DB_TYPE_UNKNOWN &&
693
legacy_db_type < DB_TYPE_FIRST_DYNAMIC &&
694
legacy_db_type != ha_legacy_type(
695
plugin_data(tmp_plugin, handlerton *)))
697
/* bad file, legacy_db_type did not match the name */
698
my_free(buff, MYF(0));
702
tmp_plugin is locked with a local lock.
703
we unlock the old value of share->db_plugin before
704
replacing it with a globally locked version of tmp_plugin
706
plugin_unlock(NULL, share->db_plugin);
707
share->db_plugin= my_plugin_lock(NULL, &tmp_plugin);
709
else if (!tmp_plugin)
711
/* purecov: begin inspected */
713
my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
714
my_free(buff, MYF(0));
718
next_chunk+= str_db_type_length + 2;
720
if (share->mysql_version >= 50110)
722
/* New auto_partitioned indicator introduced in 5.1.11 */
725
if (forminfo[46] == (uchar)255)
727
//reading long table comment
728
if (next_chunk + 2 > buff_end)
730
my_free(buff, MYF(0));
733
share->comment.length = uint2korr(next_chunk);
734
if (! (share->comment.str= strmake_root(&share->mem_root,
735
(char*)next_chunk + 2, share->comment.length)))
737
my_free(buff, MYF(0));
740
next_chunk+= 2 + share->comment.length;
742
assert(next_chunk <= buff_end);
743
if (share->mysql_version >= MYSQL_VERSION_TABLESPACE_IN_FRM_CGE)
746
New frm format in mysql_version 5.2.5 (originally in
747
mysql-5.1.22-ndb-6.2.5)
748
New column properties added:
749
COLUMN_FORMAT DYNAMIC|FIXED and STORAGE DISK|MEMORY
750
TABLESPACE name is now stored in frm
752
if (next_chunk >= buff_end)
754
if (share->mysql_version >= MYSQL_VERSION_TABLESPACE_IN_FRM)
761
const uint format_section_header_size= 8;
762
uint format_section_len= uint2korr(next_chunk+0);
764
field_extra_info= next_chunk + format_section_header_size + 1;
765
next_chunk+= format_section_len;
768
assert (next_chunk <= buff_end);
769
if (next_chunk > buff_end)
774
share->key_block_size= uint2korr(head+62);
777
extra_rec_buf_length= uint2korr(head+59);
778
rec_buff_length= ALIGN_SIZE(share->reclength + 1 + extra_rec_buf_length);
779
share->rec_buff_length= rec_buff_length;
780
if (!(record= (uchar *) alloc_root(&share->mem_root,
782
goto err; /* purecov: inspected */
783
share->default_values= record;
784
if (pread(file, record, (size_t) share->reclength, record_offset) == 0)
785
goto err; /* purecov: inspected */
787
VOID(my_seek(file,pos+288,MY_SEEK_SET,MYF(0)));
789
share->fields= uint2korr(forminfo+258);
790
pos= uint2korr(forminfo+260); /* Length of all screens */
791
n_length= uint2korr(forminfo+268);
792
interval_count= uint2korr(forminfo+270);
793
interval_parts= uint2korr(forminfo+272);
794
int_length= uint2korr(forminfo+274);
795
share->null_fields= uint2korr(forminfo+282);
796
com_length= uint2korr(forminfo+284);
797
if (forminfo[46] != (uchar)255)
799
share->comment.length= (int) (forminfo[46]);
800
share->comment.str= strmake_root(&share->mem_root, (char*) forminfo+47,
801
share->comment.length);
805
if (!(field_ptr = (Field **)
806
alloc_root(&share->mem_root,
807
(uint) ((share->fields+1)*sizeof(Field*)+
808
interval_count*sizeof(TYPELIB)+
809
(share->fields+interval_parts+
810
keys+3)*sizeof(char *)+
811
(n_length+int_length+com_length)))))
812
goto err; /* purecov: inspected */
814
share->field= field_ptr;
815
read_length=(uint) (share->fields * field_pack_length +
816
pos+ (uint) (n_length+int_length+com_length));
817
if (read_string(file,(uchar**) &disk_buff,read_length))
818
goto err; /* purecov: inspected */
819
strpos= disk_buff+pos;
821
share->intervals= (TYPELIB*) (field_ptr+share->fields+1);
822
interval_array= (const char **) (share->intervals+interval_count);
823
names= (char*) (interval_array+share->fields+interval_parts+keys+3);
825
share->intervals= 0; // For better debugging
826
memcpy((char*) names, strpos+(share->fields*field_pack_length),
827
(uint) (n_length+int_length));
828
comment_pos= names+(n_length+int_length);
829
memcpy(comment_pos, disk_buff+read_length-com_length, com_length);
831
fix_type_pointers(&interval_array, &share->fieldnames, 1, &names);
832
if (share->fieldnames.count != share->fields)
834
fix_type_pointers(&interval_array, share->intervals, interval_count,
838
/* Set ENUM and SET lengths */
840
for (interval= share->intervals;
841
interval < share->intervals + interval_count;
844
uint count= (uint) (interval->count + 1) * sizeof(uint);
845
if (!(interval->type_lengths= (uint *) alloc_root(&share->mem_root,
848
for (count= 0; count < interval->count; count++)
850
char *val= (char*) interval->type_names[count];
851
interval->type_lengths[count]= strlen(val);
853
interval->type_lengths[count]= 0;
858
fix_type_pointers(&interval_array, &share->keynames, 1, &keynames);
860
/* Allocate handler */
861
if (!(handler_file= get_new_handler(share, thd->mem_root,
865
record= share->default_values-1; /* Fieldstart = 1 */
866
if (share->null_field_first)
868
null_flags= null_pos= (uchar*) record+1;
869
null_bit_pos= (db_create_options & HA_OPTION_PACK_RECORD) ? 0 : 1;
871
null_bytes below is only correct under the condition that
872
there are no bit fields. Correct values is set below after the
873
table struct is initialized
875
share->null_bytes= (share->null_fields + null_bit_pos + 7) / 8;
878
use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
880
use_hash= !hash_init(&share->name_hash,
883
(hash_get_key) get_field_name,0,0);
885
for (i=0 ; i < share->fields; i++, strpos+=field_pack_length, field_ptr++)
887
uint pack_flag, interval_nr, unireg_type, recpos, field_length;
888
enum_field_types field_type;
889
enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
890
CHARSET_INFO *charset=NULL;
893
if (field_extra_info)
895
char tmp= field_extra_info[i];
896
column_format= (enum column_format_type)
897
((tmp >> COLUMN_FORMAT_SHIFT) & COLUMN_FORMAT_MASK);
899
if (new_frm_ver >= 3)
901
/* new frm file in 4.1 */
902
field_length= uint2korr(strpos+3);
903
recpos= uint3korr(strpos+5);
904
pack_flag= uint2korr(strpos+8);
905
unireg_type= (uint) strpos[10];
906
interval_nr= (uint) strpos[12];
907
uint comment_length=uint2korr(strpos+15);
908
field_type=(enum_field_types) (uint) strpos[13];
912
charset= &my_charset_bin;
913
else if (!(charset=get_charset((uint) strpos[14], MYF(0))))
915
error= 5; // Unknown or unavailable charset
916
errarg= (int) strpos[14];
922
comment.str= (char*) "";
927
comment.str= (char*) comment_pos;
928
comment.length= comment_length;
929
comment_pos+= comment_length;
934
field_length= (uint) strpos[3];
935
recpos= uint2korr(strpos+4),
936
pack_flag= uint2korr(strpos+6);
937
pack_flag&= ~FIELDFLAG_NO_DEFAULT; // Safety for old files
938
unireg_type= (uint) strpos[8];
939
interval_nr= (uint) strpos[10];
942
field_type= (enum_field_types) f_packtype(pack_flag);
943
if (f_is_binary(pack_flag))
946
Try to choose the best 4.1 type:
947
- for 4.0 "CHAR(N) BINARY" or "VARCHAR(N) BINARY"
948
try to find a binary collation for character set.
949
- for other types (e.g. BLOB) just use my_charset_bin.
951
if (!f_is_blob(pack_flag))
953
// 3.23 or 4.0 string
954
if (!(charset= get_charset_by_csname(share->table_charset->csname,
955
MY_CS_BINSORT, MYF(0))))
956
charset= &my_charset_bin;
959
charset= &my_charset_bin;
962
charset= share->table_charset;
963
bzero((char*) &comment, sizeof(comment));
966
if (interval_nr && charset->mbminlen > 1)
968
/* Unescape UCS2 intervals from HEX notation */
969
TYPELIB *interval= share->intervals + interval_nr - 1;
970
unhex_type2(interval);
973
#ifndef TO_BE_DELETED_ON_PRODUCTION
974
if (field_type == MYSQL_TYPE_NEWDECIMAL && !share->mysql_version)
977
Fix pack length of old decimal values from 5.0.3 -> 5.0.4
978
The difference is that in the old version we stored precision
979
in the .frm table while we now store the display_length
981
uint decimals= f_decimals(pack_flag);
982
field_length= my_decimal_precision_to_length(field_length,
984
f_is_dec(pack_flag) == 0);
985
sql_print_error("Found incompatible DECIMAL field '%s' in %s; "
986
"Please do \"ALTER TABLE '%s' FORCE\" to fix it!",
987
share->fieldnames.type_names[i], share->table_name.str,
988
share->table_name.str);
989
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
991
"Found incompatible DECIMAL field '%s' in %s; "
992
"Please do \"ALTER TABLE '%s' FORCE\" to fix it!",
993
share->fieldnames.type_names[i],
994
share->table_name.str,
995
share->table_name.str);
996
share->crashed= 1; // Marker for CHECK TABLE
1000
*field_ptr= reg_field=
1001
make_field(share, record+recpos,
1002
(uint32) field_length,
1003
null_pos, null_bit_pos,
1007
(Field::utype) MTYP_TYPENR(unireg_type),
1009
share->intervals+interval_nr-1 :
1011
share->fieldnames.type_names[i]);
1012
if (!reg_field) // Not supported field type
1015
goto err; /* purecov: inspected */
1018
reg_field->flags|= ((uint)column_format << COLUMN_FORMAT_FLAGS);
1019
reg_field->field_index= i;
1020
reg_field->comment=comment;
1021
if (!(reg_field->flags & NOT_NULL_FLAG))
1023
if (!(null_bit_pos= (null_bit_pos + 1) & 7))
1026
if (f_no_default(pack_flag))
1027
reg_field->flags|= NO_DEFAULT_VALUE_FLAG;
1029
if (reg_field->unireg_check == Field::NEXT_NUMBER)
1030
share->found_next_number_field= field_ptr;
1031
if (share->timestamp_field == reg_field)
1032
share->timestamp_field_offset= i;
1035
(void) my_hash_insert(&share->name_hash,
1036
(uchar*) field_ptr); // never fail
1038
*field_ptr=0; // End marker
1040
/* Fix key->name and key_part->field */
1043
uint primary_key=(uint) (find_type((char*) primary_key_name,
1044
&share->keynames, 3) - 1);
1045
longlong ha_option= handler_file->ha_table_flags();
1046
keyinfo= share->key_info;
1047
key_part= keyinfo->key_part;
1049
for (uint key=0 ; key < share->keys ; key++,keyinfo++)
1051
uint usable_parts= 0;
1052
keyinfo->name=(char*) share->keynames.type_names[key];
1054
if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
1057
If the UNIQUE key doesn't have NULL columns and is not a part key
1058
declare this as a primary key.
1061
for (i=0 ; i < keyinfo->key_parts ;i++)
1063
uint fieldnr= key_part[i].fieldnr;
1065
share->field[fieldnr-1]->null_ptr ||
1066
share->field[fieldnr-1]->key_length() !=
1069
primary_key=MAX_KEY; // Can't be used
1075
for (i=0 ; i < keyinfo->key_parts ; key_part++,i++)
1078
if (new_field_pack_flag <= 1)
1079
key_part->fieldnr= (uint16) find_field(share->field,
1080
share->default_values,
1081
(uint) key_part->offset,
1082
(uint) key_part->length);
1083
if (!key_part->fieldnr)
1085
error= 4; // Wrong file
1088
field= key_part->field= share->field[key_part->fieldnr-1];
1089
key_part->type= field->key_type();
1090
if (field->null_ptr)
1092
key_part->null_offset=(uint) ((uchar*) field->null_ptr -
1093
share->default_values);
1094
key_part->null_bit= field->null_bit;
1095
key_part->store_length+=HA_KEY_NULL_LENGTH;
1096
keyinfo->flags|=HA_NULL_PART_KEY;
1097
keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
1098
keyinfo->key_length+= HA_KEY_NULL_LENGTH;
1100
if (field->type() == MYSQL_TYPE_BLOB ||
1101
field->real_type() == MYSQL_TYPE_VARCHAR)
1103
if (field->type() == MYSQL_TYPE_BLOB)
1104
key_part->key_part_flag|= HA_BLOB_PART;
1106
key_part->key_part_flag|= HA_VAR_LENGTH_PART;
1107
keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
1108
key_part->store_length+=HA_KEY_BLOB_LENGTH;
1109
keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
1111
if (i == 0 && key != primary_key)
1112
field->flags |= (((keyinfo->flags & HA_NOSAME) &&
1113
(keyinfo->key_parts == 1)) ?
1114
UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
1116
field->key_start.set_bit(key);
1117
if (field->key_length() == key_part->length &&
1118
!(field->flags & BLOB_FLAG))
1120
if (handler_file->index_flags(key, i, 0) & HA_KEYREAD_ONLY)
1122
share->keys_for_keyread.set_bit(key);
1123
field->part_of_key.set_bit(key);
1124
field->part_of_key_not_clustered.set_bit(key);
1126
if (handler_file->index_flags(key, i, 1) & HA_READ_ORDER)
1127
field->part_of_sortkey.set_bit(key);
1129
if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
1131
usable_parts++; // For FILESORT
1132
field->flags|= PART_KEY_FLAG;
1133
if (key == primary_key)
1135
field->flags|= PRI_KEY_FLAG;
1137
If this field is part of the primary key and all keys contains
1138
the primary key, then we can use any key to find this column
1140
if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
1142
field->part_of_key= share->keys_in_use;
1143
if (field->part_of_sortkey.is_set(key))
1144
field->part_of_sortkey= share->keys_in_use;
1147
if (field->key_length() != key_part->length)
1149
#ifndef TO_BE_DELETED_ON_PRODUCTION
1150
if (field->type() == MYSQL_TYPE_NEWDECIMAL)
1153
Fix a fatal error in decimal key handling that causes crashes
1154
on Innodb. We fix it by reducing the key length so that
1155
InnoDB never gets a too big key when searching.
1156
This allows the end user to do an ALTER TABLE to fix the
1159
keyinfo->key_length-= (key_part->length - field->key_length());
1160
key_part->store_length-= (uint16)(key_part->length -
1161
field->key_length());
1162
key_part->length= (uint16)field->key_length();
1163
sql_print_error("Found wrong key definition in %s; "
1164
"Please do \"ALTER TABLE '%s' FORCE \" to fix it!",
1165
share->table_name.str,
1166
share->table_name.str);
1167
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
1168
ER_CRASHED_ON_USAGE,
1169
"Found wrong key definition in %s; "
1170
"Please do \"ALTER TABLE '%s' FORCE\" to fix "
1172
share->table_name.str,
1173
share->table_name.str);
1174
share->crashed= 1; // Marker for CHECK TABLE
1178
key_part->key_part_flag|= HA_PART_KEY_SEG;
1181
keyinfo->usable_key_parts= usable_parts; // Filesort
1183
set_if_bigger(share->max_key_length,keyinfo->key_length+
1184
keyinfo->key_parts);
1185
share->total_key_length+= keyinfo->key_length;
1187
MERGE tables do not have unique indexes. But every key could be
1188
an unique index on the underlying MyISAM table. (Bug #10400)
1190
if ((keyinfo->flags & HA_NOSAME) ||
1191
(ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
1192
set_if_bigger(share->max_unique_length,keyinfo->key_length);
1194
if (primary_key < MAX_KEY &&
1195
(share->keys_in_use.is_set(primary_key)))
1197
share->primary_key= primary_key;
1199
If we are using an integer as the primary key then allow the user to
1200
refer to it as '_rowid'
1202
if (share->key_info[primary_key].key_parts == 1)
1204
Field *field= share->key_info[primary_key].key_part[0].field;
1205
if (field && field->result_type() == INT_RESULT)
1207
/* note that fieldnr here (and rowid_field_offset) starts from 1 */
1208
share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
1214
share->primary_key = MAX_KEY; // we do not have a primary key
1217
share->primary_key= MAX_KEY;
1218
x_free((uchar*) disk_buff);
1220
if (new_field_pack_flag <= 1)
1222
/* Old file format with default as not null */
1223
uint null_length= (share->null_fields+7)/8;
1224
bfill(share->default_values + (null_flags - (uchar*) record),
1228
if (share->found_next_number_field)
1230
reg_field= *share->found_next_number_field;
1231
if ((int) (share->next_number_index= (uint)
1232
find_ref_key(share->key_info, share->keys,
1233
share->default_values, reg_field,
1234
&share->next_number_key_offset,
1235
&share->next_number_keypart)) < 0)
1237
/* Wrong field definition */
1242
reg_field->flags |= AUTO_INCREMENT_FLAG;
1245
if (share->blob_fields)
1250
/* Store offsets to blob fields to find them fast */
1251
if (!(share->blob_field= save=
1252
(uint*) alloc_root(&share->mem_root,
1253
(uint) (share->blob_fields* sizeof(uint)))))
1255
for (k=0, ptr= share->field ; *ptr ; ptr++, k++)
1257
if ((*ptr)->flags & BLOB_FLAG)
1263
the correct null_bytes can now be set, since bitfields have been taken
1266
share->null_bytes= (null_pos - (uchar*) null_flags +
1267
(null_bit_pos + 7) / 8);
1268
share->last_null_bit_pos= null_bit_pos;
1270
share->db_low_byte_first= handler_file->low_byte_first();
1271
share->column_bitmap_size= bitmap_buffer_size(share->fields);
1273
if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
1274
share->column_bitmap_size)))
1276
bitmap_init(&share->all_set, bitmaps, share->fields, false);
1277
bitmap_set_all(&share->all_set);
1279
delete handler_file;
1281
my_free(buff, MYF(0));
1286
my_free(buff, MYF(0));
1287
share->error= error;
1288
share->open_errno= my_errno;
1289
share->errarg= errarg;
1290
x_free((uchar*) disk_buff);
1292
delete handler_file;
1293
hash_free(&share->name_hash);
1295
open_table_error(share, error, share->open_errno, errarg);
1297
} /* open_binary_frm */
1301
Open a table based on a TABLE_SHARE
1304
open_table_from_share()
1306
share Table definition
1307
alias Alias for table
1308
db_stat open flags (for example HA_OPEN_KEYFILE|
1309
HA_OPEN_RNDFILE..) can be 0 (example in
1311
prgflag READ_ALL etc..
1312
ha_open_flags HA_OPEN_ABORT_IF_LOCKED etc..
1313
outparam result table
1314
open_mode One of OTM_OPEN|OTM_CREATE|OTM_ALTER
1315
if OTM_CREATE some errors are ignore
1316
if OTM_ALTER HA_OPEN is not called
1320
1 Error (see open_table_error)
1321
2 Error (see open_table_error)
1322
3 Wrong data in .frm file
1323
4 Error (see open_table_error)
1324
5 Error (see open_table_error: charset unavailable)
1325
7 Table definition has changed in engine
1328
int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
1329
uint db_stat, uint prgflag, uint ha_open_flags,
1330
TABLE *outparam, open_table_mode open_mode)
1333
uint records, i, bitmap_size;
1334
bool error_reported= false;
1335
uchar *record, *bitmaps;
1338
/* Parsing of partitioning information from .frm needs thd->lex set up. */
1339
assert(thd->lex->is_lex_started);
1342
bzero((char*) outparam, sizeof(*outparam));
1343
outparam->in_use= thd;
1345
outparam->db_stat= db_stat;
1346
outparam->write_row_record= NULL;
1348
init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
1350
if (!(outparam->alias= my_strdup(alias, MYF(MY_WME))))
1352
outparam->quick_keys.init();
1353
outparam->covering_keys.init();
1354
outparam->keys_in_use_for_query.init();
1356
/* Allocate handler */
1358
if (!(prgflag & OPEN_FRM_FILE_ONLY))
1360
if (!(outparam->file= get_new_handler(share, &outparam->mem_root,
1370
outparam->reginfo.lock_type= TL_UNLOCK;
1371
outparam->current_lock= F_UNLCK;
1373
if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
1375
if (prgflag & (READ_ALL+EXTRA_RECORD))
1378
if (!(record= (uchar*) alloc_root(&outparam->mem_root,
1379
share->rec_buff_length * records)))
1380
goto err; /* purecov: inspected */
1384
/* We are probably in hard repair, and the buffers should not be used */
1385
outparam->record[0]= outparam->record[1]= share->default_values;
1389
outparam->record[0]= record;
1391
outparam->record[1]= record+ share->rec_buff_length;
1393
outparam->record[1]= outparam->record[0]; // Safety
1398
We need this because when we read var-length rows, we are not updating
1399
bytes after end of varchar
1403
memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
1404
memcpy(outparam->record[1], share->default_values, share->null_bytes);
1406
memcpy(outparam->record[1], share->default_values,
1407
share->rec_buff_length);
1411
if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
1412
(uint) ((share->fields+1)*
1414
goto err; /* purecov: inspected */
1416
outparam->field= field_ptr;
1418
record= (uchar*) outparam->record[0]-1; /* Fieldstart = 1 */
1419
if (share->null_field_first)
1420
outparam->null_flags= (uchar*) record+1;
1422
outparam->null_flags= (uchar*) (record+ 1+ share->reclength -
1425
/* Setup copy of fields from share, but use the right alias and record */
1426
for (i=0 ; i < share->fields; i++, field_ptr++)
1428
if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
1431
(*field_ptr)= 0; // End marker
1433
if (share->found_next_number_field)
1434
outparam->found_next_number_field=
1435
outparam->field[(uint) (share->found_next_number_field - share->field)];
1436
if (share->timestamp_field)
1437
outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
1440
/* Fix key->name and key_part->field */
1441
if (share->key_parts)
1443
KEY *key_info, *key_info_end;
1444
KEY_PART_INFO *key_part;
1446
n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
1447
if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
1449
outparam->key_info= key_info;
1450
key_part= (my_reinterpret_cast(KEY_PART_INFO*) (key_info+share->keys));
1452
memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
1453
memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
1456
for (key_info_end= key_info + share->keys ;
1457
key_info < key_info_end ;
1460
KEY_PART_INFO *key_part_end;
1462
key_info->table= outparam;
1463
key_info->key_part= key_part;
1465
for (key_part_end= key_part+ key_info->key_parts ;
1466
key_part < key_part_end ;
1469
Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
1471
if (field->key_length() != key_part->length &&
1472
!(field->flags & BLOB_FLAG))
1475
We are using only a prefix of the column as a key:
1476
Create a new field for the key part that matches the index
1478
field= key_part->field=field->new_field(&outparam->mem_root,
1480
field->field_length= key_part->length;
1486
/* Allocate bitmaps */
1488
bitmap_size= share->column_bitmap_size;
1489
if (!(bitmaps= (uchar*) alloc_root(&outparam->mem_root, bitmap_size*3)))
1491
bitmap_init(&outparam->def_read_set,
1492
(my_bitmap_map*) bitmaps, share->fields, false);
1493
bitmap_init(&outparam->def_write_set,
1494
(my_bitmap_map*) (bitmaps+bitmap_size), share->fields, false);
1495
bitmap_init(&outparam->tmp_set,
1496
(my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, false);
1497
outparam->default_column_bitmaps();
1499
/* The table struct is now initialized; Open the table */
1501
if (db_stat && open_mode != OTM_ALTER)
1504
if ((ha_err= (outparam->file->
1505
ha_open(outparam, share->normalized_path.str,
1506
(db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
1507
(db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
1508
((db_stat & HA_WAIT_IF_LOCKED) ||
1509
(specialflag & SPECIAL_WAIT_IF_LOCKED)) ?
1510
HA_OPEN_WAIT_IF_LOCKED :
1511
(db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
1512
HA_OPEN_ABORT_IF_LOCKED :
1513
HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
1515
/* Set a flag if the table is crashed and it can be auto. repaired */
1516
share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
1517
outparam->file->auto_repair() &&
1518
!(ha_open_flags & HA_OPEN_FOR_REPAIR));
1522
case HA_ERR_NO_SUCH_TABLE:
1524
The table did not exists in storage engine, use same error message
1525
as if the .frm file didn't exist
1532
Too many files opened, use same error message as if the .frm
1539
outparam->file->print_error(ha_err, MYF(0));
1540
error_reported= true;
1541
if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
1545
goto err; /* purecov: inspected */
1549
#if defined(HAVE_purify)
1550
bzero((char*) bitmaps, bitmap_size*3);
1553
outparam->no_replicate= outparam->file &&
1554
test(outparam->file->ha_table_flags() &
1555
HA_HAS_OWN_BINLOGGING);
1556
thd->status_var.opened_tables++;
1561
if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
1562
open_table_error(share, error, my_errno, 0);
1563
delete outparam->file;
1564
outparam->file= 0; // For easier error checking
1565
outparam->db_stat=0;
1566
free_root(&outparam->mem_root, MYF(0)); // Safe to call on bzero'd root
1567
my_free((char*) outparam->alias, MYF(MY_ALLOW_ZERO_PTR));
1573
Free information allocated by openfrm
1577
table TABLE object to free
1578
free_share Is 1 if we also want to free table_share
1581
int closefrm(register TABLE *table, bool free_share)
1586
error=table->file->close();
1587
my_free((char*) table->alias, MYF(MY_ALLOW_ZERO_PTR));
1591
for (Field **ptr=table->field ; *ptr ; ptr++)
94
cursor= 0; /* For easier errorchecking */
1596
table->file= 0; /* For easier errorchecking */
1599
if (table->s->tmp_table == NO_TMP_TABLE)
1600
release_table_share(table->s, RELEASE_NORMAL);
1602
free_table_share(table->s);
106
mem_root.free_root(MYF(0));
110
void Table::resetTable(Session *session,
112
uint32_t db_stat_arg)
125
db_stat= db_stat_arg;
128
record[0]= (unsigned char *) NULL;
129
record[1]= (unsigned char *) NULL;
131
insert_values.clear();
133
next_number_field= NULL;
134
found_next_number_field= NULL;
135
timestamp_field= NULL;
137
pos_in_table_list= NULL;
147
derived_select_number= 0;
148
current_lock= F_UNLCK;
162
open_placeholder= false;
163
locked_by_name= false;
166
auto_increment_field_not_null= false;
167
alias_name_used= false;
170
quick_condition_rows= 0;
172
timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
177
covering_keys.reset();
182
keys_in_use_for_query.reset();
183
keys_in_use_for_group_by.reset();
184
keys_in_use_for_order_by.reset();
186
memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
187
memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
189
memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
190
memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
192
memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
1604
free_root(&table->mem_root, MYF(0));
197
1609
/* Deallocate temporary blob storage */
199
void free_blobs(register Table *table)
1611
void free_blobs(register TABLE *table)
202
for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
1614
for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
206
((Field_blob*) table->getField(*ptr))->free();
211
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
213
TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
1617
((Field_blob*) table->field[*ptr])->free();
1621
/* Find where a form starts */
1622
/* if formname is NullS then only formnames is read */
1624
ulong get_form_pos(File file, uchar *head, TYPELIB *save_names)
1626
uint a_length,names,length;
1630
names=uint2korr(head+8);
1631
a_length=(names+2)*sizeof(char *); /* Room for two extra */
1636
save_names->type_names=0; /* Clear if error */
1640
length=uint2korr(head+4);
1641
VOID(my_seek(file,64L,MY_SEEK_SET,MYF(0)));
1642
if (!(buf= (uchar*) my_malloc((size_t) length+a_length+names*4,
1644
my_read(file, buf+a_length, (size_t) (length+names*4),
1646
{ /* purecov: inspected */
1647
x_free((uchar*) buf); /* purecov: inspected */
1648
return(0L); /* purecov: inspected */
1650
pos= buf+a_length+length;
1651
ret_value=uint4korr(pos);
1656
my_free((uchar*) buf,MYF(0));
1659
bzero((char*) save_names,sizeof(save_names));
1663
str=(char *) (buf+a_length);
1664
fix_type_pointers((const char ***) &buf,save_names,1,&str);
1671
Read string from a file with malloc
1674
We add an \0 at end of the read string to make reading of C strings easier
1677
int read_string(File file, uchar**to, size_t length)
1681
if (!(*to= (uchar*) my_malloc(length+1,MYF(MY_WME))) ||
1682
my_read(file, *to, length,MYF(MY_NABP)))
1684
x_free(*to); /* purecov: inspected */
1685
*to= 0; /* purecov: inspected */
1686
return(1); /* purecov: inspected */
1688
*((char*) *to+length)= '\0';
1693
/* Add a new form to a form file */
1695
ulong make_new_entry(File file, uchar *fileinfo, TYPELIB *formnames,
1696
const char *newname)
1698
uint i,bufflength,maxlength,n_length,length,names;
1699
ulong endpos,newpos;
1700
uchar buff[IO_SIZE];
1703
length=(uint) strlen(newname)+1;
1704
n_length=uint2korr(fileinfo+4);
1705
maxlength=uint2korr(fileinfo+6);
1706
names=uint2korr(fileinfo+8);
1707
newpos=uint4korr(fileinfo+10);
1709
if (64+length+n_length+(names+1)*4 > maxlength)
1712
int4store(fileinfo+10,newpos);
1713
endpos=(ulong) my_seek(file,0L,MY_SEEK_END,MYF(0));/* Copy from file-end */
1714
bufflength= (uint) (endpos & (IO_SIZE-1)); /* IO_SIZE is a power of 2 */
1716
while (endpos > maxlength)
1718
VOID(my_seek(file,(ulong) (endpos-bufflength),MY_SEEK_SET,MYF(0)));
1719
if (my_read(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
1721
VOID(my_seek(file,(ulong) (endpos-bufflength+IO_SIZE),MY_SEEK_SET,
1723
if ((my_write(file, buff,bufflength,MYF(MY_NABP+MY_WME))))
1725
endpos-=bufflength; bufflength=IO_SIZE;
1727
bzero(buff,IO_SIZE); /* Null new block */
1728
VOID(my_seek(file,(ulong) maxlength,MY_SEEK_SET,MYF(0)));
1729
if (my_write(file,buff,bufflength,MYF(MY_NABP+MY_WME)))
1731
maxlength+=IO_SIZE; /* Fix old ref */
1732
int2store(fileinfo+6,maxlength);
1733
for (i=names, pos= (uchar*) *formnames->type_names+n_length-1; i-- ;
1736
endpos=uint4korr(pos)+IO_SIZE;
1737
int4store(pos,endpos);
1744
VOID(strxmov((char*) buff,"/",newname,"/",NullS));
1747
VOID(strxmov((char*) buff,newname,"/",NullS)); /* purecov: inspected */
1748
VOID(my_seek(file,63L+(ulong) n_length,MY_SEEK_SET,MYF(0)));
1749
if (my_write(file, buff, (size_t) length+1,MYF(MY_NABP+MY_WME)) ||
1750
(names && my_write(file,(uchar*) (*formnames->type_names+n_length-1),
1751
names*4, MYF(MY_NABP+MY_WME))) ||
1752
my_write(file, fileinfo+10, 4,MYF(MY_NABP+MY_WME)))
1753
return(0L); /* purecov: inspected */
1755
int2store(fileinfo+8,names+1);
1756
int2store(fileinfo+4,n_length+length);
1757
(void)ftruncate(file, newpos);/* Append file with '\0' */
1759
} /* make_new_entry */
1762
/* error message when opening a form file */
1764
void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
1767
char buff[FN_REFLEN];
1768
myf errortype= ME_ERROR+ME_WAITTANG;
1773
if (db_errno == ENOENT)
1774
my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
1777
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
1778
my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
1779
errortype, buff, db_errno);
1785
const char *datext= "";
1787
if (share->db_type() != NULL)
1789
if ((file= get_new_handler(share, current_thd->mem_root,
1792
if (!(datext= *file->bas_ext()))
1796
err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
1797
ER_FILE_USED : ER_CANT_OPEN_FILE;
1798
strxmov(buff, share->normalized_path.str, datext, NullS);
1799
my_error(err_no,errortype, buff, db_errno);
1805
const char *csname= get_charset_name((uint) errarg);
1807
if (!csname || csname[0] =='?')
1809
snprintf(tmp, sizeof(tmp), "#%d", errarg);
1812
my_printf_error(ER_UNKNOWN_COLLATION,
1813
"Unknown collation '%s' in table '%-.64s' definition",
1814
MYF(0), csname, share->table_name.str);
1818
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
1819
my_printf_error(ER_NOT_FORM_FILE,
1820
"Table '%-.64s' was created with a different version "
1821
"of MySQL and cannot be read",
1826
default: /* Better wrong error than none */
1828
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
1829
my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
1833
} /* open_table_error */
1837
** fix a str_type to a array type
1838
** typeparts separated with some char. differents types are separated
1843
fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint types,
1846
char *type_name, *ptr;
1852
point_to_type->name=0;
1853
point_to_type->type_names= *array;
1855
if ((chr= *ptr)) /* Test if empty type */
1857
while ((type_name=strchr(ptr+1,chr)) != NullS)
1859
*((*array)++) = ptr+1;
1860
*type_name= '\0'; /* End string */
1863
ptr+=2; /* Skip end mark and last 0 */
1867
point_to_type->count= (uint) (*array - point_to_type->type_names);
1869
*((*array)++)= NullS; /* End of type */
1871
*names=ptr; /* Update end */
1873
} /* fix_type_pointers */
1876
TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
1878
TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
216
result->count= strings.elements;
218
uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
220
if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
1881
result->count=strings.elements;
1883
uint nbytes= (sizeof(char*) + sizeof(uint)) * (result->count + 1);
1884
if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
223
1886
result->type_lengths= (uint*) (result->type_names + result->count + 1);
225
1887
List_iterator<String> it(strings);
227
for (uint32_t i= 0; (tmp= it++); i++)
1889
for (uint i=0; (tmp=it++) ; i++)
229
1891
result->type_names[i]= tmp->ptr();
230
1892
result->type_lengths[i]= tmp->length();
233
result->type_names[result->count]= 0; // End marker
1894
result->type_names[result->count]= 0; // End marker
234
1895
result->type_lengths[result->count]= 0;
1901
Search after a field with given start & length
1902
If an exact field isn't found, return longest field with starts
1906
This is needed because in some .frm fields 'fieldnr' was saved wrong
1913
static uint find_field(Field **fields, uchar *record, uint start, uint length)
1919
for (field= fields, i=1 ; *field ; i++,field++)
1921
if ((*field)->offset(record) == start)
1923
if ((*field)->key_length() == length)
1925
if (!pos || fields[pos-1]->pack_length() <
1926
(*field)->pack_length())
239
1934
/* Check that the integer is in the internal */
241
1936
int set_zone(register int nr, int min_zone, int max_zone)
398
2336
/* Error if empty or too long column name */
399
return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
2337
return last_char_is_space || (uint) name_length > NAME_CHAR_LEN;
2342
Checks whether a table is intact. Should be done *just* after the table has
2345
@param[in] table The table to check
2346
@param[in] table_f_count Expected number of columns in the table
2347
@param[in] table_def Expected structure of the table (column name
2351
@retval TRUE There was an error. An error message is output
2352
to the error log. We do not push an error
2353
message into the error stack because this
2354
function is currently only called at start up,
2355
and such errors never reach the user.
2359
table_check_intact(TABLE *table, const uint table_f_count,
2360
const TABLE_FIELD_W_TYPE *table_def)
2363
my_bool error= false;
2364
my_bool fields_diff_count;
2366
fields_diff_count= (table->s->fields != table_f_count);
2367
if (fields_diff_count)
2370
/* previous MySQL version */
2371
if (MYSQL_VERSION_ID > table->s->mysql_version)
2373
sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
2374
table->alias, table_f_count, table->s->fields,
2375
table->s->mysql_version, MYSQL_VERSION_ID);
2378
else if (MYSQL_VERSION_ID == table->s->mysql_version)
2380
sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), table->alias,
2381
table_f_count, table->s->fields);
2385
Something has definitely changed, but we're running an older
2386
version of MySQL with new system tables.
2387
Let's check column definitions. If a column was added at
2388
the end of the table, then we don't care much since such change
2389
is backward compatible.
2392
char buffer[STRING_BUFFER_USUAL_SIZE];
2393
for (i=0 ; i < table_f_count; i++, table_def++)
2395
String sql_type(buffer, sizeof(buffer), system_charset_info);
2397
if (i < table->s->fields)
2399
Field *field= table->field[i];
2401
if (strncmp(field->field_name, table_def->name.str,
2402
table_def->name.length))
2405
Name changes are not fatal, we use ordinal numbers to access columns.
2406
Still this can be a sign of a tampered table, output an error
2409
sql_print_error("Incorrect definition of table %s.%s: "
2410
"expected column '%s' at position %d, found '%s'.",
2411
table->s->db.str, table->alias, table_def->name.str, i,
2414
field->sql_type(sql_type);
2416
Generally, if column types don't match, then something is
2419
However, we only compare column definitions up to the
2420
length of the original definition, since we consider the
2421
following definitions compatible:
2423
1. DATETIME and DATETIM
2424
2. INT(11) and INT(11
2425
3. SET('one', 'two') and SET('one', 'two', 'more')
2427
For SETs or ENUMs, if the same prefix is there it's OK to
2428
add more elements - they will get higher ordinal numbers and
2429
the new table definition is backward compatible with the
2432
if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
2433
table_def->type.length - 1))
2435
sql_print_error("Incorrect definition of table %s.%s: "
2436
"expected column '%s' at position %d to have type "
2437
"%s, found type %s.", table->s->db.str, table->alias,
2438
table_def->name.str, i, table_def->type.str,
2439
sql_type.c_ptr_safe());
2442
else if (table_def->cset.str && !field->has_charset())
2444
sql_print_error("Incorrect definition of table %s.%s: "
2445
"expected the type of column '%s' at position %d "
2446
"to have character set '%s' but the type has no "
2447
"character set.", table->s->db.str, table->alias,
2448
table_def->name.str, i, table_def->cset.str);
2451
else if (table_def->cset.str &&
2452
strcmp(field->charset()->csname, table_def->cset.str))
2454
sql_print_error("Incorrect definition of table %s.%s: "
2455
"expected the type of column '%s' at position %d "
2456
"to have character set '%s' but found "
2457
"character set '%s'.", table->s->db.str, table->alias,
2458
table_def->name.str, i, table_def->cset.str,
2459
field->charset()->csname);
2465
sql_print_error("Incorrect definition of table %s.%s: "
2466
"expected column '%s' at position %d to have type %s "
2467
" but the column is not found.",
2468
table->s->db.str, table->alias,
2469
table_def->name.str, i, table_def->type.str);
2478
Create Item_field for each column in the table.
2481
st_table::fill_item_list()
2482
item_list a pointer to an empty list used to store items
2485
Create Item_field object for each column in the table and
2486
initialize it with the corresponding Field. New items are
2487
created in the current THD memory root.
2494
bool st_table::fill_item_list(List<Item> *item_list) const
2497
All Item_field's created using a direct pointer to a field
2498
are fixed in Item_field constructor.
2500
for (Field **ptr= field; *ptr; ptr++)
2502
Item_field *item= new Item_field(*ptr);
2503
if (!item || item_list->push_back(item))
2510
Reset an existing list of Item_field items to point to the
2511
Fields of this table.
2514
st_table::fill_item_list()
2515
item_list a non-empty list with Item_fields
2518
This is a counterpart of fill_item_list used to redirect
2519
Item_fields to the fields of a newly created table.
2520
The caller must ensure that number of items in the item_list
2521
is the same as the number of columns in the table.
2524
void st_table::reset_item_list(List<Item> *item_list) const
2526
List_iterator_fast<Item> it(*item_list);
2527
for (Field **ptr= field; *ptr; ptr++)
2529
Item_field *item_field= (Item_field*) it++;
2530
assert(item_field != 0);
2531
item_field->reset_field(*ptr);
2537
Merge ON expressions for a view
2542
table table for the VIEW
2543
is_cascaded TRUE <=> merge ON expressions from underlying views
2546
This function returns the result of ANDing the ON expressions
2547
of the given view and all underlying views. The ON expressions
2548
of the underlying views are added only if is_cascaded is TRUE.
2551
Pointer to the built expression if there is any.
2552
Otherwise and in the case of a failure NULL is returned.
2556
merge_on_conds(THD *thd, TABLE_LIST *table, bool is_cascaded)
2561
cond= table->on_expr->copy_andor_structure(thd);
2562
if (!table->nested_join)
2564
List_iterator<TABLE_LIST> li(table->nested_join->join_list);
2565
while (TABLE_LIST *tbl= li++)
2567
cond= and_conds(cond, merge_on_conds(thd, tbl, is_cascaded));
2574
Find underlying base tables (TABLE_LIST) which represent given
2575
table_to_find (TABLE)
2578
TABLE_LIST::find_underlying_table()
2579
table_to_find table to find
2582
0 table is not found
2583
found table reference
2586
TABLE_LIST *TABLE_LIST::find_underlying_table(TABLE *table_to_find)
2588
/* is this real table and table which we are looking for? */
2589
if (table == table_to_find && merge_underlying_list == 0)
2592
for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
2595
if ((result= tbl->find_underlying_table(table_to_find)))
2602
cleunup items belonged to view fields translation table
2605
TABLE_LIST::cleanup_items()
2608
void TABLE_LIST::cleanup_items()
2610
if (!field_translation)
2613
for (Field_translator *transl= field_translation;
2614
transl < field_translation_end;
2616
transl->item->walk(&Item::cleanup_processor, 0, 0);
2621
Set insert_values buffer
2625
mem_root memory pool for allocating
2629
TRUE - out of memory
2632
bool TABLE_LIST::set_insert_values(MEM_ROOT *mem_root)
2636
if (!table->insert_values &&
2637
!(table->insert_values= (uchar *)alloc_root(mem_root,
2638
table->s->rec_buff_length)))
2647
Test if this is a leaf with respect to name resolution.
2650
TABLE_LIST::is_leaf_for_name_resolution()
2653
A table reference is a leaf with respect to name resolution if
2654
it is either a leaf node in a nested join tree (table, view,
2655
schema table, subquery), or an inner node that represents a
2656
NATURAL/USING join, or a nested join with materialized join
2660
TRUE if a leaf, false otherwise.
2662
bool TABLE_LIST::is_leaf_for_name_resolution()
2664
return (is_natural_join || is_join_columns_complete || !nested_join);
2669
Retrieve the first (left-most) leaf in a nested join tree with
2670
respect to name resolution.
2673
TABLE_LIST::first_leaf_for_name_resolution()
2676
Given that 'this' is a nested table reference, recursively walk
2677
down the left-most children of 'this' until we reach a leaf
2678
table reference with respect to name resolution.
2681
The left-most child of a nested table reference is the last element
2682
in the list of children because the children are inserted in
2686
If 'this' is a nested table reference - the left-most child of
2687
the tree rooted in 'this',
2691
TABLE_LIST *TABLE_LIST::first_leaf_for_name_resolution()
2693
TABLE_LIST *cur_table_ref;
2694
NESTED_JOIN *cur_nested_join;
2696
if (is_leaf_for_name_resolution())
2698
assert(nested_join);
2700
for (cur_nested_join= nested_join;
2702
cur_nested_join= cur_table_ref->nested_join)
2704
List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
2705
cur_table_ref= it++;
2707
If the current nested join is a RIGHT JOIN, the operands in
2708
'join_list' are in reverse order, thus the first operand is
2709
already at the front of the list. Otherwise the first operand
2710
is in the end of the list of join operands.
2712
if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
2715
while ((next= it++))
2716
cur_table_ref= next;
2718
if (cur_table_ref->is_leaf_for_name_resolution())
2721
return cur_table_ref;
2726
Retrieve the last (right-most) leaf in a nested join tree with
2727
respect to name resolution.
2730
TABLE_LIST::last_leaf_for_name_resolution()
2733
Given that 'this' is a nested table reference, recursively walk
2734
down the right-most children of 'this' until we reach a leaf
2735
table reference with respect to name resolution.
2738
The right-most child of a nested table reference is the first
2739
element in the list of children because the children are inserted
2743
- If 'this' is a nested table reference - the right-most child of
2744
the tree rooted in 'this',
2748
TABLE_LIST *TABLE_LIST::last_leaf_for_name_resolution()
2750
TABLE_LIST *cur_table_ref= this;
2751
NESTED_JOIN *cur_nested_join;
2753
if (is_leaf_for_name_resolution())
2755
assert(nested_join);
2757
for (cur_nested_join= nested_join;
2759
cur_nested_join= cur_table_ref->nested_join)
2761
cur_table_ref= cur_nested_join->join_list.head();
2763
If the current nested is a RIGHT JOIN, the operands in
2764
'join_list' are in reverse order, thus the last operand is in the
2767
if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
2769
List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
2771
cur_table_ref= it++;
2772
while ((next= it++))
2773
cur_table_ref= next;
2775
if (cur_table_ref->is_leaf_for_name_resolution())
2778
return cur_table_ref;
2782
Natural_join_column::Natural_join_column(Field_translator *field_param,
2785
assert(tab->field_translation);
2786
view_field= field_param;
2793
Natural_join_column::Natural_join_column(Field *field_param,
2796
assert(tab->table == field_param->table);
2797
table_field= field_param;
2804
const char *Natural_join_column::name()
2808
assert(table_field == NULL);
2809
return view_field->name;
2812
return table_field->field_name;
2816
Item *Natural_join_column::create_item(THD *thd)
2820
assert(table_field == NULL);
2821
return create_view_field(thd, table_ref, &view_field->item,
2824
return new Item_field(thd, &thd->lex->current_select->context, table_field);
2828
Field *Natural_join_column::field()
2832
assert(table_field == NULL);
2839
const char *Natural_join_column::table_name()
2842
return table_ref->alias;
2846
const char *Natural_join_column::db_name()
2849
Test that TABLE_LIST::db is the same as st_table_share::db to
2850
ensure consistency. An exception are I_S schema tables, which
2851
are inconsistent in this respect.
2853
assert(!strcmp(table_ref->db,
2854
table_ref->table->s->db.str) ||
2855
(table_ref->schema_table &&
2856
table_ref->table->s->db.str[0] == 0));
2857
return table_ref->db;
2861
void Field_iterator_view::set(TABLE_LIST *table)
2863
assert(table->field_translation);
2865
ptr= table->field_translation;
2866
array_end= table->field_translation_end;
2870
const char *Field_iterator_table::name()
2872
return (*ptr)->field_name;
2876
Item *Field_iterator_table::create_item(THD *thd)
2878
SELECT_LEX *select= thd->lex->current_select;
2880
Item_field *item= new Item_field(thd, &select->context, *ptr);
2881
if (item && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
2882
!thd->lex->in_sum_func && select->cur_pos_in_select_list != UNDEF_POS)
2884
select->non_agg_fields.push_back(item);
2885
item->marker= select->cur_pos_in_select_list;
2891
const char *Field_iterator_view::name()
2897
Item *Field_iterator_view::create_item(THD *thd)
2899
return create_view_field(thd, view, &ptr->item, ptr->name);
2902
Item *create_view_field(THD *thd __attribute__((__unused__)),
2903
TABLE_LIST *view, Item **field_ref,
2904
const char *name __attribute__((__unused__)))
2906
if (view->schema_table_reformed)
2908
Item *field= *field_ref;
2911
Translation table items are always Item_fields and already fixed
2912
('mysql_schema_table' function). So we can return directly the
2913
field. This case happens only for 'show & where' commands.
2915
assert(field && field->fixed);
2923
void Field_iterator_natural_join::set(TABLE_LIST *table_ref)
2925
assert(table_ref->join_columns);
2926
column_ref_it.init(*(table_ref->join_columns));
2927
cur_column_ref= column_ref_it++;
2931
void Field_iterator_natural_join::next()
2933
cur_column_ref= column_ref_it++;
2934
assert(!cur_column_ref || ! cur_column_ref->table_field ||
2935
cur_column_ref->table_ref->table ==
2936
cur_column_ref->table_field->table);
2940
void Field_iterator_table_ref::set_field_iterator()
2943
If the table reference we are iterating over is a natural join, or it is
2944
an operand of a natural join, and TABLE_LIST::join_columns contains all
2945
the columns of the join operand, then we pick the columns from
2946
TABLE_LIST::join_columns, instead of the orginial container of the
2947
columns of the join operator.
2949
if (table_ref->is_join_columns_complete)
2951
/* Necesary, but insufficient conditions. */
2952
assert(table_ref->is_natural_join ||
2953
table_ref->nested_join ||
2954
((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))) ||
2955
/* This is stored table or a tmptable view. */
2956
(!table_ref->field_translation && table_ref->join_columns->elements == table_ref->table->s->fields)));
2957
field_it= &natural_join_it;
2959
/* This is a base table or stored view. */
2962
assert(table_ref->table);
2963
field_it= &table_field_it;
2965
field_it->set(table_ref);
2970
void Field_iterator_table_ref::set(TABLE_LIST *table)
2973
first_leaf= table->first_leaf_for_name_resolution();
2974
last_leaf= table->last_leaf_for_name_resolution();
2975
assert(first_leaf && last_leaf);
2976
table_ref= first_leaf;
2977
set_field_iterator();
2981
void Field_iterator_table_ref::next()
2983
/* Move to the next field in the current table reference. */
2986
If all fields of the current table reference are exhausted, move to
2987
the next leaf table reference.
2989
if (field_it->end_of_fields() && table_ref != last_leaf)
2991
table_ref= table_ref->next_name_resolution_table;
2993
set_field_iterator();
2998
const char *Field_iterator_table_ref::table_name()
3000
if (table_ref->is_natural_join)
3001
return natural_join_it.column_ref()->table_name();
3003
assert(!strcmp(table_ref->table_name,
3004
table_ref->table->s->table_name.str));
3005
return table_ref->table_name;
3009
const char *Field_iterator_table_ref::db_name()
3011
if (table_ref->is_natural_join)
3012
return natural_join_it.column_ref()->db_name();
3015
Test that TABLE_LIST::db is the same as st_table_share::db to
3016
ensure consistency. An exception are I_S schema tables, which
3017
are inconsistent in this respect.
3019
assert(!strcmp(table_ref->db, table_ref->table->s->db.str) ||
3020
(table_ref->schema_table &&
3021
table_ref->table->s->db.str[0] == 0));
3023
return table_ref->db;
3028
Create new or return existing column reference to a column of a
3032
Field_iterator_table_ref::get_or_create_column_ref()
3033
parent_table_ref the parent table reference over which the
3034
iterator is iterating
3037
Create a new natural join column for the current field of the
3038
iterator if no such column was created, or return an already
3039
created natural join column. The former happens for base tables or
3040
views, and the latter for natural/using joins. If a new field is
3041
created, then the field is added to 'parent_table_ref' if it is
3042
given, or to the original table referene of the field if
3043
parent_table_ref == NULL.
3046
This method is designed so that when a Field_iterator_table_ref
3047
walks through the fields of a table reference, all its fields
3048
are created and stored as follows:
3049
- If the table reference being iterated is a stored table, view or
3050
natural/using join, store all natural join columns in a list
3051
attached to that table reference.
3052
- If the table reference being iterated is a nested join that is
3053
not natural/using join, then do not materialize its result
3054
fields. This is OK because for such table references
3055
Field_iterator_table_ref iterates over the fields of the nested
3056
table references (recursively). In this way we avoid the storage
3057
of unnecessay copies of result columns of nested joins.
3060
# Pointer to a column of a natural join (or its operand)
3061
NULL No memory to allocate the column
3064
Natural_join_column *
3065
Field_iterator_table_ref::get_or_create_column_ref(TABLE_LIST *parent_table_ref)
3067
Natural_join_column *nj_col;
3068
bool is_created= true;
3070
TABLE_LIST *add_table_ref= parent_table_ref ?
3071
parent_table_ref : table_ref;
3073
if (field_it == &table_field_it)
3075
/* The field belongs to a stored table. */
3076
Field *tmp_field= table_field_it.field();
3077
nj_col= new Natural_join_column(tmp_field, table_ref);
3078
field_count= table_ref->table->s->fields;
3080
else if (field_it == &view_field_it)
3082
/* The field belongs to a merge view or information schema table. */
3083
Field_translator *translated_field= view_field_it.field_translator();
3084
nj_col= new Natural_join_column(translated_field, table_ref);
3085
field_count= table_ref->field_translation_end -
3086
table_ref->field_translation;
3091
The field belongs to a NATURAL join, therefore the column reference was
3092
already created via one of the two constructor calls above. In this case
3093
we just return the already created column reference.
3095
assert(table_ref->is_join_columns_complete);
3097
nj_col= natural_join_it.column_ref();
3100
assert(!nj_col->table_field ||
3101
nj_col->table_ref->table == nj_col->table_field->table);
3104
If the natural join column was just created add it to the list of
3105
natural join columns of either 'parent_table_ref' or to the table
3106
reference that directly contains the original field.
3110
/* Make sure not all columns were materialized. */
3111
assert(!add_table_ref->is_join_columns_complete);
3112
if (!add_table_ref->join_columns)
3114
/* Create a list of natural join columns on demand. */
3115
if (!(add_table_ref->join_columns= new List<Natural_join_column>))
3117
add_table_ref->is_join_columns_complete= false;
3119
add_table_ref->join_columns->push_back(nj_col);
3121
If new fields are added to their original table reference, mark if
3122
all fields were added. We do it here as the caller has no easy way
3123
of knowing when to do it.
3124
If the fields are being added to parent_table_ref, then the caller
3125
must take care to mark when all fields are created/added.
3127
if (!parent_table_ref &&
3128
add_table_ref->join_columns->elements == field_count)
3129
add_table_ref->is_join_columns_complete= true;
3137
Return an existing reference to a column of a natural/using join.
3140
Field_iterator_table_ref::get_natural_column_ref()
3143
The method should be called in contexts where it is expected that
3144
all natural join columns are already created, and that the column
3145
being retrieved is a Natural_join_column.
3148
# Pointer to a column of a natural join (or its operand)
3149
NULL No memory to allocate the column
3152
Natural_join_column *
3153
Field_iterator_table_ref::get_natural_column_ref()
3155
Natural_join_column *nj_col;
3157
assert(field_it == &natural_join_it);
3159
The field belongs to a NATURAL join, therefore the column reference was
3160
already created via one of the two constructor calls above. In this case
3161
we just return the already created column reference.
3163
nj_col= natural_join_it.column_ref();
3165
(!nj_col->table_field ||
3166
nj_col->table_ref->table == nj_col->table_field->table));
403
3170
/*****************************************************************************
404
3171
Functions to handle column usage bitmaps (read_set, write_set etc...)
589
3352
if neeed, either the primary key column or all columns to be read.
590
3353
(see mark_columns_needed_for_delete() for details)
592
If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
3355
If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
593
3356
mark all USED key columns as 'to-be-read'. This allows the engine to
594
3357
loop over the given record to find all changed keys and doesn't have to
595
3358
retrieve the row again.
598
void Table::mark_columns_needed_for_update()
3361
void st_table::mark_columns_needed_for_update()
601
If the Cursor has no cursor capabilites, or we have row-based
602
logging active for the current statement, we have to read either
603
the primary key, the hidden primary key or all columns to be
606
if (not getShare()->hasPrimaryKey())
608
/* fallback to use all columns in the table to identify row */
613
mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
615
if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
3363
if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
617
3365
/* Mark all used key columns for read */
618
3366
Field **reg_field;
619
3367
for (reg_field= field ; *reg_field ; reg_field++)
621
3369
/* Merge keys is all keys that had a column refered to in the query */
622
if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
623
setReadSet((*reg_field)->position());
3370
if (merge_keys.is_overlapping((*reg_field)->part_of_key))
3371
bitmap_set_bit(read_set, (*reg_field)->field_index);
3373
file->column_bitmaps_signal();
3375
if ((file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) ||
3376
(mysql_bin_log.is_open() && in_use && in_use->current_stmt_binlog_row_based))
3379
If the handler has no cursor capabilites, or we have row-based
3380
logging active for the current statement, we have to read either
3381
the primary key, the hidden primary key or all columns to be
3382
able to do an update
3384
if (s->primary_key == MAX_KEY)
3385
file->use_hidden_primary_key();
3388
mark_columns_used_by_index_no_reset(s->primary_key, read_set);
3389
file->column_bitmaps_signal();
631
Mark columns the Cursor needs for doing an insert
3397
Mark columns the handler needs for doing an insert
633
3399
For now, this is used to mark fields used by the trigger
637
void Table::mark_columns_needed_for_insert()
3403
void st_table::mark_columns_needed_for_insert()
639
3405
if (found_next_number_field)
640
3406
mark_auto_increment_column();
645
size_t Table::max_row_length(const unsigned char *data)
647
size_t length= getRecordLength() + 2 * sizeFields();
648
uint32_t *const beg= getBlobField();
649
uint32_t *const end= beg + sizeBlobFields();
651
for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
653
Field_blob* const blob= (Field_blob*) field[*ptr];
654
length+= blob->get_length((const unsigned char*)
655
(data + blob->offset(getInsertRecord()))) +
3410
Cleanup this table for re-execution.
3413
TABLE_LIST::reinit_before_use()
3416
void TABLE_LIST::reinit_before_use(THD *thd)
3419
Reset old pointers to TABLEs: they are not valid since the tables
3420
were closed in the end of previous prepare or execute call.
3423
/* Reset is_schema_table_processed value(needed for I_S tables */
3424
schema_table_state= NOT_PROCESSED;
3426
TABLE_LIST *embedded; /* The table at the current level of nesting. */
3427
TABLE_LIST *parent_embedding= this; /* The parent nested table reference. */
3430
embedded= parent_embedding;
3431
if (embedded->prep_on_expr)
3432
embedded->on_expr= embedded->prep_on_expr->copy_andor_structure(thd);
3433
parent_embedding= embedded->embedding;
3435
while (parent_embedding &&
3436
parent_embedding->nested_join->join_list.head() == embedded);
3440
Return subselect that contains the FROM list this table is taken from
3443
TABLE_LIST::containing_subselect()
3446
Subselect item for the subquery that contains the FROM list
3447
this table is taken from if there is any
3452
Item_subselect *TABLE_LIST::containing_subselect()
3454
return (select_lex ? select_lex->master_unit()->item : 0);
3458
Compiles the tagged hints list and fills up the bitmasks.
3461
process_index_hints()
3462
table the TABLE to operate on.
3465
The parser collects the index hints for each table in a "tagged list"
3466
(TABLE_LIST::index_hints). Using the information in this tagged list
3467
this function sets the members st_table::keys_in_use_for_query,
3468
st_table::keys_in_use_for_group_by, st_table::keys_in_use_for_order_by,
3469
st_table::force_index and st_table::covering_keys.
3471
Current implementation of the runtime does not allow mixing FORCE INDEX
3472
and USE INDEX, so this is checked here. Then the FORCE INDEX list
3473
(if non-empty) is appended to the USE INDEX list and a flag is set.
3475
Multiple hints of the same kind are processed so that each clause
3476
is applied to what is computed in the previous clause.
3478
USE INDEX (i1) USE INDEX (i2)
3481
and means "consider only i1 and i2".
3484
USE INDEX () USE INDEX (i1)
3487
and means "consider only the index i1"
3489
It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is
3492
Different kind of hints (USE/FORCE/IGNORE) are processed in the following
3494
1. All indexes in USE (or FORCE) INDEX are added to the mask.
3497
e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all
3498
as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
3500
As an optimization if there is a covering index, and we have
3501
IGNORE INDEX FOR GROUP/ORDER, and this index is used for the JOIN part,
3502
then we have to ignore the IGNORE INDEX FROM GROUP/ORDER.
3505
false no errors found
3506
TRUE found and reported an error.
3508
bool TABLE_LIST::process_index_hints(TABLE *tbl)
3510
/* initialize the result variables */
3511
tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by=
3512
tbl->keys_in_use_for_order_by= tbl->s->keys_in_use;
3514
/* index hint list processing */
3517
key_map index_join[INDEX_HINT_FORCE + 1];
3518
key_map index_order[INDEX_HINT_FORCE + 1];
3519
key_map index_group[INDEX_HINT_FORCE + 1];
3522
bool have_empty_use_join= false, have_empty_use_order= false,
3523
have_empty_use_group= false;
3524
List_iterator <Index_hint> iter(*index_hints);
3526
/* initialize temporary variables used to collect hints of each kind */
3527
for (type= INDEX_HINT_IGNORE; type <= INDEX_HINT_FORCE; type++)
3529
index_join[type].clear_all();
3530
index_order[type].clear_all();
3531
index_group[type].clear_all();
3534
/* iterate over the hints list */
3535
while ((hint= iter++))
3539
/* process empty USE INDEX () */
3540
if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
3542
if (hint->clause & INDEX_HINT_MASK_JOIN)
3544
index_join[hint->type].clear_all();
3545
have_empty_use_join= true;
3547
if (hint->clause & INDEX_HINT_MASK_ORDER)
3549
index_order[hint->type].clear_all();
3550
have_empty_use_order= true;
3552
if (hint->clause & INDEX_HINT_MASK_GROUP)
3554
index_group[hint->type].clear_all();
3555
have_empty_use_group= true;
3561
Check if an index with the given name exists and get his offset in
3562
the keys bitmask for the table
3564
if (tbl->s->keynames.type_names == 0 ||
3565
(pos= find_type(&tbl->s->keynames, hint->key_name.str,
3566
hint->key_name.length, 1)) <= 0)
3568
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), hint->key_name.str, alias);
3574
/* add to the appropriate clause mask */
3575
if (hint->clause & INDEX_HINT_MASK_JOIN)
3576
index_join[hint->type].set_bit (pos);
3577
if (hint->clause & INDEX_HINT_MASK_ORDER)
3578
index_order[hint->type].set_bit (pos);
3579
if (hint->clause & INDEX_HINT_MASK_GROUP)
3580
index_group[hint->type].set_bit (pos);
3583
/* cannot mix USE INDEX and FORCE INDEX */
3584
if ((!index_join[INDEX_HINT_FORCE].is_clear_all() ||
3585
!index_order[INDEX_HINT_FORCE].is_clear_all() ||
3586
!index_group[INDEX_HINT_FORCE].is_clear_all()) &&
3587
(!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join ||
3588
!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order ||
3589
!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group))
3591
my_error(ER_WRONG_USAGE, MYF(0), index_hint_type_name[INDEX_HINT_USE],
3592
index_hint_type_name[INDEX_HINT_FORCE]);
3596
/* process FORCE INDEX as USE INDEX with a flag */
3597
if (!index_join[INDEX_HINT_FORCE].is_clear_all() ||
3598
!index_order[INDEX_HINT_FORCE].is_clear_all() ||
3599
!index_group[INDEX_HINT_FORCE].is_clear_all())
3601
tbl->force_index= true;
3602
index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
3603
index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
3604
index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
3607
/* apply USE INDEX */
3608
if (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join)
3609
tbl->keys_in_use_for_query.intersect(index_join[INDEX_HINT_USE]);
3610
if (!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order)
3611
tbl->keys_in_use_for_order_by.intersect (index_order[INDEX_HINT_USE]);
3612
if (!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group)
3613
tbl->keys_in_use_for_group_by.intersect (index_group[INDEX_HINT_USE]);
3615
/* apply IGNORE INDEX */
3616
tbl->keys_in_use_for_query.subtract (index_join[INDEX_HINT_IGNORE]);
3617
tbl->keys_in_use_for_order_by.subtract (index_order[INDEX_HINT_IGNORE]);
3618
tbl->keys_in_use_for_group_by.subtract (index_group[INDEX_HINT_IGNORE]);
3621
/* make sure covering_keys don't include indexes disabled with a hint */
3622
tbl->covering_keys.intersect(tbl->keys_in_use_for_query);
3627
size_t max_row_length(TABLE *table, const uchar *data)
3629
TABLE_SHARE *table_s= table->s;
3630
size_t length= table_s->reclength + 2 * table_s->fields;
3631
uint *const beg= table_s->blob_field;
3632
uint *const end= beg + table_s->blob_fields;
3634
for (uint *ptr= beg ; ptr != end ; ++ptr)
3636
Field_blob* const blob= (Field_blob*) table->field[*ptr];
3637
length+= blob->get_length((const uchar*)
3638
(data + blob->offset(table->record[0]))) +
656
3639
HA_KEY_BLOB_LENGTH;
661
void Table::setVariableWidth(void)
664
if (in_use && in_use->lex->sql_command == SQLCOM_CREATE_TABLE)
666
getMutableShare()->setVariableWidth();
670
assert(0); // Programming error, you can't set this on a plain old Table.
673
/****************************************************************************
674
Functions for creating temporary tables.
675
****************************************************************************/
677
Create field for temporary table from given field.
679
@param session Thread Cursor
680
@param org_field field from which new field will be created
681
@param name New field name
682
@param table Temporary table
683
@param item !=NULL if item->result_field should point to new field.
684
This is relevant for how fill_record() is going to work:
685
If item != NULL then fill_record() will update
686
the record in the original table.
687
If item == NULL then fill_record() will update
689
@param convert_blob_length If >0 create a varstring(convert_blob_length)
690
field instead of blob.
698
Field *create_tmp_field_from_field(Session *session, Field *org_field,
699
const char *name, Table *table,
700
Item_field *item, uint32_t convert_blob_length)
705
Make sure that the blob fits into a Field_varstring which has
708
if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
709
(org_field->flags & BLOB_FLAG))
711
table->setVariableWidth();
712
new_field= new Field_varstring(convert_blob_length,
713
org_field->maybe_null(),
714
org_field->field_name,
715
org_field->charset());
719
new_field= org_field->new_field(session->mem_root, table,
720
table == org_field->getTable());
724
new_field->init(table);
725
new_field->orig_table= org_field->orig_table;
727
item->result_field= new_field;
729
new_field->field_name= name;
730
new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
731
if (org_field->maybe_null() || (item && item->maybe_null))
732
new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join
733
if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
734
table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
735
else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
736
((Field_double *) new_field)->not_fixed= true;
743
Create a temp table according to a field list.
745
Given field pointers are changed to point at tmp_table for
746
send_fields. The table object is self contained: it's
747
allocated in its own memory root, as well as Field objects
748
created for table columns.
749
This function will replace Item_sum items in 'fields' list with
750
corresponding Item_field items, pointing at the fields in the
751
temporary table, unless this was prohibited by true
752
value of argument save_sum_fields. The Item_field objects
753
are created in Session memory root.
755
@param session thread handle
756
@param param a description used as input to create the table
757
@param fields list of items that will be used to define
758
column types of the table (also see NOTES)
759
@param group TODO document
760
@param distinct should table rows be distinct
761
@param save_sum_fields see NOTES
762
@param select_options
764
@param table_alias possible name of the temporary table that can
765
be used for name resolving; can be "".
768
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
769
#define AVG_STRING_LENGTH_TO_PACK_ROWS 64
770
#define RATIO_TO_PACK_ROWS 2
773
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
774
Order *group, bool distinct, bool save_sum_fields,
775
uint64_t select_options, ha_rows rows_limit,
776
const char *table_alias)
778
memory::Root *mem_root_save;
779
uint i,field_count,null_count,null_pack_length;
780
uint32_t copy_func_count= param->func_count;
781
uint32_t hidden_null_count, hidden_null_pack_length, hidden_field_count;
782
uint32_t blob_count,group_null_items, string_count;
784
ulong reclength, string_total_length;
785
bool using_unique_constraint= false;
786
bool use_packed_rows= true;
787
bool not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
788
unsigned char *pos, *group_buff;
789
unsigned char *null_flags;
790
Field **reg_field, **from_field, **default_field;
793
KeyPartInfo *key_part_info;
795
MI_COLUMNDEF *recinfo;
796
uint32_t total_uneven_bit_length= 0;
797
bool force_copy_fields= param->force_copy_fields;
798
uint64_t max_rows= 0;
800
session->status_var.created_tmp_tables++;
804
if (! param->quick_group)
806
group= 0; // Can't use group key
808
else for (Order *tmp=group ; tmp ; tmp=tmp->next)
811
marker == 4 means two things:
812
- store NULLs in the key, and
813
- convert BIT fields to 64-bit long, needed because MEMORY tables
814
can't index BIT fields.
816
(*tmp->item)->marker= 4;
817
if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
818
using_unique_constraint= true;
820
if (param->group_length >= MAX_BLOB_WIDTH)
821
using_unique_constraint= true;
823
distinct= 0; // Can't use distinct
826
field_count=param->field_count+param->func_count+param->sum_func_count;
827
hidden_field_count=param->hidden_field_count;
830
When loose index scan is employed as access method, it already
831
computes all groups and the result of all aggregate functions. We
832
make space for the items of the aggregate function in the list of
833
functions Tmp_Table_Param::items_to_copy, so that the values of
834
these items are stored in the temporary table.
836
if (param->precomputed_group_by)
838
copy_func_count+= param->sum_func_count;
841
table::Instance *table;
842
table= session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
844
if (not table->getMemRoot()->multi_alloc_root(0,
845
&default_field, sizeof(Field*) * (field_count),
846
&from_field, sizeof(Field*)*field_count,
847
©_func, sizeof(*copy_func)*(copy_func_count+1),
848
¶m->keyinfo, sizeof(*param->keyinfo),
849
&key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
850
¶m->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
851
&group_buff, (group && ! using_unique_constraint ?
852
param->group_length : 0),
857
/* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
858
if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
862
param->items_to_copy= copy_func;
863
/* make table according to fields */
865
memset(default_field, 0, sizeof(Field*) * (field_count));
866
memset(from_field, 0, sizeof(Field*)*field_count);
868
mem_root_save= session->mem_root;
869
session->mem_root= table->getMemRoot();
871
table->getMutableShare()->setFields(field_count+1);
872
table->setFields(table->getMutableShare()->getFields(true));
873
reg_field= table->getMutableShare()->getFields(true);
874
table->setAlias(table_alias);
875
table->reginfo.lock_type=TL_WRITE; /* Will be updated */
876
table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
878
table->copy_blobs= 1;
880
table->in_use= session;
881
table->quick_keys.reset();
882
table->covering_keys.reset();
883
table->keys_in_use_for_query.reset();
885
table->getMutableShare()->blob_field.resize(field_count+1);
886
uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
887
table->getMutableShare()->blob_ptr_size= portable_sizeof_char_ptr;
888
table->getMutableShare()->db_low_byte_first=1; // True for HEAP and MyISAM
889
table->getMutableShare()->table_charset= param->table_charset;
890
table->getMutableShare()->keys_for_keyread.reset();
891
table->getMutableShare()->keys_in_use.reset();
893
/* Calculate which type of fields we will store in the temporary table */
895
reclength= string_total_length= 0;
896
blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
897
param->using_indirect_summary_function= 0;
899
List_iterator_fast<Item> li(fields);
901
Field **tmp_from_field=from_field;
904
Item::Type type=item->type();
907
if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
909
if (item->used_tables() & OUTER_REF_TABLE_BIT)
910
item->update_used_tables();
911
if (type == Item::SUBSELECT_ITEM ||
912
(item->used_tables() & ~OUTER_REF_TABLE_BIT))
915
Mark that the we have ignored an item that refers to a summary
916
function. We need to know this if someone is going to use
917
DISTINCT on the result.
919
param->using_indirect_summary_function=1;
923
if (item->const_item() && (int) hidden_field_count <= 0)
924
continue; // We don't have to store this
926
if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
927
{ /* Can't calc group yet */
928
((Item_sum*) item)->result_field= 0;
929
for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
931
Item **argp= ((Item_sum*) item)->args + i;
933
if (!arg->const_item())
936
create_tmp_field(session, table, arg, arg->type(), ©_func,
937
tmp_from_field, &default_field[fieldnr],
938
group != 0,not_all_columns,
940
param->convert_blob_length);
942
goto err; // Should be OOM
944
reclength+=new_field->pack_length();
945
if (new_field->flags & BLOB_FLAG)
947
*blob_field++= fieldnr;
950
*(reg_field++)= new_field;
951
if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
954
string_total_length+= new_field->pack_length();
956
session->mem_root= mem_root_save;
957
session->change_item_tree(argp, new Item_field(new_field));
958
session->mem_root= table->getMemRoot();
959
if (!(new_field->flags & NOT_NULL_FLAG))
963
new_field->maybe_null() is still false, it will be
964
changed below. But we have to setup Item_field correctly
966
(*argp)->maybe_null=1;
968
new_field->setPosition(fieldnr++);
975
The last parameter to create_tmp_field() is a bit tricky:
977
We need to set it to 0 in union, to get fill_record() to modify the
979
We need to set it to 1 on multi-table-update and in select to
980
write rows to the temporary table.
981
We here distinguish between UNION and multi-table-updates by the fact
982
that in the later case group is set to the row pointer.
985
create_tmp_field(session, table, item, type, ©_func,
986
tmp_from_field, &default_field[fieldnr],
988
!force_copy_fields &&
989
(not_all_columns || group != 0),
991
param->convert_blob_length);
995
if (session->is_fatal_error)
997
continue; // Some kindf of const item
999
if (type == Item::SUM_FUNC_ITEM)
1000
((Item_sum *) item)->result_field= new_field;
1002
reclength+=new_field->pack_length();
1003
if (!(new_field->flags & NOT_NULL_FLAG))
1005
if (new_field->flags & BLOB_FLAG)
1007
*blob_field++= fieldnr;
1010
if (item->marker == 4 && item->maybe_null)
1013
new_field->flags|= GROUP_FLAG;
1015
new_field->setPosition(fieldnr++);
1016
*(reg_field++)= new_field;
1018
if (!--hidden_field_count)
1021
This was the last hidden field; Remember how many hidden fields could
1024
hidden_null_count=null_count;
1026
We need to update hidden_field_count as we may have stored group
1027
functions with constant arguments
1029
param->hidden_field_count= fieldnr;
1033
assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
1034
assert(field_count >= (uint32_t) (reg_field - table->getFields()));
1035
field_count= fieldnr;
1037
*blob_field= 0; // End marker
1038
table->getMutableShare()->fields= field_count;
1040
/* If result table is small; use a heap */
1041
/* future: storage engine selection can be made dynamic? */
1042
if (blob_count || using_unique_constraint ||
1043
(session->lex->select_lex.options & SELECT_BIG_RESULT) ||
1044
(session->lex->current_select->olap == ROLLUP_TYPE) ||
1045
(select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
1047
table->getMutableShare()->storage_engine= myisam_engine;
1048
table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
1050
(param->group_parts > table->cursor->getEngine()->max_key_parts() ||
1051
param->group_length > table->cursor->getEngine()->max_key_length()))
1053
using_unique_constraint= true;
1058
table->getMutableShare()->storage_engine= heap_engine;
1059
table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
1061
if (! table->cursor)
1065
if (! using_unique_constraint)
1066
reclength+= group_null_items; // null flag is stored separately
1068
table->getMutableShare()->blob_fields= blob_count;
1069
if (blob_count == 0)
1071
/* We need to ensure that first byte is not 0 for the delete link */
1072
if (param->hidden_field_count)
1073
hidden_null_count++;
1077
hidden_null_pack_length=(hidden_null_count+7)/8;
1078
null_pack_length= (hidden_null_pack_length +
1079
(null_count + total_uneven_bit_length + 7) / 8);
1080
reclength+=null_pack_length;
1082
reclength=1; // Dummy select
1083
/* Use packed rows if there is blobs or a lot of space to gain */
1084
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)))
1087
table->getMutableShare()->setRecordLength(reclength);
1089
uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
1090
table->getMutableShare()->rec_buff_length= alloc_length;
1091
if (!(table->record[0]= (unsigned char*) table->alloc_root(alloc_length*2)))
1095
table->record[1]= table->getInsertRecord()+alloc_length;
1096
table->getMutableShare()->resizeDefaultValues(alloc_length);
1098
copy_func[0]= 0; // End marker
1099
param->func_count= copy_func - param->items_to_copy;
1101
table->setup_tmp_table_column_bitmaps();
1103
recinfo=param->start_recinfo;
1104
null_flags=(unsigned char*) table->getInsertRecord();
1105
pos=table->getInsertRecord()+ null_pack_length;
1106
if (null_pack_length)
1108
memset(recinfo, 0, sizeof(*recinfo));
1109
recinfo->type=FIELD_NORMAL;
1110
recinfo->length=null_pack_length;
1112
memset(null_flags, 255, null_pack_length); // Set null fields
1114
table->null_flags= (unsigned char*) table->getInsertRecord();
1115
table->getMutableShare()->null_fields= null_count+ hidden_null_count;
1116
table->getMutableShare()->null_bytes= null_pack_length;
1118
null_count= (blob_count == 0) ? 1 : 0;
1119
hidden_field_count=param->hidden_field_count;
1120
for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
1122
Field *field= *reg_field;
1124
memset(recinfo, 0, sizeof(*recinfo));
1126
if (!(field->flags & NOT_NULL_FLAG))
1128
if (field->flags & GROUP_FLAG && !using_unique_constraint)
1131
We have to reserve one byte here for NULL bits,
1132
as this is updated by 'end_update()'
1134
*pos++= '\0'; // Null is stored here
1136
recinfo->type=FIELD_NORMAL;
1138
memset(recinfo, 0, sizeof(*recinfo));
1142
recinfo->null_bit= 1 << (null_count & 7);
1143
recinfo->null_pos= null_count/8;
1145
field->move_field(pos,null_flags+null_count/8,
1146
1 << (null_count & 7));
1150
field->move_field(pos,(unsigned char*) 0,0);
1154
Test if there is a default field value. The test for ->ptr is to skip
1155
'offset' fields generated by initalize_tables
1157
if (default_field[i] && default_field[i]->ptr)
1160
default_field[i] is set only in the cases when 'field' can
1161
inherit the default value that is defined for the field referred
1162
by the Item_field object from which 'field' has been created.
1165
Field *orig_field= default_field[i];
1166
/* Get the value from default_values */
1167
diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
1168
orig_field->move_field_offset(diff); // Points now at default_values
1169
if (orig_field->is_real_null())
1173
field->set_notnull();
1174
memcpy(field->ptr, orig_field->ptr, field->pack_length());
1176
orig_field->move_field_offset(-diff); // Back to getInsertRecord()
1180
{ /* Not a table Item */
1181
copy->set(field,from_field[i],save_sum_fields);
1184
length=field->pack_length();
1187
/* Make entry for create table */
1188
recinfo->length=length;
1189
if (field->flags & BLOB_FLAG)
1190
recinfo->type= (int) FIELD_BLOB;
1192
recinfo->type=FIELD_NORMAL;
1193
if (!--hidden_field_count)
1194
null_count=(null_count+7) & ~7; // move to next byte
1197
param->copy_field_end=copy;
1198
param->recinfo=recinfo;
1199
table->storeRecordAsDefault(); // Make empty default record
1201
if (session->variables.tmp_table_size == ~ (uint64_t) 0) // No limit
1203
max_rows= ~(uint64_t) 0;
1207
max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
1208
min(session->variables.tmp_table_size,
1209
session->variables.max_heap_table_size) :
1210
session->variables.tmp_table_size) /
1211
table->getMutableShare()->getRecordLength());
1214
set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
1216
Push the LIMIT clause to the temporary table creation, so that we
1217
materialize only up to 'rows_limit' records instead of all result records.
1219
set_if_smaller(max_rows, rows_limit);
1221
table->getMutableShare()->setMaxRows(max_rows);
1223
param->end_write_records= rows_limit;
1225
keyinfo= param->keyinfo;
1229
table->group=group; /* Table is grouped by key */
1230
param->group_buff=group_buff;
1231
table->getMutableShare()->keys=1;
1232
table->getMutableShare()->uniques= test(using_unique_constraint);
1233
table->key_info=keyinfo;
1234
keyinfo->key_part=key_part_info;
1235
keyinfo->flags=HA_NOSAME;
1236
keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
1237
keyinfo->key_length= 0;
1238
keyinfo->rec_per_key= 0;
1239
keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1240
keyinfo->name= (char*) "group_key";
1241
Order *cur_group= group;
1242
for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1244
Field *field=(*cur_group->item)->get_tmp_table_field();
1245
bool maybe_null=(*cur_group->item)->maybe_null;
1246
key_part_info->null_bit= 0;
1247
key_part_info->field= field;
1248
key_part_info->offset= field->offset(table->getInsertRecord());
1249
key_part_info->length= (uint16_t) field->key_length();
1250
key_part_info->type= (uint8_t) field->key_type();
1251
key_part_info->key_type=
1252
((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1253
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1254
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1256
if (!using_unique_constraint)
1258
cur_group->buff=(char*) group_buff;
1259
if (!(cur_group->field= field->new_key_field(session->mem_root,table,
1268
To be able to group on NULL, we reserved place in group_buff
1269
for the NULL flag just before the column. (see above).
1270
The field data is after this flag.
1271
The NULL flag is updated in 'end_update()' and 'end_write()'
1273
keyinfo->flags|= HA_NULL_ARE_EQUAL; // def. that NULL == NULL
1274
key_part_info->null_bit=field->null_bit;
1275
key_part_info->null_offset= (uint32_t) (field->null_ptr -
1276
(unsigned char*) table->getInsertRecord());
1277
cur_group->buff++; // Pointer to field data
1278
group_buff++; // Skipp null flag
1280
/* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
1281
key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
1282
group_buff+= cur_group->field->pack_length();
1284
keyinfo->key_length+= key_part_info->length;
1288
if (distinct && field_count != param->hidden_field_count)
1291
Create an unique key or an unique constraint over all columns
1292
that should be in the result. In the temporary table, there are
1293
'param->hidden_field_count' extra columns, whose null bits are stored
1294
in the first 'hidden_null_pack_length' bytes of the row.
1299
Special mode for index creation in MyISAM used to support unique
1300
indexes on blobs with arbitrary length. Such indexes cannot be
1303
table->getMutableShare()->uniques= 1;
1305
null_pack_length-=hidden_null_pack_length;
1306
keyinfo->key_parts= ((field_count-param->hidden_field_count)+
1307
(table->getMutableShare()->uniques ? test(null_pack_length) : 0));
1309
table->getMutableShare()->keys= 1;
1310
if (!(key_part_info= (KeyPartInfo*)
1311
table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
1313
memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
1314
table->key_info=keyinfo;
1315
keyinfo->key_part=key_part_info;
1316
keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
1317
keyinfo->key_length=(uint16_t) reclength;
1318
keyinfo->name= (char*) "distinct_key";
1319
keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1320
keyinfo->rec_per_key= 0;
1323
Create an extra field to hold NULL bits so that unique indexes on
1324
blobs can distinguish NULL from 0. This extra field is not needed
1325
when we do not use UNIQUE indexes for blobs.
1327
if (null_pack_length && table->getMutableShare()->uniques)
1329
key_part_info->null_bit= 0;
1330
key_part_info->offset=hidden_null_pack_length;
1331
key_part_info->length=null_pack_length;
1332
table->setVariableWidth();
1333
key_part_info->field= new Field_varstring(table->getInsertRecord(),
1334
(uint32_t) key_part_info->length,
1340
if (!key_part_info->field)
1342
key_part_info->field->init(table);
1343
key_part_info->key_type= 1; /* binary comparison */
1344
key_part_info->type= HA_KEYTYPE_BINARY;
1347
/* Create a distinct key over the columns we are going to return */
1348
for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
1350
i++, reg_field++, key_part_info++)
1352
key_part_info->null_bit= 0;
1353
key_part_info->field= *reg_field;
1354
key_part_info->offset= (*reg_field)->offset(table->getInsertRecord());
1355
key_part_info->length= (uint16_t) (*reg_field)->pack_length();
1356
/* @todo The below method of computing the key format length of the
1357
key part is a copy/paste from optimizer/range.cc, and table.cc.
1358
This should be factored out, e.g. as a method of Field.
1359
In addition it is not clear if any of the Field::*_length
1360
methods is supposed to compute the same length. If so, it
1363
key_part_info->store_length= key_part_info->length;
1365
if ((*reg_field)->real_maybe_null())
1366
key_part_info->store_length+= HA_KEY_NULL_LENGTH;
1367
if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
1368
(*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
1369
key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
1371
key_part_info->type= (uint8_t) (*reg_field)->key_type();
1372
key_part_info->key_type =
1373
((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1374
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1375
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1380
if (session->is_fatal_error) // If end of memory
1382
table->getMutableShare()->db_record_offset= 1;
1383
if (table->getShare()->db_type() == myisam_engine)
1385
if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1386
¶m->recinfo, select_options))
1389
assert(table->in_use);
1390
if (table->open_tmp_table())
1393
session->mem_root= mem_root_save;
1398
session->mem_root= mem_root_save;
1404
/****************************************************************************/
1406
void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
1407
boost::dynamic_bitset<>& write_set_arg)
1409
read_set= &read_set_arg;
1410
write_set= &write_set_arg;
1414
const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
1416
const boost::dynamic_bitset<> old= in_map;
1417
in_map= getShare()->all_set;
1421
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
1423
for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
1436
uint32_t Table::find_shortest_key(const key_map *usable_keys)
1438
uint32_t min_length= UINT32_MAX;
1439
uint32_t best= MAX_KEY;
1440
if (usable_keys->any())
1442
for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
1444
if (usable_keys->test(nr))
1446
if (key_info[nr].key_length < min_length)
1448
min_length= key_info[nr].key_length;
1457
/*****************************************************************************
1458
Remove duplicates from tmp table
1459
This should be recoded to add a unique index to the table and remove
1461
Table is a locked single thread table
1462
fields is the number of fields to check (from the end)
1463
*****************************************************************************/
1465
bool Table::compare_record(Field **ptr)
1467
for (; *ptr ; ptr++)
1469
if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
1476
True if the table's input and output record buffers are comparable using
1477
compare_records(TABLE*).
1479
bool Table::records_are_comparable()
1481
return ((getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) == 0) ||
1482
write_set->is_subset_of(*read_set));
1486
Compares the input and outbut record buffers of the table to see if a row
1487
has changed. The algorithm iterates over updated columns and if they are
1488
nullable compares NULL bits in the buffer before comparing actual
1489
data. Special care must be taken to compare only the relevant NULL bits and
1490
mask out all others as they may be undefined. The storage engine will not
1491
and should not touch them.
1493
@param table The table to evaluate.
1495
@return true if row has changed.
1496
@return false otherwise.
1498
bool Table::compare_records()
1500
if (getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) != 0)
1503
Storage engine may not have read all columns of the record. Fields
1504
(including NULL bits) not in the write_set may not have been read and
1505
can therefore not be compared.
1507
for (Field **ptr= this->field ; *ptr != NULL; ptr++)
1510
if (write_set->test(f->position()))
1512
if (f->real_maybe_null())
1514
unsigned char null_byte_index= f->null_ptr - record[0];
1516
if (((record[0][null_byte_index]) & f->null_bit) !=
1517
((record[1][null_byte_index]) & f->null_bit))
1520
if (f->cmp_binary_offset(getShare()->rec_buff_length))
1528
The storage engine has read all columns, so it's safe to compare all bits
1529
including those not in the write_set. This is cheaper than the
1530
field-by-field comparison done above.
1532
if (not getShare()->blob_fields + getShare()->hasVariableWidth())
1533
// Fixed-size record: do bitwise comparison of the records
1534
return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
1536
/* Compare null bits */
1537
if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
1538
return true; /* Diff in NULL value */
1540
/* Compare updated fields */
1541
for (Field **ptr= field ; *ptr ; ptr++)
1543
if (isWriteSet((*ptr)->position()) &&
1544
(*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
1551
* Store a record from previous record into next
1554
void Table::storeRecord()
1556
memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1560
* Store a record as an insert
1563
void Table::storeRecordAsInsert()
1565
assert(insert_values.size() >= getShare()->getRecordLength());
1566
memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
1570
* Store a record with default values
1573
void Table::storeRecordAsDefault()
1575
memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1579
* Restore a record from previous record into next
1582
void Table::restoreRecord()
1584
memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
1588
* Restore a record with default values
1591
void Table::restoreRecordAsDefault()
1593
memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
1600
void Table::emptyRecord()
1602
restoreRecordAsDefault();
1603
memset(null_flags, 255, getShare()->null_bytes);
1620
next_number_field(NULL),
1621
found_next_number_field(NULL),
1622
timestamp_field(NULL),
1623
pos_in_table_list(NULL),
1631
derived_select_number(0),
1632
current_lock(F_UNLCK),
1642
open_placeholder(false),
1643
locked_by_name(false),
1645
auto_increment_field_not_null(false),
1646
alias_name_used(false),
1648
quick_condition_rows(0),
1649
timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1652
record[0]= (unsigned char *) 0;
1653
record[1]= (unsigned char *) 0;
1656
covering_keys.reset();
1660
keys_in_use_for_query.reset();
1661
keys_in_use_for_group_by.reset();
1662
keys_in_use_for_order_by.reset();
1664
memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
1665
memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
1667
memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
1668
memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
1671
/*****************************************************************************
1672
The different ways to read a record
1673
Returns -1 if row was not found, 0 if row was found and 1 on errors
1674
*****************************************************************************/
1676
/** Help function when we get some an error from the table Cursor. */
1678
int Table::report_error(int error)
1680
if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
1682
status= STATUS_GARBAGE;
1683
return -1; // key not found; ok
1686
Locking reads can legally return also these errors, do not
1687
print them to the .err log
1689
if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
1690
errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
1691
error, getShare()->getPath());
1692
print_error(error, MYF(0));
1698
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
1703
status= STATUS_NO_RECORD;
1704
maybe_null= table_list->outer_join;
1705
TableList *embedding= table_list->getEmbedding();
1706
while (!maybe_null && embedding)
1708
maybe_null= embedding->outer_join;
1709
embedding= embedding->getEmbedding();
1711
tablenr= table_number;
1712
map= (table_map) 1 << table_number;
1713
force_index= table_list->force_index;
1714
covering_keys= getShare()->keys_for_keyread;
1719
bool Table::fill_item_list(List<Item> *item_list) const
1722
All Item_field's created using a direct pointer to a field
1723
are fixed in Item_field constructor.
1725
for (Field **ptr= field; *ptr; ptr++)
1727
Item_field *item= new Item_field(*ptr);
1728
if (!item || item_list->push_back(item))
1735
void Table::filesort_free_buffers(bool full)
1737
if (sort.record_pointers)
1739
free((unsigned char*) sort.record_pointers);
1740
sort.record_pointers=0;
1744
if (sort.sort_keys )
1746
if ((unsigned char*) sort.sort_keys)
1747
free((unsigned char*) sort.sort_keys);
1752
if ((unsigned char*) sort.buffpek)
1753
free((unsigned char*) sort.buffpek);
1755
sort.buffpek_len= 0;
1761
free((char *) sort.addon_buf);
1762
free((char *) sort.addon_field);
1768
} /* namespace drizzled */
3645
Check type of .frm if we are not going to parse it
3656
frm_type_enum mysql_frm_type(THD *thd __attribute__((__unused__)),
3657
char *path, enum legacy_db_type *dbt)
3660
uchar header[10]; /* This should be optimized */
3663
*dbt= DB_TYPE_UNKNOWN;
3665
if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
3666
return(FRMTYPE_ERROR);
3667
error= my_read(file, (uchar*) header, sizeof(header), MYF(MY_NABP));
3668
my_close(file, MYF(MY_WME));
3671
return(FRMTYPE_ERROR);
3674
This is just a check for DB_TYPE. We'll return default unknown type
3675
if the following test is true (arg #3). This should not have effect
3676
on return value from this function (default FRMTYPE_TABLE)
3678
if (header[0] != (uchar) 254 || header[1] != 1 ||
3679
(header[2] != FRM_VER && header[2] != FRM_VER+1 &&
3680
(header[2] < FRM_VER+3 || header[2] > FRM_VER+4)))
3681
return(FRMTYPE_TABLE);
3683
*dbt= (enum legacy_db_type) (uint) *(header + 3);
3684
return(FRMTYPE_TABLE); // Is probably a .frm table
3688
/*****************************************************************************
3689
** Instansiate templates
3690
*****************************************************************************/
3692
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
3693
template class List<String>;
3694
template class List_iterator<String>;