~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: Monty Taylor
  • Date: 2010-10-19 21:51:42 UTC
  • mto: This revision was merged to the branch mainline in revision 1870.
  • Revision ID: mordred@inaugust.com-20101019215142-bwof1oqrswj9ms3v
Add a constrained_value class which allows us to set compile-time
constraints on a value.

Show diffs side-by-side

added added

removed removed

Lines of Context:
55
55
#include "drizzled/plugin/authorization.h"
56
56
#include "drizzled/table/temporary.h"
57
57
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
59
58
 
60
59
using namespace std;
61
60
 
64
63
 
65
64
extern bool volatile shutdown_in_progress;
66
65
 
 
66
TableOpenCache &get_open_cache()
 
67
{
 
68
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
69
 
 
70
  return open_cache;
 
71
}
 
72
 
 
73
static void free_cache_entry(Table *entry);
 
74
 
 
75
void remove_table(Table *arg)
 
76
{
 
77
  TableOpenCacheRange ppp;
 
78
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
79
 
 
80
  for (TableOpenCache::const_iterator iter= ppp.first;
 
81
         iter != ppp.second; ++iter)
 
82
  {
 
83
    Table *found_table= (*iter).second;
 
84
 
 
85
    if (found_table == arg)
 
86
    {
 
87
      free_cache_entry(arg);
 
88
      get_open_cache().erase(iter);
 
89
      return;
 
90
    }
 
91
  }
 
92
}
 
93
 
 
94
static bool add_table(Table *arg)
 
95
{
 
96
  TableOpenCache &open_cache(get_open_cache());
 
97
 
 
98
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
99
 
 
100
  return not (returnable == open_cache.end());
 
101
}
 
102
 
 
103
class UnusedTables {
 
104
  Table *tables;                                /* Used by mysql_test */
 
105
 
 
106
  Table *getTable() const
 
107
  {
 
108
    return tables;
 
109
  }
 
110
 
 
111
  Table *setTable(Table *arg)
 
112
  {
 
113
    return tables= arg;
 
114
  }
 
115
 
 
116
public:
 
117
 
 
118
  void cull()
 
119
  {
 
120
    /* Free cache if too big */
 
121
    while (cached_open_tables() > table_cache_size && getTable())
 
122
      remove_table(getTable());
 
123
  }
 
124
 
 
125
  void cullByVersion()
 
126
  {
 
127
    while (getTable() && not getTable()->getShare()->getVersion())
 
128
      remove_table(getTable());
 
129
  }
 
130
  
 
131
  void link(Table *table)
 
132
  {
 
133
    if (getTable())
 
134
    {
 
135
      table->setNext(getTable());               /* Link in last */
 
136
      table->setPrev(getTable()->getPrev());
 
137
      getTable()->setPrev(table);
 
138
      table->getPrev()->setNext(table);
 
139
    }
 
140
    else
 
141
    {
 
142
      table->setPrev(setTable(table));
 
143
      table->setNext(table->getPrev());
 
144
      assert(table->getNext() == table && table->getPrev() == table);
 
145
    }
 
146
  }
 
147
 
 
148
 
 
149
  void unlink(Table *table)
 
150
  {
 
151
    table->unlink();
 
152
 
 
153
    /* Unlink the table from "unused_tables" list. */
 
154
    if (table == getTable())
 
155
    {  // First unused
 
156
      setTable(getTable()->getNext()); // Remove from link
 
157
      if (table == getTable())
 
158
        setTable(NULL);
 
159
    }
 
160
  }
 
161
 
 
162
/* move table first in unused links */
 
163
 
 
164
  void relink(Table *table)
 
165
  {
 
166
    if (table != getTable())
 
167
    {
 
168
      table->unlink();
 
169
 
 
170
      table->setNext(getTable());                       /* Link in unused tables */
 
171
      table->setPrev(getTable()->getPrev());
 
172
      getTable()->getPrev()->setNext(table);
 
173
      getTable()->setPrev(table);
 
174
      setTable(table);
 
175
    }
 
176
  }
 
177
 
 
178
 
 
179
  void clear()
 
180
  {
 
181
    while (getTable())
 
182
      remove_table(getTable());
 
183
  }
 
184
 
 
185
  UnusedTables():
 
186
    tables(NULL)
 
187
  { }
 
188
 
 
189
  ~UnusedTables()
 
190
  { 
 
191
  }
 
192
};
 
193
 
 
194
static UnusedTables unused_tables;
 
195
static int open_unireg_entry(Session *session,
 
196
                             Table *entry,
 
197
                             const char *alias,
 
198
                             TableIdentifier &identifier);
 
199
 
 
200
unsigned char *table_cache_key(const unsigned char *record,
 
201
                               size_t *length,
 
202
                               bool );
 
203
 
 
204
unsigned char *table_cache_key(const unsigned char *record,
 
205
                               size_t *length,
 
206
                               bool )
 
207
{
 
208
  Table *entry=(Table*) record;
 
209
  *length= entry->getShare()->getCacheKey().size();
 
210
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
211
}
 
212
 
