~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

  • Committer: lbieber
  • Date: 2010-10-02 14:36:07 UTC
  • mfrom: (1799.7.7 drizzle-bug-649844)
  • mto: This revision was merged to the branch mainline in revision 1809.
  • Revision ID: lbieber@orisndriz08-20101002143607-fffgvc6l4gw9drmm
Merge Andrew - fix bug 649844 - Clean up and fix some drizzledump options along with some documentation fixes

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
  You should have received a copy of the GNU General Public License
13
13
  along with this program; if not, write to the Free Software
14
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
53
53
#include "drizzled/internal/iocache.h"
54
54
#include "drizzled/drizzled.h"
55
55
#include "drizzled/plugin/authorization.h"
56
 
#include "drizzled/table/temporary.h"
57
 
#include "drizzled/table/placeholder.h"
58
 
#include "drizzled/table/unused.h"
 
56
#include "drizzled/table_placeholder.h"
59
57
 
60
58
using namespace std;
61
59
 
64
62
 
65
63
extern bool volatile shutdown_in_progress;
66
64
 
 
65
TableOpenCache &get_open_cache()
 
66
{
 
67
  static TableOpenCache open_cache;                             /* Used by mysql_test */
 
68
 
 
69
  return open_cache;
 
70
}
 
71
 
 
72
static void free_cache_entry(Table *entry);
 
73
 
 
74
void remove_table(Table *arg)
 
75
{
 
76
  TableOpenCacheRange ppp;
 
77
  ppp= get_open_cache().equal_range(arg->getShare()->getCacheKey());
 
78
 
 
79
  for (TableOpenCache::const_iterator iter= ppp.first;
 
80
         iter != ppp.second; ++iter)
 
81
  {
 
82
    Table *found_table= (*iter).second;
 
83
 
 
84
    if (found_table == arg)
 
85
    {
 
86
      free_cache_entry(arg);
 
87
      get_open_cache().erase(iter);
 
88
      return;
 
89
    }
 
90
  }
 
91
}
 
92
 
 
93
static bool add_table(Table *arg)
 
94
{
 
95
  TableOpenCache &open_cache(get_open_cache());
 
96
 
 
97
  TableOpenCache::iterator returnable= open_cache.insert(make_pair(arg->getShare()->getCacheKey(), arg));
 
98
 
 
99
  return not (returnable == open_cache.end());
 
100
}
 
101
 
 
102
class UnusedTables {
 
103
  Table *tables;                                /* Used by mysql_test */
 
104
 
 
105
  Table *getTable() const
 
106
  {
 
107
    return tables;
 
108
  }
 
109
 
 
110
  Table *setTable(Table *arg)
 
111
  {
 
112
    return tables= arg;
 
113
  }
 
114
 
 
115
public:
 
116
 
 
117
  void cull()
 
118
  {
 
119
    /* Free cache if too big */
 
120
    while (cached_open_tables() > table_cache_size && getTable())
 
121
      remove_table(getTable());
 
122
  }
 
123
 
 
124
  void cullByVersion()
 
125
  {
 
126
    while (getTable() && not getTable()->getShare()->getVersion())
 
127
      remove_table(getTable());
 
128
  }
 
129
  
 
130
  void link(Table *table)
 
131
  {
 
132
    if (getTable())
 
133
    {
 
134
      table->setNext(getTable());               /* Link in last */
 
135
      table->setPrev(getTable()->getPrev());
 
136
      getTable()->setPrev(table);
 
137
      table->getPrev()->setNext(table);
 
138
    }
 
139
    else
 
140
    {
 
141
      table->setPrev(setTable(table));
 
142
      table->setNext(table->getPrev());
 
143
      assert(table->getNext() == table && table->getPrev() == table);
 
144
    }
 
145
  }
 
146
 
 
147
 
 
148
  void unlink(Table *table)
 
149
  {
 
150
    table->unlink();
 
151
 
 
152
    /* Unlink the table from "unused_tables" list. */
 
153
    if (table == getTable())
 
154
    {  // First unused
 
155
      setTable(getTable()->getNext()); // Remove from link
 
156
      if (table == getTable())
 
157
        setTable(NULL);
 
158
    }
 
159
  }
 
160
 
 
161
/* move table first in unused links */
 
162
 
 
163
  void relink(Table *table)
 
164
  {
 
165
    if (table != getTable())
 
166
    {
 
167
      table->unlink();
 
168
 
 
169
      table->setNext(getTable());                       /* Link in unused tables */
 
170
      table->setPrev(getTable()->getPrev());
 
171
      getTable()->getPrev()->setNext(table);
 
172
      getTable()->setPrev(table);
 
173
      setTable(table);
 
174
    }
 
175
  }
 
176
 
 
177
 
 
178
  void clear()
 
179
  {
 
180
    while (getTable())
 
181
      remove_table(getTable());
 
182
  }
 
183
 
 
184
  UnusedTables():
 
185
    tables(NULL)
 
186
  { }
 
187
 
 
188
  ~UnusedTables()
 
189
  { 
 
190
  }
 
191
};
 
192
 
 
193
static UnusedTables unused_tables;
 
194
static int open_unireg_entry(Session *session,
 
195
                             Table *entry,
 
196
                             const char *alias,
 
197
                             TableIdentifier &identifier);
 
198
 
 
199
unsigned char *table_cache_key(const unsigned char *record,
 
200
                               size_t *length,
 
201
                               bool );
 
202
 
 
203
unsigned char *table_cache_key(const unsigned char *record,
 
204
                               size_t *length,
 
205
                               bool )
 
206
{
 
207
  Table *entry=(Table*) record;
 
208
  *length= entry->getShare()->getCacheKey().size();
 
209
  return (unsigned char*) &entry->getShare()->getCacheKey()[0];
 
210
}
 
