~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2003 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
16
#define DRIZZLE_LEX 1
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
17
#include <drizzled/server_includes.h>
779.3.37 by Monty Taylor
Renmaed libdrizzle in the tree to libdrizzleclient to avoid namespace clashes
18
#include <libdrizzleclient/libdrizzle.h>
614 by Brian Aker
Remove filtering (wrong layer, belongs in plugin).
19
#include <mysys/hash.h>
520.8.2 by Monty Taylor
Moved sql_parse.h and sql_error.h out of common_includes.
20
#include <drizzled/logging.h>
575.4.6 by Monty Taylor
Removed my_getwd.
21
#include <drizzled/db.h>
549 by Monty Taylor
Took gettext.h out of header files.
22
#include <drizzled/error.h>
553.1.3 by Monty Taylor
Split out nested_join.h.
23
#include <drizzled/nested_join.h>
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
24
#include <drizzled/query_id.h>
520.8.2 by Monty Taylor
Moved sql_parse.h and sql_error.h out of common_includes.
25
#include <drizzled/sql_parse.h>
520.6.7 by Monty Taylor
Moved a bunch of crap out of common_includes.
26
#include <drizzled/data_home.h>
575.4.7 by Monty Taylor
More header cleanup.
27
#include <drizzled/sql_base.h>
28
#include <drizzled/show.h>
29
#include <drizzled/rename.h>
670.1.20 by Monty Taylor
Renamed functions to function... everything else is singular.
30
#include <drizzled/function/time/unix_timestamp.h>
31
#include <drizzled/function/get_system_var.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
32
#include <drizzled/item/cmpfunc.h>
642.1.20 by Lee
header file clean up
33
#include <drizzled/item/null.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
34
#include <drizzled/session.h>
35
#include <drizzled/sql_load.h>
670.2.3 by Monty Taylor
Moved connect.h out of server_includes.
36
#include <drizzled/connect.h>
670.2.4 by Monty Taylor
Removed more stuff from the headers.
37
#include <drizzled/lock.h>
590.2.18 by Monty Taylor
Changed the bitset<32> to a bitset<5>. Made the int constants into bitset constants.
38
#include <bitset>
39
40
using namespace std;
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
41
1 by brian
clean slate
42
/**
43
  @defgroup Runtime_Environment Runtime Environment
44
  @{
45
*/
46
629.2.7 by Monty Taylor
Fixed a couple of memory buffer size issues.
47
extern size_t my_thread_stack_size;
520.6.7 by Monty Taylor
Moved a bunch of crap out of common_includes.
48
extern const CHARSET_INFO *character_set_filesystem;
1 by brian
clean slate
49
const char *any_db="*any*";	// Special symbol for check_access
50
230.1.8 by Monty Taylor
Set length to catch errors in adding or removing COM_* constants.
51
const LEX_STRING command_name[COM_END+1]={
1 by brian
clean slate
52
  { C_STRING_WITH_LEN("Sleep") },
53
  { C_STRING_WITH_LEN("Quit") },
54
  { C_STRING_WITH_LEN("Init DB") },
55
  { C_STRING_WITH_LEN("Query") },
56
  { C_STRING_WITH_LEN("Field List") },
57
  { C_STRING_WITH_LEN("Create DB") },
58
  { C_STRING_WITH_LEN("Drop DB") },
59
  { C_STRING_WITH_LEN("Refresh") },
60
  { C_STRING_WITH_LEN("Shutdown") },
61
  { C_STRING_WITH_LEN("Processlist") },
62
  { C_STRING_WITH_LEN("Connect") },
63
  { C_STRING_WITH_LEN("Kill") },
64
  { C_STRING_WITH_LEN("Ping") },
65
  { C_STRING_WITH_LEN("Time") },
66
  { C_STRING_WITH_LEN("Change user") },
67
  { C_STRING_WITH_LEN("Connect Out") },
68
  { C_STRING_WITH_LEN("Set option") },
69
  { C_STRING_WITH_LEN("Daemon") },
70
  { C_STRING_WITH_LEN("Error") }  // Last command number
71
};
72
73
const char *xa_state_names[]={
74
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
75
};
76
520.1.22 by Brian Aker
Second pass of thd cleanup
77
static void unlock_locked_tables(Session *session)
1 by brian
clean slate
78
{
520.1.22 by Brian Aker
Second pass of thd cleanup
79
  if (session->locked_tables)
1 by brian
clean slate
80
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
81
    session->lock=session->locked_tables;
82
    session->locked_tables=0;			// Will be automatically closed
83
    close_thread_tables(session);			// Free tables
1 by brian
clean slate
84
  }
85
}
86
87
520.1.22 by Brian Aker
Second pass of thd cleanup
88
bool end_active_trans(Session *session)
1 by brian
clean slate
89
{
483 by Brian Aker
Removed dead bit around SP/Triggers
90
  int error= 0;
91
520.1.22 by Brian Aker
Second pass of thd cleanup
92
  if (session->transaction.xid_state.xa_state != XA_NOTR)
1 by brian
clean slate
93
  {
94
    my_error(ER_XAER_RMFAIL, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
95
             xa_state_names[session->transaction.xid_state.xa_state]);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
96
    return(1);
1 by brian
clean slate
97
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
98
  if (session->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN |
1 by brian
clean slate
99
		      OPTION_TABLE_LOCK))
100
  {
101
    /* Safety if one did "drop table" on locked tables */
520.1.22 by Brian Aker
Second pass of thd cleanup
102
    if (!session->locked_tables)
103
      session->options&= ~OPTION_TABLE_LOCK;
104
    session->server_status&= ~SERVER_STATUS_IN_TRANS;
105
    if (ha_commit(session))
1 by brian
clean slate
106
      error=1;
107
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
108
  session->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
109
  session->transaction.all.modified_non_trans_table= false;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
110
  return(error);
1 by brian
clean slate
111
}
112
113
520.1.22 by Brian Aker
Second pass of thd cleanup
114
bool begin_trans(Session *session)
1 by brian
clean slate
115
{
483 by Brian Aker
Removed dead bit around SP/Triggers
116
  int error= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
117
  if (session->locked_tables)
1 by brian
clean slate
118
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
119
    session->lock=session->locked_tables;
120
    session->locked_tables=0;			// Will be automatically closed
121
    close_thread_tables(session);			// Free tables
1 by brian
clean slate
122
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
123
  if (end_active_trans(session))
1 by brian
clean slate
124
    error= -1;
125
  else
126
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
127
    LEX *lex= session->lex;
128
    session->options|= OPTION_BEGIN;
129
    session->server_status|= SERVER_STATUS_IN_TRANS;
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
130
    if (lex->start_transaction_opt & DRIZZLE_START_TRANS_OPT_WITH_CONS_SNAPSHOT)
520.1.22 by Brian Aker
Second pass of thd cleanup
131
      error= ha_start_consistent_snapshot(session);
1 by brian
clean slate
132
  }
133
  return error;
134
}
135
136
/**
137
  Returns true if all tables should be ignored.
138
*/
614 by Brian Aker
Remove filtering (wrong layer, belongs in plugin).
139
inline bool all_tables_not_ok(Session *, TableList *)
1 by brian
clean slate
140
{
614 by Brian Aker
Remove filtering (wrong layer, belongs in plugin).
141
  return false;
1 by brian
clean slate
142
}
143
144
/**
145
  Mark all commands that somehow changes a table.
146
147
  This is used to check number of updates / hour.
148
149
  sql_command is actually set to SQLCOM_END sometimes
150
  so we need the +1 to include it in the array.
151
152
  See COMMAND_FLAG_xxx for different type of commands
153
     2  - query that returns meaningful ROW_COUNT() -
154
          a number of modified rows
155
*/
156
590.2.18 by Monty Taylor
Changed the bitset<32> to a bitset<5>. Made the int constants into bitset constants.
157
bitset<CF_BIT_SIZE> sql_command_flags[SQLCOM_END+1];
1 by brian
clean slate
158
159
void init_update_queries(void)
160
{
610 by Brian Aker
Merge of Monty's (plus fix for increment style/useless +1)
161
  uint32_t x;
162
163
  for (x= 0; x <= SQLCOM_END; x++)
164
    sql_command_flags[x].reset();
1 by brian
clean slate
165
166
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA;
167
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
168
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
169
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
170
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
171
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA;
172
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA;
173
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA;
174
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA;
175
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA;
176
177
  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
178
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
179
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
180
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
181
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
182
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
183
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
184
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
185
186
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND;
187
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND;
188
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND;
189
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND;
190
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND;
191
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND;
192
  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
193
  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
194
  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
195
  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
196
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=  CF_STATUS_COMMAND;
197
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
198
199
   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
200
                                               CF_SHOW_TABLE_COMMAND);
201
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
202
                                                CF_SHOW_TABLE_COMMAND);
203
  /*
204
    The following admin table operations are allowed
205
    on log tables.
206
  */
207
  sql_command_flags[SQLCOM_REPAIR]=           CF_WRITE_LOGS_COMMAND;
208
  sql_command_flags[SQLCOM_OPTIMIZE]=         CF_WRITE_LOGS_COMMAND;
209
  sql_command_flags[SQLCOM_ANALYZE]=          CF_WRITE_LOGS_COMMAND;
210
}
211
212
213
bool is_update_query(enum enum_sql_command command)
214
{
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
215
  assert(command >= 0 && command <= SQLCOM_END);
602.2.2 by Yoshinori Sano
Fix bugs in params of sql_command_flags[...].test(). Previously, the value such as, 0, 1, 2, 4, 8 and 16 is given to std::bitset.test() in that place, which is misunderstanding of the spec of the test(). The test(size_t n) returns true if bit n is set.
216
  return (sql_command_flags[command].test(CF_BIT_CHANGES_DATA));
1 by brian
clean slate
217
}
218
520.1.22 by Brian Aker
Second pass of thd cleanup
219
void execute_init_command(Session *session, sys_var_str *init_command_var,
658 by Brian Aker
Part removal of my_pthread.h
220
			  pthread_rwlock_t *var_mutex)
1 by brian
clean slate
221
{
222
  Vio* save_vio;
223
  ulong save_client_capabilities;
224
520.1.22 by Brian Aker
Second pass of thd cleanup
225
  session->set_proc_info("Execution of init_command");
1 by brian
clean slate
226
  /*
227
    We need to lock init_command_var because
228
    during execution of init_command_var query
229
    values of init_command_var can't be changed
230
  */
658 by Brian Aker
Part removal of my_pthread.h
231
  pthread_rwlock_rdlock(var_mutex);
520.1.22 by Brian Aker
Second pass of thd cleanup
232
  save_client_capabilities= session->client_capabilities;
233
  session->client_capabilities|= CLIENT_MULTI_STATEMENTS;
1 by brian
clean slate
234
  /*
235
    We don't need return result of execution to client side.
520.1.22 by Brian Aker
Second pass of thd cleanup
236
    To forbid this we should set session->net.vio to 0.
1 by brian
clean slate
237
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
238
  save_vio= session->net.vio;
239
  session->net.vio= 0;
240
  dispatch_command(COM_QUERY, session,
1 by brian
clean slate
241
                   init_command_var->value,
242
                   init_command_var->value_length);
658 by Brian Aker
Part removal of my_pthread.h
243
  pthread_rwlock_unlock(var_mutex);
520.1.22 by Brian Aker
Second pass of thd cleanup
244
  session->client_capabilities= save_client_capabilities;
245
  session->net.vio= save_vio;
1 by brian
clean slate
246
}
247
248
/**
249
  Ends the current transaction and (maybe) begin the next.
250
520.1.22 by Brian Aker
Second pass of thd cleanup
251
  @param session            Current thread
1 by brian
clean slate
252
  @param completion     Completion type
253
254
  @retval
255
    0   OK
256
*/
257
520.1.22 by Brian Aker
Second pass of thd cleanup
258
int end_trans(Session *session, enum enum_mysql_completiontype completion)
1 by brian
clean slate
259
{
260
  bool do_release= 0;
261
  int res= 0;
262
520.1.22 by Brian Aker
Second pass of thd cleanup
263
  if (session->transaction.xid_state.xa_state != XA_NOTR)
1 by brian
clean slate
264
  {
265
    my_error(ER_XAER_RMFAIL, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
266
             xa_state_names[session->transaction.xid_state.xa_state]);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
267
    return(1);
1 by brian
clean slate
268
  }
269
  switch (completion) {
270
  case COMMIT:
271
    /*
272
     We don't use end_active_trans() here to ensure that this works
273
     even if there is a problem with the OPTION_AUTO_COMMIT flag
274
     (Which of course should never happen...)
275
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
276
    session->server_status&= ~SERVER_STATUS_IN_TRANS;
277
    res= ha_commit(session);
278
    session->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
279
    session->transaction.all.modified_non_trans_table= false;
1 by brian
clean slate
280
    break;
281
  case COMMIT_RELEASE:
282
    do_release= 1; /* fall through */
283
  case COMMIT_AND_CHAIN:
520.1.22 by Brian Aker
Second pass of thd cleanup
284
    res= end_active_trans(session);
1 by brian
clean slate
285
    if (!res && completion == COMMIT_AND_CHAIN)
520.1.22 by Brian Aker
Second pass of thd cleanup
286
      res= begin_trans(session);
1 by brian
clean slate
287
    break;
288
  case ROLLBACK_RELEASE:
289
    do_release= 1; /* fall through */
290
  case ROLLBACK:
291
  case ROLLBACK_AND_CHAIN:
292
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
293
    session->server_status&= ~SERVER_STATUS_IN_TRANS;
294
    if (ha_rollback(session))
1 by brian
clean slate
295
      res= -1;
520.1.22 by Brian Aker
Second pass of thd cleanup
296
    session->options&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
297
    session->transaction.all.modified_non_trans_table= false;
1 by brian
clean slate
298
    if (!res && (completion == ROLLBACK_AND_CHAIN))
520.1.22 by Brian Aker
Second pass of thd cleanup
299
      res= begin_trans(session);
1 by brian
clean slate
300
    break;
301
  }
302
  default:
303
    res= -1;
304
    my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
305
    return(-1);
1 by brian
clean slate
306
  }
307
308
  if (res < 0)
520.1.22 by Brian Aker
Second pass of thd cleanup
309
    my_error(session->killed_errno(), MYF(0));
1 by brian
clean slate
310
  else if ((res == 0) && do_release)
520.1.22 by Brian Aker
Second pass of thd cleanup
311
    session->killed= Session::KILL_CONNECTION;
1 by brian
clean slate
312
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
313
  return(res);
1 by brian
clean slate
314
}
315
316
317
/**
318
  Read one command from connection and execute it (query or simple command).
319
  This function is called in loop from thread function.
320
321
  For profiling to work, it must never be called recursively.
322
323
  @retval
324
    0  success
325
  @retval
326
    1  request of thread shutdown (see dispatch_command() description)
327
*/
328
520.1.22 by Brian Aker
Second pass of thd cleanup
329
bool do_command(Session *session)
1 by brian
clean slate
330
{
331
  bool return_value;
332
  char *packet= 0;
333
  ulong packet_length;
520.1.22 by Brian Aker
Second pass of thd cleanup
334
  NET *net= &session->net;
1 by brian
clean slate
335
  enum enum_server_command command;
336
337
  /*
338
    indicator of uninitialized lex => normal flow of errors handling
339
    (see my_message_sql)
340
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
341
  session->lex->current_select= 0;
1 by brian
clean slate
342
343
  /*
344
    This thread will do a blocking read from the client which
345
    will be interrupted when the next command is received from
346
    the client, the connection is closed or "net_wait_timeout"
347
    number of seconds has passed
348
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
349
  my_net_set_read_timeout(net, session->variables.net_wait_timeout);
1 by brian
clean slate
350
351
  /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
352
    XXX: this code is here only to clear possible errors of init_connect.
1 by brian
clean slate
353
    Consider moving to init_connect() instead.
354
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
355
  session->clear_error();				// Clear error message
356
  session->main_da.reset_diagnostics_area();
1 by brian
clean slate
357
358
  net_new_transaction(net);
359
360
  packet_length= my_net_read(net);
361
  if (packet_length == packet_error)
362
  {
363
    /* Check if we can continue without closing the connection */
364
365
    /* The error must be set. */
759.1.2 by Monty Taylor
Removed the assert that's causing all of the pain.
366
    /* This assert is killing me - and tracking down why the error isn't
367
     * set here is a waste since the protocol lib is being replaced. */ 
368
    //assert(session->is_error());
520.1.22 by Brian Aker
Second pass of thd cleanup
369
    net_end_statement(session);
1 by brian
clean slate
370
371
    if (net->error != 3)
372
    {
55 by brian
Update for using real bool types.
373
      return_value= true;                       // We have to close it.
1 by brian
clean slate
374
      goto out;
375
    }
376
377
    net->error= 0;
55 by brian
Update for using real bool types.
378
    return_value= false;
1 by brian
clean slate
379
    goto out;
380
  }
381
382
  packet= (char*) net->read_pos;
383
  /*
384
    'packet_length' contains length of data, as it was stored in packet
385
    header. In case of malformed header, my_net_read returns zero.
386
    If packet_length is not zero, my_net_read ensures that the returned
387
    number of bytes was actually read from network.
388
    There is also an extra safety measure in my_net_read:
389
    it sets packet[packet_length]= 0, but only for non-zero packets.
390
  */
391
  if (packet_length == 0)                       /* safety */
392
  {
393
    /* Initialize with COM_SLEEP packet */
481 by Brian Aker
Remove all of uchar.
394
    packet[0]= (unsigned char) COM_SLEEP;
1 by brian
clean slate
395
    packet_length= 1;
396
  }
397
  /* Do not rely on my_net_read, extra safety against programming errors. */
398
  packet[packet_length]= '\0';                  /* safety */
399
481 by Brian Aker
Remove all of uchar.
400
  command= (enum enum_server_command) (unsigned char) packet[0];
1 by brian
clean slate
401
402
  if (command >= COM_END)
403
    command= COM_END;                           // Wrong command
404
405
  /* Restore read timeout value */
520.1.22 by Brian Aker
Second pass of thd cleanup
406
  my_net_set_read_timeout(net, session->variables.net_read_timeout);
1 by brian
clean slate
407
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
408
  assert(packet_length);
520.1.22 by Brian Aker
Second pass of thd cleanup
409
  return_value= dispatch_command(command, session, packet+1, (uint32_t) (packet_length-1));
1 by brian
clean slate
410
411
out:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
412
  return(return_value);
1 by brian
clean slate
413
}
414
415
/**
416
  Perform one connection-level (COM_XXXX) command.
417
418
  @param command         type of command to perform
520.1.22 by Brian Aker
Second pass of thd cleanup
419
  @param session             connection handle
1 by brian
clean slate
420
  @param packet          data for the command, packet is always null-terminated
421
  @param packet_length   length of packet + 1 (to show that data is
422
                         null-terminated) except for COM_SLEEP, where it
423
                         can be zero.
424
425
  @todo
520.1.22 by Brian Aker
Second pass of thd cleanup
426
    set session->lex->sql_command to SQLCOM_END here.
1 by brian
clean slate
427
  @todo
428
    The following has to be changed to an 8 byte integer
429
430
  @retval
431
    0   ok
432
  @retval
433
    1   request of thread shutdown, i. e. if command is
434
        COM_QUIT/COM_SHUTDOWN
435
*/
520.1.22 by Brian Aker
Second pass of thd cleanup
436
bool dispatch_command(enum enum_server_command command, Session *session,
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
437
                      char* packet, uint32_t packet_length)
