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

« back to all changes in this revision

Viewing changes to .pc/debian-changes-2010.12.06-0ubuntu4/drizzled/sql_parse.cc

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2011-01-04 09:31:58 UTC
  • mfrom: (1.2.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20110104093158-smhgvkfdi2y9au3i
Tags: 2011.01.07-0ubuntu1
New upstream release.

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