~ubuntu-branches/ubuntu/saucy/drizzle/saucy-proposed

« back to all changes in this revision

Viewing changes to drizzled/sql_parse.cc

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2010-03-18 12:12:31 UTC
  • Revision ID: james.westby@ubuntu.com-20100318121231-k6g1xe6cshbwa0f8
Tags: upstream-2010.03.1347
ImportĀ upstreamĀ versionĀ 2010.03.1347

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
16
#include "config.h"
 
17
 
 
18
#define DRIZZLE_LEX 1
 
19
 
 
20
#include <drizzled/my_hash.h>
 
21
#include <drizzled/error.h>
 
22
#include <drizzled/nested_join.h>
 
23
#include <drizzled/query_id.h>
 
24
#include <drizzled/sql_parse.h>
 
25
#include <drizzled/data_home.h>
 
26
#include <drizzled/sql_base.h>
 
27
#include <drizzled/show.h>
 
28
#include <drizzled/db.h>
 
29
#include <drizzled/function/time/unix_timestamp.h>
 
30
#include <drizzled/function/get_system_var.h>
 
31
#include <drizzled/item/cmpfunc.h>
 
32
#include <drizzled/item/null.h>
 
33
#include <drizzled/session.h>
 
34
#include <drizzled/sql_load.h>
 
35
#include <drizzled/lock.h>
 
36
#include <drizzled/select_send.h>
 
37
#include <drizzled/plugin/client.h>
 
38
#include <drizzled/statement.h>
 
39
#include <drizzled/statement/alter_table.h>
 
40
#include "drizzled/probes.h"
 
41
#include "drizzled/session_list.h"
 
42
#include "drizzled/global_charset_info.h"
 
43
#include "drizzled/transaction_services.h"
 
44
 
 
45
#include "drizzled/plugin/logging.h"
 
46
#include "drizzled/plugin/query_rewrite.h"
 
47
#include "drizzled/plugin/authorization.h"
 
48
#include "drizzled/optimizer/explain_plan.h"
 
49
#include "drizzled/pthread_globals.h"
 
50
 
 
51
#include <limits.h>
 
52
 
 
53
#include <bitset>
 
54
#include <algorithm>
 
55
 
 
56
#include "drizzled/internal/my_sys.h"
 
57
 
 
58
using namespace std;
 
59
 
 
60
extern int DRIZZLEparse(void *session); // from sql_yacc.cc
 
61
 
 
62
namespace drizzled
 
63
{
 
64
 
 
65
/* Prototypes */
 
66
bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize);
 
67
static bool parse_sql(Session *session, Lex_input_stream *lip);
 
68
void mysql_parse(Session *session, const char *inBuf, uint32_t length);
 
69
 
 
70
/**
 
71
  @defgroup Runtime_Environment Runtime Environment
 
72
  @{
 
73
*/
 
74
 
 
75
extern size_t my_thread_stack_size;
 
76
extern const CHARSET_INFO *character_set_filesystem;
 
77
 
 
78
const LEX_STRING command_name[COM_END+1]={
 
79
  { C_STRING_WITH_LEN("Sleep") },
 
80
  { C_STRING_WITH_LEN("Quit") },
 
81
  { C_STRING_WITH_LEN("Init DB") },
 
82
  { C_STRING_WITH_LEN("Query") },
 
83
  { C_STRING_WITH_LEN("Shutdown") },
 
84
  { C_STRING_WITH_LEN("Connect") },
 
85
  { C_STRING_WITH_LEN("Ping") },
 
86
  { C_STRING_WITH_LEN("Error") }  // Last command number
 
87
};
 
88
 
 
89
const char *xa_state_names[]={
 
90
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
 
91
};
 
92
 
 
93
/**
 
94
  Mark all commands that somehow changes a table.
 
95
 
 
96
  This is used to check number of updates / hour.
 
97
 
 
98
  sql_command is actually set to SQLCOM_END sometimes
 
99
  so we need the +1 to include it in the array.
 
100
 
 
101
  See COMMAND_FLAG_xxx for different type of commands
 
102
     2  - query that returns meaningful ROW_COUNT() -
 
103
          a number of modified rows
 
104
*/
 
105
bitset<CF_BIT_SIZE> sql_command_flags[SQLCOM_END+1];
 
106
 
 
107
void init_update_queries(void)
 
