NdbDictionaryImpl.cpp 134 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "NdbDictionaryImpl.hpp"
#include "API.hpp"
#include <NdbOut.hpp>
#include "NdbApiSignal.hpp"
#include "TransporterFacade.hpp"
#include <signaldata/GetTabInfo.hpp>
#include <signaldata/DictTabInfo.hpp>
#include <signaldata/CreateTable.hpp>
#include <signaldata/CreateIndx.hpp>
#include <signaldata/CreateEvnt.hpp>
#include <signaldata/SumaImpl.hpp>
#include <signaldata/DropTable.hpp>
#include <signaldata/AlterTable.hpp>
#include <signaldata/DropIndx.hpp>
#include <signaldata/ListTables.hpp>
32 33
#include <signaldata/DropFilegroup.hpp>
#include <signaldata/CreateFilegroup.hpp>
34
#include <signaldata/WaitGCP.hpp>
35 36 37 38 39
#include <SimpleProperties.hpp>
#include <Bitmask.hpp>
#include <AttributeList.hpp>
#include <NdbEventOperation.hpp>
#include "NdbEventOperationImpl.hpp"
40 41
#include <NdbBlob.hpp>
#include "NdbBlobImpl.hpp"
joreland@mysql.com's avatar
joreland@mysql.com committed
42
#include <AttributeHeader.hpp>
pekka@mysql.com's avatar
pekka@mysql.com committed
43
#include <my_sys.h>
44
#include <NdbEnv.h>
45
#include <NdbMem.h>
46
#include <ndb_version.h>
47 48 49 50

#define DEBUG_PRINT 0
#define INCOMPATIBLE_VERSION -2

51 52
#define DICT_WAITFOR_TIMEOUT (7*24*60*60*1000)

53 54 55 56 57 58
#define ERR_RETURN(a,b) \
{\
   DBUG_PRINT("exit", ("error %d", (a).code));\
   DBUG_RETURN(b);\
}

59
extern Uint64 g_latest_trans_gci;
60
int ndb_dictionary_is_mysqld = 0;
61

62
bool
63
is_ndb_blob_table(const char* name, Uint32* ptab_id, Uint32* pcol_no)
64
{
65
  return DictTabInfo::isBlobTableName(name, ptab_id, pcol_no);
66 67 68 69 70 71 72 73
}

bool
is_ndb_blob_table(const NdbTableImpl* t)
{
  return is_ndb_blob_table(t->m_internalName.c_str());
}

74 75 76 77 78 79
//#define EVENT_DEBUG

/**
 * Column
 */
NdbColumnImpl::NdbColumnImpl()
80
  : NdbDictionary::Column(* this), m_attrId(-1), m_facade(this)
81
{
82
  DBUG_ENTER("NdbColumnImpl::NdbColumnImpl");
83
  DBUG_PRINT("info", ("this: %p", this));
84
  init();
85
  DBUG_VOID_RETURN;
86 87 88
}

NdbColumnImpl::NdbColumnImpl(NdbDictionary::Column & f)
89
  : NdbDictionary::Column(* this), m_attrId(-1), m_facade(&f)
90
{
91
  DBUG_ENTER("NdbColumnImpl::NdbColumnImpl");
92
  DBUG_PRINT("info", ("this: %p", this));
93
  init();
94
  DBUG_VOID_RETURN;
95 96
}

mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
97 98
NdbColumnImpl&
NdbColumnImpl::operator=(const NdbColumnImpl& col)
99
{
100
  DBUG_ENTER("NdbColumnImpl::operator=");
101
  DBUG_PRINT("info", ("this: %p  &col: %p", this, &col));
102 103 104 105
  m_attrId = col.m_attrId;
  m_name = col.m_name;
  m_type = col.m_type;
  m_precision = col.m_precision;
pekka@mysql.com's avatar
pekka@mysql.com committed
106
  m_cs = col.m_cs;
107 108 109 110 111 112 113 114 115 116
  m_scale = col.m_scale;
  m_length = col.m_length;
  m_pk = col.m_pk;
  m_distributionKey = col.m_distributionKey;
  m_nullable = col.m_nullable;
  m_autoIncrement = col.m_autoIncrement;
  m_autoIncrementInitialValue = col.m_autoIncrementInitialValue;
  m_defaultValue = col.m_defaultValue;
  m_attrSize = col.m_attrSize; 
  m_arraySize = col.m_arraySize;
117 118
  m_arrayType = col.m_arrayType;
  m_storageType = col.m_storageType;
119
  m_keyInfoPos = col.m_keyInfoPos;
120 121 122
  if (col.m_blobTable == NULL)
    m_blobTable = NULL;
  else {
123 124
    if (m_blobTable == NULL)
      m_blobTable = new NdbTableImpl();
125 126
    m_blobTable->assign(*col.m_blobTable);
  }
127
  m_column_no = col.m_column_no;
128 129
  // Do not copy m_facade !!

130
  DBUG_RETURN(*this);
131 132 133
}

void
134
NdbColumnImpl::init(Type t)
135
{
pekka@mysql.com's avatar
pekka@mysql.com committed
136 137
  // do not use default_charset_info as it may not be initialized yet
  // use binary collation until NDB tests can handle charsets
138
  CHARSET_INFO* default_cs = &my_charset_bin;
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  m_type = t;
  switch (m_type) {
  case Tinyint:
  case Tinyunsigned:
  case Smallint:
  case Smallunsigned:
  case Mediumint:
  case Mediumunsigned:
  case Int:
  case Unsigned:
  case Bigint:
  case Bigunsigned:
  case Float:
  case Double:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
156
    m_cs = NULL;
157
    m_arrayType = NDB_ARRAYTYPE_FIXED;
158
    break;
159 160
  case Olddecimal:
  case Olddecimalunsigned:
161 162
  case Decimal:
  case Decimalunsigned:
163 164 165
    m_precision = 10;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
166
    m_cs = NULL;
167
    m_arrayType = NDB_ARRAYTYPE_FIXED;
168 169
    break;
  case Char:
170 171 172 173 174 175
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = default_cs;
    m_arrayType = NDB_ARRAYTYPE_FIXED;
    break;
176 177 178 179
  case Varchar:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
180
    m_cs = default_cs;
181
    m_arrayType = NDB_ARRAYTYPE_SHORT_VAR;
182 183
    break;
  case Binary:
184 185 186 187 188 189
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
    m_arrayType = NDB_ARRAYTYPE_FIXED;
    break;
190
  case Varbinary:
191 192 193 194 195 196
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
    m_arrayType = NDB_ARRAYTYPE_SHORT_VAR;
    break;
197
  case Datetime:
198
  case Date:
199 200 201
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
202
    m_cs = NULL;
203
    m_arrayType = NDB_ARRAYTYPE_FIXED;
204 205 206 207 208
    break;
  case Blob:
    m_precision = 256;
    m_scale = 8000;
    m_length = 4;
pekka@mysql.com's avatar
pekka@mysql.com committed
209
    m_cs = NULL;
210
    m_arrayType = NDB_ARRAYTYPE_FIXED;
211 212 213 214 215
    break;
  case Text:
    m_precision = 256;
    m_scale = 8000;
    m_length = 4;
pekka@mysql.com's avatar
pekka@mysql.com committed
216
    m_cs = default_cs;
217
    m_arrayType = NDB_ARRAYTYPE_FIXED;
218
    break;
219
  case Time:
220 221
  case Year:
  case Timestamp:
222 223 224 225
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
226
    m_arrayType = NDB_ARRAYTYPE_FIXED;
227
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
228 229 230 231 232
  case Bit:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
233
    m_arrayType = NDB_ARRAYTYPE_FIXED;
pekka@mysql.com's avatar
pekka@mysql.com committed
234 235 236 237 238 239
    break;
  case Longvarchar:
    m_precision = 0;
    m_scale = 0;
    m_length = 1; // legal
    m_cs = default_cs;
240
    m_arrayType = NDB_ARRAYTYPE_MEDIUM_VAR;
pekka@mysql.com's avatar
pekka@mysql.com committed
241 242 243 244 245 246
    break;
  case Longvarbinary:
    m_precision = 0;
    m_scale = 0;
    m_length = 1; // legal
    m_cs = NULL;
247
    m_arrayType = NDB_ARRAYTYPE_MEDIUM_VAR;
pekka@mysql.com's avatar
pekka@mysql.com committed
248
    break;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
249
  default:
250
  case Undefined:
251
    assert(false);
252
    break;
253
  }
254 255 256 257
  m_pk = false;
  m_nullable = false;
  m_distributionKey = false;
  m_keyInfoPos = 0;
258 259 260
  // next 2 are set at run time
  m_attrSize = 0;
  m_arraySize = 0;
261 262
  m_autoIncrement = false;
  m_autoIncrementInitialValue = 1;
mskold@mysql.com's avatar
mskold@mysql.com committed
263
  m_blobTable = NULL;
264 265 266 267 268
  m_storageType = NDB_STORAGETYPE_MEMORY;
#ifdef VM_TRACE
  if(NdbEnv_GetEnv("NDB_DEFAULT_DISK", (char *)0, 0))
    m_storageType = NDB_STORAGETYPE_DISK;
#endif
269 270 271 272
}

NdbColumnImpl::~NdbColumnImpl()
{
273
  DBUG_ENTER("NdbColumnImpl::~NdbColumnImpl");
274
  DBUG_PRINT("info", ("this: %p", this));
275 276 277
  if (m_blobTable != NULL)
    delete m_blobTable;
  m_blobTable = NULL;
278
  DBUG_VOID_RETURN;
279 280 281 282 283
}

