~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
17
/* Some general useful functions */
18
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
19
#include <drizzled/server_includes.h>
549 by Monty Taylor
Took gettext.h out of header files.
20
#include <drizzled/error.h>
21
#include <drizzled/gettext.h>
1 by brian
clean slate
22
553.1.3 by Monty Taylor
Split out nested_join.h.
23
#include <drizzled/nested_join.h>
520.8.2 by Monty Taylor
Moved sql_parse.h and sql_error.h out of common_includes.
24
#include <drizzled/sql_parse.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
25
#include <drizzled/item/sum.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
26
#include <drizzled/table_list.h>
27
#include <drizzled/session.h>
28
#include <drizzled/sql_base.h>
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
29
#include <drizzled/sql_select.h>
584.5.1 by Monty Taylor
Removed field includes from field.h.
30
#include <drizzled/field/blob.h>
31
#include <drizzled/field/varstring.h>
32
#include <drizzled/field/double.h>
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
33
#include <drizzled/unireg.h>
988.1.1 by Jay Pipes
Changes libserialize to libdrizzledmessage per ML discussion. All GPB messages are now in the drizzled::message namespace.
34
#include <drizzled/message/table.pb.h>
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
35
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
36
#include <drizzled/item/string.h>
37
#include <drizzled/item/int.h>
38
#include <drizzled/item/decimal.h>
39
#include <drizzled/item/float.h>
40
#include <drizzled/item/null.h>
982.1.11 by Padraig O'Sullivan
Reverted my changes for replacing Bitmap<> for the moment. Going to fix up
41
1130.3.9 by Monty Taylor
Wrapped table_proto_write.cc code in namespace drizzled.
42
#include "drizzled/table_proto.h"
1095.3.3 by Stewart Smith
move drizzle_proto_exists and drizzle_read_table_proto out of unireg.h and into table_proto.h
43
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
44
#include <string>
45
#include <vector>
46
#include <algorithm>
47
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
48
using namespace drizzled;
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
49
using namespace std;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
50
using namespace drizzled;
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
51
1208.3.2 by brian
Update for Cursor renaming.
52
/* Functions defined in this cursor */
1 by brian
clean slate
53
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
54
void open_table_error(TableShare *share, int error, int db_errno,
1 by brian
clean slate
55
                      myf errortype, int errarg);
56
57
/*************************************************************************/
58
59
/* Get column name from column hash */
60
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
61
static unsigned char *get_field_name(Field **buff, size_t *length, bool)
1 by brian
clean slate
62
{
895 by Brian Aker
Completion (?) of uint conversion.
63
  *length= (uint32_t) strlen((*buff)->field_name);
481 by Brian Aker
Remove all of uchar.
64
  return (unsigned char*) (*buff)->field_name;
1 by brian
clean slate
65
}
66
1095.3.17 by Stewart Smith
get_table_category doesn't need table name and can be static to table.cc
67
static TABLE_CATEGORY get_table_category(const LEX_STRING *db)
1 by brian
clean slate
68
{
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
69
  assert(db != NULL);
1 by brian
clean slate
70
575.4.7 by Monty Taylor
More header cleanup.
71
  if ((db->length == INFORMATION_SCHEMA_NAME.length()) &&
1 by brian
clean slate
72
      (my_strcasecmp(system_charset_info,
575.4.7 by Monty Taylor
More header cleanup.
73
                    INFORMATION_SCHEMA_NAME.c_str(),
1 by brian
clean slate
74
                    db->str) == 0))
75
  {
76
    return TABLE_CATEGORY_INFORMATION;
77
  }
78
79
  return TABLE_CATEGORY_USER;
80
}
81
82
83
/*
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
84
  Allocate a setup TableShare structure
1 by brian
clean slate
85
86
  SYNOPSIS
87
    alloc_table_share()
327.2.4 by Brian Aker
Refactoring table.h
88
    TableList		Take database and table name from there
1 by brian
clean slate
89
    key			Table cache key (db \0 table_name \0...)
90
    key_length		Length of key
91
92
  RETURN
93
    0  Error (out of memory)
94
    #  Share
95
*/
96
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
97
TableShare *alloc_table_share(TableList *table_list, char *key,
482 by Brian Aker
Remove uint.
98
                               uint32_t key_length)
1 by brian
clean slate
99
{
100
  MEM_ROOT mem_root;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
101
  TableShare *share;
1 by brian
clean slate
102
  char *key_buff, *path_buff;
103
  char path[FN_REFLEN];
482 by Brian Aker
Remove uint.
104
  uint32_t path_length;
1 by brian
clean slate
105
106
  path_length= build_table_filename(path, sizeof(path) - 1,
107
                                    table_list->db,
1039.1.6 by Brian Aker
Refactor for build_table_filename()
108
                                    table_list->table_name, false);
1 by brian
clean slate
109
  init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
110
  if (multi_alloc_root(&mem_root,
111
                       &share, sizeof(*share),
112
                       &key_buff, key_length,
113
                       &path_buff, path_length + 1,
114
                       NULL))
115
  {
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
116
    memset(share, 0, sizeof(*share));
1 by brian
clean slate
117
118
    share->set_table_cache_key(key_buff, key, key_length);
119
120
    share->path.str= path_buff;
121
    share->path.length= path_length;
641.4.1 by Toru Maesaka
First pass of replacing MySQL's my_stpcpy() with appropriate libc calls
122
    strcpy(share->path.str, path);
1 by brian
clean slate
123
    share->normalized_path.str=    share->path.str;
124
    share->normalized_path.length= path_length;
125
126
    share->version=       refresh_version;
127
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
128
    memcpy(&share->mem_root, &mem_root, sizeof(mem_root));
1 by brian
clean slate
129
    pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
130
    pthread_cond_init(&share->cond, NULL);
131
  }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
132
  return(share);
1 by brian
clean slate
133
}
134
135
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
136
static enum_field_types proto_field_type_to_drizzle_type(uint32_t proto_field_type)
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
137
{
138
  enum_field_types field_type;
139
140
  switch(proto_field_type)
141
  {
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
142
  case message::Table::Field::INTEGER:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
143
    field_type= DRIZZLE_TYPE_LONG;
144
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
145
  case message::Table::Field::DOUBLE:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
146
    field_type= DRIZZLE_TYPE_DOUBLE;
147
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
148
  case message::Table::Field::TIMESTAMP:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
149
    field_type= DRIZZLE_TYPE_TIMESTAMP;
150
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
151
  case message::Table::Field::BIGINT:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
152
    field_type= DRIZZLE_TYPE_LONGLONG;
153
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
154
  case message::Table::Field::DATETIME:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
155
    field_type= DRIZZLE_TYPE_DATETIME;
156
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
157
  case message::Table::Field::DATE:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
158
    field_type= DRIZZLE_TYPE_DATE;
159
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
160
  case message::Table::Field::VARCHAR:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
161
    field_type= DRIZZLE_TYPE_VARCHAR;
162
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
163
  case message::Table::Field::DECIMAL:
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
164
    field_type= DRIZZLE_TYPE_DECIMAL;
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
165
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
166
  case message::Table::Field::ENUM:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
167
    field_type= DRIZZLE_TYPE_ENUM;
168
    break;
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
169
  case message::Table::Field::BLOB:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
170
    field_type= DRIZZLE_TYPE_BLOB;
171
    break;
172
  default:
1152.3.1 by Stewart Smith
remove last bits of TINYINT. NOTE: this needs an updated libdrizzle to prevent a small drizzledump test failure
173
    field_type= DRIZZLE_TYPE_LONG; /* Set value to kill GCC warning */
899.1.1 by brian
Merge of Stewart + Jay's fix.
174
    assert(1);
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
175
  }
176
177
  return field_type;
178
}
179
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
180
static Item *default_value_item(enum_field_types field_type,
181
	                        const CHARSET_INFO *charset,
182
                                bool default_null, const string *default_value,
183
                                const string *default_bin_value)
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
184
{
185
  Item *default_item= NULL;
186
  int error= 0;
187
1034.1.2 by Brian Aker
Correct if() style
188
  if (default_null)
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
189
  {
190
    return new Item_null();
191
  }
192
193
  switch(field_type)
194
  {
195
  case DRIZZLE_TYPE_LONG:
196
  case DRIZZLE_TYPE_LONGLONG:
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
197
    default_item= new Item_int(default_value->c_str(),
198
			       (int64_t) my_strtoll10(default_value->c_str(),
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
199
						      NULL,
200
						      &error),
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
201
			       default_value->length());
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
202
    break;
203
  case DRIZZLE_TYPE_DOUBLE:
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
204
    default_item= new Item_float(default_value->c_str(),
205
				 default_value->length());
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
206
    break;
207
  case DRIZZLE_TYPE_NULL:
896.4.15 by Stewart Smith
should be assert, not creating Item_null as default null is set up before the type switch
208
    assert(false);
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
209
  case DRIZZLE_TYPE_TIMESTAMP:
210
  case DRIZZLE_TYPE_DATETIME:
211
  case DRIZZLE_TYPE_DATE:
1000.1.1 by Brian Aker
Remove dead table bits from old replication for ROW
212
    if (default_value->compare("NOW()") == 0)
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
213
      break;
214
  case DRIZZLE_TYPE_ENUM:
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
215
    default_item= new Item_string(default_value->c_str(),
216
				  default_value->length(),
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
217
				  system_charset_info);
218
    break;
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
219
  case DRIZZLE_TYPE_VARCHAR:
220
  case DRIZZLE_TYPE_BLOB: /* Blob is here due to TINYTEXT. Feel the hate. */
1034.1.2 by Brian Aker
Correct if() style
221
    if (charset==&my_charset_bin)
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
222
    {
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
223
      default_item= new Item_string(default_bin_value->c_str(),
224
				    default_bin_value->length(),
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
225
				    &my_charset_bin);
226
    }
227
    else
228
    {
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
229
      default_item= new Item_string(default_value->c_str(),
230
				    default_value->length(),
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
231
				    system_charset_info);
232
    }
233
    break;
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
234
  case DRIZZLE_TYPE_DECIMAL:
910.4.11 by Stewart Smith
fix default value Item generation. (spotted on Solaris)
235
    default_item= new Item_decimal(default_value->c_str(),
236
				   default_value->length(),
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
237
				   system_charset_info);
238
    break;
239
  }
240
241
  return default_item;
242
}
243
1198 by Brian Aker
Merge Brian
244
int drizzled::parse_table_proto(Session& session,
1130.3.9 by Monty Taylor
Wrapped table_proto_write.cc code in namespace drizzled.
245
                                message::Table &table,
246
                                TableShare *share)
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
247
{
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
248
  int error= 0;
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
249
  Cursor *handler_file= NULL;
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
250
1119.9.14 by Jay Pipes
Style cleanups after review. Thanks Monty :)
251
  share->setTableProto(new(nothrow) message::Table(table));
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
252
1130.1.13 by Monty Taylor
Moved some simple methods back into header to they can be inlined. Removed a couple wrapper methods.
253
  share->storage_engine= plugin::StorageEngine::findByName(session, table.engine().name());
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
254
  assert(share->storage_engine); // We use an assert() here because we should never get this far and still have no suitable engine.
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
255
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
256
  message::Table::TableOptions table_options;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
257
1034.1.2 by Brian Aker
Correct if() style
258
  if (table.has_options())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
259
    table_options= table.options();
260
1117.1.8 by Brian Aker
More dead option removal.
261
  uint32_t db_create_options= 0;
896.4.1 by Stewart Smith
read db_create_options from proto (was already stored, just had to set the right bits) instead of FRM
262
1034.1.2 by Brian Aker
Correct if() style
263
  if (table_options.has_pack_keys())
896.4.1 by Stewart Smith
read db_create_options from proto (was already stored, just had to set the right bits) instead of FRM
264
  {
1034.1.2 by Brian Aker
Correct if() style
265
    if (table_options.pack_keys())
896.4.1 by Stewart Smith
read db_create_options from proto (was already stored, just had to set the right bits) instead of FRM
266
      db_create_options|= HA_OPTION_PACK_KEYS;
267
    else
268
      db_create_options|= HA_OPTION_NO_PACK_KEYS;
269
  }
270
1034.1.2 by Brian Aker
Correct if() style
271
  if (table_options.pack_record())
896.4.1 by Stewart Smith
read db_create_options from proto (was already stored, just had to set the right bits) instead of FRM
272
    db_create_options|= HA_OPTION_PACK_RECORD;
273
896.4.2 by Stewart Smith
db_create_option is silently truncated to 16bits in FRM write path.
274
  /* db_create_options was stored as 2 bytes in FRM
275
     Any HA_OPTION_ that doesn't fit into 2 bytes was silently truncated away.
276
   */
277
  share->db_create_options= (db_create_options & 0x0000FFFF);
896.4.1 by Stewart Smith
read db_create_options from proto (was already stored, just had to set the right bits) instead of FRM
278
  share->db_options_in_use= share->db_create_options;
279
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
280
  share->row_type= table_options.has_row_type() ?
281
    (enum row_type) table_options.row_type() : ROW_TYPE_DEFAULT;
282
283
  share->block_size= table_options.has_block_size() ?
284
    table_options.block_size() : 0;
285
286
  share->table_charset= get_charset(table_options.has_collation_id()?
287
				    table_options.collation_id() : 0);
288
289
  if (!share->table_charset)
290
  {
291
    /* unknown charset in head[38] or pre-3.23 frm */
292
    if (use_mb(default_charset_info))
293
    {
294
      /* Warn that we may be changing the size of character columns */
295
      errmsg_printf(ERRMSG_LVL_WARN,
296
		    _("'%s' had no or invalid character set, "
297
		      "and default character set is multi-byte, "
298
		      "so character column sizes may have changed"),
299
		    share->path.str);
300
    }
301
    share->table_charset= default_charset_info;
302
  }
303
304
  share->db_record_offset= 1;
305
306
  share->blob_ptr_size= portable_sizeof_char_ptr; // more bonghits.
307
308
  share->db_low_byte_first= true;
309
310
  share->keys= table.indexes_size();
311
312
  share->key_parts= 0;
1046.1.6 by Brian Aker
Formatting/style cleanup.
313
  for (int indx= 0; indx < table.indexes_size(); indx++)
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
314
    share->key_parts+= table.indexes(indx).index_part_size();
315
316
  share->key_info= (KEY*) alloc_root(&share->mem_root,
317
				     table.indexes_size() * sizeof(KEY)
318
				     +share->key_parts*sizeof(KEY_PART_INFO));
319
320
  KEY_PART_INFO *key_part;
321
322
  key_part= reinterpret_cast<KEY_PART_INFO*>
323
    (share->key_info+table.indexes_size());
324
325
326
  ulong *rec_per_key= (ulong*) alloc_root(&share->mem_root,
327
					    sizeof(ulong*)*share->key_parts);
328
329
  share->keynames.count= table.indexes_size();
330
  share->keynames.name= NULL;
331
  share->keynames.type_names= (const char**)
332
    alloc_root(&share->mem_root, sizeof(char*) * (table.indexes_size()+1));
333
334
  share->keynames.type_lengths= (unsigned int*)
335
    alloc_root(&share->mem_root,
336
	       sizeof(unsigned int) * (table.indexes_size()+1));
337
338
  share->keynames.type_names[share->keynames.count]= NULL;
339
  share->keynames.type_lengths[share->keynames.count]= 0;
340
341
  KEY* keyinfo= share->key_info;
1046.1.6 by Brian Aker
Formatting/style cleanup.
342
  for (int keynr= 0; keynr < table.indexes_size(); keynr++, keyinfo++)
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
343
  {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
344
    message::Table::Index indx= table.indexes(keynr);
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
345
346
    keyinfo->table= 0;
347
    keyinfo->flags= 0;
348
1034.1.2 by Brian Aker
Correct if() style
349
    if (indx.is_unique())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
350
      keyinfo->flags|= HA_NOSAME;
351
1034.1.2 by Brian Aker
Correct if() style
352
    if (indx.has_options())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
353
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
354
      message::Table::Index::IndexOptions indx_options= indx.options();
1034.1.2 by Brian Aker
Correct if() style
355
      if (indx_options.pack_key())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
356
        keyinfo->flags|= HA_PACK_KEY;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
357
1034.1.2 by Brian Aker
Correct if() style
358
      if (indx_options.var_length_key())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
359
        keyinfo->flags|= HA_VAR_LENGTH_PART;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
360
1034.1.2 by Brian Aker
Correct if() style
361
      if (indx_options.null_part_key())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
362
        keyinfo->flags|= HA_NULL_PART_KEY;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
363
1034.1.2 by Brian Aker
Correct if() style
364
      if (indx_options.binary_pack_key())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
365
        keyinfo->flags|= HA_BINARY_PACK_KEY;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
366
1034.1.2 by Brian Aker
Correct if() style
367
      if (indx_options.has_partial_segments())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
368
        keyinfo->flags|= HA_KEY_HAS_PART_KEY_SEG;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
369
1034.1.2 by Brian Aker
Correct if() style
370
      if (indx_options.auto_generated_key())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
371
        keyinfo->flags|= HA_GENERATED_KEY;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
372
1034.1.2 by Brian Aker
Correct if() style
373
      if (indx_options.has_key_block_size())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
374
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
375
        keyinfo->flags|= HA_USES_BLOCK_SIZE;
376
        keyinfo->block_size= indx_options.key_block_size();
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
377
      }
378
      else
379
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
380
        keyinfo->block_size= 0;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
381
      }
382
    }
383
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
384
    switch (indx.type())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
385
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
386
    case message::Table::Index::UNKNOWN_INDEX:
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
387
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
388
      break;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
389
    case message::Table::Index::BTREE:
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
390
      keyinfo->algorithm= HA_KEY_ALG_BTREE;
391
      break;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
392
    case message::Table::Index::RTREE:
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
393
      keyinfo->algorithm= HA_KEY_ALG_RTREE;
394
      break;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
395
    case message::Table::Index::HASH:
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
396
      keyinfo->algorithm= HA_KEY_ALG_HASH;
397
      break;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
398
    case message::Table::Index::FULLTEXT:
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
399
      keyinfo->algorithm= HA_KEY_ALG_FULLTEXT;
400
401
    default:
402
      /* TODO: suitable warning ? */
403
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
404
      break;
405
    }
406
407
    keyinfo->key_length= indx.key_length();
408
409
    keyinfo->key_parts= indx.index_part_size();
410
411
    keyinfo->key_part= key_part;
412
    keyinfo->rec_per_key= rec_per_key;
413
1046.1.6 by Brian Aker
Formatting/style cleanup.
414
    for (unsigned int partnr= 0;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
415
         partnr < keyinfo->key_parts;
416
         partnr++, key_part++)
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
417
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
418
      message::Table::Index::IndexPart part;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
419
      part= indx.index_part(partnr);
420
1046.1.6 by Brian Aker
Formatting/style cleanup.
421
      *rec_per_key++= 0;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
422
423
      key_part->field= NULL;
896.3.13 by Stewart Smith
compute key_part->offset instead of storing in proto.
424
      key_part->fieldnr= part.fieldnr() + 1; // start from 1.
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
425
      key_part->null_bit= 0;
426
      /* key_part->null_offset is only set if null_bit (see later) */
427
      /* key_part->key_type= */ /* I *THINK* this may be okay.... */
428
      /* key_part->type ???? */
429
      key_part->key_part_flag= 0;
1034.1.2 by Brian Aker
Correct if() style
430
      if (part.has_in_reverse_order())
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
431
        key_part->key_part_flag= part.in_reverse_order()? HA_REVERSE_SORT : 0;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
432
433
      key_part->length= part.compare_length();
434
435
      key_part->store_length= key_part->length;
