~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Brian Aker
  • Date: 2008-10-06 06:47:29 UTC
  • Revision ID: brian@tangent.org-20081006064729-2i9mhjkzyvow9xsm
RemoveĀ uint.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
/* Basic functions needed by many modules */
18
18
#include <drizzled/server_includes.h>
19
 
#include <drizzled/virtual_column_info.h>
20
 
#include <drizzled/field/timestamp.h>
21
 
#include <drizzled/field/null.h>
22
 
 
23
 
#include <signal.h>
24
 
 
25
 
#if TIME_WITH_SYS_TIME
26
 
# include <sys/time.h>
27
 
# include <time.h>
28
 
#else
29
 
# if HAVE_SYS_TIME_H
30
 
#  include <sys/time.h>
31
 
# else
32
 
#  include <time.h>
33
 
# endif
34
 
#endif
35
 
#include <mysys/my_pthread.h>
36
 
 
37
19
#include <drizzled/sql_select.h>
38
20
#include <mysys/my_dir.h>
39
 
#include <drizzled/error.h>
40
 
#include <drizzled/gettext.h>
41
 
#include <drizzled/nested_join.h>
42
 
#include <drizzled/sql_base.h>
43
 
#include <drizzled/show.h>
44
 
#include <drizzled/item/cmpfunc.h>
45
 
#include <drizzled/replicator.h>
46
 
#include <drizzled/check_stack_overrun.h>
47
 
#include <drizzled/lock.h>
 
21
#include <drizzled/drizzled_error_messages.h>
 
22
#include <libdrizzle/gettext.h>
48
23
 
 
24
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")
49
25
 
50
26
/**
51
27
  @defgroup Data_Dictionary Data Dictionary
58
34
static pthread_mutex_t LOCK_table_share;
59
35
static bool table_def_inited= 0;
60
36
 
61
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
37
static int open_unireg_entry(THD *thd, Table *entry, TableList *table_list,
62
38
                             const char *alias,
63
39
                             char *cache_key, uint32_t cache_key_length);
64
 
extern "C" void free_cache_entry(void *entry);
65
 
static void close_old_data_files(Session *session, Table *table, bool morph_locks,
 
40
static void free_cache_entry(Table *entry);
 
41
static void close_old_data_files(THD *thd, Table *table, bool morph_locks,
66
42
                                 bool send_refresh);
67
43
 
68
44
 
69
45
extern "C" unsigned char *table_cache_key(const unsigned char *record, size_t *length,
70
 
                                  bool )
 
46
                                  bool not_used __attribute__((unused)))
71
47
{
72
48
  Table *entry=(Table*) record;
73
49
  *length= entry->s->table_cache_key.length;
77
53
 
78
54
bool table_cache_init(void)
79
55
{
80
 
  return hash_init(&open_cache, &my_charset_bin,
81
 
                   (size_t) table_cache_size+16,
 
56
  return hash_init(&open_cache, &my_charset_bin, table_cache_size+16,
82
57
                   0, 0, table_cache_key,
83
 
                   free_cache_entry, 0);
 
58
                   (hash_free_key) free_cache_entry, 0);
84
59
}
85
60
 
86
61
void table_cache_free(void)
104
79
 
105
80
  SYNOPSIS
106
81
    create_table_def_key()
107
 
    session                     Thread handler
 
82
    thd                 Thread handler
108
83
    key                 Create key here (must be of size MAX_DBKEY_LENGTH)
109
84
    table_list          Table definition
110
85
    tmp_table           Set if table is a tmp table
124
99
    Length of key
125
100
*/
126
101
 
127
 
