~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2004 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
1802.10.2 by Monty Taylor
Update all of the copyright headers to include the correct address.
14
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
1 by brian
clean slate
15
16
/* drop and alter of tables */
17
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
18
#include <config.h>
992.1.25 by Monty Taylor
Moved myisam to new plugin system.
19
#include <plugin/myisam/myisam.h>
575.4.7 by Monty Taylor
More header cleanup.
20
#include <drizzled/show.h>
549 by Monty Taylor
Took gettext.h out of header files.
21
#include <drizzled/error.h>
538 by Monty Taylor
Moved gettext.h into drizzled in anticipation of the new client lib.
22
#include <drizzled/gettext.h>
520.6.7 by Monty Taylor
Moved a bunch of crap out of common_includes.
23
#include <drizzled/data_home.h>
520.8.2 by Monty Taylor
Moved sql_parse.h and sql_error.h out of common_includes.
24
#include <drizzled/sql_parse.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
25
#include <drizzled/sql_lex.h>
26
#include <drizzled/session.h>
27
#include <drizzled/sql_base.h>
670.2.4 by Monty Taylor
Removed more stuff from the headers.
28
#include <drizzled/lock.h>
29
#include <drizzled/unireg.h>
642.1.21 by Lee
header file clean up
30
#include <drizzled/item/int.h>
675 by Brian Aker
Cleanup around item includes.
31
#include <drizzled/item/empty_string.h>
1336.2.2 by Jay Pipes
NO CODE CHANGES - Simply moves pieces of ReplicationServices to TransactionServices. Preparation for making the ReplicationServices component only responsible for communication between replicators, appliers, publishers, and subscribers.
32
#include <drizzled/transaction_services.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
33
#include <drizzled/transaction_services.h>
1095.3.2 by Stewart Smith
remove copy_table_proto_file and replace with read and write proto calls. affects CREATE TABLE LIKE
34
#include <drizzled/table_proto.h>
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
35
#include <drizzled/plugin/client.h>
1660.1.1 by Brian Aker
Merge in move identifier work.
36
#include <drizzled/identifier.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
37
#include <drizzled/internal/m_string.h>
38
#include <drizzled/global_charset_info.h>
39
#include <drizzled/charset.h>
40
#include <drizzled/definition/cache.h>
2241.3.2 by Olaf van der Spek
Refactor Session::variables
41
#include <drizzled/system_variables.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
42
#include <drizzled/statement/alter_table.h>
43
#include <drizzled/sql_table.h>
44
#include <drizzled/pthread_globals.h>
45
#include <drizzled/typelib.h>
46
#include <drizzled/plugin/storage_engine.h>
2241.3.10 by Olaf van der Spek
Move warn_list from Session to diagnostics_area
47
#include <drizzled/diagnostics_area.h>
1225.1.4 by Padraig O'Sullivan
The alter_table header file still needs to be included by sql_table
48
1067.4.4 by Nathan Williams
The rest of the files in the drizzled directory were purged of the cmin macro and replace with std::min (except for the definition in globals.h and 1 usage in stacktrace.cc).
49
#include <algorithm>
1241.9.17 by Monty Taylor
Removed more bits from server_includes.
50
#include <sstream>
1001.1.3 by Andrew Ettinger
Revert bad spacing
51
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
52
#include <boost/unordered_set.hpp>
53
670.3.3 by Toru Maesaka
Added namespacing for std to .cc files that needed it
54
using namespace std;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
55
2241.3.2 by Olaf van der Spek
Refactor Session::variables
56
namespace drizzled {
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
57
1535 by Brian Aker
Rename of KEY to KeyInfo
58
bool is_primary_key(KeyInfo *key_info)
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
59
{
60
  static const char * primary_key_name="PRIMARY";
61
  return (strcmp(key_info->name, primary_key_name)==0);
62
}
63
64
const char* is_primary_key_name(const char* key_name)
65
{
66
  static const char * primary_key_name="PRIMARY";
67
  if (strcmp(key_name, primary_key_name)==0)
68
    return key_name;
69
  else
70
    return NULL;
71
}
1 by brian
clean slate
72
1535 by Brian Aker
Rename of KEY to KeyInfo
73
static bool check_if_keyname_exists(const char *name,KeyInfo *start, KeyInfo *end);
74
static char *make_unique_key_name(const char *field_name,KeyInfo *start,KeyInfo *end);
1 by brian
clean slate
75
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
76
static bool prepare_blob_field(Session *session, CreateField *sql_field);
1 by brian
clean slate
77
1223.4.3 by Brian Aker
More identifier work.
78
void set_table_default_charset(HA_CREATE_INFO *create_info, const char *db)
820.1.11 by Stewart Smith
re-introduce db.opt, but with parsing it from disk instead of in process cache with mutex.
79
{
80
  /*
81
    If the table character set was not given explicitly,
82
    let's fetch the database default character set and
83
    apply it to the table.
84
  */
2087.4.1 by Brian Aker
Merge in schema identifier.
85
  identifier::Schema identifier(db);
1014.3.1 by Brian Aker
Simplify the calling stack for getting schema collation. We need to extend
86
  if (create_info->default_table_charset == NULL)
1415 by Brian Aker
Mass overhaul to use schema_identifier.
87
    create_info->default_table_charset= plugin::StorageEngine::getSchemaCollation(identifier);
820.1.11 by Stewart Smith
re-introduce db.opt, but with parsing it from disk instead of in process cache with mutex.
88
}
89
1 by brian
clean slate
90
/*
91
  Execute the drop of a normal or temporary table
92
93
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
94
    rm_table_part2()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
95
    session			Thread Cursor
1 by brian
clean slate
96
    tables		Tables to drop
97
    if_exists		If set, don't give an error if table doesn't exists.
98
			In this case we give an warning of level 'NOTE'
99
    drop_temporary	Only drop temporary tables
100
1672.3.4 by Brian Aker
This change the style on a few TODO, and fixes an error path to correctly
101
  @todo
1 by brian
clean slate
102
    When logging to the binary log, we should log
103
    tmp_tables and transactional tables as separate statements if we
104
    are in a transaction;  This is needed to get these tables into the
105
    cached binary log that is only written on COMMIT.
106
107
   The current code only writes DROP statements that only uses temporary
108
   tables to the cache binary log.  This should be ok on most cases, but
109
   not all.
110
111
 RETURN
112
   0	ok
113
   1	Error
114
   -1	Thread was killed
115
*/
116
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
117
int rm_table_part2(Session *session, TableList *tables, bool if_exists,
2085.2.1 by Brian Aker
Fix in style/scope issue/removed dead options to method.
118
                   bool drop_temporary)
1 by brian
clean slate
119
{
327.2.4 by Brian Aker
Refactoring table.h
120
  TableList *table;
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
121
  util::string::vector wrong_tables;
1 by brian
clean slate
122
  int error= 0;
1172 by Brian Aker
Update to delete table to centralize the replication logic.
123
  bool foreign_key_error= false;
1 by brian
clean slate
124
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
125
  do
1960.1.2 by Brian Aker
Move mutex behind scoped ().
126
  {
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
127
    boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1960.1.2 by Brian Aker
Move mutex behind scoped ().
128
129
    if (not drop_temporary && session->lock_table_names_exclusively(tables))
130
    {
131
      return 1;
1 by brian
clean slate
132
    }
133
1960.1.2 by Brian Aker
Move mutex behind scoped ().
134
    /* Don't give warnings for not found errors, as we already generate notes */
135
    session->no_warnings_for_error= 1;
136
137
    for (table= tables; table; table= table->next_local)
1 by brian
clean slate
138
    {
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
139
      identifier::Table tmp_identifier(table->getSchemaName(), table->getTableName());
1960.1.2 by Brian Aker
Move mutex behind scoped ().
140
141
      error= session->drop_temporary_table(tmp_identifier);
142
143
      switch (error) {
144
      case  0:
145
        // removed temporary table
146
        continue;
147
      case -1:
148
        error= 1;
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
149
        break;
1960.1.2 by Brian Aker
Move mutex behind scoped ().
150
      default:
151
        // temporary table not found
1308.2.4 by Jay Pipes
Adds DROP TABLE to the list of non RAW_SQL statements in replication stream
152
        error= 0;
1960.1.2 by Brian Aker
Move mutex behind scoped ().
153
      }
154
155
      if (drop_temporary == false)
156
      {
157
        Table *locked_table;
158
        abort_locked_tables(session, tmp_identifier);
159
        table::Cache::singleton().removeTable(session, tmp_identifier,
160
                                              RTFC_WAIT_OTHER_THREAD_FLAG |
161
                                              RTFC_CHECK_KILLED_FLAG);
162
        /*
163
          If the table was used in lock tables, remember it so that
164
          unlock_table_names can free it
165
        */
166
        if ((locked_table= drop_locked_tables(session, tmp_identifier)))
167
          table->table= locked_table;
168
169
        if (session->getKilled())
170
        {
171
          error= -1;
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
172
          break;
1960.1.2 by Brian Aker
Move mutex behind scoped ().
173
        }
174
      }
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
175
      identifier::Table identifier(table->getSchemaName(), table->getTableName(), table->getInternalTmpTable() ? message::Table::INTERNAL : message::Table::STANDARD);
1960.1.2 by Brian Aker
Move mutex behind scoped ().
176
2172.3.1 by Brian Aker
Merge in my patch for having some schema/table not replicated.
177
      message::table::shared_ptr message= plugin::StorageEngine::getTableMessage(*session, identifier, true);
2168.3.2 by Brian Aker
CREATE TABLE/SCHEMA now allow you to add REPLICATION to the list of items
178
1960.1.2 by Brian Aker
Move mutex behind scoped ().
179
      if (drop_temporary || not plugin::StorageEngine::doesTableExist(*session, identifier))
180
      {
181
        // Table was not found on disk and table can't be created from engine
182
        if (if_exists)
2168.3.2 by Brian Aker
CREATE TABLE/SCHEMA now allow you to add REPLICATION to the list of items
183
        {
1960.1.2 by Brian Aker
Move mutex behind scoped ().
184
          push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
185
                              ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR),
186
                              table->getTableName());
2168.3.2 by Brian Aker
CREATE TABLE/SCHEMA now allow you to add REPLICATION to the list of items
187
        }
1960.1.2 by Brian Aker
Move mutex behind scoped ().
188
        else
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
189
        {
1960.1.2 by Brian Aker
Move mutex behind scoped ().
190
          error= 1;
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
191
        }
1960.1.2 by Brian Aker
Move mutex behind scoped ().
192
      }
193
      else
194
      {
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
195
        drizzled::error_t local_error;
1960.1.2 by Brian Aker
Move mutex behind scoped ().
196
2016.3.1 by David Shrewsbury
No longer pass DROP SCHEMA/TABLE through the replication stream if it uses IF EXISTS and does not drop anything. Fix up test cases for this change.
197
        /* Generate transaction event ONLY when we successfully drop */ 
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
198
        if (plugin::StorageEngine::dropTable(*session, identifier, local_error))
2016.3.1 by David Shrewsbury
No longer pass DROP SCHEMA/TABLE through the replication stream if it uses IF EXISTS and does not drop anything. Fix up test cases for this change.
199
        {
2168.3.2 by Brian Aker
CREATE TABLE/SCHEMA now allow you to add REPLICATION to the list of items
200
          if (message) // If we have no definition, we don't know if the table should have been replicated
201
          {
202
            TransactionServices &transaction_services= TransactionServices::singleton();
2172.3.1 by Brian Aker
Merge in my patch for having some schema/table not replicated.
203
            transaction_services.dropTable(*session, identifier, *message, if_exists);
2168.3.2 by Brian Aker
CREATE TABLE/SCHEMA now allow you to add REPLICATION to the list of items
204
          }
2016.3.1 by David Shrewsbury
No longer pass DROP SCHEMA/TABLE through the replication stream if it uses IF EXISTS and does not drop anything. Fix up test cases for this change.
205
        }
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
206
        else
207
        {
208
          if (local_error == HA_ERR_NO_SUCH_TABLE and if_exists)
209
          {
210
            error= 0;
211
            session->clear_error();
212
          }
213
214
          if (local_error == HA_ERR_ROW_IS_REFERENCED)
215
          {
216
            /* the table is referenced by a foreign key constraint */
217
            foreign_key_error= true;
218
          }
219
          error= local_error;
1960.1.2 by Brian Aker
Move mutex behind scoped ().
220
        }
221
      }
222
223
      if (error)
224
      {
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
225
        wrong_tables.push_back(table->getTableName());
1960.1.2 by Brian Aker
Move mutex behind scoped ().
226
      }
227
    }
2064.2.3 by Brian Aker
Merge in clarification on lock for drop table.
228
229
    tables->unlock_table_names();
230
231
  } while (0);
1412 by Brian Aker
Innodb is now in the house (aka... it handls its own DFE).
232
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
233
  if (wrong_tables.size())
1 by brian
clean slate
234
  {
1412 by Brian Aker
Innodb is now in the house (aka... it handls its own DFE).
235
    if (not foreign_key_error)
236
    {
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
237
      std::string table_error;
238
2246.4.1 by Olaf van der Spek
Use BOOST_FOREACH
239
      BOOST_FOREACH(util::string::vector::reference iter, wrong_tables)
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
240
      {
2246.4.1 by Olaf van der Spek
Use BOOST_FOREACH
241
        table_error+= iter;
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
242
        table_error+= ',';
243
      }
244
      table_error.resize(table_error.size() -1);
245
1 by brian
clean slate
246
      my_printf_error(ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR), MYF(0),
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
247
                      table_error.c_str());
1412 by Brian Aker
Innodb is now in the house (aka... it handls its own DFE).
248
    }
1 by brian
clean slate
249
    else