1 by brian
clean slate
438
{
520.1.22 by Brian Aker
Second pass of thd cleanup
439
  NET *net= &session->net;
1 by brian
clean slate
440
  bool error= 0;
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
441
  Query_id &query_id= Query_id::get_query_id();
1 by brian
clean slate
442
520.1.22 by Brian Aker
Second pass of thd cleanup
443
  session->command=command;
444
  session->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
445
  session->set_time();
398.1.10 by Monty Taylor
Actually removed VOID() this time.
446
  pthread_mutex_lock(&LOCK_thread_count);
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
447
  session->query_id= query_id.value();
1 by brian
clean slate
448
449
  switch( command ) {
450
  /* Ignore these statements. */
451
  case COM_PING:
452
    break;
453
  /* Increase id and count all other statements. */
454
  default:
520.1.22 by Brian Aker
Second pass of thd cleanup
455
    statistic_increment(session->status_var.questions, &LOCK_status);
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
456
    query_id.next();
1 by brian
clean slate
457
  }
458
459
  thread_running++;
520.1.22 by Brian Aker
Second pass of thd cleanup
460
  /* TODO: set session->lex->sql_command to SQLCOM_END here */
398.1.10 by Monty Taylor
Actually removed VOID() this time.
461
  pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
462
520.1.22 by Brian Aker
Second pass of thd cleanup
463
  logging_pre_do(session);
383.6.4 by Mark Atwood
more make plug logging work
464
520.1.22 by Brian Aker
Second pass of thd cleanup
465
  session->server_status&=
1 by brian
clean slate
466
           ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
467
  switch (command) {
468
  case COM_INIT_DB:
469
  {
470
    LEX_STRING tmp;
520.1.22 by Brian Aker
Second pass of thd cleanup
471
    status_var_increment(session->status_var.com_stat[SQLCOM_CHANGE_DB]);
472
    session->convert_string(&tmp, system_charset_info,
473
                        packet, packet_length, session->charset());
474
    if (!mysql_change_db(session, &tmp, false))
1 by brian
clean slate
475
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
476
      my_ok(session);
1 by brian
clean slate
477
    }
478
    break;
479
  }
480
  case COM_CHANGE_USER:
481
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
482
    status_var_increment(session->status_var.com_other);
1 by brian
clean slate
483
    char *user= (char*) packet, *packet_end= packet + packet_length;
484
    /* Safe because there is always a trailing \0 at the end of the packet */
376 by Brian Aker
strend remove
485
    char *passwd= strchr(user, '\0')+1;
1 by brian
clean slate
486
259 by Brian Aker
First pass on PAM auth
487
520.1.22 by Brian Aker
Second pass of thd cleanup
488
    session->clear_error();                         // if errors from rollback
1 by brian
clean slate
489
490
    /*
491
      Old clients send null-terminated string ('\0' for empty string) for
492
      password.  New clients send the size (1 byte) + string (not null
493
      terminated, so also '\0' for empty string).
494
495
      Cast *passwd to an unsigned char, so that it doesn't extend the sign
438.1.13 by Brian Aker
uint cleanup.
496
      for *passwd > 127 and become 2**32-127 after casting to uint32_t.
1 by brian
clean slate
497
    */
498
    char db_buff[NAME_LEN+1];                 // buffer to store db in utf8
499
    char *db= passwd;
500
    char *save_db;
501
    /*
502
      If there is no password supplied, the packet must contain '\0',
503
      in any type of handshake (4.1 or pre-4.1).
504
     */
505
    if (passwd >= packet_end)
506
    {
507
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
508
      break;
509
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
510
    uint32_t passwd_len= (session->client_capabilities & CLIENT_SECURE_CONNECTION ?
481 by Brian Aker
Remove all of uchar.
511
                      (unsigned char)(*passwd++) : strlen(passwd));
438.1.13 by Brian Aker
uint cleanup.
512
    uint32_t dummy_errors, save_db_length, db_length;
1 by brian
clean slate
513
    int res;
514
    USER_CONN *save_user_connect;
694 by Brian Aker
Refactor out char* strdup for string class in user.
515
    string old_username;
1 by brian
clean slate
516
517
    db+= passwd_len + 1;
518
    /*
519
      Database name is always NUL-terminated, so in case of empty database
520
      the packet must contain at least the trailing '\0'.
521
    */
522
    if (db >= packet_end)
523
    {
524
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
525
      break;
526
    }
527
    db_length= strlen(db);
528
529
    char *ptr= db + db_length + 1;
438.1.13 by Brian Aker
uint cleanup.
530
    uint32_t cs_number= 0;
1 by brian
clean slate
531
532
    if (ptr < packet_end)
533
    {
534
      if (ptr + 2 > packet_end)
535
      {
536
        my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
537
        break;
538
      }
539
540
      cs_number= uint2korr(ptr);
541
    }
542
543
    /* Convert database name to utf8 */
544
    db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1,
545
                             system_charset_info, db, db_length,
520.1.22 by Brian Aker
Second pass of thd cleanup
546
                             session->charset(), &dummy_errors)]= 0;
1 by brian
clean slate
547
    db= db_buff;
548
549
    /* Save user and privileges */
520.1.22 by Brian Aker
Second pass of thd cleanup
550
    save_db_length= session->db_length;
551
    save_db= session->db;
552
    save_user_connect= session->user_connect;
1 by brian
clean slate
553
694 by Brian Aker
Refactor out char* strdup for string class in user.
554
    old_username= session->security_ctx.user;
555
    session->security_ctx.user.assign(user);
1 by brian
clean slate
556
557
    /* Clear variables that are allocated */
520.1.22 by Brian Aker
Second pass of thd cleanup
558
    session->user_connect= 0;
559
    res= check_user(session, passwd, passwd_len, db, false);
1 by brian
clean slate
560
561
    if (res)
562
    {
694 by Brian Aker
Refactor out char* strdup for string class in user.
563
      session->security_ctx.user= old_username;
520.1.22 by Brian Aker
Second pass of thd cleanup
564
      session->user_connect= save_user_connect;
565
      session->db= save_db;
566
      session->db_length= save_db_length;
1 by brian
clean slate
567
    }
568
    else
569
    {
460 by Monty Taylor
Removed x_free calls.
570
      if (save_db)
571
        free(save_db);
1 by brian
clean slate
572
573
      if (cs_number)
574
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
575
        session->update_charset();
1 by brian
clean slate
576
      }
577
    }
578
    break;
579
  }
580
  case COM_QUERY:
581
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
582
    if (alloc_query(session, packet, packet_length))
1 by brian
clean slate
583
      break;					// fatal error is set
520.1.22 by Brian Aker
Second pass of thd cleanup
584
    char *packet_end= session->query + session->query_length;
1 by brian
clean slate
585
    const char* end_of_stmt= NULL;
586
520.1.22 by Brian Aker
Second pass of thd cleanup
587
    mysql_parse(session, session->query, session->query_length, &end_of_stmt);
1 by brian
clean slate
588
520.1.22 by Brian Aker
Second pass of thd cleanup
589
    while (!session->killed && (end_of_stmt != NULL) && ! session->is_error())
1 by brian
clean slate
590
    {
591
      char *beginning_of_next_stmt= (char*) end_of_stmt;
592
520.1.22 by Brian Aker
Second pass of thd cleanup
593
      net_end_statement(session);
1 by brian
clean slate
594
      /*
595
        Multiple queries exits, execute them individually
596
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
597
      close_thread_tables(session);
1 by brian
clean slate
598
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
599
520.1.22 by Brian Aker
Second pass of thd cleanup
600
      log_slow_statement(session);
1 by brian
clean slate
601
602
      /* Remove garbage at start of query */
520.1.22 by Brian Aker
Second pass of thd cleanup
603
      while (length > 0 && my_isspace(session->charset(), *beginning_of_next_stmt))
1 by brian
clean slate
604
      {
605
        beginning_of_next_stmt++;
606
        length--;
607
      }
608
398.1.10 by Monty Taylor
Actually removed VOID() this time.
609
      pthread_mutex_lock(&LOCK_thread_count);
520.1.22 by Brian Aker
Second pass of thd cleanup
610
      session->query_length= length;
611
      session->query= beginning_of_next_stmt;
1 by brian
clean slate
612
      /*
613
        Count each statement from the client.
614
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
615
      statistic_increment(session->status_var.questions, &LOCK_status);
561.1.3 by Monty Taylor
Split some more things out of common_includes.h.
616
      session->query_id= query_id.next();
520.1.22 by Brian Aker
Second pass of thd cleanup
617
      session->set_time(); /* Reset the query start time. */
618
      /* TODO: set session->lex->sql_command to SQLCOM_END here */
398.1.10 by Monty Taylor
Actually removed VOID() this time.
619
      pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
620
520.1.22 by Brian Aker
Second pass of thd cleanup
621
      mysql_parse(session, beginning_of_next_stmt, length, &end_of_stmt);
1 by brian
clean slate
622
    }
623
    break;
624
  }
625
  case COM_FIELD_LIST:				// This isn't actually needed
626
  {
627
    char *fields, *packet_end= packet + packet_length, *arg_end;
628
    /* Locked closure of all tables */
327.2.4 by Brian Aker
Refactoring table.h
629
    TableList table_list;
1 by brian
clean slate
630
    LEX_STRING conv_name;
631
632
    /* used as fields initializator */
520.1.22 by Brian Aker
Second pass of thd cleanup
633
    lex_start(session);
1 by brian
clean slate
634
520.1.22 by Brian Aker
Second pass of thd cleanup
635
    status_var_increment(session->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
636
    memset(&table_list, 0, sizeof(table_list));
520.1.22 by Brian Aker
Second pass of thd cleanup
637
    if (session->copy_db_to(&table_list.db, &table_list.db_length))
1 by brian
clean slate
638
      break;
639
    /*
640
      We have name + wildcard in packet, separated by endzero
641
    */
376 by Brian Aker
strend remove
642
    arg_end= strchr(packet, '\0');
520.1.22 by Brian Aker
Second pass of thd cleanup
643
    session->convert_string(&conv_name, system_charset_info,
644
			packet, (uint32_t) (arg_end - packet), session->charset());
1 by brian
clean slate
645
    table_list.alias= table_list.table_name= conv_name.str;
646
    packet= arg_end + 1;
647
648
    if (!my_strcasecmp(system_charset_info, table_list.db,
575.4.7 by Monty Taylor
More header cleanup.
649
                       INFORMATION_SCHEMA_NAME.c_str()))
1 by brian
clean slate
650
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
651
      ST_SCHEMA_TABLE *schema_table= find_schema_table(session, table_list.alias);
1 by brian
clean slate
652
      if (schema_table)
653
        table_list.schema_table= schema_table;
654
    }
655
520.1.22 by Brian Aker
Second pass of thd cleanup
656
    session->query_length= (uint32_t) (packet_end - packet); // Don't count end \0
657
    if (!(session->query=fields= (char*) session->memdup(packet,session->query_length+1)))
1 by brian
clean slate
658
      break;
659
    if (lower_case_table_names)
660
      my_casedn_str(files_charset_info, table_list.table_name);
661
662
    /* init structures for VIEW processing */
520.1.22 by Brian Aker
Second pass of thd cleanup
663
    table_list.select_lex= &(session->lex->select_lex);
664
665
    lex_start(session);
735 by Brian Aker
Refactor session.
666
    session->reset_for_next_command();
520.1.22 by Brian Aker
Second pass of thd cleanup
667
668
    session->lex->
481 by Brian Aker
Remove all of uchar.
669
      select_lex.table_list.link_in_list((unsigned char*) &table_list,
670
                                         (unsigned char**) &table_list.next_local);
520.1.22 by Brian Aker
Second pass of thd cleanup
671
    session->lex->add_to_query_tables(&table_list);
1 by brian
clean slate
672
673
    /* switch on VIEW optimisation: do not fill temporary tables */
520.1.22 by Brian Aker
Second pass of thd cleanup
674
    session->lex->sql_command= SQLCOM_SHOW_FIELDS;
675
    mysqld_list_fields(session,&table_list,fields);
676
    session->lex->unit.cleanup();
677
    session->cleanup_after_query();
1 by brian
clean slate
678
    break;
679
  }
680
  case COM_QUIT:
681
    /* We don't calculate statistics for this command */
682
    net->error=0;				// Don't give 'abort' message
520.1.22 by Brian Aker
Second pass of thd cleanup
683
    session->main_da.disable_status();              // Don't send anything back
55 by brian
Update for using real bool types.
684
    error=true;					// End server
1 by brian
clean slate
685
    break;
686
  case COM_SHUTDOWN:
687
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
688
    status_var_increment(session->status_var.com_other);
689
    my_eof(session);
690
    close_thread_tables(session);			// Free before kill
575.4.4 by Yoshinori Sano
Rename mysql to drizzle.
691
    kill_drizzle();
55 by brian
Update for using real bool types.
692
    error=true;
1 by brian
clean slate
693
    break;
694
  }
695
  case COM_PING:
520.1.22 by Brian Aker
Second pass of thd cleanup
696
    status_var_increment(session->status_var.com_other);
697
    my_ok(session);				// Tell client we are alive
1 by brian
clean slate
698
    break;
699
  case COM_PROCESS_INFO:
520.1.22 by Brian Aker
Second pass of thd cleanup
700
    status_var_increment(session->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
701
    mysqld_list_processes(session, NULL, 0);
1 by brian
clean slate
702
    break;
703
  case COM_PROCESS_KILL:
704
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
705
    status_var_increment(session->status_var.com_stat[SQLCOM_KILL]);
1 by brian
clean slate
706
    ulong id=(ulong) uint4korr(packet);
520.1.22 by Brian Aker
Second pass of thd cleanup
707
    sql_kill(session,id,false);
1 by brian
clean slate
708
    break;
709
  }
710
  case COM_SET_OPTION:
711
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
712
    status_var_increment(session->status_var.com_stat[SQLCOM_SET_OPTION]);
438.1.13 by Brian Aker
uint cleanup.
713
    uint32_t opt_command= uint2korr(packet);
1 by brian
clean slate
714
715
    switch (opt_command) {
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
716
    case (int) DRIZZLE_OPTION_MULTI_STATEMENTS_ON:
520.1.22 by Brian Aker
Second pass of thd cleanup
717
      session->client_capabilities|= CLIENT_MULTI_STATEMENTS;
718
      my_eof(session);
1 by brian
clean slate
719
      break;
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
720
    case (int) DRIZZLE_OPTION_MULTI_STATEMENTS_OFF:
520.1.22 by Brian Aker
Second pass of thd cleanup
721
      session->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
722
      my_eof(session);
1 by brian
clean slate
723
      break;
724
    default:
725
      my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
726
      break;
727
    }
728
    break;
729
  }
730
  case COM_SLEEP:
731
  case COM_CONNECT:				// Impossible here
732
  case COM_TIME:				// Impossible from client
733
  case COM_END:
734
  default:
735
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
736
    break;
737
  }
738
739
  /* If commit fails, we should be able to reset the OK status. */
520.1.22 by Brian Aker
Second pass of thd cleanup
740
  session->main_da.can_overwrite_status= true;
741
  ha_autocommit_or_rollback(session, session->is_error());
742
  session->main_da.can_overwrite_status= false;
1 by brian
clean slate
743
520.1.22 by Brian Aker
Second pass of thd cleanup
744
  session->transaction.stmt.reset();
1 by brian
clean slate
745
746
747
  /* report error issued during command execution */
520.1.22 by Brian Aker
Second pass of thd cleanup
748
  if (session->killed_errno())
749
  {
750
    if (! session->main_da.is_set())
751
      session->send_kill_message();
752
  }
753
  if (session->killed == Session::KILL_QUERY || session->killed == Session::KILL_BAD_DATA)
754
  {
755
    session->killed= Session::NOT_KILLED;
756
    session->mysys_var->abort= 0;
757
  }
758
759
  net_end_statement(session);
760
761
  session->set_proc_info("closing tables");
1 by brian
clean slate
762
  /* Free tables */
520.1.22 by Brian Aker
Second pass of thd cleanup
763
  close_thread_tables(session);
764
765
  log_slow_statement(session);
766
767
  session->set_proc_info("cleaning up");
398.1.10 by Monty Taylor
Actually removed VOID() this time.
768
  pthread_mutex_lock(&LOCK_thread_count); // For process list
520.1.22 by Brian Aker
Second pass of thd cleanup
769
  session->set_proc_info(0);
770
  session->command=COM_SLEEP;
771
  session->query=0;
772
  session->query_length=0;
1 by brian
clean slate
773
  thread_running--;
398.1.10 by Monty Taylor
Actually removed VOID() this time.
774
  pthread_mutex_unlock(&LOCK_thread_count);
520.1.22 by Brian Aker
Second pass of thd cleanup
775
  session->packet.shrink(session->variables.net_buffer_length);	// Reclaim some memory
776
  free_root(session->mem_root,MYF(MY_KEEP_PREALLOC));
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
777
  return(error);
1 by brian
clean slate
778
}
779
780
520.1.22 by Brian Aker
Second pass of thd cleanup
781
void log_slow_statement(Session *session)
1 by brian
clean slate
782
{
520.1.22 by Brian Aker
Second pass of thd cleanup
783
  logging_post_do(session);
383.6.4 by Mark Atwood
more make plug logging work
784
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
785
  return;
1 by brian
clean slate
786
}
787
788
789
/**
327.2.4 by Brian Aker
Refactoring table.h
790
  Create a TableList object for an INFORMATION_SCHEMA table.
1 by brian
clean slate
791
792
    This function is used in the parser to convert a SHOW or DESCRIBE
793
    table_name command to a SELECT from INFORMATION_SCHEMA.
327.2.4 by Brian Aker
Refactoring table.h
794
    It prepares a SELECT_LEX and a TableList object to represent the
1 by brian
clean slate
795
    given command as a SELECT parse tree.
796
520.1.22 by Brian Aker
Second pass of thd cleanup
797
  @param session              thread handle
1 by brian
clean slate
798
  @param lex              current lex
799
  @param table_ident      table alias if it's used
800
  @param schema_table_idx the type of the INFORMATION_SCHEMA table to be
801
                          created
802
803
  @note
804
    Due to the way this function works with memory and LEX it cannot
805
    be used outside the parser (parse tree transformations outside
806
    the parser break PS and SP).
807
808
  @retval
809
    0                 success
810
  @retval
811
    1                 out of memory or SHOW commands are not allowed
812
                      in this version of the server.
813
*/
814
520.1.22 by Brian Aker
Second pass of thd cleanup
815
int prepare_schema_table(Session *session, LEX *lex, Table_ident *table_ident,
1 by brian
clean slate
816
                         enum enum_schema_tables schema_table_idx)
817
{
818
  SELECT_LEX *schema_select_lex= NULL;
819
820
  switch (schema_table_idx) {
821
  case SCH_SCHEMATA:
822
    break;
823
  case SCH_TABLE_NAMES:
824
  case SCH_TABLES:
825
    {
826
      LEX_STRING db;
827
      size_t dummy;
828
      if (lex->select_lex.db == NULL &&
829
          lex->copy_db_to(&lex->select_lex.db, &dummy))
830
      {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
831
        return(1);
1 by brian
clean slate
832
      }
833
      schema_select_lex= new SELECT_LEX();
834
      db.str= schema_select_lex->db= lex->select_lex.db;
835
      schema_select_lex->table_list.first= NULL;
836
      db.length= strlen(db.str);
837
838
      if (check_db_name(&db))
839
      {
840
        my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
841
        return(1);
1 by brian
clean slate
842
      }
843
      break;
844
    }
845
  case SCH_COLUMNS:
846
  case SCH_STATISTICS:
847
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
848
    assert(table_ident);
327.2.4 by Brian Aker
Refactoring table.h
849
    TableList **query_tables_last= lex->query_tables_last;
1 by brian
clean slate
850
    schema_select_lex= new SELECT_LEX();
851
    /* 'parent_lex' is used in init_query() so it must be before it. */
852
    schema_select_lex->parent_lex= lex;
853
    schema_select_lex->init_query();
520.1.22 by Brian Aker
Second pass of thd cleanup
854
    if (!schema_select_lex->add_table_to_list(session, table_ident, 0, 0, TL_READ))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
855
      return(1);
1 by brian
clean slate
856
    lex->query_tables_last= query_tables_last;
857
    break;
858
  }
859
  case SCH_OPEN_TABLES:
860
  case SCH_VARIABLES:
861
  case SCH_STATUS:
862
  case SCH_CHARSETS:
863
  case SCH_COLLATIONS:
864
  case SCH_COLLATION_CHARACTER_SET_APPLICABILITY:
865
  case SCH_TABLE_CONSTRAINTS:
866
  case SCH_KEY_COLUMN_USAGE:
867
  default:
868
    break;
869
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
870
1 by brian
clean slate
871
  SELECT_LEX *select_lex= lex->current_select;
872
  assert(select_lex);
520.1.22 by Brian Aker
Second pass of thd cleanup
873
  if (make_schema_select(session, select_lex, schema_table_idx))
1 by brian
clean slate
874
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
875
    return(1);
1 by brian
clean slate
876
  }
327.2.4 by Brian Aker
Refactoring table.h
877
  TableList *table_list= (TableList*) select_lex->table_list.first;
1 by brian
clean slate
878
  assert(table_list);
879
  table_list->schema_select_lex= schema_select_lex;
880
  table_list->schema_table_reformed= 1;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
881
  return(0);
