~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
1802.10.2 by Monty Taylor
Update all of the copyright headers to include the correct address.
14
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
1 by brian
clean slate
15
16
17
/* Some general useful functions */
18
1241.9.36 by Monty Taylor
ZOMG. I deleted drizzled/server_includes.h.
19
#include "config.h"
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
20
21
#include <float.h>
22
#include <fcntl.h>
23
24
#include <string>
25
#include <vector>
26
#include <algorithm>
27
549 by Monty Taylor
Took gettext.h out of header files.
28
#include <drizzled/error.h>
29
#include <drizzled/gettext.h>
1 by brian
clean slate
30
1273.1.15 by Jay Pipes
This patch completes the first step in the splitting of
31
#include "drizzled/plugin/transactional_storage_engine.h"
1317.2.7 by Monty Taylor
Prevent users from attempting to access schemas that he is not authorized to
32
#include "drizzled/plugin/authorization.h"
553.1.3 by Monty Taylor
Split out nested_join.h.
33
#include <drizzled/nested_join.h>
520.8.2 by Monty Taylor
Moved sql_parse.h and sql_error.h out of common_includes.
34
#include <drizzled/sql_parse.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
35
#include <drizzled/item/sum.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
36
#include <drizzled/table_list.h>
37
#include <drizzled/session.h>
38
#include <drizzled/sql_base.h>
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
39
#include <drizzled/sql_select.h>
584.5.1 by Monty Taylor
Removed field includes from field.h.
40
#include <drizzled/field/blob.h>
41
#include <drizzled/field/varstring.h>
42
#include <drizzled/field/double.h>
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
43
#include <drizzled/unireg.h>
988.1.1 by Jay Pipes
Changes libserialize to libdrizzledmessage per ML discussion. All GPB messages are now in the drizzled::message namespace.
44
#include <drizzled/message/table.pb.h>
1241.9.23 by Monty Taylor
Removed sql_table.h from server_includes.h.
45
#include "drizzled/sql_table.h"
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
46
#include "drizzled/charset.h"
1241.9.64 by Monty Taylor
Moved remaining non-public portions of mysys and mystrings to drizzled/internal.
47
#include "drizzled/internal/m_string.h"
1241.9.63 by Monty Taylor
zomg. I think drizzled/ is clean now.
48
#include "plugin/myisam/myisam.h"
820.1.8 by Stewart Smith
start reading table definition from proto instead of FRM.
49
896.3.3 by Stewart Smith
Start generating a record buffer with default values in proto read path instead of FRM write path.
50
#include <drizzled/item/string.h>
51
#include <drizzled/item/int.h>
52
#include <drizzled/item/decimal.h>
53
#include <drizzled/item/float.h>
54
#include <drizzled/item/null.h>
1215.1.6 by stewart at flamingspork
[patch 06/17] Dont store TIMESTAMP length in proto. Always the same (max string length), so just set it on load instead.
55
#include <drizzled/temporal.h>
982.1.11 by Padraig O'Sullivan
Reverted my changes for replacing Bitmap<> for the moment. Going to fix up
56
1843.8.4 by Brian Aker
Committing refactor of table out (this is part of the concurrency work).
57
#include "drizzled/table/instance.h"
1502.1.19 by Brian Aker
Adds concept of table owned TableShare.
58
1130.3.9 by Monty Taylor
Wrapped table_proto_write.cc code in namespace drizzled.
59
#include "drizzled/table_proto.h"
1095.3.3 by Stewart Smith
move drizzle_proto_exists and drizzle_read_table_proto out of unireg.h and into table_proto.h
60
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
61
using namespace std;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
62
63
namespace drizzled
64
{
534 by Monty Taylor
Removed stxnmov. Also deleted strstr which had already been removed.
65
1241.9.31 by Monty Taylor
Moved global pthread variables into their own header.
66
extern pid_t current_pid;
1241.9.32 by Monty Taylor
Moved global myisam and heap pointers out of server_includes.
67
extern plugin::StorageEngine *heap_engine;
68
extern plugin::StorageEngine *myisam_engine;
1241.9.31 by Monty Taylor
Moved global pthread variables into their own header.
69
1208.3.2 by brian
Update for Cursor renaming.
70
/* Functions defined in this cursor */
1 by brian
clean slate
71
1000.1.3 by Brian Aker
Renamed TABLE_SHARE to TableShare
72
void open_table_error(TableShare *share, int error, int db_errno,
1 by brian
clean slate
73
                      myf errortype, int errarg);
74
75
/*************************************************************************/
76
1502.1.3 by Brian Aker
Cleanup to use references.
77
// @note this should all be the destructor
78
int Table::delete_table(bool free_share)
1 by brian
clean slate
79
{
1046.1.6 by Brian Aker
Formatting/style cleanup.
80
  int error= 0;
1 by brian
clean slate
81
793 by Brian Aker
Pass through on refactoring functions to clases.
82
  if (db_stat)
1208.3.2 by brian
Update for Cursor renaming.
83
    error= cursor->close();
1864.4.4 by Brian Aker
We now handle the free of the alias inside of table.
84
  _alias.clear();
793 by Brian Aker
Pass through on refactoring functions to clases.
85
  if (field)
1 by brian
clean slate
86
  {
793 by Brian Aker
Pass through on refactoring functions to clases.
87
    for (Field **ptr=field ; *ptr ; ptr++)
1502.1.13 by Brian Aker
Next bit of TableShare to c++.
88
    {
1 by brian
clean slate
89
      delete *ptr;
1502.1.13 by Brian Aker
Next bit of TableShare to c++.
90
    }
793 by Brian Aker
Pass through on refactoring functions to clases.
91
    field= 0;
1 by brian
clean slate
92
  }
1208.3.2 by brian
Update for Cursor renaming.
93
  delete cursor;
94
  cursor= 0;				/* For easier errorchecking */
1532.1.14 by Brian Aker
We no longer use alloc for placeholders (due to HASH I didn't use a
95
1 by brian
clean slate
96
  if (free_share)
97
  {
1903.1.1 by Brian Aker
Merge of partial set of patches for locks.
98
    release();
1 by brian
clean slate
99
  }
1864.4.3 by Brian Aker
Move mem_root to the destructor.
100
101
  return error;
102
}
103
104
Table::~Table()
105
{
1487 by Brian Aker
More updates for memory::Root
106
  mem_root.free_root(MYF(0));
1 by brian
clean slate
107
}
108
109
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
110
void Table::resetTable(Session *session,
111
                       TableShare *share,
112
                       uint32_t db_stat_arg)
113
{
1827.2.2 by Brian Aker
Encapsulate the share in Table.
114
  setShare(share);
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
115
  field= NULL;
116
117
  cursor= NULL;
118
  next= NULL;
119
  prev= NULL;
120
121
  read_set= NULL;
122
  write_set= NULL;
123
124
  tablenr= 0;
125
  db_stat= db_stat_arg;
126
127
  in_use= session;
128
  record[0]= (unsigned char *) NULL;
129
  record[1]= (unsigned char *) NULL;
130
1672.3.5 by Brian Aker
This replaces the allocation we do for insert/update.
131
  insert_values.clear();
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
132
  key_info= NULL;
133
  next_number_field= NULL;
134
  found_next_number_field= NULL;
135
  timestamp_field= NULL;
136
137
  pos_in_table_list= NULL;
138
  group= NULL;
1864.4.4 by Brian Aker
We now handle the free of the alias inside of table.
139
  _alias.clear();
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
140
  null_flags= NULL;
141
142
  lock_position= 0;
143
  lock_data_start= 0;
144
  lock_count= 0;
145
  used_fields= 0;
146
  status= 0;
147
  derived_select_number= 0;
148
  current_lock= F_UNLCK;
149
  copy_blobs= false;
150
151
  maybe_null= false;
152
153
  null_row= false;
154
155
  force_index= false;
156
  distinct= false;
157
  const_table= false;
158
  no_rows= false;
159
  key_read= false;
160
  no_keyread= false;
161
162
  open_placeholder= false;
163
  locked_by_name= false;
164
  no_cache= false;
165
166
  auto_increment_field_not_null= false;
167
  alias_name_used= false;
168
169
  query_id= 0;
170
  quick_condition_rows= 0;
171
172
  timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
173
  map= 0;
174
175
  reginfo.reset();
176
177
  covering_keys.reset();
178
179
  quick_keys.reset();
180
  merge_keys.reset();
181
182
  keys_in_use_for_query.reset();
183
  keys_in_use_for_group_by.reset();
184
  keys_in_use_for_order_by.reset();
185
1273.1.1 by Jay Pipes
* Changes Session::warn_id to Session::warn_query_id
186
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
187
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
188
189
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
190
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
191
1253.1.6 by Monty Taylor
Moved mem_root functions into drizzled::memory:: namespace.
192
  memory::init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
193
}
194
195
196
1 by brian
clean slate
197
/* Deallocate temporary blob storage */
198
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
199
void free_blobs(register Table *table)
1 by brian
clean slate
200
{
482 by Brian Aker
Remove uint.
201
  uint32_t *ptr, *end;
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
202
  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
1 by brian
clean slate
203
       ptr != end ;
204
       ptr++)
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
205
  {
206
    ((Field_blob*) table->getField(*ptr))->free();
207
  }
1 by brian
clean slate
208
}
209
210
1253.1.3 by Monty Taylor
MEM_ROOT == memory::Root
211
TYPELIB *typelib(memory::Root *mem_root, List<String> &strings)
1 by brian
clean slate
212
{
1485 by Brian Aker
Updates to confine memroot
213
  TYPELIB *result= (TYPELIB*) mem_root->alloc_root(sizeof(TYPELIB));
1 by brian
clean slate
214
  if (!result)
215
    return 0;
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
216
  result->count= strings.elements;
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
217
  result->name= "";
895 by Brian Aker
Completion (?) of uint conversion.
218
  uint32_t nbytes= (sizeof(char*) + sizeof(uint32_t)) * (result->count + 1);
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
219
  
1485 by Brian Aker
Updates to confine memroot
220
  if (!(result->type_names= (const char**) mem_root->alloc_root(nbytes)))
1 by brian
clean slate
221
    return 0;
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
222
    
1 by brian
clean slate
223
  result->type_lengths= (uint*) (result->type_names + result->count + 1);
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
224
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
225
  List_iterator<String> it(strings);
226
  String *tmp;
227
  for (uint32_t i= 0; (tmp= it++); i++)
1 by brian
clean slate
228
  {
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
229
    result->type_names[i]= tmp->ptr();
230
    result->type_lengths[i]= tmp->length();
1 by brian
clean slate
231
  }
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
232
233
  result->type_names[result->count]= 0;   // End marker
1 by brian
clean slate
234
  result->type_lengths[result->count]= 0;
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
235
1 by brian
clean slate
236
  return result;
237
}
238
239
	/* Check that the integer is in the internal */
240
241
int set_zone(register int nr, int min_zone, int max_zone)
242
{
243
  if (nr<=min_zone)
244
    return (min_zone);
245
  if (nr>=max_zone)
246
    return (max_zone);
247
  return (nr);
248
} /* set_zone */
249
250
251
/*
252
  Store an SQL quoted string.
253
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
254
  SYNOPSIS
1 by brian
clean slate
255
    append_unescaped()
256
    res		result String
257
    pos		string to be quoted
258
    length	it's length
259
260
  NOTE
261
    This function works correctly with utf8 or single-byte charset strings.
262
    May fail with some multibyte charsets though.
263
*/
264
482 by Brian Aker
Remove uint.
265
void append_unescaped(String *res, const char *pos, uint32_t length)
1 by brian
clean slate
266
{
267
  const char *end= pos+length;
268
  res->append('\'');
269
270
  for (; pos != end ; pos++)
271
  {
482 by Brian Aker
Remove uint.
272
    uint32_t mblen;
1 by brian
clean slate
273
    if (use_mb(default_charset_info) &&
274
        (mblen= my_ismbchar(default_charset_info, pos, end)))
275
    {
276
      res->append(pos, mblen);
1638.6.2 by Stewart Smith
fix multibyte comments in SHOW CREATE TABLE. Was a simple off-by-one bug.
277
      pos+= mblen - 1;
814.1.1 by Jay Pipes
Fix for Bug 314502 "show create table crashes with multi-byte character in enum description"
278
      if (pos >= end)
279
        break;
814.1.2 by Jay Pipes
Forgot to add back the continue in case of multi-byte character not exceeding the end of string buffer.
280
      continue;
1 by brian
clean slate
281
    }
282
283
    switch (*pos) {
284
    case 0:				/* Must be escaped for 'mysql' */
285
      res->append('\\');
286
      res->append('0');
287
      break;
288
    case '\n':				/* Must be escaped for logs */
289
      res->append('\\');
290
      res->append('n');
291
      break;
292
    case '\r':
293
      res->append('\\');		/* This gives better readability */
294
      res->append('r');
295
      break;
296
    case '\\':
297
      res->append('\\');		/* Because of the sql syntax */
298
      res->append('\\');
299
      break;
300
    case '\'':
301
      res->append('\'');		/* Because of the sql syntax */
302
      res->append('\'');
303
      break;
304
    default:
305
      res->append(*pos);
306
      break;
307
    }
308
  }
309
  res->append('\'');
310
}
311
312
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
313
int rename_file_ext(const char * from,const char * to,const char * ext)
1 by brian
clean slate
314
{
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
315
  string from_s, to_s;
316
317
  from_s.append(from);
318
  from_s.append(ext);
319
  to_s.append(to);
320
  to_s.append(ext);
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
321
  return (internal::my_rename(from_s.c_str(),to_s.c_str(),MYF(MY_WME)));
1 by brian
clean slate
322
}
323
324
/*
1273 by Brian Aker
Revert db patch.
325
  Check if database name is valid
326
327
  SYNPOSIS
328
    check_db_name()
329
    org_name		Name of database and length
330
331
  RETURN
1415 by Brian Aker
Mass overhaul to use schema_identifier.
332
    false error
333
    true ok
1273 by Brian Aker
Revert db patch.
334
*/
335
1578.4.11 by Brian Aker
PAss through the code removing current_session
336
bool check_db_name(Session *session, SchemaIdentifier &schema_identifier)
1273 by Brian Aker
Revert db patch.
337
{
1578.4.11 by Brian Aker
PAss through the code removing current_session
338
  if (not plugin::Authorization::isAuthorized(session->getSecurityContext(), schema_identifier))
1317.2.7 by Monty Taylor
Prevent users from attempting to access schemas that he is not authorized to
339
  {
1415 by Brian Aker
Mass overhaul to use schema_identifier.
340
    return false;
1317.2.7 by Monty Taylor
Prevent users from attempting to access schemas that he is not authorized to
341
  }
342
1415 by Brian Aker
Mass overhaul to use schema_identifier.
343
  return schema_identifier.isValid();
1273 by Brian Aker
Revert db patch.
344
}
345
346
/*
1 by brian
clean slate
347
  Allow anything as a table name, as long as it doesn't contain an
348
  ' ' at the end
349
  returns 1 on error
350
*/
482 by Brian Aker
Remove uint.
351
bool check_table_name(const char *name, uint32_t length)
1 by brian
clean slate
352
{
353
  if (!length || length > NAME_LEN || name[length - 1] == ' ')
354
    return 1;
355
  LEX_STRING ident;
356
  ident.str= (char*) name;
357
  ident.length= length;
358
  return check_identifier_name(&ident);
359
}
360
361
362
/*
363
  Eventually, a "length" argument should be added
364
  to this function, and the inner loop changed to
365
  check_identifier_name() call.
366
*/
367
bool check_column_name(const char *name)
368
{
482 by Brian Aker
Remove uint.
369
  uint32_t name_length= 0;  // name length in symbols
51.1.70 by Jay Pipes
Removed/replaced DBUG symbols and removed sql_test.cc from Makefile
370
  bool last_char_is_space= true;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
371
1 by brian
clean slate
372
  while (*name)
373
  {
374
    last_char_is_space= my_isspace(system_charset_info, *name);
375
    if (use_mb(system_charset_info))
376
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
377
      int len=my_ismbchar(system_charset_info, name,
1 by brian
clean slate
378
                          name+system_charset_info->mbmaxlen);
379
      if (len)
380
      {
381
        if (len > 3) /* Disallow non-BMP characters */
382
          return 1;
383
        name += len;
384
        name_length++;
385
        continue;
386
      }
387
    }
388
    /*
389
      NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
390
      It is defined as 0xFF, which is a not valid byte in utf8.
391
      This assert is to catch use of this byte if we decide to
392
      use non-utf8 as system_character_set.
393
    */
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
394
    assert(*name != NAMES_SEP_CHAR);
1 by brian
clean slate
395
    name++;
396
    name_length++;
397
  }
398
  /* Error if empty or too long column name */
895 by Brian Aker
Completion (?) of uint conversion.
399
  return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
1 by brian
clean slate
400
}
401
402
403
/*****************************************************************************
404
  Functions to handle column usage bitmaps (read_set, write_set etc...)
405
*****************************************************************************/
406
407
/* Reset all columns bitmaps */
408
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
409
void Table::clear_column_bitmaps()
1 by brian
clean slate
410
{
411
  /*
1005.2.3 by Monty Taylor
Further reversion of P.
412
    Reset column read/write usage. It's identical to:
413
    bitmap_clear_all(&table->def_read_set);
414
    bitmap_clear_all(&table->def_write_set);
1 by brian
clean slate
415
  */
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
416
  def_read_set.reset();
417
  def_write_set.reset();
418
  column_bitmaps_set(def_read_set, def_write_set);
1 by brian
clean slate
419
}
420
421
422
/*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
423
  Tell Cursor we are going to call position() and rnd_pos() later.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
424
1 by brian
clean slate
425
  NOTES:
426
  This is needed for handlers that uses the primary key to find the
427
  row. In this case we have to extend the read bitmap with the primary
428
  key fields.
429
*/
430
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
431
void Table::prepare_for_position()
1 by brian
clean slate
432
{
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
433
1233.1.4 by Brian Aker
Added:
434
  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
1827.2.2 by Brian Aker
Encapsulate the share in Table.
435
      getShare()->hasPrimaryKey())