186 by Brian Aker
Partial fix for alter table
250
    {
1 by brian
clean slate
251
      my_message(ER_ROW_IS_REFERENCED, ER(ER_ROW_IS_REFERENCED), MYF(0));
186 by Brian Aker
Partial fix for alter table
252
    }
1 by brian
clean slate
253
    error= 1;
254
  }
255
520.1.22 by Brian Aker
Second pass of thd cleanup
256
  session->no_warnings_for_error= 0;
1034.1.7 by Brian Aker
Remove dead bits to the end of functions.
257
1412 by Brian Aker
Innodb is now in the house (aka... it handls its own DFE).
258
  return error;
1 by brian
clean slate
259
}
260
261
/*
262
  Sort keys in the following order:
263
  - PRIMARY KEY
264
  - UNIQUE keys where all column are NOT NULL
265
  - UNIQUE keys that don't contain partial segments
266
  - Other UNIQUE keys
267
  - Normal keys
268
  - Fulltext keys
269
270
  This will make checking for duplicated keys faster and ensure that
271
  PRIMARY keys are prioritized.
272
*/
273
1535 by Brian Aker
Rename of KEY to KeyInfo
274
static int sort_keys(KeyInfo *a, KeyInfo *b)
1 by brian
clean slate
275
{
276
  ulong a_flags= a->flags, b_flags= b->flags;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
277
1 by brian
clean slate
278
  if (a_flags & HA_NOSAME)
279
  {
280
    if (!(b_flags & HA_NOSAME))
281
      return -1;
53.2.14 by Monty Taylor
Removed HA_END_SPACE_KEY and references to it. It was _supposed_ to be gone anyway, but the ifdef around it was broken (MYSQL_VERSION_ID was actually undefined.)
282
    if ((a_flags ^ b_flags) & (HA_NULL_PART_KEY))
1 by brian
clean slate
283
    {
284
      /* Sort NOT NULL keys before other keys */
53.2.14 by Monty Taylor
Removed HA_END_SPACE_KEY and references to it. It was _supposed_ to be gone anyway, but the ifdef around it was broken (MYSQL_VERSION_ID was actually undefined.)
285
      return (a_flags & (HA_NULL_PART_KEY)) ? 1 : -1;
1 by brian
clean slate
286
    }
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
287
    if (is_primary_key(a))
1 by brian
clean slate
288
      return -1;
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
289
    if (is_primary_key(b))
1 by brian
clean slate
290
      return 1;
291
    /* Sort keys don't containing partial segments before others */
292
    if ((a_flags ^ b_flags) & HA_KEY_HAS_PART_KEY_SEG)
293
      return (a_flags & HA_KEY_HAS_PART_KEY_SEG) ? 1 : -1;
294
  }
295
  else if (b_flags & HA_NOSAME)
296
    return 1;					// Prefer b
297
298
  /*
299
    Prefer original key order.	usable_key_parts contains here
300
    the original key position.
301
  */
302
  return ((a->usable_key_parts < b->usable_key_parts) ? -1 :
303
          (a->usable_key_parts > b->usable_key_parts) ? 1 :
304
          0);
305
}
306
307
/*
308
  Check TYPELIB (set or enum) for duplicates
309
310
  SYNOPSIS
311
    check_duplicates_in_interval()
312
    set_or_name   "SET" or "ENUM" string for warning message
313
    name	  name of the checked column
314
    typelib	  list of values for the column
315
    dup_val_count  returns count of duplicate elements
316
317
  DESCRIPTION
318
    This function prints an warning for each value in list
319
    which has some duplicates on its right
320
321
  RETURN VALUES
322
    0             ok
323
    1             Error
324
*/
325
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
326
class typelib_set_member
327
{
328
public:
329
  string s;
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
330
  const charset_info_st * const cs;
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
331
332
  typelib_set_member(const char* value, unsigned int length,
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
333
                     const charset_info_st * const charset)
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
334
    : s(value, length),
335
      cs(charset)
336
  {}
337
};
338
339
static bool operator==(typelib_set_member const& a, typelib_set_member const& b)
340
{
341
  return (my_strnncoll(a.cs,
342
                       (const unsigned char*)a.s.c_str(), a.s.length(),
343
                       (const unsigned char*)b.s.c_str(), b.s.length())==0);
344
}
345
346
1596.1.3 by Monty Taylor
Modified hash function into a function object so that Sun Studio would
347
namespace
348
{
349
class typelib_set_member_hasher
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
350
{
351
  boost::hash<string> hasher;
1596.1.3 by Monty Taylor
Modified hash function into a function object so that Sun Studio would
352
public:
353
  std::size_t operator()(const typelib_set_member& t) const
354
  {
355
    return hasher(t.s);
356
  }
357
};
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
358
}
359
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
360
static bool check_duplicates_in_interval(const char *set_or_name,
361
                                         const char *name, TYPELIB *typelib,
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
362
                                         const charset_info_st * const cs,
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
363
                                         unsigned int *dup_val_count)
1 by brian
clean slate
364
{
365
  TYPELIB tmp= *typelib;
366
  const char **cur_value= typelib->type_names;
367
  unsigned int *cur_length= typelib->type_lengths;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
368
  *dup_val_count= 0;
369
1596.1.3 by Monty Taylor
Modified hash function into a function object so that Sun Studio would
370
  boost::unordered_set<typelib_set_member, typelib_set_member_hasher> interval_set;
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
371
372
  for ( ; tmp.count > 0; cur_value++, cur_length++)
1 by brian
clean slate
373
  {
374
    tmp.type_names++;
375
    tmp.type_lengths++;
376
    tmp.count--;
2192.5.2 by Olaf van der Spek
Use map::count
377
    if (interval_set.count(typelib_set_member(*cur_value, *cur_length, cs)))
1 by brian
clean slate
378
    {
379
      my_error(ER_DUPLICATED_VALUE_IN_TYPE, MYF(0),
380
               name,*cur_value,set_or_name);
381
      return 1;
382
    }
1579.3.10 by Stewart Smith
switch check_duplicates_in_interval() over to use a boost::unordered_set. Keep using the same comparison operator (whatever the charset/collation). Changes from O(N^2) to O(N) execution. Reduces a test case execution time for 2^16 enum elements from over 4 minutes to less than half a second. The 'real' fix is to get rid of TYPELIB of course.
383
    else
384
      interval_set.insert(typelib_set_member(*cur_value, *cur_length, cs));
1 by brian
clean slate
385
  }
386
  return 0;
387
}
388
389
390
/*
391
  Check TYPELIB (set or enum) max and total lengths
392
393
  SYNOPSIS
394
    calculate_interval_lengths()
395
    cs            charset+collation pair of the interval
396
    typelib       list of values for the column
397
    max_length    length of the longest item
398
    tot_length    sum of the item lengths
399
400
  DESCRIPTION
401
    After this function call:
402
    - ENUM uses max_length
403
    - SET uses tot_length.
404
405
  RETURN VALUES
406
    void
407
*/
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
408
static void calculate_interval_lengths(const charset_info_st * const cs,
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
409
                                       TYPELIB *interval,
410
                                       uint32_t *max_length,
411
                                       uint32_t *tot_length)
1 by brian
clean slate
412
{
413
  const char **pos;
482 by Brian Aker
Remove uint.
414
  uint32_t *len;
1 by brian
clean slate
415
  *max_length= *tot_length= 0;
416
  for (pos= interval->type_names, len= interval->type_lengths;
417
       *pos ; pos++, len++)
418
  {
482 by Brian Aker
Remove uint.
419
    uint32_t length= cs->cset->numchars(cs, *pos, *pos + *len);
1 by brian
clean slate
420
    *tot_length+= length;
205 by Brian Aker
uint32 -> uin32_t
421
    set_if_bigger(*max_length, (uint32_t)length);
1 by brian
clean slate
422
  }
423
}
424
425
/*
426
  Prepare a create_table instance for packing
427
428
  SYNOPSIS
429
    prepare_create_field()
430
    sql_field     field to prepare for packing
431
    blob_columns  count for BLOBs
432
    timestamps    count for timestamps
433
434
  DESCRIPTION
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
435
    This function prepares a CreateField instance.
1 by brian
clean slate
436
    Fields such as pack_flag are valid after this call.
437
438
  RETURN VALUES
439
   0	ok
440
   1	Error
441
*/
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
442
int prepare_create_field(CreateField *sql_field,
482 by Brian Aker
Remove uint.
443
                         uint32_t *blob_columns,
1233.1.8 by Brian Aker
Final removal table_flag().
444
                         int *timestamps,
445
                         int *timestamps_with_niladic)
1 by brian
clean slate
446
{
447
  unsigned int dup_val_count;
448
449
  /*
450
    This code came from mysql_prepare_create_table.
451
    Indent preserved to make patching easier
452
  */
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
453
  assert(sql_field->charset);
1 by brian
clean slate
454
455
  switch (sql_field->sql_type) {
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
456
  case DRIZZLE_TYPE_BLOB:
1119.9.2 by Jay Pipes
Phase I removal of FIELDFLAG_BLOB. This is a piece of poop.
457
    sql_field->length= 8; // Unireg field length
1 by brian
clean slate
458
    (*blob_columns)++;
459
    break;
2046.2.1 by Brian Aker
First pass on micro timestamp.
460
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
461
  case DRIZZLE_TYPE_ENUM:
2046.2.1 by Brian Aker
First pass on micro timestamp.
462
    {
463
      if (check_duplicates_in_interval("ENUM",
464
				       sql_field->field_name,
465
				       sql_field->interval,
466
				       sql_field->charset,
467
				       &dup_val_count))
468
      {
469
	return 1;
470
      }
471
    }
472
    break;
473
474
  case DRIZZLE_TYPE_MICROTIME:
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
475
  case DRIZZLE_TYPE_TIMESTAMP:
1 by brian
clean slate
476
    /* We should replace old TIMESTAMP fields with their newer analogs */
477
    if (sql_field->unireg_check == Field::TIMESTAMP_OLD_FIELD)
478
    {
479
      if (!*timestamps)
480
      {
481
        sql_field->unireg_check= Field::TIMESTAMP_DNUN_FIELD;
482
        (*timestamps_with_niladic)++;
483
      }
484
      else
1575 by Brian Aker
First part, remove pack flags.
485
      {
1 by brian
clean slate
486
        sql_field->unireg_check= Field::NONE;
1575 by Brian Aker
First part, remove pack flags.
487
      }
1 by brian
clean slate
488
    }
489
    else if (sql_field->unireg_check != Field::NONE)
2046.2.1 by Brian Aker
First pass on micro timestamp.
490
    {
1 by brian
clean slate
491
      (*timestamps_with_niladic)++;
2046.2.1 by Brian Aker
First pass on micro timestamp.
492
    }
1 by brian
clean slate
493
494
    (*timestamps)++;
2046.2.1 by Brian Aker
First pass on micro timestamp.
495
496
    break;
497
498
  case DRIZZLE_TYPE_BOOLEAN:
499
  case DRIZZLE_TYPE_DATE:  // Rest of string types
500
  case DRIZZLE_TYPE_DATETIME:
501
  case DRIZZLE_TYPE_DECIMAL:
502
  case DRIZZLE_TYPE_DOUBLE:
503
  case DRIZZLE_TYPE_LONG:
504
  case DRIZZLE_TYPE_LONGLONG:
505
  case DRIZZLE_TYPE_NULL:
506
  case DRIZZLE_TYPE_TIME:
507
  case DRIZZLE_TYPE_UUID:
508
  case DRIZZLE_TYPE_VARCHAR:
1 by brian
clean slate
509
    break;
510
  }
1575 by Brian Aker
First part, remove pack flags.
511
1046.1.10 by Brian Aker
Formatting around return (style)
512
  return 0;
1 by brian
clean slate
513
}
514
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
515
static int prepare_create_table(Session *session,
2064.2.2 by Brian Aker
Formattting, etc.
516
                                HA_CREATE_INFO *create_info,
517
                                message::Table &create_proto,
518
                                AlterInfo *alter_info,
519
                                bool tmp_table,
520
                                uint32_t *db_options,
521
                                KeyInfo **key_info_buffer,
522
                                uint32_t *key_count,
523
                                int select_field_count)
