~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/table.cc

  • Committer: brian
  • Date: 2008-06-25 05:29:13 UTC
  • Revision ID: brian@localhost.localdomain-20080625052913-6upwo0jsrl4lnapl
clean slate

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Some general useful functions */
18
18
 
19
 
#include "config.h"
20
 
 
21
 
#include <float.h>
22
 
#include <fcntl.h>
23
 
 
24
 
#include <string>
25
 
#include <vector>
26
 
#include <algorithm>
27
 
 
28
 
#include <drizzled/error.h>
29
 
#include <drizzled/gettext.h>
30
 
 
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"
49
 
#include "drizzled/plugin/storage_engine.h"
50
 
 
51
 
#include <drizzled/item/string.h>
52
 
#include <drizzled/item/int.h>
53
 
#include <drizzled/item/decimal.h>
54
 
#include <drizzled/item/float.h>
55
 
#include <drizzled/item/null.h>
56
 
#include <drizzled/temporal.h>
57
 
 
58
 
#include <drizzled/refresh_version.h>
59
 
 
60
 
#include "drizzled/table/singular.h"
61
 
 
62
 
#include "drizzled/table_proto.h"
63
 
 
64
 
using namespace std;
65
 
 
66
 
namespace drizzled
67
 
{
68
 
 
69
 
extern plugin::StorageEngine *heap_engine;
70
 
extern plugin::StorageEngine *myisam_engine;
71
 
 
72
 
/* Functions defined in this cursor */
 
19
#include "mysql_priv.h"
 
20
#include <m_ctype.h>
 
21
#include "my_md5.h"
 
22
 
 
23
/* INFORMATION_SCHEMA name */
 
24
LEX_STRING INFORMATION_SCHEMA_NAME= {C_STRING_WITH_LEN("information_schema")};
 
25
 
 
26
/* MYSQL_SCHEMA name */
 
27
LEX_STRING MYSQL_SCHEMA_NAME= {C_STRING_WITH_LEN("mysql")};
 
28
 
 
29
/* Functions defined in this file */
 
30
 
 
31
void open_table_error(TABLE_SHARE *share, int error, int db_errno,
 
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);
 
38
 
 
39
inline bool is_system_table_name(const char *name, uint length);
 
40
 
 
41
/**************************************************************************
 
42
  Object_creation_ctx implementation.
 
43
**************************************************************************/
 
44
 
 
45
Object_creation_ctx *Object_creation_ctx::set_n_backup(THD *thd)
 
46
{
 
47
  Object_creation_ctx *backup_ctx;
 
48
  DBUG_ENTER("Object_creation_ctx::set_n_backup");
 
49
 
 
50
  backup_ctx= create_backup_ctx(thd);
 
51
  change_env(thd);
 
52
 
 
53
  DBUG_RETURN(backup_ctx);
 
54
}
 
55
 
 
56
void Object_creation_ctx::restore_env(THD *thd, Object_creation_ctx *backup_ctx)
 
57
{
 
58
  if (!backup_ctx)
 
59
    return;
 
60
 
 
61
  backup_ctx->change_env(thd);
 
62
 
 
63
  delete backup_ctx;
 
64
}
 
65
 
 
66
/**************************************************************************
 
67
  Default_object_creation_ctx implementation.
 
68
**************************************************************************/
 
69
 
 
70
Default_object_creation_ctx::Default_object_creation_ctx(THD *thd)
 
71
  : m_client_cs(thd->variables.character_set_client),
 
72
    m_connection_cl(thd->variables.collation_connection)
 
73
{ }
 
74
 
 
75
Default_object_creation_ctx::Default_object_creation_ctx(
 
76
  CHARSET_INFO *client_cs, CHARSET_INFO *connection_cl)
 
77
  : m_client_cs(client_cs),
 
78
    m_connection_cl(connection_cl)
 
79
{ }
 
80
 
 
81
Object_creation_ctx *
 
82
Default_object_creation_ctx::create_backup_ctx(THD *thd) const
 
83
{
 
84
  return new Default_object_creation_ctx(thd);
 
85
}
 
86
 
 
87
void Default_object_creation_ctx::change_env(THD *thd) const
 
88
{
 
89
  thd->variables.character_set_client= m_client_cs;
 
90
  thd->variables.collation_connection= m_connection_cl;
 
91
 
 
92
  thd->update_charset();
 
93
}
73
94
 
74
95
/*************************************************************************/
75
96
 
76
 
// @note this should all be the destructor
77
 
int Table::delete_table(bool free_share)
78
 
{
79
 
  int error= 0;
80
 
 
81
 
  if (db_stat)
82
 
    error= cursor->close();
83
 
  _alias.clear();
84
 
 
85
 
  if (field)
86
 
  {
87
 
    for (Field **ptr=field ; *ptr ; ptr++)
88
 
    {
 
97
/* Get column name from column hash */
 
98
 
 
99
static uchar *get_field_name(Field **buff, size_t *length,
 
100
                             my_bool not_used __attribute__((unused)))
 
101
{
 
102
  *length= (uint) strlen((*buff)->field_name);
 
103
  return (uchar*) (*buff)->field_name;
 
104
}
 
105
 
 
106
 
 
107
/*
 
108
  Returns pointer to '.frm' extension of the file name.
 
109
 
 
110
  SYNOPSIS
 
111
    fn_rext()
 
112
    name       file name
 
113
 
 
114
  DESCRIPTION
 
115
    Checks file name part starting with the rightmost '.' character,
 
116
    and returns it if it is equal to '.frm'. 
 
117
 
 
118
  TODO
 
119
    It is a good idea to get rid of this function modifying the code
 
120
    to garantee that the functions presently calling fn_rext() always
 
121
    get arguments in the same format: either with '.frm' or without '.frm'.
 
122
 
 
123
  RETURN VALUES
 
124
    Pointer to the '.frm' extension. If there is no extension,
 
125
    or extension is not '.frm', pointer at the end of file name.
 
126
*/
 
127
 
 
128
char *fn_rext(char *name)
 
129
{
 
130
  char *res= strrchr(name, '.');
 
131
  if (res && !strcmp(res, reg_ext))
 
132
    return res;
 
133
  return name + strlen(name);
 
134
}
 
135
 
 
136
TABLE_CATEGORY get_table_category(const LEX_STRING *db, const LEX_STRING *name)
 
137
{
 
138
  DBUG_ASSERT(db != NULL);
 
139
  DBUG_ASSERT(name != NULL);
 
140
 
 
141
  if ((db->length == INFORMATION_SCHEMA_NAME.length) &&
 
142
      (my_strcasecmp(system_charset_info,
 
143
                    INFORMATION_SCHEMA_NAME.str,
 
144
                    db->str) == 0))
 
145
  {
 
146
    return TABLE_CATEGORY_INFORMATION;
 
147
  }
 
148
 
 
149
  if ((db->length == MYSQL_SCHEMA_NAME.length) &&
 
150
      (my_strcasecmp(system_charset_info,
 
151
                    MYSQL_SCHEMA_NAME.str,
 
152
                    db->str) == 0))
 
153
  {
 
154
    if (is_system_table_name(name->str, name->length))
 
155
    {
 
156
      return TABLE_CATEGORY_SYSTEM;
 
157
    }
 
158
  }
 
159
 
 
160
  return TABLE_CATEGORY_USER;
 
161
}
 
162
 
 
163
 
 
164
/*
 
165
  Allocate a setup TABLE_SHARE structure
 
166
 
 
167
  SYNOPSIS
 
168
    alloc_table_share()
 
169
    TABLE_LIST          Take database and table name from there
 
170
    key                 Table cache key (db \0 table_name \0...)
 
171
    key_length          Length of key
 
172
 
 
173
  RETURN
 
174
    0  Error (out of memory)
 
175
    #  Share
 
176
*/
 
177
 
 
178
TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key,
 
179
                               uint key_length)
 
180
{
 
181
  MEM_ROOT mem_root;
 
182
  TABLE_SHARE *share;
 
183
  char *key_buff, *path_buff;
 
184
  char path[FN_REFLEN];
 
185
  uint path_length;
 
186
  DBUG_ENTER("alloc_table_share");
 
187
  DBUG_PRINT("enter", ("table: '%s'.'%s'",
 
188
                       table_list->db, table_list->table_name));
 
189
 
 
190
  path_length= build_table_filename(path, sizeof(path) - 1,
 
191
                                    table_list->db,
 
192
                                    table_list->table_name, "", 0);
 
193
  init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
194
  if (multi_alloc_root(&mem_root,
 
195
                       &share, sizeof(*share),
 
196
                       &key_buff, key_length,
 
197
                       &path_buff, path_length + 1,
 
198
                       NULL))
 
199
  {
 
200
    bzero((char*) share, sizeof(*share));
 
201
 
 
202
    share->set_table_cache_key(key_buff, key, key_length);
 
203
 
 
204
    share->path.str= path_buff;
 
205
    share->path.length= path_length;
 
206
    strmov(share->path.str, path);
 
207
    share->normalized_path.str=    share->path.str;
 
208
    share->normalized_path.length= path_length;
 
209
 
 
210
    share->version=       refresh_version;
 
211
 
 
212
    share->tablespace=    NULL;
 
213
 
 
214
    /*
 
215
      This constant is used to mark that no table map version has been
 
216
      assigned.  No arithmetic is done on the value: it will be
 
217
      overwritten with a value taken from MYSQL_BIN_LOG.
 
218
    */
 
219
    share->table_map_version= ~(uint64_t)0;
 
220
 
 
221
    /*
 
222
      Since alloc_table_share() can be called without any locking (for
 
223
      example, ha_create_table... functions), we do not assign a table
 
224
      map id here.  Instead we assign a value that is not used
 
225
      elsewhere, and then assign a table map id inside open_table()
 
226
      under the protection of the LOCK_open mutex.
 
227
    */
 
228
    share->table_map_id= ~0UL;
 
229
    share->cached_row_logging_check= -1;
 
230
 
 
231
    memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root));
 
232
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
 
233
    pthread_cond_init(&share->cond, NULL);
 
234
  }
 
235
  DBUG_RETURN(share);
 
236
}
 
237
 
 
238
 
 
239
/*
 
240
  Initialize share for temporary tables
 
241
 
 
242
  SYNOPSIS
 
243
    init_tmp_table_share()
 
244
    thd         thread handle
 
245
    share       Share to fill
 
246
    key         Table_cache_key, as generated from create_table_def_key.
 
247
                must start with db name.    
 
248
    key_length  Length of key
 
249
    table_name  Table name
 
250
    path        Path to file (possible in lower case) without .frm
 
251
 
 
252
  NOTES
 
253
    This is different from alloc_table_share() because temporary tables
 
254
    don't have to be shared between threads or put into the table def
 
255
    cache, so we can do some things notable simpler and faster
 
256
 
 
257
    If table is not put in thd->temporary_tables (happens only when
 
258
    one uses OPEN TEMPORARY) then one can specify 'db' as key and
 
259
    use key_length= 0 as neither table_cache_key or key_length will be used).
 
260
*/
 
261
 
 
262
void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
 
263
                          uint key_length, const char *table_name,
 
264
                          const char *path)
 
265
{
 
266
  DBUG_ENTER("init_tmp_table_share");
 
267
  DBUG_PRINT("enter", ("table: '%s'.'%s'", key, table_name));
 
268
 
 
269
  bzero((char*) share, sizeof(*share));
 
270
  init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
271
  share->table_category=         TABLE_CATEGORY_TEMPORARY;
 
272
  share->tmp_table=              INTERNAL_TMP_TABLE;
 
273
  share->db.str=                 (char*) key;
 
274
  share->db.length=              strlen(key);
 
275
  share->table_cache_key.str=    (char*) key;
 
276
  share->table_cache_key.length= key_length;
 
277
  share->table_name.str=         (char*) table_name;
 
278
  share->table_name.length=      strlen(table_name);
 
279
  share->path.str=               (char*) path;
 
280
  share->normalized_path.str=    (char*) path;
 
281
  share->path.length= share->normalized_path.length= strlen(path);
 
282
  share->frm_version=            FRM_VER_TRUE_VARCHAR;
 
283
  share->tablespace=             NULL;
 
284
  /*
 
285
    Temporary tables are not replicated, but we set up these fields
 
286
    anyway to be able to catch errors.
 
287
   */
 
288
  share->table_map_version= ~(uint64_t)0;
 
289
  share->cached_row_logging_check= -1;
 
290
 
 
291
  /*
 
292
    table_map_id is also used for MERGE tables to suppress repeated
 
293
    compatibility checks.
 
294
  */
 
295
  share->table_map_id= (ulong) thd->query_id;
 
296
 
 
297
  DBUG_VOID_RETURN;
 
298
}
 
299
 
 
300
 
 
301
/*
 
302
  Free table share and memory used by it
 
303
 
 
304
  SYNOPSIS
 
305
    free_table_share()
 
306
    share               Table share
 
307
 
 
308
  NOTES
 
309
    share->mutex must be locked when we come here if it's not a temp table
 
310
*/
 
311
 
 
312
void free_table_share(TABLE_SHARE *share)
 
313
{
 
314
  MEM_ROOT mem_root;
 
315
  DBUG_ENTER("free_table_share");
 
316
  DBUG_PRINT("enter", ("table: %s.%s", share->db.str, share->table_name.str));
 
317
  DBUG_ASSERT(share->ref_count == 0);
 
318
 
 
319
  /*
 
320
    If someone is waiting for this to be deleted, inform it about this.
 
321
    Don't do a delete until we know that no one is refering to this anymore.
 
322
  */
 
323
  if (share->tmp_table == NO_TMP_TABLE)
 
324
  {
 
325
    /* share->mutex is locked in release_table_share() */
 
326
    while (share->waiting_on_cond)
 
327
    {
 
328
      pthread_cond_broadcast(&share->cond);
 
329
      pthread_cond_wait(&share->cond, &share->mutex);
 
330
    }
 
331
    /* No thread refers to this anymore */
 
332
    pthread_mutex_unlock(&share->mutex);
 
333
    pthread_mutex_destroy(&share->mutex);
 
334
    pthread_cond_destroy(&share->cond);
 
335
  }
 
336
  hash_free(&share->name_hash);
 
337
  
 
338
  plugin_unlock(NULL, share->db_plugin);
 
339
  share->db_plugin= NULL;
 
340
 
 
341
  /* We must copy mem_root from share because share is allocated through it */
 
342
  memcpy((char*) &mem_root, (char*) &share->mem_root, sizeof(mem_root));
 
343
  free_root(&mem_root, MYF(0));                 // Free's share
 
344
  DBUG_VOID_RETURN;
 
345
}
 
346
 
 
347
 
 
348
/**
 
349
  Return TRUE if a table name matches one of the system table names.
 
350
  Currently these are:
 
351
 
 
352
  help_category, help_keyword, help_relation, help_topic,
 
353
  proc, event
 
354
  time_zone, time_zone_leap_second, time_zone_name, time_zone_transition,
 
355
  time_zone_transition_type
 
356
 
 
357
  This function trades accuracy for speed, so may return false
 
358
  positives. Presumably mysql.* database is for internal purposes only
 
359
  and should not contain user tables.
 
360
*/
 
361
 
 
362
inline bool is_system_table_name(const char *name, uint length)
 
363
{
 
364
  CHARSET_INFO *ci= system_charset_info;
 
365
 
 
366
  return (
 
367
          /* mysql.proc table */
 
368
          (
 
369
           length == 4 &&
 
370
           my_tolower(ci, name[0]) == 'p' && 
 
371
           my_tolower(ci, name[1]) == 'r' &&
 
372
           my_tolower(ci, name[2]) == 'o' &&
 
373
           my_tolower(ci, name[3]) == 'c'
 
374
          ) ||
 
375
 
 
376
          /* one of mysql.help* tables */
 
377
          (
 
378
           length > 4 &&
 
379
           my_tolower(ci, name[0]) == 'h' &&
 
380
           my_tolower(ci, name[1]) == 'e' &&
 
381
           my_tolower(ci, name[2]) == 'l' &&
 
382
           my_tolower(ci, name[3]) == 'p'
 
383
          ) ||
 
384
 
 
385
          /* one of mysql.time_zone* tables */
 
386
          (
 
387
           my_tolower(ci, name[0]) == 't' &&
 
388
           my_tolower(ci, name[1]) == 'i' &&
 
389
           my_tolower(ci, name[2]) == 'm' &&
 
390
           my_tolower(ci, name[3]) == 'e'
 
391
          )
 
392
          );
 
393
}
 
394
 
 
395
 
 
396
/*
 
397
  Read table definition from a binary / text based .frm file
 
398
  
 
399
  SYNOPSIS
 
400
  open_table_def()
 
401
  thd           Thread handler
 
402
  share         Fill this with table definition
 
403
  db_flags      Bit mask of the following flags: OPEN_VIEW
 
404
 
 
405
  NOTES
 
406
    This function is called when the table definition is not cached in
 
407
    table_def_cache
 
408
    The data is returned in 'share', which is alloced by
 
409
    alloc_table_share().. The code assumes that share is initialized.
 
410
 
 
411
  RETURN VALUES
 
412
   0    ok
 
413
   1    Error (see open_table_error)
 
414
   2    Error (see open_table_error)
 
415
   3    Wrong data in .frm file
 
416
   4    Error (see open_table_error)
 
417
   5    Error (see open_table_error: charset unavailable)
 
418
   6    Unknown .frm version
 
419
*/
 
420
 
 
421
int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags)
 
422
{
 
423
  int error, table_type;
 
424
  bool error_given;
 
425
  File file;
 
426
  uchar head[64], *disk_buff;
 
427
  char  path[FN_REFLEN];
 
428
  MEM_ROOT **root_ptr, *old_root;
 
429
  DBUG_ENTER("open_table_def");
 
430
  DBUG_PRINT("enter", ("table: '%s'.'%s'  path: '%s'", share->db.str,
 
431
                       share->table_name.str, share->normalized_path.str));
 
432
 
 
433
  error= 1;
 
434
  error_given= 0;
 
435
  disk_buff= NULL;
 
436
 
 
437
  strxmov(path, share->normalized_path.str, reg_ext, NullS);
 
438
  if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
 
439
  {
 
440
    /*
 
441
      We don't try to open 5.0 unencoded name, if
 
442
      - non-encoded name contains '@' signs, 
 
443
        because '@' can be misinterpreted.
 
444
        It is not clear if '@' is escape character in 5.1,
 
445
        or a normal character in 5.0.
 
446
        
 
447
      - non-encoded db or table name contain "#mysql50#" prefix.
 
448
        This kind of tables must have been opened only by the
 
449
        my_open() above.
 
450
    */
 
451
    if (strchr(share->table_name.str, '@') ||
 
452
        !strncmp(share->db.str, MYSQL50_TABLE_NAME_PREFIX,
 
453
                 MYSQL50_TABLE_NAME_PREFIX_LENGTH) ||
 
454
        !strncmp(share->table_name.str, MYSQL50_TABLE_NAME_PREFIX,
 
455
                 MYSQL50_TABLE_NAME_PREFIX_LENGTH))
 
456
      goto err_not_open;
 
457
 
 
458
    /* Try unencoded 5.0 name */
 
459
    uint length;
 
460
    strxnmov(path, sizeof(path)-1,
 
461
             mysql_data_home, "/", share->db.str, "/",
 
462
             share->table_name.str, reg_ext, NullS);
 
463
    length= unpack_filename(path, path) - reg_ext_length;
 
464
    /*
 
465
      The following is a safety test and should never fail
 
466
      as the old file name should never be longer than the new one.
 
467
    */
 
468
    DBUG_ASSERT(length <= share->normalized_path.length);
 
469
    /*
 
470
      If the old and the new names have the same length,
 
471
      then table name does not have tricky characters,
 
472
      so no need to check the old file name.
 
473
    */
 
474
    if (length == share->normalized_path.length ||
 
475
        ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0))
 
476
      goto err_not_open;
 
477
 
 
478
    /* Unencoded 5.0 table name found */
 
479
    path[length]= '\0'; // Remove .frm extension
 
480
    strmov(share->normalized_path.str, path);
 
481
    share->normalized_path.length= length;
 
482
  }
 
483
 
 
484
  error= 4;
 
485
  if (my_read(file, head, 64, MYF(MY_NABP)))
 
486
    goto err;
 
487
 
 
488
  if (head[0] == (uchar) 254 && head[1] == 1)
 
489
  {
 
490
    if (head[2] == FRM_VER || head[2] == FRM_VER+1 ||
 
491
        (head[2] >= FRM_VER+3 && head[2] <= FRM_VER+4))
 
492
    {
 
493
      /* Open view only */
 
494
      if (db_flags & OPEN_VIEW_ONLY)
 
495
      {
 
496
        error_given= 1;
 
497
        goto err;
 
498
      }
 
499
      table_type= 1;
 
500
    }
 
501
    else
 
502
    {
 
503
      error= 6;                                 // Unkown .frm version
 
504
      goto err;
 
505
    }
 
506
  }
 
507
  else
 
508
    goto err;
 
509
 
 
510
  /* No handling of text based files yet */
 
511
  if (table_type == 1)
 
512
  {
 
513
    root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC);
 
514
    old_root= *root_ptr;
 
515
    *root_ptr= &share->mem_root;
 
516
    error= open_binary_frm(thd, share, head, file);
 
517
    *root_ptr= old_root;
 
518
    error_given= 1;
 
519
  }
 
520
 
 
521
  share->table_category= get_table_category(& share->db, & share->table_name);
 
522
 
 
523
  if (!error)
 
524
    thd->status_var.opened_shares++;
 
525
 
 
526
err:
 
527
  my_close(file, MYF(MY_WME));
 
528
 
 
529
err_not_open:
 
530
  if (error && !error_given)
 
531
  {
 
532
    share->error= error;
 
533
    open_table_error(share, error, (share->open_errno= my_errno), 0);
 
534
  }
 
535
 
 
536
  DBUG_RETURN(error);
 
537
}
 
538
 
 
539
 
 
540
/*
 
541
  Read data from a binary .frm file from MySQL 3.23 - 5.0 into TABLE_SHARE
 
542
*/
 
543
 
 
544
static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
 
545
                           File file)
 
