~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_table.cc

Merge in Stewart's FK work

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
/* drop and alter of tables */
17
17
 
18
 
#include <config.h>
 
18
#include "config.h"
19
19
#include <plugin/myisam/myisam.h>
20
20
#include <drizzled/show.h>
21
21
#include <drizzled/error.h>
26
26
#include <drizzled/sql_lex.h>
27
27
#include <drizzled/session.h>
28
28
#include <drizzled/sql_base.h>
29
 
#include <drizzled/strfunc.h>
 
29
#include "drizzled/strfunc.h"
 
30
#include <drizzled/db.h>
30
31
#include <drizzled/lock.h>
31
32
#include <drizzled/unireg.h>
32
33
#include <drizzled/item/int.h>
33
34
#include <drizzled/item/empty_string.h>
34
35
#include <drizzled/transaction_services.h>
35
 
#include <drizzled/transaction_services.h>
 
36
#include "drizzled/transaction_services.h"
36
37
#include <drizzled/table_proto.h>
37
38
#include <drizzled/plugin/client.h>
38
39
#include <drizzled/identifier.h>
39
 
#include <drizzled/internal/m_string.h>
40
 
#include <drizzled/global_charset_info.h>
41
 
#include <drizzled/charset.h>
42
 
 
43
 
#include <drizzled/definition/cache.h>
44
 
 
45
 
#include <drizzled/statement/alter_table.h>
46
 
#include <drizzled/sql_table.h>
47
 
#include <drizzled/pthread_globals.h>
48
 
#include <drizzled/typelib.h>
49
 
#include <drizzled/plugin/storage_engine.h>
 
40
#include "drizzled/internal/m_string.h"
 
41
#include "drizzled/global_charset_info.h"
 
42
#include "drizzled/charset.h"
 
43
 
 
44
 
 
45
#include "drizzled/statement/alter_table.h"
 
46
#include "drizzled/sql_table.h"
 
47
#include "drizzled/pthread_globals.h"
50
48
 
51
49
#include <algorithm>
52
50
#include <sstream>
58
56
namespace drizzled
59
57
{
60
58
 
 
59
extern pid_t current_pid;
 
60
 
61
61
bool is_primary_key(KeyInfo *key_info)
62
62
{
63
63
  static const char * primary_key_name="PRIMARY";
85
85
    let's fetch the database default character set and
86
86
    apply it to the table.
87
87
  */
88
 
  identifier::Schema identifier(db);
 
88
  SchemaIdentifier identifier(db);
89
89
  if (create_info->default_table_charset == NULL)
90
90
    create_info->default_table_charset= plugin::StorageEngine::getSchemaCollation(identifier);
91
91
}
105
105
    cursor
106
106
*/
107
107
 
108
 
void write_bin_log(Session *session, const std::string &query)
109
 
{
110
 
  TransactionServices &transaction_services= TransactionServices::singleton();
111
 
  transaction_services.rawStatement(*session, query);
 
108
void write_bin_log(Session *session,
 
109
                   char const *query)
 
110
{
 
111
  TransactionServices &transaction_services= TransactionServices::singleton();
 
112
  transaction_services.rawStatement(session, query);
 
113
}
 
114
 
 
115
 
 
116
/* Should should be refactored to go away */
 
117
void write_bin_log_drop_table(Session *session, bool if_exists, const char *db_name, const char *table_name)
 
118
{
 
119
  TransactionServices &transaction_services= TransactionServices::singleton();
 
120
  string built_query;
 
121
 
 
122
  if (if_exists)
 
123
    built_query.append("DROP TABLE IF EXISTS ");
 
124
  else
 
125
    built_query.append("DROP TABLE ");
 
126
 
 
127
  built_query.append("`");
 
128
  if (session->db.empty() || strcmp(db_name, session->db.c_str()) != 0)
 
129
  {
 
130
    built_query.append(db_name);
 
131
    built_query.append("`.`");
 
132
  }
 
133
 
 
134
  built_query.append(table_name);
 
135
  built_query.append("`");
 
136
  transaction_services.rawStatement(session, built_query);
112
137
}
113
138
 
114
139
/*
115
140
  Execute the drop of a normal or temporary table
116
141
 
117
142
  SYNOPSIS
118
 
    rm_table_part2()
 
143
    mysql_rm_table_part2()
119
144
    session                     Thread Cursor
120
145
    tables              Tables to drop
121
146
    if_exists           If set, don't give an error if table doesn't exists.
138
163
   -1   Thread was killed
139
164
*/
140
165
 
141
 
int rm_table_part2(Session *session, TableList *tables, bool if_exists,
142
 
                   bool drop_temporary)
 
166
int mysql_rm_table_part2(Session *session, TableList *tables, bool if_exists,
 
167
                         bool drop_temporary)
143
168
{
144
169
  TableList *table;
145
 
  util::string::vector wrong_tables;
 
170
  String wrong_tables;
146
171
  int error= 0;
147
172
  bool foreign_key_error= false;
148
173
 
149
 
  do
150
 
  {
151
 
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
152
 
 
153
 
    if (not drop_temporary && session->lock_table_names_exclusively(tables))
154
 
    {
155
 
      return 1;
156
 
    }
157
 
 
158
 
    /* Don't give warnings for not found errors, as we already generate notes */
159
 
    session->no_warnings_for_error= 1;
160
 
 
161
 
    for (table= tables; table; table= table->next_local)
162
 
    {
163
 
      identifier::Table tmp_identifier(table->getSchemaName(), table->getTableName());
164
 
 
165
 
      error= session->drop_temporary_table(tmp_identifier);
166
 
 
167
 
      switch (error) {
168
 
      case  0:
169
 
        // removed temporary table
170
 
        continue;
171
 
      case -1:
 
174
  LOCK_open.lock(); /* Part 2 of rm a table */
 
175
 
 
176
  /*
 
177
    If we have the table in the definition cache, we don't have to check the
 
178
    .frm cursor to find if the table is a normal table (not view) and what
 
179
    engine to use.
 
180
  */
 
181
 
 
182
  for (table= tables; table; table= table->next_local)
 
183
  {
 
184
    TableIdentifier identifier(table->db, table->table_name);
 
185
    TableShare *share;
 
186
    table->setDbType(NULL);
 
187
 
 
188
    if ((share= TableShare::getShare(identifier)))
 
189
    {
 
190
      table->setDbType(share->db_type());
 
191
    }
 
192
  }
 
193
 
 
194
  if (not drop_temporary && lock_table_names_exclusively(session, tables))
 
195
  {
 
196
    LOCK_open.unlock();
 
197
    return 1;
 
198
  }
 
199
 
 
200
  /* Don't give warnings for not found errors, as we already generate notes */
 
201
  session->no_warnings_for_error= 1;
 
202
 
 
203
  for (table= tables; table; table= table->next_local)
 
204
  {
 
205
    char *db=table->db;
 
206
 
 
207
    error= session->drop_temporary_table(table);
 
208
 
 
209
    switch (error) {
 
210
    case  0:
 
211
      // removed temporary table
 
212
      continue;
 
213
    case -1:
 
214
      error= 1;
 
215
      goto err_with_placeholders;
 
216
    default:
 
217
      // temporary table not found
 
218
      error= 0;
 
219
    }
 
220
 
 
221
    if (drop_temporary == false)
 
222
    {
 
223
      Table *locked_table;
 
224
      TableIdentifier identifier(db, table->table_name);
 
225
      abort_locked_tables(session, identifier);
 
226
      remove_table_from_cache(session, identifier,
 
227
                              RTFC_WAIT_OTHER_THREAD_FLAG |
 
228
                              RTFC_CHECK_KILLED_FLAG);
 
229
      /*
 
230
        If the table was used in lock tables, remember it so that
 
231
        unlock_table_names can free it
 
232
      */
 
233
      if ((locked_table= drop_locked_tables(session, identifier)))
 
234
        table->table= locked_table;
 
235
 
 
236
      if (session->killed)
 
237
      {
 
238
        error= -1;
 
239
        goto err_with_placeholders;
 
240
      }
 
241
    }
 
242
    TableIdentifier identifier(db, table->table_name, table->getInternalTmpTable() ? message::Table::INTERNAL : message::Table::STANDARD);
 
243
 
 
244
    if (drop_temporary || not plugin::StorageEngine::doesTableExist(*session, identifier))
 
245
    {
 
246
      // Table was not found on disk and table can't be created from engine
 
247
      if (if_exists)
 
248
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
249
                            ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR),
 
250
                            table->table_name);
 
251
      else
172
252
        error= 1;
173
 
        break;
174
 
      default:
175
 
        // temporary table not found
 
253
    }
 
254
    else
 
255
    {
 
256
      error= plugin::StorageEngine::dropTable(*session, identifier);
 
257
 
 
258
      if ((error == ENOENT || error == HA_ERR_NO_SUCH_TABLE) && if_exists)
 
259
      {
176
260
        error= 0;
177
 
      }
178
 
 
179
 
      if (drop_temporary == false)
180
 
      {
181
 
        Table *locked_table;
182
 
        abort_locked_tables(session, tmp_identifier);
183
 
        table::Cache::singleton().removeTable(session, tmp_identifier,
184
 
                                              RTFC_WAIT_OTHER_THREAD_FLAG |
185
 
                                              RTFC_CHECK_KILLED_FLAG);
186
 
        /*
187
 
          If the table was used in lock tables, remember it so that
188
 
          unlock_table_names can free it
189
 
        */
190
 
        if ((locked_table= drop_locked_tables(session, tmp_identifier)))
191
 
          table->table= locked_table;
192
 
 
193
 
        if (session->getKilled())
194
 
        {
195
 
          error= -1;
196
 
          break;
197
 
        }
198
 
      }
199
 
      identifier::Table identifier(table->getSchemaName(), table->getTableName(), table->getInternalTmpTable() ? message::Table::INTERNAL : message::Table::STANDARD);
200
 
 
201
 
      message::table::shared_ptr message= plugin::StorageEngine::getTableMessage(*session, identifier, true);
202
 
 
203
 
      if (drop_temporary || not plugin::StorageEngine::doesTableExist(*session, identifier))
204
 
      {
205
 
        // Table was not found on disk and table can't be created from engine
206
 
        if (if_exists)
207
 
        {
208
 
          push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
209
 
                              ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR),
210
 
                              table->getTableName());
211
 
        }
212
 
        else
213
 
        {
214
 
          error= 1;
215
 
        }
216
 
      }
217
 
      else
218
 
      {
219
 
        drizzled::error_t local_error;
220
 
 
221
 
        /* Generate transaction event ONLY when we successfully drop */ 
222
 
        if (plugin::StorageEngine::dropTable(*session, identifier, local_error))
223
 
        {
224
 
          if (message) // If we have no definition, we don't know if the table should have been replicated
225
 
          {
226
 
            TransactionServices &transaction_services= TransactionServices::singleton();
227
 
            transaction_services.dropTable(*session, identifier, *message, if_exists);
228
 
          }
229
 
        }
230
 
        else
231
 
        {
232
 
          if (local_error == HA_ERR_NO_SUCH_TABLE and if_exists)
233
 
          {
234
 
            error= 0;
235
 
            session->clear_error();
236
 
          }
237
 
 
238
 
          if (local_error == HA_ERR_ROW_IS_REFERENCED)
239
 
          {
240
 
            /* the table is referenced by a foreign key constraint */
241
 
            foreign_key_error= true;
242
 
          }
243
 
          error= local_error;
244
 
        }
245
 
      }
246
 
 
247
 
      if (error)
248
 
      {
249
 
        wrong_tables.push_back(table->getTableName());
250
 
      }
251
 
    }
252
 
 
253
 
    tables->unlock_table_names();
254
 
 
255
 
  } while (0);
256
 
 
257
 
  if (wrong_tables.size())
 
261
        session->clear_error();
 
262
      }
 
263
 
 
264
      if (error == HA_ERR_ROW_IS_REFERENCED)
 
265
      {
 
266
        /* the table is referenced by a foreign key constraint */
 
267
        foreign_key_error= true;
 
268
      }
 
269
    }
 