1 by brian
clean slate
524
{
525
  const char	*key_name;
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
526
  CreateField	*sql_field,*dup_field;
1 by brian
clean slate
527
  uint		field,null_fields,blob_columns,max_key_length;
528
  ulong		record_offset= 0;
1535 by Brian Aker
Rename of KEY to KeyInfo
529
  KeyInfo		*key_info;
1534 by Brian Aker
Remove of KeyPartInfo
530
  KeyPartInfo *key_part_info;
1 by brian
clean slate
531
  int		timestamps= 0, timestamps_with_niladic= 0;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
532
  int		dup_no;
1 by brian
clean slate
533
  int		select_field_pos,auto_increment=0;
2183.2.13 by Olaf van der Spek
Use List::begin()
534
  List<CreateField>::iterator it(alter_info->create_list.begin());
535
  List<CreateField>::iterator it2(alter_info->create_list.begin());
482 by Brian Aker
Remove uint.
536
  uint32_t total_uneven_bit_length= 0;
1 by brian
clean slate
537
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
538
  plugin::StorageEngine *engine= plugin::StorageEngine::findByName(create_proto.engine().name());
539
2183.2.20 by Olaf van der Spek
Use List::size()
540
  select_field_pos= alter_info->create_list.size() - select_field_count;
1 by brian
clean slate
541
  null_fields=blob_columns=0;
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
542
  max_key_length= engine->max_key_length();
1 by brian
clean slate
543
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
544
  for (int32_t field_no=0; (sql_field=it++) ; field_no++)
1 by brian
clean slate
545
  {
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
546
    const charset_info_st *save_cs;
1 by brian
clean slate
547
548
    /*
549
      Initialize length from its original value (number of characters),
550
      which was set in the parser. This is necessary if we're
551
      executing a prepared statement for the second time.
552
    */
553
    sql_field->length= sql_field->char_length;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
554
1 by brian
clean slate
555
    if (!sql_field->charset)
556
      sql_field->charset= create_info->default_table_charset;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
557
1 by brian
clean slate
558
    /*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
559
      table_charset is set in ALTER Table if we want change character set
1 by brian
clean slate
560
      for all varchar/char columns.
561
      But the table charset must not affect the BLOB fields, so don't
562
      allow to change my_charset_bin to somethig else.
563
    */
564
    if (create_info->table_charset && sql_field->charset != &my_charset_bin)
565
      sql_field->charset= create_info->table_charset;
566
567
    save_cs= sql_field->charset;
568
    if ((sql_field->flags & BINCMP_FLAG) &&
862 by Brian Aker
Remove charset directory code.
569
        !(sql_field->charset= get_charset_by_csname(sql_field->charset->csname, MY_CS_BINSORT)))
1 by brian
clean slate
570
    {
571
      char tmp[64];
629.5.3 by Toru Maesaka
Third pass of replacing MySQL's strmake() with libc calls
572
      char *tmp_pos= tmp;
573
      strncpy(tmp_pos, save_cs->csname, sizeof(tmp)-4);
574
      tmp_pos+= strlen(tmp);
575
      strncpy(tmp_pos, STRING_WITH_LEN("_bin"));
1 by brian
clean slate
576
      my_error(ER_UNKNOWN_COLLATION, MYF(0), tmp);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
577
      return(true);
1 by brian
clean slate
578
    }
579
580
    /*
581
      Convert the default value from client character
582
      set into the column character set if necessary.
583
    */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
584
    if (sql_field->def &&
1 by brian
clean slate
585
        save_cs != sql_field->def->collation.collation &&
325 by Brian Aker
Remove SET
586
        (sql_field->sql_type == DRIZZLE_TYPE_ENUM))
1 by brian
clean slate
587
    {
588
      /*
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
589
        Starting from 5.1 we work here with a copy of CreateField
1 by brian
clean slate
590
        created by the caller, not with the instance that was
591
        originally created during parsing. It's OK to create
592
        a temporary item and initialize with it a member of the
593
        copy -- this item will be thrown away along with the copy
594
        at the end of execution, and thus not introduce a dangling
595
        pointer in the parsed tree of a prepared statement or a
596
        stored procedure statement.
597
      */
598
      sql_field->def= sql_field->def->safe_charset_converter(save_cs);
599
600
      if (sql_field->def == NULL)
601
      {
602
        /* Could not convert */
603
        my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
604
        return(true);
1 by brian
clean slate
605
      }
606
    }
607
325 by Brian Aker
Remove SET
608
    if (sql_field->sql_type == DRIZZLE_TYPE_ENUM)
1 by brian
clean slate
609
    {
1816.3.1 by Brian Aker
Convert sql_string to use size_t (this should clean up ICC warnings).
610
      size_t dummy;
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
611
      const charset_info_st * const cs= sql_field->charset;
1 by brian
clean slate
612
      TYPELIB *interval= sql_field->interval;
613
614
      /*
615
        Create typelib from interval_list, and if necessary
616
        convert strings from client character set to the
617
        column character set.
618
      */
619
      if (!interval)
620
      {
621
        /*
622
          Create the typelib in runtime memory - we will free the
623
          occupied memory at the same time when we free this
624
          sql_field -- at the end of execution.
625
        */
520.1.22 by Brian Aker
Second pass of thd cleanup
626
        interval= sql_field->interval= typelib(session->mem_root,
1101.1.24 by Monty Taylor
Reverted my change to interval_list
627
                                               sql_field->interval_list);
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
628
2183.2.13 by Olaf van der Spek
Use List::begin()
629
        List<String>::iterator int_it(sql_field->interval_list.begin());
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
630
        String conv, *tmp;
1 by brian
clean slate
631
        char comma_buf[4];
481 by Brian Aker
Remove all of uchar.
632
        int comma_length= cs->cset->wc_mb(cs, ',', (unsigned char*) comma_buf,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
633
                                          (unsigned char*) comma_buf +
1 by brian
clean slate
634
                                          sizeof(comma_buf));
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
635
        assert(comma_length > 0);
1052.2.1 by Nathan Williams
Converted Create_field::interval_list to a std::list<String*>.
636
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
637
        for (uint32_t i= 0; (tmp= int_it++); i++)
1 by brian
clean slate
638
        {
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
639
          uint32_t lengthsp;
1 by brian
clean slate
640
          if (String::needs_conversion(tmp->length(), tmp->charset(),
641
                                       cs, &dummy))
642
          {
1816.3.1 by Brian Aker
Convert sql_string to use size_t (this should clean up ICC warnings).
643
            size_t cnv_errs;
1 by brian
clean slate
644
            conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), cs, &cnv_errs);
1487 by Brian Aker
More updates for memory::Root
645
            interval->type_names[i]= session->mem_root->strmake_root(conv.ptr(), conv.length());
1 by brian
clean slate
646
            interval->type_lengths[i]= conv.length();
647
          }
648
649
          // Strip trailing spaces.
1101.3.1 by Nathan Williams
Reverted CreateField::interval_list to a List<String>. Fixes memory leaks I introduced by converting it to a vector in branch listed below.
650
          lengthsp= cs->cset->lengthsp(cs, interval->type_names[i],
651
                                       interval->type_lengths[i]);
1 by brian
clean slate
652
          interval->type_lengths[i]= lengthsp;
481 by Brian Aker
Remove all of uchar.
653
          ((unsigned char *)interval->type_names[i])[lengthsp]= '\0';
1 by brian
clean slate
654
        }
2179.2.1 by Olaf van der Spek
Rename List::empty to clear (std::list uses clear)
655
        sql_field->interval_list.clear(); // Don't need interval_list anymore
1 by brian
clean slate
656
      }
657
325 by Brian Aker
Remove SET
658
      /* DRIZZLE_TYPE_ENUM */
1 by brian
clean slate
659
      {
205 by Brian Aker
uint32 -> uin32_t
660
        uint32_t field_length;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
661
        assert(sql_field->sql_type == DRIZZLE_TYPE_ENUM);
1 by brian
clean slate
662
        if (sql_field->def != NULL)
663
        {
664
          String str, *def= sql_field->def->val_str(&str);
665
          if (def == NULL) /* SQL "NULL" maps to NULL */
666
          {
667
            if ((sql_field->flags & NOT_NULL_FLAG) != 0)
668
            {
669
              my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
670
              return(true);
1 by brian
clean slate
671
            }
672
673
            /* else, the defaults yield the correct length for NULLs. */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
674
          }
1 by brian
clean slate
675
          else /* not NULL */
676
          {
677
            def->length(cs->cset->lengthsp(cs, def->ptr(), def->length()));
2151.5.4 by Olaf van der Spek
Move strfunc functions into TYPELIB class
678
            if (interval->find_type2(def->ptr(), def->length(), cs) == 0) /* not found */
1 by brian
clean slate
679
            {
680
              my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
681
              return(true);
1 by brian
clean slate
682
            }
683
          }
684
        }
1816.3.1 by Brian Aker
Convert sql_string to use size_t (this should clean up ICC warnings).
685
        uint32_t new_dummy;
686
        calculate_interval_lengths(cs, interval, &field_length, &new_dummy);
1 by brian
clean slate
687
        sql_field->length= field_length;
688
      }
937.2.6 by Stewart Smith
make set_if_bigger typesafe for C and C++. Fix up everywhere.
689
      set_if_smaller(sql_field->length, (uint32_t)MAX_FIELD_WIDTH-1);
1 by brian
clean slate
690
    }
691
692
    sql_field->create_length_to_internal_length();
520.1.22 by Brian Aker
Second pass of thd cleanup
693
    if (prepare_blob_field(session, sql_field))
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
694
      return(true);
1 by brian
clean slate
695
696
    if (!(sql_field->flags & NOT_NULL_FLAG))
697
      null_fields++;
698
699
    if (check_column_name(sql_field->field_name))
700
    {
701
      my_error(ER_WRONG_COLUMN_NAME, MYF(0), sql_field->field_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
702
      return(true);
1 by brian
clean slate
703
    }
704
705
    /* Check if we have used the same field name before */
706
    for (dup_no=0; (dup_field=it2++) != sql_field; dup_no++)
707
    {
708
      if (my_strcasecmp(system_charset_info,
709
                        sql_field->field_name,
710
                        dup_field->field_name) == 0)
711
      {
712
	/*
713
	  If this was a CREATE ... SELECT statement, accept a field
714
	  redefinition if we are changing a field in the SELECT part
715
	*/
716
	if (field_no < select_field_pos || dup_no >= select_field_pos)
717
	{
718
	  my_error(ER_DUP_FIELDNAME, MYF(0), sql_field->field_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
719
	  return(true);
1 by brian
clean slate
720
	}
721
	else
722
	{
723
	  /* Field redefined */
724
	  sql_field->def=		dup_field->def;
725
	  sql_field->sql_type=		dup_field->sql_type;
726
	  sql_field->charset=		(dup_field->charset ?
727
					 dup_field->charset :
728
					 create_info->default_table_charset);
729
	  sql_field->length=		dup_field->char_length;
730
          sql_field->pack_length=	dup_field->pack_length;
731
          sql_field->key_length=	dup_field->key_length;
732
	  sql_field->decimals=		dup_field->decimals;
733
	  sql_field->create_length_to_internal_length();
734
	  sql_field->unireg_check=	dup_field->unireg_check;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
735
          /*
1 by brian
clean slate
736
            We're making one field from two, the result field will have
737
            dup_field->flags as flags. If we've incremented null_fields
738
            because of sql_field->flags, decrement it back.
739
          */
740
          if (!(sql_field->flags & NOT_NULL_FLAG))
741
            null_fields--;
742
	  sql_field->flags=		dup_field->flags;
743
          sql_field->interval=          dup_field->interval;
744
	  it2.remove();			// Remove first (create) definition
745
	  select_field_pos--;
746
	  break;
747
	}
748
      }
749
    }
1308.2.11 by Jay Pipes
* Adds CREATE TABLE as a specific CreateTableStatement message in the
750
751
    /** @todo Get rid of this MyISAM-specific crap. */
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
752
    if (not create_proto.engine().name().compare("MyISAM") &&
1308.2.11 by Jay Pipes
* Adds CREATE TABLE as a specific CreateTableStatement message in the
753
        ((sql_field->flags & BLOB_FLAG) ||
1638.2.1 by Stewart Smith
remove unused row_type from table proto (although referenced in a bunch of places)
754
         (sql_field->sql_type == DRIZZLE_TYPE_VARCHAR)))
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
755
    {
1 by brian
clean slate
756
      (*db_options)|= HA_OPTION_PACK_RECORD;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
757
    }
758
2183.2.1 by Olaf van der Spek
x
759
    it2= alter_info->create_list.begin();
1 by brian
clean slate
760
  }
761
762
  /* record_offset will be increased with 'length-of-null-bits' later */
763
  record_offset= 0;
764
  null_fields+= total_uneven_bit_length;
765
2183.2.1 by Olaf van der Spek
x
766
  it= alter_info->create_list.begin();
1 by brian
clean slate
767
  while ((sql_field=it++))
768
  {
51.2.1 by Patrick Galbraith
Removed DBUG_PRINTs, DBUG_ASSERTs, DBUG_EXECUTE_IFs from
769
    assert(sql_field->charset != 0);
1 by brian
clean slate
770
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
771
    if (prepare_create_field(sql_field, &blob_columns,
1233.1.8 by Brian Aker
Final removal table_flag().
772
			     &timestamps, &timestamps_with_niladic))
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
773
      return(true);
1 by brian
clean slate
774
    sql_field->offset= record_offset;
775
    if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER)
776
      auto_increment++;
777
  }
778
  if (timestamps_with_niladic > 1)