108
{
 
109
  uint32_t x;
 
110
 
 
111
  for (x= 0; x <= SQLCOM_END; x++)
 
112
    sql_command_flags[x].reset();
 
113
 
 
114
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA;
 
115
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA;
 
116
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
 
117
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND;
 
118
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA;
 
119
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA;
 
120
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA;
 
121
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA;
 
122
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA;
 
123
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA;
 
124
 
 
125
  sql_command_flags[SQLCOM_UPDATE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
 
126
  sql_command_flags[SQLCOM_INSERT]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
 
127
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
 
128
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
 
129
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
 
130
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
 
131
 
 
132
  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
 
133
  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
 
134
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=  CF_STATUS_COMMAND;
 
135
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
 
136
 
 
137
  /*
 
138
    The following admin table operations are allowed
 
139
    on log tables.
 
140
  */
 
141
  sql_command_flags[SQLCOM_ANALYZE]=          CF_WRITE_LOGS_COMMAND;
 
142
}
 
143
 
 
144
/**
 
145
  Perform one connection-level (COM_XXXX) command.
 
146
 
 
147
  @param command         type of command to perform
 
148
  @param session             connection handle
 
149
  @param packet          data for the command, packet is always null-terminated
 
150
  @param packet_length   length of packet + 1 (to show that data is
 
151
                         null-terminated) except for COM_SLEEP, where it
 
152
                         can be zero.
 
153
 
 
154
  @todo
 
155
    set session->lex->sql_command to SQLCOM_END here.
 
156
  @todo
 
157
    The following has to be changed to an 8 byte integer
 
158
 
 
159
  @retval
 
160
    0   ok
 
161
  @retval
 
162
    1   request of thread shutdown, i. e. if command is
 
163
        COM_QUIT/COM_SHUTDOWN
 
164
*/
 
165
bool dispatch_command(enum enum_server_command command, Session *session,
 
166
                      char* packet, uint32_t packet_length)
 
167
{
 
168
  bool error= 0;
 
169
  Query_id &query_id= Query_id::get_query_id();
 
170
 
 
171
  DRIZZLE_COMMAND_START(session->thread_id,
 
172
                        command);
 
173
 
 
174
  session->command= command;
 
175
  session->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
 
176
  session->set_time();
 
177
  session->setQueryId(query_id.value());
 
178
 
 
179
  switch( command ) {
 
180
  /* Ignore these statements. */
 
181
  case COM_PING:
 
182
    break;
 
183
  /* Increase id and count all other statements. */
 
184
  default:
 
185
    statistic_increment(session->status_var.questions, &LOCK_status);
 
186
    query_id.next();
 
187
  }
 
188
 
 
189
  /* TODO: set session->lex->sql_command to SQLCOM_END here */
 
190
 
 
191
  plugin::Logging::preDo(session);
 
192
 
 
193
  session->server_status&=
 
194
           ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
195
  switch (command) {
 
196
  case COM_INIT_DB:
 
197
  {
 
198
    status_var_increment(session->status_var.com_stat[SQLCOM_CHANGE_DB]);
 
199
    string tmp(packet, packet_length);
 
200
 
 
201
    if (not mysql_change_db(session, tmp))
 
202
    {
 
203
      session->my_ok();
 
204
    }
 
205
    break;
 
206
  }
 
207
  case COM_QUERY:
 
208
  {
 
209
    if (! session->readAndStoreQuery(packet, packet_length))
 
210
      break;                                    // fatal error is set
 
211
    DRIZZLE_QUERY_START(session->query.c_str(),
 
212
                        session->thread_id,
 
213
                        const_cast<const char *>(session->db.empty() ? "" : session->db.c_str()));
 
214
 
 
215
    plugin::QueryRewriter::rewriteQuery(session->db, session->query);
 
216
    mysql_parse(session, session->query.c_str(), session->query.length());
 
217
 
 
218
    break;
 
219
  }
 
220
  case COM_QUIT:
 
221
    /* We don't calculate statistics for this command */
 
222
    session->main_da.disable_status();              // Don't send anything back
 
223
    error=true;                                 // End server
 
224
    break;
 
225
  case COM_SHUTDOWN:
 
226
  {
 
227
    status_var_increment(session->status_var.com_other);
 
228
    session->my_eof();
 
229
    session->close_thread_tables();                     // Free before kill
 
230
    kill_drizzle();
 
231
    error=true;
 
232
    break;
 
233
  }
 
234
  case COM_PING:
 
235
    status_var_increment(session->status_var.com_other);
 
236
    session->my_ok();                           // Tell client we are alive
 
237
    break;
 
238
  case COM_SLEEP:
 
239
  case COM_CONNECT:                             // Impossible here
 
240
  case COM_END:
 
241
  default:
 
242
    my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
 
243
    break;
 
244
  }
 
245
 
 
246
  /* If commit fails, we should be able to reset the OK status. */
 
247
  session->main_da.can_overwrite_status= true;
 
248
  TransactionServices &transaction_services= TransactionServices::singleton();
 
249
  transaction_services.ha_autocommit_or_rollback(session, session->is_error());
 
250
  session->main_da.can_overwrite_status= false;
 
251
 
 
252
  session->transaction.stmt.reset();
 
253
 
 
254
 
 
255
  /* report error issued during command execution */
 
256
  if (session->killed_errno())
 
257
  {
 
258
    if (! session->main_da.is_set())
 
259
      session->send_kill_message();
 
260
  }
 
261
  if (session->killed == Session::KILL_QUERY || session->killed == Session::KILL_BAD_DATA)
 
262
  {
 
263
    session->killed= Session::NOT_KILLED;
 
264
    session->mysys_var->abort= 0;
 
265
  }
 
266
 
 
267
  /* Can not be true, but do not take chances in production. */
 
268
  assert(! session->main_da.is_sent);
 
269
 
 
270
  switch (session->main_da.status())
 
271
  {
 
272
  case Diagnostics_area::DA_ERROR:
 
273
    /* The query failed, send error to log and abort bootstrap. */
 
274
    session->client->sendError(session->main_da.sql_errno(),
 
275
                               session->main_da.message());
 
276
    break;
 
277
 
 
278
  case Diagnostics_area::DA_EOF:
 
279
    session->client->sendEOF();
 
280
    break;
 
281
 
 
282
  case Diagnostics_area::DA_OK:
 
283
    session->client->sendOK();
 
284
    break;
 
285
 
 
286
  case Diagnostics_area::DA_DISABLED:
 
287
    break;
 
288
 
 
289
  case Diagnostics_area::DA_EMPTY:
 
290
  default:
 
291
    session->client->sendOK();
 
292
    break;
 
293
  }
 
294
 
 
295
  session->main_da.is_sent= true;
 
296
 
 
297
  session->set_proc_info("closing tables");
 
298
  /* Free tables */
 
299
  session->close_thread_tables();
 
300
 
 
301
  plugin::Logging::postDo(session);
 
302
 
 
303
  /* Store temp state for processlist */
 
304
  session->set_proc_info("cleaning up");
 
305
  session->command= COM_SLEEP;
 
306
  memset(session->process_list_info, 0, PROCESS_LIST_WIDTH);
 
307
  session->query.clear();
 
308
 
 
309
  session->set_proc_info(NULL);
 
310
  free_root(session->mem_root,MYF(memory::KEEP_PREALLOC));
 
311
 
 
312
  if (DRIZZLE_QUERY_DONE_ENABLED() || DRIZZLE_COMMAND_DONE_ENABLED())
 
313
  {
 
314
    if (command == COM_QUERY)
 
315
    {
 
316
      DRIZZLE_QUERY_DONE(session->is_error());
 
317
    }
 
318
    DRIZZLE_COMMAND_DONE(session->is_error());
 
319
  }
 
320
 
 
321
  return error;
 
322
}
 
323
 
 
324
 
 
325
/**
 
326
  Create a TableList object for an INFORMATION_SCHEMA table.
 
327
 
 
328
    This function is used in the parser to convert a SHOW or DESCRIBE
 
329
    table_name command to a SELECT from INFORMATION_SCHEMA.
 
330
    It prepares a Select_Lex and a TableList object to represent the
 
331
    given command as a SELECT parse tree.
 
332
 
 
333
  @param session           thread handle
 
334
  @param lex               current lex
 
335
  @param table_ident       table alias if it's used
 
336
  @param schema_table_name the name of the INFORMATION_SCHEMA table to be
 
337
                           created
 
338
 
 
339
  @note
 
340
    Due to the way this function works with memory and LEX it cannot
 
341
    be used outside the parser (parse tree transformations outside
 
342
    the parser break PS and SP).
 
343
 
 
344
  @retval
 
345
    0                 success
 
346
  @retval
 
347
    1                 out of memory or SHOW commands are not allowed
 
348
                      in this version of the server.
 
349
*/
 
350
static bool _schema_select(Session *session, Select_Lex *sel,
 
351
                           const string& schema_table_name)
 
352
{
 
353
  LEX_STRING db, table;
 
354
  /*
 
355
     We have to make non const db_name & table_name
 
356
     because of lower_case_table_names
 
357
  */
 
358
  session->make_lex_string(&db, "data_dictionary", sizeof("data_dictionary"), false);
 
359
  session->make_lex_string(&table, schema_table_name, false);
 
360
 
 
361
  if (! sel->add_table_to_list(session, new Table_ident(db, table),
 
362
                               NULL, 0, TL_READ))
 
363
  {
 
364
    return true;
 
365
  }
 
366
  return false;
 
367
}
 
368
 
 
369
int prepare_new_schema_table(Session *session, LEX *lex,
 
370
                             const string& schema_table_name)
 
371
{
 
372
  Select_Lex *schema_select_lex= NULL;
 
373
 
 
374
  Select_Lex *select_lex= lex->current_select;
 
375
  assert(select_lex);
 
376
  if (_schema_select(session, select_lex, schema_table_name))
 
377
  {
 
378
    return(1);
 
379
  }
 
380
  TableList *table_list= (TableList*) select_lex->table_list.first;
 
381
  assert(table_list);
 
382
  table_list->schema_select_lex= schema_select_lex;
 
383
 
 
384
  return 0;
 
385
}
 
386
 
 
387
/**
 
388
  Execute command saved in session and lex->sql_command.
 
389
 
 
390
    Before every operation that can request a write lock for a table
 
391
    wait if a global read lock exists. However do not wait if this
 
392
    thread has locked tables already. No new locks can be requested
 
393
    until the other locks are released. The thread that requests the
 
394
    global read lock waits for write locked tables to become unlocked.
 
395
 
 
396
    Note that wait_if_global_read_lock() sets a protection against a new
 
397
    global read lock when it succeeds. This needs to be released by
 
398
    start_waiting_global_read_lock() after the operation.
 
399
 
 
400
  @param session                       Thread handle
 
401
 
 
402
  @todo
 
403
    - Invalidate the table in the query cache if something changed
 
404
    after unlocking when changes become visible.
 
405
    TODO: this is workaround. right way will be move invalidating in
 
406
    the unlock procedure.
 
407
    - TODO: use check_change_password()
 
408
    - JOIN is not supported yet. TODO
 
409
    - SUSPEND and FOR MIGRATE are not supported yet. TODO
 
410
 
 
411
  @retval
 
412
    false       OK
 
413
  @retval
 
414
    true        Error
 
415
*/
 
416
 
 
417
static int
 
418
mysql_execute_command(Session *session)
 
419
{
 
420
  bool res= false;
 
421
  LEX  *lex= session->lex;
 
422
  /* first Select_Lex (have special meaning for many of non-SELECTcommands) */
 
423
  Select_Lex *select_lex= &lex->select_lex;
 
424
  /* list of all tables in query */
 
425
  TableList *all_tables;
 
426
  /* A peek into the query string */
 
427
  size_t proc_info_len= session->query.length() > PROCESS_LIST_WIDTH ?
 
428
                        PROCESS_LIST_WIDTH : session->query.length();
 
429
 
 
430
  memcpy(session->process_list_info, session->query.c_str(), proc_info_len);
 
431
  session->process_list_info[proc_info_len]= '\0';
 
432
 
 
433
  /*
 
434
    In many cases first table of main Select_Lex have special meaning =>
 
435
    check that it is first table in global list and relink it first in
 
436
    queries_tables list if it is necessary (we need such relinking only
 
437
    for queries with subqueries in select list, in this case tables of
 
438
    subqueries will go to global list first)
 
439
 
 
440
    all_tables will differ from first_table only if most upper Select_Lex
 
441
    do not contain tables.
 
442
 
 
443
    Because of above in place where should be at least one table in most
 
444
    outer Select_Lex we have following check:
 
445
    assert(first_table == all_tables);
 
446
    assert(first_table == all_tables && first_table != 0);
 
447
  */
 
448
  lex->first_lists_tables_same();
 
449
  /* should be assigned after making first tables same */
 
450
  all_tables= lex->query_tables;
 
451
  /* set context for commands which do not use setup_tables */
 
452
  select_lex->
 
453
    context.resolve_in_table_list_only((TableList*)select_lex->
 
454
                                       table_list.first);
 
455
 
 
456
  /*
 
457
    Reset warning count for each query that uses tables
 
458
    A better approach would be to reset this for any commands
 
459
    that is not a SHOW command or a select that only access local
 
460
    variables, but for now this is probably good enough.
 
461
    Don't reset warnings when executing a stored routine.
 
462
  */
 
463
  if (all_tables || ! lex->is_single_level_stmt())
 
464
  {
 
465
    drizzle_reset_errors(session, 0);
 
466
  }
 
467
 
 
468
  status_var_increment(session->status_var.com_stat[lex->sql_command]);
 
469
 
 
470
  assert(session->transaction.stmt.hasModifiedNonTransData() == false);
 
471
 
 
472
  /* now we are ready to execute the statement */
 
473
  res= lex->statement->execute();
 
474
 
 
475
  session->set_proc_info("query end");
 
476
 
 
477
  /*
 
478
    The return value for ROW_COUNT() is "implementation dependent" if the
 
479
    statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
 
480
    wants. We also keep the last value in case of SQLCOM_CALL or
 
481
    SQLCOM_EXECUTE.
 
482
  */
 
483
  if (! (sql_command_flags[lex->sql_command].test(CF_BIT_HAS_ROW_COUNT)))
 
484
  {
 
485
    session->row_count_func= -1;
 
486
  }
 
487
 
 
488
  return (res || session->is_error());
 
489
}
 
490
 
 
491
bool execute_sqlcom_select(Session *session, TableList *all_tables)
 
492
{
 
493
  LEX   *lex= session->lex;
 
494
  select_result *result=lex->result;
 
495
  bool res= false;
 
496
  /* assign global limit variable if limit is not given */
 
497
  {
 
498
    Select_Lex *param= lex->unit.global_parameters;
 
499
    if (!param->explicit_limit)
 
500
      param->select_limit=
 
501
        new Item_int((uint64_t) session->variables.select_limit);
 
502
  }
 
503
  if (!(res= session->openTablesLock(all_tables)))
 
504
  {
 
505
    if (lex->describe)
 
506
    {
 
507
      /*
 
508
        We always use select_send for EXPLAIN, even if it's an EXPLAIN
 
509
        for SELECT ... INTO OUTFILE: a user application should be able
 
510
        to prepend EXPLAIN to any query and receive output for it,
 
511
        even if the query itself redirects the output.
 
512
      */
 
513
      if (!(result= new select_send()))
 
514
        return true;
 
515
      session->send_explain_fields(result);
 
516
      optimizer::ExplainPlan planner;
 
517
      res= planner.explainUnion(session, &session->lex->unit, result);
 
518
      if (lex->describe & DESCRIBE_EXTENDED)
 
519
      {
 
520
        char buff[1024];
 
521
        String str(buff,(uint32_t) sizeof(buff), system_charset_info);
 
522
        str.length(0);
 
523
        session->lex->unit.print(&str, QT_ORDINARY);
 
524
        str.append('\0');
 
525
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
526
                     ER_YES, str.ptr());
 
527
      }
 
528
      if (res)
 
529
        result->abort();
 
530
      else
 
531
        result->send_eof();
 
532
      delete result;
 
533
    }
 
534
    else
 
535
    {
 
536
      if (!result && !(result= new select_send()))
 
537
        return true;
 
538
      res= handle_select(session, lex, result, 0);
 
539
      if (result != lex->result)
 
540
        delete result;
 
541
    }
 
542
  }
 
543
  return res;
 
544
}
 
