~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_parse.cc

  • Committer: Brian Aker
  • Date: 2009-08-18 07:20:29 UTC
  • mfrom: (1117.1.9 merge)
  • Revision ID: brian@gaz-20090818072029-s9ch5lcmltxwidn7
Merge of Brian

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
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>
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
17
15
 
18
16
#define DRIZZLE_LEX 1
19
 
 
20
 
#include <drizzled/item/num.h>
21
 
#include <drizzled/abort_exception.h>
22
 
#include <drizzled/my_hash.h>
 
17
#include <drizzled/server_includes.h>
 
18
#include <mysys/hash.h>
 
19
#include <drizzled/logging.h>
 
20
#include <drizzled/db.h>
23
21
#include <drizzled/error.h>
24
22
#include <drizzled/nested_join.h>
25
23
#include <drizzled/query_id.h>
26
 
#include <drizzled/transaction_services.h>
27
24
#include <drizzled/sql_parse.h>
28
25
#include <drizzled/data_home.h>
29
26
#include <drizzled/sql_base.h>
30
27
#include <drizzled/show.h>
 
28
#include <drizzled/info_schema.h>
 
29
#include <drizzled/rename.h>
31
30
#include <drizzled/function/time/unix_timestamp.h>
32
31
#include <drizzled/function/get_system_var.h>
33
32
#include <drizzled/item/cmpfunc.h>
34
33
#include <drizzled/item/null.h>
35
34
#include <drizzled/session.h>
36
 
#include <drizzled/session/cache.h>
37
35
#include <drizzled/sql_load.h>
38
36
#include <drizzled/lock.h>
39
37
#include <drizzled/select_send.h>
40
 
#include <drizzled/plugin/client.h>
41
38
#include <drizzled/statement.h>
42
 
#include <drizzled/statement/alter_table.h>
43
 
#include <drizzled/probes.h>
44
 
#include <drizzled/global_charset_info.h>
45
 
 
46
 
#include <drizzled/plugin/logging.h>
47
 
#include <drizzled/plugin/query_rewrite.h>
48
 
#include <drizzled/plugin/query_cache.h>
49
 
#include <drizzled/plugin/authorization.h>
50
 
#include <drizzled/optimizer/explain_plan.h>
51
 
#include <drizzled/pthread_globals.h>
52
 
#include <drizzled/plugin/event_observer.h>
53
 
#include <drizzled/visibility.h>
54
 
 
55
 
#include <drizzled/schema.h>
56
 
 
57
 
#include <limits.h>
58
39
 
59
40
#include <bitset>
60
41
#include <algorithm>
61
 
#include <boost/date_time.hpp>
62
 
#include <drizzled/internal/my_sys.h>
63
42
 
64
43
using namespace std;
65
44
 
66
 
extern int base_sql_parse(drizzled::Session *session); // from sql_yacc.cc
67
 
 
68
 
namespace drizzled
69
 
{
70
 
 
71
45
/* Prototypes */
72
 
bool my_yyoverflow(short **a, ParserType **b, ulong *yystacksize);
73
 
static bool parse_sql(Session *session, Lex_input_stream *lip);
74
 
void parse(Session *session, const char *inBuf, uint32_t length);
 
46
static bool append_file_to_dir(Session *session, const char **filename_ptr,
 
47
                               const char *table_name);
 
48
static bool reload_cache(Session *session, ulong options, TableList *tables);
 
49
 
 
50
bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize);
75
51
 
76
52
/**
77
53
  @defgroup Runtime_Environment Runtime Environment
80
56
 
81
57
extern size_t my_thread_stack_size;
82
58
extern const CHARSET_INFO *character_set_filesystem;
83
 
 
84
 
namespace
85
 
{
86
 
 
87
 
static const std::string command_name[COM_END+1]={
88
 
  "Sleep",
89
 
  "Quit",
90
 
  "Init DB",
91
 
  "Query",
92
 
  "Shutdown",
93
 
  "Connect",
94
 
  "Ping",
95
 
  "Error"  // Last command number
 
59
const char *any_db="*any*";     // Special symbol for check_access
 
60
 
 
61
const LEX_STRING command_name[COM_END+1]={
 
62
  { C_STRING_WITH_LEN("Sleep") },
 
63
  { C_STRING_WITH_LEN("Quit") },
 
64
  { C_STRING_WITH_LEN("Init DB") },
 
65
  { C_STRING_WITH_LEN("Query") },
 
66
  { C_STRING_WITH_LEN("Shutdown") },
 
67
  { C_STRING_WITH_LEN("Connect") },
 
68
  { C_STRING_WITH_LEN("Ping") },
 
69
  { C_STRING_WITH_LEN("Error") }  // Last command number
96
70
};
97
71
 
98
 
}
99
 
 
100
72
const char *xa_state_names[]={
101
73
  "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED"
102
74
};
115
87
*/
116
88
bitset<CF_BIT_SIZE> sql_command_flags[SQLCOM_END+1];
117
89
 
118
 
const std::string &getCommandName(const enum_server_command& command)
119
 
{
120
 
  return command_name[command];
121
 
}
122
 
 
123
90
void init_update_queries(void)
124
91
{
125
92
  uint32_t x;
145
112
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
146
113
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_HAS_ROW_COUNT;
147
114
 
 
115
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND;
 
116
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND;
 
117
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND;
 
118
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND;
 
119
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND;
 
120
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND;
148
121
  sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND;
149
122
  sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND;
 
123
  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
 
124
  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
150
125
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=  CF_STATUS_COMMAND;
151
126
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
152
127
 
 
128
   sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND |
 
129
                                               CF_SHOW_TABLE_COMMAND);
 
130
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND |
 
131
                                                CF_SHOW_TABLE_COMMAND);
153
132
  /*
154
133
    The following admin table operations are allowed
155
134
    on log tables.
156
135
  */
 
136
  sql_command_flags[SQLCOM_OPTIMIZE]=         CF_WRITE_LOGS_COMMAND;
157
137
  sql_command_flags[SQLCOM_ANALYZE]=          CF_WRITE_LOGS_COMMAND;
158
138
}
159
139
 
 
140
 
 
141
bool is_update_query(enum enum_sql_command command)
 
142
{
 
143
  assert(command >= 0 && command <= SQLCOM_END);
 
144
  return (sql_command_flags[command].test(CF_BIT_CHANGES_DATA));
 
145
}
 
146
 
160
147
/**
161
148
  Perform one connection-level (COM_XXXX) command.
162
149
 
168
155
                         can be zero.
169
156
 
170
157
  @todo
171
 
    set session->getLex()->sql_command to SQLCOM_END here.
 
158
    set session->lex->sql_command to SQLCOM_END here.
172
159
  @todo
173
160
    The following has to be changed to an 8 byte integer
174
161
 
184
171
  bool error= 0;
185
172
  Query_id &query_id= Query_id::get_query_id();
186
173
 
187
 
  DRIZZLE_COMMAND_START(session->thread_id, command);
188
 
 
189
 
  session->command= command;
190
 
  session->getLex()->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
 
174
  session->command=command;
 
175
  session->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
191
176
  session->set_time();
192
 
  session->setQueryId(query_id.value());
 
177
  session->query_id= query_id.value();
193
178
 
194
179
  switch( command ) {
195
180
  /* Ignore these statements. */
197
182
    break;
198
183
  /* Increase id and count all other statements. */
199
184
  default:
200
 
    session->status_var.questions++;
 
185
    statistic_increment(session->status_var.questions, &LOCK_status);
201
186
    query_id.next();
202
187
  }
203
188
 
204
 
  /* @todo set session->getLex()->sql_command to SQLCOM_END here */
 
189
  /* TODO: set session->lex->sql_command to SQLCOM_END here */
205
190
 
206
 
  plugin::Logging::preDo(session);
207
 
  if (unlikely(plugin::EventObserver::beforeStatement(*session)))
208
 
  {
209
 
    // We should do something about an error...
210
 
  }
 
191
  logging_pre_do(session);
211
192
 
212
193
  session->server_status&=
213
194
           ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
214
195
  switch (command) {
215
196
  case COM_INIT_DB:
216
197
  {
217
 
    if (packet_length == 0)
218
 
    {
219
 
      my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
220
 
      break;
221
 
    }
222
 
 
223
 
    string tmp(packet, packet_length);
224
 
 
225
 
    identifier::Schema identifier(tmp);
226
 
 
227
 
    if (not schema::change(*session, identifier))
 
198
    LEX_STRING tmp;
 
199
    status_var_increment(session->status_var.com_stat[SQLCOM_CHANGE_DB]);
 
200
    tmp.str= packet;
 
201
    tmp.length= packet_length;
 
202
    if (!mysql_change_db(session, &tmp, false))
228
203
    {
229
204
      session->my_ok();
230
205
    }
232
207
  }
233
208
  case COM_QUERY:
234
209
  {
235
 
    if (not session->readAndStoreQuery(packet, packet_length))
 
210
    if (! session->readAndStoreQuery(packet, packet_length))
236
211
      break;                                    // fatal error is set
237
 
    DRIZZLE_QUERY_START(session->getQueryString()->c_str(),
238
 
                        session->thread_id,
239
 
                        const_cast<const char *>(session->schema()->c_str()));
 
212
    const char* end_of_stmt= NULL;
240
213
 
241
 
    parse(session, session->getQueryString()->c_str(), session->getQueryString()->length());
 
214
    mysql_parse(session, session->query, session->query_length, &end_of_stmt);
242
215
 
243
216
    break;
244
217
  }
245
218
  case COM_QUIT:
246
219
    /* We don't calculate statistics for this command */
 
220
    session->protocol->setError(0);
247
221
    session->main_da.disable_status();              // Don't send anything back
248
222
    error=true;                                 // End server
249
223
    break;
250
224
  case COM_SHUTDOWN:
251
225
  {
252
 
    session->status_var.com_other++;
 
226
    status_var_increment(session->status_var.com_other);
253
227
    session->my_eof();
254
228
    session->close_thread_tables();                     // Free before kill
255
229
    kill_drizzle();
257
231
    break;
258
232
  }
259
233
  case COM_PING:
260
 
    session->status_var.com_other++;
 
234
    status_var_increment(session->status_var.com_other);
261
235
    session->my_ok();                           // Tell client we are alive
262
236
    break;
263
237
  case COM_SLEEP:
270
244
 
271
245
  /* If commit fails, we should be able to reset the OK status. */
272
246
  session->main_da.can_overwrite_status= true;
273
 
  TransactionServices &transaction_services= TransactionServices::singleton();
274
 
  transaction_services.autocommitOrRollback(*session, session->is_error());
 
247
  ha_autocommit_or_rollback(session, session->is_error());
275
248
  session->main_da.can_overwrite_status= false;
276
249
 
277
250
  session->transaction.stmt.reset();
283
256
    if (! session->main_da.is_set())
284
257
      session->send_kill_message();
285
258
  }
286
 
  if (session->getKilled() == Session::KILL_QUERY || session->getKilled() == Session::KILL_BAD_DATA)
 
259
  if (session->killed == Session::KILL_QUERY || session->killed == Session::KILL_BAD_DATA)
287
260
  {
288
 
    session->setKilled(Session::NOT_KILLED);
289
 
    session->setAbort(false);
 
261
    session->killed= Session::NOT_KILLED;
 
262
    session->mysys_var->abort= 0;
290
263
  }
291
264
 
292
265
  /* Can not be true, but do not take chances in production. */