270
 
 
271
    if (error == 0 || (if_exists && foreign_key_error == false))
 
272
    {
 
273
      TransactionServices &transaction_services= TransactionServices::singleton();
 
274
      transaction_services.dropTable(session, string(db), string(table->table_name), if_exists);
 
275
    }
 
276
 
 
277
    if (error)
 
278
    {
 
279
      if (wrong_tables.length())
 
280
        wrong_tables.append(',');
 
281
      wrong_tables.append(String(table->table_name,system_charset_info));
 
282
    }
 
283
  }
 
284
  /*
 
285
    It's safe to unlock LOCK_open: we have an exclusive lock
 
286
    on the table name.
 
287
  */
 
288
  LOCK_open.unlock();
 
289
  error= 0;
 
290
 
 
291
  if (wrong_tables.length())
258
292
  {
259
293
    if (not foreign_key_error)
260
294
    {
261
 
      std::string table_error;
262
 
 
263
 
      for (util::string::vector::iterator iter= wrong_tables.begin();
264
 
           iter != wrong_tables.end();
265
 
           iter++)
266
 
      {
267
 
        table_error+= *iter;
268
 
        table_error+= ',';
269
 
      }
270
 
      table_error.resize(table_error.size() -1);
271
 
 
272
295
      my_printf_error(ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR), MYF(0),
273
 
                      table_error.c_str());
 
296
                      wrong_tables.c_ptr());
274
297
    }
275
298
    else
276
299
    {
279
302
    error= 1;
280
303
  }
281
304
 
 
305
  LOCK_open.lock(); /* final bit in rm table lock */
 
306
 
 
307
err_with_placeholders:
 
308
  unlock_table_names(tables, NULL);
 
309
  LOCK_open.unlock();
282
310
  session->no_warnings_for_error= 0;
283
311
 
284
312
  return error;
285
313
}
286
314
 
 
315
 
 
316
/*
 
317
  Quickly remove a table.
 
318
 
 
319
  SYNOPSIS
 
320
    quick_rm_table()
 
321
      base                      The plugin::StorageEngine handle.
 
322
      db                        The database name.
 
323
      table_name                The table name.
 
324
      is_tmp                    If the table is temp.
 
325
 
 
326
  RETURN
 
327
    0           OK
 
328
    != 0        Error
 
329
*/
 
330
bool quick_rm_table(Session& session,
 
331
                    TableIdentifier &identifier)
 
332
{
 
333
  return (plugin::StorageEngine::dropTable(session, identifier));
 
334
}
 
335
 
287
336
/*
288
337
  Sort keys in the following order:
289
338
  - PRIMARY KEY
483
532
    sql_field->length= 8; // Unireg field length
484
533
    (*blob_columns)++;
485
534
    break;
486
 
 
 
535
  case DRIZZLE_TYPE_VARCHAR:
 
536
    break;
487
537
  case DRIZZLE_TYPE_ENUM:
488
 
    {
489
 
      if (check_duplicates_in_interval("ENUM",
490
 
                                       sql_field->field_name,
491
 
                                       sql_field->interval,
492
 
                                       sql_field->charset,
493
 
                                       &dup_val_count))
494
 
      {
495
 
        return 1;
496
 
      }
497
 
    }
498
 
    break;
499
 
 
500
 
  case DRIZZLE_TYPE_MICROTIME:
 
538
    if (check_duplicates_in_interval("ENUM",
 
539
                                     sql_field->field_name,
 
540
                                     sql_field->interval,
 
541
                                     sql_field->charset,
 
542
                                     &dup_val_count))
 
543
      return 1;
 
544
    break;
 
545
  case DRIZZLE_TYPE_DATE:  // Rest of string types
 
546
  case DRIZZLE_TYPE_DATETIME:
 
547
  case DRIZZLE_TYPE_NULL:
 
548
    break;
 
549
  case DRIZZLE_TYPE_DECIMAL:
 
550
    break;
501
551
  case DRIZZLE_TYPE_TIMESTAMP:
502
552
    /* We should replace old TIMESTAMP fields with their newer analogs */
503
553
    if (sql_field->unireg_check == Field::TIMESTAMP_OLD_FIELD)
513
563
      }
514
564
    }
515
565
    else if (sql_field->unireg_check != Field::NONE)
516
 
    {
517
566
      (*timestamps_with_niladic)++;
518
 
    }
519
567
 
520
568
    (*timestamps)++;
521
 
 
522
 
    break;
523
 
 
524
 
  case DRIZZLE_TYPE_BOOLEAN:
525
 
  case DRIZZLE_TYPE_DATE:  // Rest of string types
526
 
  case DRIZZLE_TYPE_DATETIME:
527
 
  case DRIZZLE_TYPE_DECIMAL:
528
 
  case DRIZZLE_TYPE_DOUBLE:
529
 
  case DRIZZLE_TYPE_LONG:
530
 
  case DRIZZLE_TYPE_LONGLONG:
