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