bool
NdbColumnImpl::equal(const NdbColumnImpl& col) const 
{
284
  DBUG_ENTER("NdbColumnImpl::equal");
285
  DBUG_PRINT("info", ("this: %p  &col: %p", this, &col));
286
  if(strcmp(m_name.c_str(), col.m_name.c_str()) != 0){
287
    DBUG_RETURN(false);
288 289
  }
  if(m_type != col.m_type){
290
    DBUG_RETURN(false);
291 292
  }
  if(m_pk != col.m_pk){
293
    DBUG_RETURN(false);
294 295
  }
  if(m_nullable != col.m_nullable){
296
    DBUG_RETURN(false);
297
  }
298 299
  if (m_pk) {
    if ((bool)m_distributionKey != (bool)col.m_distributionKey) {
300
      DBUG_RETURN(false);
301 302
    }
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
303 304 305 306
  if (m_precision != col.m_precision ||
      m_scale != col.m_scale ||
      m_length != col.m_length ||
      m_cs != col.m_cs) {
307
    DBUG_RETURN(false);
308 309
  }
  if (m_autoIncrement != col.m_autoIncrement){
310
    DBUG_RETURN(false);
311 312
  }
  if(strcmp(m_defaultValue.c_str(), col.m_defaultValue.c_str()) != 0){
313
    DBUG_RETURN(false);
314
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
315

316 317 318 319
  if (m_arrayType != col.m_arrayType || m_storageType != col.m_storageType){
    DBUG_RETURN(false);
  }

320
  DBUG_RETURN(true);
321 322
}

joreland@mysql.com's avatar
joreland@mysql.com committed
323
NdbDictionary::Column *
324
NdbColumnImpl::create_pseudo(const char * name){
joreland@mysql.com's avatar
joreland@mysql.com committed
325 326 327 328 329
  NdbDictionary::Column * col = new NdbDictionary::Column();
  col->setName(name);
  if(!strcmp(name, "NDB$FRAGMENT")){
    col->setType(NdbDictionary::Column::Unsigned);
    col->m_impl.m_attrId = AttributeHeader::FRAGMENT;
330 331
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 1;
332 333 334 335 336
  } else if(!strcmp(name, "NDB$FRAGMENT_MEMORY")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::FRAGMENT_MEMORY;
    col->m_impl.m_attrSize = 8;
    col->m_impl.m_arraySize = 1;
joreland@mysql.com's avatar
joreland@mysql.com committed
337 338 339
  } else if(!strcmp(name, "NDB$ROW_COUNT")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::ROW_COUNT;
340
    col->m_impl.m_attrSize = 8;
341
    col->m_impl.m_arraySize = 1;
joreland@mysql.com's avatar
joreland@mysql.com committed
342 343 344
  } else if(!strcmp(name, "NDB$COMMIT_COUNT")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::COMMIT_COUNT;
345
    col->m_impl.m_attrSize = 8;
346
    col->m_impl.m_arraySize = 1;
347 348 349 350 351
  } else if(!strcmp(name, "NDB$ROW_SIZE")){
    col->setType(NdbDictionary::Column::Unsigned);
    col->m_impl.m_attrId = AttributeHeader::ROW_SIZE;
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 1;
352 353 354 355 356
  } else if(!strcmp(name, "NDB$RANGE_NO")){
    col->setType(NdbDictionary::Column::Unsigned);
    col->m_impl.m_attrId = AttributeHeader::RANGE_NO;
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 1;
357 358 359 360 361
  } else if(!strcmp(name, "NDB$DISK_REF")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::DISK_REF;
    col->m_impl.m_attrSize = 8;
    col->m_impl.m_arraySize = 1;
362 363 364 365 366
  } else if(!strcmp(name, "NDB$RECORDS_IN_RANGE")){
    col->setType(NdbDictionary::Column::Unsigned);
    col->m_impl.m_attrId = AttributeHeader::RECORDS_IN_RANGE;
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 4;
367 368 369 370 371 372 373 374 375 376 377
  } else if(!strcmp(name, "NDB$ROWID")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::ROWID;
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 2;
  } else if(!strcmp(name, "NDB$ROW_GCI")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::ROW_GCI;
    col->m_impl.m_attrSize = 8;
    col->m_impl.m_arraySize = 1;
    col->m_impl.m_nullable = true;
joreland@mysql.com's avatar
joreland@mysql.com committed
378 379 380
  } else {
    abort();
  }
381
  col->m_impl.m_storageType = NDB_STORAGETYPE_MEMORY;
382
  return col;
383 384 385 386 387 388 389
}

/**
 * NdbTableImpl
 */

NdbTableImpl::NdbTableImpl()
390 391
  : NdbDictionary::Table(* this), 
    NdbDictObjectImpl(NdbDictionary::Object::UserTable), m_facade(this)
392
{
393
  DBUG_ENTER("NdbTableImpl::NdbTableImpl");
394
  DBUG_PRINT("info", ("this: %p", this));
395
  init();
396
  DBUG_VOID_RETURN;
397 398 399
}

NdbTableImpl::NdbTableImpl(NdbDictionary::Table & f)
400 401
  : NdbDictionary::Table(* this), 
    NdbDictObjectImpl(NdbDictionary::Object::UserTable), m_facade(&f)
402
{
403
  DBUG_ENTER("NdbTableImpl::NdbTableImpl");
404
  DBUG_PRINT("info", ("this: %p", this));
405
  init();
406
  DBUG_VOID_RETURN;
407 408 409 410
}

NdbTableImpl::~NdbTableImpl()
{
411
  DBUG_ENTER("NdbTableImpl::~NdbTableImpl");
412
  DBUG_PRINT("info", ("this: %p", this));
413 414 415 416 417
  if (m_index != 0) {
    delete m_index;
    m_index = 0;
  }
  for (unsigned i = 0; i < m_columns.size(); i++)
418 419
    delete m_columns[i];
  DBUG_VOID_RETURN;
420 421 422 423
}

void
NdbTableImpl::init(){
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
424
  m_changeMask= 0;
425
  m_id= RNIL;
426 427 428
  m_version = ~0;
  m_status = NdbDictionary::Object::Invalid;
  m_type = NdbDictionary::Object::TypeUndefined;
429
  m_primaryTableId= RNIL;
430 431 432 433
  m_internalName.clear();
  m_externalName.clear();
  m_newExternalName.clear();
  m_mysqlName.clear();
434
  m_frm.clear();
435
  m_newFrm.clear();
436 437 438 439 440 441 442 443 444
  m_ts_name.clear();
  m_new_ts_name.clear();
  m_ts.clear();
  m_new_ts.clear();
  m_fd.clear();
  m_new_fd.clear();
  m_range.clear();
  m_new_range.clear();
  m_fragmentType= NdbDictionary::Object::FragAllSmall;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
445 446
  m_hashValueMask= 0;
  m_hashpointerValue= 0;
447
  m_linear_flag= true;
448 449 450
  m_primaryTable.clear();
  m_max_rows = 0;
  m_default_no_part_flag = 1;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
451
  m_logging= true;
452 453
  m_row_gci = true;
  m_row_checksum = true;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
454 455 456 457 458 459
  m_kvalue= 6;
  m_minLoadFactor= 78;
  m_maxLoadFactor= 80;
  m_keyLenInWords= 0;
  m_fragmentCount= 0;
  m_index= NULL;
460
  m_indexType= NdbDictionary::Object::TypeUndefined;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
461 462 463 464
  m_noOfKeys= 0;
  m_noOfDistributionKeys= 0;
  m_noOfBlobs= 0;
  m_replicaCount= 0;
465
  m_tablespace_name.clear();
466
  m_tablespace_id = ~0;
467
  m_tablespace_version = ~0;
468 469 470 471 472
}

bool
NdbTableImpl::equal(const NdbTableImpl& obj) const 
{
473
  DBUG_ENTER("NdbTableImpl::equal");
474 475 476
  if ((m_internalName.c_str() == NULL) || 
      (strcmp(m_internalName.c_str(), "") == 0) ||
      (obj.m_internalName.c_str() == NULL) || 
477 478
      (strcmp(obj.m_internalName.c_str(), "") == 0))
  {
479
    // Shallow equal
480 481
    if(strcmp(getName(), obj.getName()) != 0)
    {
482 483
      DBUG_PRINT("info",("name %s != %s",getName(),obj.getName()));
      DBUG_RETURN(false);    
484
    }
485 486 487
  }
  else
  {
488
    // Deep equal
489
    if(strcmp(m_internalName.c_str(), obj.m_internalName.c_str()) != 0)
490 491 492 493 494
    {
      DBUG_PRINT("info",("m_internalName %s != %s",
			 m_internalName.c_str(),obj.m_internalName.c_str()));
      DBUG_RETURN(false);
    }
495
  }
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  if (m_frm.length() != obj.m_frm.length() ||
      (memcmp(m_frm.get_data(), obj.m_frm.get_data(), m_frm.length())))
  {
    DBUG_PRINT("info",("m_frm not equal"));
    DBUG_RETURN(false);
  }
  if (m_fd.length() != obj.m_fd.length() ||
      (memcmp(m_fd.get_data(), obj.m_fd.get_data(), m_fd.length())))
  {
    DBUG_PRINT("info",("m_fd not equal"));
    DBUG_RETURN(false);
  }
  if (m_ts.length() != obj.m_ts.length() ||
      (memcmp(m_ts.get_data(), obj.m_ts.get_data(), m_ts.length())))
  {
    DBUG_PRINT("info",("m_ts not equal"));
    DBUG_RETURN(false);
  }
  if (m_range.length() != obj.m_range.length() ||
      (memcmp(m_range.get_data(), obj.m_range.get_data(), m_range.length())))
  {
    DBUG_PRINT("info",("m_range not equal"));
    DBUG_RETURN(false);
  }
  if(m_fragmentType != obj.m_fragmentType)
  {
    DBUG_PRINT("info",("m_fragmentType %d != %d",m_fragmentType,
                        obj.m_fragmentType));
524
    DBUG_RETURN(false);
525
  }
526 527 528 529
  if(m_columns.size() != obj.m_columns.size())
  {
    DBUG_PRINT("info",("m_columns.size %d != %d",m_columns.size(),
                       obj.m_columns.size()));
530
    DBUG_RETURN(false);
531 532
  }

533 534 535 536
  for(unsigned i = 0; i<obj.m_columns.size(); i++)
  {
    if(!m_columns[i]->equal(* obj.m_columns[i]))
    {
537 538
      DBUG_PRINT("info",("m_columns [%d] != [%d]",i,i));
      DBUG_RETURN(false);
539 540 541
    }
  }
  
542 543 544 545 546 547 548
  if(m_linear_flag != obj.m_linear_flag)
  {
    DBUG_PRINT("info",("m_linear_flag %d != %d",m_linear_flag,
                        obj.m_linear_flag));
    DBUG_RETURN(false);
  }

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
  if(m_max_rows != obj.m_max_rows)
  {
    DBUG_PRINT("info",("m_max_rows %d != %d",(int32)m_max_rows,
                       (int32)obj.m_max_rows));
    DBUG_RETURN(false);
  }

  if(m_default_no_part_flag != obj.m_default_no_part_flag)
  {
    DBUG_PRINT("info",("m_default_no_part_flag %d != %d",m_default_no_part_flag,
                        obj.m_default_no_part_flag));
    DBUG_RETURN(false);
  }

  if(m_logging != obj.m_logging)
  {
565 566
    DBUG_PRINT("info",("m_logging %d != %d",m_logging,obj.m_logging));
    DBUG_RETURN(false);
567 568
  }

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  if(m_row_gci != obj.m_row_gci)
  {
    DBUG_PRINT("info",("m_row_gci %d != %d",m_row_gci,obj.m_row_gci));
    DBUG_RETURN(false);
  }

  if(m_row_checksum != obj.m_row_checksum)
  {
    DBUG_PRINT("info",("m_row_checksum %d != %d",m_row_checksum,
                        obj.m_row_checksum));
    DBUG_RETURN(false);
  }

  if(m_kvalue != obj.m_kvalue)
  {
584 585
    DBUG_PRINT("info",("m_kvalue %d != %d",m_kvalue,obj.m_kvalue));
    DBUG_RETURN(false);
586 587
  }

588 589 590 591
  if(m_minLoadFactor != obj.m_minLoadFactor)
  {
    DBUG_PRINT("info",("m_minLoadFactor %d != %d",m_minLoadFactor,
                        obj.m_minLoadFactor));
592
    DBUG_RETURN(false);
593 594
  }

595 596 597 598
  if(m_maxLoadFactor != obj.m_maxLoadFactor)
  {
    DBUG_PRINT("info",("m_maxLoadFactor %d != %d",m_maxLoadFactor,
                        obj.m_maxLoadFactor));
599
    DBUG_RETURN(false);
600
  }
601

602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  if(m_tablespace_id != obj.m_tablespace_id)
  {
    DBUG_PRINT("info",("m_tablespace_id %d != %d",m_tablespace_id,
                        obj.m_tablespace_id));
    DBUG_RETURN(false);
  }

  if(m_tablespace_version != obj.m_tablespace_version)
  {
    DBUG_PRINT("info",("m_tablespace_version %d != %d",m_tablespace_version,
                        obj.m_tablespace_version));
    DBUG_RETURN(false);
  }

  if(m_id != obj.m_id)
  {
    DBUG_PRINT("info",("m_id %d != %d",m_id,obj.m_id));
    DBUG_RETURN(false);
  }

  if(m_version != obj.m_version)
  {
    DBUG_PRINT("info",("m_version %d != %d",m_version,obj.m_version));
    DBUG_RETURN(false);
  }

  if(m_type != obj.m_type)
  {
    DBUG_PRINT("info",("m_type %d != %d",m_type,obj.m_type));
    DBUG_RETURN(false);
  }

  if (m_type == NdbDictionary::Object::UniqueHashIndex ||
      m_type == NdbDictionary::Object::OrderedIndex)
  {
    if(m_primaryTableId != obj.m_primaryTableId)
    {
      DBUG_PRINT("info",("m_primaryTableId %d != %d",m_primaryTableId,
                 obj.m_primaryTableId));
      DBUG_RETURN(false);
    }
    if (m_indexType != obj.m_indexType)
    {
      DBUG_PRINT("info",("m_indexType %d != %d",m_indexType,obj.m_indexType));
      DBUG_RETURN(false);
    }
    if(strcmp(m_primaryTable.c_str(), obj.m_primaryTable.c_str()) != 0)
    {
      DBUG_PRINT("info",("m_primaryTable %s != %s",
			 m_primaryTable.c_str(),obj.m_primaryTable.c_str()));
      DBUG_RETURN(false);
    }
  }
655
  DBUG_RETURN(true);
656 657 658 659 660
}

void
NdbTableImpl::assign(const NdbTableImpl& org)
{
661
  DBUG_ENTER("NdbColumnImpl::assign");
662
  DBUG_PRINT("info", ("this: %p  &org: %p", this, &org));
663 664
  /* m_changeMask intentionally not copied */
  m_primaryTableId = org.m_primaryTableId;
665
  m_internalName.assign(org.m_internalName);
666
  updateMysqlName();
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
667 668 669 670 671 672
  // If the name has been explicitly set, use that name
  // otherwise use the fetched name
  if (!org.m_newExternalName.empty())
    m_externalName.assign(org.m_newExternalName);
  else
    m_externalName.assign(org.m_externalName);
673
  m_frm.assign(org.m_frm.get_data(), org.m_frm.length());
674 675 676 677 678 679 680 681 682
  m_ts_name.assign(org.m_ts_name.get_data(), org.m_ts_name.length());
  m_new_ts_name.assign(org.m_new_ts_name.get_data(),
                       org.m_new_ts_name.length());
  m_ts.assign(org.m_ts.get_data(), org.m_ts.length());
  m_new_ts.assign(org.m_new_ts.get_data(), org.m_new_ts.length());
  m_fd.assign(org.m_fd.get_data(), org.m_fd.length());
  m_new_fd.assign(org.m_new_fd.get_data(), org.m_new_fd.length());
  m_range.assign(org.m_range.get_data(), org.m_range.length());
  m_new_range.assign(org.m_new_range.get_data(), org.m_new_range.length());
683

684 685 686 687 688
  m_fragmentType = org.m_fragmentType;
  /*
    m_columnHashMask, m_columnHash, m_hashValueMask, m_hashpointerValue
    is state calculated by computeAggregates and buildColumnHash
  */
689 690 691 692 693 694 695 696
  unsigned i;
  for(i = 0; i < m_columns.size(); i++)
  {
    delete m_columns[i];
  }
  m_columns.clear();
  for(i = 0; i < org.m_columns.size(); i++)
  {
697 698
    NdbColumnImpl * col = new NdbColumnImpl();
    const NdbColumnImpl * iorg = org.m_columns[i];
joreland@mysql.com's avatar
joreland@mysql.com committed
699
    (* col) = (* iorg);
700 701 702
    m_columns.push_back(col);
  }

703 704
  m_fragments = org.m_fragments;

705
  m_linear_flag = org.m_linear_flag;
706 707
  m_max_rows = org.m_max_rows;
  m_default_no_part_flag = org.m_default_no_part_flag;
708
  m_logging = org.m_logging;
709 710
  m_row_gci = org.m_row_gci;
  m_row_checksum = org.m_row_checksum;
711 712 713
  m_kvalue = org.m_kvalue;
  m_minLoadFactor = org.m_minLoadFactor;
  m_maxLoadFactor = org.m_maxLoadFactor;
714 715
  m_keyLenInWords = org.m_keyLenInWords;
  m_fragmentCount = org.m_fragmentCount;
716 717 718 719
  
  if (m_index != 0)
    delete m_index;
  m_index = org.m_index;
720 721 722 723
 
  m_primaryTable = org.m_primaryTable;
  m_indexType = org.m_indexType;

724
  m_noOfKeys = org.m_noOfKeys;
725
  m_noOfDistributionKeys = org.m_noOfDistributionKeys;
pekka@mysql.com's avatar
pekka@mysql.com committed
726
  m_noOfBlobs = org.m_noOfBlobs;
727
  m_replicaCount = org.m_replicaCount;
728

729
  m_id = org.m_id;
730 731
  m_version = org.m_version;
  m_status = org.m_status;
732 733 734 735

  m_tablespace_name = org.m_tablespace_name;
  m_tablespace_id= org.m_tablespace_id;
  m_tablespace_version = org.m_tablespace_version;
736
  DBUG_VOID_RETURN;
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
}

void NdbTableImpl::setName(const char * name)
{
  m_newExternalName.assign(name);
}

const char * 
NdbTableImpl::getName() const
{
  if (m_newExternalName.empty())
    return m_externalName.c_str();
  else
    return m_newExternalName.c_str();
}

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
void
NdbTableImpl::computeAggregates()
{
  m_noOfKeys = 0;
  m_keyLenInWords = 0;
  m_noOfDistributionKeys = 0;
  m_noOfBlobs = 0;
  Uint32 i, n;
  for (i = 0; i < m_columns.size(); i++) {
    NdbColumnImpl* col = m_columns[i];
    if (col->m_pk) {
      m_noOfKeys++;
      m_keyLenInWords += (col->m_attrSize * col->m_arraySize + 3) / 4;
    }
    if (col->m_distributionKey == 2)    // set by user
      m_noOfDistributionKeys++;
    
    if (col->getBlobType())
      m_noOfBlobs++;
    col->m_keyInfoPos = ~0;
  }
  if (m_noOfDistributionKeys == m_noOfKeys) {
    // all is none!
    m_noOfDistributionKeys = 0;
  }

  if (m_noOfDistributionKeys == 0) 
  {
    // none is all!
    for (i = 0, n = m_noOfKeys; n != 0; i++) {
      NdbColumnImpl* col = m_columns[i];
      if (col->m_pk) {
        col->m_distributionKey = true;  // set by us
        n--;
      }
    }
  }
  else 
  {
    for (i = 0, n = m_noOfKeys; n != 0; i++) {
      NdbColumnImpl* col = m_columns[i];
      if (col->m_pk)
      {
	if(col->m_distributionKey == 1)
	  col->m_distributionKey = 0;  
        n--;
      }
    }
  }
  
  Uint32 keyInfoPos = 0;
  for (i = 0, n = m_noOfKeys; n != 0; i++) {
    NdbColumnImpl* col = m_columns[i];
    if (col->m_pk) {
      col->m_keyInfoPos = keyInfoPos++;
      n--;
    }
  }
}

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
const void*
NdbTableImpl::getTablespaceNames() const
{
  if (m_new_ts_name.empty())
    return m_ts_name.get_data();
  else
    return m_new_ts_name.get_data();
}

Uint32
NdbTableImpl::getTablespaceNamesLen() const
{
  if (m_new_ts_name.empty())
    return m_ts_name.length();
  else
    return m_new_ts_name.length();
}

void NdbTableImpl::setTablespaceNames(const void *data, Uint32 len)
{
  m_new_ts_name.assign(data, len);
}

void NdbTableImpl::setFragmentCount(Uint32 count)
{
  m_fragmentCount= count;
}

Uint32 NdbTableImpl::getFragmentCount() const
{
  return m_fragmentCount;
}

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
void NdbTableImpl::setFrm(const void* data, Uint32 len)
{
  m_newFrm.assign(data, len);
}

const void * 
NdbTableImpl::getFrmData() const
{
  if (m_newFrm.empty())
    return m_frm.get_data();
  else
    return m_newFrm.get_data();
}

Uint32
NdbTableImpl::getFrmLength() const 
{
  if (m_newFrm.empty())
    return m_frm.length();
  else
    return m_newFrm.length();
}

869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
void NdbTableImpl::setFragmentData(const void* data, Uint32 len)
{
  m_new_fd.assign(data, len);
}

const void * 
NdbTableImpl::getFragmentData() const
{
  if (m_new_fd.empty())
    return m_fd.get_data();
  else
    return m_new_fd.get_data();
}

Uint32
NdbTableImpl::getFragmentDataLen() const 
{
  if (m_new_fd.empty())
    return m_fd.length();
  else
    return m_new_fd.length();
}

void NdbTableImpl::setTablespaceData(const void* data, Uint32 len)
{
  m_new_ts.assign(data, len);
}

const void * 
NdbTableImpl::getTablespaceData() const
{
  if (m_new_ts.empty())
    return m_ts.get_data();
  else
    return m_new_ts.get_data();
}

Uint32
NdbTableImpl::getTablespaceDataLen() const 
{
  if (m_new_ts.empty())
    return m_ts.length();
  else
    return m_new_ts.length();
}

void NdbTableImpl::setRangeListData(const void* data, Uint32 len)
{
  m_new_range.assign(data, len);
}

const void * 
NdbTableImpl::getRangeListData() const
{
  if (m_new_range.empty())
    return m_range.get_data();
  else
    return m_new_range.get_data();
}

Uint32
NdbTableImpl::getRangeListDataLen() const 
{
  if (m_new_range.empty())
    return m_range.length();
  else
    return m_new_range.length();
}

938 939 940 941 942 943 944 945 946 947 948
void
NdbTableImpl::updateMysqlName()
{
  Vector<BaseString> v;
  if (m_internalName.split(v,"/") == 3)
  {
    m_mysqlName.assfmt("%s/%s",v[0].c_str(),v[2].c_str());
    return;
  }
  m_mysqlName.assign("");
}
949 950 951 952

void
NdbTableImpl::buildColumnHash(){
  const Uint32 size = m_columns.size();
953
  int i;
954
  for(i = 31; i >= 0; i--){
955 956 957 958 959 960 961 962
    if(((1 << i) & size) != 0){
      m_columnHashMask = (1 << (i + 1)) - 1;
      break;
    }
  }

  Vector<Uint32> hashValues;
  Vector<Vector<Uint32> > chains; chains.fill(size, hashValues);
963
  for(i = 0; i< (int) size; i++){
964 965 966 967 968 969 970 971 972 973 974 975 976
    Uint32 hv = Hash(m_columns[i]->getName()) & 0xFFFE;
    Uint32 bucket = hv & m_columnHashMask;
    bucket = (bucket < size ? bucket : bucket - size);
    assert(bucket < size);
    hashValues.push_back(hv);
    chains[bucket].push_back(i);
  }

  m_columnHash.clear();
  Uint32 tmp = 1; 
  m_columnHash.fill((unsigned)size-1, tmp);   // Default no chaining

  Uint32 pos = 0; // In overflow vector
977
  for(i = 0; i< (int) size; i++){
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    Uint32 sz = chains[i].size();
    if(sz == 1){
      Uint32 col = chains[i][0];
      Uint32 hv = hashValues[col];
      Uint32 bucket = hv & m_columnHashMask;
      bucket = (bucket < size ? bucket : bucket - size);
      m_columnHash[bucket] = (col << 16) | hv | 1;
    } else if(sz > 1){
      Uint32 col = chains[i][0];
      Uint32 hv = hashValues[col];
      Uint32 bucket = hv & m_columnHashMask;
      bucket = (bucket < size ? bucket : bucket - size);
      m_columnHash[bucket] = (sz << 16) | (((size - bucket) + pos) << 1);
      for(size_t j = 0; j<sz; j++, pos++){
	Uint32 col = chains[i][j];	
	Uint32 hv = hashValues[col];
	m_columnHash.push_back((col << 16) | hv);
      }
    }
  }

  m_columnHash.push_back(0); // Overflow when looping in end of array

#if 0
  for(size_t i = 0; i<m_columnHash.size(); i++){
    Uint32 tmp = m_columnHash[i];
    int col = -1;
    if(i < size && (tmp & 1) == 1){
      col = (tmp >> 16);
    } else if(i >= size){
      col = (tmp >> 16);
    }
    ndbout_c("m_columnHash[%d] %s = %x", 
	     i, col > 0 ? m_columns[col]->getName() : "" , m_columnHash[i]);
  }
#endif
}
1015 1016 1017 1018

Uint32
NdbTableImpl::get_nodes(Uint32 hashValue, const Uint16 ** nodes) const
{
1019 1020 1021 1022
  Uint32 fragmentId;
  if(m_replicaCount == 0)
    return 0;
  switch (m_fragmentType)
1023
  {
1024 1025 1026 1027 1028
    case NdbDictionary::Object::FragAllSmall:
    case NdbDictionary::Object::FragAllMedium:
    case NdbDictionary::Object::FragAllLarge:
    case NdbDictionary::Object::FragSingle:
    case NdbDictionary::Object::DistrKeyLin:
1029
    {
1030
      fragmentId = hashValue & m_hashValueMask;
1031 1032 1033
      if(fragmentId < m_hashpointerValue) 
        fragmentId = hashValue & ((m_hashValueMask << 1) + 1);
      break;
1034
    }
1035
    case NdbDictionary::Object::DistrKeyHash:
1036
    {
1037 1038
      fragmentId = hashValue % m_fragmentCount;
      break;
1039
    }
1040 1041 1042 1043 1044 1045 1046 1047
    default:
      return 0;
  }
  Uint32 pos = fragmentId * m_replicaCount;
  if (pos + m_replicaCount <= m_fragments.size())
  {
    *nodes = m_fragments.getBase()+pos;
    return m_replicaCount;
1048 1049 1050
  }
  return 0;
}
1051 1052 1053 1054 1055 1056
  
/**
 * NdbIndexImpl
 */

NdbIndexImpl::NdbIndexImpl() : 
1057
  NdbDictionary::Index(* this),
1058
  NdbDictObjectImpl(NdbDictionary::Object::OrderedIndex), m_facade(this)
1059
{
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1060
  init();
1061 1062 1063 1064
}

NdbIndexImpl::NdbIndexImpl(NdbDictionary::Index & f) : 
  NdbDictionary::Index(* this), 
1065
  NdbDictObjectImpl(NdbDictionary::Object::OrderedIndex), m_facade(&f)
1066
{
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1067 1068 1069 1070 1071
  init();
}

void NdbIndexImpl::init()
{
1072 1073
  m_id= RNIL;
  m_type= NdbDictionary::Object::TypeUndefined;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1074 1075
  m_logging= true;
  m_table= NULL;
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
}

NdbIndexImpl::~NdbIndexImpl(){
  for (unsigned i = 0; i < m_columns.size(); i++)
    delete m_columns[i];  
}

void NdbIndexImpl::setName(const char * name)
{
  m_externalName.assign(name);
}

const char * 
NdbIndexImpl::getName() const
{
  return m_externalName.c_str();
}
 
void 
NdbIndexImpl::setTable(const char * table)
{
  m_tableName.assign(table);
}
 
const char * 
NdbIndexImpl::getTable() const
{
  return m_tableName.c_str();
}

1106 1107 1108 1109 1110 1111
const NdbTableImpl *
NdbIndexImpl::getIndexTable() const
{
  return m_table;
}

1112 1113 1114 1115 1116 1117
/**
 * NdbEventImpl
 */

NdbEventImpl::NdbEventImpl() : 
  NdbDictionary::Event(* this),
1118
  NdbDictObjectImpl(NdbDictionary::Object::TypeUndefined), m_facade(this)
1119
{
1120
  DBUG_ENTER("NdbEventImpl::NdbEventImpl");
1121
  DBUG_PRINT("info", ("this: %p", this));
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1122
  init();
1123
  DBUG_VOID_RETURN;
1124 1125 1126 1127
}

NdbEventImpl::NdbEventImpl(NdbDictionary::Event & f) : 
  NdbDictionary::Event(* this),
1128
  NdbDictObjectImpl(NdbDictionary::Object::TypeUndefined), m_facade(&f)
1129
{
1130
  DBUG_ENTER("NdbEventImpl::NdbEventImpl");
1131
  DBUG_PRINT("info", ("this: %p", this));
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1132
  init();
1133
  DBUG_VOID_RETURN;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1134 1135 1136 1137 1138 1139 1140 1141
}

void NdbEventImpl::init()
{
  m_eventId= RNIL;
  m_eventKey= RNIL;
  mi_type= 0;
  m_dur= NdbDictionary::Event::ED_UNDEFINED;
1142
  m_mergeEvents = false;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1143
  m_tableImpl= NULL;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1144
  m_rep= NdbDictionary::Event::ER_UPDATED;
1145 1146 1147 1148
}

NdbEventImpl::~NdbEventImpl()
{
1149
  DBUG_ENTER("NdbEventImpl::~NdbEventImpl");
1150
  DBUG_PRINT("info", ("this: %p", this));
1151 1152
  for (unsigned i = 0; i < m_columns.size(); i++)
    delete  m_columns[i];
1153 1154
  if (m_tableImpl)
    delete m_tableImpl;
1155
  DBUG_VOID_RETURN;
1156 1157 1158 1159
}

void NdbEventImpl::setName(const char * name)
{
1160
  m_name.assign(name);
1161 1162
}

1163 1164
const char *NdbEventImpl::getName() const
{
1165
  return m_name.c_str();
1166 1167
}

1168 1169 1170
void 
NdbEventImpl::setTable(const NdbDictionary::Table& table)
{
1171
  setTable(&NdbTableImpl::getImpl(table));
1172 1173 1174
  m_tableName.assign(m_tableImpl->getName());
}

1175 1176 1177
void 
NdbEventImpl::setTable(NdbTableImpl *tableImpl)
{
1178
  DBUG_ENTER("NdbEventImpl::setTable");
1179
  DBUG_PRINT("info", ("this: %p  tableImpl: %p", this, tableImpl));
1180 1181 1182 1183 1184
  DBUG_ASSERT(tableImpl->m_status != NdbDictionary::Object::Invalid);
  if (!m_tableImpl) 
    m_tableImpl = new NdbTableImpl();
  // Copy table, since event might be accessed from different threads
  m_tableImpl->assign(*tableImpl);
1185
  DBUG_VOID_RETURN;
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
}

const NdbDictionary::Table *
NdbEventImpl::getTable() const
{
  if (m_tableImpl) 
    return m_tableImpl->m_facade;
  else
    return NULL;
}

1197 1198 1199 1200 1201 1202
void 
NdbEventImpl::setTable(const char * table)
{
  m_tableName.assign(table);
}

1203 1204
const char *
NdbEventImpl::getTableName() const
1205 1206 1207 1208 1209 1210 1211
{
  return m_tableName.c_str();
}

void
NdbEventImpl::addTableEvent(const NdbDictionary::Event::TableEvent t =  NdbDictionary::Event::TE_ALL)
{
1212
  mi_type |= (unsigned)t;
1213 1214
}

1215 1216 1217 1218 1219 1220
bool
NdbEventImpl::getTableEvent(const NdbDictionary::Event::TableEvent t) const
{
  return (mi_type & (unsigned)t) == (unsigned)t;
}

1221
void
1222
NdbEventImpl::setDurability(NdbDictionary::Event::EventDurability d)
1223 1224 1225 1226
{
  m_dur = d;
}

1227 1228 1229 1230 1231 1232
NdbDictionary::Event::EventDurability
NdbEventImpl::getDurability() const
{
  return m_dur;
}

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
void
NdbEventImpl::setReport(NdbDictionary::Event::EventReport r)
{
  m_rep = r;
}

NdbDictionary::Event::EventReport
NdbEventImpl::getReport() const
{
  return m_rep;
}

1245 1246 1247 1248 1249
int NdbEventImpl::getNoOfEventColumns() const
{
  return m_attrIds.size() + m_columns.size();
}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
const NdbDictionary::Column *
NdbEventImpl::getEventColumn(unsigned no) const
{
  if (m_columns.size())
  {
    if (no < m_columns.size())
    {
      return m_columns[no];
    }
  }
  else if (m_attrIds.size())
  {
    if (no < m_attrIds.size())
    {
      NdbTableImpl* tab= m_tableImpl;
      if (tab == 0)
        return 0;
      return tab->getColumn(m_attrIds[no]);
    }
  }
  return 0;
}

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
/**
 * NdbDictionaryImpl
 */

NdbDictionaryImpl::NdbDictionaryImpl(Ndb &ndb)
  : NdbDictionary::Dictionary(* this), 
    m_facade(this), 
    m_receiver(m_error),
    m_ndb(ndb)
{
  m_globalHash = 0;
1284
  m_local_table_data_size= 0;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
}

NdbDictionaryImpl::NdbDictionaryImpl(Ndb &ndb,
				     NdbDictionary::Dictionary & f)
  : NdbDictionary::Dictionary(* this), 
    m_facade(&f), 
    m_receiver(m_error),
    m_ndb(ndb)
{
  m_globalHash = 0;
1295
  m_local_table_data_size= 0;
1296 1297
}

joreland@mysql.com's avatar
joreland@mysql.com committed
1298 1299
static int f_dictionary_count = 0;

1300 1301
NdbDictionaryImpl::~NdbDictionaryImpl()
{
1302
  NdbElement_t<Ndb_local_table_info> * curr = m_localHash.m_tableHash.getNext(0);
1303 1304 1305
  if(m_globalHash){
    while(curr != 0){
      m_globalHash->lock();
1306
      m_globalHash->release(curr->theData->m_table_impl);
1307
      Ndb_local_table_info::destroy(curr->theData);
1308 1309 1310 1311 1312
      m_globalHash->unlock();
      
      curr = m_localHash.m_tableHash.getNext(curr);
    }
    
1313
    m_globalHash->lock();
1314 1315
    if(--f_dictionary_count == 0){
      delete NdbDictionary::Column::FRAGMENT; 
1316
      delete NdbDictionary::Column::FRAGMENT_MEMORY;
1317 1318
      delete NdbDictionary::Column::ROW_COUNT;
      delete NdbDictionary::Column::COMMIT_COUNT;
1319
      delete NdbDictionary::Column::ROW_SIZE;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1320
      delete NdbDictionary::Column::RANGE_NO;
1321
      delete NdbDictionary::Column::DISK_REF;
1322
      delete NdbDictionary::Column::RECORDS_IN_RANGE;
1323 1324
      delete NdbDictionary::Column::ROWID;
      delete NdbDictionary::Column::ROW_GCI;
1325
      NdbDictionary::Column::FRAGMENT= 0;
1326
      NdbDictionary::Column::FRAGMENT_MEMORY= 0;
1327 1328
      NdbDictionary::Column::ROW_COUNT= 0;
      NdbDictionary::Column::COMMIT_COUNT= 0;
1329
      NdbDictionary::Column::ROW_SIZE= 0;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1330
      NdbDictionary::Column::RANGE_NO= 0;
1331
      NdbDictionary::Column::DISK_REF= 0;
1332
      NdbDictionary::Column::RECORDS_IN_RANGE= 0;
1333 1334
      NdbDictionary::Column::ROWID= 0;
      NdbDictionary::Column::ROW_GCI= 0;
1335
    }
1336
    m_globalHash->unlock();
1337 1338
  } else {
    assert(curr == 0);
joreland@mysql.com's avatar
joreland@mysql.com committed
1339
  }
1340 1341
}

1342 1343
NdbTableImpl *
NdbDictionaryImpl::fetchGlobalTableImplRef(const GlobalCacheInitObject &obj)
1344
{
1345
  DBUG_ENTER("fetchGlobalTableImplRef");
1346
  NdbTableImpl *impl;
1347

1348
  m_globalHash->lock();
1349
  impl = m_globalHash->get(obj.m_name.c_str());
1350 1351 1352
  m_globalHash->unlock();

  if (impl == 0){
1353
    impl = m_receiver.getTable(obj.m_name.c_str(),
1354
			       m_ndb.usingFullyQualifiedNames());
1355 1356 1357 1358
    if (impl != 0 && obj.init(*impl))
    {
      delete impl;
      impl = 0;
1359
    }
1360
    m_globalHash->lock();
1361
    m_globalHash->put(obj.m_name.c_str(), impl);
1362 1363 1364
    m_globalHash->unlock();
  }

1365
  DBUG_RETURN(impl);
1366
}
1367

1368 1369 1370
void
NdbDictionaryImpl::putTable(NdbTableImpl *impl)
{
1371 1372
  NdbTableImpl *old;

1373 1374 1375
  int ret = getBlobTables(*impl);
  assert(ret == 0);

1376
  m_globalHash->lock();
1377 1378
  if ((old= m_globalHash->get(impl->m_internalName.c_str())))
  {
1379 1380 1381 1382
    m_globalHash->alter_table_rep(old->m_internalName.c_str(),
                                  impl->m_id,
                                  impl->m_version,
                                  FALSE);
1383
  }
1384 1385 1386 1387 1388 1389
  m_globalHash->put(impl->m_internalName.c_str(), impl);
  m_globalHash->unlock();
  Ndb_local_table_info *info=
    Ndb_local_table_info::create(impl, m_local_table_data_size);
  
  m_localHash.put(impl->m_internalName.c_str(), info);
1390

1391 1392 1393 1394
  m_ndb.theFirstTupleId[impl->getTableId()] = ~0;
  m_ndb.theLastTupleId[impl->getTableId()]  = ~0;
}

1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
int
NdbDictionaryImpl::getBlobTables(NdbTableImpl &t)
{
  unsigned n= t.m_noOfBlobs;
  DBUG_ENTER("NdbDictionaryImpl::addBlobTables");
  // optimized for blob column being the last one
  // and not looking for more than one if not neccessary
  for (unsigned i = t.m_columns.size(); i > 0 && n > 0;) {
    i--;
    NdbColumnImpl & c = *t.m_columns[i];
    if (! c.getBlobType() || c.getPartSize() == 0)
      continue;
    n--;
    // retrieve blob table def from DICT - by-pass cache
    char btname[NdbBlobImpl::BlobTableNameSize];
    NdbBlob::getBlobTableName(btname, &t, &c);
    BaseString btname_internal = m_ndb.internalize_table_name(btname);
    NdbTableImpl* bt =
      m_receiver.getTable(btname_internal, m_ndb.usingFullyQualifiedNames());
    if (bt == NULL)
      DBUG_RETURN(-1);

    // TODO check primary id/version when returned by DICT

    // the blob column owns the blob table
    assert(c.m_blobTable == NULL);
    c.m_blobTable = bt;
  }
  DBUG_RETURN(0); 
}

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
NdbTableImpl*
NdbDictionaryImpl::getBlobTable(const NdbTableImpl& tab, uint col_no)
{
  if (col_no < tab.m_columns.size()) {
    NdbColumnImpl* col = tab.m_columns[col_no];
    if (col != NULL) {
      NdbTableImpl* bt = col->m_blobTable;
      if (bt != NULL)
        return bt;
      else
        m_error.code = 4273; // No blob table..
    } else
      m_error.code = 4249; // Invalid table..
  } else
    m_error.code = 4318; // Invalid attribute..
  return NULL;
}

NdbTableImpl*
NdbDictionaryImpl::getBlobTable(uint tab_id, uint col_no)
{
  DBUG_ENTER("NdbDictionaryImpl::getBlobTable");
  DBUG_PRINT("enter", ("tab_id: %u col_no %u", tab_id, col_no));

  NdbTableImpl* tab = m_receiver.getTable(tab_id,
                                          m_ndb.usingFullyQualifiedNames());
  if (tab == NULL)
    DBUG_RETURN(NULL);
  Ndb_local_table_info* info =
    get_local_table_info(tab->m_internalName);
  delete tab;
  if (info == NULL)
    DBUG_RETURN(NULL);
  NdbTableImpl* bt = getBlobTable(*info->m_table_impl, col_no);
  DBUG_RETURN(bt);
}

joreland@mysql.com's avatar
joreland@mysql.com committed
1463
#if 0
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
bool
NdbDictionaryImpl::setTransporter(class TransporterFacade * tf)
{
  if(tf != 0){
    m_globalHash = &tf->m_globalDictCache;
    return m_receiver.setTransporter(tf);
  }
  
  return false;
}
joreland@mysql.com's avatar
joreland@mysql.com committed
1474
#endif
1475 1476 1477 1478 1479 1480

bool
NdbDictionaryImpl::setTransporter(class Ndb* ndb, 
				  class TransporterFacade * tf)
{
  m_globalHash = &tf->m_globalDictCache;
joreland@mysql.com's avatar
joreland@mysql.com committed
1481 1482 1483 1484
  if(m_receiver.setTransporter(ndb, tf)){
    m_globalHash->lock();
    if(f_dictionary_count++ == 0){
      NdbDictionary::Column::FRAGMENT= 
1485
	NdbColumnImpl::create_pseudo("NDB$FRAGMENT");
1486
      NdbDictionary::Column::FRAGMENT_MEMORY= 
1487
	NdbColumnImpl::create_pseudo("NDB$FRAGMENT_MEMORY");
joreland@mysql.com's avatar
joreland@mysql.com committed
1488
      NdbDictionary::Column::ROW_COUNT= 
1489
	NdbColumnImpl::create_pseudo("NDB$ROW_COUNT");
joreland@mysql.com's avatar
joreland@mysql.com committed
1490
      NdbDictionary::Column::COMMIT_COUNT= 
1491
	NdbColumnImpl::create_pseudo("NDB$COMMIT_COUNT");
1492
      NdbDictionary::Column::ROW_SIZE=
1493
	NdbColumnImpl::create_pseudo("NDB$ROW_SIZE");
1494
      NdbDictionary::Column::RANGE_NO= 
1495
	NdbColumnImpl::create_pseudo("NDB$RANGE_NO");
1496 1497
      NdbDictionary::Column::DISK_REF= 
	NdbColumnImpl::create_pseudo("NDB$DISK_REF");
1498 1499
      NdbDictionary::Column::RECORDS_IN_RANGE= 
	NdbColumnImpl::create_pseudo("NDB$RECORDS_IN_RANGE");
1500 1501 1502 1503
      NdbDictionary::Column::ROWID= 
	NdbColumnImpl::create_pseudo("NDB$ROWID");
      NdbDictionary::Column::ROW_GCI= 
	NdbColumnImpl::create_pseudo("NDB$ROW_GCI");
joreland@mysql.com's avatar
joreland@mysql.com committed
1504 1505
    }
    m_globalHash->unlock();
1506
    return true;
joreland@mysql.com's avatar
joreland@mysql.com committed
1507
  }
1508
  return false;
1509 1510
}

1511 1512
NdbTableImpl *
NdbDictionaryImpl::getIndexTable(NdbIndexImpl * index,
1513 1514
				 NdbTableImpl * table)
{
1515 1516 1517
  const BaseString internalName(
    m_ndb.internalize_index_name(table, index->getName()));
  return getTable(m_ndb.externalizeTableName(internalName.c_str()));
1518 1519
}

1520
#if 0
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
bool
NdbDictInterface::setTransporter(class TransporterFacade * tf)
{
  if(tf == 0)
    return false;
  
  Guard g(tf->theMutexPtr);
  
  m_blockNumber = tf->open(this,
			   execSignal,
			   execNodeStatus);
  
  if ( m_blockNumber == -1 ) {
1534
    m_error.code= 4105;
1535 1536 1537 1538 1539 1540 1541 1542 1543
    return false; // no more free blocknumbers
  }//if
  Uint32 theNode = tf->ownId();
  m_reference = numberToRef(m_blockNumber, theNode);
  m_transporter = tf;
  m_waiter.m_mutex = tf->theMutexPtr;

  return true;
}
1544
#endif
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631

bool
NdbDictInterface::setTransporter(class Ndb* ndb, class TransporterFacade * tf)
{
  m_reference = ndb->getReference();
  m_transporter = tf;
  m_waiter.m_mutex = tf->theMutexPtr;
  
  return true;
}

NdbDictInterface::~NdbDictInterface()
{
}

void 
NdbDictInterface::execSignal(void* dictImpl, 
			     class NdbApiSignal* signal, 
			     class LinearSectionPtr ptr[3])
{
  NdbDictInterface * tmp = (NdbDictInterface*)dictImpl;
  
  const Uint32 gsn = signal->readSignalNumber();
  switch(gsn){
  case GSN_GET_TABINFOREF:
    tmp->execGET_TABINFO_REF(signal, ptr);
    break;
  case GSN_GET_TABINFO_CONF:
    tmp->execGET_TABINFO_CONF(signal, ptr);
    break;
  case GSN_CREATE_TABLE_REF:
    tmp->execCREATE_TABLE_REF(signal, ptr);
    break;
  case GSN_CREATE_TABLE_CONF:
    tmp->execCREATE_TABLE_CONF(signal, ptr);
    break;
  case GSN_DROP_TABLE_REF:
    tmp->execDROP_TABLE_REF(signal, ptr);
    break;
  case GSN_DROP_TABLE_CONF:
    tmp->execDROP_TABLE_CONF(signal, ptr);
    break;
  case GSN_ALTER_TABLE_REF:
    tmp->execALTER_TABLE_REF(signal, ptr);
    break;
  case GSN_ALTER_TABLE_CONF:
    tmp->execALTER_TABLE_CONF(signal, ptr);
    break;
  case GSN_CREATE_INDX_REF:
    tmp->execCREATE_INDX_REF(signal, ptr);
    break;
  case GSN_CREATE_INDX_CONF:
    tmp->execCREATE_INDX_CONF(signal, ptr);
    break;
  case GSN_DROP_INDX_REF:
    tmp->execDROP_INDX_REF(signal, ptr);
    break;
  case GSN_DROP_INDX_CONF:
    tmp->execDROP_INDX_CONF(signal, ptr);
    break;
  case GSN_CREATE_EVNT_REF:
    tmp->execCREATE_EVNT_REF(signal, ptr);
    break;
  case GSN_CREATE_EVNT_CONF:
    tmp->execCREATE_EVNT_CONF(signal, ptr);
    break;
  case GSN_SUB_START_CONF:
    tmp->execSUB_START_CONF(signal, ptr);
    break;
  case GSN_SUB_START_REF:
    tmp->execSUB_START_REF(signal, ptr);
    break;
  case GSN_SUB_STOP_CONF:
    tmp->execSUB_STOP_CONF(signal, ptr);
    break;
  case GSN_SUB_STOP_REF:
    tmp->execSUB_STOP_REF(signal, ptr);
    break;
  case GSN_DROP_EVNT_REF:
    tmp->execDROP_EVNT_REF(signal, ptr);
    break;
  case GSN_DROP_EVNT_CONF:
    tmp->execDROP_EVNT_CONF(signal, ptr);
    break;
  case GSN_LIST_TABLES_CONF:
    tmp->execLIST_TABLES_CONF(signal, ptr);
    break;
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
  case GSN_CREATE_FILEGROUP_REF:
    tmp->execCREATE_FILEGROUP_REF(signal, ptr);
    break;
  case GSN_CREATE_FILEGROUP_CONF:
    tmp->execCREATE_FILEGROUP_CONF(signal, ptr);
    break;
  case GSN_CREATE_FILE_REF:
    tmp->execCREATE_FILE_REF(signal, ptr);
    break;
  case GSN_CREATE_FILE_CONF:
    tmp->execCREATE_FILE_CONF(signal, ptr);
    break;
  case GSN_DROP_FILEGROUP_REF:
    tmp->execDROP_FILEGROUP_REF(signal, ptr);
    break;
  case GSN_DROP_FILEGROUP_CONF:
    tmp->execDROP_FILEGROUP_CONF(signal, ptr);
    break;
  case GSN_DROP_FILE_REF:
    tmp->execDROP_FILE_REF(signal, ptr);
    break;
  case GSN_DROP_FILE_CONF:
    tmp->execDROP_FILE_CONF(signal, ptr);
    break;
1656 1657 1658 1659 1660 1661
  case GSN_WAIT_GCP_CONF:
    tmp->execWAIT_GCP_CONF(signal, ptr);
    break;
  case GSN_WAIT_GCP_REF:
    tmp->execWAIT_GCP_REF(signal, ptr);
    break;
1662 1663 1664 1665 1666 1667
  default:
    abort();
  }
}

void
1668
NdbDictInterface::execNodeStatus(void* dictImpl, Uint32 aNode,
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
				 bool alive, bool nfCompleted)
{
  NdbDictInterface * tmp = (NdbDictInterface*)dictImpl;
  
  if(!alive && !nfCompleted){
    return;
  }
  
  if (!alive && nfCompleted){
    tmp->m_waiter.nodeFail(aNode);
  }
}

int
1683 1684 1685 1686 1687 1688
NdbDictInterface::dictSignal(NdbApiSignal* sig, 
			     LinearSectionPtr ptr[3], int secs,
			     int node_specification,
			     WaitSignalType wst,
			     int timeout, Uint32 RETRIES,
			     const int *errcodes, int temporaryMask)
1689
{
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1690
  DBUG_ENTER("NdbDictInterface::dictSignal");
1691
  DBUG_PRINT("enter", ("useMasterNodeId: %d", node_specification));
1692 1693 1694 1695
  for(Uint32 i = 0; i<RETRIES; i++){
    m_buffer.clear();

    // Protected area
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
1696 1697 1698 1699 1700 1701 1702
    /*
      The PollGuard has an implicit call of unlock_and_signal through the
      ~PollGuard method. This method is called implicitly by the compiler
      in all places where the object is out of context due to a return,
      break, continue or simply end of statement block
    */
    PollGuard poll_guard(m_transporter, &m_waiter, refToBlock(m_reference));
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
    Uint32 node;
    switch(node_specification){
    case 0:
      node = (m_transporter->get_node_alive(m_masterNodeId) ? m_masterNodeId :
	      (m_masterNodeId = m_transporter->get_an_alive_node()));
      break;
    case -1:
      node = m_transporter->get_an_alive_node();
      break;
    default:
      node = node_specification;
1714
    }
1715 1716
    DBUG_PRINT("info", ("node %d", node));
    if(node == 0){
1717
      m_error.code= 4009;
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1718
      DBUG_RETURN(-1);
1719
    }
1720 1721 1722 1723 1724 1725 1726
    int res = (ptr ? 
	       m_transporter->sendFragmentedSignal(sig, node, ptr, secs):
	       m_transporter->sendSignal(sig, node));
    if(res != 0){
      DBUG_PRINT("info", ("dictSignal failed to send signal"));
      continue;
    }    
1727
    
1728
    m_error.code= 0;
1729
    int ret_val= poll_guard.wait_n_unlock(timeout, node, wst);
1730 1731
    // End of Protected area  
    
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
1732
    if(ret_val == 0 && m_error.code == 0){
1733
      // Normal return
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1734
      DBUG_RETURN(0);
1735 1736 1737 1738 1739
    }
    
    /**
     * Handle error codes
     */
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
1740
    if(ret_val == -2) //WAIT_NODE_FAILURE
1741
    {
1742
      continue;
1743
    }
1744 1745
    if(m_waiter.m_state == WST_WAIT_TIMEOUT)
    {
1746
      DBUG_PRINT("info", ("dictSignal caught time-out"));
1747 1748 1749 1750
      m_error.code = 4008;
      DBUG_RETURN(-1);
    }
    
1751 1752 1753 1754 1755 1756 1757
    if ( temporaryMask == -1)
    {
      const NdbError &error= getNdbError();
      if (error.status ==  NdbError::TemporaryError)
	continue;
    }
    else if ( (temporaryMask & m_error.code) != 0 ) {
1758 1759
      continue;
    }
1760 1761 1762 1763
    DBUG_PRINT("info", ("dictSignal caught error= %d", m_error.code));
    
    if(m_error.code && errcodes)
    {
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1764 1765
      int j;
      for(j = 0; errcodes[j] ; j++){
1766
	if(m_error.code == errcodes[j]){
1767
	  break;
1768
	}
1769
      }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1770
      if(errcodes[j]) // Accepted error code
1771 1772
	continue;
    }
1773
    break;
1774
  }
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1775
  DBUG_RETURN(-1);
1776
}
1777

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1778 1779 1780 1781 1782
/*
  Get dictionary information for a table using table id as reference

  DESCRIPTION
    Sends a GET_TABINFOREQ signal containing the table id
1783
 */
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1784
NdbTableImpl *
1785
NdbDictInterface::getTable(int tableId, bool fullyQualifiedNames)
1786 1787
{
  NdbApiSignal tSignal(m_reference);
1788 1789
  GetTabInfoReq * req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
  
1790 1791
  req->senderRef = m_reference;
  req->senderData = 0;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1792
  req->requestType =
1793 1794 1795 1796 1797
    GetTabInfoReq::RequestById | GetTabInfoReq::LongSignalConf;
  req->tableId = tableId;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_GET_TABINFOREQ;
  tSignal.theLength = GetTabInfoReq::SignalLength;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1798

1799
  return getTable(&tSignal, 0, 0, fullyQualifiedNames);
1800
}
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1801 1802 1803 1804 1805 1806 1807 1808

/*
  Get dictionary information for a table using table name as the reference

  DESCRIPTION
    Send GET_TABINFOREQ signal with the table name in the first
    long section part
*/
1809

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1810
NdbTableImpl *
1811
NdbDictInterface::getTable(const BaseString& name, bool fullyQualifiedNames)
1812 1813
{
  NdbApiSignal tSignal(m_reference);
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1814
  GetTabInfoReq* const req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
1815

1816 1817
  const Uint32 namelen= name.length() + 1; // NULL terminated
  const Uint32 namelen_words= (namelen + 3) >> 2; // Size in words
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1818 1819 1820 1821

  req->senderRef= m_reference;
  req->senderData= 0;
  req->requestType=
1822
    GetTabInfoReq::RequestByName | GetTabInfoReq::LongSignalConf;
1823
  req->tableNameLen= namelen;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1824 1825 1826 1827
  tSignal.theReceiversBlockNumber= DBDICT;
  tSignal.theVerId_signalNumber= GSN_GET_TABINFOREQ;
  tSignal.theLength= GetTabInfoReq::SignalLength;

1828 1829
  // Copy name to m_buffer to get a word sized buffer
  m_buffer.clear();
1830
  m_buffer.grow(namelen_words*4+4);
1831 1832
  m_buffer.append(name.c_str(), namelen);

1833 1834 1835 1836 1837
#ifndef IGNORE_VALGRIND_WARNINGS
  Uint32 pad = 0;
  m_buffer.append(&pad, 4);
#endif
  
1838
  LinearSectionPtr ptr[1];
1839 1840
  ptr[0].p= (Uint32*)m_buffer.get_data();
  ptr[0].sz= namelen_words;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1841

1842
  return getTable(&tSignal, ptr, 1, fullyQualifiedNames);
1843 1844
}

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1845

1846
NdbTableImpl *
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1847
NdbDictInterface::getTable(class NdbApiSignal * signal,
1848
			   LinearSectionPtr ptr[3],
1849
			   Uint32 noOfSections, bool fullyQualifiedNames)
1850
{
1851 1852 1853
  int errCodes[] = {GetTabInfoRef::Busy, 0 };
  int r = dictSignal(signal, ptr, noOfSections,
		     -1, // any node
1854
		     WAIT_GET_TAB_INFO_REQ,
1855
		     DICT_WAITFOR_TIMEOUT, 100, errCodes);
1856

1857 1858 1859
  if (r)
    return 0;
  
1860
  NdbTableImpl * rt = 0;
1861 1862 1863 1864 1865 1866 1867
  m_error.code = parseTableInfo(&rt, 
				(Uint32*)m_buffer.get_data(), 
  				m_buffer.length() / 4, 
				fullyQualifiedNames);
  if(rt)
    rt->buildColumnHash();
  
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
  return rt;
}

void
NdbDictInterface::execGET_TABINFO_CONF(NdbApiSignal * signal, 
				       LinearSectionPtr ptr[3])
{
  const GetTabInfoConf* conf = CAST_CONSTPTR(GetTabInfoConf, signal->getDataPtr());
  if(signal->isFirstFragment()){
    m_fragmentId = signal->getFragmentId();
    m_buffer.grow(4 * conf->totalLen);
  } else {
    if(m_fragmentId != signal->getFragmentId()){
      abort();
    }
  }
  
  const Uint32 i = GetTabInfoConf::DICT_TAB_INFO;
  m_buffer.append(ptr[i].p, 4 * ptr[i].sz);

  if(!signal->isLastFragment()){
    return;
  }  
  
  m_waiter.signal(NO_WAIT);
}

void
NdbDictInterface::execGET_TABINFO_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
1899 1900 1901
  const GetTabInfoRef* ref = CAST_CONSTPTR(GetTabInfoRef, 
					   signal->getDataPtr());
  
1902
  m_error.code= ref->errorCode;
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
  m_waiter.signal(NO_WAIT);
}

/*****************************************************************
 * Pack/Unpack tables
 */
struct ApiKernelMapping {
  Int32 kernelConstant;
  Int32 apiConstant;
};

Uint32
getApiConstant(Int32 kernelConstant, const ApiKernelMapping map[], Uint32 def)
{
  int i = 0;
  while(map[i].kernelConstant != kernelConstant){
    if(map[i].kernelConstant == -1 &&
       map[i].apiConstant == -1){
      return def;
    }
    i++;
  }
  return map[i].apiConstant;
}

Uint32
getKernelConstant(Int32 apiConstant, const ApiKernelMapping map[], Uint32 def)
{
  int i = 0;
  while(map[i].apiConstant != apiConstant){
    if(map[i].kernelConstant == -1 &&
       map[i].apiConstant == -1){
      return def;
    }
    i++;
  }
  return map[i].kernelConstant;
}

static const
ApiKernelMapping 
fragmentTypeMapping[] = {
  { DictTabInfo::AllNodesSmallTable,  NdbDictionary::Object::FragAllSmall },
  { DictTabInfo::AllNodesMediumTable, NdbDictionary::Object::FragAllMedium },
  { DictTabInfo::AllNodesLargeTable,  NdbDictionary::Object::FragAllLarge },
  { DictTabInfo::SingleFragment,      NdbDictionary::Object::FragSingle },
1949 1950 1951
  { DictTabInfo::DistrKeyHash,      NdbDictionary::Object::DistrKeyHash },
  { DictTabInfo::DistrKeyLin,      NdbDictionary::Object::DistrKeyLin },
  { DictTabInfo::UserDefined,      NdbDictionary::Object::UserDefined },
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
  { -1, -1 }
};

static const
ApiKernelMapping
objectTypeMapping[] = {
  { DictTabInfo::SystemTable,        NdbDictionary::Object::SystemTable },
  { DictTabInfo::UserTable,          NdbDictionary::Object::UserTable },
  { DictTabInfo::UniqueHashIndex,    NdbDictionary::Object::UniqueHashIndex },
  { DictTabInfo::OrderedIndex,       NdbDictionary::Object::OrderedIndex },
  { DictTabInfo::HashIndexTrigger,   NdbDictionary::Object::HashIndexTrigger },
  { DictTabInfo::IndexTrigger,       NdbDictionary::Object::IndexTrigger },
  { DictTabInfo::SubscriptionTrigger,NdbDictionary::Object::SubscriptionTrigger },
  { DictTabInfo::ReadOnlyConstraint ,NdbDictionary::Object::ReadOnlyConstraint },
1966 1967 1968 1969
  { DictTabInfo::Tablespace,         NdbDictionary::Object::Tablespace },
  { DictTabInfo::LogfileGroup,       NdbDictionary::Object::LogfileGroup },
  { DictTabInfo::Datafile,           NdbDictionary::Object::Datafile },
  { DictTabInfo::Undofile,           NdbDictionary::Object::Undofile },
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
  { -1, -1 }
};

static const
ApiKernelMapping
objectStateMapping[] = {
  { DictTabInfo::StateOffline,       NdbDictionary::Object::StateOffline },
  { DictTabInfo::StateBuilding,      NdbDictionary::Object::StateBuilding },
  { DictTabInfo::StateDropping,      NdbDictionary::Object::StateDropping },
  { DictTabInfo::StateOnline,        NdbDictionary::Object::StateOnline },
joreland@mysql.com's avatar
joreland@mysql.com committed
1980
  { DictTabInfo::StateBackup,        NdbDictionary::Object::StateBackup },
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
  { DictTabInfo::StateBroken,        NdbDictionary::Object::StateBroken }, 
  { -1, -1 }
};

static const
ApiKernelMapping
objectStoreMapping[] = {
  { DictTabInfo::StoreTemporary,     NdbDictionary::Object::StoreTemporary },
  { DictTabInfo::StorePermanent,     NdbDictionary::Object::StorePermanent },
  { -1, -1 }
};

static const
ApiKernelMapping
indexTypeMapping[] = {
  { DictTabInfo::UniqueHashIndex,    NdbDictionary::Index::UniqueHashIndex },  
  { DictTabInfo::OrderedIndex,       NdbDictionary::Index::OrderedIndex },
  { -1, -1 }
};

int
NdbDictInterface::parseTableInfo(NdbTableImpl ** ret,
2003
				 const Uint32 * data, Uint32 len,
2004 2005
				 bool fullyQualifiedNames,
                                 Uint32 version)
2006 2007
{
  SimplePropertiesLinearReader it(data, len);
2008
  DictTabInfo::Table *tableDesc;
2009
  SimpleProperties::UnpackStatus s;
2010 2011 2012 2013 2014 2015 2016 2017 2018
  DBUG_ENTER("NdbDictInterface::parseTableInfo");

  tableDesc = (DictTabInfo::Table*)NdbMem_Allocate(sizeof(DictTabInfo::Table));
  if (!tableDesc)
  {
    DBUG_RETURN(4000);
  }
  tableDesc->init();
  s = SimpleProperties::unpack(it, tableDesc, 
2019 2020 2021 2022 2023
			       DictTabInfo::TableMapping, 
			       DictTabInfo::TableMappingSize, 
			       true, true);
  
  if(s != SimpleProperties::Break){
2024
    NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
2025
    DBUG_RETURN(703);
2026
  }
2027
  const char * internalName = tableDesc->TableName;
2028
  const char * externalName = Ndb::externalizeTableName(internalName, fullyQualifiedNames);
2029 2030

  NdbTableImpl * impl = new NdbTableImpl();
2031 2032
  impl->m_id = tableDesc->TableId;
  impl->m_version = tableDesc->TableVersion;
2033 2034
  impl->m_status = NdbDictionary::Object::Retrieved;
  impl->m_internalName.assign(internalName);
2035
  impl->updateMysqlName();
2036 2037
  impl->m_externalName.assign(externalName);

2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
  impl->m_frm.assign(tableDesc->FrmData, tableDesc->FrmLen);
  impl->m_fd.assign(tableDesc->FragmentData, tableDesc->FragmentDataLen);
  impl->m_range.assign(tableDesc->RangeListData, tableDesc->RangeListDataLen);
  impl->m_fragmentCount = tableDesc->FragmentCount;

  /*
    We specifically don't get tablespace data and range/list arrays here
    since those are known by the MySQL Server through analysing the
    frm file.
    Fragment Data contains the real node group mapping and the fragment
    identities used for each fragment. At the moment we have no need for
    this.
    Frm file is needed for autodiscovery.
  */
2052 2053
  
  impl->m_fragmentType = (NdbDictionary::Object::FragmentType)
2054
    getApiConstant(tableDesc->FragmentType, 
2055 2056 2057
		   fragmentTypeMapping, 
		   (Uint32)NdbDictionary::Object::FragUndefined);
  
2058 2059 2060 2061
  Uint64 max_rows = ((Uint64)tableDesc->MaxRowsHigh) << 32;
  max_rows += tableDesc->MaxRowsLow;
  impl->m_max_rows = max_rows;
  impl->m_default_no_part_flag = tableDesc->DefaultNoPartFlag;
2062
  impl->m_linear_flag = tableDesc->LinearHashFlag;
2063 2064 2065 2066 2067 2068
  impl->m_logging = tableDesc->TableLoggedFlag;
  impl->m_row_gci = tableDesc->RowGCIFlag;
  impl->m_row_checksum = tableDesc->RowChecksumFlag;
  impl->m_kvalue = tableDesc->TableKValue;
  impl->m_minLoadFactor = tableDesc->MinLoadFactor;
  impl->m_maxLoadFactor = tableDesc->MaxLoadFactor;
2069

2070
  impl->m_indexType = (NdbDictionary::Object::Type)
2071
    getApiConstant(tableDesc->TableType,
2072
		   indexTypeMapping,
2073
		   NdbDictionary::Object::TypeUndefined);
2074
  
2075
  if(impl->m_indexType == NdbDictionary::Object::TypeUndefined){
2076 2077
  } else {
    const char * externalPrimary = 
2078
      Ndb::externalizeTableName(tableDesc->PrimaryTable, fullyQualifiedNames);
2079 2080 2081
    impl->m_primaryTable.assign(externalPrimary);
  }
  
2082
  Uint32 i;
2083
  for(i = 0; i < tableDesc->NoOfAttributes; i++) {
2084 2085 2086 2087 2088 2089 2090 2091
    DictTabInfo::Attribute attrDesc; attrDesc.init();
    s = SimpleProperties::unpack(it, 
				 &attrDesc, 
				 DictTabInfo::AttributeMapping, 
				 DictTabInfo::AttributeMappingSize, 
				 true, true);
    if(s != SimpleProperties::Break){
      delete impl;
2092
      NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
2093
      DBUG_RETURN(703);
2094 2095 2096 2097 2098
    }
    
    NdbColumnImpl * col = new NdbColumnImpl();
    col->m_attrId = attrDesc.AttributeId;
    col->setName(attrDesc.AttributeName);
pekka@mysql.com's avatar
pekka@mysql.com committed
2099 2100 2101

    // check type and compute attribute size and array size
    if (! attrDesc.translateExtType()) {
2102
      delete impl;
2103
      NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
2104
      DBUG_RETURN(703);
2105
    }
2106
    col->m_type = (NdbDictionary::Column::Type)attrDesc.AttributeExtType;
pekka@mysql.com's avatar
pekka@mysql.com committed
2107
    col->m_precision = (attrDesc.AttributeExtPrecision & 0xFFFF);
2108 2109
    col->m_scale = attrDesc.AttributeExtScale;
    col->m_length = attrDesc.AttributeExtLength;
pekka@mysql.com's avatar
pekka@mysql.com committed
2110 2111 2112 2113 2114
    // charset in upper half of precision
    unsigned cs_number = (attrDesc.AttributeExtPrecision >> 16);
    // charset is defined exactly for char types
    if (col->getCharType() != (cs_number != 0)) {
      delete impl;
2115
      NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
2116
      DBUG_RETURN(703);
pekka@mysql.com's avatar
pekka@mysql.com committed
2117 2118 2119 2120 2121
    }
    if (col->getCharType()) {
      col->m_cs = get_charset(cs_number, MYF(0));
      if (col->m_cs == NULL) {
        delete impl;
2122
        NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
2123
        DBUG_RETURN(743);
pekka@mysql.com's avatar
pekka@mysql.com committed
2124 2125
      }
    }
2126 2127
    col->m_attrSize = (1 << attrDesc.AttributeSize) / 8;
    col->m_arraySize = attrDesc.AttributeArraySize;
2128
    col->m_arrayType = attrDesc.AttributeArrayType;
2129 2130 2131 2132 2133
    if(attrDesc.AttributeSize == 0)
    {
      col->m_attrSize = 4;
      col->m_arraySize = (attrDesc.AttributeArraySize + 31) >> 5;
    }
2134
    col->m_storageType = attrDesc.AttributeStorageType;
2135 2136
    
    col->m_pk = attrDesc.AttributeKeyFlag;
2137
    col->m_distributionKey = attrDesc.AttributeDKey ? 2 : 0;
2138 2139 2140 2141 2142
    col->m_nullable = attrDesc.AttributeNullableFlag;
    col->m_autoIncrement = (attrDesc.AttributeAutoIncrement ? true : false);
    col->m_autoIncrementInitialValue = ~0;
    col->m_defaultValue.assign(attrDesc.AttributeDefaultValue);

2143 2144
    col->m_column_no = impl->m_columns.size();
    impl->m_columns.push_back(col);
2145 2146
    it.next();
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
2147

2148
  impl->computeAggregates();
2149

2150
  if(tableDesc->ReplicaDataLen > 0)
2151
  {
2152 2153
    Uint16 replicaCount = ntohs(tableDesc->ReplicaData[0]);
    Uint16 fragCount = ntohs(tableDesc->ReplicaData[1]);
2154

2155 2156
    impl->m_replicaCount = replicaCount;
    impl->m_fragmentCount = fragCount;
2157
    DBUG_PRINT("info", ("replicaCount=%x , fragCount=%x",replicaCount,fragCount));
2158
    for(i = 0; i < (Uint32) (fragCount*replicaCount); i++)
2159
    {
2160
      impl->m_fragments.push_back(ntohs(tableDesc->ReplicaData[i+2]));
2161 2162 2163
    }

    Uint32 topBit = (1 << 31);
2164
    for(; topBit && !(fragCount & topBit); ){
2165 2166 2167 2168 2169 2170 2171
      topBit >>= 1;
    }
    impl->m_hashValueMask = topBit - 1;
    impl->m_hashpointerValue = fragCount - (impl->m_hashValueMask + 1);
  }
  else
  {
2172
    impl->m_fragmentCount = tableDesc->FragmentCount;
2173 2174 2175 2176 2177
    impl->m_replicaCount = 0;
    impl->m_hashValueMask = 0;
    impl->m_hashpointerValue = 0;
  }

2178 2179
  impl->m_tablespace_id = tableDesc->TablespaceId;
  impl->m_tablespace_version = tableDesc->TablespaceVersion;
2180
  
2181
  * ret = impl;
2182

2183
  NdbMem_Free((void*)tableDesc);
2184 2185 2186 2187 2188 2189 2190 2191
  if (version < MAKE_VERSION(5,1,3))
  {
    ;
  } 
  else
  {
    DBUG_ASSERT(impl->m_fragmentCount > 0);
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
2192
  DBUG_RETURN(0);
2193 2194 2195 2196 2197
}

/*****************************************************************
 * Create table and alter table
 */
pekka@mysql.com's avatar
pekka@mysql.com committed
2198 2199 2200
int
NdbDictionaryImpl::createTable(NdbTableImpl &t)
{ 
2201
  DBUG_ENTER("NdbDictionaryImpl::createTable");
2202 2203

  // if the new name has not been set, use the copied name
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2204 2205
  if (t.m_newExternalName.empty())
    t.m_newExternalName.assign(t.m_externalName);
2206 2207

  // create table
pekka@mysql.com's avatar
pekka@mysql.com committed
2208
  if (m_receiver.createTable(m_ndb, t) != 0)
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
    DBUG_RETURN(-1);
  Uint32* data = (Uint32*)m_receiver.m_buffer.get_data();
  t.m_id = data[0];
  t.m_version = data[1];

  // update table def from DICT - by-pass cache
  NdbTableImpl* t2 =
    m_receiver.getTable(t.m_internalName, m_ndb.usingFullyQualifiedNames());

  // check if we got back same table
  if (t2 == NULL) {
    DBUG_PRINT("info", ("table %s dropped by another thread", 
                        t.m_internalName.c_str()));
    m_error.code = 283;
2223 2224
    DBUG_RETURN(-1);
  }
2225 2226 2227 2228 2229
  if (t.m_id != t2->m_id || t.m_version != t2->m_version) {
    DBUG_PRINT("info", ("table %s re-created by another thread",
                        t.m_internalName.c_str()));
    m_error.code = 283;
    delete t2;
2230
    DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2231
  }
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264

  // auto-increment - use "t" because initial value is not in DICT
  {
    bool autoIncrement = false;
    Uint64 initialValue = 0;
    for (Uint32 i = 0; i < t.m_columns.size(); i++) {
      const NdbColumnImpl* c = t.m_columns[i];
      assert(c != NULL);
      if (c->m_autoIncrement) {
        if (autoIncrement) {
          m_error.code = 4335;
          delete t2;
          DBUG_RETURN(-1);
        }
        autoIncrement = true;
        initialValue = c->m_autoIncrementInitialValue;
      }
    }
    if (autoIncrement) {
      // XXX unlikely race condition - t.m_id may no longer be same table
      if (! m_ndb.setTupleIdInNdb(t.m_id, initialValue, false)) {
        if (m_ndb.theError.code)
          m_error.code = m_ndb.theError.code;
        else
          m_error.code = 4336;
        delete t2;
        DBUG_RETURN(-1);
      }
    }
  }

  // blob tables - use "t2" to get values set by kernel
  if (t2->m_noOfBlobs != 0 && createBlobTables(*t2) != 0) {
pekka@mysql.com's avatar
pekka@mysql.com committed
2265
    int save_code = m_error.code;
2266 2267 2268
    (void)dropTable(*t2);
    m_error.code = save_code;
    delete t2;
2269
    DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2270
  }
2271 2272 2273

  // not entered in cache
  delete t2;
2274
  DBUG_RETURN(0);
pekka@mysql.com's avatar
pekka@mysql.com committed
2275 2276 2277
}

int
2278
NdbDictionaryImpl::createBlobTables(NdbTableImpl &t)
pekka@mysql.com's avatar
pekka@mysql.com committed
2279
{
2280
  DBUG_ENTER("NdbDictionaryImpl::createBlobTables");
pekka@mysql.com's avatar
pekka@mysql.com committed
2281 2282
  for (unsigned i = 0; i < t.m_columns.size(); i++) {
    NdbColumnImpl & c = *t.m_columns[i];
pekka@mysql.com's avatar
pekka@mysql.com committed
2283
    if (! c.getBlobType() || c.getPartSize() == 0)
pekka@mysql.com's avatar
pekka@mysql.com committed
2284 2285 2286
      continue;
    NdbTableImpl bt;
    NdbBlob::getBlobTable(bt, &t, &c);
2287
    if (createTable(bt) != 0) {
2288 2289
      DBUG_RETURN(-1);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2290
  }
2291
  DBUG_RETURN(0); 
mskold@mysql.com's avatar
mskold@mysql.com committed
2292 2293
}

2294 2295 2296 2297
int 
NdbDictInterface::createTable(Ndb & ndb,
			      NdbTableImpl & impl)
{
2298 2299
  DBUG_ENTER("NdbDictInterface::createTable");
  DBUG_RETURN(createOrAlterTable(ndb, impl, false));
2300 2301 2302 2303
}

int NdbDictionaryImpl::alterTable(NdbTableImpl &impl)
{
2304
  BaseString internalName(impl.m_internalName);
2305
  const char * originalInternalName = internalName.c_str();
2306 2307

  DBUG_ENTER("NdbDictionaryImpl::alterTable");
2308
  Ndb_local_table_info * local = 0;
2309
  if((local= get_local_table_info(originalInternalName)) == 0)
2310
  {
2311
    m_error.code = 709;
2312
    DBUG_RETURN(-1);
2313
  }
2314

2315
  // Alter the table
2316 2317 2318
  int ret = alterTableGlobal(*local->m_table_impl, impl);
  if(ret == 0)
  {
2319
    m_globalHash->lock();
2320
    m_globalHash->release(local->m_table_impl, 1);
2321 2322
    m_globalHash->unlock();
    m_localHash.drop(originalInternalName);
2323
  }
mskold@mysql.com's avatar
mskold@mysql.com committed
2324
  DBUG_RETURN(ret);
2325 2326
}

2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
int NdbDictionaryImpl::alterTableGlobal(NdbTableImpl &old_impl,
                                        NdbTableImpl &impl)
{
  DBUG_ENTER("NdbDictionaryImpl::alterTableGlobal");
  // Alter the table
  int ret = m_receiver.alterTable(m_ndb, impl);
  old_impl.m_status = NdbDictionary::Object::Invalid;
  if(ret == 0){
    DBUG_RETURN(ret);
  }
  ERR_RETURN(getNdbError(), ret);
}

2340 2341 2342 2343
int 
NdbDictInterface::alterTable(Ndb & ndb,
			      NdbTableImpl & impl)
{
2344 2345
  DBUG_ENTER("NdbDictInterface::alterTable");
  DBUG_RETURN(createOrAlterTable(ndb, impl, true));
2346 2347 2348 2349 2350 2351 2352
}

int 
NdbDictInterface::createOrAlterTable(Ndb & ndb,
				     NdbTableImpl & impl,
				     bool alter)
{
2353
  unsigned i, err;
2354 2355
  char *ts_names[MAX_NDB_PARTITIONS];
  DBUG_ENTER("NdbDictInterface::createOrAlterTable");
2356 2357 2358

  impl.computeAggregates();

2359
  if((unsigned)impl.getNoOfPrimaryKeys() > NDB_MAX_NO_OF_ATTRIBUTES_IN_KEY){
2360
    m_error.code= 4317;
2361
    DBUG_RETURN(-1);
2362 2363 2364
  }
  unsigned sz = impl.m_columns.size();
  if (sz > NDB_MAX_ATTRIBUTES_IN_TABLE){
2365
    m_error.code= 4318;
2366
    DBUG_RETURN(-1);
2367
  }
2368 2369 2370 2371
  
  // Check if any changes for alter table
  
  // Name change
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2372
  if (!impl.m_newExternalName.empty()) {
2373 2374 2375 2376
    if (alter)
    {
      AlterTableReq::setNameFlag(impl.m_changeMask, true);
    }
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2377
    impl.m_externalName.assign(impl.m_newExternalName);
2378
    impl.m_newExternalName.clear();
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2379
  }
2380
  // Definition change (frm)
2381 2382
  if (!impl.m_newFrm.empty())
  {
2383 2384 2385 2386 2387 2388 2389
    if (alter)
    {
      AlterTableReq::setFrmFlag(impl.m_changeMask, true);
    }
    impl.m_frm.assign(impl.m_newFrm.get_data(), impl.m_newFrm.length());
    impl.m_newFrm.clear();
  }
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
  // Change FragmentData (fragment identity, state, tablespace id)
  if (!impl.m_new_fd.empty())
  {
    if (alter)
    {
      AlterTableReq::setFragDataFlag(impl.m_changeMask, true);
    }
    impl.m_fd.assign(impl.m_new_fd.get_data(), impl.m_new_fd.length());
    impl.m_new_fd.clear();
  }
  // Change Tablespace Name Data
  if (!impl.m_new_ts_name.empty())
  {
    if (alter)
    {
      AlterTableReq::setTsNameFlag(impl.m_changeMask, true);
    }
    impl.m_ts_name.assign(impl.m_new_ts_name.get_data(),
                          impl.m_new_ts_name.length());
    impl.m_new_ts_name.clear();
  }
  // Change Range/List Data
  if (!impl.m_new_range.empty())
  {
    if (alter)
    {
      AlterTableReq::setRangeListFlag(impl.m_changeMask, true);
    }
    impl.m_range.assign(impl.m_new_range.get_data(),
                          impl.m_new_range.length());
    impl.m_new_range.clear();
  }
  // Change Tablespace Data
  if (!impl.m_new_ts.empty())
  {
    if (alter)
    {
      AlterTableReq::setTsFlag(impl.m_changeMask, true);
    }
    impl.m_ts.assign(impl.m_new_ts.get_data(),
                     impl.m_new_ts.length());
    impl.m_new_ts.clear();
  }


  /*
     TODO RONM: Here I need to insert checks for fragment array and
     range or list array
  */
2439
  
2440 2441 2442
  //validate();
  //aggregate();

2443 2444
  const BaseString internalName(
    ndb.internalize_table_name(impl.m_externalName.c_str()));
2445
  impl.m_internalName.assign(internalName);
2446
  impl.updateMysqlName();
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
  DictTabInfo::Table *tmpTab;

  tmpTab = (DictTabInfo::Table*)NdbMem_Allocate(sizeof(DictTabInfo::Table));
  if (!tmpTab)
  {
    m_error.code = 4000;
    DBUG_RETURN(-1);
  }
  tmpTab->init();
  BaseString::snprintf(tmpTab->TableName,
	   sizeof(tmpTab->TableName),
2458
	   internalName.c_str());
2459

2460
  Uint32 distKeys= 0;
2461
  for(i = 0; i<sz; i++) {
2462
    const NdbColumnImpl * col = impl.m_columns[i];
2463 2464 2465 2466
    if (col == NULL) {
      m_error.code = 4272;
      NdbMem_Free((void*)tmpTab);
      DBUG_RETURN(-1);
2467 2468
    }
    if (col->m_distributionKey)
2469
    {
2470
      distKeys++;
2471
    }
2472
  }
2473 2474 2475 2476
  if (distKeys == impl.m_noOfKeys)
    distKeys= 0;
  impl.m_noOfDistributionKeys= distKeys;

2477 2478 2479

  // Check max length of frm data
  if (impl.m_frm.length() > MAX_FRM_DATA_SIZE){
2480
    m_error.code= 1229;
2481
    NdbMem_Free((void*)tmpTab);
2482
    DBUG_RETURN(-1);
2483
  }
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
  /*
    TODO RONM: This needs to change to dynamic arrays instead
    Frm Data, FragmentData, TablespaceData, RangeListData, TsNameData
  */
  tmpTab->FrmLen = impl.m_frm.length();
  memcpy(tmpTab->FrmData, impl.m_frm.get_data(), impl.m_frm.length());

  tmpTab->FragmentDataLen = impl.m_fd.length();
  memcpy(tmpTab->FragmentData, impl.m_fd.get_data(), impl.m_fd.length());

  tmpTab->TablespaceDataLen = impl.m_ts.length();
  memcpy(tmpTab->TablespaceData, impl.m_ts.get_data(), impl.m_ts.length());

  tmpTab->RangeListDataLen = impl.m_range.length();
  memcpy(tmpTab->RangeListData, impl.m_range.get_data(),
         impl.m_range.length());

  memcpy(ts_names, impl.m_ts_name.get_data(),
         impl.m_ts_name.length());

  tmpTab->FragmentCount= impl.m_fragmentCount;
  tmpTab->TableLoggedFlag = impl.m_logging;
  tmpTab->RowGCIFlag = impl.m_row_gci;
  tmpTab->RowChecksumFlag = impl.m_row_checksum;
  tmpTab->TableKValue = impl.m_kvalue;
  tmpTab->MinLoadFactor = impl.m_minLoadFactor;
  tmpTab->MaxLoadFactor = impl.m_maxLoadFactor;
  tmpTab->TableType = DictTabInfo::UserTable;
  tmpTab->PrimaryTableId = impl.m_primaryTableId;
  tmpTab->NoOfAttributes = sz;
  tmpTab->MaxRowsHigh = (Uint32)(impl.m_max_rows >> 32);
  tmpTab->MaxRowsLow = (Uint32)(impl.m_max_rows & 0xFFFFFFFF);
  tmpTab->DefaultNoPartFlag = impl.m_default_no_part_flag;
2517
  tmpTab->LinearHashFlag = impl.m_linear_flag;
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551

  if (impl.m_ts_name.length())
  {
    char **ts_name_ptr= (char**)ts_names;
    i= 0;
    do
    {
      NdbTablespaceImpl tmp;
      if (*ts_name_ptr)
      {
        if(get_filegroup(tmp, NdbDictionary::Object::Tablespace, 
                         (const char*)*ts_name_ptr) == 0)
        {
          tmpTab->TablespaceData[2*i] = tmp.m_id;
          tmpTab->TablespaceData[2*i + 1] = tmp.m_version;
        }
        else
        { 
          NdbMem_Free((void*)tmpTab);
          DBUG_RETURN(-1);
        }
      }
      else
      {
        /*
          No tablespace used, set tablespace id to NULL
        */
        tmpTab->TablespaceData[2*i] = RNIL;
        tmpTab->TablespaceData[2*i + 1] = 0;
      }
      ts_name_ptr++;
    } while (++i < tmpTab->FragmentCount);
    tmpTab->TablespaceDataLen= 4*i;
  }
2552

2553 2554 2555 2556 2557 2558
  tmpTab->FragmentType = getKernelConstant(impl.m_fragmentType,
 					   fragmentTypeMapping,
					   DictTabInfo::AllNodesSmallTable);
  tmpTab->TableVersion = rand();

  const char *tablespace_name= impl.m_tablespace_name.c_str();
2559 2560 2561
loop:
  if(impl.m_tablespace_id != ~(Uint32)0)
  {
2562 2563
    tmpTab->TablespaceId = impl.m_tablespace_id;
    tmpTab->TablespaceVersion = impl.m_tablespace_version;
2564 2565 2566 2567 2568 2569 2570
  }
  else if(strlen(tablespace_name))
  {
    NdbTablespaceImpl tmp;
    if(get_filegroup(tmp, NdbDictionary::Object::Tablespace, 
		     tablespace_name) == 0)
    {
2571 2572
      tmpTab->TablespaceId = tmp.m_id;
      tmpTab->TablespaceVersion = tmp.m_version;
2573 2574 2575 2576
    }
    else 
    {
      // error set by get filegroup
2577 2578
      NdbMem_Free((void*)tmpTab);
      DBUG_RETURN(-1);
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
    }
  } 
  else
  {
    for(i = 0; i<sz; i++)
    {
      if(impl.m_columns[i]->m_storageType == NDB_STORAGETYPE_DISK)
      {
	tablespace_name = "DEFAULT-TS";
	goto loop;
      }
    }
  }
  
  UtilBufferWriter w(m_buffer);
2594 2595
  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
2596
			     tmpTab,
2597 2598 2599 2600 2601 2602
			     DictTabInfo::TableMapping, 
			     DictTabInfo::TableMappingSize, true);
  
  if(s != SimpleProperties::Eof){
    abort();
  }
2603
  NdbMem_Free((void*)tmpTab);
2604
  
2605 2606
  DBUG_PRINT("info",("impl.m_noOfDistributionKeys: %d impl.m_noOfKeys: %d distKeys: %d",
		     impl.m_noOfDistributionKeys, impl.m_noOfKeys, distKeys));
2607 2608 2609
  if (distKeys == impl.m_noOfKeys)
    distKeys= 0;
  impl.m_noOfDistributionKeys= distKeys;
joreland@mysql.com's avatar
joreland@mysql.com committed
2610
  
2611
  for(i = 0; i<sz; i++){
2612 2613 2614 2615
    const NdbColumnImpl * col = impl.m_columns[i];
    if(col == 0)
      continue;
    
2616 2617
    DBUG_PRINT("info",("column: %s(%d) col->m_distributionKey: %d",
		       col->m_name.c_str(), i, col->m_distributionKey));
2618
    DictTabInfo::Attribute tmpAttr; tmpAttr.init();
2619
    BaseString::snprintf(tmpAttr.AttributeName, sizeof(tmpAttr.AttributeName), 
2620
	     col->m_name.c_str());
2621
    tmpAttr.AttributeId = col->m_attrId;
joreland@mysql.com's avatar
joreland@mysql.com committed
2622
    tmpAttr.AttributeKeyFlag = col->m_pk;
2623
    tmpAttr.AttributeNullableFlag = col->m_nullable;
2624
    tmpAttr.AttributeDKey = distKeys ? (bool)col->m_distributionKey : 0;
2625

2626
    tmpAttr.AttributeExtType = (Uint32)col->m_type;
pekka@mysql.com's avatar
pekka@mysql.com committed
2627
    tmpAttr.AttributeExtPrecision = ((unsigned)col->m_precision & 0xFFFF);
2628 2629
    tmpAttr.AttributeExtScale = col->m_scale;
    tmpAttr.AttributeExtLength = col->m_length;
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
    if(col->m_storageType == NDB_STORAGETYPE_DISK)
      tmpAttr.AttributeArrayType = NDB_ARRAYTYPE_FIXED;
    else
      tmpAttr.AttributeArrayType = col->m_arrayType;

    if(col->m_pk)
      tmpAttr.AttributeStorageType = NDB_STORAGETYPE_MEMORY;      
    else
      tmpAttr.AttributeStorageType = col->m_storageType;

    if(col->getBlobType())
      tmpAttr.AttributeStorageType = NDB_STORAGETYPE_MEMORY;      
    
pekka@mysql.com's avatar
pekka@mysql.com committed
2643 2644
    // check type and compute attribute size and array size
    if (! tmpAttr.translateExtType()) {
2645
      m_error.code= 703;
pekka@mysql.com's avatar
pekka@mysql.com committed
2646 2647
      DBUG_RETURN(-1);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2648 2649
    // charset is defined exactly for char types
    if (col->getCharType() != (col->m_cs != NULL)) {
2650
      m_error.code= 703;
2651
      DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2652 2653
    }
    // primary key type check
2654 2655 2656 2657
    if (col->m_pk && 
        (err = NdbSqlUtil::check_column_for_pk(col->m_type, col->m_cs)))
    {
      m_error.code= err;
2658
      DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2659
    }
2660
    // distribution key not supported for Char attribute
2661
    if (distKeys && col->m_distributionKey && col->m_cs != NULL) {
2662 2663 2664 2665 2666 2667 2668 2669
      // we can allow this for non-var char where strxfrm does nothing
      if (col->m_type == NdbDictionary::Column::Char &&
          (col->m_cs->state & MY_CS_BINSORT))
        ;
      else {
        m_error.code= 745;
        DBUG_RETURN(-1);
      }
2670
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2671 2672 2673 2674
    // charset in upper half of precision
    if (col->getCharType()) {
      tmpAttr.AttributeExtPrecision |= (col->m_cs->number << 16);
    }
2675 2676

    tmpAttr.AttributeAutoIncrement = col->m_autoIncrement;
2677
    BaseString::snprintf(tmpAttr.AttributeDefaultValue, 
2678 2679 2680 2681 2682
	     sizeof(tmpAttr.AttributeDefaultValue),
	     col->m_defaultValue.c_str());
    s = SimpleProperties::pack(w, 
			       &tmpAttr,
			       DictTabInfo::AttributeMapping, 
joreland@mysql.com's avatar
joreland@mysql.com committed
2683
			       DictTabInfo::AttributeMappingSize, true);
2684 2685 2686
    w.add(DictTabInfo::AttributeEnd, 1);
  }

2687
  int ret;
2688
  
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2689
  LinearSectionPtr ptr[1];
2690 2691
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = m_buffer.length() / 4;
2692 2693 2694 2695 2696 2697 2698
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  if (alter) {
    tSignal.theVerId_signalNumber   = GSN_ALTER_TABLE_REQ;
    tSignal.theLength = AlterTableReq::SignalLength;

    AlterTableReq * req = CAST_PTR(AlterTableReq, tSignal.getDataPtrSend());
2699 2700 2701 2702
    
    req->senderRef = m_reference;
    req->senderData = 0;
    req->changeMask = impl.m_changeMask;
2703
    req->tableId = impl.m_id;
2704
    req->tableVersion = impl.m_version;;
2705 2706 2707 2708 2709

    int errCodes[] = { AlterTableRef::NotMaster, AlterTableRef::Busy, 0 };
    ret = dictSignal(&tSignal, ptr, 1,
		     0, // master
		     WAIT_ALTER_TAB_REQ,
2710
		     DICT_WAITFOR_TIMEOUT, 100,
2711
		     errCodes);
2712
    
2713 2714
    if(m_error.code == AlterTableRef::InvalidTableVersion) {
      // Clear caches and try again
2715
      DBUG_RETURN(INCOMPATIBLE_VERSION);
2716 2717
    }
  } else {
2718 2719
    tSignal.theVerId_signalNumber   = GSN_CREATE_TABLE_REQ;
    tSignal.theLength = CreateTableReq::SignalLength;
2720 2721 2722 2723 2724 2725 2726 2727

    CreateTableReq * req = CAST_PTR(CreateTableReq, tSignal.getDataPtrSend());
    req->senderRef = m_reference;
    req->senderData = 0;
    int errCodes[] = { CreateTableRef::Busy, CreateTableRef::NotMaster, 0 };
    ret = dictSignal(&tSignal, ptr, 1,
		     0, // master node
		     WAIT_CREATE_INDX_REQ,
2728
		     DICT_WAITFOR_TIMEOUT, 100,
2729 2730 2731
		     errCodes);
  }
  
2732
  DBUG_RETURN(ret);
2733 2734 2735 2736 2737 2738
}

void
NdbDictInterface::execCREATE_TABLE_CONF(NdbApiSignal * signal,
					LinearSectionPtr ptr[3])
{
2739 2740
  const CreateTableConf* const conf=
    CAST_CONSTPTR(CreateTableConf, signal->getDataPtr());
2741 2742 2743 2744
  m_buffer.grow(4 * 2); // 2 words
  Uint32* data = (Uint32*)m_buffer.get_data();
  data[0] = conf->tableId;
  data[1] = conf->tableVersion;
2745 2746 2747 2748
  m_waiter.signal(NO_WAIT);  
}

void
2749
NdbDictInterface::execCREATE_TABLE_REF(NdbApiSignal * sig,
2750 2751
				       LinearSectionPtr ptr[3])
{
2752
  const CreateTableRef* ref = CAST_CONSTPTR(CreateTableRef, sig->getDataPtr());
2753
  m_error.code= ref->errorCode;
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execALTER_TABLE_CONF(NdbApiSignal * signal,
                                       LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);
}

void
2766
NdbDictInterface::execALTER_TABLE_REF(NdbApiSignal * sig,
2767 2768
				      LinearSectionPtr ptr[3])
{
2769
  const AlterTableRef * ref = CAST_CONSTPTR(AlterTableRef, sig->getDataPtr());
2770
  m_error.code= ref->errorCode;
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);
}

/*****************************************************************
 * Drop table
 */
int
NdbDictionaryImpl::dropTable(const char * name)
{
2781 2782
  DBUG_ENTER("NdbDictionaryImpl::dropTable");
  DBUG_PRINT("enter",("name: %s", name));
2783
  ASSERT_NOT_MYSQLD;
2784 2785
  NdbTableImpl * tab = getTable(name);
  if(tab == 0){
2786
    DBUG_RETURN(-1);
2787 2788 2789 2790 2791
  }
  int ret = dropTable(* tab);
  // If table stored in cache is incompatible with the one in the kernel
  // we must clear the cache and try again
  if (ret == INCOMPATIBLE_VERSION) {
2792 2793 2794
    const BaseString internalTableName(m_ndb.internalize_table_name(name));
    DBUG_PRINT("info",("INCOMPATIBLE_VERSION internal_name: %s", internalTableName.c_str()));
    m_localHash.drop(internalTableName.c_str());
2795
    m_globalHash->lock();
2796
    m_globalHash->release(tab, 1);
2797
    m_globalHash->unlock();
2798
    DBUG_RETURN(dropTable(name));
2799
  }
2800
  
2801
  DBUG_RETURN(ret);
2802 2803 2804 2805 2806
}

int
NdbDictionaryImpl::dropTable(NdbTableImpl & impl)
{
joreland@mysql.com's avatar
joreland@mysql.com committed
2807
  int res;
2808 2809 2810 2811 2812
  const char * name = impl.getName();
  if(impl.m_status == NdbDictionary::Object::New){
    return dropTable(name);
  }

2813 2814
  if (impl.m_indexType != NdbDictionary::Object::TypeUndefined)
  {
2815
    m_receiver.m_error.code= 1228;
2816 2817 2818 2819
    return -1;
  }

  List list;
2820
  if ((res = listIndexes(list, impl.m_id)) == -1){
2821
    return -1;
joreland@mysql.com's avatar
joreland@mysql.com committed
2822
  }
2823 2824
  for (unsigned i = 0; i < list.count; i++) {
    const List::Element& element = list.elements[i];
joreland@mysql.com's avatar
joreland@mysql.com committed
2825 2826
    if ((res = dropIndex(element.name, name)) == -1)
    {
2827
      return -1;
joreland@mysql.com's avatar
joreland@mysql.com committed
2828
    }
2829
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
2830
  
pekka@mysql.com's avatar
pekka@mysql.com committed
2831
  if (impl.m_noOfBlobs != 0) {
joreland@mysql.com's avatar
joreland@mysql.com committed
2832
    if (dropBlobTables(impl) != 0){
pekka@mysql.com's avatar
pekka@mysql.com committed
2833
      return -1;
joreland@mysql.com's avatar
joreland@mysql.com committed
2834
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2835
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
2836
  
2837
  int ret = m_receiver.dropTable(impl);  
2838
  if(ret == 0 || m_error.code == 709 || m_error.code == 723){
2839
    const char * internalTableName = impl.m_internalName.c_str();
2840

joreland@mysql.com's avatar
joreland@mysql.com committed
2841
    
2842 2843
    m_localHash.drop(internalTableName);
    m_globalHash->lock();
2844
    m_globalHash->release(&impl, 1);
2845
    m_globalHash->unlock();
joreland@mysql.com's avatar
joreland@mysql.com committed
2846 2847

    return 0;
2848 2849 2850 2851 2852
  }
  
  return ret;
}

2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
int
NdbDictionaryImpl::dropTableGlobal(NdbTableImpl & impl)
{
  int res;
  const char * name = impl.getName();
  DBUG_ENTER("NdbDictionaryImpl::dropTableGlobal");
  DBUG_ASSERT(impl.m_status != NdbDictionary::Object::New);
  DBUG_ASSERT(impl.m_indexType == NdbDictionary::Object::TypeUndefined);

  List list;
  if ((res = listIndexes(list, impl.m_id)) == -1){
    ERR_RETURN(getNdbError(), -1);
  }
  for (unsigned i = 0; i < list.count; i++) {
    const List::Element& element = list.elements[i];
    NdbIndexImpl *idx= getIndexGlobal(element.name, impl);
    if (idx == NULL)
    {
      ERR_RETURN(getNdbError(), -1);
    }
    if ((res = dropIndexGlobal(*idx)) == -1)
    {
      releaseIndexGlobal(*idx, 1);
      ERR_RETURN(getNdbError(), -1);
    }
    releaseIndexGlobal(*idx, 1);
  }
  
  if (impl.m_noOfBlobs != 0) {
    if (dropBlobTables(impl) != 0){
      ERR_RETURN(getNdbError(), -1);
    }
  }
  
  int ret = m_receiver.dropTable(impl);  
  impl.m_status = NdbDictionary::Object::Invalid;
  if(ret == 0 || m_error.code == 709 || m_error.code == 723)
  {
    DBUG_RETURN(0);
  }
  
  ERR_RETURN(getNdbError(), ret);
}

pekka@mysql.com's avatar
pekka@mysql.com committed
2897 2898 2899
int
NdbDictionaryImpl::dropBlobTables(NdbTableImpl & t)
{
2900
  DBUG_ENTER("NdbDictionaryImpl::dropBlobTables");
pekka@mysql.com's avatar
pekka@mysql.com committed
2901 2902
  for (unsigned i = 0; i < t.m_columns.size(); i++) {
    NdbColumnImpl & c = *t.m_columns[i];
pekka@mysql.com's avatar
pekka@mysql.com committed
2903
    if (! c.getBlobType() || c.getPartSize() == 0)
pekka@mysql.com's avatar
pekka@mysql.com committed
2904
      continue;
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
    NdbTableImpl* bt = c.m_blobTable;
    if (bt == NULL) {
      DBUG_PRINT("info", ("col %s: blob table pointer is NULL",
                          c.m_name.c_str()));
      continue; // "force" mode on
    }
    // drop directly - by-pass cache
    int ret = m_receiver.dropTable(*c.m_blobTable);
    if (ret != 0) {
      DBUG_PRINT("info", ("col %s: blob table %s: error %d",
                 c.m_name.c_str(), bt->m_internalName.c_str(), m_error.code));
      if (! (ret == 709 || ret == 723)) // "force" mode on
2917
        ERR_RETURN(getNdbError(), -1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2918
    }
2919
    // leave c.m_blobTable defined
pekka@mysql.com's avatar
pekka@mysql.com committed
2920
  }
2921
  DBUG_RETURN(0);
pekka@mysql.com's avatar
pekka@mysql.com committed
2922 2923
}

2924 2925 2926 2927 2928 2929 2930 2931
int
NdbDictInterface::dropTable(const NdbTableImpl & impl)
{
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_DROP_TABLE_REQ;
  tSignal.theLength = DropTableReq::SignalLength;
  
2932
  DropTableReq * req = CAST_PTR(DropTableReq, tSignal.getDataPtrSend());
2933 2934
  req->senderRef = m_reference;
  req->senderData = 0;
2935
  req->tableId = impl.m_id;
2936 2937
  req->tableVersion = impl.m_version;

2938 2939 2940 2941 2942 2943 2944
  int errCodes[] =
    { DropTableRef::NoDropTableRecordAvailable,
      DropTableRef::NotMaster,
      DropTableRef::Busy, 0 };
  int r = dictSignal(&tSignal, 0, 0,
		     0, // master
		     WAIT_DROP_TAB_REQ, 
2945
		     DICT_WAITFOR_TIMEOUT, 100,
2946
		     errCodes);
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
  if(m_error.code == DropTableRef::InvalidTableVersion) {
    // Clear caches and try again
    return INCOMPATIBLE_VERSION;
  }
  return r;
}

void
NdbDictInterface::execDROP_TABLE_CONF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
2958
  DBUG_ENTER("NdbDictInterface::execDROP_TABLE_CONF");
2959 2960 2961
  //DropTableConf* const conf = CAST_CONSTPTR(DropTableConf, signal->getDataPtr());

  m_waiter.signal(NO_WAIT);  
2962
  DBUG_VOID_RETURN;
2963 2964 2965 2966 2967 2968
}

void
NdbDictInterface::execDROP_TABLE_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
2969
  DBUG_ENTER("NdbDictInterface::execDROP_TABLE_REF");
2970
  const DropTableRef* ref = CAST_CONSTPTR(DropTableRef, signal->getDataPtr());
2971
  m_error.code= ref->errorCode;
2972 2973
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
2974
  DBUG_VOID_RETURN;
2975 2976 2977
}

int
2978
NdbDictionaryImpl::invalidateObject(NdbTableImpl & impl)
2979 2980
{
  const char * internalTableName = impl.m_internalName.c_str();
2981 2982
  DBUG_ENTER("NdbDictionaryImpl::invalidateObject");
  DBUG_PRINT("enter", ("internal_name: %s", internalTableName));
2983

2984
  m_localHash.drop(internalTableName);
2985
  m_globalHash->lock();
2986
  m_globalHash->release(&impl, 1);
2987
  m_globalHash->unlock();
2988
  DBUG_RETURN(0);
2989 2990 2991
}

int
2992
NdbDictionaryImpl::removeCachedObject(NdbTableImpl & impl)
2993 2994
{
  const char * internalTableName = impl.m_internalName.c_str();
2995 2996
  DBUG_ENTER("NdbDictionaryImpl::removeCachedObject");
  DBUG_PRINT("enter", ("internal_name: %s", internalTableName));
2997 2998

  m_localHash.drop(internalTableName);  
2999
  m_globalHash->lock();
3000
  m_globalHash->release(&impl);
3001
  m_globalHash->unlock();
3002
  DBUG_RETURN(0);
3003 3004
}

3005 3006
int
NdbDictInterface::create_index_obj_from_table(NdbIndexImpl** dst,
3007
					      NdbTableImpl* tab,
3008 3009 3010
					      const NdbTableImpl* prim)
{
  DBUG_ENTER("NdbDictInterface::create_index_obj_from_table");
3011
  NdbIndexImpl *idx = new NdbIndexImpl();
3012 3013
  idx->m_version = tab->m_version;
  idx->m_status = tab->m_status;
3014
  idx->m_id = tab->m_id;
3015
  idx->m_externalName.assign(tab->getName());
3016
  idx->m_tableName.assign(prim->m_externalName);
3017
  NdbDictionary::Object::Type type = idx->m_type = tab->m_indexType;
3018
  idx->m_logging = tab->m_logging;
3019
  // skip last attribute (NDB$PK or NDB$TNODE)
3020 3021 3022 3023 3024 3025

  const Uint32 distKeys = prim->m_noOfDistributionKeys;
  Uint32 keyCount = (distKeys ? distKeys : prim->m_noOfKeys);

  unsigned i;
  for(i = 0; i+1<tab->m_columns.size(); i++){
3026 3027
    NdbColumnImpl* org = tab->m_columns[i];

3028 3029
    NdbColumnImpl* col = new NdbColumnImpl;
    // Copy column definition
3030
    *col = * org;
3031
    idx->m_columns.push_back(col);
3032

3033 3034 3035
    /**
     * reverse map
     */
3036 3037
    const NdbColumnImpl* primCol = prim->getColumn(col->getName());
    int key_id = primCol->getColumnNo();
3038 3039 3040 3041
    int fill = -1;
    idx->m_key_ids.fill(key_id, fill);
    idx->m_key_ids[key_id] = i;
    col->m_keyInfoPos = key_id;
3042

3043
    if(type == NdbDictionary::Object::OrderedIndex && 
3044 3045
       (primCol->m_distributionKey ||
	(distKeys == 0 && primCol->getPrimaryKey())))
3046
    {
3047 3048
      keyCount--;
      org->m_distributionKey = 1;
3049
    }
3050
  }
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060

  if(keyCount == 0)
  {
    tab->m_noOfDistributionKeys = (distKeys ? distKeys : prim->m_noOfKeys);
  }
  else 
  {
    for(i = 0; i+1<tab->m_columns.size(); i++)
      tab->m_columns[i]->m_distributionKey = 0;
  }
3061

jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
3062 3063 3064
  idx->m_table_id = prim->getObjectId();
  idx->m_table_version = prim->getObjectVersion();
  
3065
  * dst = idx;
3066 3067
  DBUG_PRINT("exit", ("m_id: %d  m_version: %d", idx->m_id, idx->m_version));
  DBUG_RETURN(0);
3068 3069 3070 3071 3072 3073 3074 3075
}

/*****************************************************************
 * Create index
 */
int
NdbDictionaryImpl::createIndex(NdbIndexImpl &ix)
{
3076
  ASSERT_NOT_MYSQLD;
3077 3078 3079 3080 3081 3082 3083 3084 3085
  NdbTableImpl* tab = getTable(ix.getTable());
  if(tab == 0){
    m_error.code = 4249;
    return -1;
  }
  
  return m_receiver.createIndex(m_ndb, ix, * tab);
}

3086 3087 3088 3089 3090 3091
int
NdbDictionaryImpl::createIndex(NdbIndexImpl &ix, NdbTableImpl &tab)
{
  return m_receiver.createIndex(m_ndb, ix, tab);
}

3092 3093
int 
NdbDictInterface::createIndex(Ndb & ndb,
3094
			      const NdbIndexImpl & impl, 
3095 3096 3097 3098
			      const NdbTableImpl & table)
{
  //validate();
  //aggregate();
3099
  unsigned i, err;
3100 3101 3102 3103 3104 3105
  UtilBufferWriter w(m_buffer);
  const size_t len = strlen(impl.m_externalName.c_str()) + 1;
  if(len > MAX_TAB_NAME_SIZE) {
    m_error.code = 4241;
    return -1;
  }
3106 3107 3108
  const BaseString internalName(
    ndb.internalize_index_name(&table, impl.getName()));
  w.add(DictTabInfo::TableName, internalName.c_str());
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
  w.add(DictTabInfo::TableLoggedFlag, impl.m_logging);

  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_CREATE_INDX_REQ;
  tSignal.theLength = CreateIndxReq::SignalLength;
  
  CreateIndxReq * const req = CAST_PTR(CreateIndxReq, tSignal.getDataPtrSend());
  
  req->setUserRef(m_reference);
  req->setConnectionPtr(0);
  req->setRequestType(CreateIndxReq::RT_USER);
  
  Uint32 it = getKernelConstant(impl.m_type,
				indexTypeMapping,
				DictTabInfo::UndefTableType);
  
  if(it == DictTabInfo::UndefTableType){
    m_error.code = 4250;
    return -1;
  }
  req->setIndexType((DictTabInfo::TableType) it);
  
3132
  req->setTableId(table.m_id);
3133 3134 3135
  req->setOnline(true);
  AttributeList attributeList;
  attributeList.sz = impl.m_columns.size();
3136
  for(i = 0; i<attributeList.sz; i++){
3137 3138 3139 3140 3141 3142
    const NdbColumnImpl* col = 
      table.getColumn(impl.m_columns[i]->m_name.c_str());
    if(col == 0){
      m_error.code = 4247;
      return -1;
    }
3143
    // Copy column definition  XXX must be wrong, overwrites
3144 3145
    *impl.m_columns[i] = *col;

pekka@mysql.com's avatar
pekka@mysql.com committed
3146 3147
    // index key type check
    if (it == DictTabInfo::UniqueHashIndex &&
3148 3149
        (err = NdbSqlUtil::check_column_for_hash_index(col->m_type, col->m_cs))
        ||
pekka@mysql.com's avatar
pekka@mysql.com committed
3150
        it == DictTabInfo::OrderedIndex &&
3151 3152 3153
        (err = NdbSqlUtil::check_column_for_ordered_index(col->m_type, col->m_cs)))
    {
      m_error.code = err;
pekka@mysql.com's avatar
pekka@mysql.com committed
3154 3155
      return -1;
    }
3156 3157
    // API uses external column number to talk to DICT
    attributeList.id[i] = col->m_column_no;
3158
  }
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
3159
  LinearSectionPtr ptr[2];
3160 3161 3162 3163 3164
  ptr[0].p = (Uint32*)&attributeList;
  ptr[0].sz = 1 + attributeList.sz;
  ptr[1].p = (Uint32*)m_buffer.get_data();
  ptr[1].sz = m_buffer.length() >> 2;                //BUG?

3165 3166 3167
  int errCodes[] = { CreateIndxRef::Busy, CreateIndxRef::NotMaster, 0 };
  return dictSignal(&tSignal, ptr, 2,
		    0, // master
3168
		    WAIT_CREATE_INDX_REQ,
3169
		    DICT_WAITFOR_TIMEOUT, 100,
3170
		    errCodes);
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
}

void
NdbDictInterface::execCREATE_INDX_CONF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);  
}

void
3181
NdbDictInterface::execCREATE_INDX_REF(NdbApiSignal * sig,
3182 3183
				      LinearSectionPtr ptr[3])
{
3184
  const CreateIndxRef* ref = CAST_CONSTPTR(CreateIndxRef, sig->getDataPtr());
3185
  m_error.code = ref->getErrorCode();
3186
  if(m_error.code == ref->NotMaster)
3187
    m_masterNodeId= ref->masterNodeId;
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
  m_waiter.signal(NO_WAIT);  
}

/*****************************************************************
 * Drop index
 */
int
NdbDictionaryImpl::dropIndex(const char * indexName, 
			     const char * tableName)
{
3198
  ASSERT_NOT_MYSQLD;
3199 3200 3201 3202 3203 3204 3205 3206 3207
  NdbIndexImpl * idx = getIndex(indexName, tableName);
  if (idx == 0) {
    m_error.code = 4243;
    return -1;
  }
  int ret = dropIndex(*idx, tableName);
  // If index stored in cache is incompatible with the one in the kernel
  // we must clear the cache and try again
  if (ret == INCOMPATIBLE_VERSION) {
3208
    const BaseString internalIndexName((tableName)
3209
      ?
3210
      m_ndb.internalize_index_name(getTable(tableName), indexName)
3211
      :
3212 3213 3214
      m_ndb.internalize_table_name(indexName)); // Index is also a table

    m_localHash.drop(internalIndexName.c_str());
3215
    m_globalHash->lock();
3216
    m_globalHash->release(idx->m_table, 1);
3217
    m_globalHash->unlock();
3218 3219
    return dropIndex(indexName, tableName);
  }
3220

3221 3222 3223 3224 3225 3226 3227
  return ret;
}

int
NdbDictionaryImpl::dropIndex(NdbIndexImpl & impl, const char * tableName)
{
  const char * indexName = impl.getName();
3228
  if (tableName || m_ndb.usingFullyQualifiedNames()) {
3229 3230 3231 3232 3233 3234 3235
    NdbTableImpl * timpl = impl.m_table;
    
    if (timpl == 0) {
      m_error.code = 709;
      return -1;
    }

3236
    const BaseString internalIndexName((tableName)
3237
      ?
3238
      m_ndb.internalize_index_name(getTable(tableName), indexName)
3239
      :
3240
      m_ndb.internalize_table_name(indexName)); // Index is also a table
3241 3242 3243 3244

    if(impl.m_status == NdbDictionary::Object::New){
      return dropIndex(indexName, tableName);
    }
3245

3246 3247 3248
    int ret= dropIndexGlobal(impl);
    if (ret == 0)
    {
3249
      m_globalHash->lock();
3250
      m_globalHash->release(impl.m_table, 1);
3251
      m_globalHash->unlock();
3252
      m_localHash.drop(internalIndexName.c_str());
3253 3254 3255 3256 3257 3258 3259 3260
    }
    return ret;
  }

  m_error.code = 4243;
  return -1;
}

3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
int
NdbDictionaryImpl::dropIndexGlobal(NdbIndexImpl & impl)
{
  DBUG_ENTER("NdbDictionaryImpl::dropIndexGlobal");
  int ret = m_receiver.dropIndex(impl, *impl.m_table);
  impl.m_status = NdbDictionary::Object::Invalid;
  if(ret == 0)
  {
    DBUG_RETURN(0);
  }
  ERR_RETURN(getNdbError(), ret);
}

3274 3275 3276 3277
int
NdbDictInterface::dropIndex(const NdbIndexImpl & impl, 
			    const NdbTableImpl & timpl)
{
3278 3279 3280
  DBUG_ENTER("NdbDictInterface::dropIndex");
  DBUG_PRINT("enter", ("indexId: %d  indexVersion: %d",
                       timpl.m_id, timpl.m_version));
3281 3282 3283 3284 3285 3286 3287 3288 3289 3290
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_DROP_INDX_REQ;
  tSignal.theLength = DropIndxReq::SignalLength;

  DropIndxReq * const req = CAST_PTR(DropIndxReq, tSignal.getDataPtrSend());
  req->setUserRef(m_reference);
  req->setConnectionPtr(0);
  req->setRequestType(DropIndxReq::RT_USER);
  req->setTableId(~0);  // DICT overwrites
3291
  req->setIndexId(timpl.m_id);
3292 3293
  req->setIndexVersion(timpl.m_version);

3294 3295 3296
  int errCodes[] = { DropIndxRef::Busy, DropIndxRef::NotMaster, 0 };
  int r = dictSignal(&tSignal, 0, 0,
		     0, // master
3297
		     WAIT_DROP_INDX_REQ,
3298
		     DICT_WAITFOR_TIMEOUT, 100,
3299
		     errCodes);
3300 3301
  if(m_error.code == DropIndxRef::InvalidIndexVersion) {
    // Clear caches and try again
3302
    ERR_RETURN(m_error, INCOMPATIBLE_VERSION);
3303
  }
3304
  ERR_RETURN(m_error, r);
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
}

void
NdbDictInterface::execDROP_INDX_CONF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execDROP_INDX_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
3318
  const DropIndxRef* ref = CAST_CONSTPTR(DropIndxRef, signal->getDataPtr());
3319
  m_error.code = ref->getErrorCode();
3320
  if(m_error.code == ref->NotMaster)
3321
    m_masterNodeId= ref->masterNodeId;
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
  m_waiter.signal(NO_WAIT);  
}

/*****************************************************************
 * Create event
 */

int
NdbDictionaryImpl::createEvent(NdbEventImpl & evnt)
{
3332
  DBUG_ENTER("NdbDictionaryImpl::createEvent");
3333
  int i;
3334 3335 3336 3337 3338 3339 3340
  NdbTableImpl* tab= evnt.m_tableImpl;
  if (tab == 0)
  {
    tab= getTable(evnt.getTableName());
    if(tab == 0){
      DBUG_PRINT("info",("NdbDictionaryImpl::createEvent: table not found: %s",
			 evnt.getTableName()));
3341
      ERR_RETURN(getNdbError(), -1);
3342
    }
3343
    evnt.setTable(tab);
3344 3345
  }

3346
  DBUG_PRINT("info",("Table: id: %d version: %d", tab->m_id, tab->m_version));
3347

3348 3349 3350 3351
  NdbTableImpl &table = *evnt.m_tableImpl;

  int attributeList_sz = evnt.m_attrIds.size();

3352
  for (i = 0; i < attributeList_sz; i++) {
3353 3354 3355 3356 3357
    NdbColumnImpl *col_impl = table.getColumn(evnt.m_attrIds[i]);
    if (col_impl) {
      evnt.m_facade->addColumn(*(col_impl->m_facade));
    } else {
      ndbout_c("Attr id %u in table %s not found", evnt.m_attrIds[i],
3358 3359
	       evnt.getTableName());
      m_error.code= 4713;
3360
      ERR_RETURN(getNdbError(), -1);
3361 3362 3363 3364 3365 3366
    }
  }

  evnt.m_attrIds.clear();

  attributeList_sz = evnt.m_columns.size();
3367 3368

  DBUG_PRINT("info",("Event on tableId=%d, tableVersion=%d, event name %s, no of columns %d",
3369
		     table.m_id, table.m_version,
3370 3371 3372
		     evnt.m_name.c_str(),
		     evnt.m_columns.size()));

3373 3374 3375
  int pk_count = 0;
  evnt.m_attrListBitmask.clear();

3376
  for(i = 0; i<attributeList_sz; i++){
3377 3378 3379
    const NdbColumnImpl* col = 
      table.getColumn(evnt.m_columns[i]->m_name.c_str());
    if(col == 0){
3380
      m_error.code= 4247;
3381
      ERR_RETURN(getNdbError(), -1);
3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
    }
    // Copy column definition
    *evnt.m_columns[i] = *col;
    
    if(col->m_pk){
      pk_count++;
    }
    
    evnt.m_attrListBitmask.set(col->m_attrId);
  }
  
  // Sort index attributes according to primary table (using insertion sort)
3394
  for(i = 1; i < attributeList_sz; i++) {
3395 3396 3397 3398 3399 3400 3401 3402 3403
    NdbColumnImpl* temp = evnt.m_columns[i];
    unsigned int j = i;
    while((j > 0) && (evnt.m_columns[j - 1]->m_attrId > temp->m_attrId)) {
      evnt.m_columns[j] = evnt.m_columns[j - 1];
      j--;
    }
    evnt.m_columns[j] = temp;
  }
  // Check for illegal duplicate attributes
3404
  for(i = 1; i<attributeList_sz; i++) {
3405
    if (evnt.m_columns[i-1]->m_attrId == evnt.m_columns[i]->m_attrId) {
3406
      m_error.code= 4258;
3407
      ERR_RETURN(getNdbError(), -1);
3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
    }
  }
  
#ifdef EVENT_DEBUG
  char buf[128] = {0};
  evnt.m_attrListBitmask.getText(buf);
  ndbout_c("createEvent: mask = %s", buf);
#endif

  // NdbDictInterface m_receiver;
3418
  if (m_receiver.createEvent(m_ndb, evnt, 0 /* getFlag unset */) != 0)
3419
    ERR_RETURN(getNdbError(), -1);
3420 3421 3422 3423 3424 3425

  // Create blob events
  if (evnt.m_mergeEvents && createBlobEvents(evnt) != 0) {
    int save_code = m_error.code;
    (void)dropEvent(evnt.m_name.c_str());
    m_error.code = save_code;
3426
    ERR_RETURN(getNdbError(), -1);
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
  }
  DBUG_RETURN(0);
}

int
NdbDictionaryImpl::createBlobEvents(NdbEventImpl& evnt)
{
  DBUG_ENTER("NdbDictionaryImpl::createBlobEvents");
  NdbTableImpl& t = *evnt.m_tableImpl;
  Uint32 n = t.m_noOfBlobs;
  Uint32 i;
  for (i = 0; i < evnt.m_columns.size() && n > 0; i++) {
    NdbColumnImpl & c = *evnt.m_columns[i];
    if (! c.getBlobType() || c.getPartSize() == 0)
      continue;
    n--;
    NdbEventImpl blob_evnt;
    NdbBlob::getBlobEvent(blob_evnt, &evnt, &c);
    if (createEvent(blob_evnt) != 0)
3446
      ERR_RETURN(getNdbError(), -1);
3447 3448
  }
  DBUG_RETURN(0);
3449 3450 3451 3452 3453 3454 3455
}

int
NdbDictInterface::createEvent(class Ndb & ndb,
			      NdbEventImpl & evnt,
			      int getFlag)
{
3456 3457 3458
  DBUG_ENTER("NdbDictInterface::createEvent");
  DBUG_PRINT("enter",("getFlag=%d",getFlag));

3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_CREATE_EVNT_REQ;
  if (getFlag)
    tSignal.theLength = CreateEvntReq::SignalLengthGet;
  else
    tSignal.theLength = CreateEvntReq::SignalLengthCreate;

  CreateEvntReq * const req = CAST_PTR(CreateEvntReq, tSignal.getDataPtrSend());
  
  req->setUserRef(m_reference);
  req->setUserData(0);

  if (getFlag) {
    // getting event from Dictionary
    req->setRequestType(CreateEvntReq::RT_USER_GET);
  } else {
3476
    DBUG_PRINT("info",("tableId: %u tableVersion: %u",
3477 3478
		       evnt.m_tableImpl->m_id, 
                       evnt.m_tableImpl->m_version));
3479 3480
    // creating event in Dictionary
    req->setRequestType(CreateEvntReq::RT_USER_CREATE);
3481 3482
    req->setTableId(evnt.m_tableImpl->m_id);
    req->setTableVersion(evnt.m_tableImpl->m_version);
3483 3484
    req->setAttrListBitmask(evnt.m_attrListBitmask);
    req->setEventType(evnt.mi_type);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3485 3486 3487 3488 3489
    req->clearFlags();
    if (evnt.m_rep & NdbDictionary::Event::ER_ALL)
      req->setReportAll();
    if (evnt.m_rep & NdbDictionary::Event::ER_SUBSCRIBE)
      req->setReportSubscribe();
3490 3491 3492 3493
  }

  UtilBufferWriter w(m_buffer);

3494
  const size_t len = strlen(evnt.m_name.c_str()) + 1;
3495
  if(len > MAX_TAB_NAME_SIZE) {
3496
    m_error.code= 4241;
3497
    ERR_RETURN(getNdbError(), -1);
3498 3499
  }

3500
  w.add(SimpleProperties::StringValue, evnt.m_name.c_str());
3501 3502

  if (getFlag == 0)
3503 3504 3505
  {
    const BaseString internal_tabname(
      ndb.internalize_table_name(evnt.m_tableName.c_str()));
3506
    w.add(SimpleProperties::StringValue,
3507 3508
	 internal_tabname.c_str());
  }
3509

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
3510
  LinearSectionPtr ptr[1];
3511 3512 3513
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = (m_buffer.length()+3) >> 2;

3514 3515 3516
  int ret = dictSignal(&tSignal,ptr, 1,
		       0, // master
		       WAIT_CREATE_INDX_REQ,
3517
		       DICT_WAITFOR_TIMEOUT, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3518
		       0, -1);
3519 3520

  if (ret) {
3521
    ERR_RETURN(getNdbError(), ret);
3522
  }
3523
  
3524 3525 3526 3527 3528 3529 3530 3531
  char *dataPtr = (char *)m_buffer.get_data();
  unsigned int lenCreateEvntConf = *((unsigned int *)dataPtr);
  dataPtr += sizeof(lenCreateEvntConf);
  CreateEvntConf const * evntConf = (CreateEvntConf *)dataPtr;
  dataPtr += lenCreateEvntConf;
  
  //  NdbEventImpl *evntImpl = (NdbEventImpl *)evntConf->getUserData();

3532 3533 3534 3535 3536
  evnt.m_eventId = evntConf->getEventId();
  evnt.m_eventKey = evntConf->getEventKey();
  evnt.m_table_id = evntConf->getTableId();
  evnt.m_table_version = evntConf->getTableVersion();

3537 3538 3539 3540 3541
  if (getFlag) {
    evnt.m_attrListBitmask = evntConf->getAttrListBitmask();
    evnt.mi_type           = evntConf->getEventType();
    evnt.setTable(dataPtr);
  } else {
3542 3543
    if (evnt.m_tableImpl->m_id         != evntConf->getTableId() ||
	evnt.m_tableImpl->m_version    != evntConf->getTableVersion() ||
3544 3545 3546
	//evnt.m_attrListBitmask != evntConf->getAttrListBitmask() ||
	evnt.mi_type           != evntConf->getEventType()) {
      ndbout_c("ERROR*************");
3547
      ERR_RETURN(getNdbError(), 1);
3548 3549 3550
    }
  }

3551
  DBUG_RETURN(0);
3552 3553 3554
}

int
3555
NdbDictionaryImpl::executeSubscribeEvent(NdbEventOperationImpl & ev_op)
3556 3557
{
  // NdbDictInterface m_receiver;
3558
  return m_receiver.executeSubscribeEvent(m_ndb, ev_op);
3559 3560 3561 3562
}

int
NdbDictInterface::executeSubscribeEvent(class Ndb & ndb,
3563
					NdbEventOperationImpl & ev_op)
3564
{
3565
  DBUG_ENTER("NdbDictInterface::executeSubscribeEvent");
3566 3567 3568 3569 3570
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_SUB_START_REQ;
  tSignal.theLength = SubStartReq::SignalLength2;
  
3571
  SubStartReq * req = CAST_PTR(SubStartReq, tSignal.getDataPtrSend());
3572

3573 3574 3575 3576 3577
  req->subscriptionId   = ev_op.m_eventImpl->m_eventId;
  req->subscriptionKey  = ev_op.m_eventImpl->m_eventKey;
  req->part             = SubscriptionData::TableData;
  req->subscriberData   = ev_op.m_oid;
  req->subscriberRef    = m_reference;
3578

3579 3580 3581
  DBUG_PRINT("info",("GSN_SUB_START_REQ subscriptionId=%d,subscriptionKey=%d,"
		     "subscriberData=%d",req->subscriptionId,
		     req->subscriptionKey,req->subscriberData));
3582

3583
  DBUG_RETURN(dictSignal(&tSignal,NULL,0,
3584
			 0 /*use masternode id*/,
3585
			 WAIT_CREATE_INDX_REQ /*WAIT_CREATE_EVNT_REQ*/,
3586
			 -1, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3587
			 0, -1));
3588 3589 3590
}

int
3591
NdbDictionaryImpl::stopSubscribeEvent(NdbEventOperationImpl & ev_op)
3592 3593
{
  // NdbDictInterface m_receiver;
3594
  return m_receiver.stopSubscribeEvent(m_ndb, ev_op);
3595 3596 3597 3598
}

int
NdbDictInterface::stopSubscribeEvent(class Ndb & ndb,
3599
				     NdbEventOperationImpl & ev_op)
3600
{
3601
  DBUG_ENTER("NdbDictInterface::stopSubscribeEvent");
3602 3603 3604 3605 3606 3607 3608

  NdbApiSignal tSignal(m_reference);
  //  tSignal.theReceiversBlockNumber = SUMA;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_SUB_STOP_REQ;
  tSignal.theLength = SubStopReq::SignalLength;
  
3609
  SubStopReq * req = CAST_PTR(SubStopReq, tSignal.getDataPtrSend());
3610

3611 3612 3613 3614 3615
  req->subscriptionId  = ev_op.m_eventImpl->m_eventId;
  req->subscriptionKey = ev_op.m_eventImpl->m_eventKey;
  req->subscriberData  = ev_op.m_oid;
  req->part            = (Uint32) SubscriptionData::TableData;
  req->subscriberRef   = m_reference;
3616

3617 3618 3619
  DBUG_PRINT("info",("GSN_SUB_STOP_REQ subscriptionId=%d,subscriptionKey=%d,"
		     "subscriberData=%d",req->subscriptionId,
		     req->subscriptionKey,req->subscriberData));
3620

3621
  DBUG_RETURN(dictSignal(&tSignal,NULL,0,
3622
			 0 /*use masternode id*/,
3623
			 WAIT_CREATE_INDX_REQ /*WAIT_SUB_STOP__REQ*/,
3624
			 -1, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3625
			 0, -1));
3626 3627 3628
}

NdbEventImpl * 
3629
NdbDictionaryImpl::getEvent(const char * eventName, NdbTableImpl* tab)
3630
{
3631 3632
  DBUG_ENTER("NdbDictionaryImpl::getEvent");
  DBUG_PRINT("enter",("eventName= %s", eventName));
3633

3634
  NdbEventImpl *ev =  new NdbEventImpl();
3635
  if (ev == NULL) {
3636
    DBUG_RETURN(NULL);
3637 3638 3639 3640 3641 3642 3643 3644
  }

  ev->setName(eventName);

  int ret = m_receiver.createEvent(m_ndb, *ev, 1 /* getFlag set */);

  if (ret) {
    delete ev;
3645
    DBUG_RETURN(NULL);
3646 3647
  }

3648 3649 3650 3651 3652 3653
  // We only have the table name with internal name
  DBUG_PRINT("info",("table %s", ev->getTableName()));
  if (tab == NULL)
  {
    tab= fetchGlobalTableImplRef(InitTable(this, ev->getTableName()));
    if (tab == 0)
3654 3655 3656 3657 3658
    {
      DBUG_PRINT("error",("unable to find table %s", ev->getTableName()));
      delete ev;
      DBUG_RETURN(NULL);
    }
3659 3660 3661
    if ((tab->m_status != NdbDictionary::Object::Retrieved) ||
        (tab->m_id != ev->m_table_id) ||
        (table_version_major(tab->m_version) !=
3662
         table_version_major(ev->m_table_version)))
3663
    {
3664 3665 3666 3667
      DBUG_PRINT("info", ("mismatch on verison in cache"));
      releaseTableGlobal(*tab, 1);
      tab= fetchGlobalTableImplRef(InitTable(this, ev->getTableName()));
      if (tab == 0)
3668 3669 3670 3671 3672 3673
      {
        DBUG_PRINT("error",("unable to find table %s", ev->getTableName()));
        delete ev;
        DBUG_RETURN(NULL);
      }
    }
3674 3675
    ev->setTable(tab);
    releaseTableGlobal(*tab, 0);
3676
  }
3677 3678 3679
  else
    ev->setTable(tab);
  tab = 0;
3680

3681
  ev->setTable(m_ndb.externalizeTableName(ev->getTableName()));  
3682 3683 3684
  // get the columns from the attrListBitmask
  NdbTableImpl &table = *ev->m_tableImpl;
  AttributeMask & mask = ev->m_attrListBitmask;
3685
  unsigned attributeList_sz = mask.count();
3686

3687 3688
  DBUG_PRINT("info",("Table: id: %d version: %d", 
                     table.m_id, table.m_version));
3689

3690 3691 3692 3693 3694 3695 3696 3697
  if (table.m_id != ev->m_table_id ||
      table_version_major(table.m_version) !=
      table_version_major(ev->m_table_version))
  {
    m_error.code = 241;
    delete ev;
    DBUG_RETURN(NULL);
  }
3698
#ifndef DBUG_OFF
3699 3700
  char buf[128] = {0};
  mask.getText(buf);
3701 3702
  DBUG_PRINT("info",("attributeList_sz= %d, mask= %s", 
                     attributeList_sz, buf));
3703 3704
#endif

3705 3706 3707
  
  if ( attributeList_sz > table.getNoOfColumns() )
  {
3708
    m_error.code = 241;
3709 3710 3711 3712
    DBUG_PRINT("error",("Invalid version, too many columns"));
    delete ev;
    DBUG_RETURN(NULL);
  }
3713

3714 3715 3716 3717
  assert( (int)attributeList_sz <= table.getNoOfColumns() );
  for(unsigned id= 0; ev->m_columns.size() < attributeList_sz; id++) {
    if ( id >= table.getNoOfColumns())
    {
3718
      m_error.code = 241;
3719
      DBUG_PRINT("error",("Invalid version, column %d out of range", id));
3720
      delete ev;
3721
      DBUG_RETURN(NULL);
3722
    }
3723 3724 3725 3726 3727
    if (!mask.get(id))
      continue;

    const NdbColumnImpl* col = table.getColumn(id);
    DBUG_PRINT("info",("column %d %s", id, col->getName()));
3728 3729 3730 3731 3732
    NdbColumnImpl* new_col = new NdbColumnImpl;
    // Copy column definition
    *new_col = *col;
    ev->m_columns.push_back(new_col);
  }
3733
  DBUG_RETURN(ev);
3734 3735
}

3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
// ev is main event and has been retrieved previously
NdbEventImpl *
NdbDictionaryImpl::getBlobEvent(const NdbEventImpl& ev, uint col_no)
{
  DBUG_ENTER("NdbDictionaryImpl::getBlobEvent");
  DBUG_PRINT("enter", ("ev=%s col=%u", ev.m_name.c_str(), col_no));

  NdbTableImpl* tab = ev.m_tableImpl;
  assert(tab != NULL && col_no < tab->m_columns.size());
  NdbColumnImpl* col = tab->m_columns[col_no];
  assert(col != NULL && col->getBlobType() && col->getPartSize() != 0);
  NdbTableImpl* blob_tab = col->m_blobTable;
  assert(blob_tab != NULL);
  char bename[MAX_TAB_NAME_SIZE];
  NdbBlob::getBlobEventName(bename, &ev, col);

  NdbEventImpl* blob_ev = getEvent(bename, blob_tab);
  DBUG_RETURN(blob_ev);
}

3756 3757 3758 3759
void
NdbDictInterface::execCREATE_EVNT_CONF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
3760 3761
  DBUG_ENTER("NdbDictInterface::execCREATE_EVNT_CONF");

3762 3763 3764 3765 3766 3767 3768 3769 3770
  m_buffer.clear();
  unsigned int len = signal->getLength() << 2;
  m_buffer.append((char *)&len, sizeof(len));
  m_buffer.append(signal->getDataPtr(), len);

  if (signal->m_noOfSections > 0) {
    m_buffer.append((char *)ptr[0].p, strlen((char *)ptr[0].p)+1);
  }

3771 3772 3773 3774 3775 3776
  const CreateEvntConf * const createEvntConf=
    CAST_CONSTPTR(CreateEvntConf, signal->getDataPtr());

  Uint32 subscriptionId = createEvntConf->getEventId();
  Uint32 subscriptionKey = createEvntConf->getEventKey();

3777 3778
  DBUG_PRINT("info",("nodeid=%d,subscriptionId=%d,subscriptionKey=%d",
		     refToNode(signal->theSendersBlockRef),
3779
		     subscriptionId,subscriptionKey));
3780
  m_waiter.signal(NO_WAIT);
3781
  DBUG_VOID_RETURN;
3782 3783 3784 3785 3786 3787
}

void
NdbDictInterface::execCREATE_EVNT_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
3788
  DBUG_ENTER("NdbDictInterface::execCREATE_EVNT_REF");
3789

3790 3791 3792 3793 3794
  const CreateEvntRef* const ref=
    CAST_CONSTPTR(CreateEvntRef, signal->getDataPtr());
  m_error.code= ref->getErrorCode();
  DBUG_PRINT("error",("error=%d,line=%d,node=%d",ref->getErrorCode(),
		      ref->getErrorLine(),ref->getErrorNode()));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3795 3796
  if (m_error.code == CreateEvntRef::NotMaster)
    m_masterNodeId = ref->getMasterNode();
3797 3798
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
3799 3800 3801 3802 3803 3804
}

void
NdbDictInterface::execSUB_STOP_CONF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
3805 3806 3807
  DBUG_ENTER("NdbDictInterface::execSUB_STOP_CONF");
  const SubStopConf * const subStopConf=
    CAST_CONSTPTR(SubStopConf, signal->getDataPtr());
3808

3809 3810 3811
  Uint32 subscriptionId = subStopConf->subscriptionId;
  Uint32 subscriptionKey = subStopConf->subscriptionKey;
  Uint32 subscriberData = subStopConf->subscriberData;
3812

3813 3814
  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d",
		     subscriptionId,subscriptionKey,subscriberData));