296
269
  {
297
270
  case Diagnostics_area::DA_ERROR:
298
271
    /* The query failed, send error to log and abort bootstrap. */
299
 
    session->getClient()->sendError(session->main_da.sql_errno(),
300
 
                               session->main_da.message());
 
272
    session->protocol->sendError(session->main_da.sql_errno(),
 
273
                                 session->main_da.message());
301
274
    break;
302
275
 
303
276
  case Diagnostics_area::DA_EOF:
304
 
    session->getClient()->sendEOF();
 
277
    session->protocol->sendEOF();
305
278
    break;
306
279
 
307
280
  case Diagnostics_area::DA_OK:
308
 
    session->getClient()->sendOK();
 
281
    session->protocol->sendOK();
309
282
    break;
310
283
 
311
284
  case Diagnostics_area::DA_DISABLED:
313
286
 
314
287
  case Diagnostics_area::DA_EMPTY:
315
288
  default:
316
 
    session->getClient()->sendOK();
 
289
    session->protocol->sendOK();
317
290
    break;
318
291
  }
319
292
 
323
296
  /* Free tables */
324
297
  session->close_thread_tables();
325
298
 
326
 
  plugin::Logging::postDo(session);
327
 
  if (unlikely(plugin::EventObserver::afterStatement(*session)))
328
 
  {
329
 
    // We should do something about an error...
330
 
  }
 
299
  logging_post_do(session);
331
300
 
332
301
  /* Store temp state for processlist */
333
302
  session->set_proc_info("cleaning up");
334
 
  session->command= COM_SLEEP;
335
 
  session->resetQueryString();
 
303
  session->command=COM_SLEEP;
 
304
  memset(session->process_list_info, 0, PROCESS_LIST_WIDTH);
 
305
  session->query=0;
 
306
  session->query_length=0;
336
307
 
337
308
  session->set_proc_info(NULL);
338
 
  session->mem_root->free_root(MYF(memory::KEEP_PREALLOC));
339
 
 
340
 
  if (DRIZZLE_QUERY_DONE_ENABLED() || DRIZZLE_COMMAND_DONE_ENABLED())
341
 
  {
342
 
    if (command == COM_QUERY)
343
 
    {
344
 
      DRIZZLE_QUERY_DONE(session->is_error());
345
 
    }
346
 
    DRIZZLE_COMMAND_DONE(session->is_error());
347
 
  }
348
 
 
349
 
  return error;
 
309
  session->packet.shrink(session->variables.net_buffer_length); // Reclaim some memory
 
310
  free_root(session->mem_root,MYF(MY_KEEP_PREALLOC));
 
311
  return(error);
350
312
}
351
313
 
352
314
 
375
337
    1                 out of memory or SHOW commands are not allowed
376
338
                      in this version of the server.
377
339
*/
378
 
static bool _schema_select(Session *session, Select_Lex *sel,
379
 
                           const string& schema_table_name)
380
 
{
381
 
  LEX_STRING db, table;
382
 
  bitset<NUM_OF_TABLE_OPTIONS> table_options;
383
 
  /*
384
 
     We have to make non const db_name & table_name
385
 
     because of lower_case_table_names
386
 
  */
387
 
  session->make_lex_string(&db, "data_dictionary", sizeof("data_dictionary"), false);
388
 
  session->make_lex_string(&table, schema_table_name, false);
389
 
 
390
 
  if (! sel->add_table_to_list(session, new Table_ident(db, table),
391
 
                               NULL, table_options, TL_READ))
392
 
  {
393
 
    return true;
394
 
  }
395
 
  return false;
396
 
}
397
 
 
398
 
int prepare_new_schema_table(Session *session, LEX *lex,
399
 
                             const string& schema_table_name)
 
340
 
 
341
int prepare_schema_table(Session *session, LEX *lex, Table_ident *table_ident,
 
342
                         const string& schema_table_name)