531
 
  case DRIZZLE_TYPE_NULL:
532
 
  case DRIZZLE_TYPE_TIME:
533
 
  case DRIZZLE_TYPE_UUID:
534
 
  case DRIZZLE_TYPE_VARCHAR:
 
569
    /* fall-through */
 
570
  default:
535
571
    break;
536
572
  }
537
573
 
538
574
  return 0;
539
575
}
540
576
 
541
 
static int prepare_create_table(Session *session,
542
 
                                HA_CREATE_INFO *create_info,
543
 
                                message::Table &create_proto,
544
 
                                AlterInfo *alter_info,
545
 
                                bool tmp_table,
546
 
                                uint32_t *db_options,
547
 
                                KeyInfo **key_info_buffer,
548
 
                                uint32_t *key_count,
549
 
                                int select_field_count)
 
577
static int mysql_prepare_create_table(Session *session,
 
578
                                      HA_CREATE_INFO *create_info,
 
579
                                      message::Table &create_proto,
 
580
                                      AlterInfo *alter_info,
 
581
                                      bool tmp_table,
 
582
                                      uint32_t *db_options,
 
583
                                      KeyInfo **key_info_buffer,
 
584
                                      uint32_t *key_count,
 
585
                                      int select_field_count)
550
586
{
551
587
  const char    *key_name;
552
588
  CreateField   *sql_field,*dup_field;
555
591
  KeyInfo               *key_info;
556
592
  KeyPartInfo *key_part_info;
557
593
  int           timestamps= 0, timestamps_with_niladic= 0;
558
 
  int           dup_no;
 
594
  int           field_no,dup_no;
559
595
  int           select_field_pos,auto_increment=0;
560
 
  List<CreateField>::iterator it(alter_info->create_list.begin());
561
 
  List<CreateField>::iterator it2(alter_info->create_list.begin());
 
596
  List_iterator<CreateField> it(alter_info->create_list);
 
597
  List_iterator<CreateField> it2(alter_info->create_list);
562
598
  uint32_t total_uneven_bit_length= 0;
563
599
 
564
600
  plugin::StorageEngine *engine= plugin::StorageEngine::findByName(create_proto.engine().name());
567
603
  null_fields=blob_columns=0;
568
604
  max_key_length= engine->max_key_length();
569
605
 
570
 
  for (int32_t field_no=0; (sql_field=it++) ; field_no++)
 
606
  for (field_no=0; (sql_field=it++) ; field_no++)
571
607
  {
572
608
    const CHARSET_INFO *save_cs;
573
609
 
577
613
      executing a prepared statement for the second time.
578
614
    */
579
615
    sql_field->length= sql_field->char_length;
580
 
 
581
616
    if (!sql_field->charset)
582
617
      sql_field->charset= create_info->default_table_charset;
583
 
 
584
618
    /*
585
619
      table_charset is set in ALTER Table if we want change character set
586
620
      for all varchar/char columns.
633
667
 
634
668
    if (sql_field->sql_type == DRIZZLE_TYPE_ENUM)
635
669
    {
636
 
      size_t dummy;
 
670
      uint32_t dummy;
637
671
      const CHARSET_INFO * const cs= sql_field->charset;
638
672
      TYPELIB *interval= sql_field->interval;
639
673
 
652
686
        interval= sql_field->interval= typelib(session->mem_root,
653
687
                                               sql_field->interval_list);
654
688
 
655
 
        List<String>::iterator int_it(sql_field->interval_list.begin());
 
689
        List_iterator<String> int_it(sql_field->interval_list);
656
690
        String conv, *tmp;
657
691
        char comma_buf[4];
658
692
        int comma_length= cs->cset->wc_mb(cs, ',', (unsigned char*) comma_buf,
666
700
          if (String::needs_conversion(tmp->length(), tmp->charset(),
667
701
                                       cs, &dummy))
668
702
          {
669
 
            size_t cnv_errs;
 
703
            uint32_t cnv_errs;
670
704
            conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), cs, &cnv_errs);
671
705
            interval->type_names[i]= session->mem_root->strmake_root(conv.ptr(), conv.length());
672
706
            interval->type_lengths[i]= conv.length();
678
712
          interval->type_lengths[i]= lengthsp;
679
713
          ((unsigned char *)interval->type_names[i])[lengthsp]= '\0';
680
714
        }
681
 
        sql_field->interval_list.clear(); // Don't need interval_list anymore
 
715
        sql_field->interval_list.empty(); // Don't need interval_list anymore
682
716
      }
683
717
 
684
718
      /* DRIZZLE_TYPE_ENUM */
701
735
          else /* not NULL */
702
736
          {
703
737
            def->length(cs->cset->lengthsp(cs, def->ptr(), def->length()));
704
 
            if (interval->find_type2(def->ptr(), def->length(), cs) == 0) /* not found */
 
738
            if (find_type2(interval, def->ptr(), def->length(), cs) == 0) /* not found */
705
739
            {
706
740
              my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
707
741
              return(true);
708
742
            }
709
743
          }
710
744
        }
711
 
        uint32_t new_dummy;
712
 
        calculate_interval_lengths(cs, interval, &field_length, &new_dummy);
 
745
        calculate_interval_lengths(cs, interval, &field_length, &dummy);
713
746
        sql_field->length= field_length;
714
747
      }
715
748
      set_if_smaller(sql_field->length, (uint32_t)MAX_FIELD_WIDTH-1);
778
811
    if (not create_proto.engine().name().compare("MyISAM") &&
779
812
        ((sql_field->flags & BLOB_FLAG) ||
780
813
         (sql_field->sql_type == DRIZZLE_TYPE_VARCHAR)))
781
 
    {
782
814
      (*db_options)|= HA_OPTION_PACK_RECORD;
783
 
    }
784
 
 
785
 
    it2= alter_info->create_list.begin();
 
815
    it2.rewind();
786
816
  }
787
817
 
788
818
  /* record_offset will be increased with 'length-of-null-bits' later */
789
819
  record_offset= 0;
790
820
  null_fields+= total_uneven_bit_length;
791
821
 
792
 
  it= alter_info->create_list.begin();
 
822
  it.rewind();
793
823
  while ((sql_field=it++))
794
824
  {
795
825
    assert(sql_field->charset != 0);
829
859
 
830
860
  /* Create keys */
831
861
 
832
 
  List<Key>::iterator key_iterator(alter_info->key_list.begin());
833
 
  List<Key>::iterator key_iterator2(alter_info->key_list.begin());
 
862
  List_iterator<Key> key_iterator(alter_info->key_list);
 
863
  List_iterator<Key> key_iterator2(alter_info->key_list);
834
864
  uint32_t key_parts=0, fk_key_count=0;
835
865
  bool primary_key=0,unique_key=0;
836
866
  Key *key, *key2;
848
878
      fk_key_count++;
849
879
      if (((Foreign_key *)key)->validate(alter_info->create_list))
850
880
        return true;
851
 
 
852
881
      Foreign_key *fk_key= (Foreign_key*) key;
853
 
 
854
 
      add_foreign_key_to_table_message(&create_proto,
855
 
                                       fk_key->name.str,
856
 
                                       fk_key->columns,
857
 
                                       fk_key->ref_table,
858
 
                                       fk_key->ref_columns,
859
 
                                       fk_key->delete_opt,
860
 
                                       fk_key->update_opt,
861
 
                                       fk_key->match_opt);
862
 
 
863
882
      if (fk_key->ref_columns.elements &&
864
883
          fk_key->ref_columns.elements != fk_key->columns.elements)
865
884
      {
869
888
                 ER(ER_KEY_REF_DO_NOT_MATCH_TABLE_REF));
870
889
        return(true);
871
890
      }
 
891
 
 
892
      message::Table::ForeignKeyConstraint *pfkey= create_proto.add_fk_constraint();
 
893
      if (fk_key->name.str)
 
894
        pfkey->set_name(fk_key->name.str);
 
895
 
 
896
      pfkey->set_match(fk_key->match_opt);
 
897
      pfkey->set_update_option(fk_key->update_opt);
 
898
      pfkey->set_delete_option(fk_key->delete_opt);
 
899
 
 
900
      pfkey->set_references_table_name(fk_key->ref_table->table.str);
 
901
 
 
902
      Key_part_spec *keypart;
 
903
      List_iterator<Key_part_spec> col_it(fk_key->columns);
 
904
      while ((keypart= col_it++))
 
905
      {
 
906
        pfkey->add_column_names(keypart->field_name.str);
 
907
      }
 
