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 */
17
#include "mysql_priv.h"
19
#include "rpl_filter.h"
20
#include "repl_failsafe.h"
26
@defgroup Runtime_Environment Runtime Environment
30
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
32
const char *any_db="*any*"; // Special symbol for check_access
34
const LEX_STRING command_name[]={
35
{ C_STRING_WITH_LEN("Sleep") },
36
{ C_STRING_WITH_LEN("Quit") },
37
{ C_STRING_WITH_LEN("Init DB") },
38
{ C_STRING_WITH_LEN("Query") },
39
{ C_STRING_WITH_LEN("Field List") },
40
{ C_STRING_WITH_LEN("Create DB") },
41
{ C_STRING_WITH_LEN("Drop DB") },
42
{ C_STRING_WITH_LEN("Refresh") },
43
{ C_STRING_WITH_LEN("Shutdown") },
44
{ C_STRING_WITH_LEN("Statistics") },
45
{ C_STRING_WITH_LEN("Processlist") },
46
{ C_STRING_WITH_LEN("Connect") },
47
{ C_STRING_WITH_LEN("Kill") },
48
{ C_STRING_WITH_LEN("Debug") },
49
{ C_STRING_WITH_LEN("Ping") },
50
{ C_STRING_WITH_LEN("Time") },
51
{ C_STRING_WITH_LEN("Delayed insert") },
52
{ C_STRING_WITH_LEN("Change user") },
53
{ C_STRING_WITH_LEN("Binlog Dump") },
54
{ C_STRING_WITH_LEN("Table Dump") },
55
{ C_STRING_WITH_LEN("Connect Out") },
56
{ C_STRING_WITH_LEN("Register Slave") },
57
{ C_STRING_WITH_LEN("Prepare") },
58
{ C_STRING_WITH_LEN("Execute") },
59
{ C_STRING_WITH_LEN("Long Data") },
60
{ C_STRING_WITH_LEN("Close stmt") },
61
{ C_STRING_WITH_LEN("Reset stmt") },
62
{ C_STRING_WITH_LEN("Set option") },
63
{ C_STRING_WITH_LEN("Fetch") },
64
{ C_STRING_WITH_LEN("Daemon") },
65
{ C_STRING_WITH_LEN("Error") } // Last command number
68
const char *xa_state_names[]={
69
"NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
72
static void unlock_locked_tables(THD *thd)
74
if (thd->locked_tables)
76
thd->lock=thd->locked_tables;
77
thd->locked_tables=0; // Will be automatically closed
78
close_thread_tables(thd); // Free tables
83
bool end_active_trans(THD *thd)
86
DBUG_ENTER("end_active_trans");
87
if (unlikely(thd->in_sub_stmt))
89
my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
92
if (thd->transaction.xid_state.xa_state != XA_NOTR)
94
my_error(ER_XAER_RMFAIL, MYF(0),
95
xa_state_names[thd->transaction.xid_state.xa_state]);
98
if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
101
DBUG_PRINT("info",("options: 0x%llx", thd->options));
102
/* Safety if one did "drop table" on locked tables */
103
if (!thd->locked_tables)
104
thd->options&= ~OPTION_TABLE_LOCK;
105
thd->server_status&= ~SERVER_STATUS_IN_TRANS;
109
thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
110
thd->transaction.all.modified_non_trans_table= FALSE;
115
bool begin_trans(THD *thd)
118
if (unlikely(thd->in_sub_stmt))
120
my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
123
if (thd->locked_tables)
125
thd->lock=thd->locked_tables;
126
thd->locked_tables=0; // Will be automatically closed
127
close_thread_tables(thd); // Free tables
129
if (end_active_trans(thd))
134
thd->options|= OPTION_BEGIN;
135
thd->server_status|= SERVER_STATUS_IN_TRANS;
136
if (lex->start_transaction_opt & MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
137
error= ha_start_consistent_snapshot(thd);
142
#ifdef HAVE_REPLICATION
144
Returns true if all tables should be ignored.
146
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
148
return rpl_filter->is_on() && tables &&
149
!rpl_filter->tables_ok(thd->db, tables);
154
static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
156
for (TABLE_LIST *table= tables; table; table= table->next_global)
158
DBUG_ASSERT(table->db && table->table_name);
159
if (table->updating &&
160
!find_temporary_table(thd, table->db, table->table_name))
168
Mark all commands that somehow changes a table.
170
This is used to check number of updates / hour.
172
sql_command is actually set to SQLCOM_END sometimes
173
so we need the +1 to include it in the array.
175
See COMMAND_FLAG_xxx for different type of commands
176
2 - query that returns meaningful ROW_COUNT() -
177
a number of modified rows
180
uint sql_command_flags[SQLCOM_END+1];
182
void init_update_queries(void)
184
bzero((uchar*) &sql_command_flags, sizeof(sql_command_flags));
186
sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA;
187
sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA;
188
sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
189
sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
190
sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA;
191
sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA;
192
sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA;
193
sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA;
194
sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA;
195
sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA;
197
sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
198
sql_command_flags[SQLCOM_UPDATE_MULTI]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
199
sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
200
sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
201
sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
202
sql_command_flags[SQLCOM_DELETE_MULTI]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
203
sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
204
sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
206
sql_command_flags[SQLCOM_SHOW_STATUS]= CF_STATUS_COMMAND;
207
sql_command_flags[SQLCOM_SHOW_DATABASES]= CF_STATUS_COMMAND;
208
sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND;
209
sql_command_flags[SQLCOM_SHOW_FIELDS]= CF_STATUS_COMMAND;
210
sql_command_flags[SQLCOM_SHOW_KEYS]= CF_STATUS_COMMAND;
211
sql_command_flags[SQLCOM_SHOW_VARIABLES]= CF_STATUS_COMMAND;
212
sql_command_flags[SQLCOM_SHOW_CHARSETS]= CF_STATUS_COMMAND;
213
sql_command_flags[SQLCOM_SHOW_COLLATIONS]= CF_STATUS_COMMAND;
214
sql_command_flags[SQLCOM_SHOW_NEW_MASTER]= CF_STATUS_COMMAND;
215
sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND;
216
sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
217
sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
218
sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
219
sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
220
sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
221
sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND;
222
sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND;
223
sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
224
sql_command_flags[SQLCOM_SHOW_CREATE_DB]= CF_STATUS_COMMAND;
225
sql_command_flags[SQLCOM_SHOW_CREATE]= CF_STATUS_COMMAND;
226
sql_command_flags[SQLCOM_SHOW_MASTER_STAT]= CF_STATUS_COMMAND;
227
sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]= CF_STATUS_COMMAND;
229
sql_command_flags[SQLCOM_SHOW_TABLES]= (CF_STATUS_COMMAND |
230
CF_SHOW_TABLE_COMMAND);
231
sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
232
CF_SHOW_TABLE_COMMAND);
235
The following is used to preserver CF_ROW_COUNT during the
236
a CALL or EXECUTE statement, so the value generated by the
237
last called (or executed) statement is preserved.
238
See mysql_execute_command() for how CF_ROW_COUNT is used.
240
sql_command_flags[SQLCOM_EXECUTE]= CF_HAS_ROW_COUNT;
243
The following admin table operations are allowed
246
sql_command_flags[SQLCOM_REPAIR]= CF_WRITE_LOGS_COMMAND;
247
sql_command_flags[SQLCOM_OPTIMIZE]= CF_WRITE_LOGS_COMMAND;
248
sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND;
252
bool is_update_query(enum enum_sql_command command)
254
DBUG_ASSERT(command >= 0 && command <= SQLCOM_END);
255
return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
258
void execute_init_command(THD *thd, sys_var_str *init_command_var,
259
rw_lock_t *var_mutex)
262
ulong save_client_capabilities;
264
thd_proc_info(thd, "Execution of init_command");
266
We need to lock init_command_var because
267
during execution of init_command_var query
268
values of init_command_var can't be changed
270
rw_rdlock(var_mutex);
271
save_client_capabilities= thd->client_capabilities;
272
thd->client_capabilities|= CLIENT_MULTI_QUERIES;
274
We don't need return result of execution to client side.
275
To forbid this we should set thd->net.vio to 0.
277
save_vio= thd->net.vio;
279
dispatch_command(COM_QUERY, thd,
280
init_command_var->value,
281
init_command_var->value_length);
282
rw_unlock(var_mutex);
283
thd->client_capabilities= save_client_capabilities;
284
thd->net.vio= save_vio;
289
Execute commands from bootstrap_file.
291
Used when creating the initial grant tables.
294
pthread_handler_t handle_bootstrap(void *arg)
297
FILE *file=bootstrap_file;
299
const char* found_semicolon= NULL;
301
/* The following must be called before DBUG_ENTER */
302
thd->thread_stack= (char*) &thd;
303
if (my_thread_init() || thd->store_globals())
305
close_connection(thd, ER_OUT_OF_RESOURCES, 1);
309
DBUG_ENTER("handle_bootstrap");
311
pthread_detach_this_thread();
312
thd->thread_stack= (char*) &thd;
314
if (thd->variables.max_join_size == HA_POS_ERROR)
315
thd->options |= OPTION_BIG_SELECTS;
317
thd_proc_info(thd, 0);
318
thd->version=refresh_version;
319
thd->security_ctx->priv_user=
320
thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME));
321
thd->security_ctx->priv_host[0]=0;
323
Make the "client" handle multiple results. This is necessary
324
to enable stored procedures with SELECTs and Dynamic SQL
327
thd->client_capabilities|= CLIENT_MULTI_RESULTS;
329
buff= (char*) thd->net.buff;
330
thd->init_for_queries();
331
while (fgets(buff, thd->net.max_packet, file))
333
/* strlen() can't be deleted because fgets() doesn't return length */
334
ulong length= (ulong) strlen(buff);
335
while (buff[length-1] != '\n' && !feof(file))
338
We got only a part of the current string. Will try to increase
339
net buffer then read the rest of the current string.
341
/* purecov: begin tested */
342
if (net_realloc(&(thd->net), 2 * thd->net.max_packet))
344
net_end_statement(thd);
348
buff= (char*) thd->net.buff;
349
fgets(buff + length, thd->net.max_packet - length, file);
350
length+= (ulong) strlen(buff + length);
354
break; /* purecov: inspected */
356
while (length && (my_isspace(thd->charset(), buff[length-1]) ||
357
buff[length-1] == ';'))
361
/* Skip lines starting with delimiter */
362
if (strncmp(buff, STRING_WITH_LEN("delimiter")) == 0)
365
thd->query_length=length;
366
thd->query= (char*) thd->memdup_w_gap(buff, length+1,
368
thd->query[length] = '\0';
369
DBUG_PRINT("query",("%-.4096s",thd->query));
372
We don't need to obtain LOCK_thread_count here because in bootstrap
373
mode we have only one thread.
375
thd->query_id=next_query_id();
377
mysql_parse(thd, thd->query, length, & found_semicolon);
378
close_thread_tables(thd); // Free tables
380
bootstrap_error= thd->is_error();
381
net_end_statement(thd);
386
free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
387
free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC));
395
(void) pthread_mutex_lock(&LOCK_thread_count);
397
(void) pthread_mutex_unlock(&LOCK_thread_count);
398
(void) pthread_cond_broadcast(&COND_thread_count);
404
/* This works because items are allocated with sql_alloc() */
406
void free_items(Item *item)
409
DBUG_ENTER("free_items");
410
for (; item ; item=next)
418
/* This works because items are allocated with sql_alloc() */
420
void cleanup_items(Item *item)
422
DBUG_ENTER("cleanup_items");
423
for (; item ; item=item->next)
429
Ends the current transaction and (maybe) begin the next.
431
@param thd Current thread
432
@param completion Completion type
438
int end_trans(THD *thd, enum enum_mysql_completiontype completion)
442
DBUG_ENTER("end_trans");
444
if (unlikely(thd->in_sub_stmt))
446
my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0));
449
if (thd->transaction.xid_state.xa_state != XA_NOTR)
451
my_error(ER_XAER_RMFAIL, MYF(0),
452
xa_state_names[thd->transaction.xid_state.xa_state]);
455
switch (completion) {
458
We don't use end_active_trans() here to ensure that this works
459
even if there is a problem with the OPTION_AUTO_COMMIT flag
460
(Which of course should never happen...)
462
thd->server_status&= ~SERVER_STATUS_IN_TRANS;
464
thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
465
thd->transaction.all.modified_non_trans_table= FALSE;
468
do_release= 1; /* fall through */
469
case COMMIT_AND_CHAIN:
470
res= end_active_trans(thd);
471
if (!res && completion == COMMIT_AND_CHAIN)
472
res= begin_trans(thd);
474
case ROLLBACK_RELEASE:
475
do_release= 1; /* fall through */
477
case ROLLBACK_AND_CHAIN:
479
thd->server_status&= ~SERVER_STATUS_IN_TRANS;
480
if (ha_rollback(thd))
482
thd->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
483
thd->transaction.all.modified_non_trans_table= FALSE;
484
if (!res && (completion == ROLLBACK_AND_CHAIN))
485
res= begin_trans(thd);
490
my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
495
my_error(thd->killed_errno(), MYF(0));
496
else if ((res == 0) && do_release)
497
thd->killed= THD::KILL_CONNECTION;
504
Read one command from connection and execute it (query or simple command).
505
This function is called in loop from thread function.
507
For profiling to work, it must never be called recursively.
512
1 request of thread shutdown (see dispatch_command() description)
515
bool do_command(THD *thd)
521
enum enum_server_command command;
522
DBUG_ENTER("do_command");
525
indicator of uninitialized lex => normal flow of errors handling
528
thd->lex->current_select= 0;
531
This thread will do a blocking read from the client which
532
will be interrupted when the next command is received from
533
the client, the connection is closed or "net_wait_timeout"
534
number of seconds has passed
536
my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
539
XXX: this code is here only to clear possible errors of init_connect.
540
Consider moving to init_connect() instead.
542
thd->clear_error(); // Clear error message
543
thd->main_da.reset_diagnostics_area();
545
net_new_transaction(net);
547
packet_length= my_net_read(net);
548
if (packet_length == packet_error)
550
DBUG_PRINT("info",("Got error %d reading command from socket %s",
552
vio_description(net->vio)));
554
/* Check if we can continue without closing the connection */
556
/* The error must be set. */
557
DBUG_ASSERT(thd->is_error());
558
net_end_statement(thd);
562
return_value= TRUE; // We have to close it.
571
packet= (char*) net->read_pos;
573
'packet_length' contains length of data, as it was stored in packet
574
header. In case of malformed header, my_net_read returns zero.
575
If packet_length is not zero, my_net_read ensures that the returned
576
number of bytes was actually read from network.
577
There is also an extra safety measure in my_net_read:
578
it sets packet[packet_length]= 0, but only for non-zero packets.
580
if (packet_length == 0) /* safety */
582
/* Initialize with COM_SLEEP packet */
583
packet[0]= (uchar) COM_SLEEP;
586
/* Do not rely on my_net_read, extra safety against programming errors. */
587
packet[packet_length]= '\0'; /* safety */
589
command= (enum enum_server_command) (uchar) packet[0];
591
if (command >= COM_END)
592
command= COM_END; // Wrong command
594
DBUG_PRINT("info",("Command on %s = %d (%s)",
595
vio_description(net->vio), command,
596
command_name[command].str));
598
/* Restore read timeout value */
599
my_net_set_read_timeout(net, thd->variables.net_read_timeout);
601
DBUG_ASSERT(packet_length);
602
return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1));
605
DBUG_RETURN(return_value);
609
Determine if an attempt to update a non-temporary table while the
610
read-only option was enabled has been made.
612
This is a helper function to mysql_execute_command.
614
@note SQLCOM_MULTI_UPDATE is an exception and dealt with elsewhere.
616
@see mysql_execute_command
619
@retval TRUE The statement should be denied.
620
@retval FALSE The statement isn't updating any relevant tables.
623
static my_bool deny_updates_if_read_only_option(THD *thd,
624
TABLE_LIST *all_tables)
626
DBUG_ENTER("deny_updates_if_read_only_option");
633
if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
636
/* Multi update is an exception and is dealt with later. */
637
if (lex->sql_command == SQLCOM_UPDATE_MULTI)
640
const my_bool create_temp_tables=
641
(lex->sql_command == SQLCOM_CREATE_TABLE) &&
642
(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE);
644
const my_bool drop_temp_tables=
645
(lex->sql_command == SQLCOM_DROP_TABLE) &&
648
const my_bool update_real_tables=
649
some_non_temp_table_to_be_updated(thd, all_tables) &&
650
!(create_temp_tables || drop_temp_tables);
653
const my_bool create_or_drop_databases=
654
(lex->sql_command == SQLCOM_CREATE_DB) ||
655
(lex->sql_command == SQLCOM_DROP_DB);
657
if (update_real_tables || create_or_drop_databases)
660
An attempt was made to modify one or more non-temporary tables.
666
/* Assuming that only temporary tables are modified. */
671
Perform one connection-level (COM_XXXX) command.
673
@param command type of command to perform
674
@param thd connection handle
675
@param packet data for the command, packet is always null-terminated
676
@param packet_length length of packet + 1 (to show that data is
677
null-terminated) except for COM_SLEEP, where it
681
set thd->lex->sql_command to SQLCOM_END here.
683
The following has to be changed to an 8 byte integer
688
1 request of thread shutdown, i. e. if command is
689
COM_QUIT/COM_SHUTDOWN
691
bool dispatch_command(enum enum_server_command command, THD *thd,
692
char* packet, uint packet_length)
696
DBUG_ENTER("dispatch_command");
697
DBUG_PRINT("info",("packet: '%*.s'; command: %d", packet_length, packet, command));
699
thd->command=command;
701
Commands which always take a long time are logged into
702
the slow log only if opt_log_slow_admin_statements is set.
704
thd->enable_slow_log= TRUE;
705
thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
707
VOID(pthread_mutex_lock(&LOCK_thread_count));
708
thd->query_id= global_query_id;
711
/* Ignore these statements. */
715
/* Only increase id on these statements but don't count them. */
716
case COM_STMT_PREPARE:
721
/* Increase id and count all other statements. */
723
statistic_increment(thd->status_var.questions, &LOCK_status);
728
/* TODO: set thd->lex->sql_command to SQLCOM_END here */
729
VOID(pthread_mutex_unlock(&LOCK_thread_count));
732
~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
737
status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
738
thd->convert_string(&tmp, system_charset_info,
739
packet, packet_length, thd->charset());
740
if (!mysql_change_db(thd, &tmp, FALSE))
742
general_log_write(thd, command, thd->db, thd->db_length);
747
case COM_REGISTER_SLAVE:
749
if (!register_slave(thd, (uchar*)packet, packet_length))
753
case COM_CHANGE_USER:
755
status_var_increment(thd->status_var.com_other);
756
char *user= (char*) packet, *packet_end= packet + packet_length;
757
/* Safe because there is always a trailing \0 at the end of the packet */
758
char *passwd= strend(user)+1;
760
thd->clear_error(); // if errors from rollback
763
Old clients send null-terminated string ('\0' for empty string) for
764
password. New clients send the size (1 byte) + string (not null
765
terminated, so also '\0' for empty string).
767
Cast *passwd to an unsigned char, so that it doesn't extend the sign
768
for *passwd > 127 and become 2**32-127 after casting to uint.
770
char db_buff[NAME_LEN+1]; // buffer to store db in utf8
774
If there is no password supplied, the packet must contain '\0',
775
in any type of handshake (4.1 or pre-4.1).
777
if (passwd >= packet_end)
779
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
782
uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
783
(uchar)(*passwd++) : strlen(passwd));
784
uint dummy_errors, save_db_length, db_length;
786
Security_context save_security_ctx= *thd->security_ctx;
787
USER_CONN *save_user_connect;
791
Database name is always NUL-terminated, so in case of empty database
792
the packet must contain at least the trailing '\0'.
794
if (db >= packet_end)
796
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
799
db_length= strlen(db);
801
char *ptr= db + db_length + 1;
804
if (ptr < packet_end)
806
if (ptr + 2 > packet_end)
808
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
812
cs_number= uint2korr(ptr);
815
/* Convert database name to utf8 */
816
db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
817
system_charset_info, db, db_length,
818
thd->charset(), &dummy_errors)]= 0;
821
/* Save user and privileges */
822
save_db_length= thd->db_length;
824
save_user_connect= thd->user_connect;
826
if (!(thd->security_ctx->user= my_strdup(user, MYF(0))))
828
thd->security_ctx->user= save_security_ctx.user;
829
my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
833
/* Clear variables that are allocated */
834
thd->user_connect= 0;
835
thd->security_ctx->priv_user= thd->security_ctx->user;
836
res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE);
840
x_free(thd->security_ctx->user);
841
*thd->security_ctx= save_security_ctx;
842
thd->user_connect= save_user_connect;
844
thd->db_length= save_db_length;
849
x_free(save_security_ctx.user);
853
thd_init_client_charset(thd, cs_number);
854
thd->update_charset();
859
case COM_STMT_EXECUTE:
861
case COM_STMT_SEND_LONG_DATA:
862
case COM_STMT_PREPARE:
866
/* We should toss an error here */
871
if (alloc_query(thd, packet, packet_length))
872
break; // fatal error is set
873
char *packet_end= thd->query + thd->query_length;
874
/* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
875
const char* end_of_stmt= NULL;
877
general_log_write(thd, command, thd->query, thd->query_length);
878
DBUG_PRINT("query",("%-.4096s",thd->query));
880
if (!(specialflag & SPECIAL_NO_PRIOR))
881
my_pthread_setprio(pthread_self(),QUERY_PRIOR);
883
mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt);
885
while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error())
887
char *beginning_of_next_stmt= (char*) end_of_stmt;
889
net_end_statement(thd);
891
Multiple queries exits, execute them individually
893
close_thread_tables(thd);
894
ulong length= (ulong)(packet_end - beginning_of_next_stmt);
896
log_slow_statement(thd);
898
/* Remove garbage at start of query */
899
while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
901
beginning_of_next_stmt++;
905
VOID(pthread_mutex_lock(&LOCK_thread_count));
906
thd->query_length= length;
907
thd->query= beginning_of_next_stmt;
909
Count each statement from the client.
911
statistic_increment(thd->status_var.questions, &LOCK_status);
912
thd->query_id= next_query_id();
913
thd->set_time(); /* Reset the query start time. */
914
/* TODO: set thd->lex->sql_command to SQLCOM_END here */
915
VOID(pthread_mutex_unlock(&LOCK_thread_count));
917
mysql_parse(thd, beginning_of_next_stmt, length, &end_of_stmt);
920
if (!(specialflag & SPECIAL_NO_PRIOR))
921
my_pthread_setprio(pthread_self(),WAIT_PRIOR);
922
DBUG_PRINT("info",("query ready"));
925
case COM_FIELD_LIST: // This isn't actually needed
927
char *fields, *packet_end= packet + packet_length, *arg_end;
928
/* Locked closure of all tables */
929
TABLE_LIST table_list;
930
LEX_STRING conv_name;
932
/* used as fields initializator */
935
status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
936
bzero((char*) &table_list,sizeof(table_list));
937
if (thd->copy_db_to(&table_list.db, &table_list.db_length))
940
We have name + wildcard in packet, separated by endzero
942
arg_end= strend(packet);
943
thd->convert_string(&conv_name, system_charset_info,
944
packet, (uint) (arg_end - packet), thd->charset());
945
table_list.alias= table_list.table_name= conv_name.str;
948
if (!my_strcasecmp(system_charset_info, table_list.db,
949
INFORMATION_SCHEMA_NAME.str))
951
ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias);
953
table_list.schema_table= schema_table;
956
thd->query_length= (uint) (packet_end - packet); // Don't count end \0
957
if (!(thd->query=fields= (char*) thd->memdup(packet,thd->query_length+1)))
959
general_log_print(thd, command, "%s %s", table_list.table_name, fields);
960
if (lower_case_table_names)
961
my_casedn_str(files_charset_info, table_list.table_name);
963
/* init structures for VIEW processing */
964
table_list.select_lex= &(thd->lex->select_lex);
967
mysql_reset_thd_for_next_command(thd);
970
select_lex.table_list.link_in_list((uchar*) &table_list,
971
(uchar**) &table_list.next_local);
972
thd->lex->add_to_query_tables(&table_list);
974
/* switch on VIEW optimisation: do not fill temporary tables */
975
thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
976
mysqld_list_fields(thd,&table_list,fields);
977
thd->lex->unit.cleanup();
978
thd->cleanup_after_query();
982
/* We don't calculate statistics for this command */
983
general_log_print(thd, command, NullS);
984
net->error=0; // Don't give 'abort' message
985
thd->main_da.disable_status(); // Don't send anything back
986
error=TRUE; // End server
988
case COM_BINLOG_DUMP:
992
uint32 slave_server_id;
994
status_var_increment(thd->status_var.com_other);
995
thd->enable_slow_log= opt_log_slow_admin_statements;
996
/* TODO: The following has to be changed to an 8 byte integer */
997
pos = uint4korr(packet);
998
flags = uint2korr(packet + 4);
999
thd->server_id=0; /* avoid suicide */
1000
if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0
1001
kill_zombie_dump_threads(slave_server_id);
1002
thd->server_id = slave_server_id;
1004
general_log_print(thd, command, "Log: '%s' Pos: %ld", packet+10,
1006
mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags);
1007
unregister_slave(thd,1,1);
1008
/* fake COM_QUIT -- if we get here, the thread needs to terminate */
1014
status_var_increment(thd->status_var.com_other);
1016
If the client is < 4.1.3, it is going to send us no argument; then
1017
packet_length is 0, packet[0] is the end 0 of the packet. Note that
1018
SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
1021
enum mysql_enum_shutdown_level level=
1022
(enum mysql_enum_shutdown_level) (uchar) packet[0];
1023
if (level == SHUTDOWN_DEFAULT)
1024
level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
1025
else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
1027
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
1030
DBUG_PRINT("quit",("Got shutdown command for level %u", level));
1031
general_log_print(thd, command, NullS);
1033
close_thread_tables(thd); // Free before kill
1038
case COM_STATISTICS:
1040
STATUS_VAR current_global_status_var;
1043
ulonglong queries_per_second1000;
1045
uint buff_len= sizeof(buff);
1047
general_log_print(thd, command, NullS);
1048
status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
1049
calc_sum_of_all_status(¤t_global_status_var);
1050
if (!(uptime= (ulong) (thd->start_time - server_start_time)))
1051
queries_per_second1000= 0;
1053
queries_per_second1000= thd->query_id * LL(1000) / uptime;
1055
length= my_snprintf((char*) buff, buff_len - 1,
1056
"Uptime: %lu Threads: %d Questions: %lu "
1057
"Slow queries: %lu Opens: %lu Flush tables: %lu "
1058
"Open tables: %u Queries per second avg: %u.%u",
1060
(int) thread_count, (ulong) thd->query_id,
1061
current_global_status_var.long_query_count,
1062
current_global_status_var.opened_tables,
1064
cached_open_tables(),
1065
(uint) (queries_per_second1000 / 1000),
1066
(uint) (queries_per_second1000 % 1000));
1067
/* Store the buffer in permanent memory */
1068
my_ok(thd, 0, 0, buff);
1069
VOID(my_net_write(net, (uchar*) buff, length));
1070
VOID(net_flush(net));
1071
thd->main_da.disable_status();
1075
status_var_increment(thd->status_var.com_other);
1076
my_ok(thd); // Tell client we are alive
1078
case COM_PROCESS_INFO:
1079
status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
1080
general_log_print(thd, command, NullS);
1081
mysqld_list_processes(thd, NullS, 0);
1083
case COM_PROCESS_KILL:
1085
status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
1086
ulong id=(ulong) uint4korr(packet);
1087
sql_kill(thd,id,false);
1090
case COM_SET_OPTION:
1092
status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
1093
uint opt_command= uint2korr(packet);
1095
switch (opt_command) {
1096
case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
1097
thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1100
case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
1101
thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
1105
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1111
status_var_increment(thd->status_var.com_other);
1112
mysql_print_status();
1113
general_log_print(thd, command, NullS);
1117
case COM_CONNECT: // Impossible here
1118
case COM_TIME: // Impossible from client
1121
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
1125
/* If commit fails, we should be able to reset the OK status. */
1126
thd->main_da.can_overwrite_status= TRUE;
1127
ha_autocommit_or_rollback(thd, thd->is_error());
1128
thd->main_da.can_overwrite_status= FALSE;
1130
thd->transaction.stmt.reset();
1133
/* report error issued during command execution */
1134
if (thd->killed_errno())
1136
if (! thd->main_da.is_set())
1137
thd->send_kill_message();
1139
if (thd->killed == THD::KILL_QUERY || thd->killed == THD::KILL_BAD_DATA)
1141
thd->killed= THD::NOT_KILLED;
1142
thd->mysys_var->abort= 0;
1145
net_end_statement(thd);
1147
thd->proc_info= "closing tables";
1149
close_thread_tables(thd);
1151
log_slow_statement(thd);
1153
thd_proc_info(thd, "cleaning up");
1154
VOID(pthread_mutex_lock(&LOCK_thread_count)); // For process list
1155
thd_proc_info(thd, 0);
1156
thd->command=COM_SLEEP;
1158
thd->query_length=0;
1160
VOID(pthread_mutex_unlock(&LOCK_thread_count));
1161
thd->packet.shrink(thd->variables.net_buffer_length); // Reclaim some memory
1162
free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1167
void log_slow_statement(THD *thd)
1169
DBUG_ENTER("log_slow_statement");
1172
The following should never be true with our current code base,
1173
but better to keep this here so we don't accidently try to log a
1174
statement in a trigger or stored function
1176
if (unlikely(thd->in_sub_stmt))
1177
DBUG_VOID_RETURN; // Don't set time for sub stmt
1180
Do not log administrative statements unless the appropriate option is
1181
set; do not log into slow log if reading from backup.
1183
if (thd->enable_slow_log && !thd->user_time)
1185
thd_proc_info(thd, "logging slow query");
1186
ulonglong end_utime_of_query= thd->current_utime();
1188
if (((end_utime_of_query - thd->utime_after_lock) >
1189
thd->variables.long_query_time ||
1190
((thd->server_status &
1191
(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
1192
opt_log_queries_not_using_indexes &&
1193
!(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) &&
1194
thd->examined_row_count >= thd->variables.min_examined_row_limit)
1196
thd_proc_info(thd, "logging slow query");
1197
thd->status_var.long_query_count++;
1198
slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query);
1206
Create a TABLE_LIST object for an INFORMATION_SCHEMA table.
1208
This function is used in the parser to convert a SHOW or DESCRIBE
1209
table_name command to a SELECT from INFORMATION_SCHEMA.
1210
It prepares a SELECT_LEX and a TABLE_LIST object to represent the
1211
given command as a SELECT parse tree.
1213
@param thd thread handle
1214
@param lex current lex
1215
@param table_ident table alias if it's used
1216
@param schema_table_idx the type of the INFORMATION_SCHEMA table to be
1220
Due to the way this function works with memory and LEX it cannot
1221
be used outside the parser (parse tree transformations outside
1222
the parser break PS and SP).
1227
1 out of memory or SHOW commands are not allowed
1228
in this version of the server.
1231
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
1232
enum enum_schema_tables schema_table_idx)
1234
SELECT_LEX *schema_select_lex= NULL;
1235
DBUG_ENTER("prepare_schema_table");
1237
switch (schema_table_idx) {
1240
case SCH_TABLE_NAMES:
1245
if (lex->select_lex.db == NULL &&
1246
lex->copy_db_to(&lex->select_lex.db, &dummy))
1250
schema_select_lex= new SELECT_LEX();
1251
db.str= schema_select_lex->db= lex->select_lex.db;
1252
schema_select_lex->table_list.first= NULL;
1253
db.length= strlen(db.str);
1255
if (check_db_name(&db))
1257
my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
1263
case SCH_STATISTICS:
1265
DBUG_ASSERT(table_ident);
1266
TABLE_LIST **query_tables_last= lex->query_tables_last;
1267
schema_select_lex= new SELECT_LEX();
1268
/* 'parent_lex' is used in init_query() so it must be before it. */
1269
schema_select_lex->parent_lex= lex;
1270
schema_select_lex->init_query();
1271
if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ))
1273
lex->query_tables_last= query_tables_last;
1276
case SCH_OPEN_TABLES:
1280
case SCH_COLLATIONS:
1281
case SCH_COLLATION_CHARACTER_SET_APPLICABILITY:
1282
case SCH_TABLE_CONSTRAINTS:
1283
case SCH_KEY_COLUMN_USAGE:
1288
SELECT_LEX *select_lex= lex->current_select;
1290
if (make_schema_select(thd, select_lex, schema_table_idx))
1294
TABLE_LIST *table_list= (TABLE_LIST*) select_lex->table_list.first;
1296
table_list->schema_select_lex= schema_select_lex;
1297
table_list->schema_table_reformed= 1;
1303
Read query from packet and store in thd->query.
1304
Used in COM_QUERY and COM_STMT_PREPARE.
1306
Sets the following THD variables:
1313
TRUE error; In this case thd->fatal_error is set
1316
bool alloc_query(THD *thd, const char *packet, uint packet_length)
1318
/* Remove garbage at start and end of query */
1319
while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
1324
const char *pos= packet + packet_length; // Point at end null
1325
while (packet_length > 0 &&
1326
(pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
1331
/* We must allocate some extra memory for query cache */
1332
thd->query_length= 0; // Extra safety: Avoid races
1333
if (!(thd->query= (char*) thd->memdup_w_gap((uchar*) (packet),
1335
thd->db_length+ 1)))
1337
thd->query[packet_length]=0;
1338
thd->query_length= packet_length;
1340
/* Reclaim some memory */
1341
thd->packet.shrink(thd->variables.net_buffer_length);
1342
thd->convert_buffer.shrink(thd->variables.net_buffer_length);
1347
static void reset_one_shot_variables(THD *thd)
1349
thd->variables.character_set_client=
1350
global_system_variables.character_set_client;
1351
thd->variables.collation_connection=
1352
global_system_variables.collation_connection;
1353
thd->variables.collation_database=
1354
global_system_variables.collation_database;
1355
thd->variables.collation_server=
1356
global_system_variables.collation_server;
1357
thd->update_charset();
1358
thd->variables.time_zone=
1359
global_system_variables.time_zone;
1360
thd->variables.lc_time_names= &my_locale_en_US;
1361
thd->one_shot_set= 0;
1366
Execute command saved in thd and lex->sql_command.
1368
Before every operation that can request a write lock for a table
1369
wait if a global read lock exists. However do not wait if this
1370
thread has locked tables already. No new locks can be requested
1371
until the other locks are released. The thread that requests the
1372
global read lock waits for write locked tables to become unlocked.
1374
Note that wait_if_global_read_lock() sets a protection against a new
1375
global read lock when it succeeds. This needs to be released by
1376
start_waiting_global_read_lock() after the operation.
1378
@param thd Thread handle
1381
- Invalidate the table in the query cache if something changed
1382
after unlocking when changes become visible.
1383
TODO: this is workaround. right way will be move invalidating in
1384
the unlock procedure.
1385
- TODO: use check_change_password()
1386
- JOIN is not supported yet. TODO
1387
- SUSPEND and FOR MIGRATE are not supported yet. TODO
1396
mysql_execute_command(THD *thd)
1399
bool need_start_waiting= FALSE; // have protection against global read lock
1402
/* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
1403
SELECT_LEX *select_lex= &lex->select_lex;
1404
/* first table of first SELECT_LEX */
1405
TABLE_LIST *first_table= (TABLE_LIST*) select_lex->table_list.first;
1406
/* list of all tables in query */
1407
TABLE_LIST *all_tables;
1408
/* most outer SELECT_LEX_UNIT of query */
1409
SELECT_LEX_UNIT *unit= &lex->unit;
1410
/* Saved variable value */
1411
DBUG_ENTER("mysql_execute_command");
1414
In many cases first table of main SELECT_LEX have special meaning =>
1415
check that it is first table in global list and relink it first in
1416
queries_tables list if it is necessary (we need such relinking only
1417
for queries with subqueries in select list, in this case tables of
1418
subqueries will go to global list first)
1420
all_tables will differ from first_table only if most upper SELECT_LEX
1421
do not contain tables.
1423
Because of above in place where should be at least one table in most
1424
outer SELECT_LEX we have following check:
1425
DBUG_ASSERT(first_table == all_tables);
1426
DBUG_ASSERT(first_table == all_tables && first_table != 0);
1428
lex->first_lists_tables_same();
1429
/* should be assigned after making first tables same */
1430
all_tables= lex->query_tables;
1431
/* set context for commands which do not use setup_tables */
1433
context.resolve_in_table_list_only((TABLE_LIST*)select_lex->
1437
Reset warning count for each query that uses tables
1438
A better approach would be to reset this for any commands
1439
that is not a SHOW command or a select that only access local
1440
variables, but for now this is probably good enough.
1441
Don't reset warnings when executing a stored routine.
1443
if (all_tables || !lex->is_single_level_stmt())
1444
mysql_reset_errors(thd, 0);
1446
#ifdef HAVE_REPLICATION
1447
if (unlikely(thd->slave_thread))
1450
Check if statment should be skipped because of slave filtering
1454
- UPDATE MULTI: For this statement, we want to check the filtering
1455
rules later in the code
1456
- SET: we always execute it (Not that many SET commands exists in
1457
the binary log anyway -- only 4.1 masters write SET statements,
1458
in 5.0 there are no SET statements in the binary log)
1459
- DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
1460
have stale files on slave caused by exclusion of one tmp table).
1462
if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
1463
!(lex->sql_command == SQLCOM_SET_OPTION) &&
1464
!(lex->sql_command == SQLCOM_DROP_TABLE &&
1465
lex->drop_temporary && lex->drop_if_exists) &&
1466
all_tables_not_ok(thd, all_tables))
1468
/* we warn the slave SQL thread */
1469
my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
1470
if (thd->one_shot_set)
1473
It's ok to check thd->one_shot_set here:
1475
The charsets in a MySQL 5.0 slave can change by both a binlogged
1476
SET ONE_SHOT statement and the event-internal charset setting,
1477
and these two ways to change charsets do not seems to work
1480
At least there seems to be problems in the rli cache for
1481
charsets if we are using ONE_SHOT. Note that this is normally no
1482
problem because either the >= 5.0 slave reads a 4.1 binlog (with
1483
ONE_SHOT) *or* or 5.0 binlog (without ONE_SHOT) but never both."
1485
reset_one_shot_variables(thd);
1492
#endif /* HAVE_REPLICATION */
1494
When option readonly is set deny operations which change non-temporary
1495
tables. Except for the replication thread and the 'super' users.
1497
if (deny_updates_if_read_only_option(thd, all_tables))
1499
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
1502
#ifdef HAVE_REPLICATION
1503
} /* endif unlikely slave */
1505
status_var_increment(thd->status_var.com_stat[lex->sql_command]);
1507
DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE);
1509
switch (lex->sql_command) {
1510
case SQLCOM_SHOW_STATUS:
1512
system_status_var old_status_var= thd->status_var;
1513
thd->initial_status_var= &old_status_var;
1514
res= execute_sqlcom_select(thd, all_tables);
1515
/* Don't log SHOW STATUS commands to slow query log */
1516
thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
1517
SERVER_QUERY_NO_GOOD_INDEX_USED);
1519
restore status variables, as we don't want 'show status' to cause
1522
pthread_mutex_lock(&LOCK_status);
1523
add_diff_to_status(&global_status_var, &thd->status_var,
1525
thd->status_var= old_status_var;
1526
pthread_mutex_unlock(&LOCK_status);
1529
case SQLCOM_SHOW_DATABASES:
1530
case SQLCOM_SHOW_TABLES:
1531
case SQLCOM_SHOW_TABLE_STATUS:
1532
case SQLCOM_SHOW_OPEN_TABLES:
1533
case SQLCOM_SHOW_FIELDS:
1534
case SQLCOM_SHOW_KEYS:
1535
case SQLCOM_SHOW_VARIABLES:
1536
case SQLCOM_SHOW_CHARSETS:
1537
case SQLCOM_SHOW_COLLATIONS:
1540
thd->status_var.last_query_cost= 0.0;
1541
res= execute_sqlcom_select(thd, all_tables);
1544
case SQLCOM_PREPARE:
1548
case SQLCOM_EXECUTE:
1552
case SQLCOM_DEALLOCATE_PREPARE:
1556
case SQLCOM_EMPTY_QUERY:
1562
res = purge_master_logs(thd, lex->to_log);
1565
case SQLCOM_PURGE_BEFORE:
1569
/* PURGE MASTER LOGS BEFORE 'data' */
1570
it= (Item *)lex->value_list.head();
1571
if ((!it->fixed && it->fix_fields(lex->thd, &it)) ||
1574
my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE");
1577
it= new Item_func_unix_timestamp(it);
1579
it is OK only emulate fix_fieds, because we need only
1582
it->quick_fix_field();
1583
res = purge_master_logs_before_date(thd, (ulong)it->val_int());
1586
case SQLCOM_SHOW_WARNS:
1588
res= mysqld_show_warnings(thd, (ulong)
1589
((1L << (uint) MYSQL_ERROR::WARN_LEVEL_NOTE) |
1590
(1L << (uint) MYSQL_ERROR::WARN_LEVEL_WARN) |
1591
(1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR)
1595
case SQLCOM_SHOW_ERRORS:
1597
res= mysqld_show_warnings(thd, (ulong)
1598
(1L << (uint) MYSQL_ERROR::WARN_LEVEL_ERROR));
1601
case SQLCOM_SHOW_NEW_MASTER:
1603
/* This query don't work now. See comment in repl_failsafe.cc */
1604
#ifndef WORKING_NEW_MASTER
1605
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
1608
res = show_new_master(thd);
1613
#ifdef HAVE_REPLICATION
1614
case SQLCOM_SHOW_SLAVE_HOSTS:
1616
res = show_slave_hosts(thd);
1619
case SQLCOM_SHOW_BINLOG_EVENTS:
1621
res = mysql_show_binlog_events(thd);
1626
case SQLCOM_ASSIGN_TO_KEYCACHE:
1628
DBUG_ASSERT(first_table == all_tables && first_table != 0);
1629
res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
1632
case SQLCOM_PRELOAD_KEYS:
1634
DBUG_ASSERT(first_table == all_tables && first_table != 0);
1635
res = mysql_preload_keys(thd, first_table);
1638
#ifdef HAVE_REPLICATION
1639
case SQLCOM_CHANGE_MASTER:
1641
pthread_mutex_lock(&LOCK_active_mi);
1642
res = change_master(thd,active_mi);
1643
pthread_mutex_unlock(&LOCK_active_mi);
1646
case SQLCOM_SHOW_SLAVE_STAT:
1648
pthread_mutex_lock(&LOCK_active_mi);
1649
if (active_mi != NULL)
1651
res = show_master_info(thd, active_mi);
1655
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
1656
"the master info structure does not exist");
1659
pthread_mutex_unlock(&LOCK_active_mi);
1662
case SQLCOM_SHOW_MASTER_STAT:
1664
res = show_binlog_info(thd);
1668
#endif /* HAVE_REPLICATION */
1669
case SQLCOM_SHOW_ENGINE_STATUS:
1671
res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
1674
case SQLCOM_SHOW_ENGINE_MUTEX:
1676
res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
1679
case SQLCOM_CREATE_TABLE:
1681
/* If CREATE TABLE of non-temporary table, do implicit commit */
1682
if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
1684
if (end_active_trans(thd))
1690
DBUG_ASSERT(first_table == all_tables && first_table != 0);
1692
// Skip first table, which is the table we are creating
1693
TABLE_LIST *create_table= lex->unlink_first_table(&link_to_local);
1694
TABLE_LIST *select_tables= lex->query_tables;
1696
Code below (especially in mysql_create_table() and select_create
1697
methods) may modify HA_CREATE_INFO structure in LEX, so we have to
1698
use a copy of this structure to make execution prepared statement-
1699
safe. A shallow copy is enough as this code won't modify any memory
1700
referenced from this structure.
1702
HA_CREATE_INFO create_info(lex->create_info);
1704
We need to copy alter_info for the same reasons of re-execution
1705
safety, only in case of Alter_info we have to do (almost) a deep
1708
Alter_info alter_info(lex->alter_info, thd->mem_root);
1710
if (thd->is_fatal_error)
1712
/* If out of memory when creating a copy of alter_info. */
1714
goto end_with_restore_list;
1717
if ((res= create_table_precheck(thd, select_tables, create_table)))
1718
goto end_with_restore_list;
1720
/* Might have been updated in create_table_precheck */
1721
create_info.alias= create_table->alias;
1723
#ifdef HAVE_READLINK
1724
/* Fix names if symlinked tables */
1725
if (append_file_to_dir(thd, &create_info.data_file_name,
1726
create_table->table_name) ||
1727
append_file_to_dir(thd, &create_info.index_file_name,
1728
create_table->table_name))
1729
goto end_with_restore_list;
1732
If we are using SET CHARSET without DEFAULT, add an implicit
1733
DEFAULT to not confuse old users. (This may change).
1735
if ((create_info.used_fields &
1736
(HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
1737
HA_CREATE_USED_CHARSET)
1739
create_info.used_fields&= ~HA_CREATE_USED_CHARSET;
1740
create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET;
1741
create_info.default_table_charset= create_info.table_charset;
1742
create_info.table_charset= 0;
1745
The create-select command will open and read-lock the select table
1746
and then create, open and write-lock the new table. If a global
1747
read lock steps in, we get a deadlock. The write lock waits for
1748
the global read lock, while the global read lock waits for the
1749
select table to be closed. So we wait until the global readlock is
1750
gone before starting both steps. Note that
1751
wait_if_global_read_lock() sets a protection against a new global
1752
read lock when it succeeds. This needs to be released by
1753
start_waiting_global_read_lock(). We protect the normal CREATE
1754
TABLE in the same way. That way we avoid that a new table is
1755
created during a gobal read lock.
1757
if (!thd->locked_tables &&
1758
!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
1761
goto end_with_restore_list;
1763
if (select_lex->item_list.elements) // With select
1765
select_result *result;
1767
select_lex->options|= SELECT_NO_UNLOCK;
1768
unit->set_limit(select_lex);
1771
Disable non-empty MERGE tables with CREATE...SELECT. Too
1772
complicated. See Bug #26379. Empty MERGE tables are read-only
1773
and don't allow CREATE...SELECT anyway.
1775
if (create_info.used_fields & HA_CREATE_USED_UNION)
1777
my_error(ER_WRONG_OBJECT, MYF(0), create_table->db,
1778
create_table->table_name, "BASE TABLE");
1780
goto end_with_restore_list;
1783
if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1785
lex->link_first_table_back(create_table, link_to_local);
1786
create_table->create= TRUE;
1789
if (!(res= open_and_lock_tables(thd, lex->query_tables)))
1792
Is table which we are changing used somewhere in other parts
1795
if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1797
TABLE_LIST *duplicate;
1798
create_table= lex->unlink_first_table(&link_to_local);
1799
if ((duplicate= unique_table(thd, create_table, select_tables, 0)))
1801
update_non_unique_table_error(create_table, "CREATE", duplicate);
1803
goto end_with_restore_list;
1806
/* If we create merge table, we have to test tables in merge, too */
1807
if (create_info.used_fields & HA_CREATE_USED_UNION)
1810
for (tab= (TABLE_LIST*) create_info.merge_list.first;
1812
tab= tab->next_local)
1814
TABLE_LIST *duplicate;
1815
if ((duplicate= unique_table(thd, tab, select_tables, 0)))
1817
update_non_unique_table_error(tab, "CREATE", duplicate);
1819
goto end_with_restore_list;
1825
select_create is currently not re-execution friendly and
1826
needs to be created for every execution of a PS/SP.
1828
if ((result= new select_create(create_table,
1831
select_lex->item_list,
1837
CREATE from SELECT give its SELECT_LEX for SELECT,
1838
and item_list belong to SELECT
1840
res= handle_select(thd, lex, result, 0);
1844
else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1845
create_table= lex->unlink_first_table(&link_to_local);
1850
/* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
1851
if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
1852
thd->options|= OPTION_KEEP_LOG;
1853
/* regular create */
1854
if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
1855
res= mysql_create_like_table(thd, create_table, select_tables,
1859
res= mysql_create_table(thd, create_table->db,
1860
create_table->table_name, &create_info,
1867
/* put tables back for PS rexecuting */
1868
end_with_restore_list:
1869
lex->link_first_table_back(create_table, link_to_local);
1872
case SQLCOM_CREATE_INDEX:
1874
case SQLCOM_DROP_INDEX:
1876
CREATE INDEX and DROP INDEX are implemented by calling ALTER
1877
TABLE with proper arguments.
1879
In the future ALTER TABLE will notice that the request is to
1880
only add indexes and create these one by one for the existing
1881
table without having to do a full rebuild.
1884
/* Prepare stack copies to be re-execution safe */
1885
HA_CREATE_INFO create_info;
1886
Alter_info alter_info(lex->alter_info, thd->mem_root);
1888
if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
1891
DBUG_ASSERT(first_table == all_tables && first_table != 0);
1892
if (end_active_trans(thd))
1895
Currently CREATE INDEX or DROP INDEX cause a full table rebuild
1896
and thus classify as slow administrative statements just like
1899
thd->enable_slow_log= opt_log_slow_admin_statements;
1901
bzero((char*) &create_info, sizeof(create_info));
1902
create_info.db_type= 0;
1903
create_info.row_type= ROW_TYPE_NOT_USED;
1904
create_info.default_table_charset= thd->variables.collation_database;
1906
res= mysql_alter_table(thd, first_table->db, first_table->table_name,
1907
&create_info, first_table, &alter_info,
1911
#ifdef HAVE_REPLICATION
1912
case SQLCOM_SLAVE_START:
1914
pthread_mutex_lock(&LOCK_active_mi);
1915
start_slave(thd,active_mi,1 /* net report*/);
1916
pthread_mutex_unlock(&LOCK_active_mi);
1919
case SQLCOM_SLAVE_STOP:
1921
If the client thread has locked tables, a deadlock is possible.
1923
- the client thread does LOCK TABLE t READ.
1924
- then the master updates t.
1925
- then the SQL slave thread wants to update t,
1926
so it waits for the client thread because t is locked by it.
1927
- then the client thread does SLAVE STOP.
1928
SLAVE STOP waits for the SQL slave thread to terminate its
1929
update t, which waits for the client thread because t is locked by it.
1930
To prevent that, refuse SLAVE STOP if the
1931
client thread has locked tables
1933
if (thd->locked_tables || thd->active_transaction() || thd->global_read_lock)
1935
my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
1936
ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
1940
pthread_mutex_lock(&LOCK_active_mi);
1941
stop_slave(thd,active_mi,1/* net report*/);
1942
pthread_mutex_unlock(&LOCK_active_mi);
1945
#endif /* HAVE_REPLICATION */
1947
case SQLCOM_ALTER_TABLE:
1948
DBUG_ASSERT(first_table == all_tables && first_table != 0);
1951
Code in mysql_alter_table() may modify its HA_CREATE_INFO argument,
1952
so we have to use a copy of this structure to make execution
1953
prepared statement- safe. A shallow copy is enough as no memory
1954
referenced from this structure will be modified.
1956
HA_CREATE_INFO create_info(lex->create_info);
1957
Alter_info alter_info(lex->alter_info, thd->mem_root);
1959
if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */
1964
/* Must be set in the parser */
1965
DBUG_ASSERT(select_lex->db);
1967
{ // Rename of table
1968
TABLE_LIST tmp_table;
1969
bzero((char*) &tmp_table,sizeof(tmp_table));
1970
tmp_table.table_name= lex->name.str;
1971
tmp_table.db=select_lex->db;
1974
/* Don't yet allow changing of symlinks with ALTER TABLE */
1975
if (create_info.data_file_name)
1976
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
1977
"DATA DIRECTORY option ignored");
1978
if (create_info.index_file_name)
1979
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0,
1980
"INDEX DIRECTORY option ignored");
1981
create_info.data_file_name= create_info.index_file_name= NULL;
1982
/* ALTER TABLE ends previous transaction */
1983
if (end_active_trans(thd))
1986
if (!thd->locked_tables &&
1987
!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
1993
thd->enable_slow_log= opt_log_slow_admin_statements;
1994
res= mysql_alter_table(thd, select_lex->db, lex->name.str,
1998
select_lex->order_list.elements,
1999
(ORDER *) select_lex->order_list.first,
2003
case SQLCOM_RENAME_TABLE:
2005
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2007
for (table= first_table; table; table= table->next_local->next_local)
2009
TABLE_LIST old_list, new_list;
2011
we do not need initialize old_list and new_list because we will
2012
come table[0] and table->next[0] there
2015
new_list= table->next_local[0];
2018
if (end_active_trans(thd) || mysql_rename_tables(thd, first_table, 0))
2024
case SQLCOM_SHOW_BINLOGS:
2026
res = show_binlogs(thd);
2029
case SQLCOM_SHOW_CREATE:
2030
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2032
res= mysqld_show_create(thd, first_table);
2035
case SQLCOM_CHECKSUM:
2037
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2038
res = mysql_checksum_table(thd, first_table, &lex->check_opt);
2043
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2044
thd->enable_slow_log= opt_log_slow_admin_statements;
2045
res= mysql_repair_table(thd, first_table, &lex->check_opt);
2046
/* ! we write after unlocking the table */
2047
if (!res && !lex->no_write_to_binlog)
2050
Presumably, REPAIR and binlog writing doesn't require synchronization
2052
write_bin_log(thd, TRUE, thd->query, thd->query_length);
2054
select_lex->table_list.first= (uchar*) first_table;
2055
lex->query_tables=all_tables;
2060
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2061
thd->enable_slow_log= opt_log_slow_admin_statements;
2062
res = mysql_check_table(thd, first_table, &lex->check_opt);
2063
select_lex->table_list.first= (uchar*) first_table;
2064
lex->query_tables=all_tables;
2067
case SQLCOM_ANALYZE:
2069
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2070
thd->enable_slow_log= opt_log_slow_admin_statements;
2071
res= mysql_analyze_table(thd, first_table, &lex->check_opt);
2072
/* ! we write after unlocking the table */
2073
if (!res && !lex->no_write_to_binlog)
2076
Presumably, ANALYZE and binlog writing doesn't require synchronization
2078
write_bin_log(thd, TRUE, thd->query, thd->query_length);
2080
select_lex->table_list.first= (uchar*) first_table;
2081
lex->query_tables=all_tables;
2085
case SQLCOM_OPTIMIZE:
2087
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2088
thd->enable_slow_log= opt_log_slow_admin_statements;
2089
res= (specialflag & (SPECIAL_SAFE_MODE | SPECIAL_NO_NEW_FUNC)) ?
2090
mysql_recreate_table(thd, first_table) :
2091
mysql_optimize_table(thd, first_table, &lex->check_opt);
2092
/* ! we write after unlocking the table */
2093
if (!res && !lex->no_write_to_binlog)
2096
Presumably, OPTIMIZE and binlog writing doesn't require synchronization
2098
write_bin_log(thd, TRUE, thd->query, thd->query_length);
2100
select_lex->table_list.first= (uchar*) first_table;
2101
lex->query_tables=all_tables;
2105
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2106
if (update_precheck(thd, all_tables))
2108
DBUG_ASSERT(select_lex->offset_limit == 0);
2109
unit->set_limit(select_lex);
2110
res= (up_result= mysql_update(thd, all_tables,
2111
select_lex->item_list,
2114
select_lex->order_list.elements,
2115
(ORDER *) select_lex->order_list.first,
2116
unit->select_limit_cnt,
2117
lex->duplicates, lex->ignore));
2118
/* mysql_update return 2 if we need to switch to multi-update */
2122
case SQLCOM_UPDATE_MULTI:
2124
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2125
/* if we switched from normal update, rights are checked */
2128
if ((res= multi_update_precheck(thd, all_tables)))
2134
res= mysql_multi_update_prepare(thd);
2136
#ifdef HAVE_REPLICATION
2137
/* Check slave filtering rules */
2138
if (unlikely(thd->slave_thread))
2140
if (all_tables_not_ok(thd, all_tables))
2144
res= 0; /* don't care of prev failure */
2145
thd->clear_error(); /* filters are of highest prior */
2147
/* we warn the slave SQL thread */
2148
my_error(ER_SLAVE_IGNORED_TABLE, MYF(0));
2156
#endif /* HAVE_REPLICATION */
2160
some_non_temp_table_to_be_updated(thd, all_tables))
2162
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
2165
#ifdef HAVE_REPLICATION
2169
res= mysql_multi_update(thd, all_tables,
2170
&select_lex->item_list,
2173
select_lex->options,
2174
lex->duplicates, lex->ignore, unit, select_lex);
2177
case SQLCOM_REPLACE:
2179
if (mysql_bin_log.is_open())
2182
Generate an incident log event before writing the real event
2183
to the binary log. We put this event is before the statement
2184
since that makes it simpler to check that the statement was
2185
not executed on the slave (since incidents usually stop the
2188
Observe that any row events that are generated will be
2191
This is only for testing purposes and will not be present in a
2195
Incident incident= INCIDENT_NONE;
2196
DBUG_PRINT("debug", ("Just before generate_incident()"));
2197
DBUG_EXECUTE_IF("incident_database_resync_on_replace",
2198
incident= INCIDENT_LOST_EVENTS;);
2201
Incident_log_event ev(thd, incident);
2202
mysql_bin_log.write(&ev);
2203
mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
2205
DBUG_PRINT("debug", ("Just after generate_incident()"));
2210
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2211
if ((res= insert_precheck(thd, all_tables)))
2214
if (!thd->locked_tables &&
2215
!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2221
res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
2222
lex->update_list, lex->value_list,
2223
lex->duplicates, lex->ignore);
2227
case SQLCOM_REPLACE_SELECT:
2228
case SQLCOM_INSERT_SELECT:
2230
select_result *sel_result;
2231
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2232
if ((res= insert_precheck(thd, all_tables)))
2235
/* Fix lock for first table */
2236
if (first_table->lock_type == TL_WRITE_DELAYED)
2237
first_table->lock_type= TL_WRITE;
2239
/* Don't unlock tables until command is written to binary log */
2240
select_lex->options|= SELECT_NO_UNLOCK;
2242
unit->set_limit(select_lex);
2244
if (! thd->locked_tables &&
2245
! (need_start_waiting= ! wait_if_global_read_lock(thd, 0, 1)))
2251
if (!(res= open_and_lock_tables(thd, all_tables)))
2253
/* Skip first table, which is the table we are inserting in */
2254
TABLE_LIST *second_table= first_table->next_local;
2255
select_lex->table_list.first= (uchar*) second_table;
2256
select_lex->context.table_list=
2257
select_lex->context.first_name_resolution_table= second_table;
2258
res= mysql_insert_select_prepare(thd);
2259
if (!res && (sel_result= new select_insert(first_table,
2267
res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
2269
Invalidate the table in the query cache if something changed
2270
after unlocking when changes become visible.
2271
TODO: this is workaround. right way will be move invalidating in
2272
the unlock procedure.
2274
if (first_table->lock_type == TL_WRITE_CONCURRENT_INSERT &&
2277
/* INSERT ... SELECT should invalidate only the very first table */
2278
TABLE_LIST *save_table= first_table->next_local;
2279
first_table->next_local= 0;
2280
first_table->next_local= save_table;
2284
/* revert changes for SP */
2285
select_lex->table_list.first= (uchar*) first_table;
2290
case SQLCOM_TRUNCATE:
2291
if (end_active_trans(thd))
2296
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2298
Don't allow this within a transaction because we want to use
2301
if (thd->locked_tables || thd->active_transaction())
2303
my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2304
ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2308
res= mysql_truncate(thd, first_table, 0);
2313
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2314
DBUG_ASSERT(select_lex->offset_limit == 0);
2315
unit->set_limit(select_lex);
2317
if (!thd->locked_tables &&
2318
!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2324
res = mysql_delete(thd, all_tables, select_lex->where,
2325
&select_lex->order_list,
2326
unit->select_limit_cnt, select_lex->options,
2330
case SQLCOM_DELETE_MULTI:
2332
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2333
TABLE_LIST *aux_tables=
2334
(TABLE_LIST *)thd->lex->auxiliary_table_list.first;
2335
multi_delete *del_result;
2337
if (!thd->locked_tables &&
2338
!(need_start_waiting= !wait_if_global_read_lock(thd, 0, 1)))
2344
if ((res= multi_delete_precheck(thd, all_tables)))
2347
/* condition will be TRUE on SP re-excuting */
2348
if (select_lex->item_list.elements != 0)
2349
select_lex->item_list.empty();
2350
if (add_item_to_list(thd, new Item_null()))
2353
thd_proc_info(thd, "init");
2354
if ((res= open_and_lock_tables(thd, all_tables)))
2357
if ((res= mysql_multi_delete_prepare(thd)))
2360
if (!thd->is_fatal_error &&
2361
(del_result= new multi_delete(aux_tables, lex->table_count)))
2363
res= mysql_select(thd, &select_lex->ref_pointer_array,
2364
select_lex->get_table_list(),
2365
select_lex->with_wild,
2366
select_lex->item_list,
2368
0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL,
2370
select_lex->options | thd->options |
2371
SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
2372
OPTION_SETUP_TABLES_DONE,
2373
del_result, unit, select_lex);
2374
res|= thd->is_error();
2376
del_result->abort();
2383
case SQLCOM_DROP_TABLE:
2385
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2386
if (!lex->drop_temporary)
2388
if (end_active_trans(thd))
2394
If this is a slave thread, we may sometimes execute some
2395
DROP / * 40005 TEMPORARY * / TABLE
2396
that come from parts of binlogs (likely if we use RESET SLAVE or CHANGE
2397
MASTER TO), while the temporary table has already been dropped.
2398
To not generate such irrelevant "table does not exist errors",
2399
we silently add IF EXISTS if TEMPORARY was used.
2401
if (thd->slave_thread)
2402
lex->drop_if_exists= 1;
2404
/* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
2405
thd->options|= OPTION_KEEP_LOG;
2407
/* DDL and binlog write order protected by LOCK_open */
2408
res= mysql_rm_table(thd, first_table, lex->drop_if_exists,
2409
lex->drop_temporary);
2412
case SQLCOM_SHOW_PROCESSLIST:
2413
mysqld_list_processes(thd, NullS, lex->verbose);
2415
case SQLCOM_SHOW_ENGINE_LOGS:
2417
res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
2420
case SQLCOM_CHANGE_DB:
2422
LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };
2424
if (!mysql_change_db(thd, &db_str, FALSE))
2432
DBUG_ASSERT(first_table == all_tables && first_table != 0);
2433
if (lex->local_file)
2435
if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
2438
my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
2443
res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
2444
lex->update_list, lex->value_list, lex->duplicates,
2445
lex->ignore, (bool) lex->local_file);
2449
case SQLCOM_SET_OPTION:
2451
List<set_var_base> *lex_var_list= &lex->var_list;
2453
if (lex->autocommit && end_active_trans(thd))
2456
if (open_and_lock_tables(thd, all_tables))
2458
if (lex->one_shot_set && not_all_support_one_shot(lex_var_list))
2460
my_error(ER_RESERVED_SYNTAX, MYF(0), "SET ONE_SHOT");
2463
if (!(res= sql_set_variables(thd, lex_var_list)))
2466
If the previous command was a SET ONE_SHOT, we don't want to forget
2467
about the ONE_SHOT property of that SET. So we use a |= instead of = .
2469
thd->one_shot_set|= lex->one_shot_set;
2475
We encountered some sort of error, but no message was sent.
2476
Send something semi-generic here since we don't know which
2477
assignment in the list caused the error.
2479
if (!thd->is_error())
2480
my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
2487
case SQLCOM_UNLOCK_TABLES:
2489
It is critical for mysqldump --single-transaction --master-data that
2490
UNLOCK TABLES does not implicitely commit a connection which has only
2491
done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
2492
false, mysqldump will not work.
2494
unlock_locked_tables(thd);
2495
if (thd->options & OPTION_TABLE_LOCK)
2497
end_active_trans(thd);
2498
thd->options&= ~(OPTION_TABLE_LOCK);
2500
if (thd->global_read_lock)
2501
unlock_global_read_lock(thd);
2504
case SQLCOM_LOCK_TABLES:
2506
We try to take transactional locks if
2507
- only transactional locks are requested (lex->lock_transactional) and
2508
- no non-transactional locks exist (!thd->locked_tables).
2510
DBUG_PRINT("lock_info", ("lex->lock_transactional: %d "
2511
"thd->locked_tables: 0x%lx",
2512
lex->lock_transactional,
2513
(long) thd->locked_tables));
2514
if (lex->lock_transactional && !thd->locked_tables)
2518
All requested locks are transactional and no non-transactional
2521
if ((rc= try_transactional_lock(thd, all_tables)) == -1)
2529
Non-transactional locking has been requested or
2530
non-transactional locks exist already or transactional locks are
2531
not supported by all storage engines. Take non-transactional
2536
One or more requested locks are non-transactional and/or
2537
non-transactional locks exist or a storage engine does not support
2538
transactional locks. Check if at least one transactional lock is
2539
requested. If yes, warn about the conversion to non-transactional
2540
locks or abort in strict mode.
2542
if (check_transactional_lock(thd, all_tables))
2544
unlock_locked_tables(thd);
2545
/* we must end the trasaction first, regardless of anything */
2546
if (end_active_trans(thd))
2548
thd->in_lock_tables=1;
2549
thd->options|= OPTION_TABLE_LOCK;
2551
if (!(res= simple_open_n_lock_tables(thd, all_tables)))
2553
thd->locked_tables=thd->lock;
2555
(void) set_handler_table_locks(thd, all_tables, FALSE);
2556
DBUG_PRINT("lock_info", ("thd->locked_tables: 0x%lx",
2557
(long) thd->locked_tables));
2563
Need to end the current transaction, so the storage engine (InnoDB)
2564
can free its locks if LOCK TABLES locked some tables before finding
2565
that it can't lock a table in its list
2567
ha_autocommit_or_rollback(thd, 1);
2568
end_active_trans(thd);
2569
thd->options&= ~(OPTION_TABLE_LOCK);
2571
thd->in_lock_tables=0;
2573
case SQLCOM_CREATE_DB:
2576
As mysql_create_db() may modify HA_CREATE_INFO structure passed to
2577
it, we need to use a copy of LEX::create_info to make execution
2578
prepared statement- safe.
2580
HA_CREATE_INFO create_info(lex->create_info);
2581
if (end_active_trans(thd))
2587
if (!(alias=thd->strmake(lex->name.str, lex->name.length)) ||
2588
check_db_name(&lex->name))
2590
my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
2594
If in a slave thread :
2595
CREATE DATABASE DB was certainly not preceded by USE DB.
2596
For that reason, db_ok() in sql/slave.cc did not check the
2597
do_db/ignore_db. And as this query involves no tables, tables_ok()
2598
above was not called. So we have to check rules again here.
2600
if (thd->slave_thread &&
2601
(!rpl_filter->db_ok(lex->name.str) ||
2602
!rpl_filter->db_ok_with_wild_table(lex->name.str)))
2604
my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2607
res= mysql_create_db(thd,(lower_case_table_names == 2 ? alias :
2608
lex->name.str), &create_info, 0);
2611
case SQLCOM_DROP_DB:
2613
if (end_active_trans(thd))
2618
if (check_db_name(&lex->name))
2620
my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
2624
If in a slave thread :
2625
DROP DATABASE DB may not be preceded by USE DB.
2626
For that reason, maybe db_ok() in sql/slave.cc did not check the
2627
do_db/ignore_db. And as this query involves no tables, tables_ok()
2628
above was not called. So we have to check rules again here.
2630
#ifdef HAVE_REPLICATION
2631
if (thd->slave_thread &&
2632
(!rpl_filter->db_ok(lex->name.str) ||
2633
!rpl_filter->db_ok_with_wild_table(lex->name.str)))
2635
my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2639
if (thd->locked_tables || thd->active_transaction())
2641
my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2642
ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2645
res= mysql_rm_db(thd, lex->name.str, lex->drop_if_exists, 0);
2648
case SQLCOM_ALTER_DB_UPGRADE:
2650
LEX_STRING *db= & lex->name;
2651
if (end_active_trans(thd))
2656
#ifdef HAVE_REPLICATION
2657
if (thd->slave_thread &&
2658
(!rpl_filter->db_ok(db->str) ||
2659
!rpl_filter->db_ok_with_wild_table(db->str)))
2662
my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2666
if (check_db_name(db))
2668
my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
2671
if (thd->locked_tables || thd->active_transaction())
2674
my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2675
ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2679
res= mysql_upgrade_db(thd, db);
2684
case SQLCOM_ALTER_DB:
2686
LEX_STRING *db= &lex->name;
2687
HA_CREATE_INFO create_info(lex->create_info);
2688
if (check_db_name(db))
2690
my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
2694
If in a slave thread :
2695
ALTER DATABASE DB may not be preceded by USE DB.
2696
For that reason, maybe db_ok() in sql/slave.cc did not check the
2697
do_db/ignore_db. And as this query involves no tables, tables_ok()
2698
above was not called. So we have to check rules again here.
2700
#ifdef HAVE_REPLICATION
2701
if (thd->slave_thread &&
2702
(!rpl_filter->db_ok(db->str) ||
2703
!rpl_filter->db_ok_with_wild_table(db->str)))
2705
my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0));
2709
if (thd->locked_tables || thd->active_transaction())
2711
my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
2712
ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
2715
res= mysql_alter_db(thd, db->str, &create_info);
2718
case SQLCOM_SHOW_CREATE_DB:
2720
DBUG_EXECUTE_IF("4x_server_emul",
2721
my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;);
2722
if (check_db_name(&lex->name))
2724
my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
2727
res= mysqld_show_create_db(thd, lex->name.str, &lex->create_info);
2732
RESET commands are never written to the binary log, so we have to
2733
initialize this variable because RESET shares the same code as FLUSH
2735
lex->no_write_to_binlog= 1;
2738
bool write_to_binlog;
2741
reload_cache() will tell us if we are allowed to write to the
2744
if (!reload_cache(thd, lex->type, first_table, &write_to_binlog))
2747
We WANT to write and we CAN write.
2748
! we write after unlocking the table.
2751
Presumably, RESET and binlog writing doesn't require synchronization
2753
if (!lex->no_write_to_binlog && write_to_binlog)
2755
write_bin_log(thd, FALSE, thd->query, thd->query_length);
2764
Item *it= (Item *)lex->value_list.head();
2766
if (lex->table_or_sp_used())
2768
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored "
2769
"function calls as part of this statement");
2773
if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1))
2775
my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
2779
sql_kill(thd, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
2783
if (thd->transaction.xid_state.xa_state != XA_NOTR)
2785
my_error(ER_XAER_RMFAIL, MYF(0),
2786
xa_state_names[thd->transaction.xid_state.xa_state]);
2790
Breakpoints for backup testing.
2792
if (begin_trans(thd))
2797
if (end_trans(thd, lex->tx_release ? COMMIT_RELEASE :
2798
lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
2802
case SQLCOM_ROLLBACK:
2803
if (end_trans(thd, lex->tx_release ? ROLLBACK_RELEASE :
2804
lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
2808
case SQLCOM_RELEASE_SAVEPOINT:
2811
for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
2813
if (my_strnncoll(system_charset_info,
2814
(uchar *)lex->ident.str, lex->ident.length,
2815
(uchar *)sv->name, sv->length) == 0)
2820
if (ha_release_savepoint(thd, sv))
2821
res= TRUE; // cannot happen
2824
thd->transaction.savepoints=sv->prev;
2827
my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
2830
case SQLCOM_ROLLBACK_TO_SAVEPOINT:
2833
for (sv=thd->transaction.savepoints; sv; sv=sv->prev)
2835
if (my_strnncoll(system_charset_info,
2836
(uchar *)lex->ident.str, lex->ident.length,
2837
(uchar *)sv->name, sv->length) == 0)
2842
if (ha_rollback_to_savepoint(thd, sv))
2843
res= TRUE; // cannot happen
2846
if (((thd->options & OPTION_KEEP_LOG) ||
2847
thd->transaction.all.modified_non_trans_table) &&
2849
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
2850
ER_WARNING_NOT_COMPLETE_ROLLBACK,
2851
ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
2854
thd->transaction.savepoints=sv;
2857
my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
2860
case SQLCOM_SAVEPOINT:
2861
if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN) ||
2862
thd->in_sub_stmt) || !opt_using_transactions)
2866
SAVEPOINT **sv, *newsv;
2867
for (sv=&thd->transaction.savepoints; *sv; sv=&(*sv)->prev)
2869
if (my_strnncoll(system_charset_info,
2870
(uchar *)lex->ident.str, lex->ident.length,
2871
(uchar *)(*sv)->name, (*sv)->length) == 0)
2874
if (*sv) /* old savepoint of the same name exists */
2877
ha_release_savepoint(thd, *sv); // it cannot fail
2880
else if ((newsv=(SAVEPOINT *) alloc_root(&thd->transaction.mem_root,
2881
savepoint_alloc_size)) == 0)
2883
my_error(ER_OUT_OF_RESOURCES, MYF(0));
2886
newsv->name=strmake_root(&thd->transaction.mem_root,
2887
lex->ident.str, lex->ident.length);
2888
newsv->length=lex->ident.length;
2890
if we'll get an error here, don't add new savepoint to the list.
2891
we'll lose a little bit of memory in transaction mem_root, but it'll
2892
be free'd when transaction ends anyway
2894
if (ha_savepoint(thd, newsv))
2898
newsv->prev=thd->transaction.savepoints;
2899
thd->transaction.savepoints=newsv;
2904
case SQLCOM_BINLOG_BASE64_EVENT:
2906
mysql_client_binlog_statement(thd);
2910
DBUG_ASSERT(0); /* Impossible */
2914
thd_proc_info(thd, "query end");
2917
Binlog-related cleanup:
2918
Reset system variables temporarily modified by SET ONE SHOT.
2920
Exception: If this is a SET, do nothing. This is to allow
2921
mysqlbinlog to print many SET commands (in this case we want the
2922
charset temp setting to live until the real query). This is also
2923
needed so that SET CHARACTER_SET_CLIENT... does not cancel itself
2926
if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION)
2927
reset_one_shot_variables(thd);
2930
The return value for ROW_COUNT() is "implementation dependent" if the
2931
statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
2932
wants. We also keep the last value in case of SQLCOM_CALL or
2935
if (!(sql_command_flags[lex->sql_command] & CF_HAS_ROW_COUNT))
2936
thd->row_count_func= -1;
2944
if (need_start_waiting)
2947
Release the protection against the global read lock and wake
2948
everyone, who might want to set a global read lock.
2950
start_waiting_global_read_lock(thd);
2952
DBUG_RETURN(res || thd->is_error());
2956
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
2959
select_result *result=lex->result;
2961
/* assign global limit variable if limit is not given */
2963
SELECT_LEX *param= lex->unit.global_parameters;
2964
if (!param->explicit_limit)
2965
param->select_limit=
2966
new Item_int((ulonglong) thd->variables.select_limit);
2968
if (!(res= open_and_lock_tables(thd, all_tables)))
2973
We always use select_send for EXPLAIN, even if it's an EXPLAIN
2974
for SELECT ... INTO OUTFILE: a user application should be able
2975
to prepend EXPLAIN to any query and receive output for it,
2976
even if the query itself redirects the output.
2978
if (!(result= new select_send()))
2979
return 1; /* purecov: inspected */
2980
thd->send_explain_fields(result);
2981
res= mysql_explain_union(thd, &thd->lex->unit, result);
2982
if (lex->describe & DESCRIBE_EXTENDED)
2985
String str(buff,(uint32) sizeof(buff), system_charset_info);
2987
thd->lex->unit.print(&str, QT_ORDINARY);
2989
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
3000
if (!result && !(result= new select_send()))
3001
return 1; /* purecov: inspected */
3002
res= handle_select(thd, lex, result, 0);
3003
if (result != lex->result)
3010
/****************************************************************************
3011
Check stack size; Send error if there isn't enough stack to continue
3012
****************************************************************************/
3013
#if STACK_DIRECTION < 0
3014
#define used_stack(A,B) (long) (A - B)
3016
#define used_stack(A,B) (long) (B - A)
3020
long max_stack_used;
3025
Note: The 'buf' parameter is necessary, even if it is unused here.
3026
- fix_fields functions has a "dummy" buffer large enough for the
3027
corresponding exec. (Thus we only have to check in fix_fields.)
3028
- Passing to check_stack_overrun() prevents the compiler from removing it.
3030
bool check_stack_overrun(THD *thd, long margin,
3031
uchar *buf __attribute__((unused)))
3034
DBUG_ASSERT(thd == current_thd);
3035
if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
3036
(long) (my_thread_stack_size - margin))
3038
sprintf(errbuff[0],ER(ER_STACK_OVERRUN_NEED_MORE),
3039
stack_used,my_thread_stack_size,margin);
3040
my_message(ER_STACK_OVERRUN_NEED_MORE,errbuff[0],MYF(ME_FATALERROR));
3044
max_stack_used= max(max_stack_used, stack_used);
3049
#define MY_YACC_INIT 1000 // Start with big alloc
3050
#define MY_YACC_MAX 32000 // Because of 'short'
3052
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
3054
LEX *lex= current_thd->lex;
3056
if ((uint) *yystacksize >= MY_YACC_MAX)
3058
if (!lex->yacc_yyvs)
3059
old_info= *yystacksize;
3060
*yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
3061
if (!(lex->yacc_yyvs= (uchar*)
3062
my_realloc(lex->yacc_yyvs,
3063
*yystacksize*sizeof(**yyvs),
3064
MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
3065
!(lex->yacc_yyss= (uchar*)
3066
my_realloc(lex->yacc_yyss,
3067
*yystacksize*sizeof(**yyss),
3068
MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
3071
{ // Copy old info from stack
3072
memcpy(lex->yacc_yyss, (uchar*) *yyss, old_info*sizeof(**yyss));
3073
memcpy(lex->yacc_yyvs, (uchar*) *yyvs, old_info*sizeof(**yyvs));
3075
*yyss=(short*) lex->yacc_yyss;
3076
*yyvs=(YYSTYPE*) lex->yacc_yyvs;
3082
Reset THD part responsible for command processing state.
3084
This needs to be called before execution of every statement
3085
(prepared or conventional).
3086
It is not called by substatements of routines.
3089
Make it a method of THD and align its name with the rest of
3090
reset/end/start/init methods.
3092
Call it after we use THD for queries, not before.
3095
void mysql_reset_thd_for_next_command(THD *thd)
3097
DBUG_ENTER("mysql_reset_thd_for_next_command");
3098
DBUG_ASSERT(! thd->in_sub_stmt);
3100
thd->select_number= 1;
3102
Those two lines below are theoretically unneeded as
3103
THD::cleanup_after_query() should take care of this already.
3105
thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
3106
thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
3108
thd->query_start_used= 0;
3109
thd->is_fatal_error= thd->time_zone_used= 0;
3110
thd->server_status&= ~ (SERVER_MORE_RESULTS_EXISTS |
3111
SERVER_QUERY_NO_INDEX_USED |
3112
SERVER_QUERY_NO_GOOD_INDEX_USED);
3114
If in autocommit mode and not in a transaction, reset
3115
OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings
3116
in ha_rollback_trans() about some tables couldn't be rolled back.
3118
if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
3120
thd->options&= ~OPTION_KEEP_LOG;
3121
thd->transaction.all.modified_non_trans_table= FALSE;
3123
DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx);
3124
thd->thread_specific_used= FALSE;
3128
reset_dynamic(&thd->user_var_events);
3129
thd->user_var_events_alloc= thd->mem_root;
3132
thd->main_da.reset_diagnostics_area();
3133
thd->total_warn_count=0; // Warnings for this query
3135
thd->sent_row_count= thd->examined_row_count= 0;
3138
Because we come here only for start of top-statements, binlog format is
3139
constant inside a complex statement (using stored functions) etc.
3141
thd->reset_current_stmt_binlog_row_based();
3148
mysql_init_select(LEX *lex)
3150
SELECT_LEX *select_lex= lex->current_select;
3151
select_lex->init_select();
3153
if (select_lex == &lex->select_lex)
3155
DBUG_ASSERT(lex->result == 0);
3162
mysql_new_select(LEX *lex, bool move_down)
3164
SELECT_LEX *select_lex;
3166
DBUG_ENTER("mysql_new_select");
3168
if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
3170
select_lex->select_number= ++thd->select_number;
3171
select_lex->parent_lex= lex; /* Used in init_query. */
3172
select_lex->init_query();
3173
select_lex->init_select();
3175
if (lex->nest_level > (int) MAX_SELECT_NESTING)
3177
my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
3180
select_lex->nest_level= lex->nest_level;
3183
SELECT_LEX_UNIT *unit;
3184
lex->subqueries= TRUE;
3185
/* first select_lex of subselect or derived table */
3186
if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT()))
3190
unit->init_select();
3192
unit->include_down(lex->current_select);
3195
unit->return_to= lex->current_select;
3196
select_lex->include_down(unit);
3198
By default we assume that it is usual subselect and we have outer name
3199
resolution context, if no we will assign it to 0 later
3201
select_lex->context.outer_context= &select_lex->outer_select()->context;
3205
if (lex->current_select->order_list.first && !lex->current_select->braces)
3207
my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY");
3210
select_lex->include_neighbour(lex->current_select);
3211
SELECT_LEX_UNIT *unit= select_lex->master_unit();
3212
if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
3214
select_lex->context.outer_context=
3215
unit->first_select()->context.outer_context;
3218
select_lex->master_unit()->global_parameters= select_lex;
3219
select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
3220
lex->current_select= select_lex;
3222
in subquery is SELECT query and we allow resolution of names in SELECT
3225
select_lex->context.resolve_in_select_list= TRUE;
3230
Create a select to return the same output as 'SELECT @@var_name'.
3232
Used for SHOW COUNT(*) [ WARNINGS | ERROR].
3234
This will crash with a core dump if the variable doesn't exists.
3236
@param var_name Variable name
3239
void create_select_for_variable(const char *var_name)
3243
LEX_STRING tmp, null_lex_string;
3245
char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
3246
DBUG_ENTER("create_select_for_variable");
3250
mysql_init_select(lex);
3251
lex->sql_command= SQLCOM_SELECT;
3252
tmp.str= (char*) var_name;
3253
tmp.length=strlen(var_name);
3254
bzero((char*) &null_lex_string.str, sizeof(null_lex_string));
3256
We set the name of Item to @@session.var_name because that then is used
3257
as the column name in the output.
3259
if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string)))
3261
end= strxmov(buff, "@@session.", var_name, NullS);
3262
var->set_name(buff, end-buff, system_charset_info);
3263
add_item_to_list(thd, var);
3269
void mysql_init_multi_delete(LEX *lex)
3271
lex->sql_command= SQLCOM_DELETE_MULTI;
3272
mysql_init_select(lex);
3273
lex->select_lex.select_limit= 0;
3274
lex->unit.select_limit_cnt= HA_POS_ERROR;
3275
lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
3276
lex->lock_option= using_update_log ? TL_READ_NO_INSERT : TL_READ;
3277
lex->query_tables= 0;
3278
lex->query_tables_last= &lex->query_tables;
3283
When you modify mysql_parse(), you may need to mofify
3284
mysql_test_parse_for_slave() in this same file.
3290
@param thd Current thread
3291
@param inBuf Begining of the query text
3292
@param length Length of the query text
3293
@param[out] found_semicolon For multi queries, position of the character of
3294
the next query in the query text.
3297
void mysql_parse(THD *thd, const char *inBuf, uint length,
3298
const char ** found_semicolon)
3300
DBUG_ENTER("mysql_parse");
3302
DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on(););
3306
The purpose of query_cache_send_result_to_client() is to lookup the
3307
query in the query cache first, to avoid parsing and executing it.
3308
So, the natural implementation would be to:
3309
- first, call query_cache_send_result_to_client,
3310
- second, if caching failed, initialise the lexical and syntactic parser.
3311
The problem is that the query cache depends on a clean initialization
3312
of (among others) lex->safe_to_cache_query and thd->server_status,
3313
which are reset respectively in
3315
- mysql_reset_thd_for_next_command()
3316
So, initializing the lexical analyser *before* using the query cache
3317
is required for the cache to work properly.
3318
FIXME: cleanup the dependencies in the code to simplify this.
3321
mysql_reset_thd_for_next_command(thd);
3326
Lex_input_stream lip(thd, inBuf, length);
3328
bool err= parse_sql(thd, &lip, NULL);
3329
*found_semicolon= lip.found_semicolon;
3334
if (! thd->is_error())
3337
Binlog logs a string starting from thd->query and having length
3338
thd->query_length; so we set thd->query_length correctly (to not
3339
log several statements in one event, when we executed only first).
3340
We set it to not see the ';' (otherwise it would get into binlog
3341
and Query_log_event::print() would give ';;' output).
3342
This also helps display only the current query in SHOW
3344
Note that we don't need LOCK_thread_count to modify query_length.
3346
if (*found_semicolon &&
3347
(thd->query_length= (ulong)(*found_semicolon - thd->query)))
3348
thd->query_length--;
3349
/* Actually execute the query */
3350
mysql_execute_command(thd);
3356
DBUG_ASSERT(thd->is_error());
3357
DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
3358
thd->is_fatal_error));
3360
lex->unit.cleanup();
3361
thd_proc_info(thd, "freeing items");
3362
thd->end_statement();
3363
thd->cleanup_after_query();
3364
DBUG_ASSERT(thd->change_list.is_empty());
3371
#ifdef HAVE_REPLICATION
3373
Usable by the replication SQL thread only: just parse a query to know if it
3374
can be ignored because of replicate-*-table rules.
3382
bool mysql_test_parse_for_slave(THD *thd, char *inBuf, uint length)
3386
DBUG_ENTER("mysql_test_parse_for_slave");
3388
Lex_input_stream lip(thd, inBuf, length);
3390
mysql_reset_thd_for_next_command(thd);
3392
if (!parse_sql(thd, &lip, NULL) &&
3393
all_tables_not_ok(thd,(TABLE_LIST*) lex->select_lex.table_list.first))
3394
error= 1; /* Ignore question */
3395
thd->end_statement();
3396
thd->cleanup_after_query();
3404
Store field definition for create.
3410
bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type,
3411
char *length, char *decimals,
3413
enum ha_storage_media storage_type,
3414
enum column_format_type column_format,
3415
Item *default_value, Item *on_update_value,
3416
LEX_STRING *comment,
3418
List<String> *interval_list, CHARSET_INFO *cs)
3420
register Create_field *new_field;
3422
DBUG_ENTER("add_field_to_list");
3424
if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
3425
DBUG_RETURN(1); /* purecov: inspected */
3427
if (type_modifier & PRI_KEY_FLAG)
3430
lex->col_list.push_back(new Key_part_spec(*field_name, 0));
3431
key= new Key(Key::PRIMARY, null_lex_str,
3432
&default_key_create_info,
3434
lex->alter_info.key_list.push_back(key);
3435
lex->col_list.empty();
3437
if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
3440
lex->col_list.push_back(new Key_part_spec(*field_name, 0));
3441
key= new Key(Key::UNIQUE, null_lex_str,
3442
&default_key_create_info, 0,
3444
lex->alter_info.key_list.push_back(key);
3445
lex->col_list.empty();
3451
Default value should be literal => basic constants =>
3452
no need fix_fields()
3454
We allow only one function as part of default value -
3455
NOW() as default for TIMESTAMP type.
3457
if (default_value->type() == Item::FUNC_ITEM &&
3458
!(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
3459
type == MYSQL_TYPE_TIMESTAMP))
3461
my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
3464
else if (default_value->type() == Item::NULL_ITEM)
3467
if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
3470
my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
3474
else if (type_modifier & AUTO_INCREMENT_FLAG)
3476
my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
3481
if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
3483
my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
3487
if (!(new_field= new Create_field()) ||
3488
new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
3489
default_value, on_update_value, comment, change,
3490
interval_list, cs, 0,
3491
storage_type, column_format))
3494
lex->alter_info.create_list.push_back(new_field);
3495
lex->last_field=new_field;
3500
/** Store position for column in ALTER TABLE .. ADD column. */
3502
void store_position_for_column(const char *name)
3504
current_thd->lex->last_field->after=my_const_cast(char*) (name);
3508
add_proc_to_list(THD* thd, Item *item)
3513
if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*))))
3515
item_ptr = (Item**) (order+1);
3517
order->item=item_ptr;
3519
thd->lex->proc_list.link_in_list((uchar*) order,(uchar**) &order->next);
3525
save order by and tables in own lists.
3528
bool add_to_list(THD *thd, SQL_LIST &list,Item *item,bool asc)
3531
DBUG_ENTER("add_to_list");
3532
if (!(order = (ORDER *) thd->alloc(sizeof(ORDER))))
3534
order->item_ptr= item;
3535
order->item= &order->item_ptr;
3539
order->counter_used= 0;
3540
list.link_in_list((uchar*) order,(uchar**) &order->next);
3546
Add a table to list of used tables.
3548
@param table Table to add
3549
@param alias alias for table (or null if no alias)
3550
@param table_options A set of the following bits:
3551
- TL_OPTION_UPDATING : Table will be updated
3552
- TL_OPTION_FORCE_INDEX : Force usage of index
3553
- TL_OPTION_ALIAS : an alias in multi table DELETE
3554
@param lock_type How table should be locked
3555
@param use_index List of indexed used in USE INDEX
3556
@param ignore_index List of indexed used in IGNORE INDEX
3561
\# Pointer to TABLE_LIST element added to the total table list
3564
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
3567
ulong table_options,
3568
thr_lock_type lock_type,
3569
List<Index_hint> *index_hints_arg,
3572
register TABLE_LIST *ptr;
3573
TABLE_LIST *previous_table_ref; /* The table preceding the current one. */
3576
DBUG_ENTER("add_table_to_list");
3579
DBUG_RETURN(0); // End of memory
3580
alias_str= alias ? alias->str : table->table.str;
3581
if (!test(table_options & TL_OPTION_ALIAS) &&
3582
check_table_name(table->table.str, table->table.length))
3584
my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
3588
if (table->is_derived_table() == FALSE && table->db.str &&
3589
check_db_name(&table->db))
3591
my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
3595
if (!alias) /* Alias is case sensitive */
3599
my_message(ER_DERIVED_MUST_HAVE_ALIAS,
3600
ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
3603
if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1)))
3606
if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST))))
3607
DBUG_RETURN(0); /* purecov: inspected */
3611
ptr->db= table->db.str;
3612
ptr->db_length= table->db.length;
3614
else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
3617
ptr->is_fqtn= FALSE;
3619
ptr->alias= alias_str;
3620
ptr->is_alias= alias ? TRUE : FALSE;
3621
if (lower_case_table_names && table->table.length)
3622
table->table.length= my_casedn_str(files_charset_info, table->table.str);
3623
ptr->table_name=table->table.str;
3624
ptr->table_name_length=table->table.length;
3625
ptr->lock_type= lock_type;
3626
ptr->lock_timeout= -1; /* default timeout */
3627
ptr->lock_transactional= 1; /* allow transactional locks */
3628
ptr->updating= test(table_options & TL_OPTION_UPDATING);
3629
ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
3630
ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
3631
ptr->derived= table->sel;
3632
if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
3633
INFORMATION_SCHEMA_NAME.str))
3635
ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, ptr->table_name);
3636
if (!schema_table ||
3637
(schema_table->hidden &&
3638
((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 ||
3640
this check is used for show columns|keys from I_S hidden table
3642
lex->sql_command == SQLCOM_SHOW_FIELDS ||
3643
lex->sql_command == SQLCOM_SHOW_KEYS)))
3645
my_error(ER_UNKNOWN_TABLE, MYF(0),
3646
ptr->table_name, INFORMATION_SCHEMA_NAME.str);
3649
ptr->schema_table_name= ptr->table_name;
3650
ptr->schema_table= schema_table;
3652
ptr->select_lex= lex->current_select;
3653
ptr->cacheable_table= 1;
3654
ptr->index_hints= index_hints_arg;
3655
ptr->option= option ? option->str : 0;
3656
/* check that used name is unique */
3657
if (lock_type != TL_IGNORE)
3659
TABLE_LIST *first_table= (TABLE_LIST*) table_list.first;
3660
for (TABLE_LIST *tables= first_table ;
3662
tables=tables->next_local)
3664
if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
3665
!strcmp(ptr->db, tables->db))
3667
my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
3668
DBUG_RETURN(0); /* purecov: tested */
3672
/* Store the table reference preceding the current one. */
3673
if (table_list.elements > 0)
3676
table_list.next points to the last inserted TABLE_LIST->next_local'
3678
We don't use the offsetof() macro here to avoid warnings from gcc
3680
previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
3681
((char*) &(ptr->next_local) -
3684
Set next_name_resolution_table of the previous table reference to point
3685
to the current table reference. In effect the list
3686
TABLE_LIST::next_name_resolution_table coincides with
3687
TABLE_LIST::next_local. Later this may be changed in
3688
store_top_level_join_columns() for NATURAL/USING joins.
3690
previous_table_ref->next_name_resolution_table= ptr;
3694
Link the current table reference in a local list (list for current select).
3695
Notice that as a side effect here we set the next_local field of the
3696
previous table reference to 'ptr'. Here we also add one element to the
3699
table_list.link_in_list((uchar*) ptr, (uchar**) &ptr->next_local);
3700
ptr->next_name_resolution_table= NULL;
3701
/* Link table in global list (all used tables) */
3702
lex->add_to_query_tables(ptr);
3708
Initialize a new table list for a nested join.
3710
The function initializes a structure of the TABLE_LIST type
3711
for a nested join. It sets up its nested join list as empty.
3712
The created structure is added to the front of the current
3713
join list in the st_select_lex object. Then the function
3714
changes the current nest level for joins to refer to the newly
3715
created empty list after having saved the info on the old level
3716
in the initialized structure.
3718
@param thd current thread
3726
bool st_select_lex::init_nested_join(THD *thd)
3729
NESTED_JOIN *nested_join;
3730
DBUG_ENTER("init_nested_join");
3732
if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
3733
sizeof(NESTED_JOIN))))
3735
nested_join= ptr->nested_join=
3736
((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
3738
join_list->push_front(ptr);
3739
ptr->embedding= embedding;
3740
ptr->join_list= join_list;
3741
ptr->alias= (char*) "(nested_join)";
3743
join_list= &nested_join->join_list;
3750
End a nested join table list.
3752
The function returns to the previous join nest level.
3753
If the current level contains only one member, the function
3754
moves it one level up, eliminating the nest.
3756
@param thd current thread
3759
- Pointer to TABLE_LIST element added to the total table list, if success
3763
TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
3766
NESTED_JOIN *nested_join;
3767
DBUG_ENTER("end_nested_join");
3769
DBUG_ASSERT(embedding);
3771
join_list= ptr->join_list;
3772
embedding= ptr->embedding;
3773
nested_join= ptr->nested_join;
3774
if (nested_join->join_list.elements == 1)
3776
TABLE_LIST *embedded= nested_join->join_list.head();
3778
embedded->join_list= join_list;
3779
embedded->embedding= embedding;
3780
join_list->push_front(embedded);
3783
else if (nested_join->join_list.elements == 0)
3786
ptr= 0; // return value
3793
Nest last join operation.
3795
The function nest last join operation as if it was enclosed in braces.
3797
@param thd current thread
3802
\# Pointer to TABLE_LIST element created for the new nested join
3805
TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
3808
NESTED_JOIN *nested_join;
3809
List<TABLE_LIST> *embedded_list;
3810
DBUG_ENTER("nest_last_join");
3812
if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
3813
sizeof(NESTED_JOIN))))
3815
nested_join= ptr->nested_join=
3816
((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
3818
ptr->embedding= embedding;
3819
ptr->join_list= join_list;
3820
ptr->alias= (char*) "(nest_last_join)";
3821
embedded_list= &nested_join->join_list;
3822
embedded_list->empty();
3824
for (uint i=0; i < 2; i++)
3826
TABLE_LIST *table= join_list->pop();
3827
table->join_list= embedded_list;
3828
table->embedding= ptr;
3829
embedded_list->push_back(table);
3830
if (table->natural_join)
3832
ptr->is_natural_join= TRUE;
3834
If this is a JOIN ... USING, move the list of joined fields to the
3835
table reference that describes the join.
3837
if (prev_join_using)
3838
ptr->join_using_fields= prev_join_using;
3841
join_list->push_front(ptr);
3842
nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
3848
Add a table to the current join list.
3850
The function puts a table in front of the current join list
3851
of st_select_lex object.
3852
Thus, joined tables are put into this list in the reverse order
3853
(the most outer join operation follows first).
3855
@param table the table to add
3861
void st_select_lex::add_joined_table(TABLE_LIST *table)
3863
DBUG_ENTER("add_joined_table");
3864
join_list->push_front(table);
3865
table->join_list= join_list;
3866
table->embedding= embedding;
3872
Convert a right join into equivalent left join.
3874
The function takes the current join list t[0],t[1] ... and
3875
effectively converts it into the list t[1],t[0] ...
3876
Although the outer_join flag for the new nested table contains
3877
JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
3882
SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
3883
SELECT * FROM t2 LEFT JOIN t1 ON on_expr
3885
SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
3886
SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr
3888
SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
3889
SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr
3891
SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3 ON on_expr2 =>
3892
SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
3895
@param thd current thread
3898
- Pointer to the table representing the inner table, if success
3902
TABLE_LIST *st_select_lex::convert_right_join()
3904
TABLE_LIST *tab2= join_list->pop();
3905
TABLE_LIST *tab1= join_list->pop();
3906
DBUG_ENTER("convert_right_join");
3908
join_list->push_front(tab2);
3909
join_list->push_front(tab1);
3910
tab1->outer_join|= JOIN_TYPE_RIGHT;
3916
Set lock for all tables in current select level.
3918
@param lock_type Lock to set for tables
3921
If lock is a write lock, then tables->updating is set 1
3922
This is to get tables_ok to know that the table is updated by the
3926
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
3928
bool for_update= lock_type >= TL_READ_NO_INSERT;
3929
DBUG_ENTER("set_lock_for_tables");
3930
DBUG_PRINT("enter", ("lock_type: %d for_update: %d", lock_type,
3933
for (TABLE_LIST *tables= (TABLE_LIST*) table_list.first;
3935
tables= tables->next_local)
3937
tables->lock_type= lock_type;
3938
tables->updating= for_update;
3945
Create a fake SELECT_LEX for a unit.
3947
The method create a fake SELECT_LEX object for a unit.
3948
This object is created for any union construct containing a union
3949
operation and also for any single select union construct of the form
3951
(SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ...
3955
(SELECT ... ORDER BY LIMIT n) ORDER BY ...
3958
@param thd_arg thread handle
3961
The object is used to retrieve rows from the temporary table
3962
where the result on the union is obtained.
3965
1 on failure to create the object
3970
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
3972
SELECT_LEX *first_sl= first_select();
3973
DBUG_ENTER("add_fake_select_lex");
3974
DBUG_ASSERT(!fake_select_lex);
3976
if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
3978
fake_select_lex->include_standalone(this,
3979
(SELECT_LEX_NODE**)&fake_select_lex);
3980
fake_select_lex->select_number= INT_MAX;
3981
fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
3982
fake_select_lex->make_empty_select();
3983
fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
3984
fake_select_lex->select_limit= 0;
3986
fake_select_lex->context.outer_context=first_sl->context.outer_context;
3987
/* allow item list resolving in fake select for ORDER BY */
3988
fake_select_lex->context.resolve_in_select_list= TRUE;
3989
fake_select_lex->context.select_lex= fake_select_lex;
3995
(SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
3996
(SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
3997
just before the parser starts processing order_list
3999
global_parameters= fake_select_lex;
4000
fake_select_lex->no_table_names_allowed= 1;
4001
thd_arg->lex->current_select= fake_select_lex;
4003
thd_arg->lex->pop_context();
4009
Push a new name resolution context for a JOIN ... ON clause to the
4010
context stack of a query block.
4012
Create a new name resolution context for a JOIN ... ON clause,
4013
set the first and last leaves of the list of table references
4014
to be used for name resolution, and push the newly created
4015
context to the stack of contexts of the query.
4017
@param thd pointer to current thread
4018
@param left_op left operand of the JOIN
4019
@param right_op rigth operand of the JOIN
4024
TRUE if a memory allocation error occured
4028
push_new_name_resolution_context(THD *thd,
4029
TABLE_LIST *left_op, TABLE_LIST *right_op)
4031
Name_resolution_context *on_context;
4032
if (!(on_context= new (thd->mem_root) Name_resolution_context))
4035
on_context->first_name_resolution_table=
4036
left_op->first_leaf_for_name_resolution();
4037
on_context->last_name_resolution_table=
4038
right_op->last_leaf_for_name_resolution();
4039
return thd->lex->push_context(on_context);
4044
Add an ON condition to the second operand of a JOIN ... ON.
4046
Add an ON condition to the right operand of a JOIN ... ON clause.
4048
@param b the second operand of a JOIN ... ON
4049
@param expr the condition to be added to the ON clause
4052
FALSE if there was some error
4057
void add_join_on(TABLE_LIST *b, Item *expr)
4066
If called from the parser, this happens if you have both a
4067
right and left join. If called later, it happens if we add more
4068
than one condition to the ON clause.
4070
b->on_expr= new Item_cond_and(b->on_expr,expr);
4072
b->on_expr->top_level_item();
4078
Mark that there is a NATURAL JOIN or JOIN ... USING between two
4081
This function marks that table b should be joined with a either via
4082
a NATURAL JOIN or via JOIN ... USING. Both join types are special
4083
cases of each other, so we treat them together. The function
4084
setup_conds() creates a list of equal condition between all fields
4085
of the same name for NATURAL JOIN or the fields in 'using_fields'
4086
for JOIN ... USING. The list of equality conditions is stored
4087
either in b->on_expr, or in JOIN::conds, depending on whether there
4092
SELECT * FROM t1 NATURAL LEFT JOIN t2
4094
SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
4096
SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
4098
SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
4100
SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
4102
SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
4105
@param a Left join argument
4106
@param b Right join argument
4107
@param using_fields Field names from USING clause
4110
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
4114
lex->prev_join_using= using_fields;
4119
Reload/resets privileges and the different caches.
4121
@param thd Thread handler (can be NULL!)
4122
@param options What should be reset/reloaded (tables, privileges, slave...)
4123
@param tables Tables to flush (if any)
4124
@param write_to_binlog True if we can write to the binlog.
4126
@note Depending on 'options', it may be very bad to write the
4127
query to the binlog (e.g. FLUSH SLAVE); this is a
4128
pointer where reload_cache() will put 0 if
4129
it thinks we really should not write to the binlog.
4130
Otherwise it will put 1.
4132
@return Error status code
4134
@retval !=0 Error; thd->killed is set or thd->is_error() is true
4137
bool reload_cache(THD *thd, ulong options, TABLE_LIST *tables,
4138
bool *write_to_binlog)
4141
select_errors=0; /* Write if more errors */
4142
bool tmp_write_to_binlog= 1;
4144
DBUG_ASSERT(!thd || !thd->in_sub_stmt);
4146
if (options & REFRESH_LOG)
4149
Flush the normal query log, the update log, the binary log,
4150
the slow query log, the relay log (if it exists) and the log
4155
Writing this command to the binlog may result in infinite loops
4156
when doing mysqlbinlog|mysql, and anyway it does not really make
4157
sense to log it automatically (would cause more trouble to users
4158
than it would help them)
4160
tmp_write_to_binlog= 0;
4161
if( mysql_bin_log.is_open() )
4163
mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
4165
pthread_mutex_lock(&LOCK_active_mi);
4166
rotate_relay_log(active_mi);
4167
pthread_mutex_unlock(&LOCK_active_mi);
4169
/* flush slow and general logs */
4170
logger.flush_logs(thd);
4172
if (ha_flush_logs(NULL))
4174
if (flush_error_log())
4178
Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too
4181
if (options & (REFRESH_TABLES | REFRESH_READ_LOCK))
4183
if ((options & REFRESH_READ_LOCK) && thd)
4186
We must not try to aspire a global read lock if we have a write
4187
locked table. This would lead to a deadlock when trying to
4188
reopen (and re-lock) the table after the flush.
4190
if (thd->locked_tables)
4192
THR_LOCK_DATA **lock_p= thd->locked_tables->locks;
4193
THR_LOCK_DATA **end_p= lock_p + thd->locked_tables->lock_count;
4195
for (; lock_p < end_p; lock_p++)
4197
if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
4199
my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
4205
Writing to the binlog could cause deadlocks, as we don't log
4208
tmp_write_to_binlog= 0;
4209
if (lock_global_read_lock(thd))
4211
result= close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
4212
FALSE : TRUE, TRUE);
4213
if (make_global_read_lock_block_commit(thd)) // Killed
4215
/* Don't leave things in a half-locked state */
4216
unlock_global_read_lock(thd);
4221
result= close_cached_tables(thd, tables, FALSE, (options & REFRESH_FAST) ?
4222
FALSE : TRUE, FALSE);
4225
if (thd && (options & REFRESH_STATUS))
4226
refresh_status(thd);
4227
if (options & REFRESH_THREADS)
4228
flush_thread_cache();
4229
if (options & REFRESH_MASTER)
4232
tmp_write_to_binlog= 0;
4233
if (reset_master(thd))
4238
if (options & REFRESH_SLAVE)
4240
tmp_write_to_binlog= 0;
4241
pthread_mutex_lock(&LOCK_active_mi);
4242
if (reset_slave(thd, active_mi))
4244
pthread_mutex_unlock(&LOCK_active_mi);
4246
*write_to_binlog= tmp_write_to_binlog;
4254
@param thd Thread class
4256
@param only_kill_query Should it kill the query or the connection
4259
This is written such that we have a short lock on LOCK_thread_count
4262
uint kill_one_thread(THD *thd, ulong id, bool only_kill_query)
4265
uint error=ER_NO_SUCH_THREAD;
4266
DBUG_ENTER("kill_one_thread");
4267
DBUG_PRINT("enter", ("id=%lu only_kill=%d", id, only_kill_query));
4268
VOID(pthread_mutex_lock(&LOCK_thread_count)); // For unlink from list
4269
I_List_iterator<THD> it(threads);
4272
if (tmp->command == COM_DAEMON)
4274
if (tmp->thread_id == id)
4276
pthread_mutex_lock(&tmp->LOCK_delete); // Lock from delete
4280
VOID(pthread_mutex_unlock(&LOCK_thread_count));
4283
tmp->awake(only_kill_query ? THD::KILL_QUERY : THD::KILL_CONNECTION);
4285
pthread_mutex_unlock(&tmp->LOCK_delete);
4287
DBUG_PRINT("exit", ("%d", error));
4293
kills a thread and sends response
4299
only_kill_query Should it kill the query or the connection
4302
void sql_kill(THD *thd, ulong id, bool only_kill_query)
4305
if (!(error= kill_one_thread(thd, id, only_kill_query)))
4308
my_error(error, MYF(0), id);
4312
/** If pointer is not a null pointer, append filename to it. */
4314
bool append_file_to_dir(THD *thd, const char **filename_ptr,
4315
const char *table_name)
4317
char buff[FN_REFLEN],*ptr, *end;
4319
return 0; // nothing to do
4321
/* Check that the filename is not too long and it's a hard path */
4322
if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
4323
!test_if_hard_path(*filename_ptr))
4325
my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
4328
/* Fix is using unix filename format on dos */
4329
strmov(buff,*filename_ptr);
4330
end=convert_dirname(buff, *filename_ptr, NullS);
4331
if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1)))
4332
return 1; // End of memory
4334
strxmov(ptr,buff,table_name,NullS);
4340
Check if the select is a simple select (not an union).
4345
1 error ; In this case the error messege is sent to the client
4348
bool check_simple_select()
4350
THD *thd= current_thd;
4352
if (lex->current_select != &lex->select_lex)
4355
Lex_input_stream *lip= thd->m_lip;
4356
strmake(command, lip->yylval->symbol.str,
4357
min(lip->yylval->symbol.length, sizeof(command)-1));
4358
my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
4365
Comp_creator *comp_eq_creator(bool invert)
4367
return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
4371
Comp_creator *comp_ge_creator(bool invert)
4373
return invert?(Comp_creator *)<_creator:(Comp_creator *)&ge_creator;
4377
Comp_creator *comp_gt_creator(bool invert)
4379
return invert?(Comp_creator *)&le_creator:(Comp_creator *)>_creator;
4383
Comp_creator *comp_le_creator(bool invert)
4385
return invert?(Comp_creator *)>_creator:(Comp_creator *)&le_creator;
4389
Comp_creator *comp_lt_creator(bool invert)
4391
return invert?(Comp_creator *)&ge_creator:(Comp_creator *)<_creator;
4395
Comp_creator *comp_ne_creator(bool invert)
4397
return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
4402
Construct ALL/ANY/SOME subquery Item.
4404
@param left_expr pointer to left expression
4405
@param cmp compare function creator
4406
@param all true if we create ALL subquery
4407
@param select_lex pointer on parsed subquery structure
4410
constructed Item (or 0 if out of memory)
4412
Item * all_any_subquery_creator(Item *left_expr,
4413
chooser_compare_func_creator cmp,
4415
SELECT_LEX *select_lex)
4417
if ((cmp == &comp_eq_creator) && !all) // = ANY <=> IN
4418
return new Item_in_subselect(left_expr, select_lex);
4420
if ((cmp == &comp_ne_creator) && all) // <> ALL <=> NOT IN
4421
return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
4423
Item_allany_subselect *it=
4424
new Item_allany_subselect(left_expr, cmp, select_lex, all);
4426
return it->upper_item= new Item_func_not_all(it); /* ALL */
4428
return it->upper_item= new Item_func_nop_all(it); /* ANY/SOME */
4433
Multi update query pre-check.
4435
@param thd Thread handler
4436
@param tables Global/local table list (have to be the same)
4444
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
4448
SELECT_LEX *select_lex= &lex->select_lex;
4449
DBUG_ENTER("multi_update_precheck");
4451
if (select_lex->item_list.elements != lex->value_list.elements)
4453
my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
4457
if (select_lex->order_list.elements)
4459
else if (select_lex->select_limit)
4463
my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
4470
Multi delete query pre-check.
4472
@param thd Thread handler
4473
@param tables Global/local table list
4481
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
4483
SELECT_LEX *select_lex= &thd->lex->select_lex;
4484
TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
4485
DBUG_ENTER("multi_delete_precheck");
4487
thd->lex->query_tables_own_last= 0;
4488
thd->lex->query_tables_own_last= save_query_tables_own_last;
4490
if ((thd->options & OPTION_SAFE_UPDATES) && !select_lex->where)
4492
my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
4493
ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
4501
Given a table in the source list, find a correspondent table in the
4502
table references list.
4504
@param lex Pointer to LEX representing multi-delete.
4505
@param src Source table to match.
4506
@param ref Table references list.
4508
@remark The source table list (tables listed before the FROM clause
4509
or tables listed in the FROM clause before the USING clause) may
4510
contain table names or aliases that must match unambiguously one,
4511
and only one, table in the target table list (table references list,
4512
after FROM/USING clause).
4514
@return Matching table, NULL otherwise.
4517
static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl,
4520
TABLE_LIST *match= NULL;
4521
DBUG_ENTER("multi_delete_table_match");
4523
for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
4527
if (tbl->is_fqtn && elem->is_alias)
4528
continue; /* no match */
4529
if (tbl->is_fqtn && elem->is_fqtn)
4530
cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
4531
strcmp(tbl->db, elem->db);
4532
else if (elem->is_alias)
4533
cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias);
4535
cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
4536
strcmp(tbl->db, elem->db);
4543
my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias);
4551
my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE");
4558
Link tables in auxilary table list of multi-delete with corresponding
4559
elements in main table list, and set proper locks for them.
4561
@param lex pointer to LEX representing multi-delete
4569
bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
4571
TABLE_LIST *tables= (TABLE_LIST*)lex->select_lex.table_list.first;
4572
TABLE_LIST *target_tbl;
4573
DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");
4575
lex->table_count= 0;
4577
for (target_tbl= (TABLE_LIST *)lex->auxiliary_table_list.first;
4578
target_tbl; target_tbl= target_tbl->next_local)
4581
/* All tables in aux_tables must be found in FROM PART */
4582
TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
4587
target_tbl->table_name= walk->table_name;
4588
target_tbl->table_name_length= walk->table_name_length;
4590
walk->updating= target_tbl->updating;
4591
walk->lock_type= target_tbl->lock_type;
4592
target_tbl->correspondent_table= walk; // Remember corresponding table
4599
simple UPDATE query pre-check.
4601
@param thd Thread handler
4602
@param tables Global table list
4610
bool update_precheck(THD *thd, TABLE_LIST *tables)
4612
DBUG_ENTER("update_precheck");
4613
if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements)
4615
my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
4623
simple INSERT query pre-check.
4625
@param thd Thread handler
4626
@param tables Global table list
4634
bool insert_precheck(THD *thd, TABLE_LIST *tables)
4637
DBUG_ENTER("insert_precheck");
4640
Check that we have modify privileges for the first table and
4641
select privileges for the rest
4643
if (lex->update_list.elements != lex->value_list.elements)
4645
my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
4653
CREATE TABLE query pre-check.
4655
@param thd Thread handler
4656
@param tables Global table list
4657
@param create_table Table which will be created
4665
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
4666
TABLE_LIST *create_table)
4669
SELECT_LEX *select_lex= &lex->select_lex;
4670
bool error= TRUE; // Error message is given
4671
DBUG_ENTER("create_table_precheck");
4673
if (create_table && (strcmp(create_table->db, "information_schema") == 0))
4675
my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", INFORMATION_SCHEMA_NAME.str);
4679
if (select_lex->item_list.elements)
4681
/* Check permissions for used tables in CREATE TABLE ... SELECT */
4683
#ifdef NOT_NECESSARY_TO_CHECK_CREATE_TABLE_EXIST_WHEN_PREPARING_STATEMENT
4684
/* This code throws an ill error for CREATE TABLE t1 SELECT * FROM t1 */
4686
Only do the check for PS, because we on execute we have to check that
4687
against the opened tables to ensure we don't use a table that is part
4688
of the view (which can only be done after the table has been opened).
4690
if (thd->stmt_arena->is_stmt_prepare_or_first_sp_execute())
4693
For temporary tables we don't have to check if the created table exists
4695
if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) &&
4696
find_table_in_global_list(tables, create_table->db,
4697
create_table->table_name))
4712
negate given expression.
4714
@param thd thread handler
4715
@param expr expression for negation
4721
Item *negate_expression(THD *thd, Item *expr)
4724
if (expr->type() == Item::FUNC_ITEM &&
4725
((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
4727
/* it is NOT(NOT( ... )) */
4728
Item *arg= ((Item_func *) expr)->arguments()[0];
4729
enum_parsing_place place= thd->lex->current_select->parsing_place;
4730
if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
4733
if it is not boolean function then we have to emulate value of
4734
not(not(a)), it will be a != 0
4736
return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
4739
if ((negated= expr->neg_transformer(thd)) != 0)
4741
return new Item_func_not(expr);
4746
Check that byte length of a string does not exceed some limit.
4748
@param str string to be checked
4749
@param err_msg error message to be displayed if the string is too long
4750
@param max_length max length
4753
FALSE the passed string is not longer than max_length
4755
TRUE the passed string is longer than max_length
4758
The function is not used in existing code but can be useful later?
4761
bool check_string_byte_length(LEX_STRING *str, const char *err_msg,
4762
uint max_byte_length)
4764
if (str->length <= max_byte_length)
4767
my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length);
4774
Check that char length of a string does not exceed some limit.
4777
check_string_char_length()
4778
str string to be checked
4779
err_msg error message to be displayed if the string is too long
4780
max_char_length max length in symbols
4784
FALSE the passed string is not longer than max_char_length
4785
TRUE the passed string is longer than max_char_length
4789
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
4790
uint max_char_length, CHARSET_INFO *cs,
4793
int well_formed_error;
4794
uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
4795
max_char_length, &well_formed_error);
4797
if (!well_formed_error && str->length == res)
4801
my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
4806
bool check_identifier_name(LEX_STRING *str, uint max_char_length,
4807
uint err_code, const char *param_for_err_msg)
4809
#ifdef HAVE_CHARSET_utf8mb3
4811
We don't support non-BMP characters in identifiers at the moment,
4812
so they should be prohibited until such support is done.
4813
This is why we use the 3-byte utf8 to check well-formedness here.
4815
CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci;
4817
CHARSET_INFO *cs= system_charset_info;
4819
int well_formed_error;
4820
uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
4821
max_char_length, &well_formed_error);
4823
if (well_formed_error)
4825
my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
4829
if (str->length == res)
4836
case ER_WRONG_STRING_LENGTH:
4837
my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
4839
case ER_TOO_LONG_IDENT:
4840
my_error(err_code, MYF(0), str->str);
4851
Check if path does not contain mysql data home directory
4853
test_if_data_home_dir()
4855
conv_home_dir converted data home directory
4856
home_dir_len converted data home directory length
4863
bool test_if_data_home_dir(const char *dir)
4865
char path[FN_REFLEN], conv_path[FN_REFLEN];
4866
uint dir_len, home_dir_len= strlen(mysql_unpacked_real_data_home);
4867
DBUG_ENTER("test_if_data_home_dir");
4872
(void) fn_format(path, dir, "", "",
4873
(MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
4874
dir_len= unpack_dirname(conv_path, dir);
4876
if (home_dir_len < dir_len)
4878
if (lower_case_file_system)
4880
if (!my_strnncoll(character_set_filesystem,
4881
(const uchar*) conv_path, home_dir_len,
4882
(const uchar*) mysql_unpacked_real_data_home,
4886
else if (!memcmp(conv_path, mysql_unpacked_real_data_home, home_dir_len))
4893
extern int MYSQLparse(void *thd); // from sql_yacc.cc
4897
This is a wrapper of MYSQLparse(). All the code should call parse_sql()
4898
instead of MYSQLparse().
4900
@param thd Thread context.
4901
@param lip Lexer context.
4902
@param creation_ctx Object creation context.
4904
@return Error status.
4905
@retval FALSE on success.
4906
@retval TRUE on parsing error.
4909
bool parse_sql(THD *thd,
4910
Lex_input_stream *lip,
4911
Object_creation_ctx *creation_ctx)
4913
DBUG_ASSERT(thd->m_lip == NULL);
4915
/* Backup creation context. */
4917
Object_creation_ctx *backup_ctx= NULL;
4920
backup_ctx= creation_ctx->set_n_backup(thd);
4922
/* Set Lex_input_stream. */
4926
/* Parse the query. */
4928
bool mysql_parse_status= MYSQLparse(thd) != 0;
4930
/* Check that if MYSQLparse() failed, thd->is_error() is set. */
4932
DBUG_ASSERT(!mysql_parse_status || thd->is_error());
4934
/* Reset Lex_input_stream. */
4938
/* Restore creation context. */
4941
creation_ctx->restore_env(thd, backup_ctx);
4945
return mysql_parse_status || thd->is_fatal_error;
4949
@} (end of group Runtime_Environment)