896.3.1 by Stewart Smith
removal final 2 values in indexes from being read from FRM.
436
896.3.13 by Stewart Smith
compute key_part->offset instead of storing in proto.
437
      /* key_part->offset is set later */
896.3.1 by Stewart Smith
removal final 2 values in indexes from being read from FRM.
438
      key_part->key_type= part.key_type();
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
439
    }
440
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
441
    if (! indx.has_comment())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
442
    {
443
      keyinfo->comment.length= 0;
444
      keyinfo->comment.str= NULL;
445
    }
446
    else
447
    {
448
      keyinfo->flags|= HA_USES_COMMENT;
449
      keyinfo->comment.length= indx.comment().length();
450
      keyinfo->comment.str= strmake_root(&share->mem_root,
451
					 indx.comment().c_str(),
452
					 keyinfo->comment.length);
453
    }
454
455
    keyinfo->name= strmake_root(&share->mem_root,
456
				indx.name().c_str(),
457
				indx.name().length());
458
459
    share->keynames.type_names[keynr]= keyinfo->name;
460
    share->keynames.type_lengths[keynr]= indx.name().length();
461
  }
462
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
463
  share->keys_for_keyread.reset();
464
  set_prefix(share->keys_in_use, share->keys);
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
465
869.1.4 by Stewart Smith
read number of fields from proto instead of frm
466
  share->fields= table.field_size();
869.1.5 by Stewart Smith
Remove some old-format FRM code. Slightly more in proto path than frm path.
467
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
468
  share->field= (Field**) alloc_root(&share->mem_root,
469
				     ((share->fields+1) * sizeof(Field*)));
470
  share->field[share->fields]= NULL;
471
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
472
  uint32_t null_fields= 0;
473
  share->reclength= 0;
474
475
  uint32_t *field_offsets= (uint32_t*)malloc(share->fields * sizeof(uint32_t));
476
  uint32_t *field_pack_length=(uint32_t*)malloc(share->fields*sizeof(uint32_t));
477
478
  assert(field_offsets && field_pack_length); // TODO: fixme
479
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
480
  uint32_t interval_count= 0;
481
  uint32_t interval_parts= 0;
482
896.3.11 by Stewart Smith
properly calculate field offsets in record buffer in parse_table_proto.
483
  uint32_t stored_columns_reclength= 0;
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
484
1046.1.6 by Brian Aker
Formatting/style cleanup.
485
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
486
  {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
487
    message::Table::Field pfield= table.field(fieldnr);
1034.1.2 by Brian Aker
Correct if() style
488
    if (pfield.has_constraints() && pfield.constraints().is_nullable())
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
489
      null_fields++;
490
491
    enum_field_types drizzle_field_type=
492
      proto_field_type_to_drizzle_type(pfield.type());
493
896.3.11 by Stewart Smith
properly calculate field offsets in record buffer in parse_table_proto.
494
    field_offsets[fieldnr]= stored_columns_reclength;
495
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
496
    /* the below switch is very similar to
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
497
       CreateField::create_length_to_internal_length in field.cc
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
498
       (which should one day be replace by just this code)
499
    */
500
    switch(drizzle_field_type)
501
    {
502
    case DRIZZLE_TYPE_BLOB:
503
    case DRIZZLE_TYPE_VARCHAR:
504
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
505
        message::Table::Field::StringFieldOptions field_options= pfield.string_options();
506
1119.9.15 by Jay Pipes
Merge trunk and resolve conflicts.
507
        const CHARSET_INFO *cs= get_charset(field_options.has_collation_id() ?
508
                                            field_options.collation_id() : 0);
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
509
1119.9.15 by Jay Pipes
Merge trunk and resolve conflicts.
510
        if (! cs)
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
511
          cs= default_charset_info;
512
1119.9.15 by Jay Pipes
Merge trunk and resolve conflicts.
513
        field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type,
514
                                                     field_options.length() * cs->mbmaxlen);
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
515
      }
516
      break;
517
    case DRIZZLE_TYPE_ENUM:
518
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
519
        message::Table::Field::SetFieldOptions field_options= pfield.set_options();
520
521
        field_pack_length[fieldnr]=
522
          get_enum_pack_length(field_options.field_value_size());
523
524
        interval_count++;
525
        interval_parts+= field_options.field_value_size();
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
526
      }
527
      break;
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
528
    case DRIZZLE_TYPE_DECIMAL:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
529
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
530
        message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
531
1119.9.15 by Jay Pipes
Merge trunk and resolve conflicts.
532
        field_pack_length[fieldnr]= my_decimal_get_binary_size(fo.precision(), fo.scale());
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
533
      }
534
      break;
535
    default:
536
      /* Zero is okay here as length is fixed for other types. */
537
      field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type, 0);
538
    }
539
540
    share->reclength+= field_pack_length[fieldnr];
1005.2.7 by Monty Taylor
Removed is_stored - was only used for VCOL.
541
    stored_columns_reclength+= field_pack_length[fieldnr];
896.3.11 by Stewart Smith
properly calculate field offsets in record buffer in parse_table_proto.
542
  }
543
896.3.14 by Stewart Smith
stored_rec_length should include data_offset.
544
  /* data_offset added to stored_rec_length later */
896.3.11 by Stewart Smith
properly calculate field offsets in record buffer in parse_table_proto.
545
  share->stored_rec_length= stored_columns_reclength;
546
896.4.5 by Stewart Smith
share->null_fields computed from proto. assert that same as FRM
547
  share->null_fields= null_fields;
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
548
549
  ulong null_bits= null_fields;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
550
  if (! table_options.pack_record())
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
551
    null_bits++;
552
  ulong data_offset= (null_bits + 7)/8;
553
896.3.1 by Stewart Smith
removal final 2 values in indexes from being read from FRM.
554
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
555
  share->reclength+= data_offset;
896.3.14 by Stewart Smith
stored_rec_length should include data_offset.
556
  share->stored_rec_length+= data_offset;
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
557
558
  ulong rec_buff_length;
559
560
  rec_buff_length= ALIGN_SIZE(share->reclength + 1);
561
  share->rec_buff_length= rec_buff_length;
562
563
  unsigned char* record= NULL;
564
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
565
  if (! (record= (unsigned char *) alloc_root(&share->mem_root,
566
                                              rec_buff_length)))
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
567
    abort();
568
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
569
  memset(record, 0, rec_buff_length);
570
571
  int null_count= 0;
572
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
573
  if (! table_options.pack_record())
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
574
  {
575
    null_count++; // one bit for delete mark.
576
    *record|= 1;
577
  }
578
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
579
  share->default_values= record;
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
580
1034.1.2 by Brian Aker
Correct if() style
581
  if (interval_count)
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
582
  {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
583
    share->intervals= (TYPELIB *) alloc_root(&share->mem_root,
584
                                           interval_count*sizeof(TYPELIB));
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
585
  }
586
  else
587
    share->intervals= NULL;
588
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
589
  share->fieldnames.type_names= (const char **) alloc_root(&share->mem_root,
590
                                                          (share->fields + 1) * sizeof(char*));
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
591
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
592
  share->fieldnames.type_lengths= (unsigned int *) alloc_root(&share->mem_root,
593
                                                             (share->fields + 1) * sizeof(unsigned int));
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
594
595
  share->fieldnames.type_names[share->fields]= NULL;
596
  share->fieldnames.type_lengths[share->fields]= 0;
597
  share->fieldnames.count= share->fields;
598
599
600
  /* Now fix the TYPELIBs for the intervals (enum values)
601
     and field names.
602
   */
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
603
604
  uint32_t interval_nr= 0;
605
1046.1.6 by Brian Aker
Formatting/style cleanup.
606
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
607
  {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
608
    message::Table::Field pfield= table.field(fieldnr);
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
609
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
610
    /* field names */
611
    share->fieldnames.type_names[fieldnr]= strmake_root(&share->mem_root,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
612
                                                        pfield.name().c_str(),
613
                                                        pfield.name().length());
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
614
615
    share->fieldnames.type_lengths[fieldnr]= pfield.name().length();
616
617
    /* enum typelibs */
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
618
    if (pfield.type() != message::Table::Field::ENUM)
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
619
      continue;
620
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
621
    message::Table::Field::SetFieldOptions field_options= pfield.set_options();
622
623
    const CHARSET_INFO *charset= get_charset(field_options.has_collation_id() ?
624
                                             field_options.collation_id() : 0);
625
626
    if (! charset)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
627
      charset= default_charset_info;
628
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
629
    TYPELIB *t= &(share->intervals[interval_nr]);
630
631
    t->type_names= (const char**)alloc_root(&share->mem_root,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
632
                                            (field_options.field_value_size() + 1) * sizeof(char*));
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
633
634
    t->type_lengths= (unsigned int*) alloc_root(&share->mem_root,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
635
                                                (field_options.field_value_size() + 1) * sizeof(unsigned int));
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
636
637
    t->type_names[field_options.field_value_size()]= NULL;
638
    t->type_lengths[field_options.field_value_size()]= 0;
639
640
    t->count= field_options.field_value_size();
641
    t->name= NULL;
642
1046.1.6 by Brian Aker
Formatting/style cleanup.
643
    for (int n= 0; n < field_options.field_value_size(); n++)
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
644
    {
645
      t->type_names[n]= strmake_root(&share->mem_root,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
646
                                     field_options.field_value(n).c_str(),
647
                                     field_options.field_value(n).length());
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
648
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
649
      /* 
650
       * Go ask the charset what the length is as for "" length=1
651
       * and there's stripping spaces or some other crack going on.
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
652
       */
653
      uint32_t lengthsp;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
654
      lengthsp= charset->cset->lengthsp(charset,
655
                                        t->type_names[n],
656
                                        field_options.field_value(n).length());
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
657
      t->type_lengths[n]= lengthsp;
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
658
    }
659
    interval_nr++;
660
  }
661
662
663
  /* and read the fields */
664
  interval_nr= 0;
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
665
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
666
  bool use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
667
1034.1.2 by Brian Aker
Correct if() style
668
  if (use_hash)
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
669
    use_hash= ! hash_init(&share->name_hash,
670
                          system_charset_info,
671
                          share->fields,
672
                          0,
673
                          0,
674
                          (hash_get_key) get_field_name,
675
                          0,
676
                          0);
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
677
678
  unsigned char* null_pos= record;;
679
  int null_bit_pos= (table_options.pack_record()) ? 0 : 1;
680
1046.1.6 by Brian Aker
Formatting/style cleanup.
681
  for (unsigned int fieldnr= 0; fieldnr < share->fields; fieldnr++)
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
682
  {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
683
    message::Table::Field pfield= table.field(fieldnr);
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
684
685
    enum column_format_type column_format= COLUMN_FORMAT_TYPE_DEFAULT;
686
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
687
    switch (pfield.format())
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
688
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
689
    case message::Table::Field::DefaultFormat:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
690
      column_format= COLUMN_FORMAT_TYPE_DEFAULT;
691
      break;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
692
    case message::Table::Field::FixedFormat:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
693
      column_format= COLUMN_FORMAT_TYPE_FIXED;
694
      break;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
695
    case message::Table::Field::DynamicFormat:
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
696
      column_format= COLUMN_FORMAT_TYPE_DYNAMIC;
697
      break;
698
    default:
899.1.1 by brian
Merge of Stewart + Jay's fix.
699
      assert(1);
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
700
    }
701
702
    Field::utype unireg_type= Field::NONE;
703
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
704
    if (pfield.has_numeric_options() &&
705
        pfield.numeric_options().is_autoincrement())
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
706
    {
707
      unireg_type= Field::NEXT_NUMBER;
708
    }
709
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
710
    if (pfield.has_options() &&
711
        pfield.options().has_default_value() &&
712
        pfield.options().default_value().compare("NOW()") == 0)
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
713
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
714
      if (pfield.options().has_update_value() &&
715
          pfield.options().update_value().compare("NOW()") == 0)
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
716
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
717
        unireg_type= Field::TIMESTAMP_DNUN_FIELD;
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
718
      }
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
719
      else if (! pfield.options().has_update_value())
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
720
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
721
      	unireg_type= Field::TIMESTAMP_DN_FIELD;
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
722
      }
723
      else
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
724
      	assert(1); // Invalid update value.
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
725
    }
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
726
    else if (pfield.has_options() &&
727
             pfield.options().has_update_value() &&
728
             pfield.options().update_value().compare("NOW()") == 0)
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
729
    {
730
      unireg_type= Field::TIMESTAMP_UN_FIELD;
731
    }
732
733
    LEX_STRING comment;
1034.1.2 by Brian Aker
Correct if() style
734
    if (!pfield.has_comment())
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
735
    {
736
      comment.str= (char*)"";
737
      comment.length= 0;
738
    }
739
    else
740
    {
741
      size_t len= pfield.comment().length();
742
      const char* str= pfield.comment().c_str();
743
744
      comment.str= strmake_root(&share->mem_root, str, len);
745
      comment.length= len;
746
    }
747
748
    enum_field_types field_type;
749
750
    field_type= proto_field_type_to_drizzle_type(pfield.type());
751
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
752
    const CHARSET_INFO *charset= &my_charset_bin;
753
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
754
    if (field_type == DRIZZLE_TYPE_BLOB ||
755
        field_type == DRIZZLE_TYPE_VARCHAR)
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
756
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
757
      message::Table::Field::StringFieldOptions field_options= pfield.string_options();
758
759
      charset= get_charset(field_options.has_collation_id() ?
760
                           field_options.collation_id() : 0);
761
762
      if (! charset)
763
      	charset= default_charset_info;
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
764
    }
765
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
766
    if (field_type == DRIZZLE_TYPE_ENUM)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
767
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
768
      message::Table::Field::SetFieldOptions field_options= pfield.set_options();
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
769
770
      charset= get_charset(field_options.has_collation_id()?
771
			   field_options.collation_id() : 0);
772
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
773
      if (! charset)
774
	      charset= default_charset_info;
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
775
    }
776
1119.9.22 by Stewart Smith
fix up decimals type to be uint8_t throughout and check that value in the proto is valid for what the server can currently handle
777
    uint8_t decimals= 0;
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
778
    if (field_type == DRIZZLE_TYPE_DECIMAL
1119.9.16 by Stewart Smith
don't store decimal/double scale in pack_flag, instead use the numeric option scale field in the table proto. This removes f_decimals() macro and the bits in the pack_flag for scale.
779
        || field_type == DRIZZLE_TYPE_DOUBLE)
780
    {
781
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
782
783
      if (! pfield.has_numeric_options() || ! fo.has_scale())
784
      {
785
        /*
786
          We don't write the default to table proto so
787
          if no decimals specified for DOUBLE, we use the default.
788
        */
789
        decimals= NOT_FIXED_DEC;
790
      }
791
      else
792
      {
1119.9.22 by Stewart Smith
fix up decimals type to be uint8_t throughout and check that value in the proto is valid for what the server can currently handle
793
        if (fo.scale() > DECIMAL_MAX_SCALE)
794
        {
795
          error= 4;
796
          goto err;
797
        }
1145 by Brian Aker
Merge Stewart
798
        decimals= static_cast<uint8_t>(fo.scale());
1119.9.16 by Stewart Smith
don't store decimal/double scale in pack_flag, instead use the numeric option scale field in the table proto. This removes f_decimals() macro and the bits in the pack_flag for scale.
799
      }
800
    }
801
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
802
    Item *default_value= NULL;
803
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
804
    if (pfield.options().has_default_value() ||
805
        pfield.options().has_default_null()  ||
806
        pfield.options().has_default_bin_value())
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
807
    {
808
      default_value= default_value_item(field_type,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
809
                                        charset,
810
                                        pfield.options().default_null(),
811
                                        &pfield.options().default_value(),
812
                                        &pfield.options().default_bin_value());
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
813
    }
814
815
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
816
    Table temp_table; /* Use this so that BLOB DEFAULT '' works */
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
817
    memset(&temp_table, 0, sizeof(temp_table));
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
818
    temp_table.s= share;
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
819
    temp_table.in_use= &session;
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
820
    temp_table.s->db_low_byte_first= 1; //Cursor->low_byte_first();
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
821
    temp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
822
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
823
    uint32_t field_length;
824
825
    switch (field_type)
826
    {
827
    case DRIZZLE_TYPE_DOUBLE:
828
    {
829
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
830
      if (!fo.has_precision() && !fo.has_scale())
831
      {
832
        field_length= DBL_DIG+7;
833
      }
834
      else
835
      {
836
        field_length= fo.precision();
837
      }
838
      if (field_length < decimals &&
839
          decimals != NOT_FIXED_DEC)
840
      {
841
        my_error(ER_M_BIGGER_THAN_D, MYF(0), pfield.name().c_str());
842
        error= 1;
843
        goto err;
844
      }
845
      break;
846
    }
847
    case DRIZZLE_TYPE_DECIMAL:
848
    {
849
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
850
851
      field_length= my_decimal_precision_to_length(fo.precision(), fo.scale(),
852
                                                   false);
853
      break;
854
    }
855
    default:
856
      field_length= pfield.options().length();
857
      break;
858
    }
859
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
860
    Field* f= make_field(share,
861
                         &share->mem_root,
862
                         record + field_offsets[fieldnr] + data_offset,
1211.1.1 by Brian Aker
Updating with my change to to DECIMAL from NEWDECIMAL and Stewart's update
863
                         field_length,
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
864
                         pfield.has_constraints() && pfield.constraints().is_nullable() ? true : false,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
865
                         null_pos,
866
                         null_bit_pos,
1119.9.16 by Stewart Smith
don't store decimal/double scale in pack_flag, instead use the numeric option scale field in the table proto. This removes f_decimals() macro and the bits in the pack_flag for scale.
867
                         decimals,
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
868
                         field_type,
869
                         charset,
870
                         (Field::utype) MTYP_TYPENR(unireg_type),
871
                         ((field_type == DRIZZLE_TYPE_ENUM) ?
872
                          share->intervals + (interval_nr++)
873
                          : (TYPELIB*) 0),
874
                         share->fieldnames.type_names[fieldnr]);
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
875
876
    share->field[fieldnr]= f;
877
878
    f->init(&temp_table); /* blob default values need table obj */
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
879
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
880
    if (! (f->flags & NOT_NULL_FLAG))
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
881
    {
882
      *f->null_ptr|= f->null_bit;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
883
      if (! (null_bit_pos= (null_bit_pos + 1) & 7)) /* @TODO Ugh. */
884
        null_pos++;
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
885
      null_count++;
886
    }
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
887
1034.1.2 by Brian Aker
Correct if() style
888
    if (default_value)
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
889
    {
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
890
      enum_check_fields old_count_cuted_fields= session.count_cuted_fields;
891
      session.count_cuted_fields= CHECK_FIELD_WARN;
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
892
      int res= default_value->save_in_field(f, 1);
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
893
      session.count_cuted_fields= old_count_cuted_fields;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
894
      if (res != 0 && res != 3) /* @TODO Huh? */
896.4.9 by Stewart Smith
No longer write the FRM. just use proto.
895
      {
896
        my_error(ER_INVALID_DEFAULT, MYF(0), f->field_name);
897
        error= 1;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
898
        goto err;
896.4.9 by Stewart Smith
No longer write the FRM. just use proto.
899
      }
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
900
    }
1034.1.2 by Brian Aker
Correct if() style
901
    else if (f->real_type() == DRIZZLE_TYPE_ENUM &&
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
902
             (f->flags & NOT_NULL_FLAG))
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
903
    {
904
      f->set_notnull();
905
      f->store((int64_t) 1, true);
906
    }
907
    else
908
      f->reset();
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
909
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
910
    /* hack to undo f->init() */
