Drizzled Public API Documentation

table.cc
1 /* Copyright (C) 2000-2006 MySQL AB
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 
17 /* Some general useful functions */
18 
19 #include <config.h>
20 
21 #include <float.h>
22 #include <fcntl.h>
23 
24 #include <string>
25 #include <vector>
26 #include <algorithm>
27 
28 #include <drizzled/error.h>
29 #include <drizzled/gettext.h>
30 
31 #include <drizzled/plugin/transactional_storage_engine.h>
32 #include <drizzled/plugin/authorization.h>
33 #include <drizzled/nested_join.h>
34 #include <drizzled/sql_parse.h>
35 #include <drizzled/item/sum.h>
36 #include <drizzled/table_list.h>
37 #include <drizzled/session.h>
38 #include <drizzled/sql_base.h>
39 #include <drizzled/sql_select.h>
40 #include <drizzled/field/blob.h>
41 #include <drizzled/field/varstring.h>
42 #include <drizzled/field/double.h>
43 #include <drizzled/message/table.pb.h>
44 #include <drizzled/sql_table.h>
45 #include <drizzled/charset.h>
46 #include <drizzled/internal/m_string.h>
47 #include <plugin/myisam/myisam.h>
48 #include <drizzled/plugin/storage_engine.h>
49 #include <drizzled/item/string.h>
50 #include <drizzled/item/int.h>
51 #include <drizzled/item/decimal.h>
52 #include <drizzled/item/float.h>
53 #include <drizzled/item/null.h>
54 #include <drizzled/temporal.h>
55 #include <drizzled/table/singular.h>
56 #include <drizzled/table_proto.h>
57 #include <drizzled/typelib.h>
58 #include <drizzled/sql_lex.h>
59 #include <drizzled/statistics_variables.h>
60 #include <drizzled/system_variables.h>
61 #include <drizzled/open_tables_state.h>
62 
63 using namespace std;
64 
65 namespace drizzled {
66 
67 extern plugin::StorageEngine *heap_engine;
68 extern plugin::StorageEngine *myisam_engine;
69 
70 /* Functions defined in this cursor */
71 
72 /*************************************************************************/
73 
74 // @note this should all be the destructor
75 int Table::delete_table(bool free_share)
76 {
77  int error= 0;
78 
79  if (db_stat)
80  error= cursor->close();
81  _alias.clear();
82 
83  if (field)
84  {
85  for (Field **ptr=field ; *ptr ; ptr++)
86  {
87  delete *ptr;
88  }
89  field= 0;
90  }
91  safe_delete(cursor);
92 
93  if (free_share)
94  {
95  release();
96  }
97 
98  return error;
99 }
100 
101 Table::~Table()
102 {
103  mem_root.free_root(MYF(0));
104 }
105 
106 
107 void Table::resetTable(Session *session,
108  TableShare *share,
109  uint32_t db_stat_arg)
110 {
111  setShare(share);
112  in_use= session;
113 
114  field= NULL;
115 
116  cursor= NULL;
117  next= NULL;
118  prev= NULL;
119 
120  read_set= NULL;
121  write_set= NULL;
122 
123  tablenr= 0;
124  db_stat= db_stat_arg;
125 
126  record[0]= (unsigned char *) NULL;
127  record[1]= (unsigned char *) NULL;
128 
129  insert_values.clear();
130  key_info= NULL;
131  next_number_field= NULL;
132  found_next_number_field= NULL;
133  timestamp_field= NULL;
134 
135  pos_in_table_list= NULL;
136  group= NULL;
137  _alias.clear();
138  null_flags= NULL;
139 
140  lock_position= 0;
141  lock_data_start= 0;
142  lock_count= 0;
143  used_fields= 0;
144  status= 0;
145  derived_select_number= 0;
146  current_lock= F_UNLCK;
147  copy_blobs= false;
148 
149  maybe_null= false;
150 
151  null_row= false;
152 
153  force_index= false;
154  distinct= false;
155  const_table= false;
156  no_rows= false;
157  key_read= false;
158  no_keyread= false;
159 
160  open_placeholder= false;
161  locked_by_name= false;
162  no_cache= false;
163 
164  auto_increment_field_not_null= false;
165  alias_name_used= false;
166 
167  query_id= 0;
168  quick_condition_rows= 0;
169 
170  timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
171  map= 0;
172 
173  reginfo.reset();
174 
175  covering_keys.reset();
176 
177  quick_keys.reset();
178  merge_keys.reset();
179 
180  keys_in_use_for_query.reset();
181  keys_in_use_for_group_by.reset();
182  keys_in_use_for_order_by.reset();
183 
184  memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
185  memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
186 
187  memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
188  memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
189 
190  mem_root.init(TABLE_ALLOC_BLOCK_SIZE);
191 }
192 
193 
194 
195 /* Deallocate temporary blob storage */
196 
197 void free_blobs(Table *table)
198 {
199  uint32_t *ptr, *end;
200  for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
201  ptr != end ;
202  ptr++)
203  {
204  ((Field_blob*) table->getField(*ptr))->free();
205  }
206 }
207 
208 
209 TYPELIB *typelib(memory::Root& mem_root, List<String> &strings)
210 {
211  TYPELIB *result= new (mem_root) TYPELIB;
212  result->count= strings.size();
213  result->name= "";
214  result->type_names= (const char**) mem_root.alloc((sizeof(char*) + sizeof(uint32_t)) * (result->count + 1));
215  result->type_lengths= (uint*) (result->type_names + result->count + 1);
216 
217  List<String>::iterator it(strings.begin());
218  String *tmp;
219  for (uint32_t i= 0; (tmp= it++); i++)
220  {
221  result->type_names[i]= tmp->ptr();
222  result->type_lengths[i]= tmp->length();
223  }
224 
225  result->type_names[result->count]= 0; // End marker
226  result->type_lengths[result->count]= 0;
227 
228  return result;
229 }
230 
231  /* Check that the integer is in the internal */
232 
233 int set_zone(int nr, int min_zone, int max_zone)
234 {
235  if (nr<=min_zone)
236  return (min_zone);
237  if (nr>=max_zone)
238  return (max_zone);
239  return (nr);
240 } /* set_zone */
241 
242 
243 /*
244  Store an SQL quoted string.
245 
246  SYNOPSIS
247  append_unescaped()
248  res result String
249  pos string to be quoted
250  length it's length
251 
252  NOTE
253  This function works correctly with utf8 or single-byte charset strings.
254  May fail with some multibyte charsets though.
255 */
256 
257 void append_unescaped(String *res, const char *pos, uint32_t length)
258 {
259  const char *end= pos+length;
260  res->append('\'');
261 
262  for (; pos != end ; pos++)
263  {
264  uint32_t mblen;
265  if (use_mb(default_charset_info) &&
266  (mblen= my_ismbchar(default_charset_info, pos, end)))
267  {
268  res->append(pos, mblen);
269  pos+= mblen - 1;
270  if (pos >= end)
271  break;
272  continue;
273  }
274 
275  switch (*pos) {
276  case 0: /* Must be escaped for 'mysql' */
277  res->append('\\');
278  res->append('0');
279  break;
280  case '\n': /* Must be escaped for logs */
281  res->append('\\');
282  res->append('n');
283  break;
284  case '\r':
285  res->append('\\'); /* This gives better readability */
286  res->append('r');
287  break;
288  case '\\':
289  res->append('\\'); /* Because of the sql syntax */
290  res->append('\\');
291  break;
292  case '\'':
293  res->append('\''); /* Because of the sql syntax */
294  res->append('\'');
295  break;
296  default:
297  res->append(*pos);
298  break;
299  }
300  }
301  res->append('\'');
302 }
303 
304 /*
305  Allow anything as a table name, as long as it doesn't contain an
306  ' ' at the end
307  returns 1 on error
308 */
309 bool check_table_name(str_ref str)
310 {
311  return str.empty() || str.size() > NAME_LEN || str.data()[str.size() - 1] == ' ' || check_identifier_name(str);
312 }
313 
314 
315 /*
316  Eventually, a "length" argument should be added
317  to this function, and the inner loop changed to
318  check_identifier_name() call.
319 */
320 bool check_column_name(const char *name)
321 {
322  uint32_t name_length= 0; // name length in symbols
323  bool last_char_is_space= true;
324 
325  while (*name)
326  {
327  last_char_is_space= system_charset_info->isspace(*name);
328  if (use_mb(system_charset_info))
329  {
330  int len=my_ismbchar(system_charset_info, name,
331  name+system_charset_info->mbmaxlen);
332  if (len)
333  {
334  if (len > 3) /* Disallow non-BMP characters */
335  return 1;
336  name += len;
337  name_length++;
338  continue;
339  }
340  }
341  /*
342  NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
343  It is defined as 0xFF, which is a not valid byte in utf8.
344  This assert is to catch use of this byte if we decide to
345  use non-utf8 as system_character_set.
346  */
347  assert(*name != NAMES_SEP_CHAR);
348  name++;
349  name_length++;
350  }
351  /* Error if empty or too long column name */
352  return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
353 }
354 
355 
356 /*****************************************************************************
357  Functions to handle column usage bitmaps (read_set, write_set etc...)
358 *****************************************************************************/
359 
360 /* Reset all columns bitmaps */
361 
362 void Table::clear_column_bitmaps()
363 {
364  /*
365  Reset column read/write usage. It's identical to:
366  bitmap_clear_all(&table->def_read_set);
367  bitmap_clear_all(&table->def_write_set);
368  */
369  def_read_set.reset();
370  def_write_set.reset();
371  column_bitmaps_set(def_read_set, def_write_set);
372 }
373 
374 
375 /*
376  Tell Cursor we are going to call position() and rnd_pos() later.
377 
378  NOTES:
379  This is needed for handlers that uses the primary key to find the
380  row. In this case we have to extend the read bitmap with the primary
381  key fields.
382 */
383 
384 void Table::prepare_for_position()
385 {
386 
387  if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
388  getShare()->hasPrimaryKey())
389  {
390  mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
391  }
392  return;
393 }
394 
395 
396 /*
397  Mark that only fields from one key is used
398 
399  NOTE:
400  This changes the bitmap to use the tmp bitmap
401  After this, you can't access any other columns in the table until
402  bitmaps are reset, for example with Table::clear_column_bitmaps()
403  or Table::restore_column_maps_after_mark_index()
404 */
405 
406 void Table::mark_columns_used_by_index(uint32_t index)
407 {
408  boost::dynamic_bitset<> *bitmap= &tmp_set;
409 
410  (void) cursor->extra(HA_EXTRA_KEYREAD);
411  bitmap->reset();
412  mark_columns_used_by_index_no_reset(index, *bitmap);
413  column_bitmaps_set(*bitmap, *bitmap);
414  return;
415 }
416 
417 
418 /*
419  Restore to use normal column maps after key read
420 
421  NOTES
422  This reverse the change done by mark_columns_used_by_index
423 
424  WARNING
425  For this to work, one must have the normal table maps in place
426  when calling mark_columns_used_by_index
427 */
428 
429 void Table::restore_column_maps_after_mark_index()
430 {
431 
432  key_read= 0;
433  (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
434  default_column_bitmaps();
435  return;
436 }
437 
438 
439 /*
440  mark columns used by key, but don't reset other fields
441 */
442 
443 void Table::mark_columns_used_by_index_no_reset(uint32_t index)
444 {
445  mark_columns_used_by_index_no_reset(index, *read_set);
446 }
447 
448 
449 void Table::mark_columns_used_by_index_no_reset(uint32_t index,
450  boost::dynamic_bitset<>& bitmap)
451 {
452  KeyPartInfo *key_part= key_info[index].key_part;
453  KeyPartInfo *key_part_end= (key_part + key_info[index].key_parts);
454  for (; key_part != key_part_end; key_part++)
455  {
456  if (! bitmap.empty())
457  bitmap.set(key_part->fieldnr-1);
458  }
459 }
460 
461 
462 /*
463  Mark auto-increment fields as used fields in both read and write maps
464 
465  NOTES
466  This is needed in insert & update as the auto-increment field is
467  always set and sometimes read.
468 */
469 
470 void Table::mark_auto_increment_column()
471 {
472  assert(found_next_number_field);
473  /*
474  We must set bit in read set as update_auto_increment() is using the
475  store() to check overflow of auto_increment values
476  */
477  setReadSet(found_next_number_field->position());
478  setWriteSet(found_next_number_field->position());
479  if (getShare()->next_number_keypart)
480  mark_columns_used_by_index_no_reset(getShare()->next_number_index);
481 }
482 
483 
484 /*
485  Mark columns needed for doing an delete of a row
486 
487  DESCRIPTON
488  Some table engines don't have a cursor on the retrieve rows
489  so they need either to use the primary key or all columns to
490  be able to delete a row.
491 
492  If the engine needs this, the function works as follows:
493  - If primary key exits, mark the primary key columns to be read.
494  - If not, mark all columns to be read
495 
496  If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
497  mark all key columns as 'to-be-read'. This allows the engine to
498  loop over the given record to find all keys and doesn't have to
499  retrieve the row again.
500 */
501 
502 void Table::mark_columns_needed_for_delete()
503 {
504  /*
505  If the Cursor has no cursor capabilites, or we have row-based
506  replication active for the current statement, we have to read
507  either the primary key, the hidden primary key or all columns to
508  be able to do an delete
509 
510  */
511  if (not getShare()->hasPrimaryKey())
512  {
513  /* fallback to use all columns in the table to identify row */
514  use_all_columns();
515  return;
516  }
517  else
518  mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
519 
520  /* If we the engine wants all predicates we mark all keys */
521  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
522  {
523  Field **reg_field;
524  for (reg_field= field ; *reg_field ; reg_field++)
525  {
526  if ((*reg_field)->flags & PART_KEY_FLAG)
527  setReadSet((*reg_field)->position());
528  }
529  }
530 }
531 
532 
533 /*
534  Mark columns needed for doing an update of a row
535 
536  DESCRIPTON
537  Some engines needs to have all columns in an update (to be able to
538  build a complete row). If this is the case, we mark all not
539  updated columns to be read.
540 
541  If this is no the case, we do like in the delete case and mark
542  if neeed, either the primary key column or all columns to be read.
543  (see mark_columns_needed_for_delete() for details)
544 
545  If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
546  mark all USED key columns as 'to-be-read'. This allows the engine to
547  loop over the given record to find all changed keys and doesn't have to
548  retrieve the row again.
549 */
550 
551 void Table::mark_columns_needed_for_update()
552 {
553  /*
554  If the Cursor has no cursor capabilites, or we have row-based
555  logging active for the current statement, we have to read either
556  the primary key, the hidden primary key or all columns to be
557  able to do an update
558  */
559  if (not getShare()->hasPrimaryKey())
560  {
561  /* fallback to use all columns in the table to identify row */
562  use_all_columns();
563  return;
564  }
565  else
566  mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
567 
568  if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
569  {
570  /* Mark all used key columns for read */
571  Field **reg_field;
572  for (reg_field= field ; *reg_field ; reg_field++)
573  {
574  /* Merge keys is all keys that had a column refered to in the query */
575  if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
576  setReadSet((*reg_field)->position());
577  }
578  }
579 
580 }
581 
582 
583 /*
584  Mark columns the Cursor needs for doing an insert
585 
586  For now, this is used to mark fields used by the trigger
587  as changed.
588 */
589 
590 void Table::mark_columns_needed_for_insert()
591 {
592  if (found_next_number_field)
593  mark_auto_increment_column();
594 }
595 
596 
597 
598 size_t Table::max_row_length(const unsigned char *data)
599 {
600  size_t length= getRecordLength() + 2 * sizeFields();
601  uint32_t *const beg= getBlobField();
602  uint32_t *const end= beg + sizeBlobFields();
603 
604  for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
605  {
606  Field_blob* const blob= (Field_blob*) field[*ptr];
607  length+= blob->get_length((const unsigned char*)
608  (data + blob->offset(getInsertRecord()))) +
609  HA_KEY_BLOB_LENGTH;
610  }
611  return length;
612 }
613 
614 void Table::setVariableWidth(void)
615 {
616  assert(in_use);
617  if (in_use && in_use->lex().sql_command == SQLCOM_CREATE_TABLE)
618  {
619  getMutableShare()->setVariableWidth();
620  return;
621  }
622 
623  assert(0); // Programming error, you can't set this on a plain old Table.
624 }
625 
626 /****************************************************************************
627  Functions for creating temporary tables.
628 ****************************************************************************/
652  const char *name, Table *table,
653  Item_field *item, uint32_t convert_blob_length)
654 {
655  Field *new_field;
656 
657  /*
658  Make sure that the blob fits into a Field_varstring which has
659  2-byte lenght.
660  */
661  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE && (org_field->flags & BLOB_FLAG))
662  {
663  table->setVariableWidth();
664  new_field= new Field_varstring(convert_blob_length, org_field->maybe_null(), org_field->field_name, org_field->charset());
665  }
666  else
667  {
668  new_field= org_field->new_field(session->mem_root, table, table == org_field->getTable());
669  }
670  if (new_field)
671  {
672  new_field->init(table);
673  new_field->orig_table= org_field->orig_table;
674  if (item)
675  item->result_field= new_field;
676  else
677  new_field->field_name= name;
678  new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
679  if (org_field->maybe_null() || (item && item->maybe_null))
680  new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join
681  if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
682  table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
683  else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
684  ((Field_double *) new_field)->not_fixed= true;
685  }
686  return new_field;
687 }
688 
689 
716 Table *
718  Order *group, bool distinct, bool save_sum_fields,
719  uint64_t select_options, ha_rows rows_limit,
720  const char *table_alias)
721 {
722  uint i,field_count,null_count,null_pack_length;
723  uint32_t copy_func_count= param->func_count;
724  uint32_t hidden_null_count, hidden_null_pack_length, hidden_field_count;
725  uint32_t blob_count,group_null_items, string_count;
726  uint32_t fieldnr= 0;
727  ulong reclength, string_total_length;
728  bool using_unique_constraint= false;
729  bool not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
730  unsigned char *pos, *group_buff;
731  unsigned char *null_flags;
732  Field **reg_field, **from_field, **default_field;
733  CopyField *copy= 0;
734  KeyInfo *keyinfo;
735  KeyPartInfo *key_part_info;
736  Item **copy_func;
737  MI_COLUMNDEF *recinfo;
738  uint32_t total_uneven_bit_length= 0;
739  bool force_copy_fields= param->force_copy_fields;
740  uint64_t max_rows= 0;
741 
742  session->status_var.created_tmp_tables++;
743 
744  if (group)
745  {
746  if (! param->quick_group)
747  {
748  group= 0; // Can't use group key
749  }
750  else for (Order *tmp=group ; tmp ; tmp=tmp->next)
751  {
752  /*
753  marker == 4 means two things:
754  - store NULLs in the key, and
755  - convert BIT fields to 64-bit long, needed because MEMORY tables
756  can't index BIT fields.
757  */
758  (*tmp->item)->marker= 4;
759  if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
760  using_unique_constraint= true;
761  }
762  if (param->group_length >= MAX_BLOB_WIDTH)
763  using_unique_constraint= true;
764  if (group)
765  distinct= 0; // Can't use distinct
766  }
767 
768  field_count=param->field_count+param->func_count+param->sum_func_count;
769  hidden_field_count=param->hidden_field_count;
770 
771  /*
772  When loose index scan is employed as access method, it already
773  computes all groups and the result of all aggregate functions. We
774  make space for the items of the aggregate function in the list of
775  functions Tmp_Table_Param::items_to_copy, so that the values of
776  these items are stored in the temporary table.
777  */
778  if (param->precomputed_group_by)
779  {
780  copy_func_count+= param->sum_func_count;
781  }
782 
783  table::Singular* table= &session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
784 
785  table->mem().multi_alloc(0,
786  &default_field, sizeof(Field*) * (field_count),
787  &from_field, sizeof(Field*)*field_count,
788  &copy_func, sizeof(*copy_func)*(copy_func_count+1),
789  &param->keyinfo, sizeof(*param->keyinfo),
790  &key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
791  &param->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
792  &group_buff, (group && ! using_unique_constraint ? param->group_length : 0),
793  NULL);
794  /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
795  param->copy_field= copy= new (session->mem_root) CopyField[field_count];
796  param->items_to_copy= copy_func;
797  /* make table according to fields */
798 
799  memset(default_field, 0, sizeof(Field*) * (field_count));
800  memset(from_field, 0, sizeof(Field*)*field_count);
801 
802  memory::Root* mem_root_save= session->mem_root;
803  session->mem_root= &table->mem();
804 
805  table->getMutableShare()->setFields(field_count+1);
806  table->setFields(table->getMutableShare()->getFields(true));
807  reg_field= table->getMutableShare()->getFields(true);
808  table->setAlias(table_alias);
809  table->reginfo.lock_type=TL_WRITE; /* Will be updated */
810  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
811  table->map=1;
812  table->copy_blobs= 1;
813  assert(session);
814  table->in_use= session;
815  table->quick_keys.reset();
816  table->covering_keys.reset();
817  table->keys_in_use_for_query.reset();
818 
819  table->getMutableShare()->blob_field.resize(field_count+1);
820  uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
821  table->getMutableShare()->db_low_byte_first=1; // True for HEAP and MyISAM
822  table->getMutableShare()->table_charset= param->table_charset;
823  table->getMutableShare()->keys_for_keyread.reset();
824  table->getMutableShare()->keys_in_use.reset();
825 
826  /* Calculate which type of fields we will store in the temporary table */
827 
828  reclength= string_total_length= 0;
829  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
830  param->using_indirect_summary_function= 0;
831 
832  List<Item>::iterator li(fields.begin());
833  Field **tmp_from_field=from_field;
834  while (Item* item=li++)
835  {
836  Item::Type type=item->type();
837  if (not_all_columns)
838  {
839  if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
840  {
841  if (item->used_tables() & OUTER_REF_TABLE_BIT)
842  item->update_used_tables();
843  if (type == Item::SUBSELECT_ITEM ||
844  (item->used_tables() & ~OUTER_REF_TABLE_BIT))
845  {
846  /*
847  Mark that the we have ignored an item that refers to a summary
848  function. We need to know this if someone is going to use
849  DISTINCT on the result.
850  */
851  param->using_indirect_summary_function=1;
852  continue;
853  }
854  }
855  if (item->const_item() && (int) hidden_field_count <= 0)
856  continue; // We don't have to store this
857  }
858  if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
859  { /* Can't calc group yet */
860  ((Item_sum*) item)->result_field= 0;
861  for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
862  {
863  Item **argp= ((Item_sum*) item)->args + i;
864  Item *arg= *argp;
865  if (!arg->const_item())
866  {
867  Field *new_field=
868  create_tmp_field(session, table, arg, arg->type(), &copy_func,
869  tmp_from_field, &default_field[fieldnr],
870  group != 0,not_all_columns,
871  false,
872  param->convert_blob_length);
873  if (!new_field)
874  goto err; // Should be OOM
875  tmp_from_field++;
876  reclength+=new_field->pack_length();
877  if (new_field->flags & BLOB_FLAG)
878  {
879  *blob_field++= fieldnr;
880  blob_count++;
881  }
882  *(reg_field++)= new_field;
883  if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
884  {
885  string_count++;
886  string_total_length+= new_field->pack_length();
887  }
888  session->mem_root= mem_root_save;
889  *argp= new Item_field(new_field);
890  session->mem_root= &table->mem();
891  if (!(new_field->flags & NOT_NULL_FLAG))
892  {
893  null_count++;
894  /*
895  new_field->maybe_null() is still false, it will be
896  changed below. But we have to setup Item_field correctly
897  */
898  (*argp)->maybe_null=1;
899  }
900  new_field->setPosition(fieldnr++);
901  }
902  }
903  }
904  else
905  {
906  /*
907  The last parameter to create_tmp_field() is a bit tricky:
908 
909  We need to set it to 0 in union, to get fill_record() to modify the
910  temporary table.
911  We need to set it to 1 on multi-table-update and in select to
912  write rows to the temporary table.
913  We here distinguish between UNION and multi-table-updates by the fact
914  that in the later case group is set to the row pointer.
915  */
916  Field *new_field=
917  create_tmp_field(session, table, item, type, &copy_func,
918  tmp_from_field, &default_field[fieldnr],
919  group != 0,
920  !force_copy_fields &&
921  (not_all_columns || group != 0),
922  force_copy_fields,
923  param->convert_blob_length);
924 
925  if (!new_field)
926  {
927  if (session->is_fatal_error)
928  goto err; // Got OOM
929  continue; // Some kindf of const item
930  }
931  if (type == Item::SUM_FUNC_ITEM)
932  ((Item_sum *) item)->result_field= new_field;
933  tmp_from_field++;
934  reclength+=new_field->pack_length();
935  if (!(new_field->flags & NOT_NULL_FLAG))
936  null_count++;
937  if (new_field->flags & BLOB_FLAG)
938  {
939  *blob_field++= fieldnr;
940  blob_count++;
941  }
942  if (item->marker == 4 && item->maybe_null)
943  {
944  group_null_items++;
945  new_field->flags|= GROUP_FLAG;
946  }
947  new_field->setPosition(fieldnr++);
948  *(reg_field++)= new_field;
949  }
950  if (!--hidden_field_count)
951  {
952  /*
953  This was the last hidden field; Remember how many hidden fields could
954  have null
955  */
956  hidden_null_count=null_count;
957  /*
958  We need to update hidden_field_count as we may have stored group
959  functions with constant arguments
960  */
961  param->hidden_field_count= fieldnr;
962  null_count= 0;
963  }
964  }
965  assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
966  assert(field_count >= (uint32_t) (reg_field - table->getFields()));
967  field_count= fieldnr;
968  *reg_field= 0;
969  *blob_field= 0; // End marker
970  table->getMutableShare()->setFieldSize(field_count);
971 
972  /* If result table is small; use a heap */
973  /* future: storage engine selection can be made dynamic? */
974  if (blob_count || using_unique_constraint ||
975  (session->lex().select_lex.options & SELECT_BIG_RESULT) ||
976  (session->lex().current_select->olap == ROLLUP_TYPE) ||
977  (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
978  {
979  table->getMutableShare()->storage_engine= myisam_engine;
980  table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
981  if (group &&
982  (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
983  param->group_length > table->cursor->getEngine()->max_key_length()))
984  {
985  using_unique_constraint= true;
986  }
987  }
988  else
989  {
990  table->getMutableShare()->storage_engine= heap_engine;
991  table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
992  }
993  if (! table->cursor)
994  goto err;
995 
996 
997  if (! using_unique_constraint)
998  reclength+= group_null_items; // null flag is stored separately
999 
1000  table->getMutableShare()->blob_fields= blob_count;
1001  if (blob_count == 0)
1002  {
1003  /* We need to ensure that first byte is not 0 for the delete link */
1004  if (param->hidden_field_count)
1005  hidden_null_count++;
1006  else
1007  null_count++;
1008  }
1009  hidden_null_pack_length=(hidden_null_count+7)/8;
1010  null_pack_length= (hidden_null_pack_length +
1011  (null_count + total_uneven_bit_length + 7) / 8);
1012  reclength+=null_pack_length;
1013  if (!reclength)
1014  reclength=1; // Dummy select
1015 
1016  table->getMutableShare()->setRecordLength(reclength);
1017  {
1018  uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
1019  table->getMutableShare()->rec_buff_length= alloc_length;
1020  table->record[0]= table->alloc(alloc_length*2);
1021  table->record[1]= table->getInsertRecord()+alloc_length;
1022  table->getMutableShare()->resizeDefaultValues(alloc_length);
1023  }
1024  copy_func[0]= 0; // End marker
1025  param->func_count= copy_func - param->items_to_copy;
1026 
1027  table->setup_tmp_table_column_bitmaps();
1028 
1029  recinfo=param->start_recinfo;
1030  null_flags= table->getInsertRecord();
1031  pos=table->getInsertRecord()+ null_pack_length;
1032  if (null_pack_length)
1033  {
1034  memset(recinfo, 0, sizeof(*recinfo));
1035  recinfo->type=FIELD_NORMAL;
1036  recinfo->length=null_pack_length;
1037  recinfo++;
1038  memset(null_flags, 255, null_pack_length); // Set null fields
1039 
1040  table->null_flags= table->getInsertRecord();
1041  table->getMutableShare()->null_fields= null_count+ hidden_null_count;
1042  table->getMutableShare()->null_bytes= null_pack_length;
1043  }
1044  null_count= (blob_count == 0) ? 1 : 0;
1045  hidden_field_count=param->hidden_field_count;
1046  for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
1047  {
1048  Field *field= *reg_field;
1049  uint32_t length;
1050  memset(recinfo, 0, sizeof(*recinfo));
1051 
1052  if (!(field->flags & NOT_NULL_FLAG))
1053  {
1054  if (field->flags & GROUP_FLAG && !using_unique_constraint)
1055  {
1056  /*
1057  We have to reserve one byte here for NULL bits,
1058  as this is updated by 'end_update()'
1059  */
1060  *pos++= '\0'; // Null is stored here
1061  recinfo->length= 1;
1062  recinfo->type=FIELD_NORMAL;
1063  recinfo++;
1064  memset(recinfo, 0, sizeof(*recinfo));
1065  }
1066  else
1067  {
1068  recinfo->null_bit= 1 << (null_count & 7);
1069  recinfo->null_pos= null_count/8;
1070  }
1071  field->move_field(pos,null_flags+null_count/8,
1072  1 << (null_count & 7));
1073  null_count++;
1074  }
1075  else
1076  field->move_field(pos,(unsigned char*) 0,0);
1077  field->reset();
1078 
1079  /*
1080  Test if there is a default field value. The test for ->ptr is to skip
1081  'offset' fields generated by initalize_tables
1082  */
1083  if (default_field[i] && default_field[i]->ptr)
1084  {
1085  /*
1086  default_field[i] is set only in the cases when 'field' can
1087  inherit the default value that is defined for the field referred
1088  by the Item_field object from which 'field' has been created.
1089  */
1090  ptrdiff_t diff;
1091  Field *orig_field= default_field[i];
1092  /* Get the value from default_values */
1093  diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
1094  orig_field->move_field_offset(diff); // Points now at default_values
1095  if (orig_field->is_real_null())
1096  field->set_null();
1097  else
1098  {
1099  field->set_notnull();
1100  memcpy(field->ptr, orig_field->ptr, field->pack_length());
1101  }
1102  orig_field->move_field_offset(-diff); // Back to getInsertRecord()
1103  }
1104 
1105  if (from_field[i])
1106  { /* Not a table Item */
1107  copy->set(field,from_field[i],save_sum_fields);
1108  copy++;
1109  }
1110  length=field->pack_length();
1111  pos+= length;
1112 
1113  /* Make entry for create table */
1114  recinfo->length=length;
1115  if (field->flags & BLOB_FLAG)
1116  recinfo->type= (int) FIELD_BLOB;
1117  else
1118  recinfo->type=FIELD_NORMAL;
1119  if (!--hidden_field_count)
1120  null_count=(null_count+7) & ~7; // move to next byte
1121  }
1122 
1123  param->copy_field_end=copy;
1124  param->recinfo=recinfo;
1125  table->storeRecordAsDefault(); // Make empty default record
1126 
1127  if (session->variables.tmp_table_size == ~ (uint64_t) 0) // No limit
1128  {
1129  max_rows= ~(uint64_t) 0;
1130  }
1131  else
1132  {
1133  max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
1134  min(session->variables.tmp_table_size,
1135  session->variables.max_heap_table_size) :
1136  session->variables.tmp_table_size) /
1137  table->getMutableShare()->getRecordLength());
1138  }
1139 
1140  set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
1141  /*
1142  Push the LIMIT clause to the temporary table creation, so that we
1143  materialize only up to 'rows_limit' records instead of all result records.
1144  */
1145  set_if_smaller(max_rows, rows_limit);
1146 
1147  table->getMutableShare()->setMaxRows(max_rows);
1148 
1149  param->end_write_records= rows_limit;
1150 
1151  keyinfo= param->keyinfo;
1152 
1153  if (group)
1154  {
1155  table->group=group; /* Table is grouped by key */
1156  param->group_buff=group_buff;
1157  table->getMutableShare()->keys=1;
1158  table->getMutableShare()->uniques= test(using_unique_constraint);
1159  table->key_info=keyinfo;
1160  keyinfo->key_part=key_part_info;
1161  keyinfo->flags=HA_NOSAME;
1162  keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
1163  keyinfo->key_length= 0;
1164  keyinfo->rec_per_key= 0;
1165  keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1166  keyinfo->name= (char*) "group_key";
1167  Order *cur_group= group;
1168  for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1169  {
1170  Field *field=(*cur_group->item)->get_tmp_table_field();
1171  bool maybe_null=(*cur_group->item)->maybe_null;
1172  key_part_info->null_bit= 0;
1173  key_part_info->field= field;
1174  key_part_info->offset= field->offset(table->getInsertRecord());
1175  key_part_info->length= (uint16_t) field->key_length();
1176  key_part_info->type= (uint8_t) field->key_type();
1177  key_part_info->key_type=
1178  ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1179  (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1180  (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1181  0 : 1;
1182  if (!using_unique_constraint)
1183  {
1184  cur_group->buff=(char*) group_buff;
1185  if (!(cur_group->field= field->new_key_field(session->mem_root,table,
1186  group_buff +
1187  test(maybe_null),
1188  field->null_ptr,
1189  field->null_bit)))
1190  goto err;
1191  if (maybe_null)
1192  {
1193  /*
1194  To be able to group on NULL, we reserved place in group_buff
1195  for the NULL flag just before the column. (see above).
1196  The field data is after this flag.
1197  The NULL flag is updated in 'end_update()' and 'end_write()'
1198  */
1199  keyinfo->flags|= HA_NULL_ARE_EQUAL; // def. that NULL == NULL
1200  key_part_info->null_bit=field->null_bit;
1201  key_part_info->null_offset= (uint32_t) (field->null_ptr -
1202  (unsigned char*) table->getInsertRecord());
1203  cur_group->buff++; // Pointer to field data
1204  group_buff++; // Skipp null flag
1205  }
1206  /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
1207  key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
1208  group_buff+= cur_group->field->pack_length();
1209  }
1210  keyinfo->key_length+= key_part_info->length;
1211  }
1212  }
1213 
1214  if (distinct && field_count != param->hidden_field_count)
1215  {
1216  /*
1217  Create an unique key or an unique constraint over all columns
1218  that should be in the result. In the temporary table, there are
1219  'param->hidden_field_count' extra columns, whose null bits are stored
1220  in the first 'hidden_null_pack_length' bytes of the row.
1221  */
1222  if (blob_count)
1223  {
1224  /*
1225  Special mode for index creation in MyISAM used to support unique
1226  indexes on blobs with arbitrary length. Such indexes cannot be
1227  used for lookups.
1228  */
1229  table->getMutableShare()->uniques= 1;
1230  }
1231  null_pack_length-=hidden_null_pack_length;
1232  keyinfo->key_parts= ((field_count-param->hidden_field_count)+
1233  (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
1234  table->distinct= 1;
1235  table->getMutableShare()->keys= 1;
1236  key_part_info= new (table->mem()) KeyPartInfo[keyinfo->key_parts];
1237  memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
1238  table->key_info=keyinfo;
1239  keyinfo->key_part=key_part_info;
1240  keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
1241  keyinfo->key_length=(uint16_t) reclength;
1242  keyinfo->name= (char*) "distinct_key";
1243  keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1244  keyinfo->rec_per_key= 0;
1245 
1246  /*
1247  Create an extra field to hold NULL bits so that unique indexes on
1248  blobs can distinguish NULL from 0. This extra field is not needed
1249  when we do not use UNIQUE indexes for blobs.
1250  */
1251  if (null_pack_length && table->getMutableShare()->uniques)
1252  {
1253  key_part_info->null_bit= 0;
1254  key_part_info->offset=hidden_null_pack_length;
1255  key_part_info->length=null_pack_length;
1256  table->setVariableWidth();
1257  key_part_info->field= new Field_varstring(table->getInsertRecord(),
1258  (uint32_t) key_part_info->length,
1259  0,
1260  (unsigned char*) 0,
1261  (uint32_t) 0,
1262  NULL,
1263  &my_charset_bin);
1264  if (!key_part_info->field)
1265  goto err;
1266  key_part_info->field->init(table);
1267  key_part_info->key_type= 1; /* binary comparison */
1268  key_part_info->type= HA_KEYTYPE_BINARY;
1269  key_part_info++;
1270  }
1271  /* Create a distinct key over the columns we are going to return */
1272  for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
1273  i < field_count;
1274  i++, reg_field++, key_part_info++)
1275  {
1276  key_part_info->null_bit= 0;
1277  key_part_info->field= *reg_field;
1278  key_part_info->offset= (*reg_field)->offset(table->getInsertRecord());
1279  key_part_info->length= (uint16_t) (*reg_field)->pack_length();
1280  /* @todo The below method of computing the key format length of the
1281  key part is a copy/paste from optimizer/range.cc, and table.cc.
1282  This should be factored out, e.g. as a method of Field.
1283  In addition it is not clear if any of the Field::*_length
1284  methods is supposed to compute the same length. If so, it
1285  might be reused.
1286  */
1287  key_part_info->store_length= key_part_info->length;
1288 
1289  if ((*reg_field)->real_maybe_null())
1290  key_part_info->store_length+= HA_KEY_NULL_LENGTH;
1291  if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
1292  (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
1293  key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
1294 
1295  key_part_info->type= (uint8_t) (*reg_field)->key_type();
1296  key_part_info->key_type =
1297  ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
1298  (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
1299  (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
1300  0 : 1;
1301  }
1302  }
1303 
1304  if (session->is_fatal_error) // If end of memory
1305  goto err;
1306  table->getMutableShare()->db_record_offset= 1;
1307  if (table->getShare()->db_type() == myisam_engine)
1308  {
1309  if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
1310  &param->recinfo, select_options))
1311  goto err;
1312  }
1313  assert(table->in_use);
1314  if (table->open_tmp_table())
1315  goto err;
1316 
1317  session->mem_root= mem_root_save;
1318 
1319  return(table);
1320 
1321 err:
1322  session->mem_root= mem_root_save;
1323  table= NULL;
1324 
1325  return NULL;
1326 }
1327 
1328 /****************************************************************************/
1329 
1330 void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
1331  boost::dynamic_bitset<>& write_set_arg)
1332 {
1333  read_set= &read_set_arg;
1334  write_set= &write_set_arg;
1335 }
1336 
1337 
1338 const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
1339 {
1340  const boost::dynamic_bitset<> old= in_map;
1341  in_map= getShare()->all_set;
1342  return old;
1343 }
1344 
1345 void Table::restore_column_map(const boost::dynamic_bitset<>& old)
1346 {
1347  for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
1348  {
1349  if (old.test(i))
1350  {
1351  read_set->set(i);
1352  }
1353  else
1354  {
1355  read_set->reset(i);
1356  }
1357  }
1358 }
1359 
1360 uint32_t Table::find_shortest_key(const key_map *usable_keys)
1361 {
1362  uint32_t min_length= UINT32_MAX;
1363  uint32_t best= MAX_KEY;
1364  if (usable_keys->any())
1365  {
1366  for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
1367  {
1368  if (usable_keys->test(nr))
1369  {
1370  if (key_info[nr].key_length < min_length)
1371  {
1372  min_length= key_info[nr].key_length;
1373  best=nr;
1374  }
1375  }
1376  }
1377  }
1378  return best;
1379 }
1380 
1381 /*****************************************************************************
1382  Remove duplicates from tmp table
1383  This should be recoded to add a unique index to the table and remove
1384  duplicates
1385  Table is a locked single thread table
1386  fields is the number of fields to check (from the end)
1387 *****************************************************************************/
1388 
1389 bool Table::compare_record(Field **ptr)
1390 {
1391  for (; *ptr ; ptr++)
1392  {
1393  if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
1394  return true;
1395  }
1396  return false;
1397 }
1398 
1403 bool Table::records_are_comparable()
1404 {
1405  return ((getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) == 0) ||
1406  write_set->is_subset_of(*read_set));
1407 }
1408 
1422 bool Table::compare_records()
1423 {
1424  if (getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) != 0)
1425  {
1426  /*
1427  Storage engine may not have read all columns of the record. Fields
1428  (including NULL bits) not in the write_set may not have been read and
1429  can therefore not be compared.
1430  */
1431  for (Field **ptr= this->field ; *ptr != NULL; ptr++)
1432  {
1433  Field *f= *ptr;
1434  if (write_set->test(f->position()))
1435  {
1436  if (f->real_maybe_null())
1437  {
1438  unsigned char null_byte_index= f->null_ptr - record[0];
1439 
1440  if (((record[0][null_byte_index]) & f->null_bit) !=
1441  ((record[1][null_byte_index]) & f->null_bit))
1442  return true;
1443  }
1444  if (f->cmp_binary_offset(getShare()->rec_buff_length))
1445  return true;
1446  }
1447  }
1448  return false;
1449  }
1450 
1451  /*
1452  The storage engine has read all columns, so it's safe to compare all bits
1453  including those not in the write_set. This is cheaper than the
1454  field-by-field comparison done above.
1455  */
1456  if (not getShare()->blob_fields + getShare()->hasVariableWidth())
1457  // Fixed-size record: do bitwise comparison of the records
1458  return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
1459 
1460  /* Compare null bits */
1461  if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
1462  return true; /* Diff in NULL value */
1463 
1464  /* Compare updated fields */
1465  for (Field **ptr= field ; *ptr ; ptr++)
1466  {
1467  if (isWriteSet((*ptr)->position()) &&
1468  (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
1469  return true;
1470  }
1471  return false;
1472 }
1473 
1474 /*
1475  * Store a record from previous record into next
1476  *
1477  */
1478 void Table::storeRecord()
1479 {
1480  memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1481 }
1482 
1483 /*
1484  * Store a record as an insert
1485  *
1486  */
1487 void Table::storeRecordAsInsert()
1488 {
1489  assert(insert_values.size() >= getShare()->getRecordLength());
1490  memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
1491 }
1492 
1493 /*
1494  * Store a record with default values
1495  *
1496  */
1497 void Table::storeRecordAsDefault()
1498 {
1499  memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
1500 }
1501 
1502 /*
1503  * Restore a record from previous record into next
1504  *
1505  */
1506 void Table::restoreRecord()
1507 {
1508  memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
1509 }
1510 
1511 /*
1512  * Restore a record with default values
1513  *
1514  */
1515 void Table::restoreRecordAsDefault()
1516 {
1517  memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
1518 }
1519 
1520 /*
1521  * Empty a record
1522  *
1523  */
1524 void Table::emptyRecord()
1525 {
1526  restoreRecordAsDefault();
1527  memset(null_flags, 255, getShare()->null_bytes);
1528 }
1529 
1530 Table::Table() :
1531  field(NULL),
1532  cursor(NULL),
1533  next(NULL),
1534  prev(NULL),
1535  read_set(NULL),
1536  write_set(NULL),
1537  tablenr(0),
1538  db_stat(0),
1539  def_read_set(),
1540  def_write_set(),
1541  tmp_set(),
1542  in_use(NULL),
1543  key_info(NULL),
1544  next_number_field(NULL),
1545  found_next_number_field(NULL),
1546  timestamp_field(NULL),
1547  pos_in_table_list(NULL),
1548  group(NULL),
1549  null_flags(NULL),
1550  lock_position(0),
1551  lock_data_start(0),
1552  lock_count(0),
1553  used_fields(0),
1554  status(0),
1555  derived_select_number(0),
1556  current_lock(F_UNLCK),
1557  copy_blobs(false),
1558  maybe_null(false),
1559  null_row(false),
1560  force_index(false),
1561  distinct(false),
1562  const_table(false),
1563  no_rows(false),
1564  key_read(false),
1565  no_keyread(false),
1566  open_placeholder(false),
1567  locked_by_name(false),
1568  no_cache(false),
1569  auto_increment_field_not_null(false),
1570  alias_name_used(false),
1571  query_id(0),
1572  quick_condition_rows(0),
1573  timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
1574  map(0),
1575  quick_rows(),
1576  const_key_parts(),
1577  quick_key_parts(),
1578  quick_n_ranges()
1579 {
1580  record[0]= (unsigned char *) 0;
1581  record[1]= (unsigned char *) 0;
1582 }
1583 
1584 /*****************************************************************************
1585  The different ways to read a record
1586  Returns -1 if row was not found, 0 if row was found and 1 on errors
1587 *****************************************************************************/
1588 
1591 int Table::report_error(int error)
1592 {
1593  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
1594  {
1595  status= STATUS_GARBAGE;
1596  return -1; // key not found; ok
1597  }
1598  /*
1599  Locking reads can legally return also these errors, do not
1600  print them to the .err log
1601  */
1602  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
1603  errmsg_printf(error::ERROR, _("Got error %d when reading table '%s'"),
1604  error, getShare()->getPath());
1605  print_error(error, MYF(0));
1606 
1607  return 1;
1608 }
1609 
1610 
1611 void Table::setup_table_map(TableList *table_list, uint32_t table_number)
1612 {
1613  used_fields= 0;
1614  const_table= 0;
1615  null_row= 0;
1616  status= STATUS_NO_RECORD;
1617  maybe_null= table_list->outer_join;
1618  TableList *embedding= table_list->getEmbedding();
1619  while (!maybe_null && embedding)
1620  {
1621  maybe_null= embedding->outer_join;
1622  embedding= embedding->getEmbedding();
1623  }
1624  tablenr= table_number;
1625  map= (table_map) 1 << table_number;
1626  force_index= table_list->force_index;
1627  covering_keys= getShare()->keys_for_keyread;
1628  merge_keys.reset();
1629 }
1630 
1631 
1633 {
1634  /*
1635  All Item_field's created using a direct pointer to a field
1636  are fixed in Item_field constructor.
1637  */
1638  for (Field **ptr= field; *ptr; ptr++)
1639  items.push_back(new Item_field(*ptr));
1640 }
1641 
1642 
1643 void Table::filesort_free_buffers(bool full)
1644 {
1645  free(sort.record_pointers);
1646  sort.record_pointers=0;
1647  if (full)
1648  {
1649  free(sort.sort_keys);
1650  sort.sort_keys= 0;
1651  free(sort.buffpek);
1652  sort.buffpek= 0;
1653  sort.buffpek_len= 0;
1654  }
1655  free(sort.addon_buf);
1656  free(sort.addon_field);
1657  sort.addon_buf=0;
1658  sort.addon_field=0;
1659 }
1660 
1661 /*
1662  Is this instance of the table should be reopen or represents a name-lock?
1663 */
1664 bool Table::needs_reopen_or_name_lock() const
1665 {
1666  return getShare()->getVersion() != g_refresh_version;
1667 }
1668 
1669 uint32_t Table::index_flags(uint32_t idx) const
1670 {
1671  return getShare()->getEngine()->index_flags(getShare()->getKeyInfo(idx).algorithm);
1672 }
1673 
1674 void Table::print_error(int error, myf errflag) const
1675 {
1676  getShare()->getEngine()->print_error(error, errflag, *this);
1677 }
1678 
1679 } /* namespace drizzled */
virtual uint32_t pack_length() const
Definition: field.cc:707
virtual bool const_item() const
Definition: item.h:495
Field * create_tmp_field_from_field(Session *session, Field *org_field, const char *name, Table *table, Item_field *item, uint32_t convert_blob_length)
Definition: table.cc:651
table_map map
ID bit of table (1,2,4,8,16...)
Definition: table.h:270
bool copy_blobs
Definition: table.h:178
Table * create_tmp_table(Session *session, Tmp_Table_Param *param, List< Item > &fields, Order *group, bool distinct, bool save_sum_fields, uint64_t select_options, ha_rows rows_limit, const char *alias)
Definition: table.cc:717
uint32_t db_stat
Definition: table.h:117
virtual void print_error(int error, myf errflag, const Table &table) const
Table * orig_table
Definition: field.h:101
int report_error(int error)
Definition: table.cc:1591
Field ** field
Definition: table.h:45
Field * create_tmp_field(Session *session, Table *table, Item *item, Item::Type type, Item ***copy_func, Field **from_field, Field **default_field, bool group, bool modify_item, bool make_copy_field, uint32_t convert_blob_length)
Definition: item.cc:1677
unsigned char * record[2]
Definition: table.h:139
bool maybe_null
Definition: item.h:121
KeyInfo * key_info
Definition: table.h:141
uint32_t outer_join
Which join type.
Definition: table_list.h:216
bool is_fatal_error
Definition: session.h:540
Session * in_use
Definition: table.h:123
Cursor * cursor
Definition: table.h:68
unsigned char null_bit
Definition: field.h:152
bool force_index
prefer index over table scan
Definition: table_list.h:174
void fill_item_list(List< Item > &) const
Definition: table.cc:1632
void * multi_alloc(int unused,...)
Allocate many pointers at the same time.
Definition: root.cc:212
memory::Root * mem_root
Definition: session.h:118
unsigned char * null_ptr
Definition: field.h:72
const char * field_name
Definition: field.h:102
drizzle_system_variables & variables
Definition: session.h:199
unsigned char * ptr
Definition: field.h:71
void setup_table_map(TableList *table_list, uint32_t tablenr)
Definition: table.cc:1611