908
 
 
909
      List_iterator<Key_part_spec> ref_it(fk_key->ref_columns);
 
910
      while ((keypart= ref_it++))
 
911
      {
 
912
        pfkey->add_references_columns(keypart->field_name.str);
 
913
      }
 
914
 
872
915
      continue;
873
916
    }
874
917
    (*key_count)++;
880
923
    }
881
924
    if (check_identifier_name(&key->name, ER_TOO_LONG_IDENT))
882
925
      return(true);
883
 
    key_iterator2= alter_info->key_list.begin();
 
926
    key_iterator2.rewind ();
884
927
    if (key->type != Key::FOREIGN_KEY)
885
928
    {
886
929
      while ((key2 = key_iterator2++) != key)
933
976
  if (!*key_info_buffer || ! key_part_info)
934
977
    return(true);                               // Out of memory
935
978
 
936
 
  key_iterator= alter_info->key_list.begin();
 
979
  key_iterator.rewind();
937
980
  key_number=0;
938
981
  for (; (key=key_iterator++) ; key_number++)
939
982
  {
992
1035
 
993
1036
    message::Table::Field *protofield= NULL;
994
1037
 
995
 
    List<Key_part_spec>::iterator cols(key->columns.begin());
996
 
    List<Key_part_spec>::iterator cols2(key->columns.begin());
 
1038
    List_iterator<Key_part_spec> cols(key->columns), cols2(key->columns);
997
1039
    for (uint32_t column_nr=0 ; (column=cols++) ; column_nr++)
998
1040
    {
999
1041
      uint32_t length;
1000
1042
      Key_part_spec *dup_column;
1001
1043
      int proto_field_nr= 0;
1002
1044
 
1003
 
      it= alter_info->create_list.begin();
 
1045
      it.rewind();
1004
1046
      field=0;
1005
1047
      while ((sql_field=it++) && ++proto_field_nr &&
1006
1048
             my_strcasecmp(system_charset_info,
1007
1049
                           column->field_name.str,
1008
1050
                           sql_field->field_name))
1009
 
      {
1010
1051
        field++;
1011
 
      }
1012
 
 
1013
1052
      if (!sql_field)
1014
1053
      {
1015
1054
        my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name.str);
1016
1055
        return(true);
1017
1056
      }
1018
 
 
1019
1057
      while ((dup_column= cols2++) != column)
1020
1058
      {
1021
1059
        if (!my_strcasecmp(system_charset_info,
1027
1065
          return(true);
1028
1066
        }
1029
1067
      }
1030
 
      cols2= key->columns.begin();
 
1068
      cols2.rewind();
1031
1069
 
1032
1070
      if (create_proto.field_size() > 0)
1033
1071
        protofield= create_proto.mutable_field(proto_field_nr - 1);
1048
1086
            return true;
1049
1087
          }
1050
1088
        }
1051
 
 
1052
1089
        if (! (sql_field->flags & NOT_NULL_FLAG))
1053
1090
        {
1054
1091
          if (key->type == Key::PRIMARY)
1061
1098
            {
1062
1099
              message::Table::Field::FieldConstraints *constraints;
1063
1100
              constraints= protofield->mutable_constraints();
1064
 
              constraints->set_is_notnull(true);
 
1101
              constraints->set_is_nullable(false);
1065
1102
            }
1066
1103
 
1067
1104
          }
1075
1112
            }
1076
1113
          }
1077
1114
        }
1078
 
 
1079
1115
        if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER)
1080
1116
        {
1081
1117
          if (column_nr == 0 || (engine->check_flag(HTON_BIT_AUTO_PART_KEY)))
1200
1236
        key_info->name=(char*) key_name;
1201
1237
      }
1202
1238
    }
1203
 
 
1204
1239
    if (!key_info->name || check_column_name(key_info->name))
1205
1240
    {
1206
1241
      my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key_info->name);
1207
1242
      return(true);
1208
1243
    }
1209
 
 
1210
1244
    if (!(key_info->flags & HA_NULL_PART_KEY))
1211
 
    {
1212
1245
      unique_key=1;
1213
 
    }
1214
 
 
1215
1246
    key_info->key_length=(uint16_t) key_length;
1216
 
 
1217
1247
    if (key_length > max_key_length)
1218
1248
    {
1219
1249
      my_error(ER_TOO_LONG_KEY,MYF(0),max_key_length);
1220
1250
      return(true);
1221
1251
    }
1222
 
 
1223
1252
    key_info++;
1224
1253
  }
1225
 
 
1226
1254
  if (!unique_key && !primary_key &&
1227
1255
      (engine->check_flag(HTON_BIT_REQUIRE_PRIMARY_KEY)))
1228
1256
  {
1229
1257
    my_message(ER_REQUIRES_PRIMARY_KEY, ER(ER_REQUIRES_PRIMARY_KEY), MYF(0));
1230
1258
    return(true);
1231
1259
  }
1232
 
 
1233
1260
  if (auto_increment > 0)
1234
1261
  {
1235
1262
    my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0));
1240
1267
                     (qsort_cmp) sort_keys);
1241
1268
 
1242
1269
  /* Check fields. */
1243
 
  it= alter_info->create_list.begin();
 
1270
  it.rewind();
1244
1271
  while ((sql_field=it++))
1245
1272
  {
1246
1273
    Field::utype type= (Field::utype) MTYP_TYPENR(sql_field->unireg_check);
1247
1274
 
1248
1275
    if (session->variables.sql_mode & MODE_NO_ZERO_DATE &&
1249
1276
        !sql_field->def &&
1250
 
        (sql_field->sql_type == DRIZZLE_TYPE_TIMESTAMP  or sql_field->sql_type == DRIZZLE_TYPE_MICROTIME) &&
 
1277
        sql_field->sql_type == DRIZZLE_TYPE_TIMESTAMP &&
1251
1278
        (sql_field->flags & NOT_NULL_FLAG) &&
1252
1279
        (type == Field::NONE || type == Field::TIMESTAMP_UN_FIELD))
1253
1280
    {
1311
1338
}
1312
1339
 
1313
1340
static bool locked_create_event(Session *session,
1314
 
                                const identifier::Table &identifier,
 
1341
                                TableIdentifier &identifier,
1315
1342
                                HA_CREATE_INFO *create_info,
1316
1343
                                message::Table &table_proto,
1317
1344
                                AlterInfo *alter_info,
1346
1373
        return error;
1347
1374
      }
1348
1375
 
1349
 
      my_error(ER_TABLE_EXISTS_ERROR, identifier);
1350
 
 
 
1376
      my_error(ER_TABLE_EXISTS_ERROR, MYF(0), identifier.getSQLPath().c_str());
1351
1377
      return error;
1352
1378
    }
1353
1379
 
1364
1390
      /*
1365
1391
        @todo improve this error condition.
1366
1392
      */
1367
 
      if (definition::Cache::singleton().find(identifier.getKey()))
 
1393
      if (TableShare::getShare(identifier))
1368
1394
      {
1369
 
        my_error(ER_TABLE_EXISTS_ERROR, identifier);
1370
 
 
 
1395
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), identifier.getSQLPath().c_str());
1371
1396
        return error;
1372
1397
      }
1373
1398
    }
1405
1430
  if (table_proto.type() == message::Table::STANDARD && not internal_tmp_table)
1406
1431
  {
1407
1432
    TransactionServices &transaction_services= TransactionServices::singleton();
1408
 
    transaction_services.createTable(*session, table_proto);
 
1433
    transaction_services.createTable(session, table_proto);
1409
1434
  }
1410
1435
 
1411
1436
  return false;
1418
1443
  Create a table
1419
1444
 
1420
1445
  SYNOPSIS
1421
 
    create_table_no_lock()
 
1446
    mysql_create_table_no_lock()
1422
1447
    session                     Thread object
1423
1448
    db                  Database
1424
1449
    table_name          Table name
1434
1459
 
1435
1460
    Note that this function assumes that caller already have taken
1436
1461
    name-lock on table being created or used some other way to ensure
1437
 
    that concurrent operations won't intervene. create_table()
 
1462
    that concurrent operations won't intervene. mysql_create_table()
1438
1463
    is a wrapper that can be used for this.
1439
1464
 
1440
1465
  RETURN VALUES
1442
1467
    true  error
1443
1468
*/
1444
1469
 
1445
 