779
  {
780
    my_message(ER_TOO_MUCH_AUTO_TIMESTAMP_COLS,
781
               ER(ER_TOO_MUCH_AUTO_TIMESTAMP_COLS), MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
782
    return(true);
1 by brian
clean slate
783
  }
784
  if (auto_increment > 1)
785
  {
786
    my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
787
    return(true);
1 by brian
clean slate
788
  }
789
  if (auto_increment &&
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
790
      (engine->check_flag(HTON_BIT_NO_AUTO_INCREMENT)))
1 by brian
clean slate
791
  {
792
    my_message(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT,
793
               ER(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT), MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
794
    return(true);
1 by brian
clean slate
795
  }
796
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
797
  if (blob_columns && (engine->check_flag(HTON_BIT_NO_BLOBS)))
1 by brian
clean slate
798
  {
799
    my_message(ER_TABLE_CANT_HANDLE_BLOB, ER(ER_TABLE_CANT_HANDLE_BLOB),
800
               MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
801
    return(true);
1 by brian
clean slate
802
  }
803
804
  /* Create keys */
805
2183.2.13 by Olaf van der Spek
Use List::begin()
806
  List<Key>::iterator key_iterator(alter_info->key_list.begin());
807
  List<Key>::iterator key_iterator2(alter_info->key_list.begin());
482 by Brian Aker
Remove uint.
808
  uint32_t key_parts=0, fk_key_count=0;
1 by brian
clean slate
809
  bool primary_key=0,unique_key=0;
810
  Key *key, *key2;
482 by Brian Aker
Remove uint.
811
  uint32_t tmp, key_number;
1 by brian
clean slate
812
  /* special marker for keys to be ignored */
813
  static char ignore_key[1];
814
815
  /* Calculate number of key segements */
816
  *key_count= 0;
817
818
  while ((key=key_iterator++))
819
  {
820
    if (key->type == Key::FOREIGN_KEY)
821
    {
822
      fk_key_count++;
383.7.1 by Andrey Zhakov
Initial submit of code and tests
823
      if (((Foreign_key *)key)->validate(alter_info->create_list))
824
        return true;
1638.10.80 by Stewart Smith
fix storing and manipulating foreign keys in the proto around ALTER TABLE, CREATE TABLE and ALTER TABLE ADD/DROP FOREIGN KEY. We also (mostly) emulate the naming of innodb foreign keys in the upper layer.
825
1 by brian
clean slate
826
      Foreign_key *fk_key= (Foreign_key*) key;
1638.10.80 by Stewart Smith
fix storing and manipulating foreign keys in the proto around ALTER TABLE, CREATE TABLE and ALTER TABLE ADD/DROP FOREIGN KEY. We also (mostly) emulate the naming of innodb foreign keys in the upper layer.
827
828
      add_foreign_key_to_table_message(&create_proto,
829
                                       fk_key->name.str,
830
                                       fk_key->columns,
831
                                       fk_key->ref_table,
832
                                       fk_key->ref_columns,
833
                                       fk_key->delete_opt,
834
                                       fk_key->update_opt,
835
                                       fk_key->match_opt);
836
2183.2.20 by Olaf van der Spek
Use List::size()
837
      if (fk_key->ref_columns.size() &&
838
	  fk_key->ref_columns.size() != fk_key->columns.size())
1 by brian
clean slate
839
      {
840
        my_error(ER_WRONG_FK_DEF, MYF(0),
841
                 (fk_key->name.str ? fk_key->name.str :
842
                                     "foreign key without name"),
843
                 ER(ER_KEY_REF_DO_NOT_MATCH_TABLE_REF));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
844
	return(true);
1 by brian
clean slate
845
      }
846
      continue;
847
    }
848
    (*key_count)++;
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
849
    tmp= engine->max_key_parts();
2183.2.20 by Olaf van der Spek
Use List::size()
850
    if (key->columns.size() > tmp)
1 by brian
clean slate
851
    {
852
      my_error(ER_TOO_MANY_KEY_PARTS,MYF(0),tmp);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
853
      return(true);
1 by brian
clean slate
854
    }
855
    if (check_identifier_name(&key->name, ER_TOO_LONG_IDENT))
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
856
      return(true);
2183.2.1 by Olaf van der Spek
x
857
    key_iterator2= alter_info->key_list.begin();
1 by brian
clean slate
858
    if (key->type != Key::FOREIGN_KEY)
859
    {
860
      while ((key2 = key_iterator2++) != key)
861
      {
862
	/*
863
          foreign_key_prefix(key, key2) returns 0 if key or key2, or both, is
864
          'generated', and a generated key is a prefix of the other key.
865
          Then we do not need the generated shorter key.
866
        */
867
        if ((key2->type != Key::FOREIGN_KEY &&
868
             key2->name.str != ignore_key &&
869
             !foreign_key_prefix(key, key2)))
870
        {
1672.3.4 by Brian Aker
This change the style on a few TODO, and fixes an error path to correctly
871
          /* @todo issue warning message */
1 by brian
clean slate
872
          /* mark that the generated key should be ignored */
873
          if (!key2->generated ||
2183.2.20 by Olaf van der Spek
Use List::size()
874
              (key->generated && key->columns.size() <
875
               key2->columns.size()))
1 by brian
clean slate
876
            key->name.str= ignore_key;
877
          else
878
          {
879
            key2->name.str= ignore_key;
2183.2.20 by Olaf van der Spek
Use List::size()
880
            key_parts-= key2->columns.size();
1 by brian
clean slate
881
            (*key_count)--;
882
          }
883
          break;
884
        }
885
      }
886
    }
887
    if (key->name.str != ignore_key)
2183.2.20 by Olaf van der Spek
Use List::size()
888
      key_parts+=key->columns.size();
1 by brian
clean slate
889
    else
890
      (*key_count)--;
891
    if (key->name.str && !tmp_table && (key->type != Key::PRIMARY) &&
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
892
        is_primary_key_name(key->name.str))
1 by brian
clean slate
893
    {
894
      my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name.str);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
895
      return(true);
1 by brian
clean slate
896
    }
897
  }
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
898
  tmp= engine->max_keys();
1 by brian
clean slate
899
  if (*key_count > tmp)
900
  {
901
    my_error(ER_TOO_MANY_KEYS,MYF(0),tmp);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
902
    return(true);
1 by brian
clean slate
903
  }
904
1535 by Brian Aker
Rename of KEY to KeyInfo
905
  (*key_info_buffer)= key_info= (KeyInfo*) memory::sql_calloc(sizeof(KeyInfo) * (*key_count));
1534 by Brian Aker
Remove of KeyPartInfo
906
  key_part_info=(KeyPartInfo*) memory::sql_calloc(sizeof(KeyPartInfo)*key_parts);
1 by brian
clean slate
907
  if (!*key_info_buffer || ! key_part_info)
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
908
    return(true);				// Out of memory
1 by brian
clean slate
909
2183.2.1 by Olaf van der Spek
x
910
  key_iterator= alter_info->key_list.begin();
1 by brian
clean slate
911
  key_number=0;
912
  for (; (key=key_iterator++) ; key_number++)
913
  {
482 by Brian Aker
Remove uint.
914
    uint32_t key_length=0;
1 by brian
clean slate
915
    Key_part_spec *column;
916
917
    if (key->name.str == ignore_key)
918
    {
919
      /* ignore redundant keys */
920
      do
921
	key=key_iterator++;
922
      while (key && key->name.str == ignore_key);
923
      if (!key)
924
	break;
925
    }
926
927
    switch (key->type) {
928
    case Key::MULTIPLE:
929
	key_info->flags= 0;
930
	break;
931
    case Key::FOREIGN_KEY:
932
      key_number--;				// Skip this key
933
      continue;
934
    default:
935
      key_info->flags = HA_NOSAME;
936
      break;
937
    }
938
    if (key->generated)
939
      key_info->flags|= HA_GENERATED_KEY;
940
2183.2.20 by Olaf van der Spek
Use List::size()
941
    key_info->key_parts=(uint8_t) key->columns.size();
1 by brian
clean slate
942
    key_info->key_part=key_part_info;
943
    key_info->usable_key_parts= key_number;
944
    key_info->algorithm= key->key_create_info.algorithm;
945
482 by Brian Aker
Remove uint.
946
    uint32_t tmp_len= system_charset_info->cset->charpos(system_charset_info,
1 by brian
clean slate
947
                                           key->key_create_info.comment.str,
948
                                           key->key_create_info.comment.str +
949
                                           key->key_create_info.comment.length,
950
                                           INDEX_COMMENT_MAXLEN);
951
952
    if (tmp_len < key->key_create_info.comment.length)
953
    {
954
      my_error(ER_WRONG_STRING_LENGTH, MYF(0),
955
               key->key_create_info.comment.str,"INDEX COMMENT",
895 by Brian Aker
Completion (?) of uint conversion.
956
               (uint32_t) INDEX_COMMENT_MAXLEN);
1046.1.10 by Brian Aker
Formatting around return (style)
957
      return -1;
1 by brian
clean slate
958
    }
959
960
    key_info->comment.length= key->key_create_info.comment.length;
961
    if (key_info->comment.length > 0)
962
    {
963
      key_info->flags|= HA_USES_COMMENT;
964
      key_info->comment.str= key->key_create_info.comment.str;
965
    }
966
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
967
    message::Table::Field *protofield= NULL;
968
2183.2.13 by Olaf van der Spek
Use List::begin()
969
    List<Key_part_spec>::iterator cols(key->columns.begin());
970
    List<Key_part_spec>::iterator cols2(key->columns.begin());
482 by Brian Aker
Remove uint.
971
    for (uint32_t column_nr=0 ; (column=cols++) ; column_nr++)
1 by brian
clean slate
972
    {
482 by Brian Aker
Remove uint.
973
      uint32_t length;
1 by brian
clean slate
974
      Key_part_spec *dup_column;
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
975
      int proto_field_nr= 0;
1 by brian
clean slate
976
2183.2.1 by Olaf van der Spek
x
977
      it= alter_info->create_list.begin();
1 by brian
clean slate
978
      field=0;
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
979
      while ((sql_field=it++) && ++proto_field_nr &&
1 by brian
clean slate
980
	     my_strcasecmp(system_charset_info,
981
			   column->field_name.str,
982
			   sql_field->field_name))
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
983
      {
1 by brian
clean slate
984
	field++;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
985
      }
986
1 by brian
clean slate
987
      if (!sql_field)
988
      {
989
	my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name.str);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
990
	return(true);
1 by brian
clean slate
991
      }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
992
1 by brian
clean slate
993
      while ((dup_column= cols2++) != column)
994
      {
995
        if (!my_strcasecmp(system_charset_info,
1233.1.3 by Brian Aker
Move more of the flags up to engine flags.
996
                           column->field_name.str, dup_column->field_name.str))
1 by brian
clean slate
997
	{
998
	  my_printf_error(ER_DUP_FIELDNAME,
999
			  ER(ER_DUP_FIELDNAME),MYF(0),
1000
			  column->field_name.str);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1001
	  return(true);
1 by brian
clean slate
1002
	}
1003
      }
2183.2.1 by Olaf van der Spek
x
1004
      cols2= key->columns.begin();
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
1005
1320.1.3 by Brian Aker
More reference cleanup.
1006
      if (create_proto.field_size() > 0)
1007
        protofield= create_proto.mutable_field(proto_field_nr - 1);
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
1008
1 by brian
clean slate
1009
      {
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1010
        column->length*= sql_field->charset->mbmaxlen;
1 by brian
clean slate
1011
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1012
        if (sql_field->sql_type == DRIZZLE_TYPE_BLOB)
1013
        {
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1014
          if (! (engine->check_flag(HTON_BIT_CAN_INDEX_BLOBS)))
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1015
          {
1016
            my_error(ER_BLOB_USED_AS_KEY, MYF(0), column->field_name.str);
1017
            return true;
1018
          }
1019
          if (! column->length)
1020
          {
1021
            my_error(ER_BLOB_KEY_WITHOUT_LENGTH, MYF(0), column->field_name.str);
1022
            return true;
1023
          }
1024
        }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1025
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1026
        if (! (sql_field->flags & NOT_NULL_FLAG))
1027
        {
1028
          if (key->type == Key::PRIMARY)
1029
          {
1030
            /* Implicitly set primary key fields to NOT NULL for ISO conf. */
1031
            sql_field->flags|= NOT_NULL_FLAG;
1 by brian
clean slate
1032
            null_fields--;
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
1033
1034
            if (protofield)
1035
            {
1036
              message::Table::Field::FieldConstraints *constraints;
1037
              constraints= protofield->mutable_constraints();
2064.2.1 by Brian Aker
Fixes naming conventions and issues around notnull being "true" by default.
1038
              constraints->set_is_notnull(true);
1215.1.2 by stewart at flamingspork
[patch 02/17] field NULL | NOT NULL in proto in parser. Only for CREATE TABLE. Change default in proto to reflect default in SQL.
1039
            }
1040
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1041
          }
1042
          else
1 by brian
clean slate
1043
          {
1044
            key_info->flags|= HA_NULL_PART_KEY;
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1045
            if (! (engine->check_flag(HTON_BIT_NULL_IN_KEY)))
1 by brian
clean slate
1046
            {
1047
              my_error(ER_NULL_COLUMN_IN_INDEX, MYF(0), column->field_name.str);
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1048
              return true;
1 by brian
clean slate
1049
            }
1050
          }
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1051
        }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1052
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1053
        if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER)
1054
        {
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1055
          if (column_nr == 0 || (engine->check_flag(HTON_BIT_AUTO_PART_KEY)))
1119.9.10 by Jay Pipes
Removes FIELDFLAG_MAYBE_NULL and f_maybe_null() macro.
1056
            auto_increment--;			// Field is used
1057
        }
1 by brian
clean slate
1058
      }
1059
1060
      key_part_info->fieldnr= field;
206 by Brian Aker
Removed final uint dead types.
1061
      key_part_info->offset=  (uint16_t) sql_field->offset;
1575 by Brian Aker
First part, remove pack flags.
1062
      key_part_info->key_type= 0;
1 by brian
clean slate
1063
      length= sql_field->key_length;
1064
1065
      if (column->length)
1066
      {
1119.9.2 by Jay Pipes
Phase I removal of FIELDFLAG_BLOB. This is a piece of poop.
1067
	if (sql_field->sql_type == DRIZZLE_TYPE_BLOB)
1 by brian
clean slate
1068
	{
1069
	  if ((length=column->length) > max_key_length ||
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1070
	      length > engine->max_key_part_length())
1 by brian
clean slate
1071
	  {
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1072
	    length= min(max_key_length, engine->max_key_part_length());
1 by brian
clean slate
1073
	    if (key->type == Key::MULTIPLE)
1074
	    {
1075
	      /* not a critical problem */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1076
	      char warn_buff[DRIZZLE_ERRMSG_SIZE];
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1077
	      snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_KEY),
1078
                       length);
520.1.22 by Brian Aker
Second pass of thd cleanup
1079
	      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
1080
			   ER_TOO_LONG_KEY, warn_buff);
1081
              /* Align key length to multibyte char boundary */
1082
              length-= length % sql_field->charset->mbmaxlen;
1083
	    }
1084
	    else
1085
	    {
1086
	      my_error(ER_TOO_LONG_KEY,MYF(0),length);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1087
	      return(true);
1 by brian
clean slate
1088
	    }
1089
	  }
1090
	}
1091
	else if ((column->length > length ||
1119.9.11 by Jay Pipes
Removes f_is_packed() macro and FIELDFLAG_PACK
1092
            ! Field::type_can_have_key_part(sql_field->sql_type)))