3815
  m_waiter.signal(NO_WAIT);
3816
  DBUG_VOID_RETURN;
3817 3818 3819 3820 3821 3822
}

void
NdbDictInterface::execSUB_STOP_REF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
3823
  DBUG_ENTER("NdbDictInterface::execSUB_STOP_REF");
3824 3825
  const SubStopRef * const subStopRef=
    CAST_CONSTPTR(SubStopRef, signal->getDataPtr());
3826

3827 3828 3829 3830
  Uint32 subscriptionId = subStopRef->subscriptionId;
  Uint32 subscriptionKey = subStopRef->subscriptionKey;
  Uint32 subscriberData = subStopRef->subscriberData;
  m_error.code= subStopRef->errorCode;
3831

3832 3833
  DBUG_PRINT("error",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d,error=%d",
		      subscriptionId,subscriptionKey,subscriberData,m_error.code));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3834 3835
  if (m_error.code == SubStopRef::NotMaster)
    m_masterNodeId = subStopRef->m_masterNodeId;
3836
  m_waiter.signal(NO_WAIT);
3837
  DBUG_VOID_RETURN;
3838 3839 3840 3841 3842 3843
}

void
NdbDictInterface::execSUB_START_CONF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
3844 3845 3846
  DBUG_ENTER("NdbDictInterface::execSUB_START_CONF");
  const SubStartConf * const subStartConf=
    CAST_CONSTPTR(SubStartConf, signal->getDataPtr());