400
343
{
401
344
  Select_Lex *schema_select_lex= NULL;
402
345
 
 
346
 
 
347
  if (schema_table_name.compare("TABLES") == 0 ||
 
348
      schema_table_name.compare("TABLE_NAMES") == 0)
 
349
  {
 
350
    LEX_STRING db;
 
351
    size_t dummy;
 
352
    if (lex->select_lex.db == NULL &&
 
353
        lex->copy_db_to(&lex->select_lex.db, &dummy))
 
354
    {
 
355
      return (1);
 
356
    }
 
357
    schema_select_lex= new Select_Lex();
 
358
    db.str= schema_select_lex->db= lex->select_lex.db;
 
359
    schema_select_lex->table_list.first= NULL;
 
360
    db.length= strlen(db.str);
 
361
 
 
362
    if (check_db_name(&db))
 
363
    {
 
364
      my_error(ER_WRONG_DB_NAME, MYF(0), db.str);
 
365
      return (1);
 
366
    }
 
367
  }
 
368
  else if (schema_table_name.compare("COLUMNS") == 0 ||
 
369
           schema_table_name.compare("STATISTICS") == 0)
 
370
  {
 
371
    assert(table_ident);
 
372
    TableList **query_tables_last= lex->query_tables_last;
 
373
    schema_select_lex= new Select_Lex();
 
374
    /* 'parent_lex' is used in init_query() so it must be before it. */
 
375
    schema_select_lex->parent_lex= lex;
 
376
    schema_select_lex->init_query();
 
377
    if (! schema_select_lex->add_table_to_list(session, table_ident, 0, 0, TL_READ))
 
378
    {
 
379
      return (1);
 
380
    }
 
381
    lex->query_tables_last= query_tables_last;
 
382
  }
 
383
 
403
384
  Select_Lex *select_lex= lex->current_select;
404
385
  assert(select_lex);
405
 
  if (_schema_select(session, select_lex, schema_table_name))
 
386
  if (make_schema_select(session, select_lex, schema_table_name))
406
387
  {
407
388
    return(1);
408
389
  }
443
424
    true        Error
444
425
*/
445
426
 
446
 
static int execute_command(Session *session)
 
427
static int
 
428
mysql_execute_command(Session *session)
447
429
{
448
 
  bool res= false;
449
 
 
 
430
  int res= false;
 
431
  bool comm_not_executed= false;
 
432
  bool need_start_waiting= false; // have protection against global read lock
 
433
  LEX  *lex= session->lex;
450
434
  /* first Select_Lex (have special meaning for many of non-SELECTcommands) */
451
 
  Select_Lex *select_lex= &session->getLex()->select_lex;
452
 
 
 
435
  Select_Lex *select_lex= &lex->select_lex;
 
436
  /* first table of first Select_Lex */
 
437
  TableList *first_table= (TableList*) select_lex->table_list.first;
453
438
  /* list of all tables in query */
454
439
  TableList *all_tables;
 
440
  /* most outer Select_Lex_Unit of query */
 
441
  Select_Lex_Unit *unit= &lex->unit;
 
442
  /* A peek into the query string */
 
443
  size_t proc_info_len= session->query_length > PROCESS_LIST_WIDTH ?
 
444
                        PROCESS_LIST_WIDTH : session->query_length;
 
445
 
 
446
  memcpy(session->process_list_info, session->query, proc_info_len);
 
447
  session->process_list_info[proc_info_len]= '\0';
455
448
 
456
449
  /*
457
450
    In many cases first table of main Select_Lex have special meaning =>
468
461
    assert(first_table == all_tables);
469
462
    assert(first_table == all_tables && first_table != 0);
470
463
  */
471
 
  session->getLex()->first_lists_tables_same();
472
 
 
 
464
  lex->first_lists_tables_same();
473
465
  /* should be assigned after making first tables same */
474
 
  all_tables= session->getLex()->query_tables;
475
 
 
 
466
  all_tables= lex->query_tables;
476
467
  /* set context for commands which do not use setup_tables */
477
 
  select_lex->context.resolve_in_table_list_only((TableList*)select_lex->table_list.first);
 
468
  select_lex->
 
469
    context.resolve_in_table_list_only((TableList*)select_lex->
 
470
                                       table_list.first);
478
471
 
479
472
  /*
480
473
    Reset warning count for each query that uses tables
483
476
    variables, but for now this is probably good enough.
484
477
    Don't reset warnings when executing a stored routine.
485
478
  */
486
 
  if (all_tables || ! session->getLex()->is_single_level_stmt())
487
 
  {
 
479
  if (all_tables || !lex->is_single_level_stmt())
488
480
    drizzle_reset_errors(session, 0);
489
 
  }
490
 
 
491
 
  assert(session->transaction.stmt.hasModifiedNonTransData() == false);
492
 
 
493
 
  if (! (session->server_status & SERVER_STATUS_AUTOCOMMIT)
494
 
      && ! session->inTransaction()
495
 
      && session->getLex()->statement->isTransactional())
496
 
  {
497
 
    if (session->startTransaction() == false)
498
 
    {
499
 
      my_error(drizzled::ER_UNKNOWN_ERROR, MYF(0));
500
 
      return true;
501
 
    }
502
 
  }
503
 
 
504
 
  /* now we are ready to execute the statement */
505
 
  res= session->getLex()->statement->execute();
 
481
 
 
482
  status_var_increment(session->status_var.com_stat[lex->sql_command]);
 
483
 
 
484
  assert(session->transaction.stmt.modified_non_trans_table == false);
 
485
 
 
486
 
 
487
  switch (lex->sql_command) {
 
488
  case SQLCOM_CREATE_TABLE:
 
489
  {
 
490
    /* If CREATE TABLE of non-temporary table, do implicit commit */
 
491
    if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
492
    {
 
493
      if (! session->endActiveTransaction())
 
494
      {
 
495
        res= -1;
 
496
        break;
 
497
      }
 
498
    }
 
499
    assert(first_table == all_tables && first_table != 0);
 
500
    bool link_to_local;
 
501
    // Skip first table, which is the table we are creating
 
502
    TableList *create_table= lex->unlink_first_table(&link_to_local);
 
503
    TableList *select_tables= lex->query_tables;
 
504
    /*
 
505
      Code below (especially in mysql_create_table() and select_create
 
506
      methods) may modify HA_CREATE_INFO structure in LEX, so we have to
 
507
      use a copy of this structure to make execution prepared statement-
 
508
      safe. A shallow copy is enough as this code won't modify any memory
 
509
      referenced from this structure.
 
510
    */
 
511
    HA_CREATE_INFO create_info(lex->create_info);
 
512
    /*
 
513
      We need to copy alter_info for the same reasons of re-execution
 
514
      safety, only in case of Alter_info we have to do (almost) a deep
 
515
      copy.
 
516
    */
 
517
    Alter_info alter_info(lex->alter_info, session->mem_root);
 
518
 
 
519
    if (session->is_fatal_error)
 
520
    {
 
521
      /* If out of memory when creating a copy of alter_info. */
 
522
      res= 1;
 
523
      goto end_with_restore_list;
 
524
    }
 
525
 
 
526
    if ((res= create_table_precheck(session, select_tables, create_table)))
 
527
      goto end_with_restore_list;
 
528
 
 
529
    /* Might have been updated in create_table_precheck */
 
530
    create_info.alias= create_table->alias;
 
531
 
 
532
#ifdef HAVE_READLINK
 
533
    /* Fix names if symlinked tables */
 
534
    if (append_file_to_dir(session, &create_info.data_file_name,
 
535
                           create_table->table_name) ||
 
536
        append_file_to_dir(session, &create_info.index_file_name,
 
537
                           create_table->table_name))
 
538
      goto end_with_restore_list;
 
539
#endif
 
540
    /*
 
541
      The create-select command will open and read-lock the select table
 
542
      and then create, open and write-lock the new table. If a global
 
543
      read lock steps in, we get a deadlock. The write lock waits for
 
544
      the global read lock, while the global read lock waits for the
 
545
      select table to be closed. So we wait until the global readlock is
 
546
      gone before starting both steps. Note that
 
547
      wait_if_global_read_lock() sets a protection against a new global
 
548
      read lock when it succeeds. This needs to be released by
 
549
      start_waiting_global_read_lock(). We protect the normal CREATE
 
550
      TABLE in the same way. That way we avoid that a new table is
 
551
      created during a gobal read lock.
 
552
    */
 
553
    if (!(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
 
554
    {
 
555
      res= 1;
 
556
      goto end_with_restore_list;
 
557
    }
 
558
    if (select_lex->item_list.elements)         // With select
 
559
    {
 
560
      select_result *result;
 
561
 
 
562
      select_lex->options|= SELECT_NO_UNLOCK;
 
563
      unit->set_limit(select_lex);
 
564
 
 
565
      if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
566
      {
 
567
        lex->link_first_table_back(create_table, link_to_local);
 
568
        create_table->create= true;
 
569
      }
 
570
 
 
571
      if (!(res= session->openTablesLock(lex->query_tables)))
 
572
      {
 
573
        /*
 
574
          Is table which we are changing used somewhere in other parts
 
575
          of query
 
576
        */
 
577
        if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
578
        {
 
579
          TableList *duplicate;
 
580
          create_table= lex->unlink_first_table(&link_to_local);
 
581
          if ((duplicate= unique_table(session, create_table, select_tables, 0)))
 
582
          {
 
583
            my_error(ER_UPDATE_TABLE_USED, MYF(0), create_table->alias);
 
584
            res= 1;
 
585
            goto end_with_restore_list;
 
586
          }
 
587
        }
 
588
 
 
589
        /*
 
590
          select_create is currently not re-execution friendly and
 
591
          needs to be created for every execution of a PS/SP.
 
592
        */
 
593
        if ((result= new select_create(create_table,
 
594
                                       &create_info,
 
595
                                       lex->create_table_proto,
 
596
                                       &alter_info,
 
597
                                       select_lex->item_list,
 
598
                                       lex->duplicates,
 
599
                                       lex->ignore,
 
600
                                       select_tables)))
 
601
        {
 
602
          /*
 
603
            CREATE from SELECT give its Select_Lex for SELECT,
 
604
            and item_list belong to SELECT
 
605
          */
 
606
          res= handle_select(session, lex, result, 0);
 
607
          delete result;
 
608
        }
 
609
      }
 
610
      else if (!(create_info.options & HA_LEX_CREATE_TMP_TABLE))
 
611
        create_table= lex->unlink_first_table(&link_to_local);
 
612
 
 
613
    }
 
614
    else
 
615
    {
 
616
      /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */
 
617
      if (create_info.options & HA_LEX_CREATE_TMP_TABLE)
 
618
        session->options|= OPTION_KEEP_LOG;
 
619
      /* regular create */
 
620
      if (create_info.options & HA_LEX_CREATE_TABLE_LIKE)
 
621
        res= mysql_create_like_table(session, create_table, select_tables,
 
622
                                     &create_info);
 
623
      else
 
624
      {
 
625
        res= mysql_create_table(session, create_table->db,
 
626
                                create_table->table_name, &create_info,
 
627
                                lex->create_table_proto,
 
628
                                &alter_info, 0, 0);
 
629
      }
 
630
      if (!res)
 
631
        session->my_ok();
 
632
    }
 
633
 
 
634
    /* put tables back for PS rexecuting */
 
635
end_with_restore_list:
 
636
    lex->link_first_table_back(create_table, link_to_local);
 
637
    break;
 
638
  }
 
639
  case SQLCOM_CREATE_INDEX:
 
640
    /* Fall through */
 
641
  case SQLCOM_DROP_INDEX:
 
642
  /*
 
643
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
 
644
    TABLE with proper arguments.
 
645
 
 
646
    In the future ALTER TABLE will notice that the request is to
 
647
    only add indexes and create these one by one for the existing
 
648
    table without having to do a full rebuild.
 
649
  */
 
650
  {
 
651
    /* Prepare stack copies to be re-execution safe */
 
652
    HA_CREATE_INFO create_info;
 
653
    Alter_info alter_info(lex->alter_info, session->mem_root);
 
654
 
 
655
    if (session->is_fatal_error) /* out of memory creating a copy of alter_info */
 
656
      goto error;
 
657
 
 
658
    assert(first_table == all_tables && first_table != 0);
 
659
    if (! session->endActiveTransaction())
 
660
      goto error;
 
661
 
 
662
    memset(&create_info, 0, sizeof(create_info));
 
663
    create_info.db_type= 0;
 
664
    create_info.row_type= ROW_TYPE_NOT_USED;
 
665
    create_info.default_table_charset= get_default_db_collation(session->db);
 
666
 
 
667
    res= mysql_alter_table(session, first_table->db, first_table->table_name,
 
668
                           &create_info, lex->create_table_proto, first_table,
 
669
                           &alter_info,
 
670
                           0, (order_st*) 0, 0);
 
671
    break;
 
672
  }
 
673
  case SQLCOM_ALTER_TABLE:
 
674
    assert(first_table == all_tables && first_table != 0);
 
675
    {
 
676
      /*
 
677
        Code in mysql_alter_table() may modify its HA_CREATE_INFO argument,
 
678
        so we have to use a copy of this structure to make execution
 
679
        prepared statement- safe. A shallow copy is enough as no memory
 
680
        referenced from this structure will be modified.
 
681
      */
 
682
      HA_CREATE_INFO create_info(lex->create_info);
 
683
      Alter_info alter_info(lex->alter_info, session->mem_root);
 
684
 
 
685
      if (session->is_fatal_error) /* out of memory creating a copy of alter_info */
 
686
      {
 
687
        goto error;
 
688
      }
 
689
 
 
690
      /* Must be set in the parser */
 
691
      assert(select_lex->db);
 
692
 
 
693
      { // Rename of table
 
694
          TableList tmp_table;
 
695
          memset(&tmp_table, 0, sizeof(tmp_table));
 
696
          tmp_table.table_name= lex->name.str;
 
697
          tmp_table.db=select_lex->db;
 
698
      }
 
699
 
 
700
      /* Don't yet allow changing of symlinks with ALTER TABLE */
 
701
      if (create_info.data_file_name)
 
702
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, 0,
 
703
                     "DATA DIRECTORY option ignored");
 
704
      if (create_info.index_file_name)
 
705
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, 0,
 
706
                     "INDEX DIRECTORY option ignored");
 
707
      create_info.data_file_name= create_info.index_file_name= NULL;
 
708
      /* ALTER TABLE ends previous transaction */
 
709
      if (! session->endActiveTransaction())
 
710
        goto error;
 
711
 
 
712
      if (!(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
 
713
      {
 
714
        res= 1;
 
715
        break;
 
716
      }
 
717
 
 
718
      res= mysql_alter_table(session, select_lex->db, lex->name.str,
 
719
                             &create_info,
 
720
                             lex->create_table_proto,
 
721
                             first_table,
 
722
                             &alter_info,
 
723
                             select_lex->order_list.elements,
 
724
                             (order_st *) select_lex->order_list.first,
 
725
                             lex->ignore);
 
726
      break;
 
727
    }
 
728
  case SQLCOM_RENAME_TABLE:
 
729
  {
 
730
    assert(first_table == all_tables && first_table != 0);
 
731
    TableList *table;
 
732
    for (table= first_table; table; table= table->next_local->next_local)
 
733
    {
 
734
      TableList old_list, new_list;
 
735
      /*
 
736
        we do not need initialize old_list and new_list because we will
 
737
        come table[0] and table->next[0] there
 
738
      */
 
739
      old_list= table[0];
 
740
      new_list= table->next_local[0];
 
741
    }
 
742
 
 
743
    if (! session->endActiveTransaction() || drizzle_rename_tables(session, first_table))
 
744
    {
 
745
      goto error;
 
746
    }
 
747
    break;
 
748
  }
 
749
  case SQLCOM_CHECK:
 
750
  {
 
751
    assert(first_table == all_tables && first_table != 0);
 
752
    res = mysql_check_table(session, first_table, &lex->check_opt);
 
753
    select_lex->table_list.first= (unsigned char*) first_table;
 
754
    lex->query_tables=all_tables;
 
755
    break;
 
756
  }
 
757
  case SQLCOM_ANALYZE:
 
758
  {
 
759
    assert(first_table == all_tables && first_table != 0);
 
760
    res= mysql_analyze_table(session, first_table, &lex->check_opt);
 
761
    /* ! we write after unlocking the table */
 
762
    write_bin_log(session, true, session->query, session->query_length);
 
763
    select_lex->table_list.first= (unsigned char*) first_table;
 
764
    lex->query_tables=all_tables;
 
765
    break;
 
766
  }
 
767
 
 
768
  case SQLCOM_OPTIMIZE:
 
769
  {
 
770
    assert(first_table == all_tables && first_table != 0);
 
771
    res= mysql_optimize_table(session, first_table, &lex->check_opt);
 
772
    /* ! we write after unlocking the table */
 
773
    write_bin_log(session, true, session->query, session->query_length);
 
774
    select_lex->table_list.first= (unsigned char*) first_table;
 
775
    lex->query_tables=all_tables;
 
776
    break;
 
777
  }
 
778
  case SQLCOM_UPDATE:
 
779
    assert(first_table == all_tables && first_table != 0);
 
780
    if ((res= update_precheck(session, all_tables)))
 
781
      break;
 
782
    assert(select_lex->offset_limit == 0);
 
783
    unit->set_limit(select_lex);
 
784
    res= mysql_update(session, all_tables,
 
785
                      select_lex->item_list,
 
786
                      lex->value_list,
 
787
                      select_lex->where,
 
788
                      select_lex->order_list.elements,
 
789
                      (order_st *) select_lex->order_list.first,
 
790
                      unit->select_limit_cnt,
 
791
                      lex->duplicates, lex->ignore);
 
792
    break;
 
793
  case SQLCOM_REPLACE:
 
794
  case SQLCOM_INSERT:
 
795
  {
 
796
    assert(first_table == all_tables && first_table != 0);
 
797
    if ((res= insert_precheck(session, all_tables)))
 
798
      break;
 
799
 
 
800
    if (!(need_start_waiting= !wait_if_global_read_lock(session, 0, 1)))
 
801
    {
 
802
      res= 1;
 
803
      break;
 
804
    }
 
805
 
 
806
    res= mysql_insert(session, all_tables, lex->field_list, lex->many_values,
 
807
                      lex->update_list, lex->value_list,
 
808
                      lex->duplicates, lex->ignore);
 
809
 
 
810
    break;
 
811
  }
 
812
  case SQLCOM_REPLACE_SELECT:
 
813
  case SQLCOM_INSERT_SELECT:
 
814
  {
 
815
    select_result *sel_result;
 
816
    assert(first_table == all_tables && first_table != 0);
 
817
    if ((res= insert_precheck(session, all_tables)))
 
818
      break;
 
819
 
 
820
    /* Don't unlock tables until command is written to binary log */
 
821
    select_lex->options|= SELECT_NO_UNLOCK;
 
822
 
 
823
    unit->set_limit(select_lex);
 
824
 
 
825
    if (! (need_start_waiting= ! wait_if_global_read_lock(session, 0, 1)))
 
826
    {
 
827
      res= 1;
 
828
      break;
 
829
    }
 
830
 
 
831
    if (!(res= session->openTablesLock(all_tables)))
 
832
    {
 
833
      /* Skip first table, which is the table we are inserting in */
 
834
      TableList *second_table= first_table->next_local;
 
835
      select_lex->table_list.first= (unsigned char*) second_table;
 
836
      select_lex->context.table_list=
 
837
        select_lex->context.first_name_resolution_table= second_table;
 
838
      res= mysql_insert_select_prepare(session);
 
839
      if (!res && (sel_result= new select_insert(first_table,
 
840
                                                 first_table->table,
 
841
                                                 &lex->field_list,
 
842
                                                 &lex->update_list,
 
843
                                                 &lex->value_list,
 
844
                                                 lex->duplicates,
 
845
                                                 lex->ignore)))
 
846
      {
 
847
        res= handle_select(session, lex, sel_result, OPTION_SETUP_TABLES_DONE);
 
848
        /*
 
849
          Invalidate the table in the query cache if something changed
 
850
          after unlocking when changes become visible.
 
851
          TODO: this is workaround. right way will be move invalidating in
 
852
          the unlock procedure.
 
853
        */
 
854
        if (first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
 
855
            session->lock)
 
856
        {
 
857
          /* INSERT ... SELECT should invalidate only the very first table */
 
858
          TableList *save_table= first_table->next_local;
 
859
          first_table->next_local= 0;
 
860
          first_table->next_local= save_table;
 
861
        }
 
862
        delete sel_result;
 
863
      }
 
864
      /* revert changes for SP */
 
865
      select_lex->table_list.first= (unsigned char*) first_table;
 
866
    }
 
867
 
 
868
    break;
 
869
  }
 
870
  case SQLCOM_TRUNCATE:
 
871
    if (! session->endActiveTransaction())
 
872
    {
 
873
      res= -1;
 
874
      break;
 
875
    }
 
876
    assert(first_table == all_tables && first_table != 0);
 
877
    /*
 
878
      Don't allow this within a transaction because we want to use
 
879
      re-generate table
 
880
    */
 
881
    if (session->inTransaction())
 
882
    {
 
883
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
884
      goto error;
 
885
    }
 
886
 
 
887
    res= mysql_truncate(session, first_table, 0);
 
888
 
 
889
    break;
 
890
  case SQLCOM_DROP_TABLE:
 
891
  {
 
892
    assert(first_table == all_tables && first_table != 0);
 
893
    if (!lex->drop_temporary)
 
894
    {
 
895
      if (! session->endActiveTransaction())
 
896
        goto error;
 
897
    }
 
898
    else
 
899
    {
 
900
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
 
901
      session->options|= OPTION_KEEP_LOG;
 
902
    }
 
903
    /* DDL and binlog write order protected by LOCK_open */
 
904
    res= mysql_rm_table(session, first_table, lex->drop_if_exists, lex->drop_temporary);
 
905
  }
 
906
  break;
 
907
  case SQLCOM_CHANGE_DB:
 
908
  {
 
909
    LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) };
 
910
 
 
911
    if (!mysql_change_db(session, &db_str, false))
 
912
      session->my_ok();
 
913
 
 
914
    break;
 
915
  }
 
916
  case SQLCOM_SET_OPTION:
 
917
  {
 
918
    List<set_var_base> *lex_var_list= &lex->var_list;
 
919
 
 
920
    if (session->openTablesLock(all_tables))
 
921
      goto error;
 
922
    if (!(res= sql_set_variables(session, lex_var_list)))
 
923
    {
 
924
      session->my_ok();
 
925
    }
 
926
    else
 
927
    {
 
928
      /*
 
929
        We encountered some sort of error, but no message was sent.
 
930
        Send something semi-generic here since we don't know which
 
931
        assignment in the list caused the error.
 
932
      */
 
933
      if (!session->is_error())
 
934
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
 
935
      goto error;
 
936
    }
 
937
 
 
938
    break;
 
939
  }
 
940
  case SQLCOM_CREATE_DB:
 
941
  {
 
942
    /*
 
943
      As mysql_create_db() may modify HA_CREATE_INFO structure passed to
 
944
      it, we need to use a copy of LEX::create_info to make execution
 
945
      prepared statement- safe.
 
946
    */
 
947
    HA_CREATE_INFO create_info(lex->create_info);
 
948
    if (! session->endActiveTransaction())
 
949
    {
 
950
      res= -1;
 
951
      break;
 
952
    }
 
953
    char *alias;
 
954
    if (!(alias=session->strmake(lex->name.str, lex->name.length)) ||
 
955
        check_db_name(&lex->name))
 
956
    {
 
957
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
 
958
      break;
 
959
    }
 
960
    res= mysql_create_db(session,(lex->name.str), &create_info);
 
961
    break;
 
962
  }
 
963
  case SQLCOM_DROP_DB:
 
964
  {
 
965
    if (! session->endActiveTransaction())
 
966
    {
 
967
      res= -1;
 
968
      break;
 
969
    }
 
970
    if (check_db_name(&lex->name))
 
971
    {
 
972
      my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str);
 
973
      break;
 
974
    }
 
975
    if (session->inTransaction())
 
976
    {
 
977
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
978
      goto error;
 
979
    }
 
980
    res= mysql_rm_db(session, lex->name.str, lex->drop_if_exists);
 
981
    break;
 
982
  }
 
983
  case SQLCOM_ALTER_DB:
 
984
  {
 
985
    LEX_STRING *db= &lex->name;
 
986
    HA_CREATE_INFO create_info(lex->create_info);
 
987
    if (check_db_name(db))
 
988
    {
 
989
      my_error(ER_WRONG_DB_NAME, MYF(0), db->str);
 
990
      break;
 
991
    }
 
992
    if (session->inTransaction())
 
993
    {
 
994
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
 
995
      goto error;
 
996
    }
 
997
    res= mysql_alter_db(session, db->str, &create_info);
 
998
    break;
 
999
  }
 
1000
  case SQLCOM_FLUSH:
 
1001
  {
 
1002
    /*
 
1003
      reload_cache() will tell us if we are allowed to write to the
 
1004
      binlog or not.
 
1005
    */
 
1006
    if (!reload_cache(session, lex->type, first_table))
 
1007
    {
 
1008
      /*
 
1009
        We WANT to write and we CAN write.
 
1010
        ! we write after unlocking the table.
 
1011
      */
 
1012
      /*
 
1013
        Presumably, RESET and binlog writing doesn't require synchronization
 
1014
      */
 
1015
      write_bin_log(session, false, session->query, session->query_length);
 
1016
      session->my_ok();
 
1017
    }
 
1018
 
 
1019
    break;
 
1020
  }
 
1021
  case SQLCOM_KILL:
 
1022
  {
 
1023
    Item *it= (Item *)lex->value_list.head();
 
1024
 
 
1025
    if ((!it->fixed && it->fix_fields(lex->session, &it)) || it->check_cols(1))
 
1026
    {
 
1027
      my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY),
 
1028
                 MYF(0));
 
1029
      goto error;
 
1030
    }
 
1031
    sql_kill(session, (ulong)it->val_int(), lex->type & ONLY_KILL_QUERY);
 
1032
    break;
 
1033
  }
 
