Drizzled Public API Documentation

sql_insert.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 /* Insert of records */
00018 
00019 #include <config.h>
00020 #include <cstdio>
00021 #include <drizzled/sql_select.h>
00022 #include <drizzled/show.h>
00023 #include <drizzled/error.h>
00024 #include <drizzled/name_resolution_context_state.h>
00025 #include <drizzled/probes.h>
00026 #include <drizzled/sql_base.h>
00027 #include <drizzled/sql_load.h>
00028 #include <drizzled/field/epoch.h>
00029 #include <drizzled/lock.h>
00030 #include <drizzled/sql_table.h>
00031 #include <drizzled/pthread_globals.h>
00032 #include <drizzled/transaction_services.h>
00033 #include <drizzled/plugin/transactional_storage_engine.h>
00034 #include <drizzled/select_insert.h>
00035 #include <drizzled/select_create.h>
00036 #include <drizzled/table/shell.h>
00037 #include <drizzled/alter_info.h>
00038 #include <drizzled/sql_parse.h>
00039 #include <drizzled/sql_lex.h>
00040 #include <drizzled/statistics_variables.h>
00041 #include <drizzled/session/transactions.h>
00042 #include <drizzled/open_tables_state.h>
00043 #include <drizzled/table/cache.h>
00044 #include <drizzled/create_field.h>
00045 
00046 namespace drizzled {
00047 
00048 extern plugin::StorageEngine *heap_engine;
00049 extern plugin::StorageEngine *myisam_engine;
00050 
00051 /*
00052   Check if insert fields are correct.
00053 
00054   SYNOPSIS
00055     check_insert_fields()
00056     session                         The current thread.
00057     table                       The table for insert.
00058     fields                      The insert fields.
00059     values                      The insert values.
00060     check_unique                If duplicate values should be rejected.
00061 
00062   NOTE
00063     Clears TIMESTAMP_AUTO_SET_ON_INSERT from table->timestamp_field_type
00064     or leaves it as is, depending on if timestamp should be updated or
00065     not.
00066 
00067   RETURN
00068     0           OK
00069     -1          Error
00070 */
00071 
00072 static int check_insert_fields(Session *session, TableList *table_list,
00073                                List<Item> &fields, List<Item> &values,
00074                                bool check_unique,
00075                                table_map *)
00076 {
00077   Table *table= table_list->table;
00078 
00079   if (fields.size() == 0 && values.size() != 0)
00080   {
00081     if (values.size() != table->getShare()->sizeFields())
00082     {
00083       my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
00084       return -1;
00085     }
00086     clear_timestamp_auto_bits(table->timestamp_field_type,
00087                               TIMESTAMP_AUTO_SET_ON_INSERT);
00088     /*
00089       No fields are provided so all fields must be provided in the values.
00090       Thus we set all bits in the write set.
00091     */
00092     table->setWriteSet();
00093   }
00094   else
00095   {           // Part field list
00096     Select_Lex *select_lex= &session->lex().select_lex;
00097     Name_resolution_context *context= &select_lex->context;
00098     Name_resolution_context_state ctx_state;
00099     int res;
00100 
00101     if (fields.size() != values.size())
00102     {
00103       my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
00104       return -1;
00105     }
00106 
00107     session->dup_field= 0;
00108 
00109     /* Save the state of the current name resolution context. */
00110     ctx_state.save_state(context, table_list);
00111 
00112     /*
00113       Perform name resolution only in the first table - 'table_list',
00114       which is the table that is inserted into.
00115     */
00116     table_list->next_local= 0;
00117     context->resolve_in_table_list_only(table_list);
00118     res= setup_fields(session, 0, fields, MARK_COLUMNS_WRITE, 0, 0);
00119 
00120     /* Restore the current context. */
00121     ctx_state.restore_state(context, table_list);
00122 
00123     if (res)
00124       return -1;
00125 
00126     if (check_unique && session->dup_field)
00127     {
00128       my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), session->dup_field->field_name);
00129       return -1;
00130     }
00131     if (table->timestamp_field) // Don't automaticly set timestamp if used
00132     {
00133       if (table->timestamp_field->isWriteSet())
00134       {
00135         clear_timestamp_auto_bits(table->timestamp_field_type,
00136                                   TIMESTAMP_AUTO_SET_ON_INSERT);
00137       }
00138       else
00139       {
00140         table->setWriteSet(table->timestamp_field->position());
00141       }
00142     }
00143   }
00144 
00145   return 0;
00146 }
00147 
00148 
00149 /*
00150   Check update fields for the timestamp field.
00151 
00152   SYNOPSIS
00153     check_update_fields()
00154     session                         The current thread.
00155     insert_table_list           The insert table list.
00156     table                       The table for update.
00157     update_fields               The update fields.
00158 
00159   NOTE
00160     If the update fields include the timestamp field,
00161     remove TIMESTAMP_AUTO_SET_ON_UPDATE from table->timestamp_field_type.
00162 
00163   RETURN
00164     0           OK
00165     -1          Error
00166 */
00167 
00168 static int check_update_fields(Session *session, TableList *insert_table_list,
00169                                List<Item> &update_fields,
00170                                table_map *)
00171 {
00172   Table *table= insert_table_list->table;
00173   bool timestamp_mark= false;
00174 
00175   if (table->timestamp_field)
00176   {
00177     /*
00178       Unmark the timestamp field so that we can check if this is modified
00179       by update_fields
00180     */
00181     timestamp_mark= table->write_set->test(table->timestamp_field->position());
00182     table->write_set->reset(table->timestamp_field->position());
00183   }
00184 
00185   /* Check the fields we are going to modify */
00186   if (setup_fields(session, 0, update_fields, MARK_COLUMNS_WRITE, 0, 0))
00187     return -1;
00188 
00189   if (table->timestamp_field)
00190   {
00191     /* Don't set timestamp column if this is modified. */
00192     if (table->timestamp_field->isWriteSet())
00193     {
00194       clear_timestamp_auto_bits(table->timestamp_field_type,
00195                                 TIMESTAMP_AUTO_SET_ON_UPDATE);
00196     }
00197 
00198     if (timestamp_mark)
00199     {
00200       table->setWriteSet(table->timestamp_field->position());
00201     }
00202   }
00203   return 0;
00204 }
00205 
00206 
00215 static
00216 void upgrade_lock_type(Session *,
00217                        thr_lock_type *lock_type,
00218                        enum_duplicates duplic,
00219                        bool )
00220 {
00221   if (duplic == DUP_UPDATE ||
00222       (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
00223   {
00224     *lock_type= TL_WRITE_DEFAULT;
00225     return;
00226   }
00227 }
00228 
00229 
00238 bool insert_query(Session *session,TableList *table_list,
00239                   List<Item> &fields,
00240                   List<List_item> &values_list,
00241                   List<Item> &update_fields,
00242                   List<Item> &update_values,
00243                   enum_duplicates duplic,
00244       bool ignore)
00245 {
00246   int error;
00247   bool transactional_table, joins_freed= false;
00248   bool changed;
00249   uint32_t value_count;
00250   ulong counter = 1;
00251   uint64_t id;
00252   CopyInfo info;
00253   Table *table= 0;
00254   List<List_item>::iterator its(values_list.begin());
00255   List_item *values;
00256   Name_resolution_context *context;
00257   Name_resolution_context_state ctx_state;
00258   Item *unused_conds= 0;
00259 
00260 
00261   /*
00262     Upgrade lock type if the requested lock is incompatible with
00263     the current connection mode or table operation.
00264   */
00265   upgrade_lock_type(session, &table_list->lock_type, duplic,
00266                     values_list.size() > 1);
00267 
00268   if (session->openTablesLock(table_list))
00269   {
00270     DRIZZLE_INSERT_DONE(1, 0);
00271     return true;
00272   }
00273 
00274   session->set_proc_info("init");
00275   session->used_tables=0;
00276   values= its++;
00277   value_count= values->size();
00278 
00279   if (prepare_insert(session, table_list, table, fields, values,
00280          update_fields, update_values, duplic, &unused_conds,
00281                            false,
00282                            (fields.size() || !value_count ||
00283                             (0) != 0), !ignore))
00284   {
00285     if (table != NULL)
00286       table->cursor->ha_release_auto_increment();
00287     if (!joins_freed)
00288       free_underlaid_joins(session, &session->lex().select_lex);
00289     session->setAbortOnWarning(false);
00290     DRIZZLE_INSERT_DONE(1, 0);
00291     return true;
00292   }
00293 
00294   /* mysql_prepare_insert set table_list->table if it was not set */
00295   table= table_list->table;
00296 
00297   context= &session->lex().select_lex.context;
00298   /*
00299     These three asserts test the hypothesis that the resetting of the name
00300     resolution context below is not necessary at all since the list of local
00301     tables for INSERT always consists of one table.
00302   */
00303   assert(!table_list->next_local);
00304   assert(!context->table_list->next_local);
00305   assert(!context->first_name_resolution_table->next_name_resolution_table);
00306 
00307   /* Save the state of the current name resolution context. */
00308   ctx_state.save_state(context, table_list);
00309 
00310   /*
00311     Perform name resolution only in the first table - 'table_list',
00312     which is the table that is inserted into.
00313   */
00314   table_list->next_local= 0;
00315   context->resolve_in_table_list_only(table_list);
00316 
00317   while ((values= its++))
00318   {
00319     counter++;
00320     if (values->size() != value_count)
00321     {
00322       my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
00323 
00324       if (table != NULL)
00325         table->cursor->ha_release_auto_increment();
00326       if (!joins_freed)
00327         free_underlaid_joins(session, &session->lex().select_lex);
00328       session->setAbortOnWarning(false);
00329       DRIZZLE_INSERT_DONE(1, 0);
00330 
00331       return true;
00332     }
00333     if (setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0))
00334     {
00335       if (table != NULL)
00336         table->cursor->ha_release_auto_increment();
00337       if (!joins_freed)
00338         free_underlaid_joins(session, &session->lex().select_lex);
00339       session->setAbortOnWarning(false);
00340       DRIZZLE_INSERT_DONE(1, 0);
00341       return true;
00342     }
00343   }
00344   its= values_list.begin();
00345 
00346   /* Restore the current context. */
00347   ctx_state.restore_state(context, table_list);
00348 
00349   /*
00350     Fill in the given fields and dump it to the table cursor
00351   */
00352   info.ignore= ignore;
00353   info.handle_duplicates=duplic;
00354   info.update_fields= &update_fields;
00355   info.update_values= &update_values;
00356 
00357   /*
00358     Count warnings for all inserts.
00359     For single line insert, generate an error if try to set a NOT NULL field
00360     to NULL.
00361   */
00362   session->count_cuted_fields= ignore ? CHECK_FIELD_WARN : CHECK_FIELD_ERROR_FOR_NULL;
00363 
00364   session->cuted_fields = 0L;
00365   table->next_number_field=table->found_next_number_field;
00366 
00367   error=0;
00368   session->set_proc_info("update");
00369   if (duplic == DUP_REPLACE)
00370     table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
00371   if (duplic == DUP_UPDATE)
00372     table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
00373   {
00374     if (duplic != DUP_ERROR || ignore)
00375       table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
00376     table->cursor->ha_start_bulk_insert(values_list.size());
00377   }
00378 
00379 
00380   session->setAbortOnWarning(not ignore);
00381 
00382   table->mark_columns_needed_for_insert();
00383 
00384   while ((values= its++))
00385   {
00386     if (fields.size() || !value_count)
00387     {
00388       table->restoreRecordAsDefault();  // Get empty record
00389       if (fill_record(session, fields, *values))
00390       {
00391   if (values_list.size() != 1 && ! session->is_error())
00392   {
00393     info.records++;
00394     continue;
00395   }
00396   /*
00397     TODO: set session->abort_on_warning if values_list.elements == 1
00398     and check that all items return warning in case of problem with
00399     storing field.
00400         */
00401   error=1;
00402   break;
00403       }
00404     }
00405     else
00406     {
00407       table->restoreRecordAsDefault();  // Get empty record
00408 
00409       if (fill_record(session, table->getFields(), *values))
00410       {
00411   if (values_list.size() != 1 && ! session->is_error())
00412   {
00413     info.records++;
00414     continue;
00415   }
00416   error=1;
00417   break;
00418       }
00419     }
00420 
00421     // Release latches in case bulk insert takes a long time
00422     plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
00423 
00424     error=write_record(session, table ,&info);
00425     if (error)
00426       break;
00427     session->row_count++;
00428   }
00429 
00430   free_underlaid_joins(session, &session->lex().select_lex);
00431   joins_freed= true;
00432 
00433   /*
00434     Now all rows are inserted.  Time to update logs and sends response to
00435     user
00436   */
00437   {
00438     /*
00439       Do not do this release if this is a delayed insert, it would steal
00440       auto_inc values from the delayed_insert thread as they share Table.
00441     */
00442     table->cursor->ha_release_auto_increment();
00443     if (table->cursor->ha_end_bulk_insert() && !error)
00444     {
00445       table->print_error(errno,MYF(0));
00446       error=1;
00447     }
00448     if (duplic != DUP_ERROR || ignore)
00449       table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
00450 
00451     transactional_table= table->cursor->has_transactions();
00452 
00453     changed= (info.copied || info.deleted || info.updated);
00454     if ((changed && error <= 0) || session->transaction.stmt.hasModifiedNonTransData())
00455     {
00456       if (session->transaction.stmt.hasModifiedNonTransData())
00457   session->transaction.all.markModifiedNonTransData();
00458     }
00459     assert(transactional_table || !changed || session->transaction.stmt.hasModifiedNonTransData());
00460 
00461   }
00462   session->set_proc_info("end");
00463   /*
00464     We'll report to the client this id:
00465     - if the table contains an autoincrement column and we successfully
00466     inserted an autogenerated value, the autogenerated value.
00467     - if the table contains no autoincrement column and LAST_INSERT_ID(X) was
00468     called, X.
00469     - if the table contains an autoincrement column, and some rows were
00470     inserted, the id of the last "inserted" row (if IGNORE, that value may not
00471     have been really inserted but ignored).
00472   */
00473   id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
00474     session->first_successful_insert_id_in_cur_stmt :
00475     (session->arg_of_last_insert_id_function ?
00476      session->first_successful_insert_id_in_prev_stmt :
00477      ((table->next_number_field && info.copied) ?
00478      table->next_number_field->val_int() : 0));
00479   table->next_number_field=0;
00480   session->count_cuted_fields= CHECK_FIELD_IGNORE;
00481   table->auto_increment_field_not_null= false;
00482   if (duplic == DUP_REPLACE)
00483     table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
00484 
00485   if (error)
00486   {
00487     if (table != NULL)
00488       table->cursor->ha_release_auto_increment();
00489     if (!joins_freed)
00490       free_underlaid_joins(session, &session->lex().select_lex);
00491     session->setAbortOnWarning(false);
00492     DRIZZLE_INSERT_DONE(1, 0);
00493     return true;
00494   }
00495 
00496   if (values_list.size() == 1 && (!(session->options & OPTION_WARNINGS) ||
00497             !session->cuted_fields))
00498   {
00499     session->row_count_func= info.copied + info.deleted + info.updated;
00500     session->my_ok((ulong) session->rowCount(),
00501                    info.copied + info.deleted + info.touched, id);
00502   }
00503   else
00504   {
00505     char buff[160];
00506     if (ignore)
00507       snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
00508               (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
00509     else
00510       snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
00511         (ulong) (info.deleted + info.updated), (ulong) session->cuted_fields);
00512     session->row_count_func= info.copied + info.deleted + info.updated;
00513     session->my_ok((ulong) session->rowCount(),
00514                    info.copied + info.deleted + info.touched, id, buff);
00515   }
00516   session->status_var.inserted_row_count+= session->rowCount();
00517   session->setAbortOnWarning(false);
00518   DRIZZLE_INSERT_DONE(0, session->rowCount());
00519 
00520   return false;
00521 }
00522 
00523 
00524 /*
00525   Check if table can be updated
00526 
00527   SYNOPSIS
00528      prepare_insert_check_table()
00529      session    Thread handle
00530      table_list   Table list
00531      fields   List of fields to be updated
00532      where    Pointer to where clause
00533      select_insert      Check is making for SELECT ... INSERT
00534 
00535    RETURN
00536      false ok
00537      true  ERROR
00538 */
00539 
00540 static bool prepare_insert_check_table(Session *session, TableList *table_list,
00541                                              List<Item> &,
00542                                              bool select_insert)
00543 {
00544 
00545 
00546   /*
00547      first table in list is the one we'll INSERT into, requires INSERT_ACL.
00548      all others require SELECT_ACL only. the ACL requirement below is for
00549      new leaves only anyway (view-constituents), so check for SELECT rather
00550      than INSERT.
00551   */
00552 
00553   return setup_tables_and_check_access(session, &session->lex().select_lex.context,
00554     &session->lex().select_lex.top_join_list, table_list, &session->lex().select_lex.leaf_tables, select_insert);
00555 }
00556 
00557 
00558 /*
00559   Prepare items in INSERT statement
00560 
00561   SYNOPSIS
00562     prepare_insert()
00563     session     Thread handler
00564     table_list          Global/local table list
00565     table   Table to insert into (can be NULL if table should
00566       be taken from table_list->table)
00567     where   Where clause (for insert ... select)
00568     select_insert true if INSERT ... SELECT statement
00569     check_fields        true if need to check that all INSERT fields are
00570                         given values.
00571     abort_on_warning    whether to report if some INSERT field is not
00572                         assigned as an error (true) or as a warning (false).
00573 
00574   TODO (in far future)
00575     In cases of:
00576     INSERT INTO t1 SELECT a, sum(a) as sum1 from t2 GROUP BY a
00577     ON DUPLICATE KEY ...
00578     we should be able to refer to sum1 in the ON DUPLICATE KEY part
00579 
00580   WARNING
00581     You MUST set table->insert_values to 0 after calling this function
00582     before releasing the table object.
00583 
00584   RETURN VALUE
00585     false OK
00586     true  error
00587 */
00588 
00589 bool prepare_insert(Session *session, TableList *table_list,
00590                           Table *table, List<Item> &fields, List_item *values,
00591                           List<Item> &update_fields, List<Item> &update_values,
00592                           enum_duplicates duplic,
00593                           COND **,
00594                           bool select_insert,
00595                           bool check_fields, bool abort_on_warning)
00596 {
00597   Select_Lex *select_lex= &session->lex().select_lex;
00598   Name_resolution_context *context= &select_lex->context;
00599   Name_resolution_context_state ctx_state;
00600   bool insert_into_view= (0 != 0);
00601   bool res= 0;
00602   table_map map= 0;
00603 
00604   /* INSERT should have a SELECT or VALUES clause */
00605   assert (!select_insert || !values);
00606 
00607   /*
00608     For subqueries in VALUES() we should not see the table in which we are
00609     inserting (for INSERT ... SELECT this is done by changing table_list,
00610     because INSERT ... SELECT share Select_Lex it with SELECT.
00611   */
00612   if (not select_insert)
00613   {
00614     for (Select_Lex_Unit *un= select_lex->first_inner_unit();
00615          un;
00616          un= un->next_unit())
00617     {
00618       for (Select_Lex *sl= un->first_select();
00619            sl;
00620            sl= sl->next_select())
00621       {
00622         sl->context.outer_context= 0;
00623       }
00624     }
00625   }
00626 
00627   if (duplic == DUP_UPDATE)
00628   {
00629     /* it should be allocated before Item::fix_fields() */
00630     table_list->set_insert_values();
00631   }
00632 
00633   if (prepare_insert_check_table(session, table_list, fields, select_insert))
00634     return true;
00635 
00636 
00637   /* Prepare the fields in the statement. */
00638   if (values)
00639   {
00640     /* if we have INSERT ... VALUES () we cannot have a GROUP BY clause */
00641     assert (!select_lex->group_list.elements);
00642 
00643     /* Save the state of the current name resolution context. */
00644     ctx_state.save_state(context, table_list);
00645 
00646     /*
00647       Perform name resolution only in the first table - 'table_list',
00648       which is the table that is inserted into.
00649      */
00650     table_list->next_local= 0;
00651     context->resolve_in_table_list_only(table_list);
00652 
00653     res= check_insert_fields(session, context->table_list, fields, *values,
00654                              !insert_into_view, &map) ||
00655       setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0);
00656 
00657     if (!res && check_fields)
00658     {
00659       bool saved_abort_on_warning= session->abortOnWarning();
00660 
00661       session->setAbortOnWarning(abort_on_warning);
00662       res= check_that_all_fields_are_given_values(session,
00663                                                   table ? table :
00664                                                   context->table_list->table,
00665                                                   context->table_list);
00666       session->setAbortOnWarning(saved_abort_on_warning);
00667     }
00668 
00669     if (!res && duplic == DUP_UPDATE)
00670     {
00671       res= check_update_fields(session, context->table_list, update_fields, &map);
00672     }
00673 
00674     /* Restore the current context. */
00675     ctx_state.restore_state(context, table_list);
00676 
00677     if (not res)
00678       res= setup_fields(session, 0, update_values, MARK_COLUMNS_READ, 0, 0);
00679   }
00680 
00681   if (res)
00682     return res;
00683 
00684   if (not table)
00685     table= table_list->table;
00686 
00687   if (not select_insert && unique_table(table_list, table_list->next_global, true))
00688   {
00689     my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->alias);
00690     return true;
00691   }
00692 
00693   if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
00694     table->prepare_for_position();
00695 
00696   return false;
00697 }
00698 
00699 
00700   /* Check if there is more uniq keys after field */
00701 
00702 static int last_uniq_key(Table *table,uint32_t keynr)
00703 {
00704   while (++keynr < table->getShare()->sizeKeys())
00705     if (table->key_info[keynr].flags & HA_NOSAME)
00706       return 0;
00707   return 1;
00708 }
00709 
00710 
00711 /*
00712   Write a record to table with optional deleting of conflicting records,
00713   invoke proper triggers if needed.
00714 
00715   SYNOPSIS
00716      write_record()
00717       session   - thread context
00718       table - table to which record should be written
00719       info  - CopyInfo structure describing handling of duplicates
00720               and which is used for counting number of records inserted
00721               and deleted.
00722 
00723   NOTE
00724     Once this record will be written to table after insert trigger will
00725     be invoked. If instead of inserting new record we will update old one
00726     then both on update triggers will work instead. Similarly both on
00727     delete triggers will be invoked if we will delete conflicting records.
00728 
00729     Sets session->transaction.stmt.modified_non_trans_data to true if table which is updated didn't have
00730     transactions.
00731 
00732   RETURN VALUE
00733     0     - success
00734     non-0 - error
00735 */
00736 
00737 
00738 int write_record(Session *session, Table *table,CopyInfo *info)
00739 {
00740   int error;
00741   std::vector<unsigned char> key;
00742   boost::dynamic_bitset<> *save_read_set, *save_write_set;
00743   uint64_t prev_insert_id= table->cursor->next_insert_id;
00744   uint64_t insert_id_for_cur_row= 0;
00745 
00746 
00747   info->records++;
00748   save_read_set=  table->read_set;
00749   save_write_set= table->write_set;
00750 
00751   if (info->handle_duplicates == DUP_REPLACE || info->handle_duplicates == DUP_UPDATE)
00752   {
00753     while ((error=table->cursor->insertRecord(table->getInsertRecord())))
00754     {
00755       uint32_t key_nr;
00756       /*
00757         If we do more than one iteration of this loop, from the second one the
00758         row will have an explicit value in the autoinc field, which was set at
00759         the first call of handler::update_auto_increment(). So we must save
00760         the autogenerated value to avoid session->insert_id_for_cur_row to become
00761         0.
00762       */
00763       if (table->cursor->insert_id_for_cur_row > 0)
00764         insert_id_for_cur_row= table->cursor->insert_id_for_cur_row;
00765       else
00766         table->cursor->insert_id_for_cur_row= insert_id_for_cur_row;
00767       bool is_duplicate_key_error;
00768       if (table->cursor->is_fatal_error(error, HA_CHECK_DUP))
00769   goto err;
00770       is_duplicate_key_error= table->cursor->is_fatal_error(error, 0);
00771       if (!is_duplicate_key_error)
00772       {
00773         /*
00774           We come here when we had an ignorable error which is not a duplicate
00775           key error. In this we ignore error if ignore flag is set, otherwise
00776           report error as usual. We will not do any duplicate key processing.
00777         */
00778         if (info->ignore)
00779           goto gok_or_after_err; /* Ignoring a not fatal error, return 0 */
00780         goto err;
00781       }
00782       if ((int) (key_nr = table->get_dup_key(error)) < 0)
00783       {
00784   error= HA_ERR_FOUND_DUPP_KEY;         /* Database can't find key */
00785   goto err;
00786       }
00787       /* Read all columns for the row we are going to replace */
00788       table->use_all_columns();
00789       /*
00790   Don't allow REPLACE to replace a row when a auto_increment column
00791   was used.  This ensures that we don't get a problem when the
00792   whole range of the key has been used.
00793       */
00794       if (info->handle_duplicates == DUP_REPLACE &&
00795           table->next_number_field &&
00796           key_nr == table->getShare()->next_number_index &&
00797     (insert_id_for_cur_row > 0))
00798   goto err;
00799       if (table->cursor->getEngine()->check_flag(HTON_BIT_DUPLICATE_POS))
00800       {
00801   if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
00802     goto err;
00803       }
00804       else
00805       {
00806   if (table->cursor->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
00807   {
00808     error=errno;
00809     goto err;
00810   }
00811 
00812   if (not key.size())
00813   {
00814           key.resize(table->getShare()->max_unique_length);
00815   }
00816   key_copy(&key[0], table->getInsertRecord(), table->key_info+key_nr, 0);
00817   if ((error=(table->cursor->index_read_idx_map(table->getUpdateRecord(),key_nr,
00818                                                     &key[0], HA_WHOLE_KEY,
00819                                                     HA_READ_KEY_EXACT))))
00820     goto err;
00821       }
00822       if (info->handle_duplicates == DUP_UPDATE)
00823       {
00824         /*
00825           We don't check for other UNIQUE keys - the first row
00826           that matches, is updated. If update causes a conflict again,
00827           an error is returned
00828         */
00829   assert(table->insert_values.size());
00830         table->storeRecordAsInsert();
00831         table->restoreRecord();
00832         assert(info->update_fields->size() ==
00833                     info->update_values->size());
00834         if (fill_record(session, *info->update_fields,
00835                                                  *info->update_values,
00836                                                  info->ignore))
00837           goto before_err;
00838 
00839         table->cursor->restore_auto_increment(prev_insert_id);
00840         if (table->next_number_field)
00841           table->cursor->adjust_next_insert_id_after_explicit_value(
00842             table->next_number_field->val_int());
00843         info->touched++;
00844 
00845         if (! table->records_are_comparable() || table->compare_records())
00846         {
00847           if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
00848                                                 table->getInsertRecord())) &&
00849               error != HA_ERR_RECORD_IS_THE_SAME)
00850           {
00851             if (info->ignore &&
00852                 !table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
00853             {
00854               goto gok_or_after_err;
00855             }
00856             goto err;
00857           }
00858 
00859           if (error != HA_ERR_RECORD_IS_THE_SAME)
00860             info->updated++;
00861           else
00862             error= 0;
00863           /*
00864             If ON DUP KEY UPDATE updates a row instead of inserting one, it's
00865             like a regular UPDATE statement: it should not affect the value of a
00866             next SELECT LAST_INSERT_ID() or insert_id().
00867             Except if LAST_INSERT_ID(#) was in the INSERT query, which is
00868             handled separately by Session::arg_of_last_insert_id_function.
00869           */
00870           insert_id_for_cur_row= table->cursor->insert_id_for_cur_row= 0;
00871           info->copied++;
00872         }
00873 
00874         if (table->next_number_field)
00875           table->cursor->adjust_next_insert_id_after_explicit_value(
00876             table->next_number_field->val_int());
00877         info->touched++;
00878 
00879         goto gok_or_after_err;
00880       }
00881       else /* DUP_REPLACE */
00882       {
00883   /*
00884     The manual defines the REPLACE semantics that it is either
00885     an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
00886     InnoDB do not function in the defined way if we allow MySQL
00887     to convert the latter operation internally to an UPDATE.
00888           We also should not perform this conversion if we have
00889           timestamp field with ON UPDATE which is different from DEFAULT.
00890           Another case when conversion should not be performed is when
00891           we have ON DELETE trigger on table so user may notice that
00892           we cheat here. Note that it is ok to do such conversion for
00893           tables which have ON UPDATE but have no ON DELETE triggers,
00894           we just should not expose this fact to users by invoking
00895           ON UPDATE triggers.
00896   */
00897   if (last_uniq_key(table,key_nr) &&
00898       !table->cursor->referenced_by_foreign_key() &&
00899             (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
00900              table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
00901         {
00902           if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
00903                   table->getInsertRecord())) &&
00904               error != HA_ERR_RECORD_IS_THE_SAME)
00905             goto err;
00906           if (error != HA_ERR_RECORD_IS_THE_SAME)
00907             info->deleted++;
00908           else
00909             error= 0;
00910           session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
00911           /*
00912             Since we pretend that we have done insert we should call
00913             its after triggers.
00914           */
00915           goto after_n_copied_inc;
00916         }
00917         else
00918         {
00919           if ((error=table->cursor->deleteRecord(table->getUpdateRecord())))
00920             goto err;
00921           info->deleted++;
00922           if (!table->cursor->has_transactions())
00923             session->transaction.stmt.markModifiedNonTransData();
00924           /* Let us attempt do write_row() once more */
00925         }
00926       }
00927     }
00928     session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
00929     /*
00930       Restore column maps if they where replaced during an duplicate key
00931       problem.
00932     */
00933     if (table->read_set != save_read_set ||
00934         table->write_set != save_write_set)
00935       table->column_bitmaps_set(*save_read_set, *save_write_set);
00936   }
00937   else if ((error=table->cursor->insertRecord(table->getInsertRecord())))
00938   {
00939     if (!info->ignore ||
00940         table->cursor->is_fatal_error(error, HA_CHECK_DUP))
00941       goto err;
00942     table->cursor->restore_auto_increment(prev_insert_id);
00943     goto gok_or_after_err;
00944   }
00945 
00946 after_n_copied_inc:
00947   info->copied++;
00948   session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
00949 
00950 gok_or_after_err:
00951   if (!table->cursor->has_transactions())
00952     session->transaction.stmt.markModifiedNonTransData();
00953   return 0;
00954 
00955 err:
00956   info->last_errno= error;
00957   /* current_select is NULL if this is a delayed insert */
00958   if (session->lex().current_select)
00959     session->lex().current_select->no_error= 0;        // Give error
00960   table->print_error(error,MYF(0));
00961 
00962 before_err:
00963   table->cursor->restore_auto_increment(prev_insert_id);
00964   table->column_bitmaps_set(*save_read_set, *save_write_set);
00965   return 1;
00966 }
00967 
00968 
00969 /******************************************************************************
00970   Check that all fields with arn't null_fields are used
00971 ******************************************************************************/
00972 
00973 int check_that_all_fields_are_given_values(Session *session, Table *entry,
00974                                            TableList *)
00975 {
00976   int err= 0;
00977 
00978   for (Field **field=entry->getFields() ; *field ; field++)
00979   {
00980     if (not (*field)->isWriteSet())
00981     {
00982       /*
00983        * If the field doesn't have any default value
00984        * and there is no actual value specified in the
00985        * INSERT statement, throw error ER_NO_DEFAULT_FOR_FIELD.
00986        */
00987       if (((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
00988         ((*field)->real_type() != DRIZZLE_TYPE_ENUM))
00989       {
00990         my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), (*field)->field_name);
00991         err= 1;
00992       }
00993     }
00994     else
00995     {
00996       /*
00997        * However, if an actual NULL value was specified
00998        * for the field and the field is a NOT NULL field,
00999        * throw ER_BAD_NULL_ERROR.
01000        *
01001        * Per the SQL standard, inserting NULL into a NOT NULL
01002        * field requires an error to be thrown.
01003        */
01004       if (((*field)->flags & NOT_NULL_FLAG) &&
01005           (*field)->is_null())
01006       {
01007         my_error(ER_BAD_NULL_ERROR, MYF(0), (*field)->field_name);
01008         err= 1;
01009       }
01010     }
01011   }
01012   return session->abortOnWarning() ? err : 0;
01013 }
01014 
01015 /***************************************************************************
01016   Store records in INSERT ... SELECT *
01017 ***************************************************************************/
01018 
01019 
01020 /*
01021   make insert specific preparation and checks after opening tables
01022 
01023   SYNOPSIS
01024     insert_select_prepare()
01025     session         thread handler
01026 
01027   RETURN
01028     false OK
01029     true  Error
01030 */
01031 
01032 bool insert_select_prepare(Session *session)
01033 {
01034   LEX *lex= &session->lex();
01035   Select_Lex *select_lex= &lex->select_lex;
01036 
01037   /*
01038     Select_Lex do not belong to INSERT statement, so we can't add WHERE
01039     clause if table is VIEW
01040   */
01041 
01042   if (prepare_insert(session, lex->query_tables,
01043                            lex->query_tables->table, lex->field_list, 0,
01044                            lex->update_list, lex->value_list,
01045                            lex->duplicates,
01046                            &select_lex->where, true, false, false))
01047     return true;
01048 
01049   /*
01050     exclude first table from leaf tables list, because it belong to
01051     INSERT
01052   */
01053   assert(select_lex->leaf_tables != 0);
01054   lex->leaf_tables_insert= select_lex->leaf_tables;
01055   /* skip all leaf tables belonged to view where we are insert */
01056   select_lex->leaf_tables= select_lex->leaf_tables->next_leaf;
01057   return false;
01058 }
01059 
01060 
01061 select_insert::select_insert(TableList *table_list_par, Table *table_par,
01062                              List<Item> *fields_par,
01063                              List<Item> *update_fields,
01064                              List<Item> *update_values,
01065                              enum_duplicates duplic,
01066                              bool ignore_check_option_errors) :
01067   table_list(table_list_par), table(table_par), fields(fields_par),
01068   autoinc_value_of_last_inserted_row(0),
01069   insert_into_view(table_list_par && 0 != 0)
01070 {
01071   info.handle_duplicates= duplic;
01072   info.ignore= ignore_check_option_errors;
01073   info.update_fields= update_fields;
01074   info.update_values= update_values;
01075 }
01076 
01077 
01078 int
01079 select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
01080 {
01081   int res;
01082   table_map map= 0;
01083   Select_Lex *lex_current_select_save= session->lex().current_select;
01084 
01085 
01086   unit= u;
01087 
01088   /*
01089     Since table in which we are going to insert is added to the first
01090     select, LEX::current_select should point to the first select while
01091     we are fixing fields from insert list.
01092   */
01093   session->lex().current_select= &session->lex().select_lex;
01094   res= check_insert_fields(session, table_list, *fields, values,
01095                            !insert_into_view, &map) ||
01096        setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
01097 
01098   if (!res && fields->size())
01099   {
01100     bool saved_abort_on_warning= session->abortOnWarning();
01101     session->setAbortOnWarning(not info.ignore);
01102     res= check_that_all_fields_are_given_values(session, table_list->table,
01103                                                 table_list);
01104     session->setAbortOnWarning(saved_abort_on_warning);
01105   }
01106 
01107   if (info.handle_duplicates == DUP_UPDATE && !res)
01108   {
01109     Name_resolution_context *context= &session->lex().select_lex.context;
01110     Name_resolution_context_state ctx_state;
01111 
01112     /* Save the state of the current name resolution context. */
01113     ctx_state.save_state(context, table_list);
01114 
01115     /* Perform name resolution only in the first table - 'table_list'. */
01116     table_list->next_local= 0;
01117     context->resolve_in_table_list_only(table_list);
01118 
01119     res= res || check_update_fields(session, context->table_list,
01120                                     *info.update_fields, &map);
01121     /*
01122       When we are not using GROUP BY and there are no ungrouped aggregate functions
01123       we can refer to other tables in the ON DUPLICATE KEY part.
01124       We use next_name_resolution_table descructively, so check it first (views?)
01125     */
01126     assert (!table_list->next_name_resolution_table);
01127     if (session->lex().select_lex.group_list.elements == 0 and
01128         not session->lex().select_lex.with_sum_func)
01129       /*
01130         We must make a single context out of the two separate name resolution contexts :
01131         the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
01132         To do that we must concatenate the two lists
01133       */
01134       table_list->next_name_resolution_table=
01135         ctx_state.get_first_name_resolution_table();
01136 
01137     res= res || setup_fields(session, 0, *info.update_values,
01138                              MARK_COLUMNS_READ, 0, 0);
01139     if (!res)
01140     {
01141       /*
01142         Traverse the update values list and substitute fields from the
01143         select for references (Item_ref objects) to them. This is done in
01144         order to get correct values from those fields when the select
01145         employs a temporary table.
01146       */
01147       List<Item>::iterator li(info.update_values->begin());
01148       Item *item;
01149 
01150       while ((item= li++))
01151       {
01152         item->transform(&Item::update_value_transformer,
01153                         (unsigned char*)session->lex().current_select);
01154       }
01155     }
01156 
01157     /* Restore the current context. */
01158     ctx_state.restore_state(context, table_list);
01159   }
01160 
01161   session->lex().current_select= lex_current_select_save;
01162   if (res)
01163     return 1;
01164   /*
01165     if it is INSERT into join view then check_insert_fields already found
01166     real table for insert
01167   */
01168   table= table_list->table;
01169 
01170   /*
01171     Is table which we are changing used somewhere in other parts of
01172     query
01173   */
01174   if (unique_table(table_list, table_list->next_global))
01175   {
01176     /* Using same table for INSERT and SELECT */
01177     session->lex().current_select->options|= OPTION_BUFFER_RESULT;
01178     session->lex().current_select->join->select_options|= OPTION_BUFFER_RESULT;
01179   }
01180   else if (not (session->lex().current_select->options & OPTION_BUFFER_RESULT))
01181   {
01182     /*
01183       We must not yet prepare the result table if it is the same as one of the
01184       source tables (INSERT SELECT). The preparation may disable
01185       indexes on the result table, which may be used during the select, if it
01186       is the same table (Bug #6034). Do the preparation after the select phase
01187       in select_insert::prepare2().
01188       We won't start bulk inserts at all if this statement uses functions or
01189       should invoke triggers since they may access to the same table too.
01190     */
01191     table->cursor->ha_start_bulk_insert((ha_rows) 0);
01192   }
01193   table->restoreRecordAsDefault();    // Get empty record
01194   table->next_number_field=table->found_next_number_field;
01195 
01196   session->cuted_fields=0;
01197 
01198   if (info.ignore || info.handle_duplicates != DUP_ERROR)
01199     table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
01200 
01201   if (info.handle_duplicates == DUP_REPLACE)
01202     table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
01203 
01204   if (info.handle_duplicates == DUP_UPDATE)
01205     table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
01206 
01207   session->setAbortOnWarning(not info.ignore);
01208   table->mark_columns_needed_for_insert();
01209 
01210 
01211   return res;
01212 }
01213 
01214 
01215 /*
01216   Finish the preparation of the result table.
01217 
01218   SYNOPSIS
01219     select_insert::prepare2()
01220     void
01221 
01222   DESCRIPTION
01223     If the result table is the same as one of the source tables (INSERT SELECT),
01224     the result table is not finally prepared at the join prepair phase.
01225     Do the final preparation now.
01226 
01227   RETURN
01228     0   OK
01229 */
01230 
01231 int select_insert::prepare2(void)
01232 {
01233   if (session->lex().current_select->options & OPTION_BUFFER_RESULT)
01234     table->cursor->ha_start_bulk_insert((ha_rows) 0);
01235 
01236   return 0;
01237 }
01238 
01239 
01240 void select_insert::cleanup()
01241 {
01242   /* select_insert/select_create are never re-used in prepared statement */
01243   assert(0);
01244 }
01245 
01246 select_insert::~select_insert()
01247 {
01248 
01249   if (table)
01250   {
01251     table->next_number_field=0;
01252     table->auto_increment_field_not_null= false;
01253     table->cursor->ha_reset();
01254   }
01255   session->count_cuted_fields= CHECK_FIELD_IGNORE;
01256   session->setAbortOnWarning(false);
01257   return;
01258 }
01259 
01260 
01261 bool select_insert::send_data(List<Item> &values)
01262 {
01263 
01264   bool error= false;
01265 
01266   if (unit->offset_limit_cnt)
01267   {           // using limit offset,count
01268     unit->offset_limit_cnt--;
01269     return false;
01270   }
01271 
01272   session->count_cuted_fields= CHECK_FIELD_WARN;  // Calculate cuted fields
01273   store_values(values);
01274   session->count_cuted_fields= CHECK_FIELD_IGNORE;
01275   if (session->is_error())
01276     return true;
01277 
01278   // Release latches in case bulk insert takes a long time
01279   plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
01280 
01281   error= write_record(session, table, &info);
01282   table->auto_increment_field_not_null= false;
01283 
01284   if (!error)
01285   {
01286     if (info.handle_duplicates == DUP_UPDATE)
01287     {
01288       /*
01289         Restore fields of the record since it is possible that they were
01290         changed by ON DUPLICATE KEY UPDATE clause.
01291 
01292         If triggers exist then whey can modify some fields which were not
01293         originally touched by INSERT ... SELECT, so we have to restore
01294         their original values for the next row.
01295       */
01296       table->restoreRecordAsDefault();
01297     }
01298     if (table->next_number_field)
01299     {
01300       /*
01301         If no value has been autogenerated so far, we need to remember the
01302         value we just saw, we may need to send it to client in the end.
01303       */
01304       if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
01305         autoinc_value_of_last_inserted_row=
01306           table->next_number_field->val_int();
01307       /*
01308         Clear auto-increment field for the next record, if triggers are used
01309         we will clear it twice, but this should be cheap.
01310       */
01311       table->next_number_field->reset();
01312     }
01313   }
01314   return(error);
01315 }
01316 
01317 
01318 void select_insert::store_values(List<Item> &values)
01319 {
01320   if (fields->size())
01321     fill_record(session, *fields, values, true);
01322   else
01323     fill_record(session, table->getFields(), values, true);
01324 }
01325 
01326 void select_insert::send_error(drizzled::error_t errcode,const char *err)
01327 {
01328   my_message(errcode, err, MYF(0));
01329 }
01330 
01331 
01332 bool select_insert::send_eof()
01333 {
01334   int error;
01335   bool const trans_table= table->cursor->has_transactions();
01336   uint64_t id;
01337   bool changed;
01338 
01339   error= table->cursor->ha_end_bulk_insert();
01340   table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
01341   table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
01342 
01343   if ((changed= (info.copied || info.deleted || info.updated)))
01344   {
01345     /*
01346       We must invalidate the table in the query cache before binlog writing
01347       and autocommitOrRollback.
01348     */
01349     if (session->transaction.stmt.hasModifiedNonTransData())
01350       session->transaction.all.markModifiedNonTransData();
01351   }
01352   assert(trans_table || !changed ||
01353               session->transaction.stmt.hasModifiedNonTransData());
01354 
01355   table->cursor->ha_release_auto_increment();
01356 
01357   if (error)
01358   {
01359     table->print_error(error,MYF(0));
01360     DRIZZLE_INSERT_SELECT_DONE(error, 0);
01361     return 1;
01362   }
01363   char buff[160];
01364   if (info.ignore)
01365     snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
01366       (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
01367   else
01368     snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
01369       (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
01370   session->row_count_func= info.copied + info.deleted + info.updated;
01371 
01372   id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
01373     session->first_successful_insert_id_in_cur_stmt :
01374     (session->arg_of_last_insert_id_function ?
01375      session->first_successful_insert_id_in_prev_stmt :
01376      (info.copied ? autoinc_value_of_last_inserted_row : 0));
01377   session->my_ok((ulong) session->rowCount(),
01378                  info.copied + info.deleted + info.touched, id, buff);
01379   session->status_var.inserted_row_count+= session->rowCount();
01380   DRIZZLE_INSERT_SELECT_DONE(0, session->rowCount());
01381   return 0;
01382 }
01383 
01384 void select_insert::abort() {
01385 
01386 
01387   /*
01388     If the creation of the table failed (due to a syntax error, for
01389     example), no table will have been opened and therefore 'table'
01390     will be NULL. In that case, we still need to execute the rollback
01391     and the end of the function.
01392    */
01393   if (table)
01394   {
01395     bool changed, transactional_table;
01396 
01397     table->cursor->ha_end_bulk_insert();
01398 
01399     /*
01400       If at least one row has been inserted/modified and will stay in
01401       the table (the table doesn't have transactions) we must write to
01402       the binlog (and the error code will make the slave stop).
01403 
01404       For many errors (example: we got a duplicate key error while
01405       inserting into a MyISAM table), no row will be added to the table,
01406       so passing the error to the slave will not help since there will
01407       be an error code mismatch (the inserts will succeed on the slave
01408       with no error).
01409 
01410       If table creation failed, the number of rows modified will also be
01411       zero, so no check for that is made.
01412     */
01413     changed= (info.copied || info.deleted || info.updated);
01414     transactional_table= table->cursor->has_transactions();
01415     assert(transactional_table || !changed ||
01416     session->transaction.stmt.hasModifiedNonTransData());
01417     table->cursor->ha_release_auto_increment();
01418   }
01419 
01420   if (DRIZZLE_INSERT_SELECT_DONE_ENABLED())
01421   {
01422     DRIZZLE_INSERT_SELECT_DONE(0, info.copied + info.deleted + info.updated);
01423   }
01424 
01425   return;
01426 }
01427 
01428 
01429 /***************************************************************************
01430   CREATE TABLE (SELECT) ...
01431 ***************************************************************************/
01432 
01433 /*
01434   Create table from lists of fields and items (or just return Table
01435   object for pre-opened existing table).
01436 
01437   SYNOPSIS
01438     create_table_from_items()
01439       session          in     Thread object
01440       create_info  in     Create information (like MAX_ROWS, ENGINE or
01441                           temporary table flag)
01442       create_table in     Pointer to TableList object providing database
01443                           and name for table to be created or to be open
01444       alter_info   in/out Initial list of columns and indexes for the table
01445                           to be created
01446       items        in     List of items which should be used to produce rest
01447                           of fields for the table (corresponding fields will
01448                           be added to the end of alter_info->create_list)
01449       lock         out    Pointer to the DrizzleLock object for table created
01450                           (or open temporary table) will be returned in this
01451                           parameter. Since this table is not included in
01452                           Session::lock caller is responsible for explicitly
01453                           unlocking this table.
01454       hooks
01455 
01456   NOTES
01457     This function behaves differently for base and temporary tables:
01458     - For base table we assume that either table exists and was pre-opened
01459       and locked at openTablesLock() stage (and in this case we just
01460       emit error or warning and return pre-opened Table object) or special
01461       placeholder was put in table cache that guarantees that this table
01462       won't be created or opened until the placeholder will be removed
01463       (so there is an exclusive lock on this table).
01464     - We don't pre-open existing temporary table, instead we either open
01465       or create and then open table in this function.
01466 
01467     Since this function contains some logic specific to CREATE TABLE ...
01468     SELECT it should be changed before it can be used in other contexts.
01469 
01470   RETURN VALUES
01471     non-zero  Pointer to Table object for table created or opened
01472     0         Error
01473 */
01474 
01475 static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
01476                                       TableList *create_table,
01477               message::Table &table_proto,
01478                                       AlterInfo *alter_info,
01479                                       List<Item> *items,
01480                                       bool is_if_not_exists,
01481                                       DrizzleLock **lock,
01482               const identifier::Table& identifier)
01483 {
01484   TableShare share(message::Table::INTERNAL);
01485   uint32_t select_field_count= items->size();
01486   /* Add selected items to field list */
01487   List<Item>::iterator it(items->begin());
01488   Item *item;
01489   Field *tmp_field;
01490 
01491   if (not (identifier.isTmp()) && create_table->table->db_stat)
01492   {
01493     /* Table already exists and was open at openTablesLock() stage. */
01494     if (is_if_not_exists)
01495     {
01496       create_info->table_existed= 1;    // Mark that table existed
01497       push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
01498                           ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
01499                           create_table->getTableName());
01500       return create_table->table;
01501     }
01502 
01503     my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
01504     return NULL;
01505   }
01506 
01507   {
01508     table::Shell tmp_table(share);    // Used during 'CreateField()'
01509 
01510     if (not table_proto.engine().name().compare("MyISAM"))
01511       tmp_table.getMutableShare()->db_low_byte_first= true;
01512     else if (not table_proto.engine().name().compare("MEMORY"))
01513       tmp_table.getMutableShare()->db_low_byte_first= true;
01514 
01515     tmp_table.in_use= session;
01516 
01517     while ((item=it++))
01518     {
01519       CreateField *cr_field;
01520       Field *field, *def_field;
01521       if (item->type() == Item::FUNC_ITEM)
01522       {
01523         if (item->result_type() != STRING_RESULT)
01524         {
01525           field= item->tmp_table_field(&tmp_table);
01526         }
01527         else
01528         {
01529           field= item->tmp_table_field_from_field_type(&tmp_table, 0);
01530         }
01531       }
01532       else
01533       {
01534         field= create_tmp_field(session, &tmp_table, item, item->type(),
01535                                 (Item ***) 0, &tmp_field, &def_field, false,
01536                                 false, false, 0);
01537       }
01538 
01539       if (!field ||
01540           !(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
01541                                             ((Item_field *)item)->field :
01542                                             (Field*) 0))))
01543       {
01544         return NULL;
01545       }
01546 
01547       if (item->maybe_null)
01548       {
01549         cr_field->flags &= ~NOT_NULL_FLAG;
01550       }
01551 
01552       alter_info->create_list.push_back(cr_field);
01553     }
01554   }
01555 
01556   /*
01557     Create and lock table.
01558 
01559     Note that we either creating (or opening existing) temporary table or
01560     creating base table on which name we have exclusive lock. So code below
01561     should not cause deadlocks or races.
01562   */
01563   Table *table= 0;
01564   {
01565     if (not create_table_no_lock(session,
01566          identifier,
01567          create_info,
01568          table_proto,
01569          alter_info,
01570          false,
01571          select_field_count,
01572          is_if_not_exists))
01573     {
01574       if (create_info->table_existed && not identifier.isTmp())
01575       {
01576         /*
01577           This means that someone created table underneath server
01578           or it was created via different mysqld front-end to the
01579           cluster. We don't have much options but throw an error.
01580         */
01581         my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
01582         return NULL;
01583       }
01584 
01585       if (not identifier.isTmp())
01586       {
01587         /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
01588         boost::mutex::scoped_lock scopedLock(table::Cache::mutex());
01589 
01590         if (create_table->table)
01591         {
01592           table::Concurrent *concurrent_table= static_cast<table::Concurrent *>(create_table->table);
01593 
01594           if (concurrent_table->reopen_name_locked_table(create_table, session))
01595           {
01596             (void)plugin::StorageEngine::dropTable(*session, identifier);
01597           }
01598           else
01599           {
01600             table= create_table->table;
01601           }
01602         }
01603         else
01604         {
01605           (void)plugin::StorageEngine::dropTable(*session, identifier);
01606         }
01607       }
01608       else
01609       {
01610         if (not (table= session->openTable(create_table, (bool*) 0,
01611                                            DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
01612             not create_info->table_existed)
01613         {
01614           /*
01615             This shouldn't happen as creation of temporary table should make
01616             it preparable for open. But let us do close_temporary_table() here
01617             just in case.
01618           */
01619           session->open_tables.drop_temporary_table(identifier);
01620         }
01621       }
01622     }
01623     if (not table)                                   // open failed
01624       return NULL;
01625   }
01626 
01627   table->reginfo.lock_type=TL_WRITE;
01628   if (not ((*lock)= session->lockTables(&table, 1, DRIZZLE_LOCK_IGNORE_FLUSH)))
01629   {
01630     if (*lock)
01631     {
01632       session->unlockTables(*lock);
01633       *lock= 0;
01634     }
01635 
01636     if (not create_info->table_existed)
01637       session->drop_open_table(table, identifier);
01638 
01639     return NULL;
01640   }
01641 
01642   return table;
01643 }
01644 
01645 
01646 int
01647 select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
01648 {
01649   DrizzleLock *extra_lock= NULL;
01650   /*
01651     For replication, the CREATE-SELECT statement is written
01652     in two pieces: the first transaction messsage contains
01653     the CREATE TABLE statement as a CreateTableStatement message
01654     necessary to create the table.
01655 
01656     The second transaction message contains all the InsertStatement
01657     and associated InsertRecords that should go into the table.
01658    */
01659 
01660   unit= u;
01661 
01662   if (not (table= create_table_from_items(session, create_info, create_table,
01663             table_proto,
01664             alter_info, &values,
01665             is_if_not_exists,
01666             &extra_lock, identifier)))
01667   {
01668     return(-1);       // abort() deletes table
01669   }
01670 
01671   if (extra_lock)
01672   {
01673     assert(m_plock == NULL);
01674 
01675     if (identifier.isTmp())
01676       m_plock= &m_lock;
01677     else
01678       m_plock= &session->open_tables.extra_lock;
01679 
01680     *m_plock= extra_lock;
01681   }
01682 
01683   if (table->getShare()->sizeFields() < values.size())
01684   {
01685     my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
01686     return(-1);
01687   }
01688 
01689  /* First field to copy */
01690   field= table->getFields() + table->getShare()->sizeFields() - values.size();
01691 
01692   /* Mark all fields that are given values */
01693   for (Field **f= field ; *f ; f++)
01694   {
01695     table->setWriteSet((*f)->position());
01696   }
01697 
01698   /* Don't set timestamp if used */
01699   table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
01700   table->next_number_field=table->found_next_number_field;
01701 
01702   table->restoreRecordAsDefault();      // Get empty record
01703   session->cuted_fields=0;
01704   if (info.ignore || info.handle_duplicates != DUP_ERROR)
01705     table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
01706 
01707   if (info.handle_duplicates == DUP_REPLACE)
01708     table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
01709 
01710   if (info.handle_duplicates == DUP_UPDATE)
01711     table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
01712 
01713   table->cursor->ha_start_bulk_insert((ha_rows) 0);
01714   session->setAbortOnWarning(not info.ignore);
01715   if (check_that_all_fields_are_given_values(session, table, table_list))
01716     return 1;
01717 
01718   table->mark_columns_needed_for_insert();
01719   table->cursor->extra(HA_EXTRA_WRITE_CACHE);
01720   return 0;
01721 }
01722 
01723 void select_create::store_values(List<Item> &values)
01724 {
01725   fill_record(session, field, values, true);
01726 }
01727 
01728 
01729 void select_create::send_error(drizzled::error_t errcode,const char *err)
01730 {
01731   /*
01732     This will execute any rollbacks that are necessary before writing
01733     the transcation cache.
01734 
01735     We disable the binary log since nothing should be written to the
01736     binary log.  This disabling is important, since we potentially do
01737     a "roll back" of non-transactional tables by removing the table,
01738     and the actual rollback might generate events that should not be
01739     written to the binary log.
01740 
01741   */
01742   select_insert::send_error(errcode, err);
01743 }
01744 
01745 
01746 bool select_create::send_eof()
01747 {
01748   bool tmp=select_insert::send_eof();
01749   if (tmp)
01750     abort();
01751   else
01752   {
01753     /*
01754       Do an implicit commit at end of statement for non-temporary
01755       tables.  This can fail, but we should unlock the table
01756       nevertheless.
01757     */
01758     if (!table->getShare()->getType())
01759     {
01760       TransactionServices::autocommitOrRollback(*session, 0);
01761       (void) session->endActiveTransaction();
01762     }
01763 
01764     table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
01765     table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
01766     if (m_plock)
01767     {
01768       session->unlockTables(*m_plock);
01769       *m_plock= NULL;
01770       m_plock= NULL;
01771     }
01772   }
01773   return tmp;
01774 }
01775 
01776 
01777 void select_create::abort()
01778 {
01779   /*
01780     In select_insert::abort() we roll back the statement, including
01781     truncating the transaction cache of the binary log. To do this, we
01782     pretend that the statement is transactional, even though it might
01783     be the case that it was not.
01784 
01785     We roll back the statement prior to deleting the table and prior
01786     to releasing the lock on the table, since there might be potential
01787     for failure if the rollback is executed after the drop or after
01788     unlocking the table.
01789 
01790     We also roll back the statement regardless of whether the creation
01791     of the table succeeded or not, since we need to reset the binary
01792     log state.
01793   */
01794   select_insert::abort();
01795 
01796   if (m_plock)
01797   {
01798     session->unlockTables(*m_plock);
01799     *m_plock= NULL;
01800     m_plock= NULL;
01801   }
01802 
01803   if (table)
01804   {
01805     table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
01806     table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
01807     if (not create_info->table_existed)
01808       session->drop_open_table(table, identifier);
01809     table= NULL;                                    // Safety
01810   }
01811 }
01812 
01813 } /* namespace drizzled */