1 by brian
clean slate
1093
	{
1094
	  my_message(ER_WRONG_SUB_KEY, ER(ER_WRONG_SUB_KEY), MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1095
	  return(true);
1 by brian
clean slate
1096
	}
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1097
	else if (! (engine->check_flag(HTON_BIT_NO_PREFIX_CHAR_KEYS)))
1233.1.7 by Brian Aker
Final table flag removal.
1098
        {
1 by brian
clean slate
1099
	  length=column->length;
1233.1.7 by Brian Aker
Final table flag removal.
1100
        }
1 by brian
clean slate
1101
      }
1102
      else if (length == 0)
1103
      {
1104
	my_error(ER_WRONG_KEY_COLUMN, MYF(0), column->field_name.str);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1105
	  return(true);
1 by brian
clean slate
1106
      }
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1107
      if (length > engine->max_key_part_length())
1 by brian
clean slate
1108
      {
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1109
        length= engine->max_key_part_length();
1 by brian
clean slate
1110
	if (key->type == Key::MULTIPLE)
1111
	{
1112
	  /* not a critical problem */
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1113
	  char warn_buff[DRIZZLE_ERRMSG_SIZE];
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1114
	  snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_KEY),
1115
                   length);
520.1.22 by Brian Aker
Second pass of thd cleanup
1116
	  push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
1117
		       ER_TOO_LONG_KEY, warn_buff);
1118
          /* Align key length to multibyte char boundary */
1119
          length-= length % sql_field->charset->mbmaxlen;
1120
	}
1121
	else
1122
	{
1123
	  my_error(ER_TOO_LONG_KEY,MYF(0),length);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1124
	  return(true);
1 by brian
clean slate
1125
	}
1126
      }
206 by Brian Aker
Removed final uint dead types.
1127
      key_part_info->length=(uint16_t) length;
1 by brian
clean slate
1128
      /* Use packed keys for long strings on the first column */
1129
      if (!((*db_options) & HA_OPTION_NO_PACK_KEYS) &&
1502.1.27 by Brian Aker
Remove dead pack keys code.
1130
          (length >= KEY_DEFAULT_PACK_LENGTH &&
1131
           (sql_field->sql_type == DRIZZLE_TYPE_VARCHAR ||
1132
            sql_field->sql_type == DRIZZLE_TYPE_BLOB)))
1 by brian
clean slate
1133
      {
1119.9.2 by Jay Pipes
Phase I removal of FIELDFLAG_BLOB. This is a piece of poop.
1134
        if ((column_nr == 0 && sql_field->sql_type == DRIZZLE_TYPE_BLOB) ||
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1135
            sql_field->sql_type == DRIZZLE_TYPE_VARCHAR)
1502.1.27 by Brian Aker
Remove dead pack keys code.
1136
        {
1119.9.2 by Jay Pipes
Phase I removal of FIELDFLAG_BLOB. This is a piece of poop.
1137
          key_info->flags|= HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY;
1502.1.27 by Brian Aker
Remove dead pack keys code.
1138
        }
1119.9.2 by Jay Pipes
Phase I removal of FIELDFLAG_BLOB. This is a piece of poop.
1139
        else
1502.1.27 by Brian Aker
Remove dead pack keys code.
1140
        {
1119.9.2 by Jay Pipes
Phase I removal of FIELDFLAG_BLOB. This is a piece of poop.
1141
          key_info->flags|= HA_PACK_KEY;
1502.1.27 by Brian Aker
Remove dead pack keys code.
1142
        }
1 by brian
clean slate
1143
      }
1144
      /* Check if the key segment is partial, set the key flag accordingly */
1145
      if (length != sql_field->key_length)
1146
        key_info->flags|= HA_KEY_HAS_PART_KEY_SEG;
1147
1148
      key_length+=length;
1149
      key_part_info++;
1150
1151
      /* Create the key name based on the first column (if not given) */
1152
      if (column_nr == 0)
1153
      {
1154
	if (key->type == Key::PRIMARY)
1155
	{
1156
	  if (primary_key)
1157
	  {
1158
	    my_message(ER_MULTIPLE_PRI_KEY, ER(ER_MULTIPLE_PRI_KEY),
1159
                       MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1160
	    return(true);
1 by brian
clean slate
1161
	  }
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
1162
          static const char pkey_name[]= "PRIMARY";
1163
	  key_name=pkey_name;
1 by brian
clean slate
1164
	  primary_key=1;
1165
	}
1166
	else if (!(key_name= key->name.str))
1167
	  key_name=make_unique_key_name(sql_field->field_name,
1168
					*key_info_buffer, key_info);
1169
	if (check_if_keyname_exists(key_name, *key_info_buffer, key_info))
1170
	{
1171
	  my_error(ER_DUP_KEYNAME, MYF(0), key_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1172
	  return(true);
1 by brian
clean slate
1173
	}
1174
	key_info->name=(char*) key_name;
1175
      }
1176
    }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1177
1 by brian
clean slate
1178
    if (!key_info->name || check_column_name(key_info->name))
1179
    {
1180
      my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key_info->name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1181
      return(true);
1 by brian
clean slate
1182
    }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1183
1 by brian
clean slate
1184
    if (!(key_info->flags & HA_NULL_PART_KEY))
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1185
    {
1 by brian
clean slate
1186
      unique_key=1;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1187
    }
1188
206 by Brian Aker
Removed final uint dead types.
1189
    key_info->key_length=(uint16_t) key_length;
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1190
1 by brian
clean slate
1191
    if (key_length > max_key_length)
1192
    {
1193
      my_error(ER_TOO_LONG_KEY,MYF(0),max_key_length);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1194
      return(true);
1 by brian
clean slate
1195
    }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1196
1 by brian
clean slate
1197
    key_info++;
1198
  }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1199
1 by brian
clean slate
1200
  if (!unique_key && !primary_key &&
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1201
      (engine->check_flag(HTON_BIT_REQUIRE_PRIMARY_KEY)))
1 by brian
clean slate
1202
  {
1203
    my_message(ER_REQUIRES_PRIMARY_KEY, ER(ER_REQUIRES_PRIMARY_KEY), MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1204
    return(true);
1 by brian
clean slate
1205
  }
2057.2.7 by Brian Aker
Remove need for committed type for microtime in proto.
1206
1 by brian
clean slate
1207
  if (auto_increment > 0)
1208
  {
1209
    my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0));
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1210
    return(true);
1 by brian
clean slate
1211
  }
1212
  /* Sort keys in optimized order */
1535 by Brian Aker
Rename of KEY to KeyInfo
1213
  internal::my_qsort((unsigned char*) *key_info_buffer, *key_count, sizeof(KeyInfo),
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1214
	             (qsort_cmp) sort_keys);
1 by brian
clean slate
1215
1216
  /* Check fields. */
2183.2.1 by Olaf van der Spek
x
1217
  it= alter_info->create_list.begin();
1 by brian
clean slate
1218
  while ((sql_field=it++))
1219
  {
1220
    Field::utype type= (Field::utype) MTYP_TYPENR(sql_field->unireg_check);
1221
520.1.22 by Brian Aker
Second pass of thd cleanup
1222
    if (session->variables.sql_mode & MODE_NO_ZERO_DATE &&
1 by brian
clean slate
1223
        !sql_field->def &&
2167.3.1 by Brian Aker
Fix issues where int display length may be too small, and fix collation
1224
        (sql_field->sql_type == DRIZZLE_TYPE_TIMESTAMP  or sql_field->sql_type == DRIZZLE_TYPE_MICROTIME) &&
1 by brian
clean slate
1225
        (sql_field->flags & NOT_NULL_FLAG) &&
1226
        (type == Field::NONE || type == Field::TIMESTAMP_UN_FIELD))
1227
    {
1228
      /*
1229
        An error should be reported if:
1230
          - NO_ZERO_DATE SQL mode is active;
1231
          - there is no explicit DEFAULT clause (default column value);
1232
          - this is a TIMESTAMP column;
1233
          - the column is not NULL;
1234
          - this is not the DEFAULT CURRENT_TIMESTAMP column.
1235
1236
        In other words, an error should be reported if
1237
          - NO_ZERO_DATE SQL mode is active;
1238
          - the column definition is equivalent to
1239
            'column_name TIMESTAMP DEFAULT 0'.
1240
      */
1241
1242
      my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1243
      return(true);
1 by brian
clean slate
1244
    }
1245
  }
1246
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1247
  return(false);
1 by brian
clean slate
1248
}
1249
1250
/*
1251
  Extend long VARCHAR fields to blob & prepare field if it's a blob
1252
1253
  SYNOPSIS
1254
    prepare_blob_field()
1255
    sql_field		Field to check
1256
1257
  RETURN
1258
    0	ok
1259
    1	Error (sql_field can't be converted to blob)
1260
        In this case the error is given
1261
*/
1262
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
1263
static bool prepare_blob_field(Session *,
1052.2.3 by Nathan Williams
No actual code changes. Changed Create_field to CreateField to be consistent with coding standards.
1264
                               CreateField *sql_field)
1 by brian
clean slate
1265
{
1266
1267
  if (sql_field->length > MAX_FIELD_VARCHARLENGTH &&
1268
      !(sql_field->flags & BLOB_FLAG))
1269
  {
1270
    my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name,
1271
             MAX_FIELD_VARCHARLENGTH / sql_field->charset->mbmaxlen);
1046.1.10 by Brian Aker
Formatting around return (style)
1272
    return 1;
1 by brian
clean slate
1273
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1274
1 by brian
clean slate
1275
  if ((sql_field->flags & BLOB_FLAG) && sql_field->length)
1276
  {
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
1277
    if (sql_field->sql_type == DRIZZLE_TYPE_BLOB)
1 by brian
clean slate
1278
    {
1279
      /* The user has given a length to the blob column */
1280
      sql_field->pack_length= calc_pack_length(sql_field->sql_type, 0);
1281
    }
1282
    sql_field->length= 0;
1283
  }
1046.1.10 by Brian Aker
Formatting around return (style)
1284
  return 0;
1 by brian
clean slate
1285
}
1286
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1287
static bool locked_create_event(Session *session,
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1288
                                const identifier::Table &identifier,
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1289
                                HA_CREATE_INFO *create_info,
1290
                                message::Table &table_proto,
1291
                                AlterInfo *alter_info,
1292
                                bool is_if_not_exists,
1293
                                bool internal_tmp_table,
1294
                                uint db_options,
1295
                                uint key_count,
1535 by Brian Aker
Rename of KEY to KeyInfo
1296
                                KeyInfo *key_info_buffer)
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1297
{
1298
  bool error= true;
1299
1300
  {
1301
1302
    /*
1303
      @note if we are building a temp table we need to check to see if a temp table
1304
      already exists, otherwise we just need to find out if a normal table exists (aka it is fine
1305
      to create a table under a temporary table.
1306
    */
1307
    bool exists= 
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1308
      plugin::StorageEngine::doesTableExist(*session, identifier, 
1309
                                            identifier.getType() != message::Table::STANDARD );
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1310
1311
    if (exists)
1312
    {
1313
      if (is_if_not_exists)
1314
      {
1315
        error= false;
1316
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1317
                            ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1318
                            identifier.getTableName().c_str());
1319
        create_info->table_existed= 1;		// Mark that table existed
1320
        return error;
1321
      }
1322
2096.1.6 by Brian Aker
Merge in fixes for error messages.
1323
      my_error(ER_TABLE_EXISTS_ERROR, identifier);
1954.2.1 by Brian Aker
getSQLPath() modified to take a string so that we can const the table
1324
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1325
      return error;
1326
    }
1327
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1328
    if (identifier.getType() == message::Table::STANDARD) // We have a real table
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1329
    {
1330
      /*
1331
        We don't assert here, but check the result, because the table could be
1332
        in the table definition cache and in the same time the .frm could be
1333
        missing from the disk, in case of manual intervention which deletes
1334
        the .frm cursor. The user has to use FLUSH TABLES; to clear the cache.
1335
        Then she could create the table. This case is pretty obscure and
1336
        therefore we don't introduce a new error message only for it.
1337
      */
1338
      /*
1339
        @todo improve this error condition.
1340
      */
1938.4.4 by Brian Aker
Remove dead getShare() call which should have been a call on the cache
1341
      if (definition::Cache::singleton().find(identifier.getKey()))
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1342
      {
2096.1.6 by Brian Aker
Merge in fixes for error messages.
1343
        my_error(ER_TABLE_EXISTS_ERROR, identifier);
1954.2.1 by Brian Aker
getSQLPath() modified to take a string so that we can const the table
1344
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1345
        return error;
1346
      }
1347
    }
1348
  }
1349
1350
  session->set_proc_info("creating table");
1351
  create_info->table_existed= 0;		// Mark that table is created
1352
1353
  create_info->table_options= db_options;
1354
1372.1.3 by Brian Aker
Refactor for table message.
1355
  if (not rea_create_table(session, identifier,
1356
                           table_proto,
1357
                           create_info, alter_info->create_list,
1358
                           key_count, key_info_buffer))
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1359
  {
1360
    return error;
1361
  }
1362
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1363
  if (identifier.getType() == message::Table::TEMPORARY)
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1364
  {
1365
    /* Open table and put in temporary table list */
1366
    if (not (session->open_temporary_table(identifier)))
1367
    {
1368
      (void) session->rm_temporary_table(identifier);
1369
      return error;
1370
    }
1371
  }
1372
1373
  /* 
1374
    We keep this behind the lock to make sure ordering is correct for a table.
1375
    This is a very unlikely problem where before we would write out to the
1376
    trans log, someone would do a delete/create operation.
1377
  */
1378
1379
  if (table_proto.type() == message::Table::STANDARD && not internal_tmp_table)
1380
  {
1381
    TransactionServices &transaction_services= TransactionServices::singleton();
2096.2.1 by David Shrewsbury
Initial change to use references to Session in TransactionServices methods rather than pointers.
1382
    transaction_services.createTable(*session, table_proto);
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1383
  }
1384
1385
  return false;