3847

3848 3849
  Uint32 subscriptionId = subStartConf->subscriptionId;
  Uint32 subscriptionKey = subStartConf->subscriptionKey;
3850
  SubscriptionData::Part part = 
3851 3852
    (SubscriptionData::Part)subStartConf->part;
  Uint32 subscriberData = subStartConf->subscriberData;
3853 3854 3855

  switch(part) {
  case SubscriptionData::MetaData: {
3856 3857
    DBUG_PRINT("error",("SubscriptionData::MetaData"));
    m_error.code= 1;
3858 3859 3860
    break;
  }
  case SubscriptionData::TableData: {
3861
    DBUG_PRINT("info",("SubscriptionData::TableData"));
3862 3863 3864
    break;
  }
  default: {
3865 3866
    DBUG_PRINT("error",("wrong data"));
    m_error.code= 2;
3867 3868 3869
    break;
  }
  }
3870 3871
  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d",
		     subscriptionId,subscriptionKey,subscriberData));
3872
  m_waiter.signal(NO_WAIT);
3873
  DBUG_VOID_RETURN;
3874 3875 3876 3877 3878 3879
}

void
NdbDictInterface::execSUB_START_REF(NdbApiSignal * signal,
				    LinearSectionPtr ptr[3])
{
3880 3881 3882 3883
  DBUG_ENTER("NdbDictInterface::execSUB_START_REF");
  const SubStartRef * const subStartRef=
    CAST_CONSTPTR(SubStartRef, signal->getDataPtr());
  m_error.code= subStartRef->errorCode;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3884 3885
  if (m_error.code == SubStartRef::NotMaster)
    m_masterNodeId = subStartRef->m_masterNodeId;
3886 3887
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
3888 3889 3890 3891 3892 3893 3894 3895
}