1034
  case SQLCOM_BEGIN:
 
1035
    if (session->transaction.xid_state.xa_state != XA_NOTR)
 
1036
    {
 
1037
      my_error(ER_XAER_RMFAIL, MYF(0),
 
1038
               xa_state_names[session->transaction.xid_state.xa_state]);
 
1039
      break;
 
1040
    }
 
1041
    /*
 
1042
      Breakpoints for backup testing.
 
1043
    */
 
1044
    if (! session->startTransaction())
 
1045
      goto error;
 
1046
    session->my_ok();
 
1047
    break;
 
1048
  case SQLCOM_RELEASE_SAVEPOINT:
 
1049
  {
 
1050
    SAVEPOINT *sv;
 
1051
    for (sv=session->transaction.savepoints; sv; sv=sv->prev)
 
1052
    {
 
1053
      if (my_strnncoll(system_charset_info,
 
1054
                       (unsigned char *)lex->ident.str, lex->ident.length,
 
1055
                       (unsigned char *)sv->name, sv->length) == 0)
 
1056
        break;
 
1057
    }
 
1058
    if (sv)
 
1059
    {
 
1060
      if (ha_release_savepoint(session, sv))
 
1061
        res= true; // cannot happen
 
1062
      else
 
1063
        session->my_ok();
 
1064
      session->transaction.savepoints=sv->prev;
 
1065
    }
 
1066
    else
 
1067
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
 
1068
    break;
 
1069
  }
 
1070
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
 
1071
  {
 
1072
    SAVEPOINT *sv;
 
1073
    for (sv=session->transaction.savepoints; sv; sv=sv->prev)
 
1074
    {
 
1075
      if (my_strnncoll(system_charset_info,
 
1076
                       (unsigned char *)lex->ident.str, lex->ident.length,
 
1077
                       (unsigned char *)sv->name, sv->length) == 0)
 
1078
        break;
 
1079
    }
 
1080
    if (sv)
 
1081
    {
 
1082
      if (ha_rollback_to_savepoint(session, sv))
 
1083
        res= true; // cannot happen
 
1084
      else
 
1085
      {
 
1086
        if ((session->options & OPTION_KEEP_LOG) || session->transaction.all.modified_non_trans_table)
 
1087
          push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
1088
                       ER_WARNING_NOT_COMPLETE_ROLLBACK,
 
1089
                       ER(ER_WARNING_NOT_COMPLETE_ROLLBACK));
 
1090
        session->my_ok();
 
1091
      }
 
1092
      session->transaction.savepoints=sv;
 
1093
    }
 
1094
    else
 
1095
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SAVEPOINT", lex->ident.str);
 
1096
    break;
 
1097
  }
 
1098
  case SQLCOM_SAVEPOINT:
 
1099
    if (!(session->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)))
 
1100
      session->my_ok();
 
1101
    else
 
1102
    {
 
1103
      SAVEPOINT **sv, *newsv;
 
1104
      for (sv=&session->transaction.savepoints; *sv; sv=&(*sv)->prev)
 
1105
      {
 
1106
        if (my_strnncoll(system_charset_info,
 
1107
                         (unsigned char *)lex->ident.str, lex->ident.length,
 
1108
                         (unsigned char *)(*sv)->name, (*sv)->length) == 0)
 
1109
          break;
 
1110
      }
 
1111
      if (*sv) /* old savepoint of the same name exists */
 
1112
      {
 
1113
        newsv=*sv;
 
1114
        ha_release_savepoint(session, *sv); // it cannot fail
 
1115
        *sv=(*sv)->prev;
 
1116
      }
 
1117
      else if ((newsv=(SAVEPOINT *) alloc_root(&session->transaction.mem_root,
 
1118
                                               savepoint_alloc_size)) == 0)
 
1119
      {
 
1120
        my_error(ER_OUT_OF_RESOURCES, MYF(0));
 
1121
        break;
 
1122
      }
 
1123
      newsv->name=strmake_root(&session->transaction.mem_root,
 
1124
                               lex->ident.str, lex->ident.length);
 
1125
      newsv->length=lex->ident.length;
 
1126
      /*
 
1127
        if we'll get an error here, don't add new savepoint to the list.
 
1128
        we'll lose a little bit of memory in transaction mem_root, but it'll
 
1129
        be free'd when transaction ends anyway
 
1130
      */
 
1131
      if (ha_savepoint(session, newsv))
 
1132
        res= true;
 
1133
      else
 
1134
      {
 
1135
        newsv->prev=session->transaction.savepoints;
 
1136
        session->transaction.savepoints=newsv;
 
1137
        session->my_ok();
 
1138
      }
 
1139
    }
 