1 by brian
clean slate
882
}
883
884
885
/**
520.1.22 by Brian Aker
Second pass of thd cleanup
886
  Read query from packet and store in session->query.
1 by brian
clean slate
887
  Used in COM_QUERY and COM_STMT_PREPARE.
888
520.1.21 by Brian Aker
THD -> Session rename
889
    Sets the following Session variables:
1 by brian
clean slate
890
  - query
891
  - query_length
892
893
  @retval
55 by brian
Update for using real bool types.
894
    false ok
1 by brian
clean slate
895
  @retval
520.1.22 by Brian Aker
Second pass of thd cleanup
896
    true  error;  In this case session->fatal_error is set
1 by brian
clean slate
897
*/
898
520.1.22 by Brian Aker
Second pass of thd cleanup
899
bool alloc_query(Session *session, const char *packet, uint32_t packet_length)
1 by brian
clean slate
900
{
901
  /* Remove garbage at start and end of query */
520.1.22 by Brian Aker
Second pass of thd cleanup
902
  while (packet_length > 0 && my_isspace(session->charset(), packet[0]))
1 by brian
clean slate
903
  {
904
    packet++;
905
    packet_length--;
906
  }
907
  const char *pos= packet + packet_length;     // Point at end null
908
  while (packet_length > 0 &&
520.1.22 by Brian Aker
Second pass of thd cleanup
909
	 (pos[-1] == ';' || my_isspace(session->charset() ,pos[-1])))
1 by brian
clean slate
910
  {
911
    pos--;
912
    packet_length--;
913
  }
914
  /* We must allocate some extra memory for query cache */
520.1.22 by Brian Aker
Second pass of thd cleanup
915
  session->query_length= 0;                        // Extra safety: Avoid races
916
  if (!(session->query= (char*) session->memdup_w_gap((unsigned char*) (packet),
1 by brian
clean slate
917
					      packet_length,
520.1.22 by Brian Aker
Second pass of thd cleanup
918
					      session->db_length+ 1)))
55 by brian
Update for using real bool types.
919
    return true;
520.1.22 by Brian Aker
Second pass of thd cleanup
920
  session->query[packet_length]=0;
921
  session->query_length= packet_length;
1 by brian
clean slate
922
923
  /* Reclaim some memory */
520.1.22 by Brian Aker
Second pass of thd cleanup
924
  session->packet.shrink(session->variables.net_buffer_length);
925
  session->convert_buffer.shrink(session->variables.net_buffer_length);
1 by brian
clean slate
926
55 by brian
Update for using real bool types.
927
  return false;
1 by brian
clean slate
928
}
929
930
/**
520.1.22 by Brian Aker
Second pass of thd cleanup
931
  Execute command saved in session and lex->sql_command.
1 by brian
clean slate
932
933
    Before every operation that can request a write lock for a table
934
    wait if a global read lock exists. However do not wait if this
935
    thread has locked tables already. No new locks can be requested
936
    until the other locks are released. The thread that requests the
937
    global read lock waits for write locked tables to become unlocked.
938
939
    Note that wait_if_global_read_lock() sets a protection against a new
940
    global read lock when it succeeds. This needs to be released by
941
    start_waiting_global_read_lock() after the operation.
942
520.1.22 by Brian Aker
Second pass of thd cleanup
943
  @param session                       Thread handle
1 by brian
clean slate
944
945
  @todo
946
    - Invalidate the table in the query cache if something changed
947
    after unlocking when changes become visible.
948
    TODO: this is workaround. right way will be move invalidating in
949
    the unlock procedure.
950
    - TODO: use check_change_password()
951
    - JOIN is not supported yet. TODO
952
    - SUSPEND and FOR MIGRATE are not supported yet. TODO
953
954
  @retval
55 by brian
Update for using real bool types.
955
    false       OK
1 by brian
clean slate
956
  @retval
55 by brian
Update for using real bool types.
957
    true        Error
1 by brian
clean slate
958
*/
959
960
int
520.1.22 by Brian Aker
Second pass of thd cleanup
961
mysql_execute_command(Session *session)
1 by brian
clean slate
962
{
55 by brian
Update for using real bool types.
963
  int res= false;
964
  bool need_start_waiting= false; // have protection against global read lock
520.1.22 by Brian Aker
Second pass of thd cleanup
965
  LEX  *lex= session->lex;
1 by brian
clean slate
966
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
967
  SELECT_LEX *select_lex= &lex->select_lex;
968
  /* first table of first SELECT_LEX */
327.2.4 by Brian Aker
Refactoring table.h
969
  TableList *first_table= (TableList*) select_lex->table_list.first;
1 by brian
clean slate
970
  /* list of all tables in query */
327.2.4 by Brian Aker
Refactoring table.h
971
  TableList *all_tables;
1 by brian
clean slate
972
  /* most outer SELECT_LEX_UNIT of query */
973
  SELECT_LEX_UNIT *unit= &lex->unit;
974
  /* Saved variable value */
975
976
  /*
977
    In many cases first table of main SELECT_LEX have special meaning =>
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
978
    check that it is first table in global list and relink it first in
1 by brian
clean slate
979
    queries_tables list if it is necessary (we need such relinking only
980
    for queries with subqueries in select list, in this case tables of
981
    subqueries will go to global list first)
982
983
    all_tables will differ from first_table only if most upper SELECT_LEX
984
    do not contain tables.
985
986
    Because of above in place where should be at least one table in most
987
    outer SELECT_LEX we have following check:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
988
    assert(first_table == all_tables);
989
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
990
  */
991
  lex->first_lists_tables_same();
992
  /* should be assigned after making first tables same */
993
  all_tables= lex->query_tables;
994
  /* set context for commands which do not use setup_tables */
995
  select_lex->
327.2.4 by Brian Aker
Refactoring table.h
996
    context.resolve_in_table_list_only((TableList*)select_lex->
1 by brian
clean slate
997
                                       table_list.first);
998
999
  /*
1000
    Reset warning count for each query that uses tables
1001
    A better approach would be to reset this for any commands
1002
    that is not a SHOW command or a select that only access local
1003
    variables, but for now this is probably good enough.
1004
    Don't reset warnings when executing a stored routine.
1005
  */
1006
  if (all_tables || !lex->is_single_level_stmt())
520.1.22 by Brian Aker
Second pass of thd cleanup
1007
    drizzle_reset_errors(session, 0);
1 by brian
clean slate
1008
520.1.22 by Brian Aker
Second pass of thd cleanup
1009
  status_var_increment(session->status_var.com_stat[lex->sql_command]);
1 by brian
clean slate
1010
520.1.22 by Brian Aker
Second pass of thd cleanup
1011
  assert(session->transaction.stmt.modified_non_trans_table == false);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1012
1 by brian
clean slate
1013
  switch (lex->sql_command) {
1014
  case SQLCOM_SHOW_STATUS:
1015
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1016
    system_status_var old_status_var= session->status_var;
1017
    session->initial_status_var= &old_status_var;
1018
    res= execute_sqlcom_select(session, all_tables);
1 by brian
clean slate
1019
    /* Don't log SHOW STATUS commands to slow query log */
520.1.22 by Brian Aker
Second pass of thd cleanup
1020
    session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
1 by brian
clean slate
1021
                           SERVER_QUERY_NO_GOOD_INDEX_USED);
1022
    /*
1023
      restore status variables, as we don't want 'show status' to cause
1024
      changes
1025
    */
1026
    pthread_mutex_lock(&LOCK_status);
520.1.22 by Brian Aker
Second pass of thd cleanup
1027
    add_diff_to_status(&global_status_var, &session->status_var,
1 by brian
clean slate
1028
                       &old_status_var);
520.1.22 by Brian Aker
Second pass of thd cleanup
1029
    session->status_var= old_status_var;
1 by brian
clean slate
1030
    pthread_mutex_unlock(&LOCK_status);
1031
    break;
1032
  }
1033
  case SQLCOM_SHOW_DATABASES:
1034
  case SQLCOM_SHOW_TABLES:
1035
  case SQLCOM_SHOW_TABLE_STATUS:
1036
  case SQLCOM_SHOW_OPEN_TABLES:
1037
  case SQLCOM_SHOW_FIELDS:
1038
  case SQLCOM_SHOW_KEYS:
1039
  case SQLCOM_SHOW_VARIABLES:
1040
  case SQLCOM_SELECT:
1041
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1042
    session->status_var.last_query_cost= 0.0;
1043
    res= execute_sqlcom_select(session, all_tables);
1 by brian
clean slate
1044
    break;
1045
  }
1046
  case SQLCOM_EMPTY_QUERY:
520.1.22 by Brian Aker
Second pass of thd cleanup
1047
    my_ok(session);
1 by brian
clean slate
1048
    break;
1049
1050
  case SQLCOM_SHOW_WARNS:
1051
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1052
    res= mysqld_show_warnings(session, (uint32_t)
438.1.13 by Brian Aker
uint cleanup.
1053
			      ((1L << (uint32_t) DRIZZLE_ERROR::WARN_LEVEL_NOTE) |
1054
			       (1L << (uint32_t) DRIZZLE_ERROR::WARN_LEVEL_WARN) |
1055
			       (1L << (uint32_t) DRIZZLE_ERROR::WARN_LEVEL_ERROR)
1 by brian
clean slate
1056
			       ));
1057
    break;
1058
  }
1059
  case SQLCOM_SHOW_ERRORS:
1060
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1061
    res= mysqld_show_warnings(session, (uint32_t)
438.1.13 by Brian Aker
uint cleanup.
1062
			      (1L << (uint32_t) DRIZZLE_ERROR::WARN_LEVEL_ERROR));
1 by brian
clean slate
1063
    break;
1064
  }
1065
  case SQLCOM_ASSIGN_TO_KEYCACHE:
1066
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1067
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1068
    res= mysql_assign_to_keycache(session, first_table, &lex->ident);
1 by brian
clean slate
1069
    break;
1070
  }
1071
  case SQLCOM_SHOW_ENGINE_STATUS:
1072
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1073
      res = ha_show_status(session, lex->create_info.db_type, HA_ENGINE_STATUS);
1 by brian
clean slate
1074
      break;
1075
    }
1076
  case SQLCOM_CREATE_TABLE:
1077
  {
1078
    /* If CREATE TABLE of non-temporary table, do implicit commit */
1079
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
1080
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1081
      if (end_active_trans(session))
1 by brian
clean slate
1082
      {
1083
	res= -1;
1084
	break;
1085
      }
1086
    }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1087
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
1088
    bool link_to_local;
1089
    // Skip first table, which is the table we are creating
327.2.4 by Brian Aker
Refactoring table.h
1090
    TableList *create_table= lex->unlink_first_table(&link_to_local);
1091
    TableList *select_tables= lex->query_tables;
1 by brian
clean slate
1092
    /*
1093
      Code below (especially in mysql_create_table() and select_create
1094
      methods) may modify HA_CREATE_INFO structure in LEX, so we have to
1095
      use a copy of this structure to make execution prepared statement-
1096
      safe. A shallow copy is enough as this code won't modify any memory
1097
      referenced from this structure.
1098
    */
1099
    HA_CREATE_INFO create_info(lex->create_info);
1100
    /*
1101
      We need to copy alter_info for the same reasons of re-execution
1102
      safety, only in case of Alter_info we have to do (almost) a deep
1103
      copy.
1104
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1105
    Alter_info alter_info(lex->alter_info, session->mem_root);
1 by brian
clean slate
1106
520.1.22 by Brian Aker
Second pass of thd cleanup
1107
    if (session->is_fatal_error)
1 by brian
clean slate
1108
    {
1109
      /* If out of memory when creating a copy of alter_info. */
1110
      res= 1;
1111
      goto end_with_restore_list;
1112
    }
1113
520.1.22 by Brian Aker
Second pass of thd cleanup
1114
    if ((res= create_table_precheck(session, select_tables, create_table)))
1 by brian
clean slate
1115
      goto end_with_restore_list;
1116
1117
    /* Might have been updated in create_table_precheck */
1118
    create_info.alias= create_table->alias;
1119
1120
#ifdef HAVE_READLINK
1121
    /* Fix names if symlinked tables */
520.1.22 by Brian Aker
Second pass of thd cleanup
1122
    if (append_file_to_dir(session, &create_info.data_file_name,
1 by brian
clean slate
1123
			   create_table->table_name) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1124
	append_file_to_dir(session, &create_info.index_file_name,
1 by brian
clean slate
1125
			   create_table->table_name))
1126
      goto end_with_restore_list;
1127
#endif
1128
    /*
1129
      If we are using SET CHARSET without DEFAULT, add an implicit
1130
      DEFAULT to not confuse old users. (This may change).
1131
    */
1132
    if ((create_info.used_fields &
1133
	 (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) ==
1134
	HA_CREATE_USED_CHARSET)
1135
    {
1136
      create_info.used_fields&= ~HA_CREATE_USED_CHARSET;
1137
      create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET;
1138
      create_info.default_table_charset= create_info.table_charset;
1139
      create_info.table_charset= 0;
1140
    }
1141
    /*
1142
      The create-select command will open and read-lock the select table
1143
      and then create, open and write-lock the new table. If a global
1144
      read lock steps in, we get a deadlock. The write lock waits for
1145
      the global read lock, while the global read lock waits for the
1146
      select table to be closed. So we wait until the global readlock is
1147
      gone before starting both steps. Note that
1148
      wait_if_global_read_lock() sets a protection against a new global
1149
      read lock when it succeeds. This needs to be released by
1150
      start_waiting_global_read_lock(). We protect the normal CREATE
1151
      TABLE in the same way. That way we avoid that a new table is
1152
      created during a gobal read lock.
1153
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1154
    if (!session->locked_tables &&
1155
        !(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
1 by brian
clean slate
1156
    {
1157
      res= 1;
1158
      goto end_with_restore_list;
1159
    }
1160
    if (select_lex->item_list.elements)		// With select
1161
    {
1162
      select_result *result;
1163
1164
      select_lex->options|= SELECT_NO_UNLOCK;
1165
      unit->set_limit(select_lex);
1166
1167
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1168
      {
1169
        lex->link_first_table_back(create_table, link_to_local);
55 by brian
Update for using real bool types.
1170
        create_table->create= true;
1 by brian
clean slate
1171
      }
1172
520.1.22 by Brian Aker
Second pass of thd cleanup
1173
      if (!(res= open_and_lock_tables(session, lex->query_tables)))
1 by brian
clean slate
1174
      {
1175
        /*
1176
          Is table which we are changing used somewhere in other parts
1177
          of query
1178
        */
1179
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1180
        {
327.2.4 by Brian Aker
Refactoring table.h
1181
          TableList *duplicate;
1 by brian
clean slate
1182
          create_table= lex->unlink_first_table(&link_to_local);
520.1.22 by Brian Aker
Second pass of thd cleanup
1183
          if ((duplicate= unique_table(session, create_table, select_tables, 0)))
1 by brian
clean slate
1184
          {
1185
            update_non_unique_table_error(create_table, "CREATE", duplicate);
1186
            res= 1;
1187
            goto end_with_restore_list;
1188
          }
1189
        }
1190
1191
        /*
1192
          select_create is currently not re-execution friendly and
1193
          needs to be created for every execution of a PS/SP.
1194
        */
1195
        if ((result= new select_create(create_table,
1196
                                       &create_info,
1197
                                       &alter_info,
1198
                                       select_lex->item_list,
1199
                                       lex->duplicates,
1200
                                       lex->ignore,
1201
                                       select_tables)))
1202
        {
1203
          /*
1204
            CREATE from SELECT give its SELECT_LEX for SELECT,
1205
            and item_list belong to SELECT
1206
          */
520.1.22 by Brian Aker
Second pass of thd cleanup
1207
          res= handle_select(session, lex, result, 0);
1 by brian
clean slate
1208
          delete result;
1209
        }
1210
      }
1211
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
1212
        create_table= lex->unlink_first_table(&link_to_local);
1213
1214
    }
1215
    else
1216
    {
1217
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
1218
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
520.1.22 by Brian Aker
Second pass of thd cleanup
1219
        session->options|= OPTION_KEEP_LOG;
1 by brian
clean slate
1220
      /* regular create */
1221
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
520.1.22 by Brian Aker
Second pass of thd cleanup
1222
        res= mysql_create_like_table(session, create_table, select_tables,
1 by brian
clean slate
1223
                                     &create_info);
1224
      else
1225
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1226
        res= mysql_create_table(session, create_table->db,
1 by brian
clean slate
1227
                                create_table->table_name, &create_info,
1228
                                &alter_info, 0, 0);
1229
      }
1230
      if (!res)
520.1.22 by Brian Aker
Second pass of thd cleanup
1231
	my_ok(session);
1 by brian
clean slate
1232
    }
1233
1234
    /* put tables back for PS rexecuting */
1235
end_with_restore_list:
1236
    lex->link_first_table_back(create_table, link_to_local);
1237
    break;
1238
  }
1239
  case SQLCOM_CREATE_INDEX:
1240
    /* Fall through */
1241
  case SQLCOM_DROP_INDEX:
1242
  /*
1243
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
1244
    TABLE with proper arguments.
1245
1246
    In the future ALTER TABLE will notice that the request is to
1247
    only add indexes and create these one by one for the existing
1248
    table without having to do a full rebuild.
1249
  */
1250
  {
1251
    /* Prepare stack copies to be re-execution safe */
1252
    HA_CREATE_INFO create_info;
520.1.22 by Brian Aker
Second pass of thd cleanup
1253
    Alter_info alter_info(lex->alter_info, session->mem_root);
1 by brian
clean slate
1254
520.1.22 by Brian Aker
Second pass of thd cleanup
1255
    if (session->is_fatal_error) /* out of memory creating a copy of alter_info */
1 by brian
clean slate
1256
      goto error;
1257
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1258
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1259
    if (end_active_trans(session))
1 by brian
clean slate
1260
      goto error;
1261
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1262
    memset(&create_info, 0, sizeof(create_info));
1 by brian
clean slate
1263
    create_info.db_type= 0;
1264
    create_info.row_type= ROW_TYPE_NOT_USED;
520.1.22 by Brian Aker
Second pass of thd cleanup
1265
    create_info.default_table_charset= session->variables.collation_database;
1 by brian
clean slate
1266
520.1.22 by Brian Aker
Second pass of thd cleanup
1267
    res= mysql_alter_table(session, first_table->db, first_table->table_name,
1 by brian
clean slate
1268
                           &create_info, first_table, &alter_info,
327.2.3 by Brian Aker
Refactoring of class Table
1269
                           0, (order_st*) 0, 0);
1 by brian
clean slate
1270
    break;
1271
  }
1272
  case SQLCOM_ALTER_TABLE:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1273
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
1274
    {
1275
      /*
1276
        Code in mysql_alter_table() may modify its HA_CREATE_INFO argument,
1277
        so we have to use a copy of this structure to make execution
1278
        prepared statement- safe. A shallow copy is enough as no memory
1279
        referenced from this structure will be modified.
1280
      */
1281
      HA_CREATE_INFO create_info(lex->create_info);
520.1.22 by Brian Aker
Second pass of thd cleanup
1282
      Alter_info alter_info(lex->alter_info, session->mem_root);
1 by brian
clean slate
1283
520.1.22 by Brian Aker
Second pass of thd cleanup
1284
      if (session->is_fatal_error) /* out of memory creating a copy of alter_info */
1 by brian
clean slate
1285
      {
1286
        goto error;
1287
      }
1288
1289
      /* Must be set in the parser */
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1290
      assert(select_lex->db);
1 by brian
clean slate
1291
1292
      { // Rename of table
327.2.4 by Brian Aker
Refactoring table.h
1293
          TableList tmp_table;
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1294
          memset(&tmp_table, 0, sizeof(tmp_table));
1 by brian
clean slate
1295
          tmp_table.table_name= lex->name.str;
1296
          tmp_table.db=select_lex->db;
1297
      }
1298
1299
      /* Don't yet allow changing of symlinks with ALTER TABLE */
1300
      if (create_info.data_file_name)
520.1.22 by Brian Aker
Second pass of thd cleanup
1301
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, 0,
1 by brian
clean slate
1302
                     "DATA DIRECTORY option ignored");
1303
      if (create_info.index_file_name)
520.1.22 by Brian Aker
Second pass of thd cleanup
1304
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, 0,
1 by brian
clean slate
1305
                     "INDEX DIRECTORY option ignored");
1306
      create_info.data_file_name= create_info.index_file_name= NULL;
1307
      /* ALTER TABLE ends previous transaction */
520.1.22 by Brian Aker
Second pass of thd cleanup
1308
      if (end_active_trans(session))
1 by brian
clean slate
1309
	goto error;
1310
520.1.22 by Brian Aker
Second pass of thd cleanup
1311
      if (!session->locked_tables &&
1312
          !(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
1 by brian
clean slate
1313
      {
1314
        res= 1;
1315
        break;
1316
      }
1317
520.1.22 by Brian Aker
Second pass of thd cleanup
1318
      res= mysql_alter_table(session, select_lex->db, lex->name.str,
1 by brian
clean slate
1319
                             &create_info,
1320
                             first_table,
1321
                             &alter_info,
1322
                             select_lex->order_list.elements,
327.2.3 by Brian Aker
Refactoring of class Table
1323
                             (order_st *) select_lex->order_list.first,
1 by brian
clean slate
1324
                             lex->ignore);
1325
      break;
1326
    }
1327
  case SQLCOM_RENAME_TABLE:
1328
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1329
    assert(first_table == all_tables && first_table != 0);
327.2.4 by Brian Aker
Refactoring table.h
1330
    TableList *table;
1 by brian
clean slate
1331
    for (table= first_table; table; table= table->next_local->next_local)
1332
    {
327.2.4 by Brian Aker
Refactoring table.h
1333
      TableList old_list, new_list;
1 by brian
clean slate
1334
      /*
1335
        we do not need initialize old_list and new_list because we will
1336
        come table[0] and table->next[0] there
1337
      */
1338
      old_list= table[0];
1339
      new_list= table->next_local[0];
1340
    }
1341
575.2.2 by Monty Taylor
Moved vio stuff into libdrizzle.
1342
    if (end_active_trans(session) || drizzle_rename_tables(session, first_table, 0))
1 by brian
clean slate
1343
      {
1344
        goto error;
1345
      }
1346
    break;
1347
  }