uint32_t create_table_def_key(Session *session, char *key, TableList *table_list,
 
102
uint32_t create_table_def_key(THD *thd, char *key, TableList *table_list,
128
103
                          bool tmp_table)
129
104
{
130
 
  uint32_t key_length;
131
 
  char *key_pos= key;
132
 
  key_pos= strcpy(key_pos, table_list->db) + strlen(table_list->db);
133
 
  key_pos= strcpy(key_pos+1, table_list->table_name) +
134
 
                  strlen(table_list->table_name);
135
 
  key_length= (uint32_t)(key_pos-key)+1;
136
 
 
 
105
  uint32_t key_length= (uint) (my_stpcpy(my_stpcpy(key, table_list->db)+1,
 
106
                                  table_list->table_name)-key)+1;
137
107
  if (tmp_table)
138
108
  {
139
 
    int4store(key + key_length, session->server_id);
140
 
    int4store(key + key_length + 4, session->variables.pseudo_thread_id);
 
109
    int4store(key + key_length, thd->server_id);
 
110
    int4store(key + key_length + 4, thd->variables.pseudo_thread_id);
141
111
    key_length+= TMP_TABLE_KEY_EXTRA;
142
112
  }
143
113
  return key_length;
150
120
*****************************************************************************/
151
121
 
152
122
extern "C" unsigned char *table_def_key(const unsigned char *record, size_t *length,
153
 
                                bool )
 
123
                                bool not_used __attribute__((unused)))
154
124
{
155
125
  TABLE_SHARE *entry=(TABLE_SHARE*) record;
156
126
  *length= entry->table_cache_key.length;
180
150
  oldest_unused_share= &end_of_unused_share;
181
151
  end_of_unused_share.prev= &oldest_unused_share;
182
152
 
183
 
  return hash_init(&table_def_cache, &my_charset_bin, (size_t)table_def_size,
 
153
  return hash_init(&table_def_cache, &my_charset_bin, table_def_size,
184
154
                   0, 0, table_def_key,
185
155
                   (hash_free_key) table_def_free_entry, 0);
186
156
}
208
178
  Get TABLE_SHARE for a table.
209
179
 
210
180
  get_table_share()
211
 
  session                       Thread handle
 
181
  thd                   Thread handle
212
182
  table_list            Table that should be opened
213
183
  key                   Table cache key
214
184
  key_length            Length of key
229
199
   #  Share for table
230
200
*/
231
201
 
232
 
TABLE_SHARE *get_table_share(Session *session, TableList *table_list, char *key,
 
202
TABLE_SHARE *get_table_share(THD *thd, TableList *table_list, char *key,
233
203
                             uint32_t key_length, uint32_t db_flags, int *error)
234
204
{
235
205
  TABLE_SHARE *share;
272
242
    free_table_share(share);
273
243
    return(0);                          // return error
274
244
  }
275
 
  if (open_table_def(session, share, db_flags))
 
245
  if (open_table_def(thd, share, db_flags))
276
246
  {
277
247
    *error= share->error;
278
248
    (void) hash_delete(&table_def_cache, (unsigned char*) share);
283
253
  return(share);
284
254
 
285
255
found:
286
 
  /*
 
256
  /* 
287
257
     We found an existing table definition. Return it if we didn't get
288
258
     an error when reading the table definition from file.
289
259
  */
332
302
*/
333
303
 
334
304
static TABLE_SHARE
335
 
*get_table_share_with_create(Session *session, TableList *table_list,
 
305
*get_table_share_with_create(THD *thd, TableList *table_list,
336
306
                             char *key, uint32_t key_length,
337
307
                             uint32_t db_flags, int *error)
338
308
{
339
309
  TABLE_SHARE *share;
 
310
  int tmp;
340
311
 
341
 
  share= get_table_share(session, table_list, key, key_length, db_flags, error);
 
312
  share= get_table_share(thd, table_list, key, key_length, db_flags, error);
342
313
  /*
343
314
    If share is not NULL, we found an existing share.
344
315
 
345
316
    If share is NULL, and there is no error, we're inside
346
317
    pre-locking, which silences 'ER_NO_SUCH_TABLE' errors
347
 
    with the intention to silently drop non-existing tables
 
318
    with the intention to silently drop non-existing tables 
348
319
    from the pre-locking list. In this case we still need to try
349
320
    auto-discover before returning a NULL share.
350
321
 
351
322
    If share is NULL and the error is ER_NO_SUCH_TABLE, this is
352
 
    the same as above, only that the error was not silenced by
 
323
    the same as above, only that the error was not silenced by 
353
324
    pre-locking. Once again, we need to try to auto-discover
354
325
    the share.
355
326
 
358
329
 
359
330
    @todo Rework alternative ways to deal with ER_NO_SUCH Table.
360
331
  */
361
 
  if (share || (session->is_error() && (session->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
 
332
  if (share || (thd->is_error() && (thd->main_da.sql_errno() != ER_NO_SUCH_TABLE)))
362
333
 
363
334
    return(share);
364
335
 
365
 
  return 0;
 
336
  /* Table didn't exist. Check if some engine can provide it */
 
337
  if ((tmp= ha_create_table_from_engine(thd, table_list->db,
 
338
                                        table_list->table_name)) < 0)
 
339
    return(0);
 
340
 
 
341
  if (tmp)
 
342
  {
 
343
    /* Give right error message */
 
344
    thd->clear_error();
 
345
    my_printf_error(ER_UNKNOWN_ERROR,
 
346
                    "Failed to open '%-.64s', error while "
 
347
                    "unpacking from engine",
 
348
                    MYF(0), table_list->table_name);
 
349
    return(0);
 
350
  }
 
351
  /* Table existed in engine. Let's open it */
 
352
  drizzle_reset_errors(thd, 1);                   // Clear warnings
 
353
  thd->clear_error();                           // Clear error message
 
354
  return(get_table_share(thd, table_list, key, key_length,
 
355
                              db_flags, error));
366
356
}
367
357
 
368
358
 
369
 
/*
 
359
/* 
370
360
   Mark that we are not using table share anymore.
371
361
 
372
362
   SYNOPSIS
388
378
*/
389
379
 
390
380
void release_table_share(TABLE_SHARE *share,
391
 
                         enum release_type )
 
381
                         enum release_type type __attribute__((unused)))
392
382
{
393
383
  bool to_be_deleted= 0;
394
384
 
446
436
 
447
437
  table_list.db= (char*) db;
448
438
  table_list.table_name= (char*) table_name;
449
 
  key_length= create_table_def_key((Session*) 0, key, &table_list, 0);
 
439
  key_length= create_table_def_key((THD*) 0, key, &table_list, 0);
450
440
  return (TABLE_SHARE*) hash_search(&table_def_cache,(unsigned char*) key, key_length);
451
 
}
 
441
}  
452
442
 
453
443
 
454
444
/*
462
452
    By leaving the table in the table cache, it disallows any other thread
463
453
    to open the table
464
454
 
465
 
    session->killed will be set if we run out of memory
 
455
    thd->killed will be set if we run out of memory
466
456
 
467
457
    If closing a MERGE child, the calling function has to take care for
468
458
    closing the parent too, if necessary.
509
499
 
510
500
  SYNOPSIS
511
501
    list_open_tables()
 
502
    thd                 Thread THD
512
503
    wild                SQL like expression
513
504
 
514
505
  NOTES
521
512
    #           Pointer to list of names of open tables.
522
513
*/
523
514
 
524
 
OPEN_TableList *list_open_tables(const char *db, const char *wild)
 
515
OPEN_TableList *list_open_tables(THD *thd __attribute__((unused)),
 
516
                                  const char *db, const char *wild)
525
517
{
526
518
  int result = 0;
527
519
  OPEN_TableList **start_list, *open_list;
568
560
      open_list=0;                              // Out of memory
569
561
      break;
570
562
    }
571
 
    strcpy((*start_list)->table=
572
 
           strcpy(((*start_list)->db= (char*) ((*start_list)+1)),
573
 
           share->db.str)+share->db.length+1,
574
 
           share->table_name.str);
 
563
    my_stpcpy((*start_list)->table=
 
564
           my_stpcpy(((*start_list)->db= (char*) ((*start_list)+1)),
 
565
                  share->db.str)+1,
 
566
           share->table_name.str);
575
567
    (*start_list)->in_use= entry->in_use ? 1 : 0;
576
568
    (*start_list)->locked= entry->locked_by_name ? 1 : 0;
577
569
    start_list= &(*start_list)->next;
590
582
{                                               // Free all structures
591
583
  free_io_cache(table);
592
584
  if (table->file)                              // Not true if name lock
593
 
    table->closefrm(true);                      // close file
 
585
    closefrm(table, 1);                 // close file
594
586
  return;
595
587
}
596
588
 
599
591
 
600
592
  SYNOPSIS
601
593
    free_cache_entry()
602
 
    entry               Table to remove
 
594
    table               Table to remove
603
595
 
604
596
  NOTE
605
597
    We need to have a lock on LOCK_open when calling this
606
598
*/
607
599
 
608
 
void free_cache_entry(void *entry)
 
600
static void free_cache_entry(Table *table)
609
601
{
610
 
  Table *table= static_cast<Table *>(entry);
611
602
  intern_close_table(table);
612
603
  if (!table->in_use)
613
604
  {
620
611
        unused_tables=0;
621
612
    }
622
613
  }
623
 
  free(table);
 
614
  free((unsigned char*) table);
624
615
  return;
625
616
}
626
617
 
631
622
  if (table->sort.io_cache)
632
623
  {
633
624
    close_cached_file(table->sort.io_cache);
634
 
    delete table->sort.io_cache;
635
 
    table->sort.io_cache= 0;
 
625
    free((unsigned char*) table->sort.io_cache);
 
626
    table->sort.io_cache=0;
636
627
  }
637
628
  return;
638
629
}
641
632
/*
642
633
  Close all tables which aren't in use by any thread
643
634
 
644
 
  @param session Thread context
 
635
  @param thd Thread context
645
636
  @param tables List of tables to remove from the cache
646
637
  @param have_lock If LOCK_open is locked
647
638
  @param wait_for_refresh Wait for a impending flush
649
640
         won't proceed while write-locked tables are being reopened by other
650
641
         threads.
651
642
 
652
 
  @remark Session can be NULL, but then wait_for_refresh must be false
 
643
  @remark THD can be NULL, but then wait_for_refresh must be false
653
644
          and tables must be NULL.
654
645
*/
655
646
 
656
 
bool close_cached_tables(Session *session, TableList *tables, bool have_lock,
 
647
bool close_cached_tables(THD *thd, TableList *tables, bool have_lock,
657
648
                         bool wait_for_refresh, bool wait_for_placeholders)
658
649
{
659
650
  bool result=0;
660
 
  assert(session || (!wait_for_refresh && !tables));
 
651
  assert(thd || (!wait_for_refresh && !tables));
661
652
 
662
653
  if (!have_lock)
663
654
    pthread_mutex_lock(&LOCK_open);
731
722
    bool found=0;
732
723
    for (TableList *table= tables; table; table= table->next_local)
733
724
    {
734
 
      if (remove_table_from_cache(session, table->db, table->table_name,
735
 
                                  RTFC_OWNED_BY_Session_FLAG))
 
725
      if (remove_table_from_cache(thd, table->db, table->table_name,
 
726
                                  RTFC_OWNED_BY_THD_FLAG))
736
727
        found=1;
737
728
    }
738
729
    if (!found)
745
736
      If there is any table that has a lower refresh_version, wait until
746
737
      this is closed (or this thread is killed) before returning
747
738
    */
748
 
    session->mysys_var->current_mutex= &LOCK_open;
749
 
    session->mysys_var->current_cond= &COND_refresh;
750
 
    session->set_proc_info("Flushing tables");
 
739
    thd->mysys_var->current_mutex= &LOCK_open;
 
740
    thd->mysys_var->current_cond= &COND_refresh;
 
741
    thd_proc_info(thd, "Flushing tables");
751
742
 
752
 
    close_old_data_files(session,session->open_tables,1,1);
 
743
    close_old_data_files(thd,thd->open_tables,1,1);
 
744
    mysql_ha_flush(thd);
753
745
 
754
746
    bool found=1;
755
747
    /* Wait until all threads has closed all the tables we had locked */
756
 
    while (found && ! session->killed)
 
748
    while (found && ! thd->killed)
757
749
    {
758
750
      found=0;
759
751
      for (uint32_t idx=0 ; idx < open_cache.records ; idx++)
760
752
      {
761
753
        Table *table=(Table*) hash_element(&open_cache,idx);
762
754
        /* Avoid a self-deadlock. */
763
 
        if (table->in_use == session)
 
755
        if (table->in_use == thd)
764
756
          continue;
765
757
        /*
766
758
          Note that we wait here only for tables which are actually open, and
790
782
      old locks. This should always succeed (unless some external process
791
783
      has removed the tables)
792
784
    */
793
 
    session->in_lock_tables=1;
794
 
    result=reopen_tables(session,1,1);
795
 
    session->in_lock_tables=0;
 
785
    thd->in_lock_tables=1;
 
786
    result=reopen_tables(thd,1,1);
 
787
    thd->in_lock_tables=0;
796
788
    /* Set version for table */
797
 
    for (Table *table=session->open_tables; table ; table= table->next)
 
789
    for (Table *table=thd->open_tables; table ; table= table->next)
798
790
    {
799
791
      /*
800
792
        Preserve the version (0) of write locked tables so that a impending
808
800
    pthread_mutex_unlock(&LOCK_open);
809
801
  if (wait_for_refresh)
810
802
  {
811
 
    pthread_mutex_lock(&session->mysys_var->mutex);
812
 
    session->mysys_var->current_mutex= 0;
813
 
    session->mysys_var->current_cond= 0;
814
 
    session->set_proc_info(0);
815
 
    pthread_mutex_unlock(&session->mysys_var->mutex);
 
803
    pthread_mutex_lock(&thd->mysys_var->mutex);
 
804
    thd->mysys_var->current_mutex= 0;
 
805
    thd->mysys_var->current_cond= 0;
 
806
    thd_proc_info(thd, 0);
 
807
    pthread_mutex_unlock(&thd->mysys_var->mutex);
816
808
  }
817
809
  return(result);
818
810
}
823
815
  if specified string is NULL, then any table with a connection string.
824
816
*/
825
817
 
826
 
bool close_cached_connection_tables(Session *session, bool if_wait_for_refresh,
 
818
bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
827
819
                                    LEX_STRING *connection, bool have_lock)
828
820
{
829
821
  uint32_t idx;
830
822
  TableList tmp, *tables= NULL;
831
823
  bool result= false;
832
 
  assert(session);
 
824
  assert(thd);
833
825
 
834
826
  memset(&tmp, 0, sizeof(TableList));
835
827
 
859
851
    tmp.table_name= share->table_name.str;
860
852
    tmp.next_local= tables;
861
853
 
862
 
    tables= (TableList *) memdup_root(session->mem_root, (char*)&tmp,
 
854
    tables= (TableList *) memdup_root(thd->mem_root, (char*)&tmp, 
863
855
                                       sizeof(TableList));
864
856
  }
865
857
 
866
858
  if (tables)
867
 
    result= close_cached_tables(session, tables, true, false, false);
 
859
    result= close_cached_tables(thd, tables, true, false, false);
868
860
 
869
861
  if (!have_lock)
870
862
    pthread_mutex_unlock(&LOCK_open);
871
863
 
872
864
  if (if_wait_for_refresh)
873
865
  {
874
 
    pthread_mutex_lock(&session->mysys_var->mutex);
875
 
    session->mysys_var->current_mutex= 0;
876
 
    session->mysys_var->current_cond= 0;
877
 
    session->set_proc_info(0);
878
 
    pthread_mutex_unlock(&session->mysys_var->mutex);
 
866
    pthread_mutex_lock(&thd->mysys_var->mutex);
 
867
    thd->mysys_var->current_mutex= 0;
 
868
    thd->mysys_var->current_cond= 0;
 
869
    thd->set_proc_info(0);
 
870
    pthread_mutex_unlock(&thd->mysys_var->mutex);
879
871
  }
880
872
 
881
873
  return(result);
886
878
  Mark all temporary tables which were used by the current statement or
887
879
  substatement as free for reuse, but only if the query_id can be cleared.
888
880
 
889
 
  @param session thread context
 
881
  @param thd thread context
890
882
 
891
883
  @remark For temp tables associated with a open SQL HANDLER the query_id
892
884
          is not reset until the HANDLER is closed.
893
885
*/
894
886
 
895
 
static void mark_temp_tables_as_free_for_reuse(Session *session)
 
887
static void mark_temp_tables_as_free_for_reuse(THD *thd)
896
888
{
897
 
  for (Table *table= session->temporary_tables ; table ; table= table->next)
 
889
  for (Table *table= thd->temporary_tables ; table ; table= table->next)
898
890
  {
899
 
    if ((table->query_id == session->query_id) && ! table->open_by_handler)
 
891
    if ((table->query_id == thd->query_id) && ! table->open_by_handler)
900
892
    {
901
893
      table->query_id= 0;
902
894
      table->file->ha_reset();
911
903
 
912
904
  SYNOPSIS
913
905
    mark_used_tables_as_free_for_reuse()
914
 
      session   - thread context
 
906
      thd   - thread context
915
907
      table - head of the list of tables
916
908
 
917
909
  DESCRIPTION
920
912
 
921
913
  NOTE
922
914
    The reason we reset query_id is that it's not enough to just test
923
 
    if table->query_id != session->query_id to know if a table is in use.
 
915
    if table->query_id != thd->query_id to know if a table is in use.
924
916
 
925
917
    For example
926
918
    SELECT f1_that_uses_t1() FROM t1;
928
920
    set to query_id of original query.
929
921
*/
930
922
 
931
 
static void mark_used_tables_as_free_for_reuse(Session *session, Table *table)
 
923
static void mark_used_tables_as_free_for_reuse(THD *thd, Table *table)
932
924
{
933
925
  for (; table ; table= table->next)
934
926
  {
935
 
    if (table->query_id == session->query_id)
 
927
    if (table->query_id == thd->query_id)
936
928
    {
937
929
      table->query_id= 0;
938
930
      table->file->ha_reset();
944
936
/**
945
937
  Auxiliary function to close all tables in the open_tables list.
946
938
 
947
 
  @param session Thread context.
 
939
  @param thd Thread context.
948
940
 
949
941
  @remark It should not ordinarily be called directly.
950
942
*/
951
943
 
952
 
static void close_open_tables(Session *session)
 
944
static void close_open_tables(THD *thd)
953
945
{
954
946
  bool found_old_table= 0;
955
947
 
957
949
 
958
950
  pthread_mutex_lock(&LOCK_open);
959
951
 
960
 
  while (session->open_tables)
961
 
    found_old_table|= close_thread_table(session, &session->open_tables);
962
 
  session->some_tables_deleted= 0;
 
952
  while (thd->open_tables)
 
953
    found_old_table|= close_thread_table(thd, &thd->open_tables);
 
954
  thd->some_tables_deleted= 0;
963
955
 
964
956
  /* Free tables to hold down open files */
965
957
  while (open_cache.records > table_cache_size && unused_tables)
980
972
 
981
973
  SYNOPSIS
982
974
    close_thread_tables()
983
 
    session                     Thread handler
 
975
    thd                 Thread handler
984
976
 
985
977
  IMPLEMENTATION
986
978
    Unlocks tables and frees derived tables.
992
984
    leave prelocked mode if needed.
993
985
*/
994
986
 
995
 
void close_thread_tables(Session *session)
 
987
void close_thread_tables(THD *thd)
996
988
{
997
989
  Table *table;
998
990
 
999
991
  /*
1000
 
    We are assuming here that session->derived_tables contains ONLY derived
 
992
    We are assuming here that thd->derived_tables contains ONLY derived
1001
993
    tables for this substatement. i.e. instead of approach which uses
1002
994
    query_id matching for determining which of the derived tables belong
1003
995
    to this substatement we rely on the ability of substatements to
1004
 
    save/restore session->derived_tables during their execution.
 
996
    save/restore thd->derived_tables during their execution.
1005
997
 
1006
998
    TODO: Probably even better approach is to simply associate list of
1007
999
          derived tables with (sub-)statement instead of thread and destroy
1008
1000
          them at the end of its execution.
1009
1001
  */
1010
 
  if (session->derived_tables)
 
1002
  if (thd->derived_tables)
1011
1003
  {
1012
1004
    Table *next;
1013
1005
    /*
1014
1006
      Close all derived tables generated in queries like
1015
1007
      SELECT * FROM (SELECT * FROM t1)
1016
1008
    */
1017
 
    for (table= session->derived_tables ; table ; table= next)
 
1009
    for (table= thd->derived_tables ; table ; table= next)
1018
1010
    {
1019
1011
      next= table->next;
1020
 
      table->free_tmp_table(session);
 
1012
      table->free_tmp_table(thd);
1021
1013
    }
1022
 
    session->derived_tables= 0;
 
1014
    thd->derived_tables= 0;
1023
1015
  }
1024
1016
 
1025
1017
  /*
1026
1018
    Mark all temporary tables used by this statement as free for reuse.
1027
1019
  */
1028
 
  mark_temp_tables_as_free_for_reuse(session);
 
1020
  mark_temp_tables_as_free_for_reuse(thd);
1029
1021
  /*
1030
1022
    Let us commit transaction for statement. Since in 5.0 we only have
1031
1023
    one statement transaction and don't allow several nested statement
1034
1026
    does not belong to statement for which we do close_thread_tables()).
1035
1027
    TODO: This should be fixed in later releases.
1036
1028
   */
1037
 
  if (!(session->state_flags & Open_tables_state::BACKUPS_AVAIL))
 
1029
  if (!(thd->state_flags & Open_tables_state::BACKUPS_AVAIL))
1038
1030
  {
1039
 
    session->main_da.can_overwrite_status= true;
1040
 
    ha_autocommit_or_rollback(session, session->is_error());
1041
 
    session->main_da.can_overwrite_status= false;
1042
 
    session->transaction.stmt.reset();
 
1031
    thd->main_da.can_overwrite_status= true;
 
1032
    ha_autocommit_or_rollback(thd, thd->is_error());
 
1033
    thd->main_da.can_overwrite_status= false;
 
1034
    thd->transaction.stmt.reset();
1043
1035
  }
1044
1036
 
1045
 
  if (session->locked_tables)
 
1037
  if (thd->locked_tables)
1046
1038
  {
1047
1039
 
1048
1040
    /* Ensure we are calling ha_reset() for all used tables */
1049
 
    mark_used_tables_as_free_for_reuse(session, session->open_tables);
 
1041
    mark_used_tables_as_free_for_reuse(thd, thd->open_tables);
1050
1042
 
1051
1043
    /*
1052
1044
      We are under simple LOCK TABLES so should not do anything else.
1054
1046
    return;
1055
1047
  }
1056
1048
 
1057
 
  if (session->lock)
 
1049
  if (thd->lock)
1058
1050
  {
1059
1051
    /*
1060
1052
      For RBR we flush the pending event just before we unlock all the
1065
1057
      handled either before writing a query log event (inside
1066
1058
      binlog_query()) or when preparing a pending event.
1067
1059
     */
1068
 
    mysql_unlock_tables(session, session->lock);
1069
 
    session->lock=0;
 
1060
    thd->binlog_flush_pending_rows_event(true);
 
1061
    mysql_unlock_tables(thd, thd->lock);
 
1062
    thd->lock=0;
1070
1063
  }
1071
1064
  /*
1072
1065
    Note that we need to hold LOCK_open while changing the
1075
1068
    Closing a MERGE child before the parent would be fatal if the
1076
1069
    other thread tries to abort the MERGE lock in between.
1077
1070
  */
1078
 
  if (session->open_tables)
1079
 
    close_open_tables(session);
 
1071
  if (thd->open_tables)
 
1072
    close_open_tables(thd);
1080
1073
 
1081
1074
  return;
1082
1075
}
1084
1077
 
1085
1078
/* move one table to free list */
1086
1079
 
1087
 
bool close_thread_table(Session *session, Table **table_ptr)
 
1080
bool close_thread_table(THD *thd, Table **table_ptr)
1088
1081
{
1089
1082
  bool found_old_table= 0;
1090
1083
  Table *table= *table_ptr;
1095
1088
  *table_ptr=table->next;
1096
1089
 
1097
1090
  if (table->needs_reopen_or_name_lock() ||
1098
 
      session->version != refresh_version || !table->db_stat)
 
1091
      thd->version != refresh_version || !table->db_stat)
1099
1092
  {
1100
1093
    hash_delete(&open_cache,(unsigned char*) table);
1101
1094
    found_old_table=1;
1124
1117
  return(found_old_table);
1125
1118
}
1126
1119
 
 
1120
 
 
1121
/* close_temporary_tables' internal, 4 is due to uint4korr definition */
 
1122
static inline uint32_t  tmpkeyval(THD *thd __attribute__((unused)),
 
1123
                              Table *table)
 
1124
{
 
1125
  return uint4korr(table->s->table_cache_key.str + table->s->table_cache_key.length - 4);
 
1126
}
 
1127
 
 
1128
 
 
1129
/*
 
1130
  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
 
1131
  creates one DROP TEMPORARY Table binlog event for each pseudo-thread 
 
1132
*/
 
1133
 
 
1134
void close_temporary_tables(THD *thd)
 
1135
{
 
1136
  Table *table;
 
1137
  Table *next= NULL;
 
1138
  Table *prev_table;
 
1139
  /* Assume thd->options has OPTION_QUOTE_SHOW_CREATE */
 
1140
  bool was_quote_show= true;
 
1141
 
 
1142
  if (!thd->temporary_tables)
 
1143
    return;
 
1144
 
 
1145
  if (!mysql_bin_log.is_open() || thd->current_stmt_binlog_row_based)
 
1146
  {
 
1147
    Table *tmp_next;
 
1148
    for (table= thd->temporary_tables; table; table= tmp_next)
 
1149
    {
 
1150
      tmp_next= table->next;
 
1151
      close_temporary(table, 1, 1);
 
1152
    }
 
1153
    thd->temporary_tables= 0;
 
1154
    return;
 
1155
  }
 
1156
 
 
1157
  /* Better add "if exists", in case a RESET MASTER has been done */
 
1158
  const char stub[]= "DROP /*!40005 TEMPORARY */ Table IF EXISTS ";
 
1159
  uint32_t stub_len= sizeof(stub) - 1;
 
1160
  char buf[256];
 
1161
  String s_query= String(buf, sizeof(buf), system_charset_info);
 
1162
  bool found_user_tables= false;
 
1163
 
 
1164
  memcpy(buf, stub, stub_len);
 
1165
 
 
1166
  /*
 
1167
    Insertion sort of temp tables by pseudo_thread_id to build ordered list
 
1168
    of sublists of equal pseudo_thread_id
 
1169
  */
 
1170
 
 
1171
  for (prev_table= thd->temporary_tables, table= prev_table->next;
 
1172
       table;
 
1173
       prev_table= table, table= table->next)
 
1174
  {
 
1175
    Table *prev_sorted /* same as for prev_table */, *sorted;
 
1176
    if (is_user_table(table))
 
1177
    {
 
1178
      if (!found_user_tables)
 
1179
        found_user_tables= true;
 
1180
      for (prev_sorted= NULL, sorted= thd->temporary_tables; sorted != table;
 
1181
           prev_sorted= sorted, sorted= sorted->next)
 
1182
      {
 
1183
        if (!is_user_table(sorted) ||
 
1184
            tmpkeyval(thd, sorted) > tmpkeyval(thd, table))
 
1185
        {
 
1186
          /* move into the sorted part of the list from the unsorted */
 
1187
          prev_table->next= table->next;
 
1188
          table->next= sorted;
 
1189
          if (prev_sorted)
 
1190
          {
 
1191
            prev_sorted->next= table;
 
1192
          }
 
1193
          else
 
1194
          {
 
1195
            thd->temporary_tables= table;
 
1196
          }
 
1197
          table= prev_table;
 
1198
          break;
 
1199
        }
 
1200
      }
 
1201
    }
 
1202
  }
 
1203
 
 
1204
  /* We always quote db,table names though it is slight overkill */
 
1205
  if (found_user_tables &&
 
1206
      !(was_quote_show= test(thd->options & OPTION_QUOTE_SHOW_CREATE)))
 
1207
  {
 
1208
    thd->options |= OPTION_QUOTE_SHOW_CREATE;
 
1209
  }
 
1210
 
 
1211
  /* scan sorted tmps to generate sequence of DROP */
 
1212
  for (table= thd->temporary_tables; table; table= next)
 
1213
  {
 
1214
    if (is_user_table(table))
 
1215
    {
 
1216
      my_thread_id save_pseudo_thread_id= thd->variables.pseudo_thread_id;
 
1217
      /* Set pseudo_thread_id to be that of the processed table */
 
1218
      thd->variables.pseudo_thread_id= tmpkeyval(thd, table);
 
1219
      /*
 
1220
        Loop forward through all tables within the sublist of
 
1221
        common pseudo_thread_id to create single DROP query.
 
1222
      */
 
1223
      for (s_query.length(stub_len);
 
1224
           table && is_user_table(table) &&
 
1225
             tmpkeyval(thd, table) == thd->variables.pseudo_thread_id;
 
1226
           table= next)
 
1227
      {
 
1228
        /*
 
1229
          We are going to add 4 ` around the db/table names and possible more
 
1230
          due to special characters in the names
 
1231
        */
 
1232
        append_identifier(thd, &s_query, table->s->db.str, strlen(table->s->db.str));
 
1233
        s_query.append('.');
 
1234
        append_identifier(thd, &s_query, table->s->table_name.str,
 
1235
                          strlen(table->s->table_name.str));
 
1236
        s_query.append(',');
 
1237
        next= table->next;
 
1238
        close_temporary(table, 1, 1);
 
1239
      }
 
1240
      thd->clear_error();
 
1241
      const CHARSET_INFO * const cs_save= thd->variables.character_set_client;
 
1242
      thd->variables.character_set_client= system_charset_info;
 
1243
      Query_log_event qinfo(thd, s_query.ptr(),
 
1244
                            s_query.length() - 1 /* to remove trailing ',' */,
 
1245
                            0, false);
 
1246
      thd->variables.character_set_client= cs_save;
 
1247
      /*
 
1248
        Imagine the thread had created a temp table, then was doing a
 
1249
        SELECT, and the SELECT was killed. Then it's not clever to
 
1250
        mark the statement above as "killed", because it's not really
 
1251
        a statement updating data, and there are 99.99% chances it
 
1252
        will succeed on slave.  If a real update (one updating a
 
1253
        persistent table) was killed on the master, then this real
 
1254
        update will be logged with error_code=killed, rightfully
 
1255
        causing the slave to stop.
 
1256
      */
 
1257
      qinfo.error_code= 0;
 
1258
      mysql_bin_log.write(&qinfo);
 
1259
      thd->variables.pseudo_thread_id= save_pseudo_thread_id;
 
1260
    }
 
1261
    else
 
1262
    {
 
1263
      next= table->next;
 
1264
      close_temporary(table, 1, 1);
 
1265
    }
 
1266
  }
 
1267
  if (!was_quote_show)
 
1268
    thd->options&= ~OPTION_QUOTE_SHOW_CREATE; /* restore option */
 
1269
  thd->temporary_tables=0;
 
1270
}
 
1271
 
1127
1272
/*
1128
1273
  Find table in list.
1129
1274
 
1164
1309
 
1165
1310
  SYNOPSIS
1166
1311
    unique_table()
1167
 
    session                   thread handle
 
1312
    thd                   thread handle
1168
1313
    table                 table which should be checked
1169
1314
    table_list            list of tables
1170
1315
    check_alias           whether to check tables' aliases
1171
1316
 
1172
1317
  NOTE: to exclude derived tables from check we use following mechanism:
1173
 
    a) during derived table processing set Session::derived_tables_processing
 
1318
    a) during derived table processing set THD::derived_tables_processing
1174
1319
    b) JOIN::prepare set SELECT::exclude_from_table_unique_test if
1175
 
       Session::derived_tables_processing set. (we can't use JOIN::execute
 
1320
       THD::derived_tables_processing set. (we can't use JOIN::execute
1176
1321
       because for PS we perform only JOIN::prepare, but we can't set this
1177
1322
       flag in JOIN::prepare if we are not sure that we are in derived table
1178
1323
       processing loop, because multi-update call fix_fields() for some its
1195
1340
    0 if table is unique
1196
1341
*/
1197
1342
 
1198
 
TableList* unique_table(Session *session, TableList *table, TableList *table_list,
 
1343
TableList* unique_table(THD *thd, TableList *table, TableList *table_list,
1199
1344
                         bool check_alias)
1200
1345
{
1201
1346
  TableList *res;
1230
1375
  for (;;)
1231
1376
  {
1232
1377
    if (((! (res= find_table_in_global_list(table_list, d_name, t_name))) &&
1233
 
         (! (res= mysql_lock_have_duplicate(session, table, table_list)))) ||
 
1378
         (! (res= mysql_lock_have_duplicate(thd, table, table_list)))) ||
1234
1379
        ((!res->table || res->table != table->table) &&
1235
1380
         (!check_alias || !(lower_case_table_names ?
1236
1381
          my_strcasecmp(files_charset_info, t_alias, res->alias) :
1263
1408
*/
1264
1409
 
1265
1410
void update_non_unique_table_error(TableList *update,
1266
 
                                   const char *,
1267
 
                                   TableList *)
 
1411
                                   const char *operation __attribute__((unused)),
 
1412
                                   TableList *duplicate __attribute__((unused)))
1268
1413
{
1269
1414
  my_error(ER_UPDATE_TABLE_USED, MYF(0), update->alias);
1270
1415
}
1271
1416
 
1272
1417
 
1273
 
Table *find_temporary_table(Session *session, const char *db, const char *table_name)
 
1418
Table *find_temporary_table(THD *thd, const char *db, const char *table_name)
1274
1419
{
1275
1420
  TableList table_list;
1276
1421
 
1277
1422
  table_list.db= (char*) db;
1278
1423
  table_list.table_name= (char*) table_name;
1279
 
  return find_temporary_table(session, &table_list);
 
1424
  return find_temporary_table(thd, &table_list);
1280
1425
}
1281
1426
 
1282
1427
 
1283
 
Table *find_temporary_table(Session *session, TableList *table_list)
 
1428
Table *find_temporary_table(THD *thd, TableList *table_list)
1284
1429
{
1285
1430
  char  key[MAX_DBKEY_LENGTH];
1286
1431
  uint  key_length;
1287
1432
  Table *table;
1288
1433
 
1289
 
  key_length= create_table_def_key(session, key, table_list, 1);
1290
 
  for (table=session->temporary_tables ; table ; table= table->next)
 
1434
  key_length= create_table_def_key(thd, key, table_list, 1);
 
1435
  for (table=thd->temporary_tables ; table ; table= table->next)
1291
1436
  {
1292
1437
    if (table->s->table_cache_key.length == key_length &&
1293
1438
        !memcmp(table->s->table_cache_key.str, key, key_length))
1300
1445
/**
1301
1446
  Drop a temporary table.
1302
1447
 
1303
 
  Try to locate the table in the list of session->temporary_tables.
 
1448
  Try to locate the table in the list of thd->temporary_tables.
1304
1449
  If the table is found:
1305
1450
   - if the table is being used by some outer statement, fail.
1306
 
   - if the table is in session->locked_tables, unlock it and
 
1451
   - if the table is in thd->locked_tables, unlock it and
1307
1452
     remove it from the list of locked tables. Currently only transactional
1308
1453
     temporary tables are present in the locked_tables list.
1309
1454
   - Close the temporary table, remove its .FRM
1314
1459
  or ALTER Table. Even though part of the work done by this function
1315
1460
  is redundant when the table is internal, as long as we
1316
1461
  link both internal and user temporary tables into the same
1317
 
  session->temporary_tables list, it's impossible to tell here whether
 
1462
  thd->temporary_tables list, it's impossible to tell here whether
1318
1463
  we're dealing with an internal or a user temporary table.
1319
1464
 
1320
1465
  @retval  0  the table was found and dropped successfully.
1323
1468
  @retval -1  the table is in use by a outer query
1324
1469
*/
1325
1470
 
1326
 
int drop_temporary_table(Session *session, TableList *table_list)
 
1471
int drop_temporary_table(THD *thd, TableList *table_list)
1327
1472
{
1328
1473
  Table *table;
1329
1474
 
1330
 
  if (!(table= find_temporary_table(session, table_list)))
 
1475
  if (!(table= find_temporary_table(thd, table_list)))
1331
1476
    return(1);
1332
1477
 
1333
1478
  /* Table might be in use by some outer statement. */
1334
 
  if (table->query_id && table->query_id != session->query_id)
 
1479
  if (table->query_id && table->query_id != thd->query_id)
1335
1480
  {
1336
1481
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1337
1482
    return(-1);
1341
1486
    If LOCK TABLES list is not empty and contains this table,
1342
1487
    unlock the table and remove the table from this list.
1343
1488
  */
1344
 
  mysql_lock_remove(session, session->locked_tables, table, false);
1345
 
  close_temporary_table(session, table, 1, 1);
 
1489
  mysql_lock_remove(thd, thd->locked_tables, table, false);
 
1490
  close_temporary_table(thd, table, 1, 1);
1346
1491
  return(0);
1347
1492
}
1348
1493
 
1349
1494
/*
1350
 
  unlink from session->temporary tables and close temporary table
 
1495
  unlink from thd->temporary tables and close temporary table
1351
1496
*/
1352
1497
 
1353
 
void close_temporary_table(Session *session, Table *table,
 
1498
void close_temporary_table(THD *thd, Table *table,
1354
1499
                           bool free_share, bool delete_table)
1355
1500
{
1356
1501
  if (table->prev)
1362
1507
  else
1363
1508
  {
1364
1509
    /* removing the item from the list */
1365
 
    assert(table == session->temporary_tables);
 
1510
    assert(table == thd->temporary_tables);
1366
1511
    /*
1367
1512
      slave must reset its temporary list pointer to zero to exclude
1368
1513
      passing non-zero value to end_slave via rli->save_temporary_tables
1369
1514
      when no temp tables opened, see an invariant below.
1370
1515
    */
1371
 
    session->temporary_tables= table->next;
1372
 
    if (session->temporary_tables)
 
1516
    thd->temporary_tables= table->next;
 
1517
    if (thd->temporary_tables)
1373
1518
      table->next->prev= 0;
1374
1519
  }
 
1520
  if (thd->slave_thread)
 
1521
  {
 
1522
    /* natural invariant of temporary_tables */
 
1523
    assert(slave_open_temp_tables || !thd->temporary_tables);
 
1524
    slave_open_temp_tables--;
 
1525
  }
1375
1526
  close_temporary(table, free_share, delete_table);
1376
1527
  return;
1377
1528
}
1381
1532
  Close and delete a temporary table
1382
1533
 
1383
1534
  NOTE
1384
 
    This dosn't unlink table from session->temporary
 
1535
    This dosn't unlink table from thd->temporary
1385
1536
    If this is needed, use close_temporary_table()
1386
1537
*/
1387
1538
 
1390
1541
  handlerton *table_type= table->s->db_type();
1391
1542
 
1392
1543
  free_io_cache(table);
1393
 
  table->closefrm(false);
1394
 
 
 
1544
  closefrm(table, 0);
 
1545
  /*
 
1546
     Check that temporary table has not been created with
 
1547
     frm_only because it has then not been created in any storage engine
 
1548
   */
1395
1549
  if (delete_table)
1396
 
    rm_temporary_table(table_type, table->s->path.str);
1397
 
 
 
1550
    rm_temporary_table(table_type, table->s->path.str, 
 
1551
                       table->s->tmp_table == TMP_TABLE_FRM_FILE_ONLY);
1398
1552
  if (free_share)
1399
1553
  {
1400
1554
    free_table_share(table->s);
1409
1563
  only if the ALTER contained a RENAME clause (otherwise, table_name is the old
1410
1564
  name).
1411
1565
  Prepares a table cache key, which is the concatenation of db, table_name and
1412
 
  session->slave_proxy_id, separated by '\0'.
 
1566
  thd->slave_proxy_id, separated by '\0'.
1413
1567
*/
1414
1568
 
1415
 
bool rename_temporary_table(Session* session, Table *table, const char *db,
 
1569
bool rename_temporary_table(THD* thd, Table *table, const char *db,
1416
1570
                            const char *table_name)
1417
1571
{
1418
1572
  char *key;
1421
1575
  TableList table_list;
1422
1576
 
1423
1577
  if (!(key=(char*) alloc_root(&share->mem_root, MAX_DBKEY_LENGTH)))
1424
 
    return true;                                /* purecov: inspected */
 
1578
    return(1);                          /* purecov: inspected */
1425
1579
 
1426
1580
  table_list.db= (char*) db;
1427
1581
  table_list.table_name= (char*) table_name;
1428
 
  key_length= create_table_def_key(session, key, &table_list, 1);
 
1582
  key_length= create_table_def_key(thd, key, &table_list, 1);
1429
1583
  share->set_table_cache_key(key, key_length);
1430
 
 
1431
 
  return false;
 
1584
  return(0);
1432
1585
}
1433
1586
 
1434
1587
 
1453
1606
    Remove all instances of table from thread's open list and
1454
1607
    table cache.
1455
1608
 
1456
 
    @param  session     Thread context
 
1609
    @param  thd     Thread context
1457
1610
    @param  find    Table to remove
1458
1611
    @param  unlock  true  - free all locks on tables removed that are
1459
1612
                            done with LOCK TABLES
1464
1617
          not locked (for example already unlocked).
1465
1618
*/
1466
1619
 
1467
 
void unlink_open_table(Session *session, Table *find, bool unlock)
 
1620
void unlink_open_table(THD *thd, Table *find, bool unlock)
1468
1621
{
1469
1622
  char key[MAX_DBKEY_LENGTH];
1470
1623
  uint32_t key_length= find->s->table_cache_key.length;
1480
1633
    Closing a MERGE child before the parent would be fatal if the
1481
1634
    other thread tries to abort the MERGE lock in between.
1482
1635
  */
1483
 
  for (prev= &session->open_tables; *prev; )
 
1636
  for (prev= &thd->open_tables; *prev; )
1484
1637
  {
1485
1638
    list= *prev;
1486
1639
 
1487
1640
    if (list->s->table_cache_key.length == key_length &&
1488
1641
        !memcmp(list->s->table_cache_key.str, key, key_length))
1489
1642
    {
1490
 
      if (unlock && session->locked_tables)
1491
 
        mysql_lock_remove(session, session->locked_tables, list, true);
 
1643
      if (unlock && thd->locked_tables)
 
1644
        mysql_lock_remove(thd, thd->locked_tables, list, true);
1492
1645
 
1493
1646
      /* Remove table from open_tables list. */
1494
1647
      *prev= list->next;
1511
1664
/**
1512
1665
    Auxiliary routine which closes and drops open table.
1513
1666
 
1514
 
    @param  session         Thread handle
 
1667
    @param  thd         Thread handle
1515
1668
    @param  table       Table object for table to be dropped
1516
1669
    @param  db_name     Name of database for this table
1517
1670
    @param  table_name  Name of this table
1527
1680
          table that was locked with LOCK TABLES.
1528
1681
*/
1529
1682
 
1530
 
void drop_open_table(Session *session, Table *table, const char *db_name,
 
1683
void drop_open_table(THD *thd, Table *table, const char *db_name,
1531
1684
                     const char *table_name)
1532
1685
{
1533
1686
  if (table->s->tmp_table)
1534
 
    close_temporary_table(session, table, 1, 1);
 
1687
    close_temporary_table(thd, table, 1, 1);
1535
1688
  else
1536
1689
  {
1537
1690
    handlerton *table_type= table->s->db_type();
1540
1693
      unlink_open_table() also tells threads waiting for refresh or close
1541
1694
      that something has happened.
1542
1695
    */
1543
 
    unlink_open_table(session, table, false);
 
1696
    unlink_open_table(thd, table, false);
1544
1697
    quick_rm_table(table_type, db_name, table_name, 0);
1545
1698
    pthread_mutex_unlock(&LOCK_open);
1546
1699
  }
1552
1705
 
1553
1706
   SYNOPSIS
1554
1707
     wait_for_condition()
1555
 
     session    Thread handler
 
1708
     thd        Thread handler
1556
1709
     mutex      mutex that is currently hold that is associated with condition
1557
 
                Will be unlocked on return
 
1710
                Will be unlocked on return     
1558
1711
     cond       Condition to wait for
1559
1712
*/
1560
1713
 
1561
 
void wait_for_condition(Session *session, pthread_mutex_t *mutex, pthread_cond_t *cond)
 
1714
void wait_for_condition(THD *thd, pthread_mutex_t *mutex, pthread_cond_t *cond)
1562
1715
{
1563
1716
  /* Wait until the current table is up to date */
1564
1717
  const char *proc_info;
1565
 
  session->mysys_var->current_mutex= mutex;
1566
 
  session->mysys_var->current_cond= cond;
1567
 
  proc_info=session->get_proc_info();
1568
 
  session->set_proc_info("Waiting for table");
1569
 
  if (!session->killed)
 
1718
  thd->mysys_var->current_mutex= mutex;
 
1719
  thd->mysys_var->current_cond= cond;
 
1720
  proc_info=thd->get_proc_info();
 
1721
  thd_proc_info(thd, "Waiting for table");
 
1722
  if (!thd->killed)
1570
1723
    (void) pthread_cond_wait(cond, mutex);
1571
1724
 
1572
1725
  /*
1579
1732
    condition variables that are guranteed to not disapper (freed) even if this
1580
1733
    mutex is unlocked
1581
1734
  */
1582
 
 
 
1735
    
1583
1736
  pthread_mutex_unlock(mutex);
1584
 
  pthread_mutex_lock(&session->mysys_var->mutex);
1585
 
  session->mysys_var->current_mutex= 0;
1586
 
  session->mysys_var->current_cond= 0;
1587
 
  session->set_proc_info(proc_info);
1588
 
  pthread_mutex_unlock(&session->mysys_var->mutex);
 
1737
  pthread_mutex_lock(&thd->mysys_var->mutex);
 
1738
  thd->mysys_var->current_mutex= 0;
 
1739
  thd->mysys_var->current_cond= 0;
 
1740
  thd_proc_info(thd, proc_info);
 
1741
  pthread_mutex_unlock(&thd->mysys_var->mutex);
1589
1742
  return;
1590
1743
}
1591
1744
 
1594
1747
  Exclusively name-lock a table that is already write-locked by the
1595
1748
  current thread.
1596
1749
 
1597
 
  @param session current thread context
 
1750
  @param thd current thread context
1598
1751
  @param tables table list containing one table to open.
1599
1752
 
1600
1753
  @return false on success, true otherwise.
1601
1754
*/
1602
1755
 
1603
 
bool name_lock_locked_table(Session *session, TableList *tables)
 
1756
bool name_lock_locked_table(THD *thd, TableList *tables)
1604
1757
{
1605
1758
  /* Under LOCK TABLES we must only accept write locked tables. */
1606
 
  tables->table= find_locked_table(session, tables->db, tables->table_name);
 
1759
  tables->table= find_locked_table(thd, tables->db, tables->table_name);
1607
1760
 
1608
1761
  if (!tables->table)
1609
1762
    my_error(ER_TABLE_NOT_LOCKED, MYF(0), tables->alias);
1615
1768
      Ensures that table is opened only by this thread and that no
1616
1769
      other statement will open this table.
1617
1770
    */
1618
 
    wait_while_table_is_used(session, tables->table, HA_EXTRA_FORCE_REOPEN);
 
1771
    wait_while_table_is_used(thd, tables->table, HA_EXTRA_FORCE_REOPEN);
1619
1772
    return(false);
1620
1773
  }
1621
1774
 
1628
1781
 
1629
1782
  SYNOPSIS
1630
1783
    reopen_name_locked_table()
1631
 
      session         Thread handle
 
1784
      thd         Thread handle
1632
1785
      table_list  TableList object for table to be open, TableList::table
1633
1786
                  member should point to Table object which was used for
1634
1787
                  name-locking.
1635
1788
      link_in     true  - if Table object for table to be opened should be
1636
 
                          linked into Session::open_tables list.
 
1789
                          linked into THD::open_tables list.
1637
1790
                  false - placeholder used for name-locking is already in
1638
1791
                          this list so we only need to preserve Table::next
1639
1792
                          pointer.
1646
1799
    true  - Error
1647
1800
*/
1648
1801
 
1649
 
bool reopen_name_locked_table(Session* session, TableList* table_list, bool link_in)
 
1802
bool reopen_name_locked_table(THD* thd, TableList* table_list, bool link_in)
1650
1803
{
1651
1804
  Table *table= table_list->table;
1652
1805
  TABLE_SHARE *share;
1655
1808
 
1656
1809
  safe_mutex_assert_owner(&LOCK_open);
1657
1810
 
1658
 
  if (session->killed || !table)
 
1811
  if (thd->killed || !table)
1659
1812
    return(true);
1660
1813
 
1661
1814
  orig_table= *table;
1662
1815
 
1663
 
  if (open_unireg_entry(session, table, table_list, table_name,
 
1816
  if (open_unireg_entry(thd, table, table_list, table_name,
1664
1817
                        table->s->table_cache_key.str,
1665
1818
                        table->s->table_cache_key.length))
1666
1819
  {
1685
1838
    before we will get table-level lock on this table.
1686
1839
  */
1687
1840
  share->version=0;
1688
 
  table->in_use = session;
 
1841
  table->in_use = thd;
1689
1842
 
1690
1843
  if (link_in)
1691
1844
  {
1692
 
    table->next= session->open_tables;
1693
 
    session->open_tables= table;
 
1845
    table->next= thd->open_tables;
 
1846
    thd->open_tables= table;
1694
1847
  }
1695
1848
  else
1696
1849
  {
1697
1850
    /*
1698
 
      Table object should be already in Session::open_tables list so we just
 
1851
      Table object should be already in THD::open_tables list so we just
1699
1852
      need to set Table::next correctly.
1700
1853
    */
1701
1854
    table->next= orig_table.next;
1702
1855
  }
1703
1856
 
1704
 
  table->tablenr=session->current_tablenr++;
 
1857
  table->tablenr=thd->current_tablenr++;
1705
1858
  table->used_fields=0;
1706
1859
  table->const_table=0;
1707
1860
  table->null_row= false;
1717
1870
    which will prevent its opening (or creation) (a.k.a lock
1718
1871
    table name).
1719
1872
 
1720
 
    @param session         Thread context
 
1873
    @param thd         Thread context
1721
1874
    @param key         Table cache key for name to be locked
1722
1875
    @param key_length  Table cache key length
1723
1876
 
1725
1878
            case of failure.
1726
1879
*/
1727
1880
 
1728
 
Table *table_cache_insert_placeholder(Session *session, const char *key,
 
1881
Table *table_cache_insert_placeholder(THD *thd, const char *key,
1729
1882
                                      uint32_t key_length)
1730
1883
{
1731
1884
  Table *table;
1749
1902
  table->s= share;
1750
1903
  share->set_table_cache_key(key_buff, key, key_length);
1751
1904
  share->tmp_table= INTERNAL_TMP_TABLE;  // for intern_close_table
1752
 
  table->in_use= session;
 
1905
  table->in_use= thd;
1753
1906
  table->locked_by_name=1;
1754
1907
 
1755
1908
  if (my_hash_insert(&open_cache, (unsigned char*)table))
1766
1919
    Obtain an exclusive name lock on the table if it is not cached
1767
1920
    in the table cache.
1768
1921
 
1769
 
    @param      session         Thread context
 
1922
    @param      thd         Thread context
1770
1923
    @param      db          Name of database
1771
1924
    @param      table_name  Name of table
1772
1925
    @param[out] table       Out parameter which is either:
1784
1937
    @retval  false  Success. 'table' parameter set according to above rules.
1785
1938
*/
1786
1939
 
1787
 
bool lock_table_name_if_not_cached(Session *session, const char *db,
 
1940
bool lock_table_name_if_not_cached(THD *thd, const char *db,
1788
1941
                                   const char *table_name, Table **table)
1789
1942
{
1790
1943
  char key[MAX_DBKEY_LENGTH];
1791
 
  char *key_pos= key;
1792
1944
  uint32_t key_length;
1793
1945
 
1794
 
  key_pos= strcpy(key_pos, db) + strlen(db);
1795
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
1796
 
  key_length= (uint32_t) (key_pos-key)+1;
1797
 
 
 
1946
  key_length= (uint)(my_stpcpy(my_stpcpy(key, db) + 1, table_name) - key) + 1;
1798
1947
  pthread_mutex_lock(&LOCK_open);
1799
1948
 
1800
1949
  if (hash_search(&open_cache, (unsigned char *)key, key_length))
1803
1952
    *table= 0;
1804
1953
    return(false);
1805
1954
  }
1806
 
  if (!(*table= table_cache_insert_placeholder(session, key, key_length)))
 
1955
  if (!(*table= table_cache_insert_placeholder(thd, key, key_length)))
1807
1956
  {
1808
1957
    pthread_mutex_unlock(&LOCK_open);
1809
1958
    return(true);
1810
1959
  }
1811
1960
  (*table)->open_placeholder= 1;
1812
 
  (*table)->next= session->open_tables;
1813
 
  session->open_tables= *table;
 
1961
  (*table)->next= thd->open_tables;
 
1962
  thd->open_tables= *table;
1814
1963
  pthread_mutex_unlock(&LOCK_open);
1815
1964
  return(false);
1816
1965
}
1817
1966
 
 
1967
 
 
1968
/**
 
1969
    Check that table exists in table definition cache, on disk
 
1970
    or in some storage engine.
 
1971
 
 
1972
    @param       thd     Thread context
 
1973
    @param       table   Table list element
 
1974
    @param[out]  exists  Out parameter which is set to true if table
 
1975
                         exists and to false otherwise.
 
1976
 
 
1977
    @note This function assumes that caller owns LOCK_open mutex.
 
1978
          It also assumes that the fact that there are no name-locks
 
1979
          on the table was checked beforehand.
 
1980
 
 
1981
    @note If there is no .FRM file for the table but it exists in one
 
1982
          of engines (e.g. it was created on another node of NDB cluster)
 
1983
          this function will fetch and create proper .FRM file for it.
 
1984
 
 
1985
    @retval  true   Some error occured
 
1986
    @retval  false  No error. 'exists' out parameter set accordingly.
 
1987
*/
 
1988
 
 
1989
bool check_if_table_exists(THD *thd, TableList *table, bool *exists)
 
1990
{
 
1991
  char path[FN_REFLEN];
 
1992
  int rc;
 
1993
 
 
1994
  safe_mutex_assert_owner(&LOCK_open);
 
1995
 
 
1996
  *exists= true;
 
1997
 
 
1998
  if (get_cached_table_share(table->db, table->table_name))
 
1999
    return(false);
 
2000
 
 
2001
  build_table_filename(path, sizeof(path) - 1, table->db, table->table_name,
 
2002
                       reg_ext, 0);
 
2003
 
 
2004
  if (!access(path, F_OK))
 
2005
    return(false);
 
2006
 
 
2007
  /* .FRM file doesn't exist. Check if some engine can provide it. */
 
2008
 
 
2009
  rc= ha_create_table_from_engine(thd, table->db, table->table_name);
 
2010
 
 
2011
  if (rc < 0)
 
2012
  {
 
2013
    /* Table does not exists in engines as well. */
 
2014
    *exists= false;
 
2015
    return(false);
 
2016
  }
 
2017
  else if (!rc)
 
2018
  {
 
2019
    /* Table exists in some engine and .FRM for it was created. */
 
2020
    return(false);
 
2021
  }
 
2022
  else /* (rc > 0) */
 
2023
  {
 
2024
    my_printf_error(ER_UNKNOWN_ERROR, "Failed to open '%-.64s', error while "
 
2025
                    "unpacking from engine", MYF(0), table->table_name);
 
2026
    return(true);
 
2027
  }
 
2028
}
 
2029
 
 
2030
 
1818
2031
/*
1819
2032
  Open a table.
1820
2033
 
1821
2034
  SYNOPSIS
1822
2035
    open_table()
1823
 
    session                 Thread context.
 
2036
    thd                 Thread context.
1824
2037
    table_list          Open first table in list.
1825
2038
    refresh      INOUT  Pointer to memory that will be set to 1 if
1826
2039
                        we need to close all tables and reopen them.
1848
2061
*/
1849
2062
 
1850
2063
 
1851
 
Table *open_table(Session *session, TableList *table_list, bool *refresh, uint32_t flags)
 
2064
Table *open_table(THD *thd, TableList *table_list, bool *refresh, uint32_t flags)
1852
2065
{
1853
2066
  register Table *table;
1854
2067
  char key[MAX_DBKEY_LENGTH];
1856
2069
  char *alias= table_list->alias;
1857
2070
  HASH_SEARCH_STATE state;
1858
2071
 
1859
 
  /* Parsing of partitioning information from .frm needs session->lex set up. */
1860
 
  assert(session->lex->is_lex_started);
 
2072
  /* Parsing of partitioning information from .frm needs thd->lex set up. */
 
2073
  assert(thd->lex->is_lex_started);
1861
2074
 
1862
2075
  /* find a unused table in the open table cache */
1863
2076
  if (refresh)
1864
2077
    *refresh=0;
1865
2078
 
1866
2079
  /* an open table operation needs a lot of the stack space */
1867
 
  if (check_stack_overrun(session, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
1868
 
    return(0);
1869
 
 
1870
 
  if (session->killed)
1871
 
    return(0);
1872
 
 
1873
 
  key_length= (create_table_def_key(session, key, table_list, 1) -
 
2080
  if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
 
2081
    return(0);
 
2082
 
 
2083
  if (thd->killed)
 
2084
    return(0);
 
2085
 
 
2086
  key_length= (create_table_def_key(thd, key, table_list, 1) -
1874
2087
               TMP_TABLE_KEY_EXTRA);
1875
2088
 
1876
2089
  /*
1881
2094
    TODO: move this block into a separate function.
1882
2095
  */
1883
2096
  {
1884
 
    for (table= session->temporary_tables; table ; table=table->next)
 
2097
    for (table= thd->temporary_tables; table ; table=table->next)
1885
2098
    {
1886
2099
      if (table->s->table_cache_key.length == key_length +
1887
 
          TMP_TABLE_KEY_EXTRA && !memcmp(table->s->table_cache_key.str, key,
1888
 
          key_length + TMP_TABLE_KEY_EXTRA))
 
2100
          TMP_TABLE_KEY_EXTRA &&
 
2101
          !memcmp(table->s->table_cache_key.str, key,
 
2102
                  key_length + TMP_TABLE_KEY_EXTRA))
1889
2103
      {
1890
2104
        /*
1891
2105
          We're trying to use the same temporary table twice in a query.
1892
2106
          Right now we don't support this because a temporary table
1893
 
          is always represented by only one Table object in Session, and
 
2107
          is always represented by only one Table object in THD, and
1894
2108
          it can not be cloned. Emit an error for an unsupported behaviour.
1895
2109
        */
1896
 
        if (table->query_id)
1897
 
        {
1898
 
          my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
1899
 
          return(0);
1900
 
        }
1901
 
        table->query_id= session->query_id;
1902
 
        session->thread_specific_used= true;
 
2110
        if (table->query_id)
 
2111
        {
 
2112
          my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->alias);
 
2113
          return(0);
 
2114
        }
 
2115
        table->query_id= thd->query_id;
 
2116
        thd->thread_specific_used= true;
1903
2117
        goto reset;
1904
2118
      }
1905
2119
    }
1918
2132
    open not pre-opened tables in pre-locked/LOCK TABLES mode.
1919
2133
    TODO: move this block into a separate function.
1920
2134
  */
1921
 
  if (session->locked_tables)
1922
 
  { // Using table locks
 
2135
  if (thd->locked_tables)
 
2136
  {                                             // Using table locks
1923
2137
    Table *best_table= 0;
1924
2138
    int best_distance= INT_MIN;
1925
2139
    bool check_if_used= false;
1926
 
    for (table=session->open_tables; table ; table=table->next)
 
2140
    for (table=thd->open_tables; table ; table=table->next)
1927
2141
    {
1928
2142
      if (table->s->table_cache_key.length == key_length &&
1929
 
          !memcmp(table->s->table_cache_key.str, key, key_length))
 
2143
          !memcmp(table->s->table_cache_key.str, key, key_length))
1930
2144
      {
1931
2145
        if (check_if_used && table->query_id &&
1932
 
            table->query_id != session->query_id)
 
2146
            table->query_id != thd->query_id)
1933
2147
        {
1934
2148
          /*
1935
2149
            If we are in stored function or trigger we should ensure that
1946
2160
          belong to their parent and cannot be used explicitly.
1947
2161
        */
1948
2162
        if (!my_strcasecmp(system_charset_info, table->alias, alias) &&
1949
 
            table->query_id != session->query_id)  /* skip tables already used */
 
2163
            table->query_id != thd->query_id)  /* skip tables already used */
1950
2164
        {
1951
2165
          int distance= ((int) table->reginfo.lock_type -
1952
2166
                         (int) table_list->lock_type);
1983
2197
    if (best_table)
1984
2198
    {
1985
2199
      table= best_table;
1986
 
      table->query_id= session->query_id;
 
2200
      table->query_id= thd->query_id;
1987
2201
      goto reset;
1988
2202
    }
1989
2203
    /*
2023
2237
    and try to reopen them.
2024
2238
    Note: refresh_version is currently changed only during FLUSH TABLES.
2025
2239
  */
2026
 
  if (!session->open_tables)
2027
 
    session->version=refresh_version;
2028
 
  else if ((session->version != refresh_version) &&
 
2240
  if (!thd->open_tables)
 
2241
    thd->version=refresh_version;
 
2242
  else if ((thd->version != refresh_version) &&
2029
2243
           ! (flags & DRIZZLE_LOCK_IGNORE_FLUSH))
2030
2244
  {
2031
2245
    /* Someone did a refresh while thread was opening tables */
2036
2250
  }
2037
2251
 
2038
2252
  /*
 
2253
    In order for the back off and re-start process to work properly,
 
2254
    handler tables having old versions (due to FLUSH TABLES or pending
 
2255
    name-lock) MUST be closed. This is specially important if a name-lock
 
2256
    is pending for any table of the handler_tables list, otherwise a
 
2257
    deadlock may occur.
 
2258
  */
 
2259
  if (thd->handler_tables)
 
2260
    mysql_ha_flush(thd);
 
2261
 
 
2262
  /*
2039
2263
    Actually try to find the table in the open_cache.
2040
2264
    The cache may contain several "Table" instances for the same
2041
2265
    physical table. The instances that are currently "in use" by
2064
2288
      need to back off and re-start opening tables.
2065
2289
      If we do not back off now, we may dead lock in case of lock
2066
2290
      order mismatch with some other thread:
2067
 
      c1: name lock t1; -- sort of exclusive lock
 
2291
      c1: name lock t1; -- sort of exclusive lock 
2068
2292
      c2: open t2;      -- sort of shared lock
2069
2293
      c1: name lock t2; -- blocks
2070
2294
      c2: open t1; -- blocks
2074
2298
      if (flags & DRIZZLE_LOCK_IGNORE_FLUSH)
2075
2299
      {
2076
2300
        /* Force close at once after usage */
2077
 
        session->version= table->s->version;
 
2301
        thd->version= table->s->version;
2078
2302
        continue;
2079
2303
      }
2080
2304
 
2081
2305
      /* Avoid self-deadlocks by detecting self-dependencies. */
2082
 
      if (table->open_placeholder && table->in_use == session)
 
2306
      if (table->open_placeholder && table->in_use == thd)
2083
2307
      {
2084
 
        pthread_mutex_unlock(&LOCK_open);
 
2308
        pthread_mutex_unlock(&LOCK_open);
2085
2309
        my_error(ER_UPDATE_TABLE_USED, MYF(0), table->s->table_name.str);
2086
2310
        return(0);
2087
2311
      }
2099
2323
        the earlier call to mysql_ha_flush() in this same critical
2100
2324
        section.
2101
2325
      */
2102
 
      close_old_data_files(session,session->open_tables,0,0);
 
2326
      close_old_data_files(thd,thd->open_tables,0,0);
2103
2327
      /*
2104
2328
        Back-off part 2: try to avoid "busy waiting" on the table:
2105
2329
        if the table is in use by some other thread, we suspend
2115
2339
        after we open first instance but before we open second
2116
2340
        instance.
2117
2341
      */
2118
 
      if (table->in_use != session)
 
2342
      if (table->in_use != thd)
2119
2343
      {
2120
2344
        /* wait_for_conditionwill unlock LOCK_open for us */
2121
 
        wait_for_condition(session, &LOCK_open, &COND_refresh);
 
2345
        wait_for_condition(thd, &LOCK_open, &COND_refresh);
2122
2346
      }
2123
2347
      else
2124
2348
      {
2125
 
        pthread_mutex_unlock(&LOCK_open);
 
2349
        pthread_mutex_unlock(&LOCK_open);
2126
2350
      }
2127
2351
      /*
2128
2352
        There is a refresh in progress for this table.
2129
2353
        Signal the caller that it has to try again.
2130
2354
      */
2131
2355
      if (refresh)
2132
 
        *refresh=1;
 
2356
        *refresh=1;
2133
2357
      return(0);
2134
2358
    }
2135
2359
  }
2137
2361
  {
2138
2362
    /* Unlink the table from "unused_tables" list. */
2139
2363
    if (table == unused_tables)
2140
 
    {  // First unused
2141
 
      unused_tables=unused_tables->next; // Remove from link
 
2364
    {                                           // First unused
 
2365
      unused_tables=unused_tables->next;        // Remove from link
2142
2366
      if (table == unused_tables)
2143
 
        unused_tables=0;
 
2367
        unused_tables=0;
2144
2368
    }
2145
 
    table->prev->next=table->next; /* Remove from unused list */
 
2369
    table->prev->next=table->next;              /* Remove from unused list */
2146
2370
    table->next->prev=table->prev;
2147
 
    table->in_use= session;
 
2371
    table->in_use= thd;
2148
2372
  }
2149
2373
  else
2150
2374
  {
2156
2380
 
2157
2381
    if (table_list->create)
2158
2382
    {
2159
 
      if(ha_table_exists_in_engine(session, table_list->db,
2160
 
                                   table_list->table_name)
2161
 
         != HA_ERR_TABLE_EXIST)
 
2383
      bool exists;
 
2384
 
 
2385
      if (check_if_table_exists(thd, table_list, &exists))
 
2386
      {
 
2387
        pthread_mutex_unlock(&LOCK_open);
 
2388
        return(NULL);
 
2389
      }
 
2390
 
 
2391
      if (!exists)
2162
2392
      {
2163
2393
        /*
2164
2394
          Table to be created, so we need to create placeholder in table-cache.
2165
2395
        */
2166
 
        if (!(table= table_cache_insert_placeholder(session, key, key_length)))
 
2396
        if (!(table= table_cache_insert_placeholder(thd, key, key_length)))
2167
2397
        {
2168
2398
          pthread_mutex_unlock(&LOCK_open);
2169
2399
          return(NULL);
2174
2404
          by other trying to take name-lock.
2175
2405
        */
2176
2406
        table->open_placeholder= 1;
2177
 
        table->next= session->open_tables;
2178
 
        session->open_tables= table;
 
2407
        table->next= thd->open_tables;
 
2408
        thd->open_tables= table;
2179
2409
        pthread_mutex_unlock(&LOCK_open);
2180
2410
        return(table);
2181
2411
      }
2183
2413
    }
2184
2414
 
2185
2415
    /* make a new table */
2186
 
    table= (Table *) malloc(sizeof(*table));
2187
 
    if (table == NULL)
 
2416
    if (!(table=(Table*) my_malloc(sizeof(*table),MYF(MY_WME))))
2188
2417
    {
2189
2418
      pthread_mutex_unlock(&LOCK_open);
2190
2419
      return(NULL);
2191
2420
    }
2192
2421
 
2193
 
    error= open_unireg_entry(session, table, table_list, alias, key, key_length);
2194
 
    if (error != 0)
 
2422
    error= open_unireg_entry(thd, table, table_list, alias, key, key_length);
 
2423
    /* Combine the follow two */
 
2424
    if (error > 0)
2195
2425
    {
2196
 
      free(table);
 
2426
      free((unsigned char*)table);
2197
2427
      pthread_mutex_unlock(&LOCK_open);
2198
2428
      return(NULL);
2199
2429
    }
 
2430
    if (error < 0)
 
2431
    {
 
2432
      free((unsigned char*)table);
 
2433
      pthread_mutex_unlock(&LOCK_open);
 
2434
      return(0); // VIEW
 
2435
    }
2200
2436
    my_hash_insert(&open_cache,(unsigned char*) table);
2201
2437
  }
2202
2438
 
2203
2439
  pthread_mutex_unlock(&LOCK_open);
2204
2440
  if (refresh)
2205
2441
  {
2206
 
    table->next=session->open_tables; /* Link into simple list */
2207
 
    session->open_tables=table;
 
2442
    table->next=thd->open_tables;               /* Link into simple list */
 
2443
    thd->open_tables=table;
2208
2444
  }
2209
 
  table->reginfo.lock_type=TL_READ; /* Assume read */
 
2445
  table->reginfo.lock_type=TL_READ;             /* Assume read */
2210
2446
 
2211
2447
 reset:
2212
2448
  assert(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
2213
2449
 
2214
 
  if (session->lex->need_correct_ident())
 
2450
  if (thd->lex->need_correct_ident())
2215
2451
    table->alias_name_used= my_strcasecmp(table_alias_charset,
2216
2452
                                          table->s->table_name.str, alias);
2217
2453
  /* Fix alias if table name changes */
2218
2454
  if (strcmp(table->alias, alias))
2219
2455
  {
2220
 
    uint32_t length=(uint32_t) strlen(alias)+1;
2221
 
    table->alias= (char*) realloc((char*) table->alias, length);
 
2456
    uint32_t length=(uint) strlen(alias)+1;
 
2457
    table->alias= (char*) my_realloc((char*) table->alias, length,
 
2458
                                     MYF(MY_WME));
2222
2459
    memcpy((void*) table->alias, alias, length);
2223
2460
  }
2224
2461
  /* These variables are also set in reopen_table() */
2225
 
  table->tablenr=session->current_tablenr++;
 
2462
  table->tablenr=thd->current_tablenr++;
2226
2463
  table->used_fields=0;
2227
2464
  table->const_table=0;
2228
2465
  table->null_row= false;
2242
2479
}
2243
2480
 
2244
2481
 
2245
 
Table *find_locked_table(Session *session, const char *db,const char *table_name)
 
2482
Table *find_locked_table(THD *thd, const char *db,const char *table_name)
2246
2483
{
2247
 
  char key[MAX_DBKEY_LENGTH];
2248
 
  char *key_pos= key;
2249
 
  uint32_t key_length;
2250
 
 
2251
 
  key_pos= strcpy(key_pos, db) + strlen(db);
2252
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
2253
 
  key_length= (uint32_t)(key_pos-key)+1;
2254
 
 
2255
 
  for (Table *table=session->open_tables; table ; table=table->next)
 
2484
  char  key[MAX_DBKEY_LENGTH];
 
2485
  uint32_t key_length=(uint) (my_stpcpy(my_stpcpy(key,db)+1,table_name)-key)+1;
 
2486
 
 
2487
  for (Table *table=thd->open_tables; table ; table=table->next)
2256
2488
  {
2257
2489
    if (table->s->table_cache_key.length == key_length &&
2258
 
        !memcmp(table->s->table_cache_key.str, key, key_length))
 
2490
        !memcmp(table->s->table_cache_key.str, key, key_length))
2259
2491
      return table;
2260
2492
  }
2261
2493
  return(0);
2285
2517
  Field **field;
2286
2518
  uint32_t key,part;
2287
2519
  TableList table_list;
2288
 
  Session *session= table->in_use;
 
2520
  THD *thd= table->in_use;
2289
2521
 
2290
2522
  assert(table->s->ref_count == 0);
2291
2523
  assert(!table->sort.io_cache);
2292
2524
 
2293
2525
#ifdef EXTRA_DEBUG
2294
2526
  if (table->db_stat)
2295
 
    errmsg_printf(ERRMSG_LVL_ERROR, _("Table %s had a open data handler in reopen_table"),
 
2527
    sql_print_error(_("Table %s had a open data handler in reopen_table"),
2296
2528
                    table->alias);
2297
2529
#endif
2298
2530
  memset(&table_list, 0, sizeof(TableList));
2300
2532
  table_list.table_name= table->s->table_name.str;
2301
2533
  table_list.table=      table;
2302
2534
 
2303
 
  if (wait_for_locked_table_names(session, &table_list))
 
2535
  if (wait_for_locked_table_names(thd, &table_list))
2304
2536
    return(1);                             // Thread was killed
2305
2537
 
2306
 
  if (open_unireg_entry(session, &tmp, &table_list,
 
2538
  if (open_unireg_entry(thd, &tmp, &table_list,
2307
2539
                        table->alias,
2308
2540
                        table->s->table_cache_key.str,
2309
2541
                        table->s->table_cache_key.length))
2320
2552
  tmp.s->table_map_id=  table->s->table_map_id;
2321
2553
 
2322
2554
  /* Get state */
2323
 
  tmp.in_use=           session;
 
2555
  tmp.in_use=           thd;
2324
2556
  tmp.reginfo.lock_type=table->reginfo.lock_type;
2325
2557
 
2326
2558
  /* Replace table in open list */
2328
2560
  tmp.prev=             table->prev;
2329
2561
 
2330
2562
  if (table->file)
2331
 
    table->closefrm(true);              // close file, free everything
 
2563
    closefrm(table, 1);         // close file, free everything
2332
2564
 
2333
2565
  *table= tmp;
2334
2566
  table->default_column_bitmaps();
2363
2595
    Close all instances of a table open by this thread and replace
2364
2596
    them with exclusive name-locks.
2365
2597
 
2366
 
    @param session        Thread context
 
2598
    @param thd        Thread context
2367
2599
    @param db         Database name for the table to be closed
2368
2600
    @param table_name Name of the table to be closed
2369
2601
 
2376
2608
          the strings are used in a loop even after the share may be freed.
2377
2609
*/
2378
2610
 
2379
 
void close_data_files_and_morph_locks(Session *session, const char *db,
 
2611
void close_data_files_and_morph_locks(THD *thd, const char *db,
2380
2612
                                      const char *table_name)
2381
2613
{
2382
2614
  Table *table;
2383
2615
 
2384
2616
  safe_mutex_assert_owner(&LOCK_open);
2385
2617
 
2386
 
  if (session->lock)
 
2618
  if (thd->lock)
2387
2619
  {
2388
2620
    /*
2389
2621
      If we are not under LOCK TABLES we should have only one table
2390
2622
      open and locked so it makes sense to remove the lock at once.
2391
2623
    */
2392
 
    mysql_unlock_tables(session, session->lock);
2393
 
    session->lock= 0;
 
2624
    mysql_unlock_tables(thd, thd->lock);
 
2625
    thd->lock= 0;
2394
2626
  }
2395
2627
 
2396
2628
  /*
2398
2630
    for target table name if we process ALTER Table ... RENAME.
2399
2631
    So loop below makes sense even if we are not under LOCK TABLES.
2400
2632
  */
2401
 
  for (table=session->open_tables; table ; table=table->next)
 
2633
  for (table=thd->open_tables; table ; table=table->next)
2402
2634
  {
2403
2635
    if (!strcmp(table->s->table_name.str, table_name) &&
2404
2636
        !strcmp(table->s->db.str, db))
2405
2637
    {
2406
 
      if (session->locked_tables)
 
2638
      if (thd->locked_tables)
2407
2639
      {
2408
 
        mysql_lock_remove(session, session->locked_tables, table, true);
 
2640
        mysql_lock_remove(thd, thd->locked_tables, table, true);
2409
2641
      }
2410
2642
      table->open_placeholder= 1;
2411
2643
      close_handle_and_leave_table_as_lock(table);
2418
2650
/**
2419
2651
    Reopen all tables with closed data files.
2420
2652
 
2421
 
    @param session         Thread context
 
2653
    @param thd         Thread context
2422
2654
    @param get_locks   Should we get locks after reopening tables ?
2423
2655
    @param mark_share_as_old  Mark share as old to protect from a impending
2424
2656
                              global read lock.
2435
2667
    @return false in case of success, true - otherwise.
2436
2668
*/
2437
2669
 
2438
 
bool reopen_tables(Session *session, bool get_locks, bool mark_share_as_old)
 
2670
bool reopen_tables(THD *thd, bool get_locks, bool mark_share_as_old)
2439
2671
{
2440
2672
  Table *table,*next,**prev;
2441
2673
  Table **tables,**tables_ptr;                  // For locks
2444
2676
                    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
2445
2677
                    DRIZZLE_LOCK_IGNORE_FLUSH;
2446
2678
 
2447
 
  if (!session->open_tables)
 
2679
  if (!thd->open_tables)
2448
2680
    return(0);
2449
2681
 
2450
2682
  safe_mutex_assert_owner(&LOCK_open);
2455
2687
      Do not handle locks of MERGE children.
2456
2688
    */
2457
2689
    uint32_t opens=0;
2458
 
    for (table= session->open_tables; table ; table=table->next)
 
2690
    for (table= thd->open_tables; table ; table=table->next)
2459
2691
      opens++;
2460
 
    tables= (Table**) malloc(sizeof(Table*)*opens);
 
2692
    tables= (Table**) my_alloca(sizeof(Table*)*opens);
2461
2693
  }
2462
2694
  else
2463
 
    tables= &session->open_tables;
 
2695
    tables= &thd->open_tables;
2464
2696
  tables_ptr =tables;
2465
2697
 
2466
 
  prev= &session->open_tables;
2467
 
  for (table=session->open_tables; table ; table=next)
 
2698
  prev= &thd->open_tables;
 
2699
  for (table=thd->open_tables; table ; table=next)
2468
2700
  {
2469
2701
    uint32_t db_stat=table->db_stat;
2470
2702
    next=table->next;
2497
2729
      wait_for_tables() as it tries to acquire LOCK_open, which is
2498
2730
      already locked.
2499
2731
    */
2500
 
    session->some_tables_deleted=0;
2501
 
    if ((lock= mysql_lock_tables(session, tables, (uint32_t) (tables_ptr - tables),
 
2732
    thd->some_tables_deleted=0;
 
2733
    if ((lock= mysql_lock_tables(thd, tables, (uint) (tables_ptr - tables),
2502
2734
                                 flags, &not_used)))
2503
2735
    {
2504
 
      session->locked_tables=mysql_lock_merge(session->locked_tables,lock);
 
2736
      thd->locked_tables=mysql_lock_merge(thd->locked_tables,lock);
2505
2737
    }
2506
2738
    else
2507
2739
    {
2516
2748
  }
2517
2749
  if (get_locks && tables)
2518
2750
  {
2519
 
    free((unsigned char*) tables);
 
2751
    my_afree((unsigned char*) tables);
2520
2752
  }
2521
2753
  broadcast_refresh();
2522
2754
  return(error);
2527
2759
    Close handlers for tables in list, but leave the Table structure
2528
2760
    intact so that we can re-open these quickly.
2529
2761
 
2530
 
    @param session           Thread context
 
2762
    @param thd           Thread context
2531
2763
    @param table         Head of the list of Table objects
2532
2764
    @param morph_locks   true  - remove locks which we have on tables being closed
2533
2765
                                 but ensure that no DML or DDL will sneak in before
2537
2769
    @param send_refresh  Should we awake waiters even if we didn't close any tables?
2538
2770
*/
2539
2771
 
2540
 
static void close_old_data_files(Session *session, Table *table, bool morph_locks,
 
2772
static void close_old_data_files(THD *thd, Table *table, bool morph_locks,
2541
2773
                                 bool send_refresh)
2542
2774
{
2543
2775
  bool found= send_refresh;
2563
2795
              lock on it. This will also give them a chance to close their
2564
2796
              instances of this table.
2565
2797
            */
2566
 
            mysql_lock_abort(session, ulcktbl, true);
2567
 
            mysql_lock_remove(session, session->locked_tables, ulcktbl, true);
 
2798
            mysql_lock_abort(thd, ulcktbl, true);
 
2799
            mysql_lock_remove(thd, thd->locked_tables, ulcktbl, true);
2568
2800
            ulcktbl->lock_count= 0;
2569
2801
          }
2570
2802
          if ((ulcktbl != table) && ulcktbl->db_stat)
2649
2881
 
2650
2882
/* Wait until all used tables are refreshed */
2651
2883
 
2652
 
bool wait_for_tables(Session *session)
 
2884
bool wait_for_tables(THD *thd)
2653
2885
{
2654
2886
  bool result;
2655
2887
 
2656
 
  session->set_proc_info("Waiting for tables");
 
2888
  thd_proc_info(thd, "Waiting for tables");
2657
2889
  pthread_mutex_lock(&LOCK_open);
2658
 
  while (!session->killed)
 
2890
  while (!thd->killed)
2659
2891
  {
2660
 
    session->some_tables_deleted=0;
2661
 
    close_old_data_files(session,session->open_tables,0,dropping_tables != 0);
2662
 
    if (!table_is_used(session->open_tables,1))
 
2892
    thd->some_tables_deleted=0;
 
2893
    close_old_data_files(thd,thd->open_tables,0,dropping_tables != 0);
 
2894
    mysql_ha_flush(thd);
 
2895
    if (!table_is_used(thd->open_tables,1))
2663
2896
      break;
2664
2897
    (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
2665
2898
  }
2666
 
  if (session->killed)
 
2899
  if (thd->killed)
2667
2900
    result= 1;                                  // aborted
2668
2901
  else
2669
2902
  {
2670
2903
    /* Now we can open all tables without any interference */
2671
 
    session->set_proc_info("Reopen tables");
2672
 
    session->version= refresh_version;
2673
 
    result=reopen_tables(session,0,0);
 
2904
    thd_proc_info(thd, "Reopen tables");
 
2905
    thd->version= refresh_version;
 
2906
    result=reopen_tables(thd,0,0);
2674
2907
  }
2675
2908
  pthread_mutex_unlock(&LOCK_open);
2676
 
  session->set_proc_info(0);
 
2909
  thd_proc_info(thd, 0);
2677
2910
  return(result);
2678
2911
}
2679
2912
 
2683
2916
 
2684
2917
  SYNOPSIS
2685
2918
    drop_locked_tables()
2686
 
    session                     Thread thandler
 
2919
    thd                 Thread thandler
2687
2920
    db                  Database
2688
2921
    table_name          Table name
2689
2922
 
2702
2935
*/
2703
2936
 
2704
2937
 
2705
 
Table *drop_locked_tables(Session *session,const char *db, const char *table_name)
 
2938
Table *drop_locked_tables(THD *thd,const char *db, const char *table_name)
2706
2939
{
2707
2940
  Table *table,*next,**prev, *found= 0;
2708
 
  prev= &session->open_tables;
 
2941
  prev= &thd->open_tables;
2709
2942
 
2710
2943
  /*
2711
2944
    Note that we need to hold LOCK_open while changing the
2714
2947
    Closing a MERGE child before the parent would be fatal if the
2715
2948
    other thread tries to abort the MERGE lock in between.
2716
2949
  */
2717
 
  for (table= session->open_tables; table ; table=next)
 
2950
  for (table= thd->open_tables; table ; table=next)
2718
2951
  {
2719
2952
    next=table->next;
2720
2953
    if (!strcmp(table->s->table_name.str, table_name) &&
2721
2954
        !strcmp(table->s->db.str, db))
2722
2955
    {
2723
 
      mysql_lock_remove(session, session->locked_tables, table, true);
 
2956
      mysql_lock_remove(thd, thd->locked_tables, table, true);
2724
2957
 
2725
2958
      if (!found)
2726
2959
      {
2747
2980
  *prev=0;
2748
2981
  if (found)
2749
2982
    broadcast_refresh();
2750
 
  if (session->locked_tables && session->locked_tables->table_count == 0)
 
2983
  if (thd->locked_tables && thd->locked_tables->table_count == 0)
2751
2984
  {
2752
 
    free((unsigned char*) session->locked_tables);
2753
 
    session->locked_tables=0;
 
2985
    free((unsigned char*) thd->locked_tables);
 
2986
    thd->locked_tables=0;
2754
2987
  }
2755
2988
  return(found);
2756
2989
}
2762
2995
  other threads trying to get the lock.
2763
2996
*/
2764
2997
 
2765
 
void abort_locked_tables(Session *session,const char *db, const char *table_name)
 
2998
void abort_locked_tables(THD *thd,const char *db, const char *table_name)
2766
2999
{
2767
3000
  Table *table;
2768
 
  for (table= session->open_tables; table ; table= table->next)
 
3001
  for (table= thd->open_tables; table ; table= table->next)
2769
3002
  {
2770
3003
    if (!strcmp(table->s->table_name.str, table_name) &&
2771
3004
        !strcmp(table->s->db.str, db))
2772
3005
    {
2773
3006
      /* If MERGE child, forward lock handling to parent. */
2774
 
      mysql_lock_abort(session, table, true);
 
3007
      mysql_lock_abort(thd, table, true);
2775
3008
      break;
2776
3009
    }
2777
3010
  }
2835
3068
 
2836
3069
  SYNOPSIS
2837
3070
    open_unireg_entry()
2838
 
    session                     Thread handle
 
3071
    thd                 Thread handle
2839
3072
    entry               Store open table definition here
2840
3073
    table_list          TableList with db, table_name
2841
3074
    alias               Alias name
2843
3076
    cache_key_length    length of cache_key
2844
3077
 
2845
3078
  NOTES
2846
 
   Extra argument for open is taken from session->open_options
 
3079
   Extra argument for open is taken from thd->open_options
2847
3080
   One must have a lock on LOCK_open when calling this function
2848
3081
 
2849
3082
  RETURN
2851
3084
    #   Error
2852
3085
*/
2853
3086
 
2854
 
static int open_unireg_entry(Session *session, Table *entry, TableList *table_list,
 
3087
static int open_unireg_entry(THD *thd, Table *entry, TableList *table_list,
2855
3088
                             const char *alias,
2856
3089
                             char *cache_key, uint32_t cache_key_length)
2857
3090
{
2861
3094
 
2862
3095
  safe_mutex_assert_owner(&LOCK_open);
2863
3096
retry:
2864
 
  if (!(share= get_table_share_with_create(session, table_list, cache_key,
2865
 
                                           cache_key_length,
 
3097
  if (!(share= get_table_share_with_create(thd, table_list, cache_key,
 
3098
                                           cache_key_length, 
2866
3099
                                           table_list->i_s_requested_object,
2867
3100
                                           &error)))
2868
3101
    return(1);
2869
3102
 
2870
 
  while ((error= open_table_from_share(session, share, alias,
2871
 
                                       (uint32_t) (HA_OPEN_KEYFILE |
 
3103
  while ((error= open_table_from_share(thd, share, alias,
 
3104
                                       (uint) (HA_OPEN_KEYFILE |
2872
3105
                                               HA_OPEN_RNDFILE |
2873
3106
                                               HA_GET_INDEX |
2874
3107
                                               HA_TRY_READ_ONLY),
2875
3108
                                       (EXTRA_RECORD),
2876
 
                                       session->open_options, entry, OTM_OPEN)))
 
3109
                                       thd->open_options, entry, OTM_OPEN)))
2877
3110
  {
2878
3111
    if (error == 7)                             // Table def changed
2879
3112
    {
2886
3119
        Here we should wait until all threads has released the table.
2887
3120
        For now we do one retry. This may cause a deadlock if there
2888
3121
        is other threads waiting for other tables used by this thread.
2889
 
 
 
3122
        
2890
3123
        Proper fix would be to if the second retry failed:
2891
3124
        - Mark that table def changed
2892
3125
        - Return from open table
2894
3127
        - Start waiting that the share is released
2895
3128
        - Retry by opening all tables again
2896
3129
      */
2897
 
 
 
3130
      if (ha_create_table_from_engine(thd, table_list->db,
 
3131
                                      table_list->table_name))
 
3132
        goto err;
2898
3133
      /*
2899
3134
        TO BE FIXED
2900
3135
        To avoid deadlock, only wait for release if no one else is
2904
3139
        goto err;
2905
3140
      /* Free share and wait until it's released by all threads */
2906
3141
      release_table_share(share, RELEASE_WAIT_FOR_DROP);
2907
 
      if (!session->killed)
 
3142
      if (!thd->killed)
2908
3143
      {
2909
 
        drizzle_reset_errors(session, 1);         // Clear warnings
2910
 
        session->clear_error();                 // Clear error message
 
3144
        drizzle_reset_errors(thd, 1);         // Clear warnings
 
3145
        thd->clear_error();                 // Clear error message
2911
3146
        goto retry;
2912
3147
      }
2913
3148
      return(1);
2915
3150
    if (!entry->s || !entry->s->crashed)
2916
3151
      goto err;
2917
3152
     // Code below is for repairing a crashed file
2918
 
     if ((error= lock_table_name(session, table_list, true)))
 
3153
     if ((error= lock_table_name(thd, table_list, true)))
2919
3154
     {
2920
3155
       if (error < 0)
2921
3156
        goto err;
2922
 
       if (wait_for_locked_table_names(session, table_list))
 
3157
       if (wait_for_locked_table_names(thd, table_list))
2923
3158
       {
2924
 
        unlock_table_name(session, table_list);
 
3159
        unlock_table_name(thd, table_list);
2925
3160
        goto err;
2926
3161
       }
2927
3162
     }
2928
3163
     pthread_mutex_unlock(&LOCK_open);
2929
 
     session->clear_error();                            // Clear error message
 
3164
     thd->clear_error();                                // Clear error message
2930
3165
     error= 0;
2931
 
     if (open_table_from_share(session, share, alias,
2932
 
                               (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
3166
     if (open_table_from_share(thd, share, alias,
 
3167
                               (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
2933
3168
                                       HA_GET_INDEX |
2934
3169
                                       HA_TRY_READ_ONLY),
2935
3170
                               EXTRA_RECORD,
2936
3171
                               ha_open_options | HA_OPEN_FOR_REPAIR,
2937
3172
                               entry, OTM_OPEN) || ! entry->file ||
2938
 
        (entry->file->is_crashed() && entry->file->ha_check_and_repair(session)))
 
3173
        (entry->file->is_crashed() && entry->file->ha_check_and_repair(thd)))
2939
3174
     {
2940
3175
       /* Give right error message */
2941
 
       session->clear_error();
 
3176
       thd->clear_error();
2942
3177
       my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
2943
 
       errmsg_printf(ERRMSG_LVL_ERROR, _("Couldn't repair table: %s.%s"), share->db.str,
 
3178
       sql_print_error(_("Couldn't repair table: %s.%s"), share->db.str,
2944
3179
                       share->table_name.str);
2945
3180
       if (entry->file)
2946
 
        entry->closefrm(false);
 
3181
        closefrm(entry, 0);
2947
3182
       error=1;
2948
3183
     }
2949
3184
     else
2950
 
       session->clear_error();                  // Clear error message
 
3185
       thd->clear_error();                      // Clear error message
2951
3186
     pthread_mutex_lock(&LOCK_open);
2952
 
     unlock_table_name(session, table_list);
2953
 
 
 
3187
     unlock_table_name(thd, table_list);
 
3188
 
2954
3189
     if (error)
2955
3190
       goto err;
2956
3191
     break;
2963
3198
  if (unlikely(entry->file->implicit_emptied))
2964
3199
  {
2965
3200
    entry->file->implicit_emptied= 0;
 
3201
    if (mysql_bin_log.is_open())
2966
3202
    {
2967
3203
      char *query, *end;
2968
3204
      uint32_t query_buf_size= 20 + share->db.length + share->table_name.length +1;
2969
 
      if ((query= (char*) malloc(query_buf_size)))
 
3205
      if ((query= (char*) my_malloc(query_buf_size,MYF(MY_WME))))
2970
3206
      {
2971
 
        /* 
2972
 
          "this DELETE FROM is needed even with row-based binlogging"
2973
 
 
2974
 
          We inherited this from MySQL. TODO: fix it to issue a propper truncate
2975
 
          of the table (though that may not be completely right sematics).
2976
 
        */
2977
 
        end= query;
2978
 
        end+= sprintf(query, "DELETE FROM `%s`.`%s`", share->db.str,
2979
 
                      share->table_name.str);
2980
 
        (void)replicator_statement(session, query, (size_t)(end - query));
 
3207
        /* this DELETE FROM is needed even with row-based binlogging */
 
3208
        end = strxmov(my_stpcpy(query, "DELETE FROM `"),
 
3209
                      share->db.str,"`.`",share->table_name.str,"`", NULL);
 
3210
        thd->binlog_query(THD::STMT_QUERY_TYPE,
 
3211
                          query, (ulong)(end-query), false, false);
2981
3212
        free(query);
2982
3213
      }
2983
3214
      else
2984
3215
      {
2985
 
        errmsg_printf(ERRMSG_LVL_ERROR, _("When opening HEAP table, could not allocate memory "
2986
 
                                          "to write 'DELETE FROM `%s`.`%s`' to replication"),
2987
 
                      table_list->db, table_list->table_name);
2988
 
        my_error(ER_OUTOFMEMORY, MYF(0), query_buf_size);
2989
 
        entry->closefrm(false);
 
3216
        /*
 
3217
          As replication is maybe going to be corrupted, we need to warn the
 
3218
          DBA on top of warning the client (which will automatically be done
 
3219
          because of MYF(MY_WME) in my_malloc() above).
 
3220
        */
 
3221
        sql_print_error(_("When opening HEAP table, could not allocate memory "
 
3222
                          "to write 'DELETE FROM `%s`.`%s`' to the binary log"),
 
3223
                        table_list->db, table_list->table_name);
 
3224
        closefrm(entry, 0);
2990
3225
        goto err;
2991
3226
      }
2992
3227
    }
3004
3239
 
3005
3240
  SYNOPSIS
3006
3241
    open_tables()
3007
 
    session - thread handler
 
3242
    thd - thread handler
3008
3243
    start - list of tables in/out
3009
3244
    counter - number of opened tables will be return using this parameter
3010
3245
    flags   - bitmap of flags to modify how the tables will be open:
3027
3262
    -1 - error
3028
3263
*/
3029
3264
 
3030
 
int open_tables(Session *session, TableList **start, uint32_t *counter, uint32_t flags)
 
3265
int open_tables(THD *thd, TableList **start, uint32_t *counter, uint32_t flags)
3031
3266
{
3032
3267
  TableList *tables= NULL;
3033
3268
  bool refresh;
3042
3277
  */
3043
3278
  init_sql_alloc(&new_frm_mem, 8024, 8024);
3044
3279
 
3045
 
  session->current_tablenr= 0;
 
3280
  thd->current_tablenr= 0;
3046
3281
 restart:
3047
3282
  *counter= 0;
3048
 
  session->set_proc_info("Opening tables");
 
3283
  thd_proc_info(thd, "Opening tables");
3049
3284
 
3050
3285
  /*
3051
3286
    For every table in the list of tables to open, try to find or open
3073
3308
    */
3074
3309
    if (tables->schema_table)
3075
3310
    {
3076
 
      if (!mysql_schema_table(session, session->lex, tables))
 
3311
      if (!mysql_schema_table(thd, thd->lex, tables))
3077
3312
        continue;
3078
3313
      return(-1);
3079
3314
    }
3084
3319
      not opened yet. Try to open the table.
3085
3320
    */
3086
3321
    if (!tables->table)
3087
 
      tables->table= open_table(session, tables, &refresh, flags);
 
3322
      tables->table= open_table(thd, tables, &refresh, flags);
3088
3323
 
3089
3324
    if (!tables->table)
3090
3325
    {
3106
3341
          we pretend that we have finished calculation which we were doing
3107
3342
          currently.
3108
3343
        */
3109
 
        close_tables_for_reopen(session, start);
 
3344
        close_tables_for_reopen(thd, start);
3110
3345
        goto restart;
3111
3346
      }
3112
3347
 
3116
3351
      result= -1;                               // Fatal error
3117
3352
      break;
3118
3353
    }
3119
 
    if (tables->lock_type != TL_UNLOCK && ! session->locked_tables)
 
3354
    if (tables->lock_type != TL_UNLOCK && ! thd->locked_tables)
3120
3355
    {
3121
3356
      if (tables->lock_type == TL_WRITE_DEFAULT)
3122
 
        tables->table->reginfo.lock_type= session->update_lock_default;
 
3357
        tables->table->reginfo.lock_type= thd->update_lock_default;
3123
3358
      else if (tables->table->s->tmp_table == NO_TMP_TABLE)
3124
3359
        tables->table->reginfo.lock_type= tables->lock_type;
3125
3360
    }
3126
3361
  }
3127
3362
 
3128
 
  session->set_proc_info(0);
 
3363
  thd_proc_info(thd, 0);
3129
3364
  free_root(&new_frm_mem, MYF(0));              // Free pre-alloced block
3130
3365
 
3131
3366
  if (result && tables)
3132
3367
  {
3133
3368
    /*
3134
3369
      Some functions determine success as (tables->table != NULL).
3135
 
      tables->table is in session->open_tables.
 
3370
      tables->table is in thd->open_tables.
3136
3371
    */
3137
3372
    tables->table= NULL;
3138
3373
  }
3145
3380
 
3146
3381
  SYNOPSIS
3147
3382
    check_lock_and_start_stmt()
3148
 
    session                     Thread handle
 
3383
    thd                 Thread handle
3149
3384
    table_list          Table to check
3150
3385
    lock_type           Lock used for table
3151
3386
 
3154
3389
  1     error
3155
3390
*/
3156
3391
 
3157
 
static bool check_lock_and_start_stmt(Session *session, Table *table,
 
3392
static bool check_lock_and_start_stmt(THD *thd, Table *table,
3158
3393
                                      thr_lock_type lock_type)
3159
3394
{
3160
3395
  int error;
3165
3400
    my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),table->alias);
3166
3401
    return(1);
3167
3402
  }
3168
 
  if ((error=table->file->start_stmt(session, lock_type)))
 
3403
  if ((error=table->file->start_stmt(thd, lock_type)))
3169
3404
  {
3170
3405
    table->file->print_error(error,MYF(0));
3171
3406
    return(1);
3177
3412
/**
3178
3413
  @brief Open and lock one table
3179
3414
 
3180
 
  @param[in]    session             thread handle
 
3415
  @param[in]    thd             thread handle
3181
3416
  @param[in]    table_l         table to open is first table in this list
3182
3417
  @param[in]    lock_type       lock to use for table
3183
3418
 
3204
3439
    and locking issues because it does not call lock_tables().
3205
3440
*/
3206
3441
 
3207
 
Table *open_n_lock_single_table(Session *session, TableList *table_l,
 
3442
Table *open_n_lock_single_table(THD *thd, TableList *table_l,
3208
3443
                                thr_lock_type lock_type)
3209
3444
{
3210
3445
  TableList *save_next_global;
3218
3453
  table_l->lock_type= lock_type;
3219
3454
 
3220
3455
  /* Open the table. */
3221
 
  if (simple_open_n_lock_tables(session, table_l))
 
3456
  if (simple_open_n_lock_tables(thd, table_l))
3222
3457
    table_l->table= NULL; /* Just to be sure. */
3223
3458
 
3224
3459
  /* Restore list. */
3233
3468
 
3234
3469
  SYNOPSIS
3235
3470
    open_ltable()
3236
 
    session                     Thread handler
 
3471
    thd                 Thread handler
3237
3472
    table_list          Table to open is first table in this list
3238
3473
    lock_type           Lock to use for open
3239
3474
    lock_flags          Flags passed to mysql_lock_table
3246
3481
  RETURN VALUES
3247
3482
    table               Opened table
3248
3483
    0                   Error
3249
 
 
 
3484
  
3250
3485
    If ok, the following are also set:
3251
3486
      table_list->lock_type     lock_type
3252
3487
      table_list->table         table
3253
3488
*/
3254
3489
 
3255
 
Table *open_ltable(Session *session, TableList *table_list, thr_lock_type lock_type,
 
3490
Table *open_ltable(THD *thd, TableList *table_list, thr_lock_type lock_type,
3256
3491
                   uint32_t lock_flags)
3257
3492
{
3258
3493
  Table *table;
3259
3494
  bool refresh;
3260
3495
 
3261
 
  session->set_proc_info("Opening table");
3262
 
  session->current_tablenr= 0;
3263
 
  while (!(table= open_table(session, table_list, &refresh, 0)) &&
 
3496
  thd_proc_info(thd, "Opening table");
 
3497
  thd->current_tablenr= 0;
 
3498
  while (!(table= open_table(thd, table_list, &refresh, 0)) &&
3264
3499
         refresh)
3265
3500
    ;
3266
3501
 
3268
3503
  {
3269
3504
    table_list->lock_type= lock_type;
3270
3505
    table_list->table=     table;
3271
 
    if (session->locked_tables)
 
3506
    if (thd->locked_tables)
3272
3507
    {
3273
 
      if (check_lock_and_start_stmt(session, table, lock_type))
 
3508
      if (check_lock_and_start_stmt(thd, table, lock_type))
3274
3509
        table= 0;
3275
3510
    }
3276
3511
    else
3277
3512
    {
3278
 
      assert(session->lock == 0);       // You must lock everything at once
 
3513
      assert(thd->lock == 0);   // You must lock everything at once
3279
3514
      if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
3280
 
        if (! (session->lock= mysql_lock_tables(session, &table_list->table, 1,
 
3515
        if (! (thd->lock= mysql_lock_tables(thd, &table_list->table, 1,
3281
3516
                                            lock_flags, &refresh)))
3282
3517
          table= 0;
3283
3518
    }
3284
3519
  }
3285
3520
 
3286
 
  session->set_proc_info(0);
 
3521
  thd_proc_info(thd, 0);
3287
3522
  return(table);
3288
3523
}
3289
3524
 
3293
3528
 
3294
3529
  SYNOPSIS
3295
3530
    open_and_lock_tables_derived()
3296
 
    session             - thread handler
 
3531
    thd         - thread handler
3297
3532
    tables      - list of tables for open&locking
3298
3533
    derived     - if to handle derived tables
3299
3534
 
3306
3541
 
3307
3542
  NOTE
3308
3543
    There are two convenience functions:
3309
 
    - simple_open_n_lock_tables(session, tables)  without derived handling
3310
 
    - open_and_lock_tables(session, tables)       with derived handling
 
3544
    - simple_open_n_lock_tables(thd, tables)  without derived handling
 
3545
    - open_and_lock_tables(thd, tables)       with derived handling
3311
3546
    Both inline functions call open_and_lock_tables_derived() with
3312
3547
    the third argument set appropriately.
3313
3548
*/
3314
3549
 
3315
 
int open_and_lock_tables_derived(Session *session, TableList *tables, bool derived)
 
3550
int open_and_lock_tables_derived(THD *thd, TableList *tables, bool derived)
3316
3551
{
3317
3552
  uint32_t counter;
3318
3553
  bool need_reopen;
3319
3554
 
3320
 
  for ( ; ; )
 
3555
  for ( ; ; ) 
3321
3556
  {
3322
 
    if (open_tables(session, &tables, &counter, 0))
 
3557
    if (open_tables(thd, &tables, &counter, 0))
3323
3558
      return(-1);
3324
3559
 
3325
 
    if (!lock_tables(session, tables, counter, &need_reopen))
 
3560
    if (!lock_tables(thd, tables, counter, &need_reopen))
3326
3561
      break;
3327
3562
    if (!need_reopen)
3328
3563
      return(-1);
3329
 
    close_tables_for_reopen(session, &tables);
 
3564
    close_tables_for_reopen(thd, &tables);
3330
3565
  }
3331
3566
  if (derived &&
3332
 
      (mysql_handle_derived(session->lex, &mysql_derived_prepare) ||
3333
 
       (session->fill_derived_tables() &&
3334
 
        mysql_handle_derived(session->lex, &mysql_derived_filling))))
 
3567
      (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
 
3568
       (thd->fill_derived_tables() &&
 
3569
        mysql_handle_derived(thd->lex, &mysql_derived_filling))))
3335
3570
    return(true); /* purecov: inspected */
3336
3571
  return(0);
3337
3572
}
3342
3577
 
3343
3578
  SYNOPSIS
3344
3579
    open_normal_and_derived_tables
3345
 
    session             - thread handler
 
3580
    thd         - thread handler
3346
3581
    tables      - list of tables for open
3347
3582
    flags       - bitmap of flags to modify how the tables will be open:
3348
3583
                  DRIZZLE_LOCK_IGNORE_FLUSH - open table even if someone has
3352
3587
    false - ok
3353
3588
    true  - error
3354
3589
 
3355
 
  NOTE
 
3590
  NOTE 
3356
3591
    This is to be used on prepare stage when you don't read any
3357
3592
    data from the tables.
3358
3593
*/
3359
3594
 
3360
 
bool open_normal_and_derived_tables(Session *session, TableList *tables, uint32_t flags)
 
3595
bool open_normal_and_derived_tables(THD *thd, TableList *tables, uint32_t flags)
3361
3596
{
3362
3597
  uint32_t counter;
3363
 
  assert(!session->fill_derived_tables());
3364
 
  if (open_tables(session, &tables, &counter, flags) ||
3365
 
      mysql_handle_derived(session->lex, &mysql_derived_prepare))
 
3598
  assert(!thd->fill_derived_tables());
 
3599
  if (open_tables(thd, &tables, &counter, flags) ||
 
3600
      mysql_handle_derived(thd->lex, &mysql_derived_prepare))
3366
3601
    return(true); /* purecov: inspected */
3367
3602
  return(0);
3368
3603
}
3369
3604
 
 
3605
 
 
3606
/**
 
3607
   Decide on logging format to use for the statement.
 
3608
 
 
3609
   Compute the capabilities vector for the involved storage engines
 
3610
   and mask out the flags for the binary log. Right now, the binlog
 
3611
   flags only include the capabilities of the storage engines, so this
 
3612
   is safe.
 
3613
 
 
3614
   We now have three alternatives that prevent the statement from
 
3615
   being loggable:
 
3616
 
 
3617
   1. If there are no capabilities left (all flags are clear) it is
 
3618
      not possible to log the statement at all, so we roll back the
 
3619
      statement and report an error.
 
3620
 
 
3621
   2. Statement mode is set, but the capabilities indicate that
 
3622
      statement format is not possible.
 
3623
 
 
3624
   3. Row mode is set, but the capabilities indicate that row
 
3625
      format is not possible.
 
3626
 
 
3627
   4. Statement is unsafe, but the capabilities indicate that row
 
3628
      format is not possible.
 
3629
 
 
3630
   If we are in MIXED mode, we then decide what logging format to use:
 
3631
 
 
3632
   1. If the statement is unsafe, row-based logging is used.
 
3633
 
 
3634
   2. If statement-based logging is not possible, row-based logging is
 
3635
      used.
 
3636
 
 
3637
   3. Otherwise, statement-based logging is used.
 
3638
 
 
3639
   @param thd    Client thread
 
3640
   @param tables Tables involved in the query
 
3641
 */
 
3642
 
 
3643
int decide_logging_format(THD *thd, TableList *tables)
 
3644
{
 
3645
  if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
 
3646
  {
 
3647
    handler::Table_flags flags_some_set= handler::Table_flags();
 
3648
    handler::Table_flags flags_all_set= ~handler::Table_flags();
 
3649
    bool multi_engine= false;
 
3650
    void* prev_ht= NULL;
 
3651
    for (TableList *table= tables; table; table= table->next_global)
 
3652
    {
 
3653
      if (!table->placeholder() && table->lock_type >= TL_WRITE_ALLOW_WRITE)
 
3654
      {
 
3655
        uint64_t const flags= table->table->file->ha_table_flags();
 
3656
        if (prev_ht && prev_ht != table->table->file->ht)
 
3657
          multi_engine= true;
 
3658
        prev_ht= table->table->file->ht;
 
3659
        flags_all_set &= flags;
 
3660
        flags_some_set |= flags;
 
3661
      }
 
3662
    }
 
3663
 
 
3664
    int error= 0;
 
3665
    if (flags_all_set == 0)
 
3666
    {
 
3667
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3668
               "Statement cannot be logged to the binary log in"
 
3669
               " row-based nor statement-based format");
 
3670
    }
 
3671
    else if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
 
3672
             (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
 
3673
    {
 
3674
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3675
                "Statement-based format required for this statement,"
 
3676
                " but not allowed by this combination of engines");
 
3677
    }
 
3678
    else if ((thd->variables.binlog_format == BINLOG_FORMAT_ROW ||
 
3679
              thd->lex->is_stmt_unsafe()) &&
 
3680
             (flags_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
 
3681
    {
 
3682
      my_error((error= ER_BINLOG_LOGGING_IMPOSSIBLE), MYF(0),
 
3683
                "Row-based format required for this statement,"
 
3684
                " but not allowed by this combination of engines");
 
3685
    }
 
3686
 
 
3687
    if (error)
 
3688
      return -1;
 
3689
 
 
3690
    /*
 
3691
      We switch to row-based format if we are in mixed mode and one of
 
3692
      the following are true:
 
3693
 
 
3694
      1. If the statement is unsafe
 
3695
      2. If statement format cannot be used
 
3696
 
 
3697
      Observe that point to cannot be decided before the tables
 
3698
      involved in a statement has been checked, i.e., we cannot put
 
3699
      this code in reset_current_stmt_binlog_row_based(), it has to be
 
3700
      here.
 
3701
    */
 
3702
    if (thd->lex->is_stmt_unsafe() ||
 
3703
        (flags_all_set & HA_BINLOG_STMT_CAPABLE) == 0)
 
3704
    {
 
3705
      thd->set_current_stmt_binlog_row_based_if_mixed();
 
3706
    }
 
3707
  }
 
3708
 
 
3709
  return 0;
 
3710
}
 
3711
 
3370
3712
/*
3371
3713
  Lock all tables in list
3372
3714
 
3373
3715
  SYNOPSIS
3374
3716
    lock_tables()
3375
 
    session                     Thread handler
 
3717
    thd                 Thread handler
3376
3718
    tables              Tables to lock
3377
3719
    count               Number of opened tables
3378
3720
    need_reopen         Out parameter which if true indicates that some
3388
3730
 
3389
3731
    If query for which we are calling this function marked as requring
3390
3732
    prelocking, this function will do implicit LOCK TABLES and change
3391
 
    session::prelocked_mode accordingly.
 
3733
    thd::prelocked_mode accordingly.
3392
3734
 
3393
3735
  RETURN VALUES
3394
3736
   0    ok
3395
3737
   -1   Error
3396
3738
*/
3397
3739
 
3398
 
int lock_tables(Session *session, TableList *tables, uint32_t count, bool *need_reopen)
 
3740
int lock_tables(THD *thd, TableList *tables, uint32_t count, bool *need_reopen)
3399
3741
{
3400
3742
  TableList *table;
3401
3743
 
3406
3748
  *need_reopen= false;
3407
3749
 
3408
3750
  if (!tables)
3409
 
    return 0;
 
3751
    return(decide_logging_format(thd, tables));
3410
3752
 
3411
 
  if (!session->locked_tables)
 
3753
  if (!thd->locked_tables)
3412
3754
  {
3413
 
    assert(session->lock == 0); // You must lock everything at once
 
3755
    assert(thd->lock == 0);     // You must lock everything at once
3414
3756
    Table **start,**ptr;
3415
3757
    uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
3416
3758
 
3417
 
    if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
 
3759
    if (!(ptr=start=(Table**) thd->alloc(sizeof(Table*)*count)))
3418
3760
      return(-1);
3419
3761
    for (table= tables; table; table= table->next_global)
3420
3762
    {
3422
3764
        *(ptr++)= table->table;
3423
3765
    }
3424
3766
 
3425
 
    if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
3767
    if (!(thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
3426
3768
                                       lock_flag, need_reopen)))
3427
3769
    {
3428
3770
      return(-1);
3430
3772
  }
3431
3773
  else
3432
3774
  {
3433
 
    TableList *first_not_own= session->lex->first_not_own_table();
 
3775
    TableList *first_not_own= thd->lex->first_not_own_table();
3434
3776
    /*
3435
3777
      When open_and_lock_tables() is called for a single table out of
3436
3778
      a table list, the 'next_global' chain is temporarily broken. We
3444
3786
         table= table->next_global)
3445
3787
    {
3446
3788
      if (!table->placeholder() &&
3447
 
          check_lock_and_start_stmt(session, table->table, table->lock_type))
 
3789
          check_lock_and_start_stmt(thd, table->table, table->lock_type))
3448
3790
      {
3449
3791
        return(-1);
3450
3792
      }
3451
3793
    }
3452
3794
  }
3453
3795
 
3454
 
  return 0;
 
3796
  return(decide_logging_format(thd, tables));
3455
3797
}
3456
3798
 
3457
3799
 
3461
3803
 
3462
3804
  SYNOPSIS
3463
3805
    close_tables_for_reopen()
3464
 
      session    in     Thread context
 
3806
      thd    in     Thread context
3465
3807
      tables in/out List of tables which we were trying to open and lock
3466
3808
 
3467
3809
*/
3468
3810
 
3469
 
void close_tables_for_reopen(Session *session, TableList **tables)
 
3811
void close_tables_for_reopen(THD *thd, TableList **tables)
3470
3812
{
3471
3813
  /*
3472
3814
    If table list consists only from tables from prelocking set, table list
3473
3815
    for new attempt should be empty, so we have to update list's root pointer.
3474
3816
  */
3475
 
  if (session->lex->first_not_own_table() == *tables)
 
3817
  if (thd->lex->first_not_own_table() == *tables)
3476
3818
    *tables= 0;
3477
 
  session->lex->chop_off_not_own_tables();
 
3819
  thd->lex->chop_off_not_own_tables();
3478
3820
  for (TableList *tmp= *tables; tmp; tmp= tmp->next_global)
3479
3821
    tmp->table= 0;
3480
 
  close_thread_tables(session);
 
3822
  close_thread_tables(thd);
3481
3823
}
3482
3824
 
3483
3825
 
3486
3828
 
3487
3829
  SYNPOSIS
3488
3830
    open_temporary_table()
3489
 
    session               Thread object
 
3831
    thd           Thread object
3490
3832
    path          Path (without .frm)
3491
3833
    db            database
3492
3834
    table_name    Table name
3493
 
    link_in_list  1 if table should be linked into session->temporary_tables
 
3835
    link_in_list  1 if table should be linked into thd->temporary_tables
3494
3836
 
3495
3837
 NOTES:
3496
3838
    Used by alter_table to open a temporary table and when creating
3501
3843
   #  Table object
3502
3844
*/
3503
3845
 
3504
 
Table *open_temporary_table(Session *session, const char *path, const char *db,
 
3846
Table *open_temporary_table(THD *thd, const char *path, const char *db,
3505
3847
                            const char *table_name, bool link_in_list,
3506
3848
                            open_table_mode open_mode)
3507
3849
{
3508
3850
  Table *tmp_table;
3509
3851
  TABLE_SHARE *share;
3510
3852
  char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
3511
 
  uint32_t key_length, path_length;
 
3853
  uint32_t key_length;
3512
3854
  TableList table_list;
3513
3855
 
3514
3856
  table_list.db=         (char*) db;
3515
3857
  table_list.table_name= (char*) table_name;
3516
3858
  /* Create the cache_key for temporary tables */
3517
 
  key_length= create_table_def_key(session, cache_key, &table_list, 1);
3518
 
  path_length= strlen(path);
 
3859
  key_length= create_table_def_key(thd, cache_key, &table_list, 1);
3519
3860
 
3520
 
  if (!(tmp_table= (Table*) malloc(sizeof(*tmp_table) + sizeof(*share) +
3521
 
                                   path_length + 1 + key_length)))
3522
 
    return NULL;
 
3861
  if (!(tmp_table= (Table*) my_malloc(sizeof(*tmp_table) + sizeof(*share) +
 
3862
                                      strlen(path)+1 + key_length,
 
3863
                                      MYF(MY_WME))))
 
3864
    return(0);                          /* purecov: inspected */
3523
3865
 
3524
3866
  share= (TABLE_SHARE*) (tmp_table+1);
3525
3867
  tmp_path= (char*) (share+1);
3526
 
  saved_cache_key= strcpy(tmp_path, path)+path_length+1;
 
3868
  saved_cache_key= my_stpcpy(tmp_path, path)+1;
3527
3869
  memcpy(saved_cache_key, cache_key, key_length);
3528
3870
 
3529
 
  init_tmp_table_share(session, share, saved_cache_key, key_length,
 
3871
  init_tmp_table_share(thd, share, saved_cache_key, key_length,
3530
3872
                       strchr(saved_cache_key, '\0')+1, tmp_path);
3531
3873
 
3532
 
  if (open_table_def(session, share, 0) ||
3533
 
      open_table_from_share(session, share, table_name,
 
3874
  if (open_table_def(thd, share, 0) ||
 
3875
      open_table_from_share(thd, share, table_name,
3534
3876
                            (open_mode == OTM_ALTER) ? 0 :
3535
 
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
3877
                            (uint) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
3536
3878
                                    HA_GET_INDEX),
3537
3879
                            (open_mode == OTM_ALTER) ?
3538
3880
                              (EXTRA_RECORD | OPEN_FRM_FILE_ONLY)
3562
3904
  if (link_in_list)
3563
3905
  {
3564
3906
    /* growing temp list at the head */
3565
 
    tmp_table->next= session->temporary_tables;
 
3907
    tmp_table->next= thd->temporary_tables;
3566
3908
    if (tmp_table->next)
3567
3909
      tmp_table->next->prev= tmp_table;
3568
 
    session->temporary_tables= tmp_table;
3569
 
    session->temporary_tables->prev= 0;
 
3910
    thd->temporary_tables= tmp_table;
 
3911
    thd->temporary_tables->prev= 0;
 
3912
    if (thd->slave_thread)
 
3913
      slave_open_temp_tables++;
3570
3914
  }
3571
3915
  tmp_table->pos_in_table_list= 0;
3572
3916
  return(tmp_table);
3573
3917
}
3574
3918
 
3575
3919
 
3576
 
bool rm_temporary_table(handlerton *base, char *path)
 
3920
bool rm_temporary_table(handlerton *base, char *path, bool frm_only)
3577
3921
{
3578
3922
  bool error=0;
3579
3923
  handler *file;
 
3924
  char *ext;
3580
3925
 
3581
 
  if(delete_table_proto_file(path))
 
3926
  my_stpcpy(ext= strchr(path, '\0'), reg_ext);
 
3927
  if (my_delete(path,MYF(0)))
3582
3928
    error=1; /* purecov: inspected */
3583
 
 
3584
 
  file= get_new_handler((TABLE_SHARE*) 0, current_session->mem_root, base);
3585
 
  if (file && file->ha_delete_table(path))
 
3929
  *ext= 0;                              // remove extension
 
3930
  file= get_new_handler((TABLE_SHARE*) 0, current_thd->mem_root, base);
 
3931
  if (!frm_only && file && file->ha_delete_table(path))
3586
3932
  {
3587
3933
    error=1;
3588
 
    errmsg_printf(ERRMSG_LVL_WARN, _("Could not remove temporary table: '%s', error: %d"),
 
3934
    sql_print_warning(_("Could not remove temporary table: '%s', error: %d"),
3589
3935
                      path, my_errno);
3590
3936
  }
3591
3937
  delete file;
3604
3950
 
3605
3951
/* Special Field pointers as return values of find_field_in_XXX functions. */
3606
3952
Field *not_found_field= (Field*) 0x1;
3607
 
Field *view_ref_found= (Field*) 0x2;
 
3953
Field *view_ref_found= (Field*) 0x2; 
3608
3954
 
3609
3955
#define WRONG_GRANT (Field*) -1
3610
3956
 
3611
 
static void update_field_dependencies(Session *session, Field *field, Table *table)
 
3957
static void update_field_dependencies(THD *thd, Field *field, Table *table)
3612
3958
{
3613
 
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
 
3959
  if (thd->mark_used_columns != MARK_COLUMNS_NONE)
3614
3960
  {
3615
3961
    MY_BITMAP *current_bitmap, *other_bitmap;
3616
3962
 
3618
3964
      We always want to register the used keys, as the column bitmap may have
3619
3965
      been set for all fields (for example for view).
3620
3966
    */
3621
 
 
 
3967
      
3622
3968
    table->covering_keys.intersect(field->part_of_key);
3623
3969
    table->merge_keys.merge(field->part_of_key);
3624
3970
 
3625
 
    if (session->mark_used_columns == MARK_COLUMNS_READ)
 
3971
    if (thd->mark_used_columns == MARK_COLUMNS_READ)
3626
3972
    {
3627
3973
      current_bitmap= table->read_set;
3628
3974
      other_bitmap=   table->write_set;
3635
3981
 
3636
3982
    if (bitmap_fast_test_and_set(current_bitmap, field->field_index))
3637
3983
    {
3638
 
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
3639
 
        session->dup_field= field;
 
3984
      if (thd->mark_used_columns == MARK_COLUMNS_WRITE)
 
3985
        thd->dup_field= field;
3640
3986
      return;
3641
3987
    }
3642
3988
    if (table->get_fields_in_item_tree)
3654
4000
 
3655
4001
  SYNOPSIS
3656
4002
    find_field_in_natural_join()
3657
 
    session                      [in]  thread handler
 
4003
    thd                  [in]  thread handler
3658
4004
    table_ref            [in]  table reference to search
3659
4005
    name                 [in]  name of field
3660
4006
    length               [in]  length of name
3679
4025
*/
3680
4026
 
3681
4027
static Field *
3682
 
find_field_in_natural_join(Session *session, TableList *table_ref,
3683
 
                           const char *name, uint32_t , Item **,
3684
 
                           bool, TableList **actual_table)
 
4028
find_field_in_natural_join(THD *thd, TableList *table_ref, const char *name,
 
4029
                           uint32_t length __attribute__((unused)),
 
4030
                           Item **ref __attribute__((unused)), bool register_tree_change __attribute__((unused)),
 
4031
                           TableList **actual_table)
3685
4032
{
3686
4033
  List_iterator_fast<Natural_join_column>
3687
4034
    field_it(*(table_ref->join_columns));
3691
4038
  assert(table_ref->is_natural_join && table_ref->join_columns);
3692
4039
  assert(*actual_table == NULL);
3693
4040
 
3694
 
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col;
 
4041
  for (nj_col= NULL, curr_nj_col= field_it++; curr_nj_col; 
3695
4042
       curr_nj_col= field_it++)
3696
4043
  {
3697
4044
    if (!my_strcasecmp(system_charset_info, curr_nj_col->name(), name))
3698
4045
    {
3699
4046
      if (nj_col)
3700
4047
      {
3701
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
 
4048
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, thd->where);
3702
4049
        return(NULL);
3703
4050
      }
3704
4051
      nj_col= curr_nj_col;
3710
4057
    /* This is a base table. */
3711
4058
    assert(nj_col->table_ref->table == nj_col->table_field->table);
3712
4059
    found_field= nj_col->table_field;
3713
 
    update_field_dependencies(session, found_field, nj_col->table_ref->table);
 
4060
    update_field_dependencies(thd, found_field, nj_col->table_ref->table);
3714
4061
  }
3715
4062
 
3716
4063
  *actual_table= nj_col->table_ref;
3717
 
 
 
4064
  
3718
4065
  return(found_field);
3719
4066
}
3720
4067
 
3724
4071
 
3725
4072
  SYNOPSIS
3726
4073
    find_field_in_table()
3727
 
    session                             thread handler
 
4074
    thd                         thread handler
3728
4075
    table                       table where to search for the field
3729
4076
    name                        name of field
3730
4077
    length                      length of name
3738
4085
*/
3739
4086
 
3740
4087
Field *
3741
 
find_field_in_table(Session *session, Table *table, const char *name, uint32_t length,
 
4088
find_field_in_table(THD *thd, Table *table, const char *name, uint32_t length,
3742
4089
                    bool allow_rowid, uint32_t *cached_field_index_ptr)
3743
4090
{
3744
4091
  Field **field_ptr, *field;
3773
4120
 
3774
4121
  if (field_ptr && *field_ptr)
3775
4122
  {
3776
 
    if ((*field_ptr)->vcol_info)
3777
 
    {
3778
 
      if (session->mark_used_columns != MARK_COLUMNS_NONE)
3779
 
      {
3780
 
        Item *vcol_item= (*field_ptr)->vcol_info->expr_item;
3781
 
        assert(vcol_item);
3782
 
        vcol_item->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
3783
 
        /*
3784
 
          Set the virtual field for write here if
3785
 
          1) this procedure is called for a read-only operation (SELECT), and
3786
 
          2) the virtual column is not phycically stored in the table
3787
 
        */
3788
 
        if ((session->mark_used_columns != MARK_COLUMNS_WRITE) &&
3789
 
            (not (*field_ptr)->is_stored))
3790
 
          bitmap_set_bit((*field_ptr)->table->write_set, (*field_ptr)->field_index);
3791
 
      }
3792
 
    }
3793
4123
    *cached_field_index_ptr= field_ptr - table->field;
3794
4124
    field= *field_ptr;
3795
4125
  }
3802
4132
    field= table->field[table->s->rowid_field_offset-1];
3803
4133
  }
3804
4134
 
3805
 
  update_field_dependencies(session, field, table);
 
4135
  update_field_dependencies(thd, field, table);
3806
4136
 
3807
4137
  return(field);
3808
4138
}
3813
4143
 
3814
4144
  SYNOPSIS
3815
4145
    find_field_in_table_ref()
3816
 
    session                        [in]  thread handler
 
4146
    thd                    [in]  thread handler
3817
4147
    table_list             [in]  table reference to search
3818
4148
    name                   [in]  name of field
3819
4149
    length                 [in]  field length of name
3851
4181
*/
3852
4182
 
3853
4183
Field *
3854
 
find_field_in_table_ref(Session *session, TableList *table_list,
 
4184
find_field_in_table_ref(THD *thd, TableList *table_list,
3855
4185
                        const char *name, uint32_t length,
3856
4186
                        const char *item_name, const char *db_name,
3857
4187
                        const char *table_name, Item **ref,
3883
4213
          something !
3884
4214
  */
3885
4215
  if (/* Exclude nested joins. */
3886
 
      (!table_list->nested_join) &&
 
4216
      (!table_list->nested_join ||
3887
4217
       /* Include merge views and information schema tables. */
 
4218
       table_list->field_translation) &&
3888
4219
      /*
3889
4220
        Test if the field qualifiers match the table reference we plan
3890
4221
        to search.
3897
4228
 
3898
4229
  *actual_table= NULL;
3899
4230
 
3900
 
  if (!table_list->nested_join)
 
4231
  if (table_list->field_translation)
 
4232
  {
 
4233
  }
 
4234
  else if (!table_list->nested_join)
3901
4235
  {
3902
4236
    /* 'table_list' is a stored table. */
3903
4237
    assert(table_list->table);
3904
 
    if ((fld= find_field_in_table(session, table_list->table, name, length,
 
4238
    if ((fld= find_field_in_table(thd, table_list->table, name, length,
3905
4239
                                  allow_rowid,
3906
4240
                                  cached_field_index_ptr)))
3907
4241
      *actual_table= table_list;
3921
4255
      TableList *table;
3922
4256
      while ((table= it++))
3923
4257
      {
3924
 
        if ((fld= find_field_in_table_ref(session, table, name, length, item_name,
 
4258
        if ((fld= find_field_in_table_ref(thd, table, name, length, item_name,
3925
4259
                                          db_name, table_name, ref,
3926
4260
                                          check_privileges, allow_rowid,
3927
4261
                                          cached_field_index_ptr,
3936
4270
      natural join, thus if the field is not qualified, we will search
3937
4271
      directly the top-most NATURAL/USING join.
3938
4272
    */
3939
 
    fld= find_field_in_natural_join(session, table_list, name, length, ref,
 
4273
    fld= find_field_in_natural_join(thd, table_list, name, length, ref,
3940
4274
                                    register_tree_change, actual_table);
3941
4275
  }
3942
4276
 
3943
4277
  if (fld)
3944
4278
  {
3945
 
      if (session->mark_used_columns != MARK_COLUMNS_NONE)
 
4279
      if (thd->mark_used_columns != MARK_COLUMNS_NONE)
3946
4280
      {
3947
4281
        /*
3948
4282
          Get rw_set correct for this field so that the handler
3957
4291
            field_to_set= ((Item_field*)it)->field;
3958
4292
          else
3959
4293
          {
3960
 
            if (session->mark_used_columns == MARK_COLUMNS_READ)
 
4294
            if (thd->mark_used_columns == MARK_COLUMNS_READ)
3961
4295
              it->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
3962
4296
          }
3963
4297
        }
3966
4300
        if (field_to_set)
3967
4301
        {
3968
4302
          Table *table= field_to_set->table;
3969
 
          if (session->mark_used_columns == MARK_COLUMNS_READ)
 
4303
          if (thd->mark_used_columns == MARK_COLUMNS_READ)
3970
4304
            bitmap_set_bit(table->read_set, field_to_set->field_index);
3971
4305
          else
3972
4306
            bitmap_set_bit(table->write_set, field_to_set->field_index);
4028
4362
 
4029
4363
  SYNOPSIS
4030
4364
    find_field_in_tables()
4031
 
    session                       pointer to current thread structure
 
4365
    thd                   pointer to current thread structure
4032
4366
    item                  field item that should be found
4033
4367
    first_table           list of tables to be searched for item
4034
4368
    last_table            end of the list of tables to search for item. If NULL
4058
4392
*/
4059
4393
 
4060
4394
Field *
4061
 
find_field_in_tables(Session *session, Item_ident *item,
 
4395
find_field_in_tables(THD *thd, Item_ident *item,
4062
4396
                     TableList *first_table, TableList *last_table,
4063
4397
                     Item **ref, find_item_error_report_type report_error,
4064
4398
                     bool check_privileges, bool register_tree_change)
4067
4401
  const char *db= item->db_name;
4068
4402
  const char *table_name= item->table_name;
4069
4403
  const char *name= item->field_name;
4070
 
  uint32_t length=(uint32_t) strlen(name);
 
4404
  uint32_t length=(uint) strlen(name);
4071
4405
  char name_buff[NAME_LEN+1];
4072
4406
  TableList *cur_table= first_table;
4073
4407
  TableList *actual_table;
4099
4433
      when table_ref->field_translation != NULL.
4100
4434
      */
4101
4435
    if (table_ref->table)
4102
 
      found= find_field_in_table(session, table_ref->table, name, length,
 
4436
      found= find_field_in_table(thd, table_ref->table, name, length,
4103
4437
                                 true, &(item->cached_field_index));
4104
4438
    else
4105
 
      found= find_field_in_table_ref(session, table_ref, name, length, item->name,
 
4439
      found= find_field_in_table_ref(thd, table_ref, name, length, item->name,
4106
4440
                                     NULL, NULL, ref, check_privileges,
4107
4441
                                     true, &(item->cached_field_index),
4108
4442
                                     register_tree_change,
4117
4451
        fields.
4118
4452
      */
4119
4453
      {
4120
 
        Select_Lex *current_sel= session->lex->current_select;
4121
 
        Select_Lex *last_select= table_ref->select_lex;
 
4454
        SELECT_LEX *current_sel= thd->lex->current_select;
 
4455
        SELECT_LEX *last_select= table_ref->select_lex;
4122
4456
        /*
4123
4457
          If the field was an outer referencee, mark all selects using this
4124
4458
          sub query as dependent on the outer query
4125
4459
        */
4126
4460
        if (current_sel != last_select)
4127
 
          mark_select_range_as_dependent(session, last_select, current_sel,
 
4461
          mark_select_range_as_dependent(thd, last_select, current_sel,
4128
4462
                                         found, *ref, item);
4129
4463
      }
4130
4464
      return found;
4138
4472
      We can't do this in Item_field as this would change the
4139
4473
      'name' of the item which may be used in the select list
4140
4474
    */
4141
 
    strncpy(name_buff, db, sizeof(name_buff)-1);
 
4475
    strmake(name_buff, db, sizeof(name_buff)-1);
4142
4476
    my_casedn_str(files_charset_info, name_buff);
4143
4477
    db= name_buff;
4144
4478
  }
4149
4483
  for (; cur_table != last_table ;
4150
4484
       cur_table= cur_table->next_name_resolution_table)
4151
4485
  {
4152
 
    Field *cur_field= find_field_in_table_ref(session, cur_table, name, length,
 
4486
    Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,
4153
4487
                                              item->name, db, table_name, ref,
4154
 
                                              (session->lex->sql_command ==
 
4488
                                              (thd->lex->sql_command ==
4155
4489
                                               SQLCOM_SHOW_FIELDS)
4156
4490
                                              ? false : check_privileges,
4157
4491
                                              allow_rowid,
4162
4496
    {
4163
4497
      if (cur_field == WRONG_GRANT)
4164
4498
      {
4165
 
        if (session->lex->sql_command != SQLCOM_SHOW_FIELDS)
 
4499
        if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)
4166
4500
          return (Field*) 0;
4167
4501
 
4168
 
        session->clear_error();
4169
 
        cur_field= find_field_in_table_ref(session, cur_table, name, length,
 
4502
        thd->clear_error();
 
4503
        cur_field= find_field_in_table_ref(thd, cur_table, name, length,
4170
4504
                                           item->name, db, table_name, ref,
4171
4505
                                           false,
4172
4506
                                           allow_rowid,
4190
4524
      item->cached_table= (!actual_table->cacheable_table || found) ?
4191
4525
                          0 : actual_table;
4192
4526
 
4193
 
      assert(session->where);
 
4527
      assert(thd->where);
4194
4528
      /*
4195
4529
        If we found a fully qualified field we return it directly as it can't
4196
4530
        have duplicates.
4203
4537
        if (report_error == REPORT_ALL_ERRORS ||
4204
4538
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
4205
4539
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
4206
 
                   table_name ? item->full_name() : name, session->where);
 
4540
                   table_name ? item->full_name() : name, thd->where);
4207
4541
        return (Field*) 0;
4208
4542
      }
4209
4543
      found= cur_field;
4227
4561
    char buff[NAME_LEN*2+1];
4228
4562
    if (db && db[0])
4229
4563
    {
4230
 
      /* We're in an error condition, two extra strlen's aren't going
4231
 
       * to kill us */
4232
 
      assert(strlen(db) <= NAME_LEN);
4233
 
      assert(strlen(table_name) <= NAME_LEN);
4234
 
      strcpy(buff, db);
4235
 
      strcat(buff,".");
4236
 
      strcat(buff, table_name);
 
4564
      strxnmov(buff,sizeof(buff)-1,db,".",table_name,NULL);
4237
4565
      table_name=buff;
4238
4566
    }
4239
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
 
4567
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);
4240
4568
  }
4241
4569
  else
4242
4570
  {
4243
4571
    if (report_error == REPORT_ALL_ERRORS ||
4244
4572
        report_error == REPORT_EXCEPT_NON_UNIQUE)
4245
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
 
4573
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);
4246
4574
    else
4247
4575
      found= not_found_field;
4248
4576
  }
4267
4595
                                return not_found_item, report other errors,
4268
4596
                                return 0
4269
4597
      IGNORE_ERRORS             Do not report errors, return 0 if error
4270
 
    resolution                  Set to the resolution type if the item is found
4271
 
                                (it says whether the item is resolved
 
4598
    resolution                  Set to the resolution type if the item is found 
 
4599
                                (it says whether the item is resolved 
4272
4600
                                 against an alias name,
4273
4601
                                 or as a field name without alias,
4274
4602
                                 or as a field hidden by alias,
4275
4603
                                 or ignoring alias)
4276
 
 
 
4604
                                
4277
4605
  RETURN VALUES
4278
4606
    0                   Item is not found or item is not unique,
4279
4607
                        error message is reported
4307
4635
 
4308
4636
  *resolution= NOT_RESOLVED;
4309
4637
 
4310
 
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  ||
 
4638
  is_ref_by_name= (find->type() == Item::FIELD_ITEM  || 
4311
4639
                   find->type() == Item::REF_ITEM);
4312
4640
  if (is_ref_by_name)
4313
4641
  {
4324
4652
 
4325
4653
      /*
4326
4654
        In case of group_concat() with ORDER BY condition in the QUERY
4327
 
        item_field can be field of temporary table without item name
 
4655
        item_field can be field of temporary table without item name 
4328
4656
        (if this field created from expression argument of group_concat()),
4329
4657
        => we have to check presence of name before compare
4330
 
      */
 
4658
      */ 
4331
4659
      if (!item_field->name)
4332
4660
        continue;
4333
4661
 
4352
4680
        if (item_field->field_name && item_field->table_name &&
4353
4681
            !my_strcasecmp(system_charset_info, item_field->field_name,
4354
4682
                           field_name) &&
4355
 
            !my_strcasecmp(table_alias_charset, item_field->table_name,
 
4683
            !my_strcasecmp(table_alias_charset, item_field->table_name, 
4356
4684
                           table_name) &&
4357
4685
            (!db_name || (item_field->db_name &&
4358
4686
                          !strcmp(item_field->db_name, db_name))))
4368
4696
            */
4369
4697
            if (report_error != IGNORE_ERRORS)
4370
4698
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
4371
 
                       find->full_name(), current_session->where);
 
4699
                       find->full_name(), current_thd->where);
4372
4700
            return (Item**) 0;
4373
4701
          }
4374
4702
          found_unaliased= li.ref();
4399
4727
              continue;                           // Same field twice
4400
4728
            if (report_error != IGNORE_ERRORS)
4401
4729
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
4402
 
                       find->full_name(), current_session->where);
 
4730
                       find->full_name(), current_thd->where);
4403
4731
            return (Item**) 0;
4404
4732
          }
4405
4733
          found= li.ref();
4427
4755
      }
4428
4756
    }
4429
4757
    else if (!table_name)
4430
 
    {
 
4758
    { 
4431
4759
      if (is_ref_by_name && find->name && item->name &&
4432
4760
          !my_strcasecmp(system_charset_info,item->name,find->name))
4433
4761
      {
4444
4772
        break;
4445
4773
      }
4446
4774
    }
 
4775
    else if (table_name && item->type() == Item::REF_ITEM &&
 
4776
             ((Item_ref *)item)->ref_type() == Item_ref::VIEW_REF)
 
4777
    {
 
4778
      /*
 
4779
        TODO:Here we process prefixed view references only. What we should 
 
4780
        really do is process all types of Item_refs. But this will currently 
 
4781
        lead to a clash with the way references to outer SELECTs (from the 
 
4782
        HAVING clause) are handled in e.g. :
 
4783
        SELECT 1 FROM t1 AS t1_o GROUP BY a
 
4784
          HAVING (SELECT t1_o.a FROM t1 AS t1_i GROUP BY t1_i.a LIMIT 1).
 
4785
        Processing all Item_refs here will cause t1_o.a to resolve to itself.
 
4786
        We still need to process the special case of Item_direct_view_ref 
 
4787
        because in the context of views they have the same meaning as 
 
4788
        Item_field for tables.
 
4789
      */
 
4790
      Item_ident *item_ref= (Item_ident *) item;
 
4791
      if (item_ref->name && item_ref->table_name &&
 
4792
          !my_strcasecmp(system_charset_info, item_ref->name, field_name) &&
 
4793
          !my_strcasecmp(table_alias_charset, item_ref->table_name,
 
4794
                         table_name) &&
 
4795
          (!db_name || (item_ref->db_name && 
 
4796
                        !strcmp (item_ref->db_name, db_name))))
 
4797
      {
 
4798
        found= li.ref();
 
4799
        *counter= i;
 
4800
        *resolution= RESOLVED_IGNORING_ALIAS;
 
4801
        break;
 
4802
      }
 
4803
    }
4447
4804
  }
4448
4805
  if (!found)
4449
4806
  {
4451
4808
    {
4452
4809
      if (report_error != IGNORE_ERRORS)
4453
4810
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
4454
 
                 find->full_name(), current_session->where);
 
4811
                 find->full_name(), current_thd->where);
4455
4812
      return (Item **) 0;
4456
4813
    }
4457
4814
    if (found_unaliased)
4467
4824
  {
4468
4825
    if (report_error == REPORT_ALL_ERRORS)
4469
4826
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
4470
 
               find->full_name(), current_session->where);
 
4827
               find->full_name(), current_thd->where);
4471
4828
    return (Item **) 0;
4472
4829
  }
4473
4830
  else
4515
4872
 
4516
4873
  SYNOPSIS
4517
4874
    set_new_item_local_context()
4518
 
    session        pointer to current thread
 
4875
    thd        pointer to current thread
4519
4876
    item       item for which new context is created and set
4520
4877
    table_ref  table ref where an item showld be resolved
4521
4878
 
4529
4886
*/
4530
4887
 
4531
4888
static bool
4532
 
set_new_item_local_context(Session *session, Item_ident *item, TableList *table_ref)
 
4889
set_new_item_local_context(THD *thd, Item_ident *item, TableList *table_ref)
4533
4890
{
4534
4891
  Name_resolution_context *context;
4535
 
  if (!(context= new (session->mem_root) Name_resolution_context))
 
4892
  if (!(context= new (thd->mem_root) Name_resolution_context))
4536
4893
    return true;
4537
4894
  context->init();
4538
4895
  context->first_name_resolution_table=
4547
4904
 
4548
4905
  SYNOPSIS
4549
4906
    mark_common_columns()
4550
 
    session                [in] current thread
 
4907
    thd                [in] current thread
4551
4908
    table_ref_1        [in] the first (left) join operand
4552
4909
    table_ref_2        [in] the second (right) join operand
4553
4910
    using_fields       [in] if the join is JOIN...USING - the join columns,
4574
4931
*/
4575
4932
 
4576
4933
static bool
4577
 
mark_common_columns(Session *session, TableList *table_ref_1, TableList *table_ref_2,
 
4934
mark_common_columns(THD *thd, TableList *table_ref_1, TableList *table_ref_2,
4578
4935
                    List<String> *using_fields, uint32_t *found_using_fields)
4579
4936
{
4580
4937
  Field_iterator_table_ref it_1, it_2;
4603
4960
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
4604
4961
      goto err;
4605
4962
    field_name_1= nj_col_1->name();
4606
 
    is_using_column_1= using_fields &&
 
4963
    is_using_column_1= using_fields && 
4607
4964
      test_if_string_in_list(field_name_1, using_fields);
4608
4965
 
4609
4966
    /*
4630
4987
        (then cur_nj_col_2->is_common == true).
4631
4988
        Note that it is too early to check the columns outside of the
4632
4989
        USING list for ambiguity because they are not actually "referenced"
4633
 
        here. These columns must be checked only on unqualified reference
 
4990
        here. These columns must be checked only on unqualified reference 
4634
4991
        by name (e.g. in SELECT list).
4635
4992
      */
4636
4993
      if (!my_strcasecmp(system_charset_info, field_name_1, cur_field_name_2))
4638
4995
        if (cur_nj_col_2->is_common ||
4639
4996
            (found && (!using_fields || is_using_column_1)))
4640
4997
        {
4641
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
 
4998
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, thd->where);
4642
4999
          goto err;
4643
5000
        }
4644
5001
        nj_col_2= cur_nj_col_2;
4664
5021
    */
4665
5022
    if (nj_col_2 && (!using_fields ||is_using_column_1))
4666
5023
    {
4667
 
      Item *item_1=   nj_col_1->create_item(session);
4668
 
      Item *item_2=   nj_col_2->create_item(session);
 
5024
      Item *item_1=   nj_col_1->create_item(thd);
 
5025
      Item *item_2=   nj_col_2->create_item(thd);
4669
5026
      Field *field_1= nj_col_1->field();
4670
5027
      Field *field_2= nj_col_2->field();
4671
5028
      Item_ident *item_ident_1, *item_ident_2;
4695
5052
        resolution of these items, and to enable proper name resolution of
4696
5053
        the items during the execute phase of PS.
4697
5054
      */
4698
 
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
4699
 
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
 
5055
      if (set_new_item_local_context(thd, item_ident_1, nj_col_1->table_ref) ||
 
5056
          set_new_item_local_context(thd, item_ident_2, nj_col_2->table_ref))
4700
5057
        goto err;
4701
5058
 
4702
5059
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
4757
5114
 
4758
5115
  SYNOPSIS
4759
5116
    store_natural_using_join_columns()
4760
 
    session                current thread
 
5117
    thd                current thread
4761
5118
    natural_using_join the table reference of the NATURAL/USING join
4762
5119
    table_ref_1        the first (left) operand (of a NATURAL/USING join).
4763
5120
    table_ref_2        the second (right) operand (of a NATURAL/USING join).
4788
5145
*/
4789
5146
 
4790
5147
static bool
4791
 
store_natural_using_join_columns(Session *,
 
5148
store_natural_using_join_columns(THD *thd __attribute__((unused)),
4792
5149
                                 TableList *natural_using_join,
4793
5150
                                 TableList *table_ref_1,
4794
5151
                                 TableList *table_ref_2,
4842
5199
        if (!(common_field= it++))
4843
5200
        {
4844
5201
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
4845
 
                   current_session->where);
 
5202
                   current_thd->where);
4846
5203
          goto err;
4847
5204
        }
4848
5205
        if (!my_strcasecmp(system_charset_info,
4881
5238
 
4882
5239
  SYNOPSIS
4883
5240
    store_top_level_join_columns()
4884
 
    session            current thread
 
5241
    thd            current thread
4885
5242
    table_ref      nested join or table in a FROM clause
4886
5243
    left_neighbor  neighbor table reference to the left of table_ref at the
4887
5244
                   same level in the join tree
4893
5250
    and materializes the row types of NATURAL/USING joins in a
4894
5251
    bottom-up manner until it reaches the TableList elements that
4895
5252
    represent the top-most NATURAL/USING joins. The procedure should be
4896
 
    applied to each element of Select_Lex::top_join_list (i.e. to each
 
5253
    applied to each element of SELECT_LEX::top_join_list (i.e. to each
4897
5254
    top-level element of the FROM clause).
4898
5255
 
4899
5256
  IMPLEMENTATION
4907
5264
*/
4908
5265
 
4909
5266
static bool
4910
 
store_top_level_join_columns(Session *session, TableList *table_ref,
 
5267
store_top_level_join_columns(THD *thd, TableList *table_ref,
4911
5268
                             TableList *left_neighbor,
4912
5269
                             TableList *right_neighbor)
4913
5270
{
4955
5312
                           same_level_right_neighbor : right_neighbor;
4956
5313
 
4957
5314
      if (cur_table_ref->nested_join &&
4958
 
          store_top_level_join_columns(session, cur_table_ref,
 
5315
          store_top_level_join_columns(thd, cur_table_ref,
4959
5316
                                       real_left_neighbor, real_right_neighbor))
4960
5317
        goto err;
4961
5318
      same_level_right_neighbor= cur_table_ref;
4987
5344
    */
4988
5345
    if (table_ref_2->outer_join & JOIN_TYPE_RIGHT)
4989
5346
      std::swap(table_ref_1, table_ref_2);
4990
 
    if (mark_common_columns(session, table_ref_1, table_ref_2,
 
5347
    if (mark_common_columns(thd, table_ref_1, table_ref_2,
4991
5348
                            using_fields, &found_using_fields))
4992
5349
      goto err;
4993
5350
 
4998
5355
    */
4999
5356
    if (table_ref_1->outer_join & JOIN_TYPE_RIGHT)
5000
5357
      std::swap(table_ref_1, table_ref_2);
5001
 
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
 
5358
    if (store_natural_using_join_columns(thd, table_ref, table_ref_1,
5002
5359
                                         table_ref_2, using_fields,
5003
5360
                                         found_using_fields))
5004
5361
      goto err;
5045
5402
 
5046
5403
  SYNOPSIS
5047
5404
    setup_natural_join_row_types()
5048
 
    session          current thread
 
5405
    thd          current thread
5049
5406
    from_clause  list of top-level table references in a FROM clause
5050
5407
 
5051
5408
  DESCRIPTION
5063
5420
    true   Error
5064
5421
    false  OK
5065
5422
*/
5066
 
static bool setup_natural_join_row_types(Session *session,
 
5423
static bool setup_natural_join_row_types(THD *thd,
5067
5424
                                         List<TableList> *from_clause,
5068
5425
                                         Name_resolution_context *context)
5069
5426
{
5070
 
  session->where= "from clause";
 
5427
  thd->where= "from clause";
5071
5428
  if (from_clause->elements == 0)
5072
5429
    return false; /* We come here in the case of UNIONs. */
5073
5430
 
5083
5440
  {
5084
5441
    table_ref= left_neighbor;
5085
5442
    left_neighbor= table_ref_it++;
5086
 
    if (store_top_level_join_columns(session, table_ref,
 
5443
    if (store_top_level_join_columns(thd, table_ref,
5087
5444
                                     left_neighbor, right_neighbor))
5088
5445
      return true;
5089
5446
    if (left_neighbor)
5113
5470
** Expand all '*' in given fields
5114
5471
****************************************************************************/
5115
5472
 
5116
 
int setup_wild(Session *session,
5117
 
               TableList *,
 
5473
int setup_wild(THD *thd,
 
5474
               TableList *tables __attribute__((unused)),
5118
5475
               List<Item> &fields,
5119
5476
               List<Item> *sum_func_list,
5120
5477
               uint32_t wild_num)
5125
5482
  Item *item;
5126
5483
  List_iterator<Item> it(fields);
5127
5484
 
5128
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
5485
  thd->lex->current_select->cur_pos_in_select_list= 0;
5129
5486
  while (wild_num && (item= it++))
5130
5487
  {
5131
5488
    if (item->type() == Item::FIELD_ITEM &&
5135
5492
    {
5136
5493
      uint32_t elem= fields.elements;
5137
5494
      bool any_privileges= ((Item_field *) item)->any_privileges;
5138
 
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
 
5495
      Item_subselect *subsel= thd->lex->current_select->master_unit()->item;
5139
5496
      if (subsel &&
5140
5497
          subsel->substype() == Item_subselect::EXISTS_SUBS)
5141
5498
      {
5147
5504
        it.replace(new Item_int("Not_used", (int64_t) 1,
5148
5505
                                MY_INT64_NUM_DECIMAL_DIGITS));
5149
5506
      }
5150
 
      else if (insert_fields(session, ((Item_field*) item)->context,
 
5507
      else if (insert_fields(thd, ((Item_field*) item)->context,
5151
5508
                             ((Item_field*) item)->db_name,
5152
5509
                             ((Item_field*) item)->table_name, &it,
5153
5510
                             any_privileges))
5166
5523
      wild_num--;
5167
5524
    }
5168
5525
    else
5169
 
      session->lex->current_select->cur_pos_in_select_list++;
 
5526
      thd->lex->current_select->cur_pos_in_select_list++;
5170
5527
  }
5171
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
5528
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
5172
5529
  return(0);
5173
5530
}
5174
5531
 
5176
5533
** Check that all given fields exists and fill struct with current data
5177
5534
****************************************************************************/
5178
5535
 
5179
 
bool setup_fields(Session *session, Item **ref_pointer_array,
 
5536
bool setup_fields(THD *thd, Item **ref_pointer_array,
5180
5537
                  List<Item> &fields, enum_mark_columns mark_used_columns,
5181
5538
                  List<Item> *sum_func_list, bool allow_sum_func)
5182
5539
{
5183
5540
  register Item *item;
5184
 
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
5185
 
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
5541
  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
 
5542
  nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
5186
5543
  List_iterator<Item> it(fields);
5187
5544
  bool save_is_item_list_lookup;
5188
5545
 
5189
 
  session->mark_used_columns= mark_used_columns;
 
5546
  thd->mark_used_columns= mark_used_columns;
5190
5547
  if (allow_sum_func)
5191
 
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
5192
 
  session->where= Session::DEFAULT_WHERE;
5193
 
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
5194
 
  session->lex->current_select->is_item_list_lookup= 0;
 
5548
    thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
 
5549
  thd->where= THD::DEFAULT_WHERE;
 
5550
  save_is_item_list_lookup= thd->lex->current_select->is_item_list_lookup;
 
5551
  thd->lex->current_select->is_item_list_lookup= 0;
5195
5552
 
5196
5553
  /*
5197
5554
    To prevent fail on forward lookup we fill it with zerows,
5208
5565
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
5209
5566
 
5210
5567
  Item **ref= ref_pointer_array;
5211
 
  session->lex->current_select->cur_pos_in_select_list= 0;
 
5568
  thd->lex->current_select->cur_pos_in_select_list= 0;
5212
5569
  while ((item= it++))
5213
5570
  {
5214
 
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
 
5571
    if ((!item->fixed && item->fix_fields(thd, it.ref())) || (item= *(it.ref()))->check_cols(1))
5215
5572
    {
5216
 
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
5217
 
      session->lex->allow_sum_func= save_allow_sum_func;
5218
 
      session->mark_used_columns= save_mark_used_columns;
 
5573
      thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
5574
      thd->lex->allow_sum_func= save_allow_sum_func;
 
5575
      thd->mark_used_columns= save_mark_used_columns;
5219
5576
      return(true); /* purecov: inspected */
5220
5577
    }
5221
5578
    if (ref)
5222
5579
      *(ref++)= item;
5223
5580
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM &&
5224
5581
        sum_func_list)
5225
 
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
5226
 
    session->used_tables|= item->used_tables();
5227
 
    session->lex->current_select->cur_pos_in_select_list++;
 
5582
      item->split_sum_func(thd, ref_pointer_array, *sum_func_list);
 
5583
    thd->used_tables|= item->used_tables();
 
5584
    thd->lex->current_select->cur_pos_in_select_list++;
5228
5585
  }
5229
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
5230
 
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
 
5586
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
5587
  thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
5231
5588
 
5232
 
  session->lex->allow_sum_func= save_allow_sum_func;
5233
 
  session->mark_used_columns= save_mark_used_columns;
5234
 
  return(test(session->is_error()));
 
5589
  thd->lex->allow_sum_func= save_allow_sum_func;
 
5590
  thd->mark_used_columns= save_mark_used_columns;
 
5591
  return(test(thd->is_error()));
5235
5592
}
5236
5593
 
5237
5594
 
5263
5620
 
5264
5621
  SYNOPSIS
5265
5622
    setup_tables()
5266
 
    session               Thread handler
 
5623
    thd           Thread handler
5267
5624
    context       name resolution contest to setup table list there
5268
5625
    from_clause   Top-level list of table references in the FROM clause
5269
5626
    tables        Table list (select_lex->table_list)
5286
5643
    true  error
5287
5644
*/
5288
5645
 
5289
 
bool setup_tables(Session *session, Name_resolution_context *context,
 
5646
bool setup_tables(THD *thd, Name_resolution_context *context,
5290
5647
                  List<TableList> *from_clause, TableList *tables,
5291
5648
                  TableList **leaves, bool select_insert)
5292
5649
{
5293
5650
  uint32_t tablenr= 0;
5294
5651
 
5295
 
  assert ((select_insert && !tables->next_name_resolution_table) || !tables ||
 
5652
  assert ((select_insert && !tables->next_name_resolution_table) || !tables || 
5296
5653
               (context->table_list && context->first_name_resolution_table));
5297
5654
  /*
5298
5655
    this is used for INSERT ... SELECT.
5318
5675
      first_select_table= 0;
5319
5676
      tablenr= 0;
5320
5677
    }
5321
 
    table->setup_table_map(table_list, tablenr);
 
5678
    setup_table_map(table, table_list, tablenr);
5322
5679
    if (table_list->process_index_hints(table))
5323
5680
      return(1);
5324
5681
  }
5329
5686
  }
5330
5687
 
5331
5688
  /* Precompute and store the row types of NATURAL/USING joins. */
5332
 
  if (setup_natural_join_row_types(session, from_clause, context))
 
5689
  if (setup_natural_join_row_types(thd, from_clause, context))
5333
5690
    return(1);
5334
5691
 
5335
5692
  return(0);
5341
5698
 
5342
5699
  SYNOPSIS
5343
5700
    setup_tables_and_check_view_access()
5344
 
    session               Thread handler
 
5701
    thd           Thread handler
5345
5702
    context       name resolution contest to setup table list there
5346
5703
    from_clause   Top-level list of table references in the FROM clause
5347
5704
    tables        Table list (select_lex->table_list)
5359
5716
    false ok;  In this case *map will include the chosen index
5360
5717
    true  error
5361
5718
*/
5362
 
bool setup_tables_and_check_access(Session *session,
 
5719
bool setup_tables_and_check_access(THD *thd, 
5363
5720
                                   Name_resolution_context *context,
5364
5721
                                   List<TableList> *from_clause,
5365
5722
                                   TableList *tables,
5369
5726
  TableList *leaves_tmp= NULL;
5370
5727
  bool first_table= true;
5371
5728
 
5372
 
  if (setup_tables(session, context, from_clause, tables,
 
5729
  if (setup_tables(thd, context, from_clause, tables,
5373
5730
                   &leaves_tmp, select_insert))
5374
5731
    return true;
5375
5732
 
5429
5786
 
5430
5787
  SYNOPSIS
5431
5788
    insert_fields()
5432
 
    session                     Thread handler
 
5789
    thd                 Thread handler
5433
5790
    context             Context for name resolution
5434
5791
    db_name             Database name in case of 'database_name.table_name.*'
5435
5792
    table_name          Table name in case of 'table_name.*'
5443
5800
*/
5444
5801
 
5445
5802
bool
5446
 
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
 
5803
insert_fields(THD *thd, Name_resolution_context *context, const char *db_name,
5447
5804
              const char *table_name, List_iterator<Item> *it,
5448
 
              bool )
 
5805
              bool any_privileges __attribute__((unused)))
5449
5806
{
5450
5807
  Field_iterator_table_ref field_iterator;
5451
5808
  bool found;
5458
5815
      We can't do this in Item_field as this would change the
5459
5816
      'name' of the item which may be used in the select list
5460
5817
    */
5461
 
    strncpy(name_buff, db_name, sizeof(name_buff)-1);
 
5818
    strmake(name_buff, db_name, sizeof(name_buff)-1);
5462
5819
    my_casedn_str(files_charset_info, name_buff);
5463
5820
    db_name= name_buff;
5464
5821
  }
5482
5839
 
5483
5840
    assert(tables->is_leaf_for_name_resolution());
5484
5841
 
5485
 
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
 
5842
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) || 
5486
5843
        (db_name && strcmp(tables->db,db_name)))
5487
5844
      continue;
5488
5845
 
5491
5848
      views and natural joins this update is performed inside the loop below.
5492
5849
    */
5493
5850
    if (table)
5494
 
      session->used_tables|= table->map;
 
5851
      thd->used_tables|= table->map;
5495
5852
 
5496
5853
    /*
5497
5854
      Initialize a generic field iterator for the current table reference.
5505
5862
    {
5506
5863
      Item *item;
5507
5864
 
5508
 
      if (!(item= field_iterator.create_item(session)))
 
5865
      if (!(item= field_iterator.create_item(thd)))
5509
5866
        return(true);
5510
5867
 
5511
5868
      if (!found)
5520
5877
      {
5521
5878
        /* Mark fields as used to allow storage engine to optimze access */
5522
5879
        bitmap_set_bit(field->table->read_set, field->field_index);
5523
 
        /*
5524
 
          Mark virtual fields for write and others that the virtual fields
5525
 
          depend on for read.
5526
 
        */
5527
 
        if (field->vcol_info)
5528
 
        {
5529
 
          Item *vcol_item= field->vcol_info->expr_item;
5530
 
          assert(vcol_item);
5531
 
          vcol_item->walk(&Item::register_field_in_read_map, 1, (unsigned char *) 0);
5532
 
          bitmap_set_bit(field->table->write_set, field->field_index);
5533
 
        }
5534
5880
        if (table)
5535
5881
        {
5536
5882
          table->covering_keys.intersect(field->part_of_key);
5550
5896
          field_table= nj_col->table_ref->table;
5551
5897
          if (field_table)
5552
5898
          {
5553
 
            session->used_tables|= field_table->map;
 
5899
            thd->used_tables|= field_table->map;
5554
5900
            field_table->covering_keys.intersect(field->part_of_key);
5555
5901
            field_table->merge_keys.merge(field->part_of_key);
5556
5902
            field_table->used_fields++;
5558
5904
        }
5559
5905
      }
5560
5906
      else
5561
 
        session->used_tables|= item->used_tables();
5562
 
      session->lex->current_select->cur_pos_in_select_list++;
 
5907
        thd->used_tables|= item->used_tables();
 
5908
      thd->lex->current_select->cur_pos_in_select_list++;
5563
5909
    }
5564
5910
    /*
5565
5911
      In case of stored tables, all fields are considered as used,
5592
5938
 
5593
5939
  SYNOPSIS
5594
5940
    setup_conds()
5595
 
    session     thread handler
 
5941
    thd     thread handler
5596
5942
    tables  list of tables for name resolving (select_lex->table_list)
5597
5943
    leaves  list of leaves of join table tree (select_lex->leaf_tables)
5598
5944
    conds   WHERE clause
5605
5951
    false if all is OK
5606
5952
*/
5607
5953
 
5608
 
int setup_conds(Session *session, TableList *,
 
5954
int setup_conds(THD *thd, TableList *tables __attribute__((unused)),
5609
5955
                TableList *leaves,
5610
5956
                COND **conds)
5611
5957
{
5612
 
  Select_Lex *select_lex= session->lex->current_select;
 
5958
  SELECT_LEX *select_lex= thd->lex->current_select;
5613
5959
  TableList *table= NULL;       // For HP compilers
5614
 
  void *save_session_marker= session->session_marker;
 
5960
  void *save_thd_marker= thd->thd_marker;
5615
5961
  /*
5616
 
    it_is_update set to true when tables of primary Select_Lex (Select_Lex
 
5962
    it_is_update set to true when tables of primary SELECT_LEX (SELECT_LEX
5617
5963
    which belong to LEX, i.e. most up SELECT) will be updated by
5618
5964
    INSERT/UPDATE/LOAD
5619
5965
    NOTE: using this condition helps to prevent call of prepare_check_option()
5623
5969
  bool save_is_item_list_lookup= select_lex->is_item_list_lookup;
5624
5970
  select_lex->is_item_list_lookup= 0;
5625
5971
 
5626
 
  session->mark_used_columns= MARK_COLUMNS_READ;
 
5972
  thd->mark_used_columns= MARK_COLUMNS_READ;
5627
5973
  select_lex->cond_count= 0;
5628
5974
  select_lex->between_count= 0;
5629
5975
  select_lex->max_equal_elems= 0;
5630
5976
 
5631
 
  session->session_marker= (void*)1;
 
5977
  thd->thd_marker= (void*)1;
5632
5978
  if (*conds)
5633
5979
  {
5634
 
    session->where="where clause";
5635
 
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
 
5980
    thd->where="where clause";
 
5981
    if ((!(*conds)->fixed && (*conds)->fix_fields(thd, conds)) ||
5636
5982
        (*conds)->check_cols(1))
5637
5983
      goto err_no_arena;
5638
5984
  }
5639
 
  session->session_marker= save_session_marker;
 
5985
  thd->thd_marker= save_thd_marker;
5640
5986
 
5641
5987
  /*
5642
5988
    Apply fix_fields() to all ON clauses at all levels of nesting,
5652
5998
      if (embedded->on_expr)
5653
5999
      {
5654
6000
        /* Make a join an a expression */
5655
 
        session->session_marker= (void*)embedded;
5656
 
        session->where="on clause";
5657
 
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
 
6001
        thd->thd_marker= (void*)embedded;
 
6002
        thd->where="on clause";
 
6003
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(thd, &embedded->on_expr)) ||
5658
6004
            embedded->on_expr->check_cols(1))
5659
6005
          goto err_no_arena;
5660
6006
        select_lex->cond_count++;
5665
6011
           embedding->nested_join->join_list.head() == embedded);
5666
6012
 
5667
6013
  }
5668
 
  session->session_marker= save_session_marker;
 
6014
  thd->thd_marker= save_thd_marker;
5669
6015
 
5670
 
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
5671
 
  return(test(session->is_error()));
 
6016
  thd->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
6017
  return(test(thd->is_error()));
5672
6018
 
5673
6019
err_no_arena:
5674
6020
  select_lex->is_item_list_lookup= save_is_item_list_lookup;
5687
6033
 
5688
6034
  SYNOPSIS
5689
6035
    fill_record()
5690
 
    session           thread handler
 
6036
    thd           thread handler
5691
6037
    fields        Item_fields list to be filled
5692
6038
    values        values to fill with
5693
6039
    ignore_errors true if we should ignore errors
5703
6049
*/
5704
6050
 
5705
6051
bool
5706
 
fill_record(Session * session, List<Item> &fields, List<Item> &values, bool ignore_errors)
 
6052
fill_record(THD * thd, List<Item> &fields, List<Item> &values, bool ignore_errors)
5707
6053
{
5708
6054
  List_iterator_fast<Item> f(fields),v(values);
5709
6055
  Item *value, *fld;
5710
6056
  Item_field *field;
5711
6057
  Table *table= 0;
5712
 
  List<Table> tbl_list;
5713
 
  bool abort_on_warning_saved= session->abort_on_warning;
5714
 
  tbl_list.empty();
5715
6058
 
5716
6059
  /*
5717
6060
    Reset the table->auto_increment_field_not_null as it is valid for
5745
6088
    table= rfield->table;
5746
6089
    if (rfield == table->next_number_field)
5747
6090
      table->auto_increment_field_not_null= true;
5748
 
    if (rfield->vcol_info &&
5749
 
        value->type() != Item::DEFAULT_VALUE_ITEM &&
5750
 
        value->type() != Item::NULL_ITEM &&
5751
 
        table->s->table_category != TABLE_CATEGORY_TEMPORARY)
5752
 
    {
5753
 
      session->abort_on_warning= false;
5754
 
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
5755
 
                          ER_WARNING_NON_DEFAULT_VALUE_FOR_VIRTUAL_COLUMN,
5756
 
                          ER(ER_WARNING_NON_DEFAULT_VALUE_FOR_VIRTUAL_COLUMN),
5757
 
                          rfield->field_name, table->s->table_name.str);
5758
 
      session->abort_on_warning= abort_on_warning_saved;
5759
 
    }
5760
6091
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
5761
6092
    {
5762
6093
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
5763
6094
      goto err;
5764
6095
    }
5765
 
    tbl_list.push_back(table);
5766
 
  }
5767
 
  /* Update virtual fields*/
5768
 
  session->abort_on_warning= false;
5769
 
  if (tbl_list.head())
5770
 
  {
5771
 
    List_iterator_fast<Table> t(tbl_list);
5772
 
    Table *prev_table= 0;
5773
 
    while ((table= t++))
5774
 
    {
5775
 
      /*
5776
 
        Do simple optimization to prevent unnecessary re-generating
5777
 
        values for virtual fields
5778
 
      */
5779
 
      if (table != prev_table)
5780
 
      {
5781
 
        prev_table= table;
5782
 
        if (table->vfield)
5783
 
        {
5784
 
          if (update_virtual_fields_marked_for_write(table, false))
5785
 
            goto err;
5786
 
        }
5787
 
      }
5788
 
    }
5789
 
  }
5790
 
  session->abort_on_warning= abort_on_warning_saved;
5791
 
  return(session->is_error());
 
6096
  }
 
6097
  return(thd->is_error());
5792
6098
err:
5793
 
  session->abort_on_warning= abort_on_warning_saved;
5794
6099
  if (table)
5795
6100
    table->auto_increment_field_not_null= false;
5796
6101
  return(true);
5802
6107
 
5803
6108
  SYNOPSIS
5804
6109
    fill_record()
5805
 
    session           thread handler
 
6110
    thd           thread handler
5806
6111
    ptr           pointer on pointer to record
5807
6112
    values        list of fields
5808
6113
    ignore_errors true if we should ignore errors
5818
6123
*/
5819
6124
 
5820
6125
bool
5821
 
fill_record(Session *session, Field **ptr, List<Item> &values,
5822
 
            bool )
 
6126
fill_record(THD *thd, Field **ptr, List<Item> &values,
 
6127
            bool ignore_errors __attribute__((unused)))
5823
6128
{
5824
6129
  List_iterator_fast<Item> v(values);
5825
6130
  Item *value;
5826
6131
  Table *table= 0;
 
6132
 
5827
6133
  Field *field;
5828
 
  List<Table> tbl_list;
5829
 
  bool abort_on_warning_saved= session->abort_on_warning;
5830
 
 
5831
 
  tbl_list.empty();
5832
6134
  /*
5833
6135
    Reset the table->auto_increment_field_not_null as it is valid for
5834
6136
    only one row.
5842
6144
    table= (*ptr)->table;
5843
6145
    table->auto_increment_field_not_null= false;
5844
6146
  }
5845
 
  while ((field = *ptr++) && ! session->is_error())
 
6147
  while ((field = *ptr++) && ! thd->is_error())
5846
6148
  {
5847
6149
    value=v++;
5848
6150
    table= field->table;
5849
6151
    if (field == table->next_number_field)
5850
6152
      table->auto_increment_field_not_null= true;
5851
 
    if (field->vcol_info &&
5852
 
        value->type() != Item::DEFAULT_VALUE_ITEM &&
5853
 
        value->type() != Item::NULL_ITEM &&
5854
 
        table->s->table_category != TABLE_CATEGORY_TEMPORARY)
5855
 
    {
5856
 
      session->abort_on_warning= false;
5857
 
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
5858
 
                          ER_WARNING_NON_DEFAULT_VALUE_FOR_VIRTUAL_COLUMN,
5859
 
                          ER(ER_WARNING_NON_DEFAULT_VALUE_FOR_VIRTUAL_COLUMN),
5860
 
                          field->field_name, table->s->table_name.str);
5861
 
      session->abort_on_warning= abort_on_warning_saved;
5862
 
    }
5863
6153
    if (value->save_in_field(field, 0) < 0)
5864
6154
      goto err;
5865
 
    tbl_list.push_back(table);
5866
 
  }
5867
 
  /* Update virtual fields*/
5868
 
  session->abort_on_warning= false;
5869
 
  if (tbl_list.head())
5870
 
  {
5871
 
    List_iterator_fast<Table> t(tbl_list);
5872
 
    Table *prev_table= 0;
5873
 
    while ((table= t++))
5874
 
    {
5875
 
      /*
5876
 
        Do simple optimization to prevent unnecessary re-generating
5877
 
        values for virtual fields
5878
 
      */
5879
 
      if (table != prev_table)
5880
 
      {
5881
 
        prev_table= table;
5882
 
        if (table->vfield)
5883
 
        {
5884
 
          if (update_virtual_fields_marked_for_write(table, false))
5885
 
          {
5886
 
            goto err;
5887
 
          }
5888
 
        }
5889
 
      }
5890
 
    }
5891
 
  }
5892
 
  session->abort_on_warning= abort_on_warning_saved;
5893
 
  return(session->is_error());
 
6155
  }
 
6156
  return(thd->is_error());
5894
6157
 
5895
6158
err:
5896
 
  session->abort_on_warning= abort_on_warning_saved;
5897
6159
  if (table)
5898
6160
    table->auto_increment_field_not_null= false;
5899
6161
  return(true);
5900
6162
}
5901
6163
 
5902
6164
 
5903
 
bool drizzle_rm_tmp_tables(void)
 
6165
bool mysql_rm_tmp_tables(void)
5904
6166
{
5905
 
  uint32_t  idx;
5906
 
  char  filePath[FN_REFLEN], filePathCopy[FN_REFLEN];
 
6167
  uint32_t i, idx;
 
6168
  char  filePath[FN_REFLEN], *tmpdir, filePathCopy[FN_REFLEN];
5907
6169
  MY_DIR *dirp;
5908
6170
  FILEINFO *file;
5909
6171
  TABLE_SHARE share;
5910
 
  Session *session;
5911
 
 
5912
 
  assert(drizzle_tmpdir);
5913
 
 
5914
 
  if (!(session= new Session))
5915
 
    return true;
5916
 
  session->thread_stack= (char*) &session;
5917
 
  session->store_globals();
5918
 
 
5919
 
  /* Remove all temp tables in the tmpdir */
5920
 
  /* See if the directory exists */
5921
 
  if ((dirp = my_dir(drizzle_tmpdir ,MYF(MY_WME | MY_DONT_SORT))))
 
6172
  THD *thd;
 
6173
 
 
6174
  if (!(thd= new THD))
 
6175
    return(1);
 
6176
  thd->thread_stack= (char*) &thd;
 
6177
  thd->store_globals();
 
6178
 
 
6179
  for (i=0; i<=mysql_tmpdir_list.max; i++)
5922
6180
  {
 
6181
    tmpdir=mysql_tmpdir_list.list[i];
 
6182
    /* See if the directory exists */
 
6183
    if (!(dirp = my_dir(tmpdir,MYF(MY_WME | MY_DONT_SORT))))
 
6184
      continue;
 
6185
 
5923
6186
    /* Remove all SQLxxx tables from directory */
5924
 
    for (idx=0 ; idx < (uint32_t) dirp->number_off_files ; idx++)
 
6187
 
 
6188
    for (idx=0 ; idx < (uint) dirp->number_off_files ; idx++)
5925
6189
    {
5926
6190
      file=dirp->dir_entry+idx;
5927
6191
 
5930
6194
                                   (file->name[1] == '.' &&  !file->name[2])))
5931
6195
        continue;
5932
6196
 
5933
 
      if (!memcmp(file->name, TMP_FILE_PREFIX, TMP_FILE_PREFIX_LENGTH))
 
6197
      if (!memcmp(file->name, tmp_file_prefix, tmp_file_prefix_length))
5934
6198
      {
5935
6199
        char *ext= fn_ext(file->name);
5936
6200
        uint32_t ext_len= strlen(ext);
5937
6201
        uint32_t filePath_len= snprintf(filePath, sizeof(filePath),
5938
 
                                        "%s%c%s", drizzle_tmpdir, FN_LIBCHAR,
5939
 
                                        file->name);
5940
 
        if (!memcmp(".dfe", ext, ext_len))
 
6202
                                    "%s%c%s", tmpdir, FN_LIBCHAR,
 
6203
                                    file->name);
 
6204
        if (!memcmp(reg_ext, ext, ext_len))
5941
6205
        {
5942
6206
          handler *handler_file= 0;
5943
6207
          /* We should cut file extention before deleting of table */
5944
6208
          memcpy(filePathCopy, filePath, filePath_len - ext_len);
5945
6209
          filePathCopy[filePath_len - ext_len]= 0;
5946
 
          init_tmp_table_share(session, &share, "", 0, "", filePathCopy);
5947
 
          if (!open_table_def(session, &share, 0) &&
5948
 
              ((handler_file= get_new_handler(&share, session->mem_root,
 
6210
          init_tmp_table_share(thd, &share, "", 0, "", filePathCopy);
 
6211
          if (!open_table_def(thd, &share, 0) &&
 
6212
              ((handler_file= get_new_handler(&share, thd->mem_root,
5949
6213
                                              share.db_type()))))
5950
6214
          {
5951
6215
            handler_file->ha_delete_table(filePathCopy);
5958
6222
          So we hide error messages which happnes during deleting of these
5959
6223
          files(MYF(0)).
5960
6224
        */
5961
 
        my_delete(filePath, MYF(0));
 
6225
        my_delete(filePath, MYF(0)); 
5962
6226
      }
5963
6227
    }
5964
6228
    my_dirend(dirp);
5965
6229
  }
5966
 
 
5967
 
  delete session;
5968
 
 
5969
 
  return false;
 
6230
  delete thd;
 
6231
  my_pthread_setspecific_ptr(THR_THD,  0);
 
6232
  return(0);
5970
6233
}
5971
6234
 
5972
6235
 
6037
6300
    1  Table is in use by another thread
6038
6301
*/
6039
6302
 
6040
 
bool remove_table_from_cache(Session *session, const char *db, const char *table_name,
 
6303
bool remove_table_from_cache(THD *thd, const char *db, const char *table_name,
6041
6304
                             uint32_t flags)
6042
6305
{
6043
6306
  char key[MAX_DBKEY_LENGTH];
6044
 
  char *key_pos= key;
6045
6307
  uint32_t key_length;
6046
6308
  Table *table;
6047
6309
  TABLE_SHARE *share;
6048
6310
  bool result= 0, signalled= 0;
6049
6311
 
6050
 
  key_pos= strcpy(key_pos, db) + strlen(db);
6051
 
  key_pos= strcpy(key_pos+1, table_name) + strlen(table_name);
6052
 
  key_length= (uint32_t) (key_pos-key)+1;
6053
 
 
 
6312
  key_length=(uint) (my_stpcpy(my_stpcpy(key,db)+1,table_name)-key)+1;
6054
6313
  for (;;)
6055
6314
  {
6056
6315
    HASH_SEARCH_STATE state;
6062
6321
         table= (Table*) hash_next(&open_cache, (unsigned char*) key, key_length,
6063
6322
                                   &state))
6064
6323
    {
6065
 
      Session *in_use;
 
6324
      THD *in_use;
6066
6325
 
6067
6326
      table->s->version=0L;             /* Free when thread is ready */
6068
6327
      if (!(in_use=table->in_use))
6069
6328
      {
6070
6329
        relink_unused(table);
6071
6330
      }
6072
 
      else if (in_use != session)
 
6331
      else if (in_use != thd)
6073
6332
      {
6074
6333
        /*
6075
6334
          Mark that table is going to be deleted from cache. This will
6090
6349
          open_tables list. Aborting the MERGE lock after a child was
6091
6350
          closed and before the parent is closed would be fatal.
6092
6351
        */
6093
 
        for (Table *session_table= in_use->open_tables;
6094
 
             session_table ;
6095
 
             session_table= session_table->next)
 
6352
        for (Table *thd_table= in_use->open_tables;
 
6353
             thd_table ;
 
6354
             thd_table= thd_table->next)
6096
6355
        {
6097
6356
          /* Do not handle locks of MERGE children. */
6098
 
          if (session_table->db_stat)   // If table is open
6099
 
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
6357
          if (thd_table->db_stat)       // If table is open
 
6358
            signalled|= mysql_lock_abort_for_thread(thd, thd_table);
6100
6359
        }
6101
6360
      }
6102
6361
      else
6103
 
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
6362
        result= result || (flags & RTFC_OWNED_BY_THD_FLAG);
6104
6363
    }
6105
6364
    while (unused_tables && !unused_tables->s->version)
6106
6365
      hash_delete(&open_cache,(unsigned char*) unused_tables);
6124
6383
        reopen their tables
6125
6384
      */
6126
6385
      broadcast_refresh();
6127
 
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
6386
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !thd->killed)
6128
6387
      {
6129
6388
        dropping_tables++;
6130
6389
        if (likely(signalled))
6162
6421
/**
6163
6422
  @} (end of group Data_Dictionary)
6164
6423
*/
6165
 
 
6166
 
void kill_drizzle(void)
6167
 
{
6168
 
  pthread_kill(signal_thread, SIGTERM);
6169
 
  shutdown_in_progress= 1;                      // Safety if kill didn't work
6170
 
}