1 by brian
clean slate
436
  {
1827.2.2 by Brian Aker
Encapsulate the share in Table.
437
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
1 by brian
clean slate
438
  }
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
439
  return;
1 by brian
clean slate
440
}
441
442
443
/*
444
  Mark that only fields from one key is used
445
446
  NOTE:
447
    This changes the bitmap to use the tmp bitmap
448
    After this, you can't access any other columns in the table until
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
449
    bitmaps are reset, for example with Table::clear_column_bitmaps()
450
    or Table::restore_column_maps_after_mark_index()
1 by brian
clean slate
451
*/
452
482 by Brian Aker
Remove uint.
453
void Table::mark_columns_used_by_index(uint32_t index)
1 by brian
clean slate
454
{
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
455
  boost::dynamic_bitset<> *bitmap= &tmp_set;
1 by brian
clean slate
456
1208.3.2 by brian
Update for Cursor renaming.
457
  (void) cursor->extra(HA_EXTRA_KEYREAD);
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
458
  bitmap->reset();
459
  mark_columns_used_by_index_no_reset(index, *bitmap);
460
  column_bitmaps_set(*bitmap, *bitmap);
51.1.1 by Jay Pipes
Merged PatG's removal of various DBUG stuff with still keeping DBUG_ASSERT calls since they seem to be breaking test runs
461
  return;
1 by brian
clean slate
462
}
463
464
465
/*
466
  Restore to use normal column maps after key read
467
468
  NOTES
469
    This reverse the change done by mark_columns_used_by_index
470
471
  WARNING
472
    For this to work, one must have the normal table maps in place
473
    when calling mark_columns_used_by_index
474
*/
475
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
476
void Table::restore_column_maps_after_mark_index()
1 by brian
clean slate
477
{
478
479
  key_read= 0;
1208.3.2 by brian
Update for Cursor renaming.
480
  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
1 by brian
clean slate
481
  default_column_bitmaps();
1005.2.1 by Monty Taylor
Reverted a crap-ton of padraig's work.
482
  return;
1 by brian
clean slate
483
}
484
485
486
/*
487
  mark columns used by key, but don't reset other fields
488
*/
489
1003.1.7 by Brian Aker
Add mark_columns_used_by_index_no_reset() with just index (assumes read_set
490
void Table::mark_columns_used_by_index_no_reset(uint32_t index)
491
{
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
492
    mark_columns_used_by_index_no_reset(index, *read_set);
1003.1.7 by Brian Aker
Add mark_columns_used_by_index_no_reset() with just index (assumes read_set
493
}
494
1 by brian
clean slate
495
1802.16.1 by Padraig O'Sullivan
Replaced one instance of MyBitmap with dynamic_bitset from boost. Added some utility functions to MyBitmap temporarily in order to accomplish this.
496
void Table::mark_columns_used_by_index_no_reset(uint32_t index,
497
                                                boost::dynamic_bitset<>& bitmap)
498
{
499
  KeyPartInfo *key_part= key_info[index].key_part;
500
  KeyPartInfo *key_part_end= (key_part + key_info[index].key_parts);
501
  for (; key_part != key_part_end; key_part++)
502
  {
503
    if (! bitmap.empty())
504
      bitmap.set(key_part->fieldnr-1);
505
  }
506
}
507
508
1 by brian
clean slate
509
/*
510
  Mark auto-increment fields as used fields in both read and write maps
511
512
  NOTES
513
    This is needed in insert & update as the auto-increment field is
514
    always set and sometimes read.
515
*/
516
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
517
void Table::mark_auto_increment_column()
1 by brian
clean slate
518
{
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
519
  assert(found_next_number_field);
1 by brian
clean slate
520
  /*
521
    We must set bit in read set as update_auto_increment() is using the
522
    store() to check overflow of auto_increment values
523
  */
1005.2.12 by Monty Taylor
Moved some things to the API.
524
  setReadSet(found_next_number_field->field_index);
525
  setWriteSet(found_next_number_field->field_index);
1827.2.2 by Brian Aker
Encapsulate the share in Table.
526
  if (getShare()->next_number_keypart)
527
    mark_columns_used_by_index_no_reset(getShare()->next_number_index);
1 by brian
clean slate
528
}
529
530
531
/*
532
  Mark columns needed for doing an delete of a row
533
534
  DESCRIPTON
535
    Some table engines don't have a cursor on the retrieve rows
536
    so they need either to use the primary key or all columns to
537
    be able to delete a row.
538
539
    If the engine needs this, the function works as follows:
540
    - If primary key exits, mark the primary key columns to be read.
541
    - If not, mark all columns to be read
542
543
    If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
544
    mark all key columns as 'to-be-read'. This allows the engine to
545
    loop over the given record to find all keys and doesn't have to
546
    retrieve the row again.
547
*/
548
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
549
void Table::mark_columns_needed_for_delete()
1 by brian
clean slate
550
{
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
551
  /*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
552
    If the Cursor has no cursor capabilites, or we have row-based
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
553
    replication active for the current statement, we have to read
554
    either the primary key, the hidden primary key or all columns to
555
    be able to do an delete
556
557
  */
1827.2.2 by Brian Aker
Encapsulate the share in Table.
558
  if (not getShare()->hasPrimaryKey())
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
559
  {
560
    /* fallback to use all columns in the table to identify row */
561
    use_all_columns();
562
    return;
563
  }
564
  else
1827.2.2 by Brian Aker
Encapsulate the share in Table.
565
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
566
567
  /* If we the engine wants all predicates we mark all keys */
1233.1.7 by Brian Aker
Final table flag removal.
568
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
1 by brian
clean slate
569
  {
570
    Field **reg_field;
571
    for (reg_field= field ; *reg_field ; reg_field++)
572
    {
573
      if ((*reg_field)->flags & PART_KEY_FLAG)
1005.2.12 by Monty Taylor
Moved some things to the API.
574
        setReadSet((*reg_field)->field_index);
1 by brian
clean slate
575
    }
576
  }
577
}
578
579
580
/*
581
  Mark columns needed for doing an update of a row
582
583
  DESCRIPTON
584
    Some engines needs to have all columns in an update (to be able to
585
    build a complete row). If this is the case, we mark all not
586
    updated columns to be read.
587
588
    If this is no the case, we do like in the delete case and mark
589
    if neeed, either the primary key column or all columns to be read.
590
    (see mark_columns_needed_for_delete() for details)
591
1233.1.7 by Brian Aker
Final table flag removal.
592
    If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
1 by brian
clean slate
593
    mark all USED key columns as 'to-be-read'. This allows the engine to
594
    loop over the given record to find all changed keys and doesn't have to
595
    retrieve the row again.
596
*/
597
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
598
void Table::mark_columns_needed_for_update()
1 by brian
clean slate
599
{
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
600
  /*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
601
    If the Cursor has no cursor capabilites, or we have row-based
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
602
    logging active for the current statement, we have to read either
603
    the primary key, the hidden primary key or all columns to be
604
    able to do an update
605
  */
1827.2.2 by Brian Aker
Encapsulate the share in Table.
606
  if (not getShare()->hasPrimaryKey())
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
607
  {
608
    /* fallback to use all columns in the table to identify row */
609
    use_all_columns();
610
    return;
611
  }
612
  else
1827.2.2 by Brian Aker
Encapsulate the share in Table.
613
    mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
1003.1.8 by Brian Aker
The call for setting columns was backwards (engines with certain callers
614
1233.1.7 by Brian Aker
Final table flag removal.
615
  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
1 by brian
clean slate
616
  {
617
    /* Mark all used key columns for read */
618
    Field **reg_field;
619
    for (reg_field= field ; *reg_field ; reg_field++)
620
    {
621
      /* Merge keys is all keys that had a column refered to in the query */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
622
      if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
1005.2.12 by Monty Taylor
Moved some things to the API.
623
        setReadSet((*reg_field)->field_index);
1 by brian
clean slate
624
    }
625
  }
798.2.21 by Brian Aker
More work on binlog.poen
626
1 by brian
clean slate
627
}
628
629
630
/*
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
631
  Mark columns the Cursor needs for doing an insert
1 by brian
clean slate
632
633
  For now, this is used to mark fields used by the trigger
634
  as changed.
635
*/
636
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
637
void Table::mark_columns_needed_for_insert()
1 by brian
clean slate
638
{
639
  if (found_next_number_field)
640
    mark_auto_increment_column();
383.7.1 by Andrey Zhakov
Initial submit of code and tests
641
}
642
1 by brian
clean slate
643
644
481 by Brian Aker
Remove all of uchar.
645
size_t Table::max_row_length(const unsigned char *data)
1 by brian
clean slate
646
{
354 by Brian Aker
Refactor of Table methods.
647
  size_t length= getRecordLength() + 2 * sizeFields();
482 by Brian Aker
Remove uint.
648
  uint32_t *const beg= getBlobField();
649
  uint32_t *const end= beg + sizeBlobFields();
1 by brian
clean slate
650
482 by Brian Aker
Remove uint.
651
  for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
1 by brian
clean slate
652
  {
354 by Brian Aker
Refactor of Table methods.
653
    Field_blob* const blob= (Field_blob*) field[*ptr];
481 by Brian Aker
Remove all of uchar.
654
    length+= blob->get_length((const unsigned char*)
1672.3.6 by Brian Aker
First pass in encapsulating row
655
                              (data + blob->offset(getInsertRecord()))) +
1 by brian
clean slate
656
      HA_KEY_BLOB_LENGTH;
657
  }
658
  return length;
659
}
660
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
661
void Table::setVariableWidth(void)
662
{
663
  assert(in_use);
664
  if (in_use && in_use->lex->sql_command == SQLCOM_CREATE_TABLE)
665
  {
666
    getMutableShare()->setVariableWidth();
667
    return;
668
  }
669
670
  assert(0); // Programming error, you can't set this on a plain old Table.
671
}
672
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
673
/****************************************************************************
674
 Functions for creating temporary tables.
675
****************************************************************************/
676
/**
677
  Create field for temporary table from given field.
678
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
679
  @param session	       Thread Cursor
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
680
  @param org_field    field from which new field will be created
681
  @param name         New field name
682
  @param table	       Temporary table
683
  @param item	       !=NULL if item->result_field should point to new field.
684
                      This is relevant for how fill_record() is going to work:
685
                      If item != NULL then fill_record() will update
686
                      the record in the original table.
687
                      If item == NULL then fill_record() will update
688
                      the temporary table
689
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
690
                               field instead of blob.
691
692
  @retval
693
    NULL		on error
694
  @retval
695
    new_created field
696
*/
697
520.1.22 by Brian Aker
Second pass of thd cleanup
698
Field *create_tmp_field_from_field(Session *session, Field *org_field,
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
699
                                   const char *name, Table *table,
482 by Brian Aker
Remove uint.
700
                                   Item_field *item, uint32_t convert_blob_length)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
701
{
702
  Field *new_field;
703
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
704
  /*
705
    Make sure that the blob fits into a Field_varstring which has
706
    2-byte lenght.
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
707
  */
708
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
709
      (org_field->flags & BLOB_FLAG))
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
710
  {
711
    table->setVariableWidth();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
712
    new_field= new Field_varstring(convert_blob_length,
713
                                   org_field->maybe_null(),
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
714
                                   org_field->field_name,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
715
                                   org_field->charset());
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
716
  }
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
717
  else
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
718
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
719
    new_field= org_field->new_field(session->mem_root, table,
1660.1.3 by Brian Aker
Encapsulate Table in field
720
                                    table == org_field->getTable());
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
721
  }
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
722
  if (new_field)
723
  {
724
    new_field->init(table);
725
    new_field->orig_table= org_field->orig_table;
726
    if (item)
727
      item->result_field= new_field;
728
    else
729
      new_field->field_name= name;
730
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
731
    if (org_field->maybe_null() || (item && item->maybe_null))
732
      new_field->flags&= ~NOT_NULL_FLAG;	// Because of outer join
733
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
1574 by Brian Aker
Rollup patch for hiding tableshare.
734
      table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
735
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
736
      ((Field_double *) new_field)->not_fixed= true;
737
  }
738
  return new_field;
739
}
740
741
742
/**
743
  Create a temp table according to a field list.
744
745
  Given field pointers are changed to point at tmp_table for
746
  send_fields. The table object is self contained: it's
747
  allocated in its own memory root, as well as Field objects
748
  created for table columns.
749
  This function will replace Item_sum items in 'fields' list with
750
  corresponding Item_field items, pointing at the fields in the
751
  temporary table, unless this was prohibited by true
752
  value of argument save_sum_fields. The Item_field objects
520.1.21 by Brian Aker
THD -> Session rename
753
  are created in Session memory root.
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
754
520.1.22 by Brian Aker
Second pass of thd cleanup
755
  @param session                  thread handle
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
756
  @param param                a description used as input to create the table
757
  @param fields               list of items that will be used to define
758
                              column types of the table (also see NOTES)
759
  @param group                TODO document
760
  @param distinct             should table rows be distinct
761
  @param save_sum_fields      see NOTES
762
  @param select_options
763
  @param rows_limit
764
  @param table_alias          possible name of the temporary table that can
765
                              be used for name resolving; can be "".
766
*/
767
768
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
769
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
770
#define RATIO_TO_PACK_ROWS	       2
771
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
772
Table *
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
773
create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
1892.3.3 by tdavies
struct order_st changed and renamed to c++ class named:Order
774
		 Order *group, bool distinct, bool save_sum_fields,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
775
		 uint64_t select_options, ha_rows rows_limit,
1039.1.4 by Brian Aker
Modified alias to being const.
776
		 const char *table_alias)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
