Drizzled Public API Documentation

sql_parse.cc

00001 /* Copyright (C) 2000-2003 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 #include <config.h>
00017 
00018 #define DRIZZLE_LEX 1
00019 
00020 #include <drizzled/item/num.h>
00021 #include <drizzled/abort_exception.h>
00022 #include <drizzled/error.h>
00023 #include <drizzled/nested_join.h>
00024 #include <drizzled/query_id.h>
00025 #include <drizzled/transaction_services.h>
00026 #include <drizzled/sql_parse.h>
00027 #include <drizzled/data_home.h>
00028 #include <drizzled/sql_base.h>
00029 #include <drizzled/show.h>
00030 #include <drizzled/function/time/unix_timestamp.h>
00031 #include <drizzled/function/get_system_var.h>
00032 #include <drizzled/item/cmpfunc.h>
00033 #include <drizzled/item/null.h>
00034 #include <drizzled/session.h>
00035 #include <drizzled/session/cache.h>
00036 #include <drizzled/sql_load.h>
00037 #include <drizzled/lock.h>
00038 #include <drizzled/select_send.h>
00039 #include <drizzled/plugin/client.h>
00040 #include <drizzled/statement.h>
00041 #include <drizzled/statement/alter_table.h>
00042 #include <drizzled/probes.h>
00043 #include <drizzled/global_charset_info.h>
00044 #include <drizzled/plugin/logging.h>
00045 #include <drizzled/plugin/query_rewrite.h>
00046 #include <drizzled/plugin/query_cache.h>
00047 #include <drizzled/plugin/authorization.h>
00048 #include <drizzled/optimizer/explain_plan.h>
00049 #include <drizzled/pthread_globals.h>
00050 #include <drizzled/plugin/event_observer.h>
00051 #include <drizzled/display.h>
00052 #include <drizzled/visibility.h>
00053 #include <drizzled/kill.h>
00054 #include <drizzled/schema.h>
00055 #include <drizzled/item/subselect.h>
00056 
00057 #include <limits.h>
00058 
00059 #include <bitset>
00060 #include <algorithm>
00061 #include <boost/date_time.hpp>
00062 #include <drizzled/internal/my_sys.h>
00063 
00064 using namespace std;
00065 
00066 extern int base_sql_parse(drizzled::Session *session); // from sql_yacc.cc
00067 
00068 namespace drizzled
00069 {
00070 
00071 /* Prototypes */
00072 bool my_yyoverflow(short **a, ParserType **b, ulong *yystacksize);
00073 static bool parse_sql(Session *session, Lex_input_stream *lip);
00074 void parse(Session *session, const char *inBuf, uint32_t length);
00075 
00081 extern size_t my_thread_stack_size;
00082 extern const CHARSET_INFO *character_set_filesystem;
00083 
00084 namespace
00085 {
00086 
00087 static const std::string command_name[COM_END+1]={
00088   "Sleep",
00089   "Quit",
00090   "Init DB",
00091   "Query",
00092   "Shutdown",
00093   "Connect",
00094   "Ping",
00095   "Kill",
00096   "Error"  // Last command number
00097 };
00098 
00099 }
00100 
00101 const char *xa_state_names[]={
00102   "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
00103 };
00104 
00117 bitset<CF_BIT_SIZE> sql_command_flags[SQLCOM_END+1];
00118 
00119 const std::string &getCommandName(const enum_server_command& command)
00120 {
00121   return command_name[command];
00122 }
00123 
00124 void init_update_queries(void)
00125 {
00126   uint32_t x;
00127 
00128   for (x= 0; x <= SQLCOM_END; x++)
00129     sql_command_flags[x].reset();
00130 
00131   sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA;
00132   sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
00133   sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
00134   sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
00135   sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
00136   sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA;
00137   sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA;
00138   sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA;
00139   sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA;
00140   sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA;
00141 
00142   sql_command_flags[SQLCOM_UPDATE]=     CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
00143   sql_command_flags[SQLCOM_INSERT]=     CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
00144   sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
00145   sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
00146   sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
00147   sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
00148 
00149   sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
00150   sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
00151   sql_command_flags[SQLCOM_SHOW_CREATE_DB]=  CF_STATUS_COMMAND;
00152   sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
00153 
00154   /*
00155     The following admin table operations are allowed
00156     on log tables.
00157   */
00158   sql_command_flags[SQLCOM_ANALYZE]=          CF_WRITE_LOGS_COMMAND;
00159 }
00160 
00182 bool dispatch_command(enum_server_command command, Session *session,
00183                       char* packet, uint32_t packet_length)
00184 {
00185   bool error= 0;
00186   Query_id &query_id= Query_id::get_query_id();
00187 
00188   DRIZZLE_COMMAND_START(session->thread_id, command);
00189 
00190   session->command= command;
00191   session->lex().sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
00192   session->set_time();
00193   session->setQueryId(query_id.value());
00194 
00195   switch( command ) {
00196   /* Ignore these statements. */
00197   case COM_PING:
00198     break;
00199   /* Increase id and count all other statements. */
00200   default:
00201     session->status_var.questions++;
00202     query_id.next();
00203   }
00204 
00205   /* @todo set session->lex().sql_command to SQLCOM_END here */
00206 
00207   plugin::Logging::preDo(session);
00208   if (unlikely(plugin::EventObserver::beforeStatement(*session)))
00209   {
00210     // We should do something about an error...
00211   }
00212 
00213   session->server_status&=
00214            ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
00215 
00216   switch (command) {
00217   case COM_INIT_DB:
00218   {
00219     if (packet_length == 0)
00220     {
00221       my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
00222       break;
00223     }
00224 
00225     string tmp(packet, packet_length);
00226 
00227     identifier::Schema identifier(tmp);
00228 
00229     if (not schema::change(*session, identifier))
00230     {
00231       session->my_ok();
00232     }
00233     break;
00234   }
00235   case COM_QUERY:
00236   {
00237     if (not session->readAndStoreQuery(packet, packet_length))
00238       break;          // fatal error is set
00239     DRIZZLE_QUERY_START(session->getQueryString()->c_str(),
00240                         session->thread_id,
00241                         const_cast<const char *>(session->schema()->c_str()));
00242 
00243     parse(session, session->getQueryString()->c_str(), session->getQueryString()->length());
00244 
00245     break;
00246   }
00247   case COM_QUIT:
00248     /* We don't calculate statistics for this command */
00249     session->main_da.disable_status();              // Don't send anything back
00250     error= true;          // End server
00251     break;
00252   case COM_KILL:
00253     {
00254       if (packet_length != 4)
00255       {
00256         my_error(ER_NO_SUCH_THREAD, MYF(0), 0);
00257         break;
00258       }
00259       else
00260       {
00261         uint32_t kill_id;
00262         memcpy(&kill_id, packet, sizeof(uint32_t));
00263 
00264         kill_id= ntohl(kill_id);
00265         (void)drizzled::kill(*session->user(), kill_id, true);
00266       }
00267       session->my_ok();
00268       break;
00269     }
00270   case COM_SHUTDOWN:
00271   {
00272     session->status_var.com_other++;
00273     session->my_eof();
00274     session->close_thread_tables();     // Free before kill
00275     kill_drizzle();
00276     error= true;
00277     break;
00278   }
00279   case COM_PING:
00280     session->status_var.com_other++;
00281     session->my_ok();       // Tell client we are alive
00282     break;
00283   case COM_SLEEP:
00284   case COM_CONNECT:       // Impossible here
00285   case COM_END:
00286   default:
00287     my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
00288     break;
00289   }
00290 
00291   /* If commit fails, we should be able to reset the OK status. */
00292   session->main_da.can_overwrite_status= true;
00293   TransactionServices &transaction_services= TransactionServices::singleton();
00294   transaction_services.autocommitOrRollback(*session, session->is_error());
00295   session->main_da.can_overwrite_status= false;
00296 
00297   session->transaction.stmt.reset();
00298 
00299 
00300   /* report error issued during command execution */
00301   if (session->killed_errno())
00302   {
00303     if (! session->main_da.is_set())
00304       session->send_kill_message();
00305   }
00306   if (session->getKilled() == Session::KILL_QUERY || session->getKilled() == Session::KILL_BAD_DATA)
00307   {
00308     session->setKilled(Session::NOT_KILLED);
00309     session->setAbort(false);
00310   }
00311 
00312   /* Can not be true, but do not take chances in production. */
00313   assert(! session->main_da.is_sent);
00314 
00315   switch (session->main_da.status())
00316   {
00317   case Diagnostics_area::DA_ERROR:
00318     /* The query failed, send error to log and abort bootstrap. */
00319     session->getClient()->sendError(session->main_da.sql_errno(),
00320                                session->main_da.message());
00321     break;
00322 
00323   case Diagnostics_area::DA_EOF:
00324     session->getClient()->sendEOF();
00325     break;
00326 
00327   case Diagnostics_area::DA_OK:
00328     session->getClient()->sendOK();
00329     break;
00330 
00331   case Diagnostics_area::DA_DISABLED:
00332     break;
00333 
00334   case Diagnostics_area::DA_EMPTY:
00335   default:
00336     session->getClient()->sendOK();
00337     break;
00338   }
00339 
00340   session->main_da.is_sent= true;
00341 
00342   session->set_proc_info("closing tables");
00343   /* Free tables */
00344   session->close_thread_tables();
00345 
00346   plugin::Logging::postDo(session);
00347   if (unlikely(plugin::EventObserver::afterStatement(*session)))
00348   {
00349     // We should do something about an error...
00350   }
00351 
00352   /* Store temp state for processlist */
00353   session->set_proc_info("cleaning up");
00354   session->command= COM_SLEEP;
00355   session->resetQueryString();
00356 
00357   session->set_proc_info(NULL);
00358   session->mem_root->free_root(MYF(memory::KEEP_PREALLOC));
00359 
00360   if (DRIZZLE_QUERY_DONE_ENABLED() || DRIZZLE_COMMAND_DONE_ENABLED())
00361   {
00362     if (command == COM_QUERY)
00363     {
00364       DRIZZLE_QUERY_DONE(session->is_error());
00365     }
00366     DRIZZLE_COMMAND_DONE(session->is_error());
00367   }
00368 
00369   return error;
00370 }
00371 
00372 
00398 static bool _schema_select(Session *session, Select_Lex *sel,
00399                            const string& schema_table_name)
00400 {
00401   LEX_STRING db, table;
00402   bitset<NUM_OF_TABLE_OPTIONS> table_options;
00403   /*
00404      We have to make non const db_name & table_name
00405      because of lower_case_table_names
00406   */
00407   session->make_lex_string(&db, "data_dictionary", sizeof("data_dictionary"), false);
00408   session->make_lex_string(&table, schema_table_name, false);
00409 
00410   if (! sel->add_table_to_list(session, new Table_ident(db, table),
00411                                NULL, table_options, TL_READ))
00412   {
00413     return true;
00414   }
00415   return false;
00416 }
00417 
00418 int prepare_new_schema_table(Session *session, LEX& lex,
00419                              const string& schema_table_name)
00420 {
00421   Select_Lex *schema_select_lex= NULL;
00422 
00423   Select_Lex *select_lex= lex.current_select;
00424   assert(select_lex);
00425   if (_schema_select(session, select_lex, schema_table_name))
00426   {
00427     return(1);
00428   }
00429   TableList *table_list= (TableList*) select_lex->table_list.first;
00430   assert(table_list);
00431   table_list->schema_select_lex= schema_select_lex;
00432 
00433   return 0;
00434 }
00435 
00466 static int execute_command(Session *session)
00467 {
00468   bool res= false;
00469 
00470   /* first Select_Lex (have special meaning for many of non-SELECTcommands) */
00471   Select_Lex *select_lex= &session->lex().select_lex;
00472 
00473   /* list of all tables in query */
00474   TableList *all_tables;
00475 
00476   /*
00477     In many cases first table of main Select_Lex have special meaning =>
00478     check that it is first table in global list and relink it first in
00479     queries_tables list if it is necessary (we need such relinking only
00480     for queries with subqueries in select list, in this case tables of
00481     subqueries will go to global list first)
00482 
00483     all_tables will differ from first_table only if most upper Select_Lex
00484     do not contain tables.
00485 
00486     Because of above in place where should be at least one table in most
00487     outer Select_Lex we have following check:
00488     assert(first_table == all_tables);
00489     assert(first_table == all_tables && first_table != 0);
00490   */
00491   session->lex().first_lists_tables_same();
00492 
00493   /* should be assigned after making first tables same */
00494   all_tables= session->lex().query_tables;
00495 
00496   /* set context for commands which do not use setup_tables */
00497   select_lex->context.resolve_in_table_list_only((TableList*)select_lex->table_list.first);
00498 
00499   /*
00500     Reset warning count for each query that uses tables
00501     A better approach would be to reset this for any commands
00502     that is not a SHOW command or a select that only access local
00503     variables, but for now this is probably good enough.
00504     Don't reset warnings when executing a stored routine.
00505   */
00506   if (all_tables || ! session->lex().is_single_level_stmt())
00507   {
00508     drizzle_reset_errors(session, 0);
00509   }
00510 
00511   assert(session->transaction.stmt.hasModifiedNonTransData() == false);
00512 
00513   if (! (session->server_status & SERVER_STATUS_AUTOCOMMIT)
00514       && ! session->inTransaction()
00515       && session->lex().statement->isTransactional())
00516   {
00517     if (session->startTransaction() == false)
00518     {
00519       my_error(drizzled::ER_UNKNOWN_ERROR, MYF(0));
00520       return true;
00521     }
00522   }
00523 
00524   /* now we are ready to execute the statement */
00525   res= session->lex().statement->execute();
00526   session->set_proc_info("query end");
00527   /*
00528     The return value for ROW_COUNT() is "implementation dependent" if the
00529     statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
00530     wants. We also keep the last value in case of SQLCOM_CALL or
00531     SQLCOM_EXECUTE.
00532   */
00533   if (! (sql_command_flags[session->lex().sql_command].test(CF_BIT_HAS_ROW_COUNT)))
00534   {
00535     session->row_count_func= -1;
00536   }
00537 
00538   return (res || session->is_error());
00539 }
00540 bool execute_sqlcom_select(Session *session, TableList *all_tables)
00541 {
00542   LEX *lex= &session->lex();
00543   select_result *result=lex->result;
00544   bool res= false;
00545   /* assign global limit variable if limit is not given */
00546   {
00547     Select_Lex *param= lex->unit.global_parameters;
00548     if (!param->explicit_limit)
00549       param->select_limit=
00550         new Item_int((uint64_t) session->variables.select_limit);
00551   }
00552 
00553   if (all_tables
00554       && ! (session->server_status & SERVER_STATUS_AUTOCOMMIT)
00555       && ! session->inTransaction()
00556       && ! lex->statement->isShow())
00557   {
00558     if (session->startTransaction() == false)
00559     {
00560       my_error(drizzled::ER_UNKNOWN_ERROR, MYF(0));
00561       return true;
00562     }
00563   }
00564 
00565   if (not (res= session->openTablesLock(all_tables)))
00566   {
00567     if (lex->describe)
00568     {
00569       /*
00570         We always use select_send for EXPLAIN, even if it's an EXPLAIN
00571         for SELECT ... INTO OUTFILE: a user application should be able
00572         to prepend EXPLAIN to any query and receive output for it,
00573         even if the query itself redirects the output.
00574       */
00575       if (!(result= new select_send()))
00576         return true;
00577       session->send_explain_fields(result);
00578       optimizer::ExplainPlan planner;
00579       res= planner.explainUnion(session, &session->lex().unit, result);
00580       if (lex->describe & DESCRIBE_EXTENDED)
00581       {
00582         char buff[1024];
00583         String str(buff,(uint32_t) sizeof(buff), system_charset_info);
00584         str.length(0);
00585         session->lex().unit.print(&str);
00586         str.append('\0');
00587         push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
00588                      ER_YES, str.ptr());
00589       }
00590       if (res)
00591         result->abort();
00592       else
00593         result->send_eof();
00594 
00595       delete result;
00596     }
00597     else
00598     {
00599       if (!result && !(result= new select_send()))
00600         return true;
00601 
00602       /* Init the Query Cache plugin */
00603       plugin::QueryCache::prepareResultset(session);
00604       res= handle_select(session, lex, result, 0);
00605       /* Send the Resultset to the cache */
00606       plugin::QueryCache::setResultset(session);
00607 
00608       if (result != lex->result)
00609         delete result;
00610     }
00611   }
00612   return res;
00613 }
00614 
00615 
00616 #define MY_YACC_INIT 1000     // Start with big alloc
00617 #define MY_YACC_MAX  32000      // Because of 'short'
00618 
00619 bool my_yyoverflow(short **yyss, ParserType **yyvs, ulong *yystacksize)
00620 {
00621   LEX *lex= &current_session->lex();
00622   ulong old_info=0;
00623   if ((uint32_t) *yystacksize >= MY_YACC_MAX)
00624     return 1;
00625   if (!lex->yacc_yyvs)
00626     old_info= *yystacksize;
00627   *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
00628   unsigned char *tmpptr= NULL;
00629   if (!(tmpptr= (unsigned char *)realloc(lex->yacc_yyvs,
00630                                          *yystacksize* sizeof(**yyvs))))
00631       return 1;
00632   lex->yacc_yyvs= tmpptr;
00633   tmpptr= NULL;
00634   if (!(tmpptr= (unsigned char*)realloc(lex->yacc_yyss,
00635                                         *yystacksize* sizeof(**yyss))))
00636       return 1;
00637   lex->yacc_yyss= tmpptr;
00638   if (old_info)
00639   {           // Copy old info from stack
00640     memcpy(lex->yacc_yyss, *yyss, old_info*sizeof(**yyss));
00641     memcpy(lex->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
00642   }
00643   *yyss=(short*) lex->yacc_yyss;
00644   *yyvs=(ParserType*) lex->yacc_yyvs;
00645   return 0;
00646 }
00647 
00648 
00649 void
00650 init_select(LEX *lex)
00651 {
00652   Select_Lex *select_lex= lex->current_select;
00653   select_lex->init_select();
00654   lex->wild= 0;
00655   if (select_lex == &lex->select_lex)
00656   {
00657     assert(lex->result == 0);
00658     lex->exchange= 0;
00659   }
00660 }
00661 
00662 
00663 bool
00664 new_select(LEX *lex, bool move_down)
00665 {
00666   Select_Lex *select_lex;
00667   Session *session= lex->session;
00668 
00669   if (!(select_lex= new (session->mem_root) Select_Lex()))
00670     return true;
00671 
00672   select_lex->select_number= ++session->select_number;
00673   select_lex->parent_lex= lex; /* Used in init_query. */
00674   select_lex->init_query();
00675   select_lex->init_select();
00676   lex->nest_level++;
00677 
00678   if (lex->nest_level > (int) MAX_SELECT_NESTING)
00679   {
00680     my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
00681     return(1);
00682   }
00683 
00684   select_lex->nest_level= lex->nest_level;
00685   if (move_down)
00686   {
00687     Select_Lex_Unit *unit;
00688     /* first select_lex of subselect or derived table */
00689     if (!(unit= new (session->mem_root) Select_Lex_Unit()))
00690       return(1);
00691 
00692     unit->init_query();
00693     unit->init_select();
00694     unit->session= session;
00695     unit->include_down(lex->current_select);
00696     unit->link_next= 0;
00697     unit->link_prev= 0;
00698     unit->return_to= lex->current_select;
00699     select_lex->include_down(unit);
00700     /*
00701       By default we assume that it is usual subselect and we have outer name
00702       resolution context, if no we will assign it to 0 later
00703     */
00704     select_lex->context.outer_context= &select_lex->outer_select()->context;
00705   }
00706   else
00707   {
00708     if (lex->current_select->order_list.first && !lex->current_select->braces)
00709     {
00710       my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
00711       return true;
00712     }
00713 
00714     select_lex->include_neighbour(lex->current_select);
00715     Select_Lex_Unit *unit= select_lex->master_unit();
00716 
00717     if (not unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
00718       return true;
00719 
00720     select_lex->context.outer_context=
00721                 unit->first_select()->context.outer_context;
00722   }
00723 
00724   select_lex->master_unit()->global_parameters= select_lex;
00725   select_lex->include_global((Select_Lex_Node**)&lex->all_selects_list);
00726   lex->current_select= select_lex;
00727   /*
00728     in subquery is SELECT query and we allow resolution of names in SELECT
00729     list
00730   */
00731   select_lex->context.resolve_in_select_list= true;
00732 
00733   return false;
00734 }
00735 
00746 void create_select_for_variable(Session *session, const char *var_name)
00747 {
00748   LEX *lex;
00749   LEX_STRING tmp, null_lex_string;
00750   Item *var;
00751   char buff[MAX_SYS_VAR_LENGTH*2+4+8];
00752   char *end= buff;
00753 
00754   lex= &session->lex();
00755   init_select(lex);
00756   lex->sql_command= SQLCOM_SELECT;
00757   tmp.str= (char*) var_name;
00758   tmp.length=strlen(var_name);
00759   memset(&null_lex_string.str, 0, sizeof(null_lex_string));
00760   /*
00761     We set the name of Item to @@session.var_name because that then is used
00762     as the column name in the output.
00763   */
00764   if ((var= get_system_var(session, OPT_SESSION, tmp, null_lex_string)))
00765   {
00766     end+= snprintf(buff, sizeof(buff), "@@session.%s", var_name);
00767     var->set_name(buff, end-buff, system_charset_info);
00768     session->add_item_to_list(var);
00769   }
00770 }
00771 
00772 
00781 void parse(Session *session, const char *inBuf, uint32_t length)
00782 {
00783   session->lex().start(session);
00784 
00785   session->reset_for_next_command();
00786   /* Check if the Query is Cached if and return true if yes
00787    * TODO the plugin has to make sure that the query is cacheble
00788    * by setting the query_safe_cache param to TRUE
00789    */
00790   bool res= true;
00791   if (plugin::QueryCache::isCached(session))
00792   {
00793     res= plugin::QueryCache::sendCachedResultset(session);
00794   }
00795   if (not res)
00796   {
00797     return;
00798   }
00799   LEX *lex= &session->lex();
00800   Lex_input_stream lip(session, inBuf, length);
00801   bool err= parse_sql(session, &lip);
00802   if (!err)
00803   {
00804     {
00805       if (not session->is_error())
00806       {
00807         DRIZZLE_QUERY_EXEC_START(session->getQueryString()->c_str(),
00808                                  session->thread_id,
00809                                  const_cast<const char *>(session->schema()->c_str()));
00810         // Implement Views here --Brian
00811         /* Actually execute the query */
00812         try
00813         {
00814           execute_command(session);
00815         }
00816         catch (...)
00817         {
00818           // Just try to catch any random failures that could have come
00819           // during execution.
00820           DRIZZLE_ABORT;
00821         }
00822         DRIZZLE_QUERY_EXEC_DONE(0);
00823       }
00824     }
00825   }
00826   else
00827   {
00828     assert(session->is_error());
00829   }
00830   lex->unit.cleanup();
00831   session->set_proc_info("freeing items");
00832   session->end_statement();
00833   session->cleanup_after_query();
00834   session->set_end_timer();
00835 }
00836 
00837 
00838 
00846 bool add_field_to_list(Session *session, LEX_STRING *field_name, enum_field_types type,
00847            char *length, char *decimals,
00848            uint32_t type_modifier,
00849                        enum column_format_type column_format,
00850            Item *default_value, Item *on_update_value,
00851                        LEX_STRING *comment,
00852            char *change,
00853                        List<String> *interval_list, const CHARSET_INFO * const cs)
00854 {
00855   register CreateField *new_field;
00856   LEX  *lex= &session->lex();
00857   statement::AlterTable *statement= (statement::AlterTable *)lex->statement;
00858 
00859   if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
00860     return true;
00861 
00862   if (type_modifier & PRI_KEY_FLAG)
00863   {
00864     Key *key;
00865     lex->col_list.push_back(new Key_part_spec(*field_name, 0));
00866     key= new Key(Key::PRIMARY, null_lex_str,
00867                       &default_key_create_info,
00868                       0, lex->col_list);
00869     statement->alter_info.key_list.push_back(key);
00870     lex->col_list.clear();
00871   }
00872   if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
00873   {
00874     Key *key;
00875     lex->col_list.push_back(new Key_part_spec(*field_name, 0));
00876     key= new Key(Key::UNIQUE, null_lex_str,
00877                  &default_key_create_info, 0,
00878                  lex->col_list);
00879     statement->alter_info.key_list.push_back(key);
00880     lex->col_list.clear();
00881   }
00882 
00883   if (default_value)
00884   {
00885     /*
00886       Default value should be literal => basic constants =>
00887       no need fix_fields()
00888 
00889       We allow only one function as part of default value -
00890       NOW() as default for TIMESTAMP type.
00891     */
00892     if (default_value->type() == Item::FUNC_ITEM &&
00893         !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
00894          (type == DRIZZLE_TYPE_TIMESTAMP or type == DRIZZLE_TYPE_MICROTIME)))
00895     {
00896       my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
00897       return true;
00898     }
00899     else if (default_value->type() == Item::NULL_ITEM)
00900     {
00901       default_value= 0;
00902       if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG)
00903       {
00904   my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
00905   return true;
00906       }
00907     }
00908     else if (type_modifier & AUTO_INCREMENT_FLAG)
00909     {
00910       my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
00911       return true;
00912     }
00913   }
00914 
00915   if (on_update_value && (type != DRIZZLE_TYPE_TIMESTAMP and type != DRIZZLE_TYPE_MICROTIME))
00916   {
00917     my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
00918     return true;
00919   }
00920 
00921   if (!(new_field= new CreateField()) ||
00922       new_field->init(session, field_name->str, type, length, decimals, type_modifier,
00923                       default_value, on_update_value, comment, change,
00924                       interval_list, cs, 0, column_format))
00925     return true;
00926 
00927   statement->alter_info.create_list.push_back(new_field);
00928   lex->last_field=new_field;
00929 
00930   return false;
00931 }
00932 
00933 
00953 TableList *Select_Lex::add_table_to_list(Session *session,
00954                                          Table_ident *table,
00955                                          LEX_STRING *alias,
00956                                          const bitset<NUM_OF_TABLE_OPTIONS>& table_options,
00957                                          thr_lock_type lock_type,
00958                                          List<Index_hint> *index_hints_arg,
00959                                          LEX_STRING *option)
00960 {
00961   TableList *ptr;
00962   TableList *previous_table_ref; /* The table preceding the current one. */
00963   char *alias_str;
00964   LEX *lex= &session->lex();
00965 
00966   if (!table)
00967     return NULL;        // End of memory
00968   alias_str= alias ? alias->str : table->table.str;
00969   if (! table_options.test(TL_OPTION_ALIAS) &&
00970       check_table_name(table->table.str, table->table.length))
00971   {
00972     my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
00973     return NULL;
00974   }
00975 
00976   if (table->is_derived_table() == false && table->db.str)
00977   {
00978     my_casedn_str(files_charset_info, table->db.str);
00979 
00980     identifier::Schema schema_identifier(string(table->db.str));
00981     if (not schema::check(*session, schema_identifier))
00982     {
00983 
00984       my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
00985       return NULL;
00986     }
00987   }
00988 
00989   if (!alias)         /* Alias is case sensitive */
00990   {
00991     if (table->sel)
00992     {
00993       my_message(ER_DERIVED_MUST_HAVE_ALIAS,
00994                  ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
00995       return NULL;
00996     }
00997     if (!(alias_str= (char*) session->getMemRoot()->duplicate(alias_str,table->table.length+1)))
00998       return NULL;
00999   }
01000   if (!(ptr = (TableList *) session->calloc(sizeof(TableList))))
01001     return NULL;
01002 
01003   if (table->db.str)
01004   {
01005     ptr->setIsFqtn(true);
01006     ptr->setSchemaName(table->db.str);
01007     ptr->db_length= table->db.length;
01008   }
01009   else if (lex->copy_db_to(ptr->getSchemaNamePtr(), &ptr->db_length))
01010     return NULL;
01011   else
01012     ptr->setIsFqtn(false);
01013 
01014   ptr->alias= alias_str;
01015   ptr->setIsAlias(alias ? true : false);
01016   ptr->setTableName(table->table.str);
01017   ptr->table_name_length=table->table.length;
01018   ptr->lock_type=   lock_type;
01019   ptr->force_index= table_options.test(TL_OPTION_FORCE_INDEX);
01020   ptr->ignore_leaves= table_options.test(TL_OPTION_IGNORE_LEAVES);
01021   ptr->derived=     table->sel;
01022   ptr->select_lex=  lex->current_select;
01023   ptr->index_hints= index_hints_arg;
01024   ptr->option= option ? option->str : 0;
01025   /* check that used name is unique */
01026   if (lock_type != TL_IGNORE)
01027   {
01028     TableList *first_table= (TableList*) table_list.first;
01029     for (TableList *tables= first_table ;
01030    tables ;
01031    tables=tables->next_local)
01032     {
01033       if (not my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
01034     not my_strcasecmp(system_charset_info, ptr->getSchemaName(), tables->getSchemaName()))
01035       {
01036   my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str);
01037   return NULL;
01038       }
01039     }
01040   }
01041   /* Store the table reference preceding the current one. */
01042   if (table_list.size() > 0)
01043   {
01044     /*
01045       table_list.next points to the last inserted TableList->next_local'
01046       element
01047       We don't use the offsetof() macro here to avoid warnings from gcc
01048     */
01049     previous_table_ref= (TableList*) ((char*) table_list.next -
01050                                        ((char*) &(ptr->next_local) -
01051                                         (char*) ptr));
01052     /*
01053       Set next_name_resolution_table of the previous table reference to point
01054       to the current table reference. In effect the list
01055       TableList::next_name_resolution_table coincides with
01056       TableList::next_local. Later this may be changed in
01057       store_top_level_join_columns() for NATURAL/USING joins.
01058     */
01059     previous_table_ref->next_name_resolution_table= ptr;
01060   }
01061 
01062   /*
01063     Link the current table reference in a local list (list for current select).
01064     Notice that as a side effect here we set the next_local field of the
01065     previous table reference to 'ptr'. Here we also add one element to the
01066     list 'table_list'.
01067   */
01068   table_list.link_in_list((unsigned char*) ptr, (unsigned char**) &ptr->next_local);
01069   ptr->next_name_resolution_table= NULL;
01070   /* Link table in global list (all used tables) */
01071   lex->add_to_query_tables(ptr);
01072   return ptr;
01073 }
01074 
01075 
01095 bool Select_Lex::init_nested_join(Session *session)
01096 {
01097   TableList *ptr;
01098   NestedJoin *nested_join;
01099 
01100   if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
01101                                        sizeof(NestedJoin))))
01102     return true;
01103   ptr->setNestedJoin(((NestedJoin*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList)))));
01104   nested_join= ptr->getNestedJoin();
01105   join_list->push_front(ptr);
01106   ptr->setEmbedding(embedding);
01107   ptr->setJoinList(join_list);
01108   ptr->alias= (char*) "(nested_join)";
01109   embedding= ptr;
01110   join_list= &nested_join->join_list;
01111   join_list->clear();
01112   return false;
01113 }
01114 
01115 
01130 TableList *Select_Lex::end_nested_join(Session *)
01131 {
01132   TableList *ptr;
01133   NestedJoin *nested_join;
01134 
01135   assert(embedding);
01136   ptr= embedding;
01137   join_list= ptr->getJoinList();
01138   embedding= ptr->getEmbedding();
01139   nested_join= ptr->getNestedJoin();
01140   if (nested_join->join_list.size() == 1)
01141   {
01142     TableList *embedded= &nested_join->join_list.front();
01143     join_list->pop();
01144     embedded->setJoinList(join_list);
01145     embedded->setEmbedding(embedding);
01146     join_list->push_front(embedded);
01147     ptr= embedded;
01148   }
01149   else if (nested_join->join_list.size() == 0)
01150   {
01151     join_list->pop();
01152     ptr= NULL;                                     // return value
01153   }
01154   return ptr;
01155 }
01156 
01157 
01171 TableList *Select_Lex::nest_last_join(Session *session)
01172 {
01173   TableList *ptr;
01174   NestedJoin *nested_join;
01175   List<TableList> *embedded_list;
01176 
01177   if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
01178                                           sizeof(NestedJoin))))
01179     return NULL;
01180   ptr->setNestedJoin(((NestedJoin*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList)))));
01181   nested_join= ptr->getNestedJoin();
01182   ptr->setEmbedding(embedding);
01183   ptr->setJoinList(join_list);
01184   ptr->alias= (char*) "(nest_last_join)";
01185   embedded_list= &nested_join->join_list;
01186   embedded_list->clear();
01187 
01188   for (uint32_t i=0; i < 2; i++)
01189   {
01190     TableList *table= join_list->pop();
01191     table->setJoinList(embedded_list);
01192     table->setEmbedding(ptr);
01193     embedded_list->push_back(table);
01194     if (table->natural_join)
01195     {
01196       ptr->is_natural_join= true;
01197       /*
01198         If this is a JOIN ... USING, move the list of joined fields to the
01199         table reference that describes the join.
01200       */
01201       if (prev_join_using)
01202         ptr->join_using_fields= prev_join_using;
01203     }
01204   }
01205   join_list->push_front(ptr);
01206   nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
01207   return ptr;
01208 }
01209 
01210 
01225 void Select_Lex::add_joined_table(TableList *table)
01226 {
01227   join_list->push_front(table);
01228   table->setJoinList(join_list);
01229   table->setEmbedding(embedding);
01230 }
01231 
01232 
01264 TableList *Select_Lex::convert_right_join()
01265 {
01266   TableList *tab2= join_list->pop();
01267   TableList *tab1= join_list->pop();
01268 
01269   join_list->push_front(tab2);
01270   join_list->push_front(tab1);
01271   tab1->outer_join|= JOIN_TYPE_RIGHT;
01272 
01273   return tab1;
01274 }
01275 
01287 void Select_Lex::set_lock_for_tables(thr_lock_type lock_type)
01288 {
01289   for (TableList *tables= (TableList*) table_list.first;
01290        tables;
01291        tables= tables->next_local)
01292   {
01293     tables->lock_type= lock_type;
01294   }
01295 }
01296 
01297 
01324 bool Select_Lex_Unit::add_fake_select_lex(Session *session_arg)
01325 {
01326   Select_Lex *first_sl= first_select();
01327   assert(!fake_select_lex);
01328 
01329   if (!(fake_select_lex= new (session_arg->mem_root) Select_Lex()))
01330       return(1);
01331   fake_select_lex->include_standalone(this,
01332                                       (Select_Lex_Node**)&fake_select_lex);
01333   fake_select_lex->select_number= INT_MAX;
01334   fake_select_lex->parent_lex= &session_arg->lex(); /* Used in init_query. */
01335   fake_select_lex->make_empty_select();
01336   fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
01337   fake_select_lex->select_limit= 0;
01338 
01339   fake_select_lex->context.outer_context=first_sl->context.outer_context;
01340   /* allow item list resolving in fake select for ORDER BY */
01341   fake_select_lex->context.resolve_in_select_list= true;
01342   fake_select_lex->context.select_lex= fake_select_lex;
01343 
01344   if (!is_union())
01345   {
01346     /*
01347       This works only for
01348       (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
01349       (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
01350       just before the parser starts processing order_list
01351     */
01352     global_parameters= fake_select_lex;
01353     fake_select_lex->no_table_names_allowed= 1;
01354     session_arg->lex().current_select= fake_select_lex;
01355   }
01356   session_arg->lex().pop_context();
01357   return(0);
01358 }
01359 
01360 
01380 bool
01381 push_new_name_resolution_context(Session *session,
01382                                  TableList *left_op, TableList *right_op)
01383 {
01384   Name_resolution_context *on_context;
01385   if (!(on_context= new (session->mem_root) Name_resolution_context))
01386     return true;
01387   on_context->init();
01388   on_context->first_name_resolution_table=
01389     left_op->first_leaf_for_name_resolution();
01390   on_context->last_name_resolution_table=
01391     right_op->last_leaf_for_name_resolution();
01392   return session->lex().push_context(on_context);
01393 }
01394 
01395 
01410 void add_join_on(TableList *b, Item *expr)
01411 {
01412   if (expr)
01413   {
01414     if (!b->on_expr)
01415       b->on_expr= expr;
01416     else
01417     {
01418       /*
01419         If called from the parser, this happens if you have both a
01420         right and left join. If called later, it happens if we add more
01421         than one condition to the ON clause.
01422       */
01423       b->on_expr= new Item_cond_and(b->on_expr,expr);
01424     }
01425     b->on_expr->top_level_item();
01426   }
01427 }
01428 
01429 
01463 void add_join_natural(TableList *a, TableList *b, List<String> *using_fields,
01464                       Select_Lex *lex)
01465 {
01466   b->natural_join= a;
01467   lex->prev_join_using= using_fields;
01468 }
01469 
01470 
01480 bool check_simple_select(Session::pointer session)
01481 {
01482   if (session->lex().current_select != &session->lex().select_lex)
01483   {
01484     char command[80];
01485     Lex_input_stream *lip= session->m_lip;
01486     strncpy(command, lip->yylval->symbol.str,
01487             min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1)));
01488     command[min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1))]=0;
01489     my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
01490     return 1;
01491   }
01492   return 0;
01493 }
01494 
01495 
01507 Item * all_any_subquery_creator(Item *left_expr,
01508                                 chooser_compare_func_creator cmp,
01509                                 bool all,
01510                                 Select_Lex *select_lex)
01511 {
01512   if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
01513     return new Item_in_subselect(left_expr, select_lex);
01514 
01515   if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
01516     return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
01517 
01518   Item_allany_subselect *it=
01519     new Item_allany_subselect(left_expr, cmp, select_lex, all);
01520   if (all)
01521     return it->upper_item= new Item_func_not_all(it); /* ALL */
01522 
01523   return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
01524 }
01525 
01526 
01539 bool update_precheck(Session *session, TableList *)
01540 {
01541   const char *msg= 0;
01542   Select_Lex *select_lex= &session->lex().select_lex;
01543 
01544   if (session->lex().select_lex.item_list.size() != session->lex().value_list.size())
01545   {
01546     my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
01547     return(true);
01548   }
01549 
01550   if (session->lex().select_lex.table_list.size() > 1)
01551   {
01552     if (select_lex->order_list.size())
01553       msg= "ORDER BY";
01554     else if (select_lex->select_limit)
01555       msg= "LIMIT";
01556     if (msg)
01557     {
01558       my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
01559       return(true);
01560     }
01561   }
01562   return(false);
01563 }
01564 
01565 
01578 bool insert_precheck(Session *session, TableList *)
01579 {
01580   /*
01581     Check that we have modify privileges for the first table and
01582     select privileges for the rest
01583   */
01584   if (session->lex().update_list.size() != session->lex().value_list.size())
01585   {
01586     my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
01587     return(true);
01588   }
01589   return(false);
01590 }
01591 
01592 
01603 Item *negate_expression(Session *session, Item *expr)
01604 {
01605   Item *negated;
01606   if (expr->type() == Item::FUNC_ITEM &&
01607       ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
01608   {
01609     /* it is NOT(NOT( ... )) */
01610     Item *arg= ((Item_func *) expr)->arguments()[0];
01611     enum_parsing_place place= session->lex().current_select->parsing_place;
01612     if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
01613       return arg;
01614     /*
01615       if it is not boolean function then we have to emulate value of
01616       not(not(a)), it will be a != 0
01617     */
01618     return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
01619   }
01620 
01621   if ((negated= expr->neg_transformer(session)) != 0)
01622     return negated;
01623   return new Item_func_not(expr);
01624 }
01625 
01626 
01627 /*
01628   Check that char length of a string does not exceed some limit.
01629 
01630   SYNOPSIS
01631   check_string_char_length()
01632       str              string to be checked
01633       err_msg          error message to be displayed if the string is too long
01634       max_char_length  max length in symbols
01635       cs               string charset
01636 
01637   RETURN
01638     false   the passed string is not longer than max_char_length
01639     true    the passed string is longer than max_char_length
01640 */
01641 
01642 
01643 bool check_string_char_length(LEX_STRING *str, const char *err_msg,
01644                               uint32_t max_char_length, const CHARSET_INFO * const cs,
01645                               bool no_error)
01646 {
01647   int well_formed_error;
01648   uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
01649                                       max_char_length, &well_formed_error);
01650 
01651   if (!well_formed_error &&  str->length == res)
01652     return false;
01653 
01654   if (!no_error)
01655     my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
01656   return true;
01657 }
01658 
01659 
01660 bool check_identifier_name(LEX_STRING *str, error_t err_code,
01661                            uint32_t max_char_length,
01662                            const char *param_for_err_msg)
01663 {
01664   /*
01665     We don't support non-BMP characters in identifiers at the moment,
01666     so they should be prohibited until such support is done.
01667     This is why we use the 3-byte utf8 to check well-formedness here.
01668   */
01669   const CHARSET_INFO * const cs= &my_charset_utf8mb4_general_ci;
01670 
01671   int well_formed_error;
01672   uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
01673                                       max_char_length, &well_formed_error);
01674 
01675   if (well_formed_error)
01676   {
01677     my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
01678     return true;
01679   }
01680 
01681   if (str->length == res)
01682     return false;
01683 
01684   switch (err_code)
01685   {
01686   case EE_OK:
01687     break;
01688   case ER_WRONG_STRING_LENGTH:
01689     my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
01690     break;
01691   case ER_TOO_LONG_IDENT:
01692     my_error(err_code, MYF(0), str->str);
01693     break;
01694   default:
01695     assert(0);
01696     break;
01697   }
01698 
01699   return true;
01700 }
01701 
01702 
01715 static bool parse_sql(Session *session, Lex_input_stream *lip)
01716 {
01717   assert(session->m_lip == NULL);
01718 
01719   DRIZZLE_QUERY_PARSE_START(session->getQueryString()->c_str());
01720 
01721   /* Set Lex_input_stream. */
01722 
01723   session->m_lip= lip;
01724 
01725   /* Parse the query. */
01726 
01727   bool parse_status= base_sql_parse(session) != 0;
01728 
01729   /* Check that if DRIZZLEparse() failed, session->is_error() is set. */
01730 
01731   assert(!parse_status || session->is_error());
01732 
01733   /* Reset Lex_input_stream. */
01734 
01735   session->m_lip= NULL;
01736 
01737   DRIZZLE_QUERY_PARSE_DONE(parse_status || session->is_fatal_error);
01738 
01739   /* That's it. */
01740 
01741   return parse_status || session->is_fatal_error;
01742 }
01743 
01748 } /* namespace drizzled */