1140
    break;
 
1141
  default:
 
1142
    /*
 
1143
     * This occurs now because we have extracted some commands in
 
1144
     * to their own classes and thus there is no matching case
 
1145
     * label in this switch statement for those commands. Pretty soon
 
1146
     * this entire switch statement will be gone along with this 
 
1147
     * comment...
 
1148
     */
 
1149
    comm_not_executed= true;
 
1150
    break;
 
1151
  }
 
1152
  /*
 
1153
   * The following conditional statement is only temporary until
 
1154
   * the mongo switch statement that occurs above has been
 
1155
   * fully removed. Once that switch statement is gone, every
 
1156
   * command will have its own class and we won't need this
 
1157
   * check.
 
1158
   */
 
1159
  if (comm_not_executed)
 
1160
  {
 
1161
    /* now we are ready to execute the statement */
 
1162
    res= lex->statement->execute();
 
1163
  }
 
1164
 
506
1165
  session->set_proc_info("query end");
 
1166
 
507
1167
  /*
508
1168
    The return value for ROW_COUNT() is "implementation dependent" if the
509
1169
    statement is not DELETE, INSERT or UPDATE, but -1 is what JDBC and ODBC
510
1170
    wants. We also keep the last value in case of SQLCOM_CALL or
511
1171
    SQLCOM_EXECUTE.
512
1172
  */
513
 
  if (! (sql_command_flags[session->getLex()->sql_command].test(CF_BIT_HAS_ROW_COUNT)))
514
 
  {
 
1173
  if (!(sql_command_flags[lex->sql_command].test(CF_BIT_HAS_ROW_COUNT)))
515
1174
    session->row_count_func= -1;
 
1175
 
 
1176
  goto finish;
 
1177
 
 
1178
error:
 
1179
  res= true;
 
1180
 
 
1181
finish:
 
1182
  if (need_start_waiting)
 
1183
  {
 
1184
    /*
 
1185
      Release the protection against the global read lock and wake
 
1186
      everyone, who might want to set a global read lock.
 
1187
    */
 
1188
    start_waiting_global_read_lock(session);
516
1189
  }
517
 
 
518
 
  return (res || session->is_error());
 
1190
  return(res || session->is_error());
519
1191
}
 
1192
 
520
1193
bool execute_sqlcom_select(Session *session, TableList *all_tables)
521
1194
{
522
 
  LEX   *lex= session->getLex();
 
1195
  LEX   *lex= session->lex;
523
1196
  select_result *result=lex->result;
524
1197
  bool res= false;
525
1198
  /* assign global limit variable if limit is not given */
529
1202
      param->select_limit=
530
1203
        new Item_int((uint64_t) session->variables.select_limit);
531
1204
  }
532
 
 
533
 
  if (all_tables
534
 
      && ! (session->server_status & SERVER_STATUS_AUTOCOMMIT)
535
 
      && ! session->inTransaction()
536
 
      && ! lex->statement->isShow())
537
 
  {
538
 
    if (session->startTransaction() == false)
539
 
    {
540
 
      my_error(drizzled::ER_UNKNOWN_ERROR, MYF(0));
541
 
      return true;
542
 
    }
543
 
  }
544
 
 
545
 
  if (not (res= session->openTablesLock(all_tables)))
 
1205
  if (!(res= session->openTablesLock(all_tables)))
546
1206
  {
547
1207
    if (lex->describe)
548
1208
    {
553
1213
        even if the query itself redirects the output.
554
1214
      */
555
1215
      if (!(result= new select_send()))
556
 
        return true;
 
1216
        return true;                               /* purecov: inspected */
557
1217
      session->send_explain_fields(result);
558
 
      optimizer::ExplainPlan planner;
559
 
      res= planner.explainUnion(session, &session->getLex()->unit, result);
 
1218
      res= mysql_explain_union(session, &session->lex->unit, result);
560
1219
      if (lex->describe & DESCRIBE_EXTENDED)
561
1220
      {
562
1221
        char buff[1024];
563
1222
        String str(buff,(uint32_t) sizeof(buff), system_charset_info);
564
1223
        str.length(0);
565
 
        session->getLex()->unit.print(&str, QT_ORDINARY);
 
1224
        session->lex->unit.print(&str, QT_ORDINARY);
566
1225
        str.append('\0');
567
1226
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
568
1227
                     ER_YES, str.ptr());
571
1230
        result->abort();
572
1231
      else
573
1232
        result->send_eof();
574
 
 
575
1233
      delete result;
576
1234
    }
577
1235
    else
578
1236
    {
579
1237
      if (!result && !(result= new select_send()))
580
 
        return true;
581
 
 
582
 
      /* Init the Query Cache plugin */
583
 
      plugin::QueryCache::prepareResultset(session); 
 
1238
        return true;                               /* purecov: inspected */
584
1239
      res= handle_select(session, lex, result, 0);
585
 
      /* Send the Resultset to the cache */
586
 
      plugin::QueryCache::setResultset(session); 
587
 
 
588
1240
      if (result != lex->result)
589
1241
        delete result;
590
1242
    }
596
1248
#define MY_YACC_INIT 1000                       // Start with big alloc
597
1249
#define MY_YACC_MAX  32000                      // Because of 'short'
598
1250
 
599
 
bool my_yyoverflow(short **yyss, ParserType **yyvs, ulong *yystacksize)
 
1251
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize)
600
1252
{
601
 
  LEX   *lex= current_session->getLex();
 
1253
  LEX   *lex= current_session->lex;
602
1254
  ulong old_info=0;
603
1255
  if ((uint32_t) *yystacksize >= MY_YACC_MAX)
604
1256
    return 1;
621
1273
    memcpy(lex->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
622
1274
  }
623
1275
  *yyss=(short*) lex->yacc_yyss;
624
 
  *yyvs=(ParserType*) lex->yacc_yyvs;
 
1276
  *yyvs=(YYSTYPE*) lex->yacc_yyvs;
625
1277
  return 0;
626
1278
}
627
1279
 
628
1280
 
629
1281
void
630
 
init_select(LEX *lex)
 
1282
mysql_init_select(LEX *lex)
631
1283
{
632
1284
  Select_Lex *select_lex= lex->current_select;
633
1285
  select_lex->init_select();
641
1293
 
642
1294
 
643
1295
bool
644
 
new_select(LEX *lex, bool move_down)
 
1296
mysql_new_select(LEX *lex, bool move_down)
645
1297
{
646
1298
  Select_Lex *select_lex;
647
1299
  Session *session= lex->session;
648
1300
 
649
1301
  if (!(select_lex= new (session->mem_root) Select_Lex()))
650
 
    return true;
651
 
 
 
1302
    return(1);
652
1303
  select_lex->select_number= ++session->select_number;
653
1304
  select_lex->parent_lex= lex; /* Used in init_query. */
654
1305
  select_lex->init_query();
655
1306
  select_lex->init_select();
656
1307
  lex->nest_level++;
657
 
 
658
1308
  if (lex->nest_level > (int) MAX_SELECT_NESTING)
659
1309
  {
660
1310
    my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
661
1311
    return(1);
662
1312
  }
663
 
 
664
1313
  select_lex->nest_level= lex->nest_level;
665
1314
  if (move_down)
666
1315
  {
688
1337
    if (lex->current_select->order_list.first && !lex->current_select->braces)
689
1338
    {
690
1339
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "order_st BY");
691
 
      return true;
 
1340
      return(1);
692
1341
    }
693
 
 
694
1342
    select_lex->include_neighbour(lex->current_select);
695
1343
    Select_Lex_Unit *unit= select_lex->master_unit();
696
 
 
697
 
    if (not unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
698
 
      return true;
699
 
 
 
1344
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->session))
 
1345
      return(1);
700
1346
    select_lex->context.outer_context=
701
1347
                unit->first_select()->context.outer_context;
702
1348
  }
709
1355
    list
710
1356
  */
711
1357
  select_lex->context.resolve_in_select_list= true;
712
 
 
713
 
  return false;
 
1358
  return(0);
714
1359
}
715
1360
 
716
1361
/**
723
1368
  @param var_name               Variable name
724
1369
*/
725
1370
 
726
 
void create_select_for_variable(Session *session, const char *var_name)
 
1371
void create_select_for_variable(const char *var_name)
727
1372
{
 
1373
  Session *session;
728
1374
  LEX *lex;
729
1375
  LEX_STRING tmp, null_lex_string;
730
1376
  Item *var;
731
1377
  char buff[MAX_SYS_VAR_LENGTH*2+4+8];
732
1378
  char *end= buff;
733
1379
 
734
 
  lex= session->getLex();
735
 
  init_select(lex);
 
1380
  session= current_session;
 
1381
  lex= session->lex;
 
1382
  mysql_init_select(lex);
736
1383
  lex->sql_command= SQLCOM_SELECT;
737
1384
  tmp.str= (char*) var_name;
738
1385
  tmp.length=strlen(var_name);
743
1390
  */
744
1391
  if ((var= get_system_var(session, OPT_SESSION, tmp, null_lex_string)))
745
1392
  {
746
 
    end+= snprintf(buff, sizeof(buff), "@@session.%s", var_name);
 
1393
    end+= sprintf(buff, "@@session.%s", var_name);
747
1394
    var->set_name(buff, end-buff, system_charset_info);
748
1395
    session->add_item_to_list(var);
749
1396
  }
 
1397
  return;
750
1398
}
751
1399
 
752
1400
 
756
1404
  @param       session     Current thread
757
1405
  @param       inBuf   Begining of the query text
758
1406
  @param       length  Length of the query text
 
1407
  @param[out]  found_semicolon For multi queries, position of the character of
 
1408
                               the next query in the query text.
759
1409
*/
760
1410
 
761
 
void parse(Session *session, const char *inBuf, uint32_t length)
 
1411
void mysql_parse(Session *session, const char *inBuf, uint32_t length,
 
1412
                 const char ** found_semicolon)