911
    f->table= NULL;
912
    f->orig_table= NULL;
913
914
    f->field_index= fieldnr;
915
    f->comment= comment;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
916
    if (! default_value &&
917
        ! (f->unireg_check==Field::NEXT_NUMBER) &&
918
        (f->flags & NOT_NULL_FLAG) &&
919
        (f->real_type() != DRIZZLE_TYPE_TIMESTAMP))
920
    {
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
921
      f->flags|= NO_DEFAULT_VALUE_FLAG;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
922
    }
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
923
1034.1.2 by Brian Aker
Correct if() style
924
    if (f->unireg_check == Field::NEXT_NUMBER)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
925
      share->found_next_number_field= &(share->field[fieldnr]);
926
1034.1.2 by Brian Aker
Correct if() style
927
    if (share->timestamp_field == f)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
928
      share->timestamp_field_offset= fieldnr;
929
930
    if (use_hash) /* supposedly this never fails... but comments lie */
931
      (void) my_hash_insert(&share->name_hash,
932
			    (unsigned char*)&(share->field[fieldnr]));
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
933
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
934
  }
935
896.3.13 by Stewart Smith
compute key_part->offset instead of storing in proto.
936
  keyinfo= share->key_info;
1046.1.6 by Brian Aker
Formatting/style cleanup.
937
  for (unsigned int keynr= 0; keynr < share->keys; keynr++, keyinfo++)
896.3.13 by Stewart Smith
compute key_part->offset instead of storing in proto.
938
  {
939
    key_part= keyinfo->key_part;
940
1046.1.6 by Brian Aker
Formatting/style cleanup.
941
    for (unsigned int partnr= 0;
942
         partnr < keyinfo->key_parts;
943
         partnr++, key_part++)
896.3.13 by Stewart Smith
compute key_part->offset instead of storing in proto.
944
    {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
945
      /* 
946
       * Fix up key_part->offset by adding data_offset.
947
       * We really should compute offset as well.
948
       * But at least this way we are a little better.
949
       */
896.3.13 by Stewart Smith
compute key_part->offset instead of storing in proto.
950
      key_part->offset= field_offsets[key_part->fieldnr-1] + data_offset;
951
    }
952
  }
953
896.3.4 by Stewart Smith
Create default_values record from proto instead of reading from FRM. assert if different to FRM.
954
  /*
955
    We need to set the unused bits to 1. If the number of bits is a multiple
956
    of 8 there are no unused bits.
957
  */
958
959
  if (null_count & 7)
960
    *(record + null_count / 8)|= ~(((unsigned char) 1 << (null_count & 7)) - 1);
961
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
962
  share->null_bytes= (null_pos - (unsigned char*) record + (null_bit_pos + 7) / 8);
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
963
964
  share->last_null_bit_pos= null_bit_pos;
965
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
966
  free(field_offsets);
1214 by Brian Aker
Fixes leaked memory during a fail proto read.
967
  field_offsets= NULL;
869.1.24 by Stewart Smith
Generate all the info needed to get a record size on proto read instead of FRM create time.
968
  free(field_pack_length);
1214 by Brian Aker
Fixes leaked memory during a fail proto read.
969
  field_pack_length= NULL;
869.1.4 by Stewart Smith
read number of fields from proto instead of frm
970
1208.3.2 by brian
Update for Cursor renaming.
971
  if (! (handler_file= share->db_type()->getCursor(*share, session.mem_root)))
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
972
    abort(); // FIXME
973
974
  /* Fix key stuff */
975
  if (share->key_parts)
976
  {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
977
    uint32_t primary_key= (uint32_t) (find_type((char*) "PRIMARY",
978
                                                &share->keynames, 3) - 1); /* @TODO Huh? */
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
979
980
    int64_t ha_option= handler_file->ha_table_flags();
981
982
    keyinfo= share->key_info;
983
    key_part= keyinfo->key_part;
984
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
985
    for (uint32_t key= 0; key < share->keys; key++,keyinfo++)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
986
    {
987
      uint32_t usable_parts= 0;
988
989
      if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
990
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
991
        /*
992
          If the UNIQUE key doesn't have NULL columns and is not a part key
993
          declare this as a primary key.
994
        */
995
        primary_key=key;
996
        for (uint32_t i= 0; i < keyinfo->key_parts; i++)
997
        {
998
          uint32_t fieldnr= key_part[i].fieldnr;
999
          if (! fieldnr ||
1000
              share->field[fieldnr-1]->null_ptr ||
1001
              share->field[fieldnr-1]->key_length() != key_part[i].length)
1002
          {
1003
            primary_key= MAX_KEY; // Can't be used
1004
            break;
1005
          }
1006
        }
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1007
      }
1008
1046.1.6 by Brian Aker
Formatting/style cleanup.
1009
      for (uint32_t i= 0 ; i < keyinfo->key_parts ; key_part++,i++)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1010
      {
1011
        Field *field;
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1012
        if (! key_part->fieldnr)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1013
        {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1014
          abort(); // goto err;
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1015
        }
1016
        field= key_part->field= share->field[key_part->fieldnr-1];
1017
        key_part->type= field->key_type();
1018
        if (field->null_ptr)
1019
        {
1020
          key_part->null_offset=(uint32_t) ((unsigned char*) field->null_ptr -
1021
                                        share->default_values);
1022
          key_part->null_bit= field->null_bit;
1023
          key_part->store_length+=HA_KEY_NULL_LENGTH;
1024
          keyinfo->flags|=HA_NULL_PART_KEY;
1025
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
1026
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
1027
        }
1028
        if (field->type() == DRIZZLE_TYPE_BLOB ||
1029
            field->real_type() == DRIZZLE_TYPE_VARCHAR)
1030
        {
1031
          if (field->type() == DRIZZLE_TYPE_BLOB)
1032
            key_part->key_part_flag|= HA_BLOB_PART;
1033
          else
1034
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
1035
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
1036
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
1037
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
1038
        }
1039
        if (i == 0 && key != primary_key)
1040
          field->flags |= (((keyinfo->flags & HA_NOSAME) &&
1041
                           (keyinfo->key_parts == 1)) ?
1042
                           UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
1043
        if (i == 0)
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1044
          field->key_start.set(key);
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1045
        if (field->key_length() == key_part->length &&
1046
            !(field->flags & BLOB_FLAG))
1047
        {
1048
          if (handler_file->index_flags(key, i, 0) & HA_KEYREAD_ONLY)
1049
          {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1050
            share->keys_for_keyread.set(key);
1051
            field->part_of_key.set(key);
1052
            field->part_of_key_not_clustered.set(key);
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1053
          }
1054
          if (handler_file->index_flags(key, i, 1) & HA_READ_ORDER)
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1055
            field->part_of_sortkey.set(key);
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1056
        }
1057
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
1058
            usable_parts == i)
1059
          usable_parts++;			// For FILESORT
1060
        field->flags|= PART_KEY_FLAG;
1061
        if (key == primary_key)
1062
        {
1063
          field->flags|= PRI_KEY_FLAG;
1064
          /*
1065
            If this field is part of the primary key and all keys contains
1066
            the primary key, then we can use any key to find this column
1067
          */
1068
          if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
1069
          {
1070
            field->part_of_key= share->keys_in_use;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1071
            if (field->part_of_sortkey.test(key))
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1072
              field->part_of_sortkey= share->keys_in_use;
1073
          }
1074
        }
1075
        if (field->key_length() != key_part->length)
1076
        {
1077
          key_part->key_part_flag|= HA_PART_KEY_SEG;
1078
        }
1079
      }
1080
      keyinfo->usable_key_parts= usable_parts; // Filesort
1081
1082
      set_if_bigger(share->max_key_length,keyinfo->key_length+
1083
                    keyinfo->key_parts);
1084
      share->total_key_length+= keyinfo->key_length;
1085
      /*
1086
        MERGE tables do not have unique indexes. But every key could be
1087
        an unique index on the underlying MyISAM table. (Bug #10400)
1088
      */
1089
      if ((keyinfo->flags & HA_NOSAME) ||
1090
          (ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
1091
        set_if_bigger(share->max_unique_length,keyinfo->key_length);
1092
    }
1093
    if (primary_key < MAX_KEY &&
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1094
        (share->keys_in_use.test(primary_key)))
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1095
    {
1096
      share->primary_key= primary_key;
1097
      /*
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1098
        If we are using an integer as the primary key then allow the user to
1099
        refer to it as '_rowid'
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1100
      */
1101
      if (share->key_info[primary_key].key_parts == 1)
1102
      {
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1103
        Field *field= share->key_info[primary_key].key_part[0].field;
1104
        if (field && field->result_type() == INT_RESULT)
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1105
        {
1106
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1107
          share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
896.3.6 by Stewart Smith
Read Fields out of proto instead of FRM.
1108
                                      fieldnr);
1109
        }
1110
      }
1111
    }
1112
    else
1113
      share->primary_key = MAX_KEY; // we do not have a primary key
1114
  }
1115
  else
1116
    share->primary_key= MAX_KEY;
1117
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
1118
  if (share->found_next_number_field)
1119
  {
1120
    Field *reg_field= *share->found_next_number_field;
1121
    if ((int) (share->next_number_index= (uint32_t)
1122
	       find_ref_key(share->key_info, share->keys,
1123
                            share->default_values, reg_field,
1124
			    &share->next_number_key_offset,
1125
                            &share->next_number_keypart)) < 0)
1126
    {
1127
      /* Wrong field definition */
1128
      error= 4;
1129
      goto err;
1130
    }
1131
    else
1132
      reg_field->flags |= AUTO_INCREMENT_FLAG;
1133
  }
1134
1135
  if (share->blob_fields)
1136
  {
1137
    Field **ptr;
1138
    uint32_t k, *save;
1139
1140
    /* Store offsets to blob fields to find them fast */
1141
    if (!(share->blob_field= save=
1142
	  (uint*) alloc_root(&share->mem_root,
1143
                             (uint32_t) (share->blob_fields* sizeof(uint32_t)))))
1144
      goto err;
1046.1.6 by Brian Aker
Formatting/style cleanup.
1145
    for (k= 0, ptr= share->field ; *ptr ; ptr++, k++)
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
1146
    {
1147
      if ((*ptr)->flags & BLOB_FLAG)
1119.9.9 by Jay Pipes
Style cleanup in parse_table_proto() to help with my sanity.
1148
        (*save++)= k;
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
1149
    }
1150
  }
1151
896.4.7 by Stewart Smith
last bit of bitmap logic from FRM path to proto path
1152
  share->db_low_byte_first= handler_file->low_byte_first();
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
1153
  share->column_bitmap_size= bitmap_buffer_size(share->fields);
1154
1155
  my_bitmap_map *bitmaps;
1156
1157
  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
1158
                                             share->column_bitmap_size)))
1159
    goto err;
1103.6.3 by Padraig O'Sullivan
Fixing up more calls to the old bitmap API.
1160
  share->all_set.init(bitmaps, share->fields);
1161
  share->all_set.setAll();
896.4.7 by Stewart Smith
last bit of bitmap logic from FRM path to proto path
1162
1034.1.2 by Brian Aker
Correct if() style
1163
  if (handler_file)
896.4.9 by Stewart Smith
No longer write the FRM. just use proto.
1164
    delete handler_file;
896.4.7 by Stewart Smith
last bit of bitmap logic from FRM path to proto path
1165
  return (0);
1166
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
1167
err:
1214 by Brian Aker
Fixes leaked memory during a fail proto read.
1168
  if (field_offsets)
1169
    free(field_offsets);
1170
  if (field_pack_length)
1171
    free(field_pack_length);
1172
896.4.7 by Stewart Smith
last bit of bitmap logic from FRM path to proto path
1173
  share->error= error;
1174
  share->open_errno= my_errno;
1175
  share->errarg= 0;
1176
  hash_free(&share->name_hash);
1034.1.2 by Brian Aker
Correct if() style
1177
  if (handler_file)
896.4.9 by Stewart Smith
No longer write the FRM. just use proto.
1178
    delete handler_file;
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1179
  share->open_table_error(error, share->open_errno, 0);
1180
896.4.6 by Stewart Smith
move fixing auto_inc and blobs from FRM code path to table_proto code path
1181
  return error;
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
1182
}
1183
1 by brian
clean slate
1184
/*
1208.3.2 by brian
Update for Cursor renaming.
1185
  Read table definition from a binary / text based .frm cursor
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1186
1 by brian
clean slate
1187
  SYNOPSIS
1188
  open_table_def()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1189
  session		Thread Cursor
1 by brian
clean slate
1190
  share		Fill this with table definition
1191
1192
  NOTES
1193
    This function is called when the table definition is not cached in
1194
    table_def_cache
1195
    The data is returned in 'share', which is alloced by
1196
    alloc_table_share().. The code assumes that share is initialized.
1197
1198
  RETURN VALUES
1199
   0	ok
1200
   1	Error (see open_table_error)
1201
   2    Error (see open_table_error)
1208.3.2 by brian
Update for Cursor renaming.
1202
   3    Wrong data in .frm cursor
1 by brian
clean slate
1203
   4    Error (see open_table_error)
1204
   5    Error (see open_table_error: charset unavailable)
1205
   6    Unknown .frm version
1206
*/
1207
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
1208
int open_table_def(Session& session, TableShare *share)
1 by brian
clean slate
1209
{
896.4.8 by Stewart Smith
Just read table proto. Remove open_binary_frm. FRM is not read anymore.
1210
  int error;
1 by brian
clean slate
1211
  bool error_given;
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
1212
1 by brian
clean slate
1213
  error= 1;
1214
  error_given= 0;
1215
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
1216
  message::Table table;
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
1217
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
1218
  error= plugin::StorageEngine::getTableDefinition(session, share->normalized_path.str,
1183.5.1 by Brian Aker
Extended definition interface (filename building should now be moved
1219
                                                   share->db.str,
1220
                                                   share->table_name.str,
1221
                                                   false,
1222
                                                   &table);
1095.3.7 by Stewart Smith
use StorageEngine::getTableProto instead of drizzle_read_table_proto. We only read the proto file now in SE::getTableProto.
1223
1095.3.32 by Stewart Smith
misc codestyle fixes. usually around if ( and associated conditions
1224
  if (error != EEXIST)
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
1225
  {
1034.1.2 by Brian Aker
Correct if() style
1226
    if (error>0)
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
1227
    {
1228
      my_errno= error;
1229
      error= 1;
1230
    }
1231
    else
1232
    {
1034.1.2 by Brian Aker
Correct if() style
1233
      if (!table.IsInitialized())
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
1234
      {
1235
	error= 4;
1236
      }
1237
    }
1238
    goto err_not_open;
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
1239
  }
1240
896.4.9 by Stewart Smith
No longer write the FRM. just use proto.
1241
  error= parse_table_proto(session, table, share);
869.1.3 by Stewart Smith
move table proto parsing off into own function. Handle errors in reading and parsing table proto, returning correct error to user. fix tests.
1242
1095.3.17 by Stewart Smith
get_table_category doesn't need table name and can be static to table.cc
1243
  share->table_category= get_table_category(& share->db);
1 by brian
clean slate
1244
1245
  if (!error)
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
1246
    session.status_var.opened_shares++;
1 by brian
clean slate
1247
1248
err_not_open:
1249
  if (error && !error_given)
1250
  {
1251
    share->error= error;
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1252
    share->open_table_error(error, (share->open_errno= my_errno), 0);
1 by brian
clean slate
1253
  }
1254
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1255
  return(error);
1 by brian
clean slate
1256
}
1257
383.7.1 by Andrey Zhakov
Initial submit of code and tests
1258
1259
/*
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
1260
  Open a table based on a TableShare
1 by brian
clean slate
1261
1262
  SYNOPSIS
1263
    open_table_from_share()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1264
    session			Thread Cursor
1 by brian
clean slate
1265
    share		Table definition
1266
    alias       	Alias for table
1267
    db_stat		open flags (for example HA_OPEN_KEYFILE|
1268
    			HA_OPEN_RNDFILE..) can be 0 (example in
1269
                        ha_example_table)
1270
    prgflag   		READ_ALL etc..
1271
    ha_open_flags	HA_OPEN_ABORT_IF_LOCKED etc..
1272
    outparam       	result table
1273
1274
  RETURN VALUES
1275
   0	ok
1276
   1	Error (see open_table_error)
1277
   2    Error (see open_table_error)
1208.3.2 by brian
Update for Cursor renaming.
1278
   3    Wrong data in .frm cursor
1 by brian
clean slate
1279
   4    Error (see open_table_error)
1280
   5    Error (see open_table_error: charset unavailable)
1281
   7    Table definition has changed in engine
1282
*/
1283
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
1284
int open_table_from_share(Session *session, TableShare *share, const char *alias,
482 by Brian Aker
Remove uint.
1285
                          uint32_t db_stat, uint32_t prgflag, uint32_t ha_open_flags,
1217.1.1 by Brian Aker
Remove open_table_mode (no longer in use).
1286
                          Table *outparam)
1 by brian
clean slate
1287
{
1288
  int error;
1005.2.4 by Monty Taylor
Patch cleaning.
1289
  uint32_t records, i, bitmap_size;
51.1.70 by Jay Pipes
Removed/replaced DBUG symbols and removed sql_test.cc from Makefile
1290
  bool error_reported= false;
1005.2.4 by Monty Taylor
Patch cleaning.
1291
  unsigned char *record, *bitmaps;
998.1.2 by Brian Aker
First pass on removing virt columns
1292
  Field **field_ptr;
1 by brian
clean slate
1293
520.1.22 by Brian Aker
Second pass of thd cleanup
1294
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1295
  assert(session->lex->is_lex_started);
1 by brian
clean slate
1296
1297
  error= 1;
1039.1.10 by Brian Aker
Minor formating, change of one name to make grep easier :)
1298
  outparam->resetTable(session, share, db_stat);
1 by brian
clean slate
1299
1300
656.1.19 by Monty Taylor
Removed my_strdup from drizzled/
1301
  if (!(outparam->alias= strdup(alias)))
1 by brian
clean slate
1302
    goto err;
1303
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1304
  /* Allocate Cursor */
1 by brian
clean slate
1305
  if (!(prgflag & OPEN_FRM_FILE_ONLY))
1306
  {
1208.3.2 by brian
Update for Cursor renaming.
1307
    if (!(outparam->cursor= share->db_type()->getCursor(*share, &outparam->mem_root)))
1 by brian
clean slate
1308
      goto err;
1309
  }
1310
  else
1311
  {
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
1312
    assert(!db_stat);
1 by brian
clean slate
1313
  }
1314
1315
  error= 4;
1046.1.6 by Brian Aker
Formatting/style cleanup.
1316
  records= 0;
1 by brian
clean slate
1317
  if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
1318
    records=1;
1319
  if (prgflag & (READ_ALL+EXTRA_RECORD))
1320
    records++;
1321
481 by Brian Aker
Remove all of uchar.
1322
  if (!(record= (unsigned char*) alloc_root(&outparam->mem_root,
1 by brian
clean slate
1323
                                   share->rec_buff_length * records)))
971.6.11 by Eric Day
Removed purecov messages.
1324
    goto err;
1 by brian
clean slate
1325
1326
  if (records == 0)
1327
  {
1328
    /* We are probably in hard repair, and the buffers should not be used */
1329
    outparam->record[0]= outparam->record[1]= share->default_values;
1330
  }
1331
  else
1332
  {
1333
    outparam->record[0]= record;
1334
    if (records > 1)
1335
      outparam->record[1]= record+ share->rec_buff_length;
1336
    else
1337
      outparam->record[1]= outparam->record[0];   // Safety
1338
  }
1339
1340
#ifdef HAVE_purify
1341
  /*
1342
    We need this because when we read var-length rows, we are not updating
1343
    bytes after end of varchar
1344
  */
1345
  if (records > 1)
1346
  {
1347
    memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
1348
    memcpy(outparam->record[1], share->default_values, share->null_bytes);
1349
    if (records > 2)
1350
      memcpy(outparam->record[1], share->default_values,
1351
             share->rec_buff_length);
1352
  }
1353
#endif
1354
1355
  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
895 by Brian Aker
Completion (?) of uint conversion.
1356
                                          (uint32_t) ((share->fields+1)*
1 by brian
clean slate
1357
                                                  sizeof(Field*)))))