1386
}
1387
1 by brian
clean slate
1388
1389
/*
1039.1.11 by Brian Aker
Refactor function to make sense.
1390
  Ignore the name of this function... it locks :(
1391
1 by brian
clean slate
1392
  Create a table
1393
1394
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1395
    create_table_no_lock()
520.1.22 by Brian Aker
Second pass of thd cleanup
1396
    session			Thread object
1 by brian
clean slate
1397
    db			Database
1398
    table_name		Table name
1399
    create_info	        Create information (like MAX_ROWS)
1400
    fields		List of fields to create
1401
    keys		List of keys to create
1402
    internal_tmp_table  Set to 1 if this is an internal temporary table
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1403
			(From ALTER Table)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1404
    select_field_count
1 by brian
clean slate
1405
1406
  DESCRIPTION
1407
    If one creates a temporary table, this is automatically opened
1408
1409
    Note that this function assumes that caller already have taken
1410
    name-lock on table being created or used some other way to ensure
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1411
    that concurrent operations won't intervene. create_table()
1 by brian
clean slate
1412
    is a wrapper that can be used for this.
1413
1414
  RETURN VALUES
55 by brian
Update for using real bool types.
1415
    false OK
1416
    true  error
1 by brian
clean slate
1417
*/
1418
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1419
bool create_table_no_lock(Session *session,
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1420
                                const identifier::Table &identifier,
1 by brian
clean slate
1421
                                HA_CREATE_INFO *create_info,
1320.1.1 by Brian Aker
Light cleanup for references.
1422
				message::Table &table_proto,
1126.3.3 by Jay Pipes
Moves Alter_info out into its own header and source file, cleans up some related include mess in sql_lex.h, and renames Alter_info to AlterInfo.
1423
                                AlterInfo *alter_info,
1 by brian
clean slate
1424
                                bool internal_tmp_table,
1235.2.1 by Brian Aker
More identifier work.
1425
                                uint32_t select_field_count,
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
1426
                                bool is_if_not_exists)
1 by brian
clean slate
1427
{
1428
  uint		db_options, key_count;
1535 by Brian Aker
Rename of KEY to KeyInfo
1429
  KeyInfo		*key_info_buffer;
55 by brian
Update for using real bool types.
1430
  bool		error= true;
1208.3.2 by brian
Update for Cursor renaming.
1431
1 by brian
clean slate
1432
  /* Check for duplicate fields and check type of table to create */
2183.2.20 by Olaf van der Spek
Use List::size()
1433
  if (not alter_info->create_list.size())
1 by brian
clean slate
1434
  {
1435
    my_message(ER_TABLE_MUST_HAVE_COLUMNS, ER(ER_TABLE_MUST_HAVE_COLUMNS),
1436
               MYF(0));
1039.1.11 by Brian Aker
Refactor function to make sense.
1437
    return true;
1 by brian
clean slate
1438
  }
1358.1.9 by Brian Aker
Update for std::string
1439
  assert(identifier.getTableName() == table_proto.name());
1 by brian
clean slate
1440
  db_options= create_info->table_options;
1320.1.15 by Brian Aker
Remove old need for Cursor in creating table.
1441
1415 by Brian Aker
Mass overhaul to use schema_identifier.
1442
  set_table_default_charset(create_info, identifier.getSchemaName().c_str());
1 by brian
clean slate
1443
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1444
  /* Build a Table object to pass down to the engine, and the do the actual create. */
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1445
  if (not prepare_create_table(session, create_info, table_proto, alter_info,
2096.1.2 by Brian Aker
INT is never unsigned, and this fixes the bug about not showing a unique
1446
                               internal_tmp_table,
1447
                               &db_options,
1448
                               &key_info_buffer, &key_count,
1449
                               select_field_count))
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1450
  {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1451
    boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* CREATE TABLE (some confussion on naming, double check) */
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1452
    error= locked_create_event(session,
1453
                               identifier,
1454
                               create_info,
1455
                               table_proto,
1456
                               alter_info,
1457
                               is_if_not_exists,
1458
                               internal_tmp_table,
1459
                               db_options, key_count,
1460
                               key_info_buffer);
1461
  }
1462
1463
  session->set_proc_info("After create");
1464
1465
  return(error);
1466
}
1467
1468
/**
1469
  @note the following two methods implement create [temporary] table.
1470
*/
1471
static bool drizzle_create_table(Session *session,
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1472
                                 const identifier::Table &identifier,
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1473
                                 HA_CREATE_INFO *create_info,
1474
                                 message::Table &table_proto,
1475
                                 AlterInfo *alter_info,
1476
                                 bool internal_tmp_table,
1477
                                 uint32_t select_field_count,
1478
                                 bool is_if_not_exists)
1479
{
1480
  Table *name_lock= NULL;
1481
  bool result;
1482
1483
  if (session->lock_table_name_if_not_cached(identifier, &name_lock))
1484
  {
1485
    result= true;
1486
  }
1487
  else if (name_lock == NULL)
1 by brian
clean slate
1488
  {
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
1489
    if (is_if_not_exists)
1 by brian
clean slate
1490
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1491
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
1492
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1358.1.9 by Brian Aker
Update for std::string
1493
                          identifier.getTableName().c_str());
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1494
      create_info->table_existed= 1;
1495
      result= false;
1496
    }
1497
    else
1498
    {
2096.1.6 by Brian Aker
Merge in fixes for error messages.
1499
      my_error(ER_TABLE_EXISTS_ERROR, identifier);
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1500
      result= true;
1501
    }
1502
  }
1503
  else
1504
  {
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1505
    result= create_table_no_lock(session,
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1506
                                       identifier,
1507
                                       create_info,
1508
                                       table_proto,
1509
                                       alter_info,
1510
                                       internal_tmp_table,
1511
                                       select_field_count,
1512
                                       is_if_not_exists);
1513
  }
1514
1515
  if (name_lock)
1516
  {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1517
    boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* Lock for removing name_lock during table create */
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1518
    session->unlink_open_table(name_lock);
1519
  }
1520
1521
  return(result);
1 by brian
clean slate
1522
}
1523
1524
1525
/*
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1526
  Database locking aware wrapper for create_table_no_lock(),
1 by brian
clean slate
1527
*/
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1528
bool create_table(Session *session,
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1529
                        const identifier::Table &identifier,
1 by brian
clean slate
1530
                        HA_CREATE_INFO *create_info,
1320.1.2 by Brian Aker
More reference counting.
1531
			message::Table &table_proto,
1126.3.3 by Jay Pipes
Moves Alter_info out into its own header and source file, cleans up some related include mess in sql_lex.h, and renames Alter_info to AlterInfo.
1532
                        AlterInfo *alter_info,
1 by brian
clean slate
1533
                        bool internal_tmp_table,
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
1534
                        uint32_t select_field_count,
1535
                        bool is_if_not_exists)
1 by brian
clean slate
1536
{
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1537
  if (identifier.isTmp())
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1538
  {
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1539
    return create_table_no_lock(session,
1372.1.2 by Brian Aker
Rework to remove goto in the create table path.
1540
                                      identifier,
1541
                                      create_info,
1542
                                      table_proto,
1543
                                      alter_info,
1544
                                      internal_tmp_table,
1545
                                      select_field_count,
1546
                                      is_if_not_exists);
1547
  }
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1548
1549
  return drizzle_create_table(session,
1550
                              identifier,
1551
                              create_info,
1552
                              table_proto,
1553
                              alter_info,
1554
                              internal_tmp_table,
1555
                              select_field_count,
1556
                              is_if_not_exists);
1 by brian
clean slate
1557
}
1558
1559
1560
/*
1561
** Give the key name after the first field with an optional '_#' after
1562
**/
1563
1564
static bool
1535 by Brian Aker
Rename of KEY to KeyInfo
1565
check_if_keyname_exists(const char *name, KeyInfo *start, KeyInfo *end)
1 by brian
clean slate
1566
{
1535 by Brian Aker
Rename of KEY to KeyInfo
1567
  for (KeyInfo *key=start ; key != end ; key++)
1 by brian
clean slate
1568
    if (!my_strcasecmp(system_charset_info,name,key->name))
1569
      return 1;
1570
  return 0;
1571
}
1572
1573
1574
static char *
1535 by Brian Aker
Rename of KEY to KeyInfo
1575
make_unique_key_name(const char *field_name,KeyInfo *start,KeyInfo *end)
1 by brian
clean slate
1576
{
1577
  char buff[MAX_FIELD_NAME],*buff_end;
1578
1579
  if (!check_if_keyname_exists(field_name,start,end) &&
590.1.1 by Stewart Smith
begin moving from global const char* primary_key_name to methods is_primary_key() and is_primary_key_name()
1580
      !is_primary_key_name(field_name))
1 by brian
clean slate
1581
    return (char*) field_name;			// Use fieldname
629.5.3 by Toru Maesaka
Third pass of replacing MySQL's strmake() with libc calls
1582
1583
  buff_end= strncpy(buff, field_name, sizeof(buff)-4);
1584
  buff_end+= strlen(buff);
1 by brian
clean slate
1585
1586
  /*
1587
    Only 3 chars + '\0' left, so need to limit to 2 digit
1588
    This is ok as we can't have more than 100 keys anyway
1589
  */
482 by Brian Aker
Remove uint.
1590
  for (uint32_t i=2 ; i< 100; i++)
1 by brian
clean slate
1591
  {
1592
    *buff_end= '_';
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1593
    internal::int10_to_str(i, buff_end+1, 10);
1 by brian
clean slate
1594
    if (!check_if_keyname_exists(buff,start,end))
1253.1.6 by Monty Taylor
Moved mem_root functions into drizzled::memory:: namespace.
1595
      return memory::sql_strdup(buff);
1 by brian
clean slate
1596
  }
1597
  return (char*) "not_specified";		// Should never happen
1598
}
1599
1600
1601
/****************************************************************************
1602
** Alter a table definition
1603
****************************************************************************/
1604
1605
/*
1606
  Rename a table.
1607
1608
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1609
    rename_table()
1578.4.11 by Brian Aker
PAss through the code removing current_session
1610
      session
1130.1.4 by Monty Taylor
Moved StorageEngine into plugin namespace.
1611
      base                      The plugin::StorageEngine handle.
1 by brian
clean slate
1612
      old_db                    The old database name.
1613
      old_name                  The old table name.
1614
      new_db                    The new database name.
1615
      new_name                  The new table name.
1616
1617
  RETURN
55 by brian
Update for using real bool types.
1618
    false   OK
1619
    true    Error
1 by brian
clean slate
1620
*/
1621
1622
bool
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1623
rename_table(Session &session,
1578.4.11 by Brian Aker
PAss through the code removing current_session
1624
                   plugin::StorageEngine *base,
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1625
                   const identifier::Table &from,
1626
                   const identifier::Table &to)
1 by brian
clean slate
1627
{
1415 by Brian Aker
Mass overhaul to use schema_identifier.
1628
  if (not plugin::StorageEngine::doesSchemaExist(to))
1629
  {
1630
    my_error(ER_NO_DB_ERROR, MYF(0), to.getSchemaName().c_str());
1631
    return true;
1632
  }
1633
2246.4.2 by Olaf van der Spek
Refactor Identifier::getSQLPath()
1634
  int error= base->renameTable(session, from, to);
1 by brian
clean slate
1635
  if (error == HA_ERR_WRONG_COMMAND)
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1636
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "ALTER Table");
1 by brian
clean slate
1637
  else if (error)
1389 by Brian Aker
Large reord in ALTER TABLE for RENAME.
1638
  {
2246.4.2 by Olaf van der Spek
Refactor Identifier::getSQLPath()
1639
    my_error(ER_ERROR_ON_RENAME, MYF(0), 
1640
			from.isTmp() ? "#sql-temporary" : from.getSQLPath().c_str(), 
1641
			to.isTmp() ? "#sql-temporary" : to.getSQLPath().c_str(), error);
1389 by Brian Aker
Large reord in ALTER TABLE for RENAME.
1642
  }
2246.4.2 by Olaf van der Spek
Refactor Identifier::getSQLPath()
1643
  return error; 
1 by brian
clean slate
1644
}
1645
1646
1647
/*
1648
  Force all other threads to stop using the table
1649
1650
  SYNOPSIS
1651
    wait_while_table_is_used()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1652
    session			Thread Cursor
1 by brian
clean slate
1653
    table		Table to remove from cache
1654
    function            HA_EXTRA_PREPARE_FOR_DROP if table is to be deleted
1655
                        HA_EXTRA_FORCE_REOPEN if table is not be used
1656
                        HA_EXTRA_PREPARE_FOR_RENAME if table is to be renamed
1657
  NOTES
1658
   When returning, the table will be unusable for other threads until
1659
   the table is closed.
1660
1661
  PREREQUISITES
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1662
    Lock on table::Cache::singleton().mutex()
1 by brian
clean slate
1663
    Win32 clients must also have a WRITE LOCK on the table !
1664
*/
1665
520.1.22 by Brian Aker
Second pass of thd cleanup
1666
void wait_while_table_is_used(Session *session, Table *table,
1 by brian
clean slate
1667
                              enum ha_extra_function function)