545
 
 
546
 
 
547
#define MY_YACC_INIT 1000                       // Start with big alloc
 
548
#define MY_YACC_MAX  32000                      // Because of 'short'
 
549
 
 
550
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
 
551
{
 
552
  LEX   *lex= current_session->lex;
 
553
  ulong old_info=0;
 
554
  if ((uint32_t) *yystacksize >= MY_YACC_MAX)
 
555
    return 1;
 
556
  if (!lex->yacc_yyvs)
 
557
    old_info= *yystacksize;
 
558
  *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
 
559
  unsigned char *tmpptr= NULL;
 
560
  if (!(tmpptr= (unsigned char *)realloc(lex->yacc_yyvs,
 
561
                                         *yystacksize* sizeof(**yyvs))))
 
562
      return 1;
 
563
  lex->yacc_yyvs= tmpptr;
 
564
  tmpptr= NULL;
 
565
  if (!(tmpptr= (unsigned char*)realloc(lex->yacc_yyss,
 
566
                                        *yystacksize* sizeof(**yyss))))
 
567
      return 1;
 
568
  lex->yacc_yyss= tmpptr;
 
569
  if (old_info)
 
570
  {                                             // Copy old info from stack
 
571
    memcpy(lex->yacc_yyss, *yyss, old_info*sizeof(**yyss));
 
572
    memcpy(lex->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
 
573
  }
 
574
  *yyss=(short*) lex->yacc_yyss;
 
575
  *yyvs=(YYSTYPE*) lex->yacc_yyvs;
 
576
  return 0;
 
577
}
 
578
 
 
579
 
 
580
void
 
581
mysql_init_select(LEX *lex)
 
582
{
 
583
  Select_Lex *select_lex= lex->current_select;
 
584
  select_lex->init_select();
 
585
  lex->wild= 0;
 
586
  if (select_lex == &lex->select_lex)
 
587
  {
 
588
    assert(lex->result == 0);
 
589
    lex->exchange= 0;
 
590
  }
 
591
}
 
592
 
 
593
 
 
594
bool
 
595
mysql_new_select(LEX *lex, bool move_down)
 
596
{
 
597
  Select_Lex *select_lex;
 
598
  Session *session= lex->session;
 
599
 
 
600
  if (!(select_lex= new (session->mem_root) Select_Lex()))
 
601
    return(1);
 
602
  select_lex->select_number= ++session->select_number;
 
603
  select_lex->parent_lex= lex; /* Used in init_query. */
 
604
  select_lex->init_query();
 
605
  select_lex->init_select();
 
606
  lex->nest_level++;
 
607
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
 
608
  {
 
609
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
 
610
    return(1);
 
611
  }
 
612
  select_lex->nest_level= lex->nest_level;
 
613
  if (move_down)
 
614
  {
 
615
    Select_Lex_Unit *unit;
 
616
    /* first select_lex of subselect or derived table */
 
617
    if (!(unit= new (session->mem_root) Select_Lex_Unit()))
 
618
      return(1);
 
619
 
 
620
    unit->init_query();
 
621
    unit->init_select();
 
622
    unit->session= session;
 
623
    unit->include_down(lex->current_select);
 
624
    unit->link_next= 0;
 
625
    unit->link_prev= 0;
 
626
    unit->return_to= lex->current_select;
 
627
    select_lex->include_down(unit);
 
628
    /*
 
629
      By default we assume that it is usual subselect and we have outer name
 
630
      resolution context, if no we will assign it to 0 later
 
631
    */
 
632
    select_lex->context.outer_context= &select_lex->outer_select()->context;
 
633
  }
 
634
  else
 
635
  {
 
636
    if (lex->current_select->order_list.first && !lex->current_select->braces)
 
637
    {
 
638
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
 
639
      return(1);
 
640
    }
 
641
    select_lex->include_neighbour(lex->current_select);
 
642
    Select_Lex_Unit *unit= select_lex->master_unit();
 
643
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
 
644
      return(1);
 
645
    select_lex->context.outer_context=
 
646
                unit->first_select()->context.outer_context;
 
647
  }
 
648
 
 
649
  select_lex->master_unit()->global_parameters= select_lex;
 
650
  select_lex->include_global((Select_Lex_Node**)&lex->all_selects_list);
 
651
  lex->current_select= select_lex;
 
652
  /*
 
653
    in subquery is SELECT query and we allow resolution of names in SELECT
 
654
    list
 
655
  */
 
656
  select_lex->context.resolve_in_select_list= true;
 
657
  return(0);
 
658
}
 
659
 
 
660
/**
 
661
  Create a select to return the same output as 'SELECT @@var_name'.
 
662
 
 
663
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
 
664
 
 
665
  This will crash with a core dump if the variable doesn't exists.
 
666
 
 
667
  @param var_name               Variable name
 
668
*/
 
669
 
 
670
void create_select_for_variable(const char *var_name)
 
671
{
 
672
  Session *session;
 
673
  LEX *lex;
 
674
  LEX_STRING tmp, null_lex_string;
 
675
  Item *var;
 
676
  char buff[MAX_SYS_VAR_LENGTH*2+4+8];
 
677
  char *end= buff;
 
678
 
 
679
  session= current_session;
 
680
  lex= session->lex;
 
681
  mysql_init_select(lex);
 
682
  lex->sql_command= SQLCOM_SELECT;
 
683
  tmp.str= (char*) var_name;
 
684
  tmp.length=strlen(var_name);
 
685
  memset(&null_lex_string.str, 0, sizeof(null_lex_string));
 
686
  /*
 
687
    We set the name of Item to @@session.var_name because that then is used
 
688
    as the column name in the output.
 
689
  */
 
690
  if ((var= get_system_var(session, OPT_SESSION, tmp, null_lex_string)))
 
691
  {
 
692
    end+= sprintf(buff, "@@session.%s", var_name);
 
693
    var->set_name(buff, end-buff, system_charset_info);
 
694
    session->add_item_to_list(var);
 
695
  }
 
696
  return;
 
697
}
 
698
 
 
699
 
 
700
/**
 
701
  Parse a query.
 
702
 
 
703
  @param       session     Current thread
 
704
  @param       inBuf   Begining of the query text
 
705
  @param       length  Length of the query text
 
706
*/
 
707
 
 
708
void mysql_parse(Session *session, const char *inBuf, uint32_t length)
 
709
{
 
710
  lex_start(session);
 
711
  session->reset_for_next_command();
 
712
 
 
713
  LEX *lex= session->lex;
 
714
 
 
715
  Lex_input_stream lip(session, inBuf, length);
 
716
 
 
717
  bool err= parse_sql(session, &lip);
 
718
 
 
719
  if (!err)
 
720
  {
 
721
    {
 
722
      if (! session->is_error())
 
723
      {
 
724
        DRIZZLE_QUERY_EXEC_START(session->query.c_str(),
 
725
                                 session->thread_id,
 
726
                                 const_cast<const char *>(session->db.empty() ? "" : session->db.c_str()));
 
727
        /* Actually execute the query */
 
728
        mysql_execute_command(session);
 
729
        DRIZZLE_QUERY_EXEC_DONE(0);
 
730
      }
 
731
    }
 
732
  }
 
733
  else
 
734
  {
 
735
    assert(session->is_error());
 
736
  }
 
737
 
 
738
  lex->unit.cleanup();
 
739
  session->set_proc_info("freeing items");
 
740
  session->end_statement();
 
741
  session->cleanup_after_query();
 
742
 
 
743
  return;
 
744
}
 
745
 
 
746
 
 
747
 
 
748
/**
 
749
  Store field definition for create.
 
750
 
 
751
  @return
 
752
    Return 0 if ok
 
753
*/
 
754
 
 
755
bool add_field_to_list(Session *session, LEX_STRING *field_name, enum_field_types type,
 
756
                       char *length, char *decimals,
 
757
                       uint32_t type_modifier,
 
758
                       enum column_format_type column_format,
 
759
                       Item *default_value, Item *on_update_value,
 
760
                       LEX_STRING *comment,
 
761
                       char *change,
 
762
                       List<String> *interval_list, const CHARSET_INFO * const cs)
 
763
{
 
764
  register CreateField *new_field;
 
765
  LEX  *lex= session->lex;
 
766
  statement::AlterTable *statement= (statement::AlterTable *)lex->statement;
 
767
 
 
768
  if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
 
769
    return true;
 
770
 
 
771
  if (type_modifier & PRI_KEY_FLAG)
 
772
  {
 
773
    Key *key;
 
774
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
 
775
    key= new Key(Key::PRIMARY, null_lex_str,
 
776
                      &default_key_create_info,
 
777
                      0, lex->col_list);
 
778
    statement->alter_info.key_list.push_back(key);
 
779
    lex->col_list.empty();
 
780
  }
 
781
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
 
782
  {
 
783
    Key *key;
 
784
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
 
785
    key= new Key(Key::UNIQUE, null_lex_str,
 
786
                 &default_key_create_info, 0,
 
787
                 lex->col_list);
 
788
    statement->alter_info.key_list.push_back(key);
 
789
    lex->col_list.empty();
 
790
  }
 
791
 
 
792
  if (default_value)
 
793
  {
 
794
    /*
 
795
      Default value should be literal => basic constants =>
 
796
      no need fix_fields()
 
797
 
 
798
      We allow only one function as part of default value -
 
799
      NOW() as default for TIMESTAMP type.
 
800
    */
 
801
    if (default_value->type() == Item::FUNC_ITEM &&
 
802
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
 
803
         type == DRIZZLE_TYPE_TIMESTAMP))
 
804
    {
 
805
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
 
806
      return true;
 
807
    }
 
808
    else if (default_value->type() == Item::NULL_ITEM)
 
809
    {
 
810
      default_value= 0;
 
811
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
 
812
          NOT_NULL_FLAG)
 
813
      {
 
814
        my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
 
815
        return true;
 
816
      }
 
817
    }
 
818
    else if (type_modifier & AUTO_INCREMENT_FLAG)
 
819
    {
 
820
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
 
821
      return true;
 
822
    }
 
823
  }
 
