~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_base.cc

Fix merge issue.

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
 
16
16
 
17
17
/* Basic functions needed by many modules */
18
 
#include <config.h>
 
18
#include "config.h"
19
19
#include <assert.h>
20
20
 
21
21
#include <signal.h>
30
30
#  include <time.h>
31
31
# endif
32
32
#endif
33
 
#include <drizzled/internal/my_pthread.h>
34
 
#include <drizzled/internal/thread_var.h>
 
33
#include "drizzled/internal/my_pthread.h"
 
34
#include "drizzled/internal/thread_var.h"
35
35
 
36
36
#include <drizzled/sql_select.h>
37
37
#include <drizzled/error.h>
44
44
#include <drizzled/check_stack_overrun.h>
45
45
#include <drizzled/lock.h>
46
46
#include <drizzled/plugin/listen.h>
47
 
#include <drizzled/cached_directory.h>
48
 
#include <drizzled/field/epoch.h>
 
47
#include "drizzled/cached_directory.h"
 
48
#include <drizzled/field/timestamp.h>
49
49
#include <drizzled/field/null.h>
50
 
#include <drizzled/sql_table.h>
51
 
#include <drizzled/global_charset_info.h>
52
 
#include <drizzled/pthread_globals.h>
53
 
#include <drizzled/internal/iocache.h>
54
 
#include <drizzled/drizzled.h>
55
 
#include <drizzled/plugin/authorization.h>
56
 
#include <drizzled/table/temporary.h>
57
 
#include <drizzled/table/placeholder.h>
58
 
#include <drizzled/table/unused.h>
59
 
#include <drizzled/plugin/storage_engine.h>
60
 
#include <drizzled/session.h>
61
 
 
62
 
#include <drizzled/refresh_version.h>
 
50
#include "drizzled/sql_table.h"
 
51
#include "drizzled/global_charset_info.h"
 
52
#include "drizzled/pthread_globals.h"
 
53
#include "drizzled/internal/iocache.h"
 
54
#include "drizzled/drizzled.h"
 
55
#include "drizzled/plugin/authorization.h"
 
56
#include "drizzled/table/temporary.h"
 
57
#include "drizzled/table/placeholder.h"
63
58
 
64
59
using namespace std;
65
60
 
68
63
 
69
64
extern bool volatile shutdown_in_progress;
70
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::Concurrent *entry);
 
74
 
 
75
void remove_table(table::Concurrent *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::Concurrent *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::Concurrent *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::Concurrent *tables;                            /* Used by mysql_test */
 
105
 
 
106
  table::Concurrent *getTable() const
 
107
  {
 
108
    return tables;
 
109
  }
 
110
 
 
111
  table::Concurrent *setTable(Table *arg)
 
112
  {
 
113
    return tables= dynamic_cast<table::Concurrent *>(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::Concurrent *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::Concurrent *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::Concurrent *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
 
71
213
bool table_cache_init(void)
72
214
{
73
215
  return false;
75
217
 
76
218
uint32_t cached_open_tables(void)
77
219
{
78
 
  return table::getCache().size();
 
220
  return get_open_cache().size();
79
221
}
80
222
 
81
223
void table_cache_free(void)
82
224
{
83
225
  refresh_version++;                            // Force close of open tables
84
226
 
85
 
  table::getUnused().clear();
86
 
  table::getCache().clear();
 
227
  unused_tables.clear();
 
228
  get_open_cache().clear();
87
229
}
88
230
 
89
231
/*
97
239
  By leaving the table in the table cache, it disallows any other thread
98
240
  to open the table
99
241
 
100
 
  session->getKilled() will be set if we run out of memory
 
242
  session->killed will be set if we run out of memory
101
243
 
102
244
  If closing a MERGE child, the calling function has to take care for
103
245
  closing the parent too, if necessary.
114
256
    This has to be done to ensure that the table share is removed from
115
257
    the table defintion cache as soon as the last instance is removed
116
258
  */
117
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
118
 
  const identifier::Table::Key &key(identifier.getKey());
 
259
  TableIdentifier identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName(), message::Table::INTERNAL);
 
260
  const TableIdentifier::Key &key(identifier.getKey());
119
261
  TableShare *share= new TableShare(identifier.getType(),
120
262
                                    identifier,
121
 
                                    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()));
122
264
 
123
265
  table->cursor->close();
124
266
  table->db_stat= 0;                            // Mark cursor closed
125
 
  table::instance::release(table->getMutableShare());
 
267
  TableShare::release(table->getMutableShare());
126
268
  table->setShare(share);
 
269
  table->cursor->change_table_ptr(table, table->getMutableShare());
127
270
}
128
271
 
129
272
 
141
284
  }
142
285
}
143
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::Concurrent *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
 
144
309
/* Free resources allocated by filesort() and read_record() */
145
310
 
146
311
void Table::free_io_cache()
147
312
{
148
313
  if (sort.io_cache)
149
314
  {
150
 
    sort.io_cache->close_cached_file();
151
 
    safe_delete(sort.io_cache);
 
315
    close_cached_file(sort.io_cache);
 
316
    delete sort.io_cache;
 
317
    sort.io_cache= 0;
152
318
  }
153
319
}
154
320
 
158
324
 
159
325
  @param session Thread context (may be NULL)
160
326
  @param tables List of tables to remove from the cache
161
 
  @param have_lock If table::Cache::singleton().mutex() is locked
 
327
  @param have_lock If LOCK_open is locked
162
328
  @param wait_for_refresh Wait for a impending flush
163
329
  @param wait_for_placeholders Wait for tables being reopened so that the GRL
164
330
  won't proceed while write-locked tables are being reopened by other
174
340
  Session *session= this;
175
341
 
176
342
  {
177
 
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* 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 */
178
344
 
179
345
    if (tables == NULL)
180
346
    {
181
347
      refresh_version++;                                // Force close of open tables
182
348
 
183
 
      table::getUnused().clear();
 
349
      unused_tables.clear();
184
350
 
185
351
      if (wait_for_refresh)
186
352
      {
211
377
          again. There they will wait until we update all tables version
212
378
          below.
213
379
 
214
 
          Setting some_tables_deleted is done by table::Cache::singleton().removeTable()
 
380
          Setting some_tables_deleted is done by remove_table_from_cache()
215
381
          in the other branch.
216
382
 
217
383
          In other words (reviewer suggestion): You need this setting of
221
387
          after the call to Session::close_old_data_files() i.e. after removal of
222
388
          current thread locks.
223
389
        */
224
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
225
 
             iter != table::getCache().end();
 
390
        for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
391
             iter != get_open_cache().end();
226
392
             iter++)
227
393
        {
228
394
          Table *table= (*iter).second;
236
402
      bool found= false;
237
403
      for (TableList *table= tables; table; table= table->next_local)
238
404
      {
239
 
        identifier::Table identifier(table->getSchemaName(), table->getTableName());
240
 
        if (table::Cache::singleton().removeTable(session, identifier,
 
405
        TableIdentifier identifier(table->db, table->table_name);
 
406
        if (remove_table_from_cache(session, identifier,
241
407
                                    RTFC_OWNED_BY_Session_FLAG))
242
408
        {
243
409
          found= true;
253
419
        If there is any table that has a lower refresh_version, wait until
254
420
        this is closed (or this thread is killed) before returning
255
421
      */
256
 
      session->mysys_var->current_mutex= &table::Cache::singleton().mutex();
 
422
      session->mysys_var->current_mutex= &LOCK_open;
257
423
      session->mysys_var->current_cond= &COND_refresh;
258
424
      session->set_proc_info("Flushing tables");
259
425
 
261
427
 
262
428
      bool found= true;
263
429
      /* Wait until all threads has closed all the tables we had locked */
264
 
      while (found && ! session->getKilled())
 
430
      while (found && ! session->killed)
265
431
      {
266
432
        found= false;
267
 
        for (table::CacheMap::const_iterator iter= table::getCache().begin();
268
 
             iter != table::getCache().end();
 
433
        for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
434
             iter != get_open_cache().end();
269
435
             iter++)
270
436
        {
271
437
          Table *table= (*iter).second;
290
456
                                                     (table->open_placeholder && wait_for_placeholders)))
291
457
          {
292
458
            found= true;
293
 
            COND_refresh.wait(scopedLock);
 
459
            boost_unique_lock_t scoped(LOCK_open, boost::adopt_lock_t());
 
460
            COND_refresh.wait(scoped);
 
461
            scoped.release();
294
462
            break;
295
463
          }
296
464
        }
300
468
        old locks. This should always succeed (unless some external process
301
469
        has removed the tables)
302
470
      */
303
 
      result= session->reopen_tables();
 
471
      result= session->reopen_tables(true, true);
304
472
 
305
473
      /* Set version for table */
306
474
      for (Table *table= session->open_tables; table ; table= table->getNext())
313
481
          table->getMutableShare()->refreshVersion();
314
482
      }
315
483
    }
 
484
 
 
485
    LOCK_open.unlock();
316
486
  }
317
487
 
318
488
  if (wait_for_refresh)
331
501
  move one table to free list 
332
502
*/
333
503
 
334
 
bool Session::free_cached_table(boost::mutex::scoped_lock &scopedLock)
 
504
bool Session::free_cached_table()
335
505
{
336
506
  bool found_old_table= false;
337
 
 
338
 
  (void)scopedLock;
339
 
 
340
 
  table::Concurrent *table= static_cast<table::Concurrent *>(open_tables);
341
 
 
342
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
507
  table::Concurrent *table= dynamic_cast<table::Concurrent *>(open_tables);
 
508
 
 
509
  safe_mutex_assert_owner(LOCK_open.native_handle());
343
510
  assert(table->key_read == 0);
344
511
  assert(!table->cursor || table->cursor->inited == Cursor::NONE);
345
512
 
348
515
  if (table->needs_reopen_or_name_lock() ||
349
516
      version != refresh_version || !table->db_stat)
350
517
  {
351
 
    table::remove_table(table);
 
518
    remove_table(table);
352
519
    found_old_table= true;
353
520
  }
354
521
  else
361
528
 
362
529
    /* Free memory and reset for next loop */
363
530
    table->cursor->ha_reset();
364
 
    table->in_use= NULL;
 
531
    table->in_use= false;
365
532
 
366
 
    table::getUnused().link(table);
 
533
    unused_tables.link(table);
367
534
  }
368
535
 
369
536
  return found_old_table;
382
549
{
383
550
  bool found_old_table= false;
384
551
 
385
 
  safe_mutex_assert_not_owner(table::Cache::singleton().mutex().native_handle());
 
552
  safe_mutex_assert_not_owner(LOCK_open.native_handle());
386
553
 
387
 
  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 */
388
555
 
389
556
  while (open_tables)
390
557
  {
391
 
    found_old_table|= free_cached_table(scoped_lock);
 
558
    found_old_table|= free_cached_table();
392
559
  }
393
560
  some_tables_deleted= false;
394
561
 
395
562
  if (found_old_table)
396
563
  {
397
564
    /* Tell threads waiting for refresh that something has happened */
398
 
    locking::broadcast_refresh();
 
565
    broadcast_refresh();
399
566
  }
400
567
}
401
568
 
424
591
{
425
592
  for (; table; table= table->*link )
426
593
  {
427
 
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) and
428
 
        my_strcasecmp(system_charset_info, table->getSchemaName(), db_name) == 0 and
429
 
        my_strcasecmp(system_charset_info, table->getTableName(), table_name) == 0)
430
 
    {
 
594
    if ((table->table == 0 || table->table->getShare()->getType() == message::Table::STANDARD) &&
 
595
        strcasecmp(table->db, db_name) == 0 &&
 
596
        strcasecmp(table->table_name, table_name) == 0)
431
597
      break;
432
 
    }
433
598
  }
434
599
  return table;
435
600
}
499
664
    */
500
665
    assert(table);
501
666
  }