1668
{
1669
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1670
  safe_mutex_assert_owner(table::Cache::singleton().mutex().native_handle());
1 by brian
clean slate
1671
1208.3.2 by brian
Update for Cursor renaming.
1672
  table->cursor->extra(function);
1 by brian
clean slate
1673
  /* Mark all tables that are in use as 'old' */
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1674
  session->abortLock(table);	/* end threads waiting on lock */
1 by brian
clean slate
1675
1676
  /* Wait until all there are no other threads that has this table open */
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1677
  identifier::Table identifier(table->getShare()->getSchemaName(), table->getShare()->getTableName());
1877.2.8 by Brian Aker
Additional encapsulation
1678
  table::Cache::singleton().removeTable(session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG);
1 by brian
clean slate
1679
}
1680
1681
/*
1682
  Close a cached table
1683
1684
  SYNOPSIS
1685
    close_cached_table()
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1686
    session			Thread Cursor
1 by brian
clean slate
1687
    table		Table to remove from cache
1688
1689
  NOTES
1690
    Function ends by signaling threads waiting for the table to try to
1691
    reopen the table.
1692
1693
  PREREQUISITES
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1694
    Lock on table::Cache::singleton().mutex()
1 by brian
clean slate
1695
    Win32 clients must also have a WRITE LOCK on the table !
1696
*/
1697
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1698
void Session::close_cached_table(Table *table)
1 by brian
clean slate
1699
{
1700
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1701
  wait_while_table_is_used(this, table, HA_EXTRA_FORCE_REOPEN);
1 by brian
clean slate
1702
  /* Close lock if this is not got with LOCK TABLES */
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1703
  if (lock)
1 by brian
clean slate
1704
  {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1705
    unlockTables(lock);
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1706
    lock= NULL;			// Start locked threads
1 by brian
clean slate
1707
  }
1708
  /* Close all copies of 'table'.  This also frees all LOCK TABLES lock */
1054.1.11 by Brian Aker
Remove dead lock.cc commands.
1709
  unlink_open_table(table);
1 by brian
clean slate
1710
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1711
  /* When lock on table::Cache::singleton().mutex() is freed other threads can continue */
1910.2.5 by Brian Aker
Merge in changes such that lock is now broken out into its own directory.
1712
  locking::broadcast_refresh();
1 by brian
clean slate
1713
}
1714
1715
/*
1716
  RETURN VALUES
55 by brian
Update for using real bool types.
1717
    false Message sent to net (admin operation went ok)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1718
    true  Message should be sent by caller
1 by brian
clean slate
1719
          (admin operation or network communication failed)
1720
*/
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1721
static bool admin_table(Session* session, TableList* tables,
1 by brian
clean slate
1722
                              HA_CHECK_OPT* check_opt,
1723
                              const char *operator_name,
1724
                              thr_lock_type lock_type,
1725
                              bool open_for_modify,
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
1726
                              int (Cursor::*operator_func)(Session *,
1 by brian
clean slate
1727
                                                            HA_CHECK_OPT *))
1728
{
327.2.4 by Brian Aker
Refactoring table.h
1729
  TableList *table;
2227.4.8 by Olaf van der Spek
Session::lex()
1730
  Select_Lex *select= &session->lex().select_lex;
1 by brian
clean slate
1731
  List<Item> field_list;
1732
  Item *item;
1733
  int result_code= 0;
1273.1.2 by Jay Pipes
This patch does not change any algorithms or code paths,
1734
  TransactionServices &transaction_services= TransactionServices::singleton();
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
1735
  const charset_info_st * const cs= system_charset_info;
1 by brian
clean slate
1736
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
1737
  if (! session->endActiveTransaction())
1046.1.10 by Brian Aker
Formatting around return (style)
1738
    return 1;
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1739
1 by brian
clean slate
1740
  field_list.push_back(item = new Item_empty_string("Table",
1741
                                                    NAME_CHAR_LEN * 2,
1742
                                                    cs));
1743
  item->maybe_null = 1;
1744
  field_list.push_back(item = new Item_empty_string("Op", 10, cs));
1745
  item->maybe_null = 1;
1746
  field_list.push_back(item = new Item_empty_string("Msg_type", 10, cs));
1747
  item->maybe_null = 1;
1748
  field_list.push_back(item = new Item_empty_string("Msg_text", 255, cs));
1749
  item->maybe_null = 1;
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1750
  if (session->getClient()->sendFields(&field_list))
971.3.63 by Eric Day
Removed protocol field flags.
1751
    return true;
1 by brian
clean slate
1752
1753
  for (table= tables; table; table= table->next_local)
1754
  {
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1755
    identifier::Table table_identifier(table->getSchemaName(), table->getTableName());
1 by brian
clean slate
1756
    bool fatal_error=0;
1757
2246.4.2 by Olaf van der Spek
Refactor Identifier::getSQLPath()
1758
    std::string table_name = table_identifier.getSQLPath();
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1759
1 by brian
clean slate
1760
    table->lock_type= lock_type;
1761
    /* open only one table from local list of command */
1762
    {
327.2.4 by Brian Aker
Refactoring table.h
1763
      TableList *save_next_global, *save_next_local;
1 by brian
clean slate
1764
      save_next_global= table->next_global;
1765
      table->next_global= 0;
1766
      save_next_local= table->next_local;
1767
      table->next_local= 0;
481 by Brian Aker
Remove all of uchar.
1768
      select->table_list.first= (unsigned char*)table;
1 by brian
clean slate
1769
      /*
1770
        Time zone tables and SP tables can be add to lex->query_tables list,
1771
        so it have to be prepared.
1672.3.4 by Brian Aker
This change the style on a few TODO, and fixes an error path to correctly
1772
        @todo Investigate if we can put extra tables into argument instead of using lex->query_tables
1 by brian
clean slate
1773
      */
2227.4.8 by Olaf van der Spek
Session::lex()
1774
      session->lex().query_tables= table;
1775
      session->lex().query_tables_last= &table->next_global;
1776
      session->lex().query_tables_own_last= 0;
1237.6.2 by Brian Aker
Minor cleanup for dead code.
1777
      session->no_warnings_for_error= 0;
1 by brian
clean slate
1778
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1779
      session->openTablesLock(table);
520.1.22 by Brian Aker
Second pass of thd cleanup
1780
      session->no_warnings_for_error= 0;
1 by brian
clean slate
1781
      table->next_global= save_next_global;
1782
      table->next_local= save_next_local;
1783
    }
1784
1785
    /*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1786
      CHECK Table command is only command where VIEW allowed here and this
1 by brian
clean slate
1787
      command use only temporary teble method for VIEWs resolving => there
1788
      can't be VIEW tree substitition of join view => if opening table
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1789
      succeed then table->table will have real Table pointer as value (in
1 by brian
clean slate
1790
      case of join view substitution table->table can be 0, but here it is
1791
      impossible)
1792
    */
1793
    if (!table->table)
1794
    {
2241.3.10 by Olaf van der Spek
Move warn_list from Session to diagnostics_area
1795
      if (!session->main_da().m_warn_list.size())
520.1.22 by Brian Aker
Second pass of thd cleanup
1796
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1 by brian
clean slate
1797
                     ER_CHECK_NO_SUCH_TABLE, ER(ER_CHECK_NO_SUCH_TABLE));
1001.1.6 by Andrew Ettinger
Match style guide
1798
      result_code= HA_ADMIN_CORRUPT;
1 by brian
clean slate
1799
      goto send_result;
1800
    }
1801
1802
    if ((table->table->db_stat & HA_READ_ONLY) && open_for_modify)
1803
    {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1804
      char buff[FN_REFLEN + DRIZZLE_ERRMSG_SIZE];
482 by Brian Aker
Remove uint.
1805
      uint32_t length;
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1806
      session->getClient()->store(table_name.c_str());
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1807
      session->getClient()->store(operator_name);
1808
      session->getClient()->store(STRING_WITH_LEN("error"));
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1809
      length= snprintf(buff, sizeof(buff), ER(ER_OPEN_AS_READONLY),
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1810
                       table_name.c_str());
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1811
      session->getClient()->store(buff, length);
2096.2.1 by David Shrewsbury
Initial change to use references to Session in TransactionServices methods rather than pointers.
1812
      transaction_services.autocommitOrRollback(*session, false);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
1813
      session->endTransaction(COMMIT);
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1814
      session->close_thread_tables();
2227.4.8 by Olaf van der Spek
Session::lex()
1815
      session->lex().reset_query_tables_list(false);
1 by brian
clean slate
1816
      table->table=0;				// For query cache
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1817
      if (session->getClient()->flush())
1 by brian
clean slate
1818
	goto err;
1819
      continue;
1820
    }
1821
1822
    /* Close all instances of the table to allow repair to rename files */
1578.2.3 by Brian Aker
Take version and encapsulate it in TableShare
1823
    if (lock_type == TL_WRITE && table->table->getShare()->getVersion())
1 by brian
clean slate
1824
    {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1825
      table::Cache::singleton().mutex().lock(); /* Lock type is TL_WRITE and we lock to repair the table */
1826
      const char *old_message=session->enter_cond(COND_refresh, table::Cache::singleton().mutex(),
1703.1.1 by Brian Aker
Update lock interface.
1827
                                                  "Waiting to get writelock");
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1828
      session->abortLock(table->table);
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1829
      identifier::Table identifier(table->table->getShare()->getSchemaName(), table->table->getShare()->getTableName());
1887.2.5 by Brian Aker
OSX found a reference to a function that was no longer declared.
1830
      table::Cache::singleton().removeTable(session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG | RTFC_CHECK_KILLED_FLAG);
520.1.22 by Brian Aker
Second pass of thd cleanup
1831
      session->exit_cond(old_message);
1910.2.8 by Brian Aker
Enapsulate Kill.
1832
      if (session->getKilled())
1 by brian
clean slate
1833
	goto err;
1834
      open_for_modify= 0;
1835
    }
1836
1208.3.2 by brian
Update for Cursor renaming.
1837
    result_code = (table->table->cursor->*operator_func)(session, check_opt);
1001.1.3 by Andrew Ettinger
Revert bad spacing
1838
1 by brian
clean slate
1839
send_result:
1840
2227.4.8 by Olaf van der Spek
Session::lex()
1841
    session->lex().cleanup_after_one_table_open();
520.1.22 by Brian Aker
Second pass of thd cleanup
1842
    session->clear_error();  // these errors shouldn't get client
1 by brian
clean slate
1843
    {
2241.3.10 by Olaf van der Spek
Move warn_list from Session to diagnostics_area
1844
      List<DRIZZLE_ERROR>::iterator it(session->main_da().m_warn_list.begin());
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1845
      DRIZZLE_ERROR *err;
1 by brian
clean slate
1846
      while ((err= it++))
1847
      {
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1848
        session->getClient()->store(table_name.c_str());
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1849
        session->getClient()->store(operator_name);
1850
        session->getClient()->store(warning_level_names[err->level].str,
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1851
                               warning_level_names[err->level].length);
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1852
        session->getClient()->store(err->msg);
1853
        if (session->getClient()->flush())
1 by brian
clean slate
1854
          goto err;
1855
      }
520.1.22 by Brian Aker
Second pass of thd cleanup
1856
      drizzle_reset_errors(session, true);
1 by brian
clean slate
1857
    }
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1858
    session->getClient()->store(table_name.c_str());
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1859
    session->getClient()->store(operator_name);
1 by brian
clean slate
1860
1861
    switch (result_code) {
1862
    case HA_ADMIN_NOT_IMPLEMENTED:
1001.1.3 by Andrew Ettinger
Revert bad spacing
1863
      {
1864
	char buf[ERRMSGSIZE+20];
1865
	uint32_t length=snprintf(buf, ERRMSGSIZE,
1866
                             ER(ER_CHECK_NOT_IMPLEMENTED), operator_name);
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1867
	session->getClient()->store(STRING_WITH_LEN("note"));
1868
	session->getClient()->store(buf, length);
1001.1.3 by Andrew Ettinger
Revert bad spacing
1869
      }
1870
      break;
1 by brian
clean slate
1871
1872
    case HA_ADMIN_OK:
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1873
      session->getClient()->store(STRING_WITH_LEN("status"));
1874
      session->getClient()->store(STRING_WITH_LEN("OK"));
1 by brian
clean slate
1875
      break;
1876
1877
    case HA_ADMIN_FAILED:
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1878
      session->getClient()->store(STRING_WITH_LEN("status"));
1879
      session->getClient()->store(STRING_WITH_LEN("Operation failed"));
1 by brian
clean slate
1880
      break;
1881
1882
    case HA_ADMIN_REJECT:
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1883
      session->getClient()->store(STRING_WITH_LEN("status"));
1884
      session->getClient()->store(STRING_WITH_LEN("Operation need committed state"));
55 by brian
Update for using real bool types.
1885
      open_for_modify= false;
1 by brian
clean slate
1886
      break;
1887
1888
    case HA_ADMIN_ALREADY_DONE:
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1889
      session->getClient()->store(STRING_WITH_LEN("status"));
1890
      session->getClient()->store(STRING_WITH_LEN("Table is already up to date"));
1 by brian
clean slate
1891
      break;
1892
1893
    case HA_ADMIN_CORRUPT:
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1894
      session->getClient()->store(STRING_WITH_LEN("error"));
1895
      session->getClient()->store(STRING_WITH_LEN("Corrupt"));
1 by brian
clean slate
1896
      fatal_error=1;
1897
      break;
1898
1899
    case HA_ADMIN_INVALID:
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1900
      session->getClient()->store(STRING_WITH_LEN("error"));
1901
      session->getClient()->store(STRING_WITH_LEN("Invalid argument"));
1 by brian
clean slate
1902
      break;
1903
1904
    default:				// Probably HA_ADMIN_INTERNAL_ERROR
1905
      {
1906
        char buf[ERRMSGSIZE+20];
482 by Brian Aker
Remove uint.
1907
        uint32_t length=snprintf(buf, ERRMSGSIZE,
338 by Monty Taylor
Tagged more strings.
1908
                             _("Unknown - internal error %d during operation"),
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
1909
                             result_code);
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1910
        session->getClient()->store(STRING_WITH_LEN("error"));
1911
        session->getClient()->store(buf, length);
1 by brian
clean slate
1912
        fatal_error=1;
1913
        break;
1914
      }
1915
    }
1916
    if (table->table)
1917
    {
1918
      if (fatal_error)
1578.2.3 by Brian Aker
Take version and encapsulate it in TableShare
1919
      {
1920
        table->table->getMutableShare()->resetVersion();               // Force close of table
1921
      }
1 by brian
clean slate
1922
      else if (open_for_modify)
1923
      {
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
1924
        if (table->table->getShare()->getType())
1578.2.3 by Brian Aker
Take version and encapsulate it in TableShare
1925
        {
1208.3.2 by brian
Update for Cursor renaming.
1926
          table->table->cursor->info(HA_STATUS_CONST);
1578.2.3 by Brian Aker
Take version and encapsulate it in TableShare
1927
        }
1 by brian
clean slate
1928
        else
1929
        {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1930
          boost::unique_lock<boost::mutex> lock(table::Cache::singleton().mutex());
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1931
	  identifier::Table identifier(table->table->getShare()->getSchemaName(), table->table->getShare()->getTableName());
1877.2.8 by Brian Aker
Additional encapsulation
1932
          table::Cache::singleton().removeTable(session, identifier, RTFC_NO_FLAG);
1 by brian
clean slate
1933
        }
1934
      }
1935
    }
2096.2.1 by David Shrewsbury
Initial change to use references to Session in TransactionServices methods rather than pointers.
1936
    transaction_services.autocommitOrRollback(*session, false);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
1937
    session->endTransaction(COMMIT);
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1938
    session->close_thread_tables();
1 by brian
clean slate
1939
    table->table=0;				// For query cache
2015.3.1 by Brian Aker
Encapsulate client call. Also remove the need to call current_session when
1940
    if (session->getClient()->flush())
1 by brian
clean slate
1941
      goto err;
1942
  }