1348
  case SQLCOM_SHOW_CREATE:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1349
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
1350
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1351
      res= mysqld_show_create(session, first_table);
1 by brian
clean slate
1352
      break;
1353
    }
1354
  case SQLCOM_CHECKSUM:
1355
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1356
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1357
    res = mysql_checksum_table(session, first_table, &lex->check_opt);
1 by brian
clean slate
1358
    break;
1359
  }
1360
  case SQLCOM_REPAIR:
1361
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1362
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1363
    res= mysql_repair_table(session, first_table, &lex->check_opt);
1 by brian
clean slate
1364
    /* ! we write after unlocking the table */
383.1.26 by Brian Aker
Removed option for single command replication and have now left disable of
1365
    /*
1366
      Presumably, REPAIR and binlog writing doesn't require synchronization
1367
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1368
    write_bin_log(session, true, session->query, session->query_length);
481 by Brian Aker
Remove all of uchar.
1369
    select_lex->table_list.first= (unsigned char*) first_table;
1 by brian
clean slate
1370
    lex->query_tables=all_tables;
1371
    break;
1372
  }
1373
  case SQLCOM_CHECK:
1374
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1375
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1376
    res = mysql_check_table(session, first_table, &lex->check_opt);
481 by Brian Aker
Remove all of uchar.
1377
    select_lex->table_list.first= (unsigned char*) first_table;
1 by brian
clean slate
1378
    lex->query_tables=all_tables;
1379
    break;
1380
  }
1381
  case SQLCOM_ANALYZE:
1382
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1383
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1384
    res= mysql_analyze_table(session, first_table, &lex->check_opt);
1 by brian
clean slate
1385
    /* ! we write after unlocking the table */
520.1.22 by Brian Aker
Second pass of thd cleanup
1386
    write_bin_log(session, true, session->query, session->query_length);
481 by Brian Aker
Remove all of uchar.
1387
    select_lex->table_list.first= (unsigned char*) first_table;
1 by brian
clean slate
1388
    lex->query_tables=all_tables;
1389
    break;
1390
  }
1391
1392
  case SQLCOM_OPTIMIZE:
1393
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1394
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1395
    res= mysql_optimize_table(session, first_table, &lex->check_opt);
1 by brian
clean slate
1396
    /* ! we write after unlocking the table */
520.1.22 by Brian Aker
Second pass of thd cleanup
1397
    write_bin_log(session, true, session->query, session->query_length);
481 by Brian Aker
Remove all of uchar.
1398
    select_lex->table_list.first= (unsigned char*) first_table;
1 by brian
clean slate
1399
    lex->query_tables=all_tables;
1400
    break;
1401
  }
1402
  case SQLCOM_UPDATE:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1403
    assert(first_table == all_tables && first_table != 0);
826 by Brian Aker
Simplify update
1404
    if ((res= update_precheck(session, all_tables)))
1 by brian
clean slate
1405
      break;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1406
    assert(select_lex->offset_limit == 0);
1 by brian
clean slate
1407
    unit->set_limit(select_lex);
825 by Brian Aker
Cleaned up interface notes on UPDATE
1408
    res= mysql_update(session, all_tables,
1409
                      select_lex->item_list,
1410
                      lex->value_list,
1411
                      select_lex->where,
1412
                      select_lex->order_list.elements,
1413
                      (order_st *) select_lex->order_list.first,
1414
                      unit->select_limit_cnt,
1415
                      lex->duplicates, lex->ignore);
1416
    break;
1 by brian
clean slate
1417
  case SQLCOM_UPDATE_MULTI:
1418
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1419
    assert(first_table == all_tables && first_table != 0);
826 by Brian Aker
Simplify update
1420
    if ((res= update_precheck(session, all_tables)))
825 by Brian Aker
Cleaned up interface notes on UPDATE
1421
      break;
1422
1423
    if ((res= mysql_multi_update_prepare(session)))
1424
      break;
1 by brian
clean slate
1425
520.1.22 by Brian Aker
Second pass of thd cleanup
1426
    res= mysql_multi_update(session, all_tables,
1 by brian
clean slate
1427
                            &select_lex->item_list,
1428
                            &lex->value_list,
1429
                            select_lex->where,
1430
                            select_lex->options,
1431
                            lex->duplicates, lex->ignore, unit, select_lex);
1432
    break;
1433
  }
1434
  case SQLCOM_REPLACE:
1435
  case SQLCOM_INSERT:
1436
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1437
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1438
    if ((res= insert_precheck(session, all_tables)))
1 by brian
clean slate
1439
      break;
1440
520.1.22 by Brian Aker
Second pass of thd cleanup
1441
    if (!session->locked_tables &&
1442
        !(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
1 by brian
clean slate
1443
    {
1444
      res= 1;
1445
      break;
1446
    }
1447
520.1.22 by Brian Aker
Second pass of thd cleanup
1448
    res= mysql_insert(session, all_tables, lex->field_list, lex->many_values,
1 by brian
clean slate
1449
		      lex->update_list, lex->value_list,
1450
                      lex->duplicates, lex->ignore);
1451
1452
    break;
1453
  }
1454
  case SQLCOM_REPLACE_SELECT:
1455
  case SQLCOM_INSERT_SELECT:
1456
  {
1457
    select_result *sel_result;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1458
    assert(first_table == all_tables && first_table != 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1459
    if ((res= insert_precheck(session, all_tables)))
1 by brian
clean slate
1460
      break;
1461
1462
    /* Fix lock for first table */
1463
    if (first_table->lock_type == TL_WRITE_DELAYED)
1464
      first_table->lock_type= TL_WRITE;
1465
1466
    /* Don't unlock tables until command is written to binary log */
1467
    select_lex->options|= SELECT_NO_UNLOCK;
1468
1469
    unit->set_limit(select_lex);
1470
520.1.22 by Brian Aker
Second pass of thd cleanup
1471
    if (! session->locked_tables &&
1472
        ! (need_start_waiting= ! wait_if_global_read_lock(session, 0, 1)))
1 by brian
clean slate
1473
    {
1474
      res= 1;
1475
      break;
1476
    }
1477
520.1.22 by Brian Aker
Second pass of thd cleanup
1478
    if (!(res= open_and_lock_tables(session, all_tables)))
1 by brian
clean slate
1479
    {
1480
      /* Skip first table, which is the table we are inserting in */
327.2.4 by Brian Aker
Refactoring table.h
1481
      TableList *second_table= first_table->next_local;
481 by Brian Aker
Remove all of uchar.
1482
      select_lex->table_list.first= (unsigned char*) second_table;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1483
      select_lex->context.table_list=
1 by brian
clean slate
1484
        select_lex->context.first_name_resolution_table= second_table;
520.1.22 by Brian Aker
Second pass of thd cleanup
1485
      res= mysql_insert_select_prepare(session);
1 by brian
clean slate
1486
      if (!res && (sel_result= new select_insert(first_table,
1487
                                                 first_table->table,
1488
                                                 &lex->field_list,
1489
                                                 &lex->update_list,
1490
                                                 &lex->value_list,
1491
                                                 lex->duplicates,
1492
                                                 lex->ignore)))
1493
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1494
	res= handle_select(session, lex, sel_result, OPTION_SETUP_TABLES_DONE);
1 by brian
clean slate
1495
        /*
1496
          Invalidate the table in the query cache if something changed
1497
          after unlocking when changes become visible.
1498
          TODO: this is workaround. right way will be move invalidating in
1499
          the unlock procedure.
1500
        */
1501
        if (first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
520.1.22 by Brian Aker
Second pass of thd cleanup
1502
            session->lock)
1 by brian
clean slate
1503
        {
1504
          /* INSERT ... SELECT should invalidate only the very first table */
327.2.4 by Brian Aker
Refactoring table.h
1505
          TableList *save_table= first_table->next_local;
1 by brian
clean slate
1506
          first_table->next_local= 0;
1507
          first_table->next_local= save_table;
1508
        }
1509
        delete sel_result;
1510
      }
1511
      /* revert changes for SP */
481 by Brian Aker
Remove all of uchar.
1512
      select_lex->table_list.first= (unsigned char*) first_table;
1 by brian
clean slate
1513
    }
1514
1515
    break;
1516
  }
1517
  case SQLCOM_TRUNCATE:
520.1.22 by Brian Aker
Second pass of thd cleanup
1518
    if (end_active_trans(session))
1 by brian
clean slate
1519
    {
1520
      res= -1;
1521
      break;
1522
    }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1523
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
1524
    /*
1525
      Don't allow this within a transaction because we want to use
1526
      re-generate table
1527
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1528
    if (session->locked_tables || session->active_transaction())
1 by brian
clean slate
1529
    {
1530
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
1531
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
1532
      goto error;
1533
    }
1534
520.1.22 by Brian Aker
Second pass of thd cleanup
1535
    res= mysql_truncate(session, first_table, 0);
1 by brian
clean slate
1536
1537
    break;
1538
  case SQLCOM_DELETE:
1539
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1540
    assert(first_table == all_tables && first_table != 0);
1541
    assert(select_lex->offset_limit == 0);
1 by brian
clean slate
1542
    unit->set_limit(select_lex);
1543
520.1.22 by Brian Aker
Second pass of thd cleanup
1544
    if (!session->locked_tables &&
1545
        !(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
1 by brian
clean slate
1546
    {
1547
      res= 1;
1548
      break;
1549
    }
1550
520.1.22 by Brian Aker
Second pass of thd cleanup
1551
    res = mysql_delete(session, all_tables, select_lex->where,
1 by brian
clean slate
1552
                       &select_lex->order_list,
1553
                       unit->select_limit_cnt, select_lex->options,
55 by brian
Update for using real bool types.
1554
                       false);
1 by brian
clean slate
1555
    break;
1556
  }
1557
  case SQLCOM_DELETE_MULTI:
1558
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1559
    assert(first_table == all_tables && first_table != 0);
327.2.4 by Brian Aker
Refactoring table.h
1560
    TableList *aux_tables=
520.1.22 by Brian Aker
Second pass of thd cleanup
1561
      (TableList *)session->lex->auxiliary_table_list.first;
1 by brian
clean slate
1562
    multi_delete *del_result;
1563
520.1.22 by Brian Aker
Second pass of thd cleanup
1564
    if (!session->locked_tables &&
1565
        !(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
1 by brian
clean slate
1566
    {
1567
      res= 1;
1568
      break;
1569
    }
1570
520.1.22 by Brian Aker
Second pass of thd cleanup
1571
    if ((res= multi_delete_precheck(session, all_tables)))
1 by brian
clean slate
1572
      break;
1573
55 by brian
Update for using real bool types.
1574
    /* condition will be true on SP re-excuting */
1 by brian
clean slate
1575
    if (select_lex->item_list.elements != 0)
1576
      select_lex->item_list.empty();
520.1.22 by Brian Aker
Second pass of thd cleanup
1577
    if (add_item_to_list(session, new Item_null()))
1 by brian
clean slate
1578
      goto error;
1579
520.1.22 by Brian Aker
Second pass of thd cleanup
1580
    session->set_proc_info("init");
1581
    if ((res= open_and_lock_tables(session, all_tables)))
1 by brian
clean slate
1582
      break;
1583
520.1.22 by Brian Aker
Second pass of thd cleanup
1584
    if ((res= mysql_multi_delete_prepare(session)))
1 by brian
clean slate
1585
      goto error;
1586
520.1.22 by Brian Aker
Second pass of thd cleanup
1587
    if (!session->is_fatal_error &&
1 by brian
clean slate
1588
        (del_result= new multi_delete(aux_tables, lex->table_count)))
1589
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1590
      res= mysql_select(session, &select_lex->ref_pointer_array,
1 by brian
clean slate
1591
			select_lex->get_table_list(),
1592
			select_lex->with_wild,
1593
			select_lex->item_list,
1594
			select_lex->where,
327.2.3 by Brian Aker
Refactoring of class Table
1595
			0, (order_st *)NULL, (order_st *)NULL, (Item *)NULL,
1596
			(order_st *)NULL,
520.1.22 by Brian Aker
Second pass of thd cleanup
1597
			select_lex->options | session->options |
1 by brian
clean slate
1598
			SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
1599
                        OPTION_SETUP_TABLES_DONE,
1600
			del_result, unit, select_lex);
520.1.22 by Brian Aker
Second pass of thd cleanup
1601
      res|= session->is_error();
1 by brian
clean slate
1602
      if (res)
1603
        del_result->abort();
1604
      delete del_result;
1605
    }
1606
    else
55 by brian
Update for using real bool types.
1607
      res= true;                                // Error
1 by brian
clean slate
1608
    break;
1609
  }
1610
  case SQLCOM_DROP_TABLE:
1611
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1612
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
1613
    if (!lex->drop_temporary)
1614
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1615
      if (end_active_trans(session))
1 by brian
clean slate
1616
        goto error;
1617
    }
1618
    else
1619
    {
1620
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
520.1.22 by Brian Aker
Second pass of thd cleanup
1621
      session->options|= OPTION_KEEP_LOG;
1 by brian
clean slate
1622
    }
1623
    /* DDL and binlog write order protected by LOCK_open */
520.1.22 by Brian Aker
Second pass of thd cleanup
1624
    res= mysql_rm_table(session, first_table, lex->drop_if_exists, lex->drop_temporary);
1 by brian
clean slate
1625
  }
1626
  break;
1627
  case SQLCOM_SHOW_PROCESSLIST:
520.1.22 by Brian Aker
Second pass of thd cleanup
1628
    mysqld_list_processes(session, NULL, lex->verbose);
1 by brian
clean slate
1629
    break;
1630
  case SQLCOM_SHOW_ENGINE_LOGS:
1631
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1632
      res= ha_show_status(session, lex->create_info.db_type, HA_ENGINE_LOGS);
1 by brian
clean slate
1633
      break;
1634
    }
1635
  case SQLCOM_CHANGE_DB:
1636
  {
1637
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };
1638
520.1.22 by Brian Aker
Second pass of thd cleanup
1639
    if (!mysql_change_db(session, &db_str, false))
1640
      my_ok(session);
1 by brian
clean slate
1641
1642
    break;
1643
  }
1644
1645
  case SQLCOM_LOAD:
1646
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1647
    assert(first_table == all_tables && first_table != 0);
1 by brian
clean slate
1648
    if (lex->local_file)
1649
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1650
      if (!(session->client_capabilities & CLIENT_LOCAL_FILES) ||
1 by brian
clean slate
1651
          !opt_local_infile)
1652
      {
1653
	my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0));
1654
	goto error;
1655
      }
1656
    }
1657
520.1.22 by Brian Aker
Second pass of thd cleanup
1658
    res= mysql_load(session, lex->exchange, first_table, lex->field_list,
1 by brian
clean slate
1659
                    lex->update_list, lex->value_list, lex->duplicates,
1660
                    lex->ignore, (bool) lex->local_file);
1661
    break;
1662
  }
1663
1664
  case SQLCOM_SET_OPTION:
1665
  {
1666
    List<set_var_base> *lex_var_list= &lex->var_list;
1667
520.1.22 by Brian Aker
Second pass of thd cleanup
1668
    if (lex->autocommit && end_active_trans(session))
1 by brian
clean slate
1669
      goto error;
1670
520.1.22 by Brian Aker
Second pass of thd cleanup
1671
    if (open_and_lock_tables(session, all_tables))
1 by brian
clean slate
1672
      goto error;
520.1.22 by Brian Aker
Second pass of thd cleanup
1673
    if (!(res= sql_set_variables(session, lex_var_list)))
1 by brian
clean slate
1674
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1675
      my_ok(session);
1 by brian
clean slate
1676
    }
1677
    else
1678
    {
1679
      /*
1680
        We encountered some sort of error, but no message was sent.
1681
        Send something semi-generic here since we don't know which
1682
        assignment in the list caused the error.
1683
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1684
      if (!session->is_error())
1 by brian
clean slate
1685
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
1686
      goto error;
1687
    }
1688
1689
    break;
1690
  }
1691
1692
  case SQLCOM_UNLOCK_TABLES:
1693
    /*
1694
      It is critical for mysqldump --single-transaction --master-data that
1695
      UNLOCK TABLES does not implicitely commit a connection which has only
1696
      done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
1697
      false, mysqldump will not work.
1698
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1699
    unlock_locked_tables(session);
1700
    if (session->options & OPTION_TABLE_LOCK)
1 by brian
clean slate
1701
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1702
      end_active_trans(session);
1703
      session->options&= ~(OPTION_TABLE_LOCK);
1 by brian
clean slate
1704
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1705
    if (session->global_read_lock)
1706
      unlock_global_read_lock(session);
1707
    my_ok(session);
1 by brian
clean slate
1708
    break;
1709
  case SQLCOM_LOCK_TABLES:
1710
    /*
1711
      We try to take transactional locks if
1712
      - only transactional locks are requested (lex->lock_transactional) and
520.1.22 by Brian Aker
Second pass of thd cleanup
1713
      - no non-transactional locks exist (!session->locked_tables).
1 by brian
clean slate
1714
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1715
    if (lex->lock_transactional && !session->locked_tables)
1 by brian
clean slate
1716
    {
1717
      int rc;
1718
      /*
1719
        All requested locks are transactional and no non-transactional
1720
        locks exist.
1721
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1722
      if ((rc= try_transactional_lock(session, all_tables)) == -1)
1 by brian
clean slate
1723
        goto error;
1724
      if (rc == 0)
1725
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1726
        my_ok(session);
1 by brian
clean slate
1727
        break;
1728
      }
1729
      /*
1730
        Non-transactional locking has been requested or
1731
        non-transactional locks exist already or transactional locks are
1732
        not supported by all storage engines. Take non-transactional
1733
        locks.
1734
      */
1735
    }
1736
    /*
1737
      One or more requested locks are non-transactional and/or
1738
      non-transactional locks exist or a storage engine does not support
1739
      transactional locks. Check if at least one transactional lock is
1740
      requested. If yes, warn about the conversion to non-transactional
1741
      locks or abort in strict mode.
1742
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1743
    if (check_transactional_lock(session, all_tables))
1 by brian
clean slate
1744
      goto error;
520.1.22 by Brian Aker
Second pass of thd cleanup
1745
    unlock_locked_tables(session);
1 by brian
clean slate
1746
    /* we must end the trasaction first, regardless of anything */
520.1.22 by Brian Aker
Second pass of thd cleanup
1747
    if (end_active_trans(session))
1 by brian
clean slate
1748
      goto error;
520.1.22 by Brian Aker
Second pass of thd cleanup
1749
    session->in_lock_tables=1;
1750
    session->options|= OPTION_TABLE_LOCK;
1 by brian
clean slate
1751
520.1.22 by Brian Aker
Second pass of thd cleanup
1752
    if (!(res= simple_open_n_lock_tables(session, all_tables)))
1 by brian
clean slate
1753
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1754
      session->locked_tables=session->lock;
1755
      session->lock=0;
1756
      (void) set_handler_table_locks(session, all_tables, false);
1757
      my_ok(session);
1 by brian
clean slate
1758
    }
1759
    else
1760
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1761
      /*
1 by brian
clean slate
1762
        Need to end the current transaction, so the storage engine (InnoDB)
1763
        can free its locks if LOCK TABLES locked some tables before finding
1764
        that it can't lock a table in its list
1765
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1766
      ha_autocommit_or_rollback(session, 1);
1767
      end_active_trans(session);
1768
      session->options&= ~(OPTION_TABLE_LOCK);
1 by brian
clean slate
1769
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1770
    session->in_lock_tables=0;
1 by brian
clean slate
1771
    break;
1772
  case SQLCOM_CREATE_DB:
1773
  {
1774
    /*
1775
      As mysql_create_db() may modify HA_CREATE_INFO structure passed to
1776
      it, we need to use a copy of LEX::create_info to make execution
1777
      prepared statement- safe.
1778
    */
1779
    HA_CREATE_INFO create_info(lex->create_info);
520.1.22 by Brian Aker
Second pass of thd cleanup
1780
    if (end_active_trans(session))
1 by brian
clean slate
1781
    {
1782
      res= -1;
1783
      break;
1784
    }
1785
    char *alias;