546
{
 
547
  int error, errarg= 0;
 
548
  uint new_frm_ver, field_pack_length, new_field_pack_flag;
 
549
  uint interval_count, interval_parts, read_length, int_length;
 
550
  uint db_create_options, keys, key_parts, n_length;
 
551
  uint key_info_length, com_length, null_bit_pos;
 
552
  uint extra_rec_buf_length;
 
553
  uint i,j;
 
554
  bool use_hash;
 
555
  uchar forminfo[288];
 
556
  char *keynames, *names, *comment_pos;
 
557
  uchar *record;
 
558
  uchar *disk_buff, *strpos, *null_flags, *null_pos;
 
559
  ulong pos, record_offset, *rec_per_key, rec_buff_length;
 
560
  handler *handler_file= 0;
 
561
  KEY   *keyinfo;
 
562
  KEY_PART_INFO *key_part;
 
563
  SQL_CRYPT *crypted=0;
 
564
  Field  **field_ptr, *reg_field;
 
565
  const char **interval_array;
 
566
  enum legacy_db_type legacy_db_type;
 
567
  my_bitmap_map *bitmaps;
 
568
  uchar *buff= 0;
 
569
  uchar *field_extra_info= 0;
 
570
  DBUG_ENTER("open_binary_frm");
 
571
 
 
572
  new_field_pack_flag= head[27];
 
573
  new_frm_ver= (head[2] - FRM_VER);
 
574
  field_pack_length= new_frm_ver < 2 ? 11 : 17;
 
575
  disk_buff= 0;
 
576
 
 
577
  error= 3;
 
578
  if (!(pos=get_form_pos(file,head,(TYPELIB*) 0)))
 
579
    goto err;                                   /* purecov: inspected */
 
580
  VOID(my_seek(file,pos,MY_SEEK_SET,MYF(0)));
 
581
  if (my_read(file,forminfo,288,MYF(MY_NABP)))
 
582
    goto err;
 
583
 
 
584
  share->frm_version= head[2];
 
585
  /*
 
586
    Check if .frm file created by MySQL 5.0. In this case we want to
 
587
    display CHAR fields as CHAR and not as VARCHAR.
 
588
    We do it this way as we want to keep the old frm version to enable
 
589
    MySQL 4.1 to read these files.
 
590
  */
 
591
  if (share->frm_version == FRM_VER_TRUE_VARCHAR -1 && head[33] == 5)
 
592
    share->frm_version= FRM_VER_TRUE_VARCHAR;
 
593
 
 
594
  legacy_db_type= (enum legacy_db_type) (uint) *(head+3);
 
595
  DBUG_ASSERT(share->db_plugin == NULL);
 
596
  /*
 
597
    if the storage engine is dynamic, no point in resolving it by its
 
598
    dynamically allocated legacy_db_type. We will resolve it later by name.
 
599
  */
 
600
  if (legacy_db_type > DB_TYPE_UNKNOWN && 
 
601
      legacy_db_type < DB_TYPE_FIRST_DYNAMIC)
 
602
    share->db_plugin= ha_lock_engine(NULL, 
 
603
                                     ha_checktype(thd, legacy_db_type, 0, 0));
 
604
  share->db_create_options= db_create_options= uint2korr(head+30);
 
605
  share->db_options_in_use= share->db_create_options;
 
606
  share->mysql_version= uint4korr(head+51);
 
607
  share->null_field_first= 0;
 
608
  if (!head[32])                                // New frm file in 3.23
 
609
  {
 
610
    share->avg_row_length= uint4korr(head+34);
 
611
    share->transactional= (ha_choice) (head[39] & 3);
 
612
    share->page_checksum= (ha_choice) ((head[39] >> 2) & 3);
 
613
    share->row_type= (row_type) head[40];
 
614
    share->table_charset= get_charset((uint) head[38],MYF(0));
 
615
    share->null_field_first= 1;
 
616
  }
 
617
  if (!share->table_charset)
 
618
  {
 
619
    /* unknown charset in head[38] or pre-3.23 frm */
 
620
    if (use_mb(default_charset_info))
 
621
    {
 
622
      /* Warn that we may be changing the size of character columns */
 
623
      sql_print_warning("'%s' had no or invalid character set, "
 
624
                        "and default character set is multi-byte, "
 
625
                        "so character column sizes may have changed",
 
626
                        share->path.str);
 
627
    }
 
628
    share->table_charset= default_charset_info;
 
629
  }
 
630
  share->db_record_offset= 1;
 
631
  if (db_create_options & HA_OPTION_LONG_BLOB_PTR)
 
632
    share->blob_ptr_size= portable_sizeof_char_ptr;
 
633
  /* Set temporarily a good value for db_low_byte_first */
 
634
  share->db_low_byte_first= test(legacy_db_type != DB_TYPE_ISAM);
 
635
  error=4;
 
636
  share->max_rows= uint4korr(head+18);
 
637
  share->min_rows= uint4korr(head+22);
 
638
 
 
639
  /* Read keyinformation */
 
640
  key_info_length= (uint) uint2korr(head+28);
 
641
  VOID(my_seek(file,(ulong) uint2korr(head+6),MY_SEEK_SET,MYF(0)));
 
642
  if (read_string(file,(uchar**) &disk_buff,key_info_length))
 
643
    goto err;                                   /* purecov: inspected */
 
644
  if (disk_buff[0] & 0x80)
 
645
  {
 
646
    share->keys=      keys=      (disk_buff[1] << 7) | (disk_buff[0] & 0x7f);
 
647
    share->key_parts= key_parts= uint2korr(disk_buff+2);
 
648
  }
 
649
  else
 
650
  {
 
651
    share->keys=      keys=      disk_buff[0];
 
652
    share->key_parts= key_parts= disk_buff[1];
 
653
  }
 
654
  share->keys_for_keyread.init(0);
 
655
  share->keys_in_use.init(keys);
 
656
 
 
657
  n_length=keys*sizeof(KEY)+key_parts*sizeof(KEY_PART_INFO);
 
658
  if (!(keyinfo = (KEY*) alloc_root(&share->mem_root,
 
659
                                    n_length + uint2korr(disk_buff+4))))
 
660
    goto err;                                   /* purecov: inspected */
 
661
  bzero((char*) keyinfo,n_length);
 
662
  share->key_info= keyinfo;
 
663
  key_part= my_reinterpret_cast(KEY_PART_INFO*) (keyinfo+keys);
 
664
  strpos=disk_buff+6;
 
665
 
 
666
  if (!(rec_per_key= (ulong*) alloc_root(&share->mem_root,
 
667
                                         sizeof(ulong*)*key_parts)))
 
668
    goto err;
 
669
 
 
670
  for (i=0 ; i < keys ; i++, keyinfo++)
 
671
  {
 
672
    keyinfo->table= 0;                           // Updated in open_frm
 
673
    if (new_frm_ver >= 3)
 
674
    {
 
675
      keyinfo->flags=      (uint) uint2korr(strpos) ^ HA_NOSAME;
 
676
      keyinfo->key_length= (uint) uint2korr(strpos+2);
 
677
      keyinfo->key_parts=  (uint) strpos[4];
 
678
      keyinfo->algorithm=  (enum ha_key_alg) strpos[5];
 
679
      keyinfo->block_size= uint2korr(strpos+6);
 
680
      strpos+=8;
 
681
    }
 
682
    else
 
683
    {
 
684
      keyinfo->flags=    ((uint) strpos[0]) ^ HA_NOSAME;
 
685
      keyinfo->key_length= (uint) uint2korr(strpos+1);
 
686
      keyinfo->key_parts=  (uint) strpos[3];
 
687
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
688
      strpos+=4;
 
689
    }
 
690
 
 
691
    keyinfo->key_part=   key_part;
 
692
    keyinfo->rec_per_key= rec_per_key;
 
693
    for (j=keyinfo->key_parts ; j-- ; key_part++)
 
694
    {
 
695
      *rec_per_key++=0;
 
696
      key_part->fieldnr=        (uint16) (uint2korr(strpos) & FIELD_NR_MASK);
 
697
      key_part->offset= (uint) uint2korr(strpos+2)-1;
 
698
      key_part->key_type=       (uint) uint2korr(strpos+5);
 
699
      // key_part->field=       (Field*) 0;     // Will be fixed later
 
700
      if (new_frm_ver >= 1)
 
701
      {
 
702
        key_part->key_part_flag= *(strpos+4);
 
703
        key_part->length=       (uint) uint2korr(strpos+7);
 
704
        strpos+=9;
 
705
      }
 
706
      else
 
707
      {
 
708
        key_part->length=       *(strpos+4);
 
709
        key_part->key_part_flag=0;
 
710
        if (key_part->length > 128)
 
711
        {
 
712
          key_part->length&=127;                /* purecov: inspected */
 
713
          key_part->key_part_flag=HA_REVERSE_SORT; /* purecov: inspected */
 
714
        }
 
715
        strpos+=7;
 
716
      }
 
717
      key_part->store_length=key_part->length;
 
718
    }
 
719
  }
 
720
  keynames=(char*) key_part;
 
721
  strpos+= (strmov(keynames, (char *) strpos) - keynames)+1;
 
722
 
 
723
  //reading index comments
 
724
  for (keyinfo= share->key_info, i=0; i < keys; i++, keyinfo++)
 
725
  {
 
726
    if (keyinfo->flags & HA_USES_COMMENT)
 
727
    {
 
728
      keyinfo->comment.length= uint2korr(strpos);
 
729
      keyinfo->comment.str= strmake_root(&share->mem_root, (char*) strpos+2,
 
730
                                         keyinfo->comment.length);
 
731
      strpos+= 2 + keyinfo->comment.length;
 
732
    } 
 
733
    DBUG_ASSERT(test(keyinfo->flags & HA_USES_COMMENT) == 
 
734
               (keyinfo->comment.length > 0));
 
735
  }
 
736
 
 
737
  share->reclength = uint2korr((head+16));
 
738
  if (*(head+26) == 1)
 
739
    share->system= 1;                           /* one-record-database */
 
740
 
 
741
  record_offset= (ulong) (uint2korr(head+6)+
 
742
                          ((uint2korr(head+14) == 0xffff ?
 
743
                            uint4korr(head+47) : uint2korr(head+14))));
 
744
 
 
745
  if ((n_length= uint4korr(head+55)))
 
746
  {
 
747
    /* Read extra data segment */
 
748
    uchar *next_chunk, *buff_end;
 
749
    DBUG_PRINT("info", ("extra segment size is %u bytes", n_length));
 
750
    if (!(next_chunk= buff= (uchar*) my_malloc(n_length, MYF(MY_WME))))
 
751
      goto err;
 
752
    if (my_pread(file, buff, n_length, record_offset + share->reclength,
 
753
                 MYF(MY_NABP)))
 
754
    {
 
755
      goto err;
 
756
    }
 
757
    share->connect_string.length= uint2korr(buff);
 
758
    if (!(share->connect_string.str= strmake_root(&share->mem_root,
 
759
                                                  (char*) next_chunk + 2,
 
760
                                                  share->connect_string.
 
761
                                                  length)))
 
762
    {
 
763
      goto err;
 
764
    }
 
765
    next_chunk+= share->connect_string.length + 2;
 
766
    buff_end= buff + n_length;
 
767
    if (next_chunk + 2 < buff_end)
 
768
    {
 
769
      uint str_db_type_length= uint2korr(next_chunk);
 
770
      LEX_STRING name;
 
771
      name.str= (char*) next_chunk + 2;
 
772
      name.length= str_db_type_length;
 
773
 
 
774
      plugin_ref tmp_plugin= ha_resolve_by_name(thd, &name);
 
775
      if (tmp_plugin != NULL && !plugin_equals(tmp_plugin, share->db_plugin))
 
776
      {
 
777
        if (legacy_db_type > DB_TYPE_UNKNOWN &&
 
778
            legacy_db_type < DB_TYPE_FIRST_DYNAMIC &&
 
779
            legacy_db_type != ha_legacy_type(
 
780
                plugin_data(tmp_plugin, handlerton *)))
 
781
        {
 
782
          /* bad file, legacy_db_type did not match the name */
 
783
          my_free(buff, MYF(0));
 
784
          goto err;
 
785
        }
 
786
        /*
 
787
          tmp_plugin is locked with a local lock.
 
788
          we unlock the old value of share->db_plugin before
 
789
          replacing it with a globally locked version of tmp_plugin
 
790
        */
 
791
        plugin_unlock(NULL, share->db_plugin);
 
792
        share->db_plugin= my_plugin_lock(NULL, &tmp_plugin);
 
793
        DBUG_PRINT("info", ("setting dbtype to '%.*s' (%d)",
 
794
                            str_db_type_length, next_chunk + 2,
 
795
                            ha_legacy_type(share->db_type())));
 
796
      }
 
797
      else if (!tmp_plugin)
 
798
      {
 
799
        /* purecov: begin inspected */
 
800
        error= 8;
 
801
        my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
 
802
        my_free(buff, MYF(0));
 
803
        goto err;
 
804
        /* purecov: end */
 
805
      }
 
806
      next_chunk+= str_db_type_length + 2;
 
807
    }
 
808
#if MYSQL_VERSION_ID < 50200
 
809
    if (share->mysql_version >= 50106 && share->mysql_version <= 50109)
 
810
    {
 
811
      /*
 
812
         Partition state array was here in version 5.1.6 to 5.1.9, this code
 
813
         makes it possible to load a 5.1.6 table in later versions. Can most
 
814
         likely be removed at some point in time. Will only be used for
 
815
         upgrades within 5.1 series of versions. Upgrade to 5.2 can only be
 
816
         done from newer 5.1 versions.
 
817
      */
 
818
      next_chunk+= 4;
 
819
    }
 
820
    else
 
821
#endif
 
822
    if (share->mysql_version >= 50110)
 
823
    {
 
824
      /* New auto_partitioned indicator introduced in 5.1.11 */
 
825
      next_chunk++;
 
826
    }
 
827
    if (forminfo[46] == (uchar)255)
 
828
    {
 
829
      //reading long table comment
 
830
      if (next_chunk + 2 > buff_end)
 
831
      {
 
832
          DBUG_PRINT("error",
 
833
                     ("long table comment is not defined in .frm"));
 
834
          my_free(buff, MYF(0));
 
835
          goto err;
 
836
      }
 
837
      share->comment.length = uint2korr(next_chunk);
 
838
      if (! (share->comment.str= strmake_root(&share->mem_root,
 
839
                               (char*)next_chunk + 2, share->comment.length)))
 
840
      {
 
841
          my_free(buff, MYF(0));
 
842
          goto err;
 
843
      }
 
844
      next_chunk+= 2 + share->comment.length;
 
845
    }
 
846
    DBUG_ASSERT (next_chunk <= buff_end);
 
847
    if (share->mysql_version >= MYSQL_VERSION_TABLESPACE_IN_FRM_CGE)
 
848
    {
 
849
      /*
 
850
       New frm format in mysql_version 5.2.5 (originally in
 
851
       mysql-5.1.22-ndb-6.2.5)
 
852
       New column properties added:
 
853
       COLUMN_FORMAT DYNAMIC|FIXED and STORAGE DISK|MEMORY
 
854
       TABLESPACE name is now stored in frm
 
855
      */
 
856
      if (next_chunk >= buff_end)
 
857
      {
 
858
        if (share->mysql_version >= MYSQL_VERSION_TABLESPACE_IN_FRM)
 
859
        {
 
860
          DBUG_PRINT("error", ("Found no field extra info"));
 
861
          goto err;
 
862
        }
 
863
        DBUG_PRINT("info", ("Found no field extra info"));
 
864
      }
 
865
      else
 
866
      {
 
867
        DBUG_PRINT("info", ("Found field extra info"));
 
868
        const uint format_section_header_size= 8;
 
869
        uint format_section_len= uint2korr(next_chunk+0);
 
870
        uint flags=              uint4korr(next_chunk+2);
 
871
 
 
872
        share->default_storage_media= (enum ha_storage_media) (flags & 0x7);
 
873
 
 
874
        const char *tablespace= (const char*)next_chunk + format_section_header_size;
 
875
        uint tablespace_len= strlen(tablespace);
 
876
        if (tablespace_len != 0) 
 
877
        {
 
878
          share->tablespace= (char *) alloc_root(&share->mem_root,
 
879
                                                 tablespace_len+1);
 
880
          strxmov(share->tablespace, tablespace, NullS);
 
881
        }
 
882
        else
 
883
          share->tablespace= NULL;
 
884
 
 
885
        field_extra_info= next_chunk + format_section_header_size + tablespace_len + 1;
 
886
        next_chunk+= format_section_len;
 
887
      }
 
888
    }
 
889
    DBUG_ASSERT (next_chunk <= buff_end);
 
890
    if (next_chunk > buff_end)
 
891
    {
 
892
      DBUG_PRINT("error", ("Buffer overflow in field extra info"));
 
893
      goto err;
 
894
    }
 
895
  }
 
896
  share->key_block_size= uint2korr(head+62);
 
897
 
 
898
  error=4;
 
899
  extra_rec_buf_length= uint2korr(head+59);
 
900
  rec_buff_length= ALIGN_SIZE(share->reclength + 1 + extra_rec_buf_length);
 
901
  share->rec_buff_length= rec_buff_length;
 
902
  if (!(record= (uchar *) alloc_root(&share->mem_root,
 
903
                                     rec_buff_length)))
 
904
    goto err;                                   /* purecov: inspected */
 
905
  share->default_values= record;
 
906
  if (my_pread(file, record, (size_t) share->reclength,
 
907
               record_offset, MYF(MY_NABP)))
 
908
    goto err;                                   /* purecov: inspected */
 
909
 
 
910
  VOID(my_seek(file,pos+288,MY_SEEK_SET,MYF(0)));
 
911
 
 
912
  share->fields= uint2korr(forminfo+258);
 
913
  pos= uint2korr(forminfo+260);                 /* Length of all screens */
 
914
  n_length= uint2korr(forminfo+268);
 
915
  interval_count= uint2korr(forminfo+270);
 
916
  interval_parts= uint2korr(forminfo+272);
 
917
  int_length= uint2korr(forminfo+274);
 
918
  share->null_fields= uint2korr(forminfo+282);
 
919
  com_length= uint2korr(forminfo+284);
 
920
  if (forminfo[46] != (uchar)255)
 
921
  {
 
922
    share->comment.length=  (int) (forminfo[46]);
 
923
    share->comment.str= strmake_root(&share->mem_root, (char*) forminfo+47,
 
924
                                     share->comment.length);
 
925
  }
 
926
 
 
927
  DBUG_PRINT("info",("i_count: %d  i_parts: %d  index: %d  n_length: %d  int_length: %d  com_length: %d", interval_count,interval_parts, share->keys,n_length,int_length, com_length));
 
928
 
 
929
  if (!(field_ptr = (Field **)
 
930
        alloc_root(&share->mem_root,
 
931
                   (uint) ((share->fields+1)*sizeof(Field*)+
 
932
                           interval_count*sizeof(TYPELIB)+
 
933
                           (share->fields+interval_parts+
 
934
                            keys+3)*sizeof(char *)+
 
935
                           (n_length+int_length+com_length)))))
 
936
    goto err;                                   /* purecov: inspected */
 
937
 
 
938
  share->field= field_ptr;
 
939
  read_length=(uint) (share->fields * field_pack_length +
 
940
                      pos+ (uint) (n_length+int_length+com_length));
 
941
  if (read_string(file,(uchar**) &disk_buff,read_length))
 
942
    goto err;                                   /* purecov: inspected */
 
943
  strpos= disk_buff+pos;
 
944
 
 
945
  share->intervals= (TYPELIB*) (field_ptr+share->fields+1);
 
946
  interval_array= (const char **) (share->intervals+interval_count);
 
947
  names= (char*) (interval_array+share->fields+interval_parts+keys+3);
 
948
  if (!interval_count)
 
949
    share->intervals= 0;                        // For better debugging
 
950
  memcpy((char*) names, strpos+(share->fields*field_pack_length),
 
951
         (uint) (n_length+int_length));
 
952
  comment_pos= names+(n_length+int_length);
 
953
  memcpy(comment_pos, disk_buff+read_length-com_length, com_length);
 
954
 
 
955
  fix_type_pointers(&interval_array, &share->fieldnames, 1, &names);
 
956
  if (share->fieldnames.count != share->fields)
 
957
    goto err;
 
958
  fix_type_pointers(&interval_array, share->intervals, interval_count,
 
959
                    &names);
 
960
 
 
961
  {
 
962
    /* Set ENUM and SET lengths */
 
963
    TYPELIB *interval;
 
964
    for (interval= share->intervals;
 
965
         interval < share->intervals + interval_count;
 
966
         interval++)
 
967
    {
 
968
      uint count= (uint) (interval->count + 1) * sizeof(uint);
 
969
      if (!(interval->type_lengths= (uint *) alloc_root(&share->mem_root,
 
970
                                                        count)))
 
971
        goto err;
 
972
      for (count= 0; count < interval->count; count++)
 
973
      {
 
974
        char *val= (char*) interval->type_names[count];
 
975
        interval->type_lengths[count]= strlen(val);
 
976
      }
 
977
      interval->type_lengths[count]= 0;
 
978
    }
 
979
  }
 
980
 
 
981
  if (keynames)
 
982
    fix_type_pointers(&interval_array, &share->keynames, 1, &keynames);
 
983
 
 
984
 /* Allocate handler */
 
985
  if (!(handler_file= get_new_handler(share, thd->mem_root,
 
986
                                      share->db_type())))
 
987
    goto err;
 
988
 
 
989
  record= share->default_values-1;              /* Fieldstart = 1 */
 
990
  if (share->null_field_first)
 
991
  {
 
992
    null_flags= null_pos= (uchar*) record+1;
 
993
    null_bit_pos= (db_create_options & HA_OPTION_PACK_RECORD) ? 0 : 1;
 
994
    /*
 
995
      null_bytes below is only correct under the condition that
 
996
      there are no bit fields.  Correct values is set below after the
 
997
      table struct is initialized
 
998
    */
 
999
    share->null_bytes= (share->null_fields + null_bit_pos + 7) / 8;
 
1000
  }
 
1001
#ifndef WE_WANT_TO_SUPPORT_VERY_OLD_FRM_FILES
 
1002
  else
 
1003
  {
 
1004
    share->null_bytes= (share->null_fields+7)/8;
 
1005
    null_flags= null_pos= (uchar*) (record + 1 +share->reclength -
 
1006
                                    share->null_bytes);
 
1007
    null_bit_pos= 0;
 
1008
  }
 
1009
#endif
 
1010
 
 
1011
  use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
 
1012
  if (use_hash)
 
1013
    use_hash= !hash_init(&share->name_hash,
 
1014
                         system_charset_info,
 
1015
                         share->fields,0,0,
 
1016
                         (hash_get_key) get_field_name,0,0);
 
1017
 
 
1018
  for (i=0 ; i < share->fields; i++, strpos+=field_pack_length, field_ptr++)
 
1019
  {
 
1020
    uint pack_flag, interval_nr, unireg_type, recpos, field_length;
 
1021
    enum_field_types field_type;
 
1022
    enum ha_storage_media storage_type= HA_SM_DEFAULT;
 
1023
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
 
1024
    CHARSET_INFO *charset=NULL;
 
1025
    LEX_STRING comment;
 
1026
 
 
1027
    if (field_extra_info)
 
1028
    {
 
1029
      char tmp= field_extra_info[i];
 
1030
      storage_type= (enum ha_storage_media)(tmp & STORAGE_TYPE_MASK);
 
1031
      column_format= (enum column_format_type)
 
1032
                    ((tmp >> COLUMN_FORMAT_SHIFT) & COLUMN_FORMAT_MASK);
 
1033
      DBUG_PRINT("info", ("Field extra: storage %u format %u",
 
1034
                          storage_type, column_format));
 
1035
    }
 
1036
    if (new_frm_ver >= 3)
 
1037
    {
 
1038
      /* new frm file in 4.1 */
 
1039
      field_length= uint2korr(strpos+3);
 
1040
      recpos=       uint3korr(strpos+5);
 
1041
      pack_flag=    uint2korr(strpos+8);
 
1042
      unireg_type=  (uint) strpos[10];
 
1043
      interval_nr=  (uint) strpos[12];
 
1044
      uint comment_length=uint2korr(strpos+15);
 
1045
      field_type=(enum_field_types) (uint) strpos[13];
 
1046
 
 
1047
      {
 
1048
        if (!strpos[14])
 
1049
          charset= &my_charset_bin;
 
1050
        else if (!(charset=get_charset((uint) strpos[14], MYF(0))))
 
1051
        {
 
1052
          error= 5; // Unknown or unavailable charset
 
1053
          errarg= (int) strpos[14];
 
1054
          goto err;
 
1055
        }
 
1056
      }
 
1057
      if (!comment_length)
 
1058
      {
 
1059
        comment.str= (char*) "";
 
1060
        comment.length=0;
 
1061
      }
 
1062
      else
 
1063
      {
 
1064
        comment.str=    (char*) comment_pos;
 
1065
        comment.length= comment_length;
 
1066
        comment_pos+=   comment_length;
 
1067
      }
 
1068
    }
 
1069
    else
 
1070
    {
 
1071
      field_length= (uint) strpos[3];
 
1072
      recpos=       uint2korr(strpos+4),
 
1073
      pack_flag=    uint2korr(strpos+6);
 
1074
      pack_flag&=   ~FIELDFLAG_NO_DEFAULT;     // Safety for old files
 
1075
      unireg_type=  (uint) strpos[8];
 
1076
      interval_nr=  (uint) strpos[10];
 
1077
 
 
1078
      /* old frm file */
 
1079
      field_type= (enum_field_types) f_packtype(pack_flag);
 
1080
      if (f_is_binary(pack_flag))
 
1081
      {
 
1082
        /*
 
1083
          Try to choose the best 4.1 type:
 
1084
          - for 4.0 "CHAR(N) BINARY" or "VARCHAR(N) BINARY" 
 
1085
            try to find a binary collation for character set.
 
1086
          - for other types (e.g. BLOB) just use my_charset_bin. 
 
1087
        */
 
1088
        if (!f_is_blob(pack_flag))
 
1089
        {
 
1090
          // 3.23 or 4.0 string
 
1091
          if (!(charset= get_charset_by_csname(share->table_charset->csname,
 
1092
                                               MY_CS_BINSORT, MYF(0))))
 
1093
            charset= &my_charset_bin;
 
1094
        }
 
1095
        else
 
1096
          charset= &my_charset_bin;
 
1097
      }
 
1098
      else
 
1099
        charset= share->table_charset;
 
1100
      bzero((char*) &comment, sizeof(comment));
 
1101
    }
 
1102
 
 
1103
    if (interval_nr && charset->mbminlen > 1)
 
1104
    {
 
1105
      /* Unescape UCS2 intervals from HEX notation */
 
1106
      TYPELIB *interval= share->intervals + interval_nr - 1;
 
1107
      unhex_type2(interval);
 
1108
    }
 
1109
    
 
1110
#ifndef TO_BE_DELETED_ON_PRODUCTION
 
1111
    if (field_type == MYSQL_TYPE_NEWDECIMAL && !share->mysql_version)
 
1112
    {
 
1113
      /*
 
1114
        Fix pack length of old decimal values from 5.0.3 -> 5.0.4
 
1115
        The difference is that in the old version we stored precision
 
1116
        in the .frm table while we now store the display_length
 
1117
      */
 
1118
      uint decimals= f_decimals(pack_flag);
 
1119
      field_length= my_decimal_precision_to_length(field_length,
 
1120
                                                   decimals,
 
1121
                                                   f_is_dec(pack_flag) == 0);
 
1122
      sql_print_error("Found incompatible DECIMAL field '%s' in %s; "
 
1123
                      "Please do \"ALTER TABLE '%s' FORCE\" to fix it!",
 
1124
                      share->fieldnames.type_names[i], share->table_name.str,
 
1125
                      share->table_name.str);
 
1126
      push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
 
1127
                          ER_CRASHED_ON_USAGE,
 
1128
                          "Found incompatible DECIMAL field '%s' in %s; "
 
1129
                          "Please do \"ALTER TABLE '%s' FORCE\" to fix it!",
 
1130
                          share->fieldnames.type_names[i],
 
1131
                          share->table_name.str,
 
1132
                          share->table_name.str);
 
1133
      share->crashed= 1;                        // Marker for CHECK TABLE
 
1134
    }
 
1135
#endif
 
1136
 
 
1137
    *field_ptr= reg_field=
 
1138
      make_field(share, record+recpos,
 
1139
                 (uint32) field_length,
 
1140
                 null_pos, null_bit_pos,
 
1141
                 pack_flag,
 
1142
                 field_type,
 
1143
                 charset,
 
1144
                 (Field::utype) MTYP_TYPENR(unireg_type),
 
1145
                 (interval_nr ?
 
1146
                  share->intervals+interval_nr-1 :
 
1147
                  (TYPELIB*) 0),
 
1148
                 share->fieldnames.type_names[i]);
 
1149
    if (!reg_field)                             // Not supported field type
 
1150
    {
 
1151
      error= 4;
 
1152
      goto err;                 /* purecov: inspected */
 
1153
    }
 
1154
 
 
1155
    reg_field->flags|= ((uint)storage_type << FIELD_STORAGE_FLAGS);
 
1156
    reg_field->flags|= ((uint)column_format << COLUMN_FORMAT_FLAGS);
 
1157
    reg_field->field_index= i;
 
1158
    reg_field->comment=comment;
 
1159
    if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
 
1160
    {
 
1161
      if ((null_bit_pos+= field_length & 7) > 7)
 
1162
      {
 
1163
        null_pos++;
 
1164
        null_bit_pos-= 8;
 
1165
      }
 
1166
    }
 
1167
    if (!(reg_field->flags & NOT_NULL_FLAG))
 
1168
    {
 
1169
      if (!(null_bit_pos= (null_bit_pos + 1) & 7))
 
1170
        null_pos++;
 
1171
    }
 
1172
    if (f_no_default(pack_flag))
 
1173
      reg_field->flags|= NO_DEFAULT_VALUE_FLAG;
 
1174
 
 
1175
    if (reg_field->unireg_check == Field::NEXT_NUMBER)
 
1176
      share->found_next_number_field= field_ptr;
 
1177
    if (share->timestamp_field == reg_field)
 
1178
      share->timestamp_field_offset= i;
 
1179
 
 
1180
    if (use_hash)
 
1181
      (void) my_hash_insert(&share->name_hash,
 
1182
                            (uchar*) field_ptr); // never fail
 
1183
  }
 
