1
/* Copyright (C) 2000-2003 MySQL AB
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
20
#include <drizzled/my_hash.h>
21
#include <drizzled/error.h>
22
#include <drizzled/nested_join.h>
23
#include <drizzled/query_id.h>
24
#include <drizzled/sql_parse.h>
25
#include <drizzled/data_home.h>
26
#include <drizzled/sql_base.h>
27
#include <drizzled/show.h>
28
#include <drizzled/db.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/sql_load.h>
35
#include <drizzled/lock.h>
36
#include <drizzled/select_send.h>
37
#include <drizzled/plugin/client.h>
38
#include <drizzled/statement.h>
39
#include <drizzled/statement/alter_table.h>
40
#include "drizzled/probes.h"
41
#include "drizzled/session_list.h"
42
#include "drizzled/global_charset_info.h"
43
#include "drizzled/transaction_services.h"
45
#include "drizzled/plugin/logging.h"
46
#include "drizzled/plugin/query_rewrite.h"
47
#include "drizzled/plugin/authorization.h"
48
#include "drizzled/optimizer/explain_plan.h"
49
#include "drizzled/pthread_globals.h"
56
#include "drizzled/internal/my_sys.h"
60
extern int DRIZZLEparse(void *session); // from sql_yacc.cc
66
bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize);
67
static bool parse_sql(Session *session, Lex_input_stream *lip);
68
void mysql_parse(Session *session, const char *inBuf, uint32_t length);
71
@defgroup Runtime_Environment Runtime Environment
75
extern size_t my_thread_stack_size;
76
extern const CHARSET_INFO *character_set_filesystem;
78
const LEX_STRING command_name[COM_END+1]={
79
{ C_STRING_WITH_LEN("Sleep") },
80
{ C_STRING_WITH_LEN("Quit") },
81
{ C_STRING_WITH_LEN("Init DB") },
82
{ C_STRING_WITH_LEN("Query") },
83
{ C_STRING_WITH_LEN("Shutdown") },
84
{ C_STRING_WITH_LEN("Connect") },
85
{ C_STRING_WITH_LEN("Ping") },
86
{ C_STRING_WITH_LEN("Error") } // Last command number
89
const char *xa_state_names[]={
90
"NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
94
Mark all commands that somehow changes a table.
96
This is used to check number of updates / hour.
98
sql_command is actually set to SQLCOM_END sometimes
99
so we need the +1 to include it in the array.
101
See COMMAND_FLAG_xxx for different type of commands
102
2 - query that returns meaningful ROW_COUNT() -
103
a number of modified rows
105
bitset<CF_BIT_SIZE> sql_command_flags[SQLCOM_END+1];
107
void init_update_queries(void)
111
for (x= 0; x <= SQLCOM_END; x++)
112
sql_command_flags[x].reset();
114
sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA;
115
sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA;
116
sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
117
sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
118
sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA;
119
sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA;
120
sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA;
121
sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA;
122
sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA;
123
sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA;
125
sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
126
sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
127
sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
128
sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
129
sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
130
sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
132
sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
133
sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
134
sql_command_flags[SQLCOM_SHOW_CREATE_DB]= CF_STATUS_COMMAND;
135
sql_command_flags[SQLCOM_SHOW_CREATE]= CF_STATUS_COMMAND;
138
The following admin table operations are allowed
141
sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND;
145
Perform one connection-level (COM_XXXX) command.
147
@param command type of command to perform
148
@param session connection handle
149
@param packet data for the command, packet is always null-terminated
150
@param packet_length length of packet + 1 (to show that data is
151
null-terminated) except for COM_SLEEP, where it
155
set session->lex->sql_command to SQLCOM_END here.
157
The following has to be changed to an 8 byte integer
162
1 request of thread shutdown, i. e. if command is
163
COM_QUIT/COM_SHUTDOWN
165
bool dispatch_command(enum enum_server_command command, Session *session,
166
char* packet, uint32_t packet_length)
169
Query_id &query_id= Query_id::get_query_id();
171
DRIZZLE_COMMAND_START(session->thread_id,
174
session->command= command;
175
session->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
177
session->setQueryId(query_id.value());
180
/* Ignore these statements. */
183
/* Increase id and count all other statements. */
185
statistic_increment(session->status_var.questions, &LOCK_status);
189
/* TODO: set session->lex->sql_command to SQLCOM_END here */
191
plugin::Logging::preDo(session);
193
session->server_status&=
194
~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
198
status_var_increment(session->status_var.com_stat[SQLCOM_CHANGE_DB]);
199
string tmp(packet, packet_length);
201
if (not mysql_change_db(session, tmp))
209
if (! session->readAndStoreQuery(packet, packet_length))
210
break; // fatal error is set
211
DRIZZLE_QUERY_START(session->query.c_str(),
213
const_cast<const char *>(session->db.empty() ? "" : session->db.c_str()));
215
plugin::QueryRewriter::rewriteQuery(session->db, session->query);
216
mysql_parse(session, session->query.c_str(), session->query.length());
221
/* We don't calculate statistics for this command */
222
session->main_da.disable_status(); // Don't send anything back
223
error=true; // End server
227
status_var_increment(session->status_var.com_other);
229
session->close_thread_tables(); // Free before kill
235
status_var_increment(session->status_var.com_other);
236
session->my_ok(); // Tell client we are alive
239
case COM_CONNECT: // Impossible here
242
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
246
/* If commit fails, we should be able to reset the OK status. */
247
session->main_da.can_overwrite_status= true;
248
TransactionServices &transaction_services= TransactionServices::singleton();
249
transaction_services.ha_autocommit_or_rollback(session, session->is_error());
250
session->main_da.can_overwrite_status= false;
252
session->transaction.stmt.reset();
255
/* report error issued during command execution */
256
if (session->killed_errno())
258
if (! session->main_da.is_set())
259
session->send_kill_message();
261
if (session->killed == Session::KILL_QUERY || session->killed == Session::KILL_BAD_DATA)
263
session->killed= Session::NOT_KILLED;
264
session->mysys_var->abort= 0;
267
/* Can not be true, but do not take chances in production. */
268
assert(! session->main_da.is_sent);
270
switch (session->main_da.status())
272
case Diagnostics_area::DA_ERROR:
273
/* The query failed, send error to log and abort bootstrap. */
274
session->client->sendError(session->main_da.sql_errno(),
275
session->main_da.message());
278
case Diagnostics_area::DA_EOF:
279
session->client->sendEOF();
282
case Diagnostics_area::DA_OK:
283
session->client->sendOK();
286
case Diagnostics_area::DA_DISABLED:
289
case Diagnostics_area::DA_EMPTY:
291
session->client->sendOK();
295
session->main_da.is_sent= true;
297
session->set_proc_info("closing tables");
299
session->close_thread_tables();
301
plugin::Logging::postDo(session);
303
/* Store temp state for processlist */
304
session->set_proc_info("cleaning up");
305
session->command= COM_SLEEP;
306
memset(session->process_list_info, 0, PROCESS_LIST_WIDTH);
307
session->query.clear();
309
session->set_proc_info(NULL);
310
free_root(session->mem_root,MYF(memory::KEEP_PREALLOC));
312
if (DRIZZLE_QUERY_DONE_ENABLED() || DRIZZLE_COMMAND_DONE_ENABLED())
314
if (command == COM_QUERY)
316
DRIZZLE_QUERY_DONE(session->is_error());
318
DRIZZLE_COMMAND_DONE(session->is_error());
326
Create a TableList object for an INFORMATION_SCHEMA table.
328
This function is used in the parser to convert a SHOW or DESCRIBE
329
table_name command to a SELECT from INFORMATION_SCHEMA.
330
It prepares a Select_Lex and a TableList object to represent the
331
given command as a SELECT parse tree.
333
@param session thread handle
334
@param lex current lex
335
@param table_ident table alias if it's used
336
@param schema_table_name the name of the INFORMATION_SCHEMA table to be
340
Due to the way this function works with memory and LEX it cannot
341
be used outside the parser (parse tree transformations outside
342
the parser break PS and SP).
347
1 out of memory or SHOW commands are not allowed
348
in this version of the server.
350
static bool _schema_select(Session *session, Select_Lex *sel,
351
const string& schema_table_name)
353
LEX_STRING db, table;
355
We have to make non const db_name & table_name
356
because of lower_case_table_names
358
session->make_lex_string(&db, "data_dictionary", sizeof("data_dictionary"), false);
359
session->make_lex_string(&table, schema_table_name, false);
361
if (! sel->add_table_to_list(session, new Table_ident(db, table),
369
int prepare_new_schema_table(Session *session, LEX *lex,
370
const string& schema_table_name)
372
Select_Lex *schema_select_lex= NULL;
374
Select_Lex *select_lex= lex->current_select;
376
if (_schema_select(session, select_lex, schema_table_name))
380
TableList *table_list= (TableList*) select_lex->table_list.first;
382
table_list->schema_select_lex= schema_select_lex;
388
Execute command saved in session and lex->sql_command.
390
Before every operation that can request a write lock for a table
391
wait if a global read lock exists. However do not wait if this
392
thread has locked tables already. No new locks can be requested
393
until the other locks are released. The thread that requests the
394
global read lock waits for write locked tables to become unlocked.
396
Note that wait_if_global_read_lock() sets a protection against a new
397
global read lock when it succeeds. This needs to be released by
398
start_waiting_global_read_lock() after the operation.
400
@param session Thread handle
403
- Invalidate the table in the query cache if something changed
404
after unlocking when changes become visible.
405
TODO: this is workaround. right way will be move invalidating in
406
the unlock procedure.
407
- TODO: use check_change_password()
408
- JOIN is not supported yet. TODO
409
- SUSPEND and FOR MIGRATE are not supported yet. TODO
418
mysql_execute_command(Session *session)
421
LEX *lex= session->lex;
422
/* first Select_Lex (have special meaning for many of non-SELECTcommands) */
423
Select_Lex *select_lex= &lex->select_lex;
424
/* list of all tables in query */
425
TableList *all_tables;
426
/* A peek into the query string */
427
size_t proc_info_len= session->query.length() > PROCESS_LIST_WIDTH ?
428
PROCESS_LIST_WIDTH : session->query.length();
430
memcpy(session->process_list_info, session->query.c_str(), proc_info_len);
431
session->process_list_info[proc_info_len]= '\0';
434
In many cases first table of main Select_Lex have special meaning =>
435
check that it is first table in global list and relink it first in
436
queries_tables list if it is necessary (we need such relinking only
437
for queries with subqueries in select list, in this case tables of
438
subqueries will go to global list first)
440
all_tables will differ from first_table only if most upper Select_Lex
441
do not contain tables.
443
Because of above in place where should be at least one table in most
444
outer Select_Lex we have following check:
445
assert(first_table == all_tables);
446
assert(first_table == all_tables && first_table != 0);
448
lex->first_lists_tables_same();
449
/* should be assigned after making first tables same */
450
all_tables= lex->query_tables;
451
/* set context for commands which do not use setup_tables */
453
context.resolve_in_table_list_only((TableList*)select_lex->
457
Reset warning count for each query that uses tables
458
A better approach would be to reset this for any commands
459
that is not a SHOW command or a select that only access local
460
variables, but for now this is probably good enough.
461
Don't reset warnings when executing a stored routine.
463
if (all_tables || ! lex->is_single_level_stmt())
465
drizzle_reset_errors(session, 0);
468
status_var_increment(session->status_var.com_stat[lex->sql_command]);
470
assert(session->transaction.stmt.hasModifiedNonTransData() == false);
472
/* now we are ready to execute the statement */
473
res= lex->statement->execute();
475
session->set_proc_info("query end");
478
The return value for ROW_COUNT() is "implementation dependent" if the
479
statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
480
wants. We also keep the last value in case of SQLCOM_CALL or
483
if (! (sql_command_flags[lex->sql_command].test(CF_BIT_HAS_ROW_COUNT)))
485
session->row_count_func= -1;
488
return (res || session->is_error());
491
bool execute_sqlcom_select(Session *session, TableList *all_tables)
493
LEX *lex= session->lex;
494
select_result *result=lex->result;
496
/* assign global limit variable if limit is not given */
498
Select_Lex *param= lex->unit.global_parameters;
499
if (!param->explicit_limit)
501
new Item_int((uint64_t) session->variables.select_limit);
503
if (!(res= session->openTablesLock(all_tables)))
508
We always use select_send for EXPLAIN, even if it's an EXPLAIN
509
for SELECT ... INTO OUTFILE: a user application should be able
510
to prepend EXPLAIN to any query and receive output for it,
511
even if the query itself redirects the output.
513
if (!(result= new select_send()))
515
session->send_explain_fields(result);
516
optimizer::ExplainPlan planner;
517
res= planner.explainUnion(session, &session->lex->unit, result);
518
if (lex->describe & DESCRIBE_EXTENDED)
521
String str(buff,(uint32_t) sizeof(buff), system_charset_info);
523
session->lex->unit.print(&str, QT_ORDINARY);
525
push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
536
if (!result && !(result= new select_send()))
538
res= handle_select(session, lex, result, 0);
539
if (result != lex->result)
547
#define MY_YACC_INIT 1000 // Start with big alloc
548
#define MY_YACC_MAX 32000 // Because of 'short'
550
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
552
LEX *lex= current_session->lex;
554
if ((uint32_t) *yystacksize >= MY_YACC_MAX)
557
old_info= *yystacksize;
558
*yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
559
unsigned char *tmpptr= NULL;
560
if (!(tmpptr= (unsigned char *)realloc(lex->yacc_yyvs,
561
*yystacksize* sizeof(**yyvs))))
563
lex->yacc_yyvs= tmpptr;
565
if (!(tmpptr= (unsigned char*)realloc(lex->yacc_yyss,
566
*yystacksize* sizeof(**yyss))))
568
lex->yacc_yyss= tmpptr;
570
{ // Copy old info from stack
571
memcpy(lex->yacc_yyss, *yyss, old_info*sizeof(**yyss));
572
memcpy(lex->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
574
*yyss=(short*) lex->yacc_yyss;
575
*yyvs=(YYSTYPE*) lex->yacc_yyvs;
581
mysql_init_select(LEX *lex)
583
Select_Lex *select_lex= lex->current_select;
584
select_lex->init_select();
586
if (select_lex == &lex->select_lex)
588
assert(lex->result == 0);
595
mysql_new_select(LEX *lex, bool move_down)
597
Select_Lex *select_lex;
598
Session *session= lex->session;
600
if (!(select_lex= new (session->mem_root) Select_Lex()))
602
select_lex->select_number= ++session->select_number;
603
select_lex->parent_lex= lex; /* Used in init_query. */
604
select_lex->init_query();
605
select_lex->init_select();
607
if (lex->nest_level > (int) MAX_SELECT_NESTING)
609
my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
612
select_lex->nest_level= lex->nest_level;
615
Select_Lex_Unit *unit;
616
/* first select_lex of subselect or derived table */
617
if (!(unit= new (session->mem_root) Select_Lex_Unit()))
622
unit->session= session;
623
unit->include_down(lex->current_select);
626
unit->return_to= lex->current_select;
627
select_lex->include_down(unit);
629
By default we assume that it is usual subselect and we have outer name
630
resolution context, if no we will assign it to 0 later
632
select_lex->context.outer_context= &select_lex->outer_select()->context;
636
if (lex->current_select->order_list.first && !lex->current_select->braces)
638
my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
641
select_lex->include_neighbour(lex->current_select);
642
Select_Lex_Unit *unit= select_lex->master_unit();
643
if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
645
select_lex->context.outer_context=
646
unit->first_select()->context.outer_context;
649
select_lex->master_unit()->global_parameters= select_lex;
650
select_lex->include_global((Select_Lex_Node**)&lex->all_selects_list);
651
lex->current_select= select_lex;
653
in subquery is SELECT query and we allow resolution of names in SELECT
656
select_lex->context.resolve_in_select_list= true;
661
Create a select to return the same output as 'SELECT @@var_name'.
663
Used for SHOW COUNT(*) [ WARNINGS | ERROR].
665
This will crash with a core dump if the variable doesn't exists.
667
@param var_name Variable name
670
void create_select_for_variable(const char *var_name)
674
LEX_STRING tmp, null_lex_string;
676
char buff[MAX_SYS_VAR_LENGTH*2+4+8];
679
session= current_session;
681
mysql_init_select(lex);
682
lex->sql_command= SQLCOM_SELECT;
683
tmp.str= (char*) var_name;
684
tmp.length=strlen(var_name);
685
memset(&null_lex_string.str, 0, sizeof(null_lex_string));
687
We set the name of Item to @@session.var_name because that then is used
688
as the column name in the output.
690
if ((var= get_system_var(session, OPT_SESSION, tmp, null_lex_string)))
692
end+= sprintf(buff, "@@session.%s", var_name);
693
var->set_name(buff, end-buff, system_charset_info);
694
session->add_item_to_list(var);
703
@param session Current thread
704
@param inBuf Begining of the query text
705
@param length Length of the query text
708
void mysql_parse(Session *session, const char *inBuf, uint32_t length)
711
session->reset_for_next_command();
713
LEX *lex= session->lex;
715
Lex_input_stream lip(session, inBuf, length);
717
bool err= parse_sql(session, &lip);
722
if (! session->is_error())
724
DRIZZLE_QUERY_EXEC_START(session->query.c_str(),
726
const_cast<const char *>(session->db.empty() ? "" : session->db.c_str()));
727
/* Actually execute the query */
728
mysql_execute_command(session);
729
DRIZZLE_QUERY_EXEC_DONE(0);
735
assert(session->is_error());
739
session->set_proc_info("freeing items");
740
session->end_statement();
741
session->cleanup_after_query();
749
Store field definition for create.
755
bool add_field_to_list(Session *session, LEX_STRING *field_name, enum_field_types type,
756
char *length, char *decimals,
757
uint32_t type_modifier,
758
enum column_format_type column_format,
759
Item *default_value, Item *on_update_value,
762
List<String> *interval_list, const CHARSET_INFO * const cs)
764
register CreateField *new_field;
765
LEX *lex= session->lex;
766
statement::AlterTable *statement= (statement::AlterTable *)lex->statement;
768
if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
771
if (type_modifier & PRI_KEY_FLAG)
774
lex->col_list.push_back(new Key_part_spec(*field_name, 0));
775
key= new Key(Key::PRIMARY, null_lex_str,
776
&default_key_create_info,
778
statement->alter_info.key_list.push_back(key);
779
lex->col_list.empty();
781
if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
784
lex->col_list.push_back(new Key_part_spec(*field_name, 0));
785
key= new Key(Key::UNIQUE, null_lex_str,
786
&default_key_create_info, 0,
788
statement->alter_info.key_list.push_back(key);
789
lex->col_list.empty();
795
Default value should be literal => basic constants =>
798
We allow only one function as part of default value -
799
NOW() as default for TIMESTAMP type.
801
if (default_value->type() == Item::FUNC_ITEM &&
802
!(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
803
type == DRIZZLE_TYPE_TIMESTAMP))
805
my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
808
else if (default_value->type() == Item::NULL_ITEM)
811
if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
814
my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
818
else if (type_modifier & AUTO_INCREMENT_FLAG)
820
my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
825
if (on_update_value && type != DRIZZLE_TYPE_TIMESTAMP)
827
my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
831
if (!(new_field= new CreateField()) ||
832
new_field->init(session, field_name->str, type, length, decimals, type_modifier,
833
default_value, on_update_value, comment, change,
834
interval_list, cs, 0, column_format))
837
statement->alter_info.create_list.push_back(new_field);
838
lex->last_field=new_field;
844
/** Store position for column in ALTER TABLE .. ADD column. */
846
void store_position_for_column(const char *name)
848
current_session->lex->last_field->after=const_cast<char*> (name);
852
Add a table to list of used tables.
854
@param table Table to add
855
@param alias alias for table (or null if no alias)
856
@param table_options A set of the following bits:
857
- TL_OPTION_UPDATING : Table will be updated
858
- TL_OPTION_FORCE_INDEX : Force usage of index
859
- TL_OPTION_ALIAS : an alias in multi table DELETE
860
@param lock_type How table should be locked
861
@param use_index List of indexed used in USE INDEX
862
@param ignore_index List of indexed used in IGNORE INDEX
867
\# Pointer to TableList element added to the total table list
870
TableList *Select_Lex::add_table_to_list(Session *session,
873
uint32_t table_options,
874
thr_lock_type lock_type,
875
List<Index_hint> *index_hints_arg,
878
register TableList *ptr;
879
TableList *previous_table_ref; /* The table preceding the current one. */
881
LEX *lex= session->lex;
884
return NULL; // End of memory
885
alias_str= alias ? alias->str : table->table.str;
886
if (!test(table_options & TL_OPTION_ALIAS) &&
887
check_table_name(table->table.str, table->table.length))
889
my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
893
if (table->is_derived_table() == false && table->db.str &&
894
check_db_name(&table->db))
896
my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
900
if (!alias) /* Alias is case sensitive */
904
my_message(ER_DERIVED_MUST_HAVE_ALIAS,
905
ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
908
if (!(alias_str= (char*) session->memdup(alias_str,table->table.length+1)))
911
if (!(ptr = (TableList *) session->calloc(sizeof(TableList))))
916
ptr->db= table->db.str;
917
ptr->db_length= table->db.length;
919
else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
924
ptr->alias= alias_str;
925
ptr->is_alias= alias ? true : false;
926
if (table->table.length)
927
table->table.length= my_casedn_str(files_charset_info, table->table.str);
928
ptr->table_name=table->table.str;
929
ptr->table_name_length=table->table.length;
930
ptr->lock_type= lock_type;
931
ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
932
ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
933
ptr->derived= table->sel;
934
ptr->select_lex= lex->current_select;
935
ptr->index_hints= index_hints_arg;
936
ptr->option= option ? option->str : 0;
937
/* check that used name is unique */
938
if (lock_type != TL_IGNORE)
940
TableList *first_table= (TableList*) table_list.first;
941
for (TableList *tables= first_table ;
943
tables=tables->next_local)
945
if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
946
!strcmp(ptr->db, tables->db))
948
my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str);
953
/* Store the table reference preceding the current one. */
954
if (table_list.elements > 0)
957
table_list.next points to the last inserted TableList->next_local'
959
We don't use the offsetof() macro here to avoid warnings from gcc
961
previous_table_ref= (TableList*) ((char*) table_list.next -
962
((char*) &(ptr->next_local) -
965
Set next_name_resolution_table of the previous table reference to point
966
to the current table reference. In effect the list
967
TableList::next_name_resolution_table coincides with
968
TableList::next_local. Later this may be changed in
969
store_top_level_join_columns() for NATURAL/USING joins.
971
previous_table_ref->next_name_resolution_table= ptr;
975
Link the current table reference in a local list (list for current select).
976
Notice that as a side effect here we set the next_local field of the
977
previous table reference to 'ptr'. Here we also add one element to the
980
table_list.link_in_list((unsigned char*) ptr, (unsigned char**) &ptr->next_local);
981
ptr->next_name_resolution_table= NULL;
982
/* Link table in global list (all used tables) */
983
lex->add_to_query_tables(ptr);
989
Initialize a new table list for a nested join.
991
The function initializes a structure of the TableList type
992
for a nested join. It sets up its nested join list as empty.
993
The created structure is added to the front of the current
994
join list in the Select_Lex object. Then the function
995
changes the current nest level for joins to refer to the newly
996
created empty list after having saved the info on the old level
997
in the initialized structure.
999
@param session current thread
1007
bool Select_Lex::init_nested_join(Session *session)
1010
nested_join_st *nested_join;
1012
if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
1013
sizeof(nested_join_st))))
1015
nested_join= ptr->nested_join=
1016
((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
1018
join_list->push_front(ptr);
1019
ptr->embedding= embedding;
1020
ptr->join_list= join_list;
1021
ptr->alias= (char*) "(nested_join)";
1023
join_list= &nested_join->join_list;
1030
End a nested join table list.
1032
The function returns to the previous join nest level.
1033
If the current level contains only one member, the function
1034
moves it one level up, eliminating the nest.
1036
@param session current thread
1039
- Pointer to TableList element added to the total table list, if success
1043
TableList *Select_Lex::end_nested_join(Session *)
1046
nested_join_st *nested_join;
1050
join_list= ptr->join_list;
1051
embedding= ptr->embedding;
1052
nested_join= ptr->nested_join;
1053
if (nested_join->join_list.elements == 1)
1055
TableList *embedded= nested_join->join_list.head();
1057
embedded->join_list= join_list;
1058
embedded->embedding= embedding;
1059
join_list->push_front(embedded);
1062
else if (nested_join->join_list.elements == 0)
1065
ptr= NULL; // return value
1072
Nest last join operation.
1074
The function nest last join operation as if it was enclosed in braces.
1076
@param session current thread
1081
\# Pointer to TableList element created for the new nested join
1084
TableList *Select_Lex::nest_last_join(Session *session)
1087
nested_join_st *nested_join;
1088
List<TableList> *embedded_list;
1090
if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
1091
sizeof(nested_join_st))))
1093
nested_join= ptr->nested_join=
1094
((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
1096
ptr->embedding= embedding;
1097
ptr->join_list= join_list;
1098
ptr->alias= (char*) "(nest_last_join)";
1099
embedded_list= &nested_join->join_list;
1100
embedded_list->empty();
1102
for (uint32_t i=0; i < 2; i++)
1104
TableList *table= join_list->pop();
1105
table->join_list= embedded_list;
1106
table->embedding= ptr;
1107
embedded_list->push_back(table);
1108
if (table->natural_join)
1110
ptr->is_natural_join= true;
1112
If this is a JOIN ... USING, move the list of joined fields to the
1113
table reference that describes the join.
1115
if (prev_join_using)
1116
ptr->join_using_fields= prev_join_using;
1119
join_list->push_front(ptr);
1120
nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
1126
Add a table to the current join list.
1128
The function puts a table in front of the current join list
1129
of Select_Lex object.
1130
Thus, joined tables are put into this list in the reverse order
1131
(the most outer join operation follows first).
1133
@param table the table to add
1139
void Select_Lex::add_joined_table(TableList *table)
1141
join_list->push_front(table);
1142
table->join_list= join_list;
1143
table->embedding= embedding;
1148
Convert a right join into equivalent left join.
1150
The function takes the current join list t[0],t[1] ... and
1151
effectively converts it into the list t[1],t[0] ...
1152
Although the outer_join flag for the new nested table contains
1153
JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
1158
SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
1159
SELECT * FROM t2 LEFT JOIN t1 ON on_expr
1161
SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
1162
SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr
1164
SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
1165
SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr
1167
SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3 ON on_expr2 =>
1168
SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
1171
@param session current thread
1174
- Pointer to the table representing the inner table, if success
1178
TableList *Select_Lex::convert_right_join()
1180
TableList *tab2= join_list->pop();
1181
TableList *tab1= join_list->pop();
1183
join_list->push_front(tab2);
1184
join_list->push_front(tab1);
1185
tab1->outer_join|= JOIN_TYPE_RIGHT;
1191
Set lock for all tables in current select level.
1193
@param lock_type Lock to set for tables
1196
If lock is a write lock, then tables->updating is set 1
1197
This is to get tables_ok to know that the table is updated by the
1201
void Select_Lex::set_lock_for_tables(thr_lock_type lock_type)
1203
for (TableList *tables= (TableList*) table_list.first;
1205
tables= tables->next_local)
1207
tables->lock_type= lock_type;
1213
Create a fake Select_Lex for a unit.
1215
The method create a fake Select_Lex object for a unit.
1216
This object is created for any union construct containing a union
1217
operation and also for any single select union construct of the form
1219
(SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ...
1223
(SELECT ... ORDER BY LIMIT n) ORDER BY ...
1226
@param session_arg thread handle
1229
The object is used to retrieve rows from the temporary table
1230
where the result on the union is obtained.
1233
1 on failure to create the object
1238
bool Select_Lex_Unit::add_fake_select_lex(Session *session_arg)
1240
Select_Lex *first_sl= first_select();
1241
assert(!fake_select_lex);
1243
if (!(fake_select_lex= new (session_arg->mem_root) Select_Lex()))
1245
fake_select_lex->include_standalone(this,
1246
(Select_Lex_Node**)&fake_select_lex);
1247
fake_select_lex->select_number= INT_MAX;
1248
fake_select_lex->parent_lex= session_arg->lex; /* Used in init_query. */
1249
fake_select_lex->make_empty_select();
1250
fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
1251
fake_select_lex->select_limit= 0;
1253
fake_select_lex->context.outer_context=first_sl->context.outer_context;
1254
/* allow item list resolving in fake select for ORDER BY */
1255
fake_select_lex->context.resolve_in_select_list= true;
1256
fake_select_lex->context.select_lex= fake_select_lex;
1262
(SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
1263
(SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
1264
just before the parser starts processing order_list
1266
global_parameters= fake_select_lex;
1267
fake_select_lex->no_table_names_allowed= 1;
1268
session_arg->lex->current_select= fake_select_lex;
1270
session_arg->lex->pop_context();
1276
Push a new name resolution context for a JOIN ... ON clause to the
1277
context stack of a query block.
1279
Create a new name resolution context for a JOIN ... ON clause,
1280
set the first and last leaves of the list of table references
1281
to be used for name resolution, and push the newly created
1282
context to the stack of contexts of the query.
1284
@param session pointer to current thread
1285
@param left_op left operand of the JOIN
1286
@param right_op rigth operand of the JOIN
1291
true if a memory allocation error occured
1295
push_new_name_resolution_context(Session *session,
1296
TableList *left_op, TableList *right_op)
1298
Name_resolution_context *on_context;
1299
if (!(on_context= new (session->mem_root) Name_resolution_context))
1302
on_context->first_name_resolution_table=
1303
left_op->first_leaf_for_name_resolution();
1304
on_context->last_name_resolution_table=
1305
right_op->last_leaf_for_name_resolution();
1306
return session->lex->push_context(on_context);
1311
Add an ON condition to the second operand of a JOIN ... ON.
1313
Add an ON condition to the right operand of a JOIN ... ON clause.
1315
@param b the second operand of a JOIN ... ON
1316
@param expr the condition to be added to the ON clause
1319
false if there was some error
1324
void add_join_on(TableList *b, Item *expr)
1333
If called from the parser, this happens if you have both a
1334
right and left join. If called later, it happens if we add more
1335
than one condition to the ON clause.
1337
b->on_expr= new Item_cond_and(b->on_expr,expr);
1339
b->on_expr->top_level_item();
1345
Mark that there is a NATURAL JOIN or JOIN ... USING between two
1348
This function marks that table b should be joined with a either via
1349
a NATURAL JOIN or via JOIN ... USING. Both join types are special
1350
cases of each other, so we treat them together. The function
1351
setup_conds() creates a list of equal condition between all fields
1352
of the same name for NATURAL JOIN or the fields in 'using_fields'
1353
for JOIN ... USING. The list of equality conditions is stored
1354
either in b->on_expr, or in JOIN::conds, depending on whether there
1359
SELECT * FROM t1 NATURAL LEFT JOIN t2
1361
SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
1363
SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
1365
SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
1367
SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
1369
SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
1372
@param a Left join argument
1373
@param b Right join argument
1374
@param using_fields Field names from USING clause
1377
void add_join_natural(TableList *a, TableList *b, List<String> *using_fields,
1381
lex->prev_join_using= using_fields;
1388
@param session Thread class
1390
@param only_kill_query Should it kill the query or the connection
1393
This is written such that we have a short lock on LOCK_thread_count
1397
kill_one_thread(Session *, ulong id, bool only_kill_query)
1400
uint32_t error= ER_NO_SUCH_THREAD;
1401
pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
1403
for (SessionList::iterator it= getSessionList().begin(); it != getSessionList().end(); ++it )
1405
if ((*it)->thread_id == id)
1408
pthread_mutex_lock(&tmp->LOCK_delete); // Lock from delete
1412
pthread_mutex_unlock(&LOCK_thread_count);
1416
if (tmp->isViewable())
1418
tmp->awake(only_kill_query ? Session::KILL_QUERY : Session::KILL_CONNECTION);
1422
pthread_mutex_unlock(&tmp->LOCK_delete);
1429
kills a thread and sends response
1433
session Thread class
1435
only_kill_query Should it kill the query or the connection
1438
void sql_kill(Session *session, ulong id, bool only_kill_query)
1441
if (!(error= kill_one_thread(session, id, only_kill_query)))
1444
my_error(error, MYF(0), id);
1449
Check if the select is a simple select (not an union).
1454
1 error ; In this case the error messege is sent to the client
1457
bool check_simple_select()
1459
Session *session= current_session;
1460
LEX *lex= session->lex;
1461
if (lex->current_select != &lex->select_lex)
1464
Lex_input_stream *lip= session->m_lip;
1465
strncpy(command, lip->yylval->symbol.str,
1466
min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1)));
1467
command[min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1))]=0;
1468
my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
1476
Construct ALL/ANY/SOME subquery Item.
1478
@param left_expr pointer to left expression
1479
@param cmp compare function creator
1480
@param all true if we create ALL subquery
1481
@param select_lex pointer on parsed subquery structure
1484
constructed Item (or 0 if out of memory)
1486
Item * all_any_subquery_creator(Item *left_expr,
1487
chooser_compare_func_creator cmp,
1489
Select_Lex *select_lex)
1491
if ((cmp == &comp_eq_creator) && !all) // = ANY <=> IN
1492
return new Item_in_subselect(left_expr, select_lex);
1494
if ((cmp == &comp_ne_creator) && all) // <> ALL <=> NOT IN
1495
return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
1497
Item_allany_subselect *it=
1498
new Item_allany_subselect(left_expr, cmp, select_lex, all);
1500
return it->upper_item= new Item_func_not_all(it); /* ALL */
1502
return it->upper_item= new Item_func_nop_all(it); /* ANY/SOME */
1507
Update query pre-check.
1509
@param session Thread handler
1510
@param tables Global/local table list (have to be the same)
1518
bool update_precheck(Session *session, TableList *)
1521
LEX *lex= session->lex;
1522
Select_Lex *select_lex= &lex->select_lex;
1524
if (session->lex->select_lex.item_list.elements != session->lex->value_list.elements)
1526
my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1530
if (session->lex->select_lex.table_list.elements > 1)
1532
if (select_lex->order_list.elements)
1534
else if (select_lex->select_limit)
1538
my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
1547
simple INSERT query pre-check.
1549
@param session Thread handler
1550
@param tables Global table list
1558
bool insert_precheck(Session *session, TableList *)
1560
LEX *lex= session->lex;
1563
Check that we have modify privileges for the first table and
1564
select privileges for the rest
1566
if (lex->update_list.elements != lex->value_list.elements)
1568
my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1576
CREATE TABLE query pre-check.
1578
@param session Thread handler
1579
@param tables Global table list
1580
@param create_table Table which will be created
1588
bool create_table_precheck(TableIdentifier &identifier)
1590
if (not plugin::StorageEngine::canCreateTable(identifier))
1592
my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", identifier.getSchemaName());
1601
negate given expression.
1603
@param session thread handler
1604
@param expr expression for negation
1610
Item *negate_expression(Session *session, Item *expr)
1613
if (expr->type() == Item::FUNC_ITEM &&
1614
((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
1616
/* it is NOT(NOT( ... )) */
1617
Item *arg= ((Item_func *) expr)->arguments()[0];
1618
enum_parsing_place place= session->lex->current_select->parsing_place;
1619
if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
1622
if it is not boolean function then we have to emulate value of
1623
not(not(a)), it will be a != 0
1625
return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
1628
if ((negated= expr->neg_transformer(session)) != 0)
1630
return new Item_func_not(expr);
1635
Check that char length of a string does not exceed some limit.
1638
check_string_char_length()
1639
str string to be checked
1640
err_msg error message to be displayed if the string is too long
1641
max_char_length max length in symbols
1645
false the passed string is not longer than max_char_length
1646
true the passed string is longer than max_char_length
1650
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
1651
uint32_t max_char_length, const CHARSET_INFO * const cs,
1654
int well_formed_error;
1655
uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
1656
max_char_length, &well_formed_error);
1658
if (!well_formed_error && str->length == res)
1662
my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
1667
bool check_identifier_name(LEX_STRING *str, uint32_t err_code,
1668
uint32_t max_char_length,
1669
const char *param_for_err_msg)
1672
We don't support non-BMP characters in identifiers at the moment,
1673
so they should be prohibited until such support is done.
1674
This is why we use the 3-byte utf8 to check well-formedness here.
1676
const CHARSET_INFO * const cs= &my_charset_utf8mb4_general_ci;
1678
int well_formed_error;
1679
uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
1680
max_char_length, &well_formed_error);
1682
if (well_formed_error)
1684
my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
1688
if (str->length == res)
1695
case ER_WRONG_STRING_LENGTH:
1696
my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
1698
case ER_TOO_LONG_IDENT:
1699
my_error(err_code, MYF(0), str->str);
1710
This is a wrapper of DRIZZLEparse(). All the code should call parse_sql()
1711
instead of DRIZZLEparse().
1713
@param session Thread context.
1714
@param lip Lexer context.
1716
@return Error status.
1717
@retval false on success.
1718
@retval true on parsing error.
1721
static bool parse_sql(Session *session, Lex_input_stream *lip)
1723
assert(session->m_lip == NULL);
1725
DRIZZLE_QUERY_PARSE_START(session->query.c_str());
1727
/* Set Lex_input_stream. */
1729
session->m_lip= lip;
1731
/* Parse the query. */
1733
bool mysql_parse_status= DRIZZLEparse(session) != 0;
1735
/* Check that if DRIZZLEparse() failed, session->is_error() is set. */
1737
assert(!mysql_parse_status || session->is_error());
1739
/* Reset Lex_input_stream. */
1741
session->m_lip= NULL;
1743
DRIZZLE_QUERY_PARSE_DONE(mysql_parse_status || session->is_fatal_error);
1747
return mysql_parse_status || session->is_fatal_error;
1751
@} (end of group Runtime_Environment)
1754
} /* namespace drizzled */