/*****************************************************************
 * Drop event
 */
int 
NdbDictionaryImpl::dropEvent(const char * eventName)
{
3896 3897
  DBUG_ENTER("NdbDictionaryImpl::dropEvent");
  DBUG_PRINT("info", ("name=%s", eventName));
3898

3899 3900 3901 3902 3903
  NdbEventImpl *evnt = getEvent(eventName); // allocated
  if (evnt == NULL) {
    if (m_error.code != 723 && // no such table
        m_error.code != 241)   // invalid table
      DBUG_RETURN(-1);
3904
    DBUG_PRINT("info", ("no table err=%d, drop by name alone", m_error.code));
3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
    evnt = new NdbEventImpl();
    evnt->setName(eventName);
  }
  int ret = dropEvent(*evnt);
  delete evnt;  
  DBUG_RETURN(ret);
}

int
NdbDictionaryImpl::dropEvent(const NdbEventImpl& evnt)
{
  if (dropBlobEvents(evnt) != 0)
    return -1;
  if (m_receiver.dropEvent(evnt) != 0)
    return -1;
  return 0;
}

int
NdbDictionaryImpl::dropBlobEvents(const NdbEventImpl& evnt)
{
  DBUG_ENTER("NdbDictionaryImpl::dropBlobEvents");
  if (evnt.m_tableImpl != 0) {
    const NdbTableImpl& t = *evnt.m_tableImpl;
    Uint32 n = t.m_noOfBlobs;
    Uint32 i;
    for (i = 0; i < evnt.m_columns.size() && n > 0; i++) {
      const NdbColumnImpl& c = *evnt.m_columns[i];
      if (! c.getBlobType() || c.getPartSize() == 0)
        continue;
      n--;
3936 3937 3938 3939
      NdbEventImpl* blob_evnt = getBlobEvent(evnt, i);
      if (blob_evnt == NULL)
        continue;
      (void)dropEvent(*blob_evnt);
3940
      delete blob_evnt;
3941 3942
    }
  } else {
3943 3944
    // loop over MAX_ATTRIBUTES_IN_TABLE ...
    Uint32 i;
3945 3946 3947
    DBUG_PRINT("info", ("missing table definition, looping over "
                        "MAX_ATTRIBUTES_IN_TABLE(%d)",
                        MAX_ATTRIBUTES_IN_TABLE));
3948 3949 3950 3951 3952 3953 3954 3955 3956
    for (i = 0; i < MAX_ATTRIBUTES_IN_TABLE; i++) {
      char bename[MAX_TAB_NAME_SIZE];
      // XXX should get name from NdbBlob
      sprintf(bename, "NDB$BLOBEVENT_%s_%u", evnt.getName(), i);
      NdbEventImpl* bevnt = new NdbEventImpl();
      bevnt->setName(bename);
      (void)m_receiver.dropEvent(*bevnt);
      delete bevnt;
    }
3957 3958
  }
  DBUG_RETURN(0);
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975
}