520.1.22 by Brian Aker
Second pass of thd cleanup
1786
    if (!(alias=session->strmake(lex->name.str, lex->name.length)) ||
1 by brian
clean slate
1787
        check_db_name(&lex->name))
1788
    {
1789
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
1790
      break;
1791
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1792
    res= mysql_create_db(session,(lower_case_table_names == 2 ? alias :
1 by brian
clean slate
1793
                              lex->name.str), &create_info, 0);
1794
    break;
1795
  }
1796
  case SQLCOM_DROP_DB:
1797
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1798
    if (end_active_trans(session))
1 by brian
clean slate
1799
    {
1800
      res= -1;
1801
      break;
1802
    }
1803
    if (check_db_name(&lex->name))
1804
    {
1805
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
1806
      break;
1807
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1808
    if (session->locked_tables || session->active_transaction())
1 by brian
clean slate
1809
    {
1810
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
1811
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
1812
      goto error;
1813
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1814
    res= mysql_rm_db(session, lex->name.str, lex->drop_if_exists, 0);
1 by brian
clean slate
1815
    break;
1816
  }
1817
  case SQLCOM_ALTER_DB:
1818
  {
1819
    LEX_STRING *db= &lex->name;
1820
    HA_CREATE_INFO create_info(lex->create_info);
1821
    if (check_db_name(db))
1822
    {
1823
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
1824
      break;
1825
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1826
    if (session->locked_tables || session->active_transaction())
1 by brian
clean slate
1827
    {
1828
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
1829
                 ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
1830
      goto error;
1831
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1832
    res= mysql_alter_db(session, db->str, &create_info);
1 by brian
clean slate
1833
    break;
1834
  }
1835
  case SQLCOM_SHOW_CREATE_DB:
1836
  {
1837
    if (check_db_name(&lex->name))
1838
    {
1839
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
1840
      break;
1841
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1842
    res= mysqld_show_create_db(session, lex->name.str, &lex->create_info);
1 by brian
clean slate
1843
    break;
1844
  }
1845
  case SQLCOM_FLUSH:
1846
  {
1847
    bool write_to_binlog;
1848
1849
    /*
1850
      reload_cache() will tell us if we are allowed to write to the
1851
      binlog or not.
1852
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1853
    if (!reload_cache(session, lex->type, first_table, &write_to_binlog))
1 by brian
clean slate
1854
    {
1855
      /*
1856
        We WANT to write and we CAN write.
1857
        ! we write after unlocking the table.
1858
      */
1859
      /*
1860
        Presumably, RESET and binlog writing doesn't require synchronization
1861
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1862
      write_bin_log(session, false, session->query, session->query_length);
1863
      my_ok(session);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1864
    }
1865
1 by brian
clean slate
1866
    break;
1867
  }
1868
  case SQLCOM_KILL:
1869
  {
1870
    Item *it= (Item *)lex->value_list.head();
1871
520.1.22 by Brian Aker
Second pass of thd cleanup
1872
    if ((!it->fixed && it->fix_fields(lex->session, &it)) || it->check_cols(1))
1 by brian
clean slate
1873
    {
1874
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
1875
		 MYF(0));
1876
      goto error;
1877
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1878
    sql_kill(session, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
1 by brian
clean slate
1879
    break;
1880
  }
1881
  case SQLCOM_BEGIN:
520.1.22 by Brian Aker
Second pass of thd cleanup
1882
    if (session->transaction.xid_state.xa_state != XA_NOTR)
1 by brian
clean slate
1883
    {
1884
      my_error(ER_XAER_RMFAIL, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
1885
               xa_state_names[session->transaction.xid_state.xa_state]);
1 by brian
clean slate
1886
      break;
1887
    }
1888
    /*
1889
      Breakpoints for backup testing.
1890
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1891
    if (begin_trans(session))
1 by brian
clean slate
1892
      goto error;
520.1.22 by Brian Aker
Second pass of thd cleanup
1893
    my_ok(session);
1 by brian
clean slate
1894
    break;
1895
  case SQLCOM_COMMIT:
520.1.22 by Brian Aker
Second pass of thd cleanup
1896
    if (end_trans(session, lex->tx_release ? COMMIT_RELEASE :
1 by brian
clean slate
1897
                              lex->tx_chain ? COMMIT_AND_CHAIN : COMMIT))
1898
      goto error;
520.1.22 by Brian Aker
Second pass of thd cleanup
1899
    my_ok(session);
1 by brian
clean slate
1900
    break;
1901
  case SQLCOM_ROLLBACK:
520.1.22 by Brian Aker
Second pass of thd cleanup
1902
    if (end_trans(session, lex->tx_release ? ROLLBACK_RELEASE :
1 by brian
clean slate
1903
                              lex->tx_chain ? ROLLBACK_AND_CHAIN : ROLLBACK))
1904
      goto error;
520.1.22 by Brian Aker
Second pass of thd cleanup
1905
    my_ok(session);
1 by brian
clean slate
1906
    break;
1907
  case SQLCOM_RELEASE_SAVEPOINT:
1908
  {
1909
    SAVEPOINT *sv;
520.1.22 by Brian Aker
Second pass of thd cleanup
1910
    for (sv=session->transaction.savepoints; sv; sv=sv->prev)
1 by brian
clean slate
1911
    {
1912
      if (my_strnncoll(system_charset_info,
481 by Brian Aker
Remove all of uchar.
1913
                       (unsigned char *)lex->ident.str, lex->ident.length,
1914
                       (unsigned char *)sv->name, sv->length) == 0)
1 by brian
clean slate
1915
        break;
1916
    }
1917
    if (sv)
1918
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1919
      if (ha_release_savepoint(session, sv))
55 by brian
Update for using real bool types.
1920
        res= true; // cannot happen
1 by brian
clean slate
1921
      else
520.1.22 by Brian Aker
Second pass of thd cleanup
1922
        my_ok(session);
1923
      session->transaction.savepoints=sv->prev;
1 by brian
clean slate
1924
    }
1925
    else
1926
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
1927
    break;
1928
  }
1929
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
1930
  {
1931
    SAVEPOINT *sv;
520.1.22 by Brian Aker
Second pass of thd cleanup
1932
    for (sv=session->transaction.savepoints; sv; sv=sv->prev)
1 by brian
clean slate
1933
    {
1934
      if (my_strnncoll(system_charset_info,
481 by Brian Aker
Remove all of uchar.
1935
                       (unsigned char *)lex->ident.str, lex->ident.length,
1936
                       (unsigned char *)sv->name, sv->length) == 0)
1 by brian
clean slate
1937
        break;
1938
    }
1939
    if (sv)
1940
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1941
      if (ha_rollback_to_savepoint(session, sv))
55 by brian
Update for using real bool types.
1942
        res= true; // cannot happen
1 by brian
clean slate
1943
      else
1944
      {
808 by Brian Aker
Move number of threads to use for pool of threads to module. Removed slave
1945
        if ((session->options & OPTION_KEEP_LOG) || session->transaction.all.modified_non_trans_table)
520.1.22 by Brian Aker
Second pass of thd cleanup
1946
          push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
1947
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
1948
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
520.1.22 by Brian Aker
Second pass of thd cleanup
1949
        my_ok(session);
1 by brian
clean slate
1950
      }
520.1.22 by Brian Aker
Second pass of thd cleanup
1951
      session->transaction.savepoints=sv;
1 by brian
clean slate
1952
    }
1953
    else
1954
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
1955
    break;
1956
  }
1957
  case SQLCOM_SAVEPOINT:
520.1.22 by Brian Aker
Second pass of thd cleanup
1958
    if (!(session->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) || !opt_using_transactions)
1959
      my_ok(session);
1 by brian
clean slate
1960
    else
1961
    {
1962
      SAVEPOINT **sv, *newsv;
520.1.22 by Brian Aker
Second pass of thd cleanup
1963
      for (sv=&session->transaction.savepoints; *sv; sv=&(*sv)->prev)
1 by brian
clean slate
1964
      {
1965
        if (my_strnncoll(system_charset_info,
481 by Brian Aker
Remove all of uchar.
1966
                         (unsigned char *)lex->ident.str, lex->ident.length,
1967
                         (unsigned char *)(*sv)->name, (*sv)->length) == 0)
1 by brian
clean slate
1968
          break;
1969
      }
1970
      if (*sv) /* old savepoint of the same name exists */
1971
      {
1972
        newsv=*sv;
520.1.22 by Brian Aker
Second pass of thd cleanup
1973
        ha_release_savepoint(session, *sv); // it cannot fail
1 by brian
clean slate
1974
        *sv=(*sv)->prev;
1975
      }
520.1.22 by Brian Aker
Second pass of thd cleanup
1976
      else if ((newsv=(SAVEPOINT *) alloc_root(&session->transaction.mem_root,
1 by brian
clean slate
1977
                                               savepoint_alloc_size)) == 0)
1978
      {
1979
        my_error(ER_OUT_OF_RESOURCES, MYF(0));
1980
        break;
1981
      }
520.1.22 by Brian Aker
Second pass of thd cleanup
1982
      newsv->name=strmake_root(&session->transaction.mem_root,
1 by brian
clean slate
1983
                               lex->ident.str, lex->ident.length);
1984
      newsv->length=lex->ident.length;
1985
      /*
1986
        if we'll get an error here, don't add new savepoint to the list.
1987
        we'll lose a little bit of memory in transaction mem_root, but it'll
1988
        be free'd when transaction ends anyway
1989
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1990
      if (ha_savepoint(session, newsv))
55 by brian
Update for using real bool types.
1991
        res= true;
1 by brian
clean slate
1992
      else
1993
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1994
        newsv->prev=session->transaction.savepoints;
1995
        session->transaction.savepoints=newsv;
1996
        my_ok(session);
1 by brian
clean slate
1997
      }
1998
    }
1999
    break;
2000
  default:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2001
    assert(0);                             /* Impossible */
520.1.22 by Brian Aker
Second pass of thd cleanup
2002
    my_ok(session);
1 by brian
clean slate
2003
    break;
2004
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
2005
  session->set_proc_info("query end");
1 by brian
clean slate
2006
2007
  /*
2008
    The return value for ROW_COUNT() is "implementation dependent" if the
2009
    statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
2010
    wants. We also keep the last value in case of SQLCOM_CALL or
2011
    SQLCOM_EXECUTE.
2012
  */
602.2.2 by Yoshinori Sano
Fix bugs in params of sql_command_flags[...].test(). Previously, the value such as, 0, 1, 2, 4, 8 and 16 is given to std::bitset.test() in that place, which is misunderstanding of the spec of the test(). The test(size_t n) returns true if bit n is set.
2013
  if (!(sql_command_flags[lex->sql_command].test(CF_BIT_HAS_ROW_COUNT)))
520.1.22 by Brian Aker
Second pass of thd cleanup
2014
    session->row_count_func= -1;
1 by brian
clean slate
2015
2016
  goto finish;
2017
2018
error:
55 by brian
Update for using real bool types.
2019
  res= true;
1 by brian
clean slate
2020
2021
finish:
2022
  if (need_start_waiting)
2023
  {
2024
    /*
2025
      Release the protection against the global read lock and wake
2026
      everyone, who might want to set a global read lock.
2027
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
2028
    start_waiting_global_read_lock(session);
1 by brian
clean slate
2029
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
2030
  return(res || session->is_error());
1 by brian
clean slate
2031
}
2032
520.1.22 by Brian Aker
Second pass of thd cleanup
2033
bool execute_sqlcom_select(Session *session, TableList *all_tables)
1 by brian
clean slate
2034
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2035
  LEX	*lex= session->lex;
1 by brian
clean slate
2036
  select_result *result=lex->result;
2037
  bool res;
2038
  /* assign global limit variable if limit is not given */
2039
  {
2040
    SELECT_LEX *param= lex->unit.global_parameters;
2041
    if (!param->explicit_limit)
2042
      param->select_limit=
520.1.22 by Brian Aker
Second pass of thd cleanup
2043
        new Item_int((uint64_t) session->variables.select_limit);
1 by brian
clean slate
2044
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
2045
  if (!(res= open_and_lock_tables(session, all_tables)))
1 by brian
clean slate
2046
  {
2047
    if (lex->describe)
2048
    {
2049
      /*
2050
        We always use select_send for EXPLAIN, even if it's an EXPLAIN
2051
        for SELECT ... INTO OUTFILE: a user application should be able
2052
        to prepend EXPLAIN to any query and receive output for it,
2053
        even if the query itself redirects the output.
2054
      */
2055
      if (!(result= new select_send()))
2056
        return 1;                               /* purecov: inspected */
520.1.22 by Brian Aker
Second pass of thd cleanup
2057
      session->send_explain_fields(result);
2058
      res= mysql_explain_union(session, &session->lex->unit, result);
1 by brian
clean slate
2059
      if (lex->describe & DESCRIBE_EXTENDED)
2060
      {
2061
        char buff[1024];
205 by Brian Aker
uint32 -> uin32_t
2062
        String str(buff,(uint32_t) sizeof(buff), system_charset_info);
1 by brian
clean slate
2063
        str.length(0);
520.1.22 by Brian Aker
Second pass of thd cleanup
2064
        session->lex->unit.print(&str, QT_ORDINARY);
1 by brian
clean slate
2065
        str.append('\0');
520.1.22 by Brian Aker
Second pass of thd cleanup
2066
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
2067
                     ER_YES, str.ptr());
2068
      }
2069
      if (res)
2070
        result->abort();
2071
      else
2072
        result->send_eof();
2073
      delete result;
2074
    }
2075
    else
2076
    {
2077
      if (!result && !(result= new select_send()))
2078
        return 1;                               /* purecov: inspected */
520.1.22 by Brian Aker
Second pass of thd cleanup
2079
      res= handle_select(session, lex, result, 0);
1 by brian
clean slate
2080
      if (result != lex->result)
2081
        delete result;
2082
    }
2083
  }
2084
  return res;
2085
}
2086
2087
2088
#define MY_YACC_INIT 1000			// Start with big alloc
2089
#define MY_YACC_MAX  32000			// Because of 'short'
2090
2091
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
2092
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2093
  LEX	*lex= current_session->lex;
1 by brian
clean slate
2094
  ulong old_info=0;
438.1.13 by Brian Aker
uint cleanup.
2095
  if ((uint32_t) *yystacksize >= MY_YACC_MAX)
1 by brian
clean slate
2096
    return 1;
2097
  if (!lex->yacc_yyvs)
2098
    old_info= *yystacksize;
2099
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
656.1.46 by Monty Taylor
More malloc return cleanups.
2100
  unsigned char *tmpptr= NULL;
2101
  if (!(tmpptr= (unsigned char *)realloc(lex->yacc_yyvs,
2102
                                         *yystacksize* sizeof(**yyvs))))
2103
      return 1;
2104
  lex->yacc_yyvs= tmpptr;
2105
  tmpptr= NULL;
2106
  if (!(tmpptr= (unsigned char*)realloc(lex->yacc_yyss,
2107
                                        *yystacksize* sizeof(**yyss))))
2108
      return 1;
2109
  lex->yacc_yyss= tmpptr;
1 by brian
clean slate
2110
  if (old_info)
2111
  {						// Copy old info from stack
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
2112
    memcpy(lex->yacc_yyss, *yyss, old_info*sizeof(**yyss));
2113
    memcpy(lex->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
1 by brian
clean slate
2114
  }
2115
  *yyss=(short*) lex->yacc_yyss;
2116
  *yyvs=(YYSTYPE*) lex->yacc_yyvs;
2117
  return 0;
2118
}
2119
2120
2121
void
2122
mysql_init_select(LEX *lex)
2123
{
2124
  SELECT_LEX *select_lex= lex->current_select;
2125
  select_lex->init_select();
2126
  lex->wild= 0;
2127
  if (select_lex == &lex->select_lex)
2128
  {
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2129
    assert(lex->result == 0);
1 by brian
clean slate
2130
    lex->exchange= 0;
2131
  }
2132
}
2133
2134
2135
bool
2136
mysql_new_select(LEX *lex, bool move_down)
2137
{
2138
  SELECT_LEX *select_lex;
520.1.22 by Brian Aker
Second pass of thd cleanup
2139
  Session *session= lex->session;
1 by brian
clean slate
2140
520.1.22 by Brian Aker
Second pass of thd cleanup
2141
  if (!(select_lex= new (session->mem_root) SELECT_LEX()))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2142
    return(1);
520.1.22 by Brian Aker
Second pass of thd cleanup
2143
  select_lex->select_number= ++session->select_number;
1 by brian
clean slate
2144
  select_lex->parent_lex= lex; /* Used in init_query. */
2145
  select_lex->init_query();
2146
  select_lex->init_select();
2147
  lex->nest_level++;
2148
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
2149
  {
2150
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2151
    return(1);
1 by brian
clean slate
2152
  }
2153
  select_lex->nest_level= lex->nest_level;
2154
  if (move_down)
2155
  {
2156
    SELECT_LEX_UNIT *unit;
55 by brian
Update for using real bool types.
2157
    lex->subqueries= true;
1 by brian
clean slate
2158
    /* first select_lex of subselect or derived table */
520.1.22 by Brian Aker
Second pass of thd cleanup
2159
    if (!(unit= new (session->mem_root) SELECT_LEX_UNIT()))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2160
      return(1);
1 by brian
clean slate
2161
2162
    unit->init_query();
2163
    unit->init_select();
520.1.22 by Brian Aker
Second pass of thd cleanup
2164
    unit->session= session;
1 by brian
clean slate
2165
    unit->include_down(lex->current_select);
2166
    unit->link_next= 0;
2167
    unit->link_prev= 0;
2168
    unit->return_to= lex->current_select;
2169
    select_lex->include_down(unit);
2170
    /*
2171
      By default we assume that it is usual subselect and we have outer name
2172
      resolution context, if no we will assign it to 0 later
2173
    */
2174
    select_lex->context.outer_context= &select_lex->outer_select()->context;
2175
  }
2176
  else
2177
  {
2178
    if (lex->current_select->order_list.first && !lex->current_select->braces)
2179
    {
327.2.3 by Brian Aker
Refactoring of class Table
2180
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2181
      return(1);
1 by brian
clean slate
2182
    }
2183
    select_lex->include_neighbour(lex->current_select);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2184
    SELECT_LEX_UNIT *unit= select_lex->master_unit();
520.1.22 by Brian Aker
Second pass of thd cleanup
2185
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2186
      return(1);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2187
    select_lex->context.outer_context=
1 by brian
clean slate
2188
                unit->first_select()->context.outer_context;
2189
  }
2190
2191
  select_lex->master_unit()->global_parameters= select_lex;
2192
  select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
2193
  lex->current_select= select_lex;
2194
  /*
2195
    in subquery is SELECT query and we allow resolution of names in SELECT
2196
    list
2197
  */
55 by brian
Update for using real bool types.
2198
  select_lex->context.resolve_in_select_list= true;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2199
  return(0);
1 by brian
clean slate
2200
}
2201
2202
/**
2203
  Create a select to return the same output as 'SELECT @@var_name'.
2204
2205
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
2206
2207
  This will crash with a core dump if the variable doesn't exists.
2208
2209
  @param var_name		Variable name
2210
*/
2211
2212
void create_select_for_variable(const char *var_name)
2213
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2214
  Session *session;
1 by brian
clean slate
2215
  LEX *lex;
2216
  LEX_STRING tmp, null_lex_string;
2217
  Item *var;
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
2218
  char buff[MAX_SYS_VAR_LENGTH*2+4+8];
2219
  char *end= buff;
1 by brian
clean slate
2220
520.1.22 by Brian Aker
Second pass of thd cleanup
2221
  session= current_session;
2222
  lex= session->lex;
1 by brian
clean slate
2223
  mysql_init_select(lex);
2224
  lex->sql_command= SQLCOM_SELECT;
2225
  tmp.str= (char*) var_name;
2226
  tmp.length=strlen(var_name);
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
2227
  memset(&null_lex_string.str, 0, sizeof(null_lex_string));
1 by brian
clean slate
2228
  /*
2229
    We set the name of Item to @@session.var_name because that then is used
2230
    as the column name in the output.
2231
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
2232
  if ((var= get_system_var(session, OPT_SESSION, tmp, null_lex_string)))
1 by brian
clean slate
2233
  {
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
2234
    end+= sprintf(buff, "@@session.%s", var_name);
1 by brian
clean slate
2235
    var->set_name(buff, end-buff, system_charset_info);
520.1.22 by Brian Aker
Second pass of thd cleanup
2236
    add_item_to_list(session, var);
1 by brian
clean slate
2237
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2238
  return;
1 by brian
clean slate
2239
}
2240
2241
2242
void mysql_init_multi_delete(LEX *lex)
2243
{
2244
  lex->sql_command=  SQLCOM_DELETE_MULTI;
2245
  mysql_init_select(lex);
2246
  lex->select_lex.select_limit= 0;
2247
  lex->unit.select_limit_cnt= HA_POS_ERROR;
2248
  lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list);
604 by Brian Aker
Remove lock condition needed (we do row based replication, so... lock is
2249
  lex->lock_option= TL_READ;
1 by brian
clean slate
2250
  lex->query_tables= 0;
2251
  lex->query_tables_last= &lex->query_tables;
2252
}
2253
2254
2255
/*
2256
  When you modify mysql_parse(), you may need to mofify
2257
  mysql_test_parse_for_slave() in this same file.
2258
*/
2259
2260
/**
2261
  Parse a query.
2262
520.1.22 by Brian Aker
Second pass of thd cleanup
2263
  @param       session     Current thread
1 by brian
clean slate
2264
  @param       inBuf   Begining of the query text
2265
  @param       length  Length of the query text
2266
  @param[out]  found_semicolon For multi queries, position of the character of
2267
                               the next query in the query text.
2268
*/
2269
520.1.22 by Brian Aker
Second pass of thd cleanup
2270
void mysql_parse(Session *session, const char *inBuf, uint32_t length,
1 by brian
clean slate
2271
                 const char ** found_semicolon)
2272
{
2273
  /*
2274
    Warning.
2275
    The purpose of query_cache_send_result_to_client() is to lookup the
2276
    query in the query cache first, to avoid parsing and executing it.
2277
    So, the natural implementation would be to:
2278
    - first, call query_cache_send_result_to_client,
2279
    - second, if caching failed, initialise the lexical and syntactic parser.
2280
    The problem is that the query cache depends on a clean initialization
520.1.22 by Brian Aker
Second pass of thd cleanup
2281
    of (among others) lex->safe_to_cache_query and session->server_status,
1 by brian
clean slate
2282
    which are reset respectively in
2283
    - lex_start()
520.1.22 by Brian Aker
Second pass of thd cleanup
2284
    - mysql_reset_session_for_next_command()
1 by brian
clean slate
2285
    So, initializing the lexical analyser *before* using the query cache
2286
    is required for the cache to work properly.
2287
    FIXME: cleanup the dependencies in the code to simplify this.
2288
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
2289
  lex_start(session);
735 by Brian Aker
Refactor session.
2290
  session->reset_for_next_command();
1 by brian
clean slate
2291
2292
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
2293
    LEX *lex= session->lex;
2294
2295
    Lex_input_stream lip(session, inBuf, length);
2296
2297
    bool err= parse_sql(session, &lip);
1 by brian
clean slate
2298
    *found_semicolon= lip.found_semicolon;
2299
2300
    if (!err)
2301
    {
2302
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
2303
	if (! session->is_error())
1 by brian
clean slate
2304
	{
2305
          /*
520.1.22 by Brian Aker
Second pass of thd cleanup
2306
            Binlog logs a string starting from session->query and having length
2307
            session->query_length; so we set session->query_length correctly (to not
1 by brian
clean slate
2308
            log several statements in one event, when we executed only first).
2309
            We set it to not see the ';' (otherwise it would get into binlog
2310
            and Query_log_event::print() would give ';;' output).
2311
            This also helps display only the current query in SHOW
2312
            PROCESSLIST.
2313
            Note that we don't need LOCK_thread_count to modify query_length.
2314
          */
2315
          if (*found_semicolon &&
520.1.22 by Brian Aker
Second pass of thd cleanup
2316
              (session->query_length= (ulong)(*found_semicolon - session->query)))
2317
            session->query_length--;
1 by brian
clean slate
2318
          /* Actually execute the query */
520.1.22 by Brian Aker
Second pass of thd cleanup
2319
          mysql_execute_command(session);
1 by brian
clean slate
2320
	}
2321
      }
2322
    }
2323
    else
2324
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
2325
      assert(session->is_error());
1 by brian
clean slate
2326
    }
2327
    lex->unit.cleanup();
520.1.22 by Brian Aker
Second pass of thd cleanup
2328
    session->set_proc_info("freeing items");
2329
    session->end_statement();
2330
    session->cleanup_after_query();
2331
    assert(session->change_list.is_empty());
1 by brian
clean slate
2332
  }
2333
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2334
  return;
1 by brian
clean slate
2335
}
2336
2337
2338
/*
2339
  Usable by the replication SQL thread only: just parse a query to know if it
2340
  can be ignored because of replicate-*-table rules.
2341
2342
  @retval
2343
    0	cannot be ignored
2344
  @retval
2345
    1	can be ignored
2346
*/
2347
520.1.22 by Brian Aker
Second pass of thd cleanup
2348
bool mysql_test_parse_for_slave(Session *session, char *inBuf, uint32_t length)
1 by brian
clean slate
2349
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2350
  LEX *lex= session->lex;