bool create_table_no_lock(Session *session,
1446
 
                                const identifier::Table &identifier,
 
1470
bool mysql_create_table_no_lock(Session *session,
 
1471
                                TableIdentifier &identifier,
1447
1472
                                HA_CREATE_INFO *create_info,
1448
1473
                                message::Table &table_proto,
1449
1474
                                AlterInfo *alter_info,
1468
1493
  set_table_default_charset(create_info, identifier.getSchemaName().c_str());
1469
1494
 
1470
1495
  /* Build a Table object to pass down to the engine, and the do the actual create. */
1471
 
  if (not prepare_create_table(session, create_info, table_proto, alter_info,
1472
 
                               internal_tmp_table,
1473
 
                               &db_options,
1474
 
                               &key_info_buffer, &key_count,
1475
 
                               select_field_count))
 
1496
  if (not mysql_prepare_create_table(session, create_info, table_proto, alter_info,
 
1497
                                 internal_tmp_table,
 
1498
                                 &db_options,
 
1499
                                 &key_info_buffer, &key_count,
 
1500
                                 select_field_count))
1476
1501
  {
1477
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* CREATE TABLE (some confussion on naming, double check) */
 
1502
    LOCK_open.lock(); /* CREATE TABLE (some confussion on naming, double check) */
1478
1503
    error= locked_create_event(session,
1479
1504
                               identifier,
1480
1505
                               create_info,
1484
1509
                               internal_tmp_table,
1485
1510
                               db_options, key_count,
1486
1511
                               key_info_buffer);
 
1512
    LOCK_open.unlock();
1487
1513
  }
1488
1514
 
1489
1515
  session->set_proc_info("After create");
1495
1521
  @note the following two methods implement create [temporary] table.
1496
1522
*/
1497
1523
static bool drizzle_create_table(Session *session,
1498
 
                                 const identifier::Table &identifier,
 
1524
                                 TableIdentifier &identifier,
1499
1525
                                 HA_CREATE_INFO *create_info,
1500
1526
                                 message::Table &table_proto,
1501
1527
                                 AlterInfo *alter_info,
1522
1548
    }
1523
1549
    else
1524
1550
    {
1525
 
      my_error(ER_TABLE_EXISTS_ERROR, identifier);
 
1551
      my_error(ER_TABLE_EXISTS_ERROR, MYF(0), identifier.getSQLPath().c_str());
1526
1552
      result= true;
1527
1553
    }
1528
1554
  }
1529
1555
  else
1530
1556
  {
1531
 
    result= create_table_no_lock(session,
 
1557
    result= mysql_create_table_no_lock(session,
1532
1558
                                       identifier,
1533
1559
                                       create_info,
1534
1560
                                       table_proto,
1540
1566
 
1541
1567
  if (name_lock)
1542
1568
  {
1543
 
    boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* Lock for removing name_lock during table create */
 
1569
    LOCK_open.lock(); /* Lock for removing name_lock during table create */
1544
1570
    session->unlink_open_table(name_lock);
 
1571
    LOCK_open.unlock();
1545
1572
  }
1546
1573
 
1547
1574
  return(result);
1549
1576
 
1550
1577
 
1551
1578
/*
1552
 
  Database locking aware wrapper for create_table_no_lock(),
 
1579
  Database locking aware wrapper for mysql_create_table_no_lock(),
1553
1580
*/
1554
 
bool create_table(Session *session,
1555
 
                        const identifier::Table &identifier,
 
1581
bool mysql_create_table(Session *session,
 
1582
                        TableIdentifier &identifier,
1556
1583
                        HA_CREATE_INFO *create_info,
1557
1584
                        message::Table &table_proto,
1558
1585
                        AlterInfo *alter_info,
1562
1589
{
1563
1590
  if (identifier.isTmp())
1564
1591
  {
1565
 
    return create_table_no_lock(session,
 
1592
    return mysql_create_table_no_lock(session,
1566
1593
                                      identifier,
1567
1594
                                      create_info,
1568
1595
                                      table_proto,
1632
1659
  Rename a table.
1633
1660
 
1634
1661
  SYNOPSIS
1635
 
    rename_table()
 
1662
    mysql_rename_table()
1636
1663
      session
1637
1664
      base                      The plugin::StorageEngine handle.
1638
1665
      old_db                    The old database name.
1646
1673
*/
1647
1674
 
1648
1675
bool
1649
 
rename_table(Session &session,
 
1676
mysql_rename_table(Session &session,
1650
1677
                   plugin::StorageEngine *base,
1651
 
                   const identifier::Table &from,
1652
 
                   const identifier::Table &to)
 
1678
                   TableIdentifier &from,
 
1679
                   TableIdentifier &to)
1653
1680
{
1654
1681
  int error= 0;
1655
1682
 
1669
1696
  }
1670
1697
  else if (error)
1671
1698
  {
1672
 
    std::string from_path;
1673
 
    std::string to_path;
1674
 
 
1675
 
    from.getSQLPath(from_path);
1676
 
    to.getSQLPath(to_path);
1677
 
 
1678
 
    const char *from_identifier= from.isTmp() ? "#sql-temporary" : from_path.c_str();
1679
 
    const char *to_identifier= to.isTmp() ? "#sql-temporary" : to_path.c_str();
 
1699
    const char *from_identifier= from.isTmp() ? "#sql-temporary" : from.getSQLPath().c_str();
 
1700
    const char *to_identifier= to.isTmp() ? "#sql-temporary" : to.getSQLPath().c_str();
1680
1701
 
1681
1702
    my_error(ER_ERROR_ON_RENAME, MYF(0), from_identifier, to_identifier, error);
1682
1703
  }
1700
1721
   the table is closed.
1701
1722
 
1702
1723
  PREREQUISITES
1703
 
    Lock on table::Cache::singleton().mutex()
 
1724
    Lock on LOCK_open
1704
1725
    Win32 clients must also have a WRITE LOCK on the table !
1705
1726
*/
1706
1727
 
1708
1729
                              enum ha_extra_function function)
1709
1730
{
1710
1731
 
1711
 
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
 
1732
  safe_mutex_assert_owner(LOCK_open.native_handle());
1712
1733
 
1713
1734
  table->cursor->extra(function);
1714
1735
  /* Mark all tables that are in use as 'old' */
1715
 
  session->abortLock(table);    /* end threads waiting on lock */
 
1736
  mysql_lock_abort(session, table);     /* end threads waiting on lock */
1716
1737
 
1717
1738
  /* Wait until all there are no other threads that has this table open */
1718
 
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName());
1719
 
  table::Cache::singleton().removeTable(session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG);
 
1739
  TableIdentifier identifier(table->getMutableShare()->getSchemaName(), table->getMutableShare()->getTableName());
 
1740
  remove_table_from_cache(session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG);
1720
1741
}
1721
1742
 
1722
1743
/*
1732
1753
    reopen the table.
1733
1754
 
1734
1755
  PREREQUISITES
1735
 
    Lock on table::Cache::singleton().mutex()
 
1756
    Lock on LOCK_open
1736
1757
    Win32 clients must also have a WRITE LOCK on the table !
1737
1758
*/
1738
1759
 
1743
1764
  /* Close lock if this is not got with LOCK TABLES */
1744
1765
  if (lock)
1745
1766
  {
1746
 
    unlockTables(lock);
 
1767
    mysql_unlock_tables(this, lock);
1747
1768
    lock= NULL;                 // Start locked threads
1748
1769
  }
1749
1770
  /* Close all copies of 'table'.  This also frees all LOCK TABLES lock */
1750
1771
  unlink_open_table(table);
1751
1772
 
1752
 
  /* When lock on table::Cache::singleton().mutex() is freed other threads can continue */
1753
 
  locking::broadcast_refresh();
 
1773
  /* When lock on LOCK_open is freed other threads can continue */
 
1774
  broadcast_refresh();
1754
1775
}
1755
1776
 
1756
1777
/*
1759
1780
    true  Message should be sent by caller
1760
1781
          (admin operation or network communication failed)
1761
1782
*/
1762
 
static bool admin_table(Session* session, TableList* tables,
 
1783
static bool mysql_admin_table(Session* session, TableList* tables,
1763
1784
                              HA_CHECK_OPT* check_opt,
1764
1785
                              const char *operator_name,
1765
1786
                              thr_lock_type lock_type,
1768
1789
                                                            HA_CHECK_OPT *))
1769
1790
{
1770
1791
  TableList *table;
1771
 
  Select_Lex *select= &session->getLex()->select_lex;
 
1792
  Select_Lex *select= &session->lex->select_lex;
1772
1793
  List<Item> field_list;
1773
1794
  Item *item;
 
1795
  LEX *lex= session->lex;
1774
1796
  int result_code= 0;
1775
1797
  TransactionServices &transaction_services= TransactionServices::singleton();
1776
1798
  const CHARSET_INFO * const cs= system_charset_info;
1777
1799
 
1778
1800
  if (! session->endActiveTransaction())
1779
1801
    return 1;
1780
 
 
1781
1802
  field_list.push_back(item = new Item_empty_string("Table",
1782
1803
                                                    NAME_CHAR_LEN * 2,
1783
1804
                                                    cs));
1788
1809
  item->maybe_null = 1;
1789
1810
  field_list.push_back(item = new Item_empty_string("Msg_text", 255, cs));
1790
1811
  item->maybe_null = 1;
1791
 
  if (session->getClient()->sendFields(&field_list))
 
1812
  if (session->client->sendFields(&field_list))
1792
1813
    return true;
1793
1814
 
1794
1815
  for (table= tables; table; table= table->next_local)
1795
1816
  {
1796
 
    identifier::Table table_identifier(table->getSchemaName(), table->getTableName());
1797
 
    std::string table_name;
 
1817
    char table_name[NAME_LEN*2+2];
 
1818
    char* db = table->db;
1798
1819
    bool fatal_error=0;
1799
1820
 
1800
 
    table_identifier.getSQLPath(table_name);
1801
 
 
 
1821
    snprintf(table_name, sizeof(table_name), "%s.%s",db,table->table_name);
1802
1822
    table->lock_type= lock_type;
1803
1823
    /* open only one table from local list of command */
1804
1824
    {
1813
1833
        so it have to be prepared.
1814
1834
        @todo Investigate if we can put extra tables into argument instead of using lex->query_tables
1815
1835
      */
1816
 
      session->getLex()->query_tables= table;
1817
 
      session->getLex()->query_tables_last= &table->next_global;
1818
 
      session->getLex()->query_tables_own_last= 0;
 
1836
      lex->query_tables= table;
 
1837
      lex->query_tables_last= &table->next_global;
 
1838
      lex->query_tables_own_last= 0;
1819
1839
      session->no_warnings_for_error= 0;
1820
1840
 
1821
1841
      session->openTablesLock(table);
1845
1865
    {
1846
1866
      char buff[FN_REFLEN + DRIZZLE_ERRMSG_SIZE];
1847
1867
      uint32_t length;
1848
 
      session->getClient()->store(table_name.c_str());
1849
 
      session->getClient()->store(operator_name);
1850
 
      session->getClient()->store(STRING_WITH_LEN("error"));
 
1868
      session->client->store(table_name);
 
1869
      session->client->store(operator_name);
 
1870
      session->client->store(STRING_WITH_LEN("error"));
1851
1871
      length= snprintf(buff, sizeof(buff), ER(ER_OPEN_AS_READONLY),
1852
 
                       table_name.c_str());
1853
 
      session->getClient()->store(buff, length);
1854
 
      transaction_services.autocommitOrRollback(*session, false);
 
1872
                       table_name);
 
1873
      session->client->store(buff, length);
 
1874
      transaction_services.autocommitOrRollback(session, false);
1855
1875
      session->endTransaction(COMMIT);
1856
1876
      session->close_thread_tables();
1857
 
      session->getLex()->reset_query_tables_list(false);
 
1877
      lex->reset_query_tables_list(false);
1858
1878
      table->table=0;                           // For query cache
1859
 
      if (session->getClient()->flush())
 
1879
      if (session->client->flush())
1860
1880
        goto err;
1861
1881
      continue;
1862
1882
    }
1864
1884
    /* Close all instances of the table to allow repair to rename files */
1865
1885
    if (lock_type == TL_WRITE && table->table->getShare()->getVersion())
1866
1886
    {
1867
 
      table::Cache::singleton().mutex().lock(); /* Lock type is TL_WRITE and we lock to repair the table */
1868
 
      const char *old_message=session->enter_cond(COND_refresh, table::Cache::singleton().mutex(),
1869
 
                                                  "Waiting to get writelock");
1870
 
      session->abortLock(table->table);
1871
 
      identifier::Table identifier(table->table->getShare()->getSchemaName(), table->table->getShare()->getTableName());
1872
 
      table::Cache::singleton().removeTable(session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG | RTFC_CHECK_KILLED_FLAG);
 
1887
      LOCK_open.lock(); /* Lock type is TL_WRITE and we lock to repair the table */
 
1888
      const char *old_message=session->enter_cond(COND_refresh.native_handle(), LOCK_open.native_handle(),
 
1889
                                              "Waiting to get writelock");
 
1890
      mysql_lock_abort(session,table->table);
 
1891
      TableIdentifier identifier(table->table->getMutableShare()->getSchemaName(), table->table->getMutableShare()->getTableName());
 
1892
      remove_table_from_cache(session, identifier,
 
1893
                              RTFC_WAIT_OTHER_THREAD_FLAG |
 
1894
                              RTFC_CHECK_KILLED_FLAG);
1873
1895
      session->exit_cond(old_message);
1874
 
      if (session->getKilled())
 
1896
      if (session->killed)
1875
1897
        goto err;
1876
1898
      open_for_modify= 0;
1877
1899
    }
1880
1902
 
1881
1903
send_result:
1882
1904
 
1883
 
    session->getLex()->cleanup_after_one_table_open();
 
1905
    lex->cleanup_after_one_table_open();
1884
1906
    session->clear_error();  // these errors shouldn't get client
1885
1907
    {
1886
 
      List<DRIZZLE_ERROR>::iterator it(session->warn_list.begin());
 
1908
      List_iterator_fast<DRIZZLE_ERROR> it(session->warn_list);
1887
1909
      DRIZZLE_ERROR *err;
1888
1910
      while ((err= it++))
1889
1911
      {
1890
 
        session->getClient()->store(table_name.c_str());
1891
 
        session->getClient()->store(operator_name);
1892
 
        session->getClient()->store(warning_level_names[err->level].str,
 
1912
        session->client->store(table_name);
 
1913
        session->client->store(operator_name);
 
1914
        session->client->store(warning_level_names[err->level].str,
1893
1915
                               warning_level_names[err->level].length);
1894
 
        session->getClient()->store(err->msg);
1895
 
        if (session->getClient()->flush())
 
1916
        session->client->store(err->msg);
 
1917
        if (session->client->flush())
1896
1918
          goto err;
1897
1919
      }
1898
1920
      drizzle_reset_errors(session, true);
1899
1921
    }
1900
 
    session->getClient()->store(table_name.c_str());
1901
 
    session->getClient()->store(operator_name);
 
1922
    session->client->store(table_name);
 
1923
    session->client->store(operator_name);
1902
1924
 
1903
1925
    switch (result_code) {
1904
1926
    case HA_ADMIN_NOT_IMPLEMENTED:
1906
1928
        char buf[ERRMSGSIZE+20];
1907
1929
        uint32_t length=snprintf(buf, ERRMSGSIZE,
1908
1930
                             ER(ER_CHECK_NOT_IMPLEMENTED), operator_name);
1909
 
        session->getClient()->store(STRING_WITH_LEN("note"));
1910
 
        session->getClient()->store(buf, length);
 
1931
        session->client->store(STRING_WITH_LEN("note"));
 
1932
        session->client->store(buf, length);
1911
1933
      }
1912
1934
      break;
1913
1935
 
1914
1936
    case HA_ADMIN_OK:
1915
 
      session->getClient()->store(STRING_WITH_LEN("status"));
1916
 
      session->getClient()->store(STRING_WITH_LEN("OK"));
 
1937
      session->client->store(STRING_WITH_LEN("status"));
 
1938
      session->client->store(STRING_WITH_LEN("OK"));
1917
1939
      break;
1918
1940
 
1919
1941
    case HA_ADMIN_FAILED:
1920
 
      session->getClient()->store(STRING_WITH_LEN("status"));
1921
 
      session->getClient()->store(STRING_WITH_LEN("Operation failed"));
 
1942
      session->client->store(STRING_WITH_LEN("status"));
 
1943
      session->client->store(STRING_WITH_LEN("Operation failed"));
1922
1944
      break;
1923
1945
 
1924
1946
    case HA_ADMIN_REJECT:
1925
 
      session->getClient()->store(STRING_WITH_LEN("status"));
1926
 
      session->getClient()->store(STRING_WITH_LEN("Operation need committed state"));
 
1947
      session->client->store(STRING_WITH_LEN("status"));
 
1948
      session->client->store(STRING_WITH_LEN("Operation need committed state"));
1927
1949
      open_for_modify= false;
1928
1950
      break;
1929
1951
 
1930
1952
    case HA_ADMIN_ALREADY_DONE:
1931
 
      session->getClient()->store(STRING_WITH_LEN("status"));
1932
 
      session->getClient()->store(STRING_WITH_LEN("Table is already up to date"));
 
1953
      session->client->store(STRING_WITH_LEN("status"));
 
1954
      session->client->store(STRING_WITH_LEN("Table is already up to date"));
1933
1955
      break;
1934
1956
 
1935
1957
    case HA_ADMIN_CORRUPT:
1936
 
      session->getClient()->store(STRING_WITH_LEN("error"));
1937
 
      session->getClient()->store(STRING_WITH_LEN("Corrupt"));
 
1958
      session->client->store(STRING_WITH_LEN("error"));
 
1959
      session->client->store(STRING_WITH_LEN("Corrupt"));
1938
1960
      fatal_error=1;
1939
1961
      break;
1940
1962
 
1941
1963
    case HA_ADMIN_INVALID:
1942
 
      session->getClient()->store(STRING_WITH_LEN("error"));
1943
 
      session->getClient()->store(STRING_WITH_LEN("Invalid argument"));
 
1964
      session->client->store(STRING_WITH_LEN("error"));
 
1965
      session->client->store(STRING_WITH_LEN("Invalid argument"));
1944
1966
      break;
1945
1967
 
1946
1968
    default:                            // Probably HA_ADMIN_INTERNAL_ERROR
1949
1971
        uint32_t length=snprintf(buf, ERRMSGSIZE,
1950
1972
                             _("Unknown - internal error %d during operation"),
1951
1973
                             result_code);
1952
 
        session->getClient()->store(STRING_WITH_LEN("error"));
1953
 
        session->getClient()->store(buf, length);
 
1974
        session->client->store(STRING_WITH_LEN("error"));
 
1975
        session->client->store(buf, length);
1954
1976
        fatal_error=1;
1955
1977
        break;
1956
1978
      }
1969
1991
        }
1970
1992
        else
1971
1993
        {
1972
 
          boost::unique_lock<boost::mutex> lock(table::Cache::singleton().mutex());
1973
 
          identifier::Table identifier(table->table->getShare()->getSchemaName(), table->table->getShare()->getTableName());
1974
 
          table::Cache::singleton().removeTable(session, identifier, RTFC_NO_FLAG);
 
1994
          LOCK_open.lock();
 
1995
          TableIdentifier identifier(table->table->getMutableShare()->getSchemaName(), table->table->getMutableShare()->getTableName());
 
1996
          remove_table_from_cache(session, identifier, RTFC_NO_FLAG);
 
1997
          LOCK_open.unlock();
1975
1998
        }
1976
1999
      }
1977
2000
    }
1978
 
    transaction_services.autocommitOrRollback(*session, false);
 
2001
    transaction_services.autocommitOrRollback(session, false);
1979
2002
    session->endTransaction(COMMIT);
1980
2003
    session->close_thread_tables();
1981
2004
    table->table=0;                             // For query cache
1982
 
    if (session->getClient()->flush())
 
2005
    if (session->client->flush())
1983
2006
      goto err;
1984
2007
  }
1985
2008
 
1987
2010
  return(false);
1988
2011
 
1989
2012
err:
1990
 
  transaction_services.autocommitOrRollback(*session, true);
 
2013
  transaction_services.autocommitOrRollback(session, true);
1991
2014
  session->endTransaction(ROLLBACK);
1992
2015
  session->close_thread_tables();                       // Shouldn't be needed
1993
2016
  if (table)
2001
2024
    Altough exclusive name-lock on target table protects us from concurrent
2002
2025
    DML and DDL operations on it we still want to wrap .FRM creation and call
2003
2026
    to plugin::StorageEngine::createTable() in critical section protected by
2004
 
    table::Cache::singleton().mutex() in order to provide minimal atomicity against operations which
 
2027
    LOCK_open in order to provide minimal atomicity against operations which
2005
2028
    disregard name-locks, like I_S implementation, for example. This is a
2006
2029
    temporary and should not be copied. Instead we should fix our code to
2007
2030
    always honor name-locks.
2008
2031
 
2009
 
    Also some engines (e.g. NDB cluster) require that table::Cache::singleton().mutex() should be held
 
2032
    Also some engines (e.g. NDB cluster) require that LOCK_open should be held
2010
2033
    during the call to plugin::StorageEngine::createTable().
2011
2034
    See bug #28614 for more info.
2012
2035
  */
2013
 
static bool create_table_wrapper(Session &session,
2014
 
                                 const message::Table& create_table_proto,
2015
 
                                 identifier::Table::const_reference destination_identifier,
2016
 
                                 identifier::Table::const_reference source_identifier,
 
2036
static bool create_table_wrapper(Session &session, const message::Table& create_table_proto,
 
2037
                                 TableIdentifier &destination_identifier,
 
2038
                                 TableIdentifier &src_table,
2017
2039
                                 bool is_engine_set)
2018
2040
{
2019
 
  // We require an additional table message because during parsing we used
2020
 
  // a "new" message and it will not have all of the information that the
2021
 
  // source table message would have.
2022
 
  message::Table new_table_message;
2023
 
 
2024
 
  message::table::shared_ptr source_table_message= plugin::StorageEngine::getTableMessage(session, source_identifier);
2025
 
 
2026
 
  if (not source_table_message)
2027
 
  {
2028
 
    my_error(ER_TABLE_UNKNOWN, source_identifier);
2029
 
    return false;
2030
 
  }
2031
 
 
2032
 
  new_table_message.CopyFrom(*source_table_message);
 
2041
  int protoerr= EEXIST;
 
2042
  message::Table new_proto;
 
2043
  message::Table src_proto;
 
2044
 
 
2045
  protoerr= plugin::StorageEngine::getTableDefinition(session,
 
2046
                                                      src_table,
 
2047
                                                      src_proto);
 
2048
  new_proto.CopyFrom(src_proto);
2033
2049
 
2034
2050
  if (destination_identifier.isTmp())
2035
2051
  {
2036
 
    new_table_message.set_type(message::Table::TEMPORARY);
 
2052
    new_proto.set_type(message::Table::TEMPORARY);
2037
2053
  }
2038
2054
  else
2039
2055
  {
2040
 
    new_table_message.set_type(message::Table::STANDARD);
 
2056
    new_proto.set_type(message::Table::STANDARD);
2041
2057
  }
2042
2058
 
2043
2059
  if (is_engine_set)
2044
2060
  {
2045
 
    new_table_message.mutable_engine()->set_name(create_table_proto.engine().name());
 
2061
    new_proto.mutable_engine()->set_name(create_table_proto.engine().name());
2046
2062
  }
2047
2063
 
2048
2064
  { // We now do a selective copy of elements on to the new table.
2049
 
    new_table_message.set_name(create_table_proto.name());
2050
 
    new_table_message.set_schema(create_table_proto.schema());
2051
 
    new_table_message.set_catalog(create_table_proto.catalog());
 
2065
    new_proto.set_name(create_table_proto.name());
 
2066
    new_proto.set_schema(create_table_proto.schema());
 
2067
    new_proto.set_catalog(create_table_proto.catalog());
2052
2068
  }
2053
2069
 
2054
 
  /* Fix names of foreign keys being added */
2055
 
  for (int32_t j= 0; j < new_table_message.fk_constraint_size(); j++)
 
2070
  if (protoerr && protoerr != EEXIST)
2056
2071
  {
2057
 
    if (new_table_message.fk_constraint(j).has_name())
2058
 
    {
2059
 
      std::string name(new_table_message.name());
2060
 
      char number[20];
2061
 
 
2062
 
      name.append("_ibfk_");
2063
 
      snprintf(number, sizeof(number), "%d", j+1);
2064
 
      name.append(number);
2065
 
 
2066
 
      message::Table::ForeignKeyConstraint *pfkey= new_table_message.mutable_fk_constraint(j);
2067
 
      pfkey->set_name(name);
2068
 
    }
 
2072
    if (errno == ENOENT)
 
2073
      my_error(ER_BAD_DB_ERROR,MYF(0), destination_identifier.getSchemaName().c_str());
 
2074
    else
 
2075
      my_error(ER_CANT_CREATE_FILE, MYF(0), destination_identifier.getPath().c_str(), errno);
 
2076
 
 
2077
    return false;
2069
2078
  }
2070
2079
 
2071
2080
  /*
2072
2081
    As mysql_truncate don't work on a new table at this stage of
2073
 
    creation, instead create the table directly (for both normal and temporary tables).
 
2082
    creation, instead create the table directly (for both normal
 
2083
    and temporary tables).
2074
2084
  */
2075
 
  bool success= plugin::StorageEngine::createTable(session,
2076
 
                                                   destination_identifier,
2077
 
                                                   new_table_message);
 
2085
  int err= plugin::StorageEngine::createTable(session,
 
2086
                                              destination_identifier,
 
2087
                                              new_proto);
2078
2088
 
2079
 
  if (success && not destination_identifier.isTmp())
 
2089
  if (err == false && not destination_identifier.isTmp())
2080
2090
  {
2081
2091
    TransactionServices &transaction_services= TransactionServices::singleton();
2082
 
    transaction_services.createTable(session, new_table_message);
 
2092
    transaction_services.createTable(&session, new_proto);
2083
2093
  }
2084
2094
 
2085
 
  return success;
 
2095
  return err ? false : true;
2086
2096
}
2087
2097
 
2088
2098
/*
2089
2099
  Create a table identical to the specified table
2090
2100
 
2091
2101
  SYNOPSIS
2092
 
    create_like_table()
 
2102
    mysql_create_like_table()
2093
2103
    session             Thread object
2094
2104
    table       Table list element for target table
2095
2105
    src_table   Table list element for source table
2100
2110
    true  error
2101
2111
*/
2102
2112
 
2103
 
bool create_like_table(Session* session,
2104
 
                       identifier::Table::const_reference destination_identifier,
2105
 
                       identifier::Table::const_reference source_identifier,
2106
 
                       message::Table &create_table_proto,
2107
 
                       bool is_if_not_exists,
2108
 
                       bool is_engine_set)
 
2113
bool mysql_create_like_table(Session* session,
 
2114
                             TableIdentifier &destination_identifier,
 
2115
                             TableList* table, TableList* src_table,
 
2116
                             message::Table &create_table_proto,
 
2117
                             bool is_if_not_exists,
 
2118
                             bool is_engine_set)
2109
2119
{
 
2120
  char *db= table->db;
 
2121
  char *table_name= table->table_name;
2110
2122
  bool res= true;
2111
 
  bool table_exists= false;
 
2123
  uint32_t not_used;
 
2124
 
 
2125
  /*
 
2126
    By opening source table we guarantee that it exists and no concurrent
 
2127
    DDL operation will mess with it. Later we also take an exclusive
 
2128
    name-lock on target table name, which makes copying of .frm cursor,
 
2129
    call to plugin::StorageEngine::createTable() and binlogging atomic
 
2130
    against concurrent DML and DDL operations on target table.
 
2131
    Thus by holding both these "locks" we ensure that our statement is
 
2132
    properly isolated from all concurrent operations which matter.
 
2133
  */
 
2134
  if (session->open_tables_from_list(&src_table, &not_used))
 
2135
    return true;
 
2136
 
 
2137
  TableIdentifier src_identifier(src_table->table->getMutableShare()->getSchemaName(),
 
2138
                                 src_table->table->getMutableShare()->getTableName(), src_table->table->getMutableShare()->getType());
 
2139
 
 
2140
 
2112
2141
 
2113
2142
  /*
2114
2143
    Check that destination tables does not exist. Note that its name
2116
2145
 
2117
2146
    For temporary tables we don't aim to grab locks.
2118
2147
  */
 
2148
  bool table_exists= false;
2119
2149
  if (destination_identifier.isTmp())
2120
2150
  {
2121
 
    if (session->find_temporary_table(destination_identifier))
 
2151
    if (session->find_temporary_table(db, table_name))
2122
2152
    {
2123
2153
      table_exists= true;
2124
2154
    }
2125
2155
    else
2126
2156
    {
2127
 
      bool was_created= create_table_wrapper(*session,
2128
 
                                             create_table_proto,
2129
 
                                             destination_identifier,
2130
 
                                             source_identifier,
2131
 
                                             is_engine_set);
 
2157
      bool was_created= create_table_wrapper(*session, create_table_proto, destination_identifier,
 
2158
                                             src_identifier, is_engine_set);
2132
2159
      if (not was_created) // This is pretty paranoid, but we assume something might not clean up after itself
2133
2160
      {
2134
2161
        (void) session->rm_temporary_table(destination_identifier, true);
2152
2179
    {
2153
2180
      if (name_lock)
2154
2181
      {
2155
 
        boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* unlink open tables for create table like*/
 
2182
        LOCK_open.lock(); /* unlink open tables for create table like*/
2156
2183
        session->unlink_open_table(name_lock);
 
2184
        LOCK_open.unlock();
2157
2185
      }
2158
2186
 
2159
2187
      return res;
2169
2197
    }
2170
2198
    else // Otherwise we create the table
2171
2199
    {
2172
 
      bool was_created;
2173
 
      {
2174
 
        boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* We lock for CREATE TABLE LIKE to copy table definition */
2175
 
        was_created= create_table_wrapper(*session, create_table_proto, destination_identifier,
2176
 
                                          source_identifier, is_engine_set);
2177
 
      }
 
2200
      LOCK_open.lock(); /* We lock for CREATE TABLE LIKE to copy table definition */
 
2201
      bool was_created= create_table_wrapper(*session, create_table_proto, destination_identifier,
 
2202
                                             src_identifier, is_engine_set);
 
2203
      LOCK_open.unlock();
2178
2204
 
2179
2205
      // So we blew the creation of the table, and we scramble to clean up
2180
2206
      // anything that might have been created (read... it is a hack)
2181
2207
      if (not was_created)
2182
2208
      {
2183
 
        plugin::StorageEngine::dropTable(*session, destination_identifier);
 
2209
        quick_rm_table(*session, destination_identifier);
2184
2210
      } 
2185
2211
      else
2186
2212
      {
2190
2216
 
2191
2217
    if (name_lock)
2192
2218
    {
2193
 
      boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* unlink open tables for create table like*/
 
2219
      LOCK_open.lock(); /* unlink open tables for create table like*/
2194
2220
      session->unlink_open_table(name_lock);
 
2221
      LOCK_open.unlock();
2195
2222
    }
2196
2223
  }
2197
2224
 
2201
2228
    {
2202
2229
      char warn_buff[DRIZZLE_ERRMSG_SIZE];
2203
2230
      snprintf(warn_buff, sizeof(warn_buff),
2204
 
               ER(ER_TABLE_EXISTS_ERROR), destination_identifier.getTableName().c_str());
 
2231
               ER(ER_TABLE_EXISTS_ERROR), table_name);
2205
2232
      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
2206
 
                   ER_TABLE_EXISTS_ERROR, warn_buff);
2207
 
      return false;
2208
 
    }
2209
 
 
2210
 
    my_error(ER_TABLE_EXISTS_ERROR, destination_identifier);
2211
 
 
2212
 
    return true;
 
2233
                   ER_TABLE_EXISTS_ERROR,warn_buff);
 
2234
      res= false;
 
2235
    }
 
2236
    else
 
2237
    {
 
2238
      my_error(ER_TABLE_EXISTS_ERROR, MYF(0), table_name);
 
2239
    }
2213
2240
  }
2214
2241
 
2215
 
  return res;
 
2242
  return(res);
2216
2243
}
2217
2244
 
2218
2245
 
2219
 
bool analyze_table(Session* session, TableList* tables, HA_CHECK_OPT* check_opt)
 
2246
bool mysql_analyze_table(Session* session, TableList* tables, HA_CHECK_OPT* check_opt)
2220
2247
{
2221
2248
  thr_lock_type lock_type = TL_READ_NO_INSERT;
2222
2249
 
2223
 
  return(admin_table(session, tables, check_opt,
 
2250
  return(mysql_admin_table(session, tables, check_opt,
2224
2251
                                "analyze", lock_type, true,
2225
2252
                                &Cursor::ha_analyze));
2226
2253
}
2227
2254
 
2228
2255
 
2229
 
bool check_table(Session* session, TableList* tables,HA_CHECK_OPT* check_opt)
 
2256
bool mysql_check_table(Session* session, TableList* tables,HA_CHECK_OPT* check_opt)
2230
2257
{
2231
2258
  thr_lock_type lock_type = TL_READ_NO_INSERT;
2232
2259
 
2233
 
  return(admin_table(session, tables, check_opt,
 
2260
  return(mysql_admin_table(session, tables, check_opt,
2234
2261
                                "check", lock_type,
2235
2262
                                false,
2236
2263
                                &Cursor::ha_check));