1184
  *field_ptr=0;                                 // End marker
 
1185
 
 
1186
  /* Fix key->name and key_part->field */
 
1187
  if (key_parts)
 
1188
  {
 
1189
    uint primary_key=(uint) (find_type((char*) primary_key_name,
 
1190
                                       &share->keynames, 3) - 1);
 
1191
    longlong ha_option= handler_file->ha_table_flags();
 
1192
    keyinfo= share->key_info;
 
1193
    key_part= keyinfo->key_part;
 
1194
 
 
1195
    for (uint key=0 ; key < share->keys ; key++,keyinfo++)
 
1196
    {
 
1197
      uint usable_parts= 0;
 
1198
      keyinfo->name=(char*) share->keynames.type_names[key];
 
1199
 
 
1200
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
 
1201
      {
 
1202
        /*
 
1203
          If the UNIQUE key doesn't have NULL columns and is not a part key
 
1204
          declare this as a primary key.
 
1205
        */
 
1206
        primary_key=key;
 
1207
        for (i=0 ; i < keyinfo->key_parts ;i++)
 
1208
        {
 
1209
          uint fieldnr= key_part[i].fieldnr;
 
1210
          if (!fieldnr ||
 
1211
              share->field[fieldnr-1]->null_ptr ||
 
1212
              share->field[fieldnr-1]->key_length() !=
 
1213
              key_part[i].length)
 
1214
          {
 
1215
            primary_key=MAX_KEY;                // Can't be used
 
1216
            break;
 
1217
          }
 
1218
        }
 
1219
      }
 
1220
 
 
1221
      for (i=0 ; i < keyinfo->key_parts ; key_part++,i++)
 
1222
      {
 
1223
        Field *field;
 
1224
        if (new_field_pack_flag <= 1)
 
1225
          key_part->fieldnr= (uint16) find_field(share->field,
 
1226
                                                 share->default_values,
 
1227
                                                 (uint) key_part->offset,
 
1228
                                                 (uint) key_part->length);
 
1229
        if (!key_part->fieldnr)
 
1230
        {
 
1231
          error= 4;                             // Wrong file
 
1232
          goto err;
 
1233
        }
 
1234
        field= key_part->field= share->field[key_part->fieldnr-1];
 
1235
        key_part->type= field->key_type();
 
1236
        if (field->null_ptr)
 
1237
        {
 
1238
          key_part->null_offset=(uint) ((uchar*) field->null_ptr -
 
1239
                                        share->default_values);
 
1240
          key_part->null_bit= field->null_bit;
 
1241
          key_part->store_length+=HA_KEY_NULL_LENGTH;
 
1242
          keyinfo->flags|=HA_NULL_PART_KEY;
 
1243
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
 
1244
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
 
1245
        }
 
1246
        if (field->type() == MYSQL_TYPE_BLOB ||
 
1247
            field->real_type() == MYSQL_TYPE_VARCHAR)
 
1248
        {
 
1249
          if (field->type() == MYSQL_TYPE_BLOB)
 
1250
            key_part->key_part_flag|= HA_BLOB_PART;
 
1251
          else
 
1252
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
 
1253
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
 
1254
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
 
1255
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
 
1256
          /*
 
1257
            Mark that there may be many matching values for one key
 
1258
            combination ('a', 'a ', 'a  '...)
 
1259
          */
 
1260
          if (!(field->flags & BINARY_FLAG))
 
1261
            keyinfo->flags|= HA_END_SPACE_KEY;
 
1262
        }
 
1263
        if (field->type() == MYSQL_TYPE_BIT)
 
1264
          key_part->key_part_flag|= HA_BIT_PART;
 
1265
 
 
1266
        if (i == 0 && key != primary_key)
 
1267
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
 
1268
                           (keyinfo->key_parts == 1)) ?
 
1269
                           UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
 
1270
        if (i == 0)
 
1271
          field->key_start.set_bit(key);
 
1272
        if (field->key_length() == key_part->length &&
 
1273
            !(field->flags & BLOB_FLAG))
 
1274
        {
 
1275
          if (handler_file->index_flags(key, i, 0) & HA_KEYREAD_ONLY)
 
1276
          {
 
1277
            share->keys_for_keyread.set_bit(key);
 
1278
            field->part_of_key.set_bit(key);
 
1279
            field->part_of_key_not_clustered.set_bit(key);
 
1280
          }
 
1281
          if (handler_file->index_flags(key, i, 1) & HA_READ_ORDER)
 
1282
            field->part_of_sortkey.set_bit(key);
 
1283
        }
 
1284
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
 
1285
            usable_parts == i)
 
1286
          usable_parts++;                       // For FILESORT
 
1287
        field->flags|= PART_KEY_FLAG;
 
1288
        if (key == primary_key)
 
1289
        {
 
1290
          field->flags|= PRI_KEY_FLAG;
 
1291
          /*
 
1292
            If this field is part of the primary key and all keys contains
 
1293
            the primary key, then we can use any key to find this column
 
1294
          */
 
1295
          if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
 
1296
          {
 
1297
            field->part_of_key= share->keys_in_use;
 
1298
            if (field->part_of_sortkey.is_set(key))
 
1299
              field->part_of_sortkey= share->keys_in_use;
 
1300
          }
 
1301
        }
 
1302
        if (field->key_length() != key_part->length)
 
1303
        {
 
1304
#ifndef TO_BE_DELETED_ON_PRODUCTION
 
1305
          if (field->type() == MYSQL_TYPE_NEWDECIMAL)
 
1306
          {
 
1307
            /*
 
1308
              Fix a fatal error in decimal key handling that causes crashes
 
1309
              on Innodb. We fix it by reducing the key length so that
 
1310
              InnoDB never gets a too big key when searching.
 
1311
              This allows the end user to do an ALTER TABLE to fix the
 
1312
              error.
 
1313
            */
 
1314
            keyinfo->key_length-= (key_part->length - field->key_length());
 
1315
            key_part->store_length-= (uint16)(key_part->length -
 
1316
                                              field->key_length());
 
1317
            key_part->length= (uint16)field->key_length();
 
1318
            sql_print_error("Found wrong key definition in %s; "
 
1319
                            "Please do \"ALTER TABLE '%s' FORCE \" to fix it!",
 
1320
                            share->table_name.str,
 
1321
                            share->table_name.str);
 
1322
            push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
 
1323
                                ER_CRASHED_ON_USAGE,
 
1324
                                "Found wrong key definition in %s; "
 
1325
                                "Please do \"ALTER TABLE '%s' FORCE\" to fix "
 
1326
                                "it!",
 
1327
                                share->table_name.str,
 
1328
                                share->table_name.str);
 
1329
            share->crashed= 1;                // Marker for CHECK TABLE
 
1330
            continue;
 
1331
          }
 
1332
#endif
 
1333
          key_part->key_part_flag|= HA_PART_KEY_SEG;
 
1334
        }
 
1335
      }
 
1336
      keyinfo->usable_key_parts= usable_parts; // Filesort
 
1337
 
 
1338
      set_if_bigger(share->max_key_length,keyinfo->key_length+
 
1339
                    keyinfo->key_parts);
 
1340
      share->total_key_length+= keyinfo->key_length;
 
1341
      /*
 
1342
        MERGE tables do not have unique indexes. But every key could be
 
1343
        an unique index on the underlying MyISAM table. (Bug #10400)
 
1344
      */
 
1345
      if ((keyinfo->flags & HA_NOSAME) ||
 
1346
          (ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
 
1347
        set_if_bigger(share->max_unique_length,keyinfo->key_length);
 
1348
    }
 
1349
    if (primary_key < MAX_KEY &&
 
1350
        (share->keys_in_use.is_set(primary_key)))
 
1351
    {
 
1352
      share->primary_key= primary_key;
 
1353
      /*
 
1354
        If we are using an integer as the primary key then allow the user to
 
1355
        refer to it as '_rowid'
 
1356
      */
 
1357
      if (share->key_info[primary_key].key_parts == 1)
 
1358
      {
 
1359
        Field *field= share->key_info[primary_key].key_part[0].field;
 
1360
        if (field && field->result_type() == INT_RESULT)
 
1361
        {
 
1362
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
 
1363
          share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
 
1364
                                      fieldnr);
 
1365
        }
 
1366
      }
 
1367
    }
 
1368
    else
 
1369
      share->primary_key = MAX_KEY; // we do not have a primary key
 
1370
  }
 
1371
  else
 
1372
    share->primary_key= MAX_KEY;
 
1373
  x_free((uchar*) disk_buff);
 
1374
  disk_buff=0;
 
1375
  if (new_field_pack_flag <= 1)
 
1376
  {
 
1377
    /* Old file format with default as not null */
 
1378
    uint null_length= (share->null_fields+7)/8;
 
1379
    bfill(share->default_values + (null_flags - (uchar*) record),
 
1380
          null_length, 255);
 
1381
  }
 
1382
 
 
1383
  if (share->found_next_number_field)
 
1384
  {
 
1385
    reg_field= *share->found_next_number_field;
 
1386
    if ((int) (share->next_number_index= (uint)
 
1387
               find_ref_key(share->key_info, share->keys,
 
1388
                            share->default_values, reg_field,
 
1389
                            &share->next_number_key_offset,
 
1390
                            &share->next_number_keypart)) < 0)
 
1391
    {
 
1392
      /* Wrong field definition */
 
1393
      error= 4;
 
1394
      goto err;
 
1395
    }
 
1396
    else
 
1397
      reg_field->flags |= AUTO_INCREMENT_FLAG;
 
1398
  }
 
1399
 
 
1400
  if (share->blob_fields)
 
1401
  {
 
1402
    Field **ptr;
 
1403
    uint k, *save;
 
1404
 
 
1405
    /* Store offsets to blob fields to find them fast */
 
1406
    if (!(share->blob_field= save=
 
1407
          (uint*) alloc_root(&share->mem_root,
 
1408
                             (uint) (share->blob_fields* sizeof(uint)))))
 
1409
      goto err;
 
1410
    for (k=0, ptr= share->field ; *ptr ; ptr++, k++)
 
1411
    {
 
1412
      if ((*ptr)->flags & BLOB_FLAG)
 
1413
        (*save++)= k;
 
1414
    }
 
1415
  }
 
1416
 
 
1417
  /*
 
1418
    the correct null_bytes can now be set, since bitfields have been taken
 
1419
    into account
 
1420
  */
 
1421
  share->null_bytes= (null_pos - (uchar*) null_flags +
 
1422
                      (null_bit_pos + 7) / 8);
 
1423
  share->last_null_bit_pos= null_bit_pos;
 
1424
 
 
1425
  share->db_low_byte_first= handler_file->low_byte_first();
 
1426
  share->column_bitmap_size= bitmap_buffer_size(share->fields);
 
1427
 
 
1428
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
 
1429
                                             share->column_bitmap_size)))
 
1430
    goto err;
 
1431
  bitmap_init(&share->all_set, bitmaps, share->fields, FALSE);
 
1432
  bitmap_set_all(&share->all_set);
 
1433
 
 
1434
  delete handler_file;
 
1435
#ifndef DBUG_OFF
 
1436
  if (use_hash)
 
1437
    (void) hash_check(&share->name_hash);
 
1438
#endif
 
1439
  if (buff)
 
1440
    my_free(buff, MYF(0));
 
1441
  DBUG_RETURN (0);
 
1442
 
 
1443
 err:
 
1444
  if (buff)
 
1445
    my_free(buff, MYF(0));
 
1446
  share->error= error;
 
1447
  share->open_errno= my_errno;
 
1448
  share->errarg= errarg;
 
1449
  x_free((uchar*) disk_buff);
 
1450
  delete crypted;
 
1451
  delete handler_file;
 
1452
  hash_free(&share->name_hash);
 
1453
 
 
1454
  open_table_error(share, error, share->open_errno, errarg);
 
1455
  DBUG_RETURN(error);
 
1456
} /* open_binary_frm */
 
1457
 
 
1458
 
 
1459
/*
 
1460
  Open a table based on a TABLE_SHARE
 
1461
 
 
1462
  SYNOPSIS
 
1463
    open_table_from_share()
 
1464
    thd                 Thread handler
 
1465
    share               Table definition
 
1466
    alias               Alias for table
 
1467
    db_stat             open flags (for example HA_OPEN_KEYFILE|
 
1468
                        HA_OPEN_RNDFILE..) can be 0 (example in
 
1469
                        ha_example_table)
 
1470
    prgflag             READ_ALL etc..
 
1471
    ha_open_flags       HA_OPEN_ABORT_IF_LOCKED etc..
 
1472
    outparam            result table
 
1473
    open_mode           One of OTM_OPEN|OTM_CREATE|OTM_ALTER
 
1474
                        if OTM_CREATE some errors are ignore
 
1475
                        if OTM_ALTER HA_OPEN is not called
 
1476
 
 
1477
  RETURN VALUES
 
1478
   0    ok
 
1479
   1    Error (see open_table_error)
 
1480
   2    Error (see open_table_error)
 
1481
   3    Wrong data in .frm file
 
1482
   4    Error (see open_table_error)
 
1483
   5    Error (see open_table_error: charset unavailable)
 
1484
   7    Table definition has changed in engine
 
1485
*/
 
1486
 
 
1487
int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
 
1488
                          uint db_stat, uint prgflag, uint ha_open_flags,
 
1489
                          TABLE *outparam, open_table_mode open_mode)
 
1490
{
 
1491
  int error;
 
1492
  uint records, i, bitmap_size;
 
1493
  bool error_reported= FALSE;
 
1494
  uchar *record, *bitmaps;
 
1495
  Field **field_ptr;
 
1496
  DBUG_ENTER("open_table_from_share");
 
1497
  DBUG_PRINT("enter",("name: '%s.%s'  form: 0x%lx, open mode:%s",
 
1498
                      share->db.str,
 
1499
                      share->table_name.str,
 
1500
                      (long) outparam,
 
1501
                      (open_mode == OTM_OPEN)?"open":
 
1502
                      ((open_mode == OTM_CREATE)?"create":"alter")));
 
1503
 
 
1504
  /* Parsing of partitioning information from .frm needs thd->lex set up. */
 
1505
  DBUG_ASSERT(thd->lex->is_lex_started);
 
1506
 
 
1507
  error= 1;
 
1508
  bzero((char*) outparam, sizeof(*outparam));
 
1509
  outparam->in_use= thd;
 
1510
  outparam->s= share;
 
1511
  outparam->db_stat= db_stat;
 
1512
  outparam->write_row_record= NULL;
 
1513
 
 
1514
  init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
1515
 
 
1516
  if (!(outparam->alias= my_strdup(alias, MYF(MY_WME))))
 
1517
    goto err;
 
1518
  outparam->quick_keys.init();
 
1519
  outparam->covering_keys.init();
 
1520
  outparam->keys_in_use_for_query.init();
 
1521
 
 
1522
  /* Allocate handler */
 
1523
  outparam->file= 0;
 
1524
  if (!(prgflag & OPEN_FRM_FILE_ONLY))
 
1525
  {
 
1526
    if (!(outparam->file= get_new_handler(share, &outparam->mem_root,
 
1527
                                          share->db_type())))
 
1528
      goto err;
 
1529
  }
 
1530
  else
 
1531
  {
 
1532
    DBUG_ASSERT(!db_stat);
 
1533
  }
 
1534
 
 
1535
  error= 4;
 
1536
  outparam->reginfo.lock_type= TL_UNLOCK;
 
1537
  outparam->current_lock= F_UNLCK;
 
1538
  records=0;
 
1539
  if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
 
1540
    records=1;
 
1541
  if (prgflag & (READ_ALL+EXTRA_RECORD))
 
1542
    records++;
 
1543
 
 
1544
  if (!(record= (uchar*) alloc_root(&outparam->mem_root,
 
1545
                                   share->rec_buff_length * records)))
 
1546
    goto err;                                   /* purecov: inspected */
 
1547
 
 
1548
  if (records == 0)
 
1549
  {
 
1550
    /* We are probably in hard repair, and the buffers should not be used */
 
1551
    outparam->record[0]= outparam->record[1]= share->default_values;
 
1552
  }
 
1553
  else
 
1554
  {
 
1555
    outparam->record[0]= record;
 
1556
    if (records > 1)
 
1557
      outparam->record[1]= record+ share->rec_buff_length;
 
1558
    else
 
1559
      outparam->record[1]= outparam->record[0];   // Safety
 
1560
  }
 
1561
 
 
1562
#ifdef HAVE_purify
 
1563
  /*
 
1564
    We need this because when we read var-length rows, we are not updating
 
1565
    bytes after end of varchar
 
1566
  */
 
1567
  if (records > 1)
 
1568
  {
 
1569
    memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
 
1570
    memcpy(outparam->record[1], share->default_values, share->null_bytes);
 
1571
    if (records > 2)
 
1572
      memcpy(outparam->record[1], share->default_values,
 
1573
             share->rec_buff_length);
 
1574
  }
 
1575
#endif
 
1576
 
 
1577
  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
 
1578
                                          (uint) ((share->fields+1)*
 
1579
                                                  sizeof(Field*)))))
 
1580
    goto err;                                   /* purecov: inspected */
 
1581
 
 
1582
  outparam->field= field_ptr;
 
1583
 
 
1584
  record= (uchar*) outparam->record[0]-1;       /* Fieldstart = 1 */
 
1585
  if (share->null_field_first)
 
1586
    outparam->null_flags= (uchar*) record+1;
 
1587
  else
 
1588
    outparam->null_flags= (uchar*) (record+ 1+ share->reclength -
 
1589
                                    share->null_bytes);
 
1590
 
 
1591
  /* Setup copy of fields from share, but use the right alias and record */
 
1592
  for (i=0 ; i < share->fields; i++, field_ptr++)
 
1593
  {
 
1594
    if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
 
1595
      goto err;
 
1596
  }
 
1597
  (*field_ptr)= 0;                              // End marker
 
1598
 
 
1599
  if (share->found_next_number_field)
 
1600
    outparam->found_next_number_field=
 
1601
      outparam->field[(uint) (share->found_next_number_field - share->field)];
 
1602
  if (share->timestamp_field)
 
1603
    outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
 
1604
 
 
1605
 
 
1606
  /* Fix key->name and key_part->field */
 
1607
  if (share->key_parts)
 
1608
  {
 
1609
    KEY *key_info, *key_info_end;
 
1610
    KEY_PART_INFO *key_part;
 
1611
    uint n_length;
 
1612
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
 
1613
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
 
1614
      goto err;
 
1615
    outparam->key_info= key_info;
 
1616
    key_part= (my_reinterpret_cast(KEY_PART_INFO*) (key_info+share->keys));
 
1617
    
 
1618
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
 
1619
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
 
1620
                                                   share->key_parts));
 
1621
 
 
1622
    for (key_info_end= key_info + share->keys ;
 
1623
         key_info < key_info_end ;
 
1624
         key_info++)
 
1625
    {
 
1626
      KEY_PART_INFO *key_part_end;
 
1627
 
 
1628
      key_info->table= outparam;
 
1629
      key_info->key_part= key_part;
 
1630
 
 
1631
      for (key_part_end= key_part+ key_info->key_parts ;
 
1632
           key_part < key_part_end ;
 
1633
           key_part++)
 
1634
      {
 
1635
        Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
 
1636
 
 
1637
        if (field->key_length() != key_part->length &&
 
1638
            !(field->flags & BLOB_FLAG))
 
1639
        {
 
1640
          /*
 
1641
            We are using only a prefix of the column as a key:
 
1642
            Create a new field for the key part that matches the index
 
1643
          */
 
1644
          field= key_part->field=field->new_field(&outparam->mem_root,
 
1645
                                                  outparam, 0);
 
1646
          field->field_length= key_part->length;
 
1647
        }
 
1648
      }
 
1649
    }
 
1650
  }
 
1651
 
 
1652
  /* Allocate bitmaps */
 
1653
 
 
1654
  bitmap_size= share->column_bitmap_size;
 
1655
  if (!(bitmaps= (uchar*) alloc_root(&outparam->mem_root, bitmap_size*3)))
 
1656
    goto err;
 
1657
  bitmap_init(&outparam->def_read_set,
 
1658
              (my_bitmap_map*) bitmaps, share->fields, FALSE);
 
1659
  bitmap_init(&outparam->def_write_set,
 
1660
              (my_bitmap_map*) (bitmaps+bitmap_size), share->fields, FALSE);
 