971.6.11 by Eric Day
Removed purecov messages.
1358
    goto err;
1 by brian
clean slate
1359
1360
  outparam->field= field_ptr;
1361
481 by Brian Aker
Remove all of uchar.
1362
  record= (unsigned char*) outparam->record[0]-1;	/* Fieldstart = 1 */
869.1.23 by Stewart Smith
remove is_null_field_first from TABLE_SHARE. Is unused with modern FRM
1363
1364
  outparam->null_flags= (unsigned char*) record+1;
1 by brian
clean slate
1365
1366
  /* Setup copy of fields from share, but use the right alias and record */
1046.1.6 by Brian Aker
Formatting/style cleanup.
1367
  for (i= 0 ; i < share->fields; i++, field_ptr++)
1 by brian
clean slate
1368
  {
1369
    if (!((*field_ptr)= share->field[i]->clone(&outparam->mem_root, outparam)))
1370
      goto err;
1371
  }
1372
  (*field_ptr)= 0;                              // End marker
1373
1374
  if (share->found_next_number_field)
1375
    outparam->found_next_number_field=
895 by Brian Aker
Completion (?) of uint conversion.
1376
      outparam->field[(uint32_t) (share->found_next_number_field - share->field)];
1 by brian
clean slate
1377
  if (share->timestamp_field)
1378
    outparam->timestamp_field= (Field_timestamp*) outparam->field[share->timestamp_field_offset];
1379
1380
1381
  /* Fix key->name and key_part->field */
1382
  if (share->key_parts)
1383
  {
1384
    KEY	*key_info, *key_info_end;
1385
    KEY_PART_INFO *key_part;
482 by Brian Aker
Remove uint.
1386
    uint32_t n_length;
1 by brian
clean slate
1387
    n_length= share->keys*sizeof(KEY) + share->key_parts*sizeof(KEY_PART_INFO);
1388
    if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
1389
      goto err;
1390
    outparam->key_info= key_info;
451 by Monty Taylor
Removed my_reinterpret_cast. It's not GNU specific.
1391
    key_part= (reinterpret_cast<KEY_PART_INFO*> (key_info+share->keys));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1392
1 by brian
clean slate
1393
    memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
1394
    memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
1395
                                                   share->key_parts));
1396
1397
    for (key_info_end= key_info + share->keys ;
1398
         key_info < key_info_end ;
1399
         key_info++)
1400
    {
1401
      KEY_PART_INFO *key_part_end;
1402
1403
      key_info->table= outparam;
1404
      key_info->key_part= key_part;
1405
1406
      for (key_part_end= key_part+ key_info->key_parts ;
1407
           key_part < key_part_end ;
1408
           key_part++)
1409
      {
1410
        Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
1411
1412
        if (field->key_length() != key_part->length &&
1413
            !(field->flags & BLOB_FLAG))
1414
        {
1415
          /*
1416
            We are using only a prefix of the column as a key:
1417
            Create a new field for the key part that matches the index
1418
          */
1419
          field= key_part->field=field->new_field(&outparam->mem_root,
1420
                                                  outparam, 0);
1421
          field->field_length= key_part->length;
1422
        }
1423
      }
1424
    }
1425
  }
1426
1427
  /* Allocate bitmaps */
1005.2.3 by Monty Taylor
Further reversion of P.
1428
1429
  bitmap_size= share->column_bitmap_size;
1430
  if (!(bitmaps= (unsigned char*) alloc_root(&outparam->mem_root, bitmap_size*3)))
1431
    goto err;
1103.6.3 by Padraig O'Sullivan
Fixing up more calls to the old bitmap API.
1432
  outparam->def_read_set.init((my_bitmap_map*) bitmaps, share->fields);
1433
  outparam->def_write_set.init((my_bitmap_map*) (bitmaps+bitmap_size), share->fields);