762
1413
{
763
 
  session->getLex()->start(session);
764
 
 
 
1414
  /*
 
1415
    Warning.
 
1416
    The purpose of query_cache_send_result_to_client() is to lookup the
 
1417
    query in the query cache first, to avoid parsing and executing it.
 
1418
    So, the natural implementation would be to:
 
1419
    - first, call query_cache_send_result_to_client,
 
1420
    - second, if caching failed, initialise the lexical and syntactic parser.
 
1421
    The problem is that the query cache depends on a clean initialization
 
1422
    of (among others) lex->safe_to_cache_query and session->server_status,
 
1423
    which are reset respectively in
 
1424
    - lex_start()
 
1425
    - mysql_reset_session_for_next_command()
 
1426
    So, initializing the lexical analyser *before* using the query cache
 
1427
    is required for the cache to work properly.
 
1428
    FIXME: cleanup the dependencies in the code to simplify this.
 
1429
  */
 
1430
  lex_start(session);
765
1431
  session->reset_for_next_command();
766
 
  /* Check if the Query is Cached if and return true if yes
767
 
   * TODO the plugin has to make sure that the query is cacheble
768
 
   * by setting the query_safe_cache param to TRUE
769
 
   */
770
 
  bool res= true;
771
 
  if (plugin::QueryCache::isCached(session))
772
 
  {
773
 
    res= plugin::QueryCache::sendCachedResultset(session);
774
 
  }
775
 
  if (not res)
776
 
  {
777
 
    return;
778
 
  }
779
 
  LEX *lex= session->getLex();
780
 
  Lex_input_stream lip(session, inBuf, length);
781
 
  bool err= parse_sql(session, &lip);
782
 
  if (!err)
783
 
  {
 
1432
 
 
1433
  {
 
1434
    LEX *lex= session->lex;
 
1435
 
 
1436
    Lex_input_stream lip(session, inBuf, length);
 
1437
 
 
1438
    bool err= parse_sql(session, &lip);
 
1439
    *found_semicolon= lip.found_semicolon;
 
1440
 
 
1441
    if (!err)
784
1442
    {
785
 
      if (not session->is_error())
786
1443
      {
787
 
        DRIZZLE_QUERY_EXEC_START(session->getQueryString()->c_str(),
788
 
                                 session->thread_id,
789
 
                                 const_cast<const char *>(session->schema()->c_str()));
790
 
        // Implement Views here --Brian
791
 
        /* Actually execute the query */
792
 
        try 
793
 
        {
794
 
          execute_command(session);
795
 
        }
796
 
        catch (...)
797
 
        {
798
 
          // Just try to catch any random failures that could have come
799
 
          // during execution.
800
 
          DRIZZLE_ABORT;
801
 
        }
802
 
        DRIZZLE_QUERY_EXEC_DONE(0);
 
1444
        if (! session->is_error())
 
1445
        {
 
1446
          /*
 
1447
            Binlog logs a string starting from session->query and having length
 
1448
            session->query_length; so we set session->query_length correctly (to not
 
1449
            log several statements in one event, when we executed only first).
 
1450
            We set it to not see the ';' (otherwise it would get into binlog
 
1451
            and Query_log_event::print() would give ';;' output).
 
1452
            This also helps display only the current query in SHOW
 
1453
            PROCESSLIST.
 
1454
            Note that we don't need LOCK_thread_count to modify query_length.
 
1455
          */
 
1456
          if (*found_semicolon &&
 
1457
              (session->query_length= (ulong)(*found_semicolon - session->query)))
 
1458
            session->query_length--;
 
1459
          /* Actually execute the query */
 
1460
          mysql_execute_command(session);
 
1461
        }
803
1462
      }
804
1463
    }
805
 
  }
806
 
  else
807
 
  {
808
 
    assert(session->is_error());
809
 
  }
810
 
  lex->unit.cleanup();
811
 
  session->set_proc_info("freeing items");
812
 
  session->end_statement();
813
 
  session->cleanup_after_query();
814
 
  session->set_end_timer();
 
1464
    else
 
1465
    {
 
1466
      assert(session->is_error());
 
1467
    }
 
1468
    lex->unit.cleanup();
 
1469
    session->set_proc_info("freeing items");
 
1470
    session->end_statement();
 
1471
    session->cleanup_after_query();
 
1472
  }
 
1473
 
 
1474
  return;
815
1475
}
816
1476
 
817
1477
 
833
1493
                       List<String> *interval_list, const CHARSET_INFO * const cs)
834
1494
{
835
1495
  register CreateField *new_field;
836
 
  LEX  *lex= session->getLex();
837
 
  statement::AlterTable *statement= (statement::AlterTable *)lex->statement;
 
1496
  LEX  *lex= session->lex;
838
1497
 
839
1498
  if (check_identifier_name(field_name, ER_TOO_LONG_IDENT))
840
 
    return true;
 
1499
    return(1);                          /* purecov: inspected */
841
1500
 
842
1501
  if (type_modifier & PRI_KEY_FLAG)
843
1502
  {
846
1505
    key= new Key(Key::PRIMARY, null_lex_str,
847
1506
                      &default_key_create_info,
848
1507
                      0, lex->col_list);
849
 
    statement->alter_info.key_list.push_back(key);
850
 
    lex->col_list.clear();
 
1508
    lex->alter_info.key_list.push_back(key);
 
1509
    lex->col_list.empty();
851
1510
  }
852
1511
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
853
1512
  {
856
1515
    key= new Key(Key::UNIQUE, null_lex_str,
857
1516
                 &default_key_create_info, 0,
858
1517
                 lex->col_list);
859
 
    statement->alter_info.key_list.push_back(key);
860
 
    lex->col_list.clear();
 
1518
    lex->alter_info.key_list.push_back(key);
 
1519
    lex->col_list.empty();
861
1520
  }
862
1521
 
863
1522
  if (default_value)
871
1530
    */
872
1531
    if (default_value->type() == Item::FUNC_ITEM &&
873
1532
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
874
 
         (type == DRIZZLE_TYPE_TIMESTAMP or type == DRIZZLE_TYPE_MICROTIME)))
 
1533
         type == DRIZZLE_TYPE_TIMESTAMP))
875
1534
    {
876
1535
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
877
 
      return true;
 
1536
      return(1);
878
1537
    }
879
1538
    else if (default_value->type() == Item::NULL_ITEM)
880
1539
    {
881
1540
      default_value= 0;
882
 
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG)
 
1541
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
 
1542
          NOT_NULL_FLAG)
883
1543
      {
884
1544
        my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
885
 
        return true;
 
1545
        return(1);
886
1546
      }
887
1547
    }
888
1548
    else if (type_modifier & AUTO_INCREMENT_FLAG)
889
1549
    {
890
1550
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
891
 
      return true;
 
1551
      return(1);
892
1552
    }
893
1553
  }
894
1554
 
895
 
  if (on_update_value && (type != DRIZZLE_TYPE_TIMESTAMP and type != DRIZZLE_TYPE_MICROTIME))
 
1555
  if (on_update_value && type != DRIZZLE_TYPE_TIMESTAMP)
896
1556
  {
897
1557
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
898
 
    return true;
 
1558
    return(1);
899
1559
  }
900
1560
 
901
1561
  if (!(new_field= new CreateField()) ||
902
1562
      new_field->init(session, field_name->str, type, length, decimals, type_modifier,
903
1563
                      default_value, on_update_value, comment, change,
904
1564
                      interval_list, cs, 0, column_format))
905
 
    return true;
 
1565
    return(1);
906
1566
 
907
 
  statement->alter_info.create_list.push_back(new_field);
 
1567
  lex->alter_info.create_list.push_back(new_field);
908
1568
  lex->last_field=new_field;
909
 
 
910
 
  return false;
911
 
}
912
 
 
 
1569
  return(0);
 
1570
}
 
1571
 
 
1572
 
 
1573
/** Store position for column in ALTER TABLE .. ADD column. */
 
1574
 
 
1575
void store_position_for_column(const char *name)
 
1576
{
 
1577
  current_session->lex->last_field->after=const_cast<char*> (name);
 
1578
}
913
1579
 
914
1580
/**
915
1581
  Add a table to list of used tables.
931
1597
*/
932
1598
 
933
1599
TableList *Select_Lex::add_table_to_list(Session *session,
934
 
                                         Table_ident *table,
935
 
                                         LEX_STRING *alias,
936
 
                                         const bitset<NUM_OF_TABLE_OPTIONS>& table_options,
937
 
                                         thr_lock_type lock_type,
938
 
                                         List<Index_hint> *index_hints_arg,
939
 
                                         LEX_STRING *option)
 
1600
                                             Table_ident *table,
 
1601
                                             LEX_STRING *alias,
 
1602
                                             uint32_t table_options,
 
1603
                                             thr_lock_type lock_type,
 
1604
                                             List<Index_hint> *index_hints_arg,
 
1605
                                             LEX_STRING *option)
940
1606
{
941
 
  TableList *ptr;
 
1607
  register TableList *ptr;
942
1608
  TableList *previous_table_ref; /* The table preceding the current one. */
943
1609
  char *alias_str;
944
 
  LEX *lex= session->getLex();
 
1610
  LEX *lex= session->lex;
945
1611
 
946
1612
  if (!table)
947
1613
    return NULL;                                // End of memory
948
1614
  alias_str= alias ? alias->str : table->table.str;
949
 
  if (! table_options.test(TL_OPTION_ALIAS) &&
 
1615
  if (!test(table_options & TL_OPTION_ALIAS) &&
950
1616
      check_table_name(table->table.str, table->table.length))
951
1617
  {
952
1618
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
953
1619
    return NULL;
954
1620
  }
955
1621
 
956
 
  if (table->is_derived_table() == false && table->db.str)
 
1622
  if (table->is_derived_table() == false && table->db.str &&
 
1623
      check_db_name(&table->db))
957
1624
  {
958
 
    my_casedn_str(files_charset_info, table->db.str);
959
 
 
960
 
    identifier::Schema schema_identifier(string(table->db.str));
961
 
    if (not schema::check(*session, schema_identifier))
962
 
    {
963
 
 
964
 
      my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
965
 
      return NULL;
966
 
    }
 
1625
    my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str);
 
1626
    return NULL;
967
1627
  }
968
1628
 
969
1629
  if (!alias)                                   /* Alias is case sensitive */
974
1634
                 ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
975
1635
      return NULL;
976
1636
    }
977
 
    if (!(alias_str= (char*) session->getMemRoot()->duplicate(alias_str,table->table.length+1)))
 
1637
    if (!(alias_str= (char*) session->memdup(alias_str,table->table.length+1)))
978
1638
      return NULL;
979
1639
  }
980
1640
  if (!(ptr = (TableList *) session->calloc(sizeof(TableList))))
981
 
    return NULL;
982
 
 
 
1641
    return NULL;                                /* purecov: inspected */
983
1642
  if (table->db.str)
984
1643
  {
985
 
    ptr->setIsFqtn(true);
986
 
    ptr->setSchemaName(table->db.str);
 
1644
    ptr->is_fqtn= true;
 
1645
    ptr->db= table->db.str;
987
1646
    ptr->db_length= table->db.length;
988
1647
  }
989
 
  else if (lex->copy_db_to(ptr->getSchemaNamePtr(), &ptr->db_length))
 
1648
  else if (lex->copy_db_to(&ptr->db, &ptr->db_length))
990
1649
    return NULL;
991
1650
  else
992
 
    ptr->setIsFqtn(false);
 
1651
    ptr->is_fqtn= false;
993
1652
 
994
1653
  ptr->alias= alias_str;
995
 
  ptr->setIsAlias(alias ? true : false);
996
 
  ptr->setTableName(table->table.str);
 
1654
  ptr->is_alias= alias ? true : false;
 
1655
  if (table->table.length)
 
1656
    table->table.length= my_casedn_str(files_charset_info, table->table.str);
 
1657
  ptr->table_name=table->table.str;
997
1658
  ptr->table_name_length=table->table.length;
998
1659
  ptr->lock_type=   lock_type;
999
 
  ptr->force_index= table_options.test(TL_OPTION_FORCE_INDEX);
1000
 
  ptr->ignore_leaves= table_options.test(TL_OPTION_IGNORE_LEAVES);
 
1660
  ptr->updating=    test(table_options & TL_OPTION_UPDATING);
 
1661
  ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
 
1662
  ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
1001
1663
  ptr->derived=     table->sel;
 
1664
  if (!ptr->derived && !my_strcasecmp(system_charset_info, ptr->db,
 
1665
                                      INFORMATION_SCHEMA_NAME.c_str()))
 