1661
  bitmap_init(&outparam->tmp_set,
 
1662
              (my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, FALSE);
 
1663
  outparam->default_column_bitmaps();
 
1664
 
 
1665
  /* The table struct is now initialized;  Open the table */
 
1666
  error= 2;
 
1667
  if (db_stat && open_mode != OTM_ALTER)
 
1668
  {
 
1669
    int ha_err;
 
1670
    if ((ha_err= (outparam->file->
 
1671
                  ha_open(outparam, share->normalized_path.str,
 
1672
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
 
1673
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
 
1674
                           ((db_stat & HA_WAIT_IF_LOCKED) ||
 
1675
                            (specialflag & SPECIAL_WAIT_IF_LOCKED)) ?
 
1676
                           HA_OPEN_WAIT_IF_LOCKED :
 
1677
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
 
1678
                          HA_OPEN_ABORT_IF_LOCKED :
 
1679
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
 
1680
    {
 
1681
      /* Set a flag if the table is crashed and it can be auto. repaired */
 
1682
      share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
 
1683
                       outparam->file->auto_repair() &&
 
1684
                       !(ha_open_flags & HA_OPEN_FOR_REPAIR));
 
1685
 
 
1686
      switch (ha_err)
 
1687
      {
 
1688
        case HA_ERR_NO_SUCH_TABLE:
 
1689
          /*
 
1690
            The table did not exists in storage engine, use same error message
 
1691
            as if the .frm file didn't exist
 
1692
          */
 
1693
          error= 1;
 
1694
          my_errno= ENOENT;
 
1695
          break;
 
1696
        case EMFILE:
 
1697
          /*
 
1698
            Too many files opened, use same error message as if the .frm
 
1699
            file can't open
 
1700
           */
 
1701
          DBUG_PRINT("error", ("open file: %s failed, too many files opened (errno: %d)", 
 
1702
                  share->normalized_path.str, ha_err));
 
1703
          error= 1;
 
1704
          my_errno= EMFILE;
 
1705
          break;
 
1706
        default:
 
1707
          outparam->file->print_error(ha_err, MYF(0));
 
1708
          error_reported= TRUE;
 
1709
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
 
1710
            error= 7;
 
1711
          break;
 
1712
      }
 
1713
      goto err;                                 /* purecov: inspected */
 
1714
    }
 
1715
  }
 
1716
 
 
1717
#if defined(HAVE_purify) && !defined(DBUG_OFF)
 
1718
  bzero((char*) bitmaps, bitmap_size*3);
 
1719
#endif
 
1720
 
 
1721
  outparam->no_replicate= outparam->file &&
 
1722
                          test(outparam->file->ha_table_flags() &
 
1723
                               HA_HAS_OWN_BINLOGGING);
 
1724
  thd->status_var.opened_tables++;
 
1725
 
 
1726
  DBUG_RETURN (0);
 
1727
 
 
1728
 err:
 
1729
  if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
 
1730
    open_table_error(share, error, my_errno, 0);
 
1731
  delete outparam->file;
 
1732
  outparam->file= 0;                            // For easier error checking
 
1733
  outparam->db_stat=0;
 
1734
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on bzero'd root
 
1735
  my_free((char*) outparam->alias, MYF(MY_ALLOW_ZERO_PTR));
 
1736
  DBUG_RETURN (error);
 
1737
}
 
1738
 
 
1739
 
 
1740
/*
 
1741
  Free information allocated by openfrm
 
1742
 
 
1743
  SYNOPSIS
 
1744
    closefrm()
 
1745
    table               TABLE object to free
 
1746
    free_share          Is 1 if we also want to free table_share
 
1747
*/
 
1748
 
 
1749
int closefrm(register TABLE *table, bool free_share)
 
1750
{
 
1751
  int error=0;
 
1752
  DBUG_ENTER("closefrm");
 
1753
  DBUG_PRINT("enter", ("table: 0x%lx", (long) table));
 
1754
 
 
1755
  if (table->db_stat)
 
1756
    error=table->file->close();
 
1757
  my_free((char*) table->alias, MYF(MY_ALLOW_ZERO_PTR));
 
1758
  table->alias= 0;
 
1759
  if (table->field)
 
1760
  {
 
1761
    for (Field **ptr=table->field ; *ptr ; ptr++)
89
1762
      delete *ptr;
90
 
    }
91
 
    field= 0;
 
1763
    table->field= 0;
92
1764
  }
93
 
  delete cursor;
94
 
  cursor= 0;                            /* For easier errorchecking */
95
 
 
 
1765
  delete table->file;
 
1766
  table->file= 0;                               /* For easier errorchecking */
96
1767
  if (free_share)
97
1768
  {
98
 
    release();
 
1769
    if (table->s->tmp_table == NO_TMP_TABLE)
 
1770
      release_table_share(table->s, RELEASE_NORMAL);
 
1771
    else
 
1772
      free_table_share(table->s);
99
1773
  }
100
 
 
101
 
  return error;
102
 
}
103
 
 
104
 
Table::~Table()
105
 
{
106
 
  mem_root.free_root(MYF(0));
107
 
}
108
 
 
109
 
 
110
 
void Table::resetTable(Session *session,
111
 
                       TableShare *share,
112
 
                       uint32_t db_stat_arg)
113
 
{
114
 
  setShare(share);
115
 
  in_use= session;
116
 
 
117
 
  field= NULL;
118
 
 
119
 
  cursor= NULL;
120
 
  next= NULL;
121
 
  prev= NULL;
122
 
 
123
 
  read_set= NULL;
124
 
  write_set= NULL;
125
 
 
126
 
  tablenr= 0;
127
 
  db_stat= db_stat_arg;
128
 
 
129
 
  record[0]= (unsigned char *) NULL;
130
 
  record[1]= (unsigned char *) NULL;
131
 
 
132
 
  insert_values.clear();
133
 
  key_info= NULL;
134
 
  next_number_field= NULL;
135
 
  found_next_number_field= NULL;
136
 
  timestamp_field= NULL;
137
 
 
138
 
  pos_in_table_list= NULL;
139
 
  group= NULL;
140
 
  _alias.clear();
141
 
  null_flags= NULL;
142
 
 
143
 
  lock_position= 0;
144
 
  lock_data_start= 0;
145
 
  lock_count= 0;
146
 
  used_fields= 0;
147
 
  status= 0;
148
 
  derived_select_number= 0;
149
 
  current_lock= F_UNLCK;
150
 
  copy_blobs= false;
151
 
 
152
 
  maybe_null= false;
153
 
 
154
 
  null_row= false;
155
 
 
156
 
  force_index= false;
157
 
  distinct= false;
158
 
  const_table= false;
159
 
  no_rows= false;
160
 
  key_read= false;
161
 
  no_keyread= false;
162
 
 
163
 
  open_placeholder= false;
164
 
  locked_by_name= false;
165
 
  no_cache= false;
166
 
 
167
 
  auto_increment_field_not_null= false;
168
 
  alias_name_used= false;
169
 
 
170
 
  query_id= 0;
171
 
  quick_condition_rows= 0;
172
 
 
173
 
  timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
174
 
  map= 0;
175
 
 
176
 
  reginfo.reset();
177
 
 
178
 
  covering_keys.reset();
179
 
 
180
 
  quick_keys.reset();
181
 
  merge_keys.reset();
182
 
 
183
 
  keys_in_use_for_query.reset();
184
 
  keys_in_use_for_group_by.reset();
185
 
  keys_in_use_for_order_by.reset();
186
 
 
187
 
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
188
 
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
189
 
 
190
 
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
191
 
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
192
 
 
193
 
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
194
 
}
195
 
 
 
1774
  free_root(&table->mem_root, MYF(0));
 
1775
  DBUG_RETURN(error);
 
1776
}
196
1777
 
197
1778
 
198
1779
/* Deallocate temporary blob storage */
199
1780
 
200
 
void free_blobs(register Table *table)
 
1781
void free_blobs(register TABLE *table)
201
1782
{
202
 
  uint32_t *ptr, *end;
203
 
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
 
1783
  uint *ptr, *end;
 
1784
  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
204
1785
       ptr != end ;
205
1786
       ptr++)
206
 
  {
207
 
    ((Field_blob*) table->getField(*ptr))->free();
208
 
  }
209
 
}
210
 
 
211
 
 
212
 
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
213
 
{
214
 
  TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
 
1787
    ((Field_blob*) table->field[*ptr])->free();
 
1788
}
 
1789
 
 
1790
 
 
1791
        /* Find where a form starts */
 
1792
        /* if formname is NullS then only formnames is read */
 
1793
 
 
1794
ulong get_form_pos(File file, uchar *head, TYPELIB *save_names)
 
1795
{
 
1796
  uint a_length,names,length;
 
1797
  uchar *pos,*buf;
 
1798
  ulong ret_value=0;
 
1799
  DBUG_ENTER("get_form_pos");
 
1800
 
 
1801
  names=uint2korr(head+8);
 
1802
  a_length=(names+2)*sizeof(char *);            /* Room for two extra */
 
1803
 
 
1804
  if (!save_names)
 
1805
    a_length=0;
 
1806
  else
 
1807
    save_names->type_names=0;                   /* Clear if error */
 
1808
 
 
1809
  if (names)
 
1810
  {
 
1811
    length=uint2korr(head+4);
 
1812
    VOID(my_seek(file,64L,MY_SEEK_SET,MYF(0)));
 
1813
    if (!(buf= (uchar*) my_malloc((size_t) length+a_length+names*4,
 
1814
                                  MYF(MY_WME))) ||
 
1815
        my_read(file, buf+a_length, (size_t) (length+names*4),
 
1816
                MYF(MY_NABP)))
 
1817
    {                                           /* purecov: inspected */
 
1818
      x_free((uchar*) buf);                     /* purecov: inspected */
 
1819
      DBUG_RETURN(0L);                          /* purecov: inspected */
 
1820
    }
 
1821
    pos= buf+a_length+length;
 
1822
    ret_value=uint4korr(pos);
 
1823
  }
 
1824
  if (! save_names)
 
1825
  {
 
1826
    if (names)
 
1827
      my_free((uchar*) buf,MYF(0));
 
1828
  }
 
1829
  else if (!names)
 
1830
    bzero((char*) save_names,sizeof(save_names));
 
1831
  else
 
1832
  {
 
1833
    char *str;
 
1834
    str=(char *) (buf+a_length);
 
1835
    fix_type_pointers((const char ***) &buf,save_names,1,&str);
 
1836
  }
 
1837
  DBUG_RETURN(ret_value);
 
1838
}
 
1839
 
 
1840
 
 
1841
/*
 
1842
  Read string from a file with malloc
 
1843
 
 
1844
  NOTES:
 
1845
    We add an \0 at end of the read string to make reading of C strings easier
 
1846
*/
 
1847
 
 
1848
int read_string(File file, uchar**to, size_t length)
 
1849
{
 
1850
  DBUG_ENTER("read_string");
 
1851
 
 
1852
  x_free(*to);
 
1853
  if (!(*to= (uchar*) my_malloc(length+1,MYF(MY_WME))) ||
 
1854
      my_read(file, *to, length,MYF(MY_NABP)))
 
1855
  {
 
1856
    x_free(*to);                              /* purecov: inspected */
 
1857
    *to= 0;                                   /* purecov: inspected */
 
1858
    DBUG_RETURN(1);                           /* purecov: inspected */
 
1859
  }
 
1860
  *((char*) *to+length)= '\0';
 
1861
  DBUG_RETURN (0);
 
1862
} /* read_string */
 
1863
 
 
1864
 
 
1865
        /* Add a new form to a form file */
 
1866
 
 
1867
ulong make_new_entry(File file, uchar *fileinfo, TYPELIB *formnames,
 
1868
                     const char *newname)
 
1869
{
 
1870
  uint i,bufflength,maxlength,n_length,length,names;
 
1871
  ulong endpos,newpos;
 
1872
  uchar buff[IO_SIZE];
 
1873
  uchar *pos;
 
1874
  DBUG_ENTER("make_new_entry");
 
1875
 
 
1876
  length=(uint) strlen(newname)+1;
 
1877
  n_length=uint2korr(fileinfo+4);
 
1878
  maxlength=uint2korr(fileinfo+6);
 
1879
  names=uint2korr(fileinfo+8);
 
1880
  newpos=uint4korr(fileinfo+10);
 
1881
 
 
1882
  if (64+length+n_length+(names+1)*4 > maxlength)
 
1883
  {                                             /* Expand file */
 
1884
    newpos+=IO_SIZE;
 
1885
    int4store(fileinfo+10,newpos);
 
1886
    endpos=(ulong) my_seek(file,0L,MY_SEEK_END,MYF(0));/* Copy from file-end */
 
1887
    bufflength= (uint) (endpos & (IO_SIZE-1));  /* IO_SIZE is a power of 2 */
 
1888
 
 
1889
    while (endpos > maxlength)
 
1890
    {
 
1891
      VOID(my_seek(file,(ulong) (endpos-bufflength),MY_SEEK_SET,MYF(0)));
 
1892
      if (my_read(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
 
1893
        DBUG_RETURN(0L);
 
1894
      VOID(my_seek(file,(ulong) (endpos-bufflength+IO_SIZE),MY_SEEK_SET,
 
1895
                   MYF(0)));
 
1896
      if ((my_write(file, buff,bufflength,MYF(MY_NABP+MY_WME))))
 
1897
        DBUG_RETURN(0);
 
1898
      endpos-=bufflength; bufflength=IO_SIZE;
 
1899
    }
 
1900
    bzero(buff,IO_SIZE);                        /* Null new block */
 
1901
    VOID(my_seek(file,(ulong) maxlength,MY_SEEK_SET,MYF(0)));
 
1902
    if (my_write(file,buff,bufflength,MYF(MY_NABP+MY_WME)))
 
1903
        DBUG_RETURN(0L);
 
1904
    maxlength+=IO_SIZE;                         /* Fix old ref */
 
1905
    int2store(fileinfo+6,maxlength);
 
1906
    for (i=names, pos= (uchar*) *formnames->type_names+n_length-1; i-- ;
 
1907
         pos+=4)
 
1908
    {
 
1909
      endpos=uint4korr(pos)+IO_SIZE;
 
1910
      int4store(pos,endpos);
 
1911
    }
 
1912
  }
 
1913
 
 
1914
  if (n_length == 1 )
 
1915
  {                                             /* First name */
 
1916
    length++;
 
1917
    VOID(strxmov((char*) buff,"/",newname,"/",NullS));
 
1918
  }
 
1919
  else
 
1920
    VOID(strxmov((char*) buff,newname,"/",NullS)); /* purecov: inspected */
 
1921
  VOID(my_seek(file,63L+(ulong) n_length,MY_SEEK_SET,MYF(0)));
 
1922
  if (my_write(file, buff, (size_t) length+1,MYF(MY_NABP+MY_WME)) ||
 
1923
      (names && my_write(file,(uchar*) (*formnames->type_names+n_length-1),
 
1924
                         names*4, MYF(MY_NABP+MY_WME))) ||
 
1925
      my_write(file, fileinfo+10, 4,MYF(MY_NABP+MY_WME)))
 
1926
    DBUG_RETURN(0L); /* purecov: inspected */
 
1927
 
 
1928
  int2store(fileinfo+8,names+1);
 
1929
  int2store(fileinfo+4,n_length+length);
 
1930
  VOID(my_chsize(file, newpos, 0, MYF(MY_WME)));/* Append file with '\0' */
 
1931
  DBUG_RETURN(newpos);
 
1932
} /* make_new_entry */
 
1933
 
 
1934
 
 
1935
        /* error message when opening a form file */
 
1936
 
 
1937
void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
 
1938
{
 
1939
  int err_no;
 
1940
  char buff[FN_REFLEN];
 
1941
  myf errortype= ME_ERROR+ME_WAITTANG;
 
1942
  DBUG_ENTER("open_table_error");
 
1943
 
 
1944
  switch (error) {
 
1945
  case 7:
 
1946
  case 1:
 
1947
    if (db_errno == ENOENT)
 
1948
      my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
 
1949
    else
 
1950
    {
 
1951
      strxmov(buff, share->normalized_path.str, reg_ext, NullS);
 
1952
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
 
1953
               errortype, buff, db_errno);
 
1954
    }
 
1955
    break;
 
1956
  case 2:
 
1957
  {
 
1958
    handler *file= 0;
 
1959
    const char *datext= "";
 
1960
    
 
1961
    if (share->db_type() != NULL)
 
1962
    {
 
1963
      if ((file= get_new_handler(share, current_thd->mem_root,
 
1964
                                 share->db_type())))
 
1965
      {
 
1966
        if (!(datext= *file->bas_ext()))
 
1967
          datext= "";
 
1968
      }
 
1969
    }
 
1970
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
 
1971
      ER_FILE_USED : ER_CANT_OPEN_FILE;
 
1972
    strxmov(buff, share->normalized_path.str, datext, NullS);
 
1973
    my_error(err_no,errortype, buff, db_errno);
 
1974
    delete file;
 
1975
    break;
 
1976
  }
 
1977
  case 5:
 
1978
  {
 
1979
    const char *csname= get_charset_name((uint) errarg);
 
1980
    char tmp[10];
 
1981
    if (!csname || csname[0] =='?')
 
1982
    {
 
1983
      my_snprintf(tmp, sizeof(tmp), "#%d", errarg);
 
1984
      csname= tmp;
 
1985
    }
 
1986
    my_printf_error(ER_UNKNOWN_COLLATION,
 
1987
                    "Unknown collation '%s' in table '%-.64s' definition", 
 
1988
                    MYF(0), csname, share->table_name.str);
 
1989
    break;
 
1990
  }
 
1991
  case 6:
 
1992
    strxmov(buff, share->normalized_path.str, reg_ext, NullS);
 
1993
    my_printf_error(ER_NOT_FORM_FILE,
 
1994
                    "Table '%-.64s' was created with a different version "
 
1995
                    "of MySQL and cannot be read", 
 
1996
                    MYF(0), buff);
 
1997
    break;
 
1998
  case 8:
 
1999
    break;
 
2000
  default:                              /* Better wrong error than none */
 
2001
  case 4:
 
2002
    strxmov(buff, share->normalized_path.str, reg_ext, NullS);
 
2003
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
 
2004
    break;
 
2005
  }
 
2006
  DBUG_VOID_RETURN;
 
2007
} /* open_table_error */
 
2008
 
 
2009
 
 
2010
        /*
 
2011
        ** fix a str_type to a array type
 
2012
        ** typeparts separated with some char. differents types are separated
 
2013
        ** with a '\0'
 
2014
        */
 
2015
 
 
2016
static void
 
2017
fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint types,
 
2018
                  char **names)
 
2019
{
 
2020
  char *type_name, *ptr;
 
2021
  char chr;
 
2022
 
 
2023
  ptr= *names;
 
2024
  while (types--)
 
2025
  {
 
2026
    point_to_type->name=0;
 
2027
    point_to_type->type_names= *array;
 
2028
 
 
2029
    if ((chr= *ptr))                    /* Test if empty type */
 
2030
    {
 
2031
      while ((type_name=strchr(ptr+1,chr)) != NullS)
 
2032
      {
 
2033
        *((*array)++) = ptr+1;
 
2034
        *type_name= '\0';               /* End string */
 
2035
        ptr=type_name;
 
2036
      }
 
2037
      ptr+=2;                           /* Skip end mark and last 0 */
 
2038
    }
 
2039
    else
 
2040
      ptr++;
 
2041
    point_to_type->count= (uint) (*array - point_to_type->type_names);
 
2042
    point_to_type++;
 
2043
    *((*array)++)= NullS;               /* End of type */
 
2044
  }
 
2045
  *names=ptr;                           /* Update end */
 
2046
  return;
 
2047
} /* fix_type_pointers */
 
2048
 
 
2049
 
 
2050
TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
 
2051
{
 
2052
  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
215
2053
  if (!result)
216
2054
    return 0;
217
 
  result->count= strings.elements;
218
 
  result->name= "";
219
 
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
220
 
  
221
 
  if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
 
2055
  result->count=strings.elements;
 
2056
  result->name="";
 
2057
  uint nbytes= (sizeof(char*) + sizeof(uint)) * (result->count + 1);
 
2058
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
222
2059
    return 0;
223
 
    
224
2060
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
225
 
 
226
2061
  List_iterator<String> it(strings);
227
2062
  String *tmp;
228
 
  for (uint32_t i= 0; (tmp= it++); i++)
 
2063
  for (uint i=0; (tmp=it++) ; i++)
229
2064
  {
230
2065
    result->type_names[i]= tmp->ptr();
231
2066
    result->type_lengths[i]= tmp->length();
232
2067
  }
233
 
 
234
 
  result->type_names[result->count]= 0;   // End marker
 
2068
  result->type_names[result->count]= 0;         // End marker
235
2069
  result->type_lengths[result->count]= 0;
236
 
 
237
2070
  return result;
238
2071
}
239
2072
 
 
2073
 
 
2074
/*
 
2075
 Search after a field with given start & length
 
2076
 If an exact field isn't found, return longest field with starts
 
2077
 at right position.
 
2078
 
 
2079
 NOTES
 
2080
   This is needed because in some .frm fields 'fieldnr' was saved wrong
 
2081
 
 
2082
 RETURN
 
2083
   0  error
 
2084
   #  field number +1
 
2085
*/
 
2086
 
 
2087
static uint find_field(Field **fields, uchar *record, uint start, uint length)
 
2088
{
 
2089
  Field **field;
 
2090
  uint i, pos;
 
2091
 
 
2092
  pos= 0;
 
2093
  for (field= fields, i=1 ; *field ; i++,field++)
 
2094
  {
 
2095
    if ((*field)->offset(record) == start)
 
2096
    {
 
2097
      if ((*field)->key_length() == length)
 
2098
        return (i);
 
2099
      if (!pos || fields[pos-1]->pack_length() <
 
2100
          (*field)->pack_length())
 
2101
        pos= i;
 
2102
    }
 
2103
  }
 
2104
  return (pos);
 
2105
}
 
2106
 
 
2107
 
240
2108
        /* Check that the integer is in the internal */
241
2109
 
242
2110
int set_zone(register int nr, int min_zone, int max_zone)
248
2116
  return (nr);
249
2117
} /* set_zone */
250
2118
 
 
2119
        /* Adjust number to next larger disk buffer */
 
2120
 
 
2121
ulong next_io_size(register ulong pos)
 
2122
{
 
2123
  register ulong offset;
 
2124
  if ((offset= pos & (IO_SIZE-1)))
 
2125
    return pos-offset+IO_SIZE;
 
2126
  return pos;
 
2127
} /* next_io_size */
 
2128
 
251
2129
 
252
2130
/*
253
2131
  Store an SQL quoted string.
254
2132
 
255
 
  SYNOPSIS
 
2133
  SYNOPSIS  
256
2134
    append_unescaped()
257
2135
    res         result String
258
2136
    pos         string to be quoted
263
2141
    May fail with some multibyte charsets though.
264
2142
*/
265
2143
 
266
 
void append_unescaped(String *res, const char *pos, uint32_t length)
 