1 by brian
clean slate
2351
  bool error= 0;
2352
520.1.22 by Brian Aker
Second pass of thd cleanup
2353
  Lex_input_stream lip(session, inBuf, length);
2354
  lex_start(session);
735 by Brian Aker
Refactor session.
2355
  session->reset_for_next_command();
1 by brian
clean slate
2356
520.1.22 by Brian Aker
Second pass of thd cleanup
2357
  if (!parse_sql(session, &lip) &&
2358
      all_tables_not_ok(session,(TableList*) lex->select_lex.table_list.first))
1 by brian
clean slate
2359
    error= 1;                  /* Ignore question */
520.1.22 by Brian Aker
Second pass of thd cleanup
2360
  session->end_statement();
2361
  session->cleanup_after_query();
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2362
  return(error);
1 by brian
clean slate
2363
}
2364
2365
2366
2367
/**
2368
  Store field definition for create.
2369
2370
  @return
2371
    Return 0 if ok
2372
*/
2373
520.1.22 by Brian Aker
Second pass of thd cleanup
2374
bool add_field_to_list(Session *session, LEX_STRING *field_name, enum_field_types type,
1 by brian
clean slate
2375
		       char *length, char *decimals,
438.1.13 by Brian Aker
uint cleanup.
2376
		       uint32_t type_modifier,
1 by brian
clean slate
2377
                       enum column_format_type column_format,
2378
		       Item *default_value, Item *on_update_value,
2379
                       LEX_STRING *comment,
2380
		       char *change,
383.7.1 by Andrey Zhakov
Initial submit of code and tests
2381
                       List<String> *interval_list, const CHARSET_INFO * const cs,
2382
                       virtual_column_info *vcol_info)
1 by brian
clean slate
2383
{
2384
  register Create_field *new_field;
520.1.22 by Brian Aker
Second pass of thd cleanup
2385
  LEX  *lex= session->lex;
1 by brian
clean slate
2386
2387
  if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2388
    return(1);				/* purecov: inspected */
1 by brian
clean slate
2389
2390
  if (type_modifier & PRI_KEY_FLAG)
2391
  {
2392
    Key *key;
2393
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
2394
    key= new Key(Key::PRIMARY, null_lex_str,
2395
                      &default_key_create_info,
2396
                      0, lex->col_list);
2397
    lex->alter_info.key_list.push_back(key);
2398
    lex->col_list.empty();
2399
  }
2400
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
2401
  {
2402
    Key *key;
2403
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
2404
    key= new Key(Key::UNIQUE, null_lex_str,
2405
                 &default_key_create_info, 0,
2406
                 lex->col_list);
2407
    lex->alter_info.key_list.push_back(key);
2408
    lex->col_list.empty();
2409
  }
2410
2411
  if (default_value)
2412
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2413
    /*
1 by brian
clean slate
2414
      Default value should be literal => basic constants =>
2415
      no need fix_fields()
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2416
2417
      We allow only one function as part of default value -
1 by brian
clean slate
2418
      NOW() as default for TIMESTAMP type.
2419
    */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2420
    if (default_value->type() == Item::FUNC_ITEM &&
1 by brian
clean slate
2421
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
2422
         type == DRIZZLE_TYPE_TIMESTAMP))
1 by brian
clean slate
2423
    {
2424
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2425
      return(1);
1 by brian
clean slate
2426
    }
2427
    else if (default_value->type() == Item::NULL_ITEM)
2428
    {
2429
      default_value= 0;
2430
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
2431
	  NOT_NULL_FLAG)
2432
      {
2433
	my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2434
	return(1);
1 by brian
clean slate
2435
      }
2436
    }
2437
    else if (type_modifier & AUTO_INCREMENT_FLAG)
2438
    {
2439
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2440
      return(1);
1 by brian
clean slate
2441
    }
2442
  }
2443
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
2444
  if (on_update_value && type != DRIZZLE_TYPE_TIMESTAMP)
1 by brian
clean slate
2445
  {
2446
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2447
    return(1);
1 by brian
clean slate
2448
  }
2449
2450
  if (!(new_field= new Create_field()) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
2451
      new_field->init(session, field_name->str, type, length, decimals, type_modifier,
1 by brian
clean slate
2452
                      default_value, on_update_value, comment, change,
383.7.1 by Andrey Zhakov
Initial submit of code and tests
2453
                      interval_list, cs, 0, column_format,
2454
                      vcol_info))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2455
    return(1);
1 by brian
clean slate
2456
2457
  lex->alter_info.create_list.push_back(new_field);
2458
  lex->last_field=new_field;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2459
  return(0);
1 by brian
clean slate
2460
}
2461
2462
2463
/** Store position for column in ALTER TABLE .. ADD column. */
2464
2465
void store_position_for_column(const char *name)
2466
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2467
  current_session->lex->last_field->after=const_cast<char*> (name);
1 by brian
clean slate
2468
}
2469
2470
bool
520.1.22 by Brian Aker
Second pass of thd cleanup
2471
add_proc_to_list(Session* session, Item *item)
1 by brian
clean slate
2472
{
327.2.3 by Brian Aker
Refactoring of class Table
2473
  order_st *order;
1 by brian
clean slate
2474
  Item	**item_ptr;
2475
520.1.22 by Brian Aker
Second pass of thd cleanup
2476
  if (!(order = (order_st *) session->alloc(sizeof(order_st)+sizeof(Item*))))
1 by brian
clean slate
2477
    return 1;
2478
  item_ptr = (Item**) (order+1);
2479
  *item_ptr= item;
2480
  order->item=item_ptr;
2481
  order->free_me=0;
520.1.22 by Brian Aker
Second pass of thd cleanup
2482
  session->lex->proc_list.link_in_list((unsigned char*) order,(unsigned char**) &order->next);
1 by brian
clean slate
2483
  return 0;
2484
}
2485
2486
2487
/**
2488
  save order by and tables in own lists.
2489
*/
2490
520.1.22 by Brian Aker
Second pass of thd cleanup
2491
bool add_to_list(Session *session, SQL_LIST &list,Item *item,bool asc)
1 by brian
clean slate
2492
{
327.2.3 by Brian Aker
Refactoring of class Table
2493
  order_st *order;
520.1.22 by Brian Aker
Second pass of thd cleanup
2494
  if (!(order = (order_st *) session->alloc(sizeof(order_st))))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2495
    return(1);
1 by brian
clean slate
2496
  order->item_ptr= item;
2497
  order->item= &order->item_ptr;
2498
  order->asc = asc;
2499
  order->free_me=0;
2500
  order->used=0;
2501
  order->counter_used= 0;
481 by Brian Aker
Remove all of uchar.
2502
  list.link_in_list((unsigned char*) order,(unsigned char**) &order->next);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2503
  return(0);
1 by brian
clean slate
2504
}
2505
2506
2507
/**
2508
  Add a table to list of used tables.
2509
2510
  @param table		Table to add
2511
  @param alias		alias for table (or null if no alias)
2512
  @param table_options	A set of the following bits:
2513
                         - TL_OPTION_UPDATING : Table will be updated
2514
                         - TL_OPTION_FORCE_INDEX : Force usage of index
2515
                         - TL_OPTION_ALIAS : an alias in multi table DELETE
2516
  @param lock_type	How table should be locked
2517
  @param use_index	List of indexed used in USE INDEX
2518
  @param ignore_index	List of indexed used in IGNORE INDEX
2519
2520
  @retval
2521
      0		Error
2522
  @retval
327.2.4 by Brian Aker
Refactoring table.h
2523
    \#	Pointer to TableList element added to the total table list
1 by brian
clean slate
2524
*/
2525
520.1.22 by Brian Aker
Second pass of thd cleanup
2526
TableList *st_select_lex::add_table_to_list(Session *session,
1 by brian
clean slate
2527
					     Table_ident *table,
2528
					     LEX_STRING *alias,
202 by Brian Aker
Cleanup sql_lex to modern types.
2529
					     uint32_t table_options,
1 by brian
clean slate
2530
					     thr_lock_type lock_type,
2531
					     List<Index_hint> *index_hints_arg,
2532
                                             LEX_STRING *option)
2533
{
327.2.4 by Brian Aker
Refactoring table.h
2534
  register TableList *ptr;
2535
  TableList *previous_table_ref; /* The table preceding the current one. */
1 by brian
clean slate
2536
  char *alias_str;
520.1.22 by Brian Aker
Second pass of thd cleanup
2537
  LEX *lex= session->lex;
1 by brian
clean slate
2538
2539
  if (!table)
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2540
    return(0);				// End of memory
1 by brian
clean slate
2541
  alias_str= alias ? alias->str : table->table.str;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2542
  if (!test(table_options & TL_OPTION_ALIAS) &&
1 by brian
clean slate
2543
      check_table_name(table->table.str, table->table.length))
2544
  {
2545
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2546
    return(0);
1 by brian
clean slate
2547
  }
2548
55 by brian
Update for using real bool types.
2549
  if (table->is_derived_table() == false && table->db.str &&
1 by brian
clean slate
2550
      check_db_name(&table->db))
2551
  {
2552
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2553
    return(0);
1 by brian
clean slate
2554
  }
2555
2556
  if (!alias)					/* Alias is case sensitive */
2557
  {
2558
    if (table->sel)
2559
    {
2560
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
2561
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2562
      return(0);
1 by brian
clean slate
2563
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
2564
    if (!(alias_str= (char*) session->memdup(alias_str,table->table.length+1)))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2565
      return(0);
1 by brian
clean slate
2566
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
2567
  if (!(ptr = (TableList *) session->calloc(sizeof(TableList))))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2568
    return(0);				/* purecov: inspected */
1 by brian
clean slate
2569
  if (table->db.str)
2570
  {
55 by brian
Update for using real bool types.
2571
    ptr->is_fqtn= true;
1 by brian
clean slate
2572
    ptr->db= table->db.str;
2573
    ptr->db_length= table->db.length;
2574
  }
2575
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2576
    return(0);
1 by brian
clean slate
2577
  else
55 by brian
Update for using real bool types.
2578
    ptr->is_fqtn= false;
1 by brian
clean slate
2579
2580
  ptr->alias= alias_str;
55 by brian
Update for using real bool types.
2581
  ptr->is_alias= alias ? true : false;
1 by brian
clean slate
2582
  if (lower_case_table_names && table->table.length)
2583
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
2584
  ptr->table_name=table->table.str;
2585
  ptr->table_name_length=table->table.length;
2586
  ptr->lock_type=   lock_type;
2587
  ptr->lock_timeout= -1;      /* default timeout */
2588
  ptr->lock_transactional= 1; /* allow transactional locks */
2589
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
2590
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
2591
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
2592
  ptr->derived=	    table->sel;
2593
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
575.4.7 by Monty Taylor
More header cleanup.
2594
                                      INFORMATION_SCHEMA_NAME.c_str()))
1 by brian
clean slate
2595
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
2596
    ST_SCHEMA_TABLE *schema_table= find_schema_table(session, ptr->table_name);
1 by brian
clean slate
2597
    if (!schema_table ||
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2598
        (schema_table->hidden &&
602.2.2 by Yoshinori Sano
Fix bugs in params of sql_command_flags[...].test(). Previously, the value such as, 0, 1, 2, 4, 8 and 16 is given to std::bitset.test() in that place, which is misunderstanding of the spec of the test(). The test(size_t n) returns true if bit n is set.
2599
         ((sql_command_flags[lex->sql_command].test(CF_BIT_STATUS_COMMAND)) == 0 ||
1 by brian
clean slate
2600
          /*
2601
            this check is used for show columns|keys from I_S hidden table
2602
          */
2603
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
2604
          lex->sql_command == SQLCOM_SHOW_KEYS)))
2605
    {
2606
      my_error(ER_UNKNOWN_TABLE, MYF(0),
575.4.7 by Monty Taylor
More header cleanup.
2607
               ptr->table_name, INFORMATION_SCHEMA_NAME.c_str());
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2608
      return(0);
1 by brian
clean slate
2609
    }
2610
    ptr->schema_table_name= ptr->table_name;
2611
    ptr->schema_table= schema_table;
2612
  }
2613
  ptr->select_lex=  lex->current_select;
2614
  ptr->cacheable_table= 1;
2615
  ptr->index_hints= index_hints_arg;
2616
  ptr->option= option ? option->str : 0;
2617
  /* check that used name is unique */
2618
  if (lock_type != TL_IGNORE)
2619
  {
327.2.4 by Brian Aker
Refactoring table.h
2620
    TableList *first_table= (TableList*) table_list.first;
2621
    for (TableList *tables= first_table ;
1 by brian
clean slate
2622
	 tables ;
2623
	 tables=tables->next_local)
2624
    {
2625
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
2626
	  !strcmp(ptr->db, tables->db))
2627
      {
2628
	my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2629
	return(0);				/* purecov: tested */
1 by brian
clean slate
2630
      }
2631
    }
2632
  }
2633
  /* Store the table reference preceding the current one. */
2634
  if (table_list.elements > 0)
2635
  {
2636
    /*
327.2.4 by Brian Aker
Refactoring table.h
2637
      table_list.next points to the last inserted TableList->next_local'
1 by brian
clean slate
2638
      element
2639
      We don't use the offsetof() macro here to avoid warnings from gcc
2640
    */
327.2.4 by Brian Aker
Refactoring table.h
2641
    previous_table_ref= (TableList*) ((char*) table_list.next -
1 by brian
clean slate
2642
                                       ((char*) &(ptr->next_local) -
2643
                                        (char*) ptr));
2644
    /*
2645
      Set next_name_resolution_table of the previous table reference to point
2646
      to the current table reference. In effect the list
327.2.4 by Brian Aker
Refactoring table.h
2647
      TableList::next_name_resolution_table coincides with
2648
      TableList::next_local. Later this may be changed in
1 by brian
clean slate
2649
      store_top_level_join_columns() for NATURAL/USING joins.
2650
    */
2651
    previous_table_ref->next_name_resolution_table= ptr;
2652
  }
2653
2654
  /*
2655
    Link the current table reference in a local list (list for current select).
2656
    Notice that as a side effect here we set the next_local field of the
2657
    previous table reference to 'ptr'. Here we also add one element to the
2658
    list 'table_list'.
2659
  */
481 by Brian Aker
Remove all of uchar.
2660
  table_list.link_in_list((unsigned char*) ptr, (unsigned char**) &ptr->next_local);
1 by brian
clean slate
2661
  ptr->next_name_resolution_table= NULL;
2662
  /* Link table in global list (all used tables) */
2663
  lex->add_to_query_tables(ptr);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2664
  return(ptr);
1 by brian
clean slate
2665
}
2666
2667
2668
/**
2669
  Initialize a new table list for a nested join.
2670
327.2.4 by Brian Aker
Refactoring table.h
2671
    The function initializes a structure of the TableList type
1 by brian
clean slate
2672
    for a nested join. It sets up its nested join list as empty.
2673
    The created structure is added to the front of the current
2674
    join list in the st_select_lex object. Then the function
2675
    changes the current nest level for joins to refer to the newly
2676
    created empty list after having saved the info on the old level
2677
    in the initialized structure.
2678
520.1.22 by Brian Aker
Second pass of thd cleanup
2679
  @param session         current thread
1 by brian
clean slate
2680
2681
  @retval
2682
    0   if success
2683
  @retval
2684
    1   otherwise
2685
*/
2686
520.1.22 by Brian Aker
Second pass of thd cleanup
2687
bool st_select_lex::init_nested_join(Session *session)
1 by brian
clean slate
2688
{
327.2.4 by Brian Aker
Refactoring table.h
2689
  TableList *ptr;
2690
  nested_join_st *nested_join;
1 by brian
clean slate
2691
520.1.22 by Brian Aker
Second pass of thd cleanup
2692
  if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
327.2.4 by Brian Aker
Refactoring table.h
2693
                                       sizeof(nested_join_st))))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2694
    return(1);
1 by brian
clean slate
2695
  nested_join= ptr->nested_join=