1666
  {
 
1667
    InfoSchemaTable *schema_table= find_schema_table(ptr->table_name);
 
1668
    if (!schema_table ||
 
1669
        (schema_table->isHidden() &&
 
1670
         ((sql_command_flags[lex->sql_command].test(CF_BIT_STATUS_COMMAND)) == 0 ||
 
1671
          /*
 
1672
            this check is used for show columns|keys from I_S hidden table
 
1673
          */
 
1674
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
 
1675
          lex->sql_command == SQLCOM_SHOW_KEYS)))
 
1676
    {
 
1677
      my_error(ER_UNKNOWN_TABLE, MYF(0),
 
1678
               ptr->table_name, INFORMATION_SCHEMA_NAME.c_str());
 
1679
      return NULL;
 
1680
    }
 
1681
    ptr->schema_table_name= ptr->table_name;
 
1682
    ptr->schema_table= schema_table;
 
1683
  }
1002
1684
  ptr->select_lex=  lex->current_select;
1003
1685
  ptr->index_hints= index_hints_arg;
1004
1686
  ptr->option= option ? option->str : 0;
1010
1692
         tables ;
1011
1693
         tables=tables->next_local)
1012
1694
    {
1013
 
      if (not my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
1014
 
          not my_strcasecmp(system_charset_info, ptr->getSchemaName(), tables->getSchemaName()))
 
1695
      if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) &&
 
1696
          !strcmp(ptr->db, tables->db))
1015
1697
      {
1016
 
        my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str);
1017
 
        return NULL;
 
1698
        my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */
 
1699
        return NULL;                            /* purecov: tested */
1018
1700
      }
1019
1701
    }
1020
1702
  }
1075
1757
bool Select_Lex::init_nested_join(Session *session)
1076
1758
{
1077
1759
  TableList *ptr;
1078
 
  NestedJoin *nested_join;
 
1760
  nested_join_st *nested_join;
1079
1761
 
1080
1762
  if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
1081
 
                                       sizeof(NestedJoin))))
 
1763
                                       sizeof(nested_join_st))))
1082
1764
    return true;
1083
 
  ptr->setNestedJoin(((NestedJoin*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList)))));
1084
 
  nested_join= ptr->getNestedJoin();
 
1765
  nested_join= ptr->nested_join=
 
1766
    ((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
 
1767
 
1085
1768
  join_list->push_front(ptr);
1086
 
  ptr->setEmbedding(embedding);
1087
 
  ptr->setJoinList(join_list);
 
1769
  ptr->embedding= embedding;
 
1770
  ptr->join_list= join_list;
1088
1771
  ptr->alias= (char*) "(nested_join)";
1089
1772
  embedding= ptr;
1090
1773
  join_list= &nested_join->join_list;
1091
 
  join_list->clear();
 
1774
  join_list->empty();
1092
1775
  return false;
1093
1776
}
1094
1777
 
1110
1793
TableList *Select_Lex::end_nested_join(Session *)
1111
1794
{
1112
1795
  TableList *ptr;
1113
 
  NestedJoin *nested_join;
 
1796
  nested_join_st *nested_join;
1114
1797
 
1115
1798
  assert(embedding);
1116
1799
  ptr= embedding;
1117
 
  join_list= ptr->getJoinList();
1118
 
  embedding= ptr->getEmbedding();
1119
 
  nested_join= ptr->getNestedJoin();
 
1800
  join_list= ptr->join_list;
 
1801
  embedding= ptr->embedding;
 
1802
  nested_join= ptr->nested_join;
1120
1803
  if (nested_join->join_list.elements == 1)
1121
1804
  {
1122
1805
    TableList *embedded= nested_join->join_list.head();
1123
1806
    join_list->pop();
1124
 
    embedded->setJoinList(join_list);
1125
 
    embedded->setEmbedding(embedding);
 
1807
    embedded->join_list= join_list;
 
1808
    embedded->embedding= embedding;
1126
1809
    join_list->push_front(embedded);
1127
1810
    ptr= embedded;
1128
1811
  }
1151
1834
TableList *Select_Lex::nest_last_join(Session *session)
1152
1835
{
1153
1836
  TableList *ptr;
1154
 
  NestedJoin *nested_join;
 
1837
  nested_join_st *nested_join;
1155
1838
  List<TableList> *embedded_list;
1156
1839
 
1157
1840
  if (!(ptr= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
1158
 
                                          sizeof(NestedJoin))))
 
1841
                                       sizeof(nested_join_st))))
1159
1842
    return NULL;
1160
 
  ptr->setNestedJoin(((NestedJoin*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList)))));
1161
 
  nested_join= ptr->getNestedJoin();
1162
 
  ptr->setEmbedding(embedding);
1163
 
  ptr->setJoinList(join_list);
 
1843
  nested_join= ptr->nested_join=
 
1844
    ((nested_join_st*) ((unsigned char*) ptr + ALIGN_SIZE(sizeof(TableList))));
 
1845
 
 
1846
  ptr->embedding= embedding;
 
1847
  ptr->join_list= join_list;
1164
1848
  ptr->alias= (char*) "(nest_last_join)";
1165
1849
  embedded_list= &nested_join->join_list;
1166
 
  embedded_list->clear();
 
1850
  embedded_list->empty();
1167
1851
 
1168
1852
  for (uint32_t i=0; i < 2; i++)
1169
1853
  {
1170
1854
    TableList *table= join_list->pop();
1171
 
    table->setJoinList(embedded_list);
1172
 
    table->setEmbedding(ptr);
 
1855
    table->join_list= embedded_list;
 
1856
    table->embedding= ptr;
1173
1857
    embedded_list->push_back(table);
1174
1858
    if (table->natural_join)
1175
1859
    {
1205
1889
void Select_Lex::add_joined_table(TableList *table)
1206
1890
{
1207
1891
  join_list->push_front(table);
1208
 
  table->setJoinList(join_list);
1209
 
  table->setEmbedding(embedding);
 
1892
  table->join_list= join_list;
 
1893
  table->embedding= embedding;
1210
1894
}
1211
1895
 
1212
1896
 
1266
1950
 
1267
1951
void Select_Lex::set_lock_for_tables(thr_lock_type lock_type)
1268
1952
{
 
1953
  bool for_update= lock_type >= TL_READ_NO_INSERT;
 
1954
 
1269
1955
  for (TableList *tables= (TableList*) table_list.first;
1270
1956
       tables;
1271
1957
       tables= tables->next_local)
1272
1958
  {
1273
1959
    tables->lock_type= lock_type;
 
1960
    tables->updating=  for_update;
1274
1961
  }
 
1962
  return;
1275
1963
}
1276
1964
 
1277
1965
 
1282
1970
    This object is created for any union construct containing a union
1283
1971
    operation and also for any single select union construct of the form
1284
1972
    @verbatim
1285
 
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ...
 
1973
    (SELECT ... order_st BY order_list [LIMIT n]) order_st BY ...
1286
1974
    @endvarbatim
1287
1975
    or of the form
1288
1976
    @varbatim
1289
 
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
 
1977
    (SELECT ... order_st BY LIMIT n) order_st BY ...
1290
1978
    @endvarbatim
1291
1979
 
1292
1980
  @param session_arg               thread handle
1311
1999
  fake_select_lex->include_standalone(this,
1312
2000
                                      (Select_Lex_Node**)&fake_select_lex);
1313
2001
  fake_select_lex->select_number= INT_MAX;
1314
 
  fake_select_lex->parent_lex= session_arg->getLex(); /* Used in init_query. */
 
2002
  fake_select_lex->parent_lex= session_arg->lex; /* Used in init_query. */
1315
2003
  fake_select_lex->make_empty_select();
1316
2004
  fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE;
1317
2005
  fake_select_lex->select_limit= 0;
1318
2006
 
1319
2007
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
1320
 
  /* allow item list resolving in fake select for ORDER BY */
 
2008
  /* allow item list resolving in fake select for order_st BY */
1321
2009
  fake_select_lex->context.resolve_in_select_list= true;
1322
2010
  fake_select_lex->context.select_lex= fake_select_lex;
1323
2011
 
1325
2013
  {
1326
2014
    /*
1327
2015
      This works only for
1328
 
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
1329
 
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
 
2016
      (SELECT ... order_st BY list [LIMIT n]) order_st BY order_list [LIMIT m],
 
2017
      (SELECT ... LIMIT n) order_st BY order_list [LIMIT m]
1330
2018
      just before the parser starts processing order_list
1331
2019
    */
1332
2020
    global_parameters= fake_select_lex;
1333
2021
    fake_select_lex->no_table_names_allowed= 1;
1334
 
    session_arg->getLex()->current_select= fake_select_lex;
 
2022
    session_arg->lex->current_select= fake_select_lex;
1335
2023
  }
1336
 
  session_arg->getLex()->pop_context();
 
2024
  session_arg->lex->pop_context();
1337
2025
  return(0);
1338
2026
}
1339
2027
 
1369
2057
    left_op->first_leaf_for_name_resolution();
1370
2058
  on_context->last_name_resolution_table=
1371
2059
    right_op->last_leaf_for_name_resolution();
1372
 
  return session->getLex()->push_context(on_context);
 
2060
  return session->lex->push_context(on_context);
1373
2061
}
1374
2062
 
1375
2063
 
1449
2137
 
1450
2138
 
1451
2139
/**
 
2140
  Reload/resets privileges and the different caches.
 
2141
 
 
2142
  @param session Thread handler (can be NULL!)
 
2143
  @param options What should be reset/reloaded (tables, privileges, slave...)
 
2144
  @param tables Tables to flush (if any)
 
2145
  @param write_to_binlog True if we can write to the binlog.
 
2146
 
 
2147
  @note Depending on 'options', it may be very bad to write the
 
2148
    query to the binlog (e.g. FLUSH SLAVE); this is a
 
2149
    pointer where reload_cache() will put 0 if
 
2150
    it thinks we really should not write to the binlog.
 
2151
    Otherwise it will put 1.
 
2152
 
 
2153
  @return Error status code
 
2154
    @retval 0 Ok
 
2155
    @retval !=0  Error; session->killed is set or session->is_error() is true
 
2156
*/
 
2157
 
 
2158
static bool reload_cache(Session *session, ulong options, TableList *tables)
 
2159
{
 
2160
  bool result=0;
 
2161
 
 
2162
  if (options & REFRESH_LOG)
 
2163
  {
 
2164
    if (ha_flush_logs(NULL))
 
2165
      result=1;
 
2166
  }
 
2167
  /*
 
2168
    Note that if REFRESH_READ_LOCK bit is set then REFRESH_TABLES is set too
 
2169
    (see sql_yacc.yy)
 
2170
  */
 
2171
  if (options & (REFRESH_TABLES | REFRESH_READ_LOCK))
 
2172
  {
 
2173
    if ((options & REFRESH_READ_LOCK) && session)
 
2174
    {
 
2175
      if (lock_global_read_lock(session))
 
2176
        return true;                               // Killed
 
2177
      result= session->close_cached_tables(tables, (options & REFRESH_FAST) ?  false : true, true);
 
2178
      if (make_global_read_lock_block_commit(session)) // Killed
 
2179
      {
 
2180
        /* Don't leave things in a half-locked state */
 
2181
        unlock_global_read_lock(session);
 
2182
 
 
2183
        return true;
 
2184
      }
 
2185
    }
 
2186
    else
 
2187
      result= session->close_cached_tables(tables, (options & REFRESH_FAST) ?  false : true, false);
 
2188
  }
 
2189
  if (session && (options & REFRESH_STATUS))
 
2190
    session->refresh_status();
 
2191
 
 
2192
 return result;
 
2193
}
 