1434
  outparam->tmp_set.init((my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields);
1 by brian
clean slate
1435
  outparam->default_column_bitmaps();
1436
1437
  /* The table struct is now initialized;  Open the table */
1438
  error= 2;
1217.1.1 by Brian Aker
Remove open_table_mode (no longer in use).
1439
  if (db_stat)
1 by brian
clean slate
1440
  {
1441
    int ha_err;
1208.3.2 by brian
Update for Cursor renaming.
1442
    if ((ha_err= (outparam->cursor->
1 by brian
clean slate
1443
                  ha_open(outparam, share->normalized_path.str,
1444
                          (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
1445
                          (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
362 by Brian Aker
No more dead special flags...
1446
                           (db_stat & HA_WAIT_IF_LOCKED) ?  HA_OPEN_WAIT_IF_LOCKED :
1 by brian
clean slate
1447
                           (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
1448
                          HA_OPEN_ABORT_IF_LOCKED :
1449
                           HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
1450
    {
1451
      /* Set a flag if the table is crashed and it can be auto. repaired */
1452
      share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
1208.3.2 by brian
Update for Cursor renaming.
1453
                       outparam->cursor->auto_repair() &&
1 by brian
clean slate
1454
                       !(ha_open_flags & HA_OPEN_FOR_REPAIR));
1455
1456
      switch (ha_err)
1457
      {
1458
        case HA_ERR_NO_SUCH_TABLE:
1459
	  /*
1460
            The table did not exists in storage engine, use same error message
1208.3.2 by brian
Update for Cursor renaming.
1461
            as if the .frm cursor didn't exist
1 by brian
clean slate
1462
          */
1463
	  error= 1;
1464
	  my_errno= ENOENT;
1465
          break;
1466
        case EMFILE:
1467
	  /*
1468
            Too many files opened, use same error message as if the .frm
1208.3.2 by brian
Update for Cursor renaming.
1469
            cursor can't open
1 by brian
clean slate
1470
           */
1471
	  error= 1;
1472
	  my_errno= EMFILE;
1473
          break;
1474
        default:
1208.3.2 by brian
Update for Cursor renaming.
1475
          outparam->cursor->print_error(ha_err, MYF(0));
51.1.70 by Jay Pipes
Removed/replaced DBUG symbols and removed sql_test.cc from Makefile
1476
          error_reported= true;
1 by brian
clean slate
1477
          if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
1478
            error= 7;
1479
          break;
1480
      }
971.6.11 by Eric Day
Removed purecov messages.
1481
      goto err;
1 by brian
clean slate
1482
    }
1483
  }
1484
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1485
#if defined(HAVE_purify)
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1486
  memset(bitmaps, 0, bitmap_size*3);
1 by brian
clean slate
1487
#endif
1488
520.1.22 by Brian Aker
Second pass of thd cleanup
1489
  session->status_var.opened_tables++;
1 by brian
clean slate
1490
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1491
  return (0);
1 by brian
clean slate
1492
1493
 err:
1494
  if (!error_reported && !(prgflag & DONT_GIVE_ERROR))
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1495
    share->open_table_error(error, my_errno, 0);
1208.3.2 by brian
Update for Cursor renaming.
1496
  delete outparam->cursor;
1497
  outparam->cursor= 0;				// For easier error checking
1046.1.6 by Brian Aker
Formatting/style cleanup.
1498
  outparam->db_stat= 0;
212.6.3 by Mats Kindahl
Removing deprecated functions from code and replacing them with C99 equivalents:
1499
  free_root(&outparam->mem_root, MYF(0));       // Safe to call on zeroed root
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
1500
  free((char*) outparam->alias);
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1501
  return (error);
1 by brian
clean slate
1502
}
1503
1188.1.2 by Jay Pipes
Style and doxygen cleanup ONLY. Moves method documentation from source into header files. Removes TAB characters and cleans up indentation.
1504
bool Table::fill_item_list(List<Item> *item_list) const
1505
{
1506
  /*
1507
    All Item_field's created using a direct pointer to a field
1508
    are fixed in Item_field constructor.
1509
  */
1510
  for (Field **ptr= field; *ptr; ptr++)
1511
  {
1512
    Item_field *item= new Item_field(*ptr);
1513
    if (!item || item_list->push_back(item))
1514
      return true;
1515
  }
1516
  return false;
1517
}
1 by brian
clean slate
1518
793 by Brian Aker
Pass through on refactoring functions to clases.
1519
int Table::closefrm(bool free_share)
1 by brian
clean slate
1520
{
1046.1.6 by Brian Aker
Formatting/style cleanup.
1521
  int error= 0;
1 by brian
clean slate
1522
793 by Brian Aker
Pass through on refactoring functions to clases.
1523
  if (db_stat)
1208.3.2 by brian
Update for Cursor renaming.
1524
    error= cursor->close();
793 by Brian Aker
Pass through on refactoring functions to clases.
1525
  free((char*) alias);
1526
  alias= NULL;
1527
  if (field)
1 by brian
clean slate
1528
  {
793 by Brian Aker
Pass through on refactoring functions to clases.
1529
    for (Field **ptr=field ; *ptr ; ptr++)
1 by brian
clean slate
1530
      delete *ptr;
793 by Brian Aker
Pass through on refactoring functions to clases.
1531
    field= 0;
1 by brian
clean slate
1532
  }
1208.3.2 by brian
Update for Cursor renaming.
1533
  delete cursor;
1534
  cursor= 0;				/* For easier errorchecking */
1 by brian
clean slate
1535
  if (free_share)
1536
  {
793 by Brian Aker
Pass through on refactoring functions to clases.
1537
    if (s->tmp_table == NO_TMP_TABLE)
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
1538
      TableShare::release(s);
1 by brian
clean slate
1539
    else
1000.1.5 by Brian Aker
More refactoring back to TableShare object.
1540
      s->free_table_share();
1 by brian
clean slate
1541
  }
793 by Brian Aker
Pass through on refactoring functions to clases.
1542
  free_root(&mem_root, MYF(0));
1543
1544
  return error;
1 by brian
clean slate
1545
}
1546
1547
1548
/* Deallocate temporary blob storage */
1549
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1550
void free_blobs(register Table *table)
1 by brian
clean slate
1551
{
482 by Brian Aker
Remove uint.
1552
  uint32_t *ptr, *end;
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
1553
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
1 by brian
clean slate
1554
       ptr != end ;
1555
       ptr++)
1556
    ((Field_blob*) table->field[*ptr])->free();
1557
}
1558
1559
1208.3.2 by brian
Update for Cursor renaming.
1560
	/* error message when opening a form cursor */
1 by brian
clean slate
1561
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1562
void TableShare::open_table_error(int pass_error, int db_errno, int pass_errarg)
1 by brian
clean slate
1563
{
1564
  int err_no;
1565
  char buff[FN_REFLEN];
1566
  myf errortype= ME_ERROR+ME_WAITTANG;
1567
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1568
  switch (pass_error) {
1 by brian
clean slate
1569
  case 7:
1570
  case 1:
1571
    if (db_errno == ENOENT)
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1572
      my_error(ER_NO_SUCH_TABLE, MYF(0), db.str, table_name.str);
1 by brian
clean slate
1573
    else
1574
    {
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1575
      sprintf(buff,"%s",normalized_path.str);
1 by brian
clean slate
1576
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
1577
               errortype, buff, db_errno);
1578
    }
1579
    break;
1580
  case 2:
1581
  {
1208.3.2 by brian
Update for Cursor renaming.
1582
    Cursor *cursor= 0;
1 by brian
clean slate
1583
    const char *datext= "";
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1584
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1585
    if (db_type() != NULL)
1 by brian
clean slate
1586
    {
1208.3.2 by brian
Update for Cursor renaming.
1587
      if ((cursor= db_type()->getCursor(*this, current_session->mem_root)))
1 by brian
clean slate
1588
      {
1039.3.4 by Stewart Smith
merge mainline
1589
        if (!(datext= *db_type()->bas_ext()))
1 by brian
clean slate
1590
          datext= "";
1591
      }
1592
    }
1593
    err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
1594
      ER_FILE_USED : ER_CANT_OPEN_FILE;
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1595
    sprintf(buff,"%s%s", normalized_path.str,datext);
1 by brian
clean slate
1596
    my_error(err_no,errortype, buff, db_errno);
1208.3.2 by brian
Update for Cursor renaming.
1597
    delete cursor;
1 by brian
clean slate
1598
    break;
1599
  }
1600
  case 5:
1601
  {
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1602
    const char *csname= get_charset_name((uint32_t) pass_errarg);
1 by brian
clean slate
1603
    char tmp[10];
1604
    if (!csname || csname[0] =='?')
1605
    {
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1606
      snprintf(tmp, sizeof(tmp), "#%d", pass_errarg);
1 by brian
clean slate
1607
      csname= tmp;
1608
    }
1609
    my_printf_error(ER_UNKNOWN_COLLATION,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1610
                    _("Unknown collation '%s' in table '%-.64s' definition"),
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1611
                    MYF(0), csname, table_name.str);
1 by brian
clean slate
1612
    break;
1613
  }
1614
  case 6:
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1615
    sprintf(buff,"%s", normalized_path.str);
1 by brian
clean slate
1616
    my_printf_error(ER_NOT_FORM_FILE,
261.3.8 by Monty Taylor
Added strings from table.cc.
1617
                    _("Table '%-.64s' was created with a different version "
672.1.3 by Andrew Hutchings
Minor string fixes (mainly US English spelling and typos)
1618
                    "of Drizzle and cannot be read"),
1 by brian
clean slate
1619
                    MYF(0), buff);
1620
    break;
1621
  case 8:
1622
    break;
1623
  default:				/* Better wrong error than none */
1624
  case 4:
1039.1.9 by Brian Aker
Partial Refactor of TableShare
1625
    sprintf(buff,"%s", normalized_path.str);
1 by brian
clean slate
1626
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
1627
    break;
1628
  }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1629
  return;
1 by brian
clean slate
1630
} /* open_table_error */
1631
1632
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
1633
TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
1 by brian
clean slate
1634
{
1635
  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
1636
  if (!result)
1637
    return 0;
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
1638
  result->count= strings.elements;
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
1639
  result->name= "";
895 by Brian Aker
Completion (?) of uint conversion.
1640
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
1641
  
1 by brian
clean slate
1642
  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
1643
    return 0;
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
1644
    
1 by brian
clean slate
1645
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
1646
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
1647
  List_iterator<String> it(strings);
1648
  String *tmp;
1649
  for (uint32_t i= 0; (tmp= it++); i++)
1 by brian
clean slate
1650
  {
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
1651
    result->type_names[i]= tmp->ptr();
1652
    result->type_lengths[i]= tmp->length();
1 by brian
clean slate
1653
  }
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
1654
1655
  result->type_names[result->count]= 0;   // End marker
1 by brian
clean slate
1656
  result->type_lengths[result->count]= 0;
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
1657
1 by brian
clean slate
1658
  return result;
1659
}
1660
1661
	/* Check that the integer is in the internal */
1662
1663
int set_zone(register int nr, int min_zone, int max_zone)
1664
{
1665
  if (nr<=min_zone)
1666
    return (min_zone);
1667
  if (nr>=max_zone)
1668
    return (max_zone);
1669
  return (nr);
1670
} /* set_zone */
1671
1672
	/* Adjust number to next larger disk buffer */
1673
1674
ulong next_io_size(register ulong pos)
1675
{
1676
  register ulong offset;
1677
  if ((offset= pos & (IO_SIZE-1)))
1678
    return pos-offset+IO_SIZE;
1679
  return pos;
1680
} /* next_io_size */
1681
1682
1683
/*
1684
  Store an SQL quoted string.
1685
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1686
  SYNOPSIS
1 by brian
clean slate
1687
    append_unescaped()
1688
    res		result String
1689
    pos		string to be quoted
1690
    length	it's length
1691
1692
  NOTE
1693
    This function works correctly with utf8 or single-byte charset strings.
1694
    May fail with some multibyte charsets though.
1695
*/
1696
482 by Brian Aker
Remove uint.
1697
void append_unescaped(String *res, const char *pos, uint32_t length)
1 by brian
clean slate
1698
{
1699
  const char *end= pos+length;
1700
  res->append('\'');
1701
1702
  for (; pos != end ; pos++)
1703
  {
482 by Brian Aker
Remove uint.
1704
    uint32_t mblen;
1 by brian
clean slate
1705
    if (use_mb(default_charset_info) &&
1706
        (mblen= my_ismbchar(default_charset_info, pos, end)))
1707
    {
1708
      res->append(pos, mblen);
1709
      pos+= mblen;
814.1.1 by Jay Pipes
Fix for Bug 314502 "show create table crashes with multi-byte character in enum description"
1710
      if (pos >= end)
1711
        break;
814.1.2 by Jay Pipes
Forgot to add back the continue in case of multi-byte character not exceeding the end of string buffer.
1712
      continue;
1 by brian
clean slate
1713
    }
1714
1715
    switch (*pos) {
1716
    case 0:				/* Must be escaped for 'mysql' */
1717
      res->append('\\');
1718
      res->append('0');
1719
      break;
1720
    case '\n':				/* Must be escaped for logs */
1721
      res->append('\\');
1722
      res->append('n');
1723
      break;
1724
    case '\r':
1725
      res->append('\\');		/* This gives better readability */
1726
      res->append('r');
1727
      break;
1728
    case '\\':
1729
      res->append('\\');		/* Because of the sql syntax */
1730
      res->append('\\');
1731
      break;
1732
    case '\'':
1733
      res->append('\'');		/* Because of the sql syntax */
1734
      res->append('\'');
1735
      break;
1736
    default:
1737
      res->append(*pos);
1738
      break;
1739
    }
1740
  }
1741
  res->append('\'');
1742
}
1743
1744
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1745
/*
1746
  Set up column usage bitmaps for a temporary table
1747
1748
  IMPLEMENTATION
1749
    For temporary tables, we need one bitmap with all columns set and
1750
    a tmp_set bitmap to be used by things like filesort.
1751
*/
1752
1005.2.3 by Monty Taylor
Further reversion of P.
1753
void Table::setup_tmp_table_column_bitmaps(unsigned char *bitmaps)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1754
{
1005.2.3 by Monty Taylor
Further reversion of P.
1755
  uint32_t field_count= s->fields;
1756
1103.6.3 by Padraig O'Sullivan
Fixing up more calls to the old bitmap API.
1757
  this->def_read_set.init((my_bitmap_map*) bitmaps, field_count);
1758
  this->tmp_set.init((my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)), field_count);
1005.2.3 by Monty Taylor
Further reversion of P.
1759
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1760
  /* write_set and all_set are copies of read_set */
1761
  def_write_set= def_read_set;
1762
  s->all_set= def_read_set;
1103.6.3 by Padraig O'Sullivan
Fixing up more calls to the old bitmap API.
1763
  this->s->all_set.setAll();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1764
  default_column_bitmaps();
1765
}
1766
1767
1768
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
1769
void Table::updateCreateInfo(HA_CREATE_INFO *create_info,
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
1770
                             message::Table *table_proto)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1771
{
1118.2.1 by Stewart Smith
fix drizzled::message::Table usage so that in kernel .cc files we are 'using namespace drizzled'
1772
  message::Table::TableOptions *table_options= table_proto->mutable_options();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1773
  create_info->table_options= s->db_create_options;
1126.2.4 by Brian Aker
Move block code out of HA_CREATE_INFO
1774
  table_options->set_block_size(s->block_size);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1775
  create_info->row_type= s->row_type;
1776
  create_info->default_table_charset= s->table_charset;
1 by brian
clean slate
1777
  create_info->table_charset= 0;
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
1778
  table_options->set_comment(s->getComment());
1 by brian
clean slate
1779
}
1780
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
1781
int rename_file_ext(const char * from,const char * to,const char * ext)
1 by brian
clean slate
1782
{
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
1783
  string from_s, to_s;
1784
1785
  from_s.append(from);
1786
  from_s.append(ext);
1787
  to_s.append(to);
1788
  to_s.append(ext);
1789
  return (my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
1 by brian
clean slate
1790
}
1791
1792
/*
1793
  DESCRIPTION
1794
    given a buffer with a key value, and a map of keyparts
1795
    that are present in this value, returns the length of the value
1796
*/
482 by Brian Aker
Remove uint.
1797
uint32_t calculate_key_len(Table *table, uint32_t key,
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
1798
                       const unsigned char *,
1 by brian
clean slate
1799
                       key_part_map keypart_map)
1800
{
1801
  /* works only with key prefixes */
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
1802
  assert(((keypart_map + 1) & keypart_map) == 0);
1 by brian
clean slate
1803
1804
  KEY *key_info= table->s->key_info+key;
1805
  KEY_PART_INFO *key_part= key_info->key_part;
1806
  KEY_PART_INFO *end_key_part= key_part + key_info->key_parts;
482 by Brian Aker
Remove uint.
1807
  uint32_t length= 0;
1 by brian
clean slate
1808
1809
  while (key_part < end_key_part && keypart_map)
1810
  {
1811
    length+= key_part->store_length;
1812
    keypart_map >>= 1;
1813
    key_part++;
1814
  }
1815
  return length;
1816
}
1817
1818
/*
1819
  Check if database name is valid
1820
1821
  SYNPOSIS
1822
    check_db_name()
1823
    org_name		Name of database and length
1824
1825
  RETURN
1826
    0	ok
1827
    1   error
1828
*/
1829
1830
bool check_db_name(LEX_STRING *org_name)
1831
{
1832
  char *name= org_name->str;
482 by Brian Aker
Remove uint.
1833
  uint32_t name_length= org_name->length;
1 by brian
clean slate
1834
1835
  if (!name_length || name_length > NAME_LEN || name[name_length - 1] == ' ')
1836
    return 1;
1837
1039.1.5 by Brian Aker
Remove lower case filename bits (aka we just lock into the most compatible
1838
  if (name != any_db)
1 by brian
clean slate
1839
    my_casedn_str(files_charset_info, name);
1840
1841
  return check_identifier_name(org_name);
1842
}
1843
1844
1845
/*
1846
  Allow anything as a table name, as long as it doesn't contain an
1847
  ' ' at the end
1848
  returns 1 on error
1849
*/
482 by Brian Aker
Remove uint.
1850
bool check_table_name(const char *name, uint32_t length)
1 by brian
clean slate
1851
{
1852
  if (!length || length > NAME_LEN || name[length - 1] == ' ')
1853
    return 1;
1854
  LEX_STRING ident;
1855
  ident.str= (char*) name;
1856
  ident.length= length;
1857
  return check_identifier_name(&ident);
1858
}
1859
1860
1861
/*
1862
  Eventually, a "length" argument should be added
1863
  to this function, and the inner loop changed to
1864
  check_identifier_name() call.
1865
*/
1866
bool check_column_name(const char *name)
1867
{
482 by Brian Aker
Remove uint.
1868
  uint32_t name_length= 0;  // name length in symbols
51.1.70 by Jay Pipes
Removed/replaced DBUG symbols and removed sql_test.cc from Makefile
1869
  bool last_char_is_space= true;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1870
1 by brian
clean slate
1871
  while (*name)
1872
  {
1873
    last_char_is_space= my_isspace(system_charset_info, *name);
1874
    if (use_mb(system_charset_info))
1875
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1876
      int len=my_ismbchar(system_charset_info, name,
1 by brian
clean slate
1877
                          name+system_charset_info->mbmaxlen);
1878
      if (len)
1879
      {
1880
        if (len > 3) /* Disallow non-BMP characters */
1881
          return 1;
1882
        name += len;
1883
        name_length++;
1884
        continue;
1885
      }
1886
    }
1887
    /*
1888
      NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
1889
      It is defined as 0xFF, which is a not valid byte in utf8.
1890
      This assert is to catch use of this byte if we decide to
1891
      use non-utf8 as system_character_set.
1892
    */
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
1893
    assert(*name != NAMES_SEP_CHAR);
1 by brian
clean slate
1894
    name++;
1895
    name_length++;
1896
  }
1897
  /* Error if empty or too long column name */
895 by Brian Aker
Completion (?) of uint conversion.
1898
  return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
1 by brian
clean slate
1899
}
1900
1901
1902
/*****************************************************************************
1903
  Functions to handle column usage bitmaps (read_set, write_set etc...)
1904
*****************************************************************************/
1905
1906
/* Reset all columns bitmaps */
1907
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
1908
void Table::clear_column_bitmaps()
1 by brian
clean slate
1909
{
1910
  /*
1005.2.3 by Monty Taylor
Further reversion of P.
1911
    Reset column read/write usage. It's identical to:
1912
    bitmap_clear_all(&table->def_read_set);
1913
    bitmap_clear_all(&table->def_write_set);
1 by brian
clean slate
1914
  */
1103.6.3 by Padraig O'Sullivan
Fixing up more calls to the old bitmap API.
1915
  def_read_set.clearAll();
1916
  def_write_set.clearAll();
1 by brian
clean slate
1917
  column_bitmaps_set(&def_read_set, &def_write_set);
1918
}
1919
1920
1921
/*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1922
  Tell Cursor we are going to call position() and rnd_pos() later.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1923
1 by brian
clean slate
1924
  NOTES:
1925
  This is needed for handlers that uses the primary key to find the
1926
  row. In this case we have to extend the read bitmap with the primary
1927
  key fields.
1928
*/
1929
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
1930
void Table::prepare_for_position()
1 by brian
clean slate
1931
{
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
1932
1208.3.2 by brian
Update for Cursor renaming.
1933
  if ((cursor->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
1 by brian
clean slate
1934
      s->primary_key < MAX_KEY)
1935
  {
1003.1.7 by Brian Aker
Add mark_columns_used_by_index_no_reset() with just index (assumes read_set
1936
    mark_columns_used_by_index_no_reset(s->primary_key);
1 by brian
clean slate
1937
  }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1938
  return;
1 by brian
clean slate
1939
}
1940
1941
1942
/*
1943
  Mark that only fields from one key is used
1944
1945
  NOTE:
1946
    This changes the bitmap to use the tmp bitmap
1947
    After this, you can't access any other columns in the table until
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
1948
    bitmaps are reset, for example with Table::clear_column_bitmaps()
1949
    or Table::restore_column_maps_after_mark_index()
1 by brian
clean slate
1950
*/
1951
482 by Brian Aker
Remove uint.
1952
void Table::mark_columns_used_by_index(uint32_t index)
1 by brian
clean slate
1953
{
1103.6.2 by Padraig O'Sullivan
Removing references to MY_BITMAP throughout the code base and updating calls
1954
  MyBitmap *bitmap= &tmp_set;
1 by brian
clean slate
1955
1208.3.2 by brian
Update for Cursor renaming.
1956
  (void) cursor->extra(HA_EXTRA_KEYREAD);
1103.6.2 by Padraig O'Sullivan
Removing references to MY_BITMAP throughout the code base and updating calls
1957
  bitmap->clearAll();
1 by brian
clean slate
1958
  mark_columns_used_by_index_no_reset(index, bitmap);
1959
  column_bitmaps_set(bitmap, bitmap);
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
1960
  return;
1 by brian
clean slate
1961
}
1962
1963
1964
/*
1965
  Restore to use normal column maps after key read
1966
1967
  NOTES
1968
    This reverse the change done by mark_columns_used_by_index
1969
1970
  WARNING
1971
    For this to work, one must have the normal table maps in place
1972
    when calling mark_columns_used_by_index
1973
*/
1974
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
1975
void Table::restore_column_maps_after_mark_index()
1 by brian
clean slate
1976
{
1977
1978
  key_read= 0;
1208.3.2 by brian
Update for Cursor renaming.
1979
  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
1 by brian
clean slate
1980
  default_column_bitmaps();
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
1981
  return;
1 by brian
clean slate
1982
}
1983
1984
1985
/*
1986
  mark columns used by key, but don't reset other fields
1987
*/
1988
1003.1.7 by Brian Aker
Add mark_columns_used_by_index_no_reset() with just index (assumes read_set
1989
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
1990
{
1991
    mark_columns_used_by_index_no_reset(index, read_set);
1992
}
1993
482 by Brian Aker
Remove uint.
1994
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
1103.6.2 by Padraig O'Sullivan
Removing references to MY_BITMAP throughout the code base and updating calls
1995
                                                MyBitmap *bitmap)
1 by brian
clean slate
1996
{
1997
  KEY_PART_INFO *key_part= key_info[index].key_part;
1998
  KEY_PART_INFO *key_part_end= (key_part +
1999
                                key_info[index].key_parts);
2000
  for (;key_part != key_part_end; key_part++)
1103.6.2 by Padraig O'Sullivan
Removing references to MY_BITMAP throughout the code base and updating calls
2001
    bitmap->setBit(key_part->fieldnr-1);
1 by brian
clean slate
2002
}
2003
2004
2005
/*
2006
  Mark auto-increment fields as used fields in both read and write maps
2007
2008
  NOTES
2009
    This is needed in insert & update as the auto-increment field is
2010
    always set and sometimes read.
2011
*/
2012
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
2013
void Table::mark_auto_increment_column()
1 by brian
clean slate
2014
{
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
2015
  assert(found_next_number_field);
1 by brian
clean slate
2016
  /*
2017
    We must set bit in read set as update_auto_increment() is using the
2018
    store() to check overflow of auto_increment values
2019
  */
1005.2.12 by Monty Taylor
Moved some things to the API.
2020
  setReadSet(found_next_number_field->field_index);
2021
  setWriteSet(found_next_number_field->field_index);
1 by brian
clean slate
2022
  if (s->next_number_keypart)
1003.1.7 by Brian Aker
Add mark_columns_used_by_index_no_reset() with just index (assumes read_set
2023
    mark_columns_used_by_index_no_reset(s->next_number_index);
1 by brian
clean slate
2024
}
2025
2026
2027
/*
2028
  Mark columns needed for doing an delete of a row
2029
2030
  DESCRIPTON
2031
    Some table engines don't have a cursor on the retrieve rows
2032
    so they need either to use the primary key or all columns to
2033
    be able to delete a row.
2034
2035
    If the engine needs this, the function works as follows:
2036
    - If primary key exits, mark the primary key columns to be read.
2037
    - If not, mark all columns to be read
2038
2039
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
2040
    mark all key columns as 'to-be-read'. This allows the engine to
2041
    loop over the given record to find all keys and doesn't have to
2042
    retrieve the row again.
2043
*/
2044
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
2045
void Table::mark_columns_needed_for_delete()
1 by brian
clean slate
2046
{
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
2047
  /*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2048
    If the Cursor has no cursor capabilites, or we have row-based
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
2049
    replication active for the current statement, we have to read
2050
    either the primary key, the hidden primary key or all columns to
2051
    be able to do an delete
2052
2053
  */
2054
  if (s->primary_key == MAX_KEY)
2055
  {
2056
    /* fallback to use all columns in the table to identify row */
2057
    use_all_columns();
2058
    return;
2059
  }
2060
  else
2061
    mark_columns_used_by_index_no_reset(s->primary_key);
2062
2063
  /* If we the engine wants all predicates we mark all keys */
1208.3.2 by brian
Update for Cursor renaming.
2064
  if (cursor->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
1 by brian
clean slate
2065
  {
2066
    Field **reg_field;
2067
    for (reg_field= field ; *reg_field ; reg_field++)
2068
    {
2069
      if ((*reg_field)->flags & PART_KEY_FLAG)
1005.2.12 by Monty Taylor
Moved some things to the API.
2070
        setReadSet((*reg_field)->field_index);
1 by brian
clean slate
2071
    }
2072
  }
2073
}
2074
2075
2076
/*
2077
  Mark columns needed for doing an update of a row
2078
2079
  DESCRIPTON
2080
    Some engines needs to have all columns in an update (to be able to
2081
    build a complete row). If this is the case, we mark all not
2082
    updated columns to be read.
2083
2084
    If this is no the case, we do like in the delete case and mark
2085
    if neeed, either the primary key column or all columns to be read.
2086
    (see mark_columns_needed_for_delete() for details)
2087
2088
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
2089
    mark all USED key columns as 'to-be-read'. This allows the engine to
2090
    loop over the given record to find all changed keys and doesn't have to
2091
    retrieve the row again.
2092
*/
2093
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
2094
void Table::mark_columns_needed_for_update()
1 by brian
clean slate
2095
{
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
2096
  /*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2097
    If the Cursor has no cursor capabilites, or we have row-based
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
2098
    logging active for the current statement, we have to read either
2099
    the primary key, the hidden primary key or all columns to be
2100
    able to do an update
2101
  */
2102
  if (s->primary_key == MAX_KEY)
2103
  {
2104
    /* fallback to use all columns in the table to identify row */
2105
    use_all_columns();
2106
    return;
2107
  }
2108
  else
2109
    mark_columns_used_by_index_no_reset(s->primary_key);
2110
1208.3.2 by brian
Update for Cursor renaming.
2111
  if (cursor->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
1 by brian
clean slate
2112
  {
2113
    /* Mark all used key columns for read */
2114
    Field **reg_field;
2115
    for (reg_field= field ; *reg_field ; reg_field++)
2116
    {
2117
      /* Merge keys is all keys that had a column refered to in the query */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2118
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
1005.2.12 by Monty Taylor
Moved some things to the API.
2119
        setReadSet((*reg_field)->field_index);
1 by brian
clean slate
2120
    }
2121
  }
798.2.21 by Brian Aker
More work on binlog.poen
2122
1 by brian
clean slate
2123
}
2124
2125
2126
/*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2127
  Mark columns the Cursor needs for doing an insert
1 by brian
clean slate
2128
2129
  For now, this is used to mark fields used by the trigger
2130
  as changed.
2131
*/
2132
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
2133
void Table::mark_columns_needed_for_insert()
1 by brian
clean slate
2134
{
2135
  if (found_next_number_field)
2136
    mark_auto_increment_column();
383.7.1 by Andrey Zhakov
Initial submit of code and tests
2137
}
2138
1 by brian
clean slate
2139
2140
481 by Brian Aker
Remove all of uchar.
2141
size_t Table::max_row_length(const unsigned char *data)
1 by brian
clean slate
2142
{
354 by Brian Aker
Refactor of Table methods.
2143
  size_t length= getRecordLength() + 2 * sizeFields();
482 by Brian Aker
Remove uint.
2144
  uint32_t *const beg= getBlobField();
2145
  uint32_t *const end= beg + sizeBlobFields();
1 by brian
clean slate
2146
482 by Brian Aker
Remove uint.
2147
  for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
1 by brian
clean slate
2148
  {
354 by Brian Aker
Refactor of Table methods.
2149
    Field_blob* const blob= (Field_blob*) field[*ptr];
481 by Brian Aker
Remove all of uchar.
2150
    length+= blob->get_length((const unsigned char*)
354 by Brian Aker
Refactor of Table methods.
2151
                              (data + blob->offset(record[0]))) +
1 by brian
clean slate
2152
      HA_KEY_BLOB_LENGTH;
2153
  }
2154
  return length;
2155
}
2156
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2157
/****************************************************************************
2158
 Functions for creating temporary tables.
2159
****************************************************************************/
2160
2161
2162
/* Prototypes */
520.1.22 by Brian Aker
Second pass of thd cleanup
2163
void free_tmp_table(Session *session, Table *entry);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2164
2165
/**
2166
  Create field for temporary table from given field.
2167
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2168
  @param session	       Thread Cursor
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2169
  @param org_field    field from which new field will be created
2170
  @param name         New field name
2171
  @param table	       Temporary table
2172
  @param item	       !=NULL if item->result_field should point to new field.
2173
                      This is relevant for how fill_record() is going to work:
2174
                      If item != NULL then fill_record() will update
2175
                      the record in the original table.
2176
                      If item == NULL then fill_record() will update
2177
                      the temporary table
2178
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
2179
                               field instead of blob.
2180
2181
  @retval
2182
    NULL		on error
2183
  @retval
2184
    new_created field
2185
*/
2186
520.1.22 by Brian Aker
Second pass of thd cleanup
2187
Field *create_tmp_field_from_field(Session *session, Field *org_field,
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2188
                                   const char *name, Table *table,
482 by Brian Aker
Remove uint.
2189
                                   Item_field *item, uint32_t convert_blob_length)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2190
{
2191
  Field *new_field;
2192
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2193
  /*
2194
    Make sure that the blob fits into a Field_varstring which has
2195
    2-byte lenght.
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2196
  */
2197
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
2198
      (org_field->flags & BLOB_FLAG))
2199
    new_field= new Field_varstring(convert_blob_length,
2200
                                   org_field->maybe_null(),
2201
                                   org_field->field_name, table->s,
2202
                                   org_field->charset());
2203
  else
520.1.22 by Brian Aker
Second pass of thd cleanup
2204
    new_field= org_field->new_field(session->mem_root, table,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2205
                                    table == org_field->table);
2206
  if (new_field)
2207
  {
2208
    new_field->init(table);
2209
    new_field->orig_table= org_field->orig_table;
2210
    if (item)
2211
      item->result_field= new_field;
2212
    else
2213
      new_field->field_name= name;
2214
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
2215
    if (org_field->maybe_null() || (item && item->maybe_null))
2216
      new_field->flags&= ~NOT_NULL_FLAG;	// Because of outer join
2217
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
2218
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
2219
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
2220
      ((Field_double *) new_field)->not_fixed= true;
2221
  }
2222
  return new_field;
2223
}
2224
2225
2226
/**
2227
  Create field for information schema table.
2228
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2229
  @param session		Thread Cursor
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2230
  @param table		Temporary table
2231
  @param item		Item to create a field for
2232
2233
  @retval
2234
    0			on error
2235
  @retval
2236
    new_created field
2237
*/
2238
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
2239
static Field *create_tmp_field_for_schema(Item *item, Table *table)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2240
{
2241
  if (item->field_type() == DRIZZLE_TYPE_VARCHAR)
2242
  {
2243
    Field *field;
2244
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
2245
      field= new Field_blob(item->max_length, item->maybe_null,
2246
                            item->name, item->collation.collation);
2247
    else
2248
      field= new Field_varstring(item->max_length, item->maybe_null,
2249
                                 item->name,
2250
                                 table->s, item->collation.collation);
2251
    if (field)
2252
      field->init(table);
2253
    return field;
2254
  }
2255
  return item->tmp_table_field_from_field_type(table, 0);
2256
}
2257
2258
2259
/**
2260
  Create a temp table according to a field list.
2261
2262
  Given field pointers are changed to point at tmp_table for
2263
  send_fields. The table object is self contained: it's
2264
  allocated in its own memory root, as well as Field objects
2265
  created for table columns.
2266
  This function will replace Item_sum items in 'fields' list with
2267
  corresponding Item_field items, pointing at the fields in the
2268
  temporary table, unless this was prohibited by true
2269
  value of argument save_sum_fields. The Item_field objects
520.1.21 by Brian Aker
THD -> Session rename
2270
  are created in Session memory root.
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2271
520.1.22 by Brian Aker
Second pass of thd cleanup
2272
  @param session                  thread handle
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2273
  @param param                a description used as input to create the table
2274
  @param fields               list of items that will be used to define
2275
                              column types of the table (also see NOTES)
2276
  @param group                TODO document
2277
  @param distinct             should table rows be distinct
2278
  @param save_sum_fields      see NOTES
2279
  @param select_options
2280
  @param rows_limit
2281
  @param table_alias          possible name of the temporary table that can
2282
                              be used for name resolving; can be "".
2283
*/
2284
2285
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
2286
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
2287
#define RATIO_TO_PACK_ROWS	       2
2288
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2289
Table *
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
2290
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
327.2.3 by Brian Aker
Refactoring of class Table
2291
		 order_st *group, bool distinct, bool save_sum_fields,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2292
		 uint64_t select_options, ha_rows rows_limit,
1039.1.4 by Brian Aker
Modified alias to being const.
2293
		 const char *table_alias)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2294
{
2295
  MEM_ROOT *mem_root_save, own_root;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2296
  Table *table;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
2297
  TableShare *share;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2298
  uint	i,field_count,null_count,null_pack_length;
482 by Brian Aker
Remove uint.
2299
  uint32_t  copy_func_count= param->func_count;
2300
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
2301
  uint32_t  blob_count,group_null_items, string_count;
2302
  uint32_t fieldnr= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2303
  ulong reclength, string_total_length;
2304
  bool  using_unique_constraint= 0;
2305
  bool  use_packed_rows= 0;
2306
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
2307
  char  *tmpname,path[FN_REFLEN];
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
2308
  unsigned char	*pos, *group_buff, *bitmaps;
481 by Brian Aker
Remove all of uchar.
2309
  unsigned char *null_flags;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2310
  Field **reg_field, **from_field, **default_field;
482 by Brian Aker
Remove uint.
2311
  uint32_t *blob_field;
1052.2.2 by Nathan Williams
No actual code changes. Changed Copy_field to CopyField, to reflect the coding standards.
2312
  CopyField *copy= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2313
  KEY *keyinfo;
2314
  KEY_PART_INFO *key_part_info;
2315
  Item **copy_func;
2316
  MI_COLUMNDEF *recinfo;
482 by Brian Aker
Remove uint.
2317
  uint32_t total_uneven_bit_length= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2318
  bool force_copy_fields= param->force_copy_fields;
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
2319
  uint64_t max_rows= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2320
520.1.22 by Brian Aker
Second pass of thd cleanup
2321
  status_var_increment(session->status_var.created_tmp_tables);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2322
1014.2.12 by Monty Taylor
Removed the thread-safe crap in MY_BITMAP. Also remove the temp-pool option for
2323
  /* if we run out of slots or we are not using tempool */
2324
  sprintf(path,"%s%lx_%"PRIx64"_%x", TMP_FILE_PREFIX, (unsigned long)current_pid,
2325
          session->thread_id, session->tmp_table++);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2326
2327
  /*
2328
    No need to change table name to lower case as we are only creating
2329
    MyISAM or HEAP tables here
2330
  */
575.4.3 by ysano
Rename mysql to drizzle.
2331
  fn_format(path, path, drizzle_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2332
2333
2334
  if (group)
2335
  {
2336
    if (!param->quick_group)
1046.1.6 by Brian Aker
Formatting/style cleanup.
2337
      group= 0;					// Can't use group key
327.2.3 by Brian Aker
Refactoring of class Table
2338
    else for (order_st *tmp=group ; tmp ; tmp=tmp->next)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2339
    {
2340
      /*
2341
        marker == 4 means two things:
2342
        - store NULLs in the key, and
2343
        - convert BIT fields to 64-bit long, needed because MEMORY tables
2344
          can't index BIT fields.
2345
      */
2346
      (*tmp->item)->marker= 4;
2347
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
2348
	using_unique_constraint=1;
2349
    }
2350
    if (param->group_length >= MAX_BLOB_WIDTH)
2351
      using_unique_constraint=1;
2352
    if (group)
1046.1.6 by Brian Aker
Formatting/style cleanup.
2353
      distinct= 0;				// Can't use distinct
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2354
  }
2355
2356
  field_count=param->field_count+param->func_count+param->sum_func_count;
2357
  hidden_field_count=param->hidden_field_count;
2358
2359
  /*
2360
    When loose index scan is employed as access method, it already
2361
    computes all groups and the result of all aggregate functions. We
2362
    make space for the items of the aggregate function in the list of
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
2363
    functions Tmp_Table_Param::items_to_copy, so that the values of
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2364
    these items are stored in the temporary table.
2365
  */
2366
  if (param->precomputed_group_by)
2367
    copy_func_count+= param->sum_func_count;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2368
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2369
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
2370
2371
  if (!multi_alloc_root(&own_root,
2372
                        &table, sizeof(*table),
2373
                        &share, sizeof(*share),
2374
                        &reg_field, sizeof(Field*) * (field_count+1),
2375
                        &default_field, sizeof(Field*) * (field_count),
895 by Brian Aker
Completion (?) of uint conversion.
2376
                        &blob_field, sizeof(uint32_t)*(field_count+1),
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2377
                        &from_field, sizeof(Field*)*field_count,
2378
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
2379
                        &param->keyinfo, sizeof(*param->keyinfo),
2380
                        &key_part_info,
2381
                        sizeof(*key_part_info)*(param->group_parts+1),
2382
                        &param->start_recinfo,
2383
                        sizeof(*param->recinfo)*(field_count*2+4),
895 by Brian Aker
Completion (?) of uint conversion.
2384
                        &tmpname, (uint32_t) strlen(path)+1,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2385
                        &group_buff, (group && ! using_unique_constraint ?
2386
                                      param->group_length : 0),
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
2387
                        &bitmaps, bitmap_buffer_size(field_count)*2,
461 by Monty Taylor
Removed NullS. bu-bye.
2388
                        NULL))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2389
  {
971.6.11 by Eric Day
Removed purecov messages.
2390
    return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2391
  }
1052.2.2 by Nathan Williams
No actual code changes. Changed Copy_field to CopyField, to reflect the coding standards.
2392
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
2393
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2394
  {
971.6.11 by Eric Day
Removed purecov messages.
2395
    free_root(&own_root, MYF(0));
2396
    return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2397
  }
2398
  param->items_to_copy= copy_func;
641.4.1 by Toru Maesaka
First pass of replacing MySQL's my_stpcpy() with appropriate libc calls
2399
  strcpy(tmpname,path);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2400
  /* make table according to fields */
2401
2402
  memset(table, 0, sizeof(*table));
2403
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
2404
  memset(default_field, 0, sizeof(Field*) * (field_count));
2405
  memset(from_field, 0, sizeof(Field*)*field_count);
2406
2407
  table->mem_root= own_root;
520.1.22 by Brian Aker
Second pass of thd cleanup
2408
  mem_root_save= session->mem_root;
2409
  session->mem_root= &table->mem_root;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2410
2411
  table->field=reg_field;
2412
  table->alias= table_alias;
2413
  table->reginfo.lock_type=TL_WRITE;	/* Will be updated */
2414
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
2415
  table->map=1;
2416
  table->copy_blobs= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
2417
  table->in_use= session;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2418
  table->quick_keys.reset();
2419
  table->covering_keys.reset();
2420
  table->keys_in_use_for_query.reset();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2421
2422
  table->setShare(share);
1000.1.5 by Brian Aker
More refactoring back to TableShare object.
2423
  share->init(tmpname, tmpname);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2424
  share->blob_field= blob_field;
2425
  share->blob_ptr_size= portable_sizeof_char_ptr;
2426
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
2427
  share->table_charset= param->table_charset;
2428
  share->primary_key= MAX_KEY;               // Indicate no primary key
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
2429
  share->keys_for_keyread.reset();
2430
  share->keys_in_use.reset();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2431
2432
  /* Calculate which type of fields we will store in the temporary table */
2433
2434
  reclength= string_total_length= 0;
2435
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
1046.1.6 by Brian Aker
Formatting/style cleanup.
2436
  param->using_indirect_summary_function= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2437
2438
  List_iterator_fast<Item> li(fields);
2439
  Item *item;
2440
  Field **tmp_from_field=from_field;
2441
  while ((item=li++))
2442
  {
2443
    Item::Type type=item->type();
2444
    if (not_all_columns)
2445
    {
2446
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
2447
      {
2448
        if (item->used_tables() & OUTER_REF_TABLE_BIT)
2449
          item->update_used_tables();
2450
        if (type == Item::SUBSELECT_ITEM ||
2451
            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
2452
        {
2453
	  /*
2454
	    Mark that the we have ignored an item that refers to a summary
2455
	    function. We need to know this if someone is going to use
2456
	    DISTINCT on the result.
2457
	  */
2458
	  param->using_indirect_summary_function=1;
2459
	  continue;
2460
        }
2461
      }
2462
      if (item->const_item() && (int) hidden_field_count <= 0)
2463
        continue; // We don't have to store this
2464
    }
2465
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
2466
    {						/* Can't calc group yet */
1046.1.6 by Brian Aker
Formatting/style cleanup.
2467
      ((Item_sum*) item)->result_field= 0;
2468
      for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2469
      {
2470
	Item **argp= ((Item_sum*) item)->args + i;
2471
	Item *arg= *argp;
2472
	if (!arg->const_item())
2473
	{
2474
	  Field *new_field=
520.1.22 by Brian Aker
Second pass of thd cleanup
2475
            create_tmp_field(session, table, arg, arg->type(), &copy_func,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2476
                             tmp_from_field, &default_field[fieldnr],
2477
                             group != 0,not_all_columns,
2478
                             distinct, 0,
2479
                             param->convert_blob_length);
2480
	  if (!new_field)
2481
	    goto err;					// Should be OOM
2482
	  tmp_from_field++;
2483
	  reclength+=new_field->pack_length();
2484
	  if (new_field->flags & BLOB_FLAG)
2485
	  {
2486
	    *blob_field++= fieldnr;
2487
	    blob_count++;
2488
	  }
2489
	  *(reg_field++)= new_field;
2490
          if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
2491
          {
2492
            string_count++;
2493
            string_total_length+= new_field->pack_length();
2494
          }
520.1.22 by Brian Aker
Second pass of thd cleanup
2495
          session->mem_root= mem_root_save;
2496
          session->change_item_tree(argp, new Item_field(new_field));
2497
          session->mem_root= &table->mem_root;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2498
	  if (!(new_field->flags & NOT_NULL_FLAG))
2499
          {
2500
	    null_count++;
2501
            /*
2502
              new_field->maybe_null() is still false, it will be
2503
              changed below. But we have to setup Item_field correctly
2504
            */
2505
            (*argp)->maybe_null=1;
2506
          }
2507
          new_field->field_index= fieldnr++;
2508
	}
2509
      }
2510
    }
2511
    else
2512
    {
2513
      /*
2514
	The last parameter to create_tmp_field() is a bit tricky:
2515
2516
	We need to set it to 0 in union, to get fill_record() to modify the
2517
	temporary table.
2518
	We need to set it to 1 on multi-table-update and in select to
2519
	write rows to the temporary table.
2520
	We here distinguish between UNION and multi-table-updates by the fact
2521
	that in the later case group is set to the row pointer.
2522
      */
2523
      Field *new_field= (param->schema_table) ?
1014.3.4 by Brian Aker
Remove dead session calls.
2524
        create_tmp_field_for_schema(item, table) :
520.1.22 by Brian Aker
Second pass of thd cleanup
2525
        create_tmp_field(session, table, item, type, &copy_func,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2526
                         tmp_from_field, &default_field[fieldnr],
2527
                         group != 0,
2528
                         !force_copy_fields &&
1046.1.6 by Brian Aker
Formatting/style cleanup.
2529
                           (not_all_columns || group != 0),
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2530
                         /*
2531
                           If item->marker == 4 then we force create_tmp_field
2532
                           to create a 64-bit longs for BIT fields because HEAP
2533
                           tables can't index BIT fields directly. We do the same
2534
                           for distinct, as we want the distinct index to be
2535
                           usable in this case too.
2536
                         */
2537
                         item->marker == 4 || param->bit_fields_as_long,
2538
                         force_copy_fields,
2539
                         param->convert_blob_length);
2540
2541
      if (!new_field)
2542
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
2543
	if (session->is_fatal_error)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2544
	  goto err;				// Got OOM
2545
	continue;				// Some kindf of const item
2546
      }
2547
      if (type == Item::SUM_FUNC_ITEM)
2548
	((Item_sum *) item)->result_field= new_field;
2549
      tmp_from_field++;
2550
      reclength+=new_field->pack_length();
2551
      if (!(new_field->flags & NOT_NULL_FLAG))
2552
	null_count++;
2553
      if (new_field->flags & BLOB_FLAG)
2554
      {
2555
        *blob_field++= fieldnr;
2556
	blob_count++;
2557
      }
2558
      if (item->marker == 4 && item->maybe_null)
2559
      {
2560
	group_null_items++;
2561
	new_field->flags|= GROUP_FLAG;
2562
      }
2563
      new_field->field_index= fieldnr++;
2564
      *(reg_field++)= new_field;
2565
    }
2566
    if (!--hidden_field_count)
2567
    {
2568
      /*
2569
        This was the last hidden field; Remember how many hidden fields could
2570
        have null
2571
      */
2572
      hidden_null_count=null_count;
2573
      /*
2574
	We need to update hidden_field_count as we may have stored group
2575
	functions with constant arguments
2576
      */
2577
      param->hidden_field_count= fieldnr;
2578
      null_count= 0;
2579
    }
2580
  }
895 by Brian Aker
Completion (?) of uint conversion.
2581
  assert(fieldnr == (uint32_t) (reg_field - table->field));
2582
  assert(field_count >= (uint32_t) (reg_field - table->field));
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2583
  field_count= fieldnr;
2584
  *reg_field= 0;
2585
  *blob_field= 0;				// End marker
2586
  share->fields= field_count;
2587
2588
  /* If result table is small; use a heap */
2589
  /* future: storage engine selection can be made dynamic? */
2590
  if (blob_count || using_unique_constraint ||
2591
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
2592
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
2593
  {
971.1.21 by Monty Taylor
Store StorageEngine in system variables, rather than storage engine plugin.
2594
    share->storage_engine= myisam_engine;
1208.3.2 by brian
Update for Cursor renaming.
2595
    table->cursor= share->db_type()->getCursor(*share, &table->mem_root);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2596
    if (group &&
1208.3.2 by brian
Update for Cursor renaming.
2597
	(param->group_parts > table->cursor->max_key_parts() ||
2598
	 param->group_length > table->cursor->max_key_length()))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2599
      using_unique_constraint=1;
2600
  }
2601
  else
2602
  {
971.1.21 by Monty Taylor
Store StorageEngine in system variables, rather than storage engine plugin.
2603
    share->storage_engine= heap_engine;
1208.3.2 by brian
Update for Cursor renaming.
2604
    table->cursor= share->db_type()->getCursor(*share, &table->mem_root);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2605
  }
1208.3.2 by brian
Update for Cursor renaming.
2606
  if (!table->cursor)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2607
    goto err;
2608
2609
2610
  if (!using_unique_constraint)
2611
    reclength+= group_null_items;	// null flag is stored separately
2612
2613
  share->blob_fields= blob_count;
2614
  if (blob_count == 0)
2615
  {
2616
    /* We need to ensure that first byte is not 0 for the delete link */
2617
    if (param->hidden_field_count)
2618
      hidden_null_count++;
2619
    else
2620
      null_count++;
2621
  }
2622
  hidden_null_pack_length=(hidden_null_count+7)/8;
2623
  null_pack_length= (hidden_null_pack_length +
2624
                     (null_count + total_uneven_bit_length + 7) / 8);
2625
  reclength+=null_pack_length;
2626
  if (!reclength)
2627
    reclength=1;				// Dummy select
2628
  /* Use packed rows if there is blobs or a lot of space to gain */
2629
  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)))
2630
    use_packed_rows= 1;
2631
2632
  share->reclength= reclength;
2633
  {
482 by Brian Aker
Remove uint.
2634
    uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2635
    share->rec_buff_length= alloc_length;
481 by Brian Aker
Remove all of uchar.
2636
    if (!(table->record[0]= (unsigned char*)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2637
                            alloc_root(&table->mem_root, alloc_length*3)))
2638
      goto err;
2639
    table->record[1]= table->record[0]+alloc_length;
2640
    share->default_values= table->record[1]+alloc_length;
2641
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
2642
  copy_func[0]= 0;				// End marker
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2643
  param->func_count= copy_func - param->items_to_copy;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2644
1005.2.3 by Monty Taylor
Further reversion of P.
2645
  table->setup_tmp_table_column_bitmaps(bitmaps);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2646
2647
  recinfo=param->start_recinfo;
481 by Brian Aker
Remove all of uchar.
2648
  null_flags=(unsigned char*) table->record[0];
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2649
  pos=table->record[0]+ null_pack_length;
2650
  if (null_pack_length)
2651
  {
2652
    memset(recinfo, 0, sizeof(*recinfo));
2653
    recinfo->type=FIELD_NORMAL;
2654
    recinfo->length=null_pack_length;
2655
    recinfo++;
2656
    memset(null_flags, 255, null_pack_length);	// Set null fields
2657
481 by Brian Aker
Remove all of uchar.
2658
    table->null_flags= (unsigned char*) table->record[0];
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2659
    share->null_fields= null_count+ hidden_null_count;
2660
    share->null_bytes= null_pack_length;
2661
  }
2662
  null_count= (blob_count == 0) ? 1 : 0;
2663
  hidden_field_count=param->hidden_field_count;
1046.1.6 by Brian Aker
Formatting/style cleanup.
2664
  for (i= 0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2665
  {
2666
    Field *field= *reg_field;
482 by Brian Aker
Remove uint.
2667
    uint32_t length;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2668
    memset(recinfo, 0, sizeof(*recinfo));
2669
2670
    if (!(field->flags & NOT_NULL_FLAG))
2671
    {
2672
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
2673
      {
2674
	/*
2675
	  We have to reserve one byte here for NULL bits,
2676
	  as this is updated by 'end_update()'
2677
	*/
1063.5.1 by Patrick
Fix for Centos 5.2
2678
	*pos++= '\0';				// Null is stored here
1046.1.6 by Brian Aker
Formatting/style cleanup.
2679
	recinfo->length= 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2680
	recinfo->type=FIELD_NORMAL;
2681
	recinfo++;
2682
	memset(recinfo, 0, sizeof(*recinfo));
2683
      }
2684
      else
2685
      {
2686
	recinfo->null_bit= 1 << (null_count & 7);
2687
	recinfo->null_pos= null_count/8;
2688
      }
2689
      field->move_field(pos,null_flags+null_count/8,
2690
			1 << (null_count & 7));
2691
      null_count++;
2692
    }
2693
    else
481 by Brian Aker
Remove all of uchar.
2694
      field->move_field(pos,(unsigned char*) 0,0);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2695
    field->reset();
2696
2697
    /*
2698
      Test if there is a default field value. The test for ->ptr is to skip
2699
      'offset' fields generated by initalize_tables
2700
    */
2701
    if (default_field[i] && default_field[i]->ptr)
2702
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2703
      /*
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2704
         default_field[i] is set only in the cases  when 'field' can
2705
         inherit the default value that is defined for the field referred
2706
         by the Item_field object from which 'field' has been created.
2707
      */
1122.2.12 by Monty Taylor
Removed the silly my_ptrdiff_t typedef.
2708
      ptrdiff_t diff;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2709
      Field *orig_field= default_field[i];
2710
      /* Get the value from default_values */
1122.2.12 by Monty Taylor
Removed the silly my_ptrdiff_t typedef.
2711
      diff= (ptrdiff_t) (orig_field->table->s->default_values-
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2712
                            orig_field->table->record[0]);
2713
      orig_field->move_field_offset(diff);      // Points now at default_values
2714
      if (orig_field->is_real_null())
2715
        field->set_null();
2716
      else
2717
      {
2718
        field->set_notnull();
2719
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
2720
      }
2721
      orig_field->move_field_offset(-diff);     // Back to record[0]
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2722
    }
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2723
2724
    if (from_field[i])
2725
    {						/* Not a table Item */
2726
      copy->set(field,from_field[i],save_sum_fields);
2727
      copy++;
2728
    }
2729
    length=field->pack_length();
2730
    pos+= length;
2731
2732
    /* Make entry for create table */
2733
    recinfo->length=length;
2734
    if (field->flags & BLOB_FLAG)
2735
      recinfo->type= (int) FIELD_BLOB;
2736
    else
2737
      recinfo->type=FIELD_NORMAL;
2738
    if (!--hidden_field_count)
2739
      null_count=(null_count+7) & ~7;		// move to next byte
2740
2741
    // fix table name in field entry
2742
    field->table_name= &table->alias;
2743
  }
2744
2745
  param->copy_field_end=copy;
2746
  param->recinfo=recinfo;
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
2747
  table->storeRecordAsDefault();        // Make empty default record
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2748
520.1.22 by Brian Aker
Second pass of thd cleanup
2749
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)		// No limit
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
2750
    max_rows= ~(uint64_t) 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2751
  else
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
2752
    max_rows= (uint64_t) (((share->db_type() == heap_engine) ?
2753
                          min(session->variables.tmp_table_size,
2754
                              session->variables.max_heap_table_size) :
2755
                          session->variables.tmp_table_size) /
2756
                         share->reclength);
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
2757
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
2758
  set_if_bigger(max_rows, (uint64_t)1);	// For dummy start options
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2759
  /*
2760
    Push the LIMIT clause to the temporary table creation, so that we
2761
    materialize only up to 'rows_limit' records instead of all result records.
2762
  */
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
2763
  set_if_smaller(max_rows, rows_limit);
2764
2765
  share->setMaxRows(max_rows);
2766
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2767
  param->end_write_records= rows_limit;
2768
2769
  keyinfo= param->keyinfo;
2770
2771
  if (group)
2772
  {
2773
    table->group=group;				/* Table is grouped by key */
2774
    param->group_buff=group_buff;
2775
    share->keys=1;
2776
    share->uniques= test(using_unique_constraint);
2777
    table->key_info=keyinfo;
2778
    keyinfo->key_part=key_part_info;
2779
    keyinfo->flags=HA_NOSAME;
2780
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
1046.1.6 by Brian Aker
Formatting/style cleanup.
2781
    keyinfo->key_length= 0;
2782
    keyinfo->rec_per_key= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2783
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
2784
    keyinfo->name= (char*) "group_key";
327.2.3 by Brian Aker
Refactoring of class Table
2785
    order_st *cur_group= group;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2786
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
2787
    {
2788
      Field *field=(*cur_group->item)->get_tmp_table_field();
2789
      bool maybe_null=(*cur_group->item)->maybe_null;
1046.1.6 by Brian Aker
Formatting/style cleanup.
2790
      key_part_info->null_bit= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2791
      key_part_info->field=  field;
2792
      key_part_info->offset= field->offset(table->record[0]);
2793
      key_part_info->length= (uint16_t) field->key_length();
2794
      key_part_info->type=   (uint8_t) field->key_type();
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
2795
      key_part_info->key_type= 
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2796
	((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
2797
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
2798
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
2799
	0 : 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2800
      if (!using_unique_constraint)
2801
      {
2802
	cur_group->buff=(char*) group_buff;
520.1.22 by Brian Aker
Second pass of thd cleanup
2803
	if (!(cur_group->field= field->new_key_field(session->mem_root,table,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2804
                                                     group_buff +
2805
                                                     test(maybe_null),
2806
                                                     field->null_ptr,
2807
                                                     field->null_bit)))
971.6.11 by Eric Day
Removed purecov messages.
2808
	  goto err;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2809
	if (maybe_null)
2810
	{
2811
	  /*
2812
	    To be able to group on NULL, we reserved place in group_buff
2813
	    for the NULL flag just before the column. (see above).
2814
	    The field data is after this flag.
2815
	    The NULL flag is updated in 'end_update()' and 'end_write()'
2816
	  */
2817
	  keyinfo->flags|= HA_NULL_ARE_EQUAL;	// def. that NULL == NULL
2818
	  key_part_info->null_bit=field->null_bit;
895 by Brian Aker
Completion (?) of uint conversion.
2819
	  key_part_info->null_offset= (uint32_t) (field->null_ptr -
481 by Brian Aker
Remove all of uchar.
2820
					      (unsigned char*) table->record[0]);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2821
          cur_group->buff++;                        // Pointer to field data
2822
	  group_buff++;                         // Skipp null flag
2823
	}
2824
        /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
2825
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
2826
	group_buff+= cur_group->field->pack_length();
2827
      }
2828
      keyinfo->key_length+=  key_part_info->length;
2829
    }
2830
  }
2831
2832
  if (distinct && field_count != param->hidden_field_count)
2833
  {
2834
    /*
2835
      Create an unique key or an unique constraint over all columns
2836
      that should be in the result.  In the temporary table, there are
2837
      'param->hidden_field_count' extra columns, whose null bits are stored
2838
      in the first 'hidden_null_pack_length' bytes of the row.
2839
    */
2840
    if (blob_count)
2841
    {
2842
      /*
2843
        Special mode for index creation in MyISAM used to support unique
2844
        indexes on blobs with arbitrary length. Such indexes cannot be
2845
        used for lookups.
2846
      */
2847
      share->uniques= 1;
2848
    }
2849
    null_pack_length-=hidden_null_pack_length;
2850
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
2851
			 (share->uniques ? test(null_pack_length) : 0));
2852
    table->distinct= 1;
2853
    share->keys= 1;
2854
    if (!(key_part_info= (KEY_PART_INFO*)
2855
          alloc_root(&table->mem_root,
2856
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
2857
      goto err;
2858
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
2859
    table->key_info=keyinfo;
2860
    keyinfo->key_part=key_part_info;
2861
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
2862
    keyinfo->key_length=(uint16_t) reclength;
2863
    keyinfo->name= (char*) "distinct_key";
2864
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1046.1.6 by Brian Aker
Formatting/style cleanup.
2865
    keyinfo->rec_per_key= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2866
2867
    /*
2868
      Create an extra field to hold NULL bits so that unique indexes on
2869
      blobs can distinguish NULL from 0. This extra field is not needed
2870
      when we do not use UNIQUE indexes for blobs.
2871
    */
2872
    if (null_pack_length && share->uniques)
2873
    {
1046.1.6 by Brian Aker
Formatting/style cleanup.
2874
      key_part_info->null_bit= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2875
      key_part_info->offset=hidden_null_pack_length;
2876
      key_part_info->length=null_pack_length;
2877
      key_part_info->field= new Field_varstring(table->record[0],
2878
                                                (uint32_t) key_part_info->length,
2879
                                                0,
481 by Brian Aker
Remove all of uchar.
2880
                                                (unsigned char*) 0,
895 by Brian Aker
Completion (?) of uint conversion.
2881
                                                (uint32_t) 0,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2882
                                                NULL,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2883
                                                table->s,
2884
                                                &my_charset_bin);
2885
      if (!key_part_info->field)
2886
        goto err;
2887
      key_part_info->field->init(table);
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
2888
      key_part_info->key_type= 1; /* binary comparison */
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2889
      key_part_info->type=    HA_KEYTYPE_BINARY;
2890
      key_part_info++;
2891
    }
2892
    /* Create a distinct key over the columns we are going to return */
2893
    for (i=param->hidden_field_count, reg_field=table->field + i ;
2894
	 i < field_count;
2895
	 i++, reg_field++, key_part_info++)
2896
    {
1046.1.6 by Brian Aker
Formatting/style cleanup.
2897
      key_part_info->null_bit= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2898
      key_part_info->field=    *reg_field;
2899
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
2900
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
2901
      /* TODO:
2902
        The below method of computing the key format length of the
2903
        key part is a copy/paste from opt_range.cc, and table.cc.
2904
        This should be factored out, e.g. as a method of Field.
2905
        In addition it is not clear if any of the Field::*_length
2906
        methods is supposed to compute the same length. If so, it
2907
        might be reused.
2908
      */
2909
      key_part_info->store_length= key_part_info->length;
2910
2911
      if ((*reg_field)->real_maybe_null())
2912
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2913
      if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2914
          (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
2915
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
2916
2917
      key_part_info->type=     (uint8_t) (*reg_field)->key_type();
2918
      key_part_info->key_type =
2919
	((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
2920
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
2921
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
2922
	0 : 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2923
    }
2924
  }
2925
520.1.22 by Brian Aker
Second pass of thd cleanup
2926
  if (session->is_fatal_error)				// If end of memory
971.6.11 by Eric Day
Removed purecov messages.
2927
    goto err;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2928
  share->db_record_offset= 1;
960.2.25 by Monty Taylor
First step of hton rename.
2929
  if (share->db_type() == myisam_engine)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2930
  {
2931
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
2932
				       &param->recinfo, select_options))
2933
      goto err;
2934
  }
2935
  if (table->open_tmp_table())
2936
    goto err;
2937
520.1.22 by Brian Aker
Second pass of thd cleanup
2938
  session->mem_root= mem_root_save;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2939
2940
  return(table);
2941
2942
err:
520.1.22 by Brian Aker
Second pass of thd cleanup
2943
  session->mem_root= mem_root_save;
971.6.11 by Eric Day
Removed purecov messages.
2944
  table->free_tmp_table(session);
2945
  return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2946
}
2947
2948
/****************************************************************************/
2949
2950
/**
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2951
  Create a reduced Table object with properly set up Field list from a
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2952
  list of field definitions.
2953
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2954
    The created table doesn't have a table Cursor associated with
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2955
    it, has no keys, no group/distinct, no copy_funcs array.
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2956
    The sole purpose of this Table object is to use the power of Field
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2957
    class to read/write data to/from table->record[0]. Then one can store
2958
    the record in any container (RB tree, hash, etc).
520.1.21 by Brian Aker
THD -> Session rename
2959
    The table is created in Session mem_root, so are the table's fields.
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2960
    Consequently, if you don't BLOB fields, you don't need to free it.
2961
520.1.22 by Brian Aker
Second pass of thd cleanup
2962
  @param session         connection handle
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2963
  @param field_list  list of column definitions
2964
2965
  @return
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2966
    0 if out of memory, Table object in case of success
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2967
*/
2968
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
2969
Table *create_virtual_tmp_table(Session *session, List<CreateField> &field_list)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2970
{
482 by Brian Aker
Remove uint.
2971
  uint32_t field_count= field_list.elements;
2972
  uint32_t blob_count= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2973
  Field **field;
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
2974
  CreateField *cdef;                           /* column definition */
482 by Brian Aker
Remove uint.
2975
  uint32_t record_length= 0;
2976
  uint32_t null_count= 0;                 /* number of columns which may be null */
2977
  uint32_t null_pack_length;              /* NULL representation array length */
2978
  uint32_t *blob_field;
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
2979
  unsigned char *bitmaps;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2980
  Table *table;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
2981
  TableShare *share;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2982
520.1.22 by Brian Aker
Second pass of thd cleanup
2983
  if (!multi_alloc_root(session->mem_root,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2984
                        &table, sizeof(*table),
2985
                        &share, sizeof(*share),
2986
                        &field, (field_count + 1) * sizeof(Field*),
895 by Brian Aker
Completion (?) of uint conversion.
2987
                        &blob_field, (field_count+1) *sizeof(uint32_t),
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
2988
                        &bitmaps, bitmap_buffer_size(field_count)*2,
461 by Monty Taylor
Removed NullS. bu-bye.
2989
                        NULL))
1046.1.7 by Brian Aker
Style cleanup.
2990
    return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
2991
2992
  memset(table, 0, sizeof(*table));
2993
  memset(share, 0, sizeof(*share));
2994
  table->field= field;
2995
  table->s= share;
2996
  share->blob_field= blob_field;
2997
  share->fields= field_count;
2998
  share->blob_ptr_size= portable_sizeof_char_ptr;
1005.2.3 by Monty Taylor
Further reversion of P.
2999
  table->setup_tmp_table_column_bitmaps(bitmaps);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3000
3001
  /* Create all fields and calculate the total length of record */
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
3002
  List_iterator_fast<CreateField> it(field_list);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3003
  while ((cdef= it++))
3004
  {
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
3005
    *field= make_field(share,
3006
                       NULL,
3007
                       0,
3008
                       cdef->length,
3009
                       (cdef->flags & NOT_NULL_FLAG) ? false : true,
3010
                       (unsigned char *) ((cdef->flags & NOT_NULL_FLAG) ? 0 : ""),
3011
                       (cdef->flags & NOT_NULL_FLAG) ? 0 : 1,
1119.9.16 by Stewart Smith
don't store decimal/double scale in pack_flag, instead use the numeric option scale field in the table proto. This removes f_decimals() macro and the bits in the pack_flag for scale.
3012
                       cdef->decimals,
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
3013
                       cdef->sql_type,
3014
                       cdef->charset,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3015
                       cdef->unireg_check,
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
3016
                       cdef->interval,
3017
                       cdef->field_name);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3018
    if (!*field)
3019
      goto error;
3020
    (*field)->init(table);
3021
    record_length+= (*field)->pack_length();
3022
    if (! ((*field)->flags & NOT_NULL_FLAG))
3023
      null_count++;
3024
3025
    if ((*field)->flags & BLOB_FLAG)
895 by Brian Aker
Completion (?) of uint conversion.
3026
      share->blob_field[blob_count++]= (uint32_t) (field - table->field);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3027
3028
    field++;
3029
  }
3030
  *field= NULL;                             /* mark the end of the list */
3031
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
3032
  share->blob_fields= blob_count;
3033
3034
  null_pack_length= (null_count + 7)/8;
3035
  share->reclength= record_length + null_pack_length;
3036
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
520.1.22 by Brian Aker
Second pass of thd cleanup
3037
  table->record[0]= (unsigned char*) session->alloc(share->rec_buff_length);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3038
  if (!table->record[0])
3039
    goto error;
3040
3041
  if (null_pack_length)
3042
  {
481 by Brian Aker
Remove all of uchar.
3043
    table->null_flags= (unsigned char*) table->record[0];
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3044
    share->null_fields= null_count;
3045
    share->null_bytes= null_pack_length;
3046
  }
3047
520.1.22 by Brian Aker
Second pass of thd cleanup
3048
  table->in_use= session;           /* field->reset() may access table->in_use */
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3049
  {
3050
    /* Set up field pointers */
481 by Brian Aker
Remove all of uchar.
3051
    unsigned char *null_pos= table->record[0];
3052
    unsigned char *field_pos= null_pos + share->null_bytes;
482 by Brian Aker
Remove uint.
3053
    uint32_t null_bit= 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3054
3055
    for (field= table->field; *field; ++field)
3056
    {
3057
      Field *cur_field= *field;
3058
      if ((cur_field->flags & NOT_NULL_FLAG))
3059
        cur_field->move_field(field_pos);
3060
      else
3061
      {
481 by Brian Aker
Remove all of uchar.
3062
        cur_field->move_field(field_pos, (unsigned char*) null_pos, null_bit);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3063
        null_bit<<= 1;
3064
        if (null_bit == (1 << 8))
3065
        {
3066
          ++null_pos;
3067
          null_bit= 1;
3068
        }
3069
      }
3070
      cur_field->reset();
3071
3072
      field_pos+= cur_field->pack_length();
3073
    }
3074
  }
3075
  return table;
3076
error:
3077
  for (field= table->field; *field; ++field)
3078
    delete *field;                         /* just invokes field destructor */
3079
  return 0;
3080
}
3081
3082
bool Table::open_tmp_table()
3083
{
3084
  int error;
1208.3.2 by brian
Update for Cursor renaming.
3085
  if ((error=cursor->ha_open(this, s->table_name.str,O_RDWR,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3086
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
3087
  {
1208.3.2 by brian
Update for Cursor renaming.
3088
    cursor->print_error(error,MYF(0));
1046.1.6 by Brian Aker
Formatting/style cleanup.
3089
    db_stat= 0;
3090
    return true;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3091
  }
1208.3.2 by brian
Update for Cursor renaming.
3092
  (void) cursor->extra(HA_EXTRA_QUICK);		/* Faster */
1046.1.6 by Brian Aker
Formatting/style cleanup.
3093
  return false;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3094
}
3095
3096
3097
/*
3098
  Create MyISAM temporary table
3099
3100
  SYNOPSIS
3101
    create_myisam_tmp_table()
3102
      keyinfo         Description of the index (there is always one index)
3103
      start_recinfo   MyISAM's column descriptions
3104
      recinfo INOUT   End of MyISAM's column descriptions
3105
      options         Option bits
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3106
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3107
  DESCRIPTION
3108
    Create a MyISAM temporary table according to passed description. The is
3109
    assumed to have one unique index or constraint.
3110
3111
    The passed array or MI_COLUMNDEF structures must have this form:
3112
3113
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
3114
         when there are many nullable columns)
3115
      2. Table columns
3116
      3. One free MI_COLUMNDEF element (*recinfo points here)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3117
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3118
    This function may use the free element to create hash column for unique
3119
    constraint.
3120
3121
   RETURN
3122
     false - OK
3123
     true  - Error
3124
*/
3125
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3126
bool Table::create_myisam_tmp_table(KEY *keyinfo,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3127
                                    MI_COLUMNDEF *start_recinfo,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3128
                                    MI_COLUMNDEF **recinfo,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3129
				    uint64_t options)
3130
{
3131
  int error;
3132
  MI_KEYDEF keydef;
3133
  MI_UNIQUEDEF uniquedef;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
3134
  TableShare *share= s;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3135
3136
  if (share->keys)
3137
  {						// Get keys for ni_create
1046.1.6 by Brian Aker
Formatting/style cleanup.
3138
    bool using_unique_constraint= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3139
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&this->mem_root,
3140
                                            sizeof(*seg) * keyinfo->key_parts);
3141
    if (!seg)
3142
      goto err;
3143
3144
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
1208.3.2 by brian
Update for Cursor renaming.
3145
    if (keyinfo->key_length >= cursor->max_key_length() ||
3146
	keyinfo->key_parts > cursor->max_key_parts() ||
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3147
	share->uniques)
3148
    {
3149
      /* Can't create a key; Make a unique constraint instead of a key */
3150
      share->keys=    0;
3151
      share->uniques= 1;
3152
      using_unique_constraint=1;
3153
      memset(&uniquedef, 0, sizeof(uniquedef));
3154
      uniquedef.keysegs=keyinfo->key_parts;
3155
      uniquedef.seg=seg;
3156
      uniquedef.null_are_equal=1;
3157
3158
      /* Create extra column for hash value */
3159
      memset(*recinfo, 0, sizeof(**recinfo));
3160
      (*recinfo)->type= FIELD_CHECK;
3161
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
3162
      (*recinfo)++;
3163
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
3164
    }
3165
    else
3166
    {
3167
      /* Create an unique key */
3168
      memset(&keydef, 0, sizeof(keydef));
3169
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
3170
      keydef.keysegs=  keyinfo->key_parts;
3171
      keydef.seg= seg;
3172
    }
1046.1.6 by Brian Aker
Formatting/style cleanup.
3173
    for (uint32_t i= 0; i < keyinfo->key_parts ; i++,seg++)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3174
    {
779.3.10 by Monty Taylor
Turned on -Wshadow.
3175
      Field *key_field=keyinfo->key_part[i].field;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3176
      seg->flag=     0;
779.3.10 by Monty Taylor
Turned on -Wshadow.
3177
      seg->language= key_field->charset()->number;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3178
      seg->length=   keyinfo->key_part[i].length;
3179
      seg->start=    keyinfo->key_part[i].offset;
779.3.10 by Monty Taylor
Turned on -Wshadow.
3180
      if (key_field->flags & BLOB_FLAG)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3181
      {
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
3182
	seg->type= ((keyinfo->key_part[i].key_type & 1 /* binary */) ?
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3183
	 HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
779.3.10 by Monty Taylor
Turned on -Wshadow.
3184
	seg->bit_start= (uint8_t)(key_field->pack_length()
3185
                                  - share->blob_ptr_size);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3186
	seg->flag= HA_BLOB_PART;
1046.1.6 by Brian Aker
Formatting/style cleanup.
3187
	seg->length= 0;			// Whole blob in unique constraint
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3188
      }
3189
      else
3190
      {
3191
	seg->type= keyinfo->key_part[i].type;
3192
      }
779.3.10 by Monty Taylor
Turned on -Wshadow.
3193
      if (!(key_field->flags & NOT_NULL_FLAG))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3194
      {
779.3.10 by Monty Taylor
Turned on -Wshadow.
3195
	seg->null_bit= key_field->null_bit;
895 by Brian Aker
Completion (?) of uint conversion.
3196
	seg->null_pos= (uint32_t) (key_field->null_ptr - (unsigned char*) record[0]);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3197
	/*
3198
	  We are using a GROUP BY on something that contains NULL
3199
	  In this case we have to tell MyISAM that two NULL should
3200
	  on INSERT be regarded at the same value
3201
	*/
3202
	if (!using_unique_constraint)
3203
	  keydef.flag|= HA_NULL_ARE_EQUAL;
3204
      }
3205
    }
3206
  }
3207
  MI_CREATE_INFO create_info;
3208
  memset(&create_info, 0, sizeof(create_info));
3209
3210
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
3211
      OPTION_BIG_TABLES)
3212
    create_info.data_file_length= ~(uint64_t) 0;
3213
3214
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
895 by Brian Aker
Completion (?) of uint conversion.
3215
		       (uint32_t) (*recinfo-start_recinfo),
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3216
		       start_recinfo,
3217
		       share->uniques, &uniquedef,
3218
		       &create_info,
3219
		       HA_CREATE_TMP_TABLE)))
3220
  {
1208.3.2 by brian
Update for Cursor renaming.
3221
    cursor->print_error(error,MYF(0));
1046.1.6 by Brian Aker
Formatting/style cleanup.
3222
    db_stat= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3223
    goto err;
3224
  }
3225
  status_var_increment(in_use->status_var.created_tmp_disk_tables);
3226
  share->db_record_offset= 1;
3227
  return false;
3228
 err:
3229
  return true;
3230
}
3231
3232
520.1.22 by Brian Aker
Second pass of thd cleanup
3233
void Table::free_tmp_table(Session *session)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3234
{
3235
  MEM_ROOT own_root= mem_root;
3236
  const char *save_proc_info;
3237
520.1.22 by Brian Aker
Second pass of thd cleanup
3238
  save_proc_info=session->get_proc_info();
3239
  session->set_proc_info("removing tmp table");
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3240
873.2.11 by Monty Taylor
call ha_release_temporary_latches
3241
  // Release latches since this can take a long time
1152.1.4 by Brian Aker
Remove wrappers from SE
3242
  plugin::StorageEngine::releaseTemporaryLatches(session);
873.2.11 by Monty Taylor
call ha_release_temporary_latches
3243
1208.3.2 by brian
Update for Cursor renaming.
3244
  if (cursor)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3245
  {
3246
    if (db_stat)
1208.3.2 by brian
Update for Cursor renaming.
3247
      cursor->closeMarkForDelete(s->table_name.str);
1166.3.2 by Brian Aker
Remove ha_drop_table and modify it just to be a signal for the one case
3248
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
3249
    s->db_type()->doDropTable(*session, s->table_name.str);
1166.3.2 by Brian Aker
Remove ha_drop_table and modify it just to be a signal for the one case
3250
1208.3.2 by brian
Update for Cursor renaming.
3251
    delete cursor;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3252
  }
3253
3254
  /* free blobs */
3255
  for (Field **ptr= field ; *ptr ; ptr++)
3256
    (*ptr)->free();
1109.1.4 by Brian Aker
More Table refactor
3257
  free_io_cache();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3258
3259
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
520.1.22 by Brian Aker
Second pass of thd cleanup
3260
  session->set_proc_info(save_proc_info);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3261
}
3262
3263
/**
3264
  If a HEAP table gets full, create a MyISAM table and copy all rows
3265
  to this.
3266
*/
3267
520.1.22 by Brian Aker
Second pass of thd cleanup
3268
bool create_myisam_from_heap(Session *session, Table *table,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3269
                             MI_COLUMNDEF *start_recinfo,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3270
                             MI_COLUMNDEF **recinfo,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3271
			     int error, bool ignore_last_dupp_key_error)
3272
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3273
  Table new_table;
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
3274
  TableShare share;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3275
  const char *save_proc_info;
3276
  int write_err;
3277
960.2.25 by Monty Taylor
First step of hton rename.
3278
  if (table->s->db_type() != heap_engine ||
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3279
      error != HA_ERR_RECORD_FILE_FULL)
3280
  {
1208.3.2 by brian
Update for Cursor renaming.
3281
    table->cursor->print_error(error,MYF(0));
1046.1.6 by Brian Aker
Formatting/style cleanup.
3282
    return true;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3283
  }
873.2.11 by Monty Taylor
call ha_release_temporary_latches
3284
3285
  // Release latches since this can take a long time
1152.1.4 by Brian Aker
Remove wrappers from SE
3286
  plugin::StorageEngine::releaseTemporaryLatches(session);
873.2.11 by Monty Taylor
call ha_release_temporary_latches
3287
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3288
  new_table= *table;
3289
  share= *table->s;
3290
  new_table.s= &share;
971.1.21 by Monty Taylor
Store StorageEngine in system variables, rather than storage engine plugin.
3291
  new_table.s->storage_engine= myisam_engine;
1208.3.2 by brian
Update for Cursor renaming.
3292
  if (!(new_table.cursor= new_table.s->db_type()->getCursor(share, &new_table.mem_root)))
1046.1.6 by Brian Aker
Formatting/style cleanup.
3293
    return true;				// End of memory
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3294
520.1.22 by Brian Aker
Second pass of thd cleanup
3295
  save_proc_info=session->get_proc_info();
3296
  session->set_proc_info("converting HEAP to MyISAM");
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3297
3298
  if (new_table.create_myisam_tmp_table(table->key_info, start_recinfo,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3299
					recinfo, session->lex->select_lex.options |
520.1.22 by Brian Aker
Second pass of thd cleanup
3300
					session->options))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3301
    goto err2;
3302
  if (new_table.open_tmp_table())
3303
    goto err1;
1208.3.2 by brian
Update for Cursor renaming.
3304
  if (table->cursor->indexes_are_disabled())
3305
    new_table.cursor->ha_disable_indexes(HA_KEY_SWITCH_ALL);
3306
  table->cursor->ha_index_or_rnd_end();
3307
  table->cursor->ha_rnd_init(1);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3308
  if (table->no_rows)
3309
  {
1208.3.2 by brian
Update for Cursor renaming.
3310
    new_table.cursor->extra(HA_EXTRA_NO_ROWS);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3311
    new_table.no_rows=1;
3312
  }
3313
3314
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
1208.3.2 by brian
Update for Cursor renaming.
3315
  new_table.cursor->extra(HA_EXTRA_WRITE_CACHE);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3316
3317
  /*
3318
    copy all old rows from heap table to MyISAM table
3319
    This is the only code that uses record[1] to read/write but this
3320
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
3321
  */
1208.3.2 by brian
Update for Cursor renaming.
3322
  while (!table->cursor->rnd_next(new_table.record[1]))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3323
  {
1208.3.2 by brian
Update for Cursor renaming.
3324
    write_err= new_table.cursor->ha_write_row(new_table.record[1]);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3325
    if (write_err)
3326
      goto err;
3327
  }
3328
  /* copy row that filled HEAP table */
1208.3.2 by brian
Update for Cursor renaming.
3329
  if ((write_err=new_table.cursor->ha_write_row(table->record[0])))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3330
  {
1208.3.2 by brian
Update for Cursor renaming.
3331
    if (new_table.cursor->is_fatal_error(write_err, HA_CHECK_DUP) ||
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3332
	!ignore_last_dupp_key_error)
3333
      goto err;
3334
  }
3335
3336
  /* remove heap table and change to use myisam table */
1208.3.2 by brian
Update for Cursor renaming.
3337
  (void) table->cursor->ha_rnd_end();
3338
  (void) table->cursor->close();                  // This deletes the table !
3339
  delete table->cursor;
3340
  table->cursor= NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3341
  new_table.s= table->s;                       // Keep old share
3342
  *table= new_table;
3343
  *table->s= share;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3344
1208.3.2 by brian
Update for Cursor renaming.
3345
  table->cursor->change_table_ptr(table, table->s);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3346
  table->use_all_columns();
3347
  if (save_proc_info)
3348
  {
3349
    const char *new_proc_info=
3350
      (!strcmp(save_proc_info,"Copying to tmp table") ?
3351
      "Copying to tmp table on disk" : save_proc_info);
520.1.22 by Brian Aker
Second pass of thd cleanup
3352
    session->set_proc_info(new_proc_info);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3353
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
3354
  return false;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3355
3356
 err:
1208.3.2 by brian
Update for Cursor renaming.
3357
  table->cursor->print_error(write_err, MYF(0));
3358
  (void) table->cursor->ha_rnd_end();
3359
  (void) new_table.cursor->close();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3360
 err1:
1183.1.29 by Brian Aker
Clean up interface so that Truncate sets the propper engine when
3361
  new_table.s->db_type()->doDropTable(*session, new_table.s->table_name.str);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3362
 err2:
1208.3.2 by brian
Update for Cursor renaming.
3363
  delete new_table.cursor;
520.1.22 by Brian Aker
Second pass of thd cleanup
3364
  session->set_proc_info(save_proc_info);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3365
  table->mem_root= new_table.mem_root;
1046.1.6 by Brian Aker
Formatting/style cleanup.
3366
  return true;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
3367
}
3368
1103.6.2 by Padraig O'Sullivan
Removing references to MY_BITMAP throughout the code base and updating calls
3369
my_bitmap_map *Table::use_all_columns(MyBitmap *bitmap)
354 by Brian Aker
Refactor of Table methods.
3370
{
1103.6.2 by Padraig O'Sullivan
Removing references to MY_BITMAP throughout the code base and updating calls
3371
  my_bitmap_map *old= bitmap->getBitmap();
1103.6.4 by Padraig O'Sullivan
Correct all remaining references to the old bitmap interface in the code
3372
  bitmap->setBitmap(s->all_set.getBitmap());
354 by Brian Aker
Refactor of Table methods.
3373
  return old;
3374
}
3375
1005.2.3 by Monty Taylor
Further reversion of P.
3376
void Table::restore_column_map(my_bitmap_map *old)
354 by Brian Aker
Refactor of Table methods.
3377
{
1103.6.4 by Padraig O'Sullivan
Correct all remaining references to the old bitmap interface in the code
3378
  read_set->setBitmap(old);
354 by Brian Aker
Refactor of Table methods.
3379
}
3380
482 by Brian Aker
Remove uint.
3381
uint32_t Table::find_shortest_key(const key_map *usable_keys)
355 by Brian Aker
More Table cleanup
3382
{
365.2.6 by Monty Taylor
Undid some stupid int->int16_t conversions.
3383
  uint32_t min_length= UINT32_MAX;
3384
  uint32_t best= MAX_KEY;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3385
  if (usable_keys->any())
355 by Brian Aker
More Table cleanup
3386
  {
1046.1.6 by Brian Aker
Formatting/style cleanup.
3387
    for (uint32_t nr= 0; nr < s->keys ; nr++)
355 by Brian Aker
More Table cleanup
3388
    {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3389
      if (usable_keys->test(nr))
355 by Brian Aker
More Table cleanup
3390
      {
3391
        if (key_info[nr].key_length < min_length)
3392
        {
3393
          min_length= key_info[nr].key_length;
3394
          best=nr;
3395
        }
3396
      }
3397
    }
3398
  }
3399
  return best;
3400
}
3401
3402
/*****************************************************************************
3403
  Remove duplicates from tmp table
3404
  This should be recoded to add a unique index to the table and remove
3405
  duplicates
3406
  Table is a locked single thread table
3407
  fields is the number of fields to check (from the end)
3408
*****************************************************************************/
3409
3410
bool Table::compare_record(Field **ptr)
3411
{
3412
  for (; *ptr ; ptr++)
3413
  {
3414
    if ((*ptr)->cmp_offset(s->rec_buff_length))
3415
      return true;
3416
  }
3417
  return false;
3418
}
3419
3420
/* Return false if row hasn't changed */
3421
3422
bool Table::compare_record()
3423
{
3424
  if (s->blob_fields + s->varchar_fields == 0)
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3425
    return memcmp(this->record[0], this->record[1], (size_t) s->reclength);
355 by Brian Aker
More Table cleanup
3426
  /* Compare null bits */
3427
  if (memcmp(null_flags,
3428
	     null_flags + s->rec_buff_length,
3429
	     s->null_bytes))
3430
    return true;				// Diff in NULL value
3431
  /* Compare updated fields */
3432
  for (Field **ptr= field ; *ptr ; ptr++)
3433
  {
1005.2.12 by Monty Taylor
Moved some things to the API.
3434
    if (isWriteSet((*ptr)->field_index) &&
355 by Brian Aker
More Table cleanup
3435
	(*ptr)->cmp_binary_offset(s->rec_buff_length))
3436
      return true;
3437
  }
3438
  return false;
3439
}
3440
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3441
/*
3442
 * Store a record from previous record into next
3443
 *
3444
 */
3445
void Table::storeRecord()
3446
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
3447
  memcpy(record[1], record[0], (size_t) s->reclength);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3448
}
3449
3450
/*
3451
 * Store a record as an insert
3452
 *
3453
 */
3454
void Table::storeRecordAsInsert()
3455
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
3456
  memcpy(insert_values, record[0], (size_t) s->reclength);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3457
}
3458
3459
/*
3460
 * Store a record with default values
3461
 *
3462
 */
3463
void Table::storeRecordAsDefault()
3464
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
3465
  memcpy(s->default_values, record[0], (size_t) s->reclength);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3466
}
3467
3468
/*
3469
 * Restore a record from previous record into next
3470
 *
3471
 */
3472
void Table::restoreRecord()
3473
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
3474
  memcpy(record[0], record[1], (size_t) s->reclength);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3475
}
3476
3477
/*
3478
 * Restore a record with default values
3479
 *
3480
 */
3481
void Table::restoreRecordAsDefault()
3482
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
3483
  memcpy(record[0], s->default_values, (size_t) s->reclength);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3484
}
3485
3486
/*
3487
 * Empty a record
3488
 *
3489
 */
3490
void Table::emptyRecord()
3491
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
3492
  restoreRecordAsDefault();
3493
  memset(null_flags, 255, s->null_bytes);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3494
}
354 by Brian Aker
Refactor of Table methods.
3495
3496
/*****************************************************************************
3497
  The different ways to read a record
3498
  Returns -1 if row was not found, 0 if row was found and 1 on errors
3499
*****************************************************************************/
3500
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
3501
/** Help function when we get some an error from the table Cursor. */
354 by Brian Aker
Refactor of Table methods.
3502
3503
int Table::report_error(int error)
3504
{
3505
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
3506
  {
3507
    status= STATUS_GARBAGE;
3508
    return -1;					// key not found; ok
3509
  }
3510
  /*
3511
    Locking reads can legally return also these errors, do not
3512
    print them to the .err log
3513
  */
3514
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
755.2.1 by Mark Atwood
replace sql_print_error etc with errmsg_print
3515
    errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
354 by Brian Aker
Refactor of Table methods.
3516
		    error, s->path.str);
1208.3.2 by brian
Update for Cursor renaming.
3517
  cursor->print_error(error,MYF(0));
354 by Brian Aker
Refactor of Table methods.
3518
3519
  return 1;
3520
}
3521
1 by brian
clean slate
3522
934.1.1 by Brian Aker
Moved two functions in classes.
3523
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
3524
{
934.1.1 by Brian Aker
Moved two functions in classes.
3525
  used_fields= 0;
3526
  const_table= 0;
3527
  null_row= 0;
3528
  status= STATUS_NO_RECORD;
3529
  maybe_null= table_list->outer_join;
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
3530
  TableList *embedding= table_list->embedding;
934.1.1 by Brian Aker
Moved two functions in classes.
3531
  while (!maybe_null && embedding)
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
3532
  {
934.1.1 by Brian Aker
Moved two functions in classes.
3533
    maybe_null= embedding->outer_join;
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
3534
    embedding= embedding->embedding;
3535
  }
934.1.1 by Brian Aker
Moved two functions in classes.
3536
  tablenr= table_number;
3537
  map= (table_map) 1 << table_number;
3538
  force_index= table_list->force_index;
3539
  covering_keys= s->keys_for_keyread;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3540
  merge_keys.reset();
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
3541
}
3542
1054.1.7 by Brian Aker
Refactor TableList methods.
3543
Field *Table::find_field_in_table_sef(const char *name)
3544
{
3545
  Field **field_ptr;
3546
  if (s->name_hash.records)
3547
  {
3548
    field_ptr= (Field**)hash_search(&s->name_hash,(unsigned char*) name,
3549
                                    strlen(name));
3550
    if (field_ptr)
3551
    {
3552
      /*
3553
        field_ptr points to field in TableShare. Convert it to the matching
3554
        field in table
3555
      */
3556
      field_ptr= (field + (field_ptr - s->field));
3557
    }
3558
  }
3559
  else
3560
  {
3561
    if (!(field_ptr= field))
3562
      return (Field *)0;
3563
    for (; *field_ptr; ++field_ptr)
3564
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name, name))
3565
        break;
3566
  }
3567
  if (field_ptr)
3568
    return *field_ptr;
3569
  else
3570
    return (Field *)0;
3571
}
3572
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
3573
3574
/*
3575
  Used by ALTER Table when the table is a temporary one. It changes something
3576
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
3577
  name).
3578
  Prepares a table cache key, which is the concatenation of db, table_name and
3579
  session->slave_proxy_id, separated by '\0'.
3580
*/
3581
3582
bool Table::rename_temporary_table(const char *db, const char *table_name)
3583
{
3584
  char *key;
3585
  uint32_t key_length;
3586
  TableShare *share= s;
3587
3588
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
971.6.11 by Eric Day
Removed purecov messages.
3589
    return true;
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
3590
3591
  key_length= TableShare::createKey(key, db, table_name);
3592
  share->set_table_cache_key(key, key_length);
3593
3594
  return false;
3595
}
3596
1 by brian
clean slate
3597
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
3598
template class List<String>;
3599
template class List_iterator<String>;
3600
#endif