824
 
 
825
  if (on_update_value && type != DRIZZLE_TYPE_TIMESTAMP)
 
826
  {
 
827
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
 
828
    return true;
 
829
  }
 
830
 
 
831
  if (!(new_field= new CreateField()) ||
 
832
      new_field->init(session, field_name->str, type, length, decimals, type_modifier,
 
833
                      default_value, on_update_value, comment, change,
 
834
                      interval_list, cs, 0, column_format))
 
835
    return true;
 
836
 
 
837
  statement->alter_info.create_list.push_back(new_field);
 
838
  lex->last_field=new_field;
 
839
 
 
840
  return false;
 
841
}
 
842
 
 
843
 
 
844
/** Store position for column in ALTER TABLE .. ADD column. */
 
845
 
 
846
void store_position_for_column(const char *name)
 
847
{
 
848
  current_session->lex->last_field->after=const_cast<char*> (name);
 
849
}
 
850
 
 
851
/**
 
852
  Add a table to list of used tables.
 
853
 
 
854
  @param table          Table to add
 
855
  @param alias          alias for table (or null if no alias)
 
856
  @param table_options  A set of the following bits:
 
857
                         - TL_OPTION_UPDATING : Table will be updated
 
858
                         - TL_OPTION_FORCE_INDEX : Force usage of index
 
859
                         - TL_OPTION_ALIAS : an alias in multi table DELETE
 
860
  @param lock_type      How table should be locked
 
861
  @param use_index      List of indexed used in USE INDEX
 
862
  @param ignore_index   List of indexed used in IGNORE INDEX
 
863
 
 
864
  @retval
 
865
      0         Error
 
866
  @retval
 
867
    \#  Pointer to TableList element added to the total table list
 
868
*/
 