67
213
bool table_cache_init(void)
68
214
{
69
215
  return false;
71
217
 
72
218
uint32_t cached_open_tables(void)
73
219
{
74
 
  return table::getCache().size();
 
220
  return get_open_cache().size();
75
221
}
76
222
 
77
223
void table_cache_free(void)
78
224
{
79
225
  refresh_version++;                            // Force close of open tables
80
226
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
 
227
  unused_tables.clear();
 
228
  get_open_cache().clear();
83
229
}
84
230
 
85
231
/*
93
239
  By leaving the table in the table cache, it disallows any other thread
94
240
  to open the table
95
241
 
96
 
  session->getKilled() will be set if we run out of memory
 
242
  session->killed will be set if we run out of memory
97
243
 
98
244
  If closing a MERGE child, the calling function has to take care for
99
245
  closing the parent too, if necessary.
114
260
  const TableIdentifier::Key &key(identifier.getKey());
115
261
  TableShare *share= new TableShare(identifier.getType(),
116
262
                                    identifier,
117
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
263
                                    const_cast<char *>(&key[0]),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
118
264
 
119
265
  table->cursor->close();
120
266
  table->db_stat= 0;                            // Mark cursor closed
121
267
  TableShare::release(table->getMutableShare());
122
268
  table->setShare(share);
 
269
  table->cursor->change_table_ptr(table, table->getMutableShare());
123
270
}
124
271
 
125
272
 
137
284
  }
138
285
}
139
286
 
 
287
/*
 
288
  Remove table from the open table cache
 
289
 
 
290
  SYNOPSIS
 
291
  free_cache_entry()
 
292
  entry         Table to remove
 
293
 
 
294
  NOTE
 
295
  We need to have a lock on LOCK_open when calling this
 
296
*/
 
297
 
 
298
void free_cache_entry(Table *table)
 
299
{
 
300
  table->intern_close_table();
 
301
  if (not table->in_use)
 
302
  {
 
303
    unused_tables.unlink(table);
 
304
  }
 
305
 
 
306
  delete table;
 
307
}
 
308
 
140
309
/* Free resources allocated by filesort() and read_record() */
141
310
 
142
311
void Table::free_io_cache()
143
312
{
144
313
  if (sort.io_cache)
145
314
  {
146
 
    sort.io_cache->close_cached_file();
 
315
    close_cached_file(sort.io_cache);
147
316
    delete sort.io_cache;
148
317
    sort.io_cache= 0;
149
318
  }
155
324
 
156
325
  @param session Thread context (may be NULL)
157
326
  @param tables List of tables to remove from the cache
158
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
327
  @param have_lock If LOCK_open is locked
159
328
  @param wait_for_refresh Wait for a impending flush
160
329
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
161
330
  won't proceed while write-locked tables are being reopened by other
171
340
  Session *session= this;
172
341
 
173
342
  {
174
 
    table::Cache::singleton().mutex().lock(); /* Optionally lock for remove tables from open_cahe if not in use */
 
343
    LOCK_open.lock(); /* Optionally lock for remove tables from open_cahe if not in use */
175
344
 
176
345
    if (tables == NULL)
177
346
    {
178
347
      refresh_version++;                                // Force close of open tables
179
348
 
180
 
      table::getUnused().clear();
 
349
      unused_tables.clear();
181
350
 
182
351
      if (wait_for_refresh)
183
352
      {
208
377
          again. There they will wait until we update all tables version
209
378
          below.
210
379
 
211
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
 
380
          Setting some_tables_deleted is done by remove_table_from_cache()
212
381
          in the other branch.
213
382
 
214
383
          In other words (reviewer suggestion): You need this setting of
218
387
          after the call to Session::close_old_data_files() i.e. after removal of
219
388
          current thread locks.
220
389
        */
221
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
222
 
             iter != table::getCache().end();
 
390
        for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
391
             iter != get_open_cache().end();
223
392
             iter++)
224
393
        {
225
394
          Table *table= (*iter).second;
233
402
      bool found= false;
234
403
      for (TableList *table= tables; table; table= table->next_local)
235
404
      {
236
 
        TableIdentifier identifier(table->getSchemaName(), table->getTableName());
237
 
        if (table::Cache::singleton().removeTable(session, identifier,
 
405
        TableIdentifier identifier(table->db, table->table_name);
 
406
        if (remove_table_from_cache(session, identifier,
238
407
                                    RTFC_OWNED_BY_Session_FLAG))
239
408
        {
240
409
          found= true;
250
419
        If there is any table that has a lower refresh_version, wait until
251
420
        this is closed (or this thread is killed) before returning
252
421
      */
253
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
 
422
      session->mysys_var->current_mutex= &LOCK_open;
254
423
      session->mysys_var->current_cond= &COND_refresh;
255
424
      session->set_proc_info("Flushing tables");
256
425
 
258
427
 
259
428
      bool found= true;
260
429
      /* Wait until all threads has closed all the tables we had locked */
261
 
      while (found && ! session->getKilled())
 
430
      while (found && ! session->killed)
262
431
      {
263
432
        found= false;
264
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
265
 
             iter != table::getCache().end();
 
433
        for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
434
             iter != get_open_cache().end();
266
435
             iter++)
267
436
        {
268
437
          Table *table= (*iter).second;
287
456
                                                     (table->open_placeholder && wait_for_placeholders)))
288
457
          {
289
458
            found= true;
290
 
            boost_unique_lock_t scoped(table::Cache::singleton().mutex(), boost::adopt_lock_t());
 
459
            boost_unique_lock_t scoped(LOCK_open, boost::adopt_lock_t());
291
460
            COND_refresh.wait(scoped);
292
461
            scoped.release();
293
462
            break;
313
482
      }
314
483
    }
315
484
 
316
 
    table::Cache::singleton().mutex().unlock();
 
485
    LOCK_open.unlock();
317
486
  }
318
487
 
319
488
  if (wait_for_refresh)
335
504
bool Session::free_cached_table()
336
505
{
337
506
  bool found_old_table= false;
338
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
 
507
  Table *table= open_tables;
339
508
 
340
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
509
  safe_mutex_assert_owner(LOCK_open.native_handle());
341
510
  assert(table->key_read == 0);
342
511
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
343
512
 
346
515
  if (table->needs_reopen_or_name_lock() ||
347
516
      version != refresh_version || !table->db_stat)
348
517
  {
349
 
    table::remove_table(table);
 
518
    remove_table(table);
350
519
    found_old_table= true;
351
520
  }
352
521
  else
359
528
 
360
529
    /* Free memory and reset for next loop */
361
530
    table->cursor->ha_reset();
362
 
    table->in_use= NULL;
 
531
    table->in_use= false;
363
532
 
364
 
    table::getUnused().link(table);
 
533
    unused_tables.link(table);
365
534
  }
366
535
 
367
536
  return found_old_table;
380
549
{
381
550
  bool found_old_table= false;
382
551
 
383
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
552
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
384
553
 
385
 
  boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close all open tables on Session */
 
554
  boost_unique_lock_t scoped_lock(LOCK_open); /* Close all open tables on Session */
386
555
 
387
556
  while (open_tables)
388
557
  {
393
562
  if (found_old_table)
394
563
  {
395
564
    /* Tell threads waiting for refresh that something has happened */
396
 
    locking::broadcast_refresh();
 
565
    broadcast_refresh();
397
566
  }
398
567
}
399
568
 
423
592
  for (; table; table= table->*link )
424
593
  {
425
594
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
426
 
        strcasecmp(table->getSchemaName(), db_name) == 0 &&
427
 
        strcasecmp(table->getTableName(), table_name) == 0)
 
595
        strcasecmp(table->db, db_name) == 0 &&
 
596
        strcasecmp(table->table_name, table_name) == 0)
428
597
      break;
429
598
  }
430
599
  return table;
495
664
    */
496
665
    assert(table);
497
666
  }
498
 
  d_name= table->getSchemaName();
499
 
  t_name= table->getTableName();
 
667
  d_name= table->db;
 
668
  t_name= table->table_name;
500
669
  t_alias= table->alias;
501
670
 
502
671
  for (;;)
517
686
}
518
687
 
519
688
 
520
 
void Open_tables_state::doGetTableNames(const SchemaIdentifier &schema_identifier,
521
 
                                        std::set<std::string>& set_of_names)
 
689
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
690
                              std::set<std::string>& set_of_names)
522
691
{
523
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
692
  for (Table *table= temporary_tables ; table ; table= table->getNext())
524
693
  {
525
694
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
526
695
    {
529
698
  }
530
699
}
531
700
 
532
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
533
 
                                        const SchemaIdentifier &schema_identifier,
534
 
                                        std::set<std::string> &set_of_names)
 
701
void Session::doGetTableNames(CachedDirectory &,
 
702
                              const SchemaIdentifier &schema_identifier,
 
703
                              std::set<std::string> &set_of_names)
535
704
{
536
705
  doGetTableNames(schema_identifier, set_of_names);
537
706
}
538
707
 
539
 
void Open_tables_state::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
540
 
                                              TableIdentifier::vector &set_of_identifiers)
 
708
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
709
                                    TableIdentifiers &set_of_identifiers)