777
{
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
778
  memory::Root *mem_root_save;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
779
  uint	i,field_count,null_count,null_pack_length;
482 by Brian Aker
Remove uint.
780
  uint32_t  copy_func_count= param->func_count;
781
  uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
782
  uint32_t  blob_count,group_null_items, string_count;
783
  uint32_t fieldnr= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
784
  ulong reclength, string_total_length;
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
785
  bool  using_unique_constraint= false;
786
  bool  use_packed_rows= true;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
787
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
788
  unsigned char	*pos, *group_buff;
481 by Brian Aker
Remove all of uchar.
789
  unsigned char *null_flags;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
790
  Field **reg_field, **from_field, **default_field;
1052.2.2 by Nathan Williams
No actual code changes. Changed Copy_field to CopyField, to reflect the coding standards.
791
  CopyField *copy= 0;
1535 by Brian Aker
Rename of KEY to KeyInfo
792
  KeyInfo *keyinfo;
1534 by Brian Aker
Remove of KeyPartInfo
793
  KeyPartInfo *key_part_info;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
794
  Item **copy_func;
795
  MI_COLUMNDEF *recinfo;
482 by Brian Aker
Remove uint.
796
  uint32_t total_uneven_bit_length= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
797
  bool force_copy_fields= param->force_copy_fields;
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
798
  uint64_t max_rows= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
799
1689.5.1 by Joseph Daly
remove increment calls
800
  session->status_var.created_tmp_tables++;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
801
802
  if (group)
803
  {
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
804
    if (! param->quick_group)
1487.1.1 by Brian Aker
There is room for improvement around this. We should be using rows as well
805
    {
1046.1.6 by Brian Aker
Formatting/style cleanup.
806
      group= 0;					// Can't use group key
1487.1.1 by Brian Aker
There is room for improvement around this. We should be using rows as well
807
    }
1892.3.3 by tdavies
struct order_st changed and renamed to c++ class named:Order
808
    else for (Order *tmp=group ; tmp ; tmp=tmp->next)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
809
    {
810
      /*
811
        marker == 4 means two things:
812
        - store NULLs in the key, and
813
        - convert BIT fields to 64-bit long, needed because MEMORY tables
814
          can't index BIT fields.
815
      */
816
      (*tmp->item)->marker= 4;
817
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
818
	using_unique_constraint= true;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
819
    }
820
    if (param->group_length >= MAX_BLOB_WIDTH)
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
821
      using_unique_constraint= true;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
822
    if (group)
1046.1.6 by Brian Aker
Formatting/style cleanup.
823
      distinct= 0;				// Can't use distinct
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
824
  }
825
826
  field_count=param->field_count+param->func_count+param->sum_func_count;
827
  hidden_field_count=param->hidden_field_count;
828
829
  /*
830
    When loose index scan is employed as access method, it already
831
    computes all groups and the result of all aggregate functions. We
832
    make space for the items of the aggregate function in the list of
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
833
    functions Tmp_Table_Param::items_to_copy, so that the values of
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
834
    these items are stored in the temporary table.
835
  */
836
  if (param->precomputed_group_by)
1532.1.7 by Brian Aker
Fix for non-portable vastart usage.
837
  {
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
838
    copy_func_count+= param->sum_func_count;
1532.1.7 by Brian Aker
Fix for non-portable vastart usage.
839
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
840
1843.8.4 by Brian Aker
Committing refactor of table out (this is part of the concurrency work).
841
  table::Instance *table;
1843.8.5 by Brian Aker
Added concurrent type.
842
  table= session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
843
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
844
  if (not table->getMemRoot()->multi_alloc_root(0,
1532.1.7 by Brian Aker
Fix for non-portable vastart usage.
845
                                                &default_field, sizeof(Field*) * (field_count),
846
                                                &from_field, sizeof(Field*)*field_count,
847
                                                &copy_func, sizeof(*copy_func)*(copy_func_count+1),
848
                                                &param->keyinfo, sizeof(*param->keyinfo),
849
                                                &key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
850
                                                &param->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
851
                                                &group_buff, (group && ! using_unique_constraint ?
852
                                                              param->group_length : 0),
853
                                                NULL))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
854
  {
971.6.11 by Eric Day
Removed purecov messages.
855
    return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
856
  }
1052.2.2 by Nathan Williams
No actual code changes. Changed Copy_field to CopyField, to reflect the coding standards.
857
  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
858
  if (!(param->copy_field= copy= new (session->mem_root) CopyField[field_count]))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
859
  {
971.6.11 by Eric Day
Removed purecov messages.
860
    return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
861
  }
862
  param->items_to_copy= copy_func;
863
  /* make table according to fields */
864
865
  memset(default_field, 0, sizeof(Field*) * (field_count));
866
  memset(from_field, 0, sizeof(Field*)*field_count);
867
520.1.22 by Brian Aker
Second pass of thd cleanup
868
  mem_root_save= session->mem_root;
1532.1.10 by Brian Aker
Encapsulation of mem_root for session/this switches the creation of new_path
869
  session->mem_root= table->getMemRoot();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
870
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
871
  table->getMutableShare()->setFields(field_count+1);
872
  table->setFields(table->getMutableShare()->getFields(true));
873
  reg_field= table->getMutableShare()->getFields(true);
1864.4.4 by Brian Aker
We now handle the free of the alias inside of table.
874
  table->setAlias(table_alias);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
875
  table->reginfo.lock_type=TL_WRITE;	/* Will be updated */
876
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
877
  table->map=1;
878
  table->copy_blobs= 1;
1578.6.2 by Brian Aker
Remove ha_session.
879
  assert(session);
520.1.22 by Brian Aker
Second pass of thd cleanup
880
  table->in_use= session;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
881
  table->quick_keys.reset();
882
  table->covering_keys.reset();
883
  table->keys_in_use_for_query.reset();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
884
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
885
  table->getMutableShare()->blob_field.resize(field_count+1);
886
  uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
887
  table->getMutableShare()->blob_ptr_size= portable_sizeof_char_ptr;
888
  table->getMutableShare()->db_low_byte_first=1;                // True for HEAP and MyISAM
889
  table->getMutableShare()->table_charset= param->table_charset;
890
  table->getMutableShare()->keys_for_keyread.reset();
891
  table->getMutableShare()->keys_in_use.reset();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
892
893
  /* Calculate which type of fields we will store in the temporary table */
894
895
  reclength= string_total_length= 0;
896
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
1046.1.6 by Brian Aker
Formatting/style cleanup.
897
  param->using_indirect_summary_function= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
898
899
  List_iterator_fast<Item> li(fields);
900
  Item *item;
901
  Field **tmp_from_field=from_field;
902
  while ((item=li++))
903
  {
904
    Item::Type type=item->type();
905
    if (not_all_columns)
906
    {
907
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
908
      {
909
        if (item->used_tables() & OUTER_REF_TABLE_BIT)
910
          item->update_used_tables();
911
        if (type == Item::SUBSELECT_ITEM ||
912
            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
913
        {
914
	  /*
915
	    Mark that the we have ignored an item that refers to a summary
916
	    function. We need to know this if someone is going to use
917
	    DISTINCT on the result.
918
	  */
919
	  param->using_indirect_summary_function=1;
920
	  continue;
921
        }
922
      }
923
      if (item->const_item() && (int) hidden_field_count <= 0)
924
        continue; // We don't have to store this
925
    }
926
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
927
    {						/* Can't calc group yet */
1046.1.6 by Brian Aker
Formatting/style cleanup.
928
      ((Item_sum*) item)->result_field= 0;
929
      for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
930
      {
931
	Item **argp= ((Item_sum*) item)->args + i;
932
	Item *arg= *argp;
933
	if (!arg->const_item())
934
	{
935
	  Field *new_field=
520.1.22 by Brian Aker
Second pass of thd cleanup
936
            create_tmp_field(session, table, arg, arg->type(), &copy_func,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
937
                             tmp_from_field, &default_field[fieldnr],
938
                             group != 0,not_all_columns,
1273.2.4 by Stewart Smith
remove unused parameter to create_tmp_field() - was table_cant_handle_bit_fields which was around for HEAP based temp tables.
939
                             false,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
940
                             param->convert_blob_length);
941
	  if (!new_field)
942
	    goto err;					// Should be OOM
943
	  tmp_from_field++;
944
	  reclength+=new_field->pack_length();
945
	  if (new_field->flags & BLOB_FLAG)
946
	  {
947
	    *blob_field++= fieldnr;
948
	    blob_count++;
949
	  }
950
	  *(reg_field++)= new_field;
951
          if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
952
          {
953
            string_count++;
954
            string_total_length+= new_field->pack_length();
955
          }
520.1.22 by Brian Aker
Second pass of thd cleanup
956
          session->mem_root= mem_root_save;
957
          session->change_item_tree(argp, new Item_field(new_field));
1532.1.15 by Brian Aker
Partial encapsulation of TableShare from Table.
958
          session->mem_root= table->getMemRoot();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
959
	  if (!(new_field->flags & NOT_NULL_FLAG))
960
          {
961
	    null_count++;
962
            /*
963
              new_field->maybe_null() is still false, it will be
964
              changed below. But we have to setup Item_field correctly
965
            */
966
            (*argp)->maybe_null=1;
967
          }
968
          new_field->field_index= fieldnr++;
969
	}
970
      }
971
    }
972
    else
973
    {
974
      /*
975
	The last parameter to create_tmp_field() is a bit tricky:
976
977
	We need to set it to 0 in union, to get fill_record() to modify the
978
	temporary table.
979
	We need to set it to 1 on multi-table-update and in select to
980
	write rows to the temporary table.
981
	We here distinguish between UNION and multi-table-updates by the fact
982
	that in the later case group is set to the row pointer.
983
      */
1273.2.4 by Stewart Smith
remove unused parameter to create_tmp_field() - was table_cant_handle_bit_fields which was around for HEAP based temp tables.
984
      Field *new_field=
520.1.22 by Brian Aker
Second pass of thd cleanup
985
        create_tmp_field(session, table, item, type, &copy_func,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
986
                         tmp_from_field, &default_field[fieldnr],
987
                         group != 0,
988
                         !force_copy_fields &&
1046.1.6 by Brian Aker
Formatting/style cleanup.
989
                           (not_all_columns || group != 0),
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
990
                         force_copy_fields,
991
                         param->convert_blob_length);
992
993
      if (!new_field)
994
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
995
	if (session->is_fatal_error)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
996
	  goto err;				// Got OOM
997
	continue;				// Some kindf of const item
998
      }
999
      if (type == Item::SUM_FUNC_ITEM)
1000
	((Item_sum *) item)->result_field= new_field;
1001
      tmp_from_field++;
1002
      reclength+=new_field->pack_length();
1003
      if (!(new_field->flags & NOT_NULL_FLAG))
1004
	null_count++;
1005
      if (new_field->flags & BLOB_FLAG)
1006
      {
1007
        *blob_field++= fieldnr;
1008
	blob_count++;
1009
      }
1010
      if (item->marker == 4 && item->maybe_null)
1011
      {
1012
	group_null_items++;
1013
	new_field->flags|= GROUP_FLAG;
1014
      }
1015
      new_field->field_index= fieldnr++;
1016
      *(reg_field++)= new_field;
1017
    }
1018
    if (!--hidden_field_count)
1019
    {
1020
      /*
1021
        This was the last hidden field; Remember how many hidden fields could
1022
        have null
1023
      */
1024
      hidden_null_count=null_count;
1025
      /*
1026
	We need to update hidden_field_count as we may have stored group
1027
	functions with constant arguments
1028
      */
1029
      param->hidden_field_count= fieldnr;
1030
      null_count= 0;
1031
    }
1032
  }
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1033
  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
1034
  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1035
  field_count= fieldnr;
1036
  *reg_field= 0;
1037
  *blob_field= 0;				// End marker
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1038
  table->getMutableShare()->fields= field_count;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1039
1040
  /* If result table is small; use a heap */
1041
  /* future: storage engine selection can be made dynamic? */
1487.1.1 by Brian Aker
There is room for improvement around this. We should be using rows as well
1042
  if (blob_count || using_unique_constraint || 
1043
      (session->lex->select_lex.options & SELECT_BIG_RESULT) ||
1044
      (session->lex->current_select->olap == ROLLUP_TYPE) ||
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
1045
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1046
  {
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1047
    table->getMutableShare()->storage_engine= myisam_engine;
1869.1.4 by Brian Aker
TableShare is no longer in the house (i.e. we no longer directly have a copy
1048
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1049
    if (group &&
1233.1.9 by Brian Aker
Move max key stuff up to engine.
1050
	(param->group_parts > table->cursor->getEngine()->max_key_parts() ||
1051
	 param->group_length > table->cursor->getEngine()->max_key_length()))
1487.1.1 by Brian Aker
There is room for improvement around this. We should be using rows as well
1052
    {
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
1053
      using_unique_constraint= true;
1487.1.1 by Brian Aker
There is room for improvement around this. We should be using rows as well
1054
    }
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1055
  }
1056
  else
1057
  {
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1058
    table->getMutableShare()->storage_engine= heap_engine;
1869.1.4 by Brian Aker
TableShare is no longer in the house (i.e. we no longer directly have a copy
1059
    table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1060
  }
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
1061
  if (! table->cursor)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1062
    goto err;
1063
1064
1277.2.1 by Brian Aker
Remove open tables, other assorted code bits (cleanup on style)
1065
  if (! using_unique_constraint)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1066
    reclength+= group_null_items;	// null flag is stored separately
1067
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1068
  table->getMutableShare()->blob_fields= blob_count;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1069
  if (blob_count == 0)
1070
  {
1071
    /* We need to ensure that first byte is not 0 for the delete link */
1072
    if (param->hidden_field_count)
1073
      hidden_null_count++;
1074
    else
1075
      null_count++;
1076
  }
1077
  hidden_null_pack_length=(hidden_null_count+7)/8;
1078
  null_pack_length= (hidden_null_pack_length +
1079
                     (null_count + total_uneven_bit_length + 7) / 8);
1080
  reclength+=null_pack_length;
1081
  if (!reclength)
1082
    reclength=1;				// Dummy select
1083
  /* Use packed rows if there is blobs or a lot of space to gain */
1084
  if (blob_count || ((string_total_length >= STRING_TOTAL_LENGTH_TO_PACK_ROWS) && (reclength / string_total_length <= RATIO_TO_PACK_ROWS || (string_total_length / string_count) >= AVG_STRING_LENGTH_TO_PACK_ROWS)))
1085
    use_packed_rows= 1;
1086
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1087
  table->getMutableShare()->setRecordLength(reclength);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1088
  {
482 by Brian Aker
Remove uint.
1089
    uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1090
    table->getMutableShare()->rec_buff_length= alloc_length;
1672.3.6 by Brian Aker
First pass in encapsulating row
1091
    if (!(table->record[0]= (unsigned char*) table->alloc_root(alloc_length*2)))
1485 by Brian Aker
Updates to confine memroot
1092
    {
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1093
      goto err;
1485 by Brian Aker
Updates to confine memroot
1094
    }
1672.3.6 by Brian Aker
First pass in encapsulating row
1095
    table->record[1]= table->getInsertRecord()+alloc_length;
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1096
    table->getMutableShare()->resizeDefaultValues(alloc_length);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1097
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
1098
  copy_func[0]= 0;				// End marker
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1099
  param->func_count= copy_func - param->items_to_copy;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1100
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1101
  table->setup_tmp_table_column_bitmaps();
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1102
1103
  recinfo=param->start_recinfo;
1672.3.6 by Brian Aker
First pass in encapsulating row
1104
  null_flags=(unsigned char*) table->getInsertRecord();
1105
  pos=table->getInsertRecord()+ null_pack_length;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1106
  if (null_pack_length)
1107
  {
1108
    memset(recinfo, 0, sizeof(*recinfo));
1109
    recinfo->type=FIELD_NORMAL;
1110
    recinfo->length=null_pack_length;
1111
    recinfo++;
1112
    memset(null_flags, 255, null_pack_length);	// Set null fields
1113
1672.3.6 by Brian Aker
First pass in encapsulating row
1114
    table->null_flags= (unsigned char*) table->getInsertRecord();
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1115
    table->getMutableShare()->null_fields= null_count+ hidden_null_count;
1116
    table->getMutableShare()->null_bytes= null_pack_length;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1117
  }
1118
  null_count= (blob_count == 0) ? 1 : 0;
1119
  hidden_field_count=param->hidden_field_count;
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1120
  for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1121
  {
1122
    Field *field= *reg_field;
482 by Brian Aker
Remove uint.
1123
    uint32_t length;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1124
    memset(recinfo, 0, sizeof(*recinfo));
1125
1126
    if (!(field->flags & NOT_NULL_FLAG))
1127
    {
1128
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
1129
      {
1130
	/*
1131
	  We have to reserve one byte here for NULL bits,
1132
	  as this is updated by 'end_update()'
1133
	*/
1063.5.1 by Patrick
Fix for Centos 5.2
1134
	*pos++= '\0';				// Null is stored here
1046.1.6 by Brian Aker
Formatting/style cleanup.
1135
	recinfo->length= 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1136
	recinfo->type=FIELD_NORMAL;
1137
	recinfo++;
1138
	memset(recinfo, 0, sizeof(*recinfo));
1139
      }
1140
      else
1141
      {
1142
	recinfo->null_bit= 1 << (null_count & 7);
1143
	recinfo->null_pos= null_count/8;
1144
      }
1145
      field->move_field(pos,null_flags+null_count/8,
1146
			1 << (null_count & 7));
1147
      null_count++;
1148
    }
1149
    else
481 by Brian Aker
Remove all of uchar.
1150
      field->move_field(pos,(unsigned char*) 0,0);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1151
    field->reset();
1152
1153
    /*
1154
      Test if there is a default field value. The test for ->ptr is to skip
1155
      'offset' fields generated by initalize_tables
1156
    */
1157
    if (default_field[i] && default_field[i]->ptr)
1158
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1159
      /*
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1160
         default_field[i] is set only in the cases  when 'field' can
1161
         inherit the default value that is defined for the field referred
1162
         by the Item_field object from which 'field' has been created.
1163
      */
1122.2.12 by Monty Taylor
Removed the silly my_ptrdiff_t typedef.
1164
      ptrdiff_t diff;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1165
      Field *orig_field= default_field[i];
1166
      /* Get the value from default_values */
1672.3.6 by Brian Aker
First pass in encapsulating row
1167
      diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1168
      orig_field->move_field_offset(diff);      // Points now at default_values
1169
      if (orig_field->is_real_null())
1170
        field->set_null();
1171
      else
1172
      {
1173
        field->set_notnull();
1174
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
1175
      }
1672.3.6 by Brian Aker
First pass in encapsulating row
1176
      orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1177
    }
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1178
1179
    if (from_field[i])
1180
    {						/* Not a table Item */
1181
      copy->set(field,from_field[i],save_sum_fields);
1182
      copy++;
1183
    }
1184
    length=field->pack_length();
1185
    pos+= length;
1186
1187
    /* Make entry for create table */
1188
    recinfo->length=length;
1189
    if (field->flags & BLOB_FLAG)
1190
      recinfo->type= (int) FIELD_BLOB;
1191
    else
1192
      recinfo->type=FIELD_NORMAL;
1193
    if (!--hidden_field_count)
1194
      null_count=(null_count+7) & ~7;		// move to next byte
1195
  }
1196
1197
  param->copy_field_end=copy;
1198
  param->recinfo=recinfo;
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1199
  table->storeRecordAsDefault();        // Make empty default record
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1200
520.1.22 by Brian Aker
Second pass of thd cleanup
1201
  if (session->variables.tmp_table_size == ~ (uint64_t) 0)		// No limit
1578.2.8 by Brian Aker
Encapsulate record length.
1202
  {
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
1203
    max_rows= ~(uint64_t) 0;
1578.2.8 by Brian Aker
Encapsulate record length.
1204
  }
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1205
  else
1578.2.8 by Brian Aker
Encapsulate record length.
1206
  {
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1207
    max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
1578.2.8 by Brian Aker
Encapsulate record length.
1208
                           min(session->variables.tmp_table_size,
1209
                               session->variables.max_heap_table_size) :
1210
                           session->variables.tmp_table_size) /
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1211
                          table->getMutableShare()->getRecordLength());
1578.2.8 by Brian Aker
Encapsulate record length.
1212
  }
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
1213
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
1214
  set_if_bigger(max_rows, (uint64_t)1);	// For dummy start options
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1215
  /*
1216
    Push the LIMIT clause to the temporary table creation, so that we
1217
    materialize only up to 'rows_limit' records instead of all result records.
1218
  */
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
1219
  set_if_smaller(max_rows, rows_limit);
1220
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1221
  table->getMutableShare()->setMaxRows(max_rows);
1116.1.1 by Brian Aker
Fix for Stewart's patch (includes hack to solve MAX rows problem).
1222
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1223
  param->end_write_records= rows_limit;
1224
1225
  keyinfo= param->keyinfo;
1226
1227
  if (group)
1228
  {
1229
    table->group=group;				/* Table is grouped by key */
1230
    param->group_buff=group_buff;
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1231
    table->getMutableShare()->keys=1;
1232
    table->getMutableShare()->uniques= test(using_unique_constraint);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1233
    table->key_info=keyinfo;
1234
    keyinfo->key_part=key_part_info;
1235
    keyinfo->flags=HA_NOSAME;
1236
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
1046.1.6 by Brian Aker
Formatting/style cleanup.
1237
    keyinfo->key_length= 0;
1238
    keyinfo->rec_per_key= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1239
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1240
    keyinfo->name= (char*) "group_key";
1892.3.3 by tdavies
struct order_st changed and renamed to c++ class named:Order
1241
    Order *cur_group= group;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1242
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1243
    {
1244
      Field *field=(*cur_group->item)->get_tmp_table_field();
1245
      bool maybe_null=(*cur_group->item)->maybe_null;
1046.1.6 by Brian Aker
Formatting/style cleanup.
1246
      key_part_info->null_bit= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1247
      key_part_info->field=  field;
1672.3.6 by Brian Aker
First pass in encapsulating row
1248
      key_part_info->offset= field->offset(table->getInsertRecord());
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1249
      key_part_info->length= (uint16_t) field->key_length();
1250
      key_part_info->type=   (uint8_t) field->key_type();
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
1251
      key_part_info->key_type= 
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1252
	((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1253
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1254
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
1255
	0 : 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1256
      if (!using_unique_constraint)
1257
      {
1258
	cur_group->buff=(char*) group_buff;
520.1.22 by Brian Aker
Second pass of thd cleanup
1259
	if (!(cur_group->field= field->new_key_field(session->mem_root,table,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1260
                                                     group_buff +
1261
                                                     test(maybe_null),
1262
                                                     field->null_ptr,
1263
                                                     field->null_bit)))
971.6.11 by Eric Day
Removed purecov messages.
1264
	  goto err;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1265
	if (maybe_null)
1266
	{
1267
	  /*
1268
	    To be able to group on NULL, we reserved place in group_buff
1269
	    for the NULL flag just before the column. (see above).
1270
	    The field data is after this flag.
1271
	    The NULL flag is updated in 'end_update()' and 'end_write()'
1272
	  */
1273
	  keyinfo->flags|= HA_NULL_ARE_EQUAL;	// def. that NULL == NULL
1274
	  key_part_info->null_bit=field->null_bit;
895 by Brian Aker
Completion (?) of uint conversion.
1275
	  key_part_info->null_offset= (uint32_t) (field->null_ptr -
1672.3.6 by Brian Aker
First pass in encapsulating row
1276
					      (unsigned char*) table->getInsertRecord());
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1277
          cur_group->buff++;                        // Pointer to field data
1278
	  group_buff++;                         // Skipp null flag
1279
	}
1280
        /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
1281
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
1282
	group_buff+= cur_group->field->pack_length();
1283
      }
1284
      keyinfo->key_length+=  key_part_info->length;
1285
    }
1286
  }
1287
1288
  if (distinct && field_count != param->hidden_field_count)
1289
  {
1290
    /*
1291
      Create an unique key or an unique constraint over all columns
1292
      that should be in the result.  In the temporary table, there are
1293
      'param->hidden_field_count' extra columns, whose null bits are stored
1294
      in the first 'hidden_null_pack_length' bytes of the row.
1295
    */
1296
    if (blob_count)
1297
    {
1298
      /*
1299
        Special mode for index creation in MyISAM used to support unique
1300
        indexes on blobs with arbitrary length. Such indexes cannot be
1301
        used for lookups.
1302
      */
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1303
      table->getMutableShare()->uniques= 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1304
    }
1305
    null_pack_length-=hidden_null_pack_length;
1306
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1307
			 (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1308
    table->distinct= 1;
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1309
    table->getMutableShare()->keys= 1;
1534 by Brian Aker
Remove of KeyPartInfo
1310
    if (!(key_part_info= (KeyPartInfo*)
1532.1.8 by Brian Aker
Yet more movement/encapsulation of mem_root in table.
1311
         table->alloc_root(keyinfo->key_parts * sizeof(KeyPartInfo))))
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1312
      goto err;
1534 by Brian Aker
Remove of KeyPartInfo
1313
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1314
    table->key_info=keyinfo;
1315
    keyinfo->key_part=key_part_info;
1316
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
1317
    keyinfo->key_length=(uint16_t) reclength;
1318
    keyinfo->name= (char*) "distinct_key";
1319
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1046.1.6 by Brian Aker
Formatting/style cleanup.
1320
    keyinfo->rec_per_key= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1321
1322
    /*
1323
      Create an extra field to hold NULL bits so that unique indexes on
1324
      blobs can distinguish NULL from 0. This extra field is not needed
1325
      when we do not use UNIQUE indexes for blobs.
1326
    */
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1327
    if (null_pack_length && table->getMutableShare()->uniques)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1328
    {
1046.1.6 by Brian Aker
Formatting/style cleanup.
1329
      key_part_info->null_bit= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1330
      key_part_info->offset=hidden_null_pack_length;
1331
      key_part_info->length=null_pack_length;
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1332
      table->setVariableWidth();
1672.3.6 by Brian Aker
First pass in encapsulating row
1333
      key_part_info->field= new Field_varstring(table->getInsertRecord(),
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1334
                                                (uint32_t) key_part_info->length,
1335
                                                0,
481 by Brian Aker
Remove all of uchar.
1336
                                                (unsigned char*) 0,
895 by Brian Aker
Completion (?) of uint conversion.
1337
                                                (uint32_t) 0,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1338
                                                NULL,
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1339
                                                &my_charset_bin);
1340
      if (!key_part_info->field)
1341
        goto err;
1342
      key_part_info->field->init(table);
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
1343
      key_part_info->key_type= 1; /* binary comparison */
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1344
      key_part_info->type=    HA_KEYTYPE_BINARY;
1345
      key_part_info++;
1346
    }
1347
    /* Create a distinct key over the columns we are going to return */
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1348
    for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1349
	 i < field_count;
1350
	 i++, reg_field++, key_part_info++)
1351
    {
1046.1.6 by Brian Aker
Formatting/style cleanup.
1352
      key_part_info->null_bit= 0;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1353
      key_part_info->field=    *reg_field;
1672.3.6 by Brian Aker
First pass in encapsulating row
1354
      key_part_info->offset=   (*reg_field)->offset(table->getInsertRecord());
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1355
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
1672.3.4 by Brian Aker
This change the style on a few TODO, and fixes an error path to correctly
1356
      /* @todo The below method of computing the key format length of the
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
1357
        key part is a copy/paste from optimizer/range.cc, and table.cc.
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1358
        This should be factored out, e.g. as a method of Field.
1359
        In addition it is not clear if any of the Field::*_length
1360
        methods is supposed to compute the same length. If so, it
1361
        might be reused.
1362
      */
1363
      key_part_info->store_length= key_part_info->length;
1364
1365
      if ((*reg_field)->real_maybe_null())
1366
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1367
      if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1368
          (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
1369
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
1370
1371
      key_part_info->type=     (uint8_t) (*reg_field)->key_type();
1372
      key_part_info->key_type =
1373
	((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1374
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1375
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1119.9.7 by Jay Pipes
Removes FIELDFLAG_BINARY and the useless f_is_binary() macro.
1376
	0 : 1;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1377
    }
1378
  }
1379
520.1.22 by Brian Aker
Second pass of thd cleanup
1380
  if (session->is_fatal_error)				// If end of memory
971.6.11 by Eric Day
Removed purecov messages.
1381
    goto err;
1827.2.3 by Brian Aker
Switches table_share_instance to be a member of table, not table_share
1382
  table->getMutableShare()->db_record_offset= 1;
1835.1.5 by Brian Aker
Cleans up some spots where we were using mutable but did not need too.
1383
  if (table->getShare()->db_type() == myisam_engine)
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1384
  {
1385
    if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1386
				       &param->recinfo, select_options))
1387
      goto err;
1388
  }
1578.6.2 by Brian Aker
Remove ha_session.
1389
  assert(table->in_use);
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1390
  if (table->open_tmp_table())
1391
    goto err;
1392
520.1.22 by Brian Aker
Second pass of thd cleanup
1393
  session->mem_root= mem_root_save;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1394
1395
  return(table);
1396
1397
err:
520.1.22 by Brian Aker
Second pass of thd cleanup
1398
  session->mem_root= mem_root_save;
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
1399
  table= NULL;
1400
971.6.11 by Eric Day
Removed purecov messages.
1401
  return NULL;
327.1.2 by Brian Aker
Commiting next pass of Table class cleanup.
1402
}
1403
1404
/****************************************************************************/
1405
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
1406
void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
1407
                               boost::dynamic_bitset<>& write_set_arg)
1802.16.5 by Padraig O'Sullivan
Adding help method for dynamic bitset functions. Temporary until MyBitmap is removed. Got rid of another MyBitmap usage in the range optimizer.
1408
{
1802.16.9 by Padraig O'Sullivan
Resolved bitset handling during temporary table creation. All tests pass again.
1409
  read_set= &read_set_arg;
1410
  write_set= &write_set_arg;
1802.16.5 by Padraig O'Sullivan
Adding help method for dynamic bitset functions. Temporary until MyBitmap is removed. Got rid of another MyBitmap usage in the range optimizer.
1411
}
1412
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1413
1414
const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
354 by Brian Aker
Refactor of Table methods.
1415
{
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1416
  const boost::dynamic_bitset<> old= in_map;
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1417
  in_map= getShare()->all_set;
354 by Brian Aker
Refactor of Table methods.
1418
  return old;
1419
}
1420
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1421
void Table::restore_column_map(const boost::dynamic_bitset<>& old)
354 by Brian Aker
Refactor of Table methods.
1422
{
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1423
  for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
1424
  {
1425
    if (old.test(i))
1426
    {
1427
      read_set->set(i);
1428
    }
1429
    else
1430
    {
1431
      read_set->reset(i);
1432
    }
1433
  }
354 by Brian Aker
Refactor of Table methods.
1434
}
1435
482 by Brian Aker
Remove uint.
1436
uint32_t Table::find_shortest_key(const key_map *usable_keys)
355 by Brian Aker
More Table cleanup
1437
{
365.2.6 by Monty Taylor
Undid some stupid int->int16_t conversions.
1438
  uint32_t min_length= UINT32_MAX;
1439
  uint32_t best= MAX_KEY;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1440
  if (usable_keys->any())
355 by Brian Aker
More Table cleanup
1441
  {
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1442
    for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
355 by Brian Aker
More Table cleanup
1443
    {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1444
      if (usable_keys->test(nr))
355 by Brian Aker
More Table cleanup
1445
      {
1446
        if (key_info[nr].key_length < min_length)
1447
        {
1448
          min_length= key_info[nr].key_length;
1449
          best=nr;
1450
        }
1451
      }
1452
    }
1453
  }
1454
  return best;
1455
}
1456
1457
/*****************************************************************************
1458
  Remove duplicates from tmp table
1459
  This should be recoded to add a unique index to the table and remove
1460
  duplicates
1461
  Table is a locked single thread table
1462
  fields is the number of fields to check (from the end)
1463
*****************************************************************************/
1464
1465
bool Table::compare_record(Field **ptr)
1466
{
1467
  for (; *ptr ; ptr++)
1468
  {
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1469
    if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
355 by Brian Aker
More Table cleanup
1470
      return true;
1471
  }
1472
  return false;
1473
}
1474
1475
/* Return false if row hasn't changed */
1476
1477
bool Table::compare_record()
1478
{
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1479
  if (not getShare()->blob_fields + getShare()->hasVariableWidth())
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1480
    return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
1221.1.1 by Jay Pipes
Fixes some valgrind warnings regarding conditionals depending on unintialized variables. Use initializer lists properly, dang it. :) Also, removed the new_Cached_item() function's use_result_field, as this was only used for views and was producing a valgrind warning unnecessarily.
1481
  
355 by Brian Aker
More Table cleanup
1482
  /* Compare null bits */
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1483
  if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
1221.1.1 by Jay Pipes
Fixes some valgrind warnings regarding conditionals depending on unintialized variables. Use initializer lists properly, dang it. :) Also, removed the new_Cached_item() function's use_result_field, as this was only used for views and was producing a valgrind warning unnecessarily.
1484
    return true; /* Diff in NULL value */
1485
355 by Brian Aker
More Table cleanup
1486
  /* Compare updated fields */
1487
  for (Field **ptr= field ; *ptr ; ptr++)
1488
  {
1005.2.12 by Monty Taylor
Moved some things to the API.
1489
    if (isWriteSet((*ptr)->field_index) &&
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1490
	(*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
355 by Brian Aker
More Table cleanup
1491
      return true;
1492
  }
1493
  return false;
1494
}
1495
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1496
/*
1497
 * Store a record from previous record into next
1498
 *
1499
 */
1500
void Table::storeRecord()
1501
{
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1502
  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1503
}
1504
1505
/*
1506
 * Store a record as an insert
1507
 *
1508
 */
1509
void Table::storeRecordAsInsert()
1510
{
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1511
  assert(insert_values.size() >= getShare()->getRecordLength());
1512
  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1513
}
1514
1515
/*
1516
 * Store a record with default values
1517
 *
1518
 */
1519
void Table::storeRecordAsDefault()
1520
{
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1521
  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1522
}
1523
1524
/*
1525
 * Restore a record from previous record into next
1526
 *
1527
 */
1528
void Table::restoreRecord()
1529
{
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1530
  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1531
}
1532
1533
/*
1534
 * Restore a record with default values
1535
 *
1536
 */
1537
void Table::restoreRecordAsDefault()
1538
{
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1539
  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1540
}
1541
1542
/*
1543
 * Empty a record
1544
 *
1545
 */
1546
void Table::emptyRecord()
1547
{
997.5.2 by chris
Remove comments, do/while, spaces per Monty review
1548
  restoreRecordAsDefault();
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1549
  memset(null_flags, 255, getShare()->null_bytes);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1550
}
354 by Brian Aker
Refactor of Table methods.
1551
1532.1.2 by Brian Aker
Remove need for memset on Table object.
1552
Table::Table() : 
1553
  field(NULL),
1554
  cursor(NULL),
1555
  next(NULL),
1556
  prev(NULL),
1557
  read_set(NULL),
1558
  write_set(NULL),
1559
  tablenr(0),
1560
  db_stat(0),
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
1561
  def_read_set(),
1562
  def_write_set(),
1563
  tmp_set(),
1532.1.2 by Brian Aker
Remove need for memset on Table object.
1564
  in_use(NULL),
1565
  key_info(NULL),
1566
  next_number_field(NULL),
1567
  found_next_number_field(NULL),
1568
  timestamp_field(NULL),
1569
  pos_in_table_list(NULL),
1570
  group(NULL),
1571
  null_flags(NULL),
1572
  lock_position(0),
1573
  lock_data_start(0),
1574
  lock_count(0),
1575
  used_fields(0),
1576
  status(0),
1577
  derived_select_number(0),
1578
  current_lock(F_UNLCK),
1579
  copy_blobs(false),
1580
  maybe_null(false),
1581
  null_row(false),
1582
  force_index(false),
1583
  distinct(false),
1584
  const_table(false),
1585
  no_rows(false),
1586
  key_read(false),
1587
  no_keyread(false),
1588
  open_placeholder(false),
1589
  locked_by_name(false),
1590
  no_cache(false),
1591
  auto_increment_field_not_null(false),
1592
  alias_name_used(false),
1593
  query_id(0),
1594
  quick_condition_rows(0),
1595
  timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1843.7.2 by Brian Aker
Fix placeholder to actuall be a placeholder via methods.
1596
  map(0)
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
1597
{
1598
  record[0]= (unsigned char *) 0;
1599
  record[1]= (unsigned char *) 0;
1600
1532.1.2 by Brian Aker
Remove need for memset on Table object.
1601
  reginfo.reset();
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
1602
  covering_keys.reset();
1603
  quick_keys.reset();
1604
  merge_keys.reset();
1605
1606
  keys_in_use_for_query.reset();
1607
  keys_in_use_for_group_by.reset();
1608
  keys_in_use_for_order_by.reset();
1609
1273.1.1 by Jay Pipes
* Changes Session::warn_id to Session::warn_query_id
1610
  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
1241.9.1 by Monty Taylor
Removed global.h. Fixed all the headers.
1611
  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
1612
1613
  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
1614
  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
1615
}
1616
354 by Brian Aker
Refactor of Table methods.
1617
/*****************************************************************************
1618
  The different ways to read a record
1619
  Returns -1 if row was not found, 0 if row was found and 1 on errors
1620
*****************************************************************************/
1621
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1622
/** Help function when we get some an error from the table Cursor. */
354 by Brian Aker
Refactor of Table methods.
1623
1624
int Table::report_error(int error)
1625
{
1626
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
1627
  {
1628
    status= STATUS_GARBAGE;
1629
    return -1;					// key not found; ok
1630
  }
1631
  /*
1632
    Locking reads can legally return also these errors, do not
1633
    print them to the .err log
1634
  */
1635
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
755.2.1 by Mark Atwood
replace sql_print_error etc with errmsg_print
1636
    errmsg_printf(ERRMSG_LVL_ERROR, _("Got error %d when reading table '%s'"),
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1637
                  error, getShare()->getPath());
1216.1.1 by Brian Aker
Move print_error up to Engine.
1638
  print_error(error, MYF(0));
354 by Brian Aker
Refactor of Table methods.
1639
1640
  return 1;
1641
}
1642
1 by brian
clean slate
1643
934.1.1 by Brian Aker
Moved two functions in classes.
1644
void Table::setup_table_map(TableList *table_list, uint32_t table_number)
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
1645
{
934.1.1 by Brian Aker
Moved two functions in classes.
1646
  used_fields= 0;
1647
  const_table= 0;
1648
  null_row= 0;
1649
  status= STATUS_NO_RECORD;
1650
  maybe_null= table_list->outer_join;
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
1651
  TableList *embedding= table_list->getEmbedding();
934.1.1 by Brian Aker
Moved two functions in classes.
1652
  while (!maybe_null && embedding)
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
1653
  {
934.1.1 by Brian Aker
Moved two functions in classes.
1654
    maybe_null= embedding->outer_join;
1637.2.7 by Vijay Samuel
Merge encapsulate TableList-2.
1655
    embedding= embedding->getEmbedding();
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
1656
  }
934.1.1 by Brian Aker
Moved two functions in classes.
1657
  tablenr= table_number;
1658
  map= (table_map) 1 << table_number;
1659
  force_index= table_list->force_index;
1827.2.2 by Brian Aker
Encapsulate the share in Table.
1660
  covering_keys= getShare()->keys_for_keyread;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1661
  merge_keys.reset();
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
1662
}
1663
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1664
1527.1.2 by Brian Aker
Move all TableShare methods into .cc file.
1665
bool Table::fill_item_list(List<Item> *item_list) const
1666
{
1667
  /*
1668
    All Item_field's created using a direct pointer to a field
1669
    are fixed in Item_field constructor.
1670
  */
1671
  for (Field **ptr= field; *ptr; ptr++)
1672
  {
1673
    Item_field *item= new Item_field(*ptr);
1674
    if (!item || item_list->push_back(item))
1675
      return true;
1676
  }
1677
  return false;
1678
}
1679
1908.1.1 by Brian Aker
Merge in encapsulations in filesort.
1680
1681
void Table::filesort_free_buffers(bool full)
1682
{
1683
  if (sort.record_pointers)
1684
  {
1685
    free((unsigned char*) sort.record_pointers);
1686
    sort.record_pointers=0;
1687
  }
1688
  if (full)
1689
  {
1690
    if (sort.sort_keys )
1691
    {
1692
      if ((unsigned char*) sort.sort_keys)
1693
        free((unsigned char*) sort.sort_keys);
1694
      sort.sort_keys= 0;
1695
    }
1696
    if (sort.buffpek)
1697
    {
1698
      if ((unsigned char*) sort.buffpek)
1699
        free((unsigned char*) sort.buffpek);
1700
      sort.buffpek= 0;
1701
      sort.buffpek_len= 0;
1702
    }
1703
  }
1704
1705
  if (sort.addon_buf)
1706
  {
1707
    free((char *) sort.addon_buf);
1708
    free((char *) sort.addon_field);
1709
    sort.addon_buf=0;
1710
    sort.addon_field=0;
1711
  }
1712
}
1713
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1714
} /* namespace drizzled */