869
 
 
870
TableList *Select_Lex::add_table_to_list(Session *session,
 
871
                                             Table_ident *table,
 
872
                                             LEX_STRING *alias,
 
873
                                             uint32_t table_options,
 
874
                                             thr_lock_type lock_type,
 
875
                                             List<Index_hint> *index_hints_arg,
 
876
                                             LEX_STRING *option)
 
877
{
 
878
  register TableList *ptr;
 
879
  TableList *previous_table_ref; /* The table preceding the current one. */
 
880
  char *alias_str;
 
881
  LEX *lex= session->lex;
 
882
 
 
883
  if (!table)
 
884
    return NULL;                                // End of memory
 
885
  alias_str= alias ? alias->str : table->table.str;
 
886
  if (!test(table_options & TL_OPTION_ALIAS) &&
 
887
      check_table_name(table->table.str, table->table.length))
 
888
  {
 
889
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
 
890
    return NULL;
 
891
  }
 
892
 
 
893
  if (table->is_derived_table() == false && table->db.str &&
 
894
      check_db_name(&table->db))
 
895
  {
 
896
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
 
897
    return NULL;
 
898
  }
 
899
 
 
900
  if (!alias)                                   /* Alias is case sensitive */
 
901
  {
 
902
    if (table->sel)
 
903
    {
 
904
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
 
905
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
 
906
      return NULL;
 
907
    }
 
908
    if (!(alias_str= (char*) session->memdup(alias_str,table->table.length+1)))
 
909
      return NULL;
 
910
  }
 
911
  if (!(ptr = (TableList *) session->calloc(sizeof(TableList))))
 
912
    return NULL;
 
913
  if (table->db.str)
 
914
  {
 
915
    ptr->is_fqtn= true;
 
916
    ptr->db= table->db.str;
 
917
    ptr->db_length= table->db.length;
 
918
  }
 
919
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
 
920
    return NULL;
 
921
  else
 
922
    ptr->is_fqtn= false;
 
923
 
 
924
  ptr->alias= alias_str;
 
925
  ptr->is_alias= alias ? true : false;
 
926
  if (table->table.length)
 
927
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
 
928
  ptr->table_name=table->table.str;
 
929
  ptr->table_name_length=table->table.length;
 
930
  ptr->lock_type=   lock_type;
 
931
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
 
932
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
 
933
  ptr->derived=     table->sel;
 
934
  ptr->select_lex=  lex->current_select;
 
935
  ptr->index_hints= index_hints_arg;
 
936
  ptr->option= option ? option->str : 0;
 
937
  /* check that used name is unique */
 
938
  if (lock_type != TL_IGNORE)
 
939
  {
 
940
    TableList *first_table= (TableList*) table_list.first;
 
941
    for (TableList *tables= first_table ;
 
942
         tables ;
 
943
         tables=tables->next_local)
 
944
    {
 
945
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
 
946
          !strcmp(ptr->db, tables->db))
 
947
      {
 
948
        my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str);
 
949
        return NULL;
 
950
      }
 
951
    }
 
952
  }
 
953
  /* Store the table reference preceding the current one. */
 
954
  if (table_list.elements > 0)
 
955
  {
 
956
    /*
 
957
      table_list.next points to the last inserted TableList->next_local'
 
958
      element
 
959
      We don't use the offsetof() macro here to avoid warnings from gcc
 
960
    */
 
961
    previous_table_ref= (TableList*) ((char*) table_list.next -
 
962
                                       ((char*) &(ptr->next_local) -
 
963
                                        (char*) ptr));
 
964
    /*
 
965
      Set next_name_resolution_table of the previous table reference to point
 
966
      to the current table reference. In effect the list
 
967
      TableList::next_name_resolution_table coincides with
 
968
      TableList::next_local. Later this may be changed in
 
969
      store_top_level_join_columns() for NATURAL/USING joins.
 
970
    */
 
971
    previous_table_ref->next_name_resolution_table= ptr;
 
972
  }
 
973
 
 
974
  /*
 
975
    Link the current table reference in a local list (list for current select).
 
976
    Notice that as a side effect here we set the next_local field of the
 
977
    previous table reference to 'ptr'. Here we also add one element to the
 
978
    list 'table_list'.
 
979
  */
 
980
  table_list.link_in_list((unsigned char*) ptr, (unsigned char**) &ptr->next_local);
 
981
  ptr->next_name_resolution_table= NULL;
 
982
  /* Link table in global list (all used tables) */
 
983
  lex->add_to_query_tables(ptr);
 
984
  return ptr;
 
985
}
 
986
 
 
987
 
 
988
/**
 
989
  Initialize a new table list for a nested join.
 
990
 
 
991
    The function initializes a structure of the TableList type
 
992
    for a nested join. It sets up its nested join list as empty.
 
993
    The created structure is added to the front of the current
 
994
    join list in the Select_Lex object. Then the function
 
995
    changes the current nest level for joins to refer to the newly
 
996
    created empty list after having saved the info on the old level
 
997
    in the initialized structure.
 
998
 
 
999
  @param session         current thread
 
1000
 
 
1001
  @retval
 
1002
    0   if success
 
1003
  @retval
 
1004
    1   otherwise
 
1005
*/
 
1006
 
 
1007
bool Select_Lex::init_nested_join(Session *session)
 
1008
{
 
1009
  TableList *ptr;
 
1010
  nested_join_st *nested_join;
 
1011
 
 
1012
  if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
 
1013
                                       sizeof(nested_join_st))))
 
1014
    return true;
 
1015
  nested_join= ptr->nested_join=
 
1016
    ((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
 
1017
 
 
1018
  join_list->push_front(ptr);
 
1019
  ptr->embedding= embedding;
 
1020
  ptr->join_list= join_list;
 
1021
  ptr->alias= (char*) "(nested_join)";
 
1022
  embedding= ptr;
 
1023
  join_list= &nested_join->join_list;
 
1024
  join_list->empty();
 
1025
  return false;
 
1026
}
 
1027
 
 
1028
 
 
1029
/**
 
1030
  End a nested join table list.
 
1031
 
 
1032
    The function returns to the previous join nest level.
 
1033
    If the current level contains only one member, the function
 
1034
    moves it one level up, eliminating the nest.
 
1035
 
 
1036
  @param session         current thread
 
1037
 
 
1038
  @return
 
1039
    - Pointer to TableList element added to the total table list, if success
 
1040
    - 0, otherwise
 
1041
*/
 
1042
 
 
1043
TableList *Select_Lex::end_nested_join(Session *)
 
1044
{
 
1045
  TableList *ptr;
 
1046
  nested_join_st *nested_join;
 
1047
 
 
1048
  assert(embedding);
 
1049
  ptr= embedding;
 
1050
  join_list= ptr->join_list;
 
1051
  embedding= ptr->embedding;
 
1052
  nested_join= ptr->nested_join;
 
1053
  if (nested_join->join_list.elements == 1)
 
1054
  {
 
1055
    TableList *embedded= nested_join->join_list.head();
 
1056
    join_list->pop();
 
1057
    embedded->join_list= join_list;
 
1058
    embedded->embedding= embedding;
 
1059
    join_list->push_front(embedded);
 
1060
    ptr= embedded;
 
1061
  }
 
1062
  else if (nested_join->join_list.elements == 0)
 
1063
  {
 
1064
    join_list->pop();
 
1065
    ptr= NULL;                                     // return value
 
1066
  }
 
1067
  return ptr;
 
1068
}
 
1069
 
 
1070
 
 
1071
/**
 
1072
  Nest last join operation.
 
1073
 
 
1074
    The function nest last join operation as if it was enclosed in braces.
 
1075
 
 
1076
  @param session         current thread
 
1077
 
 
1078
  @retval
 
1079
    0  Error
 
1080
  @retval
 
1081
    \#  Pointer to TableList element created for the new nested join
 
1082
*/
 
1083
 
 
1084
TableList *Select_Lex::nest_last_join(Session *session)
 
1085
{
 
1086
  TableList *ptr;
 
1087
  nested_join_st *nested_join;
 
1088
  List<TableList> *embedded_list;
 
1089
 
 
1090
  if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
 
1091
                                       sizeof(nested_join_st))))
 