2144
void append_unescaped(String *res, const char *pos, uint length)
267
2145
{
268
2146
  const char *end= pos+length;
269
2147
  res->append('\'');
270
2148
 
271
2149
  for (; pos != end ; pos++)
272
2150
  {
273
 
    uint32_t mblen;
 
2151
#if defined(USE_MB) && MYSQL_VERSION_ID < 40100
 
2152
    uint mblen;
274
2153
    if (use_mb(default_charset_info) &&
275
2154
        (mblen= my_ismbchar(default_charset_info, pos, end)))
276
2155
    {
277
2156
      res->append(pos, mblen);
278
 
      pos+= mblen - 1;
279
 
      if (pos >= end)
280
 
        break;
 
2157
      pos+= mblen;
281
2158
      continue;
282
2159
    }
 
2160
#endif
283
2161
 
284
2162
    switch (*pos) {
285
2163
    case 0:                             /* Must be escaped for 'mysql' */
311
2189
}
312
2190
 
313
2191
 
314
 
int rename_file_ext(const char * from,const char * to,const char * ext)
315
 
{
316
 
  string from_s, to_s;
317
 
 
318
 
  from_s.append(from);
319
 
  from_s.append(ext);
320
 
  to_s.append(to);
321
 
  to_s.append(ext);
322
 
  return (internal::my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
 
2192
        /* Create a .frm file */
 
2193
 
 
2194
File create_frm(THD *thd, const char *name, const char *db,
 
2195
                const char *table, uint reclength, uchar *fileinfo,
 
2196
                HA_CREATE_INFO *create_info, uint keys, KEY *key_info)
 
2197
{
 
2198
  register File file;
 
2199
  ulong length;
 
2200
  uchar fill[IO_SIZE];
 
2201
  int create_flags= O_RDWR | O_TRUNC;
 
2202
  ulong key_comment_total_bytes= 0;
 
2203
  uint i;
 
2204
 
 
2205
  if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
 
2206
    create_flags|= O_EXCL | O_NOFOLLOW;
 
2207
 
 
2208
  /* Fix this when we have new .frm files;  Current limit is 4G rows (QQ) */
 
2209
  if (create_info->max_rows > UINT_MAX32)
 
2210
    create_info->max_rows= UINT_MAX32;
 
2211
  if (create_info->min_rows > UINT_MAX32)
 
2212
    create_info->min_rows= UINT_MAX32;
 
2213
 
 
2214
  if ((file= my_create(name, CREATE_MODE, create_flags, MYF(0))) >= 0)
 
2215
  {
 
2216
    uint key_length, tmp_key_length;
 
2217
    uint tmp;
 
2218
    bzero((char*) fileinfo,64);
 
2219
    /* header */
 
2220
    fileinfo[0]=(uchar) 254;
 
2221
    fileinfo[1]= 1;
 
2222
    fileinfo[2]= FRM_VER+3+ test(create_info->varchar);
 
2223
 
 
2224
    fileinfo[3]= (uchar) ha_legacy_type(
 
2225
          ha_checktype(thd,ha_legacy_type(create_info->db_type),0,0));
 
2226
    fileinfo[4]=1;
 
2227
    int2store(fileinfo+6,IO_SIZE);              /* Next block starts here */
 
2228
    for (i= 0; i < keys; i++)
 
2229
    {
 
2230
      DBUG_ASSERT(test(key_info[i].flags & HA_USES_COMMENT) == 
 
2231
                 (key_info[i].comment.length > 0));
 
2232
      if (key_info[i].flags & HA_USES_COMMENT)
 
2233
        key_comment_total_bytes += 2 + key_info[i].comment.length;
 
2234
    }
 
2235
    /*
 
2236
      Keep in sync with pack_keys() in unireg.cc
 
2237
      For each key:
 
2238
      8 bytes for the key header
 
2239
      9 bytes for each key-part (MAX_REF_PARTS)
 
2240
      NAME_LEN bytes for the name
 
2241
      1 byte for the NAMES_SEP_CHAR (before the name)
 
2242
      For all keys:
 
2243
      6 bytes for the header
 
2244
      1 byte for the NAMES_SEP_CHAR (after the last name)
 
2245
      9 extra bytes (padding for safety? alignment?)
 
2246
      comments
 
2247
    */
 
2248
    key_length= (keys * (8 + MAX_REF_PARTS * 9 + NAME_LEN + 1) + 16 +
 
2249
                 key_comment_total_bytes);
 
2250
    length= next_io_size((ulong) (IO_SIZE+key_length+reclength+
 
2251
                                  create_info->extra_size));
 
2252
    int4store(fileinfo+10,length);
 
2253
    tmp_key_length= (key_length < 0xffff) ? key_length : 0xffff;
 
2254
    int2store(fileinfo+14,tmp_key_length);
 
2255
    int2store(fileinfo+16,reclength);
 
2256
    int4store(fileinfo+18,create_info->max_rows);
 
2257
    int4store(fileinfo+22,create_info->min_rows);
 
2258
    /* fileinfo[26] is set in mysql_create_frm() */
 
2259
    fileinfo[27]=2;                             // Use long pack-fields
 
2260
    /* fileinfo[28 & 29] is set to key_info_length in mysql_create_frm() */
 
2261
    create_info->table_options|=HA_OPTION_LONG_BLOB_PTR; // Use portable blob pointers
 
2262
    int2store(fileinfo+30,create_info->table_options);
 
2263
    fileinfo[32]=0;                             // No filename anymore
 
2264
    fileinfo[33]=5;                             // Mark for 5.0 frm file
 
2265
    int4store(fileinfo+34,create_info->avg_row_length);
 
2266
    fileinfo[38]= (create_info->default_table_charset ?
 
2267
                   create_info->default_table_charset->number : 0);
 
2268
    fileinfo[39]= (uchar) ((uint) create_info->transactional |
 
2269
                           ((uint) create_info->page_checksum << 2));
 
2270
    fileinfo[40]= (uchar) create_info->row_type;
 
2271
    /* Next few bytes where for RAID support */
 
2272
    fileinfo[41]= 0;
 
2273
    fileinfo[42]= 0;
 
2274
    fileinfo[43]= 0;
 
2275
    fileinfo[44]= 0;
 
2276
    fileinfo[45]= 0;
 
2277
    fileinfo[46]= 0;
 
2278
    int4store(fileinfo+47, key_length);
 
2279
    tmp= MYSQL_VERSION_ID;          // Store to avoid warning from int4store
 
2280
    int4store(fileinfo+51, tmp);
 
2281
    int4store(fileinfo+55, create_info->extra_size);
 
2282
    /*
 
2283
      59-60 is reserved for extra_rec_buf_length,
 
2284
      61 for default_part_db_type
 
2285
    */
 
2286
    int2store(fileinfo+62, create_info->key_block_size);
 
2287
    bzero(fill,IO_SIZE);
 
2288
    for (; length > IO_SIZE ; length-= IO_SIZE)
 
2289
    {
 
2290
      if (my_write(file,fill, IO_SIZE, MYF(MY_WME | MY_NABP)))
 
2291
      {
 
2292
        VOID(my_close(file,MYF(0)));
 
2293
        VOID(my_delete(name,MYF(0)));
 
2294
        return(-1);
 
2295
      }
 
2296
    }
 
2297
  }
 
2298
  else
 
2299
  {
 
2300
    if (my_errno == ENOENT)
 
2301
      my_error(ER_BAD_DB_ERROR,MYF(0),db);
 
2302
    else
 
2303
      my_error(ER_CANT_CREATE_TABLE,MYF(0),table,my_errno);
 
2304
  }
 
2305
  return (file);
 
2306
} /* create_frm */
 
2307
 
 
2308
 
 
2309
void update_create_info_from_table(HA_CREATE_INFO *create_info, TABLE *table)
 
2310
{
 
2311
  TABLE_SHARE *share= table->s;
 
2312
  DBUG_ENTER("update_create_info_from_table");
 
2313
 
 
2314
  create_info->max_rows= share->max_rows;
 
2315
  create_info->min_rows= share->min_rows;
 
2316
  create_info->table_options= share->db_create_options;
 
2317
  create_info->avg_row_length= share->avg_row_length;
 
2318
  create_info->row_type= share->row_type;
 
2319
  create_info->default_storage_media= share->default_storage_media;
 
2320
  create_info->tablespace= share->tablespace;
 
2321
  create_info->default_table_charset= share->table_charset;
 
2322
  create_info->table_charset= 0;
 
2323
  create_info->comment= share->comment;
 
2324
 
 
2325
  DBUG_VOID_RETURN;
 
2326
}
 
2327
 
 
2328
int
 
2329
rename_file_ext(const char * from,const char * to,const char * ext)
 
2330
{
 
2331
  char from_b[FN_REFLEN],to_b[FN_REFLEN];
 
2332
  VOID(strxmov(from_b,from,ext,NullS));
 
2333
  VOID(strxmov(to_b,to,ext,NullS));
 
2334
  return (my_rename(from_b,to_b,MYF(MY_WME)));
 
2335
}
 
2336
 
 
2337
 
 
2338
/*
 
2339
  Allocate string field in MEM_ROOT and return it as String
 
2340
 
 
2341
  SYNOPSIS
 
2342
    get_field()
 
2343
    mem         MEM_ROOT for allocating
 
2344
    field       Field for retrieving of string
 
2345
    res         result String
 
2346
 
 
2347
  RETURN VALUES
 
2348
    1   string is empty
 
2349
    0   all ok
 
2350
*/
 
2351
 
 
2352
bool get_field(MEM_ROOT *mem, Field *field, String *res)
 
2353
{
 
2354
  char buff[MAX_FIELD_WIDTH], *to;
 
2355
  String str(buff,sizeof(buff),&my_charset_bin);
 
2356
  uint length;
 
2357
 
 
2358
  field->val_str(&str);
 
2359
  if (!(length= str.length()))
 
2360
  {
 
2361
    res->length(0);
 
2362
    return 1;
 
2363
  }
 
2364
  if (!(to= strmake_root(mem, str.ptr(), length)))
 
2365
    length= 0;                                  // Safety fix
 
2366
  res->set(to, length, ((Field_str*)field)->charset());
 
2367
  return 0;
 
2368
}
 
2369
 
 
2370
 
 
2371
/*
 
2372
  Allocate string field in MEM_ROOT and return it as NULL-terminated string
 
2373
 
 
2374
  SYNOPSIS
 
2375
    get_field()
 
2376
    mem         MEM_ROOT for allocating
 
2377
    field       Field for retrieving of string
 
2378
 
 
2379
  RETURN VALUES
 
2380
    NullS  string is empty
 
2381
    #      pointer to NULL-terminated string value of field
 
2382
*/
 
2383
 
 
2384
char *get_field(MEM_ROOT *mem, Field *field)
 
2385
{
 
2386
  char buff[MAX_FIELD_WIDTH], *to;
 
2387
  String str(buff,sizeof(buff),&my_charset_bin);
 
2388
  uint length;
 
2389
 
 
2390
  field->val_str(&str);
 
2391
  length= str.length();
 
2392
  if (!length || !(to= (char*) alloc_root(mem,length+1)))
 
2393
    return NullS;
 
2394
  memcpy(to,str.ptr(),(uint) length);
 
2395
  to[length]=0;
 
2396
  return to;
 
2397
}
 
2398
 
 
2399
/*
 
2400
  DESCRIPTION
 
2401
    given a buffer with a key value, and a map of keyparts
 
2402
    that are present in this value, returns the length of the value
 
2403
*/
 
2404
uint calculate_key_len(TABLE *table, uint key, const uchar *buf,
 
2405
                       key_part_map keypart_map)
 
2406
{
 
2407
  /* works only with key prefixes */
 
2408
  DBUG_ASSERT(((keypart_map + 1) & keypart_map) == 0);
 
2409
 
 
2410
  KEY *key_info= table->s->key_info+key;
 
2411
  KEY_PART_INFO *key_part= key_info->key_part;
 
2412
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
 
2413
  uint length= 0;
 
2414
 
 
2415
  while (key_part < end_key_part && keypart_map)
 
2416
  {
 
2417
    length+= key_part->store_length;
 
2418
    keypart_map >>= 1;
 
2419
    key_part++;
 
2420
  }
 
2421
  return length;
323
2422
}
324
2423
 
325
2424
/*
329
2428
    check_db_name()
330
2429
    org_name            Name of database and length
331
2430
 
 
2431
  NOTES
 
2432
    If lower_case_table_names is set then database is converted to lower case
 
2433
 
332
2434
  RETURN
333
 
    false error
334
 
    true ok
 
2435
    0   ok
 
2436
    1   error
335
2437
*/
336
2438
 
337
 
bool check_db_name(Session *session, identifier::Schema &schema_identifier)
 
2439
bool check_db_name(LEX_STRING *org_name)
338
2440
{
339
 
  if (not plugin::Authorization::isAuthorized(session->user(), schema_identifier))
340
 
  {
341
 
    return false;
342
 
  }
343
 
 
344
 
  return schema_identifier.isValid();
 
2441
  char *name= org_name->str;
 
2442
  uint name_length= org_name->length;
 
2443
 
 
2444
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
 
2445
    return 1;
 
2446
 
 
2447
  if (lower_case_table_names && name != any_db)
 
2448
    my_casedn_str(files_charset_info, name);
 
2449
 
 
2450
  return check_identifier_name(org_name);
345
2451
}
346
2452
 
 
2453
 
347
2454
/*
348
2455
  Allow anything as a table name, as long as it doesn't contain an
349
2456
  ' ' at the end
350
2457
  returns 1 on error
351
2458
*/
352
 
bool check_table_name(const char *name, uint32_t length)
 
2459
 
 
2460
 
 
2461
bool check_table_name(const char *name, uint length)
353
2462
{
354
2463
  if (!length || length > NAME_LEN || name[length - 1] == ' ')
355
2464
    return 1;
367
2476
*/
368
2477
bool check_column_name(const char *name)
369
2478
{
370
 
  uint32_t name_length= 0;  // name length in symbols
371
 
  bool last_char_is_space= true;
372
 
 
 
2479
  uint name_length= 0;  // name length in symbols
 
2480
  bool last_char_is_space= TRUE;
 
2481
  
373
2482
  while (*name)
374
2483
  {
 
2484
#if defined(USE_MB) && defined(USE_MB_IDENT)
375
2485
    last_char_is_space= my_isspace(system_charset_info, *name);
376
2486
    if (use_mb(system_charset_info))
377
2487
    {
378
 
      int len=my_ismbchar(system_charset_info, name,
 
2488
      int len=my_ismbchar(system_charset_info, name, 
379
2489
                          name+system_charset_info->mbmaxlen);
380
2490
      if (len)
381
2491
      {
386
2496
        continue;
387
2497
      }
388
2498
    }
 
2499
#else
 
2500
    last_char_is_space= *name==' ';
 
2501
#endif
389
2502
    /*
390
2503
      NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
391
2504
      It is defined as 0xFF, which is a not valid byte in utf8.
392
2505
      This assert is to catch use of this byte if we decide to
393
2506
      use non-utf8 as system_character_set.
394
2507
    */
395
 
    assert(*name != NAMES_SEP_CHAR);
 
2508
    DBUG_ASSERT(*name != NAMES_SEP_CHAR);
396
2509
    name++;
397
2510
    name_length++;
398
2511
  }
399
2512
  /* Error if empty or too long column name */
400
 
  return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
401
 
}
402
 
 
 
2513
  return last_char_is_space || (uint) name_length > NAME_CHAR_LEN;
 
2514
}
 
2515
 
 
2516
 
 
2517
/**
 
2518
  Checks whether a table is intact. Should be done *just* after the table has
 
2519
  been opened.
 
2520
 
 
2521
  @param[in] table             The table to check
 
2522
  @param[in] table_f_count     Expected number of columns in the table
 
2523
  @param[in] table_def         Expected structure of the table (column name
 
2524
                               and type)
 
2525
 
 
2526
  @retval  FALSE  OK
 
2527
  @retval  TRUE   There was an error. An error message is output
 
2528
                  to the error log.  We do not push an error
 
2529
                  message into the error stack because this
 
2530
                  function is currently only called at start up,
 
2531
                  and such errors never reach the user.
 
2532
*/
 
2533
 
 
2534
my_bool
 
2535
table_check_intact(TABLE *table, const uint table_f_count,
 
2536
                   const TABLE_FIELD_W_TYPE *table_def)
 
2537
{
 
2538
  uint i;
 
2539
  my_bool error= FALSE;
 
2540
  my_bool fields_diff_count;
 
2541
  DBUG_ENTER("table_check_intact");
 
2542
  DBUG_PRINT("info",("table: %s  expected_count: %d",
 
2543
                     table->alias, table_f_count));
 
2544
 
 
2545
  fields_diff_count= (table->s->fields != table_f_count);
 
2546
  if (fields_diff_count)
 
2547
  {
 
2548
    DBUG_PRINT("info", ("Column count has changed, checking the definition"));
 
2549
 
 
2550
    /* previous MySQL version */
 
2551
    if (MYSQL_VERSION_ID > table->s->mysql_version)
 
2552
    {
 
2553
      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
 
2554
                      table->alias, table_f_count, table->s->fields,
 
2555
                      table->s->mysql_version, MYSQL_VERSION_ID);
 
2556
      DBUG_RETURN(TRUE);
 
2557
    }
 
2558
    else if (MYSQL_VERSION_ID == table->s->mysql_version)
 
2559
    {
 
2560
      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), table->alias,
 
2561
                      table_f_count, table->s->fields);
 
2562
      DBUG_RETURN(TRUE);
 
2563
    }
 
2564
    /*
 
2565
      Something has definitely changed, but we're running an older
 
2566
      version of MySQL with new system tables.
 
2567
      Let's check column definitions. If a column was added at
 
2568
      the end of the table, then we don't care much since such change
 
2569
      is backward compatible.
 
2570
    */
 
2571
  }
 
2572
  char buffer[STRING_BUFFER_USUAL_SIZE];
 
2573
  for (i=0 ; i < table_f_count; i++, table_def++)
 
2574
  {
 
2575
    String sql_type(buffer, sizeof(buffer), system_charset_info);
 
2576
    sql_type.length(0);
 
2577
    if (i < table->s->fields)
 
2578
    {
 
2579
      Field *field= table->field[i];
 
2580
 
 
2581
      if (strncmp(field->field_name, table_def->name.str,
 
2582
                  table_def->name.length))
 
2583
      {
 
2584
        /*
 
2585
          Name changes are not fatal, we use ordinal numbers to access columns.
 
2586
          Still this can be a sign of a tampered table, output an error
 
2587
          to the error log.
 
2588
        */
 
2589
        sql_print_error("Incorrect definition of table %s.%s: "
 
2590
                        "expected column '%s' at position %d, found '%s'.",
 
2591
                        table->s->db.str, table->alias, table_def->name.str, i,
 
2592
                        field->field_name);
 
2593
      }
 
2594
      field->sql_type(sql_type);
 
2595
      /*
 
2596
        Generally, if column types don't match, then something is
 
2597
        wrong.
 
2598
 
 
2599
        However, we only compare column definitions up to the
 
2600
        length of the original definition, since we consider the
 
2601
        following definitions compatible:
 
2602
 
 
2603
        1. DATETIME and DATETIM
 
2604
        2. INT(11) and INT(11
 
2605
        3. SET('one', 'two') and SET('one', 'two', 'more')
 
2606
 
 
2607
        For SETs or ENUMs, if the same prefix is there it's OK to
 
2608
        add more elements - they will get higher ordinal numbers and
 
2609
        the new table definition is backward compatible with the
 
2610
        original one.
 
2611
       */
 
2612
      if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
 
2613
                  table_def->type.length - 1))
 
2614
      {
 
2615
        sql_print_error("Incorrect definition of table %s.%s: "
 
2616
                        "expected column '%s' at position %d to have type "
 
2617
                        "%s, found type %s.", table->s->db.str, table->alias,
 
2618
                        table_def->name.str, i, table_def->type.str,
 
2619
                        sql_type.c_ptr_safe());
 
2620
        error= TRUE;
 
2621
      }
 
2622
      else if (table_def->cset.str && !field->has_charset())
 
2623
      {
 
2624
        sql_print_error("Incorrect definition of table %s.%s: "
 
2625
                        "expected the type of column '%s' at position %d "
 
2626
                        "to have character set '%s' but the type has no "
 
2627
                        "character set.", table->s->db.str, table->alias,
 
2628
                        table_def->name.str, i, table_def->cset.str);
 
2629
        error= TRUE;
 
2630
      }
 
2631
      else if (table_def->cset.str &&
 
2632
               strcmp(field->charset()->csname, table_def->cset.str))
 
2633
      {
 
2634
        sql_print_error("Incorrect definition of table %s.%s: "
 
2635
                        "expected the type of column '%s' at position %d "
 
2636
                        "to have character set '%s' but found "
 
2637
                        "character set '%s'.", table->s->db.str, table->alias,
 
2638
                        table_def->name.str, i, table_def->cset.str,
 
2639
                        field->charset()->csname);
 
2640
        error= TRUE;
 
2641
      }
 
2642
    }
 
2643
    else
 
2644
    {
 
2645
      sql_print_error("Incorrect definition of table %s.%s: "
 
2646
                      "expected column '%s' at position %d to have type %s "
 
2647
                      " but the column is not found.",
 
2648
                      table->s->db.str, table->alias,
 
2649
                      table_def->name.str, i, table_def->type.str);
 
2650
      error= TRUE;
 
2651
    }
 
2652
  }
 
2653
  DBUG_RETURN(error);
 
2654
}
 
2655
 
 
2656
 
 
2657
/*
 
2658
  Create Item_field for each column in the table.
 
2659
 
 
2660
  SYNPOSIS
 
2661
    st_table::fill_item_list()
 
2662
      item_list          a pointer to an empty list used to store items
 
2663
 
 
2664
  DESCRIPTION
 
2665
    Create Item_field object for each column in the table and
 
2666
    initialize it with the corresponding Field. New items are
 
2667
    created in the current THD memory root.
 
2668
 
 
2669
  RETURN VALUE
 
2670
    0                    success
 
2671
    1                    out of memory
 
2672
*/
 
2673
 
 
2674
bool st_table::fill_item_list(List<Item> *item_list) const
 
2675
{
 
2676
  /*
 
2677
    All Item_field's created using a direct pointer to a field
 
2678
    are fixed in Item_field constructor.
 
2679
  */
 
2680
  for (Field **ptr= field; *ptr; ptr++)
 
2681
  {
 
2682
    Item_field *item= new Item_field(*ptr);
 
2683
    if (!item || item_list->push_back(item))
 
2684
      return TRUE;
 
2685
  }
 
2686
  return FALSE;
 
2687
}
 
2688
 
 
2689
/*
 
2690
  Reset an existing list of Item_field items to point to the
 
2691
  Fields of this table.
 
2692
 
 
2693
  SYNPOSIS
 
2694
    st_table::fill_item_list()
 
2695
      item_list          a non-empty list with Item_fields
 
2696
 
 
2697
  DESCRIPTION
 
2698
    This is a counterpart of fill_item_list used to redirect
 
2699
    Item_fields to the fields of a newly created table.
 
2700
    The caller must ensure that number of items in the item_list
 
2701
    is the same as the number of columns in the table.
 
2702
*/
 
2703
 
 
2704
void st_table::reset_item_list(List<Item> *item_list) const
 
2705
{
 
2706
  List_iterator_fast<Item> it(*item_list);
 
2707
  for (Field **ptr= field; *ptr; ptr++)
 
2708
  {
 
2709
    Item_field *item_field= (Item_field*) it++;
 
2710
    DBUG_ASSERT(item_field != 0);
 
2711
    item_field->reset_field(*ptr);
 
2712
  }
 
2713
}
 
2714
 
 
2715
 
 
2716
/*
 
2717
  Merge ON expressions for a view
 
2718
 
 
2719
  SYNOPSIS
 
2720
    merge_on_conds()
 
2721
    thd             thread handle
 
2722
    table           table for the VIEW
 
2723
    is_cascaded     TRUE <=> merge ON expressions from underlying views
 
2724
 
 
2725
  DESCRIPTION
 
2726
    This function returns the result of ANDing the ON expressions
 
2727
    of the given view and all underlying views. The ON expressions
 
2728
    of the underlying views are added only if is_cascaded is TRUE.
 
2729
 
 
2730
  RETURN
 
2731
    Pointer to the built expression if there is any.
 
2732
    Otherwise and in the case of a failure NULL is returned.
 
2733
*/
 
2734
 
 
2735
static Item *
 
2736
merge_on_conds(THD *thd, TABLE_LIST *table, bool is_cascaded)
 
2737
{
 
2738
  DBUG_ENTER("merge_on_conds");
 
2739
 
 
2740
  Item *cond= NULL;
 
2741
  DBUG_PRINT("info", ("alias: %s", table->alias));
 
2742
  if (table->on_expr)
 
2743
    cond= table->on_expr->copy_andor_structure(thd);
 
2744
  if (!table->nested_join)
 
2745
    DBUG_RETURN(cond);
 
2746
  List_iterator<TABLE_LIST> li(table->nested_join->join_list);
 
2747
  while (TABLE_LIST *tbl= li++)
 
2748
  {
 
2749
    cond= and_conds(cond, merge_on_conds(thd, tbl, is_cascaded));
 
2750
  }
 
2751
  DBUG_RETURN(cond);
 
2752
}
 
2753
 
 
2754
 
 
2755
/*
 
2756
  Find underlying base tables (TABLE_LIST) which represent given
 
2757
  table_to_find (TABLE)
 
2758
 
 
2759
  SYNOPSIS
 
2760
    TABLE_LIST::find_underlying_table()
 
2761
    table_to_find table to find
 
2762
 
 
2763
  RETURN
 
2764
    0  table is not found
 
2765
    found table reference
 
2766
*/
 
2767
 
 
2768
TABLE_LIST *TABLE_LIST::find_underlying_table(TABLE *table_to_find)
 
2769
{
 
2770
  /* is this real table and table which we are looking for? */
 
2771
  if (table == table_to_find && merge_underlying_list == 0)
 
2772
    return this;
 
2773
 
 
2774
  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
 
2775
  {
 
2776
    TABLE_LIST *result;
 
2777
    if ((result= tbl->find_underlying_table(table_to_find)))
 
2778
      return result;
 
2779
  }
 
2780
  return 0;
 
2781
}
 
2782
 
 
2783
/*
 
2784
  cleunup items belonged to view fields translation table
 
2785
 
 
2786
  SYNOPSIS
 
2787
    TABLE_LIST::cleanup_items()
 
2788
*/
 
2789
 
 
2790
void TABLE_LIST::cleanup_items()
 
2791
{
 
2792
  if (!field_translation)
 
2793
    return;
 
2794
 
 
2795
  for (Field_translator *transl= field_translation;
 
2796
       transl < field_translation_end;
 
2797
       transl++)
 
2798
    transl->item->walk(&Item::cleanup_processor, 0, 0);
 
2799
}
 
2800
 
 
2801
 
 
2802
/*
 
2803
  Set insert_values buffer
 
2804
 
 
2805
  SYNOPSIS
 
2806
    set_insert_values()
 
2807
    mem_root   memory pool for allocating
 
2808
 
 
2809
  RETURN
 
2810
    FALSE - OK
 
2811
    TRUE  - out of memory
 
2812
*/
 
2813
 
 
2814
bool TABLE_LIST::set_insert_values(MEM_ROOT *mem_root)
 
2815
{
 
2816
  if (table)
 
2817
  {
 
2818
    if (!table->insert_values &&
 
2819
        !(table->insert_values= (uchar *)alloc_root(mem_root,
 
2820
                                                   table->s->rec_buff_length)))
 
2821
      return TRUE;
 
2822
  }
 
2823
 
 
2824
  return FALSE;
 
2825
}
 
2826
 
 
2827
 
 
2828
/*
 
2829
  Test if this is a leaf with respect to name resolution.
 
2830
 
 
2831
  SYNOPSIS
 
2832
    TABLE_LIST::is_leaf_for_name_resolution()
 
2833
 
 
2834
  DESCRIPTION
 
2835
    A table reference is a leaf with respect to name resolution if
 
2836
    it is either a leaf node in a nested join tree (table, view,
 
2837
    schema table, subquery), or an inner node that represents a
 
2838
    NATURAL/USING join, or a nested join with materialized join
 
2839
    columns.
 
2840
 
 
2841
  RETURN
 
2842
    TRUE if a leaf, FALSE otherwise.
 
2843
*/
 
2844
bool TABLE_LIST::is_leaf_for_name_resolution()
 
2845
{
 
2846
  return (is_natural_join || is_join_columns_complete || !nested_join);
 
2847
}
 
2848
 
 
2849
 
 
2850
/*
 
2851
  Retrieve the first (left-most) leaf in a nested join tree with
 
2852
  respect to name resolution.
 
2853
 
 
2854
  SYNOPSIS
 
2855
    TABLE_LIST::first_leaf_for_name_resolution()
 
2856
 
 
2857
  DESCRIPTION
 
2858
    Given that 'this' is a nested table reference, recursively walk
 
2859
    down the left-most children of 'this' until we reach a leaf
 
2860
    table reference with respect to name resolution.
 
2861
 
 
2862
  IMPLEMENTATION
 
2863
    The left-most child of a nested table reference is the last element
 
2864
    in the list of children because the children are inserted in
 
2865
    reverse order.
 
2866
 
 
2867
  RETURN
 
2868
    If 'this' is a nested table reference - the left-most child of
 
2869
      the tree rooted in 'this',
 
2870
    else return 'this'
 
2871
*/
 
2872
 
 
2873
TABLE_LIST *TABLE_LIST::first_leaf_for_name_resolution()
 
2874
{
 
2875
  TABLE_LIST *cur_table_ref;
 
2876
  NESTED_JOIN *cur_nested_join;
 
2877
 
 
2878
  if (is_leaf_for_name_resolution())
 
2879
    return this;
 
2880
  DBUG_ASSERT(nested_join);
 
2881
 
 
2882
  for (cur_nested_join= nested_join;
 
2883
       cur_nested_join;
 
2884
       cur_nested_join= cur_table_ref->nested_join)
 
2885
  {
 
2886
    List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
 
2887
    cur_table_ref= it++;
 
2888
    /*
 
2889
      If the current nested join is a RIGHT JOIN, the operands in
 
2890
      'join_list' are in reverse order, thus the first operand is
 
2891
      already at the front of the list. Otherwise the first operand
 
2892
      is in the end of the list of join operands.
 
2893
    */
 
2894
    if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
 
2895
    {
 
2896
      TABLE_LIST *next;
 
2897
      while ((next= it++))
 
2898
        cur_table_ref= next;
 
2899
    }
 
2900
    if (cur_table_ref->is_leaf_for_name_resolution())
 
2901
      break;
 
2902
  }
 
2903
  return cur_table_ref;
 
2904
}
 
2905
 
 
2906
 
 
2907
/*
 
2908
  Retrieve the last (right-most) leaf in a nested join tree with
 
2909
  respect to name resolution.
 
2910
 
 
2911
  SYNOPSIS
 
2912
    TABLE_LIST::last_leaf_for_name_resolution()
 
2913
 
 
2914
  DESCRIPTION
 
2915
    Given that 'this' is a nested table reference, recursively walk
 
2916
    down the right-most children of 'this' until we reach a leaf
 
2917
    table reference with respect to name resolution.
 
2918
 
 
2919
  IMPLEMENTATION
 
2920
    The right-most child of a nested table reference is the first
 
2921
    element in the list of children because the children are inserted
 
2922
    in reverse order.
 
2923
 
 
2924
  RETURN
 
2925
    - If 'this' is a nested table reference - the right-most child of
 
2926
      the tree rooted in 'this',
 
2927
    - else - 'this'
 
2928
*/
 
2929
 
 
2930
TABLE_LIST *TABLE_LIST::last_leaf_for_name_resolution()
 