1943
836 by Brian Aker
Fixed session call from function to method.
1944
  session->my_eof();
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1945
  return(false);
1 by brian
clean slate
1946
1947
err:
2096.2.1 by David Shrewsbury
Initial change to use references to Session in TransactionServices methods rather than pointers.
1948
  transaction_services.autocommitOrRollback(*session, true);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
1949
  session->endTransaction(ROLLBACK);
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1950
  session->close_thread_tables();			// Shouldn't be needed
1 by brian
clean slate
1951
  if (table)
1952
    table->table=0;
51.1.8 by Jay Pipes
Resolving conflicts for a few files regarding FALSE=>false
1953
  return(true);
1 by brian
clean slate
1954
}
1955
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1956
  /*
1957
    Create a new table by copying from source table
1958
1959
    Altough exclusive name-lock on target table protects us from concurrent
1960
    DML and DDL operations on it we still want to wrap .FRM creation and call
1961
    to plugin::StorageEngine::createTable() in critical section protected by
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1962
    table::Cache::singleton().mutex() in order to provide minimal atomicity against operations which
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1963
    disregard name-locks, like I_S implementation, for example. This is a
1964
    temporary and should not be copied. Instead we should fix our code to
1965
    always honor name-locks.
1966
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
1967
    Also some engines (e.g. NDB cluster) require that table::Cache::singleton().mutex() should be held
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1968
    during the call to plugin::StorageEngine::createTable().
1969
    See bug #28614 for more info.
1970
  */
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
1971
static bool create_table_wrapper(Session &session,
1972
                                 const message::Table& create_table_proto,
2246.4.10 by Olaf van der Spek
Remove const_reference and reference from identifier::Table
1973
                                 const identifier::Table& destination_identifier,
1974
                                 const identifier::Table& source_identifier,
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1975
                                 bool is_engine_set)
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1976
{
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
1977
  // We require an additional table message because during parsing we used
1978
  // a "new" message and it will not have all of the information that the
1979
  // source table message would have.
2079.3.2 by Brian Aker
Fix for regression 622465.
1980
  message::Table new_table_message;
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
1981
2159.2.4 by Brian Aker
Merge in error wasteful removal.
1982
  message::table::shared_ptr source_table_message= plugin::StorageEngine::getTableMessage(session, source_identifier);
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
1983
1984
  if (not source_table_message)
1985
  {
1986
    my_error(ER_TABLE_UNKNOWN, source_identifier);
1987
    return false;
1988
  }
1989
2079.3.2 by Brian Aker
Fix for regression 622465.
1990
  new_table_message.CopyFrom(*source_table_message);
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1991
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1992
  if (destination_identifier.isTmp())
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1993
  {
2079.3.2 by Brian Aker
Fix for regression 622465.
1994
    new_table_message.set_type(message::Table::TEMPORARY);
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1995
  }
1996
  else
1997
  {
2079.3.2 by Brian Aker
Fix for regression 622465.
1998
    new_table_message.set_type(message::Table::STANDARD);
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
1999
  }
2000
2001
  if (is_engine_set)
2002
  {
2079.3.2 by Brian Aker
Fix for regression 622465.
2003
    new_table_message.mutable_engine()->set_name(create_table_proto.engine().name());
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2004
  }
2005
1389 by Brian Aker
Large reord in ALTER TABLE for RENAME.
2006
  { // We now do a selective copy of elements on to the new table.
2079.3.2 by Brian Aker
Fix for regression 622465.
2007
    new_table_message.set_name(create_table_proto.name());
2008
    new_table_message.set_schema(create_table_proto.schema());
2009
    new_table_message.set_catalog(create_table_proto.catalog());
2010
  }
2011
2012
  /* Fix names of foreign keys being added */
2013
  for (int32_t j= 0; j < new_table_message.fk_constraint_size(); j++)
2014
  {
2015
    if (new_table_message.fk_constraint(j).has_name())
2016
    {
2017
      std::string name(new_table_message.name());
2018
      char number[20];
2019
2020
      name.append("_ibfk_");
2021
      snprintf(number, sizeof(number), "%d", j+1);
2022
      name.append(number);
2023
2024
      message::Table::ForeignKeyConstraint *pfkey= new_table_message.mutable_fk_constraint(j);
2025
      pfkey->set_name(name);
2026
    }
1389 by Brian Aker
Large reord in ALTER TABLE for RENAME.
2027
  }
2028
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2029
  /*
2030
    As mysql_truncate don't work on a new table at this stage of
2068.7.6 by Brian Aker
Fix interface for create table such that it issues error and returns state
2031
    creation, instead create the table directly (for both normal and temporary tables).
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2032
  */
2068.7.6 by Brian Aker
Fix interface for create table such that it issues error and returns state
2033
  bool success= plugin::StorageEngine::createTable(session,
2034
                                                   destination_identifier,
2079.3.2 by Brian Aker
Fix for regression 622465.
2035
                                                   new_table_message);
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2036
2068.7.6 by Brian Aker
Fix interface for create table such that it issues error and returns state
2037
  if (success && not destination_identifier.isTmp())
1616 by Brian Aker
Discovery that create table like was not going through replication path
2038
  {
2039
    TransactionServices &transaction_services= TransactionServices::singleton();
2096.2.1 by David Shrewsbury
Initial change to use references to Session in TransactionServices methods rather than pointers.
2040
    transaction_services.createTable(session, new_table_message);
1616 by Brian Aker
Discovery that create table like was not going through replication path
2041
  }
2042
2068.7.6 by Brian Aker
Fix interface for create table such that it issues error and returns state
2043
  return success;
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2044
}
2045
1 by brian
clean slate
2046
/*
2047
  Create a table identical to the specified table
2048
2049
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
2050
    create_like_table()
520.1.22 by Brian Aker
Second pass of thd cleanup
2051
    session		Thread object
1 by brian
clean slate
2052
    table       Table list element for target table
2053
    src_table   Table list element for source table
2054
    create_info Create info
2055
2056
  RETURN VALUES
55 by brian
Update for using real bool types.
2057
    false OK
2058
    true  error
1 by brian
clean slate
2059
*/
2060
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
2061
bool create_like_table(Session* session,
2246.4.10 by Olaf van der Spek
Remove const_reference and reference from identifier::Table
2062
                       const identifier::Table& destination_identifier,
2063
                       const identifier::Table& source_identifier,
2068.7.6 by Brian Aker
Fix interface for create table such that it issues error and returns state
2064
                       message::Table &create_table_proto,
2065
                       bool is_if_not_exists,
2066
                       bool is_engine_set)
1 by brian
clean slate
2067
{
55 by brian
Update for using real bool types.
2068
  bool res= true;
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
2069
  bool table_exists= false;
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2070
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2071
  /*
1 by brian
clean slate
2072
    Check that destination tables does not exist. Note that its name
2073
    was already checked when it was added to the table list.
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2074
2075
    For temporary tables we don't aim to grab locks.
1 by brian
clean slate
2076
  */
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
2077
  if (destination_identifier.isTmp())
1 by brian
clean slate
2078
  {
1864.3.12 by Brian Aker
REmove an older use of find_temporary_table
2079
    if (session->find_temporary_table(destination_identifier))
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2080
    {
2081
      table_exists= true;
2082
    }
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2083
    else
2084
    {
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
2085
      bool was_created= create_table_wrapper(*session,
2086
                                             create_table_proto,
2087
                                             destination_identifier,
2088
                                             source_identifier,
2089
                                             is_engine_set);
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2090
      if (not was_created) // This is pretty paranoid, but we assume something might not clean up after itself
2091
      {
1608.2.1 by Brian Aker
Modified to table identifier to fix temporary table creation loss of file.
2092
        (void) session->rm_temporary_table(destination_identifier, true);
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2093
      }
2094
      else if (not session->open_temporary_table(destination_identifier))
2095
      {
2096
        // We created, but we can't open... also, a hack.
1608.2.1 by Brian Aker
Modified to table identifier to fix temporary table creation loss of file.
2097
        (void) session->rm_temporary_table(destination_identifier, true);
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2098
      }
2099
      else
2100
      {
2101
        res= false;
2102
      }
2103
    }
1 by brian
clean slate
2104
  }
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2105
  else // Standard table which will require locks.
1 by brian
clean slate
2106
  {
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2107
    Table *name_lock= 0;
2108
1669 by Brian Aker
This patch turns the table_cache into boost::unordered_multimap.
2109
    if (session->lock_table_name_if_not_cached(destination_identifier, &name_lock))
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2110
    {
2111
      if (name_lock)
2112
      {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
2113
        boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* unlink open tables for create table like*/
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2114
        session->unlink_open_table(name_lock);
2115
      }
2116
2117
      return res;
2118
    }
1309.2.17 by Brian Aker
Update to refactor out the inner code in create table.
2119
1309.1.27 by Brian Aker
Updating interface around doesTablExist()
2120
    if (not name_lock)
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2121
    {
2122
      table_exists= true;
2123
    }
2124
    else if (plugin::StorageEngine::doesTableExist(*session, destination_identifier))
2125
    {
2126
      table_exists= true;
2127
    }
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2128
    else // Otherwise we create the table
2129
    {
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
2130
      bool was_created;
2131
      {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
2132
        boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* We lock for CREATE TABLE LIKE to copy table definition */
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
2133
        was_created= create_table_wrapper(*session, create_table_proto, destination_identifier,
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
2134
                                          source_identifier, is_engine_set);
1718.1.1 by Brian Aker
Test scoped ptr in the tree.
2135
      }
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2136
2137
      // So we blew the creation of the table, and we scramble to clean up
2138
      // anything that might have been created (read... it is a hack)
2139
      if (not was_created)
2140
      {
1954.2.4 by Brian Aker
Remove quick_rm_table().
2141
        plugin::StorageEngine::dropTable(*session, destination_identifier);
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2142
      } 
2143
      else
2144
      {
2145
        res= false;
2146
      }
2147
    }
2148
2149
    if (name_lock)
2150
    {
1938.4.10 by Brian Aker
Convert LOCK_open to lock in mutex
2151
      boost_unique_lock_t lock(table::Cache::singleton().mutex()); /* unlink open tables for create table like*/
1547 by Brian Aker
This fixes a bug where we did a full open for a temporary table for CREATE
2152
      session->unlink_open_table(name_lock);
2153
    }
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2154
  }
2155
2156
  if (table_exists)
2157
  {
2158
    if (is_if_not_exists)
2159
    {
2160
      char warn_buff[DRIZZLE_ERRMSG_SIZE];
2161
      snprintf(warn_buff, sizeof(warn_buff),
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
2162
               ER(ER_TABLE_EXISTS_ERROR), destination_identifier.getTableName().c_str());
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2163
      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
2164
                   ER_TABLE_EXISTS_ERROR, warn_buff);
2165
      return false;
2166
    }
2167
2168
    my_error(ER_TABLE_EXISTS_ERROR, destination_identifier);
2169
2170
    return true;
1309.2.18 by Brian Aker
Remove a lot of the goto logic from createTable (this will allow me to
2171
  }
2172
2079.3.1 by Brian Aker
Rework the CREATE TABLE LIKE call.
2173
  return res;
1 by brian
clean slate
2174
}
2175
2176
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
2177
bool analyze_table(Session* session, TableList* tables, HA_CHECK_OPT* check_opt)
1 by brian
clean slate
2178
{
2179
  thr_lock_type lock_type = TL_READ_NO_INSERT;
2180
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
2181
  return(admin_table(session, tables, check_opt,
1237.6.2 by Brian Aker
Minor cleanup for dead code.
2182
				"analyze", lock_type, true,
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2183
				&Cursor::ha_analyze));
1 by brian
clean slate
2184
}
2185
2186
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
2187
bool check_table(Session* session, TableList* tables,HA_CHECK_OPT* check_opt)
1 by brian
clean slate
2188
{
2189
  thr_lock_type lock_type = TL_READ_NO_INSERT;
2190
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
2191
  return(admin_table(session, tables, check_opt,
1 by brian
clean slate
2192
				"check", lock_type,
1237.6.2 by Brian Aker
Minor cleanup for dead code.
2193
				false,
1183.1.2 by Brian Aker
Rename of handler to Cursor. You would not believe how long I have wanted
2194
				&Cursor::ha_check));
1 by brian
clean slate
2195
}
2196
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
2197
} /* namespace drizzled */