2194
 
 
2195
 
 
2196
/**
 
2197
  kill on thread.
 
2198
 
 
2199
  @param session                        Thread class
 
2200
  @param id                     Thread id
 
2201
  @param only_kill_query        Should it kill the query or the connection
 
2202
 
 
2203
  @note
 
2204
    This is written such that we have a short lock on LOCK_thread_count
 
2205
*/
 
2206
 
 
2207
static unsigned int
 
2208
kill_one_thread(Session *, ulong id, bool only_kill_query)
 
2209
{
 
2210
  Session *tmp= NULL;
 
2211
  uint32_t error=ER_NO_SUCH_THREAD;
 
2212
  pthread_mutex_lock(&LOCK_thread_count); // For unlink from list
 
2213
  
 
2214
  for( vector<Session*>::iterator it= session_list.begin(); it != session_list.end(); ++it )
 
2215
  {
 
2216
    if ((*it)->thread_id == id)
 
2217
    {
 
2218
      tmp= *it;
 
2219
      pthread_mutex_lock(&tmp->LOCK_delete);    // Lock from delete
 
2220
      break;
 
2221
    }
 
2222
  }
 
2223
  pthread_mutex_unlock(&LOCK_thread_count);
 
2224
  if (tmp)
 
2225
  {
 
2226
    tmp->awake(only_kill_query ? Session::KILL_QUERY : Session::KILL_CONNECTION);
 
2227
    error=0;
 
2228
    pthread_mutex_unlock(&tmp->LOCK_delete);
 
2229
  }
 
2230
  return(error);
 
2231
}
 
2232
 
 
2233
 
 
2234
/*
 
2235
  kills a thread and sends response
 
2236
 
 
2237
  SYNOPSIS
 
2238
    sql_kill()
 
2239
    session                     Thread class
 
2240
    id                  Thread id
 
2241
    only_kill_query     Should it kill the query or the connection
 
2242
*/
 
2243
 
 
2244
void sql_kill(Session *session, ulong id, bool only_kill_query)
 
2245
{
 
2246
  uint32_t error;
 
2247
  if (!(error= kill_one_thread(session, id, only_kill_query)))
 
2248
    session->my_ok();
 
2249
  else
 
2250
    my_error(error, MYF(0), id);
 
2251
}
 
2252
 
 
2253
 
 
2254
/** If pointer is not a null pointer, append filename to it. */
 
2255
 
 
2256
static bool append_file_to_dir(Session *session, const char **filename_ptr,
 
2257
                               const char *table_name)
 
2258
{
 
2259
  char buff[FN_REFLEN],*ptr, *end;
 
2260
  if (!*filename_ptr)
 
2261
    return 0;                                   // nothing to do
 
2262
 
 
2263
  /* Check that the filename is not too long and it's a hard path */
 
2264
  if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 ||
 
2265
      !test_if_hard_path(*filename_ptr))
 
2266
  {
 
2267
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
 
2268
    return 1;
 
2269
  }
 
2270
  /* Fix is using unix filename format on dos */
 
2271
  strcpy(buff,*filename_ptr);
 
2272
  end=convert_dirname(buff, *filename_ptr, NULL);
 
2273
  if (!(ptr= (char*) session->alloc((size_t) (end-buff) + strlen(table_name)+1)))
 
2274
    return 1;                                   // End of memory
 
2275
  *filename_ptr=ptr;
 
2276
  sprintf(ptr,"%s%s",buff,table_name);
 
2277
  return 0;
 
2278
}
 
2279
 
 
2280
 
 
2281
/**
1452
2282
  Check if the select is a simple select (not an union).
1453
2283
 
1454
2284
  @retval
1457
2287
    1   error   ; In this case the error messege is sent to the client
1458
2288
*/
1459
2289
 
1460
 
bool check_simple_select(Session::pointer session)
 
2290
bool check_simple_select()
1461
2291
{
1462
 
  if (session->getLex()->current_select != &session->getLex()->select_lex)
 
2292
  Session *session= current_session;
 
2293
  LEX *lex= session->lex;
 
2294
  if (lex->current_select != &lex->select_lex)
1463
2295
  {
1464
2296
    char command[80];
1465
2297
    Lex_input_stream *lip= session->m_lip;
1519
2351
bool update_precheck(Session *session, TableList *)
1520
2352
{
1521
2353
  const char *msg= 0;
1522
 
  Select_Lex *select_lex= &session->getLex()->select_lex;
 
2354
  LEX *lex= session->lex;
 
2355
  Select_Lex *select_lex= &lex->select_lex;
1523
2356
 
1524
 
  if (session->getLex()->select_lex.item_list.elements != session->getLex()->value_list.elements)
 
2357
  if (session->lex->select_lex.item_list.elements != session->lex->value_list.elements)
1525
2358
  {
1526
2359
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1527
2360
    return(true);
1528
2361
  }
1529
2362
 
1530
 
  if (session->getLex()->select_lex.table_list.elements > 1)
 
2363
  if (session->lex->select_lex.table_list.elements > 1)
1531
2364
  {
1532
2365
    if (select_lex->order_list.elements)
1533
2366
      msg= "ORDER BY";
1557
2390
 
1558
2391
bool insert_precheck(Session *session, TableList *)
1559
2392
{
 
2393
  LEX *lex= session->lex;
 
2394
 
1560
2395
  /*
1561
2396
    Check that we have modify privileges for the first table and
1562
2397
    select privileges for the rest
1563
2398
  */
1564
 
  if (session->getLex()->update_list.elements != session->getLex()->value_list.elements)
 
2399
  if (lex->update_list.elements != lex->value_list.elements)
1565
2400
  {
1566
2401
    my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0));
1567
2402
    return(true);
1571
2406
 
1572
2407
 
1573
2408
/**
 
2409
  CREATE TABLE query pre-check.
 
2410
 
 
2411
  @param session                        Thread handler
 
2412
  @param tables         Global table list
 
2413
  @param create_table           Table which will be created
 
2414
 
 
2415
  @retval
 
2416
    false   OK
 
2417
  @retval
 
2418
    true   Error
 
2419
*/
 
2420
 
 
2421
bool create_table_precheck(Session *, TableList *,
 
2422
                           TableList *create_table)
 
2423
{
 
2424
  bool error= true;                                 // Error message is given
 
2425
 
 
2426
  if (create_table && (strcmp(create_table->db, "information_schema") == 0))
 
2427
  {
 
2428
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", INFORMATION_SCHEMA_NAME.c_str());
 
2429
    return(true);
 
2430
  }
 
2431
 
 
2432
  error= false;
 
2433
 
 
2434
  return(error);
 
2435
}
 
2436
 
 
2437
 
 
2438
/**
1574
2439
  negate given expression.
1575
2440
 
1576
2441
  @param session  thread handler
1588
2453
  {
1589
2454
    /* it is NOT(NOT( ... )) */
1590
2455
    Item *arg= ((Item_func *) expr)->arguments()[0];
1591
 
    enum_parsing_place place= session->getLex()->current_select->parsing_place;
 
2456
    enum_parsing_place place= session->lex->current_select->parsing_place;
1592
2457
    if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING)
1593
2458
      return arg;
1594
2459
    /*
1637
2502
}
1638
2503
 
1639
2504
 
1640
 
bool check_identifier_name(LEX_STRING *str, error_t err_code,
 
2505
bool check_identifier_name(LEX_STRING *str, uint32_t err_code,
1641
2506
                           uint32_t max_char_length,
1642
2507
                           const char *param_for_err_msg)
1643
2508
{
1663
2528
 
1664
2529
  switch (err_code)
1665
2530
  {
1666
 
  case EE_OK:
 
2531
  case 0:
1667
2532
    break;
1668
2533
  case ER_WRONG_STRING_LENGTH:
1669
2534
    my_error(err_code, MYF(0), str->str, param_for_err_msg, max_char_length);
1675
2540
    assert(0);
1676
2541
    break;
1677
2542
  }
1678
 
 
1679
2543
  return true;
1680
2544
}
1681
2545
 
1682
2546
 
 
2547
/*
 
2548
  Check if path does not contain mysql data home directory
 
2549
  SYNOPSIS
 
2550
    test_if_data_home_dir()
 
2551
    dir                     directory
 
2552
    conv_home_dir           converted data home directory
 
2553
    home_dir_len            converted data home directory length
 
2554
 
 
2555
  RETURN VALUES
 
2556
    0   ok
 
2557
    1   error
 
2558
*/
 
2559
 
 
2560
bool test_if_data_home_dir(const char *dir)
 
2561
{
 
2562
  char path[FN_REFLEN], conv_path[FN_REFLEN];
 
2563
  uint32_t dir_len, home_dir_len= strlen(drizzle_unpacked_real_data_home);
 
2564
 
 
2565
  if (!dir)
 
2566
    return(0);
 
2567
 
 
2568
  (void) fn_format(path, dir, "", "",
 
2569
                   (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS));
 
2570
  dir_len= unpack_dirname(conv_path, dir);
 
2571
 
 
2572
  if (home_dir_len < dir_len)
 
2573
  {
 
2574
    if (!my_strnncoll(character_set_filesystem,
 
2575
                      (const unsigned char*) conv_path, home_dir_len,
 
2576
                      (const unsigned char*) drizzle_unpacked_real_data_home,
 
2577
                      home_dir_len))
 
2578
      return(1);
 
2579
  }
 
2580
  return(0);
 
2581
}
 
2582
 
 
2583
 
 
2584
extern int DRIZZLEparse(void *session); // from sql_yacc.cc
 
2585
 
 
2586
 
1683
2587
/**
1684
2588
  This is a wrapper of DRIZZLEparse(). All the code should call parse_sql()
1685
2589
  instead of DRIZZLEparse().
1692
2596
    @retval true on parsing error.
1693
2597
*/
1694
2598
 
1695
 
static bool parse_sql(Session *session, Lex_input_stream *lip)
 
2599
bool parse_sql(Session *session, Lex_input_stream *lip)
1696
2600
{
1697
2601
  assert(session->m_lip == NULL);
1698
2602
 
1699
 
  DRIZZLE_QUERY_PARSE_START(session->getQueryString()->c_str());
1700
 
 
1701
2603
  /* Set Lex_input_stream. */
1702
2604
 
1703
2605
  session->m_lip= lip;
1704
2606
 
1705
2607
  /* Parse the query. */
1706
2608
 
1707
 
  bool parse_status= base_sql_parse(session) != 0;
 
2609
  bool mysql_parse_status= DRIZZLEparse(session) != 0;
1708
2610
 
1709
2611
  /* Check that if DRIZZLEparse() failed, session->is_error() is set. */
1710
2612
 
1711
 
  assert(!parse_status || session->is_error());
 
2613
  assert(!mysql_parse_status || session->is_error());
1712
2614
 
1713
2615
  /* Reset Lex_input_stream. */
1714
2616
 
1715
2617
  session->m_lip= NULL;
1716
2618
 
1717
 
  DRIZZLE_QUERY_PARSE_DONE(parse_status || session->is_fatal_error);
1718
 
 
1719
2619
  /* That's it. */
1720
2620
 
1721
 
  return parse_status || session->is_fatal_error;
 
2621
  return mysql_parse_status || session->is_fatal_error;
1722
2622
}
1723
2623
 
1724
2624
/**
1725
2625
  @} (end of group Runtime_Environment)
1726
2626
*/
1727
 
 
1728
 
} /* namespace drizzled */