502
 
  d_name= table->getSchemaName();
503
 
  t_name= table->getTableName();
 
667
  d_name= table->db;
 
668
  t_name= table->table_name;
504
669
  t_alias= table->alias;
505
670
 
506
671
  for (;;)
521
686
}
522
687
 
523
688
 
524
 
void Open_tables_state::doGetTableNames(const identifier::Schema &schema_identifier,
525
 
                                        std::set<std::string>& set_of_names)
 
689
void Session::doGetTableNames(const SchemaIdentifier &schema_identifier,
 
690
                              std::set<std::string>& set_of_names)
526
691
{
527
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
692
  for (Table *table= temporary_tables ; table ; table= table->getNext())
528
693
  {
529
694
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
530
695
    {
533
698
  }
534
699
}
535
700
 
536
 
void Open_tables_state::doGetTableNames(CachedDirectory &,
537
 
                                        const identifier::Schema &schema_identifier,
538
 
                                        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)
539
704
{
540
705
  doGetTableNames(schema_identifier, set_of_names);
541
706
}
542
707
 
543
 
void Open_tables_state::doGetTableIdentifiers(const identifier::Schema &schema_identifier,
544
 
                                              identifier::Table::vector &set_of_identifiers)
 
708
void Session::doGetTableIdentifiers(const SchemaIdentifier &schema_identifier,
 
709
                                    TableIdentifiers &set_of_identifiers)
545
710
{
546
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
711
  for (Table *table= temporary_tables ; table ; table= table->getNext())
547
712
  {
548
713
    if (schema_identifier.compare(table->getShare()->getSchemaName()))
549
714
    {
550
 
      set_of_identifiers.push_back(identifier::Table(table->getShare()->getSchemaName(),
 
715
      set_of_identifiers.push_back(TableIdentifier(table->getShare()->getSchemaName(),
551
716
                                                   table->getShare()->getTableName(),
552
717
                                                   table->getShare()->getPath()));
553
718
    }
554
719
  }
555
720
}
556
721
 
557
 
void Open_tables_state::doGetTableIdentifiers(CachedDirectory &,
558
 
                                              const identifier::Schema &schema_identifier,
559
 
                                              identifier::Table::vector &set_of_identifiers)
 
722
void Session::doGetTableIdentifiers(CachedDirectory &,
 
723
                                    const SchemaIdentifier &schema_identifier,
 
724
                                    TableIdentifiers &set_of_identifiers)
560
725
{
561
726
  doGetTableIdentifiers(schema_identifier, set_of_identifiers);
562
727
}
563
728
 
564
 
bool Open_tables_state::doDoesTableExist(const identifier::Table &identifier)
 
729
bool Session::doDoesTableExist(const TableIdentifier &identifier)
565
730
{
566
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
731
  for (Table *table= temporary_tables ; table ; table= table->getNext())
567
732
  {
568
733
    if (table->getShare()->getType() == message::Table::TEMPORARY)
569
734
    {
577
742
  return false;
578
743
}
579
744
 
580
 
int Open_tables_state::doGetTableDefinition(const identifier::Table &identifier,
581
 
                                            message::Table &table_proto)
 
745
int Session::doGetTableDefinition(const TableIdentifier &identifier,
 
746
                                  message::Table &table_proto)
582
747
{
583
 
  for (Table *table= getTemporaryTables() ; table ; table= table->getNext())
 
748
  for (Table *table= temporary_tables ; table ; table= table->getNext())
584
749
  {
585
750
    if (table->getShare()->getType() == message::Table::TEMPORARY)
586
751
    {
587
752
      if (identifier.getKey() == table->getShare()->getCacheKey())
588
753
      {
589
 
        table_proto.CopyFrom(*(table->getShare()->getTableMessage()));
 
754
        table_proto.CopyFrom(*(table->getShare()->getTableProto()));
590
755
 
591
756
        return EEXIST;
592
757
      }
596
761
  return ENOENT;
597
762
}
598
763
 
599
 
Table *Open_tables_state::find_temporary_table(const identifier::Table &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)
600
789
{
601
790
  for (Table *table= temporary_tables ; table ; table= table->getNext())
602
791
  {
634
823
  @retval -1  the table is in use by a outer query
635
824
*/
636
825
 
637
 
int Open_tables_state::drop_temporary_table(const drizzled::identifier::Table &identifier)
 
826
int Session::drop_temporary_table(TableList *table_list)
638
827
{
639
828
  Table *table;
640
829
 
641
 
  if (not (table= find_temporary_table(identifier)))
 
830
  if (not (table= find_temporary_table(table_list)))
642
831
    return 1;
643
832
 
644
833
  /* Table might be in use by some outer statement. */
645
 
  if (table->query_id && table->query_id != getQueryId())
 
834
  if (table->query_id && table->query_id != query_id)
646
835
  {
647
836
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
648
837
    return -1;
661
850
  @param  session     Thread context
662
851
  @param  find    Table to remove
663
852
 
664
 
  @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.
 
853
  @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 TableSharePtr here.
665
854
*/
666
855
 
667
856
void Session::unlink_open_table(Table *find)
668
857
{
669
 
  const identifier::Table::Key find_key(find->getShare()->getCacheKey());
 
858
  const TableIdentifier::Key find_key(find->getShare()->getCacheKey());
670
859
  Table **prev;
671
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
860
  safe_mutex_assert_owner(LOCK_open.native_handle());
672
861
 
673
862
  /*
674
 
    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
675
864
    open_tables list. Another thread may work on it.
676
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
865
    (See: remove_table_from_cache(), mysql_wait_completed_table())
677
866
    Closing a MERGE child before the parent would be fatal if the
678
867
    other thread tries to abort the MERGE lock in between.
679
868
  */
687
876
      *prev= list->getNext();
688
877
 
689
878
      /* Close table. */
690
 
      table::remove_table(static_cast<table::Concurrent *>(list));
 
879
      remove_table(dynamic_cast<table::Concurrent *>(list));
691
880
    }
692
881
    else
693
882
    {
697
886
  }
698
887
 
699
888
  // Notify any 'refresh' threads
700
 
  locking::broadcast_refresh();
 
889
  broadcast_refresh();
701
890
}
702
891
 
703
892
 
720
909
  table that was locked with LOCK TABLES.
721
910
*/
722
911
 
723
 
void Session::drop_open_table(Table *table, const identifier::Table &identifier)
 
912
void Session::drop_open_table(Table *table, TableIdentifier &identifier)
724
913
{
725
914
  if (table->getShare()->getType())
726
915
  {
728
917
  }
729
918
  else
730
919
  {
731
 
    boost_unique_lock_t scoped_lock(table::Cache::singleton().mutex()); /* Close and drop a table (AUX routine) */
 
920
    boost_unique_lock_t scoped_lock(LOCK_open); /* Close and drop a table (AUX routine) */
732
921
    /*
733
922
      unlink_open_table() also tells threads waiting for refresh or close
734
923
      that something has happened.
735
924
    */
736
925
    unlink_open_table(table);
737
 
    (void)plugin::StorageEngine::dropTable(*this, identifier);
 
926
    quick_rm_table(*this, identifier);
738
927
  }
739
928
}
740
929
 
770
959
      mutex is unlocked
771
960
    */
772
961
    boost_unique_lock_t scopedLock(mutex, boost::adopt_lock_t());
773
 
    if (not getKilled())
 
962
    if (not killed)
774
963
    {
775
964
      cond.wait(scopedLock);
776
965
    }
782
971
}
783
972
 
784
973
 
 
974
/*
 
975
  Open table which is already name-locked by this thread.
 
976
 
 
977
  SYNOPSIS
 
978
  reopen_name_locked_table()
 
979
  session         Thread handle
 
980
  table_list  TableList object for table to be open, TableList::table
 
981
  member should point to Table object which was used for
 
982
  name-locking.
 
983
  link_in     true  - if Table object for table to be opened should be
 
984
  linked into Session::open_tables list.
 
985
  false - placeholder used for name-locking is already in
 
986
  this list so we only need to preserve Table::next
 
987
  pointer.
 
988
 
 
989
  NOTE
 
990
  This function assumes that its caller already acquired LOCK_open mutex.
 
991
 
 
992
  RETURN VALUE
 
993
  false - Success
 
994
  true  - Error
 
995
*/
 
996
 
 
997
bool Session::reopen_name_locked_table(TableList* table_list)
 
998
{
 
999
  Table *table= table_list->table;
 
1000
  char *table_name= table_list->table_name;
 
1001
 
 
1002
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1003
 
 
1004
  if (killed || not table)
 
1005
    return true;
 
1006
 
 
1007
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1008
  if (open_unireg_entry(this, table, table_name, identifier))
 
1009
  {
 
1010
    table->intern_close_table();
 
1011
    return true;
 
1012
  }
 
1013
 
 
1014
  /*
 
1015
    We want to prevent other connections from opening this table until end
 
1016
    of statement as it is likely that modifications of table's metadata are
 
1017
    not yet finished (for example CREATE TRIGGER have to change .TRG cursor,
 
1018
    or we might want to drop table if CREATE TABLE ... SELECT fails).
 
1019
    This also allows us to assume that no other connection will sneak in
 
1020
    before we will get table-level lock on this table.
 
1021
  */
 
1022
  table->getMutableShare()->resetVersion();
 
1023
  table->in_use = this;
 
1024
 
 
1025
  table->tablenr= current_tablenr++;
 
1026
  table->used_fields= 0;
 
1027
  table->const_table= 0;
 
1028
  table->null_row= false;
 
1029
  table->maybe_null= false;
 
1030
  table->force_index= false;
 
1031
  table->status= STATUS_NO_RECORD;
 
1032
 
 
1033
  return false;
 
1034
}
 
1035
 
 
1036
 
785
1037
/**
786
1038
  Create and insert into table cache placeholder for table
787
1039
  which will prevent its opening (or creation) (a.k.a lock
795
1047
  case of failure.
796
1048
*/
797
1049
 
798
 
table::Placeholder *Session::table_cache_insert_placeholder(const drizzled::identifier::Table &arg)
 
1050
Table *Session::table_cache_insert_placeholder(const char *db_name, const char *table_name)
799
1051
{
800
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1052
  safe_mutex_assert_owner(LOCK_open.native_handle());
801
1053
 
802
1054
  /*
803
1055
    Create a table entry with the right key and with an old refresh version
804
1056
  */
805
 
  identifier::Table identifier(arg.getSchemaName(), arg.getTableName(), message::Table::INTERNAL);
 
1057
  TableIdentifier identifier(db_name, table_name, message::Table::INTERNAL);
806
1058
  table::Placeholder *table= new table::Placeholder(this, identifier);
807
1059
 
808
 
  if (not table::Cache::singleton().insert(table))
 
1060
  if (not add_table(table))
809
1061
  {
810
 
    safe_delete(table);
 
1062
    delete table;
811
1063
 
812
1064
    return NULL;
813
1065
  }
837
1089
  @retval  true   Error occured (OOM)
838
1090
  @retval  false  Success. 'table' parameter set according to above rules.
839
1091
*/
840
 
bool Session::lock_table_name_if_not_cached(const identifier::Table &identifier, Table **table)
 
1092
bool Session::lock_table_name_if_not_cached(TableIdentifier &identifier, Table **table)
841
1093
{
842
 
  const identifier::Table::Key &key(identifier.getKey());
843
 
 
844
 
  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)  */
845
 
 
846
 
  table::CacheMap::iterator iter;
847
 
 
848
 
  iter= table::getCache().find(key);
849
 
 
850
 
  if (iter != table::getCache().end())
 
1094
  const TableIdentifier::Key &key(identifier.getKey());
 
1095
 
 
1096
  boost_unique_lock_t scope_lock(LOCK_open); /* Obtain a name lock even though table is not in cache (like for create table)  */
 
1097
 
 
1098
  TableOpenCache::iterator iter;
 
1099
 
 
1100
  iter= get_open_cache().find(key);
 
1101
 
 
1102
  if (iter != get_open_cache().end())
851
1103
  {
852
1104
    *table= 0;
853
1105
    return false;
854
1106
  }
855
1107
 
856
 
  if (not (*table= table_cache_insert_placeholder(identifier)))
 
1108
  if (not (*table= table_cache_insert_placeholder(identifier.getSchemaName().c_str(), identifier.getTableName().c_str())))
857
1109
  {
858
1110
    return true;
859
1111
  }
913
1165
  if (check_stack_overrun(this, STACK_MIN_SIZE_FOR_OPEN, (unsigned char *)&alias))
914
1166
    return NULL;
915
1167
 
916
 
  if (getKilled())
 
1168
  if (killed)
917
1169
    return NULL;
918
1170
 
919
 
  identifier::Table identifier(table_list->getSchemaName(), table_list->getTableName());
920
 
  const identifier::Table::Key &key(identifier.getKey());
921
 
  table::CacheRange ppp;
 
1171
  TableIdentifier identifier(table_list->db, table_list->table_name);
 
1172
  const TableIdentifier::Key &key(identifier.getKey());
 
1173
  TableOpenCacheRange ppp;
922
1174
 
923
1175
  /*
924
1176
    Unless requested otherwise, try to resolve this table in the list
928
1180
    TODO -> move this block into a separate function.
929
1181
  */
930
1182
  bool reset= false;
931
 
  for (table= getTemporaryTables(); table ; table=table->getNext())
 
1183
  for (table= temporary_tables; table ; table=table->getNext())
932
1184
  {
933
1185
    if (table->getShare()->getCacheKey() == key)
934
1186
    {
953
1205
  {
954
1206
    if (flags & DRIZZLE_OPEN_TEMPORARY_ONLY)
955
1207
    {
956
 
      my_error(ER_TABLE_UNKNOWN, identifier);
 
1208
      my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db, table_list->table_name);
957
1209
      return NULL;
958
1210
    }
959
1211
 
998
1250
      until no one holds a name lock on the table.
999
1251
      - if there is no such Table in the name cache, read the table definition
1000
1252
      and insert it into the cache.
1001
 
      We perform all of the above under table::Cache::singleton().mutex() which currently protects
 
1253
      We perform all of the above under LOCK_open which currently protects
1002
1254
      the open cache (also known as table cache) and table definitions stored
1003
1255
      on disk.
1004
1256
    */
1005
1257
 
1006
1258
    {
1007
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
 
1259
      LOCK_open.lock(); /* Lock for FLUSH TABLES for open table */
1008
1260
 
1009
1261
      /*
1010
1262
        Actually try to find the table in the open_cache.
1016
1268
        an implicit "pending locks queue" - see
1017
1269
        wait_for_locked_table_names for details.
1018
1270
      */
1019
 
      ppp= table::getCache().equal_range(key);
 
1271
      ppp= get_open_cache().equal_range(key);
1020
1272
 
1021
1273
      table= NULL;
1022
 
      for (table::CacheMap::const_iterator iter= ppp.first;
 
1274
      for (TableOpenCache::const_iterator iter= ppp.first;
1023
1275
           iter != ppp.second; ++iter, table= NULL)
1024
1276
      {
1025
1277
        table= (*iter).second;
1056
1308
          /* Avoid self-deadlocks by detecting self-dependencies. */
1057
1309
          if (table->open_placeholder && table->in_use == this)
1058
1310
          {
 
1311
            LOCK_open.unlock();
1059
1312
            my_error(ER_UPDATE_TABLE_USED, MYF(0), table->getShare()->getTableName());
1060
1313
            return NULL;
1061
1314
          }
1088
1341
          */
1089
1342
          if (table->in_use != this)
1090
1343
          {
1091
 
            /* wait_for_conditionwill unlock table::Cache::singleton().mutex() for us */
1092
 
            wait_for_condition(table::Cache::singleton().mutex(), COND_refresh);
1093
 
            scopedLock.release();
 
1344
            /* wait_for_conditionwill unlock LOCK_open for us */
 
1345
            wait_for_condition(LOCK_open, COND_refresh);
1094
1346
          }
1095
1347
          else
1096
1348
          {
1097
 
            scopedLock.unlock();
 
1349
            LOCK_open.unlock();
1098
1350
          }
1099
 
 
1100
1351
          /*
1101
1352
            There is a refresh in progress for this table.
1102
1353
            Signal the caller that it has to try again.
1103
1354
          */
1104
1355
          if (refresh)
1105
1356
            *refresh= true;
1106
 
 
1107
1357
          return NULL;
1108
1358
        }
1109
1359
      }
1110
 
 
1111
1360
      if (table)
1112
1361
      {
1113
 
        table::getUnused().unlink(static_cast<table::Concurrent *>(table));
 
1362
        unused_tables.unlink(dynamic_cast<table::Concurrent *>(table));
1114
1363
        table->in_use= this;
1115
1364
      }
1116
1365
      else
1118
1367
        /* Insert a new Table instance into the open cache */
1119
1368
        int error;
1120
1369
        /* Free cache if too big */
1121
 
        table::getUnused().cull();
 
1370
        unused_tables.cull();
1122
1371
 
1123
1372
        if (table_list->isCreate())
1124
1373
        {
1125
 
          identifier::Table  lock_table_identifier(table_list->getSchemaName(), table_list->getTableName(), message::Table::STANDARD);
 
1374
          TableIdentifier  lock_table_identifier(table_list->db, table_list->table_name, message::Table::STANDARD);
1126
1375
 
1127
1376
          if (not plugin::StorageEngine::doesTableExist(*this, lock_table_identifier))
1128
1377
          {
1129
1378
            /*
1130
1379
              Table to be created, so we need to create placeholder in table-cache.
1131
1380
            */
1132
 
            if (!(table= table_cache_insert_placeholder(lock_table_identifier)))
 
1381
            if (!(table= table_cache_insert_placeholder(table_list->db, table_list->table_name)))
1133
1382
            {
 
1383
              LOCK_open.unlock();
1134
1384
              return NULL;
1135
1385
            }
1136
1386
            /*
1141
1391
            table->open_placeholder= true;
1142
1392
            table->setNext(open_tables);
1143
1393
            open_tables= table;
 
1394
            LOCK_open.unlock();
1144
1395
 
1145
1396
            return table ;
1146
1397
          }
1153
1404
          table= new_table;
1154
1405
          if (new_table == NULL)
1155
1406
          {
 
1407
            LOCK_open.unlock();
1156
1408
            return NULL;
1157
1409
          }
1158
1410
 
1159
 
          error= new_table->open_unireg_entry(this, alias, identifier);
 
1411
          error= open_unireg_entry(this, new_table, alias, identifier);
1160
1412
          if (error != 0)
1161
1413
          {
1162
1414
            delete new_table;
 
1415
            LOCK_open.unlock();
1163
1416
            return NULL;
1164
1417
          }
1165
 
          (void)table::Cache::singleton().insert(new_table);
 
1418
          (void)add_table(new_table);
1166
1419
        }
1167
1420
      }
 
1421
 
 
1422
      LOCK_open.unlock();
1168
1423
    }
1169
 
 
1170
1424
    if (refresh)
1171
1425
    {
1172
1426
      table->setNext(open_tables); /* Link into simple list */
1180
1434
  /* Fix alias if table name changes */
1181
1435
  if (strcmp(table->getAlias(), alias))
1182
1436
  {
1183
 
    table->setAlias(alias);
 
1437
    uint32_t length=(uint32_t) strlen(alias)+1;
 
1438
    table->alias= (char*) realloc((char*) table->alias, length);
 
1439
    memcpy((void*) table->alias, alias, length);
1184
1440
  }
1185
1441
 
1186
1442
  /* These variables are also set in reopen_table() */
1224
1480
  the strings are used in a loop even after the share may be freed.
1225
1481
*/
1226
1482
 
1227
 
void Session::close_data_files_and_morph_locks(const identifier::Table &identifier)
 
1483
void Session::close_data_files_and_morph_locks(TableIdentifier &identifier)
1228
1484
{
1229
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle()); /* Adjust locks at the end of ALTER TABLEL */
 
1485
  safe_mutex_assert_owner(LOCK_open.native_handle()); /* Adjust locks at the end of ALTER TABLEL */
1230
1486
 
1231
1487
  if (lock)
1232
1488
  {
1234
1490
      If we are not under LOCK TABLES we should have only one table
1235
1491
      open and locked so it makes sense to remove the lock at once.
1236
1492
    */
1237
 
    unlockTables(lock);
 
1493
    mysql_unlock_tables(this, lock);
1238
1494
    lock= 0;
1239
1495
  }
1240
1496
 
1269
1525
  combination when one needs tables to be reopened (for
1270
1526
  example see openTablesLock()).
1271
1527
 
1272
 
  @note One should have lock on table::Cache::singleton().mutex() when calling this.
 
1528
  @note One should have lock on LOCK_open when calling this.
1273
1529
 
1274
1530
  @return false in case of success, true - otherwise.
1275
1531
*/
1276
1532
 
1277
 
bool Session::reopen_tables()
 
1533
bool Session::reopen_tables(bool get_locks, bool)
1278
1534
{
1279
1535
  Table *table,*next,**prev;
1280
 
  Table **tables= 0;                    // For locks
1281
 
  Table **tables_ptr= 0;                        // For locks
1282
 
  bool error= false;
 
1536
  Table **tables,**tables_ptr;                  // For locks
 
1537
  bool error=0, not_used;
1283
1538
  const uint32_t flags= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN |
1284
1539
    DRIZZLE_LOCK_IGNORE_GLOBAL_READ_LOCK |
1285
1540
    DRIZZLE_LOCK_IGNORE_FLUSH;
1287
1542
  if (open_tables == NULL)
1288
1543
    return false;
1289
1544
 
1290
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1545
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1546
  if (get_locks)
1291
1547
  {
1292
1548
    /*
1293
1549
      The ptr is checked later
1301
1557
    }
1302
1558
    tables= new Table *[opens];
1303
1559
  }
1304
 
 
 
1560
  else
 
1561
  {
 
1562
    tables= &open_tables;
 
1563
  }
1305
1564
  tables_ptr =tables;
1306
1565
 
1307
1566
  prev= &open_tables;
1310
1569
    next= table->getNext();
1311
1570
 
1312
1571
    my_error(ER_CANT_REOPEN_TABLE, MYF(0), table->getAlias());
1313
 
    table::remove_table(static_cast<table::Concurrent *>(table));
 
1572
    remove_table(dynamic_cast<table::Concurrent *>(table));
1314
1573
    error= 1;
1315
1574
  }
1316
1575
  *prev=0;
1317
 
 
1318
1576
  if (tables != tables_ptr)                     // Should we get back old locks
1319
1577
  {
1320
1578
    DrizzleLock *local_lock;
1321
1579
    /*
1322
1580
      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
 
1581
      wait_for_tables() as it tries to acquire LOCK_open, which is
1324
1582
      already locked.
1325
1583
    */
1326
1584
    some_tables_deleted= false;
1327
1585
 
1328
 
    if ((local_lock= lockTables(tables, (uint32_t) (tables_ptr - tables), flags)))
 
1586
    if ((local_lock= mysql_lock_tables(this, tables, (uint32_t) (tables_ptr - tables),
 
1587
                                 flags, &not_used)))
1329
1588
    {
1330
1589
      /* unused */
1331
1590
    }
1341
1600
    }
1342
1601
  }
1343
1602
 
1344
 
  delete [] tables;
1345
 
 
1346
 
  locking::broadcast_refresh();
1347
 
 
1348
 
  return error;
 
1603
  if (get_locks && tables)
 
1604
    delete [] tables;
 
1605
 
 
1606
  broadcast_refresh();
 
1607
 
 
1608
  return(error);
1349
1609
}
1350
1610
 
1351
1611
 
1376
1636
    */
1377
1637
    if (table->needs_reopen_or_name_lock())
1378
1638
    {
1379
 
      found= true;
 
1639
      found=1;
1380
1640
      if (table->db_stat)
1381
1641
      {
1382
1642
        if (morph_locks)
1390
1650
              lock on it. This will also give them a chance to close their
1391
1651
              instances of this table.
1392
1652
            */
1393
 
            abortLock(ulcktbl);
1394
 
            removeLock(ulcktbl);
 
1653
            mysql_lock_abort(this, ulcktbl);
 
1654
            mysql_lock_remove(this, ulcktbl);
1395
1655
            ulcktbl->lock_count= 0;
1396
1656
          }
1397
1657
          if ((ulcktbl != table) && ulcktbl->db_stat)
1431
1691
    }
1432
1692
  }
1433
1693
  if (found)
1434
 
    locking::broadcast_refresh();
 
1694
    broadcast_refresh();
 
1695
}
 
1696
 
 
1697
 
 
1698
/*
 
1699
  Wait until all threads has closed the tables in the list
 
1700
  We have also to wait if there is thread that has a lock on this table even
 
1701
  if the table is closed
 
1702
*/
 
1703
 
 
1704
bool table_is_used(Table *table, bool wait_for_name_lock)
 
1705
{
 
1706
  do
 
1707
  {
 
1708
    const TableIdentifier::Key &key(table->getShare()->getCacheKey());
 
1709
 
 
1710
    TableOpenCacheRange ppp;
 
1711
    ppp= get_open_cache().equal_range(key);
 
1712
 
 
1713
    for (TableOpenCache::const_iterator iter= ppp.first;
 
1714
         iter != ppp.second; ++iter)
 
1715
    {
 
1716
      Table *search= (*iter).second;
 
1717
      if (search->in_use == table->in_use)
 
1718
        continue;                               // Name locked by this thread
 
1719
      /*
 
1720
        We can't use the table under any of the following conditions:
 
1721
        - There is an name lock on it (Table is to be deleted or altered)
 
1722
        - If we are in flush table and we didn't execute the flush
 
1723
        - If the table engine is open and it's an old version
 
1724
        (We must wait until all engines are shut down to use the table)
 
1725
      */
 
1726
      if ( (search->locked_by_name && wait_for_name_lock) ||
 
1727
           (search->is_name_opened() && search->needs_reopen_or_name_lock()))
 
1728
        return 1;
 
1729
    }
 
1730
  } while ((table=table->getNext()));
 
1731
  return 0;
 
1732
}
 
1733
 
 
1734
 
 
1735
/* Wait until all used tables are refreshed */
 
1736
 
 
1737
bool wait_for_tables(Session *session)
 
1738
{
 
1739
  bool result;
 
1740
 
 
1741
  session->set_proc_info("Waiting for tables");
 
1742
  {
 
1743
    boost_unique_lock_t lock(LOCK_open);
 
1744
    while (!session->killed)
 
1745
    {
 
1746
      session->some_tables_deleted= false;
 
1747
      session->close_old_data_files(false, dropping_tables != 0);
 
1748
      if (!table_is_used(session->open_tables, 1))
 
1749
        break;
 
1750
      COND_refresh.wait(lock);
 
1751
    }
 
1752
    if (session->killed)
 
1753
      result= true;                                     // aborted
 
1754
    else
 
1755
    {
 
1756
      /* Now we can open all tables without any interference */
 
1757
      session->set_proc_info("Reopen tables");
 
1758
      session->version= refresh_version;
 
1759
      result= session->reopen_tables(false, false);
 
1760
    }
 
1761
  }
 
1762
  session->set_proc_info(0);
 
1763
 
 
1764
  return result;
1435
1765
}
1436
1766
 
1437
1767
 
1459
1789
*/
1460
1790
 
1461
1791
 
1462
 
Table *drop_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1792
Table *drop_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1463
1793
{
1464
1794
  Table *table,*next,**prev, *found= 0;
1465
1795
  prev= &session->open_tables;
1466
1796
 
1467
1797
  /*
1468
 
    Note that we need to hold table::Cache::singleton().mutex() while changing the
 
1798
    Note that we need to hold LOCK_open while changing the
1469
1799
    open_tables list. Another thread may work on it.
1470
 
    (See: table::Cache::singleton().removeTable(), wait_completed_table())
 
1800
    (See: remove_table_from_cache(), mysql_wait_completed_table())
1471
1801
    Closing a MERGE child before the parent would be fatal if the
1472
1802
    other thread tries to abort the MERGE lock in between.
1473
1803
  */
1476
1806
    next=table->getNext();
1477
1807
    if (table->getShare()->getCacheKey() == identifier.getKey())
1478
1808
    {
1479
 
      session->removeLock(table);
 
1809
      mysql_lock_remove(session, table);
1480
1810
 
1481
1811
      if (!found)
1482
1812
      {
1491
1821
      else
1492
1822
      {
1493
1823
        /* We already have a name lock, remove copy */
1494
 
        table::remove_table(static_cast<table::Concurrent *>(table));
 
1824
        remove_table(dynamic_cast<table::Concurrent *>(table));
1495
1825
      }
1496
1826
    }
1497
1827
    else
1501
1831
    }
1502
1832
  }
1503
1833
  *prev=0;
1504
 
 
1505
1834
  if (found)
1506
 
    locking::broadcast_refresh();
 
1835
    broadcast_refresh();
1507
1836
 
1508
 
  return found;
 
1837
  return(found);
1509
1838
}
1510
1839
 
1511
1840
 
1515
1844
  other threads trying to get the lock.
1516
1845
*/
1517
1846
 
1518
 
void abort_locked_tables(Session *session, const drizzled::identifier::Table &identifier)
 
1847
void abort_locked_tables(Session *session, const drizzled::TableIdentifier &identifier)
1519
1848
{
1520
1849
  Table *table;
1521
1850
  for (table= session->open_tables; table ; table= table->getNext())
1523
1852
    if (table->getShare()->getCacheKey() == identifier.getKey())
1524
1853
    {
1525
1854
      /* If MERGE child, forward lock handling to parent. */
1526
 
      session->abortLock(table);
1527
 
      assert(0);
 
1855
      mysql_lock_abort(session, table);
1528
1856
      break;
1529
1857
    }
1530
1858
  }
1531
1859
}
1532
1860
 
 
1861
/*
 
1862
  Load a table definition from cursor and open unireg table
 
1863
 
 
1864
  SYNOPSIS
 
1865
  open_unireg_entry()
 
1866
  session                       Thread handle
 
1867
  entry         Store open table definition here
 
1868
  table_list            TableList with db, table_name
 
1869
  alias         Alias name
 
1870
  cache_key             Key for share_cache
 
1871
  cache_key_length      length of cache_key
 
1872
 
 
1873
  NOTES
 
1874
  Extra argument for open is taken from session->open_options
 
1875
  One must have a lock on LOCK_open when calling this function
 
1876
 
 
1877
  RETURN
 
1878
  0     ok
 
1879
#       Error
 
1880
*/
 
1881
 
 
1882
static int open_unireg_entry(Session *session,
 
1883
                             Table *entry,
 
1884
                             const char *alias,
 
1885
                             TableIdentifier &identifier)
 
1886
{
 
1887
  int error;
 
1888
  TableSharePtr share;
 
1889
  uint32_t discover_retry_count= 0;
 
1890
 
 
1891
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
1892
retry:
 
1893
  if (not (share= TableShare::getShareCreate(session,
 
1894
                                             identifier,
 
1895
                                             &error)))
 
1896
    return 1;
 
1897
 
 
1898
  while ((error= share->open_table_from_share(session,
 
1899
                                              identifier,
 
1900
                                              alias,
 
1901
                                              (uint32_t) (HA_OPEN_KEYFILE |
 
1902
                                                          HA_OPEN_RNDFILE |
 
1903
                                                          HA_GET_INDEX |
 
1904
                                                          HA_TRY_READ_ONLY),
 
1905
                                              session->open_options, *entry)))
 
1906
  {
 
1907
    if (error == 7)                             // Table def changed
 
1908
    {
 
1909
      share->resetVersion();                        // Mark share as old
 
1910
      if (discover_retry_count++)               // Retry once
 
1911
      {
 
1912
        TableShare::release(share);
 
1913
        return 1;
 
1914
      }
 
1915
 
 
1916
      /*
 
1917
        TODO->
 
1918
        Here we should wait until all threads has released the table.
 
1919
        For now we do one retry. This may cause a deadlock if there
 
1920
        is other threads waiting for other tables used by this thread.
 
1921
 
 
1922
        Proper fix would be to if the second retry failed:
 
1923
        - Mark that table def changed
 
1924
        - Return from open table
 
1925
        - Close all tables used by this thread
 
1926
        - Start waiting that the share is released
 
1927
        - Retry by opening all tables again
 
1928
      */
 
1929
 
 
1930
      /*
 
1931
        TO BE FIXED
 
1932
        To avoid deadlock, only wait for release if no one else is
 
1933
        using the share.
 
1934
      */
 
1935
      if (share->getTableCount() != 1)
 
1936
      {
 
1937
        TableShare::release(share);
 
1938
        return 1;
 
1939
      }
 
1940
      /* Free share and wait until it's released by all threads */
 
1941
      TableShare::release(share);
 
1942
 
 
1943
      if (!session->killed)
 
1944
      {
 
1945
        drizzle_reset_errors(session, 1);         // Clear warnings
 
1946
        session->clear_error();                 // Clear error message
 
1947
        goto retry;
 
1948
      }
 
1949
      return 1;
 
1950
    }
 
1951
 
 
1952
    TableShare::release(share);
 
1953
 
 
1954
    return 1;
 
1955
  }
 
1956
 
 
1957
  return 0;
 
1958
}
 
1959
 
1533
1960
 
1534
1961
/*
1535
1962
  Open all tables in list
1597
2024
     * to see if it exists so that an unauthorized user cannot phish for
1598
2025
     * table/schema information via error messages
1599
2026
     */
1600
 
    identifier::Table the_table(tables->getSchemaName(), tables->getTableName());
1601
 
    if (not plugin::Authorization::isAuthorized(*user(), the_table))
 
2027
    TableIdentifier the_table(tables->db, tables->table_name);
 
2028
    if (not plugin::Authorization::isAuthorized(getSecurityContext(),
 
2029
                                                the_table))
1602
2030
    {
1603
2031
      result= -1;                               // Fatal error
1604
2032
      break;
1695
2123
 
1696
2124
  set_proc_info("Opening table");
1697
2125
  current_tablenr= 0;
1698
 
  while (!(table= openTable(table_list, &refresh)) && refresh) ;
 
2126
  while (!(table= openTable(table_list, &refresh)) &&
 
2127
         refresh)
 
2128
    ;
1699
2129
 
1700
2130
  if (table)
1701
2131
  {
1704
2134
 
1705
2135
    assert(lock == 0);  // You must lock everything at once
1706
2136
    if ((table->reginfo.lock_type= lock_type) != TL_UNLOCK)
1707
 
    {
1708
 
      if (not (lock= lockTables(&table_list->table, 1, 0)))
1709
 
        table= NULL;
1710
 
    }
 
2137
      if (! (lock= mysql_lock_tables(this, &table_list->table, 1, 0, &refresh)))
 
2138
        table= 0;
1711
2139
  }
1712
2140
 
1713
2141
  set_proc_info(0);
1761
2189
  Table **start,**ptr;
1762
2190
  uint32_t lock_flag= DRIZZLE_LOCK_NOTIFY_IF_NEED_REOPEN;
1763
2191
 
1764
 
  if (!(ptr=start=(Table**) session->getMemRoot()->allocate(sizeof(Table*)*count)))
 
2192
  if (!(ptr=start=(Table**) session->alloc(sizeof(Table*)*count)))
1765
2193
    return -1;
1766
 
 
1767
2194
  for (table= tables; table; table= table->next_global)
1768
2195
  {
1769
2196
    if (!table->placeholder())
1770
2197
      *(ptr++)= table->table;
1771
2198
  }
1772
2199
 
1773
 
  if (not (session->lock= session->lockTables(start, (uint32_t) (ptr - start), lock_flag)))
 
2200
  if (!(session->lock= mysql_lock_tables(session, start, (uint32_t) (ptr - start),
 
2201
                                         lock_flag, need_reopen)))
1774
2202
  {
1775
2203
    return -1;
1776
2204
  }
1799
2227
#  Table object
1800
2228
*/
1801
2229
 
1802
 
Table *Open_tables_state::open_temporary_table(const identifier::Table &identifier,
1803
 
                                               bool link_in_list)
 
2230
Table *Session::open_temporary_table(TableIdentifier &identifier,
 
2231
                                     bool link_in_list)
1804
2232
{
 
2233
  TableShare *share;
 
2234
 
1805
2235
  assert(identifier.isTmp());
1806
 
 
1807
 
 
1808
 
  table::Temporary *new_tmp_table= new table::Temporary(identifier.getType(),
1809
 
                                                        identifier,
1810
 
                                                        const_cast<char *>(const_cast<identifier::Table&>(identifier).getPath().c_str()),
1811
 
                                                        static_cast<uint32_t>(identifier.getPath().length()));
 
2236
  share= new TableShare(identifier.getType(),
 
2237
                        identifier,
 
2238
                        const_cast<char *>(identifier.getPath().c_str()), static_cast<uint32_t>(identifier.getPath().length()));
 
2239
 
 
2240
 
 
2241
  table::Temporary *new_tmp_table= new table::Temporary;
1812
2242
  if (not new_tmp_table)
1813
2243
    return NULL;
1814
2244
 
1815
2245
  /*
1816
2246
    First open the share, and then open the table from the share we just opened.
1817
2247
  */
1818
 
  if (new_tmp_table->getMutableShare()->open_table_def(*static_cast<Session *>(this), identifier) ||
1819
 
      new_tmp_table->getMutableShare()->open_table_from_share(static_cast<Session *>(this), identifier, identifier.getTableName().c_str(),
1820
 
                                                              (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
1821
 
                                                                          HA_GET_INDEX),
1822
 
                                                              ha_open_options,
1823
 
                                                              *new_tmp_table))
 
2248
  if (share->open_table_def(*this, identifier) ||
 
2249
      share->open_table_from_share(this, identifier, identifier.getTableName().c_str(),
 
2250
                            (uint32_t) (HA_OPEN_KEYFILE | HA_OPEN_RNDFILE |
 
2251
                                        HA_GET_INDEX),
 
2252
                            ha_open_options,
 
2253
                            *new_tmp_table))
1824
2254
  {
1825
2255
    /* No need to lock share->mutex as this is not needed for tmp tables */
1826
 
    delete new_tmp_table->getMutableShare();
 
2256
    delete share;
1827
2257
    delete new_tmp_table;
1828
2258
 
1829
2259
    return 0;
1884
2314
      current_bitmap= table->write_set;
1885
2315
    }
1886
2316
 
1887
 
    //if (current_bitmap->testAndSet(field->position()))
1888
 
    if (current_bitmap->test(field->position()))
 
2317
    //if (current_bitmap->testAndSet(field->field_index))
 
2318
    if (current_bitmap->test(field->field_index))
1889
2319
    {
1890
2320
      if (session->mark_used_columns == MARK_COLUMNS_WRITE)
1891
2321
        session->dup_field= field;
1929
2359
                           const char *name, uint32_t , Item **,
1930
2360
                           bool, TableList **actual_table)
1931
2361
{
1932
 
  List<Natural_join_column>::iterator
1933
 
    field_it(table_ref->join_columns->begin());
 
2362
  List_iterator_fast<Natural_join_column>
 
2363
    field_it(*(table_ref->join_columns));
1934
2364
  Natural_join_column *nj_col, *curr_nj_col;
1935
2365
  Field *found_field;
1936
2366
 
1944
2374
    {
1945
2375
      if (nj_col)
1946
2376
      {
1947
 
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where());
 
2377
        my_error(ER_NON_UNIQ_ERROR, MYF(0), name, session->where);
1948
2378
        return NULL;
1949
2379
      }
1950
2380
      nj_col= curr_nj_col;
2119
2549
      */
2120
2550
      table_name && table_name[0] &&
2121
2551
      (my_strcasecmp(table_alias_charset, table_list->alias, table_name) ||
2122
 
       (db_name && db_name[0] && table_list->getSchemaName() && table_list->getSchemaName()[0] &&
2123
 
        strcmp(db_name, table_list->getSchemaName()))))
 
2552
       (db_name && db_name[0] && table_list->db && table_list->db[0] &&
 
2553
        strcmp(db_name, table_list->db))))
2124
2554
    return 0;
2125
2555
 
2126
2556
  *actual_table= NULL;
2145
2575
    */
2146
2576
    if (table_name && table_name[0])
2147
2577
    {
2148
 
      List<TableList>::iterator it(table_list->getNestedJoin()->join_list.begin());
 
2578
      List_iterator<TableList> it(table_list->getNestedJoin()->join_list);
2149
2579
      TableList *table;
2150
2580
      while ((table= it++))
2151
2581
      {
2195
2625
      {
2196
2626
        Table *table= field_to_set->getTable();
2197
2627
        if (session->mark_used_columns == MARK_COLUMNS_READ)
2198
 
          table->setReadSet(field_to_set->position());
 
2628
          table->setReadSet(field_to_set->field_index);
2199
2629
        else
2200
 
          table->setWriteSet(field_to_set->position());
 
2630
          table->setWriteSet(field_to_set->field_index);
2201
2631
      }
2202
2632
    }
2203
2633
  }
2295
2725
        fields.
2296
2726
      */
2297
2727
      {
2298
 
        Select_Lex *current_sel= session->getLex()->current_select;
 
2728
        Select_Lex *current_sel= session->lex->current_select;
2299
2729
        Select_Lex *last_select= table_ref->select_lex;
2300
2730
        /*
2301
2731
          If the field was an outer referencee, mark all selects using this
2341
2771
      */
2342
2772
      item->cached_table= found ?  0 : actual_table;
2343
2773
 
2344
 
      assert(session->where());
 
2774
      assert(session->where);
2345
2775
      /*
2346
2776
        If we found a fully qualified field we return it directly as it can't
2347
2777
        have duplicates.
2354
2784
        if (report_error == REPORT_ALL_ERRORS ||
2355
2785
            report_error == IGNORE_EXCEPT_NON_UNIQUE)
2356
2786
          my_error(ER_NON_UNIQ_ERROR, MYF(0),
2357
 
                   table_name ? item->full_name() : name, session->where());
 
2787
                   table_name ? item->full_name() : name, session->where);
2358
2788
        return (Field*) 0;
2359
2789
      }
2360
2790
      found= cur_field;
2387
2817
      strcat(buff, table_name);
2388
2818
      table_name=buff;
2389
2819
    }
2390
 
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where());
 
2820
    my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, session->where);
2391
2821
  }
2392
2822
  else
2393
2823
  {
2394
2824
    if (report_error == REPORT_ALL_ERRORS ||
2395
2825
        report_error == REPORT_EXCEPT_NON_UNIQUE)
2396
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where());
 
2826
      my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), session->where);
2397
2827
    else
2398
2828
      found= not_found_field;
2399
2829
  }
2444
2874
                  find_item_error_report_type report_error,
2445
2875
                  enum_resolution_type *resolution)
2446
2876
{
2447
 
  List<Item>::iterator li(items.begin());
 
2877
  List_iterator<Item> li(items);
2448
2878
  Item **found=0, **found_unaliased= 0, *item;
2449
2879
  const char *db_name=0;
2450
2880
  const char *field_name=0;
2520
2950
            */
2521
2951
            if (report_error != IGNORE_ERRORS)
2522
2952
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2523
 
                       find->full_name(), session->where());
 
2953
                       find->full_name(), session->where);
2524
2954
            return (Item**) 0;
2525
2955
          }
2526
2956
          found_unaliased= li.ref();
2551
2981
              continue;                           // Same field twice
2552
2982
            if (report_error != IGNORE_ERRORS)
2553
2983
              my_error(ER_NON_UNIQ_ERROR, MYF(0),
2554
 
                       find->full_name(), session->where());
 
2984
                       find->full_name(), session->where);
2555
2985
            return (Item**) 0;
2556
2986
          }
2557
2987
          found= li.ref();
2603
3033
    {
2604
3034
      if (report_error != IGNORE_ERRORS)
2605
3035
        my_error(ER_NON_UNIQ_ERROR, MYF(0),
2606
 
                 find->full_name(), session->where());
 
3036
                 find->full_name(), session->where);
2607
3037
      return (Item **) 0;
2608
3038
    }
2609
3039
    if (found_unaliased)
2619
3049
  {
2620
3050
    if (report_error == REPORT_ALL_ERRORS)
2621
3051
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
2622
 
               find->full_name(), session->where());
 
3052
               find->full_name(), session->where);
2623
3053
    return (Item **) 0;
2624
3054
  }
2625
3055
  else
2647
3077
static bool
2648
3078
test_if_string_in_list(const char *find, List<String> *str_list)
2649
3079
{
2650
 
  List<String>::iterator str_list_it(str_list->begin());
 
3080
  List_iterator<String> str_list_it(*str_list);
2651
3081
  String *curr_str;
2652
3082
  size_t find_length= strlen(find);
2653
3083
  while ((curr_str= str_list_it++))
2790
3220
        if (cur_nj_col_2->is_common ||
2791
3221
            (found && (!using_fields || is_using_column_1)))
2792
3222
        {
2793
 
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where());
 
3223
          my_error(ER_NON_UNIQ_ERROR, MYF(0), field_name_1, session->where);
2794
3224
          return(result);
2795
3225
        }
2796
3226
        nj_col_2= cur_nj_col_2;
2869
3299
      {
2870
3300
        Table *table_1= nj_col_1->table_ref->table;
2871
3301
        /* Mark field_1 used for table cache. */
2872
 
        table_1->setReadSet(field_1->position());
 
3302
        table_1->setReadSet(field_1->field_index);
2873
3303
        table_1->covering_keys&= field_1->part_of_key;
2874
3304
        table_1->merge_keys|= field_1->part_of_key;
2875
3305
      }
2877
3307
      {
2878
3308
        Table *table_2= nj_col_2->table_ref->table;
2879
3309
        /* Mark field_2 used for table cache. */
2880
 
        table_2->setReadSet(field_2->position());
 
3310
        table_2->setReadSet(field_2->field_index);
2881
3311
        table_2->covering_keys&= field_2->part_of_key;
2882
3312
        table_2->merge_keys|= field_2->part_of_key;
2883
3313
      }
2981
3411
  if (using_fields && found_using_fields < using_fields->elements)
2982
3412
  {
2983
3413
    String *using_field_name;
2984
 
    List<String>::iterator using_fields_it(using_fields->begin());
 
3414
    List_iterator_fast<String> using_fields_it(*using_fields);
2985
3415
    while ((using_field_name= using_fields_it++))
2986
3416
    {
2987
3417
      const char *using_field_name_ptr= using_field_name->c_ptr();
2988
 
      List<Natural_join_column>::iterator
2989
 
        it(natural_using_join->join_columns->begin());
 
3418
      List_iterator_fast<Natural_join_column>
 
3419
        it(*(natural_using_join->join_columns));
2990
3420
      Natural_join_column *common_field;
2991
3421
 
2992
3422
      for (;;)
2995
3425
        if (!(common_field= it++))
2996
3426
        {
2997
3427
          my_error(ER_BAD_FIELD_ERROR, MYF(0), using_field_name_ptr,
2998
 
                   session->where());
 
3428
                   session->where);
2999
3429
          return(result);
3000
3430
        }
3001
3431
        if (!my_strcasecmp(system_charset_info,
3068
3498
  /* Call the procedure recursively for each nested table reference. */
3069
3499
  if (table_ref->getNestedJoin())
3070
3500
  {
3071
 
    List<TableList>::iterator nested_it(table_ref->getNestedJoin()->join_list.begin());
 
3501
    List_iterator_fast<TableList> nested_it(table_ref->getNestedJoin()->join_list);
3072
3502
    TableList *same_level_left_neighbor= nested_it++;
3073
3503
    TableList *same_level_right_neighbor= NULL;
3074
3504
    /* Left/right-most neighbors, possibly at higher levels in the join tree. */
3122
3552
  {
3123
3553
    assert(table_ref->getNestedJoin() &&
3124
3554
           table_ref->getNestedJoin()->join_list.elements == 2);
3125
 
    List<TableList>::iterator operand_it(table_ref->getNestedJoin()->join_list.begin());
 
3555
    List_iterator_fast<TableList> operand_it(table_ref->getNestedJoin()->join_list);
3126
3556
    /*
3127
3557
      Notice that the order of join operands depends on whether table_ref
3128
3558
      represents a LEFT or a RIGHT join. In a RIGHT join, the operands are
3218
3648
                                         List<TableList> *from_clause,
3219
3649
                                         Name_resolution_context *context)
3220
3650
{
3221
 
  session->setWhere("from clause");
 
3651
  session->where= "from clause";
3222
3652
  if (from_clause->elements == 0)
3223
3653
    return false; /* We come here in the case of UNIONs. */
3224
3654
 
3225
 
  List<TableList>::iterator table_ref_it(from_clause->begin());
 
3655
  List_iterator_fast<TableList> table_ref_it(*from_clause);
3226
3656
  TableList *table_ref; /* Current table reference. */
3227
3657
  /* Table reference to the left of the current. */
3228
3658
  TableList *left_neighbor;
3272
3702
    return 0;
3273
3703
 
3274
3704
  Item *item;
3275
 
  List<Item>::iterator it(fields.begin());
 
3705
  List_iterator<Item> it(fields);
3276
3706
 
3277
 
  session->getLex()->current_select->cur_pos_in_select_list= 0;
 
3707
  session->lex->current_select->cur_pos_in_select_list= 0;
3278
3708
  while (wild_num && (item= it++))
3279
3709
  {
3280
3710
    if (item->type() == Item::FIELD_ITEM &&
3284
3714
    {
3285
3715
      uint32_t elem= fields.elements;
3286
3716
      bool any_privileges= ((Item_field *) item)->any_privileges;
3287
 
      Item_subselect *subsel= session->getLex()->current_select->master_unit()->item;
 
3717
      Item_subselect *subsel= session->lex->current_select->master_unit()->item;
3288
3718
      if (subsel &&
3289
3719
          subsel->substype() == Item_subselect::EXISTS_SUBS)
3290
3720
      {
3315
3745
      wild_num--;
3316
3746
    }
3317
3747
    else
3318
 
      session->getLex()->current_select->cur_pos_in_select_list++;
 
3748
      session->lex->current_select->cur_pos_in_select_list++;
3319
3749
  }
3320
 
  session->getLex()->current_select->cur_pos_in_select_list= UNDEF_POS;
 
3750
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3321
3751
 
3322
3752
  return 0;
3323
3753
}
3332
3762
{
3333
3763
  register Item *item;
3334
3764
  enum_mark_columns save_mark_used_columns= session->mark_used_columns;
3335
 
  nesting_map save_allow_sum_func= session->getLex()->allow_sum_func;
3336
 
  List<Item>::iterator it(fields.begin());
 
3765
  nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
3766
  List_iterator<Item> it(fields);
3337
3767
  bool save_is_item_list_lookup;
3338
3768
 
3339
3769
  session->mark_used_columns= mark_used_columns;
3340
3770
  if (allow_sum_func)
3341
 
    session->getLex()->allow_sum_func|= 1 << session->getLex()->current_select->nest_level;
3342
 
  session->setWhere(Session::DEFAULT_WHERE);
3343
 
  save_is_item_list_lookup= session->getLex()->current_select->is_item_list_lookup;
3344
 
  session->getLex()->current_select->is_item_list_lookup= 0;
 
3771
    session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
 
3772
  session->where= Session::DEFAULT_WHERE;
 
3773
  save_is_item_list_lookup= session->lex->current_select->is_item_list_lookup;
 
3774
  session->lex->current_select->is_item_list_lookup= 0;
3345
3775
 
3346
3776
  /*
3347
3777
    To prevent fail on forward lookup we fill it with zerows,
3351
3781
    There is other way to solve problem: fill array with pointers to list,
3352
3782
    but it will be slower.
3353
3783
 
3354
 
    TODO-> remove it when (if) we made one list for allfields and ref_pointer_array
 
3784
TODO: remove it when (if) we made one list for allfields and
 
3785
ref_pointer_array
3355
3786
  */
3356
3787
  if (ref_pointer_array)
3357
 
  {
3358
3788
    memset(ref_pointer_array, 0, sizeof(Item *) * fields.elements);
3359
 
  }
3360
3789
 
3361
3790
  Item **ref= ref_pointer_array;
3362
 
  session->getLex()->current_select->cur_pos_in_select_list= 0;
 
3791
  session->lex->current_select->cur_pos_in_select_list= 0;
3363
3792
  while ((item= it++))
3364
3793
  {
3365
3794
    if ((!item->fixed && item->fix_fields(session, it.ref())) || (item= *(it.ref()))->check_cols(1))
3366
3795
    {
3367
 
      session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
3368
 
      session->getLex()->allow_sum_func= save_allow_sum_func;
 
3796
      session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
3797
      session->lex->allow_sum_func= save_allow_sum_func;
3369
3798
      session->mark_used_columns= save_mark_used_columns;
3370
3799
      return true;
3371
3800
    }
3375
3804
        sum_func_list)
3376
3805
      item->split_sum_func(session, ref_pointer_array, *sum_func_list);
3377
3806
    session->used_tables|= item->used_tables();
3378
 
    session->getLex()->current_select->cur_pos_in_select_list++;
 
3807
    session->lex->current_select->cur_pos_in_select_list++;
3379
3808
  }
3380
 
  session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
3381
 
  session->getLex()->current_select->cur_pos_in_select_list= UNDEF_POS;
 
3809
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
3810
  session->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
3382
3811
 
3383
 
  session->getLex()->allow_sum_func= save_allow_sum_func;
 
3812
  session->lex->allow_sum_func= save_allow_sum_func;
3384
3813
  session->mark_used_columns= save_mark_used_columns;
3385
3814
  return(test(session->is_error()));
3386
3815
}
3549
3978
 
3550
3979
bool
3551
3980
insert_fields(Session *session, Name_resolution_context *context, const char *db_name,
3552
 
              const char *table_name, List<Item>::iterator *it,
 
3981
              const char *table_name, List_iterator<Item> *it,
3553
3982
              bool )
3554
3983
{
3555
3984
  Field_iterator_table_ref field_iterator;
3588
4017
    assert(tables->is_leaf_for_name_resolution());
3589
4018
 
3590
4019
    if ((table_name && my_strcasecmp(table_alias_charset, table_name, tables->alias)) ||
3591
 
        (db_name && my_strcasecmp(system_charset_info, tables->getSchemaName(),db_name)))
 
4020
        (db_name && strcasecmp(tables->db,db_name)))
3592
4021
      continue;
3593
4022
 
3594
4023
    /*
3624
4053
      if ((field= field_iterator.field()))
3625
4054
      {
3626
4055
        /* Mark fields as used to allow storage engine to optimze access */
3627
 
        field->getTable()->setReadSet(field->position());
 
4056
        field->getTable()->setReadSet(field->field_index);
3628
4057
        if (table)
3629
4058
        {
3630
4059
          table->covering_keys&= field->part_of_key;
3652
4081
        }
3653
4082
      }
3654
4083
      else
3655
 
      {
3656
4084
        session->used_tables|= item->used_tables();
3657
 
      }
3658
 
 
3659
 
      session->getLex()->current_select->cur_pos_in_select_list++;
 
4085
      session->lex->current_select->cur_pos_in_select_list++;
3660
4086
    }
3661
4087
    /*
3662
4088
      In case of stored tables, all fields are considered as used,
3675
4101
    qualified '*', and all columns were coalesced, we have to give a more
3676
4102
    meaningful message than ER_BAD_TABLE_ERROR.
3677
4103
  */
3678
 
  if (not table_name)
3679
 
  {
 
4104
  if (!table_name)
3680
4105
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
3681
 
  }
3682
4106
  else
3683
 
  {
3684
4107
    my_error(ER_BAD_TABLE_ERROR, MYF(0), table_name);
3685
 
  }
3686
4108
 
3687
4109
  return true;
3688
4110
}
3709
4131
int Session::setup_conds(TableList *leaves, COND **conds)
3710
4132
{
3711
4133
  Session *session= this;
3712
 
  Select_Lex *select_lex= session->getLex()->current_select;
 
4134
  Select_Lex *select_lex= session->lex->current_select;
3713
4135
  TableList *table= NULL;       // For HP compilers
3714
4136
  void *save_session_marker= session->session_marker;
3715
4137
  /*
3731
4153
  session->session_marker= (void*)1;
3732
4154
  if (*conds)
3733
4155
  {
3734
 
    session->setWhere("where clause");
 
4156
    session->where="where clause";
3735
4157
    if ((!(*conds)->fixed && (*conds)->fix_fields(session, conds)) ||
3736
4158
        (*conds)->check_cols(1))
3737
4159
      goto err_no_arena;
3753
4175
      {
3754
4176
        /* Make a join an a expression */
3755
4177
        session->session_marker= (void*)embedded;
3756
 
        session->setWhere("on clause");
 
4178
        session->where="on clause";
3757
4179
        if ((!embedded->on_expr->fixed && embedded->on_expr->fix_fields(session, &embedded->on_expr)) ||
3758
4180
            embedded->on_expr->check_cols(1))
3759
4181
          goto err_no_arena;
3767
4189
  }
3768
4190
  session->session_marker= save_session_marker;
3769
4191
 
3770
 
  session->getLex()->current_select->is_item_list_lookup= save_is_item_list_lookup;
 
4192
  session->lex->current_select->is_item_list_lookup= save_is_item_list_lookup;
3771
4193
  return(test(session->is_error()));
3772
4194
 
3773
4195
err_no_arena:
3805
4227
bool
3806
4228
fill_record(Session *session, List<Item> &fields, List<Item> &values, bool ignore_errors)
3807
4229
{
3808
 
  List<Item>::iterator f(fields.begin());
3809
 
  List<Item>::iterator v(values.begin());
 
4230
  List_iterator_fast<Item> f(fields),v(values);
3810
4231
  Item *value;
3811
4232
  Item_field *field;
3812
4233
  Table *table;
3824
4245
    field= static_cast<Item_field *>(f++);
3825
4246
    table= field->field->getTable();
3826
4247
    table->auto_increment_field_not_null= false;
3827
 
    f= fields.begin();
 
4248
    f.rewind();
3828
4249
  }
3829
4250
 
3830
4251
  while ((field= static_cast<Item_field *>(f++)))
3871
4292
 
3872
4293
bool fill_record(Session *session, Field **ptr, List<Item> &values, bool)
3873
4294
{
3874
 
  List<Item>::iterator v(values.begin());
 
4295
  List_iterator_fast<Item> v(values);
3875
4296
  Item *value;
3876
4297
  Table *table= 0;
3877
4298
  Field *field;
3889
4310
    table= (*ptr)->getTable();
3890
4311
    table->auto_increment_field_not_null= false;
3891
4312
  }
3892
 
 
3893
4313
  while ((field = *ptr++) && ! session->is_error())
3894
4314
  {
3895
4315
    value=v++;
3896
4316
    table= field->getTable();
3897
 
 
3898
4317
    if (field == table->next_number_field)
3899
4318
      table->auto_increment_field_not_null= true;
3900
 
 
3901
4319
    if (value->save_in_field(field, 0) < 0)
3902
4320
    {
3903
4321
      if (table)
3913
4331
 
3914
4332
bool drizzle_rm_tmp_tables()
3915
4333
{
 
4334
  Session *session;
3916
4335
 
3917
4336
  assert(drizzle_tmpdir.size());
3918
 
  Session::shared_ptr session= Session::make_shared(plugin::Listen::getNullClient(), catalog::local());
3919
4337
 
3920
 
  if (not session)
 
4338
  if (!(session= new Session(plugin::Listen::getNullClient())))
3921
4339
    return true;
3922
 
  session->thread_stack= (char*) session.get();
 
4340
  session->thread_stack= (char*) &session;
3923
4341
  session->storeGlobals();
3924
4342
 
3925
4343
  plugin::StorageEngine::removeLostTemporaryTables(*session, drizzle_tmpdir.c_str());
3926
4344
 
 
4345
  session->lockForDelete();
 
4346
  delete session;
 
4347
 
3927
4348
  return false;
3928
4349
}
3929
4350
 
3933
4354
  unireg support functions
3934
4355
 *****************************************************************************/
3935
4356
 
3936
 
 
 
4357
/*
 
4358
  Invalidate any cache entries that are for some DB
 
4359
 
 
4360
  SYNOPSIS
 
4361
  remove_db_from_cache()
 
4362
  db            Database name. This will be in lower case if
 
4363
  lower_case_table_name is set
 
4364
 
 
4365
NOTE:
 
4366
We can't use hash_delete when looping hash_elements. We mark them first
 
4367
and afterwards delete those marked unused.
 
4368
*/
 
4369
 
 
4370
void remove_db_from_cache(const SchemaIdentifier &schema_identifier)
 
4371
{
 
4372
  safe_mutex_assert_owner(LOCK_open.native_handle());
 
4373
 
 
4374
  for (TableOpenCache::const_iterator iter= get_open_cache().begin();
 
4375
       iter != get_open_cache().end();
 
4376
       iter++)
 
4377
  {
 
4378
    table::Concurrent *table= (*iter).second;
 
4379
 
 
4380
    if (not schema_identifier.getPath().compare(table->getShare()->getSchemaName()))
 
4381
    {
 
4382
      table->getMutableShare()->resetVersion();                 /* Free when thread is ready */
 
4383
      if (not table->in_use)
 
4384
        unused_tables.relink(table);
 
4385
    }
 
4386
  }
 
4387
 
 
4388
  unused_tables.cullByVersion();
 
4389
}
 
4390
 
 
4391
 
 
4392
/*
 
4393
  Mark all entries with the table as deleted to force an reopen of the table
 
4394
 
 
4395
  The table will be closed (not stored in cache) by the current thread when
 
4396
  close_thread_tables() is called.
 
4397
 
 
4398
  PREREQUISITES
 
4399
  Lock on LOCK_open()
 
4400
 
 
4401
  RETURN
 
4402
  0  This thread now have exclusive access to this table and no other thread
 
4403
  can access the table until close_thread_tables() is called.
 
4404
  1  Table is in use by another thread
 
4405
*/
 
4406
 
 
4407
bool remove_table_from_cache(Session *session, TableIdentifier &identifier, uint32_t flags)
 
4408
{
 
4409
  const TableIdentifier::Key &key(identifier.getKey());
 
4410
  bool result= false; 
 
4411
  bool signalled= false;
 
4412
 
 
4413
  for (;;)
 
4414
  {
 
4415
    result= signalled= false;
 
4416
 
 
4417
    TableOpenCacheRange ppp;
 
4418
    ppp= get_open_cache().equal_range(key);
 
4419
 
 
4420
    for (TableOpenCache::const_iterator iter= ppp.first;
 
4421
         iter != ppp.second; ++iter)
 
4422
    {
 
4423
      table::Concurrent *table= (*iter).second;
 
4424
      Session *in_use;
 
4425
 
 
4426
      table->getMutableShare()->resetVersion();         /* Free when thread is ready */
 
4427
      if (not (in_use= table->in_use))
 
4428
      {
 
4429
        unused_tables.relink(table);
 
4430
      }
 
4431
      else if (in_use != session)
 
4432
      {
 
4433
        /*
 
4434
          Mark that table is going to be deleted from cache. This will
 
4435
          force threads that are in mysql_lock_tables() (but not yet
 
4436
          in thr_multi_lock()) to abort it's locks, close all tables and retry
 
4437
        */
 
4438
        in_use->some_tables_deleted= true;
 
4439
        if (table->is_name_opened())
 
4440
        {
 
4441
          result= true;
 
4442
        }
 
4443
        /*
 
4444
          Now we must abort all tables locks used by this thread
 
4445
          as the thread may be waiting to get a lock for another table.
 
4446
          Note that we need to hold LOCK_open while going through the
 
4447
          list. So that the other thread cannot change it. The other
 
4448
          thread must also hold LOCK_open whenever changing the
 
4449
          open_tables list. Aborting the MERGE lock after a child was
 
4450
          closed and before the parent is closed would be fatal.
 
4451
        */
 
4452
        for (Table *session_table= in_use->open_tables;
 
4453
             session_table ;
 
4454
             session_table= session_table->getNext())
 
4455
        {
 
4456
          /* Do not handle locks of MERGE children. */
 
4457
          if (session_table->db_stat)   // If table is open
 
4458
            signalled|= mysql_lock_abort_for_thread(session, session_table);
 
4459
        }
 
4460
      }
 
4461
      else
 
4462
      {
 
4463
        result= result || (flags & RTFC_OWNED_BY_Session_FLAG);
 
4464
      }
 
4465
    }
 
4466
 
 
4467
    unused_tables.cullByVersion();
 
4468
 
 
4469
    /* Remove table from table definition cache if it's not in use */
 
4470
    TableShare::release(identifier);
 
4471
 
 
4472
    if (result && (flags & RTFC_WAIT_OTHER_THREAD_FLAG))
 
4473
    {
 
4474
      /*
 
4475
        Signal any thread waiting for tables to be freed to
 
4476
        reopen their tables
 
4477
      */
 
4478
      broadcast_refresh();
 
4479
      if (!(flags & RTFC_CHECK_KILLED_FLAG) || !session->killed)
 
4480
      {
 
4481
        dropping_tables++;
 
4482
        if (likely(signalled))
 
4483
        {
 
4484
          boost_unique_lock_t scoped(LOCK_open, boost::adopt_lock_t());
 
4485
          COND_refresh.wait(scoped);
 
4486
          scoped.release();
 
4487
        }
 
4488
        else
 
4489
        {
 
4490
          /*
 
4491
            It can happen that another thread has opened the
 
4492
            table but has not yet locked any table at all. Since
 
4493
            it can be locked waiting for a table that our thread
 
4494
            has done LOCK Table x WRITE on previously, we need to
 
4495
            ensure that the thread actually hears our signal
 
4496
            before we go to sleep. Thus we wait for a short time
 
4497
            and then we retry another loop in the
 
4498
            remove_table_from_cache routine.
 
4499
          */
 
4500
          boost::xtime xt; 
 
4501
          xtime_get(&xt, boost::TIME_UTC); 
 
4502
          xt.sec += 10; 
 
4503
          boost_unique_lock_t scoped(LOCK_open, boost::adopt_lock_t());
 
4504
          COND_refresh.timed_wait(scoped, xt);
 
4505
          scoped.release();
 
4506
        }
 
4507
        dropping_tables--;
 
4508
        continue;
 
4509
      }
 
4510
    }
 
4511
    break;
 
4512
  }
 
4513
 
 
4514
  return result;
 
4515
}
3937
4516
 
3938
4517
 
3939
4518
/**