541
710
{
542
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
711
  for (Table *table= temporary_tables ; table ; table= table->getNext())
543
712
  {
544
713
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
545
714
    {
550
719
  }
551
720
}
552
721
 
553
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
554
 
                                              const SchemaIdentifier &schema_identifier,
555
 
                                              TableIdentifier::vector &set_of_identifiers)
 
722
void Session::doGetTableIdentifiers(CachedDirectory &,
 
723
                                    const SchemaIdentifier &schema_identifier,
 
724
                                    TableIdentifiers &set_of_identifiers)
556
725
{
557
726
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
558
727
}
559
728
 
560
 
bool Open_tables_state::doDoesTableExist(const TableIdentifier &identifier)
 
729
bool Session::doDoesTableExist(const TableIdentifier &identifier)
561
730
{
562
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
731
  for (Table *table= temporary_tables ; table ; table= table->getNext())
563
732
  {
564
733
    if (table->getShare()->getType() == message::Table::TEMPORARY)
565
734
    {
573
742
  return false;
574
743
}
575
744
 
576
 
int Open_tables_state::doGetTableDefinition(const TableIdentifier &identifier,
 
745
int Session::doGetTableDefinition(const TableIdentifier &identifier,
577
746
                                  message::Table &table_proto)
578
747
{
579
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
748
  for (Table *table= temporary_tables ; table ; table= table->getNext())
580
749
  {
581
750
    if (table->getShare()->getType() == message::Table::TEMPORARY)
582
751
    {
592
761
  return ENOENT;
593
762
}
594
763
 
595
 
Table *Open_tables_state::find_temporary_table(const TableIdentifier &identifier)
 
764
Table *Session::find_temporary_table(const char *new_db, const char *table_name)
 
765
{
 
766
  char  key[MAX_DBKEY_LENGTH];
 
767
  uint  key_length;
 
768
 
 
769
  key_length= TableIdentifier::createKey(key, new_db, table_name);
 
770
 
 
771
  for (Table *table= temporary_tables ; table ; table= table->getNext())
 
772
  {
 
773
    const TableIdentifier::Key &share_key(table->getShare()->getCacheKey());
 
774
    if (share_key.size() == key_length &&
 
775
        not memcmp(&share_key[0], key, key_length))
 
776
    {
 
777
      return table;
 
778
    }
 
779
  }
 
780
  return NULL;                               // Not a temporary table
 
781
}
 
782
 
 
783
Table *Session::find_temporary_table(TableList *table_list)
 
784
{
 
785
  return find_temporary_table(table_list->db, table_list->table_name);
 
786
}
 
787
 
 
788
Table *Session::find_temporary_table(TableIdentifier &identifier)
596
789
{
597
790
  for (Table *table= temporary_tables ; table ; table= table->getNext())
598
791
  {
630
823
  @retval -1  the table is in use by a outer query
631
824
*/
632
825
 
633
 
int Open_tables_state::drop_temporary_table(const drizzled::TableIdentifier &identifier)
 
826
int Session::drop_temporary_table(TableList *table_list)
634
827
{
635
828
  Table *table;
636
829
 
637
 
  if (not (table= find_temporary_table(identifier)))
 
830
  if (not (table= find_temporary_table(table_list)))
638
831
    return 1;
639
832
 
640
833
  /* Table might be in use by some outer statement. */
641
 
  if (table->query_id && table->query_id != getQueryId())
 
834
  if (table->query_id && table->query_id != query_id)
642
835
  {
643
836
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
644
837
    return -1;
656
849
 
657
850
  @param  session     Thread context
658
851
  @param  find    Table to remove
659
 
 
660
 
  @note because we risk the chance of deleting the share, we can't assume that it will exist past, this should be modified once we can use a TableShare::shared_ptr here.
661
852
*/
662
853
 
663
854
void Session::unlink_open_table(Table *find)
664
855
{
665
 
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
666
 
  Table **prev;
667
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
856
  char key[MAX_DBKEY_LENGTH];
 
857
  uint32_t key_length= find->getShare()->getCacheKeySize();
 
858
  Table *list, **prev;
 
859
  safe_mutex_assert_owner(LOCK_open.native_handle());
668
860
 
 
861
  memcpy(key, &find->getShare()->getCacheKey()[0], key_length);
669
862
  /*
670
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
863
    Note that we need to hold LOCK_open while changing the
671
864
    open_tables list. Another thread may work on it.
672
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
865
    (See: remove_table_from_cache(), mysql_wait_completed_table())
673
866
    Closing a MERGE child before the parent would be fatal if the
674
867
    other thread tries to abort the MERGE lock in between.
675
868
  */
676
869
  for (prev= &open_tables; *prev; )
677
870
  {
678
 
    Table *list= *prev;
 
871
    list= *prev;
679
872
 
680
 
    if (list->getShare()->getCacheKey() == find_key)
 
873
    if (list->getShare()->getCacheKeySize() == key_length &&
 
874
        not memcmp(&list->getShare()->getCacheKey()[0], key, key_length))
681
875
    {
682
876
      /* Remove table from open_tables list. */
683
877
      *prev= list->getNext();
684
878
 
685
879
      /* Close table. */
686
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
880
      remove_table(list);
687
881
    }
688
882
    else
689
883
    {
693
887
  }
694
888
 
695
889
  // Notify any 'refresh' threads
696
 
  locking::broadcast_refresh();
 
890
  broadcast_refresh();
697
891
}
698
892
 
699
893
 
716
910
  table that was locked with LOCK TABLES.
717
911
*/
718
912
 
719
 
void Session::drop_open_table(Table *table, const TableIdentifier &identifier)
 
913
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
720
914
{
721
915
  if (table->getShare()->getType())
722
916
  {
724
918
  }
725
919
  else
726
920
  {
727
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
921
    boost_unique_lock_t scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
728
922
    /*
729
923
      unlink_open_table() also tells threads waiting for refresh or close
730
924
      that something has happened.
731
925
    */
732
926
    unlink_open_table(table);
733
 
    plugin::StorageEngine::dropTable(*this, identifier);
 
927
    quick_rm_table(*this, identifier);
734
928
  }
735
929
}
736
930
 
766
960
      mutex is unlocked
767
961
    */
768
962
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
 
963
    if (not killed)
770
964
    {
771
965
      cond.wait(scopedLock);
772
966
    }
778
972
}
779
973
 
780
974
 
 
975
/*
 
976
  Open table which is already name-locked by this thread.
 
977
 
 
978
  SYNOPSIS
 
979
  reopen_name_locked_table()
 
980
  session         Thread handle
 
981
  table_list  TableList object for table to be open, TableList::table
 
982
  member should point to Table object which was used for
 
983
  name-locking.
 
984
  link_in     true  - if Table object for table to be opened should be
 
985
  linked into Session::open_tables list.
 
986
  false - placeholder used for name-locking is already in
 
987
  this list so we only need to preserve Table::next
 
988
  pointer.
 
989
 
 
990
  NOTE
 
991
  This function assumes that its caller already acquired LOCK_open mutex.
 
992
 
 
993
  RETURN VALUE
 
994
  false - Success
 
995
  true  - Error
 
996
*/
 
997
 
 
998
bool Session::reopen_name_locked_table(TableList* table_list, bool link_in)
 
999
{
 
1000
  Table *table= table_list->table;
 
1001
  char *table_name= table_list->table_name;
 
1002
  Table orig_table;
 
1003
 
 
1004
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1005
 
 
1006
  if (killed || !table)
 
1007
    return true;
 
1008
 
 
1009
  orig_table= *table;
 
1010
 
 
1011
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1012
  if (open_unireg_entry(this, table, table_name, identifier))
 
1013
  {
 
1014
    table->intern_close_table();
 
1015
    /*
 
1016
      If there was an error during opening of table (for example if it
 
1017
      does not exist) '*table' object can be wiped out. To be able
 
1018
      properly release name-lock in this case we should restore this
 
1019
      object to its original state.
 
1020
    */
 
1021
    *table= orig_table;
 
1022
    return true;
 
1023
  }
 
1024
 
 
1025
  /*
 
1026
    We want to prevent other connections from opening this table until end
 
1027
    of statement as it is likely that modifications of table's metadata are
 
1028
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1029
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1030
    This also allows us to assume that no other connection will sneak in
 
1031
    before we will get table-level lock on this table.
 
1032
  */
 
1033
  table->getMutableShare()->resetVersion();
 
1034
  table->in_use = this;
 
1035
 
 
1036
  if (link_in)
 
1037
  {
 
1038
    table->setNext(open_tables);
 
1039
    open_tables= table;
 
1040
  }
 
1041
  else
 
1042
  {
 
1043
    /*
 
1044
      Table object should be already in Session::open_tables list so we just
 
1045
      need to set Table::next correctly.
 
1046
    */
 
1047
    table->setNext(orig_table.getNext());
 
1048
  }
 
1049
 
 
1050
  table->tablenr= current_tablenr++;
 
1051
  table->used_fields= 0;
 
1052
  table->const_table= 0;
 
1053
  table->null_row= false;
 
1054
  table->maybe_null= false;
 
1055
  table->force_index= false;
 
1056
  table->status= STATUS_NO_RECORD;
 
1057
 
 
1058
  return false;
 
1059
}
 
1060
 
 
1061
 
781
1062
/**
782
1063
  Create and insert into table cache placeholder for table
783
1064
  which will prevent its opening (or creation) (a.k.a lock
791
1072
  case of failure.
792
1073
*/
793
1074
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1075
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
795
1076
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1077
  safe_mutex_assert_owner(LOCK_open.native_handle());
797
1078
 
798
1079
  /*
799
1080
    Create a table entry with the right key and with an old refresh version
800
1081
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
 
1082
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
802
1083
  table::Placeholder *table= new table::Placeholder(this, identifier);
803
1084
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1085
  if (not add_table(table))
805
1086
  {
806
1087
    delete table;
807
1088
 
833
1114
  @retval  true   Error occured (OOM)
834
1115
  @retval  false  Success. 'table' parameter set according to above rules.
835
1116
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1117
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
837
1118
{
838
1119
  const TableIdentifier::Key &key(identifier.getKey());
839
1120
 
840
 
  boost_unique_lock_t scope_lock(table::Cache::singleton().mutex()); /* Obtain a name lock even though table is not in cache (like for create table)  */
841
 
 
842
 
  table::CacheMap::iterator iter;
843
 
 
844
 
  iter= table::getCache().find(key);
845
 
 
846
 
  if (iter != table::getCache().end())
 
1121
  boost_unique_lock_t scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1122
 
 
1123
  TableOpenCache::iterator iter;
 
1124
 
 
1125
  iter= get_open_cache().find(key);
 
1126
 
 
1127
  if (iter != get_open_cache().end())
847
1128
  {
848
1129
    *table= 0;
849
1130
    return false;
850
1131
  }
851
1132
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1133
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
853
1134
  {
854
1135
    return true;
855
1136
  }
909
1190
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1191
    return NULL;
911
1192
 
912
 
  if (getKilled())
 
1193
  if (killed)
913
1194
    return NULL;
914
1195
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
 
1196
  TableIdentifier identifier(table_list->db, table_list->table_name);
916
1197
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1198
  TableOpenCacheRange ppp;
918
1199
 
919
1200
  /*
920
1201
    Unless requested otherwise, try to resolve this table in the list
924
1205
    TODO -> move this block into a separate function.
925
1206
  */
926
1207
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1208
  for (table= temporary_tables; table ; table=table->getNext())
928
1209
  {
929
1210
    if (table->getShare()->getCacheKey() == key)
930
1211
    {
949
1230
  {
950
1231
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
1232
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
 
1233
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
953
1234
      return NULL;
954
1235
    }
955
1236
 
994
1275
      until no one holds a name lock on the table.
995
1276
      - if there is no such Table in the name cache, read the table definition
996
1277
      and insert it into the cache.
997
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
 
1278
      We perform all of the above under LOCK_open which currently protects
998
1279
      the open cache (also known as table cache) and table definitions stored
999
1280
      on disk.
1000
1281
    */
1001
1282
 
1002
1283
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
 
1284
      LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
1004
1285
 
1005
1286
      /*
1006
1287
        Actually try to find the table in the open_cache.
1012
1293
        an implicit "pending locks queue" - see
1013
1294
        wait_for_locked_table_names for details.
1014
1295
      */
1015
 
      ppp= table::getCache().equal_range(key);
 
1296
      ppp= get_open_cache().equal_range(key);
1016
1297
 
1017
1298
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
 
1299
      for (TableOpenCache::const_iterator iter= ppp.first;
1019
1300
           iter != ppp.second; ++iter, table= NULL)
1020
1301
      {
1021
1302
        table= (*iter).second;
1052
1333
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
1334
          if (table->open_placeholder && table->in_use == this)
1054
1335
          {
1055
 
            table::Cache::singleton().mutex().unlock();
 
1336
            LOCK_open.unlock();
1056
1337
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1057
1338
            return NULL;
1058
1339
          }
1085
1366
          */
1086
1367
          if (table->in_use != this)
1087
1368
          {
1088
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
 
1369
            /* wait_for_conditionwill unlock LOCK_open for us */
 
1370
            wait_for_condition(LOCK_open, COND_refresh);
1090
1371
          }
1091
1372
          else
1092
1373
          {
1093
 
            table::Cache::singleton().mutex().unlock();
 
1374
            LOCK_open.unlock();
1094
1375
          }
1095
1376
          /*
1096
1377
            There is a refresh in progress for this table.
1103
1384
      }
1104
1385
      if (table)
1105
1386
      {
1106
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
 
1387
        unused_tables.unlink(table);
1107
1388
        table->in_use= this;
1108
1389
      }
1109
1390
      else
1111
1392
        /* Insert a new Table instance into the open cache */
1112
1393
        int error;
1113
1394
        /* Free cache if too big */
1114
 
        table::getUnused().cull();
 
1395
        unused_tables.cull();
1115
1396
 
1116
1397
        if (table_list->isCreate())
1117
1398
        {
1118
 
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
 
1399
          TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
1119
1400
 
1120
1401
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1121
1402
          {
1122
1403
            /*
1123
1404
              Table to be created, so we need to create placeholder in table-cache.
1124
1405
            */
1125
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
 
1406
            if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1126
1407
            {
1127
 
              table::Cache::singleton().mutex().unlock();
 
1408
              LOCK_open.unlock();
1128
1409
              return NULL;
1129
1410
            }
1130
1411
            /*
1135
1416
            table->open_placeholder= true;
1136
1417
            table->setNext(open_tables);
1137
1418
            open_tables= table;
1138
 
            table::Cache::singleton().mutex().unlock();
 
1419
            LOCK_open.unlock();
1139
1420
 
1140
1421
            return table ;
1141
1422
          }
1143
1424
        }
1144
1425
 
1145
1426
        /* make a new table */
 
1427
        table= new Table;
 
1428
        if (table == NULL)
1146
1429
        {
1147
 
          table::Concurrent *new_table= new table::Concurrent;
1148
 
          table= new_table;
1149
 
          if (new_table == NULL)
1150
 
          {
1151
 
            table::Cache::singleton().mutex().unlock();
1152
 
            return NULL;
1153
 
          }
 
1430
          LOCK_open.unlock();
 
1431
          return NULL;
 
1432
        }
1154
1433
 
1155
 
          error= new_table->open_unireg_entry(this, alias, identifier);
1156
 
          if (error != 0)
1157
 
          {
1158
 
            delete new_table;
1159
 
            table::Cache::singleton().mutex().unlock();
1160
 
            return NULL;
1161
 
          }
1162
 
          (void)table::Cache::singleton().insert(new_table);
 
1434
        error= open_unireg_entry(this, table, alias, identifier);
 
1435
        if (error != 0)
 
1436
        {
 
1437
          delete table;
 
1438
          LOCK_open.unlock();
 
1439
          return NULL;
1163
1440
        }
 
1441
        (void)add_table(table);
1164
1442
      }
1165
1443
 
1166
 
      table::Cache::singleton().mutex().unlock();
 
1444
      LOCK_open.unlock();
1167
1445
    }
1168
1446
    if (refresh)
1169
1447
    {
1178
1456
  /* Fix alias if table name changes */
1179
1457
  if (strcmp(table->getAlias(), alias))
1180
1458
  {
1181
 
    table->setAlias(alias);
 
1459
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1460
    table->alias= (char*) realloc((char*) table->alias, length);
 
1461
    memcpy((void*) table->alias, alias, length);
1182
1462
  }
1183
1463
 
1184
1464
  /* These variables are also set in reopen_table() */
1222
1502
  the strings are used in a loop even after the share may be freed.
1223
1503
*/
1224
1504
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1505
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1506
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1507
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1228
1508
 
1229
1509
  if (lock)
1230
1510
  {
1232
1512
      If we are not under LOCK TABLES we should have only one table
1233
1513
      open and locked so it makes sense to remove the lock at once.
1234
1514
    */
1235
 
    unlockTables(lock);
 
1515
    mysql_unlock_tables(this, lock);
1236
1516
    lock= 0;
1237
1517
  }
1238
1518
 
1267
1547
  combination when one needs tables to be reopened (for
1268
1548
  example see openTablesLock()).
1269
1549
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1550
  @note One should have lock on LOCK_open when calling this.
1271
1551
 
1272
1552
  @return false in case of success, true - otherwise.
1273
1553
*/
1284
1564
  if (open_tables == NULL)
1285
1565
    return false;
1286
1566
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1567
  safe_mutex_assert_owner(LOCK_open.native_handle());
1288
1568
  if (get_locks)
1289
1569
  {
1290
1570
    /*
1311
1591
    next= table->getNext();
1312
1592
 
1313
1593
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1594
    remove_table(table);
1315
1595
    error= 1;
1316
1596
  }
1317
1597
  *prev=0;
1320
1600
    DrizzleLock *local_lock;
1321
1601
    /*
1322
1602
      We should always get these locks. Anyway, we must not go into
1323
 
      wait_for_tables() as it tries to acquire table::Cache::singleton().mutex(), which is
 
1603
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1604
      already locked.
1325
1605
    */
1326
1606
    some_tables_deleted= false;
1327
1607
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1608
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1609
                                 flags, &not_used)))
1330
1610
    {
1331
1611
      /* unused */
1332
1612
    }
1345
1625
  if (get_locks && tables)
1346
1626
    delete [] tables;
1347
1627
 
1348
 
  locking::broadcast_refresh();
 
1628
  broadcast_refresh();
1349
1629
 
1350
1630
  return(error);
1351
1631
}
1392
1672
              lock on it. This will also give them a chance to close their
1393
1673
              instances of this table.
1394
1674
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1675
            mysql_lock_abort(this, ulcktbl);
 
1676
            mysql_lock_remove(this, ulcktbl);
1397
1677
            ulcktbl->lock_count= 0;
1398
1678
          }
1399
1679
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1713
    }
1434
1714
  }
1435
1715
  if (found)
1436
 
    locking::broadcast_refresh();
 
1716
    broadcast_refresh();
 
1717
}
 
1718
 
 
1719
 
 
1720
/*
 
1721
  Wait until all threads has closed the tables in the list
 
1722
  We have also to wait if there is thread that has a lock on this table even
 
1723
  if the table is closed
 
1724
*/
 
1725
 
 
1726
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1727
{
 
1728
  do
 
1729
  {
 
1730
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1731
 
 
1732
    TableOpenCacheRange ppp;
 
1733
    ppp= get_open_cache().equal_range(key);
 
1734
 
 
1735
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1736
         iter != ppp.second; ++iter)
 
1737
    {
 
1738
      Table *search= (*iter).second;
 
1739
      if (search->in_use == table->in_use)
 
1740
        continue;                               // Name locked by this thread
 
1741
      /*
 
1742
        We can't use the table under any of the following conditions:
 
1743
        - There is an name lock on it (Table is to be deleted or altered)
 
1744
        - If we are in flush table and we didn't execute the flush
 
1745
        - If the table engine is open and it's an old version
 
1746
        (We must wait until all engines are shut down to use the table)
 
1747
      */
 
1748
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1749
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1750
        return 1;
 
1751
    }
 
1752
  } while ((table=table->getNext()));
 
1753
  return 0;
1437
1754
}
1438
1755
 
1439
1756
 
1445
1762
 
1446
1763
  session->set_proc_info("Waiting for tables");
1447
1764
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
 
1765
    boost_unique_lock_t lock(LOCK_open);
 
1766
    while (!session->killed)
1450
1767
    {
1451
1768
      session->some_tables_deleted= false;
1452
1769
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
 
1770
      if (!table_is_used(session->open_tables, 1))
1455
1771
        break;
1456
 
      }
1457
1772
      COND_refresh.wait(lock);
1458
1773
    }
1459
 
    if (session->getKilled())
 
1774
    if (session->killed)
1460
1775
      result= true;                                     // aborted
1461
1776
    else
1462
1777
    {
1502
1817
  prev= &session->open_tables;
1503
1818
 
1504
1819
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1820
    Note that we need to hold LOCK_open while changing the
1506
1821
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1822
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1823
    Closing a MERGE child before the parent would be fatal if the
1509
1824
    other thread tries to abort the MERGE lock in between.
1510
1825
  */
1513
1828
    next=table->getNext();
1514
1829
    if (table->getShare()->getCacheKey() == identifier.getKey())
1515
1830
    {
1516
 
      session->removeLock(table);
 
1831
      mysql_lock_remove(session, table);
1517
1832
 
1518
1833
      if (!found)
1519
1834
      {
1528
1843
      else
1529
1844
      {
1530
1845
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1846
        remove_table(table);
1532
1847
      }
1533
1848
    }
1534
1849
    else
1539
1854
  }
1540
1855
  *prev=0;
1541
1856
  if (found)
1542
 
    locking::broadcast_refresh();
 
1857
    broadcast_refresh();
1543
1858
 
1544
1859
  return(found);
1545
1860
}
1559
1874
    if (table->getShare()->getCacheKey() == identifier.getKey())
1560
1875
    {
1561
1876
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1877
      mysql_lock_abort(session, table);
1563
1878
      break;
1564
1879
    }
1565
1880
  }
1566
1881
}
1567
1882
 
 
1883
/*
 
1884
  Load a table definition from cursor and open unireg table
 
1885
 
 
1886
  SYNOPSIS
 
1887
  open_unireg_entry()
 
1888
  session                       Thread handle
 
1889
  entry         Store open table definition here
 
1890
  table_list            TableList with db, table_name
 
1891
  alias         Alias name
 
1892
  cache_key             Key for share_cache
 
1893
  cache_key_length      length of cache_key
 
1894
 
 
1895
  NOTES
 
1896
  Extra argument for open is taken from session->open_options
 
1897
  One must have a lock on LOCK_open when calling this function
 
1898
 
 
1899
  RETURN
 
1900
  0     ok
 
1901
#       Error
 
1902
*/
 
1903
 
 
1904
static int open_unireg_entry(Session *session,
 
1905
                             Table *entry,
 
1906
                             const char *alias,
 
1907
                             TableIdentifier &identifier)
 
1908
{
 
1909
  int error;
 
1910
  TableSharePtr share;
 
1911
  uint32_t discover_retry_count= 0;
 
1912
 
 
1913
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1914
retry:
 
1915
  if (not (share= TableShare::getShareCreate(session,
 
1916
                                             identifier,
 
1917
                                             &error)))
 
1918
    return 1;
 
1919
 
 
1920
  while ((error= share->open_table_from_share(session,
 
1921
                                              identifier,
 
1922
                                              alias,
 
1923
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1924
                                                          HA_OPEN_RNDFILE |
 
1925
                                                          HA_GET_INDEX |
 
1926
                                                          HA_TRY_READ_ONLY),
 
1927
                                              session->open_options, *entry)))
 
1928
  {
 
1929
    if (error == 7)                             // Table def changed
 
1930
    {
 
1931
      share->resetVersion();                        // Mark share as old
 
1932
      if (discover_retry_count++)               // Retry once
 
1933
        goto err;
 
1934
 
 
1935
      /*
 
1936
        TODO->
 
1937
        Here we should wait until all threads has released the table.
 
1938
        For now we do one retry. This may cause a deadlock if there
 
1939
        is other threads waiting for other tables used by this thread.
 
1940
 
 
1941
        Proper fix would be to if the second retry failed:
 
1942
        - Mark that table def changed
 
1943
        - Return from open table
 
1944
        - Close all tables used by this thread
 
1945
        - Start waiting that the share is released
 
1946
        - Retry by opening all tables again
 
1947
      */
 
1948
 
 
1949
      /*
 
1950
        TO BE FIXED
 
1951
        To avoid deadlock, only wait for release if no one else is
 
1952
        using the share.
 
1953
      */
 
1954
      if (share->getTableCount() != 1)
 
1955
        goto err;
 
1956
      /* Free share and wait until it's released by all threads */
 
1957
      TableShare::release(share);
 
1958
 
 
1959
      if (!session->killed)
 
1960
      {
 
1961
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1962
        session->clear_error();                 // Clear error message
 
1963
        goto retry;
 
1964
      }
 
1965
      return 1;
 
1966
    }
 
1967
 
 
1968
    goto err;
 
1969
  }
 
1970
 
 
1971
  return 0;
 
1972
 
 
1973
err:
 
1974
  TableShare::release(share);
 
1975
 
 
1976
  return 1;
 
1977
}
 
1978
 
1568
1979
 
1569
1980
/*
1570
1981
  Open all tables in list
1632
2043
     * to see if it exists so that an unauthorized user cannot phish for
1633
2044
     * table/schema information via error messages
1634
2045
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
 
2046
    TableIdentifier the_table(tables->db, tables->table_name);
1636
2047
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
2048
                                                the_table))
1638
2049
    {
1742
2153
 
1743
2154
    assert(lock == 0);  // You must lock everything at once
1744
2155
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2156
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2157
        table= 0;
1747
2158
  }
1748
2159
 
1805
2216
      *(ptr++)= table->table;
1806
2217
  }
1807
2218
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2219
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2220
                                         lock_flag, need_reopen)))
1809
2221
  {
1810
2222
    return -1;
1811
2223
  }
1834
2246
#  Table object
1835
2247
*/
1836
2248
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2249
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2250
                                     bool link_in_list)
1839
2251
{
 
2252
  TableShare *share;
 
2253
 
1840
2254
  assert(identifier.isTmp());
1841
 
 
1842
 
 
1843
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1844
 
                                                        identifier,
1845
 
                                                        const_cast<char *>(const_cast<TableIdentifier&>(identifier).getPath().c_str()),
1846
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
2255
  share= new TableShare(identifier.getType(),
 
2256
                        identifier,
 
2257
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2258
 
 
2259
 
 
2260
  table::Temporary *new_tmp_table= new table::Temporary;
1847
2261
  if (not new_tmp_table)
1848
2262
    return NULL;
1849
2263
 
1850
2264
  /*
1851
2265
    First open the share, and then open the table from the share we just opened.
1852
2266
  */
1853
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1854
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1855
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1856
 
                                                                          HA_GET_INDEX),
1857
 
                                                              ha_open_options,
1858
 
                                                              *new_tmp_table))
 
2267
  if (share->open_table_def(*this, identifier) ||
 
2268
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2269
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2270
                                        HA_GET_INDEX),
 
2271
                            ha_open_options,
 
2272
                            *new_tmp_table))
1859
2273
  {
1860
2274
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
 
2275
    delete share;
1862
2276
    delete new_tmp_table;
1863
2277
 
1864
2278
    return 0;
1919
2333
      current_bitmap= table->write_set;
1920
2334
    }
1921
2335
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2336
    //if (current_bitmap->testAndSet(field->field_index))
 
2337
    if (current_bitmap->test(field->field_index))
1924
2338
    {
1925
2339
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2340
        session->dup_field= field;
2154
2568
      */
2155
2569
      table_name && table_name[0] &&
2156
2570
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2157
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2158
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2571
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2572
        strcmp(db_name, table_list->db))))
2159
2573
    return 0;
2160
2574
 
2161
2575
  *actual_table= NULL;
2230
2644
      {
2231
2645
        Table *table= field_to_set->getTable();
2232
2646
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2647
          table->setReadSet(field_to_set->field_index);
2234
2648
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2649
          table->setWriteSet(field_to_set->field_index);
2236
2650
      }
2237
2651
    }
2238
2652
  }
2788
3202
    /* true if field_name_1 is a member of using_fields */
2789
3203
    bool is_using_column_1;
2790
3204
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3205
      goto err;
2792
3206
    field_name_1= nj_col_1->name();
2793
3207
    is_using_column_1= using_fields &&
2794
3208
      test_if_string_in_list(field_name_1, using_fields);
2806
3220
      Natural_join_column *cur_nj_col_2;
2807
3221
      const char *cur_field_name_2;
2808
3222
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3223
        goto err;
2810
3224
      cur_field_name_2= cur_nj_col_2->name();
2811
3225
 
2812
3226
      /*
2826
3240
            (found && (!using_fields || is_using_column_1)))
2827
3241
        {
2828
3242
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3243
          goto err;
2830
3244
        }
2831
3245
        nj_col_2= cur_nj_col_2;
2832
3246
        found= true;
2859
3273
      Item_func_eq *eq_cond;
2860
3274
 
2861
3275
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3276
        goto err;                               // out of memory
2863
3277
 
2864
3278
      /*
2865
3279
        In the case of no_wrap_view_item == 0, the created items must be
2884
3298
      */
2885
3299
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3300
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3301
        goto err;
2888
3302
 
2889
3303
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3304
        goto err;                               /* Out of memory. */
2891
3305
 
2892
3306
      /*
2893
3307
        Add the new equi-join condition to the ON clause. Notice that
2904
3318
      {
2905
3319
        Table *table_1= nj_col_1->table_ref->table;
2906
3320
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3321
        table_1->setReadSet(field_1->field_index);
2908
3322
        table_1->covering_keys&= field_1->part_of_key;
2909
3323
        table_1->merge_keys|= field_1->part_of_key;
2910
3324
      }
2912
3326
      {
2913
3327
        Table *table_2= nj_col_2->table_ref->table;
2914
3328
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3329
        table_2->setReadSet(field_2->field_index);
2916
3330
        table_2->covering_keys&= field_2->part_of_key;
2917
3331
        table_2->merge_keys|= field_2->part_of_key;
2918
3332
      }
2933
3347
  */
2934
3348
  result= false;
2935
3349
 
 
3350
err:
2936
3351
  return(result);
2937
3352
}
2938
3353
 
2990
3405
 
2991
3406
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3407
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3408
    goto err;
2996
3409
 
2997
3410
  /* Append the columns of the first join operand. */
2998
3411
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3031
3444
        {
3032
3445
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
3446
                   session->where);
3034
 
          return(result);
 
3447
          goto err;
3035
3448
        }
3036
3449
        if (!my_strcasecmp(system_charset_info,
3037
3450
                           common_field->name(), using_field_name_ptr))
3059
3472
 
3060
3473
  result= false;
3061
3474
 
 
3475
err:
3062
3476
  return(result);
3063
3477
}
3064
3478
 
3144
3558
      if (cur_table_ref->getNestedJoin() &&
3145
3559
          store_top_level_join_columns(session, cur_table_ref,
3146
3560
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3561
        goto err;
3148
3562
      same_level_right_neighbor= cur_table_ref;
3149
3563
    }
3150
3564
  }
3176
3590
      std::swap(table_ref_1, table_ref_2);
3177
3591
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3592
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3593
      goto err;
3180
3594
 
3181
3595
    /*
3182
3596
      Swap the join operands back, so that we pick the columns of the second
3188
3602
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3603
                                         table_ref_2, using_fields,
3190
3604
                                         found_using_fields))
3191
 
      return(result);
 
3605
      goto err;
3192
3606
 
3193
3607
    /*
3194
3608
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3635
  }
3222
3636
  result= false; /* All is OK. */
3223
3637
 
 
3638
err:
3224
3639
  return(result);
3225
3640
}
3226
3641
 
3622
4037
    assert(tables->is_leaf_for_name_resolution());
3623
4038
 
3624
4039
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4040
        (db_name && strcasecmp(tables->db,db_name)))
3626
4041
      continue;
3627
4042
 
3628
4043
    /*
3658
4073
      if ((field= field_iterator.field()))
3659
4074
      {
3660
4075
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4076
        field->getTable()->setReadSet(field->field_index);
3662
4077
        if (table)
3663
4078
        {
3664
4079
          table->covering_keys&= field->part_of_key;
3865
4280
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4281
    {
3867
4282
      my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
3868
 
      if (table)
3869
 
        table->auto_increment_field_not_null= false;
3870
 
 
3871
 
      return true;
 
4283
      goto err;
3872
4284
    }
3873
4285
  }
3874
4286
 
3875
4287
  return session->is_error();
 
4288
 
 
4289
err:
 
4290
  if (table)
 
4291
    table->auto_increment_field_not_null= false;
 
4292
 
 
4293
  return true;
3876
4294
}
3877
4295
 
3878
4296
 
3922
4340
    if (field == table->next_number_field)
3923
4341
      table->auto_increment_field_not_null= true;
3924
4342
    if (value->save_in_field(field, 0) < 0)
3925
 
    {
3926
 
      if (table)
3927
 
        table->auto_increment_field_not_null= false;
3928
 
 
3929
 
      return true;
3930
 
    }
 
4343
      goto err;
3931
4344
  }
3932
4345
 
3933
4346
  return(session->is_error());
 
4347
 
 
4348
err:
 
4349
  if (table)
 
4350
    table->auto_increment_field_not_null= false;
 
4351
 
 
4352
  return true;
3934
4353
}
3935
4354
 
3936
4355
 
3947
4366
 
3948
4367
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3949
4368
 
 
4369
  session->lockForDelete();
3950
4370
  delete session;
3951
4371
 
3952
4372
  return false;
3958
4378
  unireg support functions
3959
4379
 *****************************************************************************/
3960
4380
 
3961
 
 
 
4381
/*
 
4382
  Invalidate any cache entries that are for some DB
 
4383
 
 
4384
  SYNOPSIS
 
4385
  remove_db_from_cache()
 
4386
  db            Database name. This will be in lower case if
 
4387
  lower_case_table_name is set
 
4388
 
 
4389
NOTE:
 
4390
We can't use hash_delete when looping hash_elements. We mark them first
 
4391
and afterwards delete those marked unused.
 
4392
*/
 
4393
 
 
4394
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4395
{
 
4396
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4397
 
 
4398
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4399
       iter != get_open_cache().end();
 
4400
       iter++)
 
4401
  {
 
4402
    Table *table= (*iter).second;
 
4403
 
 
4404
    if (not schema_identifier.getPath().compare(table->getShare()->getSchemaName()))
 
4405
    {
 
4406
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4407
      if (not table->in_use)
 
4408
        unused_tables.relink(table);
 
4409
    }
 
4410
  }
 
4411
 
 
4412
  unused_tables.cullByVersion();
 
4413
}
 
4414
 
 
4415
 
 
4416
/*
 
4417
  Mark all entries with the table as deleted to force an reopen of the table
 
4418
 
 
4419
  The table will be closed (not stored in cache) by the current thread when
 
4420
  close_thread_tables() is called.
 
4421
 
 
4422
  PREREQUISITES
 
4423
  Lock on LOCK_open()
 
4424
 
 
4425
  RETURN
 
4426
  0  This thread now have exclusive access to this table and no other thread
 
4427
  can access the table until close_thread_tables() is called.
 
4428
  1  Table is in use by another thread
 
4429
*/
 
4430
 
 
4431
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4432
{
 
4433
  const TableIdentifier::Key &key(identifier.getKey());
 
4434
  bool result= false; 
 
4435
  bool signalled= false;
 
4436
 
 
4437
  for (;;)
 
4438
  {
 
4439
    result= signalled= false;
 
4440
 
 
4441
    TableOpenCacheRange ppp;
 
4442
    ppp= get_open_cache().equal_range(key);
 
4443
 
 
4444
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4445
         iter != ppp.second; ++iter)
 
4446
    {
 
4447
      Table *table= (*iter).second;
 
4448
      Session *in_use;
 
4449
 
 
4450
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4451
      if (!(in_use=table->in_use))
 
4452
      {
 
4453
        unused_tables.relink(table);
 
4454
      }
 
4455
      else if (in_use != session)
 
4456
      {
 
4457
        /*
 
4458
          Mark that table is going to be deleted from cache. This will
 
4459
          force threads that are in mysql_lock_tables() (but not yet
 
4460
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4461
        */
 
4462
        in_use->some_tables_deleted= true;
 
4463
        if (table->is_name_opened())
 
4464
        {
 
4465
          result= true;
 
4466
        }
 
4467
        /*
 
4468
          Now we must abort all tables locks used by this thread
 
4469
          as the thread may be waiting to get a lock for another table.
 
4470
          Note that we need to hold LOCK_open while going through the
 
4471
          list. So that the other thread cannot change it. The other
 
4472
          thread must also hold LOCK_open whenever changing the
 
4473
          open_tables list. Aborting the MERGE lock after a child was
 
4474
          closed and before the parent is closed would be fatal.
 
4475
        */
 
4476
        for (Table *session_table= in_use->open_tables;
 
4477
             session_table ;
 
4478
             session_table= session_table->getNext())
 
4479
        {
 
4480
          /* Do not handle locks of MERGE children. */
 
4481
          if (session_table->db_stat)   // If table is open
 
4482
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4483
        }
 
4484
      }
 
4485
      else
 
4486
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4487
    }
 
4488
 
 
4489
    unused_tables.cullByVersion();
 
4490
 
 
4491
    /* Remove table from table definition cache if it's not in use */
 
4492
    TableShare::release(identifier);
 
4493
 
 
4494
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4495
    {
 
4496
      /*
 
4497
        Signal any thread waiting for tables to be freed to
 
4498
        reopen their tables
 
4499
      */
 
4500
      broadcast_refresh();
 
4501
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4502
      {
 
4503
        dropping_tables++;
 
4504
        if (likely(signalled))
 
4505
        {
 
4506
          boost_unique_lock_t scoped(LOCK_open, boost::adopt_lock_t());
 
4507
          COND_refresh.wait(scoped);
 
4508
          scoped.release();
 
4509
        }
 
4510
        else
 
4511
        {
 
4512
          /*
 
4513
            It can happen that another thread has opened the
 
4514
            table but has not yet locked any table at all. Since
 
4515
            it can be locked waiting for a table that our thread
 
4516
            has done LOCK Table x WRITE on previously, we need to
 
4517
            ensure that the thread actually hears our signal
 
4518
            before we go to sleep. Thus we wait for a short time
 
4519
            and then we retry another loop in the
 
4520
            remove_table_from_cache routine.
 
4521
          */
 
4522
          boost::xtime xt; 
 
4523
          xtime_get(&xt, boost::TIME_UTC); 
 
4524
          xt.sec += 10; 
 
4525
          boost_unique_lock_t scoped(LOCK_open, boost::adopt_lock_t());
 
4526
          COND_refresh.timed_wait(scoped, xt);
 
4527
          scoped.release();
 
4528
        }
 
4529
        dropping_tables--;
 
4530
        continue;
 
4531
      }
 
4532
    }
 
4533
    break;
 
4534
  }
 
4535
 
 
4536
  return result;
 
4537
}
3962
4538
 
3963
4539
 
3964
4540
/**