Drizzled Public API Documentation

sql_parse.cc
1 /* Copyright (C) 2000-2003 MySQL AB
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 #include <config.h>
17 
18 #define DRIZZLE_LEX 1
19 
20 #include <drizzled/item/num.h>
21 #include <drizzled/abort_exception.h>
22 #include <drizzled/error.h>
23 #include <drizzled/nested_join.h>
24 #include <drizzled/transaction_services.h>
25 #include <drizzled/sql_parse.h>
26 #include <drizzled/data_home.h>
27 #include <drizzled/sql_base.h>
28 #include <drizzled/show.h>
29 #include <drizzled/function/time/unix_timestamp.h>
30 #include <drizzled/function/get_system_var.h>
31 #include <drizzled/item/cmpfunc.h>
32 #include <drizzled/item/null.h>
33 #include <drizzled/session.h>
34 #include <drizzled/session/cache.h>
35 #include <drizzled/sql_load.h>
36 #include <drizzled/lock.h>
37 #include <drizzled/select_send.h>
38 #include <drizzled/plugin/client.h>
39 #include <drizzled/statement.h>
40 #include <drizzled/statement/alter_table.h>
41 #include <drizzled/probes.h>
42 #include <drizzled/charset.h>
43 #include <drizzled/plugin/logging.h>
44 #include <drizzled/plugin/query_rewrite.h>
45 #include <drizzled/plugin/query_cache.h>
46 #include <drizzled/plugin/authorization.h>
47 #include <drizzled/optimizer/explain_plan.h>
48 #include <drizzled/pthread_globals.h>
49 #include <drizzled/plugin/event_observer.h>
50 #include <drizzled/display.h>
51 #include <drizzled/visibility.h>
52 #include <drizzled/kill.h>
53 #include <drizzled/schema.h>
54 #include <drizzled/item/subselect.h>
55 #include <drizzled/diagnostics_area.h>
56 #include <drizzled/table_ident.h>
57 #include <drizzled/statistics_variables.h>
58 #include <drizzled/system_variables.h>
59 #include <drizzled/session/times.h>
60 #include <drizzled/session/transactions.h>
61 #include <drizzled/create_field.h>
62 #include <drizzled/lex_input_stream.h>
63 
64 #include <limits.h>
65 
66 #include <bitset>
67 #include <algorithm>
68 #include <boost/date_time.hpp>
69 #include <drizzled/internal/my_sys.h>
70 
71 using namespace std;
72 
73 extern int base_sql_parse(drizzled::Session *session); // from sql_yacc.cc
74 
75 namespace drizzled {
76 
77 /* Prototypes */
78 bool my_yyoverflow(short **a, ParserType **b, ulong *yystacksize);
79 static bool parse_sql(Session *session, Lex_input_stream *lip);
80 void parse(Session&, str_ref);
81 
87 extern size_t my_thread_stack_size;
88 extern const charset_info_st *character_set_filesystem;
89 
90 static atomic<uint64_t> g_query_id;
91 
92 namespace
93 {
94  static const std::string command_name[]=
95  {
96  "Sleep",
97  "Quit",
98  "Init DB",
99  "Query",
100  "Shutdown",
101  "Connect",
102  "Ping",
103  "Kill",
104  "Error" // Last command number
105  };
106 }
107 
108 const char *xa_state_names[]=
109 {
110  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
111 };
112 
113 
126 bitset<CF_BIT_SIZE> sql_command_flags[SQLCOM_END+1];
127 
128 const std::string &getCommandName(const enum_server_command& command)
129 {
130  return command_name[command];
131 }
132 
133 void init_update_queries(void)
134 {
135  for (uint32_t x= uint32_t(SQLCOM_SELECT);
136  x <= uint32_t(SQLCOM_END); x++)
137  {
138  sql_command_flags[x].reset();
139  }
140 
141  sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA;
142  sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA;
143  sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
144  sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
145  sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA;
146  sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA;
147  sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA;
148  sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA;
149  sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA;
150  sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA;
151 
152  sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
153  sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
154  sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
155  sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
156  sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
157  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
158 
159  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
160  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
161  sql_command_flags[SQLCOM_SHOW_CREATE_DB]= CF_STATUS_COMMAND;
162  sql_command_flags[SQLCOM_SHOW_CREATE]= CF_STATUS_COMMAND;
163 
164  /*
165  The following admin table operations are allowed
166  on log tables.
167  */
168  sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND;
169 }
170 
192 bool dispatch_command(enum_server_command command, Session& session, str_ref packet)
193 {
194  bool error= false;
195 
196  DRIZZLE_COMMAND_START(session.thread_id, command);
197 
198  session.command= command;
199  session.lex().sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
200  session.times.set_time();
201  session.setQueryId(g_query_id.increment());
202 
203  if (command != COM_PING)
204  {
205  // Increase id and count all other statements
206  session.status_var.questions++;
207  }
208 
209  /* @todo set session.lex().sql_command to SQLCOM_END here */
210 
211  plugin::Logging::preDo(&session);
212  if (unlikely(plugin::EventObserver::beforeStatement(session)))
213  {
214  // We should do something about an error...
215  }
216 
217  session.server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
218 
219  switch (command)
220  {
221  case COM_USE_SCHEMA:
222  {
223  if (packet.empty())
224  {
225  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
226  break;
227  }
228  if (not schema::change(session, identifier::Schema(session.catalog().identifier(), packet)))
229  {
230  session.my_ok();
231  }
232  break;
233  }
234 
235  case COM_QUERY:
236  {
237  session.readAndStoreQuery(packet);
238  DRIZZLE_QUERY_START(session.getQueryString()->c_str(), session.thread_id, session.schema()->c_str());
239  parse(session, *session.getQueryString());
240  break;
241  }
242 
243  case COM_QUIT:
244  /* We don't calculate statistics for this command */
245  session.main_da().disable_status(); // Don't send anything back
246  error= true; // End server
247  break;
248 
249  case COM_KILL:
250  {
251  if (packet.size() != 4)
252  {
253  my_error(ER_NO_SUCH_THREAD, MYF(0), 0);
254  break;
255  }
256  else
257  {
258  uint32_t kill_id;
259  memcpy(&kill_id, packet.data(), sizeof(uint32_t));
260 
261  kill_id= ntohl(kill_id);
262  (void)drizzled::kill(*session.user(), kill_id, true);
263  }
264  session.my_ok();
265  break;
266  }
267 
268  case COM_SHUTDOWN:
269  {
270  session.status_var.com_other++;
271  session.my_eof();
272  session.close_thread_tables(); // Free before kill
273  kill_drizzle();
274  error= true;
275  break;
276  }
277 
278  case COM_PING:
279  session.status_var.com_other++;
280  session.my_ok(); // Tell client we are alive
281  break;
282 
283  case COM_SLEEP:
284  case COM_CONNECT: // Impossible here
285  case COM_END:
286  default:
287  my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
288  break;
289  }
290 
291  /* If commit fails, we should be able to reset the OK status. */
292  session.main_da().can_overwrite_status= true;
293  TransactionServices::autocommitOrRollback(session, session.is_error());
294  session.main_da().can_overwrite_status= false;
295 
296  session.transaction.stmt.reset();
297 
298 
299  /* report error issued during command execution */
300  if (session.killed_errno())
301  {
302  if (not session.main_da().is_set())
303  session.send_kill_message();
304  }
305  if (session.getKilled() == Session::KILL_QUERY || session.getKilled() == Session::KILL_BAD_DATA)
306  {
307  session.setKilled(Session::NOT_KILLED);
308  session.setAbort(false);
309  }
310 
311  /* Can not be true, but do not take chances in production. */
312  assert(not session.main_da().is_sent);
313 
314  switch (session.main_da().status())
315  {
316  case Diagnostics_area::DA_ERROR:
317  /* The query failed, send error to log and abort bootstrap. */
318  session.getClient()->sendError(session.main_da().sql_errno(), session.main_da().message());
319  break;
320 
321  case Diagnostics_area::DA_EOF:
322  session.getClient()->sendEOF();
323  break;
324 
325  case Diagnostics_area::DA_OK:
326  session.getClient()->sendOK();
327  break;
328 
329  case Diagnostics_area::DA_DISABLED:
330  break;
331 
332  case Diagnostics_area::DA_EMPTY:
333  default:
334  session.getClient()->sendOK();
335  }
336 
337  session.main_da().is_sent= true;
338 
339  session.set_proc_info("closing tables");
340  /* Free tables */
341  session.close_thread_tables();
342 
343  plugin::Logging::postDo(&session);
344  if (unlikely(plugin::EventObserver::afterStatement(session)))
345  {
346  // We should do something about an error...
347  }
348 
349  /* Store temp state for processlist */
350  session.set_proc_info("cleaning up");
351  session.command= COM_SLEEP;
352  session.resetQueryString();
353 
354  session.set_proc_info(NULL);
355  session.mem_root->free_root(MYF(memory::KEEP_PREALLOC));
356 
357  if (DRIZZLE_QUERY_DONE_ENABLED() || DRIZZLE_COMMAND_DONE_ENABLED())
358  {
359  if (command == COM_QUERY)
360  {
361  DRIZZLE_QUERY_DONE(session.is_error());
362  }
363  DRIZZLE_COMMAND_DONE(session.is_error());
364  }
365 
366  return error;
367 }
368 
369 
395 static bool _schema_select(Session& session, Select_Lex& sel, const string& schema_table_name)
396 {
397  lex_string_t db, table;
398  bitset<NUM_OF_TABLE_OPTIONS> table_options;
399  /*
400  We have to make non const db_name & table_name
401  because of lower_case_table_names
402  */
403  session.make_lex_string(&db, str_ref("data_dictionary"));
404  session.make_lex_string(&table, schema_table_name);
405  return not sel.add_table_to_list(&session, new Table_ident(db, table), NULL, table_options, TL_READ);
406 }
407 
408 int prepare_new_schema_table(Session *session, LEX& lex0, const string& schema_table_name)
409 {
410  Select_Lex& lex= *lex0.current_select;
411  if (_schema_select(*session, lex, schema_table_name))
412  return 1;
413  TableList *table_list= (TableList*)lex.table_list.first;
414  table_list->schema_select_lex= NULL;
415  return 0;
416 }
417 
448 static int execute_command(Session *session)
449 {
450  /* first Select_Lex (have special meaning for many of non-SELECTcommands) */
451  Select_Lex *select_lex= &session->lex().select_lex;
452 
453  /*
454  In many cases first table of main Select_Lex have special meaning =>
455  check that it is first table in global list and relink it first in
456  queries_tables list if it is necessary (we need such relinking only
457  for queries with subqueries in select list, in this case tables of
458  subqueries will go to global list first)
459 
460  all_tables will differ from first_table only if most upper Select_Lex
461  do not contain tables.
462 
463  Because of above in place where should be at least one table in most
464  outer Select_Lex we have following check:
465  assert(first_table == all_tables);
466  assert(first_table == all_tables && first_table != 0);
467  */
468  session->lex().first_lists_tables_same();
469 
470  /* list of all tables in query */
471  /* should be assigned after making first tables same */
472  TableList* all_tables= session->lex().query_tables;
473 
474  /* set context for commands which do not use setup_tables */
475  select_lex->context.resolve_in_table_list_only((TableList*)select_lex->table_list.first);
476 
477  /*
478  Reset warning count for each query that uses tables
479  A better approach would be to reset this for any commands
480  that is not a SHOW command or a select that only access local
481  variables, but for now this is probably good enough.
482  Don't reset warnings when executing a stored routine.
483  */
484  if (all_tables || ! session->lex().is_single_level_stmt())
485  {
486  drizzle_reset_errors(*session, 0);
487  }
488 
489  assert(not session->transaction.stmt.hasModifiedNonTransData());
490 
491  if (not (session->server_status & SERVER_STATUS_AUTOCOMMIT)
492  && not session->inTransaction()
493  && session->lex().statement->isTransactional())
494  {
495  if (not session->startTransaction())
496  {
497  my_error(drizzled::ER_UNKNOWN_ERROR, MYF(0));
498  return true;
499  }
500  }
501 
502  /* now we are ready to execute the statement */
503  bool res= session->lex().statement->execute();
504  session->set_proc_info("query end");
505  /*
506  The return value for ROW_COUNT() is "implementation dependent" if the
507  statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
508  wants. We also keep the last value in case of SQLCOM_CALL or
509  SQLCOM_EXECUTE.
510  */
511  if (not sql_command_flags[session->lex().sql_command].test(CF_BIT_HAS_ROW_COUNT))
512  {
513  session->row_count_func= -1;
514  }
515 
516  return res || session->is_error();
517 }
518 
519 bool execute_sqlcom_select(Session *session, TableList *all_tables)
520 {
521  LEX *lex= &session->lex();
522  select_result *result=lex->result;
523  bool res= false;
524  /* assign global limit variable if limit is not given */
525  {
526  Select_Lex *param= lex->unit.global_parameters;
527  if (!param->explicit_limit)
528  param->select_limit=
529  new Item_int((uint64_t) session->variables.select_limit);
530  }
531 
532  if (all_tables
533  && ! (session->server_status & SERVER_STATUS_AUTOCOMMIT)
534  && ! session->inTransaction()
535  && ! lex->statement->isShow())
536  {
537  if (not session->startTransaction())
538  {
539  my_error(drizzled::ER_UNKNOWN_ERROR, MYF(0));
540  return true;
541  }
542  }
543 
544  if (not (res= session->openTablesLock(all_tables)))
545  {
546  if (lex->describe)
547  {
548  /*
549  We always use select_send for EXPLAIN, even if it's an EXPLAIN
550  for SELECT ... INTO OUTFILE: a user application should be able
551  to prepend EXPLAIN to any query and receive output for it,
552  even if the query itself redirects the output.
553  */
554  result= new select_send();
555  session->send_explain_fields(result);
556  optimizer::ExplainPlan planner;
557  res= planner.explainUnion(session, &session->lex().unit, result);
558  if (lex->describe & DESCRIBE_EXTENDED)
559  {
560  char buff[1024];
561  String str(buff,(uint32_t) sizeof(buff), system_charset_info);
562  str.length(0);
563  session->lex().unit.print(&str);
564  str.append('\0');
565  push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
566  ER_YES, str.ptr());
567  }
568  if (res)
569  result->abort();
570  else
571  result->send_eof();
572 
573  delete result;
574  }
575  else
576  {
577  if (not result)
578  result= new select_send();
579 
580  /* Init the Query Cache plugin */
581  plugin::QueryCache::prepareResultset(session);
582  res= handle_select(session, lex, result, 0);
583  /* Send the Resultset to the cache */
584  plugin::QueryCache::setResultset(session);
585 
586  if (result != lex->result)
587  delete result;
588  }
589  }
590  return res;
591 }
592 
593 
594 #define MY_YACC_INIT 1000 // Start with big alloc
595 #define MY_YACC_MAX 32000 // Because of 'short'
596 
597 bool my_yyoverflow(short **yyss, ParserType **yyvs, ulong *yystacksize)
598 {
599  LEX *lex= &current_session->lex();
600  ulong old_info=0;
601  if ((uint32_t) *yystacksize >= MY_YACC_MAX)
602  return 1;
603  if (!lex->yacc_yyvs)
604  old_info= *yystacksize;
605  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
606  unsigned char *tmpptr= NULL;
607  if (!(tmpptr= (unsigned char *)realloc(lex->yacc_yyvs,
608  *yystacksize* sizeof(**yyvs))))
609  return 1;
610  lex->yacc_yyvs= tmpptr;
611  tmpptr= NULL;
612  if (!(tmpptr= (unsigned char*)realloc(lex->yacc_yyss,
613  *yystacksize* sizeof(**yyss))))
614  return 1;
615  lex->yacc_yyss= tmpptr;
616  if (old_info)
617  { // Copy old info from stack
618  memcpy(lex->yacc_yyss, *yyss, old_info*sizeof(**yyss));
619  memcpy(lex->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
620  }
621  *yyss=(short*) lex->yacc_yyss;
622  *yyvs=(ParserType*) lex->yacc_yyvs;
623  return 0;
624 }
625 
626 
627 void
628 init_select(LEX *lex)
629 {
630  Select_Lex *select_lex= lex->current_select;
631  select_lex->init_select();
632  lex->wild= 0;
633  if (select_lex == &lex->select_lex)
634  {
635  assert(lex->result == 0);
636  lex->exchange= 0;
637  }
638 }
639 
640 
641 bool new_select(LEX *lex, bool move_down)
642 {
643  Session* session= lex->session;
644  Select_Lex* select_lex= new (session->mem_root) Select_Lex;
645 
646  select_lex->select_number= ++session->select_number;
647  select_lex->parent_lex= lex; /* Used in init_query. */
648  select_lex->init_query();
649  select_lex->init_select();
650  lex->nest_level++;
651 
652  if (lex->nest_level > (int) MAX_SELECT_NESTING)
653  {
654  my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
655  return 1;
656  }
657 
658  select_lex->nest_level= lex->nest_level;
659  if (move_down)
660  {
661  /* first select_lex of subselect or derived table */
662  Select_Lex_Unit* unit= new (session->mem_root) Select_Lex_Unit();
663 
664  unit->init_query();
665  unit->init_select();
666  unit->session= session;
667  unit->include_down(lex->current_select);
668  unit->link_next= 0;
669  unit->link_prev= 0;
670  unit->return_to= lex->current_select;
671  select_lex->include_down(unit);
672  /*
673  By default we assume that it is usual subselect and we have outer name
674  resolution context, if no we will assign it to 0 later
675  */
676  select_lex->context.outer_context= &select_lex->outer_select()->context;
677  }
678  else
679  {
680  if (lex->current_select->order_list.first && !lex->current_select->braces)
681  {
682  my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
683  return true;
684  }
685 
686  select_lex->include_neighbour(lex->current_select);
687  Select_Lex_Unit *unit= select_lex->master_unit();
688 
689  if (not unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
690  return true;
691 
692  select_lex->context.outer_context= unit->first_select()->context.outer_context;
693  }
694 
695  select_lex->master_unit()->global_parameters= select_lex;
696  select_lex->include_global((Select_Lex_Node**)&lex->all_selects_list);
697  lex->current_select= select_lex;
698  /*
699  in subquery is SELECT query and we allow resolution of names in SELECT
700  list
701  */
702  select_lex->context.resolve_in_select_list= true;
703 
704  return false;
705 }
706 
717 void create_select_for_variable(Session *session, const char *var_name)
718 {
719  LEX& lex= session->lex();
720  init_select(&lex);
721  lex.sql_command= SQLCOM_SELECT;
722  lex_string_t tmp;
723  tmp.assign(var_name, strlen(var_name));
724  /*
725  We set the name of Item to @@session.var_name because that then is used
726  as the column name in the output.
727  */
728  if (Item* var= get_system_var(session, OPT_SESSION, tmp, null_lex_string()))
729  {
730  char buff[MAX_SYS_VAR_LENGTH*2+4+8];
731  char *end= buff;
732  end+= snprintf(buff, sizeof(buff), "@@session.%s", var_name);
733  var->set_name(buff, end-buff);
734  session->add_item_to_list(var);
735  }
736 }
737 
738 
747 void parse(Session& session, str_ref buf)
748 {
749  session.lex().start(&session);
750  session.reset_for_next_command();
751  /* Check if the Query is Cached if and return true if yes
752  * TODO the plugin has to make sure that the query is cacheble
753  * by setting the query_safe_cache param to TRUE
754  */
755  if (plugin::QueryCache::isCached(&session) && not plugin::QueryCache::sendCachedResultset(&session))
756  return;
757  Lex_input_stream lip(session, buf);
758  if (parse_sql(&session, &lip))
759  assert(session.is_error());
760  else if (not session.is_error())
761  {
762  DRIZZLE_QUERY_EXEC_START(session.getQueryString()->c_str(), session.thread_id, session.schema()->c_str());
763  // Implement Views here --Brian
764  /* Actually execute the query */
765  try
766  {
767  execute_command(&session);
768  }
769  catch (...)
770  {
771  // Just try to catch any random failures that could have come
772  // during execution.
773  DRIZZLE_ABORT;
774  }
775  DRIZZLE_QUERY_EXEC_DONE(0);
776  }
777  session.lex().unit.cleanup();
778  session.set_proc_info("freeing items");
779  session.end_statement();
780  session.cleanup_after_query();
781  session.times.set_end_timer(session);
782 }
783 
784 
792 bool add_field_to_list(Session *session, str_ref field_name, enum_field_types type,
793  const char *length, const char *decimals,
794  uint32_t type_modifier, column_format_type column_format,
795  Item *default_value, Item *on_update_value, str_ref comment,
796  const char *change, List<String> *interval_list, const charset_info_st* cs)
797 {
798  LEX *lex= &session->lex();
799  statement::AlterTable *statement= (statement::AlterTable *)lex->statement;
800 
801  if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
802  return true;
803 
804  if (type_modifier & PRI_KEY_FLAG)
805  {
806  lex->col_list.push_back(new Key_part_spec(field_name, 0));
807  statement->alter_info.key_list.push_back(new Key(Key::PRIMARY, null_lex_string(), &default_key_create_info, 0, lex->col_list));
808  lex->col_list.clear();
809  }
810  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
811  {
812  lex->col_list.push_back(new Key_part_spec(field_name, 0));
813  statement->alter_info.key_list.push_back(new Key(Key::UNIQUE, null_lex_string(), &default_key_create_info, 0, lex->col_list));
814  lex->col_list.clear();
815  }
816 
817  if (default_value)
818  {
819  /*
820  Default value should be literal => basic constants =>
821  no need fix_fields()
822 
823  We allow only one function as part of default value -
824  NOW() as default for TIMESTAMP type.
825  */
826  if (default_value->type() == Item::FUNC_ITEM &&
827  !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
828  (type == DRIZZLE_TYPE_TIMESTAMP or type == DRIZZLE_TYPE_MICROTIME)))
829  {
830  my_error(ER_INVALID_DEFAULT, MYF(0), field_name.data());
831  return true;
832  }
833  else if (default_value->type() == Item::NULL_ITEM)
834  {
835  default_value= 0;
836  if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG)
837  {
838  my_error(ER_INVALID_DEFAULT, MYF(0), field_name.data());
839  return true;
840  }
841  }
842  else if (type_modifier & AUTO_INCREMENT_FLAG)
843  {
844  my_error(ER_INVALID_DEFAULT, MYF(0), field_name.data());
845  return true;
846  }
847  }
848 
849  if (on_update_value && (type != DRIZZLE_TYPE_TIMESTAMP and type != DRIZZLE_TYPE_MICROTIME))
850  {
851  my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name.data());
852  return true;
853  }
854 
855  CreateField* new_field= new CreateField;
856  if (new_field->init(session, field_name.data(), type, length, decimals, type_modifier, comment, change, interval_list, cs, 0, column_format)
857  || new_field->setDefaultValue(default_value, on_update_value))
858  return true;
859 
860  statement->alter_info.create_list.push_back(new_field);
861  lex->last_field=new_field;
862 
863  return false;
864 }
865 
866 
886 TableList *Select_Lex::add_table_to_list(Session *session,
887  Table_ident *table,
888  lex_string_t *alias,
889  const bitset<NUM_OF_TABLE_OPTIONS>& table_options,
890  thr_lock_type lock_type,
891  List<Index_hint> *index_hints_arg,
892  lex_string_t *option)
893 {
894  TableList *previous_table_ref; /* The table preceding the current one. */
895  LEX *lex= &session->lex();
896 
897  if (!table)
898  return NULL; // End of memory
899  const char* alias_str= alias ? alias->data() : table->table.data();
900  if (not table_options.test(TL_OPTION_ALIAS) && check_table_name(table->table))
901  {
902  my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.data());
903  return NULL;
904  }
905 
906  if (not table->is_derived_table() && table->db.data())
907  {
908  files_charset_info->casedn_str(table->db.str_);
909  if (not schema::check(*session, identifier::Schema(session->catalog().identifier(), table->db)))
910  {
911  my_error(ER_WRONG_DB_NAME, MYF(0), table->db.data());
912  return NULL;
913  }
914  }
915 
916  if (!alias) /* Alias is case sensitive */
917  {
918  if (table->sel)
919  {
920  my_message(ER_DERIVED_MUST_HAVE_ALIAS, ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
921  return NULL;
922  }
923  alias_str= (char*) session->mem.memdup(alias_str, table->table.size() + 1);
924  }
925  TableList *ptr = (TableList *) session->mem.calloc(sizeof(TableList));
926 
927  if (table->db.data())
928  {
929  ptr->setIsFqtn(true);
930  ptr->setSchemaName(table->db.data());
931  }
932  else
933  {
934  str_ref schema = lex->session->copy_db_to();
935  if (schema.empty())
936  return NULL;
937  ptr->setIsFqtn(false);
938  ptr->setSchemaName(schema.data());
939  }
940 
941  ptr->alias= alias_str;
942  ptr->setIsAlias(alias ? true : false);
943  ptr->setTableName(table->table.data());
944  ptr->lock_type= lock_type;
945  ptr->force_index= table_options.test(TL_OPTION_FORCE_INDEX);
946  ptr->ignore_leaves= table_options.test(TL_OPTION_IGNORE_LEAVES);
947  ptr->derived= table->sel;
948  ptr->select_lex= lex->current_select;
949  ptr->index_hints= index_hints_arg;
950  ptr->option= option ? option->data() : NULL;
951  /* check that used name is unique */
952  if (lock_type != TL_IGNORE)
953  {
954  TableList *first_table= (TableList*) table_list.first;
955  for (TableList *tables= first_table; tables; tables= tables->next_local)
956  {
957  if (not table_alias_charset->strcasecmp(alias_str, tables->alias) &&
958  not system_charset_info->strcasecmp(ptr->getSchemaName(), tables->getSchemaName()))
959  {
960  my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str);
961  return NULL;
962  }
963  }
964  }
965  /* Store the table reference preceding the current one. */
966  if (table_list.size() > 0)
967  {
968  /*
969  table_list.next points to the last inserted TableList->next_local'
970  element
971  We don't use the offsetof() macro here to avoid warnings from gcc
972  */
973  previous_table_ref= (TableList*) ((char*) table_list.next - ((char*) &(ptr->next_local) - (char*) ptr));
974  /*
975  Set next_name_resolution_table of the previous table reference to point
976  to the current table reference. In effect the list
977  TableList::next_name_resolution_table coincides with
978  TableList::next_local. Later this may be changed in
979  store_top_level_join_columns() for NATURAL/USING joins.
980  */
981  previous_table_ref->next_name_resolution_table= ptr;
982  }
983 
984  /*
985  Link the current table reference in a local list (list for current select).
986  Notice that as a side effect here we set the next_local field of the
987  previous table reference to 'ptr'. Here we also add one element to the
988  list 'table_list'.
989  */
990  table_list.link_in_list((unsigned char*) ptr, (unsigned char**) &ptr->next_local);
991  ptr->next_name_resolution_table= NULL;
992  /* Link table in global list (all used tables) */
993  lex->add_to_query_tables(ptr);
994  return ptr;
995 }
996 
997 
1017 void Select_Lex::init_nested_join(Session& session)
1018 {
1019  TableList* ptr= (TableList*) session.mem.calloc(ALIGN_SIZE(sizeof(TableList)) + sizeof(NestedJoin));
1020  ptr->setNestedJoin(((NestedJoin*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList)))));
1021  NestedJoin* nested_join= ptr->getNestedJoin();
1022  join_list->push_front(ptr);
1023  ptr->setEmbedding(embedding);
1024  ptr->setJoinList(join_list);
1025  ptr->alias= (char*) "(nested_join)";
1026  embedding= ptr;
1027  join_list= &nested_join->join_list;
1028  join_list->clear();
1029 }
1030 
1031 
1046 TableList *Select_Lex::end_nested_join()
1047 {
1048  assert(embedding);
1049  TableList* ptr= embedding;
1050  join_list= ptr->getJoinList();
1051  embedding= ptr->getEmbedding();
1052  NestedJoin* nested_join= ptr->getNestedJoin();
1053  if (nested_join->join_list.size() == 1)
1054  {
1055  TableList *embedded= &nested_join->join_list.front();
1056  join_list->pop();
1057  embedded->setJoinList(join_list);
1058  embedded->setEmbedding(embedding);
1059  join_list->push_front(embedded);
1060  return embedded;
1061  }
1062  else if (not nested_join->join_list.size())
1063  {
1064  join_list->pop();
1065  return NULL;
1066  }
1067  return ptr;
1068 }
1069 
1070 
1084 TableList *Select_Lex::nest_last_join(Session *session)
1085 {
1086  TableList* ptr= (TableList*) session->mem.calloc(ALIGN_SIZE(sizeof(TableList)) + sizeof(NestedJoin));
1087  ptr->setNestedJoin(((NestedJoin*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList)))));
1088  NestedJoin* nested_join= ptr->getNestedJoin();
1089  ptr->setEmbedding(embedding);
1090  ptr->setJoinList(join_list);
1091  ptr->alias= (char*) "(nest_last_join)";
1092  List<TableList>* embedded_list= &nested_join->join_list;
1093  embedded_list->clear();
1094 
1095  for (uint32_t i=0; i < 2; i++)
1096  {
1097  TableList *table= join_list->pop();
1098  table->setJoinList(embedded_list);
1099  table->setEmbedding(ptr);
1100  embedded_list->push_back(table);
1101  if (table->natural_join)
1102  {
1103  ptr->is_natural_join= true;
1104  /*
1105  If this is a JOIN ... USING, move the list of joined fields to the
1106  table reference that describes the join.
1107  */
1108  if (prev_join_using)
1109  ptr->join_using_fields= prev_join_using;
1110  }
1111  }
1112  join_list->push_front(ptr);
1113  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
1114  return ptr;
1115 }
1116 
1117 
1132 void Select_Lex::add_joined_table(TableList *table)
1133 {
1134  join_list->push_front(table);
1135  table->setJoinList(join_list);
1136  table->setEmbedding(embedding);
1137 }
1138 
1139 
1171 TableList *Select_Lex::convert_right_join()
1172 {
1173  TableList *tab2= join_list->pop();
1174  TableList *tab1= join_list->pop();
1175 
1176  join_list->push_front(tab2);
1177  join_list->push_front(tab1);
1178  tab1->outer_join|= JOIN_TYPE_RIGHT;
1179 
1180  return tab1;
1181 }
1182 
1194 void Select_Lex::set_lock_for_tables(thr_lock_type lock_type)
1195 {
1196  for (TableList *tables= (TableList*) table_list.first; tables; tables= tables->next_local)
1197  {
1198  tables->lock_type= lock_type;
1199  }
1200 }
1201 
1202 
1229 bool Select_Lex_Unit::add_fake_select_lex(Session *session_arg)
1230 {
1231  Select_Lex *first_sl= first_select();
1232  assert(!fake_select_lex);
1233 
1234  fake_select_lex= new (session_arg->mem_root) Select_Lex();
1235  fake_select_lex->include_standalone(this, (Select_Lex_Node**)&fake_select_lex);
1236  fake_select_lex->select_number= INT_MAX;
1237  fake_select_lex->parent_lex= &session_arg->lex(); /* Used in init_query. */
1238  fake_select_lex->make_empty_select();
1239  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
1240  fake_select_lex->select_limit= 0;
1241 
1242  fake_select_lex->context.outer_context=first_sl->context.outer_context;
1243  /* allow item list resolving in fake select for ORDER BY */
1244  fake_select_lex->context.resolve_in_select_list= true;
1245  fake_select_lex->context.select_lex= fake_select_lex;
1246 
1247  if (!is_union())
1248  {
1249  /*
1250  This works only for
1251  (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
1252  (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
1253  just before the parser starts processing order_list
1254  */
1255  global_parameters= fake_select_lex;
1256  fake_select_lex->no_table_names_allowed= 1;
1257  session_arg->lex().current_select= fake_select_lex;
1258  }
1259  session_arg->lex().pop_context();
1260  return 0;
1261 }
1262 
1263 
1283 void push_new_name_resolution_context(Session& session, TableList& left_op, TableList& right_op)
1284 {
1285  Name_resolution_context *on_context= new (session.mem_root) Name_resolution_context;
1286  on_context->init();
1287  on_context->first_name_resolution_table= left_op.first_leaf_for_name_resolution();
1288  on_context->last_name_resolution_table= right_op.last_leaf_for_name_resolution();
1289  session.lex().push_context(on_context);
1290 }
1291 
1292 
1307 void add_join_on(TableList *b, Item *expr)
1308 {
1309  if (expr)
1310  {
1311  if (!b->on_expr)
1312  b->on_expr= expr;
1313  else
1314  {
1315  /*
1316  If called from the parser, this happens if you have both a
1317  right and left join. If called later, it happens if we add more
1318  than one condition to the ON clause.
1319  */
1320  b->on_expr= new Item_cond_and(b->on_expr,expr);
1321  }
1322  b->on_expr->top_level_item();
1323  }
1324 }
1325 
1326 
1361  Select_Lex *lex)
1362 {
1363  b->natural_join= a;
1364  lex->prev_join_using= using_fields;
1365 }
1366 
1367 
1378 {
1379  if (session->lex().current_select != &session->lex().select_lex)
1380  {
1381  char command[80];
1382  Lex_input_stream *lip= session->m_lip;
1383  strncpy(command, lip->yylval->symbol.str,
1384  min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1)));
1385  command[min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1))]=0;
1386  my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
1387  return 1;
1388  }
1389  return 0;
1390 }
1391 
1392 
1405  chooser_compare_func_creator cmp,
1406  bool all,
1407  Select_Lex *select_lex)
1408 {
1409  if ((cmp == &comp_eq_creator) && !all) // = ANY <=> IN
1410  return new Item_in_subselect(left_expr, select_lex);
1411 
1412  if ((cmp == &comp_ne_creator) && all) // <> ALL <=> NOT IN
1413  return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
1414 
1416  new Item_allany_subselect(left_expr, cmp, select_lex, all);
1417  if (all)
1418  return it->upper_item= new Item_func_not_all(it); /* ALL */
1419 
1420  return it->upper_item= new Item_func_nop_all(it); /* ANY/SOME */
1421 }
1422 
1423 
1437 {
1438  const char *msg= 0;
1439  Select_Lex *select_lex= &session->lex().select_lex;
1440 
1441  if (session->lex().select_lex.item_list.size() != session->lex().value_list.size())
1442  {
1443  my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1444  return true;
1445  }
1446 
1447  if (session->lex().select_lex.table_list.size() > 1)
1448  {
1449  if (select_lex->order_list.size())
1450  msg= "ORDER BY";
1451  else if (select_lex->select_limit)
1452  msg= "LIMIT";
1453  if (msg)
1454  {
1455  my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
1456  return true;
1457  }
1458  }
1459  return false;
1460 }
1461 
1462 
1476 {
1477  /*
1478  Check that we have modify privileges for the first table and
1479  select privileges for the rest
1480  */
1481  if (session->lex().update_list.size() != session->lex().value_list.size())
1482  {
1483  my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1484  return true;
1485  }
1486  return false;
1487 }
1488 
1489 
1501 {
1502  Item *negated;
1503  if (expr->type() == Item::FUNC_ITEM &&
1504  ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
1505  {
1506  /* it is NOT(NOT( ... )) */
1507  Item *arg= ((Item_func *) expr)->arguments()[0];
1508  enum_parsing_place place= session->lex().current_select->parsing_place;
1509  if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
1510  return arg;
1511  /*
1512  if it is not boolean function then we have to emulate value of
1513  not(not(a)), it will be a != 0
1514  */
1515  return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
1516  }
1517 
1518  if ((negated= expr->neg_transformer(session)) != 0)
1519  return negated;
1520  return new Item_func_not(expr);
1521 }
1522 
1523 
1524 /*
1525  Check that char length of a string does not exceed some limit.
1526 
1527  SYNOPSIS
1528  check_string_char_length()
1529  str string to be checked
1530  err_msg error message to be displayed if the string is too long
1531  max_char_length max length in symbols
1532  cs string charset
1533 
1534  RETURN
1535  false the passed string is not longer than max_char_length
1536  true the passed string is longer than max_char_length
1537 */
1538 
1539 
1540 bool check_string_char_length(str_ref str, const char *err_msg,
1541  uint32_t max_char_length, const charset_info_st * const cs,
1542  bool no_error)
1543 {
1544  int well_formed_error;
1545  uint32_t res= cs->cset->well_formed_len(*cs, str, max_char_length, &well_formed_error);
1546 
1547  if (!well_formed_error && str.size() == res)
1548  return false;
1549 
1550  if (not no_error)
1551  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str.data(), err_msg, max_char_length);
1552  return true;
1553 }
1554 
1555 
1556 bool check_identifier_name(str_ref str, error_t err_code)
1557 {
1558  uint32_t max_char_length= NAME_CHAR_LEN;
1559  /*
1560  We don't support non-BMP characters in identifiers at the moment,
1561  so they should be prohibited until such support is done.
1562  This is why we use the 3-byte utf8 to check well-formedness here.
1563  */
1564  const charset_info_st * const cs= &my_charset_utf8mb4_general_ci;
1565 
1566  int well_formed_error;
1567  uint32_t res= cs->cset->well_formed_len(*cs, str, max_char_length, &well_formed_error);
1568 
1569  if (well_formed_error)
1570  {
1571  my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str.data());
1572  return true;
1573  }
1574 
1575  if (str.size() == res)
1576  return false;
1577 
1578  switch (err_code)
1579  {
1580  case EE_OK:
1581  break;
1582  case ER_WRONG_STRING_LENGTH:
1583  my_error(err_code, MYF(0), str.data(), "", max_char_length);
1584  break;
1585  case ER_TOO_LONG_IDENT:
1586  my_error(err_code, MYF(0), str.data());
1587  break;
1588  default:
1589  assert(false);
1590  }
1591 
1592  return true;
1593 }
1594 
1595 
1608 static bool parse_sql(Session *session, Lex_input_stream *lip)
1609 {
1610  assert(session->m_lip == NULL);
1611 
1612  DRIZZLE_QUERY_PARSE_START(session->getQueryString()->c_str());
1613 
1614  /* Set Lex_input_stream. */
1615 
1616  session->m_lip= lip;
1617 
1618  /* Parse the query. */
1619 
1620  bool parse_status= base_sql_parse(session) != 0;
1621 
1622  /* Check that if DRIZZLEparse() failed, session->is_error() is set. */
1623 
1624  assert(!parse_status || session->is_error());
1625 
1626  /* Reset Lex_input_stream. */
1627 
1628  session->m_lip= NULL;
1629 
1630  DRIZZLE_QUERY_PARSE_DONE(parse_status || session->is_fatal_error);
1631 
1632  /* That's it. */
1633 
1634  return parse_status || session->is_fatal_error;
1635 }
1636 
1641 } /* namespace drizzled */