2931
{
 
2932
  TABLE_LIST *cur_table_ref= this;
 
2933
  NESTED_JOIN *cur_nested_join;
 
2934
 
 
2935
  if (is_leaf_for_name_resolution())
 
2936
    return this;
 
2937
  DBUG_ASSERT(nested_join);
 
2938
 
 
2939
  for (cur_nested_join= nested_join;
 
2940
       cur_nested_join;
 
2941
       cur_nested_join= cur_table_ref->nested_join)
 
2942
  {
 
2943
    cur_table_ref= cur_nested_join->join_list.head();
 
2944
    /*
 
2945
      If the current nested is a RIGHT JOIN, the operands in
 
2946
      'join_list' are in reverse order, thus the last operand is in the
 
2947
      end of the list.
 
2948
    */
 
2949
    if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
 
2950
    {
 
2951
      List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
 
2952
      TABLE_LIST *next;
 
2953
      cur_table_ref= it++;
 
2954
      while ((next= it++))
 
2955
        cur_table_ref= next;
 
2956
    }
 
2957
    if (cur_table_ref->is_leaf_for_name_resolution())
 
2958
      break;
 
2959
  }
 
2960
  return cur_table_ref;
 
2961
}
 
2962
 
 
2963
 
 
2964
Natural_join_column::Natural_join_column(Field_translator *field_param,
 
2965
                                         TABLE_LIST *tab)
 
2966
{
 
2967
  DBUG_ASSERT(tab->field_translation);
 
2968
  view_field= field_param;
 
2969
  table_field= NULL;
 
2970
  table_ref= tab;
 
2971
  is_common= FALSE;
 
2972
}
 
2973
 
 
2974
 
 
2975
Natural_join_column::Natural_join_column(Field *field_param,
 
2976
                                         TABLE_LIST *tab)
 
2977
{
 
2978
  DBUG_ASSERT(tab->table == field_param->table);
 
2979
  table_field= field_param;
 
2980
  view_field= NULL;
 
2981
  table_ref= tab;
 
2982
  is_common= FALSE;
 
2983
}
 
2984
 
 
2985
 
 
2986
const char *Natural_join_column::name()
 
2987
{
 
2988
  if (view_field)
 
2989
  {
 
2990
    DBUG_ASSERT(table_field == NULL);
 
2991
    return view_field->name;
 
2992
  }
 
2993
 
 
2994
  return table_field->field_name;
 
2995
}
 
2996
 
 
2997
 
 
2998
Item *Natural_join_column::create_item(THD *thd)
 
2999
{
 
3000
  if (view_field)
 
3001
  {
 
3002
    DBUG_ASSERT(table_field == NULL);
 
3003
    return create_view_field(thd, table_ref, &view_field->item,
 
3004
                             view_field->name);
 
3005
  }
 
3006
  return new Item_field(thd, &thd->lex->current_select->context, table_field);
 
3007
}
 
3008
 
 
3009
 
 
3010
Field *Natural_join_column::field()
 
3011
{
 
3012
  if (view_field)
 
3013
  {
 
3014
    DBUG_ASSERT(table_field == NULL);
 
3015
    return NULL;
 
3016
  }
 
3017
  return table_field;
 
3018
}
 
3019
 
 
3020
 
 
3021
const char *Natural_join_column::table_name()
 
3022
{
 
3023
  DBUG_ASSERT(table_ref);
 
3024
  return table_ref->alias;
 
3025
}
 
3026
 
 
3027
 
 
3028
const char *Natural_join_column::db_name()
 
3029
{
 
3030
  /*
 
3031
    Test that TABLE_LIST::db is the same as st_table_share::db to
 
3032
    ensure consistency. An exception are I_S schema tables, which
 
3033
    are inconsistent in this respect.
 
3034
  */
 
3035
  DBUG_ASSERT(!strcmp(table_ref->db,
 
3036
                      table_ref->table->s->db.str) ||
 
3037
              (table_ref->schema_table &&
 
3038
               table_ref->table->s->db.str[0] == 0));
 
3039
  return table_ref->db;
 
3040
}
 
3041
 
 
3042
 
 
3043
void Field_iterator_view::set(TABLE_LIST *table)
 
3044
{
 
3045
  DBUG_ASSERT(table->field_translation);
 
3046
  view= table;
 
3047
  ptr= table->field_translation;
 
3048
  array_end= table->field_translation_end;
 
3049
}
 
3050
 
 
3051
 
 
3052
const char *Field_iterator_table::name()
 
3053
{
 
3054
  return (*ptr)->field_name;
 
3055
}
 
3056
 
 
3057
 
 
3058
Item *Field_iterator_table::create_item(THD *thd)
 
3059
{
 
3060
  SELECT_LEX *select= thd->lex->current_select;
 
3061
 
 
3062
  Item_field *item= new Item_field(thd, &select->context, *ptr);
 
3063
  if (item && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
 
3064
      !thd->lex->in_sum_func && select->cur_pos_in_select_list != UNDEF_POS)
 
3065
  {
 
3066
    select->non_agg_fields.push_back(item);
 
3067
    item->marker= select->cur_pos_in_select_list;
 
3068
  }
 
3069
  return item;
 
3070
}
 
3071
 
 
3072
 
 
3073
const char *Field_iterator_view::name()
 
3074
{
 
3075
  return ptr->name;
 
3076
}
 
3077
 
 
3078
 
 
3079
Item *Field_iterator_view::create_item(THD *thd)
 
3080
{
 
3081
  return create_view_field(thd, view, &ptr->item, ptr->name);
 
3082
}
 
3083
 
 
3084
Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref,
 
3085
                        const char *name)
 
3086
{
 
3087
  DBUG_ENTER("create_view_field");
 
3088
  if (view->schema_table_reformed)
 
3089
  {
 
3090
    Item *field= *field_ref;
 
3091
 
 
3092
    /*
 
3093
      Translation table items are always Item_fields and already fixed
 
3094
      ('mysql_schema_table' function). So we can return directly the
 
3095
      field. This case happens only for 'show & where' commands.
 
3096
    */
 
3097
    DBUG_ASSERT(field && field->fixed);
 
3098
    DBUG_RETURN(field);
 
3099
  }
 
3100
 
 
3101
  DBUG_RETURN(NULL);
 
3102
}
 
3103
 
 
3104
 
 
3105
void Field_iterator_natural_join::set(TABLE_LIST *table_ref)
 
3106
{
 
3107
  DBUG_ASSERT(table_ref->join_columns);
 
3108
  column_ref_it.init(*(table_ref->join_columns));
 
3109
  cur_column_ref= column_ref_it++;
 
3110
}
 
3111
 
 
3112
 
 
3113
void Field_iterator_natural_join::next()
 
3114
{
 
3115
  cur_column_ref= column_ref_it++;
 
3116
  DBUG_ASSERT(!cur_column_ref || ! cur_column_ref->table_field ||
 
3117
              cur_column_ref->table_ref->table ==
 
3118
              cur_column_ref->table_field->table);
 
3119
}
 
3120
 
 
3121
 
 
3122
void Field_iterator_table_ref::set_field_iterator()
 
3123
{
 
3124
  DBUG_ENTER("Field_iterator_table_ref::set_field_iterator");
 
3125
  /*
 
3126
    If the table reference we are iterating over is a natural join, or it is
 
3127
    an operand of a natural join, and TABLE_LIST::join_columns contains all
 
3128
    the columns of the join operand, then we pick the columns from
 
3129
    TABLE_LIST::join_columns, instead of the  orginial container of the
 
3130
    columns of the join operator.
 
3131
  */
 
3132
  if (table_ref->is_join_columns_complete)
 
3133
  {
 
3134
    /* Necesary, but insufficient conditions. */
 
3135
    DBUG_ASSERT(table_ref->is_natural_join ||
 
3136
                table_ref->nested_join ||
 
3137
                table_ref->join_columns &&
 
3138
                /* This is a merge view. */
 
3139
                ((table_ref->field_translation &&
 
3140
                  table_ref->join_columns->elements ==
 
3141
                  (ulong)(table_ref->field_translation_end -
 
3142
                          table_ref->field_translation)) ||
 
3143
                 /* This is stored table or a tmptable view. */
 
3144
                 (!table_ref->field_translation &&
 
3145
                  table_ref->join_columns->elements ==
 
3146
                  table_ref->table->s->fields)));
 
3147
    field_it= &natural_join_it;
 
3148
    DBUG_PRINT("info",("field_it for '%s' is Field_iterator_natural_join",
 
3149
                       table_ref->alias));
 
3150
  }
 
3151
  /* This is a base table or stored view. */
 
3152
  else
 
3153
  {
 
3154
    DBUG_ASSERT(table_ref->table);
 
3155
    field_it= &table_field_it;
 
3156
    DBUG_PRINT("info", ("field_it for '%s' is Field_iterator_table",
 
3157
                        table_ref->alias));
 
3158
  }
 
3159
  field_it->set(table_ref);
 
3160
  DBUG_VOID_RETURN;
 
3161
}
 
3162
 
 
3163
 
 
3164
void Field_iterator_table_ref::set(TABLE_LIST *table)
 
3165
{
 
3166
  DBUG_ASSERT(table);
 
3167
  first_leaf= table->first_leaf_for_name_resolution();
 
3168
  last_leaf=  table->last_leaf_for_name_resolution();
 
3169
  DBUG_ASSERT(first_leaf && last_leaf);
 
3170
  table_ref= first_leaf;
 
3171
  set_field_iterator();
 
3172
}
 
3173
 
 
3174
 
 
3175
void Field_iterator_table_ref::next()
 
3176
{
 
3177
  /* Move to the next field in the current table reference. */
 
3178
  field_it->next();
 
3179
  /*
 
3180
    If all fields of the current table reference are exhausted, move to
 
3181
    the next leaf table reference.
 
3182
  */
 
3183
  if (field_it->end_of_fields() && table_ref != last_leaf)
 
3184
  {
 
3185
    table_ref= table_ref->next_name_resolution_table;
 
3186
    DBUG_ASSERT(table_ref);
 
3187
    set_field_iterator();
 
3188
  }
 
3189
}
 
3190
 
 
3191
 
 
3192
const char *Field_iterator_table_ref::table_name()
 
3193
{
 
3194
  if (table_ref->is_natural_join)
 
3195
    return natural_join_it.column_ref()->table_name();
 
3196
 
 
3197
  DBUG_ASSERT(!strcmp(table_ref->table_name,
 
3198
                      table_ref->table->s->table_name.str));
 
3199
  return table_ref->table_name;
 
3200
}
 
3201
 
 
3202
 
 
3203
const char *Field_iterator_table_ref::db_name()
 
3204
{
 
3205
  if (table_ref->is_natural_join)
 
3206
    return natural_join_it.column_ref()->db_name();
 
3207
 
 
3208
  /*
 
3209
    Test that TABLE_LIST::db is the same as st_table_share::db to
 
3210
    ensure consistency. An exception are I_S schema tables, which
 
3211
    are inconsistent in this respect.
 
3212
  */
 
3213
  DBUG_ASSERT(!strcmp(table_ref->db, table_ref->table->s->db.str) ||
 
3214
              (table_ref->schema_table &&
 
3215
               table_ref->table->s->db.str[0] == 0));
 
3216
 
 
3217
  return table_ref->db;
 
3218
}
 
3219
 
 
3220
 
 
3221
/*
 
3222
  Create new or return existing column reference to a column of a
 
3223
  natural/using join.
 
3224
 
 
3225
  SYNOPSIS
 
3226
    Field_iterator_table_ref::get_or_create_column_ref()
 
3227
    parent_table_ref  the parent table reference over which the
 
3228
                      iterator is iterating
 
3229
 
 
3230
  DESCRIPTION
 
3231
    Create a new natural join column for the current field of the
 
3232
    iterator if no such column was created, or return an already
 
3233
    created natural join column. The former happens for base tables or
 
3234
    views, and the latter for natural/using joins. If a new field is
 
3235
    created, then the field is added to 'parent_table_ref' if it is
 
3236
    given, or to the original table referene of the field if
 
3237
    parent_table_ref == NULL.
 
3238
 
 
3239
  NOTES
 
3240
    This method is designed so that when a Field_iterator_table_ref
 
3241
    walks through the fields of a table reference, all its fields
 
3242
    are created and stored as follows:
 
3243
    - If the table reference being iterated is a stored table, view or
 
3244
      natural/using join, store all natural join columns in a list
 
3245
      attached to that table reference.
 
3246
    - If the table reference being iterated is a nested join that is
 
3247
      not natural/using join, then do not materialize its result
 
3248
      fields. This is OK because for such table references
 
3249
      Field_iterator_table_ref iterates over the fields of the nested
 
3250
      table references (recursively). In this way we avoid the storage
 
3251
      of unnecessay copies of result columns of nested joins.
 
3252
 
 
3253
  RETURN
 
3254
    #     Pointer to a column of a natural join (or its operand)
 
3255
    NULL  No memory to allocate the column
 
3256
*/
 
3257
 
 
3258
Natural_join_column *
 
3259
Field_iterator_table_ref::get_or_create_column_ref(TABLE_LIST *parent_table_ref)
 
3260
{
 
3261
  Natural_join_column *nj_col;
 
3262
  bool is_created= TRUE;
 
3263
  uint field_count;
 
3264
  TABLE_LIST *add_table_ref= parent_table_ref ?
 
3265
                             parent_table_ref : table_ref;
 
3266
 
 
3267
  if (field_it == &table_field_it)
 
3268
  {
 
3269
    /* The field belongs to a stored table. */
 
3270
    Field *tmp_field= table_field_it.field();
 
3271
    nj_col= new Natural_join_column(tmp_field, table_ref);
 
3272
    field_count= table_ref->table->s->fields;
 
3273
  }
 
3274
  else if (field_it == &view_field_it)
 
3275
  {
 
3276
    /* The field belongs to a merge view or information schema table. */
 
3277
    Field_translator *translated_field= view_field_it.field_translator();
 
3278
    nj_col= new Natural_join_column(translated_field, table_ref);
 
3279
    field_count= table_ref->field_translation_end -
 
3280
                 table_ref->field_translation;
 
3281
  }
 
3282
  else
 
3283
  {
 
3284
    /*
 
3285
      The field belongs to a NATURAL join, therefore the column reference was
 
3286
      already created via one of the two constructor calls above. In this case
 
3287
      we just return the already created column reference.
 
3288
    */
 
3289
    DBUG_ASSERT(table_ref->is_join_columns_complete);
 
3290
    is_created= FALSE;
 
3291
    nj_col= natural_join_it.column_ref();
 
3292
    DBUG_ASSERT(nj_col);
 
3293
  }
 
3294
  DBUG_ASSERT(!nj_col->table_field ||
 
3295
              nj_col->table_ref->table == nj_col->table_field->table);
 
3296
 
 
3297
  /*
 
3298
    If the natural join column was just created add it to the list of
 
3299
    natural join columns of either 'parent_table_ref' or to the table
 
3300
    reference that directly contains the original field.
 
3301
  */
 
3302
  if (is_created)
 
3303
  {
 
3304
    /* Make sure not all columns were materialized. */
 
3305
    DBUG_ASSERT(!add_table_ref->is_join_columns_complete);
 
3306
    if (!add_table_ref->join_columns)
 
3307
    {
 
3308
      /* Create a list of natural join columns on demand. */
 
3309
      if (!(add_table_ref->join_columns= new List<Natural_join_column>))
 
3310
        return NULL;
 
3311
      add_table_ref->is_join_columns_complete= FALSE;
 
3312
    }
 
3313
    add_table_ref->join_columns->push_back(nj_col);
 
3314
    /*
 
3315
      If new fields are added to their original table reference, mark if
 
3316
      all fields were added. We do it here as the caller has no easy way
 
3317
      of knowing when to do it.
 
3318
      If the fields are being added to parent_table_ref, then the caller
 
3319
      must take care to mark when all fields are created/added.
 
3320
    */
 
3321
    if (!parent_table_ref &&
 
3322
        add_table_ref->join_columns->elements == field_count)
 
3323
      add_table_ref->is_join_columns_complete= TRUE;
 
3324
  }
 
3325
 
 
3326
  return nj_col;
 
3327
}
 
3328
 
 
3329
 
 
3330
/*
 
3331
  Return an existing reference to a column of a natural/using join.
 
3332
 
 
3333
  SYNOPSIS
 
3334
    Field_iterator_table_ref::get_natural_column_ref()
 
3335
 
 
3336
  DESCRIPTION
 
3337
    The method should be called in contexts where it is expected that
 
3338
    all natural join columns are already created, and that the column
 
3339
    being retrieved is a Natural_join_column.
 
3340
 
 
3341
  RETURN
 
3342
    #     Pointer to a column of a natural join (or its operand)
 
3343
    NULL  No memory to allocate the column
 
3344
*/
 
3345
 
 
3346
Natural_join_column *
 
3347
Field_iterator_table_ref::get_natural_column_ref()
 
3348
{
 
3349
  Natural_join_column *nj_col;
 
3350
 
 
3351
  DBUG_ASSERT(field_it == &natural_join_it);
 
3352
  /*
 
3353
    The field belongs to a NATURAL join, therefore the column reference was
 
3354
    already created via one of the two constructor calls above. In this case
 
3355
    we just return the already created column reference.
 
3356
  */
 
3357
  nj_col= natural_join_it.column_ref();
 
3358
  DBUG_ASSERT(nj_col &&
 
3359
              (!nj_col->table_field ||
 
3360
               nj_col->table_ref->table == nj_col->table_field->table));
 
3361
  return nj_col;
 
3362
}
403
3363
 
404
3364
/*****************************************************************************
405
3365
  Functions to handle column usage bitmaps (read_set, write_set etc...)
407
3367
 
408
3368
/* Reset all columns bitmaps */
409
3369
 
410
 
void Table::clear_column_bitmaps()
 
3370
void st_table::clear_column_bitmaps()
411
3371
{
412
3372
  /*
413
3373
    Reset column read/write usage. It's identical to:
414
3374
    bitmap_clear_all(&table->def_read_set);
415
3375
    bitmap_clear_all(&table->def_write_set);
416
3376
  */
417
 
  def_read_set.reset();
418
 
  def_write_set.reset();
419
 
  column_bitmaps_set(def_read_set, def_write_set);
 
3377
  bzero((char*) def_read_set.bitmap, s->column_bitmap_size*2);
 
3378
  column_bitmaps_set(&def_read_set, &def_write_set);
420
3379
}
421
3380
 
422
3381
 
423
3382
/*
424
 
  Tell Cursor we are going to call position() and rnd_pos() later.
425
 
 
 
3383
  Tell handler we are going to call position() and rnd_pos() later.
 
3384
  
426
3385
  NOTES:
427
3386
  This is needed for handlers that uses the primary key to find the
428
3387
  row. In this case we have to extend the read bitmap with the primary
429
3388
  key fields.
430
3389
*/
431
3390
 
432
 
void Table::prepare_for_position()
 
3391
void st_table::prepare_for_position()
433
3392
{
 
3393
  DBUG_ENTER("st_table::prepare_for_position");
434
3394
 
435
 
  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
436
 
      getShare()->hasPrimaryKey())
 
3395
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
3396
      s->primary_key < MAX_KEY)
437
3397
  {
438
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
 
3398
    mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3399
    /* signal change */
 
3400
    file->column_bitmaps_signal();
439
3401
  }
440
 
  return;
 
3402
  DBUG_VOID_RETURN;
441
3403
}
442
3404
 
443
3405
 
447
3409
  NOTE:
448
3410
    This changes the bitmap to use the tmp bitmap
449
3411
    After this, you can't access any other columns in the table until
450
 
    bitmaps are reset, for example with Table::clear_column_bitmaps()
451
 
    or Table::restore_column_maps_after_mark_index()
 
3412
    bitmaps are reset, for example with st_table::clear_column_bitmaps()
 
3413
    or st_table::restore_column_maps_after_mark_index()
452
3414
*/
453
3415
 
454
 
void Table::mark_columns_used_by_index(uint32_t index)
 
3416
void st_table::mark_columns_used_by_index(uint index)
455
3417
{
456
 
  boost::dynamic_bitset<> *bitmap= &tmp_set;
 
3418
  MY_BITMAP *bitmap= &tmp_set;
 
3419
  DBUG_ENTER("st_table::mark_columns_used_by_index");
457
3420
 
458
 
  (void) cursor->extra(HA_EXTRA_KEYREAD);
459
 
  bitmap->reset();
460
 
  mark_columns_used_by_index_no_reset(index, *bitmap);
461
 
  column_bitmaps_set(*bitmap, *bitmap);
462
 
  return;
 
3421
  (void) file->extra(HA_EXTRA_KEYREAD);
 
3422
  bitmap_clear_all(bitmap);
 
3423
  mark_columns_used_by_index_no_reset(index, bitmap);
 
3424
  column_bitmaps_set(bitmap, bitmap);
 
3425
  DBUG_VOID_RETURN;
463
3426
}
464
3427
 
465
3428
 
474
3437
    when calling mark_columns_used_by_index
475
3438
*/
476
3439
 
477
 
void Table::restore_column_maps_after_mark_index()
 
3440
void st_table::restore_column_maps_after_mark_index()
478
3441
{
 
3442
  DBUG_ENTER("st_table::restore_column_maps_after_mark_index");
479
3443
 
480
3444
  key_read= 0;
481
 
  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
 
3445
  (void) file->extra(HA_EXTRA_NO_KEYREAD);
482
3446
  default_column_bitmaps();
483
 
  return;
 
3447
  file->column_bitmaps_signal();
 
3448
  DBUG_VOID_RETURN;
484
3449
}
485
3450
 
486
3451
 
488
3453
  mark columns used by key, but don't reset other fields
489
3454
*/
490
3455
 
491
 
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
492
 
{
493
 
    mark_columns_used_by_index_no_reset(index, *read_set);
494
 
}
495
 
 
496
 
 
497
 
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
498
 
                                                boost::dynamic_bitset<>& bitmap)
499
 
{
500
 
  KeyPartInfo *key_part= key_info[index].key_part;
501
 
  KeyPartInfo *key_part_end= (key_part + key_info[index].key_parts);
502
 
  for (; key_part != key_part_end; key_part++)
503
 
  {
504
 
    if (! bitmap.empty())
505
 
      bitmap.set(key_part->fieldnr-1);
506
 
  }
 
3456
void st_table::mark_columns_used_by_index_no_reset(uint index,
 
3457
                                                   MY_BITMAP *bitmap)
 
3458
{
 
3459
  KEY_PART_INFO *key_part= key_info[index].key_part;
 
3460
  KEY_PART_INFO *key_part_end= (key_part +
 
3461
                                key_info[index].key_parts);
 
3462
  for (;key_part != key_part_end; key_part++)
 
3463
    bitmap_set_bit(bitmap, key_part->fieldnr-1);
507
3464
}
508
3465
 
509
3466
 
515
3472
    always set and sometimes read.
516
3473
*/
517
3474
 
518
 
void Table::mark_auto_increment_column()
 
3475
void st_table::mark_auto_increment_column()
519
3476
{
520
 
  assert(found_next_number_field);
 
3477
  DBUG_ASSERT(found_next_number_field);
521
3478
  /*
522
3479
    We must set bit in read set as update_auto_increment() is using the
523
3480
    store() to check overflow of auto_increment values
524
3481
  */
525
 
  setReadSet(found_next_number_field->position());
526
 
  setWriteSet(found_next_number_field->position());
527
 
  if (getShare()->next_number_keypart)
528
 
    mark_columns_used_by_index_no_reset(getShare()->next_number_index);
 
3482
  bitmap_set_bit(read_set, found_next_number_field->field_index);
 
3483
  bitmap_set_bit(write_set, found_next_number_field->field_index);
 
3484
  if (s->next_number_keypart)
 
3485
    mark_columns_used_by_index_no_reset(s->next_number_index, read_set);
 
3486
  file->column_bitmaps_signal();
529
3487
}
530
3488
 
531
3489
 
547
3505
    retrieve the row again.
548
3506
*/
549
3507
 
550
 
void Table::mark_columns_needed_for_delete()
 
3508
void st_table::mark_columns_needed_for_delete()
551
3509
{
552
 
  /*
553
 
    If the Cursor has no cursor capabilites, or we have row-based
554
 
    replication active for the current statement, we have to read
555
 
    either the primary key, the hidden primary key or all columns to
556
 
    be able to do an delete
557
 
 
558
 
  */
559
 
  if (not getShare()->hasPrimaryKey())
560
 
  {
561
 
    /* fallback to use all columns in the table to identify row */
562
 
    use_all_columns();
563
 
    return;
564
 
  }
565
 
  else
566
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
567
 
 
568
 
  /* If we the engine wants all predicates we mark all keys */
569
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
3510
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
570
3511
  {
571
3512
    Field **reg_field;
572
3513
    for (reg_field= field ; *reg_field ; reg_field++)
573
3514
    {
574
3515
      if ((*reg_field)->flags & PART_KEY_FLAG)
575
 
        setReadSet((*reg_field)->position());
 
3516
        bitmap_set_bit(read_set, (*reg_field)->field_index);
 
3517
    }
 
3518
    file->column_bitmaps_signal();
 
3519
  }
 
3520
  if (file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE ||
 
3521
      (mysql_bin_log.is_open() && in_use && in_use->current_stmt_binlog_row_based))
 
3522
  {
 
3523
    /*
 
3524
      If the handler has no cursor capabilites, or we have row-based
 
3525
      replication active for the current statement, we have to read
 
3526
      either the primary key, the hidden primary key or all columns to
 
3527
      be able to do an delete
 
3528
    */
 
3529
    if (s->primary_key == MAX_KEY)
 
3530
      file->use_hidden_primary_key();
 
3531
    else
 
3532
    {
 
3533
      mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3534
      file->column_bitmaps_signal();
576
3535
    }
577
3536
  }
578
3537
}
590
3549
    if neeed, either the primary key column or all columns to be read.
591
3550
    (see mark_columns_needed_for_delete() for details)
592
3551
 
593
 
    If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
 
3552
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
594
3553
    mark all USED key columns as 'to-be-read'. This allows the engine to
595
3554
    loop over the given record to find all changed keys and doesn't have to
596
3555
    retrieve the row again.
597
3556
*/
598
3557
 
599
 
void Table::mark_columns_needed_for_update()
 
3558
void st_table::mark_columns_needed_for_update()
600
3559
{
601
 
  /*
602
 
    If the Cursor has no cursor capabilites, or we have row-based
603
 
    logging active for the current statement, we have to read either
604
 
    the primary key, the hidden primary key or all columns to be
605
 
    able to do an update
606
 
  */
607
 
  if (not getShare()->hasPrimaryKey())
608
 
  {
609
 
    /* fallback to use all columns in the table to identify row */
610
 
    use_all_columns();
611
 
    return;
612
 
  }
613
 
  else
614
 
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
615
 
 
616
 
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
 
3560
  DBUG_ENTER("mark_columns_needed_for_update");
 
3561
  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
617
3562
  {
618
3563
    /* Mark all used key columns for read */
619
3564
    Field **reg_field;
620
3565
    for (reg_field= field ; *reg_field ; reg_field++)
621
3566
    {
622
3567
      /* Merge keys is all keys that had a column refered to in the query */
623
 
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
624
 
        setReadSet((*reg_field)->position());
625
 
    }
626
 
  }
627
 
 
 
3568
      if (merge_keys.is_overlapping((*reg_field)->part_of_key))
 
3569
        bitmap_set_bit(read_set, (*reg_field)->field_index);
 
3570
    }
 
3571
    file->column_bitmaps_signal();
 
3572
  }
 
