sql_base.cc 308 KB
Newer Older
1
/* Copyright (c) 2000, 2016, Oracle and/or its affiliates.
Marko Mäkelä's avatar
Marko Mäkelä committed
2
   Copyright (c) 2010, 2022, MariaDB
3

unknown's avatar
unknown committed
4 5
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
6
   the Free Software Foundation; version 2 of the License.
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
12

unknown's avatar
unknown committed
13 14
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
Vicențiu Ciorbaru's avatar
Vicențiu Ciorbaru committed
15
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1335  USA */
unknown's avatar
unknown committed
16 17


18
/* Basic functions needed by many modules */
unknown's avatar
unknown committed
19

20
#include "mariadb.h"
21
#include "sql_base.h"                           // setup_table_map
22 23
#include "sql_priv.h"
#include "unireg.h"
24
#include "debug_sync.h"
25
#include "lock.h"        // mysql_lock_remove,
26 27 28 29
                         // mysql_unlock_tables,
                         // mysql_lock_have_duplicate
#include "sql_show.h"    // append_identifier
#include "strfunc.h"     // find_type
30
#include "sql_view.h"    // mysql_make_view, VIEW_ANY_ACL
31 32 33 34 35 36 37
#include "sql_parse.h"   // check_table_access
#include "sql_insert.h"  // kill_delayed_threads
#include "sql_partition.h"               // ALTER_PARTITION_PARAM_TYPE
#include "sql_derived.h" // mysql_derived_prepare,
                         // mysql_handle_derived,
                         // mysql_derived_filling
#include "sql_handler.h" // mysql_ha_flush
38
#include "sql_test.h"
39 40
#include "sql_partition.h"                      // ALTER_PARTITION_PARAM_TYPE
#include "log_event.h"                          // Query_log_event
41
#include "sql_select.h"
42
#include "sp_head.h"
43
#include "sp.h"
Konstantin Osipov's avatar
Konstantin Osipov committed
44
#include "sp_cache.h"
45
#include "sql_trigger.h"
Konstantin Osipov's avatar
Konstantin Osipov committed
46
#include "transaction.h"
47
#include "sql_prepare.h"
48
#include "sql_statistics.h"
49
#include "sql_cte.h"
unknown's avatar
unknown committed
50 51 52
#include <m_ctype.h>
#include <my_dir.h>
#include <hash.h>
53
#include "rpl_filter.h"
54
#include "sql_table.h"                          // build_table_filename
55
#include "datadict.h"   // dd_frm_is_view()
Michael Widenius's avatar
Michael Widenius committed
56
#include "rpl_rli.h"   // rpl_group_info
57
#ifdef  _WIN32
unknown's avatar
unknown committed
58 59
#include <io.h>
#endif
60
#include "wsrep_mysqld.h"
Brave Galera Crew's avatar
Brave Galera Crew committed
61
#ifdef WITH_WSREP
62
#include "wsrep_thd.h"
Brave Galera Crew's avatar
Brave Galera Crew committed
63 64 65
#include "wsrep_trans_observer.h"
#endif /* WITH_WSREP */

66

67
bool
68 69 70
No_such_table_error_handler::handle_condition(THD *,
                                              uint sql_errno,
                                              const char*,
71
                                              Sql_condition::enum_warning_level *level,
72
                                              const char*,
73
                                              Sql_condition ** cond_hdl)
Marc Alff's avatar
Marc Alff committed
74 75
{
  *cond_hdl= NULL;
76 77
  if (!first_error)
    first_error= sql_errno;
78
  if (sql_errno == ER_NO_SUCH_TABLE || sql_errno == ER_NO_SUCH_TABLE_IN_ENGINE)
79 80
  {
    m_handled_errors++;
unknown's avatar
unknown committed
81
    return TRUE;
82 83
  }

84
  if (*level == Sql_condition::WARN_LEVEL_ERROR)
85
    m_unhandled_errors++;
unknown's avatar
unknown committed
86
  return FALSE;
87 88 89
}


90
bool No_such_table_error_handler::safely_trapped_errors()
91 92 93 94 95 96 97 98 99
{
  /*
    If m_unhandled_errors != 0, something else, unanticipated, happened,
    so the error is not trapped but returned to the caller.
    Multiple ER_NO_SUCH_TABLE can be raised in case of views.
  */
  return ((m_handled_errors > 0) && (m_unhandled_errors == 0));
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/**
  This internal handler is used to trap ER_NO_SUCH_TABLE and
  ER_WRONG_MRG_TABLE errors during CHECK/REPAIR TABLE for MERGE
  tables.
*/

class Repair_mrg_table_error_handler : public Internal_error_handler
{
public:
  Repair_mrg_table_error_handler()
    : m_handled_errors(false), m_unhandled_errors(false)
  {}

  bool handle_condition(THD *thd,
                        uint sql_errno,
                        const char* sqlstate,
116
                        Sql_condition::enum_warning_level *level,
117
                        const char* msg,
118
                        Sql_condition ** cond_hdl);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

  /**
    Returns TRUE if there were ER_NO_SUCH_/WRONG_MRG_TABLE and there
    were no unhandled errors. FALSE otherwise.
  */
  bool safely_trapped_errors()
  {
    /*
      Check for m_handled_errors is here for extra safety.
      It can be useful in situation when call to open_table()
      fails because some error which was suppressed by another
      error handler (e.g. in case of MDL deadlock which we
      decided to solve by back-off and retry).
    */
    return (m_handled_errors && (! m_unhandled_errors));
  }

private:
  bool m_handled_errors;
  bool m_unhandled_errors;
};


bool
Repair_mrg_table_error_handler::handle_condition(THD *,
                                                 uint sql_errno,
                                                 const char*,
146
                                                 Sql_condition::enum_warning_level *level,
147
                                                 const char*,
148
                                                 Sql_condition ** cond_hdl)
149 150
{
  *cond_hdl= NULL;
151 152 153
  if (sql_errno == ER_NO_SUCH_TABLE ||
      sql_errno == ER_NO_SUCH_TABLE_IN_ENGINE ||
      sql_errno == ER_WRONG_MRG_TABLE)
154 155 156 157 158 159 160 161 162 163
  {
    m_handled_errors= true;
    return TRUE;
  }

  m_unhandled_errors= true;
  return FALSE;
}


164 165 166 167
/**
  @defgroup Data_Dictionary Data Dictionary
  @{
*/
168 169 170 171 172

static bool check_and_update_table_version(THD *thd, TABLE_LIST *tables,
                                           TABLE_SHARE *table_share);
static bool open_table_entry_fini(THD *thd, TABLE_SHARE *share, TABLE *entry);
static bool auto_repair_table(THD *thd, TABLE_LIST *table_list);
unknown's avatar
unknown committed
173 174


175 176 177 178 179 180 181
/**
  Get table cache key for a table list element.

  @param table_list[in]  Table list element.
  @param key[out]        On return points to table cache key for the table.

  @note Unlike create_table_def_key() call this function doesn't construct
182
        key in a buffer provided by caller. Instead it relies on the fact
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        that table list element for which key is requested has properly
        initialized MDL_request object and the fact that table definition
        cache key is suffix of key used in MDL subsystem. So to get table
        definition key it simply needs to return pointer to appropriate
        part of MDL_key object nested in this table list element.
        Indeed, this means that lifetime of key produced by this call is
        limited by the lifetime of table list element which it got as
        parameter.

  @return Length of key.
*/

uint get_table_def_key(const TABLE_LIST *table_list, const char **key)
{
  /*
    This call relies on the fact that TABLE_LIST::mdl_request::key object
    is properly initialized, so table definition cache can be produced
    from key used by MDL subsystem.
  */
  DBUG_ASSERT(!strcmp(table_list->get_db_name(),
203 204
                      table_list->mdl_request.key.db_name()));
  DBUG_ASSERT(!strcmp(table_list->get_table_name(),
205 206 207 208 209 210 211
                      table_list->mdl_request.key.name()));

  *key= (const char*)table_list->mdl_request.key.ptr() + 1;
  return table_list->mdl_request.key.length() - 1;
}


unknown's avatar
unknown committed
212 213

/*****************************************************************************
214
  Functions to handle table definition cache (TABLE_SHARE)
unknown's avatar
unknown committed
215 216
*****************************************************************************/

unknown's avatar
unknown committed
217 218 219 220 221 222 223 224 225 226 227
/*
  Create a list for all open tables matching SQL expression

  SYNOPSIS
    list_open_tables()
    thd			Thread THD
    wild		SQL like expression

  NOTES
    One gets only a list of tables for which one has any kind of privilege.
    db and table names are allocated in result struct, so one doesn't need
228
    a lock when traversing the return list.
unknown's avatar
unknown committed
229 230 231 232 233 234

  RETURN VALUES
    NULL	Error (Probably OOM)
    #		Pointer to list of names of open tables.
*/

235
struct list_open_tables_arg
236
{
237 238 239
  THD *thd;
  const char *db;
  const char *wild;
240
  TABLE_LIST table_list;
241 242
  OPEN_TABLE_LIST **start_list, *open_list;
};
243

244

245 246 247
static my_bool list_open_tables_callback(TDC_element *element,
                                         list_open_tables_arg *arg)
{
248
  const char *db= (char*) element->m_key;
249
  size_t db_length= strlen(db);
250
  const char *table_name= db + db_length + 1;
251

252 253 254 255
  if (arg->db && my_strcasecmp(system_charset_info, arg->db, db))
    return FALSE;
  if (arg->wild && wild_compare(table_name, arg->wild, 0))
    return FALSE;
unknown's avatar
unknown committed
256

257
  /* Check if user has SELECT privilege for any column in the table */
258 259 260 261
  arg->table_list.db.str= db;
  arg->table_list.db.length= db_length;
  arg->table_list.table_name.str= table_name;
  arg->table_list.table_name.length= strlen(table_name);
262
  arg->table_list.grant.privilege= NO_ACL;
263

264 265 266 267 268 269 270 271 272 273 274 275 276
  if (check_table_access(arg->thd, SELECT_ACL, &arg->table_list, TRUE, 1, TRUE))
    return FALSE;

  if (!(*arg->start_list= (OPEN_TABLE_LIST *) arg->thd->alloc(
                    sizeof(**arg->start_list) + element->m_key_length)))
    return TRUE;

  strmov((*arg->start_list)->table=
         strmov(((*arg->start_list)->db= (char*) ((*arg->start_list) + 1)),
                db) + 1, table_name);
  (*arg->start_list)->in_use= 0;

  mysql_mutex_lock(&element->LOCK_table_share);
277
  All_share_tables_list::Iterator it(element->all_tables);
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  TABLE *table;
  while ((table= it++))
    if (table->in_use)
      ++(*arg->start_list)->in_use;
  mysql_mutex_unlock(&element->LOCK_table_share);
  (*arg->start_list)->locked= 0;                   /* Obsolete. */
  arg->start_list= &(*arg->start_list)->next;
  *arg->start_list= 0;
  return FALSE;
}


OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild)
{
  list_open_tables_arg argument;
  DBUG_ENTER("list_open_tables");

  argument.thd= thd;
  argument.db= db;
  argument.wild= wild;
  bzero((char*) &argument.table_list, sizeof(argument.table_list));
  argument.start_list= &argument.open_list;
  argument.open_list= 0;

  if (tdc_iterate(thd, (my_hash_walk_action) list_open_tables_callback,
                  &argument, true))
    DBUG_RETURN(0);

  DBUG_RETURN(argument.open_list);
307
}
unknown's avatar
unknown committed
308

309

310 311 312 313
/**
   Close all tables that are not in use in table definition cache
*/

314
void purge_tables()
315 316 317 318 319 320 321 322 323 324 325 326 327
{
  /*
    Force close of all open tables.

    Note that code in TABLE_SHARE::wait_for_old_version() assumes that
    incrementing of refresh_version is followed by purge of unused table
    shares.
  */
  kill_delayed_threads();
  /*
    Get rid of all unused TABLE and TABLE_SHARE instances. By doing
    this we automatically close all tables which were marked as "old".
  */
328
  tc_purge();
329 330 331 332 333
  /* Free table shares which were not freed implicitly by loop above. */
  tdc_purge(true);
}


334 335 336 337 338 339 340 341 342 343 344 345 346
/**
   close_cached_tables

   This function has two separate usages:
   1) Close not used tables in the table cache to free memory
   2) Close a list of tables and wait until they are not used anymore. This
      is used mainly when preparing a table for export.

   If there are locked tables, they are closed and reopened before
   function returns. This is done to ensure that table files will be closed
   by all threads and thus external copyable when FLUSH TABLES returns.
*/

347
bool close_cached_tables(THD *thd, TABLE_LIST *tables,
348
                         bool wait_for_refresh, ulong timeout)
unknown's avatar
unknown committed
349 350
{
  DBUG_ENTER("close_cached_tables");
351
  DBUG_ASSERT(thd || (!wait_for_refresh && !tables));
352
  DBUG_ASSERT(wait_for_refresh || !tables);
353

unknown's avatar
unknown committed
354
  if (!tables)
unknown's avatar
unknown committed
355
  {
356
    /* Free tables that are not used */
357
    purge_tables();
358 359
    if (!wait_for_refresh)
      DBUG_RETURN(false);
unknown's avatar
unknown committed
360
  }
361

362
  DBUG_PRINT("info", ("open table definitions: %d",
363
                      (int) tdc_records()));
364

Konstantin Osipov's avatar
Konstantin Osipov committed
365
  if (thd->locked_tables_mode)
unknown's avatar
unknown committed
366 367
  {
    /*
Konstantin Osipov's avatar
Konstantin Osipov committed
368
      If we are under LOCK TABLES, we need to reopen the tables without
369 370 371
      opening a door for any concurrent threads to sneak in and get
      lock on our tables. To achieve this we use exclusive metadata
      locks.
unknown's avatar
unknown committed
372
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
373 374
    TABLE_LIST *tables_to_reopen= (tables ? tables :
                                  thd->locked_tables_list.locked_tables());
375
    bool result= false;
Konstantin Osipov's avatar
Konstantin Osipov committed
376

377
    /* close open HANDLER for this thread to allow table to be closed */
378 379
    mysql_ha_flush_tables(thd, tables_to_reopen);

Konstantin Osipov's avatar
Konstantin Osipov committed
380 381
    for (TABLE_LIST *table_list= tables_to_reopen; table_list;
         table_list= table_list->next_global)
382
    {
383
      int err;
Konstantin Osipov's avatar
Konstantin Osipov committed
384
      /* A check that the table was locked for write is done by the caller. */
385
      TABLE *table= find_table_for_mdl_upgrade(thd, table_list->db.str,
386
                                            table_list->table_name.str, &err);
Konstantin Osipov's avatar
Konstantin Osipov committed
387 388 389 390 391

      /* May return NULL if this table has already been closed via an alias. */
      if (! table)
        continue;

392 393
      if (wait_while_table_is_used(thd, table,
                                   HA_EXTRA_PREPARE_FOR_FORCED_CLOSE))
394
      {
395
        result= true;
396
        break;
397
      }
398
      close_all_tables_for_name(thd, table->s, HA_EXTRA_NOT_USED, NULL);
399
    }
unknown's avatar
unknown committed
400 401 402 403 404
    /*
      No other thread has the locked tables open; reopen them and get the
      old locks. This should always succeed (unless some external process
      has removed the tables)
    */
Marko Mäkelä's avatar
Marko Mäkelä committed
405
    if (thd->locked_tables_list.reopen_tables(thd, false))
406
      result= true;
Monty's avatar
Monty committed
407

Konstantin Osipov's avatar
Konstantin Osipov committed
408
    /*
409
      Since downgrade_lock() won't do anything with shared
Konstantin Osipov's avatar
Konstantin Osipov committed
410
      metadata lock it is much simpler to go through all open tables rather
Konstantin Osipov's avatar
Konstantin Osipov committed
411 412 413
      than picking only those tables that were flushed.
    */
    for (TABLE *tab= thd->open_tables; tab; tab= tab->next)
414
      tab->mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
415 416

    DBUG_RETURN(result);
unknown's avatar
unknown committed
417
  }
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  else if (tables)
  {
    /*
      Get an explicit MDL lock for all requested tables to ensure they are
      not used by any other thread
    */
    MDL_request_list mdl_requests;

    DBUG_PRINT("info", ("Waiting for other threads to close their open tables"));
    DEBUG_SYNC(thd, "after_flush_unlock");

    /* close open HANDLER for this thread to allow table to be closed */
    mysql_ha_flush_tables(thd, tables);

    for (TABLE_LIST *table= tables; table; table= table->next_local)
    {
      MDL_request *mdl_request= new (thd->mem_root) MDL_request;
      if (mdl_request == NULL)
        DBUG_RETURN(true);
437 438
      MDL_REQUEST_INIT_BY_KEY(mdl_request, &table->mdl_request.key,
                              MDL_EXCLUSIVE, MDL_STATEMENT);
439 440 441 442 443 444 445
      mdl_requests.push_front(mdl_request);
    }

    if (thd->mdl_context.acquire_locks(&mdl_requests, timeout))
      DBUG_RETURN(true);

    for (TABLE_LIST *table= tables; table; table= table->next_local)
446
      tdc_remove_table(thd, table->db.str, table->table_name.str);
447 448
  }
  DBUG_RETURN(false);
unknown's avatar
unknown committed
449 450 451
}


452 453 454 455 456 457 458
/**
  Collect all shares that has open tables
*/

struct tc_collect_arg
{
  DYNAMIC_ARRAY shares;
459
  flush_tables_type flush_type;
460 461 462 463 464 465 466 467 468 469 470 471
};

static my_bool tc_collect_used_shares(TDC_element *element,
                                      tc_collect_arg *arg)
{
  my_bool result= FALSE;

  DYNAMIC_ARRAY *shares= &arg->shares;
  mysql_mutex_lock(&element->LOCK_table_share);
  if (element->ref_count > 0 && !element->share->is_view)
  {
    DBUG_ASSERT(element->share);
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    bool do_flush= 0;
    switch (arg->flush_type) {
    case FLUSH_ALL:
      do_flush= 1;
      break;
    case FLUSH_NON_TRANS_TABLES:
      if (!element->share->online_backup &&
          element->share->table_category == TABLE_CATEGORY_USER)
        do_flush= 1;
      break;
    case FLUSH_SYS_TABLES:
      if (!element->share->online_backup &&
          element->share->table_category != TABLE_CATEGORY_USER)
        do_flush= 1;
    }
    if (do_flush)
    {
      element->ref_count++;                       // Protect against delete
      if (push_dynamic(shares, (uchar*) &element->share))
        result= TRUE;
    }
493 494 495 496 497 498
  }
  mysql_mutex_unlock(&element->LOCK_table_share);
  return result;
}


499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/*
  Ignore errors from opening read only tables
*/

class flush_tables_error_handler : public Internal_error_handler
{
public:
  int handled_errors;
  int unhandled_errors;
  flush_tables_error_handler() : handled_errors(0), unhandled_errors(0)
  {}

  bool handle_condition(THD *thd,
                        uint sql_errno,
                        const char* sqlstate,
                        Sql_condition::enum_warning_level *level,
                        const char* msg,
                        Sql_condition ** cond_hdl)
  {
    *cond_hdl= NULL;
519
    if (sql_errno == ER_OPEN_AS_READONLY || sql_errno == ER_LOCK_WAIT_TIMEOUT)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    {
      handled_errors++;
      return TRUE;
    }
    if (*level == Sql_condition::WARN_LEVEL_ERROR)
      unhandled_errors++;
    return FALSE;
  }

  bool got_fatal_error()
  {
    return unhandled_errors > 0;
  }
};


536 537 538 539 540 541 542 543 544 545 546 547 548
/**
   Flush cached table as part of global read lock

   @param thd
   @param flag   What type of tables should be flushed

   @return 0  ok
   @return 1  error

   After we get the list of table shares, we will call flush on all
   possible tables, even if some flush fails.
*/

549
bool flush_tables(THD *thd, flush_tables_type flag)
550 551 552 553
{
  bool result= TRUE;
  tc_collect_arg collect_arg;
  TABLE *tmp_table;
554
  flush_tables_error_handler error_handler;
555 556
  DBUG_ENTER("flush_tables");

557
  purge_tables();  /* Flush unused tables and shares */
558
  DEBUG_SYNC(thd, "after_purge_tables");
559 560 561 562 563 564 565 566

  /*
    Loop over all shares and collect shares that have open tables
    TODO:
    Optimize this to only collect shares that have been used for
    write after last time all tables was closed.
  */

567
  if (!(tmp_table= (TABLE*) my_malloc(PSI_INSTRUMENT_ME, sizeof(*tmp_table),
568 569 570
                                      MYF(MY_WME | MY_THREAD_SPECIFIC))))
    DBUG_RETURN(1);

571
  my_init_dynamic_array(PSI_INSTRUMENT_ME, &collect_arg.shares,
572
                        sizeof(TABLE_SHARE*), 100, 100, MYF(0));
573
  collect_arg.flush_type= flag;
574 575 576 577 578 579 580 581 582 583 584 585 586 587
  if (tdc_iterate(thd, (my_hash_walk_action) tc_collect_used_shares,
                  &collect_arg, true))
  {
    /* Release already collected shares */
    for (uint i= 0 ; i < collect_arg.shares.elements ; i++)
    {
      TABLE_SHARE *share= *dynamic_element(&collect_arg.shares, i,
                                           TABLE_SHARE**);
      tdc_release_share(share);
    }
    goto err;
  }

  /* Call HA_EXTRA_FLUSH on all found shares */
588 589

  thd->push_internal_handler(&error_handler);
590 591 592 593 594 595 596 597
  for (uint i= 0 ; i < collect_arg.shares.elements ; i++)
  {
    TABLE_SHARE *share= *dynamic_element(&collect_arg.shares, i,
                                         TABLE_SHARE**);
    TABLE *table= tc_acquire_table(thd, share->tdc);
    if (table)
    {
      (void) table->file->extra(HA_EXTRA_FLUSH);
598
      DEBUG_SYNC(table->in_use, "before_tc_release_table");
599 600 601 602 603
      tc_release_table(table);
    }
    else
    {
      /*
604 605 606 607 608 609
        No free TABLE instances available. We have to open a new one.

        Try to take a MDL lock to ensure we can open a new table instance.
        If the lock fails, it means that some DDL operation or flush tables
        with read lock is ongoing.
        In this case we cannot sending the HA_EXTRA_FLUSH signal.
610
      */
611 612 613 614 615 616 617 618

      MDL_request mdl_request;
      MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE,
                       share->db.str,
                       share->table_name.str,
                       MDL_SHARED, MDL_EXPLICIT);

      if (!thd->mdl_context.acquire_lock(&mdl_request, 0))
619 620
      {
        /*
621 622 623 624 625
          HA_OPEN_FOR_FLUSH is used to allow us to open the table even if
          TABLE_SHARE::incompatible_version is set. It also will tell
          SEQUENCE engine that we don't have to read the sequence information
          (which may cause deadlocks with concurrently running ALTER TABLE or
          ALTER SEQUENCE) as we will close the table at once.
626
        */
627 628 629 630 631 632 633 634 635 636 637 638 639 640
        if (!open_table_from_share(thd, share, &empty_clex_str,
                                   HA_OPEN_KEYFILE, 0,
                                   HA_OPEN_FOR_ALTER | HA_OPEN_FOR_FLUSH,
                                   tmp_table, FALSE,
                                   NULL))
        {
          (void) tmp_table->file->extra(HA_EXTRA_FLUSH);
          /*
            We don't put the table into the TDC as the table was not fully
            opened (we didn't open triggers)
          */
          closefrm(tmp_table);
        }
        thd->mdl_context.release_lock(mdl_request.ticket);
641 642 643 644
      }
    }
    tdc_release_share(share);
  }
645 646 647 648 649
  thd->pop_internal_handler();
  result= error_handler.got_fatal_error();
  DBUG_PRINT("note", ("open_errors: %u %u",
                      error_handler.handled_errors,
                      error_handler.unhandled_errors));
650 651 652 653 654 655 656
err:
  my_free(tmp_table);
  delete_dynamic(&collect_arg.shares);
  DBUG_RETURN(result);
}


657
/*
658 659 660 661 662 663 664 665 666 667 668
  Mark all tables in the list which were used by current substatement
  as free for reuse.

  SYNOPSIS
    mark_used_tables_as_free_for_reuse()
      thd   - thread context
      table - head of the list of tables

  DESCRIPTION
    Marks all tables in the list which were used by current substatement
    (they are marked by its query_id) as free for reuse.
669

670 671 672
    Clear 'check_table_binlog_row_based_done' flag. For tables which were used
    by current substatement the flag is cleared as part of 'ha_reset()' call.
    For the rest of the open tables not used by current substament if this
673 674 675
    flag is enabled as part of current substatement execution,
    (for example when THD::binlog_write_table_maps() calls
    prepare_for_row_logging()), clear the flag explicitly.
676

677 678 679 680 681 682 683 684
  NOTE
    The reason we reset query_id is that it's not enough to just test
    if table->query_id != thd->query_id to know if a table is in use.

    For example
    SELECT f1_that_uses_t1() FROM t1;
    In f1_that_uses_t1() we will see one instance of t1 where query_id is
    set to query_id of original query.
685 686 687 688
*/

static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
{
689
  DBUG_ENTER("mark_used_tables_as_free_for_reuse");
690
  for (; table ; table= table->next)
691
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
692 693
    DBUG_ASSERT(table->pos_in_locked_tables == NULL ||
                table->pos_in_locked_tables->table == table);
694
    if (table->query_id == thd->query_id)
695
    {
696
      table->query_id= 0;
697 698
      table->file->ha_reset();
    }
699
    else
700
      table->file->clear_cached_table_binlog_row_based_flag();
701
  }
702
  DBUG_VOID_RETURN;
703 704 705
}


Konstantin Osipov's avatar
Konstantin Osipov committed
706
/**
707
  Close all open instances of the table but keep the MDL lock.
Konstantin Osipov's avatar
Konstantin Osipov committed
708 709 710 711 712 713 714 715

  Works both under LOCK TABLES and in the normal mode.
  Removes all closed instances of the table from the table cache.

  @param     thd     thread handle
  @param[in] share   table share, but is just a handy way to
                     access the table cache key

716
  @param[in] extra
717 718 719 720 721 722 723 724
                     HA_EXTRA_PREPARE_FOR_DROP
                        - The table is dropped
                     HA_EXTRA_PREPARE_FOR_RENAME
                        - The table is renamed
                     HA_EXTRA_NOT_USED
                        - The table is marked as closed in the
                          locked_table_list but kept there so one can call
                          locked_table_list->reopen_tables() to put it back.
Monty's avatar
Monty committed
725

726
                     In case of drop/rename the documented behavior is to
Konstantin Osipov's avatar
Konstantin Osipov committed
727
                     implicitly remove the table from LOCK TABLES
728
                     list. 
729 730

  @pre Must be called with an X MDL lock on the table.
Konstantin Osipov's avatar
Konstantin Osipov committed
731 732 733 734
*/

void
close_all_tables_for_name(THD *thd, TABLE_SHARE *share,
735 736
                          ha_extra_function extra,
                          TABLE *skip_table)
Konstantin Osipov's avatar
Konstantin Osipov committed
737
{
738
  DBUG_ASSERT(!share->tmp_table);
739
  DBUG_ASSERT(share->tdc->flushed);
740

Konstantin Osipov's avatar
Konstantin Osipov committed
741
  char key[MAX_DBKEY_LENGTH];
742
  size_t key_length= share->table_cache_key.length;
743
  bool remove_from_locked_tables= extra != HA_EXTRA_NOT_USED;
Konstantin Osipov's avatar
Konstantin Osipov committed
744 745 746 747 748 749 750 751

  memcpy(key, share->table_cache_key.str, key_length);

  for (TABLE **prev= &thd->open_tables; *prev; )
  {
    TABLE *table= *prev;

    if (table->s->table_cache_key.length == key_length &&
752 753
        !memcmp(table->s->table_cache_key.str, key, key_length) &&
        table != skip_table)
Konstantin Osipov's avatar
Konstantin Osipov committed
754
    {
755 756
      thd->locked_tables_list.unlink_from_list(thd,
                                               table->pos_in_locked_tables,
757
                                               remove_from_locked_tables);
758 759 760
      /* Inform handler that there is a drop table or a rename going on */
      if (extra != HA_EXTRA_NOT_USED && table->db_stat)
      {
761
        table->file->extra(extra);
762 763
        extra= HA_EXTRA_NOT_USED;               // Call extra once!
      }
764

Konstantin Osipov's avatar
Konstantin Osipov committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
      /*
        Does nothing if the table is not locked.
        This allows one to use this function after a table
        has been unlocked, e.g. in partition management.
      */
      mysql_lock_remove(thd, thd->lock, table);
      close_thread_table(thd, prev);
    }
    else
    {
      /* Step to next entry in open_tables list. */
      prev= &table->next;
    }
  }
}


782 783 784
/*
  Close all tables used by the current substatement, or all tables
  used by this thread if we are on the upper level.
unknown's avatar
unknown committed
785

786 787 788 789 790 791 792
  SYNOPSIS
    close_thread_tables()
    thd			Thread handler

  IMPLEMENTATION
    Unlocks tables and frees derived tables.
    Put all normal tables used by thread in free list.
793

794 795 796 797
    It will only close/mark as free for reuse tables opened by this
    substatement, it will also check if we are closing tables after
    execution of complete query (i.e. we are on upper level) and will
    leave prelocked mode if needed.
798
*/
unknown's avatar
unknown committed
799

800
int close_thread_tables(THD *thd)
unknown's avatar
unknown committed
801
{
802
  TABLE *table;
803
  int error= 0;
unknown's avatar
unknown committed
804 805
  DBUG_ENTER("close_thread_tables");

Sergei Golubchik's avatar
Sergei Golubchik committed
806
  THD_STAGE_INFO(thd, stage_closing_tables);
807

808 809 810
#ifdef EXTRA_DEBUG
  DBUG_PRINT("tcache", ("open tables:"));
  for (table= thd->open_tables; table; table= table->next)
811 812
    DBUG_PRINT("tcache", ("table: '%s'.'%s' %p", table->s->db.str,
                          table->s->table_name.str, table));
813 814
#endif

815 816 817 818 819 820
#if defined(ENABLED_DEBUG_SYNC)
  /* debug_sync may not be initialized for some slave threads */
  if (thd->debug_sync_control)
    DEBUG_SYNC(thd, "before_close_thread_tables");
#endif

821
  DBUG_ASSERT(thd->transaction->stmt.is_empty() || thd->in_sub_stmt ||
822 823
              (thd->state_flags & Open_tables_state::BACKUPS_AVAIL));

Konstantin Osipov's avatar
Konstantin Osipov committed
824 825 826 827 828
  for (table= thd->open_tables; table; table= table->next)
  {
    /* Table might be in use by some outer statement. */
    DBUG_PRINT("tcache", ("table: '%s'  query_id: %lu",
                          table->s->table_name.str, (ulong) table->query_id));
829

830
    if (thd->locked_tables_mode)
831
    {
832
#ifdef WITH_PARTITION_STORAGE_ENGINE
833 834 835
      if (table->part_info && table->part_info->vers_require_hist_part(thd) &&
          !thd->stmt_arena->is_stmt_prepare())
        table->part_info->vers_check_limit(thd);
836
#endif
837 838 839 840 841 842
      /*
        For simple locking we cleanup it here because we don't close thread
        tables. For prelocking we close it when we do close thread tables.
      */
      if (thd->locked_tables_mode != LTM_PRELOCKED)
        table->vcol_cleanup_expr(thd);
843
    }
Marko Mäkelä's avatar
Marko Mäkelä committed
844

845
    /* Detach MERGE children after every statement. Even under LOCK TABLES. */
Konstantin Osipov's avatar
Konstantin Osipov committed
846 847 848 849 850 851 852 853
    if (thd->locked_tables_mode <= LTM_LOCK_TABLES ||
        table->query_id == thd->query_id)
    {
      DBUG_ASSERT(table->file);
      table->file->extra(HA_EXTRA_DETACH_CHILDREN);
    }
  }

854 855 856 857 858 859 860 861 862 863 864
  /*
    We are assuming here that thd->derived_tables contains ONLY derived
    tables for this substatement. i.e. instead of approach which uses
    query_id matching for determining which of the derived tables belong
    to this substatement we rely on the ability of substatements to
    save/restore thd->derived_tables during their execution.

    TODO: Probably even better approach is to simply associate list of
          derived tables with (sub-)statement instead of thread and destroy
          them at the end of its execution.
  */
865
  if (thd->derived_tables)
866
  {
867
    TABLE *next;
868
    /*
869 870
      Close all derived tables generated in queries like
      SELECT * FROM (SELECT * FROM t1)
871 872 873 874 875 876 877 878
    */
    for (table= thd->derived_tables ; table ; table= next)
    {
      next= table->next;
      free_tmp_table(thd, table);
    }
    thd->derived_tables= 0;
  }
879

Igor Babaev's avatar
Igor Babaev committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
  if (thd->rec_tables)
  {
    TABLE *next;
    /*
      Close all temporary tables created for recursive table references.
      This action was postponed because the table could be used in the
      statements like  ANALYZE WITH r AS (...) SELECT * from r
      where r is defined through recursion. 
    */
    for (table= thd->rec_tables ; table ; table= next)
    {
      next= table->next;
      free_tmp_table(thd, table);
    }
    thd->rec_tables= 0;
  }

897 898 899
  /*
    Mark all temporary tables used by this statement as free for reuse.
  */
900
  thd->mark_tmp_tables_as_free_for_reuse();
901

Konstantin Osipov's avatar
Konstantin Osipov committed
902
  if (thd->locked_tables_mode)
903
  {
904

905 906
    /* Ensure we are calling ha_reset() for all used tables */
    mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
907

908 909 910
    /*
      We are under simple LOCK TABLES or we're inside a sub-statement
      of a prelocked statement, so should not do anything else.
Konstantin Osipov's avatar
Konstantin Osipov committed
911 912 913 914 915

      Note that even if we are in LTM_LOCK_TABLES mode and statement
      requires prelocking (e.g. when we are closing tables after
      failing ot "open" all tables required for statement execution)
      we will exit this function a few lines below.
916
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
917
    if (! thd->lex->requires_prelocking())
918
      DBUG_RETURN(0);
919 920

    /*
921 922 923
      We are in the top-level statement of a prelocked statement,
      so we have to leave the prelocked mode now with doing implicit
      UNLOCK TABLES if needed.
924
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
925 926
    if (thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)
      thd->locked_tables_mode= LTM_LOCK_TABLES;
927

Konstantin Osipov's avatar
Konstantin Osipov committed
928
    if (thd->locked_tables_mode == LTM_LOCK_TABLES)
929
      DBUG_RETURN(0);
930

931
    thd->leave_locked_tables_mode();
Konstantin Osipov's avatar
Konstantin Osipov committed
932

933
    /* Fallthrough */
934
  }
unknown's avatar
unknown committed
935 936 937

  if (thd->lock)
  {
938 939 940 941 942 943 944 945 946
    /*
      For RBR we flush the pending event just before we unlock all the
      tables.  This means that we are at the end of a topmost
      statement, so we ensure that the STMT_END_F flag is set on the
      pending event.  For statements that are *inside* stored
      functions, the pending event will not be flushed: that will be
      handled either before writing a query log event (inside
      binlog_query()) or when preparing a pending event.
     */
947
    (void)thd->binlog_flush_pending_rows_event(TRUE);
948
    error= mysql_unlock_tables(thd, thd->lock);
949
    thd->lock=0;
unknown's avatar
unknown committed
950
  }
951 952 953 954
  /*
    Closing a MERGE child before the parent would be fatal if the
    other thread tries to abort the MERGE lock in between.
  */
955 956
  while (thd->open_tables)
    (void) close_thread_table(thd, &thd->open_tables);
957

958
  DBUG_RETURN(error);
unknown's avatar
unknown committed
959 960
}

961

962 963
/* move one table to free list */

964
void close_thread_table(THD *thd, TABLE **table_ptr)
965
{
966
  TABLE *table= *table_ptr;
967
  handler *file= table->file;
968
  DBUG_ENTER("close_thread_table");
969 970
  DBUG_PRINT("tcache", ("table: '%s'.'%s' %p", table->s->db.str,
                        table->s->table_name.str, table));
971 972
  DBUG_ASSERT(!file->keyread_enabled());
  DBUG_ASSERT(file->inited == handler::NONE);
973

974 975 976 977 978 979 980 981
  /*
    The metadata lock must be released after giving back
    the table to the table cache.
  */
  DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,
                                             table->s->db.str,
                                             table->s->table_name.str,
                                             MDL_SHARED));
982
  table->vcol_cleanup_expr(thd);
983
  table->mdl_ticket= NULL;
984

985 986 987 988 989
  file->update_global_table_stats();
  file->update_global_index_stats();
  if (unlikely(thd->variables.log_slow_verbosity &
               LOG_SLOW_VERBOSITY_ENGINE) &&
      likely(file->handler_stats))
Sergei Golubchik's avatar
Sergei Golubchik committed
990
  {
991 992 993 994
    Exec_time_tracker *tracker;
    if ((tracker= file->get_time_tracker()))
      file->handler_stats->engine_time+= tracker->get_cycles();
    thd->handler_stats.add(file->handler_stats);
Sergei Golubchik's avatar
Sergei Golubchik committed
995
  }
Monty's avatar
Monty committed
996 997 998 999 1000 1001
  /*
    This look is needed to allow THD::notify_shared_lock() to
    traverse the thd->open_tables list without having to worry that
    some of the tables are removed from under it
  */

1002
  mysql_mutex_lock(&thd->LOCK_thd_data);
1003
  *table_ptr=table->next;
1004 1005
  mysql_mutex_unlock(&thd->LOCK_thd_data);

1006 1007
  if (! table->needs_reopen())
  {
1008
    /* Avoid having MERGE tables with attached children in table cache. */
1009
    file->extra(HA_EXTRA_DETACH_CHILDREN);
1010 1011
    /* Free memory and reset for next loop. */
    free_field_buffers_larger_than(table, MAX_TDC_BLOB_SIZE);
1012
    file->ha_reset();
1013 1014
  }

1015 1016 1017 1018
  /*
    Do this *before* entering the TABLE_SHARE::tdc.LOCK_table_share
    critical section.
  */
1019
  MYSQL_UNBIND_TABLE(file);
Sergei Golubchik's avatar
Sergei Golubchik committed
1020

1021
  tc_release_table(table);
1022
  DBUG_VOID_RETURN;
1023 1024
}

unknown's avatar
unknown committed
1025

1026
/*
1027
  Find table in list.
1028 1029

  SYNOPSIS
1030
    find_table_in_list()
1031
    table		Pointer to table list
1032
    offset		Offset to which list in table structure to use
1033 1034
    db_name		Data base name
    table_name		Table name
unknown's avatar
VIEW  
unknown committed
1035

1036
  NOTES:
1037
    This is called by find_table_in_global_list().
unknown's avatar
VIEW  
unknown committed
1038 1039 1040 1041 1042 1043

  RETURN VALUES
    NULL	Table not found
    #		Pointer to found table.
*/

1044
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
1045
                               TABLE_LIST *TABLE_LIST::*link,
1046 1047
                               const LEX_CSTRING *db_name,
                               const LEX_CSTRING *table_name)
unknown's avatar
VIEW  
unknown committed
1048
{
1049
  for (; table; table= table->*link )
1050
  {
1051 1052
    if (cmp(&table->db, db_name) == 0 &&
        cmp(&table->table_name, table_name) == 0)
1053
      break;
1054
  }
unknown's avatar
VIEW  
unknown committed
1055 1056 1057 1058
  return table;
}


1059
/**
1060
  Test that table is unique (It's only exists once in the table list)
1061

1062 1063 1064
  @param  thd                   thread handle
  @param  table                 table which should be checked
  @param  table_list            list of tables
1065 1066
  @param  check_flag            whether to check tables' aliases
                                Currently this is only used by INSERT
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

  NOTE: to exclude derived tables from check we use following mechanism:
    a) during derived table processing set THD::derived_tables_processing
    b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
       THD::derived_tables_processing set. (we can't use JOIN::execute
       because for PS we perform only JOIN::prepare, but we can't set this
       flag in JOIN::prepare if we are not sure that we are in derived table
       processing loop, because multi-update call fix_fields() for some its
       items (which mean JOIN::prepare for subqueries) before unique_table
       call to detect which tables should be locked for write).
1077
    c) find_dup_table skip all tables which belong to SELECT with
1078 1079 1080 1081
       SELECT::exclude_from_table_unique_test set.
    Also SELECT::exclude_from_table_unique_test used to exclude from check
    tables of main SELECT of multi-delete and multi-update

1082 1083 1084 1085
    We also skip tables with TABLE_LIST::prelocking_placeholder set,
    because we want to allow SELECTs from them, and their modification
    will rise the error anyway.

1086 1087
    TODO: when we will have table/view change detection we can do this check
          only once for PS/SP
1088

1089 1090
  @retval !=0  found duplicate
  @retval 0 if table is unique
1091 1092
*/

1093 1094
static
TABLE_LIST* find_dup_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
1095
                           uint check_flag)
1096
{
1097
  TABLE_LIST *res= 0;
1098
  LEX_CSTRING *d_name, *t_name, *t_alias;
1099
  DBUG_ENTER("find_dup_table");
1100
  DBUG_PRINT("enter", ("table alias: %s", table->alias.str));
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

  /*
    If this function called for query which update table (INSERT/UPDATE/...)
    then we have in table->table pointer to TABLE object which we are
    updating even if it is VIEW so we need TABLE_LIST of this TABLE object
    to get right names (even if lower_case_table_names used).

    If this function called for CREATE command that we have not opened table
    (table->table equal to 0) and right names is in current TABLE_LIST
    object.
  */
  if (table->table)
1113
  {
1114 1115 1116
    /* All MyISAMMRG children are plain MyISAM tables. */
    DBUG_ASSERT(table->table->file->ht->db_type != DB_TYPE_MRG_MYISAM);

1117 1118 1119 1120 1121 1122
    table= table->find_underlying_table(table->table);
    /*
      as far as we have table->table we have to find real TABLE_LIST of
      it in underlying tables
    */
    DBUG_ASSERT(table);
1123
  }
1124 1125 1126
  d_name= &table->db;
  t_name= &table->table_name;
  t_alias= &table->alias;
1127

1128
retry:
1129
  DBUG_PRINT("info", ("real table: %s.%s", d_name->str, t_name->str));
1130
  for (TABLE_LIST *tl= table_list; tl ; tl= tl->next_global, res= 0)
unknown's avatar
unknown committed
1131
  {
1132
    if (tl->select_lex && tl->select_lex->master_unit() &&
1133 1134 1135 1136 1137 1138 1139 1140
        tl->select_lex->master_unit()->executed)
    {
      /*
        There is no sense to check tables of already executed parts
        of the query
      */
      continue;
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
1141 1142 1143 1144
    /*
      Table is unique if it is present only once in the global list
      of tables and once in the list of table locks.
    */
Sergei Golubchik's avatar
Sergei Golubchik committed
1145
    if (! (res= find_table_in_global_list(tl, d_name, t_name)))
Konstantin Osipov's avatar
Konstantin Osipov committed
1146
      break;
1147
    tl= res;                       // We can continue search after this table
Konstantin Osipov's avatar
Konstantin Osipov committed
1148 1149 1150

    /* Skip if same underlying table. */
    if (res->table && (res->table == table->table))
1151 1152
      continue;

1153 1154 1155 1156 1157 1158
    /* Skip if table is tmp table */
    if (check_flag & CHECK_DUP_SKIP_TEMP_TABLE &&
        res->table && res->table->s->tmp_table != NO_TMP_TABLE)
    {
      continue;
    }
1159 1160
    if (check_flag & CHECK_DUP_FOR_CREATE)
      DBUG_RETURN(res);
Konstantin Osipov's avatar
Konstantin Osipov committed
1161 1162

    /* Skip if table alias does not match. */
1163
    if (check_flag & CHECK_DUP_ALLOW_DIFFERENT_ALIAS)
Konstantin Osipov's avatar
Konstantin Osipov committed
1164
    {
1165
      if (my_strcasecmp(table_alias_charset, t_alias->str, res->alias.str))
1166
        continue;
Konstantin Osipov's avatar
Konstantin Osipov committed
1167 1168 1169
    }

    /*
1170 1171 1172 1173 1174 1175
      If table is not excluded (could be a derived table) and table is not
      a prelocking placeholder then we found either a duplicate entry
      or a table that is part of a derived table (handled below).
      Examples are:
      INSERT INTO t1 SELECT * FROM t1;
      INSERT INTO t1 SELECT * FROM view_containing_t1;
Konstantin Osipov's avatar
Konstantin Osipov committed
1176 1177 1178 1179
    */
    if (res->select_lex &&
        !res->select_lex->exclude_from_table_unique_test &&
        !res->prelocking_placeholder)
1180
      break;
Konstantin Osipov's avatar
Konstantin Osipov committed
1181

1182
    /*
1183
      If we found entry of this table or table of SELECT which already
1184
      processed in derived table or top select of multi-update/multi-delete
1185
      (exclude_from_table_unique_test) or prelocking placeholder.
1186 1187 1188
    */
    DBUG_PRINT("info",
               ("found same copy of table or table which we should skip"));
unknown's avatar
unknown committed
1189
  }
1190 1191
  if (res && res->belong_to_derived)
  {
1192 1193 1194 1195 1196 1197
    /*
      We come here for queries of type:
      INSERT INTO t1 (SELECT tmp.a FROM (select * FROM t1) as tmp);

      Try to fix by materializing the derived table
    */
1198
    TABLE_LIST *derived=  res->belong_to_derived;
1199
    if (derived->is_merged_derived() && !derived->derived->is_excluded())
1200 1201 1202 1203 1204
    {
      DBUG_PRINT("info",
                 ("convert merged to materialization to resolve the conflict"));
      derived->change_refs_to_fields();
      derived->set_materialized_derived();
unknown's avatar
unknown committed
1205
      goto retry;
1206 1207
    }
  }
1208
  DBUG_RETURN(res);
1209 1210 1211
}


1212 1213 1214 1215 1216
/**
  Test that the subject table of INSERT/UPDATE/DELETE/CREATE
  or (in case of MyISAMMRG) one of its children are not used later
  in the query.

1217 1218 1219 1220 1221
  For MyISAMMRG tables, it is assumed that all the underlying
  tables of @c table (if any) are listed right after it and that
  their @c parent_l field points at the main table.


1222 1223 1224 1225 1226 1227 1228
  @retval non-NULL The table list element for the table that
                   represents the duplicate. 
  @retval NULL     No duplicates found.
*/

TABLE_LIST*
unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list,
1229
             uint check_flag)
1230 1231
{
  TABLE_LIST *dup;
1232 1233 1234

  table= table->find_table_for_update();

1235 1236
  if (table->table &&
      table->table->file->ha_table_flags() & HA_CAN_MULTISTEP_MERGE)
1237 1238 1239 1240
  {
    TABLE_LIST *child;
    dup= NULL;
    /* Check duplicates of all merge children. */
1241
    for (child= table->next_global; child;
1242 1243
         child= child->next_global)
    {
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
      if (child->table &&
          child->table->file->ha_table_flags() & HA_CAN_MULTISTEP_MERGE)
        continue;

      /*
        Ensure that the child has one parent that is the table that is
        updated.
      */
      TABLE_LIST *tmp_parent= child;
      while ((tmp_parent= tmp_parent->parent_l))
      {
        if (tmp_parent == table)
          break;
      }
      if (!tmp_parent)
        break;

1261
      if ((dup= find_dup_table(thd, child, child->next_global, check_flag)))
1262 1263 1264 1265
        break;
    }
  }
  else
1266
    dup= find_dup_table(thd, table, table_list, check_flag);
1267 1268
  return dup;
}
1269 1270


1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
/*
  Issue correct error message in case we found 2 duplicate tables which
  prevent some update operation

  SYNOPSIS
    update_non_unique_table_error()
    update      table which we try to update
    operation   name of update operation
    duplicate   duplicate table which we found

  NOTE:
    here we hide view underlying tables if we have them
*/

void update_non_unique_table_error(TABLE_LIST *update,
                                   const char *operation,
                                   TABLE_LIST *duplicate)
{
  update= update->top_table();
  duplicate= duplicate->top_table();
  if (!update->view || !duplicate->view ||
      update->view == duplicate->view ||
      update->view_name.length != duplicate->view_name.length ||
      update->view_db.length != duplicate->view_db.length ||
1295 1296 1297 1298
      lex_string_cmp(table_alias_charset,
                     &update->view_name, &duplicate->view_name) != 0 ||
      lex_string_cmp(table_alias_charset,
                     &update->view_db, &duplicate->view_db) != 0)
1299 1300 1301 1302 1303 1304 1305
  {
    /*
      it is not the same view repeated (but it can be parts of the same copy
      of view), so we have to hide underlying tables.
    */
    if (update->view)
    {
1306
      /* Issue the ER_NON_INSERTABLE_TABLE error for an INSERT */
1307
      if (update->view == duplicate->view)
1308 1309
        my_error(!strncmp(operation, "INSERT", 6) ?
                 ER_NON_INSERTABLE_TABLE : ER_NON_UPDATABLE_TABLE, MYF(0),
1310
                 update->alias.str, operation);
1311 1312
      else
        my_error(ER_VIEW_PREVENT_UPDATE, MYF(0),
1313 1314
                 (duplicate->view ? duplicate->alias.str : update->alias.str),
                 operation, update->alias.str);
1315 1316 1317 1318
      return;
    }
    if (duplicate->view)
    {
1319 1320
      my_error(ER_VIEW_PREVENT_UPDATE, MYF(0), duplicate->alias.str, operation,
               update->alias.str);
1321 1322 1323
      return;
    }
  }
1324
  my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias.str, operation);
1325 1326 1327
}


Konstantin Osipov's avatar
Konstantin Osipov committed
1328 1329 1330 1331 1332 1333 1334 1335 1336
/**
   Force all other threads to stop using the table by upgrading
   metadata lock on it and remove unused TABLE instances from cache.

   @param thd      Thread handler
   @param table    Table to remove from cache
   @param function HA_EXTRA_PREPARE_FOR_DROP if table is to be deleted
                   HA_EXTRA_FORCE_REOPEN if table is not be used
                   HA_EXTRA_PREPARE_FOR_RENAME if table is to be renamed
1337
                   HA_EXTRA_NOT_USED             Don't call extra()
Konstantin Osipov's avatar
Konstantin Osipov committed
1338 1339 1340 1341 1342 1343 1344 1345 1346

   @note When returning, the table will be unusable for other threads
         until metadata lock is downgraded.

   @retval FALSE Success.
   @retval TRUE  Failure (e.g. because thread was killed).
*/

bool wait_while_table_is_used(THD *thd, TABLE *table,
1347
                              enum ha_extra_function function)
Konstantin Osipov's avatar
Konstantin Osipov committed
1348 1349
{
  DBUG_ENTER("wait_while_table_is_used");
1350
  DBUG_ASSERT(!table->s->tmp_table);
1351
  DBUG_PRINT("enter", ("table: '%s'  share: %p  db_stat: %u",
1352
                       table->s->table_name.str, table->s,
1353
                       table->db_stat));
Konstantin Osipov's avatar
Konstantin Osipov committed
1354

1355 1356 1357
  if (thd->mdl_context.upgrade_shared_lock(
             table->mdl_ticket, MDL_EXCLUSIVE,
             thd->variables.lock_wait_timeout))
Konstantin Osipov's avatar
Konstantin Osipov committed
1358 1359
    DBUG_RETURN(TRUE);

1360
  table->s->tdc->flush(thd, true);
Konstantin Osipov's avatar
Konstantin Osipov committed
1361
  /* extra() call must come only after all instances above are closed */
1362
  if (function != HA_EXTRA_NOT_USED)
1363 1364 1365 1366 1367 1368
  {
    int error= table->file->extra(function);
    if (error)
      table->file->print_error(error, MYF(0));
    DBUG_RETURN(error);
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
1369 1370 1371 1372 1373
  DBUG_RETURN(FALSE);
}


/**
Konstantin Osipov's avatar
Konstantin Osipov committed
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  Close a and drop a just created table in CREATE TABLE ... SELECT.

  @param  thd         Thread handle
  @param  table       TABLE object for the table to be dropped
  @param  db_name     Name of database for this table
  @param  table_name  Name of this table

  This routine assumes that the table to be closed is open only
  by the calling thread, so we needn't wait until other threads
  close the table. It also assumes that the table is first
  in thd->open_ables and a data lock on it, if any, has been
  released. To sum up, it's tuned to work with
  CREATE TABLE ... SELECT and CREATE TABLE .. SELECT only.
  Note, that currently CREATE TABLE ... SELECT is not supported
  under LOCK TABLES. This function, still, can be called in
  prelocked mode, e.g. if we do CREATE TABLE .. SELECT f1();
unknown's avatar
unknown committed
1390 1391
*/

1392 1393
void drop_open_table(THD *thd, TABLE *table, const LEX_CSTRING *db_name,
                     const LEX_CSTRING *table_name)
unknown's avatar
unknown committed
1394
{
Konstantin Osipov's avatar
Konstantin Osipov committed
1395
  DBUG_ENTER("drop_open_table");
unknown's avatar
unknown committed
1396
  if (table->s->tmp_table)
1397
    thd->drop_temporary_table(table, NULL, true);
unknown's avatar
unknown committed
1398 1399
  else
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
1400 1401
    DBUG_ASSERT(table == thd->open_tables);

unknown's avatar
unknown committed
1402
    handlerton *table_type= table->s->db_type();
Konstantin Osipov's avatar
Konstantin Osipov committed
1403
    table->file->extra(HA_EXTRA_PREPARE_FOR_DROP);
1404
    table->s->tdc->flush(thd, true);
Konstantin Osipov's avatar
Konstantin Osipov committed
1405
    close_thread_table(thd, &thd->open_tables);
1406
    /* Remove the table from the storage engine and rm the .frm. */
1407 1408
    quick_rm_table(thd, table_type, db_name, table_name, 0);
 }
Konstantin Osipov's avatar
Konstantin Osipov committed
1409
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1410 1411 1412
}


1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
/**
  An error handler which converts, if possible, ER_LOCK_DEADLOCK error
  that can occur when we are trying to acquire a metadata lock to
  a request for back-off and re-start of open_tables() process.
*/

class MDL_deadlock_handler : public Internal_error_handler
{
public:
  MDL_deadlock_handler(Open_table_context *ot_ctx_arg)
    : m_ot_ctx(ot_ctx_arg), m_is_active(FALSE)
  {}

1426
  virtual ~MDL_deadlock_handler() = default;
1427 1428 1429 1430

  virtual bool handle_condition(THD *thd,
                                uint sql_errno,
                                const char* sqlstate,
1431
                                Sql_condition::enum_warning_level *level,
1432
                                const char* msg,
1433
                                Sql_condition ** cond_hdl);
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449

private:
  /** Open table context to be used for back-off request. */
  Open_table_context *m_ot_ctx;
  /**
    Indicates that we are already in the process of handling
    ER_LOCK_DEADLOCK error. Allows to re-emit the error from
    the error handler without falling into infinite recursion.
  */
  bool m_is_active;
};


bool MDL_deadlock_handler::handle_condition(THD *,
                                            uint sql_errno,
                                            const char*,
1450
                                            Sql_condition::enum_warning_level*,
1451
                                            const char*,
1452
                                            Sql_condition ** cond_hdl)
1453 1454 1455 1456 1457 1458
{
  *cond_hdl= NULL;
  if (! m_is_active && sql_errno == ER_LOCK_DEADLOCK)
  {
    /* Disable the handler to avoid infinite recursion. */
    m_is_active= TRUE;
1459 1460 1461
    (void) m_ot_ctx->request_backoff_action(
             Open_table_context::OT_BACKOFF_AND_RETRY,
             NULL);
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    m_is_active= FALSE;
    /*
      If the above back-off request failed, a new instance of
      ER_LOCK_DEADLOCK error was emitted. Thus the current
      instance of error condition can be treated as handled.
    */
    return TRUE;
  }
  return FALSE;
}


Konstantin Osipov's avatar
Konstantin Osipov committed
1474
/**
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
  Try to acquire an MDL lock for a table being opened.

  @param[in,out] thd      Session context, to report errors.
  @param[out]    ot_ctx   Open table context, to hold the back off
                          state. If we failed to acquire a lock
                          due to a lock conflict, we add the
                          failed request to the open table context.
  @param[in,out] mdl_request A request for an MDL lock.
                          If we managed to acquire a ticket
                          (no errors or lock conflicts occurred),
                          contains a reference to it on
                          return. However, is not modified if MDL
                          lock type- modifying flags were provided.
  @param[in]    flags flags MYSQL_OPEN_FORCE_SHARED_MDL,
                          MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL or
                          MYSQL_OPEN_FAIL_ON_MDL_CONFLICT
                          @sa open_table().
  @param[out]   mdl_ticket Only modified if there was no error.
                          If we managed to acquire an MDL
                          lock, contains a reference to the
                          ticket, otherwise is set to NULL.

  @retval TRUE  An error occurred.
  @retval FALSE No error, but perhaps a lock conflict, check mdl_ticket.
Konstantin Osipov's avatar
Konstantin Osipov committed
1499 1500 1501
*/

static bool
1502
open_table_get_mdl_lock(THD *thd, Open_table_context *ot_ctx,
Konstantin Osipov's avatar
Konstantin Osipov committed
1503
                        MDL_request *mdl_request,
1504 1505
                        uint flags,
                        MDL_ticket **mdl_ticket)
Konstantin Osipov's avatar
Konstantin Osipov committed
1506
{
1507 1508
  MDL_request mdl_request_shared;

1509 1510
  if (flags & (MYSQL_OPEN_FORCE_SHARED_MDL |
               MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL))
Konstantin Osipov's avatar
Konstantin Osipov committed
1511 1512
  {
    /*
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
      MYSQL_OPEN_FORCE_SHARED_MDL flag means that we are executing
      PREPARE for a prepared statement and want to override
      the type-of-operation aware metadata lock which was set
      in the parser/during view opening with a simple shared
      metadata lock.
      This is necessary to allow concurrent execution of PREPARE
      and LOCK TABLES WRITE statement against the same table.

      MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL flag means that we open
      the table in order to get information about it for one of I_S
      queries and also want to override the type-of-operation aware
      shared metadata lock which was set earlier (e.g. during view
      opening) with a high-priority shared metadata lock.
      This is necessary to avoid unnecessary waiting and extra
      ER_WARN_I_S_SKIPPED_TABLE warnings when accessing I_S tables.

      These two flags are mutually exclusive.
Konstantin Osipov's avatar
Konstantin Osipov committed
1530
    */
1531 1532
    DBUG_ASSERT(!(flags & MYSQL_OPEN_FORCE_SHARED_MDL) ||
                !(flags & MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL));
1533

1534 1535 1536
    MDL_REQUEST_INIT_BY_KEY(&mdl_request_shared, &mdl_request->key,
        flags & MYSQL_OPEN_FORCE_SHARED_MDL ? MDL_SHARED : MDL_SHARED_HIGH_PRIO,
        MDL_TRANSACTION);
1537
    mdl_request= &mdl_request_shared;
Konstantin Osipov's avatar
Konstantin Osipov committed
1538
  }
1539

1540
  if (flags & MYSQL_OPEN_FAIL_ON_MDL_CONFLICT)
1541
  {
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    /*
      When table is being open in order to get data for I_S table,
      we might have some tables not only open but also locked (e.g. when
      this happens under LOCK TABLES or in a stored function).
      As a result by waiting on a conflicting metadata lock to go away
      we may create a deadlock which won't entirely belong to the
      MDL subsystem and thus won't be detectable by this subsystem's
      deadlock detector.
      To avoid such situation we skip the trouble-making table if
      there is a conflicting lock.
    */
    if (thd->mdl_context.try_acquire_lock(mdl_request))
      return TRUE;
    if (mdl_request->ticket == NULL)
Konstantin Osipov's avatar
Konstantin Osipov committed
1556
    {
1557 1558 1559
      my_error(ER_WARN_I_S_SKIPPED_TABLE, MYF(0),
               mdl_request->key.db_name(), mdl_request->key.name());
      return TRUE;
Konstantin Osipov's avatar
Konstantin Osipov committed
1560
    }
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
  }
  else
  {
    /*
      We are doing a normal table open. Let us try to acquire a metadata
      lock on the table. If there is a conflicting lock, acquire_lock()
      will wait for it to go away. Sometimes this waiting may lead to a
      deadlock, with the following results:
      1) If a deadlock is entirely within MDL subsystem, it is
         detected by the deadlock detector of this subsystem.
         ER_LOCK_DEADLOCK error is produced. Then, the error handler
         that is installed prior to the call to acquire_lock() attempts
         to request a back-off and retry. Upon success, ER_LOCK_DEADLOCK
         error is suppressed, otherwise propagated up the calling stack.
      2) Otherwise, a deadlock may occur when the wait-for graph
         includes edges not visible to the MDL deadlock detector.
         One such example is a wait on an InnoDB row lock, e.g. when:
         conn C1 gets SR MDL lock on t1 with SELECT * FROM t1
         conn C2 gets a row lock on t2 with  SELECT * FROM t2 FOR UPDATE
         conn C3 gets in and waits on C1 with DROP TABLE t0, t1
         conn C2 continues and blocks on C3 with SELECT * FROM t0
         conn C1 deadlocks by waiting on C2 by issuing SELECT * FROM
         t2 LOCK IN SHARE MODE.
         Such circular waits are currently only resolved by timeouts,
         e.g. @@innodb_lock_wait_timeout or @@lock_wait_timeout.
    */
    MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);

    thd->push_internal_handler(&mdl_deadlock_handler);
    bool result= thd->mdl_context.acquire_lock(mdl_request,
                                               ot_ctx->get_timeout());
    thd->pop_internal_handler();

    if (result && !ot_ctx->can_recover_from_failed_open())
1595
      return TRUE;
Konstantin Osipov's avatar
Konstantin Osipov committed
1596
  }
1597 1598
  *mdl_ticket= mdl_request->ticket;
  return FALSE;
Konstantin Osipov's avatar
Konstantin Osipov committed
1599 1600
}

Marko Mäkelä's avatar
Marko Mäkelä committed
1601
#ifdef WITH_PARTITION_STORAGE_ENGINE
1602 1603 1604 1605 1606 1607 1608
/* Set all [named] partitions as used. */
static int set_partitions_as_used(TABLE_LIST *tl, TABLE *t)
{
  if (t->part_info)
    return t->file->change_partitions_to_open(tl->partition_names);
  return 0;
}
Marko Mäkelä's avatar
Marko Mäkelä committed
1609
#endif
1610

Konstantin Osipov's avatar
Konstantin Osipov committed
1611

1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
/**
  Check if the given table is actually a VIEW that was LOCK-ed

  @param thd            Thread context.
  @param t              Table to check.

  @retval TRUE  The 't'-table is a locked view
                needed to remedy problem before retrying again.
  @retval FALSE 't' was not locked, not a VIEW or an error happened.
*/
1622

1623 1624
bool is_locked_view(THD *thd, TABLE_LIST *t)
{
1625
  DBUG_ENTER("is_locked_view");
1626 1627 1628 1629 1630 1631 1632 1633 1634
  /*
   Is this table a view and not a base table?
   (it is work around to allow to open view with locked tables,
   real fix will be made after definition cache will be made)

   Since opening of view which was not explicitly locked by LOCK
   TABLES breaks metadata locking protocol (potentially can lead
   to deadlocks) it should be disallowed.
  */
1635 1636
  if (thd->mdl_context.is_lock_owner(MDL_key::TABLE, t->db.str,
                                     t->table_name.str, MDL_SHARED))
1637 1638 1639
  {
    char path[FN_REFLEN + 1];
    build_table_filename(path, sizeof(path) - 1,
1640
                         t->db.str, t->table_name.str, reg_ext, 0);
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    /*
      Note that we can't be 100% sure that it is a view since it's
      possible that we either simply have not found unused TABLE
      instance in THD::open_tables list or were unable to open table
      during prelocking process (in this case in theory we still
      should hold shared metadata lock on it).
    */
    if (dd_frm_is_view(thd, path))
    {
      /*
        If parent_l of the table_list is non null then a merge table
        has this view as child table, which is not supported.
      */
      if (t->parent_l)
      {
        my_error(ER_WRONG_MRG_TABLE, MYF(0));
        DBUG_RETURN(FALSE);
      }

1660
      if (!tdc_open_view(thd, t, CHECK_METADATA_VERSION))
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
      {
        DBUG_ASSERT(t->view != 0);
        DBUG_RETURN(TRUE); // VIEW
      }
    }
  }

  DBUG_RETURN(FALSE);
}


1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
/**
  Open a base table.

  @param thd            Thread context.
  @param table_list     Open first table in list.
  @param ot_ctx         Context with flags which modify how open works
                        and which is used to recover from a failed
                        open_table() attempt.
                        Some examples of flags:
                        MYSQL_OPEN_IGNORE_FLUSH - Open table even if
                        someone has done a flush. No version number
                        checking is done.
                        MYSQL_OPEN_HAS_MDL_LOCK - instead of acquiring
                        metadata locks rely on that caller already has
                        appropriate ones.

  Uses a cache of open tables to find a TABLE instance not in use.

  If TABLE_LIST::open_strategy is set to OPEN_IF_EXISTS, the table is
  opened only if it exists. If the open strategy is OPEN_STUB, the
  underlying table is never opened. In both cases, metadata locks are
  always taken according to the lock strategy.

  The function used to open temporary tables, but now it opens base tables
  only.

  @retval TRUE  Open failed. "action" parameter may contain type of action
                needed to remedy problem before retrying again.
  @retval FALSE Success. Members of TABLE_LIST structure are filled properly
                (e.g.  TABLE_LIST::table is set for real tables and
                TABLE_LIST::view is set for views).
1703
*/
unknown's avatar
unknown committed
1704

1705
bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx)
unknown's avatar
unknown committed
1706
{
1707
  TABLE *table;
1708
  const char *key;
unknown's avatar
unknown committed
1709
  uint	key_length;
1710
  const char *alias= table_list->alias.str;
1711
  uint flags= ot_ctx->get_flags();
Konstantin Osipov's avatar
Konstantin Osipov committed
1712
  MDL_ticket *mdl_ticket;
1713
  TABLE_SHARE *share;
1714
  uint gts_flags;
1715
  bool from_share= false;
Marko Mäkelä's avatar
Marko Mäkelä committed
1716
#ifdef WITH_PARTITION_STORAGE_ENGINE
1717
  int part_names_error=0;
Marko Mäkelä's avatar
Marko Mäkelä committed
1718
#endif
unknown's avatar
unknown committed
1719 1720
  DBUG_ENTER("open_table");

1721 1722 1723 1724 1725 1726 1727 1728
  /*
    The table must not be opened already. The table can be pre-opened for
    some statements if it is a temporary table.

    open_temporary_table() must be used to open temporary tables.
  */
  DBUG_ASSERT(!table_list->table);

1729
  /* an open table operation needs a lot of the stack space */
1730
  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
Konstantin Osipov's avatar
Konstantin Osipov committed
1731
    DBUG_RETURN(TRUE);
1732

1733
  if (!(flags & MYSQL_OPEN_IGNORE_KILLED) && thd->killed)
1734 1735
  {
    thd->send_kill_message();
Konstantin Osipov's avatar
Konstantin Osipov committed
1736
    DBUG_RETURN(TRUE);
1737
  }
unknown's avatar
unknown committed
1738

1739
  /*
1740 1741 1742 1743
    Check if we're trying to take a write lock in a read only transaction.

    Note that we allow write locks on log tables as otherwise logging
    to general/slow log would be disabled in read only transactions.
1744
  */
1745
  if (table_list->mdl_request.is_write_lock_request() &&
1746 1747
      thd->tx_read_only &&
      !(flags & (MYSQL_LOCK_LOG_TABLE | MYSQL_OPEN_HAS_MDL_LOCK)))
unknown's avatar
unknown committed
1748
  {
1749 1750
    my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
    DBUG_RETURN(true);
unknown's avatar
unknown committed
1751 1752
  }

1753
  if (!table_list->db.str)
1754 1755 1756 1757 1758
  {
    my_error(ER_NO_DB_ERROR, MYF(0));
    DBUG_RETURN(true);
  }

1759
  key_length= get_table_def_key(table_list, &key);
unknown's avatar
unknown committed
1760

1761
  /*
1762 1763 1764 1765
    If we're in pre-locked or LOCK TABLES mode, let's try to find the
    requested table in the list of pre-opened and locked tables. If the
    table is not there, return an error - we can't open not pre-opened
    tables in pre-locked/LOCK TABLES mode.
1766 1767
    TODO: move this block into a separate function.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
1768 1769
  if (thd->locked_tables_mode &&
      ! (flags & MYSQL_OPEN_GET_NEW_TABLE))
unknown's avatar
unknown committed
1770
  {						// Using table locks
1771
    TABLE *best_table= 0;
unknown's avatar
unknown committed
1772
    int best_distance= INT_MIN;
unknown's avatar
unknown committed
1773 1774
    for (table=thd->open_tables; table ; table=table->next)
    {
unknown's avatar
unknown committed
1775 1776
      if (table->s->table_cache_key.length == key_length &&
	  !memcmp(table->s->table_cache_key.str, key, key_length))
unknown's avatar
unknown committed
1777
      {
1778
        if (!my_strcasecmp(system_charset_info, table->alias.c_ptr(), alias) &&
1779
            table->query_id != thd->query_id && /* skip tables already used */
Konstantin Osipov's avatar
Konstantin Osipov committed
1780
            (thd->locked_tables_mode == LTM_LOCK_TABLES ||
Konstantin Osipov's avatar
Konstantin Osipov committed
1781
             table->query_id == 0))
1782 1783 1784
        {
          int distance= ((int) table->reginfo.lock_type -
                         (int) table_list->lock_type);
1785

1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
          /*
            Find a table that either has the exact lock type requested,
            or has the best suitable lock. In case there is no locked
            table that has an equal or higher lock than requested,
            we us the closest matching lock to be able to produce an error
            message about wrong lock mode on the table. The best_table
            is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.

            distance <  0 - No suitable lock found
            distance >  0 - we have lock mode higher then we require
            distance == 0 - we have lock mode exactly which we need
          */
1798 1799
          if ((best_distance < 0 && distance > best_distance) ||
              (distance >= 0 && distance < best_distance))
1800 1801 1802
          {
            best_distance= distance;
            best_table= table;
1803
            if (best_distance == 0)
1804 1805
            {
              /*
1806 1807 1808 1809
                We have found a perfect match and can finish iterating
                through open tables list. Check for table use conflict
                between calling statement and SP/trigger is done in
                lock_tables().
1810 1811 1812 1813
              */
              break;
            }
          }
1814
        }
unknown's avatar
unknown committed
1815
      }
unknown's avatar
unknown committed
1816
    }
1817 1818 1819 1820
    if (best_table)
    {
      table= best_table;
      table->query_id= thd->query_id;
1821
      table->init(thd, table_list);
1822
      DBUG_PRINT("info",("Using locked table"));
Marko Mäkelä's avatar
Marko Mäkelä committed
1823
#ifdef WITH_PARTITION_STORAGE_ENGINE
1824
      part_names_error= set_partitions_as_used(table_list, table);
Marko Mäkelä's avatar
Marko Mäkelä committed
1825
#endif
1826 1827
      goto reset;
    }
1828

1829
    if (is_locked_view(thd, table_list))
1830 1831 1832 1833 1834 1835
    {
      if (table_list->sequence)
      {
        my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);
        DBUG_RETURN(true);
      }
1836
      DBUG_RETURN(FALSE); // VIEW
1837
    }
1838

1839 1840
    /*
      No table in the locked tables list. In case of explicit LOCK TABLES
Michael Widenius's avatar
Michael Widenius committed
1841
      this can happen if a user did not include the table into the list.
1842 1843 1844 1845
      In case of pre-locked mode locked tables list is generated automatically,
      so we may only end up here if the table did not exist when
      locked tables list was created.
    */
Konstantin Osipov's avatar
Konstantin Osipov committed
1846
    if (thd->locked_tables_mode == LTM_PRELOCKED)
1847
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db.str, table_list->alias.str);
Konstantin Osipov's avatar
Konstantin Osipov committed
1848 1849 1850 1851
    else
      my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
    DBUG_RETURN(TRUE);
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
1852

Konstantin Osipov's avatar
Konstantin Osipov committed
1853 1854 1855 1856
  /*
    Non pre-locked/LOCK TABLES mode, and the table is not temporary.
    This is the normal use case.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
1857

Konstantin Osipov's avatar
Konstantin Osipov committed
1858 1859
  if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))
  {
1860 1861 1862
    if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,
                                flags, &mdl_ticket) ||
        mdl_ticket == NULL)
Konstantin Osipov's avatar
Konstantin Osipov committed
1863 1864
    {
      DEBUG_SYNC(thd, "before_open_table_wait_refresh");
Konstantin Osipov's avatar
Konstantin Osipov committed
1865
      DBUG_RETURN(TRUE);
Konstantin Osipov's avatar
Konstantin Osipov committed
1866 1867
    }
    DEBUG_SYNC(thd, "after_open_table_mdl_shared");
1868
  }
1869 1870 1871 1872 1873 1874 1875 1876
  else
  {
    /*
      Grab reference to the MDL lock ticket that was acquired
      by the caller.
    */
    mdl_ticket= table_list->mdl_request.ticket;
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
1877

1878
  if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS)
unknown's avatar
unknown committed
1879
  {
1880
    if (!ha_table_exists(thd, &table_list->db, &table_list->table_name))
Konstantin Osipov's avatar
Konstantin Osipov committed
1881
      DBUG_RETURN(FALSE);
1882
  }
1883
  else if (table_list->open_strategy == TABLE_LIST::OPEN_STUB)
Konstantin Osipov's avatar
Konstantin Osipov committed
1884
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
1885

1886 1887
  /* Table exists. Let us try to open it. */

1888
  if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)
1889 1890 1891
    gts_flags= GTS_TABLE;
  else if (table_list->i_s_requested_object &  OPEN_VIEW_ONLY)
    gts_flags= GTS_VIEW;
1892
  else
1893
    gts_flags= GTS_TABLE | GTS_VIEW;
1894

1895 1896
retry_share:

1897
  share= tdc_acquire_share(thd, table_list, gts_flags, &table);
1898

1899
  if (unlikely(!share))
1900 1901
  {
    /*
1902 1903 1904 1905
      Hide "Table doesn't exist" errors if the table belongs to a view.
      The check for thd->is_error() is necessary to not push an
      unwanted error in case the error was already silenced.
      @todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
1906
    */
1907
    if (thd->is_error())
1908
    {
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
      if (table_list->parent_l)
      {
        thd->clear_error();
        my_error(ER_WRONG_MRG_TABLE, MYF(0));
      }
      else if (table_list->belong_to_view)
      {
        TABLE_LIST *view= table_list->belong_to_view;
        thd->clear_error();
        my_error(ER_VIEW_INVALID, MYF(0),
                 view->view_db.str, view->view_name.str);
      }
1921 1922 1923
    }
    DBUG_RETURN(TRUE);
  }
1924

Sergei Golubchik's avatar
Sergei Golubchik committed
1925 1926
  /*
    Check if this TABLE_SHARE-object corresponds to a view. Note, that there is
1927
    no need to check TABLE_SHARE::tdc.flushed as we do for regular tables,
Sergei Golubchik's avatar
Sergei Golubchik committed
1928 1929
    because view shares are always up to date.
  */
1930 1931
  if (share->is_view)
  {
1932
    /*
1933 1934
      If parent_l of the table_list is non null then a merge table
      has this view as child table, which is not supported.
1935
    */
1936
    if (table_list->parent_l)
1937
    {
1938
      my_error(ER_WRONG_MRG_TABLE, MYF(0));
1939
      goto err_lock;
unknown's avatar
unknown committed
1940
    }
1941 1942
    if (table_list->sequence)
    {
1943 1944
      my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str,
               table_list->alias.str);
1945 1946
      goto err_lock;
    }
1947

1948
    /*
1949 1950
      This table is a view. Validate its metadata version: in particular,
      that it was a view when the statement was prepared.
1951
    */
1952
    if (check_and_update_table_version(thd, table_list, share))
1953
      goto err_lock;
1954

1955 1956 1957 1958
    /* Open view */
    if (mysql_make_view(thd, share, table_list, false))
      goto err_lock;

1959
    /* TODO: Don't free this */
1960
    tdc_release_share(share);
1961 1962 1963 1964

    DBUG_ASSERT(table_list->view);

    DBUG_RETURN(FALSE);
1965 1966
  }

1967 1968
#ifdef WITH_WSREP
  if (!((flags & MYSQL_OPEN_IGNORE_FLUSH) ||
1969
        (thd->wsrep_applier)))
1970
#else
1971
  if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
1972
#endif
1973
  {
1974
    if (share->tdc->flushed)
1975
    {
1976 1977 1978 1979 1980 1981 1982 1983 1984
      /*
        We already have an MDL lock. But we have encountered an old
        version of table in the table definition cache which is possible
        when someone changes the table version directly in the cache
        without acquiring a metadata lock (e.g. this can happen during
        "rolling" FLUSH TABLE(S)).
        Release our reference to share, wait until old version of
        share goes away and then try to get new version of table share.
      */
1985 1986 1987 1988
      if (table)
        tc_release_table(table);
      else
        tdc_release_share(share);
1989

1990 1991 1992
      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
      bool wait_result;

1993
      thd->push_internal_handler(&mdl_deadlock_handler);
1994 1995
      wait_result= tdc_wait_for_old_version(thd, table_list->db.str,
                                            table_list->table_name.str,
1996 1997 1998 1999 2000 2001
                                            ot_ctx->get_timeout(),
                                            mdl_ticket->get_deadlock_weight());
      thd->pop_internal_handler();

      if (wait_result)
        DBUG_RETURN(TRUE);
2002

2003 2004 2005
      goto retry_share;
    }

2006
    if (thd->open_tables && thd->open_tables->s->tdc->flushed)
2007 2008 2009 2010 2011 2012 2013
    {
      /*
        If the version changes while we're opening the tables,
        we have to back off, close all the tables opened-so-far,
        and try to reopen them. Note: refresh_version is currently
        changed only during FLUSH TABLES.
      */
2014 2015 2016 2017
      if (table)
        tc_release_table(table);
      else
        tdc_release_share(share);
2018 2019
      (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,
                                           NULL);
Konstantin Osipov's avatar
Konstantin Osipov committed
2020
      DBUG_RETURN(TRUE);
2021 2022 2023
    }
  }

2024
  if (table)
2025
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
2026
    DBUG_ASSERT(table->file != NULL);
2027
    if (table->file->discover_check_version())
Sergey Vojtovich's avatar
Sergey Vojtovich committed
2028 2029 2030 2031 2032 2033
    {
      tc_release_table(table);
      (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,
                                            table_list);
      DBUG_RETURN(TRUE);
    }
2034
    table->file->rebind_psi();
Marko Mäkelä's avatar
Marko Mäkelä committed
2035
#ifdef WITH_PARTITION_STORAGE_ENGINE
2036
    part_names_error= set_partitions_as_used(table_list, table);
Marko Mäkelä's avatar
Marko Mäkelä committed
2037
#endif
unknown's avatar
unknown committed
2038 2039 2040
  }
  else
  {
2041
    enum open_frm_error error;
2042
    /* make a new table */
2043 2044
    if (!(table=(TABLE*) my_malloc(key_memory_TABLE, sizeof(*table),
                                   MYF(MY_WME))))
2045
      goto err_lock;
unknown's avatar
unknown committed
2046

2047
    error= open_table_from_share(thd, share, &table_list->alias,
2048 2049
                                 HA_OPEN_KEYFILE | HA_TRY_READ_ONLY,
                                 EXTRA_RECORD,
2050
                                 thd->open_options, table, FALSE,
Sergei Golubchik's avatar
Sergei Golubchik committed
2051
                                 IF_PARTITIONING(table_list->partition_names,0));
unknown's avatar
unknown committed
2052

2053
    if (unlikely(error))
2054
    {
2055
      my_free(table);
2056

2057
      if (error == OPEN_FRM_DISCOVER)
2058
        (void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,
2059
                                              table_list);
Konstantin Osipov's avatar
Konstantin Osipov committed
2060
      else if (share->crashed)
2061 2062 2063 2064 2065 2066 2067
      {
        if (!(flags & MYSQL_OPEN_IGNORE_REPAIR))
          (void) ot_ctx->request_backoff_action(Open_table_context::OT_REPAIR,
                                                table_list);
        else
          table_list->crashed= 1;  /* Mark that table was crashed */
      }
2068
      goto err_lock;
2069
    }
2070
    if (open_table_entry_fini(thd, share, table))
unknown's avatar
unknown committed
2071
    {
Sergey Vojtovich's avatar
Sergey Vojtovich committed
2072
      closefrm(table);
2073
      my_free(table);
2074
      goto err_lock;
unknown's avatar
unknown committed
2075
    }
2076

2077
    /* Add table to the share's used tables list. */
2078
    tc_add_table(thd, table);
2079
    from_share= true;
Sergei Golubchik's avatar
Sergei Golubchik committed
2080 2081
  }

2082 2083
  if (!(flags & MYSQL_OPEN_HAS_MDL_LOCK) &&
      table->s->table_category < TABLE_CATEGORY_INFORMATION)
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
  {
    /*
      We are not under LOCK TABLES and going to acquire write-lock/
      modify the base table. We need to acquire protection against
      global read lock until end of this statement in order to have
      this statement blocked by active FLUSH TABLES WITH READ LOCK.

      We don't need to acquire this protection under LOCK TABLES as
      such protection already acquired at LOCK TABLES time and
      not released until UNLOCK TABLES.

      We don't block statements which modify only temporary tables
      as these tables are not preserved by any form of
      backup which uses FLUSH TABLES WITH READ LOCK.

      TODO: The fact that we sometimes acquire protection against
            GRL only when we encounter table to be write-locked
            slightly increases probability of deadlock.
            This problem will be solved once Alik pushes his
            temporary table refactoring patch and we can start
            pre-acquiring metadata locks at the beggining of
            open_tables() call.
    */
2107 2108 2109 2110 2111 2112 2113
    enum enum_mdl_type mdl_type= MDL_BACKUP_DML;

    if (table->s->table_category != TABLE_CATEGORY_USER)
      mdl_type= MDL_BACKUP_SYS_DML;
    else if (table->s->online_backup)
      mdl_type= MDL_BACKUP_TRANS_DML;

2114 2115 2116 2117 2118
    if (table_list->mdl_request.is_write_lock_request() &&
        ! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
                    MYSQL_OPEN_FORCE_SHARED_MDL |
                    MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
                    MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&
2119
        ! ot_ctx->has_protection_against_grl(mdl_type))
2120 2121 2122 2123
    {
      MDL_request protection_request;
      MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);

2124
      if (thd->has_read_only_protection())
2125 2126 2127 2128 2129 2130
      {
        MYSQL_UNBIND_TABLE(table->file);
        tc_release_table(table);
        DBUG_RETURN(TRUE);
      }

2131 2132
      MDL_REQUEST_INIT(&protection_request, MDL_key::BACKUP, "", "", mdl_type,
                       MDL_STATEMENT);
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149

      /*
        Install error handler which if possible will convert deadlock error
        into request to back-off and restart process of opening tables.
      */
      thd->push_internal_handler(&mdl_deadlock_handler);
      bool result= thd->mdl_context.acquire_lock(&protection_request,
                                                 ot_ctx->get_timeout());
      thd->pop_internal_handler();

      if (result)
      {
        MYSQL_UNBIND_TABLE(table->file);
        tc_release_table(table);
        DBUG_RETURN(TRUE);
      }

2150
      ot_ctx->set_has_protection_against_grl(mdl_type);
2151 2152 2153
    }
  }

Konstantin Osipov's avatar
Konstantin Osipov committed
2154
  table->mdl_ticket= mdl_ticket;
2155 2156 2157
  table->reginfo.lock_type=TL_READ;		/* Assume read */

  table->init(thd, table_list);
Konstantin Osipov's avatar
Konstantin Osipov committed
2158

2159 2160
  table->next= thd->open_tables;		/* Link into simple list */
  thd->set_open_tables(table);
Konstantin Osipov's avatar
Konstantin Osipov committed
2161

unknown's avatar
unknown committed
2162
 reset:
2163
  /*
Sergei Golubchik's avatar
Sergei Golubchik committed
2164
    Check that there is no reference to a condition from an earlier query
2165
    (cf. Bug#58553). 
2166
  */
2167
  DBUG_ASSERT(table->file->pushed_cond == NULL);
unknown's avatar
VIEW  
unknown committed
2168
  table_list->updatable= 1; // It is not derived table nor non-updatable VIEW
Konstantin Osipov's avatar
Konstantin Osipov committed
2169
  table_list->table= table;
2170

2171
  if (!from_share && table->vcol_fix_expr(thd))
2172
    DBUG_RETURN(true);
Aleksey Midenkov's avatar
Aleksey Midenkov committed
2173

2174
#ifdef WITH_PARTITION_STORAGE_ENGINE
2175
  if (unlikely(table->part_info))
2176
  {
2177 2178 2179 2180
    /* Partitions specified were incorrect.*/
    if (part_names_error)
    {
      table->file->print_error(part_names_error, MYF(0));
2181
      DBUG_RETURN(true);
2182
    }
2183 2184 2185 2186 2187 2188 2189 2190
  }
  else if (table_list->partition_names)
  {
    /* Don't allow PARTITION () clause on a nonpartitioned table */
    my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));
    DBUG_RETURN(true);
  }
#endif
2191 2192
  if (table_list->sequence && table->s->table_type != TABLE_TYPE_SEQUENCE)
  {
2193
    my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);
2194
    DBUG_RETURN(true);
2195
  }
2196

Marko Mäkelä's avatar
Marko Mäkelä committed
2197 2198
  DBUG_ASSERT(thd->locked_tables_mode || table->file->row_logging == 0);
  DBUG_RETURN(false);
2199

2200
err_lock:
2201
  tdc_release_share(share);
Konstantin Osipov's avatar
Konstantin Osipov committed
2202

2203
  DBUG_PRINT("exit", ("failed"));
Marko Mäkelä's avatar
Marko Mäkelä committed
2204
  DBUG_RETURN(true);
unknown's avatar
unknown committed
2205 2206 2207
}


2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
/**
   Find table in the list of open tables.

   @param list       List of TABLE objects to be inspected.
   @param db         Database name
   @param table_name Table name

   @return Pointer to the TABLE object found, 0 if no table found.
*/

TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name)
unknown's avatar
unknown committed
2219 2220
{
  char	key[MAX_DBKEY_LENGTH];
2221
  uint key_length= tdc_create_key(key, db, table_name);
unknown's avatar
unknown committed
2222

2223
  for (TABLE *table= list; table ; table=table->next)
unknown's avatar
unknown committed
2224
  {
unknown's avatar
unknown committed
2225 2226
    if (table->s->table_cache_key.length == key_length &&
	!memcmp(table->s->table_cache_key.str, key, key_length))
unknown's avatar
unknown committed
2227 2228 2229 2230 2231 2232
      return table;
  }
  return(0);
}


2233
/**
2234 2235 2236
   Find instance of TABLE with upgradable or exclusive metadata
   lock from the list of open tables, emit error if no such table
   found.
2237

2238
   @param thd        Thread context
2239 2240
   @param db         Database name.
   @param table_name Name of table.
2241 2242 2243
   @param p_error    In the case of an error (when the function returns NULL)
                     the error number is stored there.
                     If the p_error is NULL, function launches the error itself.
2244

2245 2246 2247 2248 2249
   @note This function checks if the connection holds a global IX
         metadata lock. If no such lock is found, it is not safe to
         upgrade the lock and ER_TABLE_NOT_LOCKED_FOR_WRITE will be
         reported.

2250 2251 2252
   @return Pointer to TABLE instance with MDL_SHARED_UPGRADABLE
           MDL_SHARED_NO_WRITE, MDL_SHARED_NO_READ_WRITE, or
           MDL_EXCLUSIVE metadata lock, NULL otherwise.
2253 2254
*/

2255
TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db,
2256
                                  const char *table_name, int *p_error)
2257
{
2258
  TABLE *tab= find_locked_table(thd->open_tables, db, table_name);
2259
  int error;
2260

2261
  if (unlikely(!tab))
2262
  {
2263 2264
    error= ER_TABLE_NOT_LOCKED;
    goto err_exit;
2265
  }
2266 2267 2268 2269 2270 2271 2272

  /*
    It is not safe to upgrade the metadata lock without a global IX lock.
    This can happen with FLUSH TABLES <list> WITH READ LOCK as we in these
    cases don't take a global IX lock in order to be compatible with
    global read lock.
  */
2273
  if (unlikely(!thd->mdl_context.is_lock_owner(MDL_key::BACKUP, "", "",
2274
                                               MDL_BACKUP_DDL)))
2275
  {
2276 2277
    error= ER_TABLE_NOT_LOCKED_FOR_WRITE;
    goto err_exit;
2278
  }
2279 2280 2281 2282 2283 2284

  while (tab->mdl_ticket != NULL &&
         !tab->mdl_ticket->is_upgradable_or_exclusive() &&
         (tab= find_locked_table(tab->next, db, table_name)))
    continue;

2285 2286 2287 2288 2289
  if (unlikely(!tab))
  {
    error= ER_TABLE_NOT_LOCKED_FOR_WRITE;
    goto err_exit;
  }
2290

2291
  return tab;
2292 2293 2294 2295 2296 2297 2298 2299

err_exit:
  if (p_error)
    *p_error= error;
  else
    my_error(error, MYF(0), table_name);

  return NULL;
2300 2301 2302
}


Konstantin Osipov's avatar
Konstantin Osipov committed
2303 2304 2305
/***********************************************************************
  class Locked_tables_list implementation. Declared in sql_class.h
************************************************************************/
unknown's avatar
unknown committed
2306

Konstantin Osipov's avatar
Konstantin Osipov committed
2307 2308
/**
  Enter LTM_LOCK_TABLES mode.
unknown's avatar
unknown committed
2309

Konstantin Osipov's avatar
Konstantin Osipov committed
2310 2311 2312
  Enter the LOCK TABLES mode using all the tables that are
  currently open and locked in this connection.
  Initializes a TABLE_LIST instance for every locked table.
unknown's avatar
unknown committed
2313

Konstantin Osipov's avatar
Konstantin Osipov committed
2314 2315 2316
  @param  thd  thread handle

  @return TRUE if out of memory.
unknown's avatar
unknown committed
2317 2318
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2319 2320
bool
Locked_tables_list::init_locked_tables(THD *thd)
unknown's avatar
unknown committed
2321
{
Konstantin Osipov's avatar
Konstantin Osipov committed
2322 2323
  DBUG_ASSERT(thd->locked_tables_mode == LTM_NONE);
  DBUG_ASSERT(m_locked_tables == NULL);
Konstantin Osipov's avatar
Konstantin Osipov committed
2324 2325
  DBUG_ASSERT(m_reopen_array == NULL);
  DBUG_ASSERT(m_locked_tables_count == 0);
Konstantin Osipov's avatar
Konstantin Osipov committed
2326

Konstantin Osipov's avatar
Konstantin Osipov committed
2327 2328
  for (TABLE *table= thd->open_tables; table;
       table= table->next, m_locked_tables_count++)
Konstantin Osipov's avatar
Konstantin Osipov committed
2329 2330
  {
    TABLE_LIST *src_table_list= table->pos_in_table_list;
2331 2332 2333 2334 2335
    LEX_CSTRING db, table_name, alias;

    db.length=         table->s->db.length;
    table_name.length= table->s->table_name.length;
    alias.length=      table->alias.length();
Konstantin Osipov's avatar
Konstantin Osipov committed
2336 2337 2338 2339
    TABLE_LIST *dst_table_list;

    if (! multi_alloc_root(&m_locked_tables_root,
                           &dst_table_list, sizeof(*dst_table_list),
2340 2341 2342
                           &db.str, (size_t) db.length + 1,
                           &table_name.str, (size_t) table_name.length + 1,
                           &alias.str, (size_t) alias.length + 1,
Konstantin Osipov's avatar
Konstantin Osipov committed
2343
                           NullS))
Konstantin Osipov's avatar
Konstantin Osipov committed
2344
    {
2345
      reset();
Konstantin Osipov's avatar
Konstantin Osipov committed
2346 2347 2348
      return TRUE;
    }

2349 2350 2351 2352 2353 2354
    memcpy((char*) db.str,         table->s->db.str, db.length + 1);
    memcpy((char*) table_name.str, table->s->table_name.str,
           table_name.length + 1);
    memcpy((char*) alias.str,      table->alias.c_ptr(), alias.length + 1);
    dst_table_list->init_one_table(&db, &table_name,
                                   &alias, table->reginfo.lock_type);
Konstantin Osipov's avatar
Konstantin Osipov committed
2355
    dst_table_list->table= table;
Konstantin Osipov's avatar
Konstantin Osipov committed
2356 2357
    dst_table_list->mdl_request.ticket= src_table_list->mdl_request.ticket;

Konstantin Osipov's avatar
Konstantin Osipov committed
2358 2359 2360 2361 2362
    /* Link last into the list of tables */
    *(dst_table_list->prev_global= m_locked_tables_last)= dst_table_list;
    m_locked_tables_last= &dst_table_list->next_global;
    table->pos_in_locked_tables= dst_table_list;
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
2363 2364 2365 2366 2367 2368 2369
  if (m_locked_tables_count)
  {
    /**
      Allocate an auxiliary array to pass to mysql_lock_tables()
      in reopen_tables(). reopen_tables() is a critical
      path and we don't want to complicate it with extra allocations.
    */
2370 2371 2372
    m_reopen_array= (TABLE_LIST**)alloc_root(&m_locked_tables_root,
                                             sizeof(TABLE_LIST*) *
                                             (m_locked_tables_count+1));
Konstantin Osipov's avatar
Konstantin Osipov committed
2373 2374
    if (m_reopen_array == NULL)
    {
2375
      reset();
Konstantin Osipov's avatar
Konstantin Osipov committed
2376 2377 2378
      return TRUE;
    }
  }
2379 2380 2381

  TRANSACT_TRACKER(add_trx_state(thd, TX_LOCKED_TABLES));

2382
  thd->enter_locked_tables_mode(LTM_LOCK_TABLES);
Konstantin Osipov's avatar
Konstantin Osipov committed
2383

Konstantin Osipov's avatar
Konstantin Osipov committed
2384 2385
  return FALSE;
}
unknown's avatar
unknown committed
2386

2387

Konstantin Osipov's avatar
Konstantin Osipov committed
2388 2389
/**
  Leave LTM_LOCK_TABLES mode if it's been entered.
unknown's avatar
unknown committed
2390

Konstantin Osipov's avatar
Konstantin Osipov committed
2391
  Close all locked tables, free memory, and leave the mode.
2392

Konstantin Osipov's avatar
Konstantin Osipov committed
2393 2394
  @note This function is a no-op if we're not in LOCK TABLES.
*/
unknown's avatar
unknown committed
2395

2396
int
Konstantin Osipov's avatar
Konstantin Osipov committed
2397 2398
Locked_tables_list::unlock_locked_tables(THD *thd)
{
2399
  int error;
2400 2401 2402 2403 2404 2405 2406 2407 2408
  DBUG_ASSERT(!thd->in_sub_stmt &&
              !(thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
  /*
    Sic: we must be careful to not close open tables if
    we're not in LOCK TABLES mode: unlock_locked_tables() is
    sometimes called implicitly, expecting no effect on
    open tables, e.g. from begin_trans().
  */
  if (thd->locked_tables_mode != LTM_LOCK_TABLES)
2409
    return 0;
2410 2411 2412

  for (TABLE_LIST *table_list= m_locked_tables;
       table_list; table_list= table_list->next_global)
2413
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
2414
    /*
2415 2416
      Clear the position in the list, the TABLE object will be
      returned to the table cache.
Konstantin Osipov's avatar
Konstantin Osipov committed
2417
    */
2418 2419 2420 2421
    if (table_list->table)                    // If not closed
      table_list->table->pos_in_locked_tables= NULL;
  }
  thd->leave_locked_tables_mode();
Konstantin Osipov's avatar
Konstantin Osipov committed
2422

2423 2424
  TRANSACT_TRACKER(clear_trx_state(thd, TX_LOCKED_TABLES));

2425
  DBUG_ASSERT(thd->transaction->stmt.is_empty());
2426
  error= close_thread_tables(thd);
2427 2428 2429 2430 2431

  /*
    We rely on the caller to implicitly commit the
    transaction and release transactional locks.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
2432

2433
  /*
Konstantin Osipov's avatar
Konstantin Osipov committed
2434 2435
    After closing tables we can free memory used for storing lock
    request for metadata locks and TABLE_LIST elements.
2436
  */
2437
  reset();
2438
  return error;
2439 2440
}

2441 2442 2443 2444 2445 2446

/**
  Remove all meta data locks associated with table and release locked
  table mode if there is no locked tables anymore
*/

2447
int
2448 2449 2450 2451 2452 2453 2454 2455
Locked_tables_list::unlock_locked_table(THD *thd, MDL_ticket *mdl_ticket)
{
  /*
    Ensure we are in locked table mode.
    As this function is only called on error condition it's better
    to check this condition here than in the caller.
  */
  if (thd->locked_tables_mode != LTM_LOCK_TABLES)
2456
    return 0;
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468

  if (mdl_ticket)
  {
    /*
      Under LOCK TABLES we may have several instances of table open
      and locked and therefore have to remove several metadata lock
      requests associated with them.
    */
    thd->mdl_context.release_all_locks_for_name(mdl_ticket);
  }

  if (thd->lock->table_count == 0)
2469 2470
    return unlock_locked_tables(thd);
  return 0;
2471 2472 2473
}


2474 2475 2476 2477 2478 2479
/*
  Free memory allocated for storing locks
*/

void Locked_tables_list::reset()
{
Konstantin Osipov's avatar
Konstantin Osipov committed
2480 2481 2482
  free_root(&m_locked_tables_root, MYF(0));
  m_locked_tables= NULL;
  m_locked_tables_last= &m_locked_tables;
Konstantin Osipov's avatar
Konstantin Osipov committed
2483 2484
  m_reopen_array= NULL;
  m_locked_tables_count= 0;
2485
  some_table_marked_for_reopen= 0;
unknown's avatar
unknown committed
2486 2487 2488
}


2489
/**
Konstantin Osipov's avatar
Konstantin Osipov committed
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
  Unlink a locked table from the locked tables list, either
  temporarily or permanently.

  @param  thd        thread handle
  @param  table_list the element of locked tables list.
                     The implementation assumes that this argument
                     points to a TABLE_LIST element linked into
                     the locked tables list. Passing a TABLE_LIST
                     instance that is not part of locked tables
                     list will lead to a crash.
Konstantin Osipov's avatar
Konstantin Osipov committed
2500
  @param  remove_from_locked_tables
Konstantin Osipov's avatar
Konstantin Osipov committed
2501 2502 2503 2504 2505 2506
                      TRUE if the table is removed from the list
                      permanently.

  This function is a no-op if we're not under LOCK TABLES.

  @sa Locked_tables_list::reopen_tables()
unknown's avatar
unknown committed
2507
*/
unknown's avatar
unknown committed
2508

Konstantin Osipov's avatar
Konstantin Osipov committed
2509 2510 2511 2512

void Locked_tables_list::unlink_from_list(THD *thd,
                                          TABLE_LIST *table_list,
                                          bool remove_from_locked_tables)
unknown's avatar
unknown committed
2513
{
Konstantin Osipov's avatar
Konstantin Osipov committed
2514 2515 2516 2517
  /*
    If mode is not LTM_LOCK_TABLES, we needn't do anything. Moreover,
    outside this mode pos_in_locked_tables value is not trustworthy.
  */
2518 2519
  if (thd->locked_tables_mode != LTM_LOCK_TABLES &&
      thd->locked_tables_mode != LTM_PRELOCKED_UNDER_LOCK_TABLES)
Konstantin Osipov's avatar
Konstantin Osipov committed
2520
    return;
2521

Konstantin Osipov's avatar
Konstantin Osipov committed
2522 2523 2524 2525 2526
  /*
    table_list must be set and point to pos_in_locked_tables of some
    table.
  */
  DBUG_ASSERT(table_list->table->pos_in_locked_tables == table_list);
2527

Konstantin Osipov's avatar
Konstantin Osipov committed
2528 2529 2530 2531 2532
  /* Clear the pointer, the table will be returned to the table cache. */
  table_list->table->pos_in_locked_tables= NULL;

  /* Mark the table as closed in the locked tables list. */
  table_list->table= NULL;
unknown's avatar
unknown committed
2533

Konstantin Osipov's avatar
Konstantin Osipov committed
2534 2535 2536 2537 2538 2539
  /*
    If the table is being dropped or renamed, remove it from
    the locked tables list (implicitly drop the LOCK TABLES lock
    on it).
  */
  if (remove_from_locked_tables)
unknown's avatar
unknown committed
2540
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
2541 2542 2543 2544 2545
    *table_list->prev_global= table_list->next_global;
    if (table_list->next_global == NULL)
      m_locked_tables_last= table_list->prev_global;
    else
      table_list->next_global->prev_global= table_list->prev_global;
2546
    m_locked_tables_count--;
unknown's avatar
unknown committed
2547 2548 2549
  }
}

unknown's avatar
unknown committed
2550
/**
Konstantin Osipov's avatar
Konstantin Osipov committed
2551 2552 2553 2554
  This is an attempt to recover (somewhat) in case of an error.
  If we failed to reopen a closed table, let's unlink it from the
  list and forget about it. From a user perspective that would look
  as if the server "lost" the lock on one of the locked tables.
2555

Konstantin Osipov's avatar
Konstantin Osipov committed
2556
  @note This function is a no-op if we're not under LOCK TABLES.
2557 2558
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2559 2560
void Locked_tables_list::
unlink_all_closed_tables(THD *thd, MYSQL_LOCK *lock, size_t reopen_count)
2561
{
Konstantin Osipov's avatar
Konstantin Osipov committed
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
  /* If we managed to take a lock, unlock tables and free the lock. */
  if (lock)
    mysql_unlock_tables(thd, lock);
  /*
    If a failure happened in reopen_tables(), we may have succeeded
    reopening some tables, but not all.
    This works when the connection was killed in mysql_lock_tables().
  */
  if (reopen_count)
  {
    while (reopen_count--)
    {
      /*
        When closing the table, we must remove it
        from thd->open_tables list.
        We rely on the fact that open_table() that was used
        in reopen_tables() always links the opened table
        to the beginning of the open_tables list.
      */
2581
      DBUG_ASSERT(thd->open_tables == m_reopen_array[reopen_count]->table);
Konstantin Osipov's avatar
Konstantin Osipov committed
2582 2583

      thd->open_tables->pos_in_locked_tables->table= NULL;
2584
      thd->open_tables->pos_in_locked_tables= NULL;
Konstantin Osipov's avatar
Konstantin Osipov committed
2585 2586 2587 2588 2589

      close_thread_table(thd, &thd->open_tables);
    }
  }
  /* Exclude all closed tables from the LOCK TABLES list. */
Konstantin Osipov's avatar
Konstantin Osipov committed
2590 2591
  for (TABLE_LIST *table_list= m_locked_tables; table_list; table_list=
       table_list->next_global)
2592
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
2593
    if (table_list->table == NULL)
2594
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
2595 2596 2597 2598
      /* Unlink from list. */
      *table_list->prev_global= table_list->next_global;
      if (table_list->next_global == NULL)
        m_locked_tables_last= table_list->prev_global;
2599
      else
Konstantin Osipov's avatar
Konstantin Osipov committed
2600
        table_list->next_global->prev_global= table_list->prev_global;
2601
      m_locked_tables_count--;
2602 2603
    }
  }
2604 2605 2606

  /* If no tables left, do an automatic UNLOCK TABLES */
  if (thd->lock && thd->lock->table_count == 0)
2607 2608 2609 2610 2611 2612 2613 2614 2615
  {
    /*
      We have to rollback any open transactions here.
      This is required in the case where the server has been killed
      but some transations are still open (as part of locked tables).
      If we don't do this, we will get an assert in unlock_locked_tables().
    */
    ha_rollback_trans(thd, FALSE);
    ha_rollback_trans(thd, TRUE);
2616
    unlock_locked_tables(thd);
2617
  }
2618 2619 2620
}


2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
/*
  Mark all instances of the table to be reopened

  This is only needed when LOCK TABLES is active
*/

void Locked_tables_list::mark_table_for_reopen(THD *thd, TABLE *table)
{
  TABLE_SHARE *share= table->s;

2631
  for (TABLE_LIST *table_list= m_locked_tables;
2632 2633
       table_list; table_list= table_list->next_global)
  {
2634 2635 2636 2637 2638 2639
    /*
      table_list->table can be NULL in the case of TRUNCATE TABLE where
      the table was locked twice and one instance closed in
      close_all_tables_for_name().
    */
    if (table_list->table && table_list->table->s == share)
2640 2641 2642 2643 2644 2645 2646 2647
      table_list->table->internal_set_needs_reopen(true);
  }
  /* This is needed in the case where lock tables where not used */
  table->internal_set_needs_reopen(true);
  some_table_marked_for_reopen= 1;
}


unknown's avatar
unknown committed
2648
/**
Konstantin Osipov's avatar
Konstantin Osipov committed
2649 2650
  Reopen the tables locked with LOCK TABLES and temporarily closed
  by a DDL statement or FLUSH TABLES.
unknown's avatar
unknown committed
2651

2652 2653 2654 2655
  @param need_reopen  If set, reopen open tables that are marked with
                      for reopen.
                      If not set, reopen tables that where closed.

Konstantin Osipov's avatar
Konstantin Osipov committed
2656
  @note This function is a no-op if we're not under LOCK TABLES.
unknown's avatar
unknown committed
2657

Konstantin Osipov's avatar
Konstantin Osipov committed
2658 2659 2660 2661
  @return TRUE if an error reopening the tables. May happen in
               case of some fatal system error only, e.g. a disk
               corruption, out of memory or a serious bug in the
               locking.
unknown's avatar
unknown committed
2662 2663
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
2664
bool
2665
Locked_tables_list::reopen_tables(THD *thd, bool need_reopen)
unknown's avatar
unknown committed
2666
{
2667 2668 2669
  bool is_ok= thd->get_stmt_da()->is_ok();
  Open_table_context ot_ctx(thd, !is_ok ? MYSQL_OPEN_REOPEN:
                                  MYSQL_OPEN_IGNORE_KILLED | MYSQL_OPEN_REOPEN);
2670
  uint reopen_count= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
2671 2672
  MYSQL_LOCK *lock;
  MYSQL_LOCK *merged_lock;
2673
  DBUG_ENTER("Locked_tables_list::reopen_tables");
unknown's avatar
unknown committed
2674

2675 2676 2677 2678
  DBUG_ASSERT(some_table_marked_for_reopen || !need_reopen);


  /* Reset flag that some table was marked for reopen */
2679 2680
  if (need_reopen)
    some_table_marked_for_reopen= 0;
2681

Konstantin Osipov's avatar
Konstantin Osipov committed
2682 2683
  for (TABLE_LIST *table_list= m_locked_tables;
       table_list; table_list= table_list->next_global)
unknown's avatar
unknown committed
2684
  {
2685 2686 2687 2688
    if (need_reopen)
    {
      if (!table_list->table || !table_list->table->needs_reopen())
        continue;
2689 2690 2691 2692 2693 2694
      for (TABLE **prev= &thd->open_tables; *prev; prev= &(*prev)->next)
      {
        if (*prev == table_list->table)
        {
          thd->locked_tables_list.unlink_from_list(thd, table_list, false);
          mysql_lock_remove(thd, thd->lock, *prev);
2695
          (*prev)->file->extra(HA_EXTRA_PREPARE_FOR_FORCED_CLOSE);
2696 2697 2698 2699
          close_thread_table(thd, prev);
          break;
        }
      }
2700 2701 2702 2703 2704
      DBUG_ASSERT(table_list->table == NULL);
    }
    else
    {
      if (table_list->table)                      /* The table was not closed */
2705
        continue;
unknown's avatar
unknown committed
2706
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
2707 2708

    DBUG_ASSERT(reopen_count < m_locked_tables_count);
2709
    m_reopen_array[reopen_count++]= table_list;
Konstantin Osipov's avatar
Konstantin Osipov committed
2710 2711 2712
  }
  if (reopen_count)
  {
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    TABLE **tables= (TABLE**) my_alloca(reopen_count * sizeof(TABLE*));

    for (uint i= 0 ; i < reopen_count ; i++)
    {
      TABLE_LIST *table_list= m_reopen_array[i];
      /* Links into thd->open_tables upon success */
      if (open_table(thd, table_list, &ot_ctx))
      {
        unlink_all_closed_tables(thd, 0, i);
        my_afree((void*) tables);
        DBUG_RETURN(TRUE);
      }
      tables[i]= table_list->table;
      table_list->table->pos_in_locked_tables= table_list;
      /* See also the comment on lock type in init_locked_tables(). */
      table_list->table->reginfo.lock_type= table_list->lock_type;
    }

Konstantin Osipov's avatar
Konstantin Osipov committed
2731
    thd->in_lock_tables= 1;
Konstantin Osipov's avatar
Konstantin Osipov committed
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
    /*
      We re-lock all tables with mysql_lock_tables() at once rather
      than locking one table at a time because of the case
      reported in Bug#45035: when the same table is present
      in the list many times, thr_lock.c fails to grant READ lock
      on a table that is already locked by WRITE lock, even if
      WRITE lock is taken by the same thread. If READ and WRITE
      lock are passed to thr_lock.c in the same list, everything
      works fine. Patching legacy code of thr_lock.c is risking to
      break something else.
    */
2743
    lock= mysql_lock_tables(thd, tables, reopen_count,
Monty's avatar
Monty committed
2744
                            MYSQL_OPEN_REOPEN | MYSQL_LOCK_USE_MALLOC);
Konstantin Osipov's avatar
Konstantin Osipov committed
2745
    thd->in_lock_tables= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
2746 2747
    if (lock == NULL || (merged_lock=
                         mysql_lock_merge(thd->lock, lock)) == NULL)
2748
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
2749 2750 2751
      unlink_all_closed_tables(thd, lock, reopen_count);
      if (! thd->killed)
        my_error(ER_LOCK_DEADLOCK, MYF(0));
2752
      my_afree((void*) tables);
2753
      DBUG_RETURN(TRUE);
2754
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
2755
    thd->lock= merged_lock;
2756
    my_afree((void*) tables);
unknown's avatar
unknown committed
2757
  }
2758
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
2759 2760
}

2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
/**
  Add back a locked table to the locked list that we just removed from it.
  This is needed in CREATE OR REPLACE TABLE where we are dropping, creating
  and re-opening a locked table.

  @return 0  0k
  @return 1  error
*/

bool Locked_tables_list::restore_lock(THD *thd, TABLE_LIST *dst_table_list,
                                      TABLE *table, MYSQL_LOCK *lock)
{
  MYSQL_LOCK *merged_lock;
  DBUG_ENTER("restore_lock");
2775
  DBUG_ASSERT(!strcmp(dst_table_list->table_name.str, table->s->table_name.str));
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792

  /* Ensure we have the memory to add the table back */
  if (!(merged_lock= mysql_lock_merge(thd->lock, lock)))
    DBUG_RETURN(1);
  thd->lock= merged_lock;

  /* Link to the new table */
  dst_table_list->table= table;
  /*
    The lock type may have changed (normally it should not as create
    table will lock the table in write mode
  */
  dst_table_list->lock_type= table->reginfo.lock_type;
  table->pos_in_locked_tables= dst_table_list;

  add_back_last_deleted_lock(dst_table_list);

2793
  table->mdl_ticket->downgrade_lock(table->reginfo.lock_type >=
2794
                                    TL_FIRST_WRITE ?
2795 2796 2797
                                    MDL_SHARED_NO_READ_WRITE :
                                    MDL_SHARED_READ);

2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
  DBUG_RETURN(0);
}

/*
  Add back the last deleted lock structure.
  This should be followed by a call to reopen_tables() to
  open the table.
*/

void Locked_tables_list::add_back_last_deleted_lock(TABLE_LIST *dst_table_list)
{
  /* Link the lock back in the locked tables list */
  dst_table_list->prev_global= m_locked_tables_last;
  *m_locked_tables_last= dst_table_list;
  m_locked_tables_last= &dst_table_list->next_global;
  dst_table_list->next_global= 0;
  m_locked_tables_count++;
}

2817

2818
#ifndef DBUG_OFF
2819
/* Cause a spurious statement reprepare for debug purposes. */
2820
static bool inject_reprepare(THD *thd)
2821 2822 2823 2824 2825 2826 2827 2828 2829
{
  if (thd->m_reprepare_observer && thd->stmt_arena->is_reprepared == FALSE)
  {
    thd->m_reprepare_observer->report_error(thd);
    return TRUE;
  }

  return FALSE;
}
2830
#endif
2831

unknown's avatar
unknown committed
2832 2833 2834 2835
/**
  Compare metadata versions of an element obtained from the table
  definition cache and its corresponding node in the parse tree.

2836
  @details If the new and the old values mismatch, invoke
unknown's avatar
unknown committed
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
  Metadata_version_observer.
  At prepared statement prepare, all TABLE_LIST version values are
  NULL and we always have a mismatch. But there is no observer set
  in THD, and therefore no error is reported. Instead, we update
  the value in the parse tree, effectively recording the original
  version.
  At prepared statement execute, an observer may be installed.  If
  there is a version mismatch, we push an error and return TRUE.

  For conventional execution (no prepared statements), the
  observer is never installed.

  @sa Execute_observer
  @sa check_prepared_statement() to see cases when an observer is installed
2851
  @sa TABLE_LIST::is_the_same_definition()
2852
  @sa TABLE_SHARE::get_table_ref_id()
unknown's avatar
unknown committed
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863

  @param[in]      thd         used to report errors
  @param[in,out]  tables      TABLE_LIST instance created by the parser
                              Metadata version information in this object
                              is updated upon success.
  @param[in]      table_share an element from the table definition cache

  @retval  TRUE  an error, which has been reported
  @retval  FALSE success, version in TABLE_LIST has been updated
*/

2864
static bool
unknown's avatar
unknown committed
2865 2866 2867
check_and_update_table_version(THD *thd,
                               TABLE_LIST *tables, TABLE_SHARE *table_share)
{
2868 2869 2870 2871 2872 2873
  /*
    First, verify that TABLE_LIST was indeed *created by the parser* -
    it must be in the global TABLE_LIST list. Standalone TABLE_LIST objects
    created with TABLE_LIST::init_one_table() have a short life time and
    aren't linked anywhere.
  */
2874
  if (tables->prev_global && !tables->is_the_same_definition(thd, table_share))
unknown's avatar
unknown committed
2875
  {
2876 2877
    if (thd->m_reprepare_observer &&
        thd->m_reprepare_observer->report_error(thd))
unknown's avatar
unknown committed
2878 2879 2880 2881 2882 2883
    {
      /*
        Version of the table share is different from the
        previous execution of the prepared statement, and it is
        unacceptable for this SQLCOM. Error has been reported.
      */
2884
      DBUG_ASSERT(thd->is_error());
unknown's avatar
unknown committed
2885 2886
      return TRUE;
    }
2887
    /* Always maintain the latest version and type */
2888
    tables->set_table_ref_id(table_share);
unknown's avatar
unknown committed
2889
  }
2890

2891
  DBUG_EXECUTE_IF("reprepare_each_statement", return inject_reprepare(thd););
unknown's avatar
unknown committed
2892 2893 2894
  return FALSE;
}

2895

Konstantin Osipov's avatar
Konstantin Osipov committed
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
/**
  Compares versions of a stored routine obtained from the sp cache
  and the version used at prepare.

  @details If the new and the old values mismatch, invoke
  Metadata_version_observer.
  At prepared statement prepare, all Sroutine_hash_entry version values
  are NULL and we always have a mismatch. But there is no observer set
  in THD, and therefore no error is reported. Instead, we update
  the value in Sroutine_hash_entry, effectively recording the original
  version.
  At prepared statement execute, an observer may be installed.  If
  there is a version mismatch, we push an error and return TRUE.

  For conventional execution (no prepared statements), the
  observer is never installed.

  @param[in]      thd         used to report errors
  @param[in/out]  rt          pointer to stored routine entry in the
                              parse tree
  @param[in]      sp          pointer to stored routine cache entry.
                              Can be NULL if there is no such routine.
  @retval  TRUE  an error, which has been reported
  @retval  FALSE success, version in Sroutine_hash_entry has been updated
*/

static bool
check_and_update_routine_version(THD *thd, Sroutine_hash_entry *rt,
                                 sp_head *sp)
{
  ulong spc_version= sp_cache_version();
  /* sp is NULL if there is no such routine. */
  ulong version= sp ? sp->sp_cache_version() : spc_version;
  /*
    If the version in the parse tree is stale,
    or the version in the cache is stale and sp is not used,
    we need to reprepare.
    Sic: version != spc_version <--> sp is not NULL.
  */
  if (rt->m_sp_cache_version != version ||
      (version != spc_version && !sp->is_invoked()))
  {
    if (thd->m_reprepare_observer &&
        thd->m_reprepare_observer->report_error(thd))
    {
      /*
        Version of the sp cache is different from the
        previous execution of the prepared statement, and it is
        unacceptable for this SQLCOM. Error has been reported.
      */
      DBUG_ASSERT(thd->is_error());
      return TRUE;
    }
    /* Always maintain the latest cache version. */
    rt->m_sp_cache_version= version;
  }
  return FALSE;
}


2956 2957
/**
   Open view by getting its definition from disk (and table cache in future).
2958

2959 2960 2961
   @param thd               Thread handle
   @param table_list        TABLE_LIST with db, table_name & belong_to_view
   @param flags             Flags which modify how we open the view
2962

2963 2964 2965 2966 2967 2968
   @todo This function is needed for special handling of views under
         LOCK TABLES. We probably should get rid of it in long term.

   @return FALSE if success, TRUE - otherwise.
*/

2969
bool tdc_open_view(THD *thd, TABLE_LIST *table_list, uint flags)
2970 2971 2972
{
  TABLE not_used;
  TABLE_SHARE *share;
Sergei Golubchik's avatar
Sergei Golubchik committed
2973
  bool err= TRUE;
2974

2975
  if (!(share= tdc_acquire_share(thd, table_list, GTS_VIEW)))
2976
    return TRUE;
2977

2978
  DBUG_ASSERT(share->is_view);
2979

2980 2981 2982
  err= mysql_make_view(thd, share, table_list, (flags & OPEN_VIEW_NO_PARSE));

  if (!err && (flags & CHECK_METADATA_VERSION))
2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
  {
    /*
      Check TABLE_SHARE-version of view only if we have been instructed to do
      so. We do not need to check the version if we're executing CREATE VIEW or
      ALTER VIEW statements.

      In the future, this functionality should be moved out from
      tdc_open_view(), and  tdc_open_view() should became a part of a clean
      table-definition-cache interface.
    */
    if (check_and_update_table_version(thd, table_list, share))
Sergei Golubchik's avatar
Sergei Golubchik committed
2994
      goto ret;
2995 2996
  }

Sergei Golubchik's avatar
Sergei Golubchik committed
2997
ret:
2998
  tdc_release_share(share);
2999 3000

  return err;
3001 3002 3003 3004
}


/**
Konstantin Osipov's avatar
Konstantin Osipov committed
3005 3006
   Finalize the process of TABLE creation by loading table triggers
   and taking action if a HEAP table content was emptied implicitly.
3007 3008 3009 3010
*/

static bool open_table_entry_fini(THD *thd, TABLE_SHARE *share, TABLE *entry)
{
3011 3012
  if (Table_triggers_list::check_n_load(thd, &share->db,
                                        &share->table_name, entry, 0))
3013 3014
    return TRUE;

unknown's avatar
unknown committed
3015 3016 3017 3018 3019 3020 3021 3022 3023
  /*
    If we are here, there was no fatal error (but error may be still
    unitialized).
  */
  if (unlikely(entry->file->implicit_emptied))
  {
    entry->file->implicit_emptied= 0;
    if (mysql_bin_log.is_open())
    {
unknown's avatar
unknown committed
3024 3025
      char query_buf[2*FN_REFLEN + 21];
      String query(query_buf, sizeof(query_buf), system_charset_info);
3026

unknown's avatar
unknown committed
3027
      query.length(0);
Monty's avatar
Monty committed
3028
      query.append(STRING_WITH_LEN("DELETE FROM "));
3029
      append_identifier(thd, &query, &share->db);
Monty's avatar
Monty committed
3030
      query.append('.');
3031
      append_identifier(thd, &query, &share->table_name);
3032 3033 3034 3035 3036 3037 3038 3039

      /*
        we bypass thd->binlog_query() here,
        as it does a lot of extra work, that is simply wrong in this case
      */
      Query_log_event qinfo(thd, query.ptr(), query.length(),
                            FALSE, TRUE, TRUE, 0);
      if (mysql_bin_log.write(&qinfo))
3040
        return TRUE;
unknown's avatar
unknown committed
3041
    }
unknown's avatar
unknown committed
3042
  }
3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
  return FALSE;
}


/**
   Auxiliary routine which is used for performing automatical table repair.
*/

static bool auto_repair_table(THD *thd, TABLE_LIST *table_list)
{
  TABLE_SHARE *share;
3054
  TABLE entry;
3055
  bool result= TRUE;
3056 3057 3058

  thd->clear_error();

3059
  if (!(share= tdc_acquire_share(thd, table_list, GTS_TABLE)))
3060
    return result;
3061

3062
  DBUG_ASSERT(! share->is_view);
unknown's avatar
unknown committed
3063

3064
  if (open_table_from_share(thd, share, &table_list->alias,
3065 3066
                            HA_OPEN_KEYFILE | HA_TRY_READ_ONLY,
                            EXTRA_RECORD,
3067
                            ha_open_options | HA_OPEN_FOR_REPAIR,
3068 3069
                            &entry, FALSE) || ! entry.file ||
      (entry.file->is_crashed() && entry.file->ha_check_and_repair(thd)))
3070 3071 3072
  {
    /* Give right error message */
    thd->clear_error();
Guilhem Bichot's avatar
Guilhem Bichot committed
3073
    my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str);
3074 3075
    sql_print_error("Couldn't repair table: %s.%s", share->db.str,
                    share->table_name.str);
3076 3077
    if (entry.file)
      closefrm(&entry);
3078 3079 3080 3081
  }
  else
  {
    thd->clear_error();			// Clear error message
3082
    closefrm(&entry);
3083
    result= FALSE;
3084 3085
  }

3086
  tdc_remove_referenced_share(thd, share);
3087 3088 3089 3090
  return result;
}


Konstantin Osipov's avatar
Konstantin Osipov committed
3091 3092
/** Open_table_context */

3093
Open_table_context::Open_table_context(THD *thd, uint flags)
3094 3095
  :m_thd(thd),
   m_failed_table(NULL),
3096
   m_start_of_statement_svp(thd->mdl_context.mdl_savepoint()),
3097 3098 3099 3100
   m_timeout(flags & MYSQL_LOCK_IGNORE_TIMEOUT ?
             LONG_TIMEOUT : thd->variables.lock_wait_timeout),
   m_flags(flags),
   m_action(OT_NO_ACTION),
3101
   m_has_locks(thd->mdl_context.has_locks()),
3102
   m_has_protection_against_grl(0)
Konstantin Osipov's avatar
Konstantin Osipov committed
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
{}


/**
  Check if we can back-off and set back off action if we can.
  Otherwise report and return error.

  @retval  TRUE if back-off is impossible.
  @retval  FALSE if we can back off. Back off action has been set.
*/

bool
Open_table_context::
3116
request_backoff_action(enum_open_table_action action_arg,
3117
                       TABLE_LIST *table)
Konstantin Osipov's avatar
Konstantin Osipov committed
3118 3119
{
  /*
3120
    A back off action may be one of three kinds:
3121 3122 3123 3124

    * We met a broken table that needs repair, or a table that
      is not present on this MySQL server and needs re-discovery.
      To perform the action, we need an exclusive metadata lock on
3125 3126 3127 3128 3129
      the table. Acquiring X lock while holding other shared
      locks can easily lead to deadlocks. We rely on MDL deadlock
      detector to discover them. If this is a multi-statement
      transaction that holds metadata locks for completed statements,
      we should keep these locks after discovery/repair.
3130
      The action type in this case is OT_DISCOVER or OT_REPAIR.
3131 3132 3133
    * Our attempt to acquire an MDL lock lead to a deadlock,
      detected by the MDL deadlock detector. The current
      session was chosen a victim. If this is a multi-statement
3134 3135 3136 3137 3138
      transaction that holds metadata locks taken by completed
      statements, restarting locking for the current statement
      may lead to a livelock. Releasing locks of completed
      statements can not be done as will lead to violation
      of ACID. Thus, again, if m_has_locks is set,
3139 3140 3141 3142
      we report an error. Otherwise, when there are no metadata
      locks other than which belong to this statement, we can
      try to recover from error by releasing all locks and
      restarting the pre-locking.
3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168
      Similarly, a deadlock error can occur when the
      pre-locking process met a TABLE_SHARE that is being
      flushed, and unsuccessfully waited for the flush to
      complete. A deadlock in this case can happen, e.g.,
      when our session is holding a metadata lock that
      is being waited on by a session which is using
      the table which is being flushed. The only way
      to recover from this error is, again, to close all
      open tables, release all locks, and retry pre-locking.
      Action type name is OT_REOPEN_TABLES. Re-trying
      while holding some locks may lead to a livelock,
      and thus we don't do it.
    * Finally, this session has open TABLEs from different
      "generations" of the table cache. This can happen, e.g.,
      when, after this session has successfully opened one
      table used for a statement, FLUSH TABLES interfered and
      expelled another table used in it. FLUSH TABLES then
      blocks and waits on the table already opened by this
      statement.
      We detect this situation by ensuring that table cache
      version of all tables used in a statement is the same.
      If it isn't, all tables needs to be reopened.
      Note, that we can always perform a reopen in this case,
      even if we already have metadata locks, since we don't
      keep tables open between statements and a livelock
      is not possible.
Konstantin Osipov's avatar
Konstantin Osipov committed
3169
  */
3170
  if (action_arg == OT_BACKOFF_AND_RETRY && m_has_locks)
Konstantin Osipov's avatar
Konstantin Osipov committed
3171 3172
  {
    my_error(ER_LOCK_DEADLOCK, MYF(0));
3173
    m_thd->mark_transaction_to_rollback(true);
Konstantin Osipov's avatar
Konstantin Osipov committed
3174 3175
    return TRUE;
  }
3176 3177 3178 3179
  /*
    If auto-repair or discovery are requested, a pointer to table
    list element must be provided.
  */
3180 3181 3182
  if (table)
  {
    DBUG_ASSERT(action_arg == OT_DISCOVER || action_arg == OT_REPAIR);
3183
    m_failed_table= (TABLE_LIST*) m_thd->alloc(sizeof(TABLE_LIST));
3184 3185
    if (m_failed_table == NULL)
      return TRUE;
3186
    m_failed_table->init_one_table(&table->db, &table->table_name, &table->alias, TL_WRITE);
3187
    m_failed_table->open_strategy= table->open_strategy;
3188 3189 3190
    m_failed_table->mdl_request.set_type(MDL_EXCLUSIVE);
  }
  m_action= action_arg;
Konstantin Osipov's avatar
Konstantin Osipov committed
3191 3192 3193 3194
  return FALSE;
}


3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
/**
  An error handler to mark transaction to rollback on DEADLOCK error
  during DISCOVER / REPAIR.
*/
class MDL_deadlock_discovery_repair_handler : public Internal_error_handler
{
public:
  virtual bool handle_condition(THD *thd,
                                  uint sql_errno,
                                  const char* sqlstate,
3205
                                  Sql_condition::enum_warning_level *level,
3206
                                  const char* msg,
3207
                                  Sql_condition ** cond_hdl)
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
  {
    if (sql_errno == ER_LOCK_DEADLOCK)
    {
      thd->mark_transaction_to_rollback(true);
    }
    /*
      We have marked this transaction to rollback. Return false to allow
      error to be reported or handled by other handlers.
    */
    return false;
  }
};

3221
/**
Konstantin Osipov's avatar
Konstantin Osipov committed
3222
   Recover from failed attempt of open table by performing requested action.
3223

Konstantin Osipov's avatar
Konstantin Osipov committed
3224 3225
   @pre This function should be called only with "action" != OT_NO_ACTION
        and after having called @sa close_tables_for_reopen().
Konstantin Osipov's avatar
Konstantin Osipov committed
3226

3227 3228 3229 3230
   @retval FALSE - Success. One should try to open tables once again.
   @retval TRUE  - Error
*/

Konstantin Osipov's avatar
Konstantin Osipov committed
3231
bool
Sergei Golubchik's avatar
Sergei Golubchik committed
3232
Open_table_context::recover_from_failed_open()
3233 3234
{
  bool result= FALSE;
3235 3236 3237 3238 3239 3240
  MDL_deadlock_discovery_repair_handler handler;
  /*
    Install error handler to mark transaction to rollback on DEADLOCK error.
  */
  m_thd->push_internal_handler(&handler);

Konstantin Osipov's avatar
Konstantin Osipov committed
3241 3242
  /* Execute the action. */
  switch (m_action)
3243
  {
3244
    case OT_BACKOFF_AND_RETRY:
3245
    case OT_REOPEN_TABLES:
3246 3247
      break;
    case OT_DISCOVER:
3248 3249 3250 3251 3252
    case OT_REPAIR:
      if ((result= lock_table_names(m_thd, m_thd->lex->create_info,
                                    m_failed_table, NULL,
                                    get_timeout(), 0)))
        break;
3253

3254 3255
      tdc_remove_table(m_thd, m_failed_table->db.str,
                       m_failed_table->table_name.str);
3256

3257 3258 3259
      switch (m_action)
      {
        case OT_DISCOVER:
3260
        {
3261 3262
          m_thd->get_stmt_da()->clear_warning_info(m_thd->query_id);
          m_thd->clear_error();                 // Clear error message
3263

3264 3265
          No_such_table_error_handler no_such_table_handler;
          bool open_if_exists= m_failed_table->open_strategy == TABLE_LIST::OPEN_IF_EXISTS;
3266

3267 3268
          if (open_if_exists)
            m_thd->push_internal_handler(&no_such_table_handler);
Konstantin Osipov's avatar
Konstantin Osipov committed
3269

3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
          result= !tdc_acquire_share(m_thd, m_failed_table,
                                 GTS_TABLE | GTS_FORCE_DISCOVERY | GTS_NOLOCK);
          if (open_if_exists)
          {
            m_thd->pop_internal_handler();
            if (result && no_such_table_handler.safely_trapped_errors())
              result= FALSE;
          }
          break;
        }
        case OT_REPAIR:
          result= auto_repair_table(m_thd, m_failed_table);
          break;
        case OT_BACKOFF_AND_RETRY:
        case OT_REOPEN_TABLES:
        case OT_NO_ACTION:
          DBUG_ASSERT(0);
Konstantin Osipov's avatar
Konstantin Osipov committed
3287
      }
3288 3289 3290 3291 3292 3293 3294 3295
      /*
        Rollback to start of the current statement to release exclusive lock
        on table which was discovered but preserve locks from previous statements
        in current transaction.
      */
      m_thd->mdl_context.rollback_to_savepoint(start_of_statement_svp());
      break;
    case OT_NO_ACTION:
3296 3297
      DBUG_ASSERT(0);
  }
3298
  m_thd->pop_internal_handler();
3299 3300 3301 3302 3303 3304
  /*
    Reset the pointers to conflicting MDL request and the
    TABLE_LIST element, set when we need auto-discovery or repair,
    for safety.
  */
  m_failed_table= NULL;
3305 3306 3307 3308 3309
  /*
    Reset flag indicating that we have already acquired protection
    against GRL. It is no longer valid as the corresponding lock was
    released by close_tables_for_reopen().
  */
3310
  m_has_protection_against_grl= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
3311 3312
  /* Prepare for possible another back-off. */
  m_action= OT_NO_ACTION;
3313
  return result;
unknown's avatar
unknown committed
3314 3315
}

3316

3317 3318 3319
/*
  Return a appropriate read lock type given a table object.

3320 3321 3322
  @param thd              Thread context
  @param prelocking_ctx   Prelocking context.
  @param table_list       Table list element for table to be locked.
Sergei Golubchik's avatar
Sergei Golubchik committed
3323 3324
  @param routine_modifies_data
                          Some routine that is invoked by statement
3325
                          modifies data.
3326 3327 3328 3329 3330 3331 3332 3333

  @remark Due to a statement-based replication limitation, statements such as
          INSERT INTO .. SELECT FROM .. and CREATE TABLE .. SELECT FROM need
          to grab a TL_READ_NO_INSERT lock on the source table in order to
          prevent the replication of a concurrent statement that modifies the
          source table. If such a statement gets applied on the slave before
          the INSERT .. SELECT statement finishes, data on the master could
          differ from data on the slave and end-up with a discrepancy between
3334 3335 3336 3337
          the binary log and table state.
          This also applies to SELECT/SET/DO statements which use stored
          functions. Calls to such functions are going to be logged as a
          whole and thus should be serialized against concurrent changes
3338 3339 3340 3341 3342 3343 3344
          to tables used by those functions. This is avoided when functions
          do not modify data but only read it, since in this case nothing is
          written to the binary log. Argument routine_modifies_data
          denotes the same. So effectively, if the statement is not a
          update query and routine_modifies_data is false, then
          prelocking_placeholder does not take importance.

3345 3346 3347 3348 3349
          Furthermore, this does not apply to I_S and log tables as it's
          always unsafe to replicate such tables under statement-based
          replication as the table on the slave might contain other data
          (ie: general_log is enabled on the slave). The statement will
          be marked as unsafe for SBR in decide_logging_format().
3350 3351 3352 3353 3354
  @remark Note that even in prelocked mode it is important to correctly
          determine lock type value. In this mode lock type is passed to
          handler::start_stmt() method and can be used by storage engine,
          for example, to determine what kind of row locks it should acquire
          when reading data from the table.
3355 3356
*/

3357 3358
thr_lock_type read_lock_type_for_table(THD *thd,
                                       Query_tables_list *prelocking_ctx,
3359 3360
                                       TABLE_LIST *table_list,
                                       bool routine_modifies_data)
3361
{
3362 3363 3364 3365 3366
  /*
    In cases when this function is called for a sub-statement executed in
    prelocked mode we can't rely on OPTION_BIN_LOG flag in THD::options
    bitmap to determine that binary logging is turned on as this bit can
    be cleared before executing sub-statement. So instead we have to look
3367
    at THD::variables::sql_log_bin member.
3368
  */
3369
  bool log_on= mysql_bin_log.is_open() && thd->variables.sql_log_bin;
3370
  if ((log_on == FALSE) || (thd->wsrep_binlog_format() == BINLOG_FORMAT_ROW) ||
3371 3372 3373
      (table_list->table->s->table_category == TABLE_CATEGORY_LOG) ||
      (table_list->table->s->table_category == TABLE_CATEGORY_PERFORMANCE) ||
      !(is_update_query(prelocking_ctx->sql_command) ||
3374
        (routine_modifies_data && table_list->prelocking_placeholder) ||
3375
        (thd->locked_tables_mode > LTM_LOCK_TABLES)))
3376 3377 3378 3379 3380 3381
    return TL_READ;
  else
    return TL_READ_NO_INSERT;
}


3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
/*
  Extend the prelocking set with tables and routines used by a routine.

  @param[in]  thd                   Thread context.
  @param[in]  rt                    Element of prelocking set to be processed.
  @param[in]  ot_ctx                Context of open_table used to recover from
                                    locking failures.
  @retval false  Success.
  @retval true   Failure (Conflicting metadata lock, OOM, other errors).
*/
static bool
sp_acquire_mdl(THD *thd, Sroutine_hash_entry *rt, Open_table_context *ot_ctx)
{
  DBUG_ENTER("sp_acquire_mdl");
  /*
    Since we acquire only shared lock on routines we don't
    need to care about global intention exclusive locks.
  */
  DBUG_ASSERT(rt->mdl_request.type == MDL_SHARED);

  /*
    Waiting for a conflicting metadata lock to go away may
    lead to a deadlock, detected by MDL subsystem.
    If possible, we try to resolve such deadlocks by releasing all
    metadata locks and restarting the pre-locking process.
    To prevent the error from polluting the diagnostics area
    in case of successful resolution, install a special error
    handler for ER_LOCK_DEADLOCK error.
  */
  MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);

  thd->push_internal_handler(&mdl_deadlock_handler);
  bool result= thd->mdl_context.acquire_lock(&rt->mdl_request,
                                             ot_ctx->get_timeout());
  thd->pop_internal_handler();

  DBUG_RETURN(result);
}


unknown's avatar
unknown committed
3422
/*
3423 3424 3425
  Handle element of prelocking set other than table. E.g. cache routine
  and, if prelocking strategy prescribes so, extend the prelocking set
  with tables and routines used by it.
Konstantin Osipov's avatar
Konstantin Osipov committed
3426

3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441
  @param[in]  thd                   Thread context.
  @param[in]  prelocking_ctx        Prelocking context.
  @param[in]  rt                    Element of prelocking set to be processed.
  @param[in]  prelocking_strategy   Strategy which specifies how the
                                    prelocking set should be extended when
                                    one of its elements is processed.
  @param[in]  has_prelocking_list   Indicates that prelocking set/list for
                                    this statement has already been built.
  @param[in]  ot_ctx                Context of open_table used to recover from
                                    locking failures.
  @param[out] need_prelocking       Set to TRUE if it was detected that this
                                    statement will require prelocked mode for
                                    its execution, not touched otherwise.
  @param[out] routine_modifies_data Set to TRUE if it was detected that this
                                    routine does modify table data.
Konstantin Osipov's avatar
Konstantin Osipov committed
3442 3443 3444 3445 3446 3447

  @retval FALSE  Success.
  @retval TRUE   Failure (Conflicting metadata lock, OOM, other errors).
*/

static bool
3448 3449 3450
open_and_process_routine(THD *thd, Query_tables_list *prelocking_ctx,
                         Sroutine_hash_entry *rt,
                         Prelocking_strategy *prelocking_strategy,
Konstantin Osipov's avatar
Konstantin Osipov committed
3451 3452
                         bool has_prelocking_list,
                         Open_table_context *ot_ctx,
3453
                         bool *need_prelocking, bool *routine_modifies_data)
Konstantin Osipov's avatar
Konstantin Osipov committed
3454
{
Konstantin Osipov's avatar
Konstantin Osipov committed
3455
  MDL_key::enum_mdl_namespace mdl_type= rt->mdl_request.key.mdl_namespace();
3456
  DBUG_ENTER("open_and_process_routine");
Konstantin Osipov's avatar
Konstantin Osipov committed
3457

3458 3459
  *routine_modifies_data= false;

Konstantin Osipov's avatar
Konstantin Osipov committed
3460
  switch (mdl_type)
3461
  {
3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
  case MDL_key::PACKAGE_BODY:
    DBUG_ASSERT(rt != (Sroutine_hash_entry*)prelocking_ctx->sroutines_list.first);
    /*
      No need to cache the package body itself.
      It gets cached during open_and_process_routine()
      for the first used package routine. See the package related code
      in the "case" below.
    */
    if (sp_acquire_mdl(thd, rt, ot_ctx))
      DBUG_RETURN(TRUE);
    break;
Konstantin Osipov's avatar
Konstantin Osipov committed
3473 3474
  case MDL_key::FUNCTION:
  case MDL_key::PROCEDURE:
Konstantin Osipov's avatar
Konstantin Osipov committed
3475
    {
3476
      sp_head *sp;
Konstantin Osipov's avatar
Konstantin Osipov committed
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
      /*
        Try to get MDL lock on the routine.
        Note that we do not take locks on top-level CALLs as this can
        lead to a deadlock. Not locking top-level CALLs does not break
        the binlog as only the statements in the called procedure show
        up there, not the CALL itself.
      */
      if (rt != (Sroutine_hash_entry*)prelocking_ctx->sroutines_list.first ||
          mdl_type != MDL_key::PROCEDURE)
      {
3487 3488 3489 3490
        /*
          TODO: If this is a package routine, we should not put MDL
          TODO: on the routine itself. We should put only the package MDL.
        */
3491
        if (sp_acquire_mdl(thd, rt, ot_ctx))
Konstantin Osipov's avatar
Konstantin Osipov committed
3492
          DBUG_RETURN(TRUE);
3493

Konstantin Osipov's avatar
Konstantin Osipov committed
3494
        /* Ensures the routine is up-to-date and cached, if exists. */
3495
        if (rt->sp_cache_routine(thd, has_prelocking_list, &sp))
Konstantin Osipov's avatar
Konstantin Osipov committed
3496
          DBUG_RETURN(TRUE);
Konstantin Osipov's avatar
Konstantin Osipov committed
3497

Konstantin Osipov's avatar
Konstantin Osipov committed
3498 3499 3500 3501 3502
        /* Remember the version of the routine in the parse tree. */
        if (check_and_update_routine_version(thd, rt, sp))
          DBUG_RETURN(TRUE);

        /* 'sp' is NULL when there is no such routine. */
3503
        if (sp)
Konstantin Osipov's avatar
Konstantin Osipov committed
3504
        {
3505 3506 3507
          *routine_modifies_data= sp->modifies_data();

          if (!has_prelocking_list)
3508
          {
3509 3510
            prelocking_strategy->handle_routine(thd, prelocking_ctx, rt, sp,
                                                need_prelocking);
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
            if (sp->m_parent)
            {
              /*
                If it's a package routine, we need also to handle the
                package body, as its initialization section can use
                some tables and routine calls.
                TODO: Only package public routines actually need this.
                TODO: Skip package body handling for private routines.
              */
              *routine_modifies_data|= sp->m_parent->modifies_data();
              prelocking_strategy->handle_routine(thd, prelocking_ctx, rt,
                                                  sp->m_parent,
                                                  need_prelocking);
            }
          }
Konstantin Osipov's avatar
Konstantin Osipov committed
3526 3527 3528
        }
      }
      else
3529
      {
Konstantin Osipov's avatar
Konstantin Osipov committed
3530 3531 3532 3533 3534 3535
        /*
          If it's a top level call, just make sure we have a recent
          version of the routine, if it exists.
          Validating routine version is unnecessary, since CALL
          does not affect the prepared statement prelocked list.
        */
3536
        if (rt->sp_cache_routine(thd, false, &sp))
3537
          DBUG_RETURN(TRUE);
Konstantin Osipov's avatar
Konstantin Osipov committed
3538 3539
      }
    }
3540
    break;
Konstantin Osipov's avatar
Konstantin Osipov committed
3541
  case MDL_key::TRIGGER:
Konstantin Osipov's avatar
Konstantin Osipov committed
3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
    /**
      We add trigger entries to lex->sroutines_list, but we don't
      load them here. The trigger entry is only used when building
      a transitive closure of objects used in a statement, to avoid
      adding to this closure objects that are used in the trigger more
      than once.
      E.g. if a trigger trg refers to table t2, and the trigger table t1
      is used multiple times in the statement (say, because it's used in
      function f1() twice), we will only add t2 once to the list of
      tables to prelock.

      We don't take metadata locks on triggers either: they are protected
      by a respective lock on the table, on which the trigger is defined.

      The only two cases which give "trouble" are SHOW CREATE TRIGGER
      and DROP TRIGGER statements. For these, statement syntax doesn't
      specify the table on which this trigger is defined, so we have
      to make a "dirty" read in the data dictionary to find out the
      table name. Once we discover the table name, we take a metadata
      lock on it, and this protects all trigger operations.
      Of course the table, in theory, may disappear between the dirty
      read and metadata lock acquisition, but in that case we just return
      a run-time error.

      Grammar of other trigger DDL statements (CREATE, DROP) requires
      the table to be specified explicitly, so we use the table metadata
      lock to protect trigger metadata in these statements. Similarly, in
      DML we always use triggers together with their tables, and thus don't
      need to take separate metadata locks on them.
    */
3572 3573 3574 3575
    break;
  default:
    /* Impossible type value. */
    DBUG_ASSERT(0);
Konstantin Osipov's avatar
Konstantin Osipov committed
3576 3577 3578 3579
  }
  DBUG_RETURN(FALSE);
}

Sergei Golubchik's avatar
Sergei Golubchik committed
3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
/*
  If we are not already in prelocked mode and extended table list is not
  yet built we might have to build the prelocking set for this statement.

  Since currently no prelocking strategy prescribes doing anything for
  tables which are only read, we do below checks only if table is going
  to be changed.
*/
bool extend_table_list(THD *thd, TABLE_LIST *tables,
                       Prelocking_strategy *prelocking_strategy,
                       bool has_prelocking_list)
{
  bool error= false;
  LEX *lex= thd->lex;
3594
  bool maybe_need_prelocking=
3595
    (tables->updating && tables->lock_type >= TL_FIRST_WRITE)
3596
    || thd->lex->default_used;
Sergei Golubchik's avatar
Sergei Golubchik committed
3597 3598

  if (thd->locked_tables_mode <= LTM_LOCK_TABLES &&
3599
      ! has_prelocking_list && maybe_need_prelocking)
Sergei Golubchik's avatar
Sergei Golubchik committed
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
  {
    bool need_prelocking= FALSE;
    TABLE_LIST **save_query_tables_last= lex->query_tables_last;
    /*
      Extend statement's table list and the prelocking set with
      tables and routines according to the current prelocking
      strategy.

      For example, for DML statements we need to add tables and routines
      used by triggers which are going to be invoked for this element of
      table list and also add tables required for handling of foreign keys.
    */
    error= prelocking_strategy->handle_table(thd, lex, tables,
                                             &need_prelocking);

    if (need_prelocking && ! lex->requires_prelocking())
      lex->mark_as_requiring_prelocking(save_query_tables_last);
  }
  return error;
}

Konstantin Osipov's avatar
Konstantin Osipov committed
3621

3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646
/**
  Handle table list element by obtaining metadata lock, opening table or view
  and, if prelocking strategy prescribes so, extending the prelocking set with
  tables and routines used by it.

  @param[in]     thd                  Thread context.
  @param[in]     lex                  LEX structure for statement.
  @param[in]     tables               Table list element to be processed.
  @param[in,out] counter              Number of tables which are open.
  @param[in]     flags                Bitmap of flags to modify how the tables
                                      will be open, see open_table() description
                                      for details.
  @param[in]     prelocking_strategy  Strategy which specifies how the
                                      prelocking set should be extended
                                      when table or view is processed.
  @param[in]     has_prelocking_list  Indicates that prelocking set/list for
                                      this statement has already been built.
  @param[in]     ot_ctx               Context used to recover from a failed
                                      open_table() attempt.

  @retval  FALSE  Success.
  @retval  TRUE   Error, reported unless there is a chance to recover from it.
*/

static bool
Sergei Golubchik's avatar
Sergei Golubchik committed
3647
open_and_process_table(THD *thd, TABLE_LIST *tables, uint *counter, uint flags,
3648
                       Prelocking_strategy *prelocking_strategy,
3649
                       bool has_prelocking_list, Open_table_context *ot_ctx)
3650 3651 3652
{
  bool error= FALSE;
  bool safe_to_ignore_table= FALSE;
Sergei Golubchik's avatar
Sergei Golubchik committed
3653
  LEX *lex= thd->lex;
3654
  DBUG_ENTER("open_and_process_table");
3655
  DEBUG_SYNC(thd, "open_and_process_table");
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665

  /*
    Ignore placeholders for derived tables. After derived tables
    processing, link to created temporary table will be put here.
    If this is derived table for view then we still want to process
    routines used by this view.
  */
  if (tables->derived)
  {
    if (!tables->view)
3666 3667 3668
    {
      if (!tables->is_derived())
        tables->set_derived();
3669
      goto end;
3670
    }
3671 3672 3673 3674 3675 3676
    /*
      We restore view's name and database wiped out by derived tables
      processing and fall back to standard open process in order to
      obtain proper metadata locks and do other necessary steps like
      stored routine processing.
    */
3677 3678
    tables->db= tables->view_db;
    tables->table_name= tables->view_name;
3679
  }
3680

Marko Mäkelä's avatar
Marko Mäkelä committed
3681
  if (!tables->derived && is_infoschema_db(&tables->db))
3682 3683 3684 3685 3686
  {
    /*
      Check whether the information schema contains a table
      whose name is tables->schema_table_name
    */
3687
    ST_SCHEMA_TABLE *schema_table= tables->schema_table;
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
    if (!schema_table ||
        (schema_table->hidden &&
         ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 ||
          /*
            this check is used for show columns|keys from I_S hidden table
          */
          lex->sql_command == SQLCOM_SHOW_FIELDS ||
          lex->sql_command == SQLCOM_SHOW_KEYS)))
    {
      my_error(ER_UNKNOWN_TABLE, MYF(0),
3698
               tables->table_name.str, INFORMATION_SCHEMA_NAME.str);
3699 3700 3701
      DBUG_RETURN(1);
    }
  }
3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715
  /*
    If this TABLE_LIST object is a placeholder for an information_schema
    table, create a temporary table to represent the information_schema
    table in the query. Do not fill it yet - will be filled during
    execution.
  */
  if (tables->schema_table)
  {
    /*
      If this information_schema table is merged into a mergeable
      view, ignore it for now -- it will be filled when its respective
      TABLE_LIST is processed. This code works only during re-execution.
    */
    if (tables->view)
3716
    {
3717
      MDL_ticket *mdl_ticket;
3718 3719 3720 3721
      /*
        We still need to take a MDL lock on the merged view to protect
        it from concurrent changes.
      */
3722 3723 3724
      if (!open_table_get_mdl_lock(thd, ot_ctx, &tables->mdl_request,
                                   flags, &mdl_ticket) &&
          mdl_ticket != NULL)
3725 3726 3727 3728 3729
        goto process_view_routines;
      /* Fall-through to return error. */
    }
    else if (!mysql_schema_table(thd, lex, tables) &&
             !check_and_update_table_version(thd, tables, tables->table->s))
3730 3731 3732 3733 3734 3735
    {
      goto end;
    }
    error= TRUE;
    goto end;
  }
3736 3737 3738 3739 3740 3741 3742 3743

  if (tables->table_function)
  {
    if (!create_table_for_function(thd, tables))
      error= TRUE;
    goto end;
  }

3744
  DBUG_PRINT("tcache", ("opening table: '%s'.'%s'  item: %p",
3745
                        tables->db.str, tables->table_name.str, tables));
3746 3747
  (*counter)++;

3748 3749 3750 3751 3752 3753 3754 3755
  /*
    Not a placeholder: must be a base/temporary table or a view. Let us open it.
  */
  if (tables->table)
  {
    /*
      If this TABLE_LIST object has an associated open TABLE object
      (TABLE_LIST::table is not NULL), that TABLE object must be a pre-opened
3756
      temporary table or SEQUENCE (see sequence_insert()).
3757
    */
3758
    DBUG_ASSERT(is_temporary_table(tables) || tables->table->s->sequence);
3759 3760
    if (tables->sequence &&
        tables->table->s->table_type != TABLE_TYPE_SEQUENCE)
3761
    {
3762 3763
      my_error(ER_NOT_SEQUENCE, MYF(0), tables->db.str, tables->alias.str);
      DBUG_RETURN(true);
3764
    }
3765 3766
  }
  else if (tables->open_type == OT_TEMPORARY_ONLY)
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780
  {
    /*
      OT_TEMPORARY_ONLY means that we are in CREATE TEMPORARY TABLE statement.
      Also such table list element can't correspond to prelocking placeholder
      or to underlying table of merge table.
      So existing temporary table should have been preopened by this moment
      and we can simply continue without trying to open temporary or base
      table.
    */
    DBUG_ASSERT(tables->open_strategy);
    DBUG_ASSERT(!tables->prelocking_placeholder);
    DBUG_ASSERT(!tables->parent_l);
    DBUG_RETURN(0);
  }
3781

3782
  /* Not a placeholder: must be a base table or a view. Let us open it. */
3783 3784 3785 3786 3787 3788 3789 3790
  if (tables->prelocking_placeholder)
  {
    /*
      For the tables added by the pre-locking code, attempt to open
      the table but fail silently if the table does not exist.
      The real failure will occur when/if a statement attempts to use
      that table.
    */
3791 3792
    No_such_table_error_handler no_such_table_handler;
    thd->push_internal_handler(&no_such_table_handler);
unknown's avatar
unknown committed
3793 3794 3795 3796 3797 3798 3799 3800

    /*
      We're opening a table from the prelocking list.

      Since this table list element might have been added after pre-opening
      of temporary tables we have to try to open temporary table for it.

      We can't simply skip this table list element and postpone opening of
3801
      temporary table till the execution of substatement for several reasons:
unknown's avatar
unknown committed
3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
      - Temporary table can be a MERGE table with base underlying tables,
        so its underlying tables has to be properly open and locked at
        prelocking stage.
      - Temporary table can be a MERGE table and we might be in PREPARE
        phase for a prepared statement. In this case it is important to call
        HA_ATTACH_CHILDREN for all merge children.
        This is necessary because merge children remember "TABLE_SHARE ref type"
        and "TABLE_SHARE def version" in the HA_ATTACH_CHILDREN operation.
        If HA_ATTACH_CHILDREN is not called, these attributes are not set.
        Then, during the first EXECUTE, those attributes need to be updated.
        That would cause statement re-preparing (because changing those
        attributes during EXECUTE is caught by THD::m_reprepare_observers).
        The problem is that since those attributes are not set in merge
        children, another round of PREPARE will not help.
    */
3817 3818 3819
    if (!thd->has_temporary_tables() ||
        (!(error= thd->open_temporary_table(tables)) &&
         !tables->table))
3820
      error= open_table(thd, tables, ot_ctx);
unknown's avatar
unknown committed
3821

3822
    thd->pop_internal_handler();
3823
    safe_to_ignore_table= no_such_table_handler.safely_trapped_errors();
3824
  }
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834
  else if (tables->parent_l && (thd->open_options & HA_OPEN_FOR_REPAIR))
  {
    /*
      Also fail silently for underlying tables of a MERGE table if this
      table is opened for CHECK/REPAIR TABLE statement. This is needed
      to provide complete list of problematic underlying tables in
      CHECK/REPAIR TABLE output.
    */
    Repair_mrg_table_error_handler repair_mrg_table_handler;
    thd->push_internal_handler(&repair_mrg_table_handler);
unknown's avatar
unknown committed
3835

3836 3837 3838
    if (!thd->has_temporary_tables() ||
        (!(error= thd->open_temporary_table(tables)) &&
         !tables->table))
3839
      error= open_table(thd, tables, ot_ctx);
unknown's avatar
unknown committed
3840

3841 3842 3843
    thd->pop_internal_handler();
    safe_to_ignore_table= repair_mrg_table_handler.safely_trapped_errors();
  }
3844
  else
unknown's avatar
unknown committed
3845 3846 3847 3848 3849 3850 3851 3852
  {
    if (tables->parent_l)
    {
      /*
        Even if we are opening table not from the prelocking list we
        still might need to look for a temporary table if this table
        list element corresponds to underlying table of a merge table.
      */
3853 3854
      if (thd->has_temporary_tables())
        error= thd->open_temporary_table(tables);
unknown's avatar
unknown committed
3855 3856 3857
    }

    if (!error && !tables->table)
3858
      error= open_table(thd, tables, ot_ctx);
unknown's avatar
unknown committed
3859
  }
3860

3861
  if (unlikely(error))
3862
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
3863
    if (! ot_ctx->can_recover_from_failed_open() && safe_to_ignore_table)
3864 3865
    {
      DBUG_PRINT("info", ("open_table: ignoring table '%s'.'%s'",
3866
                          tables->db.str, tables->alias.str));
3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911
      error= FALSE;
    }
    goto end;
  }

  /*
    We can't rely on simple check for TABLE_LIST::view to determine
    that this is a view since during re-execution we might reopen
    ordinary table in place of view and thus have TABLE_LIST::view
    set from repvious execution and TABLE_LIST::table set from
    current.
  */
  if (!tables->table && tables->view)
  {
    /* VIEW placeholder */
    (*counter)--;

    /*
      tables->next_global list consists of two parts:
      1) Query tables and underlying tables of views.
      2) Tables used by all stored routines that this statement invokes on
         execution.
      We need to know where the bound between these two parts is. If we've
      just opened a view, which was the last table in part #1, and it
      has added its base tables after itself, adjust the boundary pointer
      accordingly.
    */
    if (lex->query_tables_own_last == &(tables->next_global) &&
        tables->view->query_tables)
      lex->query_tables_own_last= tables->view->query_tables_last;
    /*
      Let us free memory used by 'sroutines' hash here since we never
      call destructor for this LEX.
    */
    my_hash_free(&tables->view->sroutines);
    goto process_view_routines;
  }

  /*
    Special types of open can succeed but still don't set
    TABLE_LIST::table to anything.
  */
  if (tables->open_strategy && !tables->table)
    goto end;

3912 3913 3914 3915 3916 3917
  /* Check and update metadata version of a base table. */
  error= check_and_update_table_version(thd, tables, tables->table->s);

  if (unlikely(error))
    goto end;

Sergei Golubchik's avatar
Sergei Golubchik committed
3918
  error= extend_table_list(thd, tables, prelocking_strategy, has_prelocking_list);
3919
  if (unlikely(error))
Sergei Golubchik's avatar
Sergei Golubchik committed
3920
    goto end;
3921

3922
  /* Copy grant information from TABLE_LIST instance to TABLE one. */
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956
  tables->table->grant= tables->grant;

  /*
    After opening a MERGE table add the children to the query list of
    tables, so that they are opened too.
    Note that placeholders don't have the handler open.
  */
  /* MERGE tables need to access parent and child TABLE_LISTs. */
  DBUG_ASSERT(tables->table->pos_in_table_list == tables);
  /* Non-MERGE tables ignore this call. */
  if (tables->table->file->extra(HA_EXTRA_ADD_CHILDREN_LIST))
  {
    error= TRUE;
    goto end;
  }

process_view_routines:
  /*
    Again we may need cache all routines used by this view and add
    tables used by them to table list.
  */
  if (tables->view &&
      thd->locked_tables_mode <= LTM_LOCK_TABLES &&
      ! has_prelocking_list)
  {
    bool need_prelocking= FALSE;
    TABLE_LIST **save_query_tables_last= lex->query_tables_last;

    error= prelocking_strategy->handle_view(thd, lex, tables,
                                            &need_prelocking);

    if (need_prelocking && ! lex->requires_prelocking())
      lex->mark_as_requiring_prelocking(save_query_tables_last);

3957
    if (unlikely(error))
3958 3959 3960 3961 3962 3963 3964 3965
      goto end;
  }

end:
  DBUG_RETURN(error);
}


3966 3967 3968 3969 3970 3971 3972 3973 3974 3975
static bool upgrade_lock_if_not_exists(THD *thd,
                                       const DDL_options_st &create_info,
                                       TABLE_LIST *create_table,
                                       ulong lock_wait_timeout)
{
  DBUG_ENTER("upgrade_lock_if_not_exists");

  if (thd->lex->sql_command == SQLCOM_CREATE_TABLE ||
      thd->lex->sql_command == SQLCOM_CREATE_SEQUENCE)
  {
3976
    DEBUG_SYNC(thd,"create_table_before_check_if_exists");
3977
    if (!create_info.or_replace() &&
3978
        ha_table_exists(thd, &create_table->db, &create_table->table_name,
3979
                        NULL, NULL, &create_table->db_type))
3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
    {
      if (create_info.if_not_exists())
      {
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                            ER_TABLE_EXISTS_ERROR,
                            ER_THD(thd, ER_TABLE_EXISTS_ERROR),
                            create_table->table_name.str);
      }
      else
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name.str);
      DBUG_RETURN(true);
    }
    DBUG_RETURN(thd->mdl_context.upgrade_shared_lock(
                                   create_table->mdl_request.ticket,
                                   MDL_EXCLUSIVE,
                                   lock_wait_timeout));
  }
  DBUG_RETURN(false);
}


4001
/**
4002 4003
  Acquire upgradable (SNW, SNRW) metadata locks on tables used by
  LOCK TABLES or by a DDL statement. Under LOCK TABLES, we can't take
4004
  new locks, so use open_tables_check_upgradable_mdl() instead.
4005

4006
  @param thd               Thread context.
4007
  @param options           DDL options.
4008 4009 4010 4011 4012 4013
  @param tables_start      Start of list of tables on which upgradable locks
                           should be acquired.
  @param tables_end        End of list of tables.
  @param lock_wait_timeout Seconds to wait before timeout.
  @param flags             Bitmap of flags to modify how the tables will be
                           open, see open_table() description for details.
4014 4015

  @retval FALSE  Success.
4016 4017
  @retval TRUE   Failure (e.g. connection was killed) or table existed
	         for a CREATE TABLE.
4018 4019

  @notes
4020 4021 4022 4023 4024 4025 4026
  In case of CREATE TABLE we avoid a wait for tables that are in use
  by first trying to do a meta data lock with timeout == 0.  If we get a
  timeout we will check if table exists (it should) and retry with
  normal timeout if it didn't exists.
  Note that for CREATE TABLE IF EXISTS we only generate a warning
  but still return TRUE (to abort the calling open_table() function).
  On must check THD->is_error() if one wants to distinguish between warning
4027 4028
  and error.  If table existed, tables_start->db_type is set to the handlerton
  for the found table.
4029 4030
*/

4031
bool
4032
lock_table_names(THD *thd, const DDL_options_st &options,
4033 4034
                 TABLE_LIST *tables_start, TABLE_LIST *tables_end,
                 ulong lock_wait_timeout, uint flags)
4035 4036 4037
{
  MDL_request_list mdl_requests;
  TABLE_LIST *table;
4038
  MDL_request global_request;
4039
  MDL_savepoint mdl_savepoint;
4040
  DBUG_ENTER("lock_table_names");
4041

4042 4043
  DBUG_ASSERT(!thd->locked_tables_mode);

4044 4045 4046
  for (table= tables_start; table && table != tables_end;
       table= table->next_global)
  {
Monty's avatar
Monty committed
4047 4048
    DBUG_PRINT("info", ("mdl_request.type: %d  open_type: %d",
                        table->mdl_request.type, table->open_type));
4049
    if (table->mdl_request.type < MDL_SHARED_UPGRADABLE ||
4050
        table->mdl_request.type == MDL_SHARED_READ_ONLY ||
4051 4052
        table->open_type == OT_TEMPORARY_ONLY ||
        (table->open_type == OT_TEMPORARY_OR_BASE && is_temporary_table(table)))
4053
    {
4054 4055
      continue;
    }
4056

Michael Widenius's avatar
Michael Widenius committed
4057
    /* Write lock on normal tables is not allowed in a read only transaction. */
4058 4059 4060 4061
    if (thd->tx_read_only)
    {
      my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
      DBUG_RETURN(true);
4062
    }
4063

4064 4065 4066 4067 4068 4069
    /* Scoped locks: Take intention exclusive locks on all involved schemas. */
    if (!(flags & MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK))
    {
      MDL_request *schema_request= new (thd->mem_root) MDL_request;
      if (schema_request == NULL)
        DBUG_RETURN(TRUE);
4070 4071
      MDL_REQUEST_INIT(schema_request, MDL_key::SCHEMA, table->db.str, "",
                       MDL_INTENTION_EXCLUSIVE, MDL_TRANSACTION);
4072 4073
      mdl_requests.push_front(schema_request);
    }
4074 4075

    mdl_requests.push_front(&table->mdl_request);
4076 4077
  }

4078 4079 4080
  if (mdl_requests.is_empty())
    DBUG_RETURN(FALSE);

4081
  if (flags & MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)
4082
  {
4083 4084 4085 4086
    DBUG_RETURN(thd->mdl_context.acquire_locks(&mdl_requests,
                                               lock_wait_timeout) ||
                upgrade_lock_if_not_exists(thd, options, tables_start,
                                           lock_wait_timeout));
4087 4088
  }

4089 4090 4091
  /* Protect this statement against concurrent BACKUP STAGE or FTWRL. */
  if (thd->has_read_only_protection())
    DBUG_RETURN(true);
4092

4093 4094
  MDL_REQUEST_INIT(&global_request, MDL_key::BACKUP, "", "", MDL_BACKUP_DDL,
                   MDL_STATEMENT);
4095
  mdl_savepoint= thd->mdl_context.mdl_savepoint();
4096

4097 4098 4099 4100 4101 4102
  while (!thd->mdl_context.acquire_locks(&mdl_requests, lock_wait_timeout) &&
         !upgrade_lock_if_not_exists(thd, options, tables_start,
                                     lock_wait_timeout) &&
         !thd->mdl_context.try_acquire_lock(&global_request))
  {
    if (global_request.ticket)
4103
    {
4104 4105
      thd->mdl_backup_ticket= global_request.ticket;
      DBUG_RETURN(false);
4106
    }
4107

4108
    /*
4109 4110
      There is ongoing or pending BACKUP STAGE or FTWRL.
      Wait until it finishes and re-try.
4111
    */
4112 4113 4114 4115 4116 4117 4118 4119 4120 4121
    thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
    if (thd->mdl_context.acquire_lock(&global_request, lock_wait_timeout))
      break;
    thd->mdl_context.rollback_to_savepoint(mdl_savepoint);

    /* Reset tickets for all acquired locks */
    global_request.ticket= 0;
    MDL_request_list::Iterator it(mdl_requests);
    while (auto mdl_request= it++)
      mdl_request->ticket= 0;
4122
  }
4123
  DBUG_RETURN(true);
4124 4125 4126
}


4127 4128 4129 4130 4131 4132 4133 4134 4135
/**
  Check for upgradable (SNW, SNRW) metadata locks on tables to be opened
  for a DDL statement. Under LOCK TABLES, we can't take new locks, so we
  must check if appropriate locks were pre-acquired.

  @param thd           Thread context.
  @param tables_start  Start of list of tables on which upgradable locks
                       should be searched for.
  @param tables_end    End of list of tables.
4136 4137
  @param flags         Bitmap of flags to modify how the tables will be
                       open, see open_table() description for details.
4138 4139 4140 4141 4142 4143 4144

  @retval FALSE  Success.
  @retval TRUE   Failure (e.g. connection was killed)
*/

static bool
open_tables_check_upgradable_mdl(THD *thd, TABLE_LIST *tables_start,
4145
                                 TABLE_LIST *tables_end, uint flags)
4146 4147 4148 4149 4150 4151 4152 4153
{
  TABLE_LIST *table;

  DBUG_ASSERT(thd->locked_tables_mode);

  for (table= tables_start; table && table != tables_end;
       table= table->next_global)
  {
4154 4155 4156 4157 4158
    /*
      Check below needs to be updated if this function starts
      called for SRO locks.
    */
    DBUG_ASSERT(table->mdl_request.type != MDL_SHARED_READ_ONLY);
4159 4160 4161
    if (table->mdl_request.type < MDL_SHARED_UPGRADABLE ||
        table->open_type == OT_TEMPORARY_ONLY ||
        (table->open_type == OT_TEMPORARY_OR_BASE && is_temporary_table(table)))
4162
    {
4163
      continue;
4164
    }
4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183

    /*
      We don't need to do anything about the found TABLE instance as it
      will be handled later in open_tables(), we only need to check that
      an upgradable lock is already acquired. When we enter LOCK TABLES
      mode, SNRW locks are acquired before all other locks. So if under
      LOCK TABLES we find that there is TABLE instance with upgradeable
      lock, all other instances of TABLE for the same table will have the
      same ticket.

      Note that this works OK even for CREATE TABLE statements which
      request X type of metadata lock. This is because under LOCK TABLES
      such statements don't create the table but only check if it exists
      or, in most complex case, only insert into it.
      Thus SNRW lock should be enough.

      Note that find_table_for_mdl_upgrade() will report an error if
      no suitable ticket is found.
    */
4184 4185
    if (!find_table_for_mdl_upgrade(thd, table->db.str, table->table_name.str,
                                    NULL))
4186
      return TRUE;
4187 4188 4189 4190 4191 4192
  }

  return FALSE;
}


Konstantin Osipov's avatar
Konstantin Osipov committed
4193
/**
unknown's avatar
unknown committed
4194 4195
  Open all tables in list

Konstantin Osipov's avatar
Konstantin Osipov committed
4196
  @param[in]     thd      Thread context.
4197
  @param[in]     options  DDL options.
Konstantin Osipov's avatar
Konstantin Osipov committed
4198 4199 4200 4201 4202 4203 4204 4205
  @param[in,out] start    List of tables to be open (it can be adjusted for
                          statement that uses tables only implicitly, e.g.
                          for "SELECT f1()").
  @param[out]    counter  Number of tables which were open.
  @param[in]     flags    Bitmap of flags to modify how the tables will be
                          open, see open_table() description for details.
  @param[in]     prelocking_strategy  Strategy which specifies how prelocking
                                      algorithm should work for this statement.
unknown's avatar
unknown committed
4206

Konstantin Osipov's avatar
Konstantin Osipov committed
4207 4208 4209 4210 4211 4212
  @note
    Unless we are already in prelocked mode and prelocking strategy prescribes
    so this function will also precache all SP/SFs explicitly or implicitly
    (via views and triggers) used by the query and add tables needed for their
    execution to table list. Statement that uses SFs, invokes triggers or
    requires foreign key checks will be marked as requiring prelocking.
4213 4214 4215 4216 4217 4218
    Prelocked mode will be enabled for such query during lock_tables() call.

    If query for which we are opening tables is already marked as requiring
    prelocking it won't do such precaching and will simply reuse table list
    which is already built.

Konstantin Osipov's avatar
Konstantin Osipov committed
4219 4220
  @retval  FALSE  Success.
  @retval  TRUE   Error, reported.
unknown's avatar
unknown committed
4221 4222
*/

4223
bool open_tables(THD *thd, const DDL_options_st &options,
4224
                 TABLE_LIST **start, uint *counter, uint flags,
4225
                 Prelocking_strategy *prelocking_strategy)
unknown's avatar
unknown committed
4226
{
4227
  /*
4228 4229 4230 4231 4232 4233
    We use pointers to "next_global" member in the last processed
    TABLE_LIST element and to the "next" member in the last processed
    Sroutine_hash_entry element as iterators over, correspondingly,
    the table list and stored routines list which stay valid and allow
    to continue iteration when new elements are added to the tail of
    the lists.
4234 4235 4236 4237
  */
  TABLE_LIST **table_to_open;
  Sroutine_hash_entry **sroutine_to_open;
  TABLE_LIST *tables;
4238
  Open_table_context ot_ctx(thd, flags);
Konstantin Osipov's avatar
Konstantin Osipov committed
4239
  bool error= FALSE;
4240
  bool some_routine_modifies_data= FALSE;
Konstantin Osipov's avatar
Konstantin Osipov committed
4241
  bool has_prelocking_list;
4242
  DBUG_ENTER("open_tables");
Konstantin Osipov's avatar
Konstantin Osipov committed
4243

4244
  /* Data access in XA transaction is only allowed when it is active. */
4245 4246 4247
  for (TABLE_LIST *table= *start; table; table= table->next_global)
    if (!table->schema_table)
    {
Marko Mäkelä's avatar
Marko Mäkelä committed
4248
      if (thd->transaction->xid_state.check_has_uncommitted_xa())
4249
      {
Marko Mäkelä's avatar
Marko Mäkelä committed
4250
	thd->transaction->xid_state.er_xaer_rmfail();
4251 4252 4253 4254 4255
        DBUG_RETURN(true);
      }
      else
        break;
    }
4256

4257
  thd->current_tablenr= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
4258
restart:
4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
  /*
    Close HANDLER tables which are marked for flush or against which there
    are pending exclusive metadata locks. This is needed both in order to
    avoid deadlocks and to have a point during statement execution at
    which such HANDLERs are closed even if they don't create problems for
    the current session (i.e. to avoid having a DDL blocked by HANDLERs
    opened for a long time).
  */
  if (thd->handler_tables_hash.records)
    mysql_ha_flush(thd);

Konstantin Osipov's avatar
Konstantin Osipov committed
4270
  has_prelocking_list= thd->lex->requires_prelocking();
4271
  table_to_open= start;
Sergei Golubchik's avatar
Sergei Golubchik committed
4272
  sroutine_to_open= &thd->lex->sroutines_list.first;
4273
  *counter= 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
4274
  THD_STAGE_INFO(thd, stage_opening_tables);
4275
  prelocking_strategy->reset(thd);
4276

4277 4278 4279 4280 4281
  /*
    If we are executing LOCK TABLES statement or a DDL statement
    (in non-LOCK TABLES mode) we might have to acquire upgradable
    semi-exclusive metadata locks (SNW or SNRW) on some of the
    tables to be opened.
4282 4283 4284 4285
    When executing CREATE TABLE .. If NOT EXISTS .. SELECT, the
    table may not yet exist, in which case we acquire an exclusive
    lock.
    We acquire all such locks at once here as doing this in one
4286 4287 4288 4289 4290
    by one fashion may lead to deadlocks or starvation. Later when
    we will be opening corresponding table pre-acquired metadata
    lock will be reused (thanks to the fact that in recursive case
    metadata locks are acquired without waiting).
  */
4291 4292 4293
  if (! (flags & (MYSQL_OPEN_HAS_MDL_LOCK |
                  MYSQL_OPEN_FORCE_SHARED_MDL |
                  MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL)))
4294
  {
4295 4296 4297 4298 4299 4300 4301
    if (thd->locked_tables_mode)
    {
      /*
        Under LOCK TABLES, we can't acquire new locks, so we instead
        need to check if appropriate locks were pre-acquired.
      */
      if (open_tables_check_upgradable_mdl(thd, *start,
4302 4303
                                           thd->lex->first_not_own_table(),
                                           flags))
4304 4305
      {
        error= TRUE;
4306
        goto error;
4307 4308
      }
    }
4309
    else
4310
    {
4311
      TABLE_LIST *table;
4312 4313
      if (lock_table_names(thd, options, *start,
                           thd->lex->first_not_own_table(),
4314 4315 4316
                           ot_ctx.get_timeout(), flags))
      {
        error= TRUE;
4317
        goto error;
4318 4319 4320 4321
      }
      for (table= *start; table && table != thd->lex->first_not_own_table();
           table= table->next_global)
      {
4322
        if (table->mdl_request.type >= MDL_SHARED_UPGRADABLE)
4323 4324
          table->mdl_request.ticket= NULL;
      }
4325 4326 4327
    }
  }

4328
  /*
4329 4330
    Perform steps of prelocking algorithm until there are unprocessed
    elements in prelocking list/set.
4331
  */
4332
  while (*table_to_open  ||
Sergei Golubchik's avatar
Sergei Golubchik committed
4333
         (thd->locked_tables_mode <= LTM_LOCK_TABLES && *sroutine_to_open))
unknown's avatar
unknown committed
4334
  {
4335
    /*
4336 4337
      For every table in the list of tables to open, try to find or open
      a table.
4338
    */
4339 4340
    for (tables= *table_to_open; tables;
         table_to_open= &tables->next_global, tables= tables->next_global)
4341
    {
Sergei Golubchik's avatar
Sergei Golubchik committed
4342 4343
      error= open_and_process_table(thd, tables, counter, flags,
                                    prelocking_strategy, has_prelocking_list,
4344
                                    &ot_ctx);
unknown's avatar
VIEW  
unknown committed
4345

4346
      if (unlikely(error))
unknown's avatar
unknown committed
4347
      {
Konstantin Osipov's avatar
Konstantin Osipov committed
4348
        if (ot_ctx.can_recover_from_failed_open())
4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364
        {
          /*
            We have met exclusive metadata lock or old version of table.
            Now we have to close all tables and release metadata locks.
            We also have to throw away set of prelocked tables (and thus
            close tables from this set that were open by now) since it
            is possible that one of tables which determined its content
            was changed.

            Instead of implementing complex/non-robust logic mentioned
            above we simply close and then reopen all tables.

            We have to save pointer to table list element for table which we
            have failed to open since closing tables can trigger removal of
            elements from the table list (if MERGE tables are involved),
          */
4365
          close_tables_for_reopen(thd, start, ot_ctx.start_of_statement_svp());
Konstantin Osipov's avatar
Konstantin Osipov committed
4366

4367 4368 4369 4370 4371
          /*
            Here we rely on the fact that 'tables' still points to the valid
            TABLE_LIST element. Altough currently this assumption is valid
            it may change in future.
          */
4372
          if (ot_ctx.recover_from_failed_open())
4373
            goto error;
4374

Michael Widenius's avatar
Michael Widenius committed
4375
          /* Re-open temporary tables after close_tables_for_reopen(). */
4376
          if (thd->open_temporary_tables(*start))
4377
            goto error;
Michael Widenius's avatar
Michael Widenius committed
4378

4379 4380 4381
          error= FALSE;
          goto restart;
        }
4382
        goto error;
4383
      }
4384 4385

      DEBUG_SYNC(thd, "open_tables_after_open_and_process_table");
unknown's avatar
unknown committed
4386
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
4387 4388

    /*
4389 4390 4391
      If we are not already in prelocked mode and extended table list is
      not yet built for our statement we need to cache routines it uses
      and build the prelocking list for it.
Konstantin Osipov's avatar
Konstantin Osipov committed
4392 4393 4394
      If we are not in prelocked mode but have built the extended table
      list, we still need to call open_and_process_routine() to take
      MDL locks on the routines.
Konstantin Osipov's avatar
Konstantin Osipov committed
4395
    */
4396
    if (thd->locked_tables_mode <= LTM_LOCK_TABLES && *sroutine_to_open)
Konstantin Osipov's avatar
Konstantin Osipov committed
4397
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
4398
      /*
4399 4400 4401
        Process elements of the prelocking set which are present there
        since parsing stage or were added to it by invocations of
        Prelocking_strategy methods in the above loop over tables.
Konstantin Osipov's avatar
Konstantin Osipov committed
4402

4403 4404 4405
        For example, if element is a routine, cache it and then,
        if prelocking strategy prescribes so, add tables it uses to the
        table list and routines it might invoke to the prelocking set.
Konstantin Osipov's avatar
Konstantin Osipov committed
4406
      */
4407 4408 4409
      for (Sroutine_hash_entry *rt= *sroutine_to_open; rt;
           sroutine_to_open= &rt->next, rt= rt->next)
      {
4410
        bool need_prelocking= false;
4411
        bool routine_modifies_data;
4412 4413
        TABLE_LIST **save_query_tables_last= thd->lex->query_tables_last;

Konstantin Osipov's avatar
Konstantin Osipov committed
4414 4415
        error= open_and_process_routine(thd, thd->lex, rt, prelocking_strategy,
                                        has_prelocking_list, &ot_ctx,
4416 4417 4418 4419 4420
                                        &need_prelocking,
                                        &routine_modifies_data);

        // Remember if any of SF modifies data.
        some_routine_modifies_data|= routine_modifies_data;
Konstantin Osipov's avatar
Konstantin Osipov committed
4421

4422 4423 4424 4425 4426 4427
        if (need_prelocking && ! thd->lex->requires_prelocking())
          thd->lex->mark_as_requiring_prelocking(save_query_tables_last);

        if (need_prelocking && ! *start)
          *start= thd->lex->query_tables;

4428
        if (unlikely(error))
4429
        {
Konstantin Osipov's avatar
Konstantin Osipov committed
4430 4431
          if (ot_ctx.can_recover_from_failed_open())
          {
4432 4433
            close_tables_for_reopen(thd, start,
                                    ot_ctx.start_of_statement_svp());
4434
            if (ot_ctx.recover_from_failed_open())
4435
              goto error;
Konstantin Osipov's avatar
Konstantin Osipov committed
4436

Michael Widenius's avatar
Michael Widenius committed
4437
            /* Re-open temporary tables after close_tables_for_reopen(). */
4438
            if (thd->open_temporary_tables(*start))
4439
              goto error;
Michael Widenius's avatar
Michael Widenius committed
4440

Konstantin Osipov's avatar
Konstantin Osipov committed
4441 4442 4443
            error= FALSE;
            goto restart;
          }
4444 4445 4446 4447 4448
          /*
            Serious error during reading stored routines from mysql.proc table.
            Something is wrong with the table or its contents, and an error has
            been emitted; we must abort.
          */
4449
          goto error;
4450 4451
        }
      }
4452
    }
4453
    if ((error= prelocking_strategy->handle_end(thd)))
4454
      goto error;
unknown's avatar
unknown committed
4455
  }
4456

Konstantin Osipov's avatar
Konstantin Osipov committed
4457 4458 4459 4460 4461
  /*
    After successful open of all tables, including MERGE parents and
    children, attach the children to their parents. At end of statement,
    the children are detached. Attaching and detaching are always done,
    even under LOCK TABLES.
4462

4463 4464 4465
    We also convert all TL_WRITE_DEFAULT and TL_READ_DEFAULT locks to
    appropriate "real" lock types to be used for locking and to be passed
    to storage engine.
Sergei Golubchik's avatar
Sergei Golubchik committed
4466

4467
    And start wsrep TOI if needed.
Konstantin Osipov's avatar
Konstantin Osipov committed
4468 4469 4470 4471 4472
  */
  for (tables= *start; tables; tables= tables->next_global)
  {
    TABLE *tbl= tables->table;

4473 4474 4475
    if (!tbl)
      continue;

Konstantin Osipov's avatar
Konstantin Osipov committed
4476
    /* Schema tables may not have a TABLE object here. */
4477
    if (tbl->file->ha_table_flags() & HA_CAN_MULTISTEP_MERGE)
Konstantin Osipov's avatar
Konstantin Osipov committed
4478 4479 4480 4481 4482
    {
      /* MERGE tables need to access parent and child TABLE_LISTs. */
      DBUG_ASSERT(tbl->pos_in_table_list == tables);
      if (tbl->file->extra(HA_EXTRA_ATTACH_CHILDREN))
      {
Konstantin Osipov's avatar
Konstantin Osipov committed
4483
        error= TRUE;
4484
        goto error;
Konstantin Osipov's avatar
Konstantin Osipov committed
4485 4486
      }
    }
4487 4488 4489 4490

    /* Set appropriate TABLE::lock_type. */
    if (tbl && tables->lock_type != TL_UNLOCK && !thd->locked_tables_mode)
    {
4491 4492 4493 4494 4495 4496 4497 4498 4499
      if (tables->lock_type == TL_WRITE_DEFAULT ||
          unlikely(tables->lock_type == TL_WRITE_SKIP_LOCKED &&
           !(tables->table->file->ha_table_flags() & HA_CAN_SKIP_LOCKED)))
          tbl->reginfo.lock_type= thd->update_lock_default;
      else if (likely(tables->lock_type == TL_READ_DEFAULT) ||
               (tables->lock_type == TL_READ_SKIP_LOCKED &&
                !(tables->table->file->ha_table_flags() & HA_CAN_SKIP_LOCKED)))
          tbl->reginfo.lock_type= read_lock_type_for_table(thd, thd->lex, tables,
                                                           some_routine_modifies_data);
4500 4501
      else
        tbl->reginfo.lock_type= tables->lock_type;
4502
      tbl->reginfo.skip_locked= tables->skip_locked;
4503
    }
mkaruza's avatar
mkaruza committed
4504
#ifdef WITH_WSREP
4505
    /*
mkaruza's avatar
mkaruza committed
4506 4507 4508
       At this point we have SE associated with table so we can check wsrep_mode
       rules at this point.
    */
4509
    if (WSREP(thd) &&
mkaruza's avatar
mkaruza committed
4510
        wsrep_thd_is_local(thd) &&
4511 4512 4513 4514
        tbl &&
        tables == *start &&
        !wsrep_check_mode_after_open_table(thd,
                                           tbl->file->ht, tables))
mkaruza's avatar
mkaruza committed
4515 4516 4517 4518
    {
      error= TRUE;
      goto error;
    }
4519 4520 4521 4522 4523 4524 4525 4526 4527 4528

    /* If user has issued wsrep_on = OFF and wsrep was on before
    we need to check is local gtid feature disabled */
    if (thd->wsrep_was_on &&
	thd->variables.sql_log_bin == 1 &&
	!WSREP(thd) &&
        wsrep_check_mode(WSREP_MODE_DISALLOW_LOCAL_GTID))
    {
      enum_sql_command sql_command= thd->lex->sql_command;
      bool is_dml_stmt= thd->get_command() != COM_STMT_PREPARE &&
4529
                    !thd->stmt_arena->is_stmt_prepare()        &&
4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554
                    (sql_command == SQLCOM_INSERT ||
                     sql_command == SQLCOM_INSERT_SELECT ||
                     sql_command == SQLCOM_REPLACE ||
                     sql_command == SQLCOM_REPLACE_SELECT ||
                     sql_command == SQLCOM_UPDATE ||
                     sql_command == SQLCOM_UPDATE_MULTI ||
                     sql_command == SQLCOM_LOAD ||
                     sql_command == SQLCOM_DELETE);

      if (is_dml_stmt && !is_temporary_table(tables))
      {
        /* wsrep_mode = WSREP_MODE_DISALLOW_LOCAL_GTID, treat as error */
        my_error(ER_GALERA_REPLICATION_NOT_SUPPORTED, MYF(0));
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                            ER_OPTION_PREVENTS_STATEMENT,
                            "You can't execute statements that would generate local "
                            "GTIDs when wsrep_mode = DISALLOW_LOCAL_GTID is set. "
                            "Try disabling binary logging with SET sql_log_bin=0 "
                            "to execute this statement.");

        error= TRUE;
        goto error;
      }
    }
#endif /* WITH_WSREP */
Konstantin Osipov's avatar
Konstantin Osipov committed
4555 4556
  }

4557
error:
Sergei Golubchik's avatar
Sergei Golubchik committed
4558
  THD_STAGE_INFO(thd, stage_after_opening_tables);
4559 4560
  thd_proc_info(thd, 0);

4561
  if (unlikely(error) && *table_to_open)
4562
  {
4563
    (*table_to_open)->table= NULL;
4564
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
4565 4566
  DBUG_PRINT("open_tables", ("returning: %d", (int) error));
  DBUG_RETURN(error);
unknown's avatar
unknown committed
4567 4568 4569
}


Konstantin Osipov's avatar
Konstantin Osipov committed
4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593
/**
  Defines how prelocking algorithm for DML statements should handle routines:
  - For CALL statements we do unrolling (i.e. open and lock tables for each
    sub-statement individually). So for such statements prelocking is enabled
    only if stored functions are used in parameter list and only for period
    during which we calculate values of parameters. Thus in this strategy we
    ignore procedure which is directly called by such statement and extend
    the prelocking set only with tables/functions used by SF called from the
    parameter list.
  - For any other statement any routine which is directly or indirectly called
    by statement is going to be executed in prelocked mode. So in this case we
    simply add all tables and routines used by it to the prelocking set.

  @param[in]  thd              Thread context.
  @param[in]  prelocking_ctx   Prelocking context of the statement.
  @param[in]  rt               Prelocking set element describing routine.
  @param[in]  sp               Routine body.
  @param[out] need_prelocking  Set to TRUE if method detects that prelocking
                               required, not changed otherwise.

  @retval FALSE  Success.
  @retval TRUE   Failure (OOM).
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
4594 4595 4596
bool DML_prelocking_strategy::handle_routine(THD *thd,
               Query_tables_list *prelocking_ctx, Sroutine_hash_entry *rt,
               sp_head *sp, bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
4597 4598 4599 4600 4601 4602 4603 4604 4605
{
  /*
    We assume that for any "CALL proc(...)" statement sroutines_list will
    have 'proc' as first element (it may have several, consider e.g.
    "proc(sp_func(...)))". This property is currently guaranted by the
    parser.
  */

  if (rt != (Sroutine_hash_entry*)prelocking_ctx->sroutines_list.first ||
Konstantin Osipov's avatar
Konstantin Osipov committed
4606
      rt->mdl_request.key.mdl_namespace() != MDL_key::PROCEDURE)
Konstantin Osipov's avatar
Konstantin Osipov committed
4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619
  {
    *need_prelocking= TRUE;
    sp_update_stmt_used_routines(thd, prelocking_ctx, &sp->m_sroutines,
                                 rt->belong_to_view);
    (void)sp->add_used_tables_to_table_list(thd,
                                            &prelocking_ctx->query_tables_last,
                                            rt->belong_to_view);
  }
  sp->propagate_attributes(prelocking_ctx);
  return FALSE;
}


4620 4621 4622 4623
/*
  @note this can be changed to use a hash, instead of scanning the linked
  list, if the performance of this function will ever become an issue
*/
4624 4625
bool table_already_fk_prelocked(TABLE_LIST *tl, LEX_CSTRING *db,
                                LEX_CSTRING *table, thr_lock_type lock_type)
4626 4627 4628 4629
{
  for (; tl; tl= tl->next_global )
  {
    if (tl->lock_type >= lock_type &&
4630
        tl->prelocking_placeholder == TABLE_LIST::PRELOCK_FK &&
4631 4632
        strcmp(tl->db.str, db->str) == 0 &&
        strcmp(tl->table_name.str, table->str) == 0)
4633 4634 4635 4636 4637 4638
      return true;
  }
  return false;
}


4639 4640
static TABLE_LIST *internal_table_exists(TABLE_LIST *global_list,
                                         const char *table_name)
4641 4642 4643
{
  do
  {
4644
    if (global_list->table_name.str == table_name)
4645
      return global_list;
4646 4647 4648 4649 4650
  } while ((global_list= global_list->next_global));
  return 0;
}


4651 4652
static bool
add_internal_tables(THD *thd, Query_tables_list *prelocking_ctx,
4653
                    TABLE_LIST *tables)
4654
{
4655
  TABLE_LIST *global_table_list= prelocking_ctx->query_tables;
4656
  DBUG_ENTER("add_internal_tables");
4657

4658 4659
  do
  {
4660
    TABLE_LIST *tmp __attribute__((unused));
4661
    DBUG_PRINT("info", ("table name: %s", tables->table_name.str));
4662 4663 4664
    /*
      Skip table if already in the list. Can happen with prepared statements
    */
4665 4666 4667 4668 4669 4670 4671 4672 4673 4674
    if ((tmp= internal_table_exists(global_table_list,
                                    tables->table_name.str)))
    {
      /*
        Use the original value for the next local, used by the
        original prepared statement. We cannot trust the original
        next_local value as it may have been changed by a previous
        statement using the same table.
      */
      tables->next_local= tmp;
4675
      continue;
4676
    }
4677

4678 4679
    TABLE_LIST *tl= (TABLE_LIST *) thd->alloc(sizeof(TABLE_LIST));
    if (!tl)
4680
      DBUG_RETURN(TRUE);
4681 4682
    tl->init_one_table_for_prelocking(&tables->db,
                                      &tables->table_name,
4683 4684 4685
                                      NULL, tables->lock_type,
                                      TABLE_LIST::PRELOCK_NONE,
                                      0, 0,
4686 4687
                                      &prelocking_ctx->query_tables_last,
                                      tables->for_insert_data);
4688 4689 4690 4691 4692
    /*
      Store link to the new table_list that will be used by open so that
      Item_func_nextval() can find it
    */
    tables->next_local= tl;
4693
    DBUG_PRINT("info", ("table name: %s added", tables->table_name.str));
4694
  } while ((tables= tables->next_global));
4695
  DBUG_RETURN(FALSE);
4696 4697
}

4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715
/**
  Extend the table_list to include foreign tables for prelocking.

  @param[in]  thd              Thread context.
  @param[in]  prelocking_ctx   Prelocking context of the statement.
  @param[in]  table_list       Table list element for table.
  @param[in]  sp               Routine body.
  @param[out] need_prelocking  Set to TRUE if method detects that prelocking
                               required, not changed otherwise.

  @retval FALSE  Success.
  @retval TRUE   Failure (OOM).
*/
inline bool
prepare_fk_prelocking_list(THD *thd, Query_tables_list *prelocking_ctx,
                           TABLE_LIST *table_list, bool *need_prelocking,
                           uint8 op)
{
4716
  DBUG_ENTER("prepare_fk_prelocking_list");
4717 4718 4719 4720
  List <FOREIGN_KEY_INFO> fk_list;
  List_iterator<FOREIGN_KEY_INFO> fk_list_it(fk_list);
  FOREIGN_KEY_INFO *fk;
  Query_arena *arena, backup;
4721
  TABLE *table= table_list->table;
4722 4723 4724

  arena= thd->activate_stmt_arena_if_needed(&backup);

4725 4726
  table->file->get_parent_foreign_key_list(thd, &fk_list);
  if (unlikely(thd->is_error()))
4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
  {
    if (arena)
      thd->restore_active_arena(arena, &backup);
    return TRUE;
  }

  *need_prelocking= TRUE;

  while ((fk= fk_list_it++))
  {
    // FK_OPTION_RESTRICT and FK_OPTION_NO_ACTION only need read access
    thr_lock_type lock_type;
4739

Sergei Golubchik's avatar
Sergei Golubchik committed
4740 4741
    if ((op & trg2bit(TRG_EVENT_DELETE) && fk_modifies_child(fk->delete_method))
     || (op & trg2bit(TRG_EVENT_UPDATE) && fk_modifies_child(fk->update_method)))
Marko Mäkelä's avatar
Marko Mäkelä committed
4742
      lock_type= TL_FIRST_WRITE;
4743 4744 4745 4746 4747 4748 4749 4750 4751
    else
      lock_type= TL_READ;

    if (table_already_fk_prelocked(prelocking_ctx->query_tables,
          fk->foreign_db, fk->foreign_table,
          lock_type))
      continue;

    TABLE_LIST *tl= (TABLE_LIST *) thd->alloc(sizeof(TABLE_LIST));
4752 4753 4754 4755 4756 4757 4758
    tl->init_one_table_for_prelocking(fk->foreign_db,
        fk->foreign_table,
        NULL, lock_type,
        TABLE_LIST::PRELOCK_FK,
        table_list->belong_to_view, op,
        &prelocking_ctx->query_tables_last,
        table_list->for_insert_data);
4759 4760 4761
  }
  if (arena)
    thd->restore_active_arena(arena, &backup);
4762
  DBUG_RETURN(FALSE);
4763
}
4764

Konstantin Osipov's avatar
Konstantin Osipov committed
4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786
/**
  Defines how prelocking algorithm for DML statements should handle table list
  elements:
  - If table has triggers we should add all tables and routines
    used by them to the prelocking set.

  We do not need to acquire metadata locks on trigger names
  in DML statements, since all DDL statements
  that change trigger metadata always lock their
  subject tables.

  @param[in]  thd              Thread context.
  @param[in]  prelocking_ctx   Prelocking context of the statement.
  @param[in]  table_list       Table list element for table.
  @param[in]  sp               Routine body.
  @param[out] need_prelocking  Set to TRUE if method detects that prelocking
                               required, not changed otherwise.

  @retval FALSE  Success.
  @retval TRUE   Failure (OOM).
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
4787 4788 4789
bool DML_prelocking_strategy::handle_table(THD *thd,
             Query_tables_list *prelocking_ctx, TABLE_LIST *table_list,
             bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
4790
{
4791
  DBUG_ENTER("handle_table");
4792
  TABLE *table= table_list->table;
Konstantin Osipov's avatar
Konstantin Osipov committed
4793
  /* We rely on a caller to check that table is going to be changed. */
4794
  DBUG_ASSERT(table_list->lock_type >= TL_FIRST_WRITE ||
4795
              thd->lex->default_used);
Konstantin Osipov's avatar
Konstantin Osipov committed
4796 4797 4798

  if (table_list->trg_event_map)
  {
4799
    if (table->triggers)
Konstantin Osipov's avatar
Konstantin Osipov committed
4800 4801 4802
    {
      *need_prelocking= TRUE;

4803
      if (table->triggers->
Konstantin Osipov's avatar
Konstantin Osipov committed
4804 4805 4806
          add_tables_and_routines_for_triggers(thd, prelocking_ctx, table_list))
        return TRUE;
    }
4807

4808
    if (table->file->referenced_by_foreign_key())
4809
    {
4810 4811 4812 4813
      if (prepare_fk_prelocking_list(thd, prelocking_ctx, table_list,
                                     need_prelocking,
                                     table_list->trg_event_map))
        return TRUE;
4814
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
4815
  }
4816
  else if (table_list->slave_fk_event_map &&
4817
           table->file->referenced_by_foreign_key())
4818
  {
4819 4820 4821 4822 4823
    if (prepare_fk_prelocking_list(thd, prelocking_ctx, table_list,
                                   need_prelocking,
                                   table_list->slave_fk_event_map))
      return TRUE;
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
4824

4825
  /* Open any tables used by DEFAULT (like sequence tables) */
4826 4827 4828
  DBUG_PRINT("info", ("table: %p  name: %s  db: %s  flags: %u",
                      table_list, table_list->table_name.str,
                      table_list->db.str, table_list->for_insert_data));
4829
  if (table->internal_tables &&
4830
      (table_list->for_insert_data ||
4831
       thd->lex->default_used))
4832
  {
4833 4834 4835 4836 4837 4838 4839
    Query_arena *arena, backup;
    bool error;
    arena= thd->activate_stmt_arena_if_needed(&backup);
    error= add_internal_tables(thd, prelocking_ctx,
                               table->internal_tables);
    if (arena)
      thd->restore_active_arena(arena, &backup);
4840
    if (unlikely(error))
4841 4842
    {
      *need_prelocking= TRUE;
4843
      DBUG_RETURN(TRUE);
4844
    }
4845
  }
4846
  DBUG_RETURN(FALSE);
Konstantin Osipov's avatar
Konstantin Osipov committed
4847 4848 4849
}


4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862
/**
  Open all tables used by DEFAULT functions.

  This is different from normal open_and_lock_tables() as we may
  already have other tables opened and locked and we have to merge the
  new table with the old ones.
*/

bool open_and_lock_internal_tables(TABLE *table, bool lock_table)
{
  THD *thd= table->in_use;
  TABLE_LIST *tl;
  MYSQL_LOCK *save_lock,*new_lock;
4863
  DBUG_ENTER("open_and_lock_internal_tables");
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902

  /* remove pointer to old select_lex which is already destroyed */
  for (tl= table->internal_tables ; tl ; tl= tl->next_global)
    tl->select_lex= 0;

  uint counter;
  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
  TABLE_LIST *tmp= table->internal_tables;
  DML_prelocking_strategy prelocking_strategy;

  if (open_tables(thd, thd->lex->create_info, &tmp, &counter, 0,
                  &prelocking_strategy))
    goto err;

  if (lock_table)
  {
    save_lock= thd->lock;
    thd->lock= 0;
    if (lock_tables(thd, table->internal_tables, counter,
                    MYSQL_LOCK_USE_MALLOC))
      goto err;

    if (!(new_lock= mysql_lock_merge(save_lock, thd->lock)))
    {
      thd->lock= save_lock;
      mysql_unlock_tables(thd, save_lock, 1);
      /* We don't have to close tables as caller will do that */
      goto err;
    }
    thd->lock= new_lock;
  }
  DBUG_RETURN(0);

err:
  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
  DBUG_RETURN(1);
}


Konstantin Osipov's avatar
Konstantin Osipov committed
4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917
/**
  Defines how prelocking algorithm for DML statements should handle view -
  all view routines should be added to the prelocking set.

  @param[in]  thd              Thread context.
  @param[in]  prelocking_ctx   Prelocking context of the statement.
  @param[in]  table_list       Table list element for view.
  @param[in]  sp               Routine body.
  @param[out] need_prelocking  Set to TRUE if method detects that prelocking
                               required, not changed otherwise.

  @retval FALSE  Success.
  @retval TRUE   Failure (OOM).
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
4918 4919 4920
bool DML_prelocking_strategy::handle_view(THD *thd,
            Query_tables_list *prelocking_ctx, TABLE_LIST *table_list,
            bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
4921 4922 4923 4924 4925 4926 4927 4928 4929
{
  if (table_list->view->uses_stored_routines())
  {
    *need_prelocking= TRUE;

    sp_update_stmt_used_routines(thd, prelocking_ctx,
                                 &table_list->view->sroutines_list,
                                 table_list->top_table());
  }
4930 4931 4932 4933 4934 4935 4936 4937 4938

  /*
    If a trigger was defined on one of the associated tables then assign the
    'trg_event_map' value of the view to the next table in table_list. When a
    Stored function is invoked, all the associated tables including the tables
    associated with the trigger are prelocked.
  */
  if (table_list->trg_event_map && table_list->next_global)
    table_list->next_global->trg_event_map= table_list->trg_event_map;
Konstantin Osipov's avatar
Konstantin Osipov committed
4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957
  return FALSE;
}


/**
  Defines how prelocking algorithm for LOCK TABLES statement should handle
  table list elements.

  @param[in]  thd              Thread context.
  @param[in]  prelocking_ctx   Prelocking context of the statement.
  @param[in]  table_list       Table list element for table.
  @param[in]  sp               Routine body.
  @param[out] need_prelocking  Set to TRUE if method detects that prelocking
                               required, not changed otherwise.

  @retval FALSE  Success.
  @retval TRUE   Failure (OOM).
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
4958 4959 4960
bool Lock_tables_prelocking_strategy::handle_table(THD *thd,
             Query_tables_list *prelocking_ctx, TABLE_LIST *table_list,
             bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
4961
{
4962 4963
  TABLE_LIST **last= prelocking_ctx->query_tables_last;

Konstantin Osipov's avatar
Konstantin Osipov committed
4964 4965 4966 4967
  if (DML_prelocking_strategy::handle_table(thd, prelocking_ctx, table_list,
                                            need_prelocking))
    return TRUE;

4968 4969 4970 4971 4972 4973 4974
  /*
    normally we don't need to open FK-prelocked tables for RESTRICT,
    MDL is enough. But under LOCK TABLES we have to open everything
  */
  for (TABLE_LIST *tl= *last; tl; tl= tl->next_global)
    tl->open_strategy= TABLE_LIST::OPEN_NORMAL;

Konstantin Osipov's avatar
Konstantin Osipov committed
4975
  /* We rely on a caller to check that table is going to be changed. */
4976
  DBUG_ASSERT(table_list->lock_type >= TL_FIRST_WRITE);
Konstantin Osipov's avatar
Konstantin Osipov committed
4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990

  return FALSE;
}


/**
  Defines how prelocking algorithm for ALTER TABLE statement should handle
  routines - do nothing as this statement is not supposed to call routines.

  We still can end up in this method when someone tries
  to define a foreign key referencing a view, and not just
  a simple view, but one that uses stored routines.
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
4991 4992 4993
bool Alter_table_prelocking_strategy::handle_routine(THD *thd,
               Query_tables_list *prelocking_ctx, Sroutine_hash_entry *rt,
               sp_head *sp, bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016
{
  return FALSE;
}


/**
  Defines how prelocking algorithm for ALTER TABLE statement should handle
  table list elements.

  Unlike in DML, we do not process triggers here.

  @param[in]  thd              Thread context.
  @param[in]  prelocking_ctx   Prelocking context of the statement.
  @param[in]  table_list       Table list element for table.
  @param[in]  sp               Routine body.
  @param[out] need_prelocking  Set to TRUE if method detects that prelocking
                               required, not changed otherwise.


  @retval FALSE  Success.
  @retval TRUE   Failure (OOM).
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
5017 5018 5019
bool Alter_table_prelocking_strategy::handle_table(THD *thd,
             Query_tables_list *prelocking_ctx, TABLE_LIST *table_list,
             bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031
{
  return FALSE;
}


/**
  Defines how prelocking algorithm for ALTER TABLE statement
  should handle view - do nothing. We don't need to add view
  routines to the prelocking set in this case as view is not going
  to be materialized.
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
5032 5033 5034
bool Alter_table_prelocking_strategy::handle_view(THD *thd,
            Query_tables_list *prelocking_ctx, TABLE_LIST *table_list,
            bool *need_prelocking)
Konstantin Osipov's avatar
Konstantin Osipov committed
5035 5036 5037 5038 5039
{
  return FALSE;
}


5040
/**
unknown's avatar
unknown committed
5041 5042
  Check that lock is ok for tables; Call start stmt if ok

5043 5044 5045
  @param thd             Thread handle.
  @param prelocking_ctx  Prelocking context.
  @param table_list      Table list element for table to be checked.
unknown's avatar
unknown committed
5046

5047 5048
  @retval FALSE - Ok.
  @retval TRUE  - Error.
unknown's avatar
unknown committed
5049 5050
*/

5051 5052 5053
static bool check_lock_and_start_stmt(THD *thd,
                                      Query_tables_list *prelocking_ctx,
                                      TABLE_LIST *table_list)
unknown's avatar
unknown committed
5054 5055
{
  int error;
5056
  thr_lock_type lock_type;
unknown's avatar
unknown committed
5057 5058
  DBUG_ENTER("check_lock_and_start_stmt");

5059 5060 5061 5062
  /*
    Prelocking placeholder is not set for TABLE_LIST that
    are directly used by TOP level statement.
  */
5063
  DBUG_ASSERT(table_list->prelocking_placeholder == TABLE_LIST::PRELOCK_NONE);
5064

5065 5066 5067 5068 5069 5070 5071
  /*
    TL_WRITE_DEFAULT and TL_READ_DEFAULT are supposed to be parser only
    types of locks so they should be converted to appropriate other types
    to be passed to storage engine. The exact lock type passed to the
    engine is important as, for example, InnoDB uses it to determine
    what kind of row locks should be acquired when executing statement
    in prelocked mode or under LOCK TABLES with @@innodb_table_locks = 0.
5072 5073 5074

    Last argument routine_modifies_data for read_lock_type_for_table()
    is ignored, as prelocking placeholder will never be set here.
5075 5076 5077 5078
  */
  if (table_list->lock_type == TL_WRITE_DEFAULT)
    lock_type= thd->update_lock_default;
  else if (table_list->lock_type == TL_READ_DEFAULT)
5079
    lock_type= read_lock_type_for_table(thd, prelocking_ctx, table_list, true);
5080 5081 5082
  else
    lock_type= table_list->lock_type;

5083 5084
  if ((int) lock_type >= (int) TL_FIRST_WRITE &&
      (int) table_list->table->reginfo.lock_type < (int) TL_FIRST_WRITE)
unknown's avatar
unknown committed
5085
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
5086 5087
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),
             table_list->table->alias.c_ptr());
unknown's avatar
unknown committed
5088 5089
    DBUG_RETURN(1);
  }
5090
  if (unlikely((error= table_list->table->file->start_stmt(thd, lock_type))))
unknown's avatar
unknown committed
5091
  {
5092
    table_list->table->file->print_error(error, MYF(0));
unknown's avatar
unknown committed
5093 5094
    DBUG_RETURN(1);
  }
5095 5096 5097 5098 5099 5100 5101

  /*
    Record in transaction state tracking
  */
  TRANSACT_TRACKER(add_trx_state(thd, lock_type,
                                 table_list->table->file->has_transactions()));

unknown's avatar
unknown committed
5102 5103 5104 5105
  DBUG_RETURN(0);
}


5106 5107 5108 5109 5110 5111
/**
  @brief Open and lock one table

  @param[in]    thd             thread handle
  @param[in]    table_l         table to open is first table in this list
  @param[in]    lock_type       lock to use for table
Konstantin Osipov's avatar
Konstantin Osipov committed
5112 5113
  @param[in]    flags           options to be used while opening and locking
                                table (see open_table(), mysql_lock_tables())
5114 5115
  @param[in]    prelocking_strategy  Strategy which specifies how prelocking
                                     algorithm should work for this statement.
5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135

  @return       table
    @retval     != NULL         OK, opened table returned
    @retval     NULL            Error

  @note
    If ok, the following are also set:
      table_list->lock_type 	lock_type
      table_list->table		table

  @note
    If table_l is a list, not a single table, the list is temporarily
    broken.

  @detail
    This function is meant as a replacement for open_ltable() when
    MERGE tables can be opened. open_ltable() cannot open MERGE tables.

    There may be more differences between open_n_lock_single_table() and
    open_ltable(). One known difference is that open_ltable() does
5136
    neither call thd->decide_logging_format() nor handle some other logging
5137 5138 5139 5140
    and locking issues because it does not call lock_tables().
*/

TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
5141 5142
                                thr_lock_type lock_type, uint flags,
                                Prelocking_strategy *prelocking_strategy)
5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
{
  TABLE_LIST *save_next_global;
  DBUG_ENTER("open_n_lock_single_table");

  /* Remember old 'next' pointer. */
  save_next_global= table_l->next_global;
  /* Break list. */
  table_l->next_global= NULL;

  /* Set requested lock type. */
  table_l->lock_type= lock_type;
  /* Allow to open real tables only. */
5155
  table_l->required_type= TABLE_TYPE_NORMAL;
5156 5157

  /* Open the table. */
5158 5159
  if (open_and_lock_tables(thd, table_l, FALSE, flags,
                           prelocking_strategy))
5160 5161 5162 5163 5164 5165 5166 5167 5168
    table_l->table= NULL; /* Just to be sure. */

  /* Restore list. */
  table_l->next_global= save_next_global;

  DBUG_RETURN(table_l->table);
}


unknown's avatar
unknown committed
5169 5170 5171 5172 5173 5174 5175 5176
/*
  Open and lock one table

  SYNOPSIS
    open_ltable()
    thd			Thread handler
    table_list		Table to open is first table in this list
    lock_type		Lock to use for open
5177
    lock_flags          Flags passed to mysql_lock_table
unknown's avatar
unknown committed
5178

5179
  NOTE
5180
    This function doesn't do anything like SP/SF/views/triggers analysis done 
Staale Smedseng's avatar
Staale Smedseng committed
5181
    in open_table()/lock_tables(). It is intended for opening of only one
5182
    concrete table. And used only in special contexts.
5183

unknown's avatar
unknown committed
5184 5185 5186 5187 5188 5189 5190 5191 5192
  RETURN VALUES
    table		Opened table
    0			Error
  
    If ok, the following are also set:
      table_list->lock_type 	lock_type
      table_list->table		table
*/

5193 5194
TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
                   uint lock_flags)
unknown's avatar
unknown committed
5195 5196
{
  TABLE *table;
5197
  Open_table_context ot_ctx(thd, lock_flags);
Konstantin Osipov's avatar
Konstantin Osipov committed
5198
  bool error;
unknown's avatar
unknown committed
5199 5200
  DBUG_ENTER("open_ltable");

5201
  /* Ignore temporary tables as they have already been opened. */
Michael Widenius's avatar
Michael Widenius committed
5202 5203 5204
  if (table_list->table)
    DBUG_RETURN(table_list->table);

Staale Smedseng's avatar
Staale Smedseng committed
5205
  /* should not be used in a prelocked_mode context, see NOTE above */
Konstantin Osipov's avatar
Konstantin Osipov committed
5206
  DBUG_ASSERT(thd->locked_tables_mode < LTM_PRELOCKED);
Staale Smedseng's avatar
Staale Smedseng committed
5207

Sergei Golubchik's avatar
Sergei Golubchik committed
5208
  THD_STAGE_INFO(thd, stage_opening_tables);
5209
  thd->current_tablenr= 0;
5210
  /* open_ltable can be used only for BASIC TABLEs */
5211
  table_list->required_type= TABLE_TYPE_NORMAL;
5212

5213
  /* This function can't properly handle requests for such metadata locks. */
5214
  DBUG_ASSERT(table_list->mdl_request.type < MDL_SHARED_UPGRADABLE);
5215

5216
  while ((error= open_table(thd, table_list, &ot_ctx)) &&
Konstantin Osipov's avatar
Konstantin Osipov committed
5217
         ot_ctx.can_recover_from_failed_open())
5218 5219
  {
    /*
Konstantin Osipov's avatar
Konstantin Osipov committed
5220
      Even though we have failed to open table we still need to
5221
      call release_transactional_locks() to release metadata locks which
5222 5223
      might have been acquired successfully.
    */
5224
    thd->mdl_context.rollback_to_savepoint(ot_ctx.start_of_statement_svp());
Konstantin Osipov's avatar
Konstantin Osipov committed
5225
    table_list->mdl_request.ticket= 0;
5226
    if (ot_ctx.recover_from_failed_open())
5227 5228
      break;
  }
unknown's avatar
unknown committed
5229

5230
  if (likely(!error))
unknown's avatar
unknown committed
5231
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
5232
    /*
5233
      We can't have a view or some special "open_strategy" in this function
Konstantin Osipov's avatar
Konstantin Osipov committed
5234 5235 5236 5237
      so there should be a TABLE instance.
    */
    DBUG_ASSERT(table_list->table);
    table= table_list->table;
5238
    if (table->file->ha_table_flags() & HA_CAN_MULTISTEP_MERGE)
5239 5240 5241 5242 5243 5244 5245 5246 5247 5248
    {
      /* A MERGE table must not come here. */
      /* purecov: begin tested */
      my_error(ER_WRONG_OBJECT, MYF(0), table->s->db.str,
               table->s->table_name.str, "BASE TABLE");
      table= 0;
      goto end;
      /* purecov: end */
    }

unknown's avatar
unknown committed
5249
    table_list->lock_type= lock_type;
unknown's avatar
unknown committed
5250
    table->grant= table_list->grant;
Konstantin Osipov's avatar
Konstantin Osipov committed
5251
    if (thd->locked_tables_mode)
unknown's avatar
unknown committed
5252
    {
5253
      if (check_lock_and_start_stmt(thd, thd->lex, table_list))
unknown's avatar
unknown committed
5254 5255 5256 5257
	table= 0;
    }
    else
    {
5258
      DBUG_ASSERT(thd->lock == 0);	// You must lock everything at once
unknown's avatar
unknown committed
5259
      if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
5260
	if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
5261
                                            lock_flags)))
5262
        {
5263
          table= 0;
5264
        }
unknown's avatar
unknown committed
5265 5266
    }
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
5267 5268
  else
    table= 0;
5269

Konstantin Osipov's avatar
Konstantin Osipov committed
5270
end:
5271
  if (table == NULL)
5272
  {
5273 5274
    if (!thd->in_sub_stmt)
      trans_rollback_stmt(thd);
5275
    close_thread_tables(thd);
5276
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
5277
  THD_STAGE_INFO(thd, stage_after_opening_tables);
5278 5279

  thd_proc_info(thd, 0);
unknown's avatar
unknown committed
5280 5281 5282
  DBUG_RETURN(table);
}

unknown's avatar
unknown committed
5283

Konstantin Osipov's avatar
Konstantin Osipov committed
5284
/**
5285
  Open all tables in list, locks them and optionally process derived tables.
unknown's avatar
unknown committed
5286

Konstantin Osipov's avatar
Konstantin Osipov committed
5287
  @param thd		      Thread context.
5288
  @param options              DDL options.
Konstantin Osipov's avatar
Konstantin Osipov committed
5289
  @param tables	              List of tables for open and locking.
5290
  @param derived              Whether to handle derived tables.
Konstantin Osipov's avatar
Konstantin Osipov committed
5291 5292 5293 5294 5295
  @param flags                Bitmap of options to be used to open and lock
                              tables (see open_tables() and mysql_lock_tables()
                              for details).
  @param prelocking_strategy  Strategy which specifies how prelocking algorithm
                              should work for this statement.
unknown's avatar
unknown committed
5296

Konstantin Osipov's avatar
Konstantin Osipov committed
5297
  @note
5298 5299
    The thr_lock locks will automatically be freed by
    close_thread_tables().
5300

Konstantin Osipov's avatar
Konstantin Osipov committed
5301 5302
  @retval FALSE  OK.
  @retval TRUE   Error
unknown's avatar
unknown committed
5303 5304
*/

5305 5306
bool open_and_lock_tables(THD *thd, const DDL_options_st &options,
                          TABLE_LIST *tables,
5307 5308
                          bool derived, uint flags,
                          Prelocking_strategy *prelocking_strategy)
unknown's avatar
unknown committed
5309 5310
{
  uint counter;
5311
  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
5312
  DBUG_ENTER("open_and_lock_tables");
5313
  DBUG_PRINT("enter", ("derived handling: %d", derived));
5314

5315
  if (open_tables(thd, options, &tables, &counter, flags, prelocking_strategy))
5316
    goto err;
5317 5318 5319 5320 5321 5322 5323 5324

  DBUG_EXECUTE_IF("sleep_open_and_lock_after_open", {
                  const char *old_proc_info= thd->proc_info;
                  thd->proc_info= "DBUG sleep";
                  my_sleep(6000000);
                  thd->proc_info= old_proc_info;});

  if (lock_tables(thd, tables, counter, flags))
5325
    goto err;
5326

5327
  /* Don't read statistics tables when opening internal tables */
5328 5329
  if (!(flags & (MYSQL_OPEN_IGNORE_LOGGING_FORMAT |
                 MYSQL_OPEN_IGNORE_ENGINE_STATS)))
5330
    (void) read_statistics_for_tables_if_needed(thd, tables);
Igor Babaev's avatar
Igor Babaev committed
5331
  
5332 5333
  if (derived)
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
5334
    if (mysql_handle_derived(thd->lex, DT_INIT))
5335
      goto err;
Sergei Golubchik's avatar
Sergei Golubchik committed
5336 5337
    if (thd->prepare_derived_at_open &&
        (mysql_handle_derived(thd->lex, DT_PREPARE)))
5338 5339
      goto err;
  }
5340

Konstantin Osipov's avatar
Konstantin Osipov committed
5341
  DBUG_RETURN(FALSE);
5342 5343 5344 5345 5346 5347 5348
err:
  if (! thd->in_sub_stmt)
    trans_rollback_stmt(thd);  /* Necessary if derived handling failed. */
  close_thread_tables(thd);
  /* Don't keep locks for a failed statement. */
  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5349 5350 5351
}


5352 5353 5354 5355 5356 5357
/*
  Open all tables in list and process derived tables

  SYNOPSIS
    open_normal_and_derived_tables
    thd		- thread handler
5358
    tables	- list of tables for open
5359 5360
    flags       - bitmap of flags to modify how the tables will be open:
                  MYSQL_LOCK_IGNORE_FLUSH - open table even if someone has
5361
                  done a flush on it.
5362
    dt_phases   - set of flags to pass to the mysql_handle_derived
5363 5364 5365 5366 5367 5368 5369 5370 5371 5372

  RETURN
    FALSE - ok
    TRUE  - error

  NOTE 
    This is to be used on prepare stage when you don't read any
    data from the tables.
*/

5373 5374
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags,
                                    uint dt_phases)
5375
{
5376
  DML_prelocking_strategy prelocking_strategy;
5377
  uint counter;
5378
  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
5379
  DBUG_ENTER("open_normal_and_derived_tables");
5380
  if (open_tables(thd, &tables, &counter, flags, &prelocking_strategy) ||
5381
      mysql_handle_derived(thd->lex, dt_phases))
5382 5383
    goto end;

unknown's avatar
unknown committed
5384
  DBUG_RETURN(0);
5385
end:
5386 5387 5388 5389 5390 5391
  /*
    No need to commit/rollback the statement transaction: it's
    either not started or we're filling in an INFORMATION_SCHEMA
    table on the fly, and thus mustn't manipulate with the
    transaction of the enclosing statement.
  */
5392
  DBUG_ASSERT(thd->transaction->stmt.is_empty() ||
5393
              (thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
5394 5395 5396 5397 5398
  close_thread_tables(thd);
  /* Don't keep locks for a failed statement. */
  thd->mdl_context.rollback_to_savepoint(mdl_savepoint);

  DBUG_RETURN(TRUE); /* purecov: inspected */
5399 5400 5401
}


5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436
/**
  Open a table to read its structure, e.g. for:
  - SHOW FIELDS
  - delayed SP variable data type definition: DECLARE a t1.a%TYPE

  The flag MYSQL_OPEN_GET_NEW_TABLE is passed to make %TYPE work
  in stored functions, as during a stored function call
  (e.g. in a SELECT query) the tables referenced in %TYPE can already be locked,
  and attempt to open it again would return an error in open_table().

  The flag MYSQL_OPEN_GET_NEW_TABLE is not really needed for
  SHOW FIELDS or for a "CALL sp()" statement, but it's not harmful,
  so let's pass it unconditionally.
*/

bool open_tables_only_view_structure(THD *thd, TABLE_LIST *table_list,
                                     bool can_deadlock)
{
  DBUG_ENTER("open_tables_only_view_structure");
  /*
    Let us set fake sql_command so views won't try to merge
    themselves into main statement. If we don't do this,
    SELECT * from information_schema.xxxx will cause problems.
    SQLCOM_SHOW_FIELDS is used because it satisfies
    'LEX::only_view_structure()'.
  */
  enum_sql_command save_sql_command= thd->lex->sql_command;
  thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
  bool rc= (thd->open_temporary_tables(table_list) ||
           open_normal_and_derived_tables(thd, table_list,
                                          (MYSQL_OPEN_IGNORE_FLUSH |
                                           MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
                                           MYSQL_OPEN_GET_NEW_TABLE |
                                           (can_deadlock ?
                                            MYSQL_OPEN_FAIL_ON_MDL_CONFLICT : 0)),
5437
                                          DT_INIT | DT_PREPARE));
5438 5439 5440 5441 5442 5443 5444 5445 5446
  /*
    Restore old value of sql_command back as it is being looked at in
    process_table() function.
  */
  thd->lex->sql_command= save_sql_command;
  DBUG_RETURN(rc);
}


5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459
/*
  Mark all real tables in the list as free for reuse.

  SYNOPSIS
    mark_real_tables_as_free_for_reuse()
      thd   - thread context
      table - head of the list of tables

  DESCRIPTION
    Marks all real tables in the list (i.e. not views, derived
    or schema tables) as free for reuse.
*/

5460
static void mark_real_tables_as_free_for_reuse(TABLE_LIST *table_list)
5461
{
5462
  TABLE_LIST *table;
5463 5464 5465 5466 5467 5468
  DBUG_ENTER("mark_real_tables_as_free_for_reuse");

  /*
    We have to make two loops as HA_EXTRA_DETACH_CHILDREN may
    remove items from the table list that we have to reset
  */
5469
  for (table= table_list; table; table= table->next_global)
5470
  {
5471
    if (!table->placeholder())
5472
      table->table->query_id= 0;
5473
  }
5474
  for (table= table_list; table; table= table->next_global)
5475
  {
5476 5477 5478 5479 5480 5481 5482 5483 5484 5485
    if (!table->placeholder())
    {
      /*
        Detach children of MyISAMMRG tables used in
        sub-statements, they will be reattached at open.
        This has to be done in a separate loop to make sure
        that children have had their query_id cleared.
      */
      table->table->file->extra(HA_EXTRA_DETACH_CHILDREN);
    }
5486 5487
  }
  DBUG_VOID_RETURN;
5488 5489
}

5490

5491 5492
/**
  Lock all tables in a list.
unknown's avatar
unknown committed
5493

5494 5495 5496 5497
  @param  thd           Thread handler
  @param  tables        Tables to lock
  @param  count         Number of opened tables
  @param  flags         Options (see mysql_lock_tables() for details)
unknown's avatar
unknown committed
5498

5499 5500
  You can't call lock_tables() while holding thr_lock locks, as
  this would break the dead-lock-free handling thr_lock gives us.
5501
  You must always get all needed locks at once.
5502

5503 5504 5505
  If the query for which we are calling this function is marked as
  requiring prelocking, this function will change
  locked_tables_mode to LTM_PRELOCKED.
5506

5507 5508
  @retval FALSE         Success. 
  @retval TRUE          A lock wait timeout, deadlock or out of memory.
unknown's avatar
unknown committed
5509 5510
*/

5511
bool lock_tables(THD *thd, TABLE_LIST *tables, uint count, uint flags)
unknown's avatar
unknown committed
5512
{
5513
  TABLE_LIST *table, *first_not_own;
5514 5515 5516 5517 5518
  DBUG_ENTER("lock_tables");
  /*
    We can't meet statement requiring prelocking if we already
    in prelocked mode.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
5519 5520
  DBUG_ASSERT(thd->locked_tables_mode <= LTM_LOCK_TABLES ||
              !thd->lex->requires_prelocking());
5521

5522
  if (!tables && !thd->lex->requires_prelocking())
5523 5524 5525
    DBUG_RETURN(0);

  first_not_own= thd->lex->first_not_own_table();
unknown's avatar
unknown committed
5526

5527
  /*
Konstantin Osipov's avatar
Konstantin Osipov committed
5528 5529 5530 5531
    Check for thd->locked_tables_mode to avoid a redundant
    and harmful attempt to lock the already locked tables again.
    Checking for thd->lock is not enough in some situations. For example,
    if a stored function contains
5532
    "drop table t3; create temporary t3 ..; insert into t3 ...;"
Konstantin Osipov's avatar
Konstantin Osipov committed
5533 5534 5535
    thd->lock may be 0 after drop tables, whereas locked_tables_mode
    is still on. In this situation an attempt to lock temporary
    table t3 will lead to a memory leak.
5536
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
5537
  if (! thd->locked_tables_mode)
unknown's avatar
unknown committed
5538
  {
5539
    DBUG_ASSERT(thd->lock == 0);	// You must lock everything at once
unknown's avatar
unknown committed
5540
    TABLE **start,**ptr;
5541
    bool found_first_not_own= 0;
5542

5543
    if (!(ptr=start=(TABLE**) thd->alloc(sizeof(TABLE*)*count)))
Konstantin Osipov's avatar
Konstantin Osipov committed
5544
      DBUG_RETURN(TRUE);
5545 5546 5547 5548 5549 5550

    /*
      Collect changes tables for table lock.
      Mark own tables with query id as this is needed by
      prepare_for_row_logging()
    */
unknown's avatar
VIEW  
unknown committed
5551
    for (table= tables; table; table= table->next_global)
unknown's avatar
unknown committed
5552
    {
5553 5554
      if (table == first_not_own)
        found_first_not_own= 1;
5555
      if (!table->placeholder())
5556 5557 5558 5559 5560
      {
        *(ptr++)= table->table;
        if (!found_first_not_own)
          table->table->query_id= thd->query_id;
      }
unknown's avatar
unknown committed
5561
    }
5562

5563 5564
    DEBUG_SYNC(thd, "before_lock_tables_takes_lock");

5565
    if (! (thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
5566
                                        flags)))
Konstantin Osipov's avatar
Konstantin Osipov committed
5567
      DBUG_RETURN(TRUE);
5568

5569 5570
    DEBUG_SYNC(thd, "after_lock_tables_takes_lock");

5571
    if (thd->lex->requires_prelocking() &&
5572 5573
        thd->lex->sql_command != SQLCOM_LOCK_TABLES &&
        thd->lex->sql_command != SQLCOM_FLUSH)
5574 5575 5576 5577 5578
    {
      /*
        We just have done implicit LOCK TABLES, and now we have
        to emulate first open_and_lock_tables() after it.

5579 5580 5581 5582 5583 5584 5585 5586 5587 5588
        When open_and_lock_tables() is called for a single table out of
        a table list, the 'next_global' chain is temporarily broken. We
        may not find 'first_not_own' before the end of the "list".
        Look for example at those places where open_n_lock_single_table()
        is called. That function implements the temporary breaking of
        a table list for opening a single table.
      */
      for (table= tables;
           table && table != first_not_own;
           table= table->next_global)
5589
      {
5590
        if (!table->placeholder())
5591
        {
5592
          if (check_lock_and_start_stmt(thd, thd->lex, table))
5593
          {
Konstantin Osipov's avatar
Konstantin Osipov committed
5594
            mysql_unlock_tables(thd, thd->lock);
Konstantin Osipov's avatar
Konstantin Osipov committed
5595
            thd->lock= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
5596
            DBUG_RETURN(TRUE);
5597 5598 5599 5600 5601 5602 5603 5604
          }
        }
      }
      /*
        Let us mark all tables which don't belong to the statement itself,
        and was marked as occupied during open_tables() as free for reuse.
      */
      mark_real_tables_as_free_for_reuse(first_not_own);
Konstantin Osipov's avatar
Konstantin Osipov committed
5605
      DBUG_PRINT("info",("locked_tables_mode= LTM_PRELOCKED"));
5606
      thd->enter_locked_tables_mode(LTM_PRELOCKED);
5607
    }
unknown's avatar
unknown committed
5608
  }
unknown's avatar
unknown committed
5609 5610
  else
  {
5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621
    /*
      When open_and_lock_tables() is called for a single table out of
      a table list, the 'next_global' chain is temporarily broken. We
      may not find 'first_not_own' before the end of the "list".
      Look for example at those places where open_n_lock_single_table()
      is called. That function implements the temporary breaking of
      a table list for opening a single table.
    */
    for (table= tables;
         table && table != first_not_own;
         table= table->next_global)
unknown's avatar
unknown committed
5622
    {
5623 5624 5625
      if (table->placeholder())
        continue;

5626
      table->table->query_id= thd->query_id;
5627 5628 5629 5630
      /*
        In a stored function or trigger we should ensure that we won't change
        a table that is already used by the calling statement.
      */
Konstantin Osipov's avatar
Konstantin Osipov committed
5631
      if (thd->locked_tables_mode >= LTM_PRELOCKED &&
5632
          table->lock_type >= TL_FIRST_WRITE)
5633 5634 5635
      {
        for (TABLE* opentab= thd->open_tables; opentab; opentab= opentab->next)
        {
Staale Smedseng's avatar
Staale Smedseng committed
5636 5637
          if (table->table->s == opentab->s && opentab->query_id &&
              table->table->query_id != opentab->query_id)
5638 5639
          {
            my_error(ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG, MYF(0),
Staale Smedseng's avatar
Staale Smedseng committed
5640
                     table->table->s->table_name.str);
Konstantin Osipov's avatar
Konstantin Osipov committed
5641
            DBUG_RETURN(TRUE);
5642 5643 5644 5645
          }
        }
      }

5646
      if (check_lock_and_start_stmt(thd, thd->lex, table))
unknown's avatar
unknown committed
5647
      {
Konstantin Osipov's avatar
Konstantin Osipov committed
5648
	DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5649 5650
      }
    }
5651 5652 5653 5654 5655 5656 5657 5658
    /*
      If we are under explicit LOCK TABLES and our statement requires
      prelocking, we should mark all "additional" tables as free for use
      and enter prelocked mode.
    */
    if (thd->lex->requires_prelocking())
    {
      mark_real_tables_as_free_for_reuse(first_not_own);
Konstantin Osipov's avatar
Konstantin Osipov committed
5659 5660 5661
      DBUG_PRINT("info",
                 ("thd->locked_tables_mode= LTM_PRELOCKED_UNDER_LOCK_TABLES"));
      thd->locked_tables_mode= LTM_PRELOCKED_UNDER_LOCK_TABLES;
5662
    }
unknown's avatar
unknown committed
5663
  }
5664

Marko Mäkelä's avatar
Marko Mäkelä committed
5665 5666
  const bool res= !(flags & MYSQL_OPEN_IGNORE_LOGGING_FORMAT) &&
    thd->decide_logging_format(tables);
5667 5668

  DBUG_RETURN(res);
unknown's avatar
unknown committed
5669 5670
}

unknown's avatar
unknown committed
5671

5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701
/*
  Restart transaction for tables

  This is used when we had to do an implicit commit after tables are opened
  and want to restart transactions on tables.

  This is used in case of:
  LOCK TABLES xx
  CREATE OR REPLACE TABLE xx;
*/

bool restart_trans_for_tables(THD *thd, TABLE_LIST *table)
{
  DBUG_ENTER("restart_trans_for_tables");

  for (; table; table= table->next_global)
  {
    if (table->placeholder())
      continue;

    if (check_lock_and_start_stmt(thd, thd->lex, table))
    {
      DBUG_ASSERT(0);                           // Should never happen
      DBUG_RETURN(TRUE);
    }
  }
  DBUG_RETURN(FALSE);
}


5702
/**
5703 5704 5705
  Prepare statement for reopening of tables and recalculation of set of
  prelocked tables.

5706 5707 5708 5709 5710 5711 5712 5713 5714 5715
  @param[in] thd         Thread context.
  @param[in,out] tables  List of tables which we were trying to open
                         and lock.
  @param[in] start_of_statement_svp MDL savepoint which represents the set
                         of metadata locks which the current transaction
                         managed to acquire before execution of the current
                         statement and to which we should revert before
                         trying to reopen tables. NULL if no metadata locks
                         were held and thus all metadata locks should be
                         released.
5716 5717
*/

5718
void close_tables_for_reopen(THD *thd, TABLE_LIST **tables,
5719
                             const MDL_savepoint &start_of_statement_svp)
5720
{
Konstantin Osipov's avatar
Konstantin Osipov committed
5721 5722 5723
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
  TABLE_LIST *tmp;

5724 5725 5726 5727
  /*
    If table list consists only from tables from prelocking set, table list
    for new attempt should be empty, so we have to update list's root pointer.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
5728
  if (first_not_own_table == *tables)
5729
    *tables= 0;
5730
  thd->lex->chop_off_not_own_tables();
Konstantin Osipov's avatar
Konstantin Osipov committed
5731 5732 5733 5734 5735
  /* Reset MDL tickets for procedures/functions */
  for (Sroutine_hash_entry *rt=
         (Sroutine_hash_entry*)thd->lex->sroutines_list.first;
       rt; rt= rt->next)
    rt->mdl_request.ticket= NULL;
5736
  sp_remove_not_own_routines(thd->lex);
Konstantin Osipov's avatar
Konstantin Osipov committed
5737
  for (tmp= *tables; tmp; tmp= tmp->next_global)
Konstantin Osipov's avatar
Konstantin Osipov committed
5738
  {
5739
    tmp->table= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
5740
    tmp->mdl_request.ticket= NULL;
Konstantin Osipov's avatar
Konstantin Osipov committed
5741 5742
    /* We have to cleanup translation tables of views. */
    tmp->cleanup_items();
Konstantin Osipov's avatar
Konstantin Osipov committed
5743
  }
5744 5745 5746 5747 5748 5749
  /*
    No need to commit/rollback the statement transaction: it's
    either not started or we're filling in an INFORMATION_SCHEMA
    table on the fly, and thus mustn't manipulate with the
    transaction of the enclosing statement.
  */
5750
  DBUG_ASSERT(thd->transaction->stmt.is_empty() ||
5751
              (thd->state_flags & Open_tables_state::BACKUPS_AVAIL));
Konstantin Osipov's avatar
Konstantin Osipov committed
5752
  close_thread_tables(thd);
5753
  thd->mdl_context.rollback_to_savepoint(start_of_statement_svp);
5754 5755 5756
}


unknown's avatar
unknown committed
5757
/*****************************************************************************
unknown's avatar
unknown committed
5758 5759 5760 5761 5762 5763
* The following find_field_in_XXX procedures implement the core of the
* name resolution functionality. The entry point to resolve a column name in a
* list of tables is 'find_field_in_tables'. It calls 'find_field_in_table_ref'
* for each table reference. In turn, depending on the type of table reference,
* 'find_field_in_table_ref' calls one of the 'find_field_in_XXX' procedures
* below specific for the type of table reference.
unknown's avatar
unknown committed
5764 5765
******************************************************************************/

unknown's avatar
unknown committed
5766
/* Special Field pointers as return values of find_field_in_XXX functions. */
unknown's avatar
unknown committed
5767 5768
Field *not_found_field= (Field*) 0x1;
Field *view_ref_found= (Field*) 0x2; 
unknown's avatar
VIEW  
unknown committed
5769

unknown's avatar
unknown committed
5770 5771
#define WRONG_GRANT (Field*) -1

unknown's avatar
unknown committed
5772 5773
static void update_field_dependencies(THD *thd, Field *field, TABLE *table)
{
5774
  DBUG_ENTER("update_field_dependencies");
5775
  if (should_mark_column(thd->column_usage))
unknown's avatar
unknown committed
5776
  {
5777 5778 5779 5780
    /*
      We always want to register the used keys, as the column bitmap may have
      been set for all fields (for example for view).
    */
5781
    table->covering_keys.intersect(field->part_of_key);
5782

Sergei Golubchik's avatar
Sergei Golubchik committed
5783
    if (thd->column_usage == MARK_COLUMNS_READ)
5784 5785 5786 5787
    {
      if (table->mark_column_with_deps(field))
        DBUG_VOID_RETURN; // Field was already marked
    }
unknown's avatar
unknown committed
5788
    else
5789
    {
5790
      if (bitmap_fast_test_and_set(table->write_set, field->field_index))
5791 5792 5793
      {
        DBUG_PRINT("warning", ("Found duplicated field"));
        thd->dup_field= field;
5794
        DBUG_VOID_RETURN;
5795 5796
      }
    }
5797

5798 5799
    table->used_fields++;
  }
5800
  if (table->get_fields_in_item_tree)
5801
    field->flags|= GET_FIXED_FIELDS_FLAG;
5802
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
5803 5804
}

unknown's avatar
VIEW  
unknown committed
5805 5806

/*
unknown's avatar
unknown committed
5807
  Find a field by name in a view that uses merge algorithm.
unknown's avatar
VIEW  
unknown committed
5808 5809

  SYNOPSIS
unknown's avatar
unknown committed
5810
    find_field_in_view()
unknown's avatar
VIEW  
unknown committed
5811
    thd				thread handler
unknown's avatar
unknown committed
5812
    table_list			view to search for 'name'
unknown's avatar
VIEW  
unknown committed
5813 5814
    name			name of field
    length			length of name
5815
    item_name                   name of item if it will be created (VIEW)
unknown's avatar
unknown committed
5816 5817
    ref				expression substituted in VIEW should be passed
                                using this reference (return view_ref_found)
unknown's avatar
unknown committed
5818
    register_tree_change        TRUE if ref is not stack variable and we
unknown's avatar
unknown committed
5819
                                need register changes in item tree
unknown's avatar
VIEW  
unknown committed
5820 5821 5822 5823

  RETURN
    0			field is not found
    view_ref_found	found value in VIEW (real result is in *ref)
unknown's avatar
unknown committed
5824
    #			pointer to field - only for schema table fields
unknown's avatar
VIEW  
unknown committed
5825 5826
*/

unknown's avatar
unknown committed
5827 5828
static Field *
find_field_in_view(THD *thd, TABLE_LIST *table_list,
5829
                   const char *name, size_t length,
5830
                   const char *item_name, Item **ref,
unknown's avatar
unknown committed
5831
                   bool register_tree_change)
unknown's avatar
VIEW  
unknown committed
5832
{
unknown's avatar
unknown committed
5833 5834
  DBUG_ENTER("find_field_in_view");
  DBUG_PRINT("enter",
5835
             ("view: '%s', field name: '%s', item name: '%s', ref %p",
5836
              table_list->alias.str, name, item_name, ref));
unknown's avatar
unknown committed
5837 5838
  Field_iterator_view field_it;
  field_it.set(table_list);
unknown's avatar
unknown committed
5839
  Query_arena *arena= 0, backup;  
5840

unknown's avatar
unknown committed
5841
  for (; !field_it.end_of_fields(); field_it.next())
unknown's avatar
VIEW  
unknown committed
5842
  {
5843
    if (!my_strcasecmp(system_charset_info, field_it.name()->str, name))
5844
    {
5845
      // in PS use own arena or data will be freed after prepare
5846 5847
      if (register_tree_change &&
          thd->stmt_arena->is_stmt_prepare_or_first_stmt_execute())
5848
        arena= thd->activate_stmt_arena_if_needed(&backup);
5849 5850 5851 5852
      /*
        create_item() may, or may not create a new Item, depending on
        the column reference. See create_view_field() for details.
      */
unknown's avatar
unknown committed
5853
      Item *item= field_it.create_item(thd);
unknown's avatar
unknown committed
5854
      if (arena)
5855 5856
        thd->restore_active_arena(arena, &backup);
      
unknown's avatar
unknown committed
5857 5858
      if (!item)
        DBUG_RETURN(0);
5859 5860
      if (!ref)
        DBUG_RETURN((Field*) view_ref_found);
unknown's avatar
unknown committed
5861 5862 5863 5864 5865
      /*
       *ref != NULL means that *ref contains the item that we need to
       replace. If the item was aliased by the user, set the alias to
       the replacing item.
      */
5866
      if (*ref && (*ref)->is_explicit_name())
5867
        item->set_name(thd, (*ref)->name);
unknown's avatar
unknown committed
5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895
      if (register_tree_change)
        thd->change_item_tree(ref, item);
      else
        *ref= item;
      DBUG_RETURN((Field*) view_ref_found);
    }
  }
  DBUG_RETURN(0);
}


/*
  Find field by name in a NATURAL/USING join table reference.

  SYNOPSIS
    find_field_in_natural_join()
    thd			 [in]  thread handler
    table_ref            [in]  table reference to search
    name		 [in]  name of field
    length		 [in]  length of name
    ref                  [in/out] if 'name' is resolved to a view field, ref is
                               set to point to the found view field
    register_tree_change [in]  TRUE if ref is not stack variable and we
                               need register changes in item tree
    actual_table         [out] the original table reference where the field
                               belongs - differs from 'table_list' only for
                               NATURAL/USING joins

5896 5897 5898 5899 5900 5901
  DESCRIPTION
    Search for a field among the result fields of a NATURAL/USING join.
    Notice that this procedure is called only for non-qualified field
    names. In the case of qualified fields, we search directly the base
    tables of a natural join.

unknown's avatar
unknown committed
5902
  RETURN
5903 5904 5905
    NULL        if the field was not found
    WRONG_GRANT if no access rights to the found field
    #           Pointer to the found Field
unknown's avatar
unknown committed
5906 5907 5908
*/

static Field *
5909
find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name, size_t length, Item **ref, bool register_tree_change,
5910
                           TABLE_LIST **actual_table)
unknown's avatar
unknown committed
5911
{
5912 5913
  List_iterator_fast<Natural_join_column>
    field_it(*(table_ref->join_columns));
5914
  Natural_join_column *nj_col, *curr_nj_col;
5915 5916
  Field *UNINIT_VAR(found_field);
  Query_arena *UNINIT_VAR(arena), backup;
unknown's avatar
unknown committed
5917
  DBUG_ENTER("find_field_in_natural_join");
5918 5919
  DBUG_PRINT("enter", ("field name: '%s', ref %p",
		       name, ref));
unknown's avatar
unknown committed
5920
  DBUG_ASSERT(table_ref->is_natural_join && table_ref->join_columns);
5921
  DBUG_ASSERT(*actual_table == NULL);
unknown's avatar
unknown committed
5922

5923 5924
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col; 
       curr_nj_col= field_it++)
unknown's avatar
unknown committed
5925
  {
5926
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name()->str, name))
5927 5928 5929 5930 5931 5932 5933 5934
    {
      if (nj_col)
      {
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
        DBUG_RETURN(NULL);
      }
      nj_col= curr_nj_col;
    }
unknown's avatar
VIEW  
unknown committed
5935
  }
5936 5937
  if (!nj_col)
    DBUG_RETURN(NULL);
unknown's avatar
unknown committed
5938 5939 5940

  if (nj_col->view_field)
  {
unknown's avatar
unknown committed
5941
    Item *item;
5942 5943
    if (register_tree_change)
      arena= thd->activate_stmt_arena_if_needed(&backup);
5944 5945 5946 5947
    /*
      create_item() may, or may not create a new Item, depending on the
      column reference. See create_view_field() for details.
    */
unknown's avatar
unknown committed
5948
    item= nj_col->create_item(thd);
5949 5950 5951
    if (!item)
      DBUG_RETURN(NULL);

5952 5953 5954 5955 5956
    /*
     *ref != NULL means that *ref contains the item that we need to
     replace. If the item was aliased by the user, set the alias to
     the replacing item.
     */
5957
    if (*ref && (*ref)->is_explicit_name())
5958
      item->set_name(thd, (*ref)->name);
5959 5960 5961
    if (register_tree_change && arena)
      thd->restore_active_arena(arena, &backup);

unknown's avatar
unknown committed
5962 5963 5964 5965
    if (!item)
      DBUG_RETURN(NULL);
    DBUG_ASSERT(nj_col->table_field == NULL);
    if (nj_col->table_ref->schema_table_reformed)
5966
    {
unknown's avatar
unknown committed
5967 5968 5969 5970 5971 5972
      /*
        Translation table items are always Item_fields and fixed
        already('mysql_schema_table' function). So we can return
        ->field. It is used only for 'show & where' commands.
      */
      DBUG_RETURN(((Item_field*) (nj_col->view_field->item))->field);
5973
    }
unknown's avatar
unknown committed
5974 5975 5976 5977 5978 5979 5980 5981 5982 5983
    if (register_tree_change)
      thd->change_item_tree(ref, item);
    else
      *ref= item;
    found_field= (Field*) view_ref_found;
  }
  else
  {
    /* This is a base table. */
    DBUG_ASSERT(nj_col->view_field == NULL);
5984
    Item *ref= 0;
5985 5986 5987 5988 5989 5990
    /*
      This fix_fields is not necessary (initially this item is fixed by
      the Item_field constructor; after reopen_tables the Item_func_eq
      calls fix_fields on that item), it's just a check during table
      reopening for columns that was dropped by the concurrent connection.
    */
5991
    if (nj_col->table_field->fix_fields_if_needed(thd, &ref))
5992 5993
    {
      DBUG_PRINT("info", ("column '%s' was dropped by the concurrent connection",
5994
                          nj_col->table_field->name.str));
5995 5996
      DBUG_RETURN(NULL);
    }
5997
    DBUG_ASSERT(ref == 0);                      // Should not have changed
5998 5999
    DBUG_ASSERT(nj_col->table_ref->table == nj_col->table_field->field->table);
    found_field= nj_col->table_field->field;
unknown's avatar
unknown committed
6000 6001 6002 6003 6004 6005
    update_field_dependencies(thd, found_field, nj_col->table_ref->table);
  }

  *actual_table= nj_col->table_ref;
  
  DBUG_RETURN(found_field);
unknown's avatar
VIEW  
unknown committed
6006 6007
}

6008

unknown's avatar
VIEW  
unknown committed
6009
/*
unknown's avatar
unknown committed
6010
  Find field by name in a base table or a view with temp table algorithm.
unknown's avatar
VIEW  
unknown committed
6011

6012 6013
  The caller is expected to check column-level privileges.

unknown's avatar
VIEW  
unknown committed
6014
  SYNOPSIS
unknown's avatar
unknown committed
6015
    find_field_in_table()
unknown's avatar
VIEW  
unknown committed
6016
    thd				thread handler
unknown's avatar
unknown committed
6017
    table			table where to search for the field
unknown's avatar
VIEW  
unknown committed
6018 6019 6020
    name			name of field
    length			length of name
    allow_rowid			do allow finding of "_rowid" field?
unknown's avatar
unknown committed
6021 6022
    cached_field_index_ptr	cached position in field list (used to speedup
                                lookup for fields in prepared tables)
unknown's avatar
VIEW  
unknown committed
6023 6024

  RETURN
6025 6026
    0	field is not found
    #	pointer to field
unknown's avatar
VIEW  
unknown committed
6027 6028
*/

unknown's avatar
unknown committed
6029
Field *
6030
find_field_in_table(THD *thd, TABLE *table, const char *name, size_t length,
6031
                    bool allow_rowid, field_index_t *cached_field_index_ptr)
unknown's avatar
unknown committed
6032
{
6033
  Field *field;
6034
  field_index_t cached_field_index= *cached_field_index_ptr;
6035
  DBUG_ENTER("find_field_in_table");
6036 6037
  DBUG_PRINT("enter", ("table: '%s', field name: '%s'", table->alias.c_ptr(),
                       name));
unknown's avatar
unknown committed
6038 6039

  /* We assume here that table->field < NO_CACHED_FIELD_INDEX = UINT_MAX */
6040
  if (cached_field_index < table->s->fields &&
6041
      !my_strcasecmp(system_charset_info,
6042
                     table->field[cached_field_index]->field_name.str, name))
6043
  {
6044
    field= table->field[cached_field_index];
6045 6046
    DEBUG_SYNC(thd, "table_field_cached");
  }
unknown's avatar
unknown committed
6047 6048
  else
  {
6049 6050
    LEX_CSTRING fname= {name, length};
    field= table->find_field_by_name(&fname);
unknown's avatar
unknown committed
6051 6052
  }

6053
  if (field)
unknown's avatar
unknown committed
6054
  {
6055
    if (field->invisible == INVISIBLE_FULL &&
6056
        DBUG_EVALUATE_IF("test_completely_invisible", 0, 1))
6057
      DBUG_RETURN((Field*)0);
6058 6059 6060 6061 6062

    if (field->invisible == INVISIBLE_SYSTEM &&
        thd->column_usage != MARK_COLUMNS_READ &&
        thd->column_usage != COLUMNS_READ)
      DBUG_RETURN((Field*)0);
unknown's avatar
unknown committed
6063 6064 6065
  }
  else
  {
unknown's avatar
unknown committed
6066 6067
    if (!allow_rowid ||
        my_strcasecmp(system_charset_info, name, "_rowid") ||
unknown's avatar
unknown committed
6068
        table->s->rowid_field_offset == 0)
unknown's avatar
unknown committed
6069
      DBUG_RETURN((Field*) 0);
unknown's avatar
unknown committed
6070
    field= table->field[table->s->rowid_field_offset-1];
unknown's avatar
unknown committed
6071
  }
6072
  *cached_field_index_ptr= field->field_index;
unknown's avatar
unknown committed
6073

unknown's avatar
unknown committed
6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087
  update_field_dependencies(thd, field, table);

  DBUG_RETURN(field);
}


/*
  Find field in a table reference.

  SYNOPSIS
    find_field_in_table_ref()
    thd			   [in]  thread handler
    table_list		   [in]  table reference to search
    name		   [in]  name of field
6088
    length		   [in]  field length of name
unknown's avatar
unknown committed
6089 6090
    item_name              [in]  name of item if it will be created (VIEW)
    db_name                [in]  optional database name that qualifies the
6091
    table_name             [in]  optional table name that qualifies the field
6092
                                 0 for non-qualified field in natural joins
unknown's avatar
unknown committed
6093 6094
    ref		       [in/out] if 'name' is resolved to a view field, ref
                                 is set to point to the found view field
6095
    check_privileges       [in]  check privileges
unknown's avatar
unknown committed
6096 6097 6098 6099 6100 6101 6102 6103 6104
    allow_rowid		   [in]  do allow finding of "_rowid" field?
    cached_field_index_ptr [in]  cached position in field list (used to
                                 speedup lookup for fields in prepared tables)
    register_tree_change   [in]  TRUE if ref is not stack variable and we
                                 need register changes in item tree
    actual_table           [out] the original table reference where the field
                                 belongs - differs from 'table_list' only for
                                 NATURAL_USING joins.

unknown's avatar
unknown committed
6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
  DESCRIPTION
    Find a field in a table reference depending on the type of table
    reference. There are three types of table references with respect
    to the representation of their result columns:
    - an array of Field_translator objects for MERGE views and some
      information_schema tables,
    - an array of Field objects (and possibly a name hash) for stored
      tables,
    - a list of Natural_join_column objects for NATURAL/USING joins.
    This procedure detects the type of the table reference 'table_list'
    and calls the corresponding search routine.

6117 6118
    The routine checks column-level privieleges for the found field.

unknown's avatar
unknown committed
6119 6120 6121 6122 6123 6124 6125 6126
  RETURN
    0			field is not found
    view_ref_found	found value in VIEW (real result is in *ref)
    #			pointer to field
*/

Field *
find_field_in_table_ref(THD *thd, TABLE_LIST *table_list,
6127
                        const char *name, size_t length,
6128
                        const char *item_name, const char *db_name,
6129 6130
                        const char *table_name,
                        ignored_tables_list_t ignored_tables,
6131
                        Item **ref,
6132
                        bool check_privileges, bool allow_rowid,
6133
                        field_index_t *cached_field_index_ptr,
unknown's avatar
unknown committed
6134 6135 6136 6137
                        bool register_tree_change, TABLE_LIST **actual_table)
{
  Field *fld;
  DBUG_ENTER("find_field_in_table_ref");
6138
  DBUG_ASSERT(table_list->alias.str);
unknown's avatar
unknown committed
6139 6140
  DBUG_ASSERT(name);
  DBUG_ASSERT(item_name);
unknown's avatar
unknown committed
6141
  DBUG_PRINT("enter",
6142
             ("table: '%s'  field name: '%s'  item name: '%s'  ref %p",
6143
              table_list->alias.str, name, item_name, ref));
unknown's avatar
unknown committed
6144 6145 6146

  /*
    Check that the table and database that qualify the current field name
unknown's avatar
unknown committed
6147 6148
    are the same as the table reference we are going to search for the field.

6149 6150 6151 6152
    Exclude from the test below nested joins because the columns in a
    nested join generally originate from different tables. Nested joins
    also have no table name, except when a nested join is a merge view
    or an information schema table.
unknown's avatar
unknown committed
6153 6154 6155 6156 6157 6158

    We include explicitly table references with a 'field_translation' table,
    because if there are views over natural joins we don't want to search
    inside the view, but we want to search directly in the view columns
    which are represented as a 'field_translation'.

6159 6160 6161
    tables->db.str may be 0 if we are preparing a statement
    db_name is 0 if item doesn't have a db name
    table_name is 0 if item doesn't have a specified table_name
unknown's avatar
unknown committed
6162
  */
6163 6164 6165
  if (db_name && !db_name[0])
    db_name= 0;                                 // Simpler test later

6166 6167
  if (/* Exclude nested joins. */
      (!table_list->nested_join ||
unknown's avatar
unknown committed
6168 6169 6170 6171 6172 6173
       /* Include merge views and information schema tables. */
       table_list->field_translation) &&
      /*
        Test if the field qualifiers match the table reference we plan
        to search.
      */
6174
      table_name && table_name[0] &&
6175 6176 6177
      (my_strcasecmp(table_alias_charset, table_list->alias.str, table_name) ||
       (db_name && (!table_list->db.str || !table_list->db.str[0])) ||
       (db_name && table_list->db.str && table_list->db.str[0] &&
6178
        (table_list->schema_table ?
6179 6180
         my_strcasecmp(system_charset_info, db_name, table_list->db.str) :
         strcmp(db_name, table_list->db.str)))))
unknown's avatar
unknown committed
6181 6182
    DBUG_RETURN(0);

6183 6184 6185 6186 6187 6188 6189
  /*
    Don't allow usage of fields in sequence table that is opened as part of
    NEXT VALUE for sequence_name
  */
  if (table_list->sequence)
    DBUG_RETURN(0);

6190
  *actual_table= NULL;
unknown's avatar
unknown committed
6191

unknown's avatar
unknown committed
6192 6193
  if (table_list->field_translation)
  {
unknown's avatar
unknown committed
6194
    /* 'table_list' is a view or an information schema table. */
6195
    if ((fld= find_field_in_view(thd, table_list, name, length, item_name, ref,
6196
                                 register_tree_change)))
unknown's avatar
unknown committed
6197 6198
      *actual_table= table_list;
  }
6199
  else if (!table_list->nested_join)
6200
  {
6201 6202
    /* 'table_list' is a stored table. */
    DBUG_ASSERT(table_list->table);
unknown's avatar
unknown committed
6203
    if ((fld= find_field_in_table(thd, table_list->table, name, length,
6204 6205
                                  allow_rowid,
                                  cached_field_index_ptr)))
unknown's avatar
unknown committed
6206 6207 6208
      *actual_table= table_list;
  }
  else
6209
  {
unknown's avatar
unknown committed
6210
    /*
unknown's avatar
unknown committed
6211 6212 6213 6214 6215
      'table_list' is a NATURAL/USING join, or an operand of such join that
      is a nested join itself.

      If the field name we search for is qualified, then search for the field
      in the table references used by NATURAL/USING the join.
unknown's avatar
unknown committed
6216
    */
6217 6218 6219 6220 6221 6222
    if (table_name && table_name[0])
    {
      List_iterator<TABLE_LIST> it(table_list->nested_join->join_list);
      TABLE_LIST *table;
      while ((table= it++))
      {
6223 6224 6225 6226 6227
        /*
          Check if the table is in the ignore list. Only base tables can be in
          the ignore list.
        */
        if (table->table && ignored_list_includes_table(ignored_tables, table))
6228
          continue;
6229

6230
        if ((fld= find_field_in_table_ref(thd, table, name, length, item_name,
6231 6232
                                          db_name, table_name, ignored_tables,
                                          ref, check_privileges, allow_rowid,
6233
                                          cached_field_index_ptr,
6234 6235 6236 6237 6238 6239 6240
                                          register_tree_change, actual_table)))
          DBUG_RETURN(fld);
      }
      DBUG_RETURN(0);
    }
    /*
      Non-qualified field, search directly in the result columns of the
unknown's avatar
unknown committed
6241 6242 6243
      natural join. The condition of the outer IF is true for the top-most
      natural join, thus if the field is not qualified, we will search
      directly the top-most NATURAL/USING join.
6244 6245
    */
    fld= find_field_in_natural_join(thd, table_list, name, length, ref,
unknown's avatar
unknown committed
6246
                                    register_tree_change, actual_table);
6247
  }
unknown's avatar
unknown committed
6248

6249 6250
  if (fld)
  {
6251
#ifndef NO_EMBEDDED_ACCESS_CHECKS
6252 6253
    /* Check if there are sufficient access rights to the found field. */
    if (check_privileges &&
6254
        !table_list->is_derived() &&
6255
        check_column_grant_in_table_ref(thd, *actual_table, name, length, fld))
6256 6257
      fld= WRONG_GRANT;
    else
6258
#endif
6259
      if (should_mark_column(thd->column_usage))
6260
      {
6261
        /*
6262 6263 6264
          Get rw_set correct for this field so that the handler
          knows that this field is involved in the query and gets
          retrieved/updated
6265
         */
6266 6267 6268
        Field *field_to_set= NULL;
        if (fld == view_ref_found)
        {
6269 6270
          if (!ref)
            DBUG_RETURN(fld);
6271 6272 6273
          Item *it= (*ref)->real_item();
          if (it->type() == Item::FIELD_ITEM)
            field_to_set= ((Item_field*)it)->field;
6274 6275
          else
          {
Sergei Golubchik's avatar
Sergei Golubchik committed
6276
            if (thd->column_usage == MARK_COLUMNS_READ)
6277
              it->walk(&Item::register_field_in_read_map, 0, 0);
6278
            else
6279
              it->walk(&Item::register_field_in_write_map, 0, 0);
6280
          }
6281 6282 6283 6284
        }
        else
          field_to_set= fld;
        if (field_to_set)
6285 6286
        {
          TABLE *table= field_to_set->table;
6287
          DBUG_ASSERT(table);
Sergei Golubchik's avatar
Sergei Golubchik committed
6288
          if (thd->column_usage == MARK_COLUMNS_READ)
6289
            field_to_set->register_field_in_read_map();
6290 6291 6292
          else
            bitmap_set_bit(table->write_set, field_to_set->field_index);
        }
6293 6294
      }
  }
unknown's avatar
unknown committed
6295
  DBUG_RETURN(fld);
unknown's avatar
unknown committed
6296 6297
}

6298

6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317
/*
  Find field in table, no side effects, only purpose is to check for field
  in table object and get reference to the field if found.

  SYNOPSIS
  find_field_in_table_sef()

  table                         table where to find
  name                          Name of field searched for

  RETURN
    0                   field is not found
    #                   pointer to field
*/

Field *find_field_in_table_sef(TABLE *table, const char *name)
{
  Field **field_ptr;
  if (table->s->name_hash.records)
unknown's avatar
unknown committed
6318
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
6319 6320
    field_ptr= (Field**)my_hash_search(&table->s->name_hash,(uchar*) name,
                                       strlen(name));
unknown's avatar
unknown committed
6321 6322 6323 6324 6325 6326 6327 6328 6329
    if (field_ptr)
    {
      /*
        field_ptr points to field in TABLE_SHARE. Convert it to the matching
        field in table
      */
      field_ptr= (table->field + (field_ptr - table->s->field));
    }
  }
6330 6331 6332 6333 6334
  else
  {
    if (!(field_ptr= table->field))
      return (Field *)0;
    for (; *field_ptr; ++field_ptr)
6335 6336
      if (!my_strcasecmp(system_charset_info, (*field_ptr)->field_name.str,
                         name))
6337 6338 6339 6340 6341 6342 6343 6344 6345
        break;
  }
  if (field_ptr)
    return *field_ptr;
  else
    return (Field *)0;
}


6346 6347 6348 6349 6350
/*
  Find field in table list.

  SYNOPSIS
    find_field_in_tables()
unknown's avatar
unknown committed
6351 6352 6353 6354 6355
    thd			  pointer to current thread structure
    item		  field item that should be found
    first_table           list of tables to be searched for item
    last_table            end of the list of tables to search for item. If NULL
                          then search to the end of the list 'first_table'.
6356 6357
    ignored_tables        Set of tables that should be ignored. Do not try to
                          find the field in those.
unknown's avatar
unknown committed
6358
    ref			  if 'item' is resolved to a view field, ref is set to
6359
                          point to the found view field
unknown's avatar
unknown committed
6360
    report_error	  Degree of error reporting:
6361 6362
                          - IGNORE_ERRORS then do not report any error
                          - IGNORE_EXCEPT_NON_UNIQUE report only non-unique
unknown's avatar
unknown committed
6363
                            fields, suppress all other errors
6364 6365 6366 6367
                          - REPORT_EXCEPT_NON_UNIQUE report all other errors
                            except when non-unique fields were found
                          - REPORT_ALL_ERRORS
    check_privileges      need to check privileges
unknown's avatar
unknown committed
6368 6369
    register_tree_change  TRUE if ref is not a stack variable and we
                          to need register changes in item tree
6370 6371

  RETURN VALUES
6372 6373 6374
    0			If error: the found field is not unique, or there are
                        no sufficient access priviliges for the found field,
                        or the field is qualified with non-existing table.
6375 6376 6377 6378 6379
    not_found_field	The function was called with report_error ==
                        (IGNORE_ERRORS || IGNORE_EXCEPT_NON_UNIQUE) and a
			field was not found.
    view_ref_found	View field is found, item passed through ref parameter
    found field         If a item was resolved to some field
6380
*/
unknown's avatar
unknown committed
6381 6382

Field *
unknown's avatar
unknown committed
6383 6384
find_field_in_tables(THD *thd, Item_ident *item,
                     TABLE_LIST *first_table, TABLE_LIST *last_table,
6385
                     ignored_tables_list_t ignored_tables,
6386
		     Item **ref, find_item_error_report_type report_error,
6387
                     bool check_privileges, bool register_tree_change)
unknown's avatar
unknown committed
6388 6389
{
  Field *found=0;
6390 6391
  const char *db= item->db_name.str;
  const char *table_name= item->table_name.str;
6392
  const char *name= item->field_name.str;
6393
  size_t length= item->field_name.length;
6394
  char name_buff[SAFE_NAME_LEN+1];
unknown's avatar
unknown committed
6395 6396
  TABLE_LIST *cur_table= first_table;
  TABLE_LIST *actual_table;
unknown's avatar
unknown committed
6397 6398 6399 6400 6401 6402 6403 6404 6405
  bool allow_rowid;

  if (!table_name || !table_name[0])
  {
    table_name= 0;                              // For easier test
    db= 0;
  }

  allow_rowid= table_name || (cur_table && !cur_table->next_local);
unknown's avatar
unknown committed
6406

unknown's avatar
unknown committed
6407 6408
  if (item->cached_table)
  {
Monty's avatar
Monty committed
6409
    DBUG_PRINT("info", ("using cached table"));
unknown's avatar
unknown committed
6410
    /*
unknown's avatar
unknown committed
6411 6412
      This shortcut is used by prepared statements. We assume that
      TABLE_LIST *first_table is not changed during query execution (which
6413
      is true for all queries except RENAME but luckily RENAME doesn't
unknown's avatar
unknown committed
6414
      use fields...) so we can rely on reusing pointer to its member.
unknown's avatar
unknown committed
6415
      With this optimization we also miss case when addition of one more
6416
      field makes some prepared query ambiguous and so erroneous, but we
unknown's avatar
unknown committed
6417 6418
      accept this trade off.
    */
unknown's avatar
unknown committed
6419 6420 6421 6422 6423 6424
    TABLE_LIST *table_ref= item->cached_table;
    /*
      The condition (table_ref->view == NULL) ensures that we will call
      find_field_in_table even in the case of information schema tables
      when table_ref->field_translation != NULL.
      */
6425
    if (table_ref->table && !table_ref->view &&
6426 6427
        (!table_ref->is_merged_derived() ||
         (!table_ref->is_multitable() && table_ref->merged_for_insert)))
6428
    {
6429

unknown's avatar
unknown committed
6430
      found= find_field_in_table(thd, table_ref->table, name, length,
6431
                                 TRUE, &(item->cached_field_index));
6432 6433
#ifndef NO_EMBEDDED_ACCESS_CHECKS
      /* Check if there are sufficient access rights to the found field. */
6434
      if (found && check_privileges && !is_temporary_table(table_ref) &&
6435 6436
          check_column_grant_in_table_ref(thd, table_ref, name, length,
                                          found))
6437 6438 6439
        found= WRONG_GRANT;
#endif
    }
6440
    else
6441
      found= find_field_in_table_ref(thd, table_ref, name, length, item->name.str,
6442 6443 6444
                                     NULL, NULL, ignored_tables, ref,
                                     check_privileges, TRUE,
                                     &(item->cached_field_index),
unknown's avatar
unknown committed
6445 6446
                                     register_tree_change,
                                     &actual_table);
unknown's avatar
unknown committed
6447 6448 6449
    if (found)
    {
      if (found == WRONG_GRANT)
6450
	return (Field*) 0;
6451 6452 6453 6454 6455

      /*
        Only views fields should be marked as dependent, not an underlying
        fields.
      */
6456 6457
      if (!table_ref->belong_to_view &&
          !table_ref->belong_to_derived)
6458
      {
6459
        SELECT_LEX *current_sel= item->context->select_lex;
unknown's avatar
unknown committed
6460
        SELECT_LEX *last_select= table_ref->select_lex;
6461 6462 6463 6464 6465
        bool all_merged= TRUE;
        for (SELECT_LEX *sl= current_sel; sl && sl!=last_select;
             sl=sl->outer_select())
        {
          Item *subs= sl->master_unit()->item;
6466 6467 6468 6469
          if (!subs)
            continue;

          Item_in_subselect *in_subs= subs->get_IN_subquery();
6470 6471 6472
          if (in_subs &&
              in_subs->substype() == Item_subselect::IN_SUBS &&
              in_subs->test_strategy(SUBS_SEMI_JOIN))
6473 6474 6475 6476 6477 6478
          {
            continue;
          }
          all_merged= FALSE;
          break;
        }
unknown's avatar
unknown committed
6479 6480
        /*
          If the field was an outer referencee, mark all selects using this
unknown's avatar
unknown committed
6481
          sub query as dependent on the outer query
unknown's avatar
unknown committed
6482
        */
6483
        if (!all_merged && current_sel != last_select)
unknown's avatar
unknown committed
6484
        {
unknown's avatar
unknown committed
6485
          mark_select_range_as_dependent(thd, last_select, current_sel,
6486
                                         found, *ref, item, true);
unknown's avatar
unknown committed
6487
        }
6488
      }
unknown's avatar
unknown committed
6489 6490 6491
      return found;
    }
  }
unknown's avatar
unknown committed
6492 6493
  else
    item->can_be_depended= TRUE;
unknown's avatar
unknown committed
6494

6495 6496 6497
  if (db && lower_case_table_names)
  {
    /*
unknown's avatar
unknown committed
6498
      convert database to lower case for comparison.
6499 6500 6501
      We can't do this in Item_field as this would change the
      'name' of the item which may be used in the select list
    */
6502
    strmake_buf(name_buff, db);
unknown's avatar
unknown committed
6503
    my_casedn_str(files_charset_info, name_buff);
6504 6505
    db= name_buff;
  }
unknown's avatar
unknown committed
6506

6507
  if (last_table)
6508 6509
    last_table= last_table->next_name_resolution_table;

Marko Mäkelä's avatar
Marko Mäkelä committed
6510
  field_index_t fake_index_for_duplicate_search= NO_CACHED_FIELD_INDEX;
6511 6512 6513 6514 6515
  /*
    For the field search it will point to field cache, but for duplicate
    search it will point to fake_index_for_duplicate_search (no cache
    present).
  */
Marko Mäkelä's avatar
Marko Mäkelä committed
6516
  field_index_t *current_cache= &(item->cached_field_index);
6517 6518
  for (; cur_table != last_table ;
       cur_table= cur_table->next_name_resolution_table)
unknown's avatar
unknown committed
6519
  {
6520 6521
    if (cur_table->table &&
        ignored_list_includes_table(ignored_tables, cur_table))
6522 6523
      continue;

6524
    Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,
6525 6526
                                              item->name.str, db, table_name,
                                              ignored_tables, ref,
6527 6528 6529
                                              (thd->lex->sql_command ==
                                               SQLCOM_SHOW_FIELDS)
                                              ? false : check_privileges,
6530
                                              allow_rowid,
6531
                                              current_cache,
unknown's avatar
unknown committed
6532 6533 6534
                                              register_tree_change,
                                              &actual_table);
    if (cur_field)
6535
    {
unknown's avatar
unknown committed
6536
      if (cur_field == WRONG_GRANT)
6537 6538 6539 6540 6541 6542
      {
        if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)
          return (Field*) 0;

        thd->clear_error();
        cur_field= find_field_in_table_ref(thd, cur_table, name, length,
6543 6544
                                           item->name.str, db, table_name,
                                           ignored_tables, ref, false,
6545
                                           allow_rowid,
6546
                                           current_cache,
6547 6548 6549 6550 6551
                                           register_tree_change,
                                           &actual_table);
        if (cur_field)
        {
          Field *nf=new Field_null(NULL,0,Field::NONE,
6552
                                   &cur_field->field_name,
6553
                                   &my_charset_bin);
6554
          nf->init(cur_table->table);
6555 6556 6557
          cur_field= nf;
        }
      }
unknown's avatar
unknown committed
6558 6559 6560 6561 6562

      /*
        Store the original table of the field, which may be different from
        cur_table in the case of NATURAL/USING join.
      */
6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575
      if (actual_table->cacheable_table /*(1)*/ && !found /*(2)*/)
      {
        /*
          We have just found a field allowed to cache (1) and
          it is not dublicate search (2).
        */
        item->cached_table= actual_table;
      }
      else
      {
        item->cached_table= NULL;
        item->cached_field_index= NO_CACHED_FIELD_INDEX;
      }
unknown's avatar
unknown committed
6576

6577 6578 6579 6580 6581
      DBUG_ASSERT(thd->where);
      /*
        If we found a fully qualified field we return it directly as it can't
        have duplicates.
       */
unknown's avatar
unknown committed
6582
      if (db)
6583
        return cur_field;
6584
      
6585
      if (unlikely(found))
unknown's avatar
unknown committed
6586
      {
6587 6588
        if (report_error == REPORT_ALL_ERRORS ||
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
6589
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
unknown's avatar
unknown committed
6590
                   table_name ? item->full_name() : name, thd->where);
6591
        return (Field*) 0;
unknown's avatar
unknown committed
6592
      }
unknown's avatar
unknown committed
6593
      found= cur_field;
6594
      current_cache= &fake_index_for_duplicate_search;
unknown's avatar
unknown committed
6595 6596
    }
  }
6597

6598
  if (likely(found))
unknown's avatar
unknown committed
6599
    return found;
6600
  
6601 6602 6603 6604 6605 6606 6607
  /*
    If the field was qualified and there were no tables to search, issue
    an error that an unknown table was given. The situation is detected
    as follows: if there were no tables we wouldn't go through the loop
    and cur_table wouldn't be updated by the loop increment part, so it
    will be equal to the first table.
  */
unknown's avatar
unknown committed
6608
  if (table_name && (cur_table == first_table) &&
6609 6610 6611
      (report_error == REPORT_ALL_ERRORS ||
       report_error == REPORT_EXCEPT_NON_UNIQUE))
  {
6612
    char buff[SAFE_NAME_LEN*2 + 2];
6613 6614 6615 6616 6617 6618 6619
    if (db && db[0])
    {
      strxnmov(buff,sizeof(buff)-1,db,".",table_name,NullS);
      table_name=buff;
    }
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
  }
6620
  else
unknown's avatar
unknown committed
6621
  {
6622 6623 6624 6625 6626
    if (report_error == REPORT_ALL_ERRORS ||
        report_error == REPORT_EXCEPT_NON_UNIQUE)
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);
    else
      found= not_found_field;
unknown's avatar
unknown committed
6627
  }
6628
  return found;
unknown's avatar
unknown committed
6629 6630
}

6631 6632 6633

/*
  Find Item in list of items (find_field_in_tables analog)
6634 6635 6636 6637

  TODO
    is it better return only counter?

6638 6639
  SYNOPSIS
    find_item_in_list()
6640 6641 6642
    find			Item to find
    items			List of items
    counter			To return number of found item
6643
    report_error
6644 6645 6646 6647 6648
      REPORT_ALL_ERRORS		report errors, return 0 if error
      REPORT_EXCEPT_NOT_FOUND	Do not report 'not found' error and
				return not_found_item, report other errors,
				return 0
      IGNORE_ERRORS		Do not report errors, return 0 if error
unknown's avatar
unknown committed
6649 6650 6651 6652 6653 6654
    resolution                  Set to the resolution type if the item is found 
                                (it says whether the item is resolved 
                                 against an alias name,
                                 or as a field name without alias,
                                 or as a field hidden by alias,
                                 or ignoring alias)
Igor Babaev's avatar
Igor Babaev committed
6655 6656
    limit                       How many items in the list to check
                                (if limit==0 then all items are to be checked)
unknown's avatar
unknown committed
6657
                                
6658
  RETURN VALUES
6659 6660 6661 6662 6663
    0			Item is not found or item is not unique,
			error message is reported
    not_found_item	Function was called with
			report_error == REPORT_EXCEPT_NOT_FOUND and
			item was not found. No error message was reported
6664
                        found field
6665 6666
*/

6667
/* Special Item pointer to serve as a return value from find_item_in_list(). */
unknown's avatar
unknown committed
6668
Item **not_found_item= (Item**) 0x1;
6669 6670


unknown's avatar
unknown committed
6671
Item **
6672
find_item_in_list(Item *find, List<Item> &items, uint *counter,
unknown's avatar
unknown committed
6673
                  find_item_error_report_type report_error,
Igor Babaev's avatar
Igor Babaev committed
6674
                  enum_resolution_type *resolution, uint limit)
unknown's avatar
unknown committed
6675 6676
{
  List_iterator<Item> li(items);
Igor Babaev's avatar
Igor Babaev committed
6677
  uint n_items= limit == 0 ? items.elements : limit;
6678
  Item **found=0, **found_unaliased= 0, *item;
6679
  const char *db_name=0;
6680
  const LEX_CSTRING *field_name= 0;
unknown's avatar
unknown committed
6681
  const char *table_name=0;
6682
  bool found_unaliased_non_uniq= 0;
6683 6684 6685 6686 6687
  /*
    true if the item that we search for is a valid name reference
    (and not an item that happens to have a name).
  */
  bool is_ref_by_name= 0;
Staale Smedseng's avatar
Staale Smedseng committed
6688
  uint unaliased_counter= 0;
6689

unknown's avatar
unknown committed
6690
  *resolution= NOT_RESOLVED;
6691

6692 6693 6694
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  || 
                   find->type() == Item::REF_ITEM);
  if (is_ref_by_name)
unknown's avatar
unknown committed
6695
  {
6696
    field_name= &((Item_ident*) find)->field_name;
6697 6698
    table_name= ((Item_ident*) find)->table_name.str;
    db_name=    ((Item_ident*) find)->db_name.str;
unknown's avatar
unknown committed
6699 6700
  }

Igor Babaev's avatar
Igor Babaev committed
6701
  for (uint i= 0; i < n_items; i++)
unknown's avatar
unknown committed
6702
  {
Igor Babaev's avatar
Igor Babaev committed
6703
    item= li++;
6704
    if (field_name && field_name->str &&
6705 6706 6707
        (item->real_item()->type() == Item::FIELD_ITEM ||
         ((item->type() == Item::REF_ITEM) &&
          (((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF))))
unknown's avatar
unknown committed
6708
    {
6709
      Item_ident *item_field= (Item_ident*) item;
6710

unknown's avatar
unknown committed
6711 6712 6713 6714 6715 6716
      /*
	In case of group_concat() with ORDER BY condition in the QUERY
	item_field can be field of temporary table without item name 
	(if this field created from expression argument of group_concat()),
	=> we have to check presence of name before compare
      */ 
6717
      if (unlikely(!item_field->name.str))
6718 6719 6720
        continue;

      if (table_name)
unknown's avatar
unknown committed
6721
      {
6722 6723 6724
        /*
          If table name is specified we should find field 'field_name' in
          table 'table_name'. According to SQL-standard we should ignore
6725 6726 6727 6728 6729
          aliases in this case.

          Since we should NOT prefer fields from the select list over
          other fields from the tables participating in this select in
          case of ambiguity we have to do extra check outside this function.
6730

6731
          We use strcmp for table names and database names as these may be
6732 6733
          case sensitive. In cases where they are not case sensitive, they
          are always in lower case.
6734 6735

	  item_field->field_name and item_field->table_name can be 0x0 if
6736
	  item is not fix_field()'ed yet.
6737
        */
6738
        if (item_field->field_name.str && item_field->table_name.str &&
6739 6740
	    !lex_string_cmp(system_charset_info, &item_field->field_name,
                            field_name) &&
6741
            !my_strcasecmp(table_alias_charset, item_field->table_name.str,
unknown's avatar
unknown committed
6742
                           table_name) &&
6743 6744
            (!db_name || (item_field->db_name.str &&
                          !strcmp(item_field->db_name.str, db_name))))
6745
        {
6746
          if (found_unaliased)
6747
          {
6748 6749 6750 6751 6752 6753 6754
            if ((*found_unaliased)->eq(item, 0))
              continue;
            /*
              Two matching fields in select list.
              We already can bail out because we are searching through
              unaliased names only and will have duplicate error anyway.
            */
6755
            if (report_error != IGNORE_ERRORS)
6756 6757
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
                       find->full_name(), current_thd->where);
6758 6759
            return (Item**) 0;
          }
6760 6761
          found_unaliased= li.ref();
          unaliased_counter= i;
unknown's avatar
unknown committed
6762
          *resolution= RESOLVED_IGNORING_ALIAS;
6763 6764
          if (db_name)
            break;                              // Perfect match
6765 6766
        }
      }
unknown's avatar
unknown committed
6767
      else
6768
      {
6769 6770 6771 6772 6773
        bool fname_cmp= lex_string_cmp(system_charset_info,
                                       &item_field->field_name,
                                       field_name);
        if (!lex_string_cmp(system_charset_info,
                            &item_field->name, field_name))
6774
        {
unknown's avatar
unknown committed
6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794
          /*
            If table name was not given we should scan through aliases
            and non-aliased fields first. We are also checking unaliased
            name of the field in then next  else-if, to be able to find
            instantly field (hidden by alias) if no suitable alias or
            non-aliased field was found.
          */
          if (found)
          {
            if ((*found)->eq(item, 0))
              continue;                           // Same field twice
            if (report_error != IGNORE_ERRORS)
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
                       find->full_name(), current_thd->where);
            return (Item**) 0;
          }
          found= li.ref();
          *counter= i;
          *resolution= fname_cmp ? RESOLVED_AGAINST_ALIAS:
	                           RESOLVED_WITH_NO_ALIAS;
6795
        }
unknown's avatar
unknown committed
6796
        else if (!fname_cmp)
6797
        {
unknown's avatar
unknown committed
6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809
          /*
            We will use non-aliased field or react on such ambiguities only if
            we won't be able to find aliased field.
            Again if we have ambiguity with field outside of select list
            we should prefer fields from select list.
          */
          if (found_unaliased)
          {
            if ((*found_unaliased)->eq(item, 0))
              continue;                           // Same field twice
            found_unaliased_non_uniq= 1;
          }
6810 6811 6812
          found_unaliased= li.ref();
          unaliased_counter= i;
        }
unknown's avatar
unknown committed
6813 6814
      }
    }
unknown's avatar
unknown committed
6815 6816
    else if (!table_name)
    { 
6817 6818
      if (is_ref_by_name && find->name.str && item->name.str &&
          find->name.length == item->name.length &&
6819
	  !lex_string_cmp(system_charset_info, &item->name, &find->name))
unknown's avatar
unknown committed
6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832
      {
        found= li.ref();
        *counter= i;
        *resolution= RESOLVED_AGAINST_ALIAS;
        break;
      }
      else if (find->eq(item,0))
      {
        found= li.ref();
        *counter= i;
        *resolution= RESOLVED_IGNORING_ALIAS;
        break;
      }
6833
    }
unknown's avatar
unknown committed
6834
  }
6835 6836 6837 6838 6839

  if (likely(found))
    return found;

  if (unlikely(found_unaliased_non_uniq))
6840
  {
6841 6842 6843 6844
    if (report_error != IGNORE_ERRORS)
      my_error(ER_NON_UNIQ_ERROR, MYF(0),
               find->full_name(), current_thd->where);
    return (Item **) 0;
6845
  }
6846 6847 6848 6849 6850 6851 6852
  if (found_unaliased)
  {
    found= found_unaliased;
    *counter= unaliased_counter;
    *resolution= RESOLVED_BEHIND_ALIAS;
  }

6853 6854
  if (found)
    return found;
6855

6856
  if (report_error != REPORT_EXCEPT_NOT_FOUND)
6857 6858
  {
    if (report_error == REPORT_ALL_ERRORS)
6859 6860
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
               find->full_name(), current_thd->where);
6861 6862 6863 6864
    return (Item **) 0;
  }
  else
    return (Item **) not_found_item;
unknown's avatar
unknown committed
6865 6866
}

unknown's avatar
unknown committed
6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894

/*
  Test if a string is a member of a list of strings.

  SYNOPSIS
    test_if_string_in_list()
    find      the string to look for
    str_list  a list of strings to be searched

  DESCRIPTION
    Sequentially search a list of strings for a string, and test whether
    the list contains the same string.

  RETURN
    TRUE  if find is in str_list
    FALSE otherwise
*/

static bool
test_if_string_in_list(const char *find, List<String> *str_list)
{
  List_iterator<String> str_list_it(*str_list);
  String *curr_str;
  size_t find_length= strlen(find);
  while ((curr_str= str_list_it++))
  {
    if (find_length != curr_str->length())
      continue;
6895
    if (!my_strcasecmp(system_charset_info, find, curr_str->ptr()))
unknown's avatar
unknown committed
6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916
      return TRUE;
  }
  return FALSE;
}


/*
  Create a new name resolution context for an item so that it is
  being resolved in a specific table reference.

  SYNOPSIS
    set_new_item_local_context()
    thd        pointer to current thread
    item       item for which new context is created and set
    table_ref  table ref where an item showld be resolved

  DESCRIPTION
    Create a new name resolution context for an item, so that the item
    is resolved only the supplied 'table_ref'.

  RETURN
6917 6918
    FALSE  if all OK
    TRUE   otherwise
unknown's avatar
unknown committed
6919 6920 6921 6922 6923 6924
*/

static bool
set_new_item_local_context(THD *thd, Item_ident *item, TABLE_LIST *table_ref)
{
  Name_resolution_context *context;
6925
  if (!(context= new (thd->mem_root) Name_resolution_context))
unknown's avatar
unknown committed
6926 6927
    return TRUE;
  context->init();
6928 6929
  context->first_name_resolution_table=
    context->last_name_resolution_table= table_ref;
unknown's avatar
unknown committed
6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961
  item->context= context;
  return FALSE;
}


/*
  Find and mark the common columns of two table references.

  SYNOPSIS
    mark_common_columns()
    thd                [in] current thread
    table_ref_1        [in] the first (left) join operand
    table_ref_2        [in] the second (right) join operand
    using_fields       [in] if the join is JOIN...USING - the join columns,
                            if NATURAL join, then NULL
    found_using_fields [out] number of fields from the USING clause that were
                             found among the common fields

  DESCRIPTION
    The procedure finds the common columns of two relations (either
    tables or intermediate join results), and adds an equi-join condition
    to the ON clause of 'table_ref_2' for each pair of matching columns.
    If some of table_ref_XXX represents a base table or view, then we
    create new 'Natural_join_column' instances for each column
    reference and store them in the 'join_columns' of the table
    reference.

  IMPLEMENTATION
    The procedure assumes that store_natural_using_join_columns() was
    called for the previous level of NATURAL/USING joins.

  RETURN
6962 6963
    TRUE   error when some common column is non-unique, or out of memory
    FALSE  OK
unknown's avatar
unknown committed
6964 6965 6966 6967 6968 6969 6970 6971 6972 6973
*/

static bool
mark_common_columns(THD *thd, TABLE_LIST *table_ref_1, TABLE_LIST *table_ref_2,
                    List<String> *using_fields, uint *found_using_fields)
{
  Field_iterator_table_ref it_1, it_2;
  Natural_join_column *nj_col_1, *nj_col_2;
  Query_arena *arena, backup;
  bool result= TRUE;
unknown's avatar
unknown committed
6974
  bool first_outer_loop= TRUE;
6975
  Field *field_1;
6976
  field_visibility_t field_1_invisible, field_2_invisible;
unknown's avatar
unknown committed
6977 6978 6979 6980 6981 6982 6983 6984 6985 6986
  /*
    Leaf table references to which new natural join columns are added
    if the leaves are != NULL.
  */
  TABLE_LIST *leaf_1= (table_ref_1->nested_join &&
                       !table_ref_1->is_natural_join) ?
                      NULL : table_ref_1;
  TABLE_LIST *leaf_2= (table_ref_2->nested_join &&
                       !table_ref_2->is_natural_join) ?
                      NULL : table_ref_2;
unknown's avatar
unknown committed
6987 6988

  DBUG_ENTER("mark_common_columns");
6989
  DBUG_PRINT("info", ("operand_1: %s  operand_2: %s",
6990
                      table_ref_1->alias.str, table_ref_2->alias.str));
unknown's avatar
unknown committed
6991

6992
  *found_using_fields= 0;
unknown's avatar
unknown committed
6993
  arena= thd->activate_stmt_arena_if_needed(&backup);
unknown's avatar
unknown committed
6994 6995 6996

  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
  {
6997
    bool found= FALSE;
6998
    const LEX_CSTRING *field_name_1;
6999 7000
    Field *field_2= 0;

7001 7002
    /* true if field_name_1 is a member of using_fields */
    bool is_using_column_1;
7003
    if (!(nj_col_1= it_1.get_or_create_column_ref(thd, leaf_1)))
unknown's avatar
unknown committed
7004
      goto err;
7005

7006
    field_1= nj_col_1->field();
7007 7008 7009
    field_1_invisible= field_1 ? field_1->invisible : VISIBLE;

    if (field_1_invisible == INVISIBLE_FULL)
7010 7011
      continue;

unknown's avatar
unknown committed
7012
    field_name_1= nj_col_1->name();
7013
    is_using_column_1= using_fields && 
7014
      test_if_string_in_list(field_name_1->str, using_fields);
7015
    DBUG_PRINT ("info", ("field_name_1=%s.%s", 
7016
                         nj_col_1->safe_table_name(),
7017
                         field_name_1->str));
unknown's avatar
unknown committed
7018

7019 7020 7021
    if (field_1_invisible && !is_using_column_1)
      continue;

7022 7023 7024 7025 7026 7027 7028
    /*
      Find a field with the same name in table_ref_2.

      Note that for the second loop, it_2.set() will iterate over
      table_ref_2->join_columns and not generate any new elements or
      lists.
    */
unknown's avatar
unknown committed
7029 7030 7031 7032
    nj_col_2= NULL;
    for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
    {
      Natural_join_column *cur_nj_col_2;
7033
      const LEX_CSTRING *cur_field_name_2;
7034
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(thd, leaf_2)))
unknown's avatar
unknown committed
7035
        goto err;
7036 7037

      field_2= cur_nj_col_2->field();
7038 7039 7040 7041 7042
      field_2_invisible= field_2 ? field_2->invisible : VISIBLE;

      if (field_2_invisible == INVISIBLE_FULL)
        continue;

7043
      cur_field_name_2= cur_nj_col_2->name();
7044
      DBUG_PRINT ("info", ("cur_field_name_2=%s.%s", 
7045
                           cur_nj_col_2->safe_table_name(),
7046
                           cur_field_name_2->str));
unknown's avatar
unknown committed
7047

unknown's avatar
unknown committed
7048 7049 7050 7051 7052 7053
      /*
        Compare the two columns and check for duplicate common fields.
        A common field is duplicate either if it was already found in
        table_ref_2 (then found == TRUE), or if a field in table_ref_2
        was already matched by some previous field in table_ref_1
        (then cur_nj_col_2->is_common == TRUE).
7054 7055 7056 7057
        Note that it is too early to check the columns outside of the
        USING list for ambiguity because they are not actually "referenced"
        here. These columns must be checked only on unqualified reference 
        by name (e.g. in SELECT list).
unknown's avatar
unknown committed
7058
      */
7059 7060
      if (!lex_string_cmp(system_charset_info, field_name_1,
                          cur_field_name_2))
unknown's avatar
unknown committed
7061
      {
7062
        DBUG_PRINT ("info", ("match c1.is_common=%d", nj_col_1->is_common));
7063
        if (cur_nj_col_2->is_common || found)
unknown's avatar
unknown committed
7064
        {
7065
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1->str, thd->where);
unknown's avatar
unknown committed
7066 7067
          goto err;
        }
7068
        if ((!using_fields && !field_2_invisible) || is_using_column_1)
7069 7070 7071 7072 7073
        {
          DBUG_ASSERT(nj_col_2 == NULL);
          nj_col_2= cur_nj_col_2;
          found= TRUE;
        }
unknown's avatar
unknown committed
7074 7075
      }
    }
unknown's avatar
unknown committed
7076 7077 7078 7079 7080 7081 7082 7083 7084
    if (first_outer_loop && leaf_2)
    {
      /*
        Make sure that the next inner loop "knows" that all columns
        are materialized already.
      */
      leaf_2->is_join_columns_complete= TRUE;
      first_outer_loop= FALSE;
    }
unknown's avatar
unknown committed
7085
    if (!found)
7086
      continue;                                 // No matching field
unknown's avatar
unknown committed
7087 7088 7089 7090 7091 7092

    /*
      field_1 and field_2 have the same names. Check if they are in the USING
      clause (if present), mark them as common fields, and add a new
      equi-join condition to the ON clause.
    */
7093
    if (nj_col_2)
unknown's avatar
unknown committed
7094
    {
7095 7096 7097 7098
      /*
        Create non-fixed fully qualified field and let fix_fields to
        resolve it.
      */
unknown's avatar
unknown committed
7099 7100 7101
      Item *item_1=   nj_col_1->create_item(thd);
      Item *item_2=   nj_col_2->create_item(thd);
      Item_ident *item_ident_1, *item_ident_2;
7102 7103 7104 7105 7106
      Item_func_eq *eq_cond;

      if (!item_1 || !item_2)
        goto err;                               // out of memory

unknown's avatar
unknown committed
7107
      /*
7108
        The following assert checks that the two created items are of
unknown's avatar
unknown committed
7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132
        type Item_ident.
      */
      DBUG_ASSERT(!thd->lex->current_select->no_wrap_view_item);
      /*
        In the case of no_wrap_view_item == 0, the created items must be
        of sub-classes of Item_ident.
      */
      DBUG_ASSERT(item_1->type() == Item::FIELD_ITEM ||
                  item_1->type() == Item::REF_ITEM);
      DBUG_ASSERT(item_2->type() == Item::FIELD_ITEM ||
                  item_2->type() == Item::REF_ITEM);

      /*
        We need to cast item_1,2 to Item_ident, because we need to hook name
        resolution contexts specific to each item.
      */
      item_ident_1= (Item_ident*) item_1;
      item_ident_2= (Item_ident*) item_2;
      /*
        Create and hook special name resolution contexts to each item in the
        new join condition . We need this to both speed-up subsequent name
        resolution of these items, and to enable proper name resolution of
        the items during the execute phase of PS.
      */
7133 7134
      if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) ||
          set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref))
unknown's avatar
unknown committed
7135 7136
        goto err;

Monty's avatar
Monty committed
7137
      if (!(eq_cond= new (thd->mem_root) Item_func_eq(thd, item_ident_1, item_ident_2)))
7138
        goto err;                               /* Out of memory. */
unknown's avatar
unknown committed
7139 7140 7141 7142 7143

      /*
        Add the new equi-join condition to the ON clause. Notice that
        fix_fields() is applied to all ON conditions in setup_conds()
        so we don't do it here.
Igor Babaev's avatar
Igor Babaev committed
7144
      */
7145 7146
      add_join_on(thd, (table_ref_1->outer_join & JOIN_TYPE_RIGHT ?
                        table_ref_1 : table_ref_2),
7147
                  eq_cond);
unknown's avatar
unknown committed
7148 7149

      nj_col_1->is_common= nj_col_2->is_common= TRUE;
7150
      DBUG_PRINT ("info", ("%s.%s and %s.%s are common", 
7151
                           nj_col_1->safe_table_name(),
7152
                           nj_col_1->name()->str,
7153
                           nj_col_2->safe_table_name(),
7154
                           nj_col_2->name()->str));
unknown's avatar
unknown committed
7155 7156

      if (field_1)
7157
        update_field_dependencies(thd, field_1, field_1->table);
unknown's avatar
unknown committed
7158
      if (field_2)
7159
        update_field_dependencies(thd, field_2, field_2->table);
unknown's avatar
unknown committed
7160 7161 7162 7163 7164

      if (using_fields != NULL)
        ++(*found_using_fields);
    }
  }
unknown's avatar
unknown committed
7165 7166
  if (leaf_1)
    leaf_1->is_join_columns_complete= TRUE;
unknown's avatar
unknown committed
7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178

  /*
    Everything is OK.
    Notice that at this point there may be some column names in the USING
    clause that are not among the common columns. This is an SQL error and
    we check for this error in store_natural_using_join_columns() when
    (found_using_fields < length(join_using_fields)).
  */
  result= FALSE;

err:
  if (arena)
unknown's avatar
unknown committed
7179
    thd->restore_active_arena(arena, &backup);
unknown's avatar
unknown committed
7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215
  DBUG_RETURN(result);
}



/*
  Materialize and store the row type of NATURAL/USING join.

  SYNOPSIS
    store_natural_using_join_columns()
    thd                current thread
    natural_using_join the table reference of the NATURAL/USING join
    table_ref_1        the first (left) operand (of a NATURAL/USING join).
    table_ref_2        the second (right) operand (of a NATURAL/USING join).
    using_fields       if the join is JOIN...USING - the join columns,
                       if NATURAL join, then NULL
    found_using_fields number of fields from the USING clause that were
                       found among the common fields

  DESCRIPTION
    Iterate over the columns of both join operands and sort and store
    all columns into the 'join_columns' list of natural_using_join
    where the list is formed by three parts:
      part1: The coalesced columns of table_ref_1 and table_ref_2,
             sorted according to the column order of the first table.
      part2: The other columns of the first table, in the order in
             which they were defined in CREATE TABLE.
      part3: The other columns of the second table, in the order in
             which they were defined in CREATE TABLE.
    Time complexity - O(N1+N2), where Ni = length(table_ref_i).

  IMPLEMENTATION
    The procedure assumes that mark_common_columns() has been called
    for the join that is being processed.

  RETURN
7216 7217
    TRUE    error: Some common column is ambiguous
    FALSE   OK
unknown's avatar
unknown committed
7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230
*/

static bool
store_natural_using_join_columns(THD *thd, TABLE_LIST *natural_using_join,
                                 TABLE_LIST *table_ref_1,
                                 TABLE_LIST *table_ref_2,
                                 List<String> *using_fields,
                                 uint found_using_fields)
{
  Field_iterator_table_ref it_1, it_2;
  Natural_join_column *nj_col_1, *nj_col_2;
  Query_arena *arena, backup;
  bool result= TRUE;
7231
  List<Natural_join_column> *non_join_columns;
7232
  List<Natural_join_column> *join_columns;
unknown's avatar
unknown committed
7233 7234
  DBUG_ENTER("store_natural_using_join_columns");

7235 7236
  DBUG_ASSERT(!natural_using_join->join_columns);

unknown's avatar
unknown committed
7237
  arena= thd->activate_stmt_arena_if_needed(&backup);
unknown's avatar
unknown committed
7238

7239
  if (!(non_join_columns= new List<Natural_join_column>) ||
7240
      !(join_columns= new List<Natural_join_column>))
unknown's avatar
unknown committed
7241 7242 7243 7244 7245
    goto err;

  /* Append the columns of the first join operand. */
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
  {
7246
    nj_col_1= it_1.get_natural_column_ref();
unknown's avatar
unknown committed
7247 7248
    if (nj_col_1->is_common)
    {
7249
      join_columns->push_back(nj_col_1, thd->mem_root);
unknown's avatar
unknown committed
7250 7251 7252 7253
      /* Reset the common columns for the next call to mark_common_columns. */
      nj_col_1->is_common= FALSE;
    }
    else
7254
      non_join_columns->push_back(nj_col_1, thd->mem_root);
unknown's avatar
unknown committed
7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267
  }

  /*
    Check that all columns in the USING clause are among the common
    columns. If this is not the case, report the first one that was
    not found in an error.
  */
  if (using_fields && found_using_fields < using_fields->elements)
  {
    String *using_field_name;
    List_iterator_fast<String> using_fields_it(*using_fields);
    while ((using_field_name= using_fields_it++))
    {
7268
      const char *using_field_name_ptr= using_field_name->c_ptr();
unknown's avatar
unknown committed
7269
      List_iterator_fast<Natural_join_column>
7270
        it(*join_columns);
unknown's avatar
unknown committed
7271
      Natural_join_column *common_field;
7272 7273

      for (;;)
unknown's avatar
unknown committed
7274
      {
7275 7276 7277 7278 7279 7280 7281
        /* If reached the end of fields, and none was found, report error. */
        if (!(common_field= it++))
        {
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
                   current_thd->where);
          goto err;
        }
unknown's avatar
unknown committed
7282
        if (!my_strcasecmp(system_charset_info,
7283
                           common_field->name()->str, using_field_name_ptr))
7284
          break;                                // Found match
unknown's avatar
unknown committed
7285 7286 7287 7288 7289 7290 7291
      }
    }
  }

  /* Append the non-equi-join columns of the second join operand. */
  for (it_2.set(table_ref_2); !it_2.end_of_fields(); it_2.next())
  {
7292
    nj_col_2= it_2.get_natural_column_ref();
unknown's avatar
unknown committed
7293
    if (!nj_col_2->is_common)
7294
      non_join_columns->push_back(nj_col_2, thd->mem_root);
unknown's avatar
unknown committed
7295
    else
7296
    {
unknown's avatar
unknown committed
7297 7298
      /* Reset the common columns for the next call to mark_common_columns. */
      nj_col_2->is_common= FALSE;
7299
    }
unknown's avatar
unknown committed
7300 7301 7302
  }

  if (non_join_columns->elements > 0)
7303
    join_columns->append(non_join_columns);
7304
  natural_using_join->join_columns= join_columns;
unknown's avatar
unknown committed
7305 7306 7307 7308 7309
  natural_using_join->is_join_columns_complete= TRUE;

  result= FALSE;

  if (arena)
unknown's avatar
unknown committed
7310
    thd->restore_active_arena(arena, &backup);
unknown's avatar
unknown committed
7311
  DBUG_RETURN(result);
7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324

err:
  /*
     Actually we failed to build join columns list, so we have to
     clear it to avoid problems with half-build join on next run.
     The list was created in mark_common_columns().
   */
  table_ref_1->remove_join_columns();
  table_ref_2->remove_join_columns();

  if (arena)
    thd->restore_active_arena(arena, &backup);
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
7325 7326
}

7327

unknown's avatar
unknown committed
7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353
/*
  Precompute and store the row types of the top-most NATURAL/USING joins.

  SYNOPSIS
    store_top_level_join_columns()
    thd            current thread
    table_ref      nested join or table in a FROM clause
    left_neighbor  neighbor table reference to the left of table_ref at the
                   same level in the join tree
    right_neighbor neighbor table reference to the right of table_ref at the
                   same level in the join tree

  DESCRIPTION
    The procedure performs a post-order traversal of a nested join tree
    and materializes the row types of NATURAL/USING joins in a
    bottom-up manner until it reaches the TABLE_LIST elements that
    represent the top-most NATURAL/USING joins. The procedure should be
    applied to each element of SELECT_LEX::top_join_list (i.e. to each
    top-level element of the FROM clause).

  IMPLEMENTATION
    Notice that the table references in the list nested_join->join_list
    are in reverse order, thus when we iterate over it, we are moving
    from the right to the left in the FROM clause.

  RETURN
7354 7355
    TRUE   Error
    FALSE  OK
unknown's avatar
unknown committed
7356 7357 7358 7359 7360 7361 7362
*/

static bool
store_top_level_join_columns(THD *thd, TABLE_LIST *table_ref,
                             TABLE_LIST *left_neighbor,
                             TABLE_LIST *right_neighbor)
{
unknown's avatar
unknown committed
7363 7364 7365
  Query_arena *arena, backup;
  bool result= TRUE;

unknown's avatar
unknown committed
7366
  DBUG_ENTER("store_top_level_join_columns");
7367

unknown's avatar
unknown committed
7368
  arena= thd->activate_stmt_arena_if_needed(&backup);
unknown's avatar
unknown committed
7369

unknown's avatar
unknown committed
7370 7371 7372 7373
  /* Call the procedure recursively for each nested table reference. */
  if (table_ref->nested_join)
  {
    List_iterator_fast<TABLE_LIST> nested_it(table_ref->nested_join->join_list);
unknown's avatar
unknown committed
7374 7375 7376 7377
    TABLE_LIST *same_level_left_neighbor= nested_it++;
    TABLE_LIST *same_level_right_neighbor= NULL;
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
    TABLE_LIST *real_left_neighbor, *real_right_neighbor;
7378

unknown's avatar
unknown committed
7379
    while (same_level_left_neighbor)
unknown's avatar
unknown committed
7380
    {
unknown's avatar
unknown committed
7381 7382
      TABLE_LIST *cur_table_ref= same_level_left_neighbor;
      same_level_left_neighbor= nested_it++;
7383 7384 7385 7386
      /*
        The order of RIGHT JOIN operands is reversed in 'join list' to
        transform it into a LEFT JOIN. However, in this procedure we need
        the join operands in their lexical order, so below we reverse the
unknown's avatar
unknown committed
7387 7388 7389 7390 7391
        join operands. Notice that this happens only in the first loop,
        and not in the second one, as in the second loop
        same_level_left_neighbor == NULL.
        This is the correct behavior, because the second loop sets
        cur_table_ref reference correctly after the join operands are
7392 7393
        swapped in the first loop.
      */
unknown's avatar
unknown committed
7394
      if (same_level_left_neighbor &&
7395 7396 7397 7398
          cur_table_ref->outer_join & JOIN_TYPE_RIGHT)
      {
        /* This can happen only for JOIN ... ON. */
        DBUG_ASSERT(table_ref->nested_join->join_list.elements == 2);
unknown's avatar
unknown committed
7399
        swap_variables(TABLE_LIST*, same_level_left_neighbor, cur_table_ref);
7400 7401
      }

unknown's avatar
unknown committed
7402 7403 7404 7405 7406 7407 7408 7409 7410
      /*
        Pick the parent's left and right neighbors if there are no immediate
        neighbors at the same level.
      */
      real_left_neighbor=  (same_level_left_neighbor) ?
                           same_level_left_neighbor : left_neighbor;
      real_right_neighbor= (same_level_right_neighbor) ?
                           same_level_right_neighbor : right_neighbor;

7411 7412
      if (cur_table_ref->nested_join &&
          store_top_level_join_columns(thd, cur_table_ref,
unknown's avatar
unknown committed
7413
                                       real_left_neighbor, real_right_neighbor))
unknown's avatar
unknown committed
7414
        goto err;
unknown's avatar
unknown committed
7415
      same_level_right_neighbor= cur_table_ref;
unknown's avatar
unknown committed
7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445
    }
  }

  /*
    If this is a NATURAL/USING join, materialize its result columns and
    convert to a JOIN ... ON.
  */
  if (table_ref->is_natural_join)
  {
    DBUG_ASSERT(table_ref->nested_join &&
                table_ref->nested_join->join_list.elements == 2);
    List_iterator_fast<TABLE_LIST> operand_it(table_ref->nested_join->join_list);
    /*
      Notice that the order of join operands depends on whether table_ref
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
      in inverted order.
     */
    TABLE_LIST *table_ref_2= operand_it++; /* Second NATURAL join operand.*/
    TABLE_LIST *table_ref_1= operand_it++; /* First NATURAL join operand. */
    List<String> *using_fields= table_ref->join_using_fields;
    uint found_using_fields;

    /*
      The two join operands were interchanged in the parser, change the order
      back for 'mark_common_columns'.
    */
    if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
      swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
    if (mark_common_columns(thd, table_ref_1, table_ref_2,
                            using_fields, &found_using_fields))
unknown's avatar
unknown committed
7446
      goto err;
unknown's avatar
unknown committed
7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457

    /*
      Swap the join operands back, so that we pick the columns of the second
      one as the coalesced columns. In this way the coalesced columns are the
      same as of an equivalent LEFT JOIN.
    */
    if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
      swap_variables(TABLE_LIST*, table_ref_1, table_ref_2);
    if (store_natural_using_join_columns(thd, table_ref, table_ref_1,
                                         table_ref_2, using_fields,
                                         found_using_fields))
unknown's avatar
unknown committed
7458
      goto err;
unknown's avatar
unknown committed
7459 7460 7461 7462 7463 7464 7465 7466 7467

    /*
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
      because either one of them or the other is the one with the
      natural join flag because RIGHT joins are transformed into LEFT,
      and the two tables may be reordered.
    */
    table_ref_1->natural_join= table_ref_2->natural_join= NULL;

unknown's avatar
unknown committed
7468 7469 7470
    /* Add a TRUE condition to outer joins that have no common columns. */
    if (table_ref_2->outer_join &&
        !table_ref_1->on_expr && !table_ref_2->on_expr)
7471
      table_ref_2->on_expr= (Item*) &Item_true;
unknown's avatar
unknown committed
7472

unknown's avatar
unknown committed
7473 7474 7475
    /* Change this table reference to become a leaf for name resolution. */
    if (left_neighbor)
    {
7476
      TABLE_LIST *last_leaf_on_the_left;
unknown's avatar
unknown committed
7477 7478 7479 7480 7481
      last_leaf_on_the_left= left_neighbor->last_leaf_for_name_resolution();
      last_leaf_on_the_left->next_name_resolution_table= table_ref;
    }
    if (right_neighbor)
    {
7482
      TABLE_LIST *first_leaf_on_the_right;
unknown's avatar
unknown committed
7483 7484 7485 7486 7487 7488
      first_leaf_on_the_right= right_neighbor->first_leaf_for_name_resolution();
      table_ref->next_name_resolution_table= first_leaf_on_the_right;
    }
    else
      table_ref->next_name_resolution_table= NULL;
  }
unknown's avatar
unknown committed
7489 7490 7491 7492
  result= FALSE; /* All is OK. */

err:
  if (arena)
unknown's avatar
unknown committed
7493
    thd->restore_active_arena(arena, &backup);
unknown's avatar
unknown committed
7494
  DBUG_RETURN(result);
unknown's avatar
unknown committed
7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517
}


/*
  Compute and store the row types of the top-most NATURAL/USING joins
  in a FROM clause.

  SYNOPSIS
    setup_natural_join_row_types()
    thd          current thread
    from_clause  list of top-level table references in a FROM clause

  DESCRIPTION
    Apply the procedure 'store_top_level_join_columns' to each of the
    top-level table referencs of the FROM clause. Adjust the list of tables
    for name resolution - context->first_name_resolution_table to the
    top-most, lef-most NATURAL/USING join.

  IMPLEMENTATION
    Notice that the table references in 'from_clause' are in reverse
    order, thus when we iterate over it, we are moving from the right
    to the left in the FROM clause.

7518 7519 7520 7521 7522
  NOTES
    We can't run this many times as the first_name_resolution_table would
    be different for subsequent runs when sub queries has been optimized
    away.

unknown's avatar
unknown committed
7523
  RETURN
7524 7525
    TRUE   Error
    FALSE  OK
unknown's avatar
unknown committed
7526
*/
7527

7528 7529
static bool setup_natural_join_row_types(THD *thd,
                                         List<TABLE_LIST> *from_clause,
unknown's avatar
unknown committed
7530 7531
                                         Name_resolution_context *context)
{
7532
  DBUG_ENTER("setup_natural_join_row_types");
unknown's avatar
unknown committed
7533 7534
  thd->where= "from clause";
  if (from_clause->elements == 0)
7535
    DBUG_RETURN(false); /* We come here in the case of UNIONs. */
unknown's avatar
unknown committed
7536

7537 7538 7539 7540 7541 7542 7543
  /* 
     Do not redo work if already done:
     1) for stored procedures,
     2) for multitable update after lock failure and table reopening.
  */
  if (!context->select_lex->first_natural_join_processing)
  {
7544 7545
    context->first_name_resolution_table= context->natural_join_first_table;
    DBUG_PRINT("info", ("using cached setup_natural_join_row_types"));
7546 7547 7548
    DBUG_RETURN(false);
  }

unknown's avatar
unknown committed
7549 7550 7551
  List_iterator_fast<TABLE_LIST> table_ref_it(*from_clause);
  TABLE_LIST *table_ref; /* Current table reference. */
  /* Table reference to the left of the current. */
7552
  TABLE_LIST *left_neighbor;
unknown's avatar
unknown committed
7553 7554 7555
  /* Table reference to the right of the current. */
  TABLE_LIST *right_neighbor= NULL;

7556 7557
  /* Note that tables in the list are in reversed order */
  for (left_neighbor= table_ref_it++; left_neighbor ; )
unknown's avatar
unknown committed
7558 7559
  {
    table_ref= left_neighbor;
7560 7561 7562 7563 7564
    do
    {
      left_neighbor= table_ref_it++;
    }
    while (left_neighbor && left_neighbor->sj_subq_pred);
7565 7566 7567 7568 7569

    if (store_top_level_join_columns(thd, table_ref,
                                     left_neighbor, right_neighbor))
      DBUG_RETURN(true);
    if (left_neighbor)
unknown's avatar
unknown committed
7570
    {
7571 7572 7573
      TABLE_LIST *first_leaf_on_the_right;
      first_leaf_on_the_right= table_ref->first_leaf_for_name_resolution();
      left_neighbor->next_name_resolution_table= first_leaf_on_the_right;
unknown's avatar
unknown committed
7574 7575 7576 7577 7578 7579 7580
    }
    right_neighbor= table_ref;
  }

  /*
    Store the top-most, left-most NATURAL/USING join, so that we start
    the search from that one instead of context->table_list. At this point
7581
    right_neighbor points to the left-most top-level table reference in the
unknown's avatar
unknown committed
7582 7583 7584 7585 7586
    FROM clause.
  */
  DBUG_ASSERT(right_neighbor);
  context->first_name_resolution_table=
    right_neighbor->first_leaf_for_name_resolution();
7587 7588 7589 7590 7591
  /*
    This is only to ensure that first_name_resolution_table doesn't
    change on re-execution
  */
  context->natural_join_first_table= context->first_name_resolution_table;
7592
  context->select_lex->first_natural_join_processing= false;
7593
  DBUG_RETURN (false);
unknown's avatar
unknown committed
7594 7595 7596
}


unknown's avatar
unknown committed
7597
/****************************************************************************
7598
** Expand all '*' in given fields
unknown's avatar
unknown committed
7599 7600
****************************************************************************/

7601
int setup_wild(THD *thd, TABLE_LIST *tables, List<Item> &fields,
7602
	       List<Item> *sum_func_list, SELECT_LEX *select_lex, bool returning_field)
unknown's avatar
unknown committed
7603
{
7604
  Item *item;
unknown's avatar
unknown committed
7605
  List_iterator<Item> it(fields);
unknown's avatar
unknown committed
7606
  Query_arena *arena, backup;
7607 7608
  uint *with_wild= returning_field ? &(thd->lex->returning()->with_wild) :
                                     &(select_lex->with_wild);
7609
  DBUG_ENTER("setup_wild");
unknown's avatar
unknown committed
7610

7611 7612
  if (!(*with_wild))
     DBUG_RETURN(0);
7613

unknown's avatar
unknown committed
7614
  /*
7615 7616
    Don't use arena if we are not in prepared statements or stored procedures
    For PS/SP we have to use arena to remember the changes
unknown's avatar
unknown committed
7617
  */
unknown's avatar
unknown committed
7618
  arena= thd->activate_stmt_arena_if_needed(&backup);
7619

7620
  thd->lex->current_select->cur_pos_in_select_list= 0;
7621
  while (*with_wild && (item= it++))
unknown's avatar
VIEW  
unknown committed
7622
  {
7623
    if (item->type() == Item::FIELD_ITEM &&
7624
        ((Item_field*) item)->field_name.str == star_clex_str.str &&
7625
	!((Item_field*) item)->field)
7626
    {
7627
      uint elem= fields.elements;
unknown's avatar
VIEW  
unknown committed
7628
      bool any_privileges= ((Item_field *) item)->any_privileges;
unknown's avatar
unknown committed
7629 7630 7631 7632 7633 7634 7635 7636 7637
      Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
      if (subsel &&
          subsel->substype() == Item_subselect::EXISTS_SUBS)
      {
        /*
          It is EXISTS(SELECT * ...) and we can replace * by any constant.

          Item_int do not need fix_fields() because it is basic constant.
        */
Monty's avatar
Monty committed
7638
        it.replace(new (thd->mem_root) Item_int(thd, "Not_used", (longlong) 1,
7639
                                MY_INT64_NUM_DECIMAL_DIGITS));
unknown's avatar
unknown committed
7640
      }
7641
      else if (insert_fields(thd, ((Item_field*) item)->context,
7642 7643
                             ((Item_field*) item)->db_name.str,
                             ((Item_field*) item)->table_name.str, &it,
7644
                             any_privileges, &select_lex->hidden_bit_fields, returning_field))
unknown's avatar
unknown committed
7645 7646
      {
	if (arena)
unknown's avatar
unknown committed
7647
	  thd->restore_active_arena(arena, &backup);
7648
	DBUG_RETURN(-1);
unknown's avatar
unknown committed
7649
      }
7650
      if (sum_func_list)
7651 7652 7653 7654 7655 7656 7657 7658
      {
	/*
	  sum_func_list is a list that has the fields list as a tail.
	  Because of this we have to update the element count also for this
	  list after expanding the '*' entry.
	*/
	sum_func_list->elements+= fields.elements - elem;
      }
7659
      (*with_wild)--;
7660
    }
7661 7662
    else
      thd->lex->current_select->cur_pos_in_select_list++;
7663
  }
7664
  DBUG_ASSERT(!(*with_wild));
7665
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
unknown's avatar
unknown committed
7666
  if (arena)
unknown's avatar
unknown committed
7667
    thd->restore_active_arena(arena, &backup);
7668
  DBUG_RETURN(0);
7669 7670
}

7671 7672 7673 7674
/****************************************************************************
** Check that all given fields exists and fill struct with current data
****************************************************************************/

7675
bool setup_fields(THD *thd, Ref_ptr_array ref_pointer_array,
Sergei Golubchik's avatar
Sergei Golubchik committed
7676
                  List<Item> &fields, enum_column_usage column_usage,
7677 7678
                  List<Item> *sum_func_list, List<Item> *pre_fix,
                  bool allow_sum_func)
7679
{
7680
  Item *item;
Sergei Golubchik's avatar
Sergei Golubchik committed
7681
  enum_column_usage saved_column_usage= thd->column_usage;
unknown's avatar
unknown committed
7682
  nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
7683
  List_iterator<Item> it(fields);
7684
  bool save_is_item_list_lookup;
7685
  bool make_pre_fix= (pre_fix && (pre_fix->elements == 0));
7686
  DBUG_ENTER("setup_fields");
Sergei Petrunia's avatar
Sergei Petrunia committed
7687
  DBUG_PRINT("enter", ("ref_pointer_array: %p", ref_pointer_array.array()));
7688

Sergei Golubchik's avatar
Sergei Golubchik committed
7689 7690
  thd->column_usage= column_usage;
  DBUG_PRINT("info", ("thd->column_usage: %d", thd->column_usage));
7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701
  /*
    Followimg 2 condition always should be true (but they was added
    due to an error present only in 10.3):
    1) nest_level shoud be 0 or positive;
    2) nest level of all SELECTs on the same level shoud be equal first
       SELECT on this level (and each other).
  */
  DBUG_ASSERT(thd->lex->current_select->nest_level >= 0);
  DBUG_ASSERT(thd->lex->current_select->master_unit()->first_select()
                ->nest_level ==
              thd->lex->current_select->nest_level);
unknown's avatar
unknown committed
7702
  if (allow_sum_func)
7703
    thd->lex->allow_sum_func.set_bit(thd->lex->current_select->nest_level);
7704
  thd->where= THD::DEFAULT_WHERE;
7705 7706
  save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup;
  thd->lex->current_select->is_item_list_lookup= 0;
7707

7708
  /*
7709
    To prevent fail on forward lookup we fill it with zeroes,
7710 7711 7712 7713 7714 7715 7716 7717 7718
    then if we got pointer on zero after find_item_in_list we will know
    that it is forward lookup.

    There is other way to solve problem: fill array with pointers to list,
    but it will be slower.

    TODO: remove it when (if) we made one list for allfields and
    ref_pointer_array
  */
7719 7720 7721 7722 7723
  if (!ref_pointer_array.is_null())
  {
    DBUG_ASSERT(ref_pointer_array.size() >= fields.elements);
    memset(ref_pointer_array.array(), 0, sizeof(Item *) * fields.elements);
  }
7724

7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740
  /*
    We call set_entry() there (before fix_fields() of the whole list of field
    items) because:
    1) the list of field items has same order as in the query, and the
       Item_func_get_user_var item may go before the Item_func_set_user_var:
          SELECT @a, @a := 10 FROM t;
    2) The entry->update_query_id value controls constantness of
       Item_func_get_user_var items, so in presence of Item_func_set_user_var
       items we have to refresh their entries before fixing of
       Item_func_get_user_var items.
  */
  List_iterator<Item_func_set_user_var> li(thd->lex->set_var_list);
  Item_func_set_user_var *var;
  while ((var= li++))
    var->set_entry(thd, FALSE);

7741
  Ref_ptr_array ref= ref_pointer_array;
7742
  thd->lex->current_select->cur_pos_in_select_list= 0;
unknown's avatar
unknown committed
7743
  while ((item= it++))
7744
  {
7745 7746 7747
    if (make_pre_fix)
      pre_fix->push_back(item, thd->stmt_arena->mem_root);

7748
    if (item->fix_fields_if_needed_for_scalar(thd, it.ref()))
unknown's avatar
unknown committed
7749
    {
7750
      thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
unknown's avatar
unknown committed
7751
      thd->lex->allow_sum_func= save_allow_sum_func;
Sergei Golubchik's avatar
Sergei Golubchik committed
7752 7753
      thd->column_usage= saved_column_usage;
      DBUG_PRINT("info", ("thd->column_usage: %d", thd->column_usage));
unknown's avatar
unknown committed
7754
      DBUG_RETURN(TRUE); /* purecov: inspected */
unknown's avatar
unknown committed
7755
    }
7756
    item= *(it.ref()); // Item might have changed in fix_fields()
7757 7758 7759 7760 7761
    if (!ref.is_null())
    {
      ref[0]= item;
      ref.pop_front();
    }
7762 7763 7764 7765
    /*
      split_sum_func() must be called for Window Function items, see
      Item_window_func::split_sum_func.
    */
7766
    if (sum_func_list &&
7767 7768
        ((item->with_sum_func() && item->type() != Item::SUM_FUNC_ITEM) ||
         item->with_window_func()))
7769
    {
7770 7771
      item->split_sum_func(thd, ref_pointer_array, *sum_func_list,
                           SPLIT_SUM_SELECT);
7772
    }
7773
    thd->lex->current_select->select_list_tables|= item->used_tables();
7774
    thd->lex->used_tables|= item->used_tables();
7775
    thd->lex->current_select->cur_pos_in_select_list++;
7776 7777

    thd->lex->current_select->rownum_in_field_list |= item->with_rownum_func();
7778
  }
7779
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
7780 7781
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;

unknown's avatar
unknown committed
7782
  thd->lex->allow_sum_func= save_allow_sum_func;
Sergei Golubchik's avatar
Sergei Golubchik committed
7783 7784
  thd->column_usage= saved_column_usage;
  DBUG_PRINT("info", ("thd->column_usage: %d", thd->column_usage));
7785
  DBUG_RETURN(MY_TEST(thd->is_error()));
7786
}
7787

7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820
/*
  make list of leaves for a single TABLE_LIST

  SYNOPSIS
    make_leaves_for_single_table()
    thd             Thread handler
    leaves          List of leaf tables to be filled
    table           TABLE_LIST object to process
    full_table_list Whether to include tables from mergeable derived table/view
*/
void make_leaves_for_single_table(THD *thd, List<TABLE_LIST> &leaves,
                              TABLE_LIST *table, bool& full_table_list,
                              TABLE_LIST *boundary)
{
  if (table == boundary)
    full_table_list= !full_table_list;
  if (full_table_list && table->is_merged_derived())
  {
    SELECT_LEX *select_lex= table->get_single_select();
    /*
      It's safe to use select_lex->leaf_tables because all derived
      tables/views were already prepared and has their leaf_tables
      set properly.
    */
    make_leaves_list(thd, leaves, select_lex->get_table_list(),
                     full_table_list, boundary);
  }
  else
  {
    leaves.push_back(table, thd->mem_root);
  }
}

7821

7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835
/*
  Perform checks like all given fields exists, if exists fill struct with
  current data and expand all '*' in given fields for LEX::returning.

  SYNOPSIS
     thd                 Thread handler
     table_list          Global/local table list
*/

int setup_returning_fields(THD* thd, TABLE_LIST* table_list)
{
  if (!thd->lex->has_returning())
    return 0;
  return setup_wild(thd, table_list, thd->lex->returning()->item_list, NULL,
7836
                    thd->lex->returning(), true)
7837 7838 7839 7840 7841
      || setup_fields(thd, Ref_ptr_array(), thd->lex->returning()->item_list,
                      MARK_COLUMNS_READ, NULL, NULL, false);
}


7842 7843 7844 7845 7846
/*
  make list of leaves of join table tree

  SYNOPSIS
    make_leaves_list()
7847 7848 7849 7850
    leaves          List of leaf tables to be filled
    tables          Table list
    full_table_list Whether to include tables from mergeable derived table/view.
                    We need them for checks for INSERT/UPDATE statements only.
7851 7852
*/

7853
void make_leaves_list(THD *thd, List<TABLE_LIST> &leaves, TABLE_LIST *tables,
7854 7855
                      bool full_table_list, TABLE_LIST *boundary)
 
7856 7857 7858
{
  for (TABLE_LIST *table= tables; table; table= table->next_local)
  {
7859 7860
    make_leaves_for_single_table(thd, leaves, table, full_table_list,
                                 boundary);
7861 7862 7863
  }
}

7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890

/*
  Setup the map and other attributes for a single TABLE_LIST object

  SYNOPSIS
    setup_table_attributes()
    thd                 Thread handler
    table_list          TABLE_LIST object to process
    first_select_table  First table participating in SELECT for INSERT..SELECT
                        statements, NULL for other cases
    tablenr             Serial number of the table in the SQL statement

  RETURN
    false               Success
    true                Failure
*/
bool setup_table_attributes(THD *thd, TABLE_LIST *table_list,
                            TABLE_LIST *first_select_table,
                            uint &tablenr)
{
  TABLE *table= table_list->table;
  if (table)
    table->pos_in_table_list= table_list;
  if (first_select_table && table_list->top_table() == first_select_table)
  {
    /* new counting for SELECT of INSERT ... SELECT command */
    first_select_table= 0;
7891
    thd->lex->first_select_lex()->insert_tables= tablenr;
7892
    tablenr= 0;
7893
  }
7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916
  if (table_list->jtbm_subselect)
  {
    table_list->jtbm_table_no= tablenr;
  }
  else if (table)
  {
    table->pos_in_table_list= table_list;
    setup_table_map(table, table_list, tablenr);

    if (table_list->process_index_hints(table))
      return true;
  }
  tablenr++;
  /*
    We test the max tables here as we setup_table_map() should not be called
    with tablenr >= 64
  */
  if (tablenr > MAX_TABLES)
  {
    my_error(ER_TOO_MANY_TABLES, MYF(0), static_cast<int>(MAX_TABLES));
    return true;
  }
  return false;
7917 7918
}

7919

7920
/*
unknown's avatar
unknown committed
7921 7922 7923 7924
  prepare tables

  SYNOPSIS
    setup_tables()
unknown's avatar
unknown committed
7925
    thd		  Thread handler
7926
    context       name resolution contest to setup table list there
unknown's avatar
unknown committed
7927 7928 7929
    from_clause   Top-level list of table references in the FROM clause
    tables	  Table list (select_lex->table_list)
    leaves        List of join table leaves list (select_lex->leaf_tables)
Monty's avatar
Monty committed
7930
    refresh       It is only refresh for subquery
unknown's avatar
unknown committed
7931
    select_insert It is SELECT ... INSERT command
7932
    full_table_list a parameter to pass to the make_leaves_list function
unknown's avatar
unknown committed
7933

unknown's avatar
unknown committed
7934 7935
  NOTE
    Check also that the 'used keys' and 'ignored keys' exists and set up the
unknown's avatar
unknown committed
7936 7937 7938 7939
    table structure accordingly.
    Create a list of leaf tables. For queries with NATURAL/USING JOINs,
    compute the row types of the top most natural/using join table references
    and link these into a list of table references for name resolution.
7940

unknown's avatar
unknown committed
7941 7942
    This has to be called for all tables that are used by items, as otherwise
    table->map is not set and all Item_field will be regarded as const items.
unknown's avatar
VIEW  
unknown committed
7943

unknown's avatar
unknown committed
7944
  RETURN
unknown's avatar
unknown committed
7945
    FALSE ok;  In this case *map will includes the chosen index
unknown's avatar
unknown committed
7946
    TRUE  error
7947 7948
*/

7949
bool setup_tables(THD *thd, Name_resolution_context *context,
unknown's avatar
unknown committed
7950
                  List<TABLE_LIST> *from_clause, TABLE_LIST *tables,
7951 7952
                  List<TABLE_LIST> &leaves, bool select_insert,
                  bool full_table_list)
7953
{
unknown's avatar
unknown committed
7954
  uint tablenr= 0;
7955 7956 7957
  List_iterator<TABLE_LIST> ti(leaves);
  TABLE_LIST *table_list;

7958
  DBUG_ENTER("setup_tables");
7959

7960 7961
  DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables || 
               (context->table_list && context->first_name_resolution_table));
unknown's avatar
unknown committed
7962 7963
  /*
    this is used for INSERT ... SELECT.
7964
    For select we setup tables except first (and its underlying tables)
unknown's avatar
unknown committed
7965 7966 7967 7968
  */
  TABLE_LIST *first_select_table= (select_insert ?
                                   tables->next_local:
                                   0);
7969
  SELECT_LEX *select_lex= select_insert ? thd->lex->first_select_lex() :
7970 7971
                                          thd->lex->current_select;
  if (select_lex->first_cond_optimization)
unknown's avatar
unknown committed
7972
  {
7973
    leaves.empty();
7974
    if (select_lex->prep_leaf_list_state != SELECT_LEX::SAVED)
Igor Babaev's avatar
Igor Babaev committed
7975
    {
7976 7977 7978 7979 7980 7981 7982 7983
      /*
        For INSERT ... SELECT statements we must not include the first table
        (where the data is being inserted into) in the list of leaves
      */
      TABLE_LIST *tables_for_leaves=
          select_insert ? first_select_table : tables;
      make_leaves_list(thd, leaves, tables_for_leaves, full_table_list,
                       first_select_table);
7984
      select_lex->prep_leaf_list_state= SELECT_LEX::READY;
Igor Babaev's avatar
Igor Babaev committed
7985 7986 7987 7988 7989 7990
      select_lex->leaf_tables_exec.empty();
    }
    else
    {
      List_iterator_fast <TABLE_LIST> ti(select_lex->leaf_tables_prep);
      while ((table_list= ti++))
7991
        leaves.push_back(table_list, thd->mem_root);
Igor Babaev's avatar
Igor Babaev committed
7992 7993
    }
      
7994
    List_iterator<TABLE_LIST> ti(leaves);
7995
    while ((table_list= ti++))
unknown's avatar
unknown committed
7996
    {
7997 7998 7999
      if (setup_table_attributes(thd, table_list, first_select_table, tablenr))
        DBUG_RETURN(1);
    }
8000

8001 8002
    if (select_insert)
    {
Monty's avatar
Monty committed
8003
      /*
8004 8005 8006 8007
        The table/view in which the data is inserted must not be included into
        the leaf_tables list. But we need this table/view to setup attributes
        for it. So build a temporary list of leaves and setup attributes for
        the tables included
Monty's avatar
Monty committed
8008
      */
8009 8010 8011 8012 8013 8014 8015 8016
      List<TABLE_LIST> leaves;
      TABLE_LIST *table= tables;

      make_leaves_for_single_table(thd, leaves, table, full_table_list,
                                   first_select_table);

      List_iterator<TABLE_LIST> ti(leaves);
      while ((table_list= ti++))
Monty's avatar
Monty committed
8017
      {
8018 8019
        if (setup_table_attributes(thd, table_list, first_select_table,
                                   tablenr))
8020
          DBUG_RETURN(1);
Monty's avatar
Monty committed
8021
      }
Sergey Petrunya's avatar
Sergey Petrunya committed
8022
    }
unknown's avatar
unknown committed
8023
  }
8024 8025 8026 8027 8028 8029
  else
  { 
    List_iterator_fast <TABLE_LIST> ti(select_lex->leaf_tables_exec);
    select_lex->leaf_tables.empty();
    while ((table_list= ti++))
    {
Igor Babaev's avatar
Igor Babaev committed
8030 8031 8032 8033 8034 8035 8036 8037
      if(table_list->jtbm_subselect)
      {
        table_list->jtbm_table_no= table_list->tablenr_exec;
      }
      else
      {
        table_list->table->tablenr= table_list->tablenr_exec;
        table_list->table->map= table_list->map_exec;
Igor Babaev's avatar
Igor Babaev committed
8038
        table_list->table->maybe_null= table_list->maybe_null_exec;
Igor Babaev's avatar
Igor Babaev committed
8039
        table_list->table->pos_in_table_list= table_list;
Igor Babaev's avatar
Igor Babaev committed
8040 8041
        if (table_list->process_index_hints(table_list->table))
          DBUG_RETURN(1);
Igor Babaev's avatar
Igor Babaev committed
8042
      }
8043 8044 8045 8046
      select_lex->leaf_tables.push_back(table_list);
    }
  }    

unknown's avatar
unknown committed
8047
  for (table_list= tables;
8048 8049
       table_list;
       table_list= table_list->next_local)
8050
  {
8051
    if (table_list->is_merged_derived() && table_list->merge_underlying_list)
8052
    {
8053 8054
      Query_arena *arena, backup;
      arena= thd->activate_stmt_arena_if_needed(&backup);
8055
      bool res;
8056
      res= table_list->setup_underlying(thd);
8057
      if (arena)
unknown's avatar
unknown committed
8058
        thd->restore_active_arena(arena, &backup);
8059 8060 8061
      if (res)
        DBUG_RETURN(1);
    }
8062

8063 8064
    if (table_list->jtbm_subselect)
    {
8065
      Item *item= table_list->jtbm_subselect->optimizer;
8066
      if (!table_list->jtbm_subselect->optimizer->fixed() &&
8067
          table_list->jtbm_subselect->optimizer->fix_fields(thd, &item))
8068
      {
Sergei Golubchik's avatar
Sergei Golubchik committed
8069
        my_error(ER_TOO_MANY_TABLES,MYF(0), static_cast<int>(MAX_TABLES)); /* psergey-todo: WHY ER_TOO_MANY_TABLES ???*/
8070 8071
        DBUG_RETURN(1);
      }
8072
      DBUG_ASSERT(item == table_list->jtbm_subselect->optimizer);
8073
    }
8074
  }
unknown's avatar
unknown committed
8075 8076 8077 8078 8079

  /* Precompute and store the row types of NATURAL/USING joins. */
  if (setup_natural_join_row_types(thd, from_clause, context))
    DBUG_RETURN(1);

8080
  DBUG_RETURN(0);
unknown's avatar
unknown committed
8081
}
8082

unknown's avatar
unknown committed
8083

8084 8085 8086 8087
/*
  prepare tables and check access for the view tables

  SYNOPSIS
8088
    setup_tables_and_check_access()
8089 8090 8091 8092 8093 8094 8095 8096 8097
    thd		  Thread handler
    context       name resolution contest to setup table list there
    from_clause   Top-level list of table references in the FROM clause
    tables	  Table list (select_lex->table_list)
    conds	  Condition of current SELECT (can be changed by VIEW)
    leaves        List of join table leaves list (select_lex->leaf_tables)
    refresh       It is onle refresh for subquery
    select_insert It is SELECT ... INSERT command
    want_access   what access is needed
8098
    full_table_list a parameter to pass to the make_leaves_list function
8099 8100 8101 8102 8103 8104 8105 8106 8107

  NOTE
    a wrapper for check_tables that will also check the resulting
    table leaves list for access to all the tables that belong to a view

  RETURN
    FALSE ok;  In this case *map will include the chosen index
    TRUE  error
*/
8108
bool setup_tables_and_check_access(THD *thd, Name_resolution_context *context,
8109 8110
                                   List<TABLE_LIST> *from_clause,
                                   TABLE_LIST *tables,
8111
                                   List<TABLE_LIST> &leaves,
8112
                                   bool select_insert,
8113 8114
                                   privilege_t want_access_first,
                                   privilege_t want_access,
8115
                                   bool full_table_list)
8116
{
8117
  DBUG_ENTER("setup_tables_and_check_access");
8118

unknown's avatar
unknown committed
8119
  if (setup_tables(thd, context, from_clause, tables,
8120
                   leaves, select_insert, full_table_list))
8121
    DBUG_RETURN(TRUE);
8122

8123 8124
  List_iterator<TABLE_LIST> ti(leaves);
  TABLE_LIST *table_list;
8125
  privilege_t access= want_access_first;
Monty's avatar
Monty committed
8126
  while ((table_list= ti++))
unknown's avatar
unknown committed
8127
  {
8128
    if (table_list->belong_to_view && !table_list->view && 
Monty's avatar
Monty committed
8129
        check_single_table_access(thd, access, table_list, FALSE))
8130 8131
    {
      tables->hide_view_error(thd);
8132
      DBUG_RETURN(TRUE);
8133
    }
Monty's avatar
Monty committed
8134
    access= want_access;
unknown's avatar
unknown committed
8135
  }
8136
  DBUG_RETURN(FALSE);
8137 8138 8139
}


8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154
/*
   Create a key_map from a list of index names

   SYNOPSIS
     get_key_map_from_key_list()
     map		key_map to fill in
     table		Table
     index_list		List of index names

   RETURN
     0	ok;  In this case *map will includes the choosed index
     1	error
*/

bool get_key_map_from_key_list(key_map *map, TABLE *table,
8155
                               List<String> *index_list)
unknown's avatar
unknown committed
8156
{
unknown's avatar
unknown committed
8157
  List_iterator_fast<String> it(*index_list);
unknown's avatar
unknown committed
8158 8159
  String *name;
  uint pos;
8160 8161

  map->clear_all();
unknown's avatar
unknown committed
8162 8163
  while ((name=it++))
  {
8164 8165 8166
    if (table->s->keynames.type_names == 0 ||
        (pos= find_type(&table->s->keynames, name->ptr(),
                        name->length(), 1)) <=
8167
        0)
unknown's avatar
unknown committed
8168
    {
8169
      my_error(ER_KEY_DOES_NOT_EXISTS, MYF(0), name->c_ptr(),
8170
	       table->pos_in_table_list->alias.str);
8171
      map->set_all();
8172
      return 1;
unknown's avatar
unknown committed
8173
    }
8174
    map->set_bit(pos-1);
unknown's avatar
unknown committed
8175
  }
8176
  return 0;
unknown's avatar
unknown committed
8177 8178
}

8179

8180 8181 8182 8183 8184 8185
/*
  Drops in all fields instead of current '*' field

  SYNOPSIS
    insert_fields()
    thd			Thread handler
8186
    context             Context for name resolution
8187 8188 8189 8190 8191 8192 8193
    db_name		Database name in case of 'database_name.table_name.*'
    table_name		Table name in case of 'table_name.*'
    it			Pointer to '*'
    any_privileges	0 If we should ensure that we have SELECT privileges
		          for all columns
                        1 If any privilege is ok
  RETURN
8194
    0	ok     'it' is updated to point at last inserted
unknown's avatar
unknown committed
8195
    1	error.  Error message is generated but not sent to client
8196
*/
unknown's avatar
unknown committed
8197

unknown's avatar
unknown committed
8198
bool
8199
insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
unknown's avatar
VIEW  
unknown committed
8200
	      const char *table_name, List_iterator<Item> *it,
8201
              bool any_privileges, uint *hidden_bit_fields, bool returning_field)
unknown's avatar
unknown committed
8202
{
unknown's avatar
unknown committed
8203 8204
  Field_iterator_table_ref field_iterator;
  bool found;
8205
  char name_buff[SAFE_NAME_LEN+1];
unknown's avatar
unknown committed
8206
  DBUG_ENTER("insert_fields");
8207
  DBUG_PRINT("arena", ("stmt arena: %p",thd->stmt_arena));
unknown's avatar
unknown committed
8208

8209 8210
  if (db_name && lower_case_table_names)
  {
unknown's avatar
unknown committed
8211 8212 8213 8214 8215
    /*
      convert database to lower case for comparison
      We can't do this in Item_field as this would change the
      'name' of the item which may be used in the select list
    */
8216
    strmake_buf(name_buff, db_name);
unknown's avatar
unknown committed
8217
    my_casedn_str(files_charset_info, name_buff);
unknown's avatar
unknown committed
8218
    db_name= name_buff;
8219 8220
  }

unknown's avatar
unknown committed
8221
  found= FALSE;
8222 8223 8224 8225 8226 8227

  /*
    If table names are qualified, then loop over all tables used in the query,
    else treat natural joins as leaves and do not iterate over their underlying
    tables.
  */
8228 8229
  TABLE_LIST *first= context->first_name_resolution_table;
  TABLE_LIST *TABLE_LIST::* next= &TABLE_LIST::next_name_resolution_table;
8230
  if (table_name && !returning_field)
8231 8232 8233 8234 8235
  {
    first= context->table_list;
    next= &TABLE_LIST::next_local;
  }
  for (TABLE_LIST *tables= first; tables; tables= tables->*next)
unknown's avatar
unknown committed
8236
  {
8237 8238 8239
    Field *field;
    TABLE *table= tables->table;

unknown's avatar
unknown committed
8240 8241
    DBUG_ASSERT(tables->is_leaf_for_name_resolution());

8242
    if ((table_name && my_strcasecmp(table_alias_charset, table_name,
8243 8244
                                     tables->alias.str)) ||
        (db_name && strcmp(tables->db.str, db_name)))
8245
      continue;
unknown's avatar
unknown committed
8246

unknown's avatar
unknown committed
8247
#ifndef NO_EMBEDDED_ACCESS_CHECKS
8248
    /* 
8249 8250
       Ensure that we have access rights to all fields to be inserted
       the table 'tables'. Under some circumstances, this check may be skipped.
8251

8252
       The check is skipped in the following cases:
8253

8254
       - any_privileges is true
8255

8256
       - the table is a derived table
8257

8258
       - the table is a view with SELECT privilege
8259

8260
       - the table is a base table with SELECT privilege
8261
    */
8262 8263 8264 8265
    if (!any_privileges &&
        !tables->is_derived() &&
        !(tables->is_view() && (tables->grant.privilege & SELECT_ACL)) &&
        !(table && (table->grant.privilege & SELECT_ACL)))
unknown's avatar
unknown committed
8266 8267
    {
      field_iterator.set(tables);
8268
      if (check_grant_all_columns(thd, SELECT_ACL, &field_iterator))
unknown's avatar
unknown committed
8269 8270
        DBUG_RETURN(TRUE);
    }
unknown's avatar
unknown committed
8271
#endif
unknown's avatar
VIEW  
unknown committed
8272

unknown's avatar
unknown committed
8273 8274 8275 8276 8277
    /*
      Update the tables used in the query based on the referenced fields. For
      views and natural joins this update is performed inside the loop below.
    */
    if (table)
8278
    {
8279
      thd->lex->used_tables|= table->map;
8280 8281
      thd->lex->current_select->select_list_tables|= table->map;
    }
unknown's avatar
unknown committed
8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292

    /*
      Initialize a generic field iterator for the current table reference.
      Notice that it is guaranteed that this iterator will iterate over the
      fields of a single table reference, because 'tables' is a leaf (for
      name resolution purposes).
    */
    field_iterator.set(tables);

    for (; !field_iterator.end_of_fields(); field_iterator.next())
    {
8293 8294 8295 8296 8297
      /*
        field() is always NULL for views (see, e.g. Field_iterator_view or
        Field_iterator_natural_join).
        But view fields can never be invisible.
      */
8298
      if ((field= field_iterator.field()) && field->invisible != VISIBLE)
8299
        continue;
8300

unknown's avatar
unknown committed
8301 8302 8303 8304
      Item *item;

      if (!(item= field_iterator.create_item(thd)))
        DBUG_RETURN(TRUE);
8305

8306 8307 8308
      /* cache the table for the Item_fields inserted by expanding stars */
      if (item->type() == Item::FIELD_ITEM && tables->cacheable_table)
        ((Item_field *)item)->cached_table= tables;
unknown's avatar
unknown committed
8309 8310

      if (!found)
8311
      {
unknown's avatar
unknown committed
8312
        found= TRUE;
8313
        it->replace(item); /* Replace '*' with the first found item. */
8314
      }
unknown's avatar
VIEW  
unknown committed
8315
      else
unknown's avatar
unknown committed
8316 8317
        it->after(item);   /* Add 'item' to the SELECT list. */

8318 8319 8320
      if (item->type() == Item::FIELD_ITEM && item->field_type() == MYSQL_TYPE_BIT)
        (*hidden_bit_fields)++;

unknown's avatar
unknown committed
8321 8322 8323 8324 8325
#ifndef NO_EMBEDDED_ACCESS_CHECKS
      /*
        Set privilege information for the fields of newly created views.
        We have that (any_priviliges == TRUE) if and only if we are creating
        a view. In the time of view creation we can't use the MERGE algorithm,
8326 8327 8328
        therefore if 'tables' is itself a view, it is represented by a
        temporary table. Thus in this case we can be sure that 'item' is an
        Item_field.
unknown's avatar
unknown committed
8329
      */
8330
      if (any_privileges && !tables->is_with_table() && !tables->is_derived())
8331
      {
8332
        DBUG_ASSERT((tables->field_translation == NULL && table) ||
unknown's avatar
unknown committed
8333 8334 8335
                    tables->is_natural_join);
        DBUG_ASSERT(item->type() == Item::FIELD_ITEM);
        Item_field *fld= (Item_field*) item;
8336
        const char *field_db_name= field_iterator.get_db_name();
8337
        const char *field_table_name= field_iterator.get_table_name();
8338

unknown's avatar
unknown committed
8339 8340 8341
        if (!tables->schema_table && 
            !(fld->have_privileges=
              (get_column_grant(thd, field_iterator.grant(),
8342
                                field_db_name,
8343
                                field_table_name, fld->field_name.str) &
unknown's avatar
unknown committed
8344 8345
               VIEW_ANY_ACL)))
        {
8346
          my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), "ANY",
8347 8348
                   thd->security_ctx->priv_user,
                   thd->security_ctx->host_or_ip,
8349
                   field_db_name, field_table_name);
unknown's avatar
unknown committed
8350 8351
          DBUG_RETURN(TRUE);
        }
8352
      }
unknown's avatar
unknown committed
8353
#endif
8354

unknown's avatar
unknown committed
8355
      if ((field= field_iterator.field()))
unknown's avatar
unknown committed
8356
      {
8357
        field->table->mark_column_with_deps(field);
unknown's avatar
unknown committed
8358
        if (table)
8359
          table->covering_keys.intersect(field->part_of_key);
unknown's avatar
unknown committed
8360
        if (tables->is_natural_join)
unknown's avatar
unknown committed
8361
        {
unknown's avatar
unknown committed
8362 8363
          TABLE *field_table;
          /*
8364
            In this case we are sure that the column ref will not be created
unknown's avatar
unknown committed
8365
            because it was already created and stored with the natural join.
8366
          */
unknown's avatar
unknown committed
8367
          Natural_join_column *nj_col;
unknown's avatar
unknown committed
8368
          if (!(nj_col= field_iterator.get_natural_column_ref()))
unknown's avatar
unknown committed
8369
            DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
8370
          DBUG_ASSERT(nj_col->table_field);
unknown's avatar
unknown committed
8371 8372
          field_table= nj_col->table_ref->table;
          if (field_table)
unknown's avatar
VIEW  
unknown committed
8373
          {
8374
            thd->lex->used_tables|= field_table->map;
8375 8376
            thd->lex->current_select->select_list_tables|=
              field_table->map;
8377
            field_table->covering_keys.intersect(field->part_of_key);
unknown's avatar
unknown committed
8378
            field_table->used_fields++;
unknown's avatar
VIEW  
unknown committed
8379
          }
unknown's avatar
unknown committed
8380
        }
unknown's avatar
unknown committed
8381
      }
unknown's avatar
unknown committed
8382
      else
8383
        thd->lex->used_tables|= item->used_tables();
8384
      thd->lex->current_select->cur_pos_in_select_list++;
unknown's avatar
unknown committed
8385
    }
unknown's avatar
unknown committed
8386 8387 8388 8389 8390 8391 8392 8393
    /*
      In case of stored tables, all fields are considered as used,
      while in the case of views, the fields considered as used are the
      ones marked in setup_tables during fix_fields of view columns.
      For NATURAL joins, used_tables is updated in the IF above.
    */
    if (table)
      table->used_fields= table->s->fields;
unknown's avatar
unknown committed
8394
  }
8395
  if (found)
unknown's avatar
unknown committed
8396
    DBUG_RETURN(FALSE);
8397

unknown's avatar
unknown committed
8398
  /*
8399 8400 8401
    TODO: in the case when we skipped all columns because there was a
    qualified '*', and all columns were coalesced, we have to give a more
    meaningful message than ER_BAD_TABLE_ERROR.
unknown's avatar
unknown committed
8402
  */
8403
  if (!table_name)
8404
    my_error(ER_NO_TABLES_USED, MYF(0));
8405
  else if (!db_name && !thd->db.str)
8406
    my_error(ER_NO_DB_ERROR, MYF(0));
8407
  else
8408 8409 8410
  {
    char name[FN_REFLEN];
    my_snprintf(name, sizeof(name), "%s.%s",
8411
                db_name ? db_name : thd->get_db(), table_name);
8412 8413
    my_error(ER_BAD_TABLE_ERROR, MYF(0), name);
  }
unknown's avatar
unknown committed
8414 8415

  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
8416 8417 8418
}


8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429
/**
  Wrap Item_ident

  @param thd             thread handle
  @param conds           pointer to the condition which should be wrapped
*/

void wrap_ident(THD *thd, Item **conds)
{
  Item_direct_ref_to_ident *wrapper;
  DBUG_ASSERT((*conds)->type() == Item::FIELD_ITEM || (*conds)->type() == Item::REF_ITEM);
8430 8431
  Query_arena *arena, backup;
  arena= thd->activate_stmt_arena_if_needed(&backup);
Monty's avatar
Monty committed
8432
  if ((wrapper= new (thd->mem_root) Item_direct_ref_to_ident(thd, (Item_ident *) (*conds))))
8433 8434 8435 8436 8437
    (*conds)= (Item*) wrapper;
  if (arena)
    thd->restore_active_arena(arena, &backup);
}

8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464
/**
  Prepare ON expression

  @param thd             Thread handle
  @param table           Pointer to table list
  @param is_update       Update flag

  @retval TRUE error.
  @retval FALSE OK.
*/

bool setup_on_expr(THD *thd, TABLE_LIST *table, bool is_update)
{
  uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
    return TRUE;				// Fatal error flag is set!
  for(; table; table= table->next_local)
  {
    TABLE_LIST *embedded; /* The table at the current level of nesting. */
    TABLE_LIST *embedding= table; /* The parent nested table reference. */
    do
    {
      embedded= embedding;
      if (embedded->on_expr)
      {
        thd->where="on clause";
        embedded->on_expr->mark_as_condition_AND_part(embedded);
8465 8466
        if (embedded->on_expr->fix_fields_if_needed_for_bool(thd,
                                                           &embedded->on_expr))
8467 8468 8469 8470 8471 8472 8473 8474
          return TRUE;
      }
      /*
        If it's a semi-join nest, fix its "left expression", as it is used by
        the SJ-Materialization
      */
      if (embedded->sj_subq_pred)
      {
8475
        Item **left_expr= embedded->sj_subq_pred->left_exp_ptr();
8476
        if ((*left_expr)->fix_fields_if_needed(thd, left_expr))
8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504
          return TRUE;
      }

      embedding= embedded->embedding;
    }
    while (embedding &&
           embedding->nested_join->join_list.head() == embedded);

    if (table->is_merged_derived())
    {
      SELECT_LEX *select_lex= table->get_single_select();
      setup_on_expr(thd, select_lex->get_table_list(), is_update);
    }

    /* process CHECK OPTION */
    if (is_update)
    {
      TABLE_LIST *view= table->top_table();
      if (view->effective_with_check)
      {
        if (view->prepare_check_option(thd))
          return TRUE;
        thd->change_item_tree(&table->check_option, view->check_option);
      }
    }
  }
  return FALSE;
}
8505

unknown's avatar
unknown committed
8506
/*
unknown's avatar
unknown committed
8507
  Fix all conditions and outer join expressions.
8508 8509 8510 8511

  SYNOPSIS
    setup_conds()
    thd     thread handler
unknown's avatar
unknown committed
8512 8513 8514 8515 8516 8517 8518 8519
    tables  list of tables for name resolving (select_lex->table_list)
    leaves  list of leaves of join table tree (select_lex->leaf_tables)
    conds   WHERE clause

  DESCRIPTION
    TODO

  RETURN
8520
    TRUE  if some error occurred (e.g. out of memory)
unknown's avatar
unknown committed
8521
    FALSE if all is OK
unknown's avatar
unknown committed
8522 8523
*/

8524
int setup_conds(THD *thd, TABLE_LIST *tables, List<TABLE_LIST> &leaves,
8525
                COND **conds)
unknown's avatar
unknown committed
8526
{
unknown's avatar
unknown committed
8527
  SELECT_LEX *select_lex= thd->lex->current_select;
unknown's avatar
unknown committed
8528
  TABLE_LIST *table= NULL;	// For HP compilers
8529 8530 8531 8532 8533 8534 8535 8536
  /*
    it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX
    which belong to LEX, i.e. most up SELECT) will be updated by
    INSERT/UPDATE/LOAD
    NOTE: using this condition helps to prevent call of prepare_check_option()
    from subquery of VIEW, because tables of subquery belongs to VIEW
    (see condition before prepare_check_option() call)
  */
8537
  bool it_is_update= (select_lex == thd->lex->first_select_lex()) &&
8538
    thd->lex->which_check_option_applicable();
8539
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
8540
  TABLE_LIST *derived= select_lex->master_unit()->derived;
8541
  bool save_resolve_in_select_list= select_lex->context.resolve_in_select_list;
unknown's avatar
unknown committed
8542
  DBUG_ENTER("setup_conds");
unknown's avatar
unknown committed
8543

8544
  select_lex->is_item_list_lookup= 0;
8545
  select_lex->context.resolve_in_select_list= false;
8546

Sergei Golubchik's avatar
Sergei Golubchik committed
8547 8548
  thd->column_usage= MARK_COLUMNS_READ;
  DBUG_PRINT("info", ("thd->column_usage: %d", thd->column_usage));
unknown's avatar
unknown committed
8549
  select_lex->cond_count= 0;
8550
  select_lex->between_count= 0;
unknown's avatar
unknown committed
8551
  select_lex->max_equal_elems= 0;
unknown's avatar
VIEW  
unknown committed
8552

8553 8554
  for (table= tables; table; table= table->next_local)
  {
8555
    if (select_lex == thd->lex->first_select_lex() &&
8556 8557 8558
        select_lex->first_cond_optimization &&
        table->merged_for_insert &&
        table->prepare_where(thd, conds, FALSE))
8559 8560 8561
      goto err_no_arena;
  }

unknown's avatar
unknown committed
8562 8563 8564
  if (*conds)
  {
    thd->where="where clause";
unknown's avatar
unknown committed
8565 8566 8567 8568
    DBUG_EXECUTE("where",
                 print_where(*conds,
                             "WHERE in setup_conds",
                             QT_ORDINARY););
8569 8570 8571 8572
    /*
      Wrap alone field in WHERE clause in case it will be outer field of subquery
      which need persistent pointer on it, but conds could be changed by optimizer
    */
8573
    if ((*conds)->type() == Item::FIELD_ITEM && !derived)
8574
      wrap_ident(thd, conds);
8575
    (*conds)->mark_as_condition_AND_part(NO_JOIN_NEST);
8576
    if ((*conds)->fix_fields_if_needed_for_bool(thd, conds))
8577
      goto err_no_arena;
unknown's avatar
unknown committed
8578 8579
  }

unknown's avatar
unknown committed
8580 8581 8582 8583
  /*
    Apply fix_fields() to all ON clauses at all levels of nesting,
    including the ones inside view definitions.
  */
8584 8585
  if (setup_on_expr(thd, tables, it_is_update))
    goto err_no_arena;
unknown's avatar
unknown committed
8586

unknown's avatar
unknown committed
8587
  if (!thd->stmt_arena->is_conventional())
unknown's avatar
unknown committed
8588 8589 8590 8591 8592 8593 8594 8595 8596
  {
    /*
      We are in prepared statement preparation code => we should store
      WHERE clause changing for next executions.

      We do this ON -> WHERE transformation only once per PS/SP statement.
    */
    select_lex->where= *conds;
  }
8597
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
8598
  select_lex->context.resolve_in_select_list= save_resolve_in_select_list;
8599
  DBUG_RETURN(thd->is_error());
unknown's avatar
unknown committed
8600

8601
err_no_arena:
8602
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
unknown's avatar
unknown committed
8603
  DBUG_RETURN(1);
unknown's avatar
unknown committed
8604 8605 8606 8607 8608 8609 8610 8611
}


/******************************************************************************
** Fill a record with data (for INSERT or UPDATE)
** Returns : 1 if some field has wrong type
******************************************************************************/

unknown's avatar
unknown committed
8612

8613 8614
/**
  Fill the fields of a table with the values of an Item list
unknown's avatar
unknown committed
8615

8616 8617 8618 8619 8620
  @param thd           thread handler
  @param table_arg     the table that is being modified
  @param fields        Item_fields list to be filled
  @param values        values to fill with
  @param ignore_errors TRUE if we should ignore errors
8621
  @param update        TRUE if update query
unknown's avatar
unknown committed
8622

8623
  @details
8624 8625 8626
    fill_record() may set table->auto_increment_field_not_null and a
    caller should make sure that it is reset after their last call to this
    function.
8627 8628
    default functions are executed for inserts.
    virtual fields are always updated
8629

8630
  @return Status
8631
  @retval true An error occurred.
8632
  @retval false OK.
unknown's avatar
unknown committed
8633 8634
*/

8635
bool
8636
fill_record(THD *thd, TABLE *table_arg, List<Item> &fields, List<Item> &values,
8637
            bool ignore_errors, bool update)
unknown's avatar
unknown committed
8638
{
unknown's avatar
unknown committed
8639
  List_iterator_fast<Item> f(fields),v(values);
8640
  Item *value, *fld;
unknown's avatar
unknown committed
8641
  Item_field *field;
8642 8643
  Field *rfield;
  TABLE *table;
Sergei Golubchik's avatar
Sergei Golubchik committed
8644
  bool only_unvers_fields= update && table_arg->versioned();
Michael Widenius's avatar
Michael Widenius committed
8645 8646
  bool save_abort_on_warning= thd->abort_on_warning;
  bool save_no_errors= thd->no_errors;
unknown's avatar
unknown committed
8647 8648
  DBUG_ENTER("fill_record");

Michael Widenius's avatar
Michael Widenius committed
8649
  thd->no_errors= ignore_errors;
8650 8651 8652 8653 8654
  /*
    Reset the table->auto_increment_field_not_null as it is valid for
    only one row.
  */
  if (fields.elements)
8655 8656
    table_arg->auto_increment_field_not_null= FALSE;

8657
  while ((fld= f++))
unknown's avatar
unknown committed
8658
  {
8659
    if (!(field= fld->field_for_view_update()))
8660
    {
8661
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name.str);
8662
      goto err;
8663
    }
unknown's avatar
unknown committed
8664
    value=v++;
8665
    DBUG_ASSERT(value);
8666 8667
    rfield= field->field;
    table= rfield->table;
8668 8669
    if (table->next_number_field &&
        rfield->field_index ==  table->next_number_field->field_index)
unknown's avatar
unknown committed
8670
      table->auto_increment_field_not_null= TRUE;
8671 8672
    const bool skip_sys_field= rfield->vers_sys_field(); // TODO: && !thd->vers_modify_history() [MDEV-16546]
    if ((rfield->vcol_info || skip_sys_field) &&
8673
        !value->vcol_assignment_allowed_value() &&
8674 8675
        table->s->table_category != TABLE_CATEGORY_TEMPORARY)
    {
8676
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
8677 8678
                          ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN,
                          ER_THD(thd, ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN),
8679
                          rfield->field_name.str, table->s->table_name.str);
8680
    }
Sergei Golubchik's avatar
Sergei Golubchik committed
8681 8682
    if (only_unvers_fields && !rfield->vers_update_unversioned())
      only_unvers_fields= false;
8683

8684
    if (rfield->stored_in_db())
unknown's avatar
unknown committed
8685
    {
8686 8687
      if (!skip_sys_field &&
          unlikely(value->save_in_field(rfield, 0) < 0) && !ignore_errors)
8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699
      {
        my_message(ER_UNKNOWN_ERROR, ER_THD(thd, ER_UNKNOWN_ERROR), MYF(0));
        goto err;
      }
      /*
        In sql MODE_SIMULTANEOUS_ASSIGNMENT,
        move field pointer on value stored in record[1]
        which contains row before update (see MDEV-13417)
      */
      if (update && thd->variables.sql_mode & MODE_SIMULTANEOUS_ASSIGNMENT)
        rfield->move_field_offset((my_ptrdiff_t) (table->record[1] -
                                                  table->record[0]));
unknown's avatar
unknown committed
8700
    }
8701
    rfield->set_has_explicit_value();
unknown's avatar
unknown committed
8702
  }
8703

8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719
  if (update && thd->variables.sql_mode & MODE_SIMULTANEOUS_ASSIGNMENT)
  {
    // restore fields pointers on record[0]
    f.rewind();
    while ((fld= f++))
    {
      rfield= fld->field_for_view_update()->field;
      if (rfield->stored_in_db())
      {
        table= rfield->table;
        rfield->move_field_offset((my_ptrdiff_t) (table->record[0] -
                                                  table->record[1]));
      }
    }
  }

8720 8721 8722 8723 8724 8725 8726
  if (update)
    table_arg->evaluate_update_default_function();
  else
    if (table_arg->default_field &&
        table_arg->update_default_fields(ignore_errors))
      goto err;

8727 8728
  if (table_arg->versioned() && !only_unvers_fields)
    table_arg->vers_update_fields();
8729
  /* Update virtual fields */
8730
  if (table_arg->vfield &&
8731
      table_arg->update_virtual_fields(table_arg->file, VCOL_UPDATE_FOR_WRITE))
Michael Widenius's avatar
Michael Widenius committed
8732
    goto err;
Michael Widenius's avatar
Michael Widenius committed
8733 8734
  thd->abort_on_warning= save_abort_on_warning;
  thd->no_errors=        save_no_errors;
8735
  DBUG_RETURN(thd->is_error());
8736
err:
8737
  DBUG_PRINT("error",("got error"));
Michael Widenius's avatar
Michael Widenius committed
8738 8739
  thd->abort_on_warning= save_abort_on_warning;
  thd->no_errors=        save_no_errors;
8740 8741
  if (fields.elements)
    table_arg->auto_increment_field_not_null= FALSE;
8742
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
8743 8744 8745
}


8746 8747 8748 8749 8750 8751 8752 8753 8754 8755
/**
  Prepare Item_field's for fill_record_n_invoke_before_triggers()

  This means redirecting from table->field to
  table->field_to_fill(), if needed.
*/
void switch_to_nullable_trigger_fields(List<Item> &items, TABLE *table)
{
  Field** field= table->field_to_fill();

Michael Widenius's avatar
Michael Widenius committed
8756
 /* True if we have NOT NULL fields and BEFORE triggers */
8757
  if (field != table->field)
8758 8759 8760 8761 8762
  {
    List_iterator_fast<Item> it(items);
    Item *item;

    while ((item= it++))
8763
      item->walk(&Item::switch_to_nullable_fields_processor, 1, field);
8764 8765 8766 8767 8768
    table->triggers->reset_extra_null_bitmap();
  }
}


8769 8770 8771 8772 8773 8774 8775 8776
/**
  Prepare Virtual fields and field with default expressions to use
  trigger fields

  This means redirecting from table->field to
  table->field_to_fill(), if needed.
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
8777
void switch_defaults_to_nullable_trigger_fields(TABLE *table)
8778
{
Sergei Golubchik's avatar
Sergei Golubchik committed
8779 8780 8781
  if (!table->default_field)
    return; // no defaults

8782 8783
  Field **trigger_field= table->field_to_fill();

Sergei Golubchik's avatar
Sergei Golubchik committed
8784
 /* True if we have NOT NULL fields and BEFORE triggers */
8785
  if (*trigger_field != *table->field)
8786
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
8787
    for (Field **field_ptr= table->default_field; *field_ptr ; field_ptr++)
8788 8789
    {
      Field *field= (*field_ptr);
8790
      field->default_value->expr->walk(&Item::switch_to_nullable_fields_processor, 1, trigger_field);
8791 8792 8793 8794 8795 8796
      *field_ptr= (trigger_field[field->field_index]);
    }
  }
}


8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814
/**
  Test NOT NULL constraint after BEFORE triggers
*/
static bool not_null_fields_have_null_values(TABLE *table)
{
  Field **orig_field= table->field;
  Field **filled_field= table->field_to_fill();

  if (filled_field != orig_field)
  {
    THD *thd=table->in_use;
    for (uint i=0; i < table->s->fields; i++)
    {
      Field *of= orig_field[i];
      Field *ff= filled_field[i];
      if (ff != of)
      {
        // copy after-update flags to of, copy before-update flags to ff
8815
        swap_variables(uint32, of->flags, ff->flags);
8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829
        if (ff->is_real_null())
        {
          ff->set_notnull(); // for next row WHERE condition in UPDATE
          if (convert_null_to_field_value_or_error(of) || thd->is_error())
            return true;
        }
      }
    }
  }

  return false;
}

/**
unknown's avatar
unknown committed
8830 8831 8832
  Fill fields in list with values from the list of items and invoke
  before triggers.

8833 8834 8835 8836 8837 8838
  @param thd           thread context
  @param table         the table that is being modified
  @param fields        Item_fields list to be filled
  @param values        values to fill with
  @param ignore_errors TRUE if we should ignore errors
  @param event         event type for triggers to be invoked
unknown's avatar
unknown committed
8839

8840
  @detail
unknown's avatar
unknown committed
8841 8842 8843 8844
    This function assumes that fields which values will be set and triggers
    to be invoked belong to the same table, and that TABLE::record[0] and
    record[1] buffers correspond to new and old versions of row respectively.

8845
  @return Status
8846
  @retval true An error occurred.
8847
  @retval false OK.
unknown's avatar
unknown committed
8848 8849 8850
*/

bool
Michael Widenius's avatar
Michael Widenius committed
8851 8852
fill_record_n_invoke_before_triggers(THD *thd, TABLE *table,
                                     List<Item> &fields,
unknown's avatar
unknown committed
8853 8854 8855
                                     List<Item> &values, bool ignore_errors,
                                     enum trg_event_type event)
{
8856
  int result;
8857
  Table_triggers_list *triggers= table->triggers;
8858

8859 8860
  result= fill_record(thd, table, fields, values, ignore_errors,
                      event == TRG_EVENT_UPDATE);
8861

Sergei Golubchik's avatar
Sergei Golubchik committed
8862
  if (!result && triggers)
8863
  {
Michael Widenius's avatar
Michael Widenius committed
8864 8865 8866 8867 8868 8869 8870 8871 8872
    if (triggers->process_triggers(thd, event, TRG_ACTION_BEFORE,
                                    TRUE) ||
        not_null_fields_have_null_values(table))
      return TRUE;

    /*
      Re-calculate virtual fields to cater for cases when base columns are
      updated by the triggers.
    */
8873
    if (table->vfield && fields.elements)
8874
    {
8875 8876 8877
      Item *fld= (Item_field*) fields.head();
      Item_field *item_field= fld->field_for_view_update();
      if (item_field)
8878 8879
      {
        DBUG_ASSERT(table == item_field->field->table);
8880 8881
        result|= table->update_virtual_fields(table->file,
                                              VCOL_UPDATE_FOR_WRITE);
8882
      }
8883 8884 8885
    }
  }
  return result;
unknown's avatar
unknown committed
8886 8887 8888
}


8889 8890
/**
  Fill the field buffer of a table with the values of an Item list
Michael Widenius's avatar
Michael Widenius committed
8891
  All fields are given a value
unknown's avatar
unknown committed
8892

8893 8894 8895 8896 8897 8898
  @param thd           thread handler
  @param table_arg     the table that is being modified
  @param ptr           pointer on pointer to record of fields
  @param values        values to fill with
  @param ignore_errors TRUE if we should ignore errors
  @param use_value     forces usage of value of the items instead of result
unknown's avatar
unknown committed
8899

8900
  @details
8901 8902 8903 8904
    fill_record() may set table->auto_increment_field_not_null and a
    caller should make sure that it is reset after their last call to this
    function.

8905
  @return Status
8906
  @retval true An error occurred.
8907
  @retval false OK.
unknown's avatar
unknown committed
8908 8909 8910
*/

bool
8911 8912
fill_record(THD *thd, TABLE *table, Field **ptr, List<Item> &values,
            bool ignore_errors, bool use_value)
unknown's avatar
unknown committed
8913
{
unknown's avatar
unknown committed
8914
  List_iterator_fast<Item> v(values);
8915
  List<TABLE> tbl_list;
unknown's avatar
unknown committed
8916
  Item *value;
8917
  Field *field;
8918
  bool abort_on_warning_saved= thd->abort_on_warning;
8919 8920 8921
  uint autoinc_index= table->next_number_field
                        ? table->next_number_field->field_index
                        : ~0U;
unknown's avatar
unknown committed
8922
  DBUG_ENTER("fill_record");
8923 8924 8925 8926 8927 8928 8929 8930 8931 8932
  if (!*ptr)
  {
    /* No fields to update, quite strange!*/
    DBUG_RETURN(0);
  }

  /*
    On INSERT or UPDATE fields are checked to be from the same table,
    thus we safely can take table from the first field.
  */
8933
  DBUG_ASSERT((*ptr)->table == table);
8934

8935 8936 8937 8938
  /*
    Reset the table->auto_increment_field_not_null as it is valid for
    only one row.
  */
8939
  table->auto_increment_field_not_null= FALSE;
8940
  while ((field = *ptr++) && ! thd->is_error())
unknown's avatar
unknown committed
8941
  {
8942 8943 8944
    /* Ensure that all fields are from the same table */
    DBUG_ASSERT(field->table == table);

8945
    if (unlikely(field->invisible))
8946
      continue;
8947 8948

    value=v++;
8949 8950 8951

    bool vers_sys_field= table->versioned() && field->vers_sys_field();

8952
    if (field->field_index == autoinc_index)
unknown's avatar
unknown committed
8953
      table->auto_increment_field_not_null= TRUE;
8954
    if ((unlikely(field->vcol_info) || (vers_sys_field && !ignore_errors)) &&
8955
        !value->vcol_assignment_allowed_value() &&
8956 8957
        table->s->table_category != TABLE_CATEGORY_TEMPORARY)
    {
8958
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
8959 8960 8961 8962 8963
                          ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN,
                          ER_THD(thd, ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN),
                          field->field_name.str, table->s->table_name.str);
      if (vers_sys_field)
        continue;
8964
    }
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
8965

unknown's avatar
unknown committed
8966 8967 8968 8969 8970
    if (use_value)
      value->save_val(field);
    else
      if (value->save_in_field(field, 0) < 0)
        goto err;
8971
    field->set_has_explicit_value();
unknown's avatar
unknown committed
8972
  }
8973 8974 8975 8976
  /* Update virtual fields if there wasn't any errors */
  if (!thd->is_error())
  {
    thd->abort_on_warning= FALSE;
Marko Mäkelä's avatar
Marko Mäkelä committed
8977 8978
    if (table->default_field && table->update_default_fields(ignore_errors))
      goto err;
8979 8980 8981 8982 8983 8984 8985
    if (table->versioned())
      table->vers_update_fields();
    if (table->vfield &&
        table->update_virtual_fields(table->file, VCOL_UPDATE_FOR_WRITE))
      goto err;
    thd->abort_on_warning= abort_on_warning_saved;
  }
8986
  DBUG_RETURN(thd->is_error());
8987 8988

err:
8989
  thd->abort_on_warning= abort_on_warning_saved;
8990
  table->auto_increment_field_not_null= FALSE;
8991
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
8992 8993 8994
}


unknown's avatar
unknown committed
8995
/*
8996
  Fill fields in an array with values from the list of items and invoke
unknown's avatar
unknown committed
8997 8998
  before triggers.

8999 9000 9001 9002 9003 9004
  @param thd           thread context
  @param table         the table that is being modified
  @param ptr        the fields to be filled
  @param values        values to fill with
  @param ignore_errors TRUE if we should ignore errors
  @param event         event type for triggers to be invoked
unknown's avatar
unknown committed
9005

9006
  @detail
unknown's avatar
unknown committed
9007 9008 9009 9010
    This function assumes that fields which values will be set and triggers
    to be invoked belong to the same table, and that TABLE::record[0] and
    record[1] buffers correspond to new and old versions of row respectively.

9011
  @return Status
9012
  @retval true An error occurred.
9013
  @retval false OK.
unknown's avatar
unknown committed
9014 9015 9016
*/

bool
9017
fill_record_n_invoke_before_triggers(THD *thd, TABLE *table, Field **ptr,
unknown's avatar
unknown committed
9018 9019 9020
                                     List<Item> &values, bool ignore_errors,
                                     enum trg_event_type event)
{
9021
  bool result;
9022
  Table_triggers_list *triggers= table->triggers;
9023 9024 9025 9026 9027 9028

  result= fill_record(thd, table, ptr, values, ignore_errors, FALSE);

  if (!result && triggers && *ptr)
    result= triggers->process_triggers(thd, event, TRG_ACTION_BEFORE, TRUE) ||
            not_null_fields_have_null_values(table);
9029 9030 9031 9032 9033 9034
  /*
    Re-calculate virtual fields to cater for cases when base columns are
    updated by the triggers.
  */
  if (!result && triggers && *ptr)
  {
9035
    DBUG_ASSERT(table == (*ptr)->table);
9036
    if (table->vfield)
9037
      result= table->update_virtual_fields(table->file, VCOL_UPDATE_FOR_WRITE);
9038 9039 9040
  }
  return result;

unknown's avatar
unknown committed
9041 9042 9043
}


9044
my_bool mysql_rm_tmp_tables(void)
unknown's avatar
unknown committed
9045
{
unknown's avatar
unknown committed
9046
  uint i, idx;
9047
  char	path[FN_REFLEN], *tmpdir, path_copy[FN_REFLEN];
unknown's avatar
unknown committed
9048 9049
  MY_DIR *dirp;
  FILEINFO *file;
unknown's avatar
unknown committed
9050
  TABLE_SHARE share;
9051
  THD *thd;
unknown's avatar
unknown committed
9052 9053
  DBUG_ENTER("mysql_rm_tmp_tables");

Monty's avatar
Monty committed
9054
  if (!(thd= new THD(0)))
9055
    DBUG_RETURN(1);
unknown's avatar
unknown committed
9056
  thd->thread_stack= (char*) &thd;
9057 9058
  thd->store_globals();

unknown's avatar
unknown committed
9059 9060 9061
  for (i=0; i<=mysql_tmpdir_list.max; i++)
  {
    tmpdir=mysql_tmpdir_list.list[i];
unknown's avatar
unknown committed
9062
    /* See if the directory exists */
unknown's avatar
unknown committed
9063 9064
    if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
      continue;
unknown's avatar
unknown committed
9065

unknown's avatar
unknown committed
9066
    /* Remove all SQLxxx tables from directory */
unknown's avatar
unknown committed
9067

Sergei Golubchik's avatar
Sergei Golubchik committed
9068
    for (idx=0 ; idx < (uint) dirp->number_of_files ; idx++)
unknown's avatar
unknown committed
9069 9070
    {
      file=dirp->dir_entry+idx;
unknown's avatar
unknown committed
9071

9072
      if (!strncmp(file->name, tmp_file_prefix, tmp_file_prefix_length))
unknown's avatar
unknown committed
9073
      {
unknown's avatar
unknown committed
9074
        char *ext= fn_ext(file->name);
9075
        size_t ext_len= strlen(ext);
9076
        size_t path_len= my_snprintf(path, sizeof(path),
unknown's avatar
unknown committed
9077 9078
                                       "%s%c%s", tmpdir, FN_LIBCHAR,
                                       file->name);
Michael Widenius's avatar
Michael Widenius committed
9079
        if (!strcmp(reg_ext, ext))
9080
        {
unknown's avatar
unknown committed
9081
          /* We should cut file extention before deleting of table */
9082 9083 9084 9085 9086
          memcpy(path_copy, path, path_len - ext_len);
          path_copy[path_len - ext_len]= 0;
          init_tmp_table_share(thd, &share, "", 0, "", path_copy);
          if (!open_table_def(thd, &share))
            share.db_type()->drop_table(share.db_type(), path_copy);
unknown's avatar
unknown committed
9087
          free_table_share(&share);
9088
        }
unknown's avatar
unknown committed
9089 9090 9091 9092 9093
        /*
          File can be already deleted by tmp_table.file->delete_table().
          So we hide error messages which happnes during deleting of these
          files(MYF(0)).
        */
9094
        (void) mysql_file_delete(key_file_misc, path, MYF(0));
unknown's avatar
unknown committed
9095
      }
unknown's avatar
unknown committed
9096
    }
unknown's avatar
unknown committed
9097
    my_dirend(dirp);
unknown's avatar
unknown committed
9098
  }
9099 9100
  delete thd;
  DBUG_RETURN(0);
unknown's avatar
unknown committed
9101 9102 9103 9104 9105 9106 9107
}


/*****************************************************************************
	unireg support functions
*****************************************************************************/

9108
int setup_ftfuncs(SELECT_LEX *select_lex)
unknown's avatar
unknown committed
9109
{
9110 9111
  List_iterator<Item_func_match> li(*(select_lex->ftfunc_list)),
                                 lj(*(select_lex->ftfunc_list));
9112
  Item_func_match *ftf, *ftf2;
unknown's avatar
unknown committed
9113 9114

  while ((ftf=li++))
9115
  {
unknown's avatar
unknown committed
9116 9117
    if (ftf->fix_index())
      return 1;
9118 9119
    lj.rewind();
    while ((ftf2=lj++) != ftf)
9120
    {
9121
      if (ftf->eq(ftf2,1) && !ftf2->master)
9122 9123 9124
        ftf2->master=ftf;
    }
  }
unknown's avatar
unknown committed
9125 9126 9127

  return 0;
}
9128

9129

9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142
void cleanup_ftfuncs(SELECT_LEX *select_lex)
{
  List_iterator<Item_func_match> li(*(select_lex->ftfunc_list)),
                                 lj(*(select_lex->ftfunc_list));
  Item_func_match *ftf;

  while ((ftf=li++))
  {
    ftf->cleanup();
  }
}


9143
int init_ftfuncs(THD *thd, SELECT_LEX *select_lex, bool no_order)
9144
{
9145
  if (select_lex->ftfunc_list->elements)
9146
  {
9147
    List_iterator<Item_func_match> li(*(select_lex->ftfunc_list));
unknown's avatar
unknown committed
9148
    Item_func_match *ifm;
9149

unknown's avatar
unknown committed
9150
    while ((ifm=li++))
9151
      if (unlikely(!ifm->fixed()))
9152 9153 9154 9155 9156
        /*
          it mean that clause where was FT function was removed, so we have
          to remove the function from the list.
        */
        li.remove();
9157 9158
      else if (ifm->init_search(thd, no_order))
	return 1;
unknown's avatar
unknown committed
9159
  }
9160 9161
  return 0;
}
unknown's avatar
VIEW  
unknown committed
9162 9163


9164
bool is_equal(const LEX_CSTRING *a, const LEX_CSTRING *b)
9165 9166 9167
{
  return a->length == b->length && !strncmp(a->str, b->str, a->length);
}
unknown's avatar
unknown committed
9168

9169 9170 9171 9172 9173 9174 9175 9176 9177
/*
  Open and lock system tables for read.

  SYNOPSIS
    open_system_tables_for_read()
      thd         Thread context.
      table_list  List of tables to open.

  NOTES
9178 9179 9180
    Caller should have used start_new_trans object to start a new
    transcation when reading system tables.

9181 9182
    Thanks to restrictions which we put on opening and locking of
    system tables for writing, we can open and lock them for reading
9183 9184 9185
    even when we already have some other tables open and locked.
    One should call thd->commit_whole_transaction_and_close_tables()
    to close systems tables opened with this call.
9186

Igor Babaev's avatar
Igor Babaev committed
9187 9188 9189 9190 9191 9192
  NOTES
   In some situations we  use this function to open system tables for
   writing. It happens, for examples, with statistical tables when
   they are updated by an ANALYZE command. In these cases we should
   guarantee that system tables will not be deadlocked.

9193 9194 9195 9196 9197 9198
  RETURN
    FALSE   Success
    TRUE    Error
*/

bool
9199
open_system_tables_for_read(THD *thd, TABLE_LIST *table_list)
9200
{
Konstantin Osipov's avatar
Konstantin Osipov committed
9201 9202
  Query_tables_list query_tables_list_backup;
  LEX *lex= thd->lex;
9203
  DBUG_ENTER("open_system_tables_for_read");
9204
  DBUG_ASSERT(thd->internal_transaction());
9205

Konstantin Osipov's avatar
Konstantin Osipov committed
9206 9207 9208 9209 9210 9211 9212
  /*
    Besides using new Open_tables_state for opening system tables,
    we also have to backup and reset/and then restore part of LEX
    which is accessed by open_tables() in order to determine if
    prelocking is needed and what tables should be added for it.
  */
  lex->reset_n_backup_query_tables_list(&query_tables_list_backup);
9213
  thd->lex->sql_command= SQLCOM_SELECT;
9214

9215 9216 9217 9218 9219
  /*
    Only use MYSQL_LOCK_IGNORE_TIMEOUT for tables opened for read.
    This is to ensure that lock_wait_timeout is honored when trying
    to update stats tables.
  */
9220
  if (open_and_lock_tables(thd, table_list, FALSE,
9221
                           (MYSQL_OPEN_IGNORE_FLUSH |
9222
                            MYSQL_OPEN_IGNORE_LOGGING_FORMAT |
9223
                            (table_list->lock_type < TL_FIRST_WRITE ?
9224
                             MYSQL_LOCK_IGNORE_TIMEOUT : 0))))
9225
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
9226
    lex->restore_backup_query_tables_list(&query_tables_list_backup);
9227
    DBUG_RETURN(TRUE);
9228 9229
  }

Konstantin Osipov's avatar
Konstantin Osipov committed
9230
  for (TABLE_LIST *tables= table_list; tables; tables= tables->next_global)
9231
  {
Konstantin Osipov's avatar
Konstantin Osipov committed
9232
    DBUG_ASSERT(tables->table->s->table_category == TABLE_CATEGORY_SYSTEM);
9233
    tables->table->file->row_logging= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
9234
    tables->table->use_all_columns();
9235
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
9236 9237 9238
  lex->restore_backup_query_tables_list(&query_tables_list_backup);

  DBUG_RETURN(FALSE);
9239 9240
}

9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260
/**
  A helper function to close a mysql.* table opened
  in an auxiliary THD during bootstrap or in the main
  connection, when we know that there are no locks
  held by the connection due to a preceding implicit
  commit.

  We need this function since we'd like to not
  just close the system table, but also release
  the metadata lock on it.

  Note, that in LOCK TABLES mode this function
  does not release the metadata lock. But in this
  mode the table can be opened only if it is locked
  explicitly with LOCK TABLES.
*/

void
close_mysql_tables(THD *thd)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
9261
  if (! thd->in_sub_stmt)
Marko Mäkelä's avatar
Marko Mäkelä committed
9262
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
9263
    trans_commit_stmt(thd);
Marko Mäkelä's avatar
Marko Mäkelä committed
9264 9265
    trans_commit(thd);
  }
9266
  close_thread_tables(thd);
9267
  thd->release_transactional_locks();
9268 9269
}

9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290
/*
  Open and lock one system table for update.

  SYNOPSIS
    open_system_table_for_update()
      thd        Thread context.
      one_table  Table to open.

  NOTES
    Table opened with this call should closed using close_thread_tables().

  RETURN
    0	Error
    #	Pointer to TABLE object of system table
*/

TABLE *
open_system_table_for_update(THD *thd, TABLE_LIST *one_table)
{
  DBUG_ENTER("open_system_table_for_update");

9291 9292
  TABLE *table= open_ltable(thd, one_table, one_table->lock_type,
                            MYSQL_LOCK_IGNORE_TIMEOUT);
9293 9294
  if (table)
  {
9295
    DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_SYSTEM);
9296
    table->use_all_columns();
9297 9298
    /* This table instance is not row logged */
    table->file->row_logging= 0;
9299 9300 9301
  }
  DBUG_RETURN(table);
}
9302 9303

/**
Marc Alff's avatar
Marc Alff committed
9304
  Open a log table.
9305 9306 9307 9308
  Opening such tables is performed internally in the server
  implementation, and is a 'nested' open, since some tables
  might be already opened by the current thread.
  The thread context before this call is saved, and is restored
Marc Alff's avatar
Marc Alff committed
9309
  when calling close_log_table().
9310
  @param thd The current thread
Marc Alff's avatar
Marc Alff committed
9311
  @param one_table Log table to open
9312 9313 9314
  @param backup [out] Temporary storage used to save the thread context
*/
TABLE *
9315
open_log_table(THD *thd, TABLE_LIST *one_table, Open_tables_backup *backup)
9316
{
9317
  uint flags= ( MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
9318
                MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY |
9319
                MYSQL_OPEN_IGNORE_FLUSH |
9320
                MYSQL_LOCK_IGNORE_TIMEOUT |
9321
                MYSQL_LOCK_LOG_TABLE);
9322 9323 9324
  TABLE *table;
  /* Save value that is changed in mysql_lock_tables() */
  ulonglong save_utime_after_lock= thd->utime_after_lock;
Marc Alff's avatar
Marc Alff committed
9325
  DBUG_ENTER("open_log_table");
9326 9327 9328

  thd->reset_n_backup_open_tables_state(backup);

9329
  if ((table= open_ltable(thd, one_table, one_table->lock_type, flags)))
9330
  {
9331
    DBUG_ASSERT(table->s->table_category == TABLE_CATEGORY_LOG);
9332 9333
    DBUG_ASSERT(!table->file->row_logging);

9334 9335 9336
    /* Make sure all columns get assigned to a default value */
    table->use_all_columns();
    DBUG_ASSERT(table->s->no_replicate);
9337
  }
9338 9339
  else
    thd->restore_backup_open_tables_state(backup);
9340

9341
  thd->utime_after_lock= save_utime_after_lock;
9342 9343
  DBUG_RETURN(table);
}
9344 9345

/**
Marc Alff's avatar
Marc Alff committed
9346 9347
  Close a log table.
  The last table opened by open_log_table()
9348 9349 9350 9351
  is closed, then the thread context is restored.
  @param thd The current thread
  @param backup [in] the context to restore.
*/
9352

9353
void close_log_table(THD *thd, Open_tables_backup *backup)
9354
{
9355 9356 9357 9358 9359 9360 9361 9362
  /*
    Inform the transaction handler that we are closing the
    system tables and we don't need the read view anymore.
  */
  for (TABLE *table= thd->open_tables ; table ; table= table->next)
    table->file->extra(HA_EXTRA_PREPARE_FOR_FORCED_CLOSE);
  close_thread_tables(thd);
  thd->restore_backup_open_tables_state(backup);
9363 9364
}

9365

9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382
/**
  @brief
  Remove 'fixed' flag from items in a list

  @param items list of items to un-fix

  @details
  This function sets to 0 the 'fixed' flag for items in the 'items' list.
  It's needed to force correct marking of views' fields for INSERT/UPDATE
  statements.
*/

void unfix_fields(List<Item> &fields)
{
  List_iterator<Item> li(fields);
  Item *item;
  while ((item= li++))
9383
    item->unfix_fields();
9384 9385
}

Igor Babaev's avatar
Merge  
Igor Babaev committed
9386

9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399
/**
  Check result of dynamic column function and issue error if it is needed

  @param rc              The result code of dynamic column function

  @return the result code which was get as an argument\
*/

int dynamic_column_error_message(enum_dyncol_func_result rc)
{
  switch (rc) {
  case ER_DYNCOL_YES:
  case ER_DYNCOL_OK:
9400
  case ER_DYNCOL_TRUNCATED:
9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420
    break; // it is not an error
  case ER_DYNCOL_FORMAT:
    my_error(ER_DYN_COL_WRONG_FORMAT, MYF(0));
    break;
  case ER_DYNCOL_LIMIT:
    my_error(ER_DYN_COL_IMPLEMENTATION_LIMIT, MYF(0));
    break;
  case ER_DYNCOL_RESOURCE:
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    break;
  case ER_DYNCOL_DATA:
    my_error(ER_DYN_COL_DATA, MYF(0));
    break;
  case ER_DYNCOL_UNKNOWN_CHARSET:
    my_error(ER_DYN_COL_WRONG_CHARSET, MYF(0));
    break;
  }
  return rc;
}

9421 9422 9423
/**
  @} (end of group Data_Dictionary)
*/