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