3573
  if ((file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) ||
 
3574
      (mysql_bin_log.is_open() && in_use && in_use->current_stmt_binlog_row_based))
 
3575
  {
 
3576
    /*
 
3577
      If the handler has no cursor capabilites, or we have row-based
 
3578
      logging active for the current statement, we have to read either
 
3579
      the primary key, the hidden primary key or all columns to be
 
3580
      able to do an update
 
3581
    */
 
3582
    if (s->primary_key == MAX_KEY)
 
3583
      file->use_hidden_primary_key();
 
3584
    else
 
3585
    {
 
3586
      mark_columns_used_by_index_no_reset(s->primary_key, read_set);
 
3587
      file->column_bitmaps_signal();
 
3588
    }
 
3589
  }
 
3590
  DBUG_VOID_RETURN;
628
3591
}
629
3592
 
630
3593
 
631
3594
/*
632
 
  Mark columns the Cursor needs for doing an insert
 
3595
  Mark columns the handler needs for doing an insert
633
3596
 
634
3597
  For now, this is used to mark fields used by the trigger
635
3598
  as changed.
636
3599
*/
637
3600
 
638
 
void Table::mark_columns_needed_for_insert()
 
3601
void st_table::mark_columns_needed_for_insert()
639
3602
{
640
3603
  if (found_next_number_field)
641
3604
    mark_auto_increment_column();
642
3605
}
643
3606
 
644
 
 
645
 
 
646
 
size_t Table::max_row_length(const unsigned char *data)
647
 
{
648
 
  size_t length= getRecordLength() + 2 * sizeFields();
649
 
  uint32_t *const beg= getBlobField();
650
 
  uint32_t *const end= beg + sizeBlobFields();
651
 
 
652
 
  for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
653
 
  {
654
 
    Field_blob* const blob= (Field_blob*) field[*ptr];
655
 
    length+= blob->get_length((const unsigned char*)
656
 
                              (data + blob->offset(getInsertRecord()))) +
 
3607
/*
 
3608
  Cleanup this table for re-execution.
 
3609
 
 
3610
  SYNOPSIS
 
3611
    TABLE_LIST::reinit_before_use()
 
3612
*/
 
3613
 
 
3614
void TABLE_LIST::reinit_before_use(THD *thd)
 
3615
{
 
3616
  /*
 
3617
    Reset old pointers to TABLEs: they are not valid since the tables
 
3618
    were closed in the end of previous prepare or execute call.
 
3619
  */
 
3620
  table= 0;
 
3621
  /* Reset is_schema_table_processed value(needed for I_S tables */
 
3622
  schema_table_state= NOT_PROCESSED;
 
3623
 
 
3624
  TABLE_LIST *embedded; /* The table at the current level of nesting. */
 
3625
  TABLE_LIST *parent_embedding= this; /* The parent nested table reference. */
 
3626
  do
 
3627
  {
 
3628
    embedded= parent_embedding;
 
3629
    if (embedded->prep_on_expr)
 
3630
      embedded->on_expr= embedded->prep_on_expr->copy_andor_structure(thd);
 
3631
    parent_embedding= embedded->embedding;
 
3632
  }
 
3633
  while (parent_embedding &&
 
3634
         parent_embedding->nested_join->join_list.head() == embedded);
 
3635
}
 
3636
 
 
3637
/*
 
3638
  Return subselect that contains the FROM list this table is taken from
 
3639
 
 
3640
  SYNOPSIS
 
3641
    TABLE_LIST::containing_subselect()
 
3642
 
 
3643
  RETURN
 
3644
    Subselect item for the subquery that contains the FROM list
 
3645
    this table is taken from if there is any
 
3646
    0 - otherwise
 
3647
 
 
3648
*/
 
3649
 
 
3650
Item_subselect *TABLE_LIST::containing_subselect()
 
3651
{    
 
3652
  return (select_lex ? select_lex->master_unit()->item : 0);
 
3653
}
 
3654
 
 
3655
/*
 
3656
  Compiles the tagged hints list and fills up the bitmasks.
 
3657
 
 
3658
  SYNOPSIS
 
3659
    process_index_hints()
 
3660
      table         the TABLE to operate on.
 
3661
 
 
3662
  DESCRIPTION
 
3663
    The parser collects the index hints for each table in a "tagged list" 
 
3664
    (TABLE_LIST::index_hints). Using the information in this tagged list
 
3665
    this function sets the members st_table::keys_in_use_for_query, 
 
3666
    st_table::keys_in_use_for_group_by, st_table::keys_in_use_for_order_by,
 
3667
    st_table::force_index and st_table::covering_keys.
 
3668
 
 
3669
    Current implementation of the runtime does not allow mixing FORCE INDEX
 
3670
    and USE INDEX, so this is checked here. Then the FORCE INDEX list 
 
3671
    (if non-empty) is appended to the USE INDEX list and a flag is set.
 
3672
 
 
3673
    Multiple hints of the same kind are processed so that each clause 
 
3674
    is applied to what is computed in the previous clause.
 
3675
    For example:
 
3676
        USE INDEX (i1) USE INDEX (i2)
 
3677
    is equivalent to
 
3678
        USE INDEX (i1,i2)
 
3679
    and means "consider only i1 and i2".
 
3680
        
 
3681
    Similarly
 
3682
        USE INDEX () USE INDEX (i1)
 
3683
    is equivalent to
 
3684
        USE INDEX (i1)
 
3685
    and means "consider only the index i1"
 
3686
 
 
3687
    It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is
 
3688
    not an error.
 
3689
        
 
3690
    Different kind of hints (USE/FORCE/IGNORE) are processed in the following
 
3691
    order:
 
3692
      1. All indexes in USE (or FORCE) INDEX are added to the mask.
 
3693
      2. All IGNORE INDEX
 
3694
 
 
3695
    e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all
 
3696
    as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
 
3697
 
 
3698
    As an optimization if there is a covering index, and we have 
 
3699
    IGNORE INDEX FOR GROUP/ORDER, and this index is used for the JOIN part, 
 
3700
    then we have to ignore the IGNORE INDEX FROM GROUP/ORDER.
 
3701
 
 
3702
  RETURN VALUE
 
3703
    FALSE                no errors found
 
3704
    TRUE                 found and reported an error.
 
3705
*/
 
3706
bool TABLE_LIST::process_index_hints(TABLE *tbl)
 
3707
{
 
3708
  /* initialize the result variables */
 
3709
  tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by= 
 
3710
    tbl->keys_in_use_for_order_by= tbl->s->keys_in_use;
 
3711
 
 
3712
  /* index hint list processing */
 
3713
  if (index_hints)
 
3714
  {
 
3715
    key_map index_join[INDEX_HINT_FORCE + 1];
 
3716
    key_map index_order[INDEX_HINT_FORCE + 1];
 
3717
    key_map index_group[INDEX_HINT_FORCE + 1];
 
3718
    Index_hint *hint;
 
3719
    int type;
 
3720
    bool have_empty_use_join= FALSE, have_empty_use_order= FALSE, 
 
3721
         have_empty_use_group= FALSE;
 
3722
    List_iterator <Index_hint> iter(*index_hints);
 
3723
 
 
3724
    /* initialize temporary variables used to collect hints of each kind */
 
3725
    for (type= INDEX_HINT_IGNORE; type <= INDEX_HINT_FORCE; type++)
 
3726
    {
 
3727
      index_join[type].clear_all();
 
3728
      index_order[type].clear_all();
 
3729
      index_group[type].clear_all();
 
3730
    }
 
3731
 
 
3732
    /* iterate over the hints list */
 
3733
    while ((hint= iter++))
 
3734
    {
 
3735
      uint pos;
 
3736
 
 
3737
      /* process empty USE INDEX () */
 
3738
      if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
 
3739
      {
 
3740
        if (hint->clause & INDEX_HINT_MASK_JOIN)
 
3741
        {
 
3742
          index_join[hint->type].clear_all();
 
3743
          have_empty_use_join= TRUE;
 
3744
        }
 
3745
        if (hint->clause & INDEX_HINT_MASK_ORDER)
 
3746
        {
 
3747
          index_order[hint->type].clear_all();
 
3748
          have_empty_use_order= TRUE;
 
3749
        }
 
3750
        if (hint->clause & INDEX_HINT_MASK_GROUP)
 
3751
        {
 
3752
          index_group[hint->type].clear_all();
 
3753
          have_empty_use_group= TRUE;
 
3754
        }
 
3755
        continue;
 
3756
      }
 
3757
 
 
3758
      /* 
 
3759
        Check if an index with the given name exists and get his offset in 
 
3760
        the keys bitmask for the table 
 
3761
      */
 
3762
      if (tbl->s->keynames.type_names == 0 ||
 
3763
          (pos= find_type(&tbl->s->keynames, hint->key_name.str,
 
3764
                          hint->key_name.length, 1)) <= 0)
 
3765
      {
 
3766
        my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), hint->key_name.str, alias);
 
3767
        return 1;
 
3768
      }
 
3769
 
 
3770
      pos--;
 
3771
 
 
3772
      /* add to the appropriate clause mask */
 
3773
      if (hint->clause & INDEX_HINT_MASK_JOIN)
 
3774
        index_join[hint->type].set_bit (pos);
 
3775
      if (hint->clause & INDEX_HINT_MASK_ORDER)
 
3776
        index_order[hint->type].set_bit (pos);
 
3777
      if (hint->clause & INDEX_HINT_MASK_GROUP)
 
3778
        index_group[hint->type].set_bit (pos);
 
3779
    }
 
3780
 
 
3781
    /* cannot mix USE INDEX and FORCE INDEX */
 
3782
    if ((!index_join[INDEX_HINT_FORCE].is_clear_all() ||
 
3783
         !index_order[INDEX_HINT_FORCE].is_clear_all() ||
 
3784
         !index_group[INDEX_HINT_FORCE].is_clear_all()) &&
 
3785
        (!index_join[INDEX_HINT_USE].is_clear_all() ||  have_empty_use_join ||
 
3786
         !index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order ||
 
3787
         !index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group))
 
3788
    {
 
3789
      my_error(ER_WRONG_USAGE, MYF(0), index_hint_type_name[INDEX_HINT_USE],
 
3790
               index_hint_type_name[INDEX_HINT_FORCE]);
 
3791
      return 1;
 
3792
    }
 
3793
 
 
3794
    /* process FORCE INDEX as USE INDEX with a flag */
 
3795
    if (!index_join[INDEX_HINT_FORCE].is_clear_all() ||
 
3796
        !index_order[INDEX_HINT_FORCE].is_clear_all() ||
 
3797
        !index_group[INDEX_HINT_FORCE].is_clear_all())
 
3798
    {
 
3799
      tbl->force_index= TRUE;
 
3800
      index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
 
3801
      index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
 
3802
      index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
 
3803
    }
 
3804
 
 
3805
    /* apply USE INDEX */
 
3806
    if (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join)
 
3807
      tbl->keys_in_use_for_query.intersect(index_join[INDEX_HINT_USE]);
 
3808
    if (!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order)
 
3809
      tbl->keys_in_use_for_order_by.intersect (index_order[INDEX_HINT_USE]);
 
3810
    if (!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group)
 
3811
      tbl->keys_in_use_for_group_by.intersect (index_group[INDEX_HINT_USE]);
 
3812
 
 
3813
    /* apply IGNORE INDEX */
 
3814
    tbl->keys_in_use_for_query.subtract (index_join[INDEX_HINT_IGNORE]);
 
3815
    tbl->keys_in_use_for_order_by.subtract (index_order[INDEX_HINT_IGNORE]);
 
3816
    tbl->keys_in_use_for_group_by.subtract (index_group[INDEX_HINT_IGNORE]);
 
3817
  }
 
3818
 
 
3819
  /* make sure covering_keys don't include indexes disabled with a hint */
 
3820
  tbl->covering_keys.intersect(tbl->keys_in_use_for_query);
 
3821
  return 0;
 
3822
}
 
3823
 
 
3824
 
 
3825
size_t max_row_length(TABLE *table, const uchar *data)
 
3826
{
 
3827
  TABLE_SHARE *table_s= table->s;
 
3828
  size_t length= table_s->reclength + 2 * table_s->fields;
 
3829
  uint *const beg= table_s->blob_field;
 
3830
  uint *const end= beg + table_s->blob_fields;
 
3831
 
 
3832
  for (uint *ptr= beg ; ptr != end ; ++ptr)
 
3833
  {
 
3834
    Field_blob* const blob= (Field_blob*) table->field[*ptr];
 
3835
    length+= blob->get_length((const uchar*)
 
3836
                              (data + blob->offset(table->record[0]))) +
657
3837
      HA_KEY_BLOB_LENGTH;
658
3838
  }
659
3839
  return length;
660
3840
}
661
3841
 
662
 
void Table::setVariableWidth(void)
663
 
{
664
 
  assert(in_use);
665
 
  if (in_use && in_use->lex->sql_command == SQLCOM_CREATE_TABLE)
666
 
  {
667
 
    getMutableShare()->setVariableWidth();
668
 
    return;
669
 
  }
670
 
 
671
 
  assert(0); // Programming error, you can't set this on a plain old Table.
672
 
}
673
 
 
674
 
/****************************************************************************
675
 
 Functions for creating temporary tables.
676
 
****************************************************************************/
677
 
/**
678
 
  Create field for temporary table from given field.
679
 
 
680
 
  @param session               Thread Cursor
681
 
  @param org_field    field from which new field will be created
682
 
  @param name         New field name
683
 
  @param table         Temporary table
684
 
  @param item          !=NULL if item->result_field should point to new field.
685
 
                      This is relevant for how fill_record() is going to work:
686
 
                      If item != NULL then fill_record() will update
687
 
                      the record in the original table.
688
 
                      If item == NULL then fill_record() will update
689
 
                      the temporary table
690
 
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
691
 
                               field instead of blob.
692
 
 
693
 
  @retval
694
 
    NULL                on error
695
 
  @retval
696
 
    new_created field
697
 
*/
698
 
 
699
 
Field *create_tmp_field_from_field(Session *session, Field *org_field,
700
 
                                   const char *name, Table *table,
701
 
                                   Item_field *item, uint32_t convert_blob_length)
702
 
{
703
 
  Field *new_field;
704
 
 
705
 
  /*
706
 
    Make sure that the blob fits into a Field_varstring which has
707
 
    2-byte lenght.
708
 
  */
709
 
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
710
 
      (org_field->flags & BLOB_FLAG))
711
 
  {
712
 
    table->setVariableWidth();
713
 
    new_field= new Field_varstring(convert_blob_length,
714
 
                                   org_field->maybe_null(),
715
 
                                   org_field->field_name,
716
 
                                   org_field->charset());
717
 
  }
718
 
  else
719
 
  {
720
 
    new_field= org_field->new_field(session->mem_root, table,
721
 
                                    table == org_field->getTable());
722
 
  }
723
 
  if (new_field)
724
 
  {
725
 
    new_field->init(table);
726
 
    new_field->orig_table= org_field->orig_table;
727
 
    if (item)
728
 
      item->result_field= new_field;
729
 
    else
730
 
      new_field->field_name= name;
731
 
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
732
 
    if (org_field->maybe_null() || (item && item->maybe_null))
733
 
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
734
 
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
735
 
      table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
736
 
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
737
 
      ((Field_double *) new_field)->not_fixed= true;
738
 
  }
739
 
  return new_field;
740
 
}
741
 
 
742
 
 
743
 
/**
744
 
  Create a temp table according to a field list.
745
 
 
746
 
  Given field pointers are changed to point at tmp_table for
747
 
  send_fields. The table object is self contained: it's
748
 
  allocated in its own memory root, as well as Field objects
749
 
  created for table columns.
750
 
  This function will replace Item_sum items in 'fields' list with
751
 
  corresponding Item_field items, pointing at the fields in the
752
 
  temporary table, unless this was prohibited by true
753
 
  value of argument save_sum_fields. The Item_field objects
754
 
  are created in Session memory root.
755
 
 
756
 
  @param session                  thread handle
757
 
  @param param                a description used as input to create the table
758
 
  @param fields               list of items that will be used to define
759
 
                              column types of the table (also see NOTES)
760
 
  @param group                TODO document
761
 
  @param distinct             should table rows be distinct
762
 
  @param save_sum_fields      see NOTES
763
 
  @param select_options
764
 
  @param rows_limit
765
 
  @param table_alias          possible name of the temporary table that can
766
 
                              be used for name resolving; can be "".
767
 
*/
768
 
 
769
 
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
770
 
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
771
 
#define RATIO_TO_PACK_ROWS             2
772
 
 
773
 
Table *
774
 
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
775
 
                 Order *group, bool distinct, bool save_sum_fields,
776
 
                 uint64_t select_options, ha_rows rows_limit,
777
 
                 const char *table_alias)
778
 
{
779
 
  memory::Root *mem_root_save;
780
 
  uint  i,field_count,null_count,null_pack_length;
781
 
  uint32_t  copy_func_count= param->func_count;
782
 
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
783
 
  uint32_t  blob_count,group_null_items, string_count;
784
 
  uint32_t fieldnr= 0;
785
 
  ulong reclength, string_total_length;
786
 
  bool  using_unique_constraint= false;
787
 
  bool  use_packed_rows= true;
788
 
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
789
 
  unsigned char *pos, *group_buff;
790
 
  unsigned char *null_flags;
791
 
  Field **reg_field, **from_field, **default_field;
792
 
  CopyField *copy= 0;
793
 
  KeyInfo *keyinfo;
794
 
  KeyPartInfo *key_part_info;
795
 
  Item **copy_func;
796
 
  MI_COLUMNDEF *recinfo;
797
 
  uint32_t total_uneven_bit_length= 0;
798
 
  bool force_copy_fields= param->force_copy_fields;
799
 
  uint64_t max_rows= 0;
800
 
 
801
 
  session->status_var.created_tmp_tables++;
802
 
 
803
 
  if (group)
804
 
  {
805
 
    if (! param->quick_group)
806
 
    {
807
 
      group= 0;                                 // Can't use group key
808
 
    }
809
 
    else for (Order *tmp=group ; tmp ; tmp=tmp->next)
810
 
    {
811
 
      /*
812
 
        marker == 4 means two things:
813
 
        - store NULLs in the key, and
814
 
        - convert BIT fields to 64-bit long, needed because MEMORY tables
815
 
          can't index BIT fields.
816
 
      */
817
 
      (*tmp->item)->marker= 4;
818
 
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
819
 
        using_unique_constraint= true;
820
 
    }
821
 
    if (param->group_length >= MAX_BLOB_WIDTH)
822
 
      using_unique_constraint= true;
823
 
    if (group)
824
 
      distinct= 0;                              // Can't use distinct
825
 
  }
826
 
 
827
 
  field_count=param->field_count+param->func_count+param->sum_func_count;
828
 
  hidden_field_count=param->hidden_field_count;
829
 
 
830
 
  /*
831
 
    When loose index scan is employed as access method, it already
832
 
    computes all groups and the result of all aggregate functions. We
833
 
    make space for the items of the aggregate function in the list of
834
 
    functions Tmp_Table_Param::items_to_copy, so that the values of
835
 
    these items are stored in the temporary table.
836
 
  */
837
 
  if (param->precomputed_group_by)
838
 
  {
839
 
    copy_func_count+= param->sum_func_count;
840
 
  }
841
 
 
842
 
  table::Singular *table;
843
 
  table= session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
844
 
 
845
 
  if (not table->getMemRoot()->multi_alloc_root(0,
846
 
                                                &default_field, sizeof(Field*) * (field_count),
847
 
                                                &from_field, sizeof(Field*)*field_count,
848
 
                                                &copy_func, sizeof(*copy_func)*(copy_func_count+1),
849
 
                                                &param->keyinfo, sizeof(*param->keyinfo),
850
 
                                                &key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
851
 
                                                &param->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
852
 
                                                &group_buff, (group && ! using_unique_constraint ?
853
 
                                                              param->group_length : 0),
854
 
                                                NULL))
855
 
  {
856
 
    return NULL;
857
 
  }
858
 
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
859
 
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
860
 
  {
861
 
    return NULL;
862
 
  }
863
 
  param->items_to_copy= copy_func;
864
 
  /* make table according to fields */
865
 
 
866
 
  memset(default_field, 0, sizeof(Field*) * (field_count));
867
 
  memset(from_field, 0, sizeof(Field*)*field_count);
868
 
 
869
 
  mem_root_save= session->mem_root;
870
 
  session->mem_root= table->getMemRoot();
871
 
 
872
 
  table->getMutableShare()->setFields(field_count+1);
873
 
  table->setFields(table->getMutableShare()->getFields(true));
874
 
  reg_field= table->getMutableShare()->getFields(true);
875
 
  table->setAlias(table_alias);
876
 
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
877
 
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
878
 
  table->map=1;
879
 
  table->copy_blobs= 1;
880
 
  assert(session);
881
 
  table->in_use= session;
882
 
  table->quick_keys.reset();
883
 
  table->covering_keys.reset();
884
 
  table->keys_in_use_for_query.reset();
885
 
 
886
 
  table->getMutableShare()->blob_field.resize(field_count+1);
887
 
  uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
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();
892
 
 
893
 
  /* Calculate which type of fields we will store in the temporary table */
894
 
 
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;
898
 
 
899
 
  List_iterator_fast<Item> li(fields);
900
 
  Item *item;
901
 
  Field **tmp_from_field=from_field;
902
 
  while ((item=li++))
903
 
  {
904
 
    Item::Type type=item->type();
905
 
    if (not_all_columns)
906
 
    {
907
 
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
908
 
      {
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))
913
 
        {
914
 
          /*
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.
918
 
          */
919
 
          param->using_indirect_summary_function=1;
920
 
          continue;
921
 
        }
922
 
      }
923
 
      if (item->const_item() && (int) hidden_field_count <= 0)
924
 
        continue; // We don't have to store this
925
 
    }
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++)
930
 
      {
931
 
        Item **argp= ((Item_sum*) item)->args + i;
932
 
        Item *arg= *argp;
933
 
        if (!arg->const_item())
934
 
        {
935
 
          Field *new_field=
936
 
            create_tmp_field(session, table, arg, arg->type(), &copy_func,
937
 
                             tmp_from_field, &default_field[fieldnr],
938
 
                             group != 0,not_all_columns,
939
 
                             false,
940
 
                             param->convert_blob_length);
941
 
          if (!new_field)
942
 
            goto err;                                   // Should be OOM
943
 
          tmp_from_field++;
944
 
          reclength+=new_field->pack_length();
945
 
          if (new_field->flags & BLOB_FLAG)
946
 
          {
947
 
            *blob_field++= fieldnr;
948
 
            blob_count++;
949
 
          }
950
 
          *(reg_field++)= new_field;
951
 
          if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
952
 
          {
953
 
            string_count++;
954
 
            string_total_length+= new_field->pack_length();
955
 
          }
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))
960
 
          {
961
 
            null_count++;
962
 
            /*
963
 
              new_field->maybe_null() is still false, it will be
964
 
              changed below. But we have to setup Item_field correctly
965
 
            */
966
 
            (*argp)->maybe_null=1;
967
 
          }
968
 
          new_field->setPosition(fieldnr++);
969
 
        }
970
 
      }
971
 
    }
972
 
    else