int
NdbDictInterface::dropEvent(const NdbEventImpl &evnt)
{
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_DROP_EVNT_REQ;
  tSignal.theLength = DropEvntReq::SignalLength;
  
  DropEvntReq * const req = CAST_PTR(DropEvntReq, tSignal.getDataPtrSend());

  req->setUserRef(m_reference);
  req->setUserData(0);

  UtilBufferWriter w(m_buffer);

3976
  w.add(SimpleProperties::StringValue, evnt.m_name.c_str());
3977 3978 3979 3980 3981

  LinearSectionPtr ptr[1];
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = (m_buffer.length()+3) >> 2;

3982 3983 3984 3985
  return dictSignal(&tSignal,ptr, 1,
		    0 /*use masternode id*/,
		    WAIT_CREATE_INDX_REQ,
		    -1, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3986
		    0, -1);
3987
}
3988

3989 3990 3991 3992
void
NdbDictInterface::execDROP_EVNT_CONF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
3993
  DBUG_ENTER("NdbDictInterface::execDROP_EVNT_CONF");
3994
  m_waiter.signal(NO_WAIT);  
3995
  DBUG_VOID_RETURN;
3996 3997 3998 3999 4000 4001
}

void
NdbDictInterface::execDROP_EVNT_REF(NdbApiSignal * signal,
				    LinearSectionPtr ptr[3])
{
4002 4003 4004 4005
  DBUG_ENTER("NdbDictInterface::execDROP_EVNT_REF");
  const DropEvntRef* const ref=
    CAST_CONSTPTR(DropEvntRef, signal->getDataPtr());
  m_error.code= ref->getErrorCode();
4006

4007 4008
  DBUG_PRINT("info",("ErrorCode=%u Errorline=%u ErrorNode=%u",
	     ref->getErrorCode(), ref->getErrorLine(), ref->getErrorNode()));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
4009 4010
  if (m_error.code == DropEvntRef::NotMaster)
    m_masterNodeId = ref->getMasterNode();
4011 4012
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024
}

