~drizzle-trunk/drizzle/development

1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 *
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
4
 *  Copyright (C) 2010 Brian Aker
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
5
 *  Copyright (C) 2009 Sun Microsystems
6
 *
7
 *  This program is free software; you can redistribute it and/or modify
8
 *  it under the terms of the GNU General Public License as published by
9
 *  the Free Software Foundation; either version 2 of the License, or
10
 *  (at your option) any later version.
11
 *
12
 *  This program is distributed in the hope that it will be useful,
13
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 *  GNU General Public License for more details.
16
 *
17
 *  You should have received a copy of the GNU General Public License
18
 *  along with this program; if not, write to the Free Software
19
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
 */
21
22
/*
23
  This class is shared between different table objects. There is one
24
  instance of table share per one table in the database.
25
*/
26
27
/* Basic functions needed by many modules */
1241.9.36 by Monty Taylor
ZOMG. I deleted drizzled/server_includes.h.
28
#include "config.h"
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
29
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
30
#include <pthread.h>
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
31
#include <float.h>
32
33
#include <sys/types.h>
34
#include <sys/stat.h>
35
#include <fcntl.h>
36
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
37
38
#include <cassert>
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
39
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
40
#include "drizzled/error.h"
41
#include "drizzled/gettext.h"
42
#include "drizzled/sql_base.h"
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
43
#include "drizzled/pthread_globals.h"
1241.9.64 by Monty Taylor
Moved remaining non-public portions of mysys and mystrings to drizzled/internal.
44
#include "drizzled/internal/my_pthread.h"
1502.5.7 by Barry.Leslie at PrimeBase
Renamed the 'Event' plugin to 'EventObserver' plugin along with some internal class renames to make things clearer.
45
#include "drizzled/plugin/event_observer.h"
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
46
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
47
#include "drizzled/table.h"
48
#include "drizzled/table/shell.h"
49
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
50
#include "drizzled/session.h"
51
52
#include "drizzled/charset.h"
53
#include "drizzled/internal/m_string.h"
54
#include "drizzled/internal/my_sys.h"
55
56
#include "drizzled/item/string.h"
57
#include "drizzled/item/int.h"
58
#include "drizzled/item/decimal.h"
59
#include "drizzled/item/float.h"
60
#include "drizzled/item/null.h"
61
#include "drizzled/temporal.h"
62
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
63
#include "drizzled/field.h"
64
#include "drizzled/field/str.h"
65
#include "drizzled/field/num.h"
66
#include "drizzled/field/blob.h"
67
#include "drizzled/field/enum.h"
68
#include "drizzled/field/null.h"
69
#include "drizzled/field/date.h"
70
#include "drizzled/field/decimal.h"
71
#include "drizzled/field/real.h"
72
#include "drizzled/field/double.h"
73
#include "drizzled/field/long.h"
74
#include "drizzled/field/int64_t.h"
75
#include "drizzled/field/num.h"
76
#include "drizzled/field/timestamp.h"
77
#include "drizzled/field/datetime.h"
78
#include "drizzled/field/varstring.h"
79
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
80
using namespace std;
81
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
82
namespace drizzled
83
{
84
1241.9.33 by Monty Taylor
Moved most of the global vars to set_var where they belong.
85
extern size_t table_def_size;
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
86
87
/*****************************************************************************
88
  Functions to handle table definition cach (TableShare)
89
 *****************************************************************************/
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
90
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
91
/*
92
  Mark that we are not using table share anymore.
93
94
  SYNOPSIS
95
  release()
96
  share		Table share
97
98
  IMPLEMENTATION
99
  If ref_count goes to zero and (we have done a refresh or if we have
100
  already too many open table shares) then delete the definition.
101
*/
102
103
void TableShare::release(TableShare *share)
104
{
105
  bool to_be_deleted= false;
1689.2.7 by Brian Aker
LOCK_open to boost.
106
  safe_mutex_assert_owner(LOCK_open.native_handle);
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
107
1685.2.2 by Brian Aker
Remove wait condition.
108
  share->lock();
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
109
  if (!--share->ref_count)
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
110
  {
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
111
    to_be_deleted= true;
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
112
  }
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
113
114
  if (to_be_deleted)
115
  {
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
116
    TableIdentifier identifier(share->getSchemaName(), share->getTableName());
1502.5.8 by Barry.Leslie at PrimeBase
- Changed names to match the drizzle naming convention.
117
    plugin::EventObserver::deregisterTableEvents(*share);
1502.5.2 by Barry.Leslie at PrimeBase
Changes made to drizzle source when building in the events plugin.
118
   
1877.2.12 by Brian Aker
Additional encapsulation of definition cache
119
    definition::Cache::singleton().erase(identifier);
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
120
    return;
121
  }
1685.2.2 by Brian Aker
Remove wait condition.
122
  share->unlock();
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
123
}
124
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
125
void TableShare::release(TableSharePtr &share)
126
{
127
  bool to_be_deleted= false;
128
  safe_mutex_assert_owner(LOCK_open.native_handle);
129
130
  share->lock();
131
  if (!--share->ref_count)
132
  {
133
    to_be_deleted= true;
134
  }
135
136
  if (to_be_deleted)
137
  {
138
    TableIdentifier identifier(share->getSchemaName(), share->getTableName());
139
    plugin::EventObserver::deregisterTableEvents(*share);
140
   
1877.2.12 by Brian Aker
Additional encapsulation of definition cache
141
    definition::Cache::singleton().erase(identifier);
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
142
    return;
143
  }
144
  share->unlock();
145
}
146
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
147
void TableShare::release(TableIdentifier &identifier)
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
148
{
1877.2.12 by Brian Aker
Additional encapsulation of definition cache
149
  TableSharePtr share= definition::Cache::singleton().find(identifier);
150
  if (share)
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
151
  {
152
    share->version= 0;                          // Mark for delete
153
    if (share->ref_count == 0)
154
    {
1685.2.2 by Brian Aker
Remove wait condition.
155
      share->lock();
1502.5.8 by Barry.Leslie at PrimeBase
- Changed names to match the drizzle naming convention.
156
      plugin::EventObserver::deregisterTableEvents(*share);
1877.2.12 by Brian Aker
Additional encapsulation of definition cache
157
      definition::Cache::singleton().erase(identifier);
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
158
    }
159
  }
160
}
161
162
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
163
static TableSharePtr foundTableShare(TableSharePtr share)
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
164
{
165
  /*
166
    We found an existing table definition. Return it if we didn't get
167
    an error when reading the table definition from file.
168
  */
169
170
  /* We must do a lock to ensure that the structure is initialized */
171
  if (share->error)
172
  {
173
    /* Table definition contained an error */
174
    share->open_table_error(share->error, share->open_errno, share->errarg);
175
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
176
    return TableSharePtr();
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
177
  }
178
1578.2.4 by Brian Aker
More encapsulation of table Share, this time table count.
179
  share->incrementTableCount();
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
180
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
181
  return share;
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
182
}
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
183
184
/*
185
  Get TableShare for a table.
186
187
  get_table_share()
188
  session			Thread handle
189
  table_list		Table that should be opened
190
  key			Table cache key
191
  key_length		Length of key
192
  error			out: Error code from open_table_def()
193
194
  IMPLEMENTATION
195
  Get a table definition from the table definition cache.
196
  If it doesn't exist, create a new from the table definition file.
197
198
  NOTES
199
  We must have wrlock on LOCK_open when we come here
200
  (To be changed later)
201
202
  RETURN
203
  0  Error
204
#  Share for table
205
*/
206
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
207
TableSharePtr TableShare::getShareCreate(Session *session, 
208
                                         TableIdentifier &identifier,
209
                                         int *error)
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
210
{
1835.1.1 by Brian Aker
Convert the internal of our definition cache to be shared_ptr.
211
  TableSharePtr share;
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
212
213
  *error= 0;
214
215
  /* Read table definition from cache */
1877.2.12 by Brian Aker
Additional encapsulation of definition cache
216
  if ((share= definition::Cache::singleton().find(identifier)))
1223.3.1 by Monty Taylor
Replace HASH in table_share with drizzled::hash_map
217
    return foundTableShare(share);
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
218
1835.1.1 by Brian Aker
Convert the internal of our definition cache to be shared_ptr.
219
  share.reset(new TableShare(message::Table::STANDARD, identifier));
220
  
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
221
  /*
222
    Lock mutex to be able to read table definition from file without
223
    conflicts
224
  */
1685.2.2 by Brian Aker
Remove wait condition.
225
  share->lock();
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
226
1877.2.11 by Brian Aker
Merge in changes for encapsulation out to cache.
227
  bool ret= definition::Cache::singleton().insert(identifier, share);
228
229
  if (not ret)
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
230
    return TableSharePtr();
1530.1.3 by Brian Aker
Style cleanup for table_share
231
1502.1.24 by Brian Aker
Absorb TableShare proto to share methods.
232
  if (share->open_table_def(*session, identifier))
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
233
  {
234
    *error= share->error;
1877.2.11 by Brian Aker
Merge in changes for encapsulation out to cache.
235
    definition::Cache::singleton().erase(identifier);
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
236
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
237
    return TableSharePtr();
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
238
  }
239
  share->ref_count++;				// Mark in use
1502.5.2 by Barry.Leslie at PrimeBase
Changes made to drizzle source when building in the events plugin.
240
  
1502.5.8 by Barry.Leslie at PrimeBase
- Changed names to match the drizzle naming convention.
241
  plugin::EventObserver::registerTableEvents(*share);
1502.5.2 by Barry.Leslie at PrimeBase
Changes made to drizzle source when building in the events plugin.
242
  
1685.2.2 by Brian Aker
Remove wait condition.
243
  share->unlock();
1371 by Brian Aker
Small corrections.
244
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
245
  return share;
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
246
}
247
248
249
/*
250
  Check if table definition exits in cache
251
252
  SYNOPSIS
253
  get_cached_table_share()
254
  db			Database name
255
  table_name		Table name
256
257
  RETURN
258
  0  Not cached
259
#  TableShare for table
260
*/
1835.1.2 by Brian Aker
Further push down the logic for shared_ptr.
261
TableSharePtr TableShare::getShare(TableIdentifier &identifier)
1358.1.9 by Brian Aker
Update for std::string
262
{
1689.2.7 by Brian Aker
LOCK_open to boost.
263
  safe_mutex_assert_owner(LOCK_open.native_handle);
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
264
1877.2.12 by Brian Aker
Additional encapsulation of definition cache
265
  return definition::Cache::singleton().find(identifier);
1093.6.1 by Brian Aker
Refactor TableShare has to be behind class.
266
}
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
267
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
268
static enum_field_types proto_field_type_to_drizzle_type(uint32_t proto_field_type)
269
{
270
  enum_field_types field_type;
271
272
  switch(proto_field_type)
273
  {
274
  case message::Table::Field::INTEGER:
275
    field_type= DRIZZLE_TYPE_LONG;
276
    break;
277
  case message::Table::Field::DOUBLE:
278
    field_type= DRIZZLE_TYPE_DOUBLE;
279
    break;
280
  case message::Table::Field::TIMESTAMP:
281
    field_type= DRIZZLE_TYPE_TIMESTAMP;
282
    break;
283
  case message::Table::Field::BIGINT:
284
    field_type= DRIZZLE_TYPE_LONGLONG;
285
    break;
286
  case message::Table::Field::DATETIME:
287
    field_type= DRIZZLE_TYPE_DATETIME;
288
    break;
289
  case message::Table::Field::DATE:
290
    field_type= DRIZZLE_TYPE_DATE;
291
    break;
292
  case message::Table::Field::VARCHAR:
293
    field_type= DRIZZLE_TYPE_VARCHAR;
294
    break;
295
  case message::Table::Field::DECIMAL:
296
    field_type= DRIZZLE_TYPE_DECIMAL;
297
    break;
298
  case message::Table::Field::ENUM:
299
    field_type= DRIZZLE_TYPE_ENUM;
300
    break;
301
  case message::Table::Field::BLOB:
302
    field_type= DRIZZLE_TYPE_BLOB;
303
    break;
304
  default:
305
    field_type= DRIZZLE_TYPE_LONG; /* Set value to kill GCC warning */
306
    assert(1);
307
  }
308
309
  return field_type;
310
}
311
312
static Item *default_value_item(enum_field_types field_type,
313
                                const CHARSET_INFO *charset,
314
                                bool default_null, const string *default_value,
315
                                const string *default_bin_value)
316
{
317
  Item *default_item= NULL;
318
  int error= 0;
319
320
  if (default_null)
321
  {
322
    return new Item_null();
323
  }
324
325
  switch(field_type)
326
  {
327
  case DRIZZLE_TYPE_LONG:
328
  case DRIZZLE_TYPE_LONGLONG:
329
    default_item= new Item_int(default_value->c_str(),
330
                               (int64_t) internal::my_strtoll10(default_value->c_str(),
331
                                                                NULL,
332
                                                                &error),
333
                               default_value->length());
334
    break;
335
  case DRIZZLE_TYPE_DOUBLE:
336
    default_item= new Item_float(default_value->c_str(),
337
                                 default_value->length());
338
    break;
339
  case DRIZZLE_TYPE_NULL:
340
    assert(false);
341
  case DRIZZLE_TYPE_TIMESTAMP:
342
  case DRIZZLE_TYPE_DATETIME:
343
  case DRIZZLE_TYPE_DATE:
344
  case DRIZZLE_TYPE_ENUM:
345
    default_item= new Item_string(default_value->c_str(),
346
                                  default_value->length(),
347
                                  system_charset_info);
348
    break;
349
  case DRIZZLE_TYPE_VARCHAR:
350
  case DRIZZLE_TYPE_BLOB: /* Blob is here due to TINYTEXT. Feel the hate. */
351
    if (charset==&my_charset_bin)
352
    {
353
      default_item= new Item_string(default_bin_value->c_str(),
354
                                    default_bin_value->length(),
355
                                    &my_charset_bin);
356
    }
357
    else
358
    {
359
      default_item= new Item_string(default_value->c_str(),
360
                                    default_value->length(),
361
                                    system_charset_info);
362
    }
363
    break;
364
  case DRIZZLE_TYPE_DECIMAL:
365
    default_item= new Item_decimal(default_value->c_str(),
366
                                   default_value->length(),
367
                                   system_charset_info);
368
    break;
369
  }
370
371
  return default_item;
372
}
373
374
375
1308.2.2 by Jay Pipes
Fixes transaction log/replication for multi-column primary keys. Changes CREATE SCHEMA to not use statement-base RAW_SQL and instead use a derived message::Statement subclass.
376
/**
377
 * @todo
378
 *
379
 * Precache this stuff....
380
 */
381
bool TableShare::fieldInPrimaryKey(Field *in_field) const
382
{
383
  assert(table_proto != NULL);
1530.1.3 by Brian Aker
Style cleanup for table_share
384
1308.2.2 by Jay Pipes
Fixes transaction log/replication for multi-column primary keys. Changes CREATE SCHEMA to not use statement-base RAW_SQL and instead use a derived message::Statement subclass.
385
  size_t num_indexes= table_proto->indexes_size();
386
387
  for (size_t x= 0; x < num_indexes; ++x)
388
  {
389
    const message::Table::Index &index= table_proto->indexes(x);
390
    if (index.is_primary())
391
    {
392
      size_t num_parts= index.index_part_size();
393
      for (size_t y= 0; y < num_parts; ++y)
394
      {
395
        if (index.index_part(y).fieldnr() == in_field->field_index)
396
          return true;
397
      }
398
    }
399
  }
400
  return false;
401
}
402
1608.2.4 by Brian Aker
Update for having share declared type.
403
TableShare::TableShare(TableIdentifier::Type type_arg) :
1608.2.2 by Brian Aker
Move constructors to .cc file.
404
  table_category(TABLE_UNKNOWN_CATEGORY),
405
  found_next_number_field(NULL),
406
  timestamp_field(NULL),
407
  key_info(NULL),
1672.3.3 by Brian Aker
Fix init of mem_root in Share.
408
  mem_root(TABLE_ALLOC_BLOCK_SIZE),
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
409
  all_set(),
1608.2.2 by Brian Aker
Move constructors to .cc file.
410
  block_size(0),
411
  version(0),
412
  timestamp_offset(0),
413
  reclength(0),
414
  stored_rec_length(0),
415
  max_rows(0),
416
  table_proto(NULL),
417
  storage_engine(NULL),
1608.2.4 by Brian Aker
Update for having share declared type.
418
  tmp_table(type_arg),
1608.2.2 by Brian Aker
Move constructors to .cc file.
419
  ref_count(0),
420
  null_bytes(0),
421
  last_null_bit_pos(0),
422
  fields(0),
423
  rec_buff_length(0),
424
  keys(0),
425
  key_parts(0),
426
  max_key_length(0),
427
  max_unique_length(0),
428
  total_key_length(0),
429
  uniques(0),
430
  null_fields(0),
431
  blob_fields(0),
432
  timestamp_field_offset(0),
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
433
  has_variable_width(false),
1608.2.2 by Brian Aker
Move constructors to .cc file.
434
  db_create_options(0),
435
  db_options_in_use(0),
436
  db_record_offset(0),
437
  rowid_field_offset(0),
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
438
  primary_key(MAX_KEY),
1608.2.2 by Brian Aker
Move constructors to .cc file.
439
  next_number_index(0),
440
  next_number_key_offset(0),
441
  next_number_keypart(0),
442
  error(0),
443
  open_errno(0),
444
  errarg(0),
445
  blob_ptr_size(0),
446
  db_low_byte_first(false),
447
  name_lock(false),
448
  replace_with_name_lock(false),
449
  waiting_on_cond(false),
450
  keys_in_use(0),
451
  keys_for_keyread(0),
1669.2.5 by Brian Aker
Since table is now fixed, we no longer need "newed"
452
  event_observers(NULL)
1608.2.2 by Brian Aker
Move constructors to .cc file.
453
{
454
455
  table_charset= 0;
456
  memset(&db, 0, sizeof(LEX_STRING));
457
  memset(&table_name, 0, sizeof(LEX_STRING));
458
  memset(&path, 0, sizeof(LEX_STRING));
459
  memset(&normalized_path, 0, sizeof(LEX_STRING));
460
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
461
  if (type_arg == message::Table::INTERNAL)
462
  {
1878.5.3 by Brian Aker
Update Key to work a bit faster.
463
    TableIdentifier::build_tmptable_filename(private_key_for_cache.vectorPtr());
464
    init(private_key_for_cache.vector(), private_key_for_cache.vector());
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
465
  }
466
  else
467
  {
468
    init("", "");
469
  }
1608.2.2 by Brian Aker
Move constructors to .cc file.
470
}
471
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
472
TableShare::TableShare(TableIdentifier &identifier, const TableIdentifier::Key &key) :// Used by placeholder
1608.2.2 by Brian Aker
Move constructors to .cc file.
473
  table_category(TABLE_UNKNOWN_CATEGORY),
474
  found_next_number_field(NULL),
475
  timestamp_field(NULL),
476
  key_info(NULL),
1672.3.3 by Brian Aker
Fix init of mem_root in Share.
477
  mem_root(TABLE_ALLOC_BLOCK_SIZE),
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
478
  all_set(),
1608.2.2 by Brian Aker
Move constructors to .cc file.
479
  block_size(0),
480
  version(0),
481
  timestamp_offset(0),
482
  reclength(0),
483
  stored_rec_length(0),
484
  max_rows(0),
485
  table_proto(NULL),
486
  storage_engine(NULL),
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
487
  tmp_table(message::Table::INTERNAL),
1608.2.2 by Brian Aker
Move constructors to .cc file.
488
  ref_count(0),
489
  null_bytes(0),
490
  last_null_bit_pos(0),
491
  fields(0),
492
  rec_buff_length(0),
493
  keys(0),
494
  key_parts(0),
495
  max_key_length(0),
496
  max_unique_length(0),
497
  total_key_length(0),
498
  uniques(0),
499
  null_fields(0),
500
  blob_fields(0),
501
  timestamp_field_offset(0),
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
502
  has_variable_width(false),
1608.2.2 by Brian Aker
Move constructors to .cc file.
503
  db_create_options(0),
504
  db_options_in_use(0),
505
  db_record_offset(0),
506
  rowid_field_offset(0),
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
507
  primary_key(MAX_KEY),
1608.2.2 by Brian Aker
Move constructors to .cc file.
508
  next_number_index(0),
509
  next_number_key_offset(0),
510
  next_number_keypart(0),
511
  error(0),
512
  open_errno(0),
513
  errarg(0),
514
  blob_ptr_size(0),
515
  db_low_byte_first(false),
516
  name_lock(false),
517
  replace_with_name_lock(false),
518
  waiting_on_cond(false),
519
  keys_in_use(0),
520
  keys_for_keyread(0),
1669.2.5 by Brian Aker
Since table is now fixed, we no longer need "newed"
521
  event_observers(NULL)
1608.2.2 by Brian Aker
Move constructors to .cc file.
522
{
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
523
  assert(identifier.getKey() == key);
524
1608.2.2 by Brian Aker
Move constructors to .cc file.
525
  table_charset= 0;
526
  memset(&path, 0, sizeof(LEX_STRING));
527
  memset(&normalized_path, 0, sizeof(LEX_STRING));
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
528
529
  private_key_for_cache= key;
530
531
  table_category=         TABLE_CATEGORY_TEMPORARY;
532
  tmp_table=              message::Table::INTERNAL;
533
1878.5.3 by Brian Aker
Update Key to work a bit faster.
534
  db.str= const_cast<char *>(private_key_for_cache.vector());
535
  db.length= strlen(private_key_for_cache.vector());
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
536
1878.5.3 by Brian Aker
Update Key to work a bit faster.
537
  table_name.str= const_cast<char *>(private_key_for_cache.vector()) + strlen(private_key_for_cache.vector()) + 1;
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
538
  table_name.length= strlen(table_name.str);
539
  path.str= (char *)"";
540
  normalized_path.str= path.str;
541
  path.length= normalized_path.length= 0;
542
  assert(strcmp(identifier.getTableName().c_str(), table_name.str) == 0);
543
  assert(strcmp(identifier.getSchemaName().c_str(), db.str) == 0);
1608.2.4 by Brian Aker
Update for having share declared type.
544
}
545
546
1618.1.1 by Brian Aker
Modify TableIdentifier to be const
547
TableShare::TableShare(const TableIdentifier &identifier) : // Just used during createTable()
1608.2.4 by Brian Aker
Update for having share declared type.
548
  table_category(TABLE_UNKNOWN_CATEGORY),
549
  found_next_number_field(NULL),
550
  timestamp_field(NULL),
551
  key_info(NULL),
1672.3.3 by Brian Aker
Fix init of mem_root in Share.
552
  mem_root(TABLE_ALLOC_BLOCK_SIZE),
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
553
  all_set(),
1608.2.4 by Brian Aker
Update for having share declared type.
554
  block_size(0),
555
  version(0),
556
  timestamp_offset(0),
557
  reclength(0),
558
  stored_rec_length(0),
559
  max_rows(0),
560
  table_proto(NULL),
561
  storage_engine(NULL),
562
  tmp_table(identifier.getType()),
563
  ref_count(0),
564
  null_bytes(0),
565
  last_null_bit_pos(0),
566
  fields(0),
567
  rec_buff_length(0),
568
  keys(0),
569
  key_parts(0),
570
  max_key_length(0),
571
  max_unique_length(0),
572
  total_key_length(0),
573
  uniques(0),
574
  null_fields(0),
575
  blob_fields(0),
576
  timestamp_field_offset(0),
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
577
  has_variable_width(false),
1608.2.4 by Brian Aker
Update for having share declared type.
578
  db_create_options(0),
579
  db_options_in_use(0),
580
  db_record_offset(0),
581
  rowid_field_offset(0),
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
582
  primary_key(MAX_KEY),
1608.2.4 by Brian Aker
Update for having share declared type.
583
  next_number_index(0),
584
  next_number_key_offset(0),
585
  next_number_keypart(0),
586
  error(0),
587
  open_errno(0),
588
  errarg(0),
589
  blob_ptr_size(0),
590
  db_low_byte_first(false),
591
  name_lock(false),
592
  replace_with_name_lock(false),
593
  waiting_on_cond(false),
594
  keys_in_use(0),
595
  keys_for_keyread(0),
1669.2.5 by Brian Aker
Since table is now fixed, we no longer need "newed"
596
  event_observers(NULL)
1608.2.4 by Brian Aker
Update for having share declared type.
597
{
598
  table_charset= 0;
599
  memset(&db, 0, sizeof(LEX_STRING));
600
  memset(&table_name, 0, sizeof(LEX_STRING));
601
  memset(&path, 0, sizeof(LEX_STRING));
602
  memset(&normalized_path, 0, sizeof(LEX_STRING));
603
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
604
  private_key_for_cache= identifier.getKey();
605
  assert(identifier.getPath().size()); // Since we are doing a create table, this should be a positive value
606
  private_normalized_path.resize(identifier.getPath().size() + 1);
607
  memcpy(&private_normalized_path[0], identifier.getPath().c_str(), identifier.getPath().size());
608
1608.2.4 by Brian Aker
Update for having share declared type.
609
  {
610
    table_category=         TABLE_CATEGORY_TEMPORARY;
611
    tmp_table=              message::Table::INTERNAL;
1878.5.3 by Brian Aker
Update Key to work a bit faster.
612
    db.str= const_cast<char *>(private_key_for_cache.vector());
613
    db.length= strlen(private_key_for_cache.vector());
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
614
    table_name.str= db.str + 1;
615
    table_name.length= strlen(table_name.str);
616
    path.str= &private_normalized_path[0];
617
    normalized_path.str= path.str;
618
    path.length= normalized_path.length= private_normalized_path.size();
1608.2.4 by Brian Aker
Update for having share declared type.
619
  }
620
}
621
622
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
623
/*
624
  Used for shares that will go into the cache.
625
*/
1608.2.4 by Brian Aker
Update for having share declared type.
626
TableShare::TableShare(TableIdentifier::Type type_arg,
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
627
                       TableIdentifier &identifier,
1608.2.2 by Brian Aker
Move constructors to .cc file.
628
                       char *path_arg,
629
                       uint32_t path_length_arg) :
1502.1.22 by Brian Aker
Additional remove of memset on TableShare().
630
  table_category(TABLE_UNKNOWN_CATEGORY),
631
  found_next_number_field(NULL),
632
  timestamp_field(NULL),
633
  key_info(NULL),
1672.3.3 by Brian Aker
Fix init of mem_root in Share.
634
  mem_root(TABLE_ALLOC_BLOCK_SIZE),
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
635
  all_set(),
1502.1.22 by Brian Aker
Additional remove of memset on TableShare().
636
  block_size(0),
637
  version(0),
638
  timestamp_offset(0),
639
  reclength(0),
640
  stored_rec_length(0),
641
  max_rows(0),
642
  table_proto(NULL),
643
  storage_engine(NULL),
1608.2.4 by Brian Aker
Update for having share declared type.
644
  tmp_table(type_arg),
1502.1.22 by Brian Aker
Additional remove of memset on TableShare().
645
  ref_count(0),
646
  null_bytes(0),
647
  last_null_bit_pos(0),
648
  fields(0),
649
  rec_buff_length(0),
650
  keys(0),
651
  key_parts(0),
652
  max_key_length(0),
653
  max_unique_length(0),
654
  total_key_length(0),
655
  uniques(0),
656
  null_fields(0),
657
  blob_fields(0),
658
  timestamp_field_offset(0),
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
659
  has_variable_width(false),
1502.1.22 by Brian Aker
Additional remove of memset on TableShare().
660
  db_create_options(0),
661
  db_options_in_use(0),
662
  db_record_offset(0),
663
  rowid_field_offset(0),
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
664
  primary_key(MAX_KEY),
1502.1.22 by Brian Aker
Additional remove of memset on TableShare().
665
  next_number_index(0),
666
  next_number_key_offset(0),
667
  next_number_keypart(0),
668
  error(0),
669
  open_errno(0),
670
  errarg(0),
671
  blob_ptr_size(0),
672
  db_low_byte_first(false),
673
  name_lock(false),
674
  replace_with_name_lock(false),
675
  waiting_on_cond(false),
676
  keys_in_use(0),
677
  keys_for_keyread(0),
1669.2.5 by Brian Aker
Since table is now fixed, we no longer need "newed"
678
  event_observers(NULL)
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
679
{
1502.1.22 by Brian Aker
Additional remove of memset on TableShare().
680
  table_charset= 0;
681
  memset(&db, 0, sizeof(LEX_STRING));
682
  memset(&table_name, 0, sizeof(LEX_STRING));
683
  memset(&path, 0, sizeof(LEX_STRING));
684
  memset(&normalized_path, 0, sizeof(LEX_STRING));
1502.1.14 by Brian Aker
Remove memcpy() from TableShare and just have it deal with its own mem_root.
685
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
686
  char *path_buff;
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
687
  std::string _path;
688
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
689
  private_key_for_cache= identifier.getKey();
690
  /*
691
    Let us use the fact that the key is "db/0/table_name/0" + optional
692
    part for temporary tables.
693
  */
1878.5.3 by Brian Aker
Update Key to work a bit faster.
694
  db.str= const_cast<char *>(private_key_for_cache.vector());
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
695
  db.length=         strlen(db.str);
696
  table_name.str=    db.str + db.length + 1;
1502.1.15 by Brian Aker
Small opt to not need TableList
697
  table_name.length= strlen(table_name.str);
698
1502.1.12 by Brian Aker
Second pass through TableShare to new(). Partial hack in using bool for the
699
  if (path_arg)
700
  {
701
    _path.append(path_arg, path_length_arg);
702
  }
703
  else
704
  {
1601 by Brian Aker
Move functions to class methods.
705
    TableIdentifier::build_table_filename(_path, db.str, table_name.str, false);
1502.1.12 by Brian Aker
Second pass through TableShare to new(). Partial hack in using bool for the
706
  }
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
707
1755.2.3 by Brian Aker
Change alloc call.
708
  if ((path_buff= (char *)mem_root.alloc_root(_path.length() + 1)))
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
709
  {
710
    setPath(path_buff, _path.length());
711
    strcpy(path_buff, _path.c_str());
712
    setNormalizedPath(path_buff, _path.length());
713
1532.1.12 by Brian Aker
Remove one of the set key table cache methods.
714
    version= refresh_version;
1502.1.11 by Brian Aker
This fixes TableShare such that for the cache we now correctly call new()
715
  }
716
  else
717
  {
718
    assert(0); // We should throw here.
719
  }
720
}
721
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
722
void TableShare::init(const char *new_table_name,
1608.2.2 by Brian Aker
Move constructors to .cc file.
723
                      const char *new_path)
724
{
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
725
1608.2.2 by Brian Aker
Move constructors to .cc file.
726
  table_category=         TABLE_CATEGORY_TEMPORARY;
727
  tmp_table=              message::Table::INTERNAL;
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
728
  db.str= (char *)"";
729
  db.length= 0;
1608.2.2 by Brian Aker
Move constructors to .cc file.
730
  table_name.str=         (char*) new_table_name;
731
  table_name.length=      strlen(new_table_name);
732
  path.str=               (char*) new_path;
733
  normalized_path.str=    (char*) new_path;
734
  path.length= normalized_path.length= strlen(new_path);
735
}
736
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
737
TableShare::~TableShare() 
738
{
739
  assert(ref_count == 0);
740
741
  /*
742
    If someone is waiting for this to be deleted, inform it about this.
743
    Don't do a delete until we know that no one is refering to this anymore.
744
  */
745
  if (tmp_table == message::Table::STANDARD)
746
  {
747
    /* share->mutex is locked in release_table_share() */
748
    while (waiting_on_cond)
749
    {
1755.2.5 by Brian Aker
Move over to use boost for the locks in table_share.
750
      cond.notify_all();
1798.3.11 by Brian Aker
Caught another scoped handle
751
      boost::mutex::scoped_lock scoped(mutex, boost::adopt_lock_t());
752
      cond.wait(scoped);
753
      scoped.release();
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
754
    }
755
    /* No thread refers to this anymore */
1755.2.5 by Brian Aker
Move over to use boost for the locks in table_share.
756
    mutex.unlock();
1619.1.1 by Brian Aker
Update for TableShare usage of key (remove a case where we had to build it).
757
  }
758
759
  storage_engine= NULL;
760
761
  delete table_proto;
762
  table_proto= NULL;
763
764
  mem_root.free_root(MYF(0));                 // Free's share
765
}
766
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
767
void TableShare::setIdentifier(TableIdentifier &identifier_arg)
768
{
769
  private_key_for_cache= identifier_arg.getKey();
770
771
  /*
772
    Let us use the fact that the key is "db/0/table_name/0" + optional
773
    part for temporary tables.
774
  */
1878.5.3 by Brian Aker
Update Key to work a bit faster.
775
  db.str= const_cast<char *>(private_key_for_cache.vector());
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
776
  db.length=         strlen(db.str);
777
  table_name.str=    db.str + db.length + 1;
778
  table_name.length= strlen(table_name.str);
779
780
  table_proto->set_name(identifier_arg.getTableName());
781
  table_proto->set_schema(identifier_arg.getSchemaName());
782
}
783
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
784
int TableShare::inner_parse_table_proto(Session& session, message::Table &table)
785
{
786
  int local_error= 0;
787
788
  if (! table.IsInitialized())
789
  {
790
    my_error(ER_CORRUPT_TABLE_DEFINITION, MYF(0), table.InitializationErrorString().c_str());
791
    return ER_CORRUPT_TABLE_DEFINITION;
792
  }
793
1574.1.2 by Brian Aker
Remove =this reference.
794
  setTableProto(new(nothrow) message::Table(table));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
795
1574.1.2 by Brian Aker
Remove =this reference.
796
  storage_engine= plugin::StorageEngine::findByName(session, table.engine().name());
797
  assert(storage_engine); // We use an assert() here because we should never get this far and still have no suitable engine.
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
798
799
  message::Table::TableOptions table_options;
800
801
  if (table.has_options())
802
    table_options= table.options();
803
804
  uint32_t local_db_create_options= 0;
805
806
  if (table_options.pack_record())
807
    local_db_create_options|= HA_OPTION_PACK_RECORD;
808
809
  /* local_db_create_options was stored as 2 bytes in FRM
1530.1.3 by Brian Aker
Style cleanup for table_share
810
    Any HA_OPTION_ that doesn't fit into 2 bytes was silently truncated away.
811
  */
1574.1.2 by Brian Aker
Remove =this reference.
812
  db_create_options= (local_db_create_options & 0x0000FFFF);
813
  db_options_in_use= db_create_options;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
814
1574.1.2 by Brian Aker
Remove =this reference.
815
  block_size= table_options.has_block_size() ?
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
816
    table_options.block_size() : 0;
817
1638.1.5 by Stewart Smith
explicit collation in table proto (from review)
818
  table_charset= get_charset(table_options.collation_id());
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
819
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
820
  if (! table_charset)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
821
  {
1638.1.2 by Stewart Smith
fix error message for parsing invalid table collation to fit other forms of corruption by returning to the user session an appropriate error message.
822
    char errmsg[100];
823
    snprintf(errmsg, sizeof(errmsg),
824
             _("Table %s has invalid/unknown collation: %d,%s"),
825
             getPath(),
826
             table_options.collation_id(),
827
             table_options.collation().c_str());
828
    errmsg[99]='\0';
829
830
    my_error(ER_CORRUPT_TABLE_DEFINITION, MYF(0), errmsg);
1638.1.1 by Stewart Smith
have table wide default collation/collation_id in table proto as well as move to only storing it when it's not the default (utf8_general_ci). This means that the replication stream now doesn't produce COLLATE= in the transformation of create table back to SQL.
831
    return ER_CORRUPT_TABLE_DEFINITION;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
832
  }
833
1574.1.2 by Brian Aker
Remove =this reference.
834
  db_record_offset= 1;
835
836
  blob_ptr_size= portable_sizeof_char_ptr; // more bonghits.
837
838
  keys= table.indexes_size();
839
840
  key_parts= 0;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
841
  for (int indx= 0; indx < table.indexes_size(); indx++)
1574.1.2 by Brian Aker
Remove =this reference.
842
    key_parts+= table.indexes(indx).index_part_size();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
843
1574.1.2 by Brian Aker
Remove =this reference.
844
  key_info= (KeyInfo*) alloc_root( table.indexes_size() * sizeof(KeyInfo) +key_parts*sizeof(KeyPartInfo));
1534 by Brian Aker
Remove of KeyPartInfo
845
846
  KeyPartInfo *key_part;
847
848
  key_part= reinterpret_cast<KeyPartInfo*>
1574.1.2 by Brian Aker
Remove =this reference.
849
    (key_info+table.indexes_size());
850
851
852
  ulong *rec_per_key= (ulong*) alloc_root(sizeof(ulong*)*key_parts);
853
854
  KeyInfo* keyinfo= key_info;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
855
  for (int keynr= 0; keynr < table.indexes_size(); keynr++, keyinfo++)
856
  {
857
    message::Table::Index indx= table.indexes(keynr);
858
859
    keyinfo->table= 0;
860
    keyinfo->flags= 0;
861
862
    if (indx.is_unique())
863
      keyinfo->flags|= HA_NOSAME;
864
865
    if (indx.has_options())
866
    {
1537 by Brian Aker
Remove dead options/rename Option and remove the update that we no longer
867
      message::Table::Index::Options indx_options= indx.options();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
868
      if (indx_options.pack_key())
869
        keyinfo->flags|= HA_PACK_KEY;
870
871
      if (indx_options.var_length_key())
872
        keyinfo->flags|= HA_VAR_LENGTH_PART;
873
874
      if (indx_options.null_part_key())
875
        keyinfo->flags|= HA_NULL_PART_KEY;
876
877
      if (indx_options.binary_pack_key())
878
        keyinfo->flags|= HA_BINARY_PACK_KEY;
879
880
      if (indx_options.has_partial_segments())
881
        keyinfo->flags|= HA_KEY_HAS_PART_KEY_SEG;
882
883
      if (indx_options.auto_generated_key())
884
        keyinfo->flags|= HA_GENERATED_KEY;
885
886
      if (indx_options.has_key_block_size())
887
      {
888
        keyinfo->flags|= HA_USES_BLOCK_SIZE;
889
        keyinfo->block_size= indx_options.key_block_size();
890
      }
891
      else
892
      {
893
        keyinfo->block_size= 0;
894
      }
895
    }
896
897
    switch (indx.type())
898
    {
899
    case message::Table::Index::UNKNOWN_INDEX:
900
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
901
      break;
902
    case message::Table::Index::BTREE:
903
      keyinfo->algorithm= HA_KEY_ALG_BTREE;
904
      break;
905
    case message::Table::Index::HASH:
906
      keyinfo->algorithm= HA_KEY_ALG_HASH;
907
      break;
908
909
    default:
910
      /* TODO: suitable warning ? */
911
      keyinfo->algorithm= HA_KEY_ALG_UNDEF;
912
      break;
913
    }
914
915
    keyinfo->key_length= indx.key_length();
916
917
    keyinfo->key_parts= indx.index_part_size();
918
919
    keyinfo->key_part= key_part;
920
    keyinfo->rec_per_key= rec_per_key;
921
922
    for (unsigned int partnr= 0;
923
         partnr < keyinfo->key_parts;
924
         partnr++, key_part++)
925
    {
926
      message::Table::Index::IndexPart part;
927
      part= indx.index_part(partnr);
928
929
      *rec_per_key++= 0;
930
931
      key_part->field= NULL;
932
      key_part->fieldnr= part.fieldnr() + 1; // start from 1.
933
      key_part->null_bit= 0;
934
      /* key_part->null_offset is only set if null_bit (see later) */
935
      /* key_part->key_type= */ /* I *THINK* this may be okay.... */
936
      /* key_part->type ???? */
937
      key_part->key_part_flag= 0;
938
      if (part.has_in_reverse_order())
939
        key_part->key_part_flag= part.in_reverse_order()? HA_REVERSE_SORT : 0;
940
941
      key_part->length= part.compare_length();
942
1638.8.1 by Stewart Smith
make the compare_length() of index parts of VARCHAR and BLOB (i.e. those with charsets) be a length in characters instead of bytes. This makes the logic converting a table proto back into a CREATE TABLE statement remotely sane. This does mean that if we increase the number of bytes utf8_general_ci uses, engines may have issues with their on disk formats (if they're not too smart)
943
      int mbmaxlen= 1;
944
945
      if (table.field(part.fieldnr()).type() == message::Table::Field::VARCHAR
946
          || table.field(part.fieldnr()).type() == message::Table::Field::BLOB)
947
      {
948
        uint32_t collation_id;
949
950
        if (table.field(part.fieldnr()).string_options().has_collation_id())
951
          collation_id= table.field(part.fieldnr()).string_options().collation_id();
952
        else
953
          collation_id= table.options().collation_id();
954
955
        const CHARSET_INFO *cs= get_charset(collation_id);
956
957
        mbmaxlen= cs->mbmaxlen;
958
      }
959
      key_part->length*= mbmaxlen;
960
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
961
      key_part->store_length= key_part->length;
962
963
      /* key_part->offset is set later */
1577 by Brian Aker
Next bit of pack removal (this removes it from where we store it).
964
      key_part->key_type= 0;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
965
    }
966
967
    if (! indx.has_comment())
968
    {
969
      keyinfo->comment.length= 0;
970
      keyinfo->comment.str= NULL;
971
    }
972
    else
973
    {
974
      keyinfo->flags|= HA_USES_COMMENT;
975
      keyinfo->comment.length= indx.comment().length();
1574.1.2 by Brian Aker
Remove =this reference.
976
      keyinfo->comment.str= strmake_root(indx.comment().c_str(), keyinfo->comment.length);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
977
    }
978
1574.1.2 by Brian Aker
Remove =this reference.
979
    keyinfo->name= strmake_root(indx.name().c_str(), indx.name().length());
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
980
1527.1.3 by Brian Aker
This is:
981
    addKeyName(string(keyinfo->name, indx.name().length()));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
982
  }
983
1574.1.2 by Brian Aker
Remove =this reference.
984
  keys_for_keyread.reset();
985
  set_prefix(keys_in_use, keys);
986
987
  fields= table.field_size();
988
1578.2.11 by Brian Aker
Use the Fields generated from share for Table.
989
  setFields(fields + 1);
1574.1.2 by Brian Aker
Remove =this reference.
990
  field[fields]= NULL;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
991
992
  uint32_t local_null_fields= 0;
1574.1.2 by Brian Aker
Remove =this reference.
993
  reclength= 0;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
994
995
  vector<uint32_t> field_offsets;
996
  vector<uint32_t> field_pack_length;
997
1574.1.2 by Brian Aker
Remove =this reference.
998
  field_offsets.resize(fields);
999
  field_pack_length.resize(fields);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1000
1001
  uint32_t interval_count= 0;
1002
  uint32_t interval_parts= 0;
1003
1004
  uint32_t stored_columns_reclength= 0;
1005
1574.1.2 by Brian Aker
Remove =this reference.
1006
  for (unsigned int fieldnr= 0; fieldnr < fields; fieldnr++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1007
  {
1008
    message::Table::Field pfield= table.field(fieldnr);
1009
    if (pfield.constraints().is_nullable())
1010
      local_null_fields++;
1011
1012
    enum_field_types drizzle_field_type=
1013
      proto_field_type_to_drizzle_type(pfield.type());
1014
1015
    field_offsets[fieldnr]= stored_columns_reclength;
1016
1017
    /* the below switch is very similar to
1530.1.3 by Brian Aker
Style cleanup for table_share
1018
      CreateField::create_length_to_internal_length in field.cc
1019
      (which should one day be replace by just this code)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1020
    */
1021
    switch(drizzle_field_type)
1022
    {
1023
    case DRIZZLE_TYPE_BLOB:
1024
    case DRIZZLE_TYPE_VARCHAR:
1025
      {
1026
        message::Table::Field::StringFieldOptions field_options= pfield.string_options();
1027
1028
        const CHARSET_INFO *cs= get_charset(field_options.has_collation_id() ?
1029
                                            field_options.collation_id() : 0);
1030
1031
        if (! cs)
1032
          cs= default_charset_info;
1033
1034
        field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type,
1035
                                                     field_options.length() * cs->mbmaxlen);
1036
      }
1037
      break;
1038
    case DRIZZLE_TYPE_ENUM:
1039
      {
1040
        message::Table::Field::EnumerationValues field_options= pfield.enumeration_values();
1041
1782.4.4 by Brian Aker
Fix enum at being an intefer (which is what PG did, and it saves on
1042
        field_pack_length[fieldnr]= 4;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1043
1044
        interval_count++;
1045
        interval_parts+= field_options.field_value_size();
1046
      }
1047
      break;
1048
    case DRIZZLE_TYPE_DECIMAL:
1049
      {
1050
        message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
1051
1052
        field_pack_length[fieldnr]= my_decimal_get_binary_size(fo.precision(), fo.scale());
1053
      }
1054
      break;
1055
    default:
1056
      /* Zero is okay here as length is fixed for other types. */
1057
      field_pack_length[fieldnr]= calc_pack_length(drizzle_field_type, 0);
1058
    }
1059
1574.1.2 by Brian Aker
Remove =this reference.
1060
    reclength+= field_pack_length[fieldnr];
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1061
    stored_columns_reclength+= field_pack_length[fieldnr];
1062
  }
1063
1064
  /* data_offset added to stored_rec_length later */
1574.1.2 by Brian Aker
Remove =this reference.
1065
  stored_rec_length= stored_columns_reclength;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1066
1574.1.2 by Brian Aker
Remove =this reference.
1067
  null_fields= local_null_fields;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1068
1069
  ulong null_bits= local_null_fields;
1070
  if (! table_options.pack_record())
1071
    null_bits++;
1072
  ulong data_offset= (null_bits + 7)/8;
1073
1074
1574.1.2 by Brian Aker
Remove =this reference.
1075
  reclength+= data_offset;
1076
  stored_rec_length+= data_offset;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1077
1078
  ulong local_rec_buff_length;
1079
1574.1.2 by Brian Aker
Remove =this reference.
1080
  local_rec_buff_length= ALIGN_SIZE(reclength + 1);
1081
  rec_buff_length= local_rec_buff_length;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1082
1574.1.2 by Brian Aker
Remove =this reference.
1083
  resizeDefaultValues(local_rec_buff_length);
1084
  unsigned char* record= getDefaultValues();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1085
  int null_count= 0;
1086
1087
  if (! table_options.pack_record())
1088
  {
1089
    null_count++; // one bit for delete mark.
1090
    *record|= 1;
1091
  }
1092
1093
1574.1.7 by Brian Aker
Remove interval allocation via memroot.
1094
  intervals.resize(interval_count);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1095
1096
  /* Now fix the TYPELIBs for the intervals (enum values)
1530.1.3 by Brian Aker
Style cleanup for table_share
1097
    and field names.
1098
  */
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1099
1100
  uint32_t interval_nr= 0;
1101
1574.1.2 by Brian Aker
Remove =this reference.
1102
  for (unsigned int fieldnr= 0; fieldnr < fields; fieldnr++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1103
  {
1104
    message::Table::Field pfield= table.field(fieldnr);
1105
1106
    /* enum typelibs */
1107
    if (pfield.type() != message::Table::Field::ENUM)
1108
      continue;
1109
1110
    message::Table::Field::EnumerationValues field_options= pfield.enumeration_values();
1111
1579.3.14 by Stewart Smith
have a constant for the maximum number of enum elements
1112
    if (field_options.field_value_size() > Field_enum::max_supported_elements)
1579.3.11 by Stewart Smith
Fix parsing the table proto message so that an error is returned (ER_CORRUPT_TABLE_DEFINITION) if there are too many elements for an ENUM column.
1113
    {
1114
      char errmsg[100];
1115
      snprintf(errmsg, sizeof(errmsg),
1116
               _("ENUM column %s has greater than %d possible values"),
1579.3.14 by Stewart Smith
have a constant for the maximum number of enum elements
1117
               pfield.name().c_str(),
1118
               Field_enum::max_supported_elements);
1579.3.11 by Stewart Smith
Fix parsing the table proto message so that an error is returned (ER_CORRUPT_TABLE_DEFINITION) if there are too many elements for an ENUM column.
1119
      errmsg[99]='\0';
1120
1121
      my_error(ER_CORRUPT_TABLE_DEFINITION, MYF(0), errmsg);
1122
      return ER_CORRUPT_TABLE_DEFINITION;
1123
    }
1124
1125
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1126
    const CHARSET_INFO *charset= get_charset(field_options.has_collation_id() ?
1127
                                             field_options.collation_id() : 0);
1128
1129
    if (! charset)
1130
      charset= default_charset_info;
1131
1574.1.7 by Brian Aker
Remove interval allocation via memroot.
1132
    TYPELIB *t= (&intervals[interval_nr]);
1574.1.2 by Brian Aker
Remove =this reference.
1133
1134
    t->type_names= (const char**)alloc_root((field_options.field_value_size() + 1) * sizeof(char*));
1135
1136
    t->type_lengths= (unsigned int*) alloc_root((field_options.field_value_size() + 1) * sizeof(unsigned int));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1137
1138
    t->type_names[field_options.field_value_size()]= NULL;
1139
    t->type_lengths[field_options.field_value_size()]= 0;
1140
1141
    t->count= field_options.field_value_size();
1142
    t->name= NULL;
1143
1144
    for (int n= 0; n < field_options.field_value_size(); n++)
1145
    {
1574.1.2 by Brian Aker
Remove =this reference.
1146
      t->type_names[n]= strmake_root(field_options.field_value(n).c_str(), field_options.field_value(n).length());
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1147
1148
      /* 
1149
       * Go ask the charset what the length is as for "" length=1
1150
       * and there's stripping spaces or some other crack going on.
1530.1.3 by Brian Aker
Style cleanup for table_share
1151
     */
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1152
      uint32_t lengthsp;
1153
      lengthsp= charset->cset->lengthsp(charset,
1154
                                        t->type_names[n],
1155
                                        field_options.field_value(n).length());
1156
      t->type_lengths[n]= lengthsp;
1157
    }
1158
    interval_nr++;
1159
  }
1160
1161
1162
  /* and read the fields */
1163
  interval_nr= 0;
1164
1574.1.2 by Brian Aker
Remove =this reference.
1165
  bool use_hash= fields >= MAX_FIELDS_BEFORE_HASH;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1166
1574.1.2 by Brian Aker
Remove =this reference.
1167
  unsigned char* null_pos= getDefaultValues();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1168
  int null_bit_pos= (table_options.pack_record()) ? 0 : 1;
1169
1574.1.2 by Brian Aker
Remove =this reference.
1170
  for (unsigned int fieldnr= 0; fieldnr < fields; fieldnr++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1171
  {
1172
    message::Table::Field pfield= table.field(fieldnr);
1173
1174
    Field::utype unireg_type= Field::NONE;
1175
1176
    if (pfield.has_numeric_options() &&
1177
        pfield.numeric_options().is_autoincrement())
1178
    {
1179
      unireg_type= Field::NEXT_NUMBER;
1180
    }
1181
1182
    if (pfield.has_options() &&
1638.3.2 by Stewart Smith
use default_expression and update_expression instead of default_value and update_value in the table proto for NOW()
1183
        pfield.options().has_default_expression() &&
1638.3.3 by Stewart Smith
store CURRENT_TIMESTAMP instead of NOW() in the table proto as this is what we end up displaying in SHOW CREATE so more accurately represents what's going on. Although it could go either way (it totally does not matter), this paves the way for SHOW CREATE TABLE running through statement_transform.
1184
        pfield.options().default_expression().compare("CURRENT_TIMESTAMP") == 0)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1185
    {
1638.3.2 by Stewart Smith
use default_expression and update_expression instead of default_value and update_value in the table proto for NOW()
1186
      if (pfield.options().has_update_expression() &&
1638.3.3 by Stewart Smith
store CURRENT_TIMESTAMP instead of NOW() in the table proto as this is what we end up displaying in SHOW CREATE so more accurately represents what's going on. Although it could go either way (it totally does not matter), this paves the way for SHOW CREATE TABLE running through statement_transform.
1187
          pfield.options().update_expression().compare("CURRENT_TIMESTAMP") == 0)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1188
      {
1189
        unireg_type= Field::TIMESTAMP_DNUN_FIELD;
1190
      }
1638.3.2 by Stewart Smith
use default_expression and update_expression instead of default_value and update_value in the table proto for NOW()
1191
      else if (! pfield.options().has_update_expression())
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1192
      {
1530.1.3 by Brian Aker
Style cleanup for table_share
1193
        unireg_type= Field::TIMESTAMP_DN_FIELD;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1194
      }
1195
      else
1530.1.3 by Brian Aker
Style cleanup for table_share
1196
        assert(1); // Invalid update value.
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1197
    }
1198
    else if (pfield.has_options() &&
1638.3.2 by Stewart Smith
use default_expression and update_expression instead of default_value and update_value in the table proto for NOW()
1199
             pfield.options().has_update_expression() &&
1638.3.3 by Stewart Smith
store CURRENT_TIMESTAMP instead of NOW() in the table proto as this is what we end up displaying in SHOW CREATE so more accurately represents what's going on. Although it could go either way (it totally does not matter), this paves the way for SHOW CREATE TABLE running through statement_transform.
1200
             pfield.options().update_expression().compare("CURRENT_TIMESTAMP") == 0)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1201
    {
1202
      unireg_type= Field::TIMESTAMP_UN_FIELD;
1203
    }
1204
1205
    LEX_STRING comment;
1206
    if (!pfield.has_comment())
1207
    {
1208
      comment.str= (char*)"";
1209
      comment.length= 0;
1210
    }
1211
    else
1212
    {
1213
      size_t len= pfield.comment().length();
1214
      const char* str= pfield.comment().c_str();
1215
1574.1.2 by Brian Aker
Remove =this reference.
1216
      comment.str= strmake_root(str, len);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1217
      comment.length= len;
1218
    }
1219
1220
    enum_field_types field_type;
1221
1222
    field_type= proto_field_type_to_drizzle_type(pfield.type());
1223
1224
    const CHARSET_INFO *charset= &my_charset_bin;
1225
1226
    if (field_type == DRIZZLE_TYPE_BLOB ||
1227
        field_type == DRIZZLE_TYPE_VARCHAR)
1228
    {
1229
      message::Table::Field::StringFieldOptions field_options= pfield.string_options();
1230
1231
      charset= get_charset(field_options.has_collation_id() ?
1232
                           field_options.collation_id() : 0);
1233
1234
      if (! charset)
1530.1.3 by Brian Aker
Style cleanup for table_share
1235
        charset= default_charset_info;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1236
    }
1237
1238
    if (field_type == DRIZZLE_TYPE_ENUM)
1239
    {
1240
      message::Table::Field::EnumerationValues field_options= pfield.enumeration_values();
1241
1242
      charset= get_charset(field_options.has_collation_id()?
1530.1.3 by Brian Aker
Style cleanup for table_share
1243
                           field_options.collation_id() : 0);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1244
1245
      if (! charset)
1530.1.3 by Brian Aker
Style cleanup for table_share
1246
        charset= default_charset_info;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1247
    }
1248
1249
    uint8_t decimals= 0;
1250
    if (field_type == DRIZZLE_TYPE_DECIMAL
1251
        || field_type == DRIZZLE_TYPE_DOUBLE)
1252
    {
1253
      message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
1254
1255
      if (! pfield.has_numeric_options() || ! fo.has_scale())
1256
      {
1257
        /*
1258
          We don't write the default to table proto so
1259
          if no decimals specified for DOUBLE, we use the default.
1260
        */
1261
        decimals= NOT_FIXED_DEC;
1262
      }
1263
      else
1264
      {
1265
        if (fo.scale() > DECIMAL_MAX_SCALE)
1266
        {
1267
          local_error= 4;
1268
1530.1.3 by Brian Aker
Style cleanup for table_share
1269
          return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1270
        }
1271
        decimals= static_cast<uint8_t>(fo.scale());
1272
      }
1273
    }
1274
1275
    Item *default_value= NULL;
1276
1277
    if (pfield.options().has_default_value() ||
1638.7.1 by Stewart Smith
in the table proto, having default_null set to false explicitly (instead of just having it as a default) had a different behaviour than if it was not set and defaulting to NULL. This meant that you'd get empty defaults instead of no default. This only showed up in table_function tables.
1278
        pfield.options().default_null()  ||
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1279
        pfield.options().has_default_bin_value())
1280
    {
1281
      default_value= default_value_item(field_type,
1282
                                        charset,
1283
                                        pfield.options().default_null(),
1284
                                        &pfield.options().default_value(),
1285
                                        &pfield.options().default_bin_value());
1286
    }
1287
1288
1843.6.1 by Brian Aker
Remove random use of table (we just needed the blob to be set correctly to
1289
    db_low_byte_first= true; //Cursor->low_byte_first();
1290
    blob_ptr_size= portable_sizeof_char_ptr;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1291
1292
    uint32_t field_length= 0; //Assignment is for compiler complaint.
1293
1294
    switch (field_type)
1295
    {
1296
    case DRIZZLE_TYPE_BLOB:
1297
    case DRIZZLE_TYPE_VARCHAR:
1530.1.3 by Brian Aker
Style cleanup for table_share
1298
      {
1299
        message::Table::Field::StringFieldOptions field_options= pfield.string_options();
1300
1301
        charset= get_charset(field_options.has_collation_id() ?
1302
                             field_options.collation_id() : 0);
1303
1304
        if (! charset)
1305
          charset= default_charset_info;
1306
1307
        field_length= field_options.length() * charset->mbmaxlen;
1308
      }
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1309
      break;
1310
    case DRIZZLE_TYPE_DOUBLE:
1530.1.3 by Brian Aker
Style cleanup for table_share
1311
      {
1312
        message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
1313
        if (!fo.has_precision() && !fo.has_scale())
1314
        {
1315
          field_length= DBL_DIG+7;
1316
        }
1317
        else
1318
        {
1319
          field_length= fo.precision();
1320
        }
1321
        if (field_length < decimals &&
1322
            decimals != NOT_FIXED_DEC)
1323
        {
1324
          my_error(ER_M_BIGGER_THAN_D, MYF(0), pfield.name().c_str());
1325
          local_error= 1;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1326
1530.1.3 by Brian Aker
Style cleanup for table_share
1327
          return local_error;
1328
        }
1329
        break;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1330
      }
1331
    case DRIZZLE_TYPE_DECIMAL:
1530.1.3 by Brian Aker
Style cleanup for table_share
1332
      {
1333
        message::Table::Field::NumericFieldOptions fo= pfield.numeric_options();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1334
1530.1.3 by Brian Aker
Style cleanup for table_share
1335
        field_length= my_decimal_precision_to_length(fo.precision(), fo.scale(),
1336
                                                     false);
1337
        break;
1338
      }
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1339
    case DRIZZLE_TYPE_TIMESTAMP:
1340
    case DRIZZLE_TYPE_DATETIME:
1341
      field_length= DateTime::MAX_STRING_LENGTH;
1342
      break;
1343
    case DRIZZLE_TYPE_DATE:
1344
      field_length= Date::MAX_STRING_LENGTH;
1345
      break;
1346
    case DRIZZLE_TYPE_ENUM:
1347
      {
1530.1.3 by Brian Aker
Style cleanup for table_share
1348
        field_length= 0;
1349
1350
        message::Table::Field::EnumerationValues fo= pfield.enumeration_values();
1351
1352
        for (int valnr= 0; valnr < fo.field_value_size(); valnr++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1353
        {
1530.1.3 by Brian Aker
Style cleanup for table_share
1354
          if (fo.field_value(valnr).length() > field_length)
1355
          {
1356
            field_length= charset->cset->numchars(charset,
1357
                                                  fo.field_value(valnr).c_str(),
1358
                                                  fo.field_value(valnr).c_str()
1359
                                                  + fo.field_value(valnr).length())
1360
              * charset->mbmaxlen;
1361
          }
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1362
        }
1363
      }
1530.1.3 by Brian Aker
Style cleanup for table_share
1364
      break;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1365
    case DRIZZLE_TYPE_LONG:
1366
      {
1367
        uint32_t sign_len= pfield.constraints().is_unsigned() ? 0 : 1;
1530.1.3 by Brian Aker
Style cleanup for table_share
1368
        field_length= MAX_INT_WIDTH+sign_len;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1369
      }
1370
      break;
1371
    case DRIZZLE_TYPE_LONGLONG:
1372
      field_length= MAX_BIGINT_WIDTH;
1373
      break;
1374
    case DRIZZLE_TYPE_NULL:
1375
      abort(); // Programming error
1376
    }
1377
1574.1.2 by Brian Aker
Remove =this reference.
1378
    Field* f= make_field(record + field_offsets[fieldnr] + data_offset,
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1379
                                field_length,
1380
                                pfield.constraints().is_nullable(),
1381
                                null_pos,
1382
                                null_bit_pos,
1383
                                decimals,
1384
                                field_type,
1385
                                charset,
1386
                                (Field::utype) MTYP_TYPENR(unireg_type),
1387
                                ((field_type == DRIZZLE_TYPE_ENUM) ?
1574.1.7 by Brian Aker
Remove interval allocation via memroot.
1388
                                 &intervals[interval_nr++]
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1389
                                 : (TYPELIB*) 0),
1532 by Brian Aker
just remove entirely the need for fieldnames.
1390
                                getTableProto()->field(fieldnr).name().c_str());
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1391
1574.1.2 by Brian Aker
Remove =this reference.
1392
    field[fieldnr]= f;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1393
1843.6.2 by Brian Aker
Add back in init(). Grr.... this should not be required.
1394
    // This needs to go, we should be setting the "use" on the field so that
1395
    // it does not reference the share/table.
1859.2.11 by Brian Aker
Merge in so that shell requires a share to construct.
1396
    table::Shell temp_table(*this); /* Use this so that BLOB DEFAULT '' works */
1843.6.2 by Brian Aker
Add back in init(). Grr.... this should not be required.
1397
    temp_table.in_use= &session;
1398
1399
    f->init(&temp_table); /* blob default values need table obj */
1400
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1401
    if (! (f->flags & NOT_NULL_FLAG))
1402
    {
1403
      *f->null_ptr|= f->null_bit;
1404
      if (! (null_bit_pos= (null_bit_pos + 1) & 7)) /* @TODO Ugh. */
1405
        null_pos++;
1406
      null_count++;
1407
    }
1408
1409
    if (default_value)
1410
    {
1411
      enum_check_fields old_count_cuted_fields= session.count_cuted_fields;
1637.1.2 by Brian Aker
Put in call for to make sure enum is always accurate.
1412
      session.count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1413
      int res= default_value->save_in_field(f, 1);
1414
      session.count_cuted_fields= old_count_cuted_fields;
1415
      if (res != 0 && res != 3) /* @TODO Huh? */
1416
      {
1417
        my_error(ER_INVALID_DEFAULT, MYF(0), f->field_name);
1418
        local_error= 1;
1419
1530.1.3 by Brian Aker
Style cleanup for table_share
1420
        return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1421
      }
1422
    }
1423
    else if (f->real_type() == DRIZZLE_TYPE_ENUM &&
1424
             (f->flags & NOT_NULL_FLAG))
1425
    {
1426
      f->set_notnull();
1427
      f->store((int64_t) 1, true);
1428
    }
1429
    else
1430
    {
1431
      f->reset();
1432
    }
1433
1434
    /* hack to undo f->init() */
1660.1.3 by Brian Aker
Encapsulate Table in field
1435
    f->setTable(NULL);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1436
    f->orig_table= NULL;
1437
1438
    f->field_index= fieldnr;
1439
    f->comment= comment;
1440
    if (! default_value &&
1441
        ! (f->unireg_check==Field::NEXT_NUMBER) &&
1442
        (f->flags & NOT_NULL_FLAG) &&
1443
        (f->real_type() != DRIZZLE_TYPE_TIMESTAMP))
1444
    {
1445
      f->flags|= NO_DEFAULT_VALUE_FLAG;
1446
    }
1447
1448
    if (f->unireg_check == Field::NEXT_NUMBER)
1574.1.2 by Brian Aker
Remove =this reference.
1449
      found_next_number_field= &(field[fieldnr]);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1450
1574.1.2 by Brian Aker
Remove =this reference.
1451
    if (timestamp_field == f)
1452
      timestamp_field_offset= fieldnr;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1453
1454
    if (use_hash) /* supposedly this never fails... but comments lie */
1669.3.1 by Brian Aker
Remove usage of my_hash in table_share.
1455
    {
1456
      const char *local_field_name= field[fieldnr]->field_name;
1457
      name_hash.insert(make_pair(local_field_name, &(field[fieldnr])));
1458
    }
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1459
1460
  }
1461
1574.1.2 by Brian Aker
Remove =this reference.
1462
  keyinfo= key_info;
1463
  for (unsigned int keynr= 0; keynr < keys; keynr++, keyinfo++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1464
  {
1465
    key_part= keyinfo->key_part;
1466
1467
    for (unsigned int partnr= 0;
1468
         partnr < keyinfo->key_parts;
1469
         partnr++, key_part++)
1470
    {
1471
      /* 
1472
       * Fix up key_part->offset by adding data_offset.
1473
       * We really should compute offset as well.
1474
       * But at least this way we are a little better.
1530.1.3 by Brian Aker
Style cleanup for table_share
1475
     */
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1476
      key_part->offset= field_offsets[key_part->fieldnr-1] + data_offset;
1477
    }
1478
  }
1479
1480
  /*
1481
    We need to set the unused bits to 1. If the number of bits is a multiple
1482
    of 8 there are no unused bits.
1483
  */
1484
1485
  if (null_count & 7)
1486
    *(record + null_count / 8)|= ~(((unsigned char) 1 << (null_count & 7)) - 1);
1487
1574.1.2 by Brian Aker
Remove =this reference.
1488
  null_bytes= (null_pos - (unsigned char*) record + (null_bit_pos + 7) / 8);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1489
1574.1.2 by Brian Aker
Remove =this reference.
1490
  last_null_bit_pos= null_bit_pos;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1491
1492
  /* Fix key stuff */
1574.1.2 by Brian Aker
Remove =this reference.
1493
  if (key_parts)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1494
  {
1527.1.4 by Brian Aker
Second pass to remove keynames typelib.
1495
    uint32_t local_primary_key= 0;
1496
    doesKeyNameExist("PRIMARY", local_primary_key);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1497
1574.1.2 by Brian Aker
Remove =this reference.
1498
    keyinfo= key_info;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1499
    key_part= keyinfo->key_part;
1500
1574.1.2 by Brian Aker
Remove =this reference.
1501
    for (uint32_t key= 0; key < keys; key++,keyinfo++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1502
    {
1503
      uint32_t usable_parts= 0;
1504
1505
      if (local_primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
1506
      {
1530.1.3 by Brian Aker
Style cleanup for table_share
1507
        /*
1508
          If the UNIQUE key doesn't have NULL columns and is not a part key
1509
          declare this as a primary key.
1510
        */
1511
        local_primary_key=key;
1512
        for (uint32_t i= 0; i < keyinfo->key_parts; i++)
1513
        {
1514
          uint32_t fieldnr= key_part[i].fieldnr;
1515
          if (! fieldnr ||
1574.1.2 by Brian Aker
Remove =this reference.
1516
              field[fieldnr-1]->null_ptr ||
1517
              field[fieldnr-1]->key_length() != key_part[i].length)
1530.1.3 by Brian Aker
Style cleanup for table_share
1518
          {
1519
            local_primary_key= MAX_KEY; // Can't be used
1520
            break;
1521
          }
1522
        }
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1523
      }
1524
1525
      for (uint32_t i= 0 ; i < keyinfo->key_parts ; key_part++,i++)
1526
      {
1530.1.3 by Brian Aker
Style cleanup for table_share
1527
        Field *local_field;
1528
        if (! key_part->fieldnr)
1529
        {
1530
          return ENOMEM;
1531
        }
1574.1.2 by Brian Aker
Remove =this reference.
1532
        local_field= key_part->field= field[key_part->fieldnr-1];
1530.1.3 by Brian Aker
Style cleanup for table_share
1533
        key_part->type= local_field->key_type();
1534
        if (local_field->null_ptr)
1535
        {
1574.1.2 by Brian Aker
Remove =this reference.
1536
          key_part->null_offset=(uint32_t) ((unsigned char*) local_field->null_ptr - getDefaultValues());
1530.1.3 by Brian Aker
Style cleanup for table_share
1537
          key_part->null_bit= local_field->null_bit;
1538
          key_part->store_length+=HA_KEY_NULL_LENGTH;
1539
          keyinfo->flags|=HA_NULL_PART_KEY;
1540
          keyinfo->extra_length+= HA_KEY_NULL_LENGTH;
1541
          keyinfo->key_length+= HA_KEY_NULL_LENGTH;
1542
        }
1543
        if (local_field->type() == DRIZZLE_TYPE_BLOB ||
1544
            local_field->real_type() == DRIZZLE_TYPE_VARCHAR)
1545
        {
1546
          if (local_field->type() == DRIZZLE_TYPE_BLOB)
1547
            key_part->key_part_flag|= HA_BLOB_PART;
1548
          else
1549
            key_part->key_part_flag|= HA_VAR_LENGTH_PART;
1550
          keyinfo->extra_length+=HA_KEY_BLOB_LENGTH;
1551
          key_part->store_length+=HA_KEY_BLOB_LENGTH;
1552
          keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
1553
        }
1554
        if (i == 0 && key != local_primary_key)
1555
          local_field->flags |= (((keyinfo->flags & HA_NOSAME) &&
1556
                                  (keyinfo->key_parts == 1)) ?
1557
                                 UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
1558
        if (i == 0)
1559
          local_field->key_start.set(key);
1560
        if (local_field->key_length() == key_part->length &&
1561
            !(local_field->flags & BLOB_FLAG))
1562
        {
1574.1.2 by Brian Aker
Remove =this reference.
1563
          enum ha_key_alg algo= key_info[key].algorithm;
1564
          if (db_type()->index_flags(algo) & HA_KEYREAD_ONLY)
1530.1.3 by Brian Aker
Style cleanup for table_share
1565
          {
1574.1.2 by Brian Aker
Remove =this reference.
1566
            keys_for_keyread.set(key);
1530.1.3 by Brian Aker
Style cleanup for table_share
1567
            local_field->part_of_key.set(key);
1568
            local_field->part_of_key_not_clustered.set(key);
1569
          }
1574.1.2 by Brian Aker
Remove =this reference.
1570
          if (db_type()->index_flags(algo) & HA_READ_ORDER)
1530.1.3 by Brian Aker
Style cleanup for table_share
1571
            local_field->part_of_sortkey.set(key);
1572
        }
1573
        if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
1574
            usable_parts == i)
1575
          usable_parts++;			// For FILESORT
1576
        local_field->flags|= PART_KEY_FLAG;
1577
        if (key == local_primary_key)
1578
        {
1579
          local_field->flags|= PRI_KEY_FLAG;
1580
          /*
1581
            If this field is part of the primary key and all keys contains
1582
            the primary key, then we can use any key to find this column
1583
          */
1574.1.2 by Brian Aker
Remove =this reference.
1584
          if (storage_engine->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX))
1530.1.3 by Brian Aker
Style cleanup for table_share
1585
          {
1574.1.2 by Brian Aker
Remove =this reference.
1586
            local_field->part_of_key= keys_in_use;
1530.1.3 by Brian Aker
Style cleanup for table_share
1587
            if (local_field->part_of_sortkey.test(key))
1574.1.2 by Brian Aker
Remove =this reference.
1588
              local_field->part_of_sortkey= keys_in_use;
1530.1.3 by Brian Aker
Style cleanup for table_share
1589
          }
1590
        }
1591
        if (local_field->key_length() != key_part->length)
1592
        {
1593
          key_part->key_part_flag|= HA_PART_KEY_SEG;
1594
        }
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1595
      }
1596
      keyinfo->usable_key_parts= usable_parts; // Filesort
1597
1574.1.2 by Brian Aker
Remove =this reference.
1598
      set_if_bigger(max_key_length,keyinfo->key_length+
1530.1.3 by Brian Aker
Style cleanup for table_share
1599
                    keyinfo->key_parts);
1574.1.2 by Brian Aker
Remove =this reference.
1600
      total_key_length+= keyinfo->key_length;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1601
1602
      if (keyinfo->flags & HA_NOSAME)
1603
      {
1574.1.2 by Brian Aker
Remove =this reference.
1604
        set_if_bigger(max_unique_length,keyinfo->key_length);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1605
      }
1606
    }
1607
    if (local_primary_key < MAX_KEY &&
1574.1.2 by Brian Aker
Remove =this reference.
1608
        (keys_in_use.test(local_primary_key)))
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1609
    {
1574.1.2 by Brian Aker
Remove =this reference.
1610
      primary_key= local_primary_key;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1611
      /*
1612
        If we are using an integer as the primary key then allow the user to
1613
        refer to it as '_rowid'
1614
      */
1574.1.2 by Brian Aker
Remove =this reference.
1615
      if (key_info[local_primary_key].key_parts == 1)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1616
      {
1574.1.2 by Brian Aker
Remove =this reference.
1617
        Field *local_field= key_info[local_primary_key].key_part[0].field;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1618
        if (local_field && local_field->result_type() == INT_RESULT)
1619
        {
1620
          /* note that fieldnr here (and rowid_field_offset) starts from 1 */
1574.1.2 by Brian Aker
Remove =this reference.
1621
          rowid_field_offset= (key_info[local_primary_key].key_part[0].
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1622
                                      fieldnr);
1623
        }
1624
      }
1625
    }
1626
  }
1627
1574.1.2 by Brian Aker
Remove =this reference.
1628
  if (found_next_number_field)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1629
  {
1574.1.2 by Brian Aker
Remove =this reference.
1630
    Field *reg_field= *found_next_number_field;
1631
    if ((int) (next_number_index= (uint32_t)
1632
               find_ref_key(key_info, keys,
1633
                            getDefaultValues(), reg_field,
1634
                            &next_number_key_offset,
1635
                            &next_number_keypart)) < 0)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1636
    {
1637
      /* Wrong field definition */
1638
      local_error= 4;
1639
1640
      return local_error;
1641
    }
1642
    else
1643
    {
1644
      reg_field->flags |= AUTO_INCREMENT_FLAG;
1645
    }
1646
  }
1647
1574.1.2 by Brian Aker
Remove =this reference.
1648
  if (blob_fields)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1649
  {
1650
    /* Store offsets to blob fields to find them fast */
1574.1.8 by Brian Aker
Blob now allocated via vector
1651
    blob_field.resize(blob_fields);
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1652
    uint32_t *save= &blob_field[0];
1653
    uint32_t k= 0;
1578.2.14 by Brian Aker
Additional pass through to remove raw field access.
1654
    for (Fields::iterator iter= field.begin(); iter != field.end()-1; iter++, k++)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1655
    {
1578.2.13 by Brian Aker
Use iterator for Field in share creation.
1656
      if ((*iter)->flags & BLOB_FLAG)
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1657
        (*save++)= k;
1658
    }
1659
  }
1660
1574.1.2 by Brian Aker
Remove =this reference.
1661
  db_low_byte_first= true; // @todo Question this.
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
1662
  all_set.clear();
1663
  all_set.resize(fields);
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1664
  all_set.set();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1665
1666
  return local_error;
1667
}
1668
1669
int TableShare::parse_table_proto(Session& session, message::Table &table)
1670
{
1671
  int local_error= inner_parse_table_proto(session, table);
1672
1673
  if (not local_error)
1674
    return 0;
1675
1676
  error= local_error;
1677
  open_errno= errno;
1678
  errarg= 0;
1679
  open_table_error(local_error, open_errno, 0);
1680
1681
  return local_error;
1682
}
1683
1684
1685
/*
1686
  Read table definition from a binary / text based .frm cursor
1687
1688
  SYNOPSIS
1689
  open_table_def()
1690
  session		Thread Cursor
1691
  share		Fill this with table definition
1692
1693
  NOTES
1530.1.3 by Brian Aker
Style cleanup for table_share
1694
  This function is called when the table definition is not cached in
1877.2.9 by Brian Aker
Adding cache.h for definition.
1695
  definition::Cache::singleton().getCache()
1530.1.3 by Brian Aker
Style cleanup for table_share
1696
  The data is returned in 'share', which is alloced by
1697
  alloc_table_share().. The code assumes that share is initialized.
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1698
1699
  RETURN VALUES
1530.1.3 by Brian Aker
Style cleanup for table_share
1700
  0	ok
1701
  1	Error (see open_table_error)
1702
  2    Error (see open_table_error)
1703
  3    Wrong data in .frm cursor
1704
  4    Error (see open_table_error)
1705
  5    Error (see open_table_error: charset unavailable)
1706
  6    Unknown .frm version
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1707
*/
1708
1709
int TableShare::open_table_def(Session& session, TableIdentifier &identifier)
1710
{
1711
  int local_error;
1712
  bool error_given;
1713
1714
  local_error= 1;
1715
  error_given= 0;
1716
1717
  message::Table table;
1718
1719
  local_error= plugin::StorageEngine::getTableDefinition(session, identifier, table);
1720
1721
  if (local_error != EEXIST)
1722
  {
1723
    if (local_error > 0)
1724
    {
1725
      errno= local_error;
1726
      local_error= 1;
1727
    }
1728
    else
1729
    {
1730
      if (not table.IsInitialized())
1731
      {
1530.1.3 by Brian Aker
Style cleanup for table_share
1732
        local_error= 4;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1733
      }
1734
    }
1735
    goto err_not_open;
1736
  }
1737
1738
  local_error= parse_table_proto(session, table);
1739
1740
  setTableCategory(TABLE_CATEGORY_USER);
1741
1742
err_not_open:
1743
  if (local_error && !error_given)
1744
  {
1745
    error= local_error;
1746
    open_table_error(error, (open_errno= errno), 0);
1747
  }
1748
1749
  return(error);
1750
}
1751
1752
1753
/*
1754
  Open a table based on a TableShare
1755
1756
  SYNOPSIS
1530.1.3 by Brian Aker
Style cleanup for table_share
1757
  open_table_from_share()
1758
  session			Thread Cursor
1759
  share		Table definition
1760
  alias       	Alias for table
1761
  db_stat		open flags (for example HA_OPEN_KEYFILE|
1762
  HA_OPEN_RNDFILE..) can be 0 (example in
1763
  ha_example_table)
1764
  ha_open_flags	HA_OPEN_ABORT_IF_LOCKED etc..
1765
  outparam       	result table
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1766
1767
  RETURN VALUES
1530.1.3 by Brian Aker
Style cleanup for table_share
1768
  0	ok
1769
  1	Error (see open_table_error)
1770
  2    Error (see open_table_error)
1771
  3    Wrong data in .frm cursor
1772
  4    Error (see open_table_error)
1773
  5    Error (see open_table_error: charset unavailable)
1774
  7    Table definition has changed in engine
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1775
*/
1626.3.2 by Brian Aker
Cleanup table_share to pass in identifier.
1776
int TableShare::open_table_from_share(Session *session,
1777
                                      const TableIdentifier &identifier,
1778
                                      const char *alias,
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1779
                                      uint32_t db_stat, uint32_t ha_open_flags,
1780
                                      Table &outparam)
1781
{
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1782
  bool error_reported= false;
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1783
  int ret= open_table_from_share_inner(session, alias, db_stat, outparam);
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1784
1785
  if (not ret)
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1786
    ret= open_table_cursor_inner(identifier, db_stat, ha_open_flags, outparam, error_reported);
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1787
1788
  if (not ret)
1789
    return ret;
1790
1791
  if (not error_reported)
1792
    open_table_error(ret, errno, 0);
1793
1794
  delete outparam.cursor;
1795
  outparam.cursor= 0;				// For easier error checking
1796
  outparam.db_stat= 0;
1797
  outparam.getMemRoot()->free_root(MYF(0));       // Safe to call on zeroed root
1864.4.4 by Brian Aker
We now handle the free of the alias inside of table.
1798
  outparam.clearAlias();
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1799
1800
  return ret;
1801
}
1802
1803
int TableShare::open_table_from_share_inner(Session *session,
1804
                                            const char *alias,
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1805
                                            uint32_t db_stat,
1806
                                            Table &outparam)
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1807
{
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1808
  int local_error;
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
1809
  uint32_t records;
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1810
  unsigned char *record= NULL;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1811
  Field **field_ptr;
1812
1813
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1814
  assert(session->lex->is_lex_started);
1815
1816
  local_error= 1;
1817
  outparam.resetTable(session, this, db_stat);
1818
1864.4.4 by Brian Aker
We now handle the free of the alias inside of table.
1819
  outparam.setAlias(alias);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1820
1821
  /* Allocate Cursor */
1869.1.4 by Brian Aker
TableShare is no longer in the house (i.e. we no longer directly have a copy
1822
  if (not (outparam.cursor= db_type()->getCursor(outparam)))
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1823
    return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1824
1825
  local_error= 4;
1826
  records= 0;
1827
  if ((db_stat & HA_OPEN_KEYFILE))
1828
    records=1;
1829
1830
  records++;
1831
1532.1.8 by Brian Aker
Yet more movement/encapsulation of mem_root in table.
1832
  if (!(record= (unsigned char*) outparam.alloc_root(rec_buff_length * records)))
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1833
    return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1834
1835
  if (records == 0)
1836
  {
1837
    /* We are probably in hard repair, and the buffers should not be used */
1574 by Brian Aker
Rollup patch for hiding tableshare.
1838
    outparam.record[0]= outparam.record[1]= getDefaultValues();
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1839
  }
1840
  else
1841
  {
1842
    outparam.record[0]= record;
1843
    if (records > 1)
1844
      outparam.record[1]= record+ rec_buff_length;
1845
    else
1672.3.6 by Brian Aker
First pass in encapsulating row
1846
      outparam.record[1]= outparam.getInsertRecord();   // Safety
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1847
  }
1848
1859.2.14 by Brian Aker
Add support for --with-valgrind
1849
#ifdef HAVE_VALGRIND
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1850
  /*
1851
    We need this because when we read var-length rows, we are not updating
1852
    bytes after end of varchar
1853
  */
1854
  if (records > 1)
1855
  {
1672.3.6 by Brian Aker
First pass in encapsulating row
1856
    memcpy(outparam.getInsertRecord(), getDefaultValues(), rec_buff_length);
1857
    memcpy(outparam.getUpdateRecord(), getDefaultValues(), null_bytes);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1858
    if (records > 2)
1672.3.6 by Brian Aker
First pass in encapsulating row
1859
      memcpy(outparam.getUpdateRecord(), getDefaultValues(), rec_buff_length);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1860
  }
1861
#endif
1862
  if (records > 1)
1863
  {
1672.3.6 by Brian Aker
First pass in encapsulating row
1864
    memcpy(outparam.getUpdateRecord(), getDefaultValues(), null_bytes);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1865
  }
1866
1532.1.8 by Brian Aker
Yet more movement/encapsulation of mem_root in table.
1867
  if (!(field_ptr = (Field **) outparam.alloc_root( (uint32_t) ((fields+1)* sizeof(Field*)))))
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1868
  {
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1869
    return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1870
  }
1871
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1872
  outparam.setFields(field_ptr);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1873
1672.3.6 by Brian Aker
First pass in encapsulating row
1874
  record= (unsigned char*) outparam.getInsertRecord()-1;	/* Fieldstart = 1 */
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1875
1876
  outparam.null_flags= (unsigned char*) record+1;
1877
1878
  /* Setup copy of fields from share, but use the right alias and record */
1879
  for (uint32_t i= 0 ; i < fields; i++, field_ptr++)
1880
  {
1532.1.8 by Brian Aker
Yet more movement/encapsulation of mem_root in table.
1881
    if (!((*field_ptr)= field[i]->clone(outparam.getMemRoot(), &outparam)))
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1882
      return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1883
  }
1884
  (*field_ptr)= 0;                              // End marker
1885
1886
  if (found_next_number_field)
1887
    outparam.found_next_number_field=
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1888
      outparam.getField(positionFields(found_next_number_field));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1889
  if (timestamp_field)
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1890
    outparam.timestamp_field= (Field_timestamp*) outparam.getField(timestamp_field_offset);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1891
1892
1893
  /* Fix key->name and key_part->field */
1894
  if (key_parts)
1895
  {
1535 by Brian Aker
Rename of KEY to KeyInfo
1896
    KeyInfo	*local_key_info, *key_info_end;
1534 by Brian Aker
Remove of KeyPartInfo
1897
    KeyPartInfo *key_part;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1898
    uint32_t n_length;
1535 by Brian Aker
Rename of KEY to KeyInfo
1899
    n_length= keys*sizeof(KeyInfo) + key_parts*sizeof(KeyPartInfo);
1532.1.8 by Brian Aker
Yet more movement/encapsulation of mem_root in table.
1900
    if (!(local_key_info= (KeyInfo*) outparam.alloc_root(n_length)))
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1901
      return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1902
    outparam.key_info= local_key_info;
1534 by Brian Aker
Remove of KeyPartInfo
1903
    key_part= (reinterpret_cast<KeyPartInfo*> (local_key_info+keys));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1904
1905
    memcpy(local_key_info, key_info, sizeof(*local_key_info)*keys);
1906
    memcpy(key_part, key_info[0].key_part, (sizeof(*key_part) *
1530.1.3 by Brian Aker
Style cleanup for table_share
1907
                                            key_parts));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1908
1909
    for (key_info_end= local_key_info + keys ;
1910
         local_key_info < key_info_end ;
1911
         local_key_info++)
1912
    {
1534 by Brian Aker
Remove of KeyPartInfo
1913
      KeyPartInfo *key_part_end;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1914
1915
      local_key_info->table= &outparam;
1916
      local_key_info->key_part= key_part;
1917
1918
      for (key_part_end= key_part+ local_key_info->key_parts ;
1919
           key_part < key_part_end ;
1920
           key_part++)
1921
      {
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1922
        Field *local_field= key_part->field= outparam.getField(key_part->fieldnr-1);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1923
1924
        if (local_field->key_length() != key_part->length &&
1925
            !(local_field->flags & BLOB_FLAG))
1926
        {
1927
          /*
1928
            We are using only a prefix of the column as a key:
1929
            Create a new field for the key part that matches the index
1930
          */
1532.1.8 by Brian Aker
Yet more movement/encapsulation of mem_root in table.
1931
          local_field= key_part->field= local_field->new_field(outparam.getMemRoot(), &outparam, 0);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1932
          local_field->field_length= key_part->length;
1933
        }
1934
      }
1935
    }
1936
  }
1937
1938
  /* Allocate bitmaps */
1939
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1940
  outparam.def_read_set.resize(fields);
1941
  outparam.def_write_set.resize(fields);
1942
  outparam.tmp_set.resize(fields);
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1943
  outparam.default_column_bitmaps();
1944
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1945
  return 0;
1946
}
1947
1864.4.1 by Brian Aker
Move share creation into temporary table (there still exists and issue with
1948
int TableShare::open_table_cursor_inner(const TableIdentifier &identifier,
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1949
                                        uint32_t db_stat, uint32_t ha_open_flags,
1950
                                        Table &outparam,
1951
                                        bool &error_reported)
1952
{
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1953
  /* The table struct is now initialized;  Open the table */
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1954
  int local_error= 2;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1955
  if (db_stat)
1956
  {
1578.2.9 by Brian Aker
Simplify ha_open.
1957
    assert(!(db_stat & HA_WAIT_IF_LOCKED));
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1958
    int ha_err;
1626.3.1 by Brian Aker
Adding in TableIdentifier for ha_open; (first pass)
1959
1869.1.7 by Brian Aker
Cleanup of caller to ha_open().
1960
    if ((ha_err= (outparam.cursor->ha_open(identifier,
1961
                                           (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
1962
                                           (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE : HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1963
    {
1964
      switch (ha_err)
1965
      {
1530.1.3 by Brian Aker
Style cleanup for table_share
1966
      case HA_ERR_NO_SUCH_TABLE:
1967
        /*
1968
          The table did not exists in storage engine, use same error message
1969
          as if the .frm cursor didn't exist
1970
        */
1971
        local_error= 1;
1972
        errno= ENOENT;
1973
        break;
1974
      case EMFILE:
1975
        /*
1976
          Too many files opened, use same error message as if the .frm
1977
          cursor can't open
1978
        */
1979
        local_error= 1;
1980
        errno= EMFILE;
1981
        break;
1982
      default:
1983
        outparam.print_error(ha_err, MYF(0));
1984
        error_reported= true;
1985
        if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
1986
          local_error= 7;
1987
        break;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1988
      }
1861.4.2 by Brian Aker
Small refactor around how we build up the share (this is partwise between
1989
      return local_error;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1990
    }
1991
  }
1992
1993
  return 0;
1994
}
1995
1996
/* error message when opening a form cursor */
1997
void TableShare::open_table_error(int pass_error, int db_errno, int pass_errarg)
1998
{
1999
  int err_no;
2000
  char buff[FN_REFLEN];
2001
  myf errortype= ME_ERROR+ME_WAITTANG;
2002
2003
  switch (pass_error) {
2004
  case 7:
2005
  case 1:
2006
    if (db_errno == ENOENT)
2007
    {
2008
      my_error(ER_NO_SUCH_TABLE, MYF(0), db.str, table_name.str);
2009
    }
2010
    else
2011
    {
2012
      snprintf(buff, sizeof(buff), "%s",normalized_path.str);
2013
      my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
2014
               errortype, buff, db_errno);
2015
    }
2016
    break;
2017
  case 2:
1530.1.3 by Brian Aker
Style cleanup for table_share
2018
    {
2019
      err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
2020
        ER_FILE_USED : ER_CANT_OPEN_FILE;
1578.4.11 by Brian Aker
PAss through the code removing current_session
2021
      my_error(err_no, errortype, normalized_path.str, db_errno);
1530.1.3 by Brian Aker
Style cleanup for table_share
2022
      break;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
2023
    }
2024
  case 5:
2025
    {
1530.1.3 by Brian Aker
Style cleanup for table_share
2026
      const char *csname= get_charset_name((uint32_t) pass_errarg);
2027
      char tmp[10];
2028
      if (!csname || csname[0] =='?')
2029
      {
2030
        snprintf(tmp, sizeof(tmp), "#%d", pass_errarg);
2031
        csname= tmp;
2032
      }
2033
      my_printf_error(ER_UNKNOWN_COLLATION,
2034
                      _("Unknown collation '%s' in table '%-.64s' definition"),
2035
                      MYF(0), csname, table_name.str);
2036
      break;
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
2037
    }
2038
  case 6:
2039
    snprintf(buff, sizeof(buff), "%s", normalized_path.str);
2040
    my_printf_error(ER_NOT_FORM_FILE,
2041
                    _("Table '%-.64s' was created with a different version "
1530.1.3 by Brian Aker
Style cleanup for table_share
2042
                      "of Drizzle and cannot be read"),
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
2043
                    MYF(0), buff);
2044
    break;
2045
  case 8:
2046
    break;
2047
  default:				/* Better wrong error than none */
2048
  case 4:
2049
    snprintf(buff, sizeof(buff), "%s", normalized_path.str);
2050
    my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
2051
    break;
2052
  }
2053
  return;
2054
} /* open_table_error */
2055
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2056
Field *TableShare::make_field(unsigned char *ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2057
                              uint32_t field_length,
2058
                              bool is_nullable,
2059
                              unsigned char *null_pos,
2060
                              unsigned char null_bit,
2061
                              uint8_t decimals,
2062
                              enum_field_types field_type,
2063
                              const CHARSET_INFO * field_charset,
2064
                              Field::utype unireg_check,
2065
                              TYPELIB *interval,
2066
                              const char *field_name)
2067
{
2068
  if (! is_nullable)
2069
  {
2070
    null_pos=0;
2071
    null_bit=0;
2072
  }
2073
  else
2074
  {
2075
    null_bit= ((unsigned char) 1) << null_bit;
2076
  }
2077
2078
  switch (field_type) 
2079
  {
2080
  case DRIZZLE_TYPE_DATE:
2081
  case DRIZZLE_TYPE_DATETIME:
2082
  case DRIZZLE_TYPE_TIMESTAMP:
2083
    field_charset= &my_charset_bin;
2084
  default: break;
2085
  }
2086
2087
  switch (field_type)
2088
  {
2089
  case DRIZZLE_TYPE_ENUM:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2090
    return new (&mem_root) Field_enum(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2091
                                 field_length,
2092
                                 null_pos,
2093
                                 null_bit,
2094
                                 field_name,
2095
                                 interval,
2096
                                 field_charset);
2097
  case DRIZZLE_TYPE_VARCHAR:
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
2098
    setVariableWidth();
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2099
    return new (&mem_root) Field_varstring(ptr,field_length,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2100
                                      HA_VARCHAR_PACKLENGTH(field_length),
2101
                                      null_pos,null_bit,
2102
                                      field_name,
2103
                                      field_charset);
2104
  case DRIZZLE_TYPE_BLOB:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2105
    return new (&mem_root) Field_blob(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2106
                                 null_pos,
2107
                                 null_bit,
2108
                                 field_name,
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2109
                                 this,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2110
                                 calc_pack_length(DRIZZLE_TYPE_LONG, 0),
2111
                                 field_charset);
2112
  case DRIZZLE_TYPE_DECIMAL:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2113
    return new (&mem_root) Field_decimal(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2114
                                    field_length,
2115
                                    null_pos,
2116
                                    null_bit,
2117
                                    unireg_check,
2118
                                    field_name,
2119
                                    decimals,
2120
                                    false,
2121
                                    false /* is_unsigned */);
2122
  case DRIZZLE_TYPE_DOUBLE:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2123
    return new (&mem_root) Field_double(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2124
                                   field_length,
2125
                                   null_pos,
2126
                                   null_bit,
2127
                                   unireg_check,
2128
                                   field_name,
2129
                                   decimals,
2130
                                   false,
2131
                                   false /* is_unsigned */);
2132
  case DRIZZLE_TYPE_LONG:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2133
    return new (&mem_root) Field_long(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2134
                                 field_length,
2135
                                 null_pos,
2136
                                 null_bit,
2137
                                 unireg_check,
2138
                                 field_name,
2139
                                 false,
2140
                                 false /* is_unsigned */);
2141
  case DRIZZLE_TYPE_LONGLONG:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2142
    return new (&mem_root) Field_int64_t(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2143
                                    field_length,
2144
                                    null_pos,
2145
                                    null_bit,
2146
                                    unireg_check,
2147
                                    field_name,
2148
                                    false,
2149
                                    false /* is_unsigned */);
2150
  case DRIZZLE_TYPE_TIMESTAMP:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2151
    return new (&mem_root) Field_timestamp(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2152
                                      field_length,
2153
                                      null_pos,
2154
                                      null_bit,
2155
                                      unireg_check,
2156
                                      field_name,
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2157
                                      this,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2158
                                      field_charset);
2159
  case DRIZZLE_TYPE_DATE:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2160
    return new (&mem_root) Field_date(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2161
                                 null_pos,
2162
                                 null_bit,
2163
                                 field_name,
2164
                                 field_charset);
2165
  case DRIZZLE_TYPE_DATETIME:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2166
    return new (&mem_root) Field_datetime(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2167
                                     null_pos,
2168
                                     null_bit,
2169
                                     field_name,
2170
                                     field_charset);
2171
  case DRIZZLE_TYPE_NULL:
1532.1.6 by Brian Aker
Encapsulate the ownership of the table members to the table (so not in
2172
    return new (&mem_root) Field_null(ptr,
1530.1.2 by Brian Aker
Second pass through field name, this also corrects _ name usage.
2173
                                 field_length,
2174
                                 field_name,
2175
                                 field_charset);
2176
  default: // Impossible (Wrong version)
2177
    break;
2178
  }
2179
  return 0;
2180
}
2181
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
2182
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
2183
} /* namespace drizzled */