1092
    return NULL;
 
1093
  nested_join= ptr->nested_join=
 
1094
    ((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
 
1095
 
 
1096
  ptr->embedding= embedding;
 
1097
  ptr->join_list= join_list;
 
1098
  ptr->alias= (char*) "(nest_last_join)";
 
1099
  embedded_list= &nested_join->join_list;
 
1100
  embedded_list->empty();
 
1101
 
 
1102
  for (uint32_t i=0; i < 2; i++)
 
1103
  {
 
1104
    TableList *table= join_list->pop();
 
1105
    table->join_list= embedded_list;
 
1106
    table->embedding= ptr;
 
1107
    embedded_list->push_back(table);
 
1108
    if (table->natural_join)
 
1109
    {
 
1110
      ptr->is_natural_join= true;
 
1111
      /*
 
1112
        If this is a JOIN ... USING, move the list of joined fields to the
 
1113
        table reference that describes the join.
 
1114
      */
 
1115
      if (prev_join_using)
 
1116
        ptr->join_using_fields= prev_join_using;
 
1117
    }
 
1118
  }
 
1119
  join_list->push_front(ptr);
 
1120
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
 
1121
  return ptr;
 
1122
}
 
1123
 
 
1124
 
 
1125
/**
 
1126
  Add a table to the current join list.
 
1127
 
 
1128
    The function puts a table in front of the current join list
 
1129
    of Select_Lex object.
 
1130
    Thus, joined tables are put into this list in the reverse order
 
1131
    (the most outer join operation follows first).
 
1132
 
 
1133
  @param table       the table to add
 
1134
 
 
1135
  @return
 
1136
    None
 
1137
*/
 
1138
 
 
1139
void Select_Lex::add_joined_table(TableList *table)
 
1140
{
 
1141
  join_list->push_front(table);
 
1142
  table->join_list= join_list;
 
1143
  table->embedding= embedding;
 
1144
}
 
1145
 
 
1146
 
 
1147
/**
 
1148
  Convert a right join into equivalent left join.
 
1149
 
 
1150
    The function takes the current join list t[0],t[1] ... and
 
1151
    effectively converts it into the list t[1],t[0] ...
 
1152
    Although the outer_join flag for the new nested table contains
 
1153
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
 
1154
    operation.
 
1155
 
 
1156
  EXAMPLES
 
1157
  @verbatim
 
1158
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
 
1159
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr
 
1160
 
 
1161
    SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
 
1162
      SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr
 
1163
 
 
1164
    SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
 
1165
      SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr
 
1166
 
 
1167
    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
 
1168
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
 
1169
   @endverbatim
 
1170
 
 
1171
  @param session         current thread
 
1172
 
 
1173
  @return
 
1174
    - Pointer to the table representing the inner table, if success
 
1175
    - 0, otherwise
 
1176
*/
 
1177
 
 
1178
TableList *Select_Lex::convert_right_join()
 
1179
{
 
1180
  TableList *tab2= join_list->pop();
 
1181
  TableList *tab1= join_list->pop();
 
1182
 
 
1183
  join_list->push_front(tab2);
 
1184
  join_list->push_front(tab1);
 
1185
  tab1->outer_join|= JOIN_TYPE_RIGHT;
 
1186
 
 
1187
  return tab1;
 
1188
}
 
1189
 
 
1190
/**
 
1191
  Set lock for all tables in current select level.
 
1192
 
 
1193
  @param lock_type                      Lock to set for tables
 
1194
 
 
1195
  @note
 
1196
    If lock is a write lock, then tables->updating is set 1
 
1197
    This is to get tables_ok to know that the table is updated by the
 
1198
    query
 
1199
*/
 
1200
 
 
1201
void Select_Lex::set_lock_for_tables(thr_lock_type lock_type)
 
1202
{
 
1203
  for (TableList *tables= (TableList*) table_list.first;
 
1204
       tables;
 
1205
       tables= tables->next_local)
 
1206
  {
 
1207
    tables->lock_type= lock_type;
 
1208
  }
 
1209
}
 
1210
 
 
1211
 
 
1212
/**
 
1213
  Create a fake Select_Lex for a unit.
 
1214
 
 
1215
    The method create a fake Select_Lex object for a unit.
 
1216
    This object is created for any union construct containing a union
 
1217
    operation and also for any single select union construct of the form
 
1218
    @verbatim
 
1219
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ...
 
1220
    @endvarbatim
 
1221
    or of the form
 
1222
    @varbatim
 
1223
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
 
1224
    @endvarbatim
 
1225
 
 
1226
  @param session_arg               thread handle
 
1227
 
 
1228
  @note
 
1229
    The object is used to retrieve rows from the temporary table
 
1230
    where the result on the union is obtained.
 
1231
 
 
1232
  @retval
 
1233
    1     on failure to create the object
 
1234
  @retval
 
1235
    0     on success
 
1236
*/
 
1237
 
 
1238
bool Select_Lex_Unit::add_fake_select_lex(Session *session_arg)
 
1239
{
 
1240
  Select_Lex *first_sl= first_select();
 
1241
  assert(!fake_select_lex);
 
1242
 
 
1243
  if (!(fake_select_lex= new (session_arg->mem_root) Select_Lex()))
 
1244
      return(1);
 
1245
  fake_select_lex->include_standalone(this,
 
1246
                                      (Select_Lex_Node**)&fake_select_lex);
 
1247
  fake_select_lex->select_number= INT_MAX;
 
1248
  fake_select_lex->parent_lex= session_arg->lex; /* Used in init_query. */
 
1249
  fake_select_lex->make_empty_select();
 
1250
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
 
1251
  fake_select_lex->select_limit= 0;
 
1252
 
 
1253
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
 
1254
  /* allow item list resolving in fake select for ORDER BY */
 
1255
  fake_select_lex->context.resolve_in_select_list= true;
 
1256
  fake_select_lex->context.select_lex= fake_select_lex;
 
1257
 
 
1258
  if (!is_union())
 
1259
  {
 
1260
    /*
 
1261
      This works only for
 
1262
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
 
1263
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
 
1264
      just before the parser starts processing order_list
 
1265
    */
 
1266
    global_parameters= fake_select_lex;
 
1267
    fake_select_lex->no_table_names_allowed= 1;
 
1268
    session_arg->lex->current_select= fake_select_lex;
 
1269
  }
 
1270
  session_arg->lex->pop_context();
 
1271
  return(0);
 
1272
}
 
1273
 
 
1274
 
 
1275
/**
 
1276
  Push a new name resolution context for a JOIN ... ON clause to the
 
1277
  context stack of a query block.
 
1278
 
 
1279
    Create a new name resolution context for a JOIN ... ON clause,
 
1280
    set the first and last leaves of the list of table references
 
1281
    to be used for name resolution, and push the newly created
 
1282
    context to the stack of contexts of the query.
 
1283
 
 
1284
  @param session       pointer to current thread
 
1285
  @param left_op   left  operand of the JOIN
 
1286
  @param right_op  rigth operand of the JOIN
 
1287
 
 
1288
  @retval
 
1289
    false  if all is OK
 
1290
  @retval
 
1291
    true   if a memory allocation error occured
 
1292
*/
 
1293
 
 
1294
bool
 
1295
push_new_name_resolution_context(Session *session,
 
1296
                                 TableList *left_op, TableList *right_op)
 
1297
{
 
1298
  Name_resolution_context *on_context;
 
1299
  if (!(on_context= new (session->mem_root) Name_resolution_context))
 
1300
    return true;
 
1301
  on_context->init();
 
1302
  on_context->first_name_resolution_table=
 
1303
    left_op->first_leaf_for_name_resolution();
 
1304
  on_context->last_name_resolution_table=
 
1305
    right_op->last_leaf_for_name_resolution();
 
1306
  return session->lex->push_context(on_context);
 
1307
}
 
1308
 
 
1309
 
 
1310
/**
 
1311
  Add an ON condition to the second operand of a JOIN ... ON.
 
1312
 
 
1313
    Add an ON condition to the right operand of a JOIN ... ON clause.
 
1314
 
 
1315
  @param b     the second operand of a JOIN ... ON
 
1316
  @param expr  the condition to be added to the ON clause
 
1317
 
 
1318
  @retval
 
1319
    false  if there was some error
 
1320
  @retval
 
1321
    true   if all is OK
 
1322
*/
 
1323
 
 
1324
void add_join_on(TableList *b, Item *expr)
 
1325
{
 
1326
  if (expr)
 
1327
  {
 
1328
    if (!b->on_expr)
 
1329
      b->on_expr= expr;
 
1330
    else
 
1331
    {
 
1332
      /*
 
1333
        If called from the parser, this happens if you have both a
 
1334
        right and left join. If called later, it happens if we add more
 
1335
        than one condition to the ON clause.
 
1336
      */
 
1337
      b->on_expr= new Item_cond_and(b->on_expr,expr);
 
1338
    }
 
1339
    b->on_expr->top_level_item();
 
1340
  }
 
1341
}
 
1342
 
 
1343
 
 
1344
/**
 
1345
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
 
1346
  tables.
 
1347
 
 
1348
    This function marks that table b should be joined with a either via
 
1349
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
 
1350
    cases of each other, so we treat them together. The function
 
1351
    setup_conds() creates a list of equal condition between all fields
 
1352
    of the same name for NATURAL JOIN or the fields in 'using_fields'
 
1353
    for JOIN ... USING. The list of equality conditions is stored
 
1354
    either in b->on_expr, or in JOIN::conds, depending on whether there
 
1355
    was an outer join.
 
1356
 
 
1357
  EXAMPLE
 
1358
  @verbatim
 
1359
    SELECT * FROM t1 NATURAL LEFT JOIN t2
 
1360
     <=>
 
1361
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
 
1362
 
 
1363
    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
 
1364
     <=>
 
1365
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
 
1366
 
 
1367
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
 
1368
     <=>
 
1369
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
 
1370
   @endverbatim
 
1371
 
 
1372
  @param a                Left join argument
 
1373
  @param b                Right join argument
 
1374
  @param using_fields    Field names from USING clause
 
1375
*/
 
1376
 
 
1377
void add_join_natural(TableList *a, TableList *b, List<String> *using_fields,
 
1378
                      Select_Lex *lex)
 
1379
{
 
1380
  b->natural_join= a;
 
1381
  lex->prev_join_using= using_fields;
 
1382
}
 
1383
 
 
1384
 
 
1385
/**
 
1386
  kill on thread.
 
1387
 
 
1388
  @param session                        Thread class
 
1389
  @param id                     Thread id
 
1390
  @param only_kill_query        Should it kill the query or the connection
 
1391
 
 
1392
  @note
 
1393
    This is written such that we have a short lock on LOCK_thread_count
 
1394
*/
 
1395
 
 
1396
static unsigned int
 
1397
kill_one_thread(Session *, ulong id, bool only_kill_query)
 
1398
{
 
1399
  Session *tmp= NULL;
 
1400
  uint32_t error= ER_NO_SUCH_THREAD;
 
1401
  pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
 
1402
  
 
1403
  for (SessionList::iterator it= getSessionList().begin(); it != getSessionList().end(); ++it )
 
1404
  {
 
1405
    if ((*it)->thread_id == id)
 
1406
    {
 
1407
      tmp= *it;
 
1408
      pthread_mutex_lock(&tmp->LOCK_delete);    // Lock from delete
 
1409
      break;
 
1410
    }
 
1411
  }
 
1412
  pthread_mutex_unlock(&LOCK_thread_count);
 
1413
  if (tmp)
 
1414
  {
 
1415
 
 
1416
    if (tmp->isViewable())
 
1417
    {
 
1418
      tmp->awake(only_kill_query ? Session::KILL_QUERY : Session::KILL_CONNECTION);
 
1419
      error= 0;
 
1420
    }
 
1421
 
 
1422
    pthread_mutex_unlock(&tmp->LOCK_delete);
 
1423
  }
 
1424
  return(error);
 
1425
}
 
1426
 
 
1427
 
 
1428
/*
 
1429
  kills a thread and sends response
 
1430
 
 
1431
  SYNOPSIS
 
1432
    sql_kill()
 
1433
    session                     Thread class
 
1434
    id                  Thread id
 
1435
    only_kill_query     Should it kill the query or the connection
 
1436
*/
 
1437
 
 
1438
void sql_kill(Session *session, ulong id, bool only_kill_query)
 
1439
{
 
1440
  uint32_t error;
 
1441
  if (!(error= kill_one_thread(session, id, only_kill_query)))
 
1442
    session->my_ok();
 
1443
  else
 
1444
    my_error(error, MYF(0), id);
 
1445
}
 
1446
 
 
1447
 
 
1448
/**
 
1449
  Check if the select is a simple select (not an union).
 
1450
 
 
1451
  @retval
 
1452
    0   ok
 
1453
  @retval
 
1454
    1   error   ; In this case the error messege is sent to the client
 
1455
*/
 
1456
 
 
1457
bool check_simple_select()
 
1458
{
 
1459
  Session *session= current_session;
 
1460
  LEX *lex= session->lex;
 
1461
  if (lex->current_select != &lex->select_lex)
 
1462
  {
 
1463
    char command[80];
 
1464
    Lex_input_stream *lip= session->m_lip;
 
1465
    strncpy(command, lip->yylval->symbol.str,
 
1466
            min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1)));
 
1467
    command[min(lip->yylval->symbol.length, (uint32_t)(sizeof(command)-1))]=0;
 
1468
    my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command);
 