/*****************************************************************
 * List objects or indexes
 */
int
NdbDictionaryImpl::listObjects(List& list, NdbDictionary::Object::Type type)
{
  ListTablesReq req;
  req.requestData = 0;
  req.setTableType(getKernelConstant(type, objectTypeMapping, 0));
  req.setListNames(true);
4025
  return m_receiver.listObjects(list, req.requestData, m_ndb.usingFullyQualifiedNames());
4026 4027 4028
}

int
joreland@mysql.com's avatar
joreland@mysql.com committed
4029
NdbDictionaryImpl::listIndexes(List& list, Uint32 indexId)
4030
{
4031
  ListTablesReq req;
4032
  req.requestData = 0;
joreland@mysql.com's avatar
joreland@mysql.com committed
4033
  req.setTableId(indexId);
4034 4035
  req.setListNames(true);
  req.setListIndexes(true);
4036
  return m_receiver.listObjects(list, req.requestData, m_ndb.usingFullyQualifiedNames());
4037 4038 4039 4040
}

int
NdbDictInterface::listObjects(NdbDictionary::Dictionary::List& list,
4041
			      Uint32 requestData, bool fullyQualifiedNames)
4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
{
  NdbApiSignal tSignal(m_reference);
  ListTablesReq* const req = CAST_PTR(ListTablesReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->requestData = requestData;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber = GSN_LIST_TABLES_REQ;
  tSignal.theLength = ListTablesReq::SignalLength;
  if (listObjects(&tSignal) != 0)
    return -1;
  // count
  const Uint32* data = (const Uint32*)m_buffer.get_data();
  const unsigned length = m_buffer.length() / 4;
  list.count = 0;
  bool ok = true;
  unsigned pos, count;
  pos = count = 0;
  while (pos < length) {
    // table id - name length - name
    pos++;
    if (pos >= length) {
      ok = false;
      break;
    }
    Uint32 n = (data[pos++] + 3) >> 2;
    pos += n;
    if (pos > length) {
      ok = false;
      break;
    }
    count++;
  }
  if (! ok) {
    // bad signal data
4077
    m_error.code= 4213;
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
    return -1;
  }
  list.count = count;
  list.elements = new NdbDictionary::Dictionary::List::Element[count];
  pos = count = 0;
  while (pos < length) {
    NdbDictionary::Dictionary::List::Element& element = list.elements[count];
    Uint32 d = data[pos++];
    element.id = ListTablesConf::getTableId(d);
    element.type = (NdbDictionary::Object::Type)
      getApiConstant(ListTablesConf::getTableType(d), objectTypeMapping, 0);
    element.state = (NdbDictionary::Object::State)
      getApiConstant(ListTablesConf::getTableState(d), objectStateMapping, 0);
    element.store = (NdbDictionary::Object::Store)
      getApiConstant(ListTablesConf::getTableStore(d), objectStoreMapping, 0);
    // table or index name
    Uint32 n = (data[pos++] + 3) >> 2;
    BaseString databaseName;
    BaseString schemaName;
    BaseString objectName;
    if ((element.type == NdbDictionary::Object::UniqueHashIndex) ||
	(element.type == NdbDictionary::Object::OrderedIndex)) {
      char * indexName = new char[n << 2];
      memcpy(indexName, &data[pos], n << 2);
      databaseName = Ndb::getDatabaseFromInternalName(indexName);
      schemaName = Ndb::getSchemaFromInternalName(indexName);
4104
      objectName = BaseString(Ndb::externalizeIndexName(indexName, fullyQualifiedNames));
4105 4106 4107 4108 4109 4110 4111
      delete [] indexName;
    } else if ((element.type == NdbDictionary::Object::SystemTable) || 
	       (element.type == NdbDictionary::Object::UserTable)) {
      char * tableName = new char[n << 2];
      memcpy(tableName, &data[pos], n << 2);
      databaseName = Ndb::getDatabaseFromInternalName(tableName);
      schemaName = Ndb::getSchemaFromInternalName(tableName);
4112
      objectName = BaseString(Ndb::externalizeTableName(tableName, fullyQualifiedNames));
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
      delete [] tableName;
    }
    else {
      char * otherName = new char[n << 2];
      memcpy(otherName, &data[pos], n << 2);
      objectName = BaseString(otherName);
      delete [] otherName;
    }
    element.database = new char[databaseName.length() + 1]; 
    strcpy(element.database, databaseName.c_str());
    element.schema = new char[schemaName.length() + 1]; 
    strcpy(element.schema, schemaName.c_str());
    element.name = new char[objectName.length() + 1]; 
    strcpy(element.name, objectName.c_str());
    pos += n;
    count++;
  }
  return 0;
}

int
NdbDictInterface::listObjects(NdbApiSignal* signal)
{
  const Uint32 RETRIES = 100;
  for (Uint32 i = 0; i < RETRIES; i++) {
    m_buffer.clear();
    // begin protected
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
4140 4141 4142 4143 4144 4145 4146
    /*
      The PollGuard has an implicit call of unlock_and_signal through the
      ~PollGuard method. This method is called implicitly by the compiler
      in all places where the object is out of context due to a return,
      break, continue or simply end of statement block
    */
    PollGuard poll_guard(m_transporter, &m_waiter, refToBlock(m_reference));
4147 4148
    Uint16 aNodeId = m_transporter->get_an_alive_node();
    if (aNodeId == 0) {
4149
      m_error.code= 4009;
4150 4151 4152 4153 4154
      return -1;
    }
    if (m_transporter->sendSignal(signal, aNodeId) != 0) {
      continue;
    }
4155
    m_error.code= 0;
4156
    int ret_val= poll_guard.wait_n_unlock(DICT_WAITFOR_TIMEOUT,
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
4157
                                          aNodeId, WAIT_LIST_TABLES_CONF);
4158
    // end protected
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
4159
    if (ret_val == 0 && m_error.code == 0)
4160
      return 0;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
4161
    if (ret_val == -2) //WAIT_NODE_FAILURE
4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
      continue;
    return -1;
  }
  return -1;
}

void
NdbDictInterface::execLIST_TABLES_CONF(NdbApiSignal* signal,
				       LinearSectionPtr ptr[3])
{
  const unsigned off = ListTablesConf::HeaderLength;
  const unsigned len = (signal->getLength() - off);
  m_buffer.append(signal->getDataPtr() + off, len << 2);
  if (signal->getLength() < ListTablesConf::SignalLength) {
    // last signal has less than full length
    m_waiter.signal(NO_WAIT);
  }
}
4180

4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215
int
NdbDictionaryImpl::forceGCPWait()
{
  return m_receiver.forceGCPWait();
}

int
NdbDictInterface::forceGCPWait()
{
  NdbApiSignal tSignal(m_reference);
  WaitGCPReq* const req = CAST_PTR(WaitGCPReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->requestType = WaitGCPReq::CompleteForceStart;
  tSignal.theReceiversBlockNumber = DBDIH;
  tSignal.theVerId_signalNumber = GSN_WAIT_GCP_REQ;
  tSignal.theLength = WaitGCPReq::SignalLength;

  const Uint32 RETRIES = 100;
  for (Uint32 i = 0; i < RETRIES; i++)
  {
    m_transporter->lock_mutex();
    Uint16 aNodeId = m_transporter->get_an_alive_node();
    if (aNodeId == 0) {
      m_error.code= 4009;
      m_transporter->unlock_mutex();
      return -1;
    }
    if (m_transporter->sendSignal(&tSignal, aNodeId) != 0) {
      m_transporter->unlock_mutex();
      continue;
    }
    m_error.code= 0;
    m_waiter.m_node = aNodeId;
    m_waiter.m_state = WAIT_LIST_TABLES_CONF;
4216
    m_waiter.wait(DICT_WAITFOR_TIMEOUT);
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239
    m_transporter->unlock_mutex();    
    return 0;
  }
  return -1;
}

void
NdbDictInterface::execWAIT_GCP_CONF(NdbApiSignal* signal,
				    LinearSectionPtr ptr[3])
{
  const WaitGCPConf * const conf=
    CAST_CONSTPTR(WaitGCPConf, signal->getDataPtr());
  g_latest_trans_gci= conf->gcp;
  m_waiter.signal(NO_WAIT);
}

void
NdbDictInterface::execWAIT_GCP_REF(NdbApiSignal* signal,
				    LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);
}

4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263
NdbFilegroupImpl::NdbFilegroupImpl(NdbDictionary::Object::Type t)
  : NdbDictObjectImpl(t)
{
  m_extent_size = 0;
  m_undo_buffer_size = 0;
  m_logfile_group_id = ~0;
  m_logfile_group_version = ~0;
}

NdbTablespaceImpl::NdbTablespaceImpl() : 
  NdbDictionary::Tablespace(* this), 
  NdbFilegroupImpl(NdbDictionary::Object::Tablespace), m_facade(this)
{
}

NdbTablespaceImpl::NdbTablespaceImpl(NdbDictionary::Tablespace & f) : 
  NdbDictionary::Tablespace(* this), 
  NdbFilegroupImpl(NdbDictionary::Object::Tablespace), m_facade(&f)
{
}

NdbTablespaceImpl::~NdbTablespaceImpl(){
}

4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
void
NdbTablespaceImpl::assign(const NdbTablespaceImpl& org)
{
  m_id = org.m_id;
  m_version = org.m_version;
  m_status = org.m_status;
  m_type = org.m_type;

  m_name.assign(org.m_name);
  m_grow_spec = org.m_grow_spec;
  m_extent_size = org.m_extent_size;
  m_undo_free_words = org.m_undo_free_words;
  m_logfile_group_id = org.m_logfile_group_id;
  m_logfile_group_version = org.m_logfile_group_version;
  m_logfile_group_name.assign(org.m_logfile_group_name);
  m_undo_free_words = org.m_undo_free_words;
}

4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
NdbLogfileGroupImpl::NdbLogfileGroupImpl() : 
  NdbDictionary::LogfileGroup(* this), 
  NdbFilegroupImpl(NdbDictionary::Object::LogfileGroup), m_facade(this)
{
}

NdbLogfileGroupImpl::NdbLogfileGroupImpl(NdbDictionary::LogfileGroup & f) : 
  NdbDictionary::LogfileGroup(* this), 
  NdbFilegroupImpl(NdbDictionary::Object::LogfileGroup), m_facade(&f)
{
}

NdbLogfileGroupImpl::~NdbLogfileGroupImpl(){
}

4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314
void
NdbLogfileGroupImpl::assign(const NdbLogfileGroupImpl& org)
{
  m_id = org.m_id;
  m_version = org.m_version;
  m_status = org.m_status;
  m_type = org.m_type;

  m_name.assign(org.m_name);
  m_grow_spec = org.m_grow_spec;
  m_extent_size = org.m_extent_size;
  m_undo_free_words = org.m_undo_free_words;
  m_logfile_group_id = org.m_logfile_group_id;
  m_logfile_group_version = org.m_logfile_group_version;
  m_logfile_group_name.assign(org.m_logfile_group_name);
  m_undo_free_words = org.m_undo_free_words;
}

4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338
NdbFileImpl::NdbFileImpl(NdbDictionary::Object::Type t)
  : NdbDictObjectImpl(t)
{
  m_size = 0;
  m_free = 0;
  m_filegroup_id = ~0;
  m_filegroup_version = ~0;
}

NdbDatafileImpl::NdbDatafileImpl() : 
  NdbDictionary::Datafile(* this), 
  NdbFileImpl(NdbDictionary::Object::Datafile), m_facade(this)
{
}

NdbDatafileImpl::NdbDatafileImpl(NdbDictionary::Datafile & f) : 
  NdbDictionary::Datafile(* this), 
  NdbFileImpl(NdbDictionary::Object::Datafile), m_facade(&f)
{
}

NdbDatafileImpl::~NdbDatafileImpl(){
}

4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354
void
NdbDatafileImpl::assign(const NdbDatafileImpl& org)
{
  m_id = org.m_id;
  m_version = org.m_version;
  m_status = org.m_status;
  m_type = org.m_type;

  m_size = org.m_size;
  m_free = org.m_free;
  m_filegroup_id = org.m_filegroup_id;
  m_filegroup_version = org.m_filegroup_version;
  m_path.assign(org.m_path);
  m_filegroup_name.assign(org.m_filegroup_name);
}

4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369
NdbUndofileImpl::NdbUndofileImpl() : 
  NdbDictionary::Undofile(* this), 
  NdbFileImpl(NdbDictionary::Object::Undofile), m_facade(this)
{
}

NdbUndofileImpl::NdbUndofileImpl(NdbDictionary::Undofile & f) : 
  NdbDictionary::Undofile(* this), 
  NdbFileImpl(NdbDictionary::Object::Undofile), m_facade(&f)
{
}

NdbUndofileImpl::~NdbUndofileImpl(){
}

4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385
void
NdbUndofileImpl::assign(const NdbUndofileImpl& org)
{
  m_id = org.m_id;
  m_version = org.m_version;
  m_status = org.m_status;
  m_type = org.m_type;

  m_size = org.m_size;
  m_free = org.m_free;
  m_filegroup_id = org.m_filegroup_id;
  m_filegroup_version = org.m_filegroup_version;
  m_path.assign(org.m_path);
  m_filegroup_name.assign(org.m_filegroup_name);
}

4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493
int 
NdbDictionaryImpl::createDatafile(const NdbDatafileImpl & file, bool force){
  DBUG_ENTER("NdbDictionaryImpl::createDatafile");
  NdbFilegroupImpl tmp(NdbDictionary::Object::Tablespace);
  if(file.m_filegroup_version != ~(Uint32)0){
    tmp.m_id = file.m_filegroup_id;
    tmp.m_version = file.m_filegroup_version;
    DBUG_RETURN(m_receiver.create_file(file, tmp));
  }
  
  
  if(m_receiver.get_filegroup(tmp, NdbDictionary::Object::Tablespace,
			      file.m_filegroup_name.c_str()) == 0){
    DBUG_RETURN(m_receiver.create_file(file, tmp, force));
  }
  DBUG_RETURN(-1); 
}

int
NdbDictionaryImpl::dropDatafile(const NdbDatafileImpl & file){
  return m_receiver.drop_file(file);
}

int
NdbDictionaryImpl::createUndofile(const NdbUndofileImpl & file, bool force){
  DBUG_ENTER("NdbDictionaryImpl::createUndofile");
  NdbFilegroupImpl tmp(NdbDictionary::Object::LogfileGroup);
  if(file.m_filegroup_version != ~(Uint32)0){
    tmp.m_id = file.m_filegroup_id;
    tmp.m_version = file.m_filegroup_version;
    DBUG_RETURN(m_receiver.create_file(file, tmp));
  }
  
  
  if(m_receiver.get_filegroup(tmp, NdbDictionary::Object::LogfileGroup,
			      file.m_filegroup_name.c_str()) == 0){
    DBUG_RETURN(m_receiver.create_file(file, tmp, force));
  }
  DBUG_PRINT("info", ("Failed to find filegroup"));
  DBUG_RETURN(-1);
}

int
NdbDictionaryImpl::dropUndofile(const NdbUndofileImpl & file){
  return m_receiver.drop_file(file);
}

int
NdbDictionaryImpl::createTablespace(const NdbTablespaceImpl & fg){
  return m_receiver.create_filegroup(fg);
}

int
NdbDictionaryImpl::dropTablespace(const NdbTablespaceImpl & fg){
  return m_receiver.drop_filegroup(fg);
}

int
NdbDictionaryImpl::createLogfileGroup(const NdbLogfileGroupImpl & fg){
 return m_receiver.create_filegroup(fg);
}

int
NdbDictionaryImpl::dropLogfileGroup(const NdbLogfileGroupImpl & fg){
  return m_receiver.drop_filegroup(fg);
}

int
NdbDictInterface::create_file(const NdbFileImpl & file,
			      const NdbFilegroupImpl & group,
			      bool overwrite){
  DBUG_ENTER("NdbDictInterface::create_file"); 
  UtilBufferWriter w(m_buffer);
  DictFilegroupInfo::File f; f.init();
  snprintf(f.FileName, sizeof(f.FileName), file.m_path.c_str());
  f.FileType = file.m_type;
  f.FilegroupId = group.m_id;
  f.FilegroupVersion = group.m_version;
  f.FileSizeHi = (file.m_size >> 32);
  f.FileSizeLo = (file.m_size & 0xFFFFFFFF);
  
  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
			     &f,
			     DictFilegroupInfo::FileMapping, 
			     DictFilegroupInfo::FileMappingSize, true);
  
  if(s != SimpleProperties::Eof){
    abort();
  }
  
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber = GSN_CREATE_FILE_REQ;
  tSignal.theLength = CreateFileReq::SignalLength;
  
  CreateFileReq* req = CAST_PTR(CreateFileReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->objType = file.m_type;
  req->requestInfo = 0;
  if (overwrite)
    req->requestInfo |= CreateFileReq::ForceCreateFile;
  
  LinearSectionPtr ptr[3];
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = m_buffer.length() / 4;

jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4494
  int err[] = { CreateFileRef::Busy, CreateFileRef::NotMaster, 0};
4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537
  /*
    Send signal without time-out since creating files can take a very long
    time if the file is very big.
  */
  DBUG_RETURN(dictSignal(&tSignal, ptr, 1,
	                 0, // master
		         WAIT_CREATE_INDX_REQ,
		         -1, 100,
		         err));
}

void
NdbDictInterface::execCREATE_FILE_CONF(NdbApiSignal * signal,
					    LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execCREATE_FILE_REF(NdbApiSignal * signal,
					   LinearSectionPtr ptr[3])
{
  const CreateFileRef* ref = 
    CAST_CONSTPTR(CreateFileRef, signal->getDataPtr());
  m_error.code = ref->errorCode;
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
}

int
NdbDictInterface::drop_file(const NdbFileImpl & file){
  DBUG_ENTER("NdbDictInterface::drop_file");
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber = GSN_DROP_FILE_REQ;
  tSignal.theLength = DropFileReq::SignalLength;
  
  DropFileReq* req = CAST_PTR(DropFileReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->file_id = file.m_id;
  req->file_version = file.m_version;

jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4538
  int err[] = { DropFileRef::Busy, DropFileRef::NotMaster, 0};
4539 4540 4541
  DBUG_RETURN(dictSignal(&tSignal, 0, 0,
	                 0, // master
		         WAIT_CREATE_INDX_REQ,
4542
		         DICT_WAITFOR_TIMEOUT, 100,
4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636
		         err));
}

void
NdbDictInterface::execDROP_FILE_CONF(NdbApiSignal * signal,
					    LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execDROP_FILE_REF(NdbApiSignal * signal,
					   LinearSectionPtr ptr[3])
{
  const DropFileRef* ref = 
    CAST_CONSTPTR(DropFileRef, signal->getDataPtr());
  m_error.code = ref->errorCode;
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
}

int
NdbDictInterface::create_filegroup(const NdbFilegroupImpl & group){
  DBUG_ENTER("NdbDictInterface::create_filegroup");
  UtilBufferWriter w(m_buffer);
  DictFilegroupInfo::Filegroup fg; fg.init();
  snprintf(fg.FilegroupName, sizeof(fg.FilegroupName), group.m_name.c_str());
  switch(group.m_type){
  case NdbDictionary::Object::Tablespace:
  {
    fg.FilegroupType = DictTabInfo::Tablespace;
    //fg.TS_DataGrow = group.m_grow_spec;
    fg.TS_ExtentSize = group.m_extent_size;

    if(group.m_logfile_group_version != ~(Uint32)0)
    {
      fg.TS_LogfileGroupId = group.m_logfile_group_id;
      fg.TS_LogfileGroupVersion = group.m_logfile_group_version;
    }
    else 
    {
      NdbLogfileGroupImpl tmp;
      if(get_filegroup(tmp, NdbDictionary::Object::LogfileGroup, 
		       group.m_logfile_group_name.c_str()) == 0)
      {
	fg.TS_LogfileGroupId = tmp.m_id;
	fg.TS_LogfileGroupVersion = tmp.m_version;
      }
      else // error set by get filegroup
      {
	DBUG_RETURN(-1);
      }
    }
  }
  break;
  case NdbDictionary::Object::LogfileGroup:
    fg.LF_UndoBufferSize = group.m_undo_buffer_size;
    fg.FilegroupType = DictTabInfo::LogfileGroup;
    //fg.LF_UndoGrow = group.m_grow_spec;
    break;
  default:
    abort();
    DBUG_RETURN(-1);
  };
  
  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
			     &fg,
			     DictFilegroupInfo::Mapping, 
			     DictFilegroupInfo::MappingSize, true);
  
  if(s != SimpleProperties::Eof){
    abort();
  }
  
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber = GSN_CREATE_FILEGROUP_REQ;
  tSignal.theLength = CreateFilegroupReq::SignalLength;
  
  CreateFilegroupReq* req = 
    CAST_PTR(CreateFilegroupReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->objType = fg.FilegroupType;
  
  LinearSectionPtr ptr[3];
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = m_buffer.length() / 4;

  int err[] = { CreateFilegroupRef::Busy, CreateFilegroupRef::NotMaster, 0};
  DBUG_RETURN(dictSignal(&tSignal, ptr, 1,
	                 0, // master
		         WAIT_CREATE_INDX_REQ,
4637
		         DICT_WAITFOR_TIMEOUT, 100,
4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676
		         err));
}

void
NdbDictInterface::execCREATE_FILEGROUP_CONF(NdbApiSignal * signal,
					    LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execCREATE_FILEGROUP_REF(NdbApiSignal * signal,
					   LinearSectionPtr ptr[3])
{
  const CreateFilegroupRef* ref = 
    CAST_CONSTPTR(CreateFilegroupRef, signal->getDataPtr());
  m_error.code = ref->errorCode;
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
}

int
NdbDictInterface::drop_filegroup(const NdbFilegroupImpl & group){
  DBUG_ENTER("NdbDictInterface::drop_filegroup");
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber = GSN_DROP_FILEGROUP_REQ;
  tSignal.theLength = DropFilegroupReq::SignalLength;
  
  DropFilegroupReq* req = CAST_PTR(DropFilegroupReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->filegroup_id = group.m_id;
  req->filegroup_version = group.m_version;
  
  int err[] = { DropFilegroupRef::Busy, DropFilegroupRef::NotMaster, 0};
  DBUG_RETURN(dictSignal(&tSignal, 0, 0,
                         0, // master
		         WAIT_CREATE_INDX_REQ,
4677
		         DICT_WAITFOR_TIMEOUT, 100,
4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703
		         err));
}

void
NdbDictInterface::execDROP_FILEGROUP_CONF(NdbApiSignal * signal,
					    LinearSectionPtr ptr[3])
{
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execDROP_FILEGROUP_REF(NdbApiSignal * signal,
					   LinearSectionPtr ptr[3])
{
  const DropFilegroupRef* ref = 
    CAST_CONSTPTR(DropFilegroupRef, signal->getDataPtr());
  m_error.code = ref->errorCode;
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
}


int
NdbDictInterface::get_filegroup(NdbFilegroupImpl & dst,
				NdbDictionary::Object::Type type,
				const char * name){
4704
  DBUG_ENTER("NdbDictInterface::get_filegroup");
4705 4706
  NdbApiSignal tSignal(m_reference);
  GetTabInfoReq * req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
4707

4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721
  size_t strLen = strlen(name) + 1;

  req->senderRef = m_reference;
  req->senderData = 0;
  req->requestType = 
    GetTabInfoReq::RequestByName | GetTabInfoReq::LongSignalConf;
  req->tableNameLen = strLen;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_GET_TABINFOREQ;
  tSignal.theLength = GetTabInfoReq::SignalLength;

  LinearSectionPtr ptr[1];
  ptr[0].p  = (Uint32*)name;
  ptr[0].sz = (strLen + 3)/4;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4722 4723 4724 4725 4726 4727 4728 4729
  
#ifndef IGNORE_VALGRIND_WARNINGS
  if (strLen & 3)
  {
    Uint32 pad = 0;
    m_buffer.clear();
    m_buffer.append(name, strLen);
    m_buffer.append(&pad, 4);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4730
    ptr[0].p = (Uint32*)m_buffer.get_data();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4731 4732 4733
  }
#endif
  
4734 4735 4736
  int r = dictSignal(&tSignal, ptr, 1,
		     -1, // any node
		     WAIT_GET_TAB_INFO_REQ,
4737
		     DICT_WAITFOR_TIMEOUT, 100);
4738 4739
  if (r)
  {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4740 4741 4742
    dst.m_id = -1;
    dst.m_version = ~0;
    
4743 4744 4745
    DBUG_PRINT("info", ("get_filegroup failed dictSignal"));
    DBUG_RETURN(-1);
  }
4746 4747 4748

  m_error.code = parseFilegroupInfo(dst,
				    (Uint32*)m_buffer.get_data(),
4749
				    m_buffer.length() / 4);
4750

4751 4752 4753 4754 4755 4756 4757
  if(m_error.code)
  {
    DBUG_PRINT("info", ("get_filegroup failed parseFilegroupInfo %d",
                         m_error.code));
    DBUG_RETURN(m_error.code);
  }

4758 4759 4760 4761 4762 4763 4764 4765 4766
  if(dst.m_type == NdbDictionary::Object::Tablespace)
  {
    NdbDictionary::LogfileGroup tmp;
    get_filegroup(NdbLogfileGroupImpl::getImpl(tmp),
		  NdbDictionary::Object::LogfileGroup,
		  dst.m_logfile_group_id);
    dst.m_logfile_group_name.assign(tmp.getName());
  }
  
4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
  if(dst.m_type == type)
  {
    DBUG_RETURN(0);
  }
  DBUG_PRINT("info", ("get_filegroup failed no such filegroup"));
  DBUG_RETURN(m_error.code = GetTabInfoRef::TableNotDefined);
}

int
NdbDictInterface::parseFilegroupInfo(NdbFilegroupImpl &dst,
				     const Uint32 * data, Uint32 len)
  
{
  SimplePropertiesLinearReader it(data, len);

  SimpleProperties::UnpackStatus status;
  DictFilegroupInfo::Filegroup fg; fg.init();
  status = SimpleProperties::unpack(it, &fg, 
				    DictFilegroupInfo::Mapping, 
				    DictFilegroupInfo::MappingSize, 
				    true, true);
  
  if(status != SimpleProperties::Eof){
    return CreateFilegroupRef::InvalidFormat;
  }

  dst.m_id = fg.FilegroupId;
  dst.m_version = fg.FilegroupVersion;
  dst.m_type = (NdbDictionary::Object::Type)fg.FilegroupType;
  dst.m_status = NdbDictionary::Object::Retrieved;
  
  dst.m_name.assign(fg.FilegroupName);
  dst.m_extent_size = fg.TS_ExtentSize;
  dst.m_undo_buffer_size = fg.LF_UndoBufferSize;
  dst.m_logfile_group_id = fg.TS_LogfileGroupId;
  dst.m_logfile_group_version = fg.TS_LogfileGroupVersion;
4803 4804 4805
  dst.m_undo_free_words= ((Uint64)fg.LF_UndoFreeWordsHi << 32)
    | (fg.LF_UndoFreeWordsLo);

4806 4807 4808
  return 0;
}

4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828
int
NdbDictInterface::get_filegroup(NdbFilegroupImpl & dst,
				NdbDictionary::Object::Type type,
				Uint32 id){
  DBUG_ENTER("NdbDictInterface::get_filegroup");
  NdbApiSignal tSignal(m_reference);
  GetTabInfoReq * req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());

  req->senderRef = m_reference;
  req->senderData = 0;
  req->requestType =
    GetTabInfoReq::RequestById | GetTabInfoReq::LongSignalConf;
  req->tableId = id;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_GET_TABINFOREQ;
  tSignal.theLength = GetTabInfoReq::SignalLength;

  int r = dictSignal(&tSignal, NULL, 1,
		     -1, // any node
		     WAIT_GET_TAB_INFO_REQ,
4829
		     DICT_WAITFOR_TIMEOUT, 100);
4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854
  if (r)
  {
    DBUG_PRINT("info", ("get_filegroup failed dictSignal"));
    DBUG_RETURN(-1);
  }

  m_error.code = parseFilegroupInfo(dst,
				    (Uint32*)m_buffer.get_data(),
				    m_buffer.length() / 4);

  if(m_error.code)
  {
    DBUG_PRINT("info", ("get_filegroup failed parseFilegroupInfo %d",
                         m_error.code));
    DBUG_RETURN(m_error.code);
  }

  if(dst.m_type == type)
  {
    DBUG_RETURN(0);
  }
  DBUG_PRINT("info", ("get_filegroup failed no such filegroup"));
  DBUG_RETURN(m_error.code = GetTabInfoRef::TableNotDefined);
}

4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877
int
NdbDictInterface::get_file(NdbFileImpl & dst,
			   NdbDictionary::Object::Type type,
			   int node,
			   const char * name){
  DBUG_ENTER("NdbDictInterface::get_file");
  NdbApiSignal tSignal(m_reference);
  GetTabInfoReq * req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());

  size_t strLen = strlen(name) + 1;

  req->senderRef = m_reference;
  req->senderData = 0;
  req->requestType =
    GetTabInfoReq::RequestByName | GetTabInfoReq::LongSignalConf;
  req->tableNameLen = strLen;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_GET_TABINFOREQ;
  tSignal.theLength = GetTabInfoReq::SignalLength;

  LinearSectionPtr ptr[1];
  ptr[0].p  = (Uint32*)name;
  ptr[0].sz = (strLen + 3)/4;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4878 4879 4880 4881 4882 4883 4884 4885
  
#ifndef IGNORE_VALGRIND_WARNINGS
  if (strLen & 3)
  {
    Uint32 pad = 0;
    m_buffer.clear();
    m_buffer.append(name, strLen);
    m_buffer.append(&pad, 4);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4886
    ptr[0].p = (Uint32*)m_buffer.get_data();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4887 4888 4889
  }
#endif
  
4890 4891 4892
  int r = dictSignal(&tSignal, ptr, 1,
		     node,
		     WAIT_GET_TAB_INFO_REQ,
4893
		     DICT_WAITFOR_TIMEOUT, 100);
4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910
  if (r)
  {
    DBUG_PRINT("info", ("get_file failed dictSignal"));
    DBUG_RETURN(-1);
  }

  m_error.code = parseFileInfo(dst,
			       (Uint32*)m_buffer.get_data(),
			       m_buffer.length() / 4);

  if(m_error.code)
  {
    DBUG_PRINT("info", ("get_file failed parseFileInfo %d",
                         m_error.code));
    DBUG_RETURN(m_error.code);
  }

4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930
  if(dst.m_type == NdbDictionary::Object::Undofile)
  {
    NdbDictionary::LogfileGroup tmp;
    get_filegroup(NdbLogfileGroupImpl::getImpl(tmp),
		  NdbDictionary::Object::LogfileGroup,
		  dst.m_filegroup_id);
    dst.m_filegroup_name.assign(tmp.getName());
  }
  else if(dst.m_type == NdbDictionary::Object::Datafile)
  {
    NdbDictionary::Tablespace tmp;
    get_filegroup(NdbTablespaceImpl::getImpl(tmp),
		  NdbDictionary::Object::Tablespace,
		  dst.m_filegroup_id);
    dst.m_filegroup_name.assign(tmp.getName());
    dst.m_free *= tmp.getExtentSize();
  }
  else
    dst.m_filegroup_name.assign("Not Yet Implemented");
  
4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956
  if(dst.m_type == type)
  {
    DBUG_RETURN(0);
  }
  DBUG_PRINT("info", ("get_file failed no such file"));
  DBUG_RETURN(m_error.code = GetTabInfoRef::TableNotDefined);
}

int
NdbDictInterface::parseFileInfo(NdbFileImpl &dst,
				const Uint32 * data, Uint32 len)
{
  SimplePropertiesLinearReader it(data, len);

  SimpleProperties::UnpackStatus status;
  DictFilegroupInfo::File f; f.init();
  status = SimpleProperties::unpack(it, &f,
				    DictFilegroupInfo::FileMapping,
				    DictFilegroupInfo::FileMappingSize,
				    true, true);

  if(status != SimpleProperties::Eof){
    return CreateFilegroupRef::InvalidFormat;
  }

  dst.m_type= (NdbDictionary::Object::Type)f.FileType;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
4957 4958
  dst.m_id= f.FileId;
  dst.m_version = f.FileVersion;
4959 4960 4961

  dst.m_size= ((Uint64)f.FileSizeHi << 32) | (f.FileSizeLo);
  dst.m_path.assign(f.FileName);
4962

4963 4964
  dst.m_filegroup_id= f.FilegroupId;
  dst.m_filegroup_version= f.FilegroupVersion;
4965
  dst.m_free=  f.FileFreeExtents;
4966 4967 4968
  return 0;
}

4969
template class Vector<int>;
4970
template class Vector<Uint16>;
4971 4972
template class Vector<Uint32>;
template class Vector<Vector<Uint32> >;
4973 4974
template class Vector<NdbTableImpl*>;
template class Vector<NdbColumnImpl*>;
4975

4976 4977 4978 4979 4980 4981 4982 4983 4984 4985
const NdbDictionary::Column * NdbDictionary::Column::FRAGMENT = 0;
const NdbDictionary::Column * NdbDictionary::Column::FRAGMENT_MEMORY = 0;
const NdbDictionary::Column * NdbDictionary::Column::ROW_COUNT = 0;
const NdbDictionary::Column * NdbDictionary::Column::COMMIT_COUNT = 0;
const NdbDictionary::Column * NdbDictionary::Column::ROW_SIZE = 0;
const NdbDictionary::Column * NdbDictionary::Column::RANGE_NO = 0;
const NdbDictionary::Column * NdbDictionary::Column::DISK_REF = 0;
const NdbDictionary::Column * NdbDictionary::Column::RECORDS_IN_RANGE = 0;
const NdbDictionary::Column * NdbDictionary::Column::ROWID = 0;
const NdbDictionary::Column * NdbDictionary::Column::ROW_GCI = 0;