Drizzled Public API Documentation

table.cc
00001 /* Copyright (C) 2000-2006 MySQL AB
00002 
00003    This program is free software; you can redistribute it and/or modify
00004    it under the terms of the GNU General Public License as published by
00005    the Free Software Foundation; version 2 of the License.
00006 
00007    This program is distributed in the hope that it will be useful,
00008    but WITHOUT ANY WARRANTY; without even the implied warranty of
00009    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00010    GNU General Public License for more details.
00011 
00012    You should have received a copy of the GNU General Public License
00013    along with this program; if not, write to the Free Software
00014    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
00015 
00016 
00017 /* Some general useful functions */
00018 
00019 #include <config.h>
00020 
00021 #include <float.h>
00022 #include <fcntl.h>
00023 
00024 #include <string>
00025 #include <vector>
00026 #include <algorithm>
00027 
00028 #include <drizzled/error.h>
00029 #include <drizzled/gettext.h>
00030 
00031 #include <drizzled/plugin/transactional_storage_engine.h>
00032 #include <drizzled/plugin/authorization.h>
00033 #include <drizzled/nested_join.h>
00034 #include <drizzled/sql_parse.h>
00035 #include <drizzled/item/sum.h>
00036 #include <drizzled/table_list.h>
00037 #include <drizzled/session.h>
00038 #include <drizzled/sql_base.h>
00039 #include <drizzled/sql_select.h>
00040 #include <drizzled/field/blob.h>
00041 #include <drizzled/field/varstring.h>
00042 #include <drizzled/field/double.h>
00043 #include <drizzled/message/table.pb.h>
00044 #include <drizzled/sql_table.h>
00045 #include <drizzled/charset.h>
00046 #include <drizzled/internal/m_string.h>
00047 #include <plugin/myisam/myisam.h>
00048 #include <drizzled/plugin/storage_engine.h>
00049 #include <drizzled/item/string.h>
00050 #include <drizzled/item/int.h>
00051 #include <drizzled/item/decimal.h>
00052 #include <drizzled/item/float.h>
00053 #include <drizzled/item/null.h>
00054 #include <drizzled/temporal.h>
00055 #include <drizzled/table/singular.h>
00056 #include <drizzled/table_proto.h>
00057 #include <drizzled/typelib.h>
00058 #include <drizzled/sql_lex.h>
00059 #include <drizzled/statistics_variables.h>
00060 #include <drizzled/system_variables.h>
00061 #include <drizzled/open_tables_state.h>
00062 
00063 using namespace std;
00064 
00065 namespace drizzled {
00066 
00067 extern plugin::StorageEngine *heap_engine;
00068 extern plugin::StorageEngine *myisam_engine;
00069 
00070 /* Functions defined in this cursor */
00071 
00072 /*************************************************************************/
00073 
00074 // @note this should all be the destructor
00075 int Table::delete_table(bool free_share)
00076 {
00077   int error= 0;
00078 
00079   if (db_stat)
00080     error= cursor->close();
00081   _alias.clear();
00082 
00083   if (field)
00084   {
00085     for (Field **ptr=field ; *ptr ; ptr++)
00086     {
00087       delete *ptr;
00088     }
00089     field= 0;
00090   }
00091   safe_delete(cursor);
00092 
00093   if (free_share)
00094   {
00095     release();
00096   }
00097 
00098   return error;
00099 }
00100 
00101 Table::~Table()
00102 {
00103   mem_root.free_root(MYF(0));
00104 }
00105 
00106 
00107 void Table::resetTable(Session *session,
00108                        TableShare *share,
00109                        uint32_t db_stat_arg)
00110 {
00111   setShare(share);
00112   in_use= session;
00113 
00114   field= NULL;
00115 
00116   cursor= NULL;
00117   next= NULL;
00118   prev= NULL;
00119 
00120   read_set= NULL;
00121   write_set= NULL;
00122 
00123   tablenr= 0;
00124   db_stat= db_stat_arg;
00125 
00126   record[0]= (unsigned char *) NULL;
00127   record[1]= (unsigned char *) NULL;
00128 
00129   insert_values.clear();
00130   key_info= NULL;
00131   next_number_field= NULL;
00132   found_next_number_field= NULL;
00133   timestamp_field= NULL;
00134 
00135   pos_in_table_list= NULL;
00136   group= NULL;
00137   _alias.clear();
00138   null_flags= NULL;
00139 
00140   lock_position= 0;
00141   lock_data_start= 0;
00142   lock_count= 0;
00143   used_fields= 0;
00144   status= 0;
00145   derived_select_number= 0;
00146   current_lock= F_UNLCK;
00147   copy_blobs= false;
00148 
00149   maybe_null= false;
00150 
00151   null_row= false;
00152 
00153   force_index= false;
00154   distinct= false;
00155   const_table= false;
00156   no_rows= false;
00157   key_read= false;
00158   no_keyread= false;
00159 
00160   open_placeholder= false;
00161   locked_by_name= false;
00162   no_cache= false;
00163 
00164   auto_increment_field_not_null= false;
00165   alias_name_used= false;
00166 
00167   query_id= 0;
00168   quick_condition_rows= 0;
00169 
00170   timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
00171   map= 0;
00172 
00173   reginfo.reset();
00174 
00175   covering_keys.reset();
00176 
00177   quick_keys.reset();
00178   merge_keys.reset();
00179 
00180   keys_in_use_for_query.reset();
00181   keys_in_use_for_group_by.reset();
00182   keys_in_use_for_order_by.reset();
00183 
00184   memset(quick_rows, 0, sizeof(ha_rows) * MAX_KEY);
00185   memset(const_key_parts, 0, sizeof(ha_rows) * MAX_KEY);
00186 
00187   memset(quick_key_parts, 0, sizeof(unsigned int) * MAX_KEY);
00188   memset(quick_n_ranges, 0, sizeof(unsigned int) * MAX_KEY);
00189 
00190   mem_root.init(TABLE_ALLOC_BLOCK_SIZE);
00191 }
00192 
00193 
00194 
00195 /* Deallocate temporary blob storage */
00196 
00197 void free_blobs(Table *table)
00198 {
00199   uint32_t *ptr, *end;
00200   for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
00201        ptr != end ;
00202        ptr++)
00203   {
00204     ((Field_blob*) table->getField(*ptr))->free();
00205   }
00206 }
00207 
00208 
00209 TYPELIB *typelib(memory::Root& mem_root, List<String> &strings)
00210 {
00211   TYPELIB *result= new (mem_root) TYPELIB;
00212   result->count= strings.size();
00213   result->name= "";
00214   result->type_names= (const char**) mem_root.alloc((sizeof(char*) + sizeof(uint32_t)) * (result->count + 1));
00215   result->type_lengths= (uint*) (result->type_names + result->count + 1);
00216 
00217   List<String>::iterator it(strings.begin());
00218   String *tmp;
00219   for (uint32_t i= 0; (tmp= it++); i++)
00220   {
00221     result->type_names[i]= tmp->ptr();
00222     result->type_lengths[i]= tmp->length();
00223   }
00224 
00225   result->type_names[result->count]= 0;   // End marker
00226   result->type_lengths[result->count]= 0;
00227 
00228   return result;
00229 }
00230 
00231   /* Check that the integer is in the internal */
00232 
00233 int set_zone(int nr, int min_zone, int max_zone)
00234 {
00235   if (nr<=min_zone)
00236     return (min_zone);
00237   if (nr>=max_zone)
00238     return (max_zone);
00239   return (nr);
00240 } /* set_zone */
00241 
00242 
00243 /*
00244   Store an SQL quoted string.
00245 
00246   SYNOPSIS
00247     append_unescaped()
00248     res   result String
00249     pos   string to be quoted
00250     length  it's length
00251 
00252   NOTE
00253     This function works correctly with utf8 or single-byte charset strings.
00254     May fail with some multibyte charsets though.
00255 */
00256 
00257 void append_unescaped(String *res, const char *pos, uint32_t length)
00258 {
00259   const char *end= pos+length;
00260   res->append('\'');
00261 
00262   for (; pos != end ; pos++)
00263   {
00264     uint32_t mblen;
00265     if (use_mb(default_charset_info) &&
00266         (mblen= my_ismbchar(default_charset_info, pos, end)))
00267     {
00268       res->append(pos, mblen);
00269       pos+= mblen - 1;
00270       if (pos >= end)
00271         break;
00272       continue;
00273     }
00274 
00275     switch (*pos) {
00276     case 0:       /* Must be escaped for 'mysql' */
00277       res->append('\\');
00278       res->append('0');
00279       break;
00280     case '\n':        /* Must be escaped for logs */
00281       res->append('\\');
00282       res->append('n');
00283       break;
00284     case '\r':
00285       res->append('\\');    /* This gives better readability */
00286       res->append('r');
00287       break;
00288     case '\\':
00289       res->append('\\');    /* Because of the sql syntax */
00290       res->append('\\');
00291       break;
00292     case '\'':
00293       res->append('\'');    /* Because of the sql syntax */
00294       res->append('\'');
00295       break;
00296     default:
00297       res->append(*pos);
00298       break;
00299     }
00300   }
00301   res->append('\'');
00302 }
00303 
00304 /*
00305   Allow anything as a table name, as long as it doesn't contain an
00306   ' ' at the end
00307   returns 1 on error
00308 */
00309 bool check_table_name(str_ref str)
00310 {
00311   return str.empty() || str.size() > NAME_LEN || str.data()[str.size() - 1] == ' ' || check_identifier_name(str);
00312 }
00313 
00314 
00315 /*
00316   Eventually, a "length" argument should be added
00317   to this function, and the inner loop changed to
00318   check_identifier_name() call.
00319 */
00320 bool check_column_name(const char *name)
00321 {
00322   uint32_t name_length= 0;  // name length in symbols
00323   bool last_char_is_space= true;
00324 
00325   while (*name)
00326   {
00327     last_char_is_space= system_charset_info->isspace(*name);
00328     if (use_mb(system_charset_info))
00329     {
00330       int len=my_ismbchar(system_charset_info, name,
00331                           name+system_charset_info->mbmaxlen);
00332       if (len)
00333       {
00334         if (len > 3) /* Disallow non-BMP characters */
00335           return 1;
00336         name += len;
00337         name_length++;
00338         continue;
00339       }
00340     }
00341     /*
00342       NAMES_SEP_CHAR is used in FRM format to separate SET and ENUM values.
00343       It is defined as 0xFF, which is a not valid byte in utf8.
00344       This assert is to catch use of this byte if we decide to
00345       use non-utf8 as system_character_set.
00346     */
00347     assert(*name != NAMES_SEP_CHAR);
00348     name++;
00349     name_length++;
00350   }
00351   /* Error if empty or too long column name */
00352   return last_char_is_space || (uint32_t) name_length > NAME_CHAR_LEN;
00353 }
00354 
00355 
00356 /*****************************************************************************
00357   Functions to handle column usage bitmaps (read_set, write_set etc...)
00358 *****************************************************************************/
00359 
00360 /* Reset all columns bitmaps */
00361 
00362 void Table::clear_column_bitmaps()
00363 {
00364   /*
00365     Reset column read/write usage. It's identical to:
00366     bitmap_clear_all(&table->def_read_set);
00367     bitmap_clear_all(&table->def_write_set);
00368   */
00369   def_read_set.reset();
00370   def_write_set.reset();
00371   column_bitmaps_set(def_read_set, def_write_set);
00372 }
00373 
00374 
00375 /*
00376   Tell Cursor we are going to call position() and rnd_pos() later.
00377 
00378   NOTES:
00379   This is needed for handlers that uses the primary key to find the
00380   row. In this case we have to extend the read bitmap with the primary
00381   key fields.
00382 */
00383 
00384 void Table::prepare_for_position()
00385 {
00386 
00387   if ((cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
00388       getShare()->hasPrimaryKey())
00389   {
00390     mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
00391   }
00392   return;
00393 }
00394 
00395 
00396 /*
00397   Mark that only fields from one key is used
00398 
00399   NOTE:
00400     This changes the bitmap to use the tmp bitmap
00401     After this, you can't access any other columns in the table until
00402     bitmaps are reset, for example with Table::clear_column_bitmaps()
00403     or Table::restore_column_maps_after_mark_index()
00404 */
00405 
00406 void Table::mark_columns_used_by_index(uint32_t index)
00407 {
00408   boost::dynamic_bitset<> *bitmap= &tmp_set;
00409 
00410   (void) cursor->extra(HA_EXTRA_KEYREAD);
00411   bitmap->reset();
00412   mark_columns_used_by_index_no_reset(index, *bitmap);
00413   column_bitmaps_set(*bitmap, *bitmap);
00414   return;
00415 }
00416 
00417 
00418 /*
00419   Restore to use normal column maps after key read
00420 
00421   NOTES
00422     This reverse the change done by mark_columns_used_by_index
00423 
00424   WARNING
00425     For this to work, one must have the normal table maps in place
00426     when calling mark_columns_used_by_index
00427 */
00428 
00429 void Table::restore_column_maps_after_mark_index()
00430 {
00431 
00432   key_read= 0;
00433   (void) cursor->extra(HA_EXTRA_NO_KEYREAD);
00434   default_column_bitmaps();
00435   return;
00436 }
00437 
00438 
00439 /*
00440   mark columns used by key, but don't reset other fields
00441 */
00442 
00443 void Table::mark_columns_used_by_index_no_reset(uint32_t index)
00444 {
00445     mark_columns_used_by_index_no_reset(index, *read_set);
00446 }
00447 
00448 
00449 void Table::mark_columns_used_by_index_no_reset(uint32_t index,
00450                                                 boost::dynamic_bitset<>& bitmap)
00451 {
00452   KeyPartInfo *key_part= key_info[index].key_part;
00453   KeyPartInfo *key_part_end= (key_part + key_info[index].key_parts);
00454   for (; key_part != key_part_end; key_part++)
00455   {
00456     if (! bitmap.empty())
00457       bitmap.set(key_part->fieldnr-1);
00458   }
00459 }
00460 
00461 
00462 /*
00463   Mark auto-increment fields as used fields in both read and write maps
00464 
00465   NOTES
00466     This is needed in insert & update as the auto-increment field is
00467     always set and sometimes read.
00468 */
00469 
00470 void Table::mark_auto_increment_column()
00471 {
00472   assert(found_next_number_field);
00473   /*
00474     We must set bit in read set as update_auto_increment() is using the
00475     store() to check overflow of auto_increment values
00476   */
00477   setReadSet(found_next_number_field->position());
00478   setWriteSet(found_next_number_field->position());
00479   if (getShare()->next_number_keypart)
00480     mark_columns_used_by_index_no_reset(getShare()->next_number_index);
00481 }
00482 
00483 
00484 /*
00485   Mark columns needed for doing an delete of a row
00486 
00487   DESCRIPTON
00488     Some table engines don't have a cursor on the retrieve rows
00489     so they need either to use the primary key or all columns to
00490     be able to delete a row.
00491 
00492     If the engine needs this, the function works as follows:
00493     - If primary key exits, mark the primary key columns to be read.
00494     - If not, mark all columns to be read
00495 
00496     If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
00497     mark all key columns as 'to-be-read'. This allows the engine to
00498     loop over the given record to find all keys and doesn't have to
00499     retrieve the row again.
00500 */
00501 
00502 void Table::mark_columns_needed_for_delete()
00503 {
00504   /*
00505     If the Cursor has no cursor capabilites, or we have row-based
00506     replication active for the current statement, we have to read
00507     either the primary key, the hidden primary key or all columns to
00508     be able to do an delete
00509 
00510   */
00511   if (not getShare()->hasPrimaryKey())
00512   {
00513     /* fallback to use all columns in the table to identify row */
00514     use_all_columns();
00515     return;
00516   }
00517   else
00518     mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
00519 
00520   /* If we the engine wants all predicates we mark all keys */
00521   if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
00522   {
00523     Field **reg_field;
00524     for (reg_field= field ; *reg_field ; reg_field++)
00525     {
00526       if ((*reg_field)->flags & PART_KEY_FLAG)
00527         setReadSet((*reg_field)->position());
00528     }
00529   }
00530 }
00531 
00532 
00533 /*
00534   Mark columns needed for doing an update of a row
00535 
00536   DESCRIPTON
00537     Some engines needs to have all columns in an update (to be able to
00538     build a complete row). If this is the case, we mark all not
00539     updated columns to be read.
00540 
00541     If this is no the case, we do like in the delete case and mark
00542     if neeed, either the primary key column or all columns to be read.
00543     (see mark_columns_needed_for_delete() for details)
00544 
00545     If the engine has HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
00546     mark all USED key columns as 'to-be-read'. This allows the engine to
00547     loop over the given record to find all changed keys and doesn't have to
00548     retrieve the row again.
00549 */
00550 
00551 void Table::mark_columns_needed_for_update()
00552 {
00553   /*
00554     If the Cursor has no cursor capabilites, or we have row-based
00555     logging active for the current statement, we have to read either
00556     the primary key, the hidden primary key or all columns to be
00557     able to do an update
00558   */
00559   if (not getShare()->hasPrimaryKey())
00560   {
00561     /* fallback to use all columns in the table to identify row */
00562     use_all_columns();
00563     return;
00564   }
00565   else
00566     mark_columns_used_by_index_no_reset(getShare()->getPrimaryKey());
00567 
00568   if (cursor->getEngine()->check_flag(HTON_BIT_REQUIRES_KEY_COLUMNS_FOR_DELETE))
00569   {
00570     /* Mark all used key columns for read */
00571     Field **reg_field;
00572     for (reg_field= field ; *reg_field ; reg_field++)
00573     {
00574       /* Merge keys is all keys that had a column refered to in the query */
00575       if (is_overlapping(merge_keys, (*reg_field)->part_of_key))
00576         setReadSet((*reg_field)->position());
00577     }
00578   }
00579 
00580 }
00581 
00582 
00583 /*
00584   Mark columns the Cursor needs for doing an insert
00585 
00586   For now, this is used to mark fields used by the trigger
00587   as changed.
00588 */
00589 
00590 void Table::mark_columns_needed_for_insert()
00591 {
00592   if (found_next_number_field)
00593     mark_auto_increment_column();
00594 }
00595 
00596 
00597 
00598 size_t Table::max_row_length(const unsigned char *data)
00599 {
00600   size_t length= getRecordLength() + 2 * sizeFields();
00601   uint32_t *const beg= getBlobField();
00602   uint32_t *const end= beg + sizeBlobFields();
00603 
00604   for (uint32_t *ptr= beg ; ptr != end ; ++ptr)
00605   {
00606     Field_blob* const blob= (Field_blob*) field[*ptr];
00607     length+= blob->get_length((const unsigned char*)
00608                               (data + blob->offset(getInsertRecord()))) +
00609       HA_KEY_BLOB_LENGTH;
00610   }
00611   return length;
00612 }
00613 
00614 void Table::setVariableWidth(void)
00615 {
00616   assert(in_use);
00617   if (in_use && in_use->lex().sql_command == SQLCOM_CREATE_TABLE)
00618   {
00619     getMutableShare()->setVariableWidth();
00620     return;
00621   }
00622 
00623   assert(0); // Programming error, you can't set this on a plain old Table.
00624 }
00625 
00626 /****************************************************************************
00627  Functions for creating temporary tables.
00628 ****************************************************************************/
00651 Field *create_tmp_field_from_field(Session *session, Field *org_field,
00652                                    const char *name, Table *table,
00653                                    Item_field *item, uint32_t convert_blob_length)
00654 {
00655   Field *new_field;
00656 
00657   /*
00658     Make sure that the blob fits into a Field_varstring which has
00659     2-byte lenght.
00660   */
00661   if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE && (org_field->flags & BLOB_FLAG))
00662   {
00663     table->setVariableWidth();
00664     new_field= new Field_varstring(convert_blob_length, org_field->maybe_null(), org_field->field_name, org_field->charset());
00665   }
00666   else
00667   {
00668     new_field= org_field->new_field(session->mem_root, table, table == org_field->getTable());
00669   }
00670   if (new_field)
00671   {
00672     new_field->init(table);
00673     new_field->orig_table= org_field->orig_table;
00674     if (item)
00675       item->result_field= new_field;
00676     else
00677       new_field->field_name= name;
00678     new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
00679     if (org_field->maybe_null() || (item && item->maybe_null))
00680       new_field->flags&= ~NOT_NULL_FLAG;  // Because of outer join
00681     if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
00682       table->getMutableShare()->db_create_options|= HA_OPTION_PACK_RECORD;
00683     else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
00684       ((Field_double *) new_field)->not_fixed= true;
00685   }
00686   return new_field;
00687 }
00688 
00689 
00716 Table *
00717 create_tmp_table(Session *session,Tmp_Table_Param *param,List<Item> &fields,
00718      Order *group, bool distinct, bool save_sum_fields,
00719      uint64_t select_options, ha_rows rows_limit,
00720      const char *table_alias)
00721 {
00722   uint  i,field_count,null_count,null_pack_length;
00723   uint32_t  copy_func_count= param->func_count;
00724   uint32_t  hidden_null_count, hidden_null_pack_length, hidden_field_count;
00725   uint32_t  blob_count,group_null_items, string_count;
00726   uint32_t fieldnr= 0;
00727   ulong reclength, string_total_length;
00728   bool  using_unique_constraint= false;
00729   bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
00730   unsigned char *pos, *group_buff;
00731   unsigned char *null_flags;
00732   Field **reg_field, **from_field, **default_field;
00733   CopyField *copy= 0;
00734   KeyInfo *keyinfo;
00735   KeyPartInfo *key_part_info;
00736   Item **copy_func;
00737   MI_COLUMNDEF *recinfo;
00738   uint32_t total_uneven_bit_length= 0;
00739   bool force_copy_fields= param->force_copy_fields;
00740   uint64_t max_rows= 0;
00741 
00742   session->status_var.created_tmp_tables++;
00743 
00744   if (group)
00745   {
00746     if (! param->quick_group)
00747     {
00748       group= 0;         // Can't use group key
00749     }
00750     else for (Order *tmp=group ; tmp ; tmp=tmp->next)
00751     {
00752       /*
00753         marker == 4 means two things:
00754         - store NULLs in the key, and
00755         - convert BIT fields to 64-bit long, needed because MEMORY tables
00756           can't index BIT fields.
00757       */
00758       (*tmp->item)->marker= 4;
00759       if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
00760   using_unique_constraint= true;
00761     }
00762     if (param->group_length >= MAX_BLOB_WIDTH)
00763       using_unique_constraint= true;
00764     if (group)
00765       distinct= 0;        // Can't use distinct
00766   }
00767 
00768   field_count=param->field_count+param->func_count+param->sum_func_count;
00769   hidden_field_count=param->hidden_field_count;
00770 
00771   /*
00772     When loose index scan is employed as access method, it already
00773     computes all groups and the result of all aggregate functions. We
00774     make space for the items of the aggregate function in the list of
00775     functions Tmp_Table_Param::items_to_copy, so that the values of
00776     these items are stored in the temporary table.
00777   */
00778   if (param->precomputed_group_by)
00779   {
00780     copy_func_count+= param->sum_func_count;
00781   }
00782 
00783   table::Singular* table= &session->getInstanceTable(); // This will not go into the tableshare cache, so no key is used.
00784 
00785   table->mem().multi_alloc(0,
00786     &default_field, sizeof(Field*) * (field_count),
00787     &from_field, sizeof(Field*)*field_count,
00788     &copy_func, sizeof(*copy_func)*(copy_func_count+1),
00789     &param->keyinfo, sizeof(*param->keyinfo),
00790     &key_part_info, sizeof(*key_part_info)*(param->group_parts+1),
00791     &param->start_recinfo, sizeof(*param->recinfo)*(field_count*2+4),
00792     &group_buff, (group && ! using_unique_constraint ? param->group_length : 0),
00793     NULL);
00794   /* CopyField belongs to Tmp_Table_Param, allocate it in Session mem_root */
00795   param->copy_field= copy= new (session->mem_root) CopyField[field_count];
00796   param->items_to_copy= copy_func;
00797   /* make table according to fields */
00798 
00799   memset(default_field, 0, sizeof(Field*) * (field_count));
00800   memset(from_field, 0, sizeof(Field*)*field_count);
00801 
00802   memory::Root* mem_root_save= session->mem_root;
00803   session->mem_root= &table->mem();
00804 
00805   table->getMutableShare()->setFields(field_count+1);
00806   table->setFields(table->getMutableShare()->getFields(true));
00807   reg_field= table->getMutableShare()->getFields(true);
00808   table->setAlias(table_alias);
00809   table->reginfo.lock_type=TL_WRITE;  /* Will be updated */
00810   table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
00811   table->map=1;
00812   table->copy_blobs= 1;
00813   assert(session);
00814   table->in_use= session;
00815   table->quick_keys.reset();
00816   table->covering_keys.reset();
00817   table->keys_in_use_for_query.reset();
00818 
00819   table->getMutableShare()->blob_field.resize(field_count+1);
00820   uint32_t *blob_field= &table->getMutableShare()->blob_field[0];
00821   table->getMutableShare()->db_low_byte_first=1;                // True for HEAP and MyISAM
00822   table->getMutableShare()->table_charset= param->table_charset;
00823   table->getMutableShare()->keys_for_keyread.reset();
00824   table->getMutableShare()->keys_in_use.reset();
00825 
00826   /* Calculate which type of fields we will store in the temporary table */
00827 
00828   reclength= string_total_length= 0;
00829   blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
00830   param->using_indirect_summary_function= 0;
00831 
00832   List<Item>::iterator li(fields.begin());
00833   Field **tmp_from_field=from_field;
00834   while (Item* item=li++)
00835   {
00836     Item::Type type=item->type();
00837     if (not_all_columns)
00838     {
00839       if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
00840       {
00841         if (item->used_tables() & OUTER_REF_TABLE_BIT)
00842           item->update_used_tables();
00843         if (type == Item::SUBSELECT_ITEM ||
00844             (item->used_tables() & ~OUTER_REF_TABLE_BIT))
00845         {
00846     /*
00847       Mark that the we have ignored an item that refers to a summary
00848       function. We need to know this if someone is going to use
00849       DISTINCT on the result.
00850     */
00851     param->using_indirect_summary_function=1;
00852     continue;
00853         }
00854       }
00855       if (item->const_item() && (int) hidden_field_count <= 0)
00856         continue; // We don't have to store this
00857     }
00858     if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
00859     {           /* Can't calc group yet */
00860       ((Item_sum*) item)->result_field= 0;
00861       for (i= 0 ; i < ((Item_sum*) item)->arg_count ; i++)
00862       {
00863   Item **argp= ((Item_sum*) item)->args + i;
00864   Item *arg= *argp;
00865   if (!arg->const_item())
00866   {
00867     Field *new_field=
00868             create_tmp_field(session, table, arg, arg->type(), &copy_func,
00869                              tmp_from_field, &default_field[fieldnr],
00870                              group != 0,not_all_columns,
00871                              false,
00872                              param->convert_blob_length);
00873     if (!new_field)
00874       goto err;         // Should be OOM
00875     tmp_from_field++;
00876     reclength+=new_field->pack_length();
00877     if (new_field->flags & BLOB_FLAG)
00878     {
00879       *blob_field++= fieldnr;
00880       blob_count++;
00881     }
00882     *(reg_field++)= new_field;
00883           if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
00884           {
00885             string_count++;
00886             string_total_length+= new_field->pack_length();
00887           }
00888           session->mem_root= mem_root_save;
00889           *argp= new Item_field(new_field);
00890           session->mem_root= &table->mem();
00891     if (!(new_field->flags & NOT_NULL_FLAG))
00892           {
00893       null_count++;
00894             /*
00895               new_field->maybe_null() is still false, it will be
00896               changed below. But we have to setup Item_field correctly
00897             */
00898             (*argp)->maybe_null=1;
00899           }
00900           new_field->setPosition(fieldnr++);
00901   }
00902       }
00903     }
00904     else
00905     {
00906       /*
00907   The last parameter to create_tmp_field() is a bit tricky:
00908 
00909   We need to set it to 0 in union, to get fill_record() to modify the
00910   temporary table.
00911   We need to set it to 1 on multi-table-update and in select to
00912   write rows to the temporary table.
00913   We here distinguish between UNION and multi-table-updates by the fact
00914   that in the later case group is set to the row pointer.
00915       */
00916       Field *new_field=
00917         create_tmp_field(session, table, item, type, &copy_func,
00918                          tmp_from_field, &default_field[fieldnr],
00919                          group != 0,
00920                          !force_copy_fields &&
00921                            (not_all_columns || group != 0),
00922                          force_copy_fields,
00923                          param->convert_blob_length);
00924 
00925       if (!new_field)
00926       {
00927   if (session->is_fatal_error)
00928     goto err;       // Got OOM
00929   continue;       // Some kindf of const item
00930       }
00931       if (type == Item::SUM_FUNC_ITEM)
00932   ((Item_sum *) item)->result_field= new_field;
00933       tmp_from_field++;
00934       reclength+=new_field->pack_length();
00935       if (!(new_field->flags & NOT_NULL_FLAG))
00936   null_count++;
00937       if (new_field->flags & BLOB_FLAG)
00938       {
00939         *blob_field++= fieldnr;
00940   blob_count++;
00941       }
00942       if (item->marker == 4 && item->maybe_null)
00943       {
00944   group_null_items++;
00945   new_field->flags|= GROUP_FLAG;
00946       }
00947       new_field->setPosition(fieldnr++);
00948       *(reg_field++)= new_field;
00949     }
00950     if (!--hidden_field_count)
00951     {
00952       /*
00953         This was the last hidden field; Remember how many hidden fields could
00954         have null
00955       */
00956       hidden_null_count=null_count;
00957       /*
00958   We need to update hidden_field_count as we may have stored group
00959   functions with constant arguments
00960       */
00961       param->hidden_field_count= fieldnr;
00962       null_count= 0;
00963     }
00964   }
00965   assert(fieldnr == (uint32_t) (reg_field - table->getFields()));
00966   assert(field_count >= (uint32_t) (reg_field - table->getFields()));
00967   field_count= fieldnr;
00968   *reg_field= 0;
00969   *blob_field= 0;       // End marker
00970   table->getMutableShare()->setFieldSize(field_count);
00971 
00972   /* If result table is small; use a heap */
00973   /* future: storage engine selection can be made dynamic? */
00974   if (blob_count || using_unique_constraint || 
00975       (session->lex().select_lex.options & SELECT_BIG_RESULT) ||
00976       (session->lex().current_select->olap == ROLLUP_TYPE) ||
00977       (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) == OPTION_BIG_TABLES)
00978   {
00979     table->getMutableShare()->storage_engine= myisam_engine;
00980     table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
00981     if (group &&
00982   (param->group_parts > table->cursor->getEngine()->max_key_parts() ||
00983    param->group_length > table->cursor->getEngine()->max_key_length()))
00984     {
00985       using_unique_constraint= true;
00986     }
00987   }
00988   else
00989   {
00990     table->getMutableShare()->storage_engine= heap_engine;
00991     table->cursor= table->getMutableShare()->db_type()->getCursor(*table);
00992   }
00993   if (! table->cursor)
00994     goto err;
00995 
00996 
00997   if (! using_unique_constraint)
00998     reclength+= group_null_items; // null flag is stored separately
00999 
01000   table->getMutableShare()->blob_fields= blob_count;
01001   if (blob_count == 0)
01002   {
01003     /* We need to ensure that first byte is not 0 for the delete link */
01004     if (param->hidden_field_count)
01005       hidden_null_count++;
01006     else
01007       null_count++;
01008   }
01009   hidden_null_pack_length=(hidden_null_count+7)/8;
01010   null_pack_length= (hidden_null_pack_length +
01011                      (null_count + total_uneven_bit_length + 7) / 8);
01012   reclength+=null_pack_length;
01013   if (!reclength)
01014     reclength=1;        // Dummy select
01015 
01016   table->getMutableShare()->setRecordLength(reclength);
01017   {
01018     uint32_t alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
01019     table->getMutableShare()->rec_buff_length= alloc_length;
01020     table->record[0]= table->alloc(alloc_length*2);
01021     table->record[1]= table->getInsertRecord()+alloc_length;
01022     table->getMutableShare()->resizeDefaultValues(alloc_length);
01023   }
01024   copy_func[0]= 0;        // End marker
01025   param->func_count= copy_func - param->items_to_copy;
01026 
01027   table->setup_tmp_table_column_bitmaps();
01028 
01029   recinfo=param->start_recinfo;
01030   null_flags= table->getInsertRecord();
01031   pos=table->getInsertRecord()+ null_pack_length;
01032   if (null_pack_length)
01033   {
01034     memset(recinfo, 0, sizeof(*recinfo));
01035     recinfo->type=FIELD_NORMAL;
01036     recinfo->length=null_pack_length;
01037     recinfo++;
01038     memset(null_flags, 255, null_pack_length);  // Set null fields
01039 
01040     table->null_flags= table->getInsertRecord();
01041     table->getMutableShare()->null_fields= null_count+ hidden_null_count;
01042     table->getMutableShare()->null_bytes= null_pack_length;
01043   }
01044   null_count= (blob_count == 0) ? 1 : 0;
01045   hidden_field_count=param->hidden_field_count;
01046   for (i= 0,reg_field= table->getFields(); i < field_count; i++,reg_field++,recinfo++)
01047   {
01048     Field *field= *reg_field;
01049     uint32_t length;
01050     memset(recinfo, 0, sizeof(*recinfo));
01051 
01052     if (!(field->flags & NOT_NULL_FLAG))
01053     {
01054       if (field->flags & GROUP_FLAG && !using_unique_constraint)
01055       {
01056   /*
01057     We have to reserve one byte here for NULL bits,
01058     as this is updated by 'end_update()'
01059   */
01060   *pos++= '\0';       // Null is stored here
01061   recinfo->length= 1;
01062   recinfo->type=FIELD_NORMAL;
01063   recinfo++;
01064   memset(recinfo, 0, sizeof(*recinfo));
01065       }
01066       else
01067       {
01068   recinfo->null_bit= 1 << (null_count & 7);
01069   recinfo->null_pos= null_count/8;
01070       }
01071       field->move_field(pos,null_flags+null_count/8,
01072       1 << (null_count & 7));
01073       null_count++;
01074     }
01075     else
01076       field->move_field(pos,(unsigned char*) 0,0);
01077     field->reset();
01078 
01079     /*
01080       Test if there is a default field value. The test for ->ptr is to skip
01081       'offset' fields generated by initalize_tables
01082     */
01083     if (default_field[i] && default_field[i]->ptr)
01084     {
01085       /*
01086          default_field[i] is set only in the cases  when 'field' can
01087          inherit the default value that is defined for the field referred
01088          by the Item_field object from which 'field' has been created.
01089       */
01090       ptrdiff_t diff;
01091       Field *orig_field= default_field[i];
01092       /* Get the value from default_values */
01093       diff= (ptrdiff_t) (orig_field->getTable()->getDefaultValues() - orig_field->getTable()->getInsertRecord());
01094       orig_field->move_field_offset(diff);      // Points now at default_values
01095       if (orig_field->is_real_null())
01096         field->set_null();
01097       else
01098       {
01099         field->set_notnull();
01100         memcpy(field->ptr, orig_field->ptr, field->pack_length());
01101       }
01102       orig_field->move_field_offset(-diff);     // Back to getInsertRecord()
01103     }
01104 
01105     if (from_field[i])
01106     {           /* Not a table Item */
01107       copy->set(field,from_field[i],save_sum_fields);
01108       copy++;
01109     }
01110     length=field->pack_length();
01111     pos+= length;
01112 
01113     /* Make entry for create table */
01114     recinfo->length=length;
01115     if (field->flags & BLOB_FLAG)
01116       recinfo->type= (int) FIELD_BLOB;
01117     else
01118       recinfo->type=FIELD_NORMAL;
01119     if (!--hidden_field_count)
01120       null_count=(null_count+7) & ~7;   // move to next byte
01121   }
01122 
01123   param->copy_field_end=copy;
01124   param->recinfo=recinfo;
01125   table->storeRecordAsDefault();        // Make empty default record
01126 
01127   if (session->variables.tmp_table_size == ~ (uint64_t) 0)    // No limit
01128   {
01129     max_rows= ~(uint64_t) 0;
01130   }
01131   else
01132   {
01133     max_rows= (uint64_t) (((table->getMutableShare()->db_type() == heap_engine) ?
01134                            min(session->variables.tmp_table_size,
01135                                session->variables.max_heap_table_size) :
01136                            session->variables.tmp_table_size) /
01137                           table->getMutableShare()->getRecordLength());
01138   }
01139 
01140   set_if_bigger(max_rows, (uint64_t)1); // For dummy start options
01141   /*
01142     Push the LIMIT clause to the temporary table creation, so that we
01143     materialize only up to 'rows_limit' records instead of all result records.
01144   */
01145   set_if_smaller(max_rows, rows_limit);
01146 
01147   table->getMutableShare()->setMaxRows(max_rows);
01148 
01149   param->end_write_records= rows_limit;
01150 
01151   keyinfo= param->keyinfo;
01152 
01153   if (group)
01154   {
01155     table->group=group;       /* Table is grouped by key */
01156     param->group_buff=group_buff;
01157     table->getMutableShare()->keys=1;
01158     table->getMutableShare()->uniques= test(using_unique_constraint);
01159     table->key_info=keyinfo;
01160     keyinfo->key_part=key_part_info;
01161     keyinfo->flags=HA_NOSAME;
01162     keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
01163     keyinfo->key_length= 0;
01164     keyinfo->rec_per_key= 0;
01165     keyinfo->algorithm= HA_KEY_ALG_UNDEF;
01166     keyinfo->name= (char*) "group_key";
01167     Order *cur_group= group;
01168     for (; cur_group ; cur_group= cur_group->next, key_part_info++)
01169     {
01170       Field *field=(*cur_group->item)->get_tmp_table_field();
01171       bool maybe_null=(*cur_group->item)->maybe_null;
01172       key_part_info->null_bit= 0;
01173       key_part_info->field=  field;
01174       key_part_info->offset= field->offset(table->getInsertRecord());
01175       key_part_info->length= (uint16_t) field->key_length();
01176       key_part_info->type=   (uint8_t) field->key_type();
01177       key_part_info->key_type= 
01178   ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
01179    (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
01180    (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
01181   0 : 1;
01182       if (!using_unique_constraint)
01183       {
01184   cur_group->buff=(char*) group_buff;
01185   if (!(cur_group->field= field->new_key_field(session->mem_root,table,
01186                                                      group_buff +
01187                                                      test(maybe_null),
01188                                                      field->null_ptr,
01189                                                      field->null_bit)))
01190     goto err;
01191   if (maybe_null)
01192   {
01193     /*
01194       To be able to group on NULL, we reserved place in group_buff
01195       for the NULL flag just before the column. (see above).
01196       The field data is after this flag.
01197       The NULL flag is updated in 'end_update()' and 'end_write()'
01198     */
01199     keyinfo->flags|= HA_NULL_ARE_EQUAL; // def. that NULL == NULL
01200     key_part_info->null_bit=field->null_bit;
01201     key_part_info->null_offset= (uint32_t) (field->null_ptr -
01202                 (unsigned char*) table->getInsertRecord());
01203           cur_group->buff++;                        // Pointer to field data
01204     group_buff++;                         // Skipp null flag
01205   }
01206         /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
01207         key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
01208   group_buff+= cur_group->field->pack_length();
01209       }
01210       keyinfo->key_length+=  key_part_info->length;
01211     }
01212   }
01213 
01214   if (distinct && field_count != param->hidden_field_count)
01215   {
01216     /*
01217       Create an unique key or an unique constraint over all columns
01218       that should be in the result.  In the temporary table, there are
01219       'param->hidden_field_count' extra columns, whose null bits are stored
01220       in the first 'hidden_null_pack_length' bytes of the row.
01221     */
01222     if (blob_count)
01223     {
01224       /*
01225         Special mode for index creation in MyISAM used to support unique
01226         indexes on blobs with arbitrary length. Such indexes cannot be
01227         used for lookups.
01228       */
01229       table->getMutableShare()->uniques= 1;
01230     }
01231     null_pack_length-=hidden_null_pack_length;
01232     keyinfo->key_parts= ((field_count-param->hidden_field_count)+
01233        (table->getMutableShare()->uniques ? test(null_pack_length) : 0));
01234     table->distinct= 1;
01235     table->getMutableShare()->keys= 1;
01236     key_part_info= new (table->mem()) KeyPartInfo[keyinfo->key_parts];
01237     memset(key_part_info, 0, keyinfo->key_parts * sizeof(KeyPartInfo));
01238     table->key_info=keyinfo;
01239     keyinfo->key_part=key_part_info;
01240     keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
01241     keyinfo->key_length=(uint16_t) reclength;
01242     keyinfo->name= (char*) "distinct_key";
01243     keyinfo->algorithm= HA_KEY_ALG_UNDEF;
01244     keyinfo->rec_per_key= 0;
01245 
01246     /*
01247       Create an extra field to hold NULL bits so that unique indexes on
01248       blobs can distinguish NULL from 0. This extra field is not needed
01249       when we do not use UNIQUE indexes for blobs.
01250     */
01251     if (null_pack_length && table->getMutableShare()->uniques)
01252     {
01253       key_part_info->null_bit= 0;
01254       key_part_info->offset=hidden_null_pack_length;
01255       key_part_info->length=null_pack_length;
01256       table->setVariableWidth();
01257       key_part_info->field= new Field_varstring(table->getInsertRecord(),
01258                                                 (uint32_t) key_part_info->length,
01259                                                 0,
01260                                                 (unsigned char*) 0,
01261                                                 (uint32_t) 0,
01262                                                 NULL,
01263                                                 &my_charset_bin);
01264       if (!key_part_info->field)
01265         goto err;
01266       key_part_info->field->init(table);
01267       key_part_info->key_type= 1; /* binary comparison */
01268       key_part_info->type=    HA_KEYTYPE_BINARY;
01269       key_part_info++;
01270     }
01271     /* Create a distinct key over the columns we are going to return */
01272     for (i=param->hidden_field_count, reg_field=table->getFields() + i ;
01273    i < field_count;
01274    i++, reg_field++, key_part_info++)
01275     {
01276       key_part_info->null_bit= 0;
01277       key_part_info->field=    *reg_field;
01278       key_part_info->offset=   (*reg_field)->offset(table->getInsertRecord());
01279       key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
01280       /* @todo The below method of computing the key format length of the
01281         key part is a copy/paste from optimizer/range.cc, and table.cc.
01282         This should be factored out, e.g. as a method of Field.
01283         In addition it is not clear if any of the Field::*_length
01284         methods is supposed to compute the same length. If so, it
01285         might be reused.
01286       */
01287       key_part_info->store_length= key_part_info->length;
01288 
01289       if ((*reg_field)->real_maybe_null())
01290         key_part_info->store_length+= HA_KEY_NULL_LENGTH;
01291       if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB ||
01292           (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
01293         key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
01294 
01295       key_part_info->type=     (uint8_t) (*reg_field)->key_type();
01296       key_part_info->key_type =
01297   ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
01298    (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
01299    (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
01300   0 : 1;
01301     }
01302   }
01303 
01304   if (session->is_fatal_error)        // If end of memory
01305     goto err;
01306   table->getMutableShare()->db_record_offset= 1;
01307   if (table->getShare()->db_type() == myisam_engine)
01308   {
01309     if (table->create_myisam_tmp_table(param->keyinfo, param->start_recinfo,
01310                &param->recinfo, select_options))
01311       goto err;
01312   }
01313   assert(table->in_use);
01314   if (table->open_tmp_table())
01315     goto err;
01316 
01317   session->mem_root= mem_root_save;
01318 
01319   return(table);
01320 
01321 err:
01322   session->mem_root= mem_root_save;
01323   table= NULL;
01324 
01325   return NULL;
01326 }
01327 
01328 /****************************************************************************/
01329 
01330 void Table::column_bitmaps_set(boost::dynamic_bitset<>& read_set_arg,
01331                                boost::dynamic_bitset<>& write_set_arg)
01332 {
01333   read_set= &read_set_arg;
01334   write_set= &write_set_arg;
01335 }
01336 
01337 
01338 const boost::dynamic_bitset<> Table::use_all_columns(boost::dynamic_bitset<>& in_map)
01339 {
01340   const boost::dynamic_bitset<> old= in_map;
01341   in_map= getShare()->all_set;
01342   return old;
01343 }
01344 
01345 void Table::restore_column_map(const boost::dynamic_bitset<>& old)
01346 {
01347   for (boost::dynamic_bitset<>::size_type i= 0; i < old.size(); i++)
01348   {
01349     if (old.test(i))
01350     {
01351       read_set->set(i);
01352     }
01353     else
01354     {
01355       read_set->reset(i);
01356     }
01357   }
01358 }
01359 
01360 uint32_t Table::find_shortest_key(const key_map *usable_keys)
01361 {
01362   uint32_t min_length= UINT32_MAX;
01363   uint32_t best= MAX_KEY;
01364   if (usable_keys->any())
01365   {
01366     for (uint32_t nr= 0; nr < getShare()->sizeKeys() ; nr++)
01367     {
01368       if (usable_keys->test(nr))
01369       {
01370         if (key_info[nr].key_length < min_length)
01371         {
01372           min_length= key_info[nr].key_length;
01373           best=nr;
01374         }
01375       }
01376     }
01377   }
01378   return best;
01379 }
01380 
01381 /*****************************************************************************
01382   Remove duplicates from tmp table
01383   This should be recoded to add a unique index to the table and remove
01384   duplicates
01385   Table is a locked single thread table
01386   fields is the number of fields to check (from the end)
01387 *****************************************************************************/
01388 
01389 bool Table::compare_record(Field **ptr)
01390 {
01391   for (; *ptr ; ptr++)
01392   {
01393     if ((*ptr)->cmp_offset(getShare()->rec_buff_length))
01394       return true;
01395   }
01396   return false;
01397 }
01398 
01403 bool Table::records_are_comparable()
01404 {
01405   return ((getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) == 0) ||
01406           write_set->is_subset_of(*read_set));
01407 }
01408 
01422 bool Table::compare_records()
01423 {
01424   if (getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) != 0)
01425   {
01426     /*
01427       Storage engine may not have read all columns of the record.  Fields
01428       (including NULL bits) not in the write_set may not have been read and
01429       can therefore not be compared.
01430     */
01431     for (Field **ptr= this->field ; *ptr != NULL; ptr++)
01432     {
01433       Field *f= *ptr;
01434       if (write_set->test(f->position()))
01435       {
01436         if (f->real_maybe_null())
01437         {
01438           unsigned char null_byte_index= f->null_ptr - record[0];
01439 
01440           if (((record[0][null_byte_index]) & f->null_bit) !=
01441               ((record[1][null_byte_index]) & f->null_bit))
01442             return true;
01443         }
01444         if (f->cmp_binary_offset(getShare()->rec_buff_length))
01445           return true;
01446       }
01447     }
01448     return false;
01449   }
01450 
01451   /*
01452     The storage engine has read all columns, so it's safe to compare all bits
01453     including those not in the write_set. This is cheaper than the
01454     field-by-field comparison done above.
01455   */
01456   if (not getShare()->blob_fields + getShare()->hasVariableWidth())
01457     // Fixed-size record: do bitwise comparison of the records
01458     return memcmp(this->getInsertRecord(), this->getUpdateRecord(), (size_t) getShare()->getRecordLength());
01459 
01460   /* Compare null bits */
01461   if (memcmp(null_flags, null_flags + getShare()->rec_buff_length, getShare()->null_bytes))
01462     return true; /* Diff in NULL value */
01463 
01464   /* Compare updated fields */
01465   for (Field **ptr= field ; *ptr ; ptr++)
01466   {
01467     if (isWriteSet((*ptr)->position()) &&
01468   (*ptr)->cmp_binary_offset(getShare()->rec_buff_length))
01469       return true;
01470   }
01471   return false;
01472 }
01473 
01474 /*
01475  * Store a record from previous record into next
01476  *
01477  */
01478 void Table::storeRecord()
01479 {
01480   memcpy(getUpdateRecord(), getInsertRecord(), (size_t) getShare()->getRecordLength());
01481 }
01482 
01483 /*
01484  * Store a record as an insert
01485  *
01486  */
01487 void Table::storeRecordAsInsert()
01488 {
01489   assert(insert_values.size() >= getShare()->getRecordLength());
01490   memcpy(&insert_values[0], getInsertRecord(), (size_t) getShare()->getRecordLength());
01491 }
01492 
01493 /*
01494  * Store a record with default values
01495  *
01496  */
01497 void Table::storeRecordAsDefault()
01498 {
01499   memcpy(getMutableShare()->getDefaultValues(), getInsertRecord(), (size_t) getShare()->getRecordLength());
01500 }
01501 
01502 /*
01503  * Restore a record from previous record into next
01504  *
01505  */
01506 void Table::restoreRecord()
01507 {
01508   memcpy(getInsertRecord(), getUpdateRecord(), (size_t) getShare()->getRecordLength());
01509 }
01510 
01511 /*
01512  * Restore a record with default values
01513  *
01514  */
01515 void Table::restoreRecordAsDefault()
01516 {
01517   memcpy(getInsertRecord(), getMutableShare()->getDefaultValues(), (size_t) getShare()->getRecordLength());
01518 }
01519 
01520 /*
01521  * Empty a record
01522  *
01523  */
01524 void Table::emptyRecord()
01525 {
01526   restoreRecordAsDefault();
01527   memset(null_flags, 255, getShare()->null_bytes);
01528 }
01529 
01530 Table::Table() : 
01531   field(NULL),
01532   cursor(NULL),
01533   next(NULL),
01534   prev(NULL),
01535   read_set(NULL),
01536   write_set(NULL),
01537   tablenr(0),
01538   db_stat(0),
01539   def_read_set(),
01540   def_write_set(),
01541   tmp_set(),
01542   in_use(NULL),
01543   key_info(NULL),
01544   next_number_field(NULL),
01545   found_next_number_field(NULL),
01546   timestamp_field(NULL),
01547   pos_in_table_list(NULL),
01548   group(NULL),
01549   null_flags(NULL),
01550   lock_position(0),
01551   lock_data_start(0),
01552   lock_count(0),
01553   used_fields(0),
01554   status(0),
01555   derived_select_number(0),
01556   current_lock(F_UNLCK),
01557   copy_blobs(false),
01558   maybe_null(false),
01559   null_row(false),
01560   force_index(false),
01561   distinct(false),
01562   const_table(false),
01563   no_rows(false),
01564   key_read(false),
01565   no_keyread(false),
01566   open_placeholder(false),
01567   locked_by_name(false),
01568   no_cache(false),
01569   auto_increment_field_not_null(false),
01570   alias_name_used(false),
01571   query_id(0),
01572   quick_condition_rows(0),
01573   timestamp_field_type(TIMESTAMP_NO_AUTO_SET),
01574   map(0),
01575   quick_rows(),
01576   const_key_parts(),
01577   quick_key_parts(),
01578   quick_n_ranges()
01579 {
01580   record[0]= (unsigned char *) 0;
01581   record[1]= (unsigned char *) 0;
01582 }
01583 
01584 /*****************************************************************************
01585   The different ways to read a record
01586   Returns -1 if row was not found, 0 if row was found and 1 on errors
01587 *****************************************************************************/
01588 
01591 int Table::report_error(int error)
01592 {
01593   if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
01594   {
01595     status= STATUS_GARBAGE;
01596     return -1;          // key not found; ok
01597   }
01598   /*
01599     Locking reads can legally return also these errors, do not
01600     print them to the .err log
01601   */
01602   if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
01603     errmsg_printf(error::ERROR, _("Got error %d when reading table '%s'"),
01604                   error, getShare()->getPath());
01605   print_error(error, MYF(0));
01606 
01607   return 1;
01608 }
01609 
01610 
01611 void Table::setup_table_map(TableList *table_list, uint32_t table_number)
01612 {
01613   used_fields= 0;
01614   const_table= 0;
01615   null_row= 0;
01616   status= STATUS_NO_RECORD;
01617   maybe_null= table_list->outer_join;
01618   TableList *embedding= table_list->getEmbedding();
01619   while (!maybe_null && embedding)
01620   {
01621     maybe_null= embedding->outer_join;
01622     embedding= embedding->getEmbedding();
01623   }
01624   tablenr= table_number;
01625   map= (table_map) 1 << table_number;
01626   force_index= table_list->force_index;
01627   covering_keys= getShare()->keys_for_keyread;
01628   merge_keys.reset();
01629 }
01630 
01631 
01632 void Table::fill_item_list(List<Item>& items) const
01633 {
01634   /*
01635     All Item_field's created using a direct pointer to a field
01636     are fixed in Item_field constructor.
01637   */
01638   for (Field **ptr= field; *ptr; ptr++)
01639     items.push_back(new Item_field(*ptr));
01640 }
01641 
01642 
01643 void Table::filesort_free_buffers(bool full)
01644 {
01645   free(sort.record_pointers);
01646   sort.record_pointers=0;
01647   if (full)
01648   {
01649     free(sort.sort_keys);
01650     sort.sort_keys= 0;
01651     free(sort.buffpek);
01652     sort.buffpek= 0;
01653     sort.buffpek_len= 0;
01654   }
01655   free(sort.addon_buf);
01656   free(sort.addon_field);
01657   sort.addon_buf=0;
01658   sort.addon_field=0;
01659 }
01660 
01661 /*
01662   Is this instance of the table should be reopen or represents a name-lock?
01663 */
01664 bool Table::needs_reopen_or_name_lock() const
01665 { 
01666   return getShare()->getVersion() != g_refresh_version;
01667 }
01668 
01669 uint32_t Table::index_flags(uint32_t idx) const
01670 {
01671   return getShare()->getEngine()->index_flags(getShare()->getKeyInfo(idx).algorithm);
01672 }
01673 
01674 void Table::print_error(int error, myf errflag) const
01675 {
01676   getShare()->getEngine()->print_error(error, errflag, *this);
01677 }
01678 
01679 } /* namespace drizzled */