481 by Brian Aker
Remove all of uchar.
2696
    ((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
1 by brian
clean slate
2697
2698
  join_list->push_front(ptr);
2699
  ptr->embedding= embedding;
2700
  ptr->join_list= join_list;
2701
  ptr->alias= (char*) "(nested_join)";
2702
  embedding= ptr;
2703
  join_list= &nested_join->join_list;
2704
  join_list->empty();
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2705
  return(0);
1 by brian
clean slate
2706
}
2707
2708
2709
/**
2710
  End a nested join table list.
2711
2712
    The function returns to the previous join nest level.
2713
    If the current level contains only one member, the function
2714
    moves it one level up, eliminating the nest.
2715
520.1.22 by Brian Aker
Second pass of thd cleanup
2716
  @param session         current thread
1 by brian
clean slate
2717
2718
  @return
327.2.4 by Brian Aker
Refactoring table.h
2719
    - Pointer to TableList element added to the total table list, if success
1 by brian
clean slate
2720
    - 0, otherwise
2721
*/
2722
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
2723
TableList *st_select_lex::end_nested_join(Session *)
1 by brian
clean slate
2724
{
327.2.4 by Brian Aker
Refactoring table.h
2725
  TableList *ptr;
2726
  nested_join_st *nested_join;
1 by brian
clean slate
2727
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2728
  assert(embedding);
1 by brian
clean slate
2729
  ptr= embedding;
2730
  join_list= ptr->join_list;
2731
  embedding= ptr->embedding;
2732
  nested_join= ptr->nested_join;
2733
  if (nested_join->join_list.elements == 1)
2734
  {
327.2.4 by Brian Aker
Refactoring table.h
2735
    TableList *embedded= nested_join->join_list.head();
1 by brian
clean slate
2736
    join_list->pop();
2737
    embedded->join_list= join_list;
2738
    embedded->embedding= embedding;
2739
    join_list->push_front(embedded);
2740
    ptr= embedded;
2741
  }
2742
  else if (nested_join->join_list.elements == 0)
2743
  {
2744
    join_list->pop();
2745
    ptr= 0;                                     // return value
2746
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2747
  return(ptr);
1 by brian
clean slate
2748
}
2749
2750
2751
/**
2752
  Nest last join operation.
2753
2754
    The function nest last join operation as if it was enclosed in braces.
2755
520.1.22 by Brian Aker
Second pass of thd cleanup
2756
  @param session         current thread
1 by brian
clean slate
2757
2758
  @retval
2759
    0  Error
2760
  @retval
327.2.4 by Brian Aker
Refactoring table.h
2761
    \#  Pointer to TableList element created for the new nested join
1 by brian
clean slate
2762
*/
2763
520.1.22 by Brian Aker
Second pass of thd cleanup
2764
TableList *st_select_lex::nest_last_join(Session *session)
1 by brian
clean slate
2765
{
327.2.4 by Brian Aker
Refactoring table.h
2766
  TableList *ptr;
2767
  nested_join_st *nested_join;
2768
  List<TableList> *embedded_list;
1 by brian
clean slate
2769
520.1.22 by Brian Aker
Second pass of thd cleanup
2770
  if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
327.2.4 by Brian Aker
Refactoring table.h
2771
                                       sizeof(nested_join_st))))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2772
    return(0);
1 by brian
clean slate
2773
  nested_join= ptr->nested_join=
481 by Brian Aker
Remove all of uchar.
2774
    ((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
1 by brian
clean slate
2775
2776
  ptr->embedding= embedding;
2777
  ptr->join_list= join_list;
2778
  ptr->alias= (char*) "(nest_last_join)";
2779
  embedded_list= &nested_join->join_list;
2780
  embedded_list->empty();
2781
438.1.13 by Brian Aker
uint cleanup.
2782
  for (uint32_t i=0; i < 2; i++)
1 by brian
clean slate
2783
  {
327.2.4 by Brian Aker
Refactoring table.h
2784
    TableList *table= join_list->pop();
1 by brian
clean slate
2785
    table->join_list= embedded_list;
2786
    table->embedding= ptr;
2787
    embedded_list->push_back(table);
2788
    if (table->natural_join)
2789
    {
55 by brian
Update for using real bool types.
2790
      ptr->is_natural_join= true;
1 by brian
clean slate
2791
      /*
2792
        If this is a JOIN ... USING, move the list of joined fields to the
2793
        table reference that describes the join.
2794
      */
2795
      if (prev_join_using)
2796
        ptr->join_using_fields= prev_join_using;
2797
    }
2798
  }
2799
  join_list->push_front(ptr);
2800
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2801
  return(ptr);
1 by brian
clean slate
2802
}
2803
2804
2805
/**
2806
  Add a table to the current join list.
2807
2808
    The function puts a table in front of the current join list
2809
    of st_select_lex object.
2810
    Thus, joined tables are put into this list in the reverse order
2811
    (the most outer join operation follows first).
2812
2813
  @param table       the table to add
2814
2815
  @return
2816
    None
2817
*/
2818
327.2.4 by Brian Aker
Refactoring table.h
2819
void st_select_lex::add_joined_table(TableList *table)
1 by brian
clean slate
2820
{
2821
  join_list->push_front(table);
2822
  table->join_list= join_list;
2823
  table->embedding= embedding;
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2824
  return;
1 by brian
clean slate
2825
}
2826
2827
2828
/**
2829
  Convert a right join into equivalent left join.
2830
2831
    The function takes the current join list t[0],t[1] ... and
2832
    effectively converts it into the list t[1],t[0] ...
2833
    Although the outer_join flag for the new nested table contains
2834
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
2835
    operation.
2836
2837
  EXAMPLES
2838
  @verbatim
2839
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
2840
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr
2841
2842
    SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
2843
      SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr
2844
2845
    SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
2846
      SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr
2847
2848
    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
2849
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
2850
   @endverbatim
2851
520.1.22 by Brian Aker
Second pass of thd cleanup
2852
  @param session         current thread
1 by brian
clean slate
2853
2854
  @return
2855
    - Pointer to the table representing the inner table, if success
2856
    - 0, otherwise
2857
*/
2858
327.2.4 by Brian Aker
Refactoring table.h
2859
TableList *st_select_lex::convert_right_join()
1 by brian
clean slate
2860
{
327.2.4 by Brian Aker
Refactoring table.h
2861
  TableList *tab2= join_list->pop();
2862
  TableList *tab1= join_list->pop();
1 by brian
clean slate
2863
2864
  join_list->push_front(tab2);
2865
  join_list->push_front(tab1);
2866
  tab1->outer_join|= JOIN_TYPE_RIGHT;
2867
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2868
  return(tab1);
1 by brian
clean slate
2869
}
2870
2871
/**
2872
  Set lock for all tables in current select level.
2873
2874
  @param lock_type			Lock to set for tables
2875
2876
  @note
2877
    If lock is a write lock, then tables->updating is set 1
2878
    This is to get tables_ok to know that the table is updated by the
2879
    query
2880
*/
2881
2882
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type)
2883
{
2884
  bool for_update= lock_type >= TL_READ_NO_INSERT;
2885
327.2.4 by Brian Aker
Refactoring table.h
2886
  for (TableList *tables= (TableList*) table_list.first;
1 by brian
clean slate
2887
       tables;
2888
       tables= tables->next_local)
2889
  {
2890
    tables->lock_type= lock_type;
2891
    tables->updating=  for_update;
2892
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2893
  return;
1 by brian
clean slate
2894
}
2895
2896
2897
/**
2898
  Create a fake SELECT_LEX for a unit.
2899
2900
    The method create a fake SELECT_LEX object for a unit.
2901
    This object is created for any union construct containing a union
2902
    operation and also for any single select union construct of the form
2903
    @verbatim
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2904
    (SELECT ... order_st BY order_list [LIMIT n]) order_st BY ...
1 by brian
clean slate
2905
    @endvarbatim
2906
    or of the form
2907
    @varbatim
327.2.3 by Brian Aker
Refactoring of class Table
2908
    (SELECT ... order_st BY LIMIT n) order_st BY ...
1 by brian
clean slate
2909
    @endvarbatim
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2910
520.1.22 by Brian Aker
Second pass of thd cleanup
2911
  @param session_arg		   thread handle
1 by brian
clean slate
2912
2913
  @note
2914
    The object is used to retrieve rows from the temporary table
2915
    where the result on the union is obtained.
2916
2917
  @retval
2918
    1     on failure to create the object
2919
  @retval
2920
    0     on success
2921
*/
2922
520.1.22 by Brian Aker
Second pass of thd cleanup
2923
bool st_select_lex_unit::add_fake_select_lex(Session *session_arg)
1 by brian
clean slate
2924
{
2925
  SELECT_LEX *first_sl= first_select();
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2926
  assert(!fake_select_lex);
1 by brian
clean slate
2927
520.1.22 by Brian Aker
Second pass of thd cleanup
2928
  if (!(fake_select_lex= new (session_arg->mem_root) SELECT_LEX()))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2929
      return(1);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2930
  fake_select_lex->include_standalone(this,
1 by brian
clean slate
2931
                                      (SELECT_LEX_NODE**)&fake_select_lex);
2932
  fake_select_lex->select_number= INT_MAX;
520.1.22 by Brian Aker
Second pass of thd cleanup
2933
  fake_select_lex->parent_lex= session_arg->lex; /* Used in init_query. */
1 by brian
clean slate
2934
  fake_select_lex->make_empty_select();
2935
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
2936
  fake_select_lex->select_limit= 0;
2937
2938
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
327.2.3 by Brian Aker
Refactoring of class Table
2939
  /* allow item list resolving in fake select for order_st BY */
55 by brian
Update for using real bool types.
2940
  fake_select_lex->context.resolve_in_select_list= true;
1 by brian
clean slate
2941
  fake_select_lex->context.select_lex= fake_select_lex;
2942
2943
  if (!is_union())
2944
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2945
    /*
2946
      This works only for
327.2.3 by Brian Aker
Refactoring of class Table
2947
      (SELECT ... order_st BY list [LIMIT n]) order_st BY order_list [LIMIT m],
2948
      (SELECT ... LIMIT n) order_st BY order_list [LIMIT m]
1 by brian
clean slate
2949
      just before the parser starts processing order_list
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2950
    */
1 by brian
clean slate
2951
    global_parameters= fake_select_lex;
2952
    fake_select_lex->no_table_names_allowed= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
2953
    session_arg->lex->current_select= fake_select_lex;
1 by brian
clean slate
2954
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
2955
  session_arg->lex->pop_context();
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
2956
  return(0);
1 by brian
clean slate
2957
}
2958
2959
2960
/**
2961
  Push a new name resolution context for a JOIN ... ON clause to the
2962
  context stack of a query block.
2963
2964
    Create a new name resolution context for a JOIN ... ON clause,
2965
    set the first and last leaves of the list of table references
2966
    to be used for name resolution, and push the newly created
2967
    context to the stack of contexts of the query.
2968
520.1.22 by Brian Aker
Second pass of thd cleanup
2969
  @param session       pointer to current thread
1 by brian
clean slate
2970
  @param left_op   left  operand of the JOIN
2971
  @param right_op  rigth operand of the JOIN
2972
2973
  @retval
55 by brian
Update for using real bool types.
2974
    false  if all is OK
1 by brian
clean slate
2975
  @retval
55 by brian
Update for using real bool types.
2976
    true   if a memory allocation error occured
1 by brian
clean slate
2977
*/
2978
2979
bool
520.1.22 by Brian Aker
Second pass of thd cleanup
2980
push_new_name_resolution_context(Session *session,
327.2.4 by Brian Aker
Refactoring table.h
2981
                                 TableList *left_op, TableList *right_op)
1 by brian
clean slate
2982
{
2983
  Name_resolution_context *on_context;
520.1.22 by Brian Aker
Second pass of thd cleanup
2984
  if (!(on_context= new (session->mem_root) Name_resolution_context))
55 by brian
Update for using real bool types.
2985
    return true;
1 by brian
clean slate
2986
  on_context->init();
2987
  on_context->first_name_resolution_table=
2988
    left_op->first_leaf_for_name_resolution();
2989
  on_context->last_name_resolution_table=
2990
    right_op->last_leaf_for_name_resolution();
520.1.22 by Brian Aker
Second pass of thd cleanup
2991
  return session->lex->push_context(on_context);
1 by brian
clean slate
2992
}
2993
2994
2995
/**
2996
  Add an ON condition to the second operand of a JOIN ... ON.
2997
2998
    Add an ON condition to the right operand of a JOIN ... ON clause.
2999
3000
  @param b     the second operand of a JOIN ... ON
3001
  @param expr  the condition to be added to the ON clause
3002
3003
  @retval
55 by brian
Update for using real bool types.
3004
    false  if there was some error
1 by brian
clean slate
3005
  @retval
55 by brian
Update for using real bool types.
3006
    true   if all is OK
1 by brian
clean slate
3007
*/
3008
327.2.4 by Brian Aker
Refactoring table.h
3009
void add_join_on(TableList *b, Item *expr)
1 by brian
clean slate
3010
{
3011
  if (expr)
3012
  {
3013
    if (!b->on_expr)
3014
      b->on_expr= expr;
3015
    else
3016
    {
3017
      /*
3018
        If called from the parser, this happens if you have both a
3019
        right and left join. If called later, it happens if we add more
3020
        than one condition to the ON clause.
3021
      */
3022
      b->on_expr= new Item_cond_and(b->on_expr,expr);
3023
    }
3024
    b->on_expr->top_level_item();
3025
  }
3026
}
3027
3028
3029
/**
3030
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
3031
  tables.
3032
3033
    This function marks that table b should be joined with a either via
3034
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
3035
    cases of each other, so we treat them together. The function
3036
    setup_conds() creates a list of equal condition between all fields
3037
    of the same name for NATURAL JOIN or the fields in 'using_fields'
3038
    for JOIN ... USING. The list of equality conditions is stored
3039
    either in b->on_expr, or in JOIN::conds, depending on whether there
3040
    was an outer join.
3041
3042
  EXAMPLE
3043
  @verbatim
3044
    SELECT * FROM t1 NATURAL LEFT JOIN t2
3045
     <=>
3046
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
3047
3048
    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
3049
     <=>
3050
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
3051
3052
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
3053
     <=>
3054
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
3055
   @endverbatim
3056
3057
  @param a		  Left join argument
3058
  @param b		  Right join argument
3059
  @param using_fields    Field names from USING clause
3060
*/
3061
327.2.4 by Brian Aker
Refactoring table.h
3062
void add_join_natural(TableList *a, TableList *b, List<String> *using_fields,
1 by brian
clean slate
3063
                      SELECT_LEX *lex)
3064
{
3065
  b->natural_join= a;
3066
  lex->prev_join_using= using_fields;
3067
}
3068
3069
3070
/**
3071
  Reload/resets privileges and the different caches.
3072
520.1.22 by Brian Aker
Second pass of thd cleanup
3073
  @param session Thread handler (can be NULL!)
1 by brian
clean slate
3074
  @param options What should be reset/reloaded (tables, privileges, slave...)
3075
  @param tables Tables to flush (if any)
3076
  @param write_to_binlog True if we can write to the binlog.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3077
1 by brian
clean slate
3078
  @note Depending on 'options', it may be very bad to write the
3079
    query to the binlog (e.g. FLUSH SLAVE); this is a
3080
    pointer where reload_cache() will put 0 if
3081
    it thinks we really should not write to the binlog.
3082
    Otherwise it will put 1.
3083
3084
  @return Error status code
3085
    @retval 0 Ok
520.1.22 by Brian Aker
Second pass of thd cleanup
3086
    @retval !=0  Error; session->killed is set or session->is_error() is true
1 by brian
clean slate
3087
*/
3088
520.1.22 by Brian Aker
Second pass of thd cleanup
3089
bool reload_cache(Session *session, ulong options, TableList *tables,
1 by brian
clean slate
3090
                          bool *write_to_binlog)
3091
{
3092
  bool result=0;
3093
  select_errors=0;				/* Write if more errors */
3094
  bool tmp_write_to_binlog= 1;
3095
3096
  if (options & REFRESH_LOG)
3097
  {
3098
    /*
3099
      Flush the normal query log, the update log, the binary log,
3100
      the slow query log, the relay log (if it exists) and the log
3101
      tables.
3102
    */
3103
3104
    /*
3105
      Writing this command to the binlog may result in infinite loops
3106
      when doing mysqlbinlog|mysql, and anyway it does not really make
3107
      sense to log it automatically (would cause more trouble to users
3108
      than it would help them)
3109
    */
3110
    tmp_write_to_binlog= 0;
3111
3112
    if (ha_flush_logs(NULL))
3113
      result=1;
3114
  }
3115
  /*
3116
    Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too
3117
    (see sql_yacc.yy)
3118
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3119
  if (options & (REFRESH_TABLES | REFRESH_READ_LOCK))
1 by brian
clean slate
3120
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
3121
    if ((options & REFRESH_READ_LOCK) && session)
1 by brian
clean slate
3122
    {
3123
      /*
3124
        We must not try to aspire a global read lock if we have a write
3125
        locked table. This would lead to a deadlock when trying to
3126
        reopen (and re-lock) the table after the flush.
3127
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
3128
      if (session->locked_tables)
1 by brian
clean slate
3129
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
3130
        THR_LOCK_DATA **lock_p= session->locked_tables->locks;
3131
        THR_LOCK_DATA **end_p= lock_p + session->locked_tables->lock_count;
1 by brian
clean slate
3132
3133
        for (; lock_p < end_p; lock_p++)
3134
        {
3135
          if ((*lock_p)->type >= TL_WRITE_ALLOW_WRITE)
3136
          {
3137
            my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
3138
            return 1;
3139
          }
3140
        }
3141
      }
3142
      /*
3143
	Writing to the binlog could cause deadlocks, as we don't log
3144
	UNLOCK TABLES
3145
      */
3146
      tmp_write_to_binlog= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
3147
      if (lock_global_read_lock(session))
1 by brian
clean slate
3148
	return 1;                               // Killed
520.1.22 by Brian Aker
Second pass of thd cleanup
3149
      result= close_cached_tables(session, tables, false, (options & REFRESH_FAST) ?
55 by brian
Update for using real bool types.
3150
                                  false : true, true);
520.1.22 by Brian Aker
Second pass of thd cleanup
3151
      if (make_global_read_lock_block_commit(session)) // Killed
1 by brian
clean slate
3152
      {
3153
        /* Don't leave things in a half-locked state */
520.1.22 by Brian Aker
Second pass of thd cleanup
3154
        unlock_global_read_lock(session);
1 by brian
clean slate
3155
        return 1;
3156
      }
3157
    }
3158
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
3159
      result= close_cached_tables(session, tables, false, (options & REFRESH_FAST) ?
55 by brian
Update for using real bool types.
3160
                                  false : true, false);
1 by brian
clean slate
3161
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
3162
  if (session && (options & REFRESH_STATUS))
3163
    refresh_status(session);
1 by brian
clean slate
3164
 *write_to_binlog= tmp_write_to_binlog;
3165
 return result;
3166
}
3167
3168
3169
/**
3170
  kill on thread.
3171
520.1.22 by Brian Aker
Second pass of thd cleanup
3172
  @param session			Thread class
1 by brian
clean slate
3173
  @param id			Thread id
3174
  @param only_kill_query        Should it kill the query or the connection
3175
3176
  @note
3177
    This is written such that we have a short lock on LOCK_thread_count
3178
*/
3179
230.1.9 by Monty Taylor
Merged in remove-include-dir.
3180
static unsigned int
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
3181
kill_one_thread(Session *, ulong id, bool only_kill_query)
1 by brian
clean slate
3182
{
520.1.21 by Brian Aker
THD -> Session rename
3183
  Session *tmp;
438.1.13 by Brian Aker
uint cleanup.
3184
  uint32_t error=ER_NO_SUCH_THREAD;
398.1.10 by Monty Taylor
Actually removed VOID() this time.
3185
  pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
520.1.21 by Brian Aker
THD -> Session rename
3186
  I_List_iterator<Session> it(threads);
1 by brian
clean slate
3187
  while ((tmp=it++))
3188
  {
3189
    if (tmp->command == COM_DAEMON)
3190
      continue;
3191
    if (tmp->thread_id == id)
3192
    {
3193
      pthread_mutex_lock(&tmp->LOCK_delete);	// Lock from delete
3194
      break;
3195
    }
3196
  }
398.1.10 by Monty Taylor
Actually removed VOID() this time.
3197
  pthread_mutex_unlock(&LOCK_thread_count);
1 by brian
clean slate
3198
  if (tmp)
3199
  {
520.1.21 by Brian Aker
THD -> Session rename
3200
    tmp->awake(only_kill_query ? Session::KILL_QUERY : Session::KILL_CONNECTION);
1 by brian
clean slate
3201
    error=0;
3202
    pthread_mutex_unlock(&tmp->LOCK_delete);
3203
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3204
  return(error);
1 by brian
clean slate
3205
}
3206
3207
3208
/*
3209
  kills a thread and sends response
3210
3211
  SYNOPSIS
3212
    sql_kill()
520.1.22 by Brian Aker
Second pass of thd cleanup
3213
    session			Thread class
1 by brian
clean slate
3214
    id			Thread id
3215
    only_kill_query     Should it kill the query or the connection
3216
*/
3217
520.1.22 by Brian Aker
Second pass of thd cleanup
3218
void sql_kill(Session *session, ulong id, bool only_kill_query)
1 by brian
clean slate
3219
{
438.1.13 by Brian Aker
uint cleanup.
3220
  uint32_t error;
520.1.22 by Brian Aker
Second pass of thd cleanup
3221
  if (!(error= kill_one_thread(session, id, only_kill_query)))
3222
    my_ok(session);
1 by brian
clean slate
3223
  else
3224
    my_error(error, MYF(0), id);
3225
}
3226
3227
3228
/** If pointer is not a null pointer, append filename to it. */
3229
520.1.22 by Brian Aker
Second pass of thd cleanup
3230
bool append_file_to_dir(Session *session, const char **filename_ptr,
1 by brian
clean slate
3231
                        const char *table_name)
3232
{
3233
  char buff[FN_REFLEN],*ptr, *end;
3234
  if (!*filename_ptr)
3235
    return 0;					// nothing to do
3236
3237
  /* Check that the filename is not too long and it's a hard path */
3238
  if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
3239
      !test_if_hard_path(*filename_ptr))
3240
  {
3241
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
3242
    return 1;
3243
  }
3244
  /* Fix is using unix filename format on dos */
641.4.3 by Toru Maesaka
Final pass of replacing MySQL's my_stpcpy() with appropriate libc calls
3245
  strcpy(buff,*filename_ptr);
461 by Monty Taylor
Removed NullS. bu-bye.
3246
  end=convert_dirname(buff, *filename_ptr, NULL);
520.1.22 by Brian Aker
Second pass of thd cleanup
3247
  if (!(ptr= (char*) session->alloc((size_t) (end-buff) + strlen(table_name)+1)))
1 by brian
clean slate
3248
    return 1;					// End of memory
3249
  *filename_ptr=ptr;
673.2.1 by Toru Maesaka
First pass of replacing MySQL's strxmov with libc alternatives
3250
  sprintf(ptr,"%s%s",buff,table_name);
1 by brian
clean slate
3251
  return 0;
3252
}
3253
3254
3255
/**
3256
  Check if the select is a simple select (not an union).
3257
3258
  @retval
3259
    0	ok
3260
  @retval
3261
    1	error	; In this case the error messege is sent to the client
3262
*/
3263
3264
bool check_simple_select()
3265
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3266
  Session *session= current_session;