211
 
67
212
bool table_cache_init(void)
68
213
{
69
214
  return false;
71
216
 
72
217
uint32_t cached_open_tables(void)
73
218
{
74
 
  return table::getCache().size();
 
219
  return get_open_cache().size();
75
220
}
76
221
 
77
222
void table_cache_free(void)
78
223
{
79
224
  refresh_version++;                            // Force close of open tables
80
225
 
81
 
  table::getUnused().clear();
82
 
  table::getCache().clear();
 
226
  unused_tables.clear();
 
227
  get_open_cache().clear();
83
228
}
84
229
 
85
230
/*
93
238
  By leaving the table in the table cache, it disallows any other thread
94
239
  to open the table
95
240
 
96
 
  session->getKilled() will be set if we run out of memory
 
241
  session->killed will be set if we run out of memory
97
242
 
98
243
  If closing a MERGE child, the calling function has to take care for
99
244
  closing the parent too, if necessary.
102
247
 
103
248
void close_handle_and_leave_table_as_lock(Table *table)
104
249
{
 
250
  TableShare *share, *old_share= table->getMutableShare();
105
251
  assert(table->db_stat);
106
252
  assert(table->getShare()->getType() == message::Table::STANDARD);
107
253
 
112
258
  */
113
259
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
114
260
  const TableIdentifier::Key &key(identifier.getKey());
115
 
  TableShare *share= new TableShare(identifier.getType(),
116
 
                                    identifier,
117
 
                                    const_cast<char *>(key.vector()),  static_cast<uint32_t>(table->getShare()->getCacheKeySize()));
 
261
  share= new TableShare(identifier.getType(),
 
262
                        identifier,
 
263
                        const_cast<char *>(&key[0]),  static_cast<uint32_t>(old_share->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::mutex::scoped_lock 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)
320
489
  {
321
 
    boost_unique_lock_t scopedLock(session->mysys_var->mutex);
 
490
    boost::mutex::scoped_lock scopedLock(session->mysys_var->mutex);
322
491
    session->mysys_var->current_mutex= 0;
323
492
    session->mysys_var->current_cond= 0;
324
493
    session->set_proc_info(0);
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::mutex::scoped_lock 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->getMutableShare()->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::mutex::scoped_lock 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
 
746
940
  cond  Condition to wait for
747
941
*/
748
942
 
749
 
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable_any &cond)
 
943
void Session::wait_for_condition(boost::mutex &mutex, boost::condition_variable &cond)
750
944
{
751
945
  /* Wait until the current table is up to date */
752
946
  const char *saved_proc_info;
765
959
      condition variables that are guranteed to not disapper (freed) even if this
766
960
      mutex is unlocked
767
961
    */
768
 
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
769
 
    if (not getKilled())
 
962
    boost::mutex::scoped_lock scopedLock(mutex, boost::adopt_lock_t());
 
963
    if (not killed)
770
964
    {
771
965
      cond.wait(scopedLock);
772
966
    }
773
967
  }
774
 
  boost_unique_lock_t mysys_scopedLock(mysys_var->mutex);
 
968
  boost::mutex::scoped_lock (mysys_var->mutex);
775
969
  mysys_var->current_mutex= 0;
776
970
  mysys_var->current_cond= 0;
777
971
  set_proc_info(saved_proc_info);
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
  TableShare *share;
 
1002
  char *table_name= table_list->table_name;
 
1003
  Table orig_table;
 
1004
 
 
1005
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1006
 
 
1007
  if (killed || !table)
 
1008
    return true;
 
1009
 
 
1010
  orig_table= *table;
 
1011
 
 
1012
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1013
  if (open_unireg_entry(this, table, table_name, identifier))
 
1014
  {
 
1015
    table->intern_close_table();
 
1016
    /*
 
1017
      If there was an error during opening of table (for example if it
 
1018
      does not exist) '*table' object can be wiped out. To be able
 
1019
      properly release name-lock in this case we should restore this
 
1020
      object to its original state.
 
1021
    */
 
1022
    *table= orig_table;
 
1023
    return true;
 
1024
  }
 
1025
 
 
1026
  share= table->getMutableShare();
 
1027
  /*
 
1028
    We want to prevent other connections from opening this table until end
 
1029
    of statement as it is likely that modifications of table's metadata are
 
1030
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1031
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1032
    This also allows us to assume that no other connection will sneak in
 
1033
    before we will get table-level lock on this table.
 
1034
  */
 
1035
  share->resetVersion();
 
1036
  table->in_use = this;
 
1037
 
 
1038
  if (link_in)
 
1039
  {
 
1040
    table->setNext(open_tables);
 
1041
    open_tables= table;
 
1042
  }
 
1043
  else
 
1044
  {
 
1045
    /*
 
1046
      Table object should be already in Session::open_tables list so we just
 
1047
      need to set Table::next correctly.
 
1048
    */
 
1049
    table->setNext(orig_table.getNext());
 
1050
  }
 
1051
 
 
1052
  table->tablenr= current_tablenr++;
 
1053
  table->used_fields= 0;
 
1054
  table->const_table= 0;
 
1055
  table->null_row= false;
 
1056
  table->maybe_null= false;
 
1057
  table->force_index= false;
 
1058
  table->status= STATUS_NO_RECORD;
 
1059
 
 
1060
  return false;
 
1061
}
 
1062
 
 
1063
 
781
1064
/**
782
1065
  Create and insert into table cache placeholder for table
783
1066
  which will prevent its opening (or creation) (a.k.a lock
791
1074
  case of failure.
792
1075
*/
793
1076
 
794
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::TableIdentifier &arg)
 
