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