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