1469
    return 1;
 
1470
  }
 
1471
  return 0;
 
1472
}
 
1473
 
 
1474
 
 
1475
/**
 
1476
  Construct ALL/ANY/SOME subquery Item.
 
1477
 
 
1478
  @param left_expr   pointer to left expression
 
1479
  @param cmp         compare function creator
 
1480
  @param all         true if we create ALL subquery
 
1481
  @param select_lex  pointer on parsed subquery structure
 
1482
 
 
1483
  @return
 
1484
    constructed Item (or 0 if out of memory)
 
1485
*/
 
1486
Item * all_any_subquery_creator(Item *left_expr,
 
1487
                                chooser_compare_func_creator cmp,
 
1488
                                bool all,
 
1489
                                Select_Lex *select_lex)
 
1490
{
 
1491
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
 
1492
    return new Item_in_subselect(left_expr, select_lex);
 
1493
 
 
1494
  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
 
1495
    return new Item_func_not(new Item_in_subselect(left_expr, select_lex));
 
1496
 
 
1497
  Item_allany_subselect *it=
 
1498
    new Item_allany_subselect(left_expr, cmp, select_lex, all);
 
1499
  if (all)
 
1500
    return it->upper_item= new Item_func_not_all(it);   /* ALL */
 
1501
 
 
1502
  return it->upper_item= new Item_func_nop_all(it);      /* ANY/SOME */
 
1503
}
 
1504
 
 
1505
 
 
1506
/**
 
1507
  Update query pre-check.
 
1508
 
 
1509
  @param session                Thread handler
 
1510
  @param tables Global/local table list (have to be the same)
 
1511
 
 
1512
  @retval
 
1513
    false OK
 
1514
  @retval
 
1515
    true  Error
 
1516
*/
 
1517
 
 
1518
bool update_precheck(Session *session, TableList *)
 