973
 
    {
974
 
      /*
975
 
        The last parameter to create_tmp_field() is a bit tricky:
976
 
 
977
 
        We need to set it to 0 in union, to get fill_record() to modify the
978
 
        temporary table.
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.
983
 
      */
984
 
      Field *new_field=
985
 
        create_tmp_field(session, table, item, type, &copy_func,
986
 
                         tmp_from_field, &default_field[fieldnr],
987
 
                         group != 0,
988
 
                         !force_copy_fields &&
989
 
                           (not_all_columns || group != 0),
990
 
                         force_copy_fields,
991
 
                         param->convert_blob_length);
992
 
 
993
 
      if (!new_field)
994
 
      {
995
 
        if (session->is_fatal_error)
996
 
          goto err;                             // Got OOM
997
 
        continue;                               // Some kindf of const item
998
 
      }
999
 
      if (type == Item::SUM_FUNC_ITEM)
1000
 
        ((Item_sum *) item)->result_field= new_field;
1001
 
      tmp_from_field++;
1002
 
      reclength+=new_field->pack_length();
1003
 
      if (!(new_field->flags & NOT_NULL_FLAG))
1004
 
        null_count++;
1005
 
      if (new_field->flags & BLOB_FLAG)
1006
 
      {
1007
 
        *blob_field++= fieldnr;
1008
 
        blob_count++;
1009
 
      }
1010
 
      if (item->marker == 4 && item->maybe_null)
1011
 
      {
1012
 
        group_null_items++;
1013
 
        new_field->flags|= GROUP_FLAG;
1014
 
      }
1015
 
      new_field->setPosition(fieldnr++);
1016
 
      *(reg_field++)= new_field;
1017
 
    }
1018
 
    if (!--hidden_field_count)
1019
 
    {
1020
 
      /*
1021
 
        This was the last hidden field; Remember how many hidden fields could
1022
 
        have null
1023
 
      */
1024
 
      hidden_null_count=null_count;
1025
 
      /*
1026
 
        We need to update hidden_field_count as we may have stored group
1027
 
        functions with constant arguments
1028
 
      */
1029
 
      param->hidden_field_count= fieldnr;
1030
 
      null_count= 0;
1031
 
    }
1032
 
  }
1033
 
  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
1034
 
  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
1035
 
  field_count= fieldnr;
1036
 
  *reg_field= 0;
1037
 
  *blob_field= 0;                               // End marker
1038
 
  table->getMutableShare()->setFieldSize(field_count);
1039
 
 
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)
1046
 
  {
1047
 
    table->getMutableShare()->storage_engine= myisam_engine;
1048
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
1049
 
    if (group &&
1050
 
        (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
1051
 
         param->group_length > table->cursor->getEngine()->max_key_length()))
1052
 
    {
1053
 
      using_unique_constraint= true;
1054
 
    }
1055
 
  }
1056
 
  else
1057
 
  {
1058
 
    table->getMutableShare()->storage_engine= heap_engine;
1059
 
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
1060
 
  }
1061
 
  if (! table->cursor)
1062
 
    goto err;
1063
 
 
1064
 
 
1065
 
  if (! using_unique_constraint)
1066
 
    reclength+= group_null_items;       // null flag is stored separately
1067
 
 
1068
 
  table->getMutableShare()->blob_fields= blob_count;
1069
 
  if (blob_count == 0)
1070
 
  {
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++;
1074
 
    else
1075
 
      null_count++;
1076
 
  }
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;
1081
 
  if (!reclength)
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)))
1085
 
    use_packed_rows= 1;
1086
 
 
1087
 
  table->getMutableShare()->setRecordLength(reclength);
1088
 
  {
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)))
1092
 
    {
1093
 
      goto err;
1094
 
    }
1095
 
    table->record[1]= table->getInsertRecord()+alloc_length;
1096
 
    table->getMutableShare()->resizeDefaultValues(alloc_length);
1097
 
  }
1098
 
  copy_func[0]= 0;                              // End marker
1099
 
  param->func_count= copy_func - param->items_to_copy;
1100
 
 
1101
 
  table->setup_tmp_table_column_bitmaps();
1102
 
 
1103
 
  recinfo=param->start_recinfo;
1104
 
  null_flags=(unsigned char*) table->getInsertRecord();
1105
 
  pos=table->getInsertRecord()+ null_pack_length;
1106
 
  if (null_pack_length)
1107
 
  {
1108
 
    memset(recinfo, 0, sizeof(*recinfo));
1109
 
    recinfo->type=FIELD_NORMAL;
1110
 
    recinfo->length=null_pack_length;
1111
 
    recinfo++;
1112
 
    memset(null_flags, 255, null_pack_length);  // Set null fields
1113
 
 
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;
1117
 
  }
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++)
1121
 
  {
1122
 
    Field *field= *reg_field;
1123
 
    uint32_t length;
1124
 
    memset(recinfo, 0, sizeof(*recinfo));
1125
 
 
1126
 
    if (!(field->flags & NOT_NULL_FLAG))
1127
 
    {
1128
 
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
1129
 
      {
1130
 
        /*
1131
 
          We have to reserve one byte here for NULL bits,
1132
 
          as this is updated by 'end_update()'
1133
 
        */
1134
 
        *pos++= '\0';                           // Null is stored here
1135
 
        recinfo->length= 1;
1136
 
        recinfo->type=FIELD_NORMAL;
1137
 
        recinfo++;
1138
 
        memset(recinfo, 0, sizeof(*recinfo));
1139
 
      }
1140
 
      else
1141
 
      {
1142
 
        recinfo->null_bit= 1 << (null_count & 7);
1143
 
        recinfo->null_pos= null_count/8;
1144
 
      }
1145
 
      field->move_field(pos,null_flags+null_count/8,
1146
 
                        1 << (null_count & 7));
1147
 
      null_count++;
1148
 
    }
1149
 
    else
1150
 
      field->move_field(pos,(unsigned char*) 0,0);
1151
 
    field->reset();
1152
 
 
1153
 
    /*
1154
 
      Test if there is a default field value. The test for ->ptr is to skip
1155
 
      'offset' fields generated by initalize_tables
1156
 
    */
1157
 
    if (default_field[i] && default_field[i]->ptr)
1158
 
    {
1159
 
      /*
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.
1163
 
      */
1164
 
      ptrdiff_t diff;
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())
1170
 
        field->set_null();
1171
 
      else
1172
 
      {
1173
 
        field->set_notnull();
1174
 
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
1175
 
      }
1176
 
      orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
1177
 
    }
1178
 
 
1179
 
    if (from_field[i])
1180
 
    {                                           /* Not a table Item */
1181
 
      copy->set(field,from_field[i],save_sum_fields);
1182
 
      copy++;
1183
 
    }
1184
 
    length=field->pack_length();
1185
 
    pos+= length;
1186
 
 
1187
 
    /* Make entry for create table */
1188
 
    recinfo->length=length;
1189
 
    if (field->flags & BLOB_FLAG)
1190
 
      recinfo->type= (int) FIELD_BLOB;
1191
 
    else
1192
 
      recinfo->type=FIELD_NORMAL;
1193
 
    if (!--hidden_field_count)
1194
 
      null_count=(null_count+7) & ~7;           // move to next byte
1195
 
  }
1196
 
 
1197
 
  param->copy_field_end=copy;
1198
 
  param->recinfo=recinfo;
1199
 
  table->storeRecordAsDefault();        // Make empty default record
1200
 
 
1201
 
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)              // No limit
1202
 
  {
1203
 
    max_rows= ~(uint64_t) 0;
1204
 
  }
1205
 
  else
1206
 
  {
1207
 
    max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
1208
 
                           min(session->variables.tmp_table_size,
1209
 
                               session->variables.max_heap_table_size) :
1210
 
                           session->variables.tmp_table_size) /
1211
 
                          table->getMutableShare()->getRecordLength());
1212
 
  }
1213
 
 
1214
 
  set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
1215
 
  /*
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.
1218
 
  */
1219
 
  set_if_smaller(max_rows, rows_limit);
1220
 
 
1221
 
  table->getMutableShare()->setMaxRows(max_rows);
1222
 
 
1223
 
  param->end_write_records= rows_limit;
1224
 
 
1225
 
  keyinfo= param->keyinfo;
1226
 
 
1227
 
  if (group)
1228
 
  {
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++)
1243
 
    {
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) ?
1255
 
        0 : 1;
1256
 
      if (!using_unique_constraint)
1257
 
      {
1258
 
        cur_group->buff=(char*) group_buff;
1259
 
        if (!(cur_group->field= field->new_key_field(session->mem_root,table,
1260
 
                                                     group_buff +
1261
 
                                                     test(maybe_null),
1262
 
                                                     field->null_ptr,
1263
 
                                                     field->null_bit)))
1264
 
          goto err;
1265
 
        if (maybe_null)
1266
 
        {
1267
 
          /*
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()'
1272
 
          */
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
1279
 
        }
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();
1283
 
      }
1284
 
      keyinfo->key_length+=  key_part_info->length;
1285
 
    }
1286
 
  }
1287
 
 
1288
 
  if (distinct && field_count != param->hidden_field_count)
1289
 
  {
1290
 
    /*
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.
1295
 
    */
1296
 
    if (blob_count)
1297
 
    {
1298
 
      /*
1299
 
        Special mode for index creation in MyISAM used to support unique
1300
 
        indexes on blobs with arbitrary length. Such indexes cannot be
1301
 
        used for lookups.
1302
 
      */
1303
 
      table->getMutableShare()->uniques= 1;
1304
 
    }
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));
1308
 
    table->distinct= 1;
1309
 
    table->getMutableShare()->keys= 1;
1310
 
    if (!(key_part_info= (KeyPartInfo*)
1311
 
         table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
1312
 
      goto err;
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;
1321
 
 
1322
 
    /*
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.
1326
 
    */
1327
 
    if (null_pack_length && table->getMutableShare()->uniques)
1328
 
    {
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,
1335
 
                                                0,
1336
 
                                                (unsigned char*) 0,
1337
 
                                                (uint32_t) 0,
1338
 
                                                NULL,
1339
 
                                                &my_charset_bin);
1340
 
      if (!key_part_info->field)
1341
 
        goto err;
1342
 
      key_part_info->field->init(table);
1343
 
      key_part_info->key_type= 1; /* binary comparison */
1344
 
      key_part_info->type=    HA_KEYTYPE_BINARY;
1345
 
      key_part_info++;
1346
 
    }
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 ;
1349
 
         i < field_count;
1350
 
         i++, reg_field++, key_part_info++)
1351
 
    {
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
1361
 
        might be reused.
1362
 
      */
1363
 
      key_part_info->store_length= key_part_info->length;
1364
 
 
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;
1370
 
 
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) ?
1376
 
        0 : 1;
1377
 
    }
1378
 
  }
1379
 
 
1380
 
  if (session->is_fatal_error)                          // If end of memory
1381
 
    goto err;
1382
 
  table->getMutableShare()->db_record_offset= 1;
1383
 
  if (table->getShare()->db_type() == myisam_engine)
1384
 
  {
1385
 
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1386
 
                                       &param->recinfo, select_options))
1387
 
      goto err;
1388
 
  }
1389
 
  assert(table->in_use);
1390
 
  if (table->open_tmp_table())
1391
 
    goto err;
1392
 
 
1393
 
  session->mem_root= mem_root_save;
1394
 
 
1395
 
  return(table);
1396
 
 
1397
 
err:
1398
 
  session->mem_root= mem_root_save;
1399
 
  table= NULL;
1400
 
 
1401
 
  return NULL;
1402
 
}
1403
 
 
1404
 
/****************************************************************************/
1405
 
 
1406
 
void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
1407
 
                               boost::dynamic_bitset<>& write_set_arg)
1408
 
{
1409
 
  read_set= &read_set_arg;
1410
 
  write_set= &write_set_arg;
1411
 
}
1412
 
 
1413
 
 
1414
 
const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
1415
 
{
1416
 
  const boost::dynamic_bitset<> old= in_map;
1417
 
  in_map= getShare()->all_set;
1418
 
  return old;
1419
 
}
1420
 
 
1421
 
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
1422
 
{
1423
 
  for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
1424
 
  {
1425
 
    if (old.test(i))
1426
 
    {
1427
 
      read_set->set(i);
1428
 
    }
1429
 
    else
1430
 
    {
1431
 
      read_set->reset(i);
1432
 
    }
1433
 
  }
1434
 
}
1435
 
 
1436
 
uint32_t Table::find_shortest_key(const key_map *usable_keys)
1437
 
{
1438
 
  uint32_t min_length= UINT32_MAX;
1439
 
  uint32_t best= MAX_KEY;
1440
 
  if (usable_keys->any())
1441
 
  {
1442
 
    for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
1443
 
    {
1444
 
      if (usable_keys->test(nr))
1445
 
      {
1446
 
        if (key_info[nr].key_length < min_length)
1447
 
        {
1448
 
          min_length= key_info[nr].key_length;
1449
 
          best=nr;
1450
 
        }
1451
 
      }
1452
 
    }
1453
 
  }
1454
 
  return best;
1455
 
}
1456
 
 
1457
 
/*****************************************************************************
1458
 
  Remove duplicates from tmp table
1459
 
  This should be recoded to add a unique index to the table and remove
1460
 
  duplicates
1461
 
  Table is a locked single thread table
1462
 
  fields is the number of fields to check (from the end)
1463
 
*****************************************************************************/
1464
 
 
1465
 
bool Table::compare_record(Field **ptr)
1466
 
{
1467
 
  for (; *ptr ; ptr++)
1468
 
  {
1469
 
    if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
1470
 
      return true;
1471
 
  }
1472
 
  return false;
1473
 
}
1474
 
 
1475
 
/**
1476
 
   True if the table's input and output record buffers are comparable using
1477
 
   compare_records(TABLE*).
1478
 
 */
1479
 
bool Table::records_are_comparable()
1480
 
{
1481
 
  return ((getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) == 0) ||
1482
 
          write_set->is_subset_of(*read_set));
1483
 
}
1484
 
 
1485
 
/**
1486
 
   Compares the input and outbut record buffers of the table to see if a row
1487
 
   has changed. The algorithm iterates over updated columns and if they are
1488
 
   nullable compares NULL bits in the buffer before comparing actual
1489
 
   data. Special care must be taken to compare only the relevant NULL bits and
1490
 
   mask out all others as they may be undefined. The storage engine will not
1491
 
   and should not touch them.
1492
 
 
1493
 
   @param table The table to evaluate.
1494
 
 
1495
 
   @return true if row has changed.
1496
 
   @return false otherwise.
1497
 
*/
1498
 
bool Table::compare_records()
1499
 
{
1500
 
  if (getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) != 0)
1501
 
  {
1502
 
    /*
1503
 
      Storage engine may not have read all columns of the record.  Fields
1504
 
      (including NULL bits) not in the write_set may not have been read and
1505
 
      can therefore not be compared.
1506
 
    */
1507
 
    for (Field **ptr= this->field ; *ptr != NULL; ptr++)
1508
 
    {
1509
 
      Field *f= *ptr;
1510
 
      if (write_set->test(f->position()))
1511
 
      {
1512
 
        if (f->real_maybe_null())
1513
 
        {
1514
 
          unsigned char null_byte_index= f->null_ptr - record[0];
1515
 
 
1516
 
          if (((record[0][null_byte_index]) & f->null_bit) !=
1517
 
              ((record[1][null_byte_index]) & f->null_bit))
1518
 
            return true;
1519
 
        }
1520
 
        if (f->cmp_binary_offset(getShare()->rec_buff_length))
1521
 
          return true;
1522
 
      }
1523
 
    }
1524
 
    return false;
1525
 
  }
1526
 
 
1527
 
  /*
1528
 
    The storage engine has read all columns, so it's safe to compare all bits
1529
 
    including those not in the write_set. This is cheaper than the
1530
 
    field-by-field comparison done above.
1531
 
  */
1532
 
  if (not getShare()->blob_fields + getShare()->hasVariableWidth())
1533
 
    // Fixed-size record: do bitwise comparison of the records
1534
 
    return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
1535
 
 
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 */
1539
 
 
1540
 
  /* Compare updated fields */
1541
 
  for (Field **ptr= field ; *ptr ; ptr++)
1542
 
  {
1543
 
    if (isWriteSet((*ptr)->position()) &&
1544
 
        (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
1545
 
      return true;
1546
 
  }
1547
 
  return false;
1548
 
}
1549
 
 
1550
 
/*
1551
 
 * Store a record from previous record into next
1552
 
 *
1553
 
 */
1554
 
void Table::storeRecord()
1555
 
{
1556
 
  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1557
 
}
1558
 
 
1559
 
/*
1560
 
 * Store a record as an insert
1561
 
 *
1562
 
 */
1563
 
void Table::storeRecordAsInsert()
1564
 
{
1565
 
  assert(insert_values.size() >= getShare()->getRecordLength());
1566
 
  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
1567
 
}
1568
 
 
1569
 
/*
1570
 
 * Store a record with default values
1571
 
 *
1572
 
 */
1573
 
void Table::storeRecordAsDefault()
1574
 
{
1575
 
  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1576
 
}
1577
 
 
1578
 
/*
1579
 
 * Restore a record from previous record into next
1580
 
 *
1581
 
 */
1582
 
void Table::restoreRecord()
1583
 
{
1584
 
  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
1585
 
}
1586
 
 
1587
 
/*
1588
 
 * Restore a record with default values
1589
 
 *
1590
 
 */
1591
 
void Table::restoreRecordAsDefault()
1592
 
{
1593
 
  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
1594
 
}
1595
 
 
1596
 
/*
1597
 
 * Empty a record
1598
 
 *
1599
 
 */
1600
 
void Table::emptyRecord()
1601
 
{
1602
 
  restoreRecordAsDefault();
1603
 
  memset(null_flags, 255, getShare()->null_bytes);
1604
 
}
1605
 
 
1606
 
Table::Table() : 
1607
 
  field(NULL),
1608
 
  cursor(NULL),
1609
 
  next(NULL),
1610
 
  prev(NULL),
1611
 
  read_set(NULL),
1612
 
  write_set(NULL),
1613
 
  tablenr(0),
1614
 
  db_stat(0),
1615
 
  def_read_set(),
1616
 
  def_write_set(),
1617
 
  tmp_set(),
1618
 
  in_use(NULL),
1619
 
  key_info(NULL),
1620
 
  next_number_field(NULL),
1621
 
  found_next_number_field(NULL),
1622
 
  timestamp_field(NULL),
1623
 
  pos_in_table_list(NULL),
1624
 
  group(NULL),
1625
 
  null_flags(NULL),
1626
 
  lock_position(0),
1627
 
  lock_data_start(0),
1628
 
  lock_count(0),
1629
 
  used_fields(0),
1630
 
  status(0),
1631
 
  derived_select_number(0),
1632
 
  current_lock(F_UNLCK),
1633
 
  copy_blobs(false),
1634
 
  maybe_null(false),
1635
 
  null_row(false),
1636
 
  force_index(false),
1637
 
  distinct(false),
1638
 
  const_table(false),
1639
 
  no_rows(false),
1640
 
  key_read(false),
1641
 
  no_keyread(false),
1642
 
  open_placeholder(false),
1643
 
  locked_by_name(false),
1644
 
  no_cache(false),
1645
 
  auto_increment_field_not_null(false),
1646
 
  alias_name_used(false),
1647
 
  query_id(0),
1648
 
  quick_condition_rows(0),
1649
 
  timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1650
 
  map(0),
1651
 
  quick_rows(),
1652
 
  const_key_parts(),
1653
 
  quick_key_parts(),
1654
 
  quick_n_ranges()
1655
 
{
1656
 
  record[0]= (unsigned char *) 0;
1657
 
  record[1]= (unsigned char *) 0;
1658
 
}
1659
 
 
1660
 
/*****************************************************************************
1661
 
  The different ways to read a record
1662
 
  Returns -1 if row was not found, 0 if row was found and 1 on errors
1663
 
*****************************************************************************/
1664
 
 
1665
 
/** Help function when we get some an error from the table Cursor. */
1666
 
 
1667
 
int Table::report_error(int error)
1668
 
{
1669
 
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
1670
 
  {
1671
 
    status= STATUS_GARBAGE;
1672
 
    return -1;                                  // key not found; ok
1673
 
  }
1674
 
  /*
1675
 
    Locking reads can legally return also these errors, do not
1676
 
    print them to the .err log
1677
 
  */
1678
 
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
1679
 
    errmsg_printf(error::ERROR, _("Got error %d when reading table '%s'"),
1680
 
                  error, getShare()->getPath());
1681
 
  print_error(error, MYF(0));
1682
 
 
1683
 
  return 1;
1684
 
}
1685
 
 
1686
 
 
1687
 
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
1688
 
{
1689
 
  used_fields= 0;
1690
 
  const_table= 0;
1691
 
  null_row= 0;
1692
 
  status= STATUS_NO_RECORD;
1693
 
  maybe_null= table_list->outer_join;
1694
 
  TableList *embedding= table_list->getEmbedding();
1695
 
  while (!maybe_null && embedding)
1696
 
  {
1697
 
    maybe_null= embedding->outer_join;
1698
 
    embedding= embedding->getEmbedding();
1699
 
  }
1700
 
  tablenr= table_number;
1701
 
  map= (table_map) 1 << table_number;
1702
 
  force_index= table_list->force_index;
1703
 
  covering_keys= getShare()->keys_for_keyread;
1704
 
  merge_keys.reset();
1705
 
}
1706
 
 
1707
 
 
1708
 
bool Table::fill_item_list(List<Item> *item_list) const
1709
 
{
1710
 
  /*
1711
 
    All Item_field's created using a direct pointer to a field
1712
 
    are fixed in Item_field constructor.
1713
 
  */
1714
 
  for (Field **ptr= field; *ptr; ptr++)
1715
 
  {
1716
 
    Item_field *item= new Item_field(*ptr);
1717
 
    if (!item || item_list->push_back(item))
1718
 
      return true;
1719
 
  }
1720
 
  return false;
1721
 
}
1722
 
 
1723
 
 
1724
 
void Table::filesort_free_buffers(bool full)
1725
 
{
1726
 
  if (sort.record_pointers)
1727
 
  {
1728
 
    free((unsigned char*) sort.record_pointers);
1729
 
    sort.record_pointers=0;
1730
 
  }
1731
 
  if (full)
1732
 
  {
1733
 
    if (sort.sort_keys )
1734
 
    {
1735
 
      if ((unsigned char*) sort.sort_keys)
1736
 
        free((unsigned char*) sort.sort_keys);
1737
 
      sort.sort_keys= 0;
1738
 
    }
1739
 
    if (sort.buffpek)
1740
 
    {
1741
 
      if ((unsigned char*) sort.buffpek)
1742
 
        free((unsigned char*) sort.buffpek);
1743
 
      sort.buffpek= 0;
1744
 
      sort.buffpek_len= 0;
1745
 
    }
1746
 
  }
1747
 
 
1748
 
  if (sort.addon_buf)
1749
 
  {
1750
 
    free((char *) sort.addon_buf);
1751
 
    free((char *) sort.addon_field);
1752
 
    sort.addon_buf=0;
1753
 
    sort.addon_field=0;
1754
 
  }
1755
 
}
1756
 
 
1757
 
/*
1758
 
  Is this instance of the table should be reopen or represents a name-lock?
1759
 
*/
1760
 
bool Table::needs_reopen_or_name_lock() const
1761
 
1762
 
  return getShare()->getVersion() != refresh_version;
1763
 
}
1764
 
 
1765
 
uint32_t Table::index_flags(uint32_t idx) const
1766
 
{
1767
 
  return getShare()->getEngine()->index_flags(getShare()->getKeyInfo(idx).algorithm);
1768
 
}
1769
 
 
1770
 
void Table::print_error(int error, myf errflag) const
1771
 
{
1772
 
  getShare()->getEngine()->print_error(error, errflag, *this);
1773
 
}
1774
 
 
1775
 
} /* namespace drizzled */
 
3842
/*
 
3843
  Check type of .frm if we are not going to parse it
 
3844
 
 
3845
  SYNOPSIS
 
3846
  mysql_frm_type()
 
3847
  path        path to file
 
3848
 
 
3849
  RETURN
 
3850
  FRMTYPE_ERROR       error                
 
3851
  FRMTYPE_TABLE       table                
 
3852
 */    
 
3853
 
 
3854
frm_type_enum mysql_frm_type(THD *thd, char *path, enum legacy_db_type *dbt)
 
3855
{   
 
3856
  File file;
 
3857
  uchar header[10];     /* This should be optimized */
 
3858
  int error;
 
3859
  DBUG_ENTER("mysql_frm_type");
 
3860
 
 
3861
  *dbt= DB_TYPE_UNKNOWN;
 
3862
 
 
3863
  if ((file= my_open(path, O_RDONLY | O_SHARE, MYF(0))) < 0)
 
3864
    DBUG_RETURN(FRMTYPE_ERROR);
 
3865
  error= my_read(file, (uchar*) header, sizeof(header), MYF(MY_NABP));
 
3866
  my_close(file, MYF(MY_WME));
 
3867
 
 
3868
  if (error)
 
3869
    DBUG_RETURN(FRMTYPE_ERROR);
 
3870
 
 
3871
  /*  
 
3872
    This is just a check for DB_TYPE. We'll return default unknown type
 
3873
    if the following test is true (arg #3). This should not have effect
 
3874
    on return value from this function (default FRMTYPE_TABLE)
 
3875
   */  
 
3876
  if (header[0] != (uchar) 254 || header[1] != 1 ||
 
3877
      (header[2] != FRM_VER && header[2] != FRM_VER+1 &&
 
3878
       (header[2] < FRM_VER+3 || header[2] > FRM_VER+4)))
 
3879
    DBUG_RETURN(FRMTYPE_TABLE);
 
3880
 
 
3881
  *dbt= (enum legacy_db_type) (uint) *(header + 3);
 
3882
  DBUG_RETURN(FRMTYPE_TABLE);                   // Is probably a .frm table
 
3883
}
 
3884
 
 
3885
 
 
3886
/*****************************************************************************
 
3887
** Instansiate templates
 
3888
*****************************************************************************/
 
3889
 
 
3890
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
3891
template class List<String>;
 
3892
template class List_iterator<String>;
 
3893
#endif