3267
  LEX *lex= session->lex;
1 by brian
clean slate
3268
  if (lex->current_select != &lex->select_lex)
3269
  {
3270
    char command[80];
520.1.22 by Brian Aker
Second pass of thd cleanup
3271
    Lex_input_stream *lip= session->m_lip;
629.5.2 by Toru Maesaka
Second pass of replacing MySQL's strmake() with libc calls
3272
    strncpy(command, lip->yylval->symbol.str,
722.2.33 by Monty Taylor
Fixed a wanton lack of null termination.
3273
            cmin(lip->yylval->symbol.length, sizeof(command)-1));
3274
    command[cmin(lip->yylval->symbol.length, sizeof(command)-1)]=0;
1 by brian
clean slate
3275
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
3276
    return 1;
3277
  }
3278
  return 0;
3279
}
3280
3281
3282
/**
3283
  Construct ALL/ANY/SOME subquery Item.
3284
3285
  @param left_expr   pointer to left expression
3286
  @param cmp         compare function creator
3287
  @param all         true if we create ALL subquery
3288
  @param select_lex  pointer on parsed subquery structure
3289
3290
  @return
3291
    constructed Item (or 0 if out of memory)
3292
*/
3293
Item * all_any_subquery_creator(Item *left_expr,
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
3294
                                chooser_compare_func_creator cmp,
3295
                                bool all,
3296
                                SELECT_LEX *select_lex)
1 by brian
clean slate
3297
{
3298
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
3299
    return new Item_in_subselect(left_expr, select_lex);
3300
3301
  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
3302
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
3303
3304
  Item_allany_subselect *it=
3305
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
3306
  if (all)
3307
    return it->upper_item= new Item_func_not_all(it);	/* ALL */
3308
3309
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
3310
}
3311
3312
3313
/**
826 by Brian Aker
Simplify update
3314
  Update query pre-check.
1 by brian
clean slate
3315
520.1.22 by Brian Aker
Second pass of thd cleanup
3316
  @param session		Thread handler
1 by brian
clean slate
3317
  @param tables	Global/local table list (have to be the same)
3318
3319
  @retval
55 by brian
Update for using real bool types.
3320
    false OK
1 by brian
clean slate
3321
  @retval
55 by brian
Update for using real bool types.
3322
    true  Error
1 by brian
clean slate
3323
*/
3324
826 by Brian Aker
Simplify update
3325
bool update_precheck(Session *session, TableList *)
1 by brian
clean slate
3326
{
3327
  const char *msg= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
3328
  LEX *lex= session->lex;
1 by brian
clean slate
3329
  SELECT_LEX *select_lex= &lex->select_lex;
3330
826 by Brian Aker
Simplify update
3331
  if (session->lex->select_lex.item_list.elements != session->lex->value_list.elements)
1 by brian
clean slate
3332
  {
3333
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3334
    return(true);
1 by brian
clean slate
3335
  }
3336
826 by Brian Aker
Simplify update
3337
  if (session->lex->select_lex.table_list.elements > 1)
1 by brian
clean slate
3338
  {
826 by Brian Aker
Simplify update
3339
    if (select_lex->order_list.elements)
3340
      msg= "ORDER BY";
3341
    else if (select_lex->select_limit)
3342
      msg= "LIMIT";
3343
    if (msg)
3344
    {
3345
      my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
3346
      return(true);
3347
    }
1 by brian
clean slate
3348
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3349
  return(false);
1 by brian
clean slate
3350
}
3351
3352
/**
3353
  Multi delete query pre-check.
3354
520.1.22 by Brian Aker
Second pass of thd cleanup
3355
  @param session			Thread handler
1 by brian
clean slate
3356
  @param tables		Global/local table list
3357
3358
  @retval
55 by brian
Update for using real bool types.
3359
    false OK
1 by brian
clean slate
3360
  @retval
55 by brian
Update for using real bool types.
3361
    true  error
1 by brian
clean slate
3362
*/
3363
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
3364
bool multi_delete_precheck(Session *session, TableList *)
1 by brian
clean slate
3365
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3366
  SELECT_LEX *select_lex= &session->lex->select_lex;
3367
  TableList **save_query_tables_own_last= session->lex->query_tables_own_last;
3368
3369
  session->lex->query_tables_own_last= 0;
3370
  session->lex->query_tables_own_last= save_query_tables_own_last;
3371
3372
  if ((session->options & OPTION_SAFE_UPDATES) && !select_lex->where)
1 by brian
clean slate
3373
  {
3374
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
3375
               ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3376
    return(true);
1 by brian
clean slate
3377
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3378
  return(false);
1 by brian
clean slate
3379
}
3380
3381
3382
/*
3383
  Given a table in the source list, find a correspondent table in the
3384
  table references list.
3385
3386
  @param lex Pointer to LEX representing multi-delete.
3387
  @param src Source table to match.
3388
  @param ref Table references list.
3389
3390
  @remark The source table list (tables listed before the FROM clause
3391
  or tables listed in the FROM clause before the USING clause) may
3392
  contain table names or aliases that must match unambiguously one,
3393
  and only one, table in the target table list (table references list,
3394
  after FROM/USING clause).
3395
3396
  @return Matching table, NULL otherwise.
3397
*/
3398
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
3399
static TableList *multi_delete_table_match(LEX *, TableList *tbl,
3400
                                           TableList *tables)
1 by brian
clean slate
3401
{
327.2.4 by Brian Aker
Refactoring table.h
3402
  TableList *match= NULL;
1 by brian
clean slate
3403
327.2.4 by Brian Aker
Refactoring table.h
3404
  for (TableList *elem= tables; elem; elem= elem->next_local)
1 by brian
clean slate
3405
  {
3406
    int cmp;
3407
3408
    if (tbl->is_fqtn && elem->is_alias)
3409
      continue; /* no match */
3410
    if (tbl->is_fqtn && elem->is_fqtn)
3411
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
3412
           strcmp(tbl->db, elem->db);
3413
    else if (elem->is_alias)
3414
      cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias);
3415
    else
3416
      cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) ||
3417
           strcmp(tbl->db, elem->db);
3418
3419
    if (cmp)
3420
      continue;
3421
3422
    if (match)
3423
    {
3424
      my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias);
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3425
      return(NULL);
1 by brian
clean slate
3426
    }
3427
3428
    match= elem;
3429
  }
3430
3431
  if (!match)
3432
    my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE");
3433
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3434
  return(match);
1 by brian
clean slate
3435
}
3436
3437
3438
/**
3439
  Link tables in auxilary table list of multi-delete with corresponding
3440
  elements in main table list, and set proper locks for them.
3441
3442
  @param lex   pointer to LEX representing multi-delete
3443
3444
  @retval
55 by brian
Update for using real bool types.
3445
    false   success
1 by brian
clean slate
3446
  @retval
55 by brian
Update for using real bool types.
3447
    true    error
1 by brian
clean slate
3448
*/
3449
3450
bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
3451
{
327.2.4 by Brian Aker
Refactoring table.h
3452
  TableList *tables= (TableList*)lex->select_lex.table_list.first;
3453
  TableList *target_tbl;
1 by brian
clean slate
3454
3455
  lex->table_count= 0;
3456
327.2.4 by Brian Aker
Refactoring table.h
3457
  for (target_tbl= (TableList *)lex->auxiliary_table_list.first;
1 by brian
clean slate
3458
       target_tbl; target_tbl= target_tbl->next_local)
3459
  {
3460
    lex->table_count++;
3461
    /* All tables in aux_tables must be found in FROM PART */
327.2.4 by Brian Aker
Refactoring table.h
3462
    TableList *walk= multi_delete_table_match(lex, target_tbl, tables);
1 by brian
clean slate
3463
    if (!walk)
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3464
      return(true);
1 by brian
clean slate
3465
    if (!walk->derived)
3466
    {
3467
      target_tbl->table_name= walk->table_name;
3468
      target_tbl->table_name_length= walk->table_name_length;
3469
    }
3470
    walk->updating= target_tbl->updating;
3471
    walk->lock_type= target_tbl->lock_type;
3472
    target_tbl->correspondent_table= walk;	// Remember corresponding table
3473
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3474
  return(false);
1 by brian
clean slate
3475
}
3476
3477
3478
/**
3479
  simple INSERT query pre-check.
3480
520.1.22 by Brian Aker
Second pass of thd cleanup
3481
  @param session		Thread handler
1 by brian
clean slate
3482
  @param tables	Global table list
3483
3484
  @retval
55 by brian
Update for using real bool types.
3485
    false  OK
1 by brian
clean slate
3486
  @retval
55 by brian
Update for using real bool types.
3487
    true   error
1 by brian
clean slate
3488
*/
3489
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
3490
bool insert_precheck(Session *session, TableList *)
1 by brian
clean slate
3491
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3492
  LEX *lex= session->lex;
1 by brian
clean slate
3493
3494
  /*
3495
    Check that we have modify privileges for the first table and
3496
    select privileges for the rest
3497
  */
3498
  if (lex->update_list.elements != lex->value_list.elements)
3499
  {
3500
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3501
    return(true);
1 by brian
clean slate
3502
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3503
  return(false);
1 by brian
clean slate
3504
}
3505
3506
3507
/**
3508
  CREATE TABLE query pre-check.
3509
520.1.22 by Brian Aker
Second pass of thd cleanup
3510
  @param session			Thread handler
1 by brian
clean slate
3511
  @param tables		Global table list
3512
  @param create_table	        Table which will be created
3513
3514
  @retval
55 by brian
Update for using real bool types.
3515
    false   OK
1 by brian
clean slate
3516
  @retval
55 by brian
Update for using real bool types.
3517
    true   Error
1 by brian
clean slate
3518
*/
3519
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
3520
bool create_table_precheck(Session *, TableList *,
327.2.4 by Brian Aker
Refactoring table.h
3521
                           TableList *create_table)
1 by brian
clean slate
3522
{
55 by brian
Update for using real bool types.
3523
  bool error= true;                                 // Error message is given
1 by brian
clean slate
3524
3525
  if (create_table && (strcmp(create_table->db, "information_schema") == 0))
3526
  {
575.4.7 by Monty Taylor
More header cleanup.
3527
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", INFORMATION_SCHEMA_NAME.c_str());
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3528
    return(true);
1 by brian
clean slate
3529
  }
3530
55 by brian
Update for using real bool types.
3531
  error= false;
1 by brian
clean slate
3532
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3533
  return(error);
1 by brian
clean slate
3534
}
3535
3536
3537
/**
3538
  negate given expression.
3539
520.1.22 by Brian Aker
Second pass of thd cleanup
3540
  @param session  thread handler
1 by brian
clean slate
3541
  @param expr expression for negation
3542
3543
  @return
3544
    negated expression
3545
*/
3546
520.1.22 by Brian Aker
Second pass of thd cleanup
3547
Item *negate_expression(Session *session, Item *expr)
1 by brian
clean slate
3548
{
3549
  Item *negated;
3550
  if (expr->type() == Item::FUNC_ITEM &&
3551
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
3552
  {
3553
    /* it is NOT(NOT( ... )) */
3554
    Item *arg= ((Item_func *) expr)->arguments()[0];
520.1.22 by Brian Aker
Second pass of thd cleanup
3555
    enum_parsing_place place= session->lex->current_select->parsing_place;
1 by brian
clean slate
3556
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
3557
      return arg;
3558
    /*
3559
      if it is not boolean function then we have to emulate value of
3560
      not(not(a)), it will be a != 0
3561
    */
3562
    return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
3563
  }
3564
520.1.22 by Brian Aker
Second pass of thd cleanup
3565
  if ((negated= expr->neg_transformer(session)) != 0)
1 by brian
clean slate
3566
    return negated;
3567
  return new Item_func_not(expr);
3568
}
3569
3570
3571
/*
3572
  Check that char length of a string does not exceed some limit.
3573
3574
  SYNOPSIS
3575
  check_string_char_length()
3576
      str              string to be checked
3577
      err_msg          error message to be displayed if the string is too long
3578
      max_char_length  max length in symbols
3579
      cs               string charset
3580
3581
  RETURN
55 by brian
Update for using real bool types.
3582
    false   the passed string is not longer than max_char_length
3583
    true    the passed string is longer than max_char_length
1 by brian
clean slate
3584
*/
3585
3586
3587
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
438.1.13 by Brian Aker
uint cleanup.
3588
                              uint32_t max_char_length, const CHARSET_INFO * const cs,
1 by brian
clean slate
3589
                              bool no_error)
3590
{
3591
  int well_formed_error;
438.1.13 by Brian Aker
uint cleanup.
3592
  uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
1 by brian
clean slate
3593
                                      max_char_length, &well_formed_error);
3594
3595
  if (!well_formed_error &&  str->length == res)
55 by brian
Update for using real bool types.
3596
    return false;
1 by brian
clean slate
3597
3598
  if (!no_error)
3599
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
55 by brian
Update for using real bool types.
3600
  return true;
1 by brian
clean slate
3601
}
3602
3603
575.4.7 by Monty Taylor
More header cleanup.
3604
bool check_identifier_name(LEX_STRING *str, uint32_t err_code,
3605
                           uint32_t max_char_length,
3606
                           const char *param_for_err_msg)
1 by brian
clean slate
3607
{
3608
  /*
3609
    We don't support non-BMP characters in identifiers at the moment,
3610
    so they should be prohibited until such support is done.
3611
    This is why we use the 3-byte utf8 to check well-formedness here.
3612
  */
760 by Brian Aker
Cleanup around UTf8 code.
3613
  const CHARSET_INFO * const cs= &my_charset_utf8mb4_general_ci;
3614
1 by brian
clean slate
3615
  int well_formed_error;
438.1.13 by Brian Aker
uint cleanup.
3616
  uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
1 by brian
clean slate
3617
                                      max_char_length, &well_formed_error);
3618
3619
  if (well_formed_error)
3620
  {
3621
    my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
55 by brian
Update for using real bool types.
3622
    return true;
1 by brian
clean slate
3623
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3624
1 by brian
clean slate
3625
  if (str->length == res)
55 by brian
Update for using real bool types.
3626
    return false;
1 by brian
clean slate
3627
3628
  switch (err_code)
3629
  {
3630
  case 0:
3631
    break;
3632
  case ER_WRONG_STRING_LENGTH:
3633
    my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
3634
    break;
3635
  case ER_TOO_LONG_IDENT:
3636
    my_error(err_code, MYF(0), str->str);
3637
    break;
3638
  default:
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3639
    assert(0);
1 by brian
clean slate
3640
    break;
3641
  }
55 by brian
Update for using real bool types.
3642
  return true;
1 by brian
clean slate
3643
}
3644
3645
3646
/*
3647
  Check if path does not contain mysql data home directory
3648
  SYNOPSIS
3649
    test_if_data_home_dir()
3650
    dir                     directory
3651
    conv_home_dir           converted data home directory
3652
    home_dir_len            converted data home directory length
3653
3654
  RETURN VALUES
3655
    0	ok
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3656
    1	error
1 by brian
clean slate
3657
*/
3658
3659
bool test_if_data_home_dir(const char *dir)
3660
{
3661
  char path[FN_REFLEN], conv_path[FN_REFLEN];
575.4.1 by ysano
Rename mysql to drizzle.
3662
  uint32_t dir_len, home_dir_len= strlen(drizzle_unpacked_real_data_home);
1 by brian
clean slate
3663
3664
  if (!dir)
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3665
    return(0);
1 by brian
clean slate
3666
3667
  (void) fn_format(path, dir, "", "",
3668
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
3669
  dir_len= unpack_dirname(conv_path, dir);
3670
3671
  if (home_dir_len < dir_len)
3672
  {
224.2.2 by Brian Aker
Second pass cleanup around filesystem type.
3673
    if (!my_strnncoll(character_set_filesystem,
481 by Brian Aker
Remove all of uchar.
3674
                      (const unsigned char*) conv_path, home_dir_len,
575.4.1 by ysano
Rename mysql to drizzle.
3675
                      (const unsigned char*) drizzle_unpacked_real_data_home,
224.2.2 by Brian Aker
Second pass cleanup around filesystem type.
3676
                      home_dir_len))
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3677
      return(1);
1 by brian
clean slate
3678
  }
51.1.61 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3679
  return(0);
1 by brian
clean slate
3680
}
3681
3682
520.4.50 by Monty Taylor
Finish changing the bison namespace argument from MYSQL to DRIZZLE
3683
extern int DRIZZLEparse(void *session); // from sql_yacc.cc
1 by brian
clean slate
3684
3685
3686
/**
520.4.50 by Monty Taylor
Finish changing the bison namespace argument from MYSQL to DRIZZLE
3687
  This is a wrapper of DRIZZLEparse(). All the code should call parse_sql()
3688
  instead of DRIZZLEparse().
1 by brian
clean slate
3689
520.1.22 by Brian Aker
Second pass of thd cleanup
3690
  @param session Thread context.
1 by brian
clean slate
3691
  @param lip Lexer context.
3692
3693
  @return Error status.
55 by brian
Update for using real bool types.
3694
    @retval false on success.
3695
    @retval true on parsing error.
1 by brian
clean slate
3696
*/
3697
520.1.22 by Brian Aker
Second pass of thd cleanup
3698
bool parse_sql(Session *session, Lex_input_stream *lip)
1 by brian
clean slate
3699
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3700
  assert(session->m_lip == NULL);
1 by brian
clean slate
3701
3702
  /* Set Lex_input_stream. */
3703
520.1.22 by Brian Aker
Second pass of thd cleanup
3704
  session->m_lip= lip;
1 by brian
clean slate
3705
3706
  /* Parse the query. */
3707
520.4.50 by Monty Taylor
Finish changing the bison namespace argument from MYSQL to DRIZZLE
3708
  bool mysql_parse_status= DRIZZLEparse(session) != 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
3709
520.4.50 by Monty Taylor
Finish changing the bison namespace argument from MYSQL to DRIZZLE
3710
  /* Check that if DRIZZLEparse() failed, session->is_error() is set. */
520.1.22 by Brian Aker
Second pass of thd cleanup
3711
3712
  assert(!mysql_parse_status || session->is_error());
1 by brian
clean slate
3713
3714
  /* Reset Lex_input_stream. */
3715
520.1.22 by Brian Aker
Second pass of thd cleanup
3716
  session->m_lip= NULL;
1 by brian
clean slate
3717
3718
  /* That's it. */
3719
520.1.22 by Brian Aker
Second pass of thd cleanup
3720
  return mysql_parse_status || session->is_fatal_error;
1 by brian
clean slate
3721
}
3722
3723
/**
3724
  @} (end of group Runtime_Environment)
3725
*/