1519
{
 
1520
  const char *msg= 0;
 
1521
  LEX *lex= session->lex;
 
1522
  Select_Lex *select_lex= &lex->select_lex;
 
1523
 
 
1524
  if (session->lex->select_lex.item_list.elements != session->lex->value_list.elements)
 
1525
  {
 
1526
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
 
1527
    return(true);
 
1528
  }
 
1529
 
 
1530
  if (session->lex->select_lex.table_list.elements > 1)
 
1531
  {
 
1532
    if (select_lex->order_list.elements)
 
1533
      msg= "ORDER BY";
 
1534
    else if (select_lex->select_limit)
 
1535
      msg= "LIMIT";
 
1536
    if (msg)
 
1537
    {
 
1538
      my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg);
 
1539
      return(true);
 
1540
    }
 
1541
  }
 
1542
  return(false);
 
1543
}
 
1544
 
 
1545
 
 
1546
/**
 
1547
  simple INSERT query pre-check.
 
1548
 
 
1549
  @param session                Thread handler
 
1550
  @param tables Global table list
 
1551
 
 
1552
  @retval
 
1553
    false  OK
 
1554
  @retval
 
1555
    true   error
 
1556
*/
 
1557
 
 
1558
bool insert_precheck(Session *session, TableList *)
 
1559
{
 
1560
  LEX *lex= session->lex;
 
1561
 
 
1562
  /*
 
1563
    Check that we have modify privileges for the first table and
 
1564
    select privileges for the rest
 
1565
  */
 
1566
  if (lex->update_list.elements != lex->value_list.elements)
 
1567
  {
 
1568
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
 
1569
    return(true);
 
1570
  }
 
1571
  return(false);
 
1572
}
 
1573
 
 
1574
 
 
1575
/**
 
1576
  CREATE TABLE query pre-check.
 
1577
 
 
1578
  @param session                        Thread handler
 
1579
  @param tables         Global table list
 
1580
  @param create_table           Table which will be created
 
1581
 
 
1582
  @retval
 
1583
    false   OK
 
1584
  @retval
 
1585
    true   Error
 
1586
*/
 
1587
 
 
1588
bool create_table_precheck(TableIdentifier &identifier)
 
1589
{
 
1590
  if (not plugin::StorageEngine::canCreateTable(identifier))
 
1591
  {
 
1592
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", identifier.getSchemaName());
 
1593
    return true;
 
1594
  }
 
1595
 
 
1596
  return false;
 
1597
}
 
1598
 
 
1599
 
 
1600
/**
 
1601
  negate given expression.
 
1602
 
 
1603
  @param session  thread handler
 
1604
  @param expr expression for negation
 
1605
 
 
1606
  @return
 
1607
    negated expression
 
1608
*/
 
1609
 
 
1610
Item *negate_expression(Session *session, Item *expr)
 
1611
{
 
1612
  Item *negated;
 
1613
  if (expr->type() == Item::FUNC_ITEM &&
 
1614
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
 
1615
  {
 
1616
    /* it is NOT(NOT( ... )) */
 
1617
    Item *arg= ((Item_func *) expr)->arguments()[0];
 
1618
    enum_parsing_place place= session->lex->current_select->parsing_place;
 
1619
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
 
1620
      return arg;
 
1621
    /*
 
1622
      if it is not boolean function then we have to emulate value of
 
1623
      not(not(a)), it will be a != 0
 
1624
    */
 
1625
    return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1));
 
1626
  }
 
1627
 
 
1628
  if ((negated= expr->neg_transformer(session)) != 0)
 
1629
    return negated;
 
1630
  return new Item_func_not(expr);
 
1631
}
 
1632
 
 
1633
 
 
1634
/*
 
1635
  Check that char length of a string does not exceed some limit.
 
1636
 
 
1637
  SYNOPSIS
 
1638
  check_string_char_length()
 
1639
      str              string to be checked
 
1640
      err_msg          error message to be displayed if the string is too long
 
1641
      max_char_length  max length in symbols
 
1642
      cs               string charset
 
1643
 
 
1644
  RETURN
 
1645
    false   the passed string is not longer than max_char_length
 
1646
    true    the passed string is longer than max_char_length
 
1647
*/
 
1648
 
 
1649
 
 
1650
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
 
1651
                              uint32_t max_char_length, const CHARSET_INFO * const cs,
 
1652
                              bool no_error)
 
1653
{
 
1654
  int well_formed_error;
 
1655
  uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
 
1656
                                      max_char_length, &well_formed_error);
 
1657
 
 
1658
  if (!well_formed_error &&  str->length == res)
 
1659
    return false;
 
1660
 
 
1661
  if (!no_error)
 
1662
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_char_length);
 
1663
  return true;
 
1664
}
 
1665
 
 
1666
 
 
1667
bool check_identifier_name(LEX_STRING *str, uint32_t err_code,
 
1668
                           uint32_t max_char_length,
 
1669
                           const char *param_for_err_msg)
 
1670
{
 
1671
  /*
 
1672
    We don't support non-BMP characters in identifiers at the moment,
 
1673
    so they should be prohibited until such support is done.
 
1674
    This is why we use the 3-byte utf8 to check well-formedness here.
 
1675
  */
 
1676
  const CHARSET_INFO * const cs= &my_charset_utf8mb4_general_ci;
 
1677
 
 
1678
  int well_formed_error;
 
1679
  uint32_t res= cs->cset->well_formed_len(cs, str->str, str->str + str->length,
 
1680
                                      max_char_length, &well_formed_error);
 
1681
 
 
1682
  if (well_formed_error)
 
1683
  {
 
1684
    my_error(ER_INVALID_CHARACTER_STRING, MYF(0), "identifier", str->str);
 
1685
    return true;
 
1686
  }
 
1687
 
 
1688
  if (str->length == res)
 
1689
    return false;
 
1690
 
 
1691
  switch (err_code)
 
1692
  {
 
1693
  case 0:
 
1694
    break;
 
1695
  case ER_WRONG_STRING_LENGTH:
 
1696
    my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
 
1697
    break;
 
1698
  case ER_TOO_LONG_IDENT:
 
1699
    my_error(err_code, MYF(0), str->str);
 
1700
    break;
 
1701
  default:
 
1702
    assert(0);
 
1703
    break;
 
1704
  }
 
1705
  return true;
 
1706
}
 
1707
 
 
1708
 
 
1709
/**
 
1710
  This is a wrapper of DRIZZLEparse(). All the code should call parse_sql()
 
1711
  instead of DRIZZLEparse().
 
1712
 
 
1713
  @param session Thread context.
 
1714
  @param lip Lexer context.
 
1715
 
 
1716
  @return Error status.
 
1717
    @retval false on success.
 
1718
    @retval true on parsing error.
 
1719
*/
 
1720
 
 
1721
static bool parse_sql(Session *session, Lex_input_stream *lip)
 
1722
{
 
1723
  assert(session->m_lip == NULL);
 
1724
 
 
1725
  DRIZZLE_QUERY_PARSE_START(session->query.c_str());
 
1726
 
 
1727
  /* Set Lex_input_stream. */
 
1728
 
 
1729
  session->m_lip= lip;
 
1730
 
 
1731
  /* Parse the query. */
 
1732
 
 
1733
  bool mysql_parse_status= DRIZZLEparse(session) != 0;
 
1734
 
 
1735
  /* Check that if DRIZZLEparse() failed, session->is_error() is set. */
 
1736
 
 
1737
  assert(!mysql_parse_status || session->is_error());
 
1738
 
 
1739
  /* Reset Lex_input_stream. */
 
1740
 
 
1741
  session->m_lip= NULL;
 
1742
 
 
1743
  DRIZZLE_QUERY_PARSE_DONE(mysql_parse_status || session->is_fatal_error);
 
1744
 
 
1745
  /* That's it. */
 
1746
 
 
1747
  return mysql_parse_status || session->is_fatal_error;
 
1748
}
 
1749
 
 
1750
/**
 
1751
  @} (end of group Runtime_Environment)
 
1752
*/
 
1753
 
 
1754
} /* namespace drizzled */