1077
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
795
1078
{
796
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1079
  safe_mutex_assert_owner(LOCK_open.native_handle());
797
1080
 
798
1081
  /*
799
1082
    Create a table entry with the right key and with an old refresh version
800
1083
  */
801
 
  TableIdentifier identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
802
 
  table::Placeholder *table= new table::Placeholder(this, identifier);
 
1084
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
 
1085
  TablePlaceholder *table= new TablePlaceholder(this, identifier);
803
1086
 
804
 
  if (not table::Cache::singleton().insert(table))
 
1087
  if (not add_table(table))
805
1088
  {
806
1089
    delete table;
807
1090
 
833
1116
  @retval  true   Error occured (OOM)
834
1117
  @retval  false  Success. 'table' parameter set according to above rules.
835
1118
*/
836
 
bool Session::lock_table_name_if_not_cached(const TableIdentifier &identifier, Table **table)
 
1119
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
837
1120
{
838
1121
  const TableIdentifier::Key &key(identifier.getKey());
839
1122
 
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())
 
1123
  boost::mutex::scoped_lock scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1124
 
 
1125
  TableOpenCache::iterator iter;
 
1126
 
 
1127
  iter= get_open_cache().find(key);
 
1128
 
 
1129
  if (iter != get_open_cache().end())
847
1130
  {
848
1131
    *table= 0;
849
1132
    return false;
850
1133
  }
851
1134
 
852
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1135
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
853
1136
  {
854
1137
    return true;
855
1138
  }
909
1192
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
910
1193
    return NULL;
911
1194
 
912
 
  if (getKilled())
 
1195
  if (killed)
913
1196
    return NULL;
914
1197
 
915
 
  TableIdentifier identifier(table_list->getSchemaName(), table_list->getTableName());
 
1198
  TableIdentifier identifier(table_list->db, table_list->table_name);
916
1199
  const TableIdentifier::Key &key(identifier.getKey());
917
 
  table::CacheRange ppp;
 
1200
  TableOpenCacheRange ppp;
918
1201
 
919
1202
  /*
920
1203
    Unless requested otherwise, try to resolve this table in the list
924
1207
    TODO -> move this block into a separate function.
925
1208
  */
926
1209
  bool reset= false;
927
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1210
  for (table= temporary_tables; table ; table=table->getNext())
928
1211
  {
929
1212
    if (table->getShare()->getCacheKey() == key)
930
1213
    {
949
1232
  {
950
1233
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
951
1234
    {
952
 
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->getSchemaName(), table_list->getTableName());
 
1235
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
953
1236
      return NULL;
954
1237
    }
955
1238
 
994
1277
      until no one holds a name lock on the table.
995
1278
      - if there is no such Table in the name cache, read the table definition
996
1279
      and insert it into the cache.
997
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
 
1280
      We perform all of the above under LOCK_open which currently protects
998
1281
      the open cache (also known as table cache) and table definitions stored
999
1282
      on disk.
1000
1283
    */
1001
1284
 
1002
1285
    {
1003
 
      table::Cache::singleton().mutex().lock(); /* Lock for FLUSH TABLES for open table */
 
1286
      LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
1004
1287
 
1005
1288
      /*
1006
1289
        Actually try to find the table in the open_cache.
1012
1295
        an implicit "pending locks queue" - see
1013
1296
        wait_for_locked_table_names for details.
1014
1297
      */
1015
 
      ppp= table::getCache().equal_range(key);
 
1298
      ppp= get_open_cache().equal_range(key);
1016
1299
 
1017
1300
      table= NULL;
1018
 
      for (table::CacheMap::const_iterator iter= ppp.first;
 
1301
      for (TableOpenCache::const_iterator iter= ppp.first;
1019
1302
           iter != ppp.second; ++iter, table= NULL)
1020
1303
      {
1021
1304
        table= (*iter).second;
1052
1335
          /* Avoid self-deadlocks by detecting self-dependencies. */
1053
1336
          if (table->open_placeholder && table->in_use == this)
1054
1337
          {
1055
 
            table::Cache::singleton().mutex().unlock();
1056
 
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
 
1338
            LOCK_open.unlock();
 
1339
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getMutableShare()->getTableName());
1057
1340
            return NULL;
1058
1341
          }
1059
1342
 
1085
1368
          */
1086
1369
          if (table->in_use != this)
1087
1370
          {
1088
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1089
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
 
1371
            /* wait_for_conditionwill unlock LOCK_open for us */
 
1372
            wait_for_condition(LOCK_open, COND_refresh);
1090
1373
          }
1091
1374
          else
1092
1375
          {
1093
 
            table::Cache::singleton().mutex().unlock();
 
1376
            LOCK_open.unlock();
1094
1377
          }
1095
1378
          /*
1096
1379
            There is a refresh in progress for this table.
1103
1386
      }
1104
1387
      if (table)
1105
1388
      {
1106
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
 
1389
        unused_tables.unlink(table);
1107
1390
        table->in_use= this;
1108
1391
      }
1109
1392
      else
1111
1394
        /* Insert a new Table instance into the open cache */
1112
1395
        int error;
1113
1396
        /* Free cache if too big */
1114
 
        table::getUnused().cull();
 
1397
        unused_tables.cull();
1115
1398
 
1116
1399
        if (table_list->isCreate())
1117
1400
        {
1118
 
          TableIdentifier  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
 
1401
          TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
1119
1402
 
1120
1403
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1121
1404
          {
1122
1405
            /*
1123
1406
              Table to be created, so we need to create placeholder in table-cache.
1124
1407
            */
1125
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
 
1408
            if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1126
1409
            {
1127
 
              table::Cache::singleton().mutex().unlock();
 
1410
              LOCK_open.unlock();
1128
1411
              return NULL;
1129
1412
            }
1130
1413
            /*
1135
1418
            table->open_placeholder= true;
1136
1419
            table->setNext(open_tables);
1137
1420
            open_tables= table;
1138
 
            table::Cache::singleton().mutex().unlock();
 
1421
            LOCK_open.unlock();
1139
1422
 
1140
1423
            return table ;
1141
1424
          }
1143
1426
        }
1144
1427
 
1145
1428
        /* make a new table */
 
1429
        table= new Table;
 
1430
        if (table == NULL)
1146
1431
        {
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
 
          }
 
1432
          LOCK_open.unlock();
 
1433
          return NULL;
 
1434
        }
1154
1435
 
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);
 
1436
        error= open_unireg_entry(this, table, alias, identifier);
 
1437
        if (error != 0)
 
1438
        {
 
1439
          delete table;
 
1440
          LOCK_open.unlock();
 
1441
          return NULL;
1163
1442
        }
 
1443
        (void)add_table(table);
1164
1444
      }
1165
1445
 
1166
 
      table::Cache::singleton().mutex().unlock();
 
1446
      LOCK_open.unlock();
1167
1447
    }
1168
1448
    if (refresh)
1169
1449
    {
1175
1455
  }
1176
1456
  assert(table->getShare()->getTableCount() > 0 || table->getShare()->getType() != message::Table::STANDARD);
1177
1457
 
 
1458
  if (lex->need_correct_ident())
 
1459
    table->alias_name_used= my_strcasecmp(table_alias_charset,
 
1460
                                          table->getMutableShare()->getTableName(), alias);
1178
1461
  /* Fix alias if table name changes */
1179
1462
  if (strcmp(table->getAlias(), alias))
1180
1463
  {
1181
 
    table->setAlias(alias);
 
1464
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1465
    table->alias= (char*) realloc((char*) table->alias, length);
 
1466
    memcpy((void*) table->alias, alias, length);
1182
1467
  }
1183
1468
 
1184
1469
  /* These variables are also set in reopen_table() */
1222
1507
  the strings are used in a loop even after the share may be freed.
1223
1508
*/
1224
1509
 
1225
 
void Session::close_data_files_and_morph_locks(const TableIdentifier &identifier)
 
1510
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1226
1511
{
1227
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1512
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1228
1513
 
1229
1514
  if (lock)
1230
1515
  {
1232
1517
      If we are not under LOCK TABLES we should have only one table
1233
1518
      open and locked so it makes sense to remove the lock at once.
1234
1519
    */
1235
 
    unlockTables(lock);
 
1520
    mysql_unlock_tables(this, lock);
1236
1521
    lock= 0;
1237
1522
  }
1238
1523
 
1267
1552
  combination when one needs tables to be reopened (for
1268
1553
  example see openTablesLock()).
1269
1554
 
1270
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1555
  @note One should have lock on LOCK_open when calling this.
1271
1556
 
1272
1557
  @return false in case of success, true - otherwise.
1273
1558
*/
1284
1569
  if (open_tables == NULL)
1285
1570
    return false;
1286
1571
 
1287
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1572
  safe_mutex_assert_owner(LOCK_open.native_handle());
1288
1573
  if (get_locks)
1289
1574
  {
1290
1575
    /*
1311
1596
    next= table->getNext();
1312
1597
 
1313
1598
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1314
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1599
    remove_table(table);
1315
1600
    error= 1;
1316
1601
  }
1317
1602
  *prev=0;
1320
1605
    DrizzleLock *local_lock;
1321
1606
    /*
1322
1607
      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
 
1608
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1609
      already locked.
1325
1610
    */
1326
1611
    some_tables_deleted= false;
1327
1612
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables),
1329
 
                                       flags, &not_used)))
 
1613
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1614
                                 flags, &not_used)))
1330
1615
    {
1331
1616
      /* unused */
1332
1617
    }
1345
1630
  if (get_locks && tables)
1346
1631
    delete [] tables;
1347
1632
 
1348
 
  locking::broadcast_refresh();
 
1633
  broadcast_refresh();
1349
1634
 
1350
1635
  return(error);
1351
1636
}
1392
1677
              lock on it. This will also give them a chance to close their
1393
1678
              instances of this table.
1394
1679
            */
1395
 
            abortLock(ulcktbl);
1396
 
            removeLock(ulcktbl);
 
1680
            mysql_lock_abort(this, ulcktbl);
 
1681
            mysql_lock_remove(this, ulcktbl);
1397
1682
            ulcktbl->lock_count= 0;
1398
1683
          }
1399
1684
          if ((ulcktbl != table) && ulcktbl->db_stat)
1433
1718
    }
1434
1719
  }
1435
1720
  if (found)
1436
 
    locking::broadcast_refresh();
 
1721
    broadcast_refresh();
 
1722
}
 
1723
 
 
1724
 
 
1725
/*
 
1726
  Wait until all threads has closed the tables in the list
 
1727
  We have also to wait if there is thread that has a lock on this table even
 
1728
  if the table is closed
 
1729
*/
 
1730
 
 
1731
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1732
{
 
1733
  do
 
1734
  {
 
1735
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1736
 
 
1737
    TableOpenCacheRange ppp;
 
1738
    ppp= get_open_cache().equal_range(key);
 
1739
 
 
1740
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1741
         iter != ppp.second; ++iter)
 
1742
    {
 
1743
      Table *search= (*iter).second;
 
1744
      if (search->in_use == table->in_use)
 
1745
        continue;                               // Name locked by this thread
 
1746
      /*
 
1747
        We can't use the table under any of the following conditions:
 
1748
        - There is an name lock on it (Table is to be deleted or altered)
 
1749
        - If we are in flush table and we didn't execute the flush
 
1750
        - If the table engine is open and it's an old version
 
1751
        (We must wait until all engines are shut down to use the table)
 
1752
      */
 
1753
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1754
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1755
        return 1;
 
1756
    }
 
1757
  } while ((table=table->getNext()));
 
1758
  return 0;
1437
1759
}
1438
1760
 
1439
1761
 
1445
1767
 
1446
1768
  session->set_proc_info("Waiting for tables");
1447
1769
  {
1448
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex());
1449
 
    while (not session->getKilled())
 
1770
    boost::mutex::scoped_lock lock(LOCK_open);
 
1771
    while (!session->killed)
1450
1772
    {
1451
1773
      session->some_tables_deleted= false;
1452
1774
      session->close_old_data_files(false, dropping_tables != 0);
1453
 
      if (not table::Cache::singleton().areTablesUsed(session->open_tables, 1))
1454
 
      {
 
1775
      if (!table_is_used(session->open_tables, 1))
1455
1776
        break;
1456
 
      }
1457
1777
      COND_refresh.wait(lock);
1458
1778
    }
1459
 
    if (session->getKilled())
 
1779
    if (session->killed)
1460
1780
      result= true;                                     // aborted
1461
1781
    else
1462
1782
    {
1502
1822
  prev= &session->open_tables;
1503
1823
 
1504
1824
  /*
1505
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1825
    Note that we need to hold LOCK_open while changing the
1506
1826
    open_tables list. Another thread may work on it.
1507
 
    (See: table::Cache::singleton().removeTable(), mysql_wait_completed_table())
 
1827
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1508
1828
    Closing a MERGE child before the parent would be fatal if the
1509
1829
    other thread tries to abort the MERGE lock in between.
1510
1830
  */
1513
1833
    next=table->getNext();
1514
1834
    if (table->getShare()->getCacheKey() == identifier.getKey())
1515
1835
    {
1516
 
      session->removeLock(table);
 
1836
      mysql_lock_remove(session, table);
1517
1837
 
1518
1838
      if (!found)
1519
1839
      {
1528
1848
      else
1529
1849
      {
1530
1850
        /* We already have a name lock, remove copy */
1531
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1851
        remove_table(table);
1532
1852
      }
1533
1853
    }
1534
1854
    else
1539
1859
  }
1540
1860
  *prev=0;
1541
1861
  if (found)
1542
 
    locking::broadcast_refresh();
 
1862
    broadcast_refresh();
1543
1863
 
1544
1864
  return(found);
1545
1865
}
1559
1879
    if (table->getShare()->getCacheKey() == identifier.getKey())
1560
1880
    {
1561
1881
      /* If MERGE child, forward lock handling to parent. */
1562
 
      session->abortLock(table);
 
1882
      mysql_lock_abort(session, table);
1563
1883
      break;
1564
1884
    }
1565
1885
  }
1566
1886
}
1567
1887
 
 
1888
/*
 
1889
  Load a table definition from cursor and open unireg table
 
1890
 
 
1891
  SYNOPSIS
 
1892
  open_unireg_entry()
 
1893
  session                       Thread handle
 
1894
  entry         Store open table definition here
 
1895
  table_list            TableList with db, table_name
 
1896
  alias         Alias name
 
1897
  cache_key             Key for share_cache
 
1898
  cache_key_length      length of cache_key
 
1899
 
 
1900
  NOTES
 
1901
  Extra argument for open is taken from session->open_options
 
1902
  One must have a lock on LOCK_open when calling this function
 
1903
 
 
1904
  RETURN
 
1905
  0     ok
 
1906
#       Error
 
1907
*/
 
1908
 
 
1909
static int open_unireg_entry(Session *session,
 
1910
                             Table *entry,
 
1911
                             const char *alias,
 
1912
                             TableIdentifier &identifier)
 
1913
{
 
1914
  int error;
 
1915
  TableShare *share;
 
1916
  uint32_t discover_retry_count= 0;
 
1917
 
 
1918
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1919
retry:
 
1920
  if (not (share= TableShare::getShareCreate(session,
 
1921
                                             identifier,
 
1922
                                             &error)))
 
1923
    return 1;
 
1924
 
 
1925
  while ((error= share->open_table_from_share(session,
 
1926
                                              identifier,
 
1927
                                              alias,
 
1928
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1929
                                                          HA_OPEN_RNDFILE |
 
1930
                                                          HA_GET_INDEX |
 
1931
                                                          HA_TRY_READ_ONLY),
 
1932
                                              session->open_options, *entry)))
 
1933
  {
 
1934
    if (error == 7)                             // Table def changed
 
1935
    {
 
1936
      share->resetVersion();                        // Mark share as old
 
1937
      if (discover_retry_count++)               // Retry once
 
1938
        goto err;
 
1939
 
 
1940
      /*
 
1941
        TODO->
 
1942
        Here we should wait until all threads has released the table.
 
1943
        For now we do one retry. This may cause a deadlock if there
 
1944
        is other threads waiting for other tables used by this thread.
 
1945
 
 
1946
        Proper fix would be to if the second retry failed:
 
1947
        - Mark that table def changed
 
1948
        - Return from open table
 
1949
        - Close all tables used by this thread
 
1950
        - Start waiting that the share is released
 
1951
        - Retry by opening all tables again
 
1952
      */
 
1953
 
 
1954
      /*
 
1955
        TO BE FIXED
 
1956
        To avoid deadlock, only wait for release if no one else is
 
1957
        using the share.
 
1958
      */
 
1959
      if (share->getTableCount() != 1)
 
1960
        goto err;
 
1961
      /* Free share and wait until it's released by all threads */
 
1962
      TableShare::release(share);
 
1963
 
 
1964
      if (!session->killed)
 
1965
      {
 
1966
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1967
        session->clear_error();                 // Clear error message
 
1968
        goto retry;
 
1969
      }
 
1970
      return 1;
 
1971
    }
 
1972
 
 
1973
    goto err;
 
1974
  }
 
1975
 
 
1976
  return 0;
 
1977
 
 
1978
err:
 
1979
  TableShare::release(share);
 
1980
 
 
1981
  return 1;
 
1982
}
 
1983
 
1568
1984
 
1569
1985
/*
1570
1986
  Open all tables in list
1632
2048
     * to see if it exists so that an unauthorized user cannot phish for
1633
2049
     * table/schema information via error messages
1634
2050
     */
1635
 
    TableIdentifier the_table(tables->getSchemaName(), tables->getTableName());
 
2051
    TableIdentifier the_table(tables->db, tables->table_name);
1636
2052
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
1637
2053
                                                the_table))
1638
2054
    {
1742
2158
 
1743
2159
    assert(lock == 0);  // You must lock everything at once
1744
2160
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1745
 
      if (! (lock= lockTables(&table_list->table, 1, 0, &refresh)))
 
2161
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
1746
2162
        table= 0;
1747
2163
  }
1748
2164
 
1805
2221
      *(ptr++)= table->table;
1806
2222
  }
1807
2223
 
1808
 
  if (!(session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag, need_reopen)))
 
2224
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2225
                                         lock_flag, need_reopen)))
1809
2226
  {
1810
2227
    return -1;
1811
2228
  }
1834
2251
#  Table object
1835
2252
*/
1836
2253
 
1837
 
Table *Open_tables_state::open_temporary_table(const TableIdentifier &identifier,
1838
 
                                               bool link_in_list)
 
2254
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2255
                                     bool link_in_list)
1839
2256
{
 
2257
  TableShare *share;
 
2258
 
1840
2259
  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()));
 
2260
  share= new TableShare(identifier.getType(),
 
2261
                        identifier,
 
2262
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2263
 
 
2264
 
 
2265
  Table *new_tmp_table= new Table;
1847
2266
  if (not new_tmp_table)
1848
2267
    return NULL;
1849
2268
 
1850
2269
  /*
1851
2270
    First open the share, and then open the table from the share we just opened.
1852
2271
  */
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))
 
2272
  if (share->open_table_def(*this, identifier) ||
 
2273
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2274
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2275
                                        HA_GET_INDEX),
 
2276
                            ha_open_options,
 
2277
                            *new_tmp_table))
1859
2278
  {
1860
2279
    /* No need to lock share->mutex as this is not needed for tmp tables */
1861
 
    delete new_tmp_table->getMutableShare();
 
2280
    delete share;
1862
2281
    delete new_tmp_table;
1863
2282
 
1864
2283
    return 0;
1900
2319
{
1901
2320
  if (session->mark_used_columns != MARK_COLUMNS_NONE)
1902
2321
  {
1903
 
    boost::dynamic_bitset<> *current_bitmap= NULL;
 
2322
    MyBitmap *current_bitmap, *other_bitmap;
1904
2323
 
1905
2324
    /*
1906
2325
      We always want to register the used keys, as the column bitmap may have
1913
2332
    if (session->mark_used_columns == MARK_COLUMNS_READ)
1914
2333
    {
1915
2334
      current_bitmap= table->read_set;
 
2335
      other_bitmap=   table->write_set;
1916
2336
    }
1917
2337
    else
1918
2338
    {
1919
2339
      current_bitmap= table->write_set;
 
2340
      other_bitmap=   table->read_set;
1920
2341
    }
1921
2342
 
1922
 
    //if (current_bitmap->testAndSet(field->position()))
1923
 
    if (current_bitmap->test(field->position()))
 
2343
    if (current_bitmap->testAndSet(field->field_index))
1924
2344
    {
1925
2345
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1926
2346
        session->dup_field= field;
2154
2574
      */
2155
2575
      table_name && table_name[0] &&
2156
2576
      (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()))))
 
2577
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2578
        strcmp(db_name, table_list->db))))
2159
2579
    return 0;
2160
2580
 
2161
2581
  *actual_table= NULL;
2230
2650
      {
2231
2651
        Table *table= field_to_set->getTable();
2232
2652
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2233
 
          table->setReadSet(field_to_set->position());
 
2653
          table->setReadSet(field_to_set->field_index);
2234
2654
        else
2235
 
          table->setWriteSet(field_to_set->position());
 
2655
          table->setWriteSet(field_to_set->field_index);
2236
2656
      }
2237
2657
    }
2238
2658
  }
2788
3208
    /* true if field_name_1 is a member of using_fields */
2789
3209
    bool is_using_column_1;
2790
3210
    if (!(nj_col_1= it_1.get_or_create_column_ref(leaf_1)))
2791
 
      return(result);
 
3211
      goto err;
2792
3212
    field_name_1= nj_col_1->name();
2793
3213
    is_using_column_1= using_fields &&
2794
3214
      test_if_string_in_list(field_name_1, using_fields);
2806
3226
      Natural_join_column *cur_nj_col_2;
2807
3227
      const char *cur_field_name_2;
2808
3228
      if (!(cur_nj_col_2= it_2.get_or_create_column_ref(leaf_2)))
2809
 
        return(result);
 
3229
        goto err;
2810
3230
      cur_field_name_2= cur_nj_col_2->name();
2811
3231
 
2812
3232
      /*
2826
3246
            (found && (!using_fields || is_using_column_1)))
2827
3247
        {
2828
3248
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2829
 
          return(result);
 
3249
          goto err;
2830
3250
        }
2831
3251
        nj_col_2= cur_nj_col_2;
2832
3252
        found= true;
2859
3279
      Item_func_eq *eq_cond;
2860
3280
 
2861
3281
      if (!item_1 || !item_2)
2862
 
        return(result); // out of memory
 
3282
        goto err;                               // out of memory
2863
3283
 
2864
3284
      /*
2865
3285
        In the case of no_wrap_view_item == 0, the created items must be
2884
3304
      */
2885
3305
      if (set_new_item_local_context(session, item_ident_1, nj_col_1->table_ref) ||
2886
3306
          set_new_item_local_context(session, item_ident_2, nj_col_2->table_ref))
2887
 
        return(result);
 
3307
        goto err;
2888
3308
 
2889
3309
      if (!(eq_cond= new Item_func_eq(item_ident_1, item_ident_2)))
2890
 
        return(result);                               /* Out of memory. */
 
3310
        goto err;                               /* Out of memory. */
2891
3311
 
2892
3312
      /*
2893
3313
        Add the new equi-join condition to the ON clause. Notice that
2904
3324
      {
2905
3325
        Table *table_1= nj_col_1->table_ref->table;
2906
3326
        /* Mark field_1 used for table cache. */
2907
 
        table_1->setReadSet(field_1->position());
 
3327
        table_1->setReadSet(field_1->field_index);
2908
3328
        table_1->covering_keys&= field_1->part_of_key;
2909
3329
        table_1->merge_keys|= field_1->part_of_key;
2910
3330
      }
2912
3332
      {
2913
3333
        Table *table_2= nj_col_2->table_ref->table;
2914
3334
        /* Mark field_2 used for table cache. */
2915
 
        table_2->setReadSet(field_2->position());
 
3335
        table_2->setReadSet(field_2->field_index);
2916
3336
        table_2->covering_keys&= field_2->part_of_key;
2917
3337
        table_2->merge_keys|= field_2->part_of_key;
2918
3338
      }
2933
3353
  */
2934
3354
  result= false;
2935
3355
 
 
3356
err:
2936
3357
  return(result);
2937
3358
}
2938
3359
 
2990
3411
 
2991
3412
  if (!(non_join_columns= new List<Natural_join_column>) ||
2992
3413
      !(natural_using_join->join_columns= new List<Natural_join_column>))
2993
 
  {
2994
 
    return(result);
2995
 
  }
 
3414
    goto err;
2996
3415
 
2997
3416
  /* Append the columns of the first join operand. */
2998
3417
  for (it_1.set(table_ref_1); !it_1.end_of_fields(); it_1.next())
3031
3450
        {
3032
3451
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
3033
3452
                   session->where);
3034
 
          return(result);
 
3453
          goto err;
3035
3454
        }
3036
3455
        if (!my_strcasecmp(system_charset_info,
3037
3456
                           common_field->name(), using_field_name_ptr))
3059
3478
 
3060
3479
  result= false;
3061
3480
 
 
3481
err:
3062
3482
  return(result);
3063
3483
}
3064
3484
 
3144
3564
      if (cur_table_ref->getNestedJoin() &&
3145
3565
          store_top_level_join_columns(session, cur_table_ref,
3146
3566
                                       real_left_neighbor, real_right_neighbor))
3147
 
        return(result);
 
3567
        goto err;
3148
3568
      same_level_right_neighbor= cur_table_ref;
3149
3569
    }
3150
3570
  }
3176
3596
      std::swap(table_ref_1, table_ref_2);
3177
3597
    if (mark_common_columns(session, table_ref_1, table_ref_2,
3178
3598
                            using_fields, &found_using_fields))
3179
 
      return(result);
 
3599
      goto err;
3180
3600
 
3181
3601
    /*
3182
3602
      Swap the join operands back, so that we pick the columns of the second
3188
3608
    if (store_natural_using_join_columns(session, table_ref, table_ref_1,
3189
3609
                                         table_ref_2, using_fields,
3190
3610
                                         found_using_fields))
3191
 
      return(result);
 
3611
      goto err;
3192
3612
 
3193
3613
    /*
3194
3614
      Change NATURAL JOIN to JOIN ... ON. We do this for both operands
3221
3641
  }
3222
3642
  result= false; /* All is OK. */
3223
3643
 
 
3644
err:
3224
3645
  return(result);
3225
3646
}
3226
3647
 
3622
4043
    assert(tables->is_leaf_for_name_resolution());
3623
4044
 
3624
4045
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3625
 
        (db_name && strcasecmp(tables->getSchemaName(),db_name)))
 
4046
        (db_name && strcasecmp(tables->db,db_name)))
3626
4047
      continue;
3627
4048
 
3628
4049
    /*
3658
4079
      if ((field= field_iterator.field()))
3659
4080
      {
3660
4081
        /* Mark fields as used to allow storage engine to optimze access */
3661
 
        field->getTable()->setReadSet(field->position());
 
4082
        field->getTable()->setReadSet(field->field_index);
3662
4083
        if (table)
3663
4084
        {
3664
4085
          table->covering_keys&= field->part_of_key;
3865
4286
    if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
3866
4287
    {
3867
4288
      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;
 
4289
      goto err;
3872
4290
    }
3873
4291
  }
3874
4292
 
3875
4293
  return session->is_error();
 
4294
 
 
4295
err:
 
4296
  if (table)
 
4297
    table->auto_increment_field_not_null= false;
 
4298
 
 
4299
  return true;
3876
4300
}
3877
4301
 
3878
4302
 
3922
4346
    if (field == table->next_number_field)
3923
4347
      table->auto_increment_field_not_null= true;
3924
4348
    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
 
    }
 
4349
      goto err;
3931
4350
  }
3932
4351
 
3933
4352
  return(session->is_error());
 
4353
 
 
4354
err:
 
4355
  if (table)
 
4356
    table->auto_increment_field_not_null= false;
 
4357
 
 
4358
  return true;
3934
4359
}
3935
4360
 
3936
4361
 
3947
4372
 
3948
4373
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3949
4374
 
 
4375
  session->lockForDelete();
3950
4376
  delete session;
3951
4377
 
3952
4378
  return false;
3958
4384
  unireg support functions
3959
4385
 *****************************************************************************/
3960
4386
 
3961
 
 
 
4387
/*
 
4388
  Invalidate any cache entries that are for some DB
 
4389
 
 
4390
  SYNOPSIS
 
4391
  remove_db_from_cache()
 
4392
  db            Database name. This will be in lower case if
 
4393
  lower_case_table_name is set
 
4394
 
 
4395
NOTE:
 
4396
We can't use hash_delete when looping hash_elements. We mark them first
 
4397
and afterwards delete those marked unused.
 
4398
*/
 
4399
 
 
4400
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4401
{
 
4402
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4403
 
 
4404
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4405
       iter != get_open_cache().end();
 
4406
       iter++)
 
4407
  {
 
4408
    Table *table= (*iter).second;
 
4409
 
 
4410
    if (not schema_identifier.getPath().compare(table->getMutableShare()->getSchemaName()))
 
4411
    {
 
4412
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4413
      if (not table->in_use)
 
4414
        unused_tables.relink(table);
 
4415
    }
 
4416
  }
 
4417
 
 
4418
  unused_tables.cullByVersion();
 
4419
}
 
4420
 
 
4421
 
 
4422
/*
 
4423
  Mark all entries with the table as deleted to force an reopen of the table
 
4424
 
 
4425
  The table will be closed (not stored in cache) by the current thread when
 
4426
  close_thread_tables() is called.
 
4427
 
 
4428
  PREREQUISITES
 
4429
  Lock on LOCK_open()
 
4430
 
 
4431
  RETURN
 
4432
  0  This thread now have exclusive access to this table and no other thread
 
4433
  can access the table until close_thread_tables() is called.
 
4434
  1  Table is in use by another thread
 
4435
*/
 
4436
 
 
4437
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4438
{
 
4439
  const TableIdentifier::Key &key(identifier.getKey());
 
4440
  bool result= false; 
 
4441
  bool signalled= false;
 
4442
 
 
4443
  for (;;)
 
4444
  {
 
4445
    result= signalled= false;
 
4446
 
 
4447
    TableOpenCacheRange ppp;
 
4448
    ppp= get_open_cache().equal_range(key);
 
4449
 
 
4450
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4451
         iter != ppp.second; ++iter)
 
4452
    {
 
4453
      Table *table= (*iter).second;
 
4454
      Session *in_use;
 
4455
 
 
4456
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4457
      if (!(in_use=table->in_use))
 
4458
      {
 
4459
        unused_tables.relink(table);
 
4460
      }
 
4461
      else if (in_use != session)
 
4462
      {
 
4463
        /*
 
4464
          Mark that table is going to be deleted from cache. This will
 
4465
          force threads that are in mysql_lock_tables() (but not yet
 
4466
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4467
        */
 
4468
        in_use->some_tables_deleted= true;
 
4469
        if (table->is_name_opened())
 
4470
        {
 
4471
          result= true;
 
4472
        }
 
4473
        /*
 
4474
          Now we must abort all tables locks used by this thread
 
4475
          as the thread may be waiting to get a lock for another table.
 
4476
          Note that we need to hold LOCK_open while going through the
 
4477
          list. So that the other thread cannot change it. The other
 
4478
          thread must also hold LOCK_open whenever changing the
 
4479
          open_tables list. Aborting the MERGE lock after a child was
 
4480
          closed and before the parent is closed would be fatal.
 
4481
        */
 
4482
        for (Table *session_table= in_use->open_tables;
 
4483
             session_table ;
 
4484
             session_table= session_table->getNext())
 
4485
        {
 
4486
          /* Do not handle locks of MERGE children. */
 
4487
          if (session_table->db_stat)   // If table is open
 
4488
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4489
        }
 
4490
      }
 
4491
      else
 
4492
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4493
    }
 
4494
 
 
4495
    unused_tables.cullByVersion();
 
4496
 
 
4497
    /* Remove table from table definition cache if it's not in use */
 
4498
    TableShare::release(identifier);
 
4499
 
 
4500
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4501
    {
 
4502
      /*
 
4503
        Signal any thread waiting for tables to be freed to
 
4504
        reopen their tables
 
4505
      */
 
4506
      broadcast_refresh();
 
4507
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4508
      {
 
4509
        dropping_tables++;
 
4510
        if (likely(signalled))
 
4511
        {
 
4512
          boost::mutex::scoped_lock scoped(LOCK_open, boost::adopt_lock_t());
 
4513
          COND_refresh.wait(scoped);
 
4514
          scoped.release();
 
4515
        }
 
4516
        else
 
4517
        {
 
4518
          /*
 
4519
            It can happen that another thread has opened the
 
4520
            table but has not yet locked any table at all. Since
 
4521
            it can be locked waiting for a table that our thread
 
4522
            has done LOCK Table x WRITE on previously, we need to
 
4523
            ensure that the thread actually hears our signal
 
4524
            before we go to sleep. Thus we wait for a short time
 
4525
            and then we retry another loop in the
 
4526
            remove_table_from_cache routine.
 
4527
          */
 
4528
          boost::xtime xt; 
 
4529
          xtime_get(&xt, boost::TIME_UTC); 
 
4530
          xt.sec += 10; 
 
4531
          boost::mutex::scoped_lock scoped(LOCK_open, boost::adopt_lock_t());
 
4532
          COND_refresh.timed_wait(scoped, xt);
 
4533
          scoped.release();
 
4534
        }
 
4535
        dropping_tables--;
 
4536
        continue;
 
4537
      }
 
4538
    }
 
4539
    break;
 
4540
  }
 
4541
 
 
4542
  return result;
 
4543
}
3962
4544
 
3963
4545
 
3964
4546
/**