NdbDictionaryImpl.cpp 127 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 47 48 49

#define DEBUG_PRINT 0
#define INCOMPATIBLE_VERSION -2

50 51
extern Uint64 g_latest_trans_gci;

52 53 54 55 56 57
//#define EVENT_DEBUG

/**
 * Column
 */
NdbColumnImpl::NdbColumnImpl()
58
  : NdbDictionary::Column(* this), m_attrId(-1), m_facade(this)
59 60 61 62 63
{
  init();
}

NdbColumnImpl::NdbColumnImpl(NdbDictionary::Column & f)
64
  : NdbDictionary::Column(* this), m_attrId(-1), m_facade(&f)
65 66 67 68
{
  init();
}

mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
69 70
NdbColumnImpl&
NdbColumnImpl::operator=(const NdbColumnImpl& col)
71 72 73 74 75
{
  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
76
  m_cs = col.m_cs;
77 78 79 80 81 82 83 84 85 86
  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;
87 88
  m_arrayType = col.m_arrayType;
  m_storageType = col.m_storageType;
89
  m_keyInfoPos = col.m_keyInfoPos;
90 91 92 93 94 95
  if (col.m_blobTable == NULL)
    m_blobTable = NULL;
  else {
    m_blobTable = new NdbTableImpl();
    m_blobTable->assign(*col.m_blobTable);
  }
96
  m_column_no = col.m_column_no;
97 98 99 100 101 102
  // Do not copy m_facade !!

  return *this;
}

void
103
NdbColumnImpl::init(Type t)
104
{
pekka@mysql.com's avatar
pekka@mysql.com committed
105 106
  // do not use default_charset_info as it may not be initialized yet
  // use binary collation until NDB tests can handle charsets
107
  CHARSET_INFO* default_cs = &my_charset_bin;
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  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
125
    m_cs = NULL;
126
    m_arrayType = NDB_ARRAYTYPE_FIXED;
127
    break;
128 129
  case Olddecimal:
  case Olddecimalunsigned:
130 131
  case Decimal:
  case Decimalunsigned:
132 133 134
    m_precision = 10;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
135
    m_cs = NULL;
136
    m_arrayType = NDB_ARRAYTYPE_FIXED;
137 138
    break;
  case Char:
139 140 141 142 143 144
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = default_cs;
    m_arrayType = NDB_ARRAYTYPE_FIXED;
    break;
145 146 147 148
  case Varchar:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
149
    m_cs = default_cs;
150
    m_arrayType = NDB_ARRAYTYPE_SHORT_VAR;
151 152
    break;
  case Binary:
153 154 155 156 157 158
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
    m_arrayType = NDB_ARRAYTYPE_FIXED;
    break;
159
  case Varbinary:
160 161 162 163 164 165
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
    m_arrayType = NDB_ARRAYTYPE_SHORT_VAR;
    break;
166
  case Datetime:
167
  case Date:
168 169 170
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
pekka@mysql.com's avatar
pekka@mysql.com committed
171
    m_cs = NULL;
172
    m_arrayType = NDB_ARRAYTYPE_FIXED;
173 174 175 176 177
    break;
  case Blob:
    m_precision = 256;
    m_scale = 8000;
    m_length = 4;
pekka@mysql.com's avatar
pekka@mysql.com committed
178
    m_cs = NULL;
179
    m_arrayType = NDB_ARRAYTYPE_FIXED;
180 181 182 183 184
    break;
  case Text:
    m_precision = 256;
    m_scale = 8000;
    m_length = 4;
pekka@mysql.com's avatar
pekka@mysql.com committed
185
    m_cs = default_cs;
186
    m_arrayType = NDB_ARRAYTYPE_FIXED;
187
    break;
188
  case Time:
189 190
  case Year:
  case Timestamp:
191 192 193 194
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
195
    m_arrayType = NDB_ARRAYTYPE_FIXED;
196
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
197 198 199 200 201
  case Bit:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
202
    m_arrayType = NDB_ARRAYTYPE_FIXED;
pekka@mysql.com's avatar
pekka@mysql.com committed
203 204 205 206 207 208
    break;
  case Longvarchar:
    m_precision = 0;
    m_scale = 0;
    m_length = 1; // legal
    m_cs = default_cs;
209
    m_arrayType = NDB_ARRAYTYPE_MEDIUM_VAR;
pekka@mysql.com's avatar
pekka@mysql.com committed
210 211 212 213 214 215
    break;
  case Longvarbinary:
    m_precision = 0;
    m_scale = 0;
    m_length = 1; // legal
    m_cs = NULL;
216
    m_arrayType = NDB_ARRAYTYPE_MEDIUM_VAR;
pekka@mysql.com's avatar
pekka@mysql.com committed
217
    break;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
218
  default:
219
  case Undefined:
220
    assert(false);
221
    break;
222
  }
223 224 225 226
  m_pk = false;
  m_nullable = false;
  m_distributionKey = false;
  m_keyInfoPos = 0;
227 228 229
  // next 2 are set at run time
  m_attrSize = 0;
  m_arraySize = 0;
230 231
  m_autoIncrement = false;
  m_autoIncrementInitialValue = 1;
mskold@mysql.com's avatar
mskold@mysql.com committed
232
  m_blobTable = NULL;
233 234 235 236 237
  m_storageType = NDB_STORAGETYPE_MEMORY;
#ifdef VM_TRACE
  if(NdbEnv_GetEnv("NDB_DEFAULT_DISK", (char *)0, 0))
    m_storageType = NDB_STORAGETYPE_DISK;
#endif
238 239 240 241 242 243 244 245 246
}

NdbColumnImpl::~NdbColumnImpl()
{
}

bool
NdbColumnImpl::equal(const NdbColumnImpl& col) const 
{
247
  DBUG_ENTER("NdbColumnImpl::equal");
248
  if(strcmp(m_name.c_str(), col.m_name.c_str()) != 0){
249
    DBUG_RETURN(false);
250 251
  }
  if(m_type != col.m_type){
252
    DBUG_RETURN(false);
253 254
  }
  if(m_pk != col.m_pk){
255
    DBUG_RETURN(false);
256 257
  }
  if(m_nullable != col.m_nullable){
258
    DBUG_RETURN(false);
259
  }
260 261
  if (m_pk) {
    if ((bool)m_distributionKey != (bool)col.m_distributionKey) {
262
      DBUG_RETURN(false);
263 264
    }
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
265 266 267 268
  if (m_precision != col.m_precision ||
      m_scale != col.m_scale ||
      m_length != col.m_length ||
      m_cs != col.m_cs) {
269
    DBUG_RETURN(false);
270 271
  }
  if (m_autoIncrement != col.m_autoIncrement){
272
    DBUG_RETURN(false);
273 274
  }
  if(strcmp(m_defaultValue.c_str(), col.m_defaultValue.c_str()) != 0){
275
    DBUG_RETURN(false);
276
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
277

278 279 280 281
  if (m_arrayType != col.m_arrayType || m_storageType != col.m_storageType){
    DBUG_RETURN(false);
  }

282
  DBUG_RETURN(true);
283 284
}

joreland@mysql.com's avatar
joreland@mysql.com committed
285
NdbDictionary::Column *
286
NdbColumnImpl::create_pseudo(const char * name){
joreland@mysql.com's avatar
joreland@mysql.com committed
287 288 289 290 291
  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;
292 293
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 1;
294 295 296 297 298
  } 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
299 300 301
  } else if(!strcmp(name, "NDB$ROW_COUNT")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::ROW_COUNT;
302
    col->m_impl.m_attrSize = 8;
303
    col->m_impl.m_arraySize = 1;
joreland@mysql.com's avatar
joreland@mysql.com committed
304 305 306
  } else if(!strcmp(name, "NDB$COMMIT_COUNT")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::COMMIT_COUNT;
307
    col->m_impl.m_attrSize = 8;
308
    col->m_impl.m_arraySize = 1;
309 310 311 312 313
  } 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;
314 315 316 317 318
  } 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;
319 320 321 322 323
  } 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;
324 325 326 327 328
  } 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;
329 330 331 332 333 334 335 336 337 338 339
  } 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
340 341 342
  } else {
    abort();
  }
343
  col->m_impl.m_storageType = NDB_STORAGETYPE_MEMORY;
344
  return col;
345 346 347 348 349 350 351
}

/**
 * NdbTableImpl
 */

NdbTableImpl::NdbTableImpl()
352 353
  : NdbDictionary::Table(* this), 
    NdbDictObjectImpl(NdbDictionary::Object::UserTable), m_facade(this)
354 355 356 357 358
{
  init();
}

NdbTableImpl::NdbTableImpl(NdbDictionary::Table & f)
359 360
  : NdbDictionary::Table(* this), 
    NdbDictObjectImpl(NdbDictionary::Object::UserTable), m_facade(&f)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
{
  init();
}

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

void
NdbTableImpl::init(){
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
377
  m_changeMask= 0;
378
  m_id= RNIL;
379 380 381
  m_version = ~0;
  m_status = NdbDictionary::Object::Invalid;
  m_type = NdbDictionary::Object::TypeUndefined;
382
  m_primaryTableId= RNIL;
383 384 385 386
  m_internalName.clear();
  m_externalName.clear();
  m_newExternalName.clear();
  m_mysqlName.clear();
387
  m_frm.clear();
388
  m_newFrm.clear();
389 390 391 392 393 394 395 396 397
  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
398 399
  m_hashValueMask= 0;
  m_hashpointerValue= 0;
400
  m_linear_flag= true;
401 402 403
  m_primaryTable.clear();
  m_max_rows = 0;
  m_default_no_part_flag = 1;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
404
  m_logging= true;
405 406
  m_row_gci = true;
  m_row_checksum = true;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
407 408 409 410 411 412
  m_kvalue= 6;
  m_minLoadFactor= 78;
  m_maxLoadFactor= 80;
  m_keyLenInWords= 0;
  m_fragmentCount= 0;
  m_index= NULL;
413
  m_indexType= NdbDictionary::Object::TypeUndefined;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
414 415 416 417
  m_noOfKeys= 0;
  m_noOfDistributionKeys= 0;
  m_noOfBlobs= 0;
  m_replicaCount= 0;
418
  m_tablespace_name.clear();
419
  m_tablespace_id = ~0;
420
  m_tablespace_version = ~0;
421 422 423 424 425
}

bool
NdbTableImpl::equal(const NdbTableImpl& obj) const 
{
426
  DBUG_ENTER("NdbTableImpl::equal");
427 428 429
  if ((m_internalName.c_str() == NULL) || 
      (strcmp(m_internalName.c_str(), "") == 0) ||
      (obj.m_internalName.c_str() == NULL) || 
430 431
      (strcmp(obj.m_internalName.c_str(), "") == 0))
  {
432
    // Shallow equal
433 434
    if(strcmp(getName(), obj.getName()) != 0)
    {
435 436
      DBUG_PRINT("info",("name %s != %s",getName(),obj.getName()));
      DBUG_RETURN(false);    
437
    }
438 439 440
  }
  else
  {
441
    // Deep equal
442
    if(strcmp(m_internalName.c_str(), obj.m_internalName.c_str()) != 0)
443 444 445 446 447
    {
      DBUG_PRINT("info",("m_internalName %s != %s",
			 m_internalName.c_str(),obj.m_internalName.c_str()));
      DBUG_RETURN(false);
    }
448
  }
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  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));
477
    DBUG_RETURN(false);
478
  }
479 480 481 482
  if(m_columns.size() != obj.m_columns.size())
  {
    DBUG_PRINT("info",("m_columns.size %d != %d",m_columns.size(),
                       obj.m_columns.size()));
483
    DBUG_RETURN(false);
484 485
  }

486 487 488 489
  for(unsigned i = 0; i<obj.m_columns.size(); i++)
  {
    if(!m_columns[i]->equal(* obj.m_columns[i]))
    {
490 491
      DBUG_PRINT("info",("m_columns [%d] != [%d]",i,i));
      DBUG_RETURN(false);
492 493 494
    }
  }
  
495 496 497 498 499 500 501
  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);
  }

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
  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)
  {
518 519
    DBUG_PRINT("info",("m_logging %d != %d",m_logging,obj.m_logging));
    DBUG_RETURN(false);
520 521
  }

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
  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)
  {
537 538
    DBUG_PRINT("info",("m_kvalue %d != %d",m_kvalue,obj.m_kvalue));
    DBUG_RETURN(false);
539 540
  }

541 542 543 544
  if(m_minLoadFactor != obj.m_minLoadFactor)
  {
    DBUG_PRINT("info",("m_minLoadFactor %d != %d",m_minLoadFactor,
                        obj.m_minLoadFactor));
545
    DBUG_RETURN(false);
546 547
  }

548 549 550 551
  if(m_maxLoadFactor != obj.m_maxLoadFactor)
  {
    DBUG_PRINT("info",("m_maxLoadFactor %d != %d",m_maxLoadFactor,
                        obj.m_maxLoadFactor));
552
    DBUG_RETURN(false);
553
  }
554

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
  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);
    }
  }
608
  DBUG_RETURN(true);
609 610 611 612 613
}

void
NdbTableImpl::assign(const NdbTableImpl& org)
{
614 615
  /* m_changeMask intentionally not copied */
  m_primaryTableId = org.m_primaryTableId;
616
  m_internalName.assign(org.m_internalName);
617
  updateMysqlName();
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
618 619 620 621 622 623
  // 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);
624
  m_frm.assign(org.m_frm.get_data(), org.m_frm.length());
625 626 627 628 629 630 631 632 633
  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());
634

635 636 637 638 639
  m_fragmentType = org.m_fragmentType;
  /*
    m_columnHashMask, m_columnHash, m_hashValueMask, m_hashpointerValue
    is state calculated by computeAggregates and buildColumnHash
  */
640 641 642
  for(unsigned i = 0; i<org.m_columns.size(); i++){
    NdbColumnImpl * col = new NdbColumnImpl();
    const NdbColumnImpl * iorg = org.m_columns[i];
joreland@mysql.com's avatar
joreland@mysql.com committed
643
    (* col) = (* iorg);
644 645 646
    m_columns.push_back(col);
  }

647 648
  m_fragments = org.m_fragments;

649
  m_linear_flag = org.m_linear_flag;
650 651
  m_max_rows = org.m_max_rows;
  m_default_no_part_flag = org.m_default_no_part_flag;
652
  m_logging = org.m_logging;
653 654
  m_row_gci = org.m_row_gci;
  m_row_checksum = org.m_row_checksum;
655 656 657
  m_kvalue = org.m_kvalue;
  m_minLoadFactor = org.m_minLoadFactor;
  m_maxLoadFactor = org.m_maxLoadFactor;
658 659
  m_keyLenInWords = org.m_keyLenInWords;
  m_fragmentCount = org.m_fragmentCount;
660 661 662 663
  
  if (m_index != 0)
    delete m_index;
  m_index = org.m_index;
664 665 666 667
 
  m_primaryTable = org.m_primaryTable;
  m_indexType = org.m_indexType;

668
  m_noOfKeys = org.m_noOfKeys;
669
  m_noOfDistributionKeys = org.m_noOfDistributionKeys;
pekka@mysql.com's avatar
pekka@mysql.com committed
670
  m_noOfBlobs = org.m_noOfBlobs;
671
  m_replicaCount = org.m_replicaCount;
672

673
  m_id = org.m_id;
674 675
  m_version = org.m_version;
  m_status = org.m_status;
676 677 678 679

  m_tablespace_name = org.m_tablespace_name;
  m_tablespace_id= org.m_tablespace_id;
  m_tablespace_version = org.m_tablespace_version;
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
}

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();
}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
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--;
    }
  }
}

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
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;
}

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
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();
}

812 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 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
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();
}

881 882 883 884 885 886 887 888 889 890 891
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("");
}
892 893 894 895

void
NdbTableImpl::buildColumnHash(){
  const Uint32 size = m_columns.size();
896
  int i;
897
  for(i = 31; i >= 0; i--){
898 899 900 901 902 903 904 905
    if(((1 << i) & size) != 0){
      m_columnHashMask = (1 << (i + 1)) - 1;
      break;
    }
  }

  Vector<Uint32> hashValues;
  Vector<Vector<Uint32> > chains; chains.fill(size, hashValues);
906
  for(i = 0; i< (int) size; i++){
907 908 909 910 911 912 913 914 915 916 917 918 919
    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
920
  for(i = 0; i< (int) size; i++){
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    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
}
958 959 960 961

Uint32
NdbTableImpl::get_nodes(Uint32 hashValue, const Uint16 ** nodes) const
{
962 963 964 965
  Uint32 fragmentId;
  if(m_replicaCount == 0)
    return 0;
  switch (m_fragmentType)
966
  {
967 968 969 970 971
    case NdbDictionary::Object::FragAllSmall:
    case NdbDictionary::Object::FragAllMedium:
    case NdbDictionary::Object::FragAllLarge:
    case NdbDictionary::Object::FragSingle:
    case NdbDictionary::Object::DistrKeyLin:
972
    {
973
      fragmentId = hashValue & m_hashValueMask;
974 975 976
      if(fragmentId < m_hashpointerValue) 
        fragmentId = hashValue & ((m_hashValueMask << 1) + 1);
      break;
977
    }
978
    case NdbDictionary::Object::DistrKeyHash:
979
    {
980 981
      fragmentId = hashValue % m_fragmentCount;
      break;
982
    }
983 984 985 986 987 988 989 990
    default:
      return 0;
  }
  Uint32 pos = fragmentId * m_replicaCount;
  if (pos + m_replicaCount <= m_fragments.size())
  {
    *nodes = m_fragments.getBase()+pos;
    return m_replicaCount;
991 992 993
  }
  return 0;
}
994 995 996 997 998 999 1000
  
/**
 * NdbIndexImpl
 */

NdbIndexImpl::NdbIndexImpl() : 
  NdbDictionary::Index(* this), 
1001
  NdbDictObjectImpl(NdbDictionary::Object::OrderedIndex), m_facade(this)
1002
{
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1003
  init();
1004 1005 1006 1007
}

NdbIndexImpl::NdbIndexImpl(NdbDictionary::Index & f) : 
  NdbDictionary::Index(* this), 
1008
  NdbDictObjectImpl(NdbDictionary::Object::OrderedIndex), m_facade(&f)
1009
{
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1010 1011 1012 1013 1014
  init();
}

void NdbIndexImpl::init()
{
1015 1016
  m_id= RNIL;
  m_type= NdbDictionary::Object::TypeUndefined;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1017 1018
  m_logging= true;
  m_table= NULL;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
}

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();
}

1049 1050 1051 1052 1053 1054
const NdbTableImpl *
NdbIndexImpl::getIndexTable() const
{
  return m_table;
}

1055 1056 1057 1058 1059 1060
/**
 * NdbEventImpl
 */

NdbEventImpl::NdbEventImpl() : 
  NdbDictionary::Event(* this),
1061
  NdbDictObjectImpl(NdbDictionary::Object::TypeUndefined), m_facade(this)
1062
{
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1063
  init();
1064 1065 1066 1067
}

NdbEventImpl::NdbEventImpl(NdbDictionary::Event & f) : 
  NdbDictionary::Event(* this),
1068
  NdbDictObjectImpl(NdbDictionary::Object::TypeUndefined), m_facade(&f)
1069
{
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1070 1071 1072 1073 1074 1075 1076 1077 1078
  init();
}

void NdbEventImpl::init()
{
  m_eventId= RNIL;
  m_eventKey= RNIL;
  mi_type= 0;
  m_dur= NdbDictionary::Event::ED_UNDEFINED;
1079
  m_mergeEvents = false;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1080
  m_tableImpl= NULL;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1081
  m_rep= NdbDictionary::Event::ER_UPDATED;
1082 1083 1084 1085 1086 1087
}

NdbEventImpl::~NdbEventImpl()
{
  for (unsigned i = 0; i < m_columns.size(); i++)
    delete  m_columns[i];
1088 1089
  if (m_tableImpl)
    delete m_tableImpl;
1090 1091 1092 1093
}

void NdbEventImpl::setName(const char * name)
{
1094
  m_name.assign(name);
1095 1096
}

1097 1098
const char *NdbEventImpl::getName() const
{
1099
  return m_name.c_str();
1100 1101
}

1102 1103 1104
void 
NdbEventImpl::setTable(const NdbDictionary::Table& table)
{
1105
  setTable(&NdbTableImpl::getImpl(table));
1106 1107 1108
  m_tableName.assign(m_tableImpl->getName());
}

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
void 
NdbEventImpl::setTable(NdbTableImpl *tableImpl)
{
  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);
}

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

1128 1129 1130 1131 1132 1133
void 
NdbEventImpl::setTable(const char * table)
{
  m_tableName.assign(table);
}

1134 1135
const char *
NdbEventImpl::getTableName() const
1136 1137 1138 1139 1140 1141 1142
{
  return m_tableName.c_str();
}

void
NdbEventImpl::addTableEvent(const NdbDictionary::Event::TableEvent t =  NdbDictionary::Event::TE_ALL)
{
1143
  mi_type |= (unsigned)t;
1144 1145
}

1146 1147 1148 1149 1150 1151
bool
NdbEventImpl::getTableEvent(const NdbDictionary::Event::TableEvent t) const
{
  return (mi_type & (unsigned)t) == (unsigned)t;
}

1152
void
1153
NdbEventImpl::setDurability(NdbDictionary::Event::EventDurability d)
1154 1155 1156 1157
{
  m_dur = d;
}

1158 1159 1160 1161 1162 1163
NdbDictionary::Event::EventDurability
NdbEventImpl::getDurability() const
{
  return m_dur;
}

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
void
NdbEventImpl::setReport(NdbDictionary::Event::EventReport r)
{
  m_rep = r;
}

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

1176 1177 1178 1179 1180
int NdbEventImpl::getNoOfEventColumns() const
{
  return m_attrIds.size() + m_columns.size();
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
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;
}

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
/**
 * NdbDictionaryImpl
 */

NdbDictionaryImpl::NdbDictionaryImpl(Ndb &ndb)
  : NdbDictionary::Dictionary(* this), 
    m_facade(this), 
    m_receiver(m_error),
    m_ndb(ndb)
{
  m_globalHash = 0;
1215
  m_local_table_data_size= 0;
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
}

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

joreland@mysql.com's avatar
joreland@mysql.com committed
1229 1230
static int f_dictionary_count = 0;

1231 1232
NdbDictionaryImpl::~NdbDictionaryImpl()
{
1233
  NdbElement_t<Ndb_local_table_info> * curr = m_localHash.m_tableHash.getNext(0);
1234 1235 1236
  if(m_globalHash){
    while(curr != 0){
      m_globalHash->lock();
1237
      m_globalHash->release(curr->theData->m_table_impl);
1238
      Ndb_local_table_info::destroy(curr->theData);
1239 1240 1241 1242 1243
      m_globalHash->unlock();
      
      curr = m_localHash.m_tableHash.getNext(curr);
    }
    
1244
    m_globalHash->lock();
1245 1246
    if(--f_dictionary_count == 0){
      delete NdbDictionary::Column::FRAGMENT; 
1247
      delete NdbDictionary::Column::FRAGMENT_MEMORY;
1248 1249
      delete NdbDictionary::Column::ROW_COUNT;
      delete NdbDictionary::Column::COMMIT_COUNT;
1250
      delete NdbDictionary::Column::ROW_SIZE;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1251
      delete NdbDictionary::Column::RANGE_NO;
1252
      delete NdbDictionary::Column::DISK_REF;
1253
      delete NdbDictionary::Column::RECORDS_IN_RANGE;
1254 1255
      delete NdbDictionary::Column::ROWID;
      delete NdbDictionary::Column::ROW_GCI;
1256
      NdbDictionary::Column::FRAGMENT= 0;
1257
      NdbDictionary::Column::FRAGMENT_MEMORY= 0;
1258 1259
      NdbDictionary::Column::ROW_COUNT= 0;
      NdbDictionary::Column::COMMIT_COUNT= 0;
1260
      NdbDictionary::Column::ROW_SIZE= 0;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1261
      NdbDictionary::Column::RANGE_NO= 0;
1262
      NdbDictionary::Column::DISK_REF= 0;
1263
      NdbDictionary::Column::RECORDS_IN_RANGE= 0;
1264 1265
      NdbDictionary::Column::ROWID= 0;
      NdbDictionary::Column::ROW_GCI= 0;
1266
    }
1267
    m_globalHash->unlock();
1268 1269
  } else {
    assert(curr == 0);
joreland@mysql.com's avatar
joreland@mysql.com committed
1270
  }
1271 1272
}

1273
Ndb_local_table_info *
1274
NdbDictionaryImpl::fetchGlobalTableImpl(const BaseString& internalTableName)
1275 1276
{
  NdbTableImpl *impl;
1277

1278
  m_globalHash->lock();
1279
  impl = m_globalHash->get(internalTableName.c_str());
1280 1281 1282
  m_globalHash->unlock();

  if (impl == 0){
1283 1284
    impl = m_receiver.getTable(internalTableName,
			       m_ndb.usingFullyQualifiedNames());
1285
    m_globalHash->lock();
1286
    m_globalHash->put(internalTableName.c_str(), impl);
1287 1288 1289 1290 1291 1292 1293
    m_globalHash->unlock();
    
    if(impl == 0){
      return 0;
    }
  }

1294 1295
  Ndb_local_table_info *info=
    Ndb_local_table_info::create(impl, m_local_table_data_size);
1296

1297
  m_localHash.put(internalTableName.c_str(), info);
1298 1299 1300 1301 1302 1303

  m_ndb.theFirstTupleId[impl->getTableId()] = ~0;
  m_ndb.theLastTupleId[impl->getTableId()]  = ~0;
  
  return info;
}
1304

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
void
NdbDictionaryImpl::putTable(NdbTableImpl *impl)
{
  m_globalHash->lock();
  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);
  
  m_ndb.theFirstTupleId[impl->getTableId()] = ~0;
  m_ndb.theLastTupleId[impl->getTableId()]  = ~0;
}

joreland@mysql.com's avatar
joreland@mysql.com committed
1320
#if 0
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
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
1331
#endif
1332 1333 1334 1335 1336 1337

bool
NdbDictionaryImpl::setTransporter(class Ndb* ndb, 
				  class TransporterFacade * tf)
{
  m_globalHash = &tf->m_globalDictCache;
joreland@mysql.com's avatar
joreland@mysql.com committed
1338 1339 1340 1341
  if(m_receiver.setTransporter(ndb, tf)){
    m_globalHash->lock();
    if(f_dictionary_count++ == 0){
      NdbDictionary::Column::FRAGMENT= 
1342
	NdbColumnImpl::create_pseudo("NDB$FRAGMENT");
1343
      NdbDictionary::Column::FRAGMENT_MEMORY= 
1344
	NdbColumnImpl::create_pseudo("NDB$FRAGMENT_MEMORY");
joreland@mysql.com's avatar
joreland@mysql.com committed
1345
      NdbDictionary::Column::ROW_COUNT= 
1346
	NdbColumnImpl::create_pseudo("NDB$ROW_COUNT");
joreland@mysql.com's avatar
joreland@mysql.com committed
1347
      NdbDictionary::Column::COMMIT_COUNT= 
1348
	NdbColumnImpl::create_pseudo("NDB$COMMIT_COUNT");
1349
      NdbDictionary::Column::ROW_SIZE=
1350
	NdbColumnImpl::create_pseudo("NDB$ROW_SIZE");
1351
      NdbDictionary::Column::RANGE_NO= 
1352
	NdbColumnImpl::create_pseudo("NDB$RANGE_NO");
1353 1354
      NdbDictionary::Column::DISK_REF= 
	NdbColumnImpl::create_pseudo("NDB$DISK_REF");
1355 1356
      NdbDictionary::Column::RECORDS_IN_RANGE= 
	NdbColumnImpl::create_pseudo("NDB$RECORDS_IN_RANGE");
1357 1358 1359 1360
      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
1361 1362
    }
    m_globalHash->unlock();
1363
    return true;
joreland@mysql.com's avatar
joreland@mysql.com committed
1364
  }
1365
  return false;
1366 1367
}

1368 1369
NdbTableImpl *
NdbDictionaryImpl::getIndexTable(NdbIndexImpl * index,
1370 1371
				 NdbTableImpl * table)
{
1372 1373 1374
  const BaseString internalName(
    m_ndb.internalize_index_name(table, index->getName()));
  return getTable(m_ndb.externalizeTableName(internalName.c_str()));
1375 1376
}

1377
#if 0
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
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 ) {
1391
    m_error.code= 4105;
1392 1393 1394 1395 1396 1397 1398 1399 1400
    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;
}
1401
#endif
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 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 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488

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;
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
  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;
1513 1514 1515 1516 1517 1518
  case GSN_WAIT_GCP_CONF:
    tmp->execWAIT_GCP_CONF(signal, ptr);
    break;
  case GSN_WAIT_GCP_REF:
    tmp->execWAIT_GCP_REF(signal, ptr);
    break;
1519 1520 1521 1522 1523 1524
  default:
    abort();
  }
}

void
1525
NdbDictInterface::execNodeStatus(void* dictImpl, Uint32 aNode,
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
				 bool alive, bool nfCompleted)
{
  NdbDictInterface * tmp = (NdbDictInterface*)dictImpl;
  
  if(!alive && !nfCompleted){
    return;
  }
  
  if (!alive && nfCompleted){
    tmp->m_waiter.nodeFail(aNode);
  }
}

int
1540 1541 1542 1543 1544 1545
NdbDictInterface::dictSignal(NdbApiSignal* sig, 
			     LinearSectionPtr ptr[3], int secs,
			     int node_specification,
			     WaitSignalType wst,
			     int timeout, Uint32 RETRIES,
			     const int *errcodes, int temporaryMask)
1546
{
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1547
  DBUG_ENTER("NdbDictInterface::dictSignal");
1548
  DBUG_PRINT("enter", ("useMasterNodeId: %d", node_specification));
1549 1550 1551 1552
  for(Uint32 i = 0; i<RETRIES; i++){
    m_buffer.clear();

    // Protected area
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
1553 1554 1555 1556 1557 1558 1559
    /*
      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));
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
    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;
1571
    }
1572 1573
    DBUG_PRINT("info", ("node %d", node));
    if(node == 0){
1574
      m_error.code= 4009;
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1575
      DBUG_RETURN(-1);
1576
    }
1577 1578 1579 1580 1581 1582 1583
    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;
    }    
1584
    
1585
    m_error.code= 0;
1586
    int ret_val= poll_guard.wait_n_unlock(timeout, node, wst);
1587 1588
    // End of Protected area  
    
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
1589
    if(ret_val == 0 && m_error.code == 0){
1590
      // Normal return
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1591
      DBUG_RETURN(0);
1592 1593 1594 1595 1596
    }
    
    /**
     * Handle error codes
     */
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
1597
    if(ret_val == -2) //WAIT_NODE_FAILURE
1598
    {
1599
      continue;
1600
    }
1601 1602
    if(m_waiter.m_state == WST_WAIT_TIMEOUT)
    {
1603
      DBUG_PRINT("info", ("dictSignal caught time-out"));
1604 1605 1606 1607
      m_error.code = 4008;
      DBUG_RETURN(-1);
    }
    
1608 1609 1610 1611 1612 1613 1614
    if ( temporaryMask == -1)
    {
      const NdbError &error= getNdbError();
      if (error.status ==  NdbError::TemporaryError)
	continue;
    }
    else if ( (temporaryMask & m_error.code) != 0 ) {
1615 1616
      continue;
    }
1617 1618 1619 1620
    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
1621 1622
      int j;
      for(j = 0; errcodes[j] ; j++){
1623
	if(m_error.code == errcodes[j]){
1624
	  break;
1625
	}
1626
      }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1627
      if(errcodes[j]) // Accepted error code
1628 1629
	continue;
    }
1630
    break;
1631
  }
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
1632
  DBUG_RETURN(-1);
1633
}
1634
#if 0
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1635 1636 1637 1638 1639
/*
  Get dictionary information for a table using table id as reference

  DESCRIPTION
    Sends a GET_TABINFOREQ signal containing the table id
1640
 */
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1641
NdbTableImpl *
1642
NdbDictInterface::getTable(int tableId, bool fullyQualifiedNames)
1643 1644
{
  NdbApiSignal tSignal(m_reference);
1645 1646
  GetTabInfoReq * req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
  
1647 1648
  req->senderRef = m_reference;
  req->senderData = 0;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1649
  req->requestType =
1650 1651 1652 1653 1654
    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
1655

1656
  return getTable(&tSignal, 0, 0, fullyQualifiedNames);
1657
}
1658
#endif
1659

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1660 1661 1662 1663 1664 1665 1666 1667

/*
  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
*/
1668

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1669
NdbTableImpl *
1670
NdbDictInterface::getTable(const BaseString& name, bool fullyQualifiedNames)
1671 1672
{
  NdbApiSignal tSignal(m_reference);
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1673
  GetTabInfoReq* const req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
1674

1675 1676
  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
1677 1678 1679 1680

  req->senderRef= m_reference;
  req->senderData= 0;
  req->requestType=
1681
    GetTabInfoReq::RequestByName | GetTabInfoReq::LongSignalConf;
1682
  req->tableNameLen= namelen;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1683 1684 1685 1686
  tSignal.theReceiversBlockNumber= DBDICT;
  tSignal.theVerId_signalNumber= GSN_GET_TABINFOREQ;
  tSignal.theLength= GetTabInfoReq::SignalLength;

1687 1688 1689 1690 1691
  // Copy name to m_buffer to get a word sized buffer
  m_buffer.clear();
  m_buffer.grow(namelen_words*4);
  m_buffer.append(name.c_str(), namelen);

1692
  LinearSectionPtr ptr[1];
1693 1694
  ptr[0].p= (Uint32*)m_buffer.get_data();
  ptr[0].sz= namelen_words;
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1695

1696
  return getTable(&tSignal, ptr, 1, fullyQualifiedNames);
1697 1698
}

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

1700
NdbTableImpl *
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1701
NdbDictInterface::getTable(class NdbApiSignal * signal,
1702
			   LinearSectionPtr ptr[3],
1703
			   Uint32 noOfSections, bool fullyQualifiedNames)
1704
{
1705 1706 1707
  int errCodes[] = {GetTabInfoRef::Busy, 0 };
  int r = dictSignal(signal, ptr, noOfSections,
		     -1, // any node
1708
		     WAIT_GET_TAB_INFO_REQ,
1709
		     WAITFOR_RESPONSE_TIMEOUT, 100, errCodes);
1710

1711 1712 1713
  if (r)
    return 0;
  
1714
  NdbTableImpl * rt = 0;
1715 1716 1717 1718 1719 1720 1721
  m_error.code = parseTableInfo(&rt, 
				(Uint32*)m_buffer.get_data(), 
  				m_buffer.length() / 4, 
				fullyQualifiedNames);
  if(rt)
    rt->buildColumnHash();
  
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
  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])
{
1753 1754 1755
  const GetTabInfoRef* ref = CAST_CONSTPTR(GetTabInfoRef, 
					   signal->getDataPtr());
  
1756
  m_error.code= ref->errorCode;
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
  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 },
1803 1804 1805
  { DictTabInfo::DistrKeyHash,      NdbDictionary::Object::DistrKeyHash },
  { DictTabInfo::DistrKeyLin,      NdbDictionary::Object::DistrKeyLin },
  { DictTabInfo::UserDefined,      NdbDictionary::Object::UserDefined },
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
  { -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 },
1820 1821 1822 1823
  { DictTabInfo::Tablespace,         NdbDictionary::Object::Tablespace },
  { DictTabInfo::LogfileGroup,       NdbDictionary::Object::LogfileGroup },
  { DictTabInfo::Datafile,           NdbDictionary::Object::Datafile },
  { DictTabInfo::Undofile,           NdbDictionary::Object::Undofile },
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
  { -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
1834
  { DictTabInfo::StateBackup,        NdbDictionary::Object::StateBackup },
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
  { 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,
1857 1858
				 const Uint32 * data, Uint32 len,
				 bool fullyQualifiedNames)
1859 1860
{
  SimplePropertiesLinearReader it(data, len);
1861
  DictTabInfo::Table *tableDesc;
1862
  SimpleProperties::UnpackStatus s;
1863 1864 1865 1866 1867 1868 1869 1870 1871
  DBUG_ENTER("NdbDictInterface::parseTableInfo");

  tableDesc = (DictTabInfo::Table*)NdbMem_Allocate(sizeof(DictTabInfo::Table));
  if (!tableDesc)
  {
    DBUG_RETURN(4000);
  }
  tableDesc->init();
  s = SimpleProperties::unpack(it, tableDesc, 
1872 1873 1874 1875 1876
			       DictTabInfo::TableMapping, 
			       DictTabInfo::TableMappingSize, 
			       true, true);
  
  if(s != SimpleProperties::Break){
1877
    NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
1878
    DBUG_RETURN(703);
1879
  }
1880
  const char * internalName = tableDesc->TableName;
1881
  const char * externalName = Ndb::externalizeTableName(internalName, fullyQualifiedNames);
1882 1883

  NdbTableImpl * impl = new NdbTableImpl();
1884 1885
  impl->m_id = tableDesc->TableId;
  impl->m_version = tableDesc->TableVersion;
1886 1887
  impl->m_status = NdbDictionary::Object::Retrieved;
  impl->m_internalName.assign(internalName);
1888
  impl->updateMysqlName();
1889 1890
  impl->m_externalName.assign(externalName);

1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
  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.
  */
1905 1906
  
  impl->m_fragmentType = (NdbDictionary::Object::FragmentType)
1907
    getApiConstant(tableDesc->FragmentType, 
1908 1909 1910
		   fragmentTypeMapping, 
		   (Uint32)NdbDictionary::Object::FragUndefined);
  
1911 1912 1913 1914
  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;
1915
  impl->m_linear_flag = tableDesc->LinearHashFlag;
1916 1917 1918 1919 1920 1921
  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;
1922

1923
  impl->m_indexType = (NdbDictionary::Object::Type)
1924
    getApiConstant(tableDesc->TableType,
1925
		   indexTypeMapping,
1926
		   NdbDictionary::Object::TypeUndefined);
1927
  
1928
  if(impl->m_indexType == NdbDictionary::Object::TypeUndefined){
1929 1930
  } else {
    const char * externalPrimary = 
1931
      Ndb::externalizeTableName(tableDesc->PrimaryTable, fullyQualifiedNames);
1932 1933 1934
    impl->m_primaryTable.assign(externalPrimary);
  }
  
1935
  Uint32 i;
1936
  for(i = 0; i < tableDesc->NoOfAttributes; i++) {
1937 1938 1939 1940 1941 1942 1943 1944
    DictTabInfo::Attribute attrDesc; attrDesc.init();
    s = SimpleProperties::unpack(it, 
				 &attrDesc, 
				 DictTabInfo::AttributeMapping, 
				 DictTabInfo::AttributeMappingSize, 
				 true, true);
    if(s != SimpleProperties::Break){
      delete impl;
1945
      NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
1946
      DBUG_RETURN(703);
1947 1948 1949 1950 1951
    }
    
    NdbColumnImpl * col = new NdbColumnImpl();
    col->m_attrId = attrDesc.AttributeId;
    col->setName(attrDesc.AttributeName);
pekka@mysql.com's avatar
pekka@mysql.com committed
1952 1953 1954

    // check type and compute attribute size and array size
    if (! attrDesc.translateExtType()) {
1955
      delete impl;
1956
      NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
1957
      DBUG_RETURN(703);
1958
    }
1959
    col->m_type = (NdbDictionary::Column::Type)attrDesc.AttributeExtType;
pekka@mysql.com's avatar
pekka@mysql.com committed
1960
    col->m_precision = (attrDesc.AttributeExtPrecision & 0xFFFF);
1961 1962
    col->m_scale = attrDesc.AttributeExtScale;
    col->m_length = attrDesc.AttributeExtLength;
pekka@mysql.com's avatar
pekka@mysql.com committed
1963 1964 1965 1966 1967
    // 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;
1968
      NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
1969
      DBUG_RETURN(703);
pekka@mysql.com's avatar
pekka@mysql.com committed
1970 1971 1972 1973 1974
    }
    if (col->getCharType()) {
      col->m_cs = get_charset(cs_number, MYF(0));
      if (col->m_cs == NULL) {
        delete impl;
1975
        NdbMem_Free((void*)tableDesc);
pekka@mysql.com's avatar
pekka@mysql.com committed
1976
        DBUG_RETURN(743);
pekka@mysql.com's avatar
pekka@mysql.com committed
1977 1978
      }
    }
1979 1980
    col->m_attrSize = (1 << attrDesc.AttributeSize) / 8;
    col->m_arraySize = attrDesc.AttributeArraySize;
1981
    col->m_arrayType = attrDesc.AttributeArrayType;
1982 1983 1984 1985 1986
    if(attrDesc.AttributeSize == 0)
    {
      col->m_attrSize = 4;
      col->m_arraySize = (attrDesc.AttributeArraySize + 31) >> 5;
    }
1987
    col->m_storageType = attrDesc.AttributeStorageType;
1988 1989
    
    col->m_pk = attrDesc.AttributeKeyFlag;
1990
    col->m_distributionKey = attrDesc.AttributeDKey ? 2 : 0;
1991 1992 1993 1994 1995
    col->m_nullable = attrDesc.AttributeNullableFlag;
    col->m_autoIncrement = (attrDesc.AttributeAutoIncrement ? true : false);
    col->m_autoIncrementInitialValue = ~0;
    col->m_defaultValue.assign(attrDesc.AttributeDefaultValue);

1996 1997
    col->m_column_no = impl->m_columns.size();
    impl->m_columns.push_back(col);
1998 1999
    it.next();
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
2000

2001
  impl->computeAggregates();
2002

2003
  if(tableDesc->ReplicaDataLen > 0)
2004
  {
2005 2006
    Uint16 replicaCount = tableDesc->ReplicaData[0];
    Uint16 fragCount = tableDesc->ReplicaData[1];
2007

2008 2009
    impl->m_replicaCount = replicaCount;
    impl->m_fragmentCount = fragCount;
2010
    DBUG_PRINT("info", ("replicaCount=%x , fragCount=%x",replicaCount,fragCount));
2011
    for(i = 0; i < (Uint32) (fragCount*replicaCount); i++)
2012
    {
2013
      impl->m_fragments.push_back(tableDesc->ReplicaData[i+2]);
2014 2015 2016
    }

    Uint32 topBit = (1 << 31);
2017
    for(; topBit && !(fragCount & topBit); ){
2018 2019 2020 2021 2022 2023 2024
      topBit >>= 1;
    }
    impl->m_hashValueMask = topBit - 1;
    impl->m_hashpointerValue = fragCount - (impl->m_hashValueMask + 1);
  }
  else
  {
2025
    impl->m_fragmentCount = tableDesc->FragmentCount;
2026 2027 2028 2029 2030
    impl->m_replicaCount = 0;
    impl->m_hashValueMask = 0;
    impl->m_hashpointerValue = 0;
  }

2031 2032
  impl->m_tablespace_id = tableDesc->TablespaceId;
  impl->m_tablespace_version = tableDesc->TablespaceVersion;
2033
  
2034
  * ret = impl;
2035

2036
  NdbMem_Free((void*)tableDesc);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2037
  DBUG_ASSERT(impl->m_fragmentCount > 0);
pekka@mysql.com's avatar
pekka@mysql.com committed
2038
  DBUG_RETURN(0);
2039 2040 2041 2042 2043
}

/*****************************************************************
 * Create table and alter table
 */
pekka@mysql.com's avatar
pekka@mysql.com committed
2044 2045 2046
int
NdbDictionaryImpl::createTable(NdbTableImpl &t)
{ 
2047
  DBUG_ENTER("NdbDictionaryImpl::createTable");
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2048 2049 2050
  // If the a new name has not been set, used the copied name
  if (t.m_newExternalName.empty())
    t.m_newExternalName.assign(t.m_externalName);
pekka@mysql.com's avatar
pekka@mysql.com committed
2051
  if (m_receiver.createTable(m_ndb, t) != 0)
2052 2053 2054
  {
    DBUG_RETURN(-1);
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
2055
  if (t.m_noOfBlobs == 0)
2056 2057 2058
  {
    DBUG_RETURN(0);
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
2059
  // update table def from DICT
2060
  Ndb_local_table_info *info=
2061
    get_local_table_info(t.m_internalName,false);
2062
  if (info == NULL) {
2063
    m_error.code= 709;
2064
    DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2065
  }
2066
  if (createBlobTables(t, *(info->m_table_impl)) != 0) {
pekka@mysql.com's avatar
pekka@mysql.com committed
2067 2068
    int save_code = m_error.code;
    (void)dropTable(t);
2069
    m_error.code= save_code;
2070
    DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2071
  }
2072
  DBUG_RETURN(0);
pekka@mysql.com's avatar
pekka@mysql.com committed
2073 2074 2075
}

int
2076
NdbDictionaryImpl::createBlobTables(NdbTableImpl& org, NdbTableImpl &t)
pekka@mysql.com's avatar
pekka@mysql.com committed
2077
{
2078
  DBUG_ENTER("NdbDictionaryImpl::createBlobTables");
pekka@mysql.com's avatar
pekka@mysql.com committed
2079 2080
  for (unsigned i = 0; i < t.m_columns.size(); i++) {
    NdbColumnImpl & c = *t.m_columns[i];
2081
    NdbColumnImpl & oc = *org.m_columns[i];
pekka@mysql.com's avatar
pekka@mysql.com committed
2082
    if (! c.getBlobType() || c.getPartSize() == 0)
pekka@mysql.com's avatar
pekka@mysql.com committed
2083 2084
      continue;
    NdbTableImpl bt;
2085 2086
    NdbDictionary::Column::StorageType save = c.getStorageType();
    c.setStorageType(oc.getStorageType());
pekka@mysql.com's avatar
pekka@mysql.com committed
2087
    NdbBlob::getBlobTable(bt, &t, &c);
2088
    c.setStorageType(save);
pekka@mysql.com's avatar
pekka@mysql.com committed
2089
    if (createTable(bt) != 0)
2090 2091 2092
    {
      DBUG_RETURN(-1);
    }
mskold@mysql.com's avatar
mskold@mysql.com committed
2093
    // Save BLOB table handle
2094
    Ndb_local_table_info *info=
2095
      get_local_table_info(bt.m_internalName, false);
2096 2097 2098
    if (info == 0)
    {
      DBUG_RETURN(-1);
2099 2100
    }
    c.m_blobTable = info->m_table_impl;
pekka@mysql.com's avatar
pekka@mysql.com committed
2101
  }
2102
  DBUG_RETURN(0); 
mskold@mysql.com's avatar
mskold@mysql.com committed
2103 2104 2105 2106 2107
}

int
NdbDictionaryImpl::addBlobTables(NdbTableImpl &t)
{
2108
  unsigned n= t.m_noOfBlobs;
2109
  DBUG_ENTER("NdbDictionaryImpl::addBlobTables");
2110 2111 2112 2113
  // 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--;
mskold@mysql.com's avatar
mskold@mysql.com committed
2114 2115 2116
    NdbColumnImpl & c = *t.m_columns[i];
    if (! c.getBlobType() || c.getPartSize() == 0)
      continue;
2117
    n--;
2118
    char btname[NdbBlobImpl::BlobTableNameSize];
mskold@mysql.com's avatar
mskold@mysql.com committed
2119 2120
    NdbBlob::getBlobTableName(btname, &t, &c);
    // Save BLOB table handle
2121 2122
    NdbTableImpl * cachedBlobTable = getTable(btname);
    if (cachedBlobTable == 0) {
2123
      DBUG_RETURN(-1);
2124
    }
mskold@mysql.com's avatar
mskold@mysql.com committed
2125 2126
    c.m_blobTable = cachedBlobTable;
  }
2127
  DBUG_RETURN(0); 
pekka@mysql.com's avatar
pekka@mysql.com committed
2128 2129
}

2130 2131 2132 2133
int 
NdbDictInterface::createTable(Ndb & ndb,
			      NdbTableImpl & impl)
{
2134 2135
  DBUG_ENTER("NdbDictInterface::createTable");
  DBUG_RETURN(createOrAlterTable(ndb, impl, false));
2136 2137 2138 2139
}

int NdbDictionaryImpl::alterTable(NdbTableImpl &impl)
{
2140
  BaseString internalName(impl.m_internalName);
2141
  const char * originalInternalName = internalName.c_str();
2142 2143

  DBUG_ENTER("NdbDictionaryImpl::alterTable");
2144 2145 2146
  Ndb_local_table_info * local = 0;
  if((local= get_local_table_info(originalInternalName, false)) == 0)
  {
2147
    m_error.code = 709;
2148
    DBUG_RETURN(-1);
2149
  }
2150

2151 2152 2153 2154
  // Alter the table
  int ret = m_receiver.alterTable(m_ndb, impl);
  if(ret == 0){
    // Remove cached information and let it be refreshed at next access
2155 2156 2157 2158 2159
    m_globalHash->lock();
    local->m_table_impl->m_status = NdbDictionary::Object::Invalid;
    m_globalHash->drop(local->m_table_impl);
    m_globalHash->unlock();
    m_localHash.drop(originalInternalName);
2160
  }
mskold@mysql.com's avatar
mskold@mysql.com committed
2161
  DBUG_RETURN(ret);
2162 2163 2164 2165 2166 2167
}

int 
NdbDictInterface::alterTable(Ndb & ndb,
			      NdbTableImpl & impl)
{
2168 2169
  DBUG_ENTER("NdbDictInterface::alterTable");
  DBUG_RETURN(createOrAlterTable(ndb, impl, true));
2170 2171 2172 2173 2174 2175 2176
}

int 
NdbDictInterface::createOrAlterTable(Ndb & ndb,
				     NdbTableImpl & impl,
				     bool alter)
{
2177
  unsigned i;
2178 2179
  char *ts_names[MAX_NDB_PARTITIONS];
  DBUG_ENTER("NdbDictInterface::createOrAlterTable");
2180 2181 2182

  impl.computeAggregates();

2183
  if((unsigned)impl.getNoOfPrimaryKeys() > NDB_MAX_NO_OF_ATTRIBUTES_IN_KEY){
2184
    m_error.code= 4317;
2185
    DBUG_RETURN(-1);
2186 2187 2188
  }
  unsigned sz = impl.m_columns.size();
  if (sz > NDB_MAX_ATTRIBUTES_IN_TABLE){
2189
    m_error.code= 4318;
2190
    DBUG_RETURN(-1);
2191
  }
2192 2193 2194 2195
  
  // Check if any changes for alter table
  
  // Name change
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2196
  if (!impl.m_newExternalName.empty()) {
2197 2198 2199 2200
    if (alter)
    {
      AlterTableReq::setNameFlag(impl.m_changeMask, true);
    }
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2201
    impl.m_externalName.assign(impl.m_newExternalName);
2202
    impl.m_newExternalName.clear();
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2203
  }
2204
  // Definition change (frm)
2205 2206
  if (!impl.m_newFrm.empty())
  {
2207 2208 2209 2210 2211 2212 2213
    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();
  }
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 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
  // 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
  */
2263
  
2264 2265 2266
  //validate();
  //aggregate();

2267 2268
  const BaseString internalName(
    ndb.internalize_table_name(impl.m_externalName.c_str()));
2269
  impl.m_internalName.assign(internalName);
2270
  impl.updateMysqlName();
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
  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),
2282
	   internalName.c_str());
2283 2284

  bool haveAutoIncrement = false;
2285
  Uint64 autoIncrementValue = 0;
2286
  Uint32 distKeys= 0;
2287
  for(i = 0; i<sz; i++){
2288 2289 2290 2291 2292
    const NdbColumnImpl * col = impl.m_columns[i];
    if(col == 0)
      continue;
    if (col->m_autoIncrement) {
      if (haveAutoIncrement) {
2293
        m_error.code= 4335;
2294
        NdbMem_Free((void*)tmpTab);
pekka@mysql.com's avatar
pekka@mysql.com committed
2295
        DBUG_RETURN(-1);
2296 2297 2298
      }
      haveAutoIncrement = true;
      autoIncrementValue = col->m_autoIncrementInitialValue;
2299 2300
    }
    if (col->m_distributionKey)
2301
    {
2302
      distKeys++;
2303
    }
2304
  }
2305 2306 2307 2308
  if (distKeys == impl.m_noOfKeys)
    distKeys= 0;
  impl.m_noOfDistributionKeys= distKeys;

2309 2310 2311

  // Check max length of frm data
  if (impl.m_frm.length() > MAX_FRM_DATA_SIZE){
2312
    m_error.code= 1229;
2313
    NdbMem_Free((void*)tmpTab);
2314
    DBUG_RETURN(-1);
2315
  }
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
  /*
    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;
2349
  tmpTab->LinearHashFlag = impl.m_linear_flag;
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383

  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;
  }
2384

2385 2386 2387 2388 2389 2390
  tmpTab->FragmentType = getKernelConstant(impl.m_fragmentType,
 					   fragmentTypeMapping,
					   DictTabInfo::AllNodesSmallTable);
  tmpTab->TableVersion = rand();

  const char *tablespace_name= impl.m_tablespace_name.c_str();
2391 2392 2393
loop:
  if(impl.m_tablespace_id != ~(Uint32)0)
  {
2394 2395
    tmpTab->TablespaceId = impl.m_tablespace_id;
    tmpTab->TablespaceVersion = impl.m_tablespace_version;
2396 2397 2398 2399 2400 2401 2402
  }
  else if(strlen(tablespace_name))
  {
    NdbTablespaceImpl tmp;
    if(get_filegroup(tmp, NdbDictionary::Object::Tablespace, 
		     tablespace_name) == 0)
    {
2403 2404
      tmpTab->TablespaceId = tmp.m_id;
      tmpTab->TablespaceVersion = tmp.m_version;
2405 2406 2407 2408
    }
    else 
    {
      // error set by get filegroup
2409 2410
      NdbMem_Free((void*)tmpTab);
      DBUG_RETURN(-1);
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
    }
  } 
  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);
2426 2427
  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
2428
			     tmpTab,
2429 2430 2431 2432 2433 2434
			     DictTabInfo::TableMapping, 
			     DictTabInfo::TableMappingSize, true);
  
  if(s != SimpleProperties::Eof){
    abort();
  }
2435
  NdbMem_Free((void*)tmpTab);
2436
  
2437 2438
  DBUG_PRINT("info",("impl.m_noOfDistributionKeys: %d impl.m_noOfKeys: %d distKeys: %d",
		     impl.m_noOfDistributionKeys, impl.m_noOfKeys, distKeys));
2439 2440 2441
  if (distKeys == impl.m_noOfKeys)
    distKeys= 0;
  impl.m_noOfDistributionKeys= distKeys;
joreland@mysql.com's avatar
joreland@mysql.com committed
2442
  
2443
  for(i = 0; i<sz; i++){
2444 2445 2446 2447
    const NdbColumnImpl * col = impl.m_columns[i];
    if(col == 0)
      continue;
    
2448 2449
    DBUG_PRINT("info",("column: %s(%d) col->m_distributionKey: %d",
		       col->m_name.c_str(), i, col->m_distributionKey));
2450
    DictTabInfo::Attribute tmpAttr; tmpAttr.init();
2451
    BaseString::snprintf(tmpAttr.AttributeName, sizeof(tmpAttr.AttributeName), 
2452
	     col->m_name.c_str());
2453
    tmpAttr.AttributeId = col->m_attrId;
joreland@mysql.com's avatar
joreland@mysql.com committed
2454
    tmpAttr.AttributeKeyFlag = col->m_pk;
2455
    tmpAttr.AttributeNullableFlag = col->m_nullable;
2456
    tmpAttr.AttributeDKey = distKeys ? (bool)col->m_distributionKey : 0;
2457

2458
    tmpAttr.AttributeExtType = (Uint32)col->m_type;
pekka@mysql.com's avatar
pekka@mysql.com committed
2459
    tmpAttr.AttributeExtPrecision = ((unsigned)col->m_precision & 0xFFFF);
2460 2461
    tmpAttr.AttributeExtScale = col->m_scale;
    tmpAttr.AttributeExtLength = col->m_length;
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
    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
2475 2476
    // check type and compute attribute size and array size
    if (! tmpAttr.translateExtType()) {
2477
      m_error.code= 703;
pekka@mysql.com's avatar
pekka@mysql.com committed
2478 2479
      DBUG_RETURN(-1);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2480 2481
    // charset is defined exactly for char types
    if (col->getCharType() != (col->m_cs != NULL)) {
2482
      m_error.code= 703;
2483
      DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2484 2485 2486
    }
    // primary key type check
    if (col->m_pk && ! NdbSqlUtil::usable_in_pk(col->m_type, col->m_cs)) {
pekka@mysql.com's avatar
pekka@mysql.com committed
2487
      m_error.code= (col->m_cs != 0 ? 743 : 739);
2488
      DBUG_RETURN(-1);
pekka@mysql.com's avatar
pekka@mysql.com committed
2489
    }
2490
    // distribution key not supported for Char attribute
2491
    if (distKeys && col->m_distributionKey && col->m_cs != NULL) {
2492 2493 2494 2495 2496 2497 2498 2499
      // 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);
      }
2500
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2501 2502 2503 2504
    // charset in upper half of precision
    if (col->getCharType()) {
      tmpAttr.AttributeExtPrecision |= (col->m_cs->number << 16);
    }
2505 2506

    tmpAttr.AttributeAutoIncrement = col->m_autoIncrement;
2507
    BaseString::snprintf(tmpAttr.AttributeDefaultValue, 
2508 2509 2510 2511 2512
	     sizeof(tmpAttr.AttributeDefaultValue),
	     col->m_defaultValue.c_str());
    s = SimpleProperties::pack(w, 
			       &tmpAttr,
			       DictTabInfo::AttributeMapping, 
joreland@mysql.com's avatar
joreland@mysql.com committed
2513
			       DictTabInfo::AttributeMappingSize, true);
2514 2515 2516
    w.add(DictTabInfo::AttributeEnd, 1);
  }

2517
  int ret;
2518
  
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2519
  LinearSectionPtr ptr[1];
2520 2521
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = m_buffer.length() / 4;
2522 2523 2524 2525 2526 2527 2528
  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());
2529 2530 2531 2532
    
    req->senderRef = m_reference;
    req->senderData = 0;
    req->changeMask = impl.m_changeMask;
2533
    req->tableId = impl.m_id;
2534
    req->tableVersion = impl.m_version;;
2535 2536 2537 2538 2539 2540 2541

    int errCodes[] = { AlterTableRef::NotMaster, AlterTableRef::Busy, 0 };
    ret = dictSignal(&tSignal, ptr, 1,
		     0, // master
		     WAIT_ALTER_TAB_REQ,
		     WAITFOR_RESPONSE_TIMEOUT, 100,
		     errCodes);
2542
    
2543 2544
    if(m_error.code == AlterTableRef::InvalidTableVersion) {
      // Clear caches and try again
2545
      DBUG_RETURN(INCOMPATIBLE_VERSION);
2546 2547
    }
  } else {
2548 2549
    tSignal.theVerId_signalNumber   = GSN_CREATE_TABLE_REQ;
    tSignal.theLength = CreateTableReq::SignalLength;
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570

    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,
		     WAITFOR_RESPONSE_TIMEOUT, 100,
		     errCodes);
  }
  
  if (!ret && !alter && haveAutoIncrement) {
    if (!ndb.setAutoIncrementValue(impl.m_externalName.c_str(), 
				   autoIncrementValue)) {
      if (ndb.theError.code == 0) {
	m_error.code = 4336;
	ndb.theError = m_error;
      } else
	m_error= ndb.theError;
      ret = -1; // errorcode set in initialize_autoincrement
2571 2572
    }
  }
2573
  DBUG_RETURN(ret);
2574 2575 2576 2577 2578 2579
}

void
NdbDictInterface::execCREATE_TABLE_CONF(NdbApiSignal * signal,
					LinearSectionPtr ptr[3])
{
2580
#if 0
2581 2582 2583 2584
  const CreateTableConf* const conf=
    CAST_CONSTPTR(CreateTableConf, signal->getDataPtr());
  Uint32 tableId= conf->tableId;
  Uint32 tableVersion= conf->tableVersion;
2585
#endif
2586 2587 2588 2589
  m_waiter.signal(NO_WAIT);  
}

void
2590
NdbDictInterface::execCREATE_TABLE_REF(NdbApiSignal * sig,
2591 2592
				       LinearSectionPtr ptr[3])
{
2593
  const CreateTableRef* ref = CAST_CONSTPTR(CreateTableRef, sig->getDataPtr());
2594
  m_error.code= ref->errorCode;
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
  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
2607
NdbDictInterface::execALTER_TABLE_REF(NdbApiSignal * sig,
2608 2609
				      LinearSectionPtr ptr[3])
{
2610
  const AlterTableRef * ref = CAST_CONSTPTR(AlterTableRef, sig->getDataPtr());
2611
  m_error.code= ref->errorCode;
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);
}

/*****************************************************************
 * Drop table
 */
int
NdbDictionaryImpl::dropTable(const char * name)
{
2622 2623
  DBUG_ENTER("NdbDictionaryImpl::dropTable");
  DBUG_PRINT("enter",("name: %s", name));
2624 2625
  NdbTableImpl * tab = getTable(name);
  if(tab == 0){
2626
    DBUG_RETURN(-1);
2627 2628 2629 2630 2631
  }
  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) {
2632 2633 2634
    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());
2635
    m_globalHash->lock();
2636
    tab->m_status = NdbDictionary::Object::Invalid;
2637
    m_globalHash->drop(tab);
2638
    m_globalHash->unlock();
2639
    DBUG_RETURN(dropTable(name));
2640
  }
2641
  
2642
  DBUG_RETURN(ret);
2643 2644 2645 2646 2647
}

int
NdbDictionaryImpl::dropTable(NdbTableImpl & impl)
{
joreland@mysql.com's avatar
joreland@mysql.com committed
2648
  int res;
2649 2650 2651 2652 2653
  const char * name = impl.getName();
  if(impl.m_status == NdbDictionary::Object::New){
    return dropTable(name);
  }

2654 2655
  if (impl.m_indexType != NdbDictionary::Object::TypeUndefined)
  {
2656
    m_receiver.m_error.code= 1228;
2657 2658 2659 2660
    return -1;
  }

  List list;
2661
  if ((res = listIndexes(list, impl.m_id)) == -1){
2662
    return -1;
joreland@mysql.com's avatar
joreland@mysql.com committed
2663
  }
2664 2665
  for (unsigned i = 0; i < list.count; i++) {
    const List::Element& element = list.elements[i];
joreland@mysql.com's avatar
joreland@mysql.com committed
2666 2667
    if ((res = dropIndex(element.name, name)) == -1)
    {
2668
      return -1;
joreland@mysql.com's avatar
joreland@mysql.com committed
2669
    }
2670
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
2671
  
pekka@mysql.com's avatar
pekka@mysql.com committed
2672
  if (impl.m_noOfBlobs != 0) {
joreland@mysql.com's avatar
joreland@mysql.com committed
2673
    if (dropBlobTables(impl) != 0){
pekka@mysql.com's avatar
pekka@mysql.com committed
2674
      return -1;
joreland@mysql.com's avatar
joreland@mysql.com committed
2675
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
2676
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
2677
  
2678
  int ret = m_receiver.dropTable(impl);  
2679
  if(ret == 0 || m_error.code == 709 || m_error.code == 723){
2680
    const char * internalTableName = impl.m_internalName.c_str();
2681

joreland@mysql.com's avatar
joreland@mysql.com committed
2682
    
2683 2684
    m_localHash.drop(internalTableName);
    m_globalHash->lock();
2685
    impl.m_status = NdbDictionary::Object::Invalid;
2686 2687
    m_globalHash->drop(&impl);
    m_globalHash->unlock();
joreland@mysql.com's avatar
joreland@mysql.com committed
2688 2689

    return 0;
2690 2691 2692 2693 2694
  }
  
  return ret;
}

pekka@mysql.com's avatar
pekka@mysql.com committed
2695 2696 2697
int
NdbDictionaryImpl::dropBlobTables(NdbTableImpl & t)
{
2698
  DBUG_ENTER("NdbDictionaryImpl::dropBlobTables");
pekka@mysql.com's avatar
pekka@mysql.com committed
2699 2700
  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
2701
    if (! c.getBlobType() || c.getPartSize() == 0)
pekka@mysql.com's avatar
pekka@mysql.com committed
2702
      continue;
2703
    char btname[NdbBlobImpl::BlobTableNameSize];
pekka@mysql.com's avatar
pekka@mysql.com committed
2704 2705
    NdbBlob::getBlobTableName(btname, &t, &c);
    if (dropTable(btname) != 0) {
2706
      if (m_error.code != 709 && m_error.code != 723){
2707 2708
	DBUG_PRINT("exit",("error %u - exiting",m_error.code));
        DBUG_RETURN(-1);
joreland@mysql.com's avatar
joreland@mysql.com committed
2709
      }
2710
      DBUG_PRINT("info",("error %u - continuing",m_error.code));
pekka@mysql.com's avatar
pekka@mysql.com committed
2711 2712
    }
  }
2713
  DBUG_RETURN(0);
pekka@mysql.com's avatar
pekka@mysql.com committed
2714 2715
}

2716 2717 2718 2719 2720 2721 2722 2723
int
NdbDictInterface::dropTable(const NdbTableImpl & impl)
{
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_DROP_TABLE_REQ;
  tSignal.theLength = DropTableReq::SignalLength;
  
2724
  DropTableReq * req = CAST_PTR(DropTableReq, tSignal.getDataPtrSend());
2725 2726
  req->senderRef = m_reference;
  req->senderData = 0;
2727
  req->tableId = impl.m_id;
2728 2729
  req->tableVersion = impl.m_version;

2730 2731 2732 2733 2734 2735 2736 2737 2738
  int errCodes[] =
    { DropTableRef::NoDropTableRecordAvailable,
      DropTableRef::NotMaster,
      DropTableRef::Busy, 0 };
  int r = dictSignal(&tSignal, 0, 0,
		     0, // master
		     WAIT_DROP_TAB_REQ, 
		     WAITFOR_RESPONSE_TIMEOUT, 100,
		     errCodes);
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
  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])
{
2750
  DBUG_ENTER("NdbDictInterface::execDROP_TABLE_CONF");
2751 2752 2753
  //DropTableConf* const conf = CAST_CONSTPTR(DropTableConf, signal->getDataPtr());

  m_waiter.signal(NO_WAIT);  
2754
  DBUG_VOID_RETURN;
2755 2756 2757 2758 2759 2760
}

void
NdbDictInterface::execDROP_TABLE_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
2761
  DBUG_ENTER("NdbDictInterface::execDROP_TABLE_REF");
2762
  const DropTableRef* ref = CAST_CONSTPTR(DropTableRef, signal->getDataPtr());
2763
  m_error.code= ref->errorCode;
2764 2765
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
2766
  DBUG_VOID_RETURN;
2767 2768 2769 2770 2771 2772
}

int
NdbDictionaryImpl::invalidateObject(NdbTableImpl & impl)
{
  const char * internalTableName = impl.m_internalName.c_str();
2773 2774 2775
  DBUG_ENTER("NdbDictionaryImpl::invalidateObject");
  DBUG_PRINT("enter", ("internal_name: %s", internalTableName));
  m_localHash.drop(internalTableName);
2776
  m_globalHash->lock();
2777
  impl.m_status = NdbDictionary::Object::Invalid;
2778 2779
  m_globalHash->drop(&impl);
  m_globalHash->unlock();
2780
  DBUG_RETURN(0);
2781 2782 2783
}

int
2784
NdbDictionaryImpl::removeCachedObject(NdbTableImpl & impl, bool lock)
2785 2786 2787
{
  const char * internalTableName = impl.m_internalName.c_str();

2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
  if (lock)
    m_globalHash->lock();
  if (impl.m_noOfBlobs != 0) {
    for (uint i = 0; i < impl.m_columns.size(); i++) {
      NdbColumnImpl& c = *impl.m_columns[i];
      if (! c.getBlobType() || c.getPartSize() == 0)
        continue;
      assert(c.m_blobTable != NULL);
      removeCachedObject(*c.m_blobTable, false);
    }
  }
2799 2800
  m_localHash.drop(internalTableName);  
  m_globalHash->release(&impl);
2801 2802
  if (lock)
    m_globalHash->unlock();
2803 2804 2805 2806 2807 2808 2809
  return 0;
}

/*****************************************************************
 * Get index info
 */
NdbIndexImpl*
2810 2811
NdbDictionaryImpl::getIndexImpl(const char * externalName,
				const BaseString& internalName)
2812
{
2813 2814
  Ndb_local_table_info * info = get_local_table_info(internalName,
						     false);
2815
  if(info == 0){
2816 2817 2818
    m_error.code = 4243;
    return 0;
  }
2819
  NdbTableImpl * tab = info->m_table_impl;
2820

2821 2822
  if(tab->m_indexType == NdbDictionary::Object::TypeUndefined)
  {
2823 2824 2825 2826 2827
    // Not an index
    m_error.code = 4243;
    return 0;
  }

2828 2829
  NdbTableImpl* prim = getTable(tab->m_primaryTable.c_str());
  if(prim == 0){
2830 2831 2832
    m_error.code = 4243;
    return 0;
  }
2833

2834 2835 2836
  /**
   * Create index impl
   */
2837 2838 2839
  NdbIndexImpl* idx;
  if(NdbDictInterface::create_index_obj_from_table(&idx, tab, prim) == 0){
    idx->m_table = tab;
joreland@mysql.com's avatar
joreland@mysql.com committed
2840
    idx->m_externalName.assign(externalName);
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
    idx->m_internalName.assign(internalName);
    // TODO Assign idx to tab->m_index
    // Don't do it right now since assign can't asign a table with index
    // tab->m_index = idx;
    return idx;
  }
  return 0;
}

int
NdbDictInterface::create_index_obj_from_table(NdbIndexImpl** dst,
2852
					      NdbTableImpl* tab,
2853 2854
					      const NdbTableImpl* prim){
  NdbIndexImpl *idx = new NdbIndexImpl();
2855 2856
  idx->m_version = tab->m_version;
  idx->m_status = tab->m_status;
2857
  idx->m_id = tab->m_id;
2858
  idx->m_externalName.assign(tab->getName());
2859
  idx->m_tableName.assign(prim->m_externalName);
2860
  NdbDictionary::Object::Type type = idx->m_type = tab->m_indexType;
2861
  idx->m_logging = tab->m_logging;
2862
  // skip last attribute (NDB$PK or NDB$TNODE)
2863 2864 2865 2866 2867 2868

  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++){
2869 2870
    NdbColumnImpl* org = tab->m_columns[i];

2871 2872
    NdbColumnImpl* col = new NdbColumnImpl;
    // Copy column definition
2873
    *col = * org;
2874
    idx->m_columns.push_back(col);
2875

2876 2877 2878
    /**
     * reverse map
     */
2879 2880
    const NdbColumnImpl* primCol = prim->getColumn(col->getName());
    int key_id = primCol->getColumnNo();
2881 2882 2883 2884
    int fill = -1;
    idx->m_key_ids.fill(key_id, fill);
    idx->m_key_ids[key_id] = i;
    col->m_keyInfoPos = key_id;
2885

2886
    if(type == NdbDictionary::Object::OrderedIndex && 
2887 2888
       (primCol->m_distributionKey ||
	(distKeys == 0 && primCol->getPrimaryKey())))
2889
    {
2890 2891
      keyCount--;
      org->m_distributionKey = 1;
2892
    }
2893
  }
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903

  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;
  }
2904 2905

  * dst = idx;
2906

2907
  return 0;
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
}

/*****************************************************************
 * Create index
 */
int
NdbDictionaryImpl::createIndex(NdbIndexImpl &ix)
{
  NdbTableImpl* tab = getTable(ix.getTable());
  if(tab == 0){
    m_error.code = 4249;
    return -1;
  }
  
  return m_receiver.createIndex(m_ndb, ix, * tab);
}

int 
NdbDictInterface::createIndex(Ndb & ndb,
2927
			      const NdbIndexImpl & impl, 
2928 2929 2930 2931
			      const NdbTableImpl & table)
{
  //validate();
  //aggregate();
2932
  unsigned i;
2933 2934 2935 2936 2937 2938
  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;
  }
2939 2940 2941
  const BaseString internalName(
    ndb.internalize_index_name(&table, impl.getName()));
  w.add(DictTabInfo::TableName, internalName.c_str());
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
  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);
  
2965
  req->setTableId(table.m_id);
2966 2967 2968
  req->setOnline(true);
  AttributeList attributeList;
  attributeList.sz = impl.m_columns.size();
2969
  for(i = 0; i<attributeList.sz; i++){
2970 2971 2972 2973 2974 2975
    const NdbColumnImpl* col = 
      table.getColumn(impl.m_columns[i]->m_name.c_str());
    if(col == 0){
      m_error.code = 4247;
      return -1;
    }
2976
    // Copy column definition  XXX must be wrong, overwrites
2977 2978
    *impl.m_columns[i] = *col;

pekka@mysql.com's avatar
pekka@mysql.com committed
2979 2980 2981 2982 2983 2984 2985 2986
    // index key type check
    if (it == DictTabInfo::UniqueHashIndex &&
        ! NdbSqlUtil::usable_in_hash_index(col->m_type, col->m_cs) ||
        it == DictTabInfo::OrderedIndex &&
        ! NdbSqlUtil::usable_in_ordered_index(col->m_type, col->m_cs)) {
      m_error.code = 743;
      return -1;
    }
2987 2988
    // API uses external column number to talk to DICT
    attributeList.id[i] = col->m_column_no;
2989
  }
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
2990
  LinearSectionPtr ptr[2];
2991 2992 2993 2994 2995
  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?

2996 2997 2998
  int errCodes[] = { CreateIndxRef::Busy, CreateIndxRef::NotMaster, 0 };
  return dictSignal(&tSignal, ptr, 2,
		    0, // master
2999
		    WAIT_CREATE_INDX_REQ,
3000 3001
		    WAITFOR_RESPONSE_TIMEOUT, 100,
		    errCodes);
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
}

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

void
3012
NdbDictInterface::execCREATE_INDX_REF(NdbApiSignal * sig,
3013 3014
				      LinearSectionPtr ptr[3])
{
3015
  const CreateIndxRef* ref = CAST_CONSTPTR(CreateIndxRef, sig->getDataPtr());
3016
  m_error.code = ref->getErrorCode();
3017
  if(m_error.code == ref->NotMaster)
3018
    m_masterNodeId= ref->masterNodeId;
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037
  m_waiter.signal(NO_WAIT);  
}

/*****************************************************************
 * Drop index
 */
int
NdbDictionaryImpl::dropIndex(const char * indexName, 
			     const char * tableName)
{
  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) {
3038
    const BaseString internalIndexName((tableName)
3039
      ?
3040
      m_ndb.internalize_index_name(getTable(tableName), indexName)
3041
      :
3042 3043 3044
      m_ndb.internalize_table_name(indexName)); // Index is also a table

    m_localHash.drop(internalIndexName.c_str());
3045
    m_globalHash->lock();
3046
    idx->m_table->m_status = NdbDictionary::Object::Invalid;
3047
    m_globalHash->drop(idx->m_table);
3048
    m_globalHash->unlock();
3049 3050
    return dropIndex(indexName, tableName);
  }
3051

3052 3053 3054 3055 3056 3057 3058
  return ret;
}

int
NdbDictionaryImpl::dropIndex(NdbIndexImpl & impl, const char * tableName)
{
  const char * indexName = impl.getName();
3059
  if (tableName || m_ndb.usingFullyQualifiedNames()) {
3060 3061 3062 3063 3064 3065 3066
    NdbTableImpl * timpl = impl.m_table;
    
    if (timpl == 0) {
      m_error.code = 709;
      return -1;
    }

3067
    const BaseString internalIndexName((tableName)
3068
      ?
3069
      m_ndb.internalize_index_name(getTable(tableName), indexName)
3070
      :
3071
      m_ndb.internalize_table_name(indexName)); // Index is also a table
3072 3073 3074 3075

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

3077 3078
    int ret = m_receiver.dropIndex(impl, *timpl);
    if(ret == 0){
3079
      m_localHash.drop(internalIndexName.c_str());
3080
      m_globalHash->lock();
3081
      impl.m_table->m_status = NdbDictionary::Object::Invalid;
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
      m_globalHash->drop(impl.m_table);
      m_globalHash->unlock();
    }
    return ret;
  }

  m_error.code = 4243;
  return -1;
}

int
NdbDictInterface::dropIndex(const NdbIndexImpl & impl, 
			    const NdbTableImpl & timpl)
{
  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
3106
  req->setIndexId(timpl.m_id);
3107 3108
  req->setIndexVersion(timpl.m_version);

3109 3110 3111
  int errCodes[] = { DropIndxRef::Busy, DropIndxRef::NotMaster, 0 };
  int r = dictSignal(&tSignal, 0, 0,
		     0, // master
3112
		     WAIT_DROP_INDX_REQ,
3113 3114
		     WAITFOR_RESPONSE_TIMEOUT, 100,
		     errCodes);
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
  if(m_error.code == DropIndxRef::InvalidIndexVersion) {
    // Clear caches and try again
    return INCOMPATIBLE_VERSION;
  }
  return r;
}

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])
{
3133
  const DropIndxRef* ref = CAST_CONSTPTR(DropIndxRef, signal->getDataPtr());
3134
  m_error.code = ref->getErrorCode();
3135
  if(m_error.code == ref->NotMaster)
3136
    m_masterNodeId= ref->masterNodeId;
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
  m_waiter.signal(NO_WAIT);  
}

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

int
NdbDictionaryImpl::createEvent(NdbEventImpl & evnt)
{
3147
  DBUG_ENTER("NdbDictionaryImpl::createEvent");
3148
  int i;
3149 3150 3151 3152 3153 3154 3155 3156 3157
  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()));
      DBUG_RETURN(-1);
    }
3158
    evnt.setTable(tab);
3159 3160
  }

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

3163 3164 3165 3166
  NdbTableImpl &table = *evnt.m_tableImpl;

  int attributeList_sz = evnt.m_attrIds.size();

3167
  for (i = 0; i < attributeList_sz; i++) {
3168 3169 3170 3171 3172
    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],
3173 3174
	       evnt.getTableName());
      m_error.code= 4713;
3175
      DBUG_RETURN(-1);
3176 3177 3178 3179 3180 3181
    }
  }

  evnt.m_attrIds.clear();

  attributeList_sz = evnt.m_columns.size();
3182 3183

  DBUG_PRINT("info",("Event on tableId=%d, tableVersion=%d, event name %s, no of columns %d",
3184
		     table.m_id, table.m_version,
3185 3186 3187
		     evnt.m_name.c_str(),
		     evnt.m_columns.size()));

3188 3189 3190
  int pk_count = 0;
  evnt.m_attrListBitmask.clear();

3191
  for(i = 0; i<attributeList_sz; i++){
3192 3193 3194
    const NdbColumnImpl* col = 
      table.getColumn(evnt.m_columns[i]->m_name.c_str());
    if(col == 0){
3195
      m_error.code= 4247;
3196
      DBUG_RETURN(-1);
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
    }
    // 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)
3209
  for(i = 1; i < attributeList_sz; i++) {
3210 3211 3212 3213 3214 3215 3216 3217 3218
    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
3219
  for(i = 1; i<attributeList_sz; i++) {
3220
    if (evnt.m_columns[i-1]->m_attrId == evnt.m_columns[i]->m_attrId) {
3221
      m_error.code= 4258;
3222
      DBUG_RETURN(-1);
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
    }
  }
  
#ifdef EVENT_DEBUG
  char buf[128] = {0};
  evnt.m_attrListBitmask.getText(buf);
  ndbout_c("createEvent: mask = %s", buf);
#endif

  // NdbDictInterface m_receiver;
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
  if (m_receiver.createEvent(m_ndb, evnt, 0 /* getFlag unset */) != 0)
    DBUG_RETURN(-1);

  // 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;
    DBUG_RETURN(-1);
  }
  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)
      DBUG_RETURN(-1);
  }
  DBUG_RETURN(0);
3264 3265 3266 3267 3268 3269 3270
}

int
NdbDictInterface::createEvent(class Ndb & ndb,
			      NdbEventImpl & evnt,
			      int getFlag)
{
3271 3272 3273
  DBUG_ENTER("NdbDictInterface::createEvent");
  DBUG_PRINT("enter",("getFlag=%d",getFlag));

3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290
  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 {
3291
    DBUG_PRINT("info",("tableId: %u tableVersion: %u",
3292 3293
		       evnt.m_tableImpl->m_id, 
                       evnt.m_tableImpl->m_version));
3294 3295
    // creating event in Dictionary
    req->setRequestType(CreateEvntReq::RT_USER_CREATE);
3296 3297
    req->setTableId(evnt.m_tableImpl->m_id);
    req->setTableVersion(evnt.m_tableImpl->m_version);
3298 3299
    req->setAttrListBitmask(evnt.m_attrListBitmask);
    req->setEventType(evnt.mi_type);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3300 3301 3302 3303 3304
    req->clearFlags();
    if (evnt.m_rep & NdbDictionary::Event::ER_ALL)
      req->setReportAll();
    if (evnt.m_rep & NdbDictionary::Event::ER_SUBSCRIBE)
      req->setReportSubscribe();
3305 3306 3307 3308
  }

  UtilBufferWriter w(m_buffer);

3309
  const size_t len = strlen(evnt.m_name.c_str()) + 1;
3310
  if(len > MAX_TAB_NAME_SIZE) {
3311
    m_error.code= 4241;
3312
    DBUG_RETURN(-1);
3313 3314
  }

3315
  w.add(SimpleProperties::StringValue, evnt.m_name.c_str());
3316 3317

  if (getFlag == 0)
3318 3319 3320
  {
    const BaseString internal_tabname(
      ndb.internalize_table_name(evnt.m_tableName.c_str()));
3321
    w.add(SimpleProperties::StringValue,
3322 3323
	 internal_tabname.c_str());
  }
3324

msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
3325
  LinearSectionPtr ptr[1];
3326 3327 3328
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = (m_buffer.length()+3) >> 2;

3329 3330 3331 3332
  int ret = dictSignal(&tSignal,ptr, 1,
		       0, // master
		       WAIT_CREATE_INDX_REQ,
		       WAITFOR_RESPONSE_TIMEOUT, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3333
		       0, -1);
3334 3335

  if (ret) {
3336
    DBUG_RETURN(ret);
3337
  }
3338
  
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
  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();

  if (getFlag) {
    evnt.m_attrListBitmask = evntConf->getAttrListBitmask();
    evnt.mi_type           = evntConf->getEventType();
    evnt.setTable(dataPtr);
  } else {
3352 3353
    if (evnt.m_tableImpl->m_id         != evntConf->getTableId() ||
	evnt.m_tableImpl->m_version    != evntConf->getTableVersion() ||
3354 3355 3356
	//evnt.m_attrListBitmask != evntConf->getAttrListBitmask() ||
	evnt.mi_type           != evntConf->getEventType()) {
      ndbout_c("ERROR*************");
3357
      DBUG_RETURN(1);
3358 3359 3360 3361 3362 3363
    }
  }

  evnt.m_eventId         = evntConf->getEventId();
  evnt.m_eventKey        = evntConf->getEventKey();

3364
  DBUG_RETURN(0);
3365 3366 3367
}

int
3368
NdbDictionaryImpl::executeSubscribeEvent(NdbEventOperationImpl & ev_op)
3369 3370
{
  // NdbDictInterface m_receiver;
3371
  return m_receiver.executeSubscribeEvent(m_ndb, ev_op);
3372 3373 3374 3375
}

int
NdbDictInterface::executeSubscribeEvent(class Ndb & ndb,
3376
					NdbEventOperationImpl & ev_op)
3377
{
3378
  DBUG_ENTER("NdbDictInterface::executeSubscribeEvent");
3379 3380 3381 3382 3383
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_SUB_START_REQ;
  tSignal.theLength = SubStartReq::SignalLength2;
  
3384
  SubStartReq * req = CAST_PTR(SubStartReq, tSignal.getDataPtrSend());
3385

3386 3387 3388 3389 3390
  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;
3391

3392 3393 3394
  DBUG_PRINT("info",("GSN_SUB_START_REQ subscriptionId=%d,subscriptionKey=%d,"
		     "subscriberData=%d",req->subscriptionId,
		     req->subscriptionKey,req->subscriberData));
3395

3396
  DBUG_RETURN(dictSignal(&tSignal,NULL,0,
3397
			 0 /*use masternode id*/,
3398
			 WAIT_CREATE_INDX_REQ /*WAIT_CREATE_EVNT_REQ*/,
3399
			 -1, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3400
			 0, -1));
3401 3402 3403
}

int
3404
NdbDictionaryImpl::stopSubscribeEvent(NdbEventOperationImpl & ev_op)
3405 3406
{
  // NdbDictInterface m_receiver;
3407
  return m_receiver.stopSubscribeEvent(m_ndb, ev_op);
3408 3409 3410 3411
}

int
NdbDictInterface::stopSubscribeEvent(class Ndb & ndb,
3412
				     NdbEventOperationImpl & ev_op)
3413
{
3414
  DBUG_ENTER("NdbDictInterface::stopSubscribeEvent");
3415 3416 3417 3418 3419 3420 3421

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

3424 3425 3426 3427 3428
  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;
3429

3430 3431 3432
  DBUG_PRINT("info",("GSN_SUB_STOP_REQ subscriptionId=%d,subscriptionKey=%d,"
		     "subscriberData=%d",req->subscriptionId,
		     req->subscriptionKey,req->subscriberData));
3433

3434
  DBUG_RETURN(dictSignal(&tSignal,NULL,0,
3435
			 0 /*use masternode id*/,
3436
			 WAIT_CREATE_INDX_REQ /*WAIT_SUB_STOP__REQ*/,
3437
			 -1, 100,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3438
			 0, -1));
3439 3440 3441 3442 3443
}

NdbEventImpl * 
NdbDictionaryImpl::getEvent(const char * eventName)
{
3444 3445
  DBUG_ENTER("NdbDictionaryImpl::getEvent");
  DBUG_PRINT("enter",("eventName= %s", eventName));
3446

3447
 NdbEventImpl *ev =  new NdbEventImpl();
3448
  if (ev == NULL) {
3449
    DBUG_RETURN(NULL);
3450 3451 3452 3453 3454 3455 3456 3457
  }

  ev->setName(eventName);

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

  if (ret) {
    delete ev;
3458
    DBUG_RETURN(NULL);
3459 3460 3461
  }

  // We only have the table name with internal name
3462 3463
  DBUG_PRINT("info",("table %s", ev->getTableName()));
  Ndb_local_table_info *info;
3464 3465
  info= get_local_table_info(ev->getTableName(), true);
  if (info == 0)
3466
  {
3467 3468 3469
    DBUG_PRINT("error",("unable to find table %s", ev->getTableName()));
    delete ev;
    DBUG_RETURN(NULL);
3470
  }
3471
  if (info->m_table_impl->m_status != NdbDictionary::Object::Retrieved)
3472 3473 3474 3475 3476 3477 3478 3479 3480 3481
  {
    removeCachedObject(*info->m_table_impl);
    info= get_local_table_info(ev->getTableName(), true);
    if (info == 0)
    {
      DBUG_PRINT("error",("unable to find table %s", ev->getTableName()));
      delete ev;
      DBUG_RETURN(NULL);
    }
  }
3482 3483
  ev->setTable(info->m_table_impl);
  ev->setTable(m_ndb.externalizeTableName(ev->getTableName()));  
3484 3485 3486
  // get the columns from the attrListBitmask
  NdbTableImpl &table = *ev->m_tableImpl;
  AttributeMask & mask = ev->m_attrListBitmask;
3487
  unsigned attributeList_sz = mask.count();
3488

3489 3490
  DBUG_PRINT("info",("Table: id: %d version: %d", 
                     table.m_id, table.m_version));
3491 3492

#ifndef DBUG_OFF
3493 3494
  char buf[128] = {0};
  mask.getText(buf);
3495 3496
  DBUG_PRINT("info",("attributeList_sz= %d, mask= %s", 
                     attributeList_sz, buf));
3497 3498
#endif

3499 3500 3501
  
  if ( attributeList_sz > table.getNoOfColumns() )
  {
3502
    m_error.code = 241;
3503 3504 3505 3506
    DBUG_PRINT("error",("Invalid version, too many columns"));
    delete ev;
    DBUG_RETURN(NULL);
  }
3507

3508 3509 3510 3511
  assert( (int)attributeList_sz <= table.getNoOfColumns() );
  for(unsigned id= 0; ev->m_columns.size() < attributeList_sz; id++) {
    if ( id >= table.getNoOfColumns())
    {
3512
      m_error.code = 241;
3513
      DBUG_PRINT("error",("Invalid version, column %d out of range", id));
3514
      delete ev;
3515
      DBUG_RETURN(NULL);
3516
    }
3517 3518 3519 3520 3521
    if (!mask.get(id))
      continue;

    const NdbColumnImpl* col = table.getColumn(id);
    DBUG_PRINT("info",("column %d %s", id, col->getName()));
3522 3523 3524 3525 3526
    NdbColumnImpl* new_col = new NdbColumnImpl;
    // Copy column definition
    *new_col = *col;
    ev->m_columns.push_back(new_col);
  }
3527
  DBUG_RETURN(ev);
3528 3529 3530 3531 3532 3533
}

void
NdbDictInterface::execCREATE_EVNT_CONF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
3534 3535
  DBUG_ENTER("NdbDictInterface::execCREATE_EVNT_CONF");

3536 3537 3538 3539 3540 3541 3542 3543 3544
  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);
  }

3545 3546 3547 3548 3549 3550
  const CreateEvntConf * const createEvntConf=
    CAST_CONSTPTR(CreateEvntConf, signal->getDataPtr());

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

3551 3552
  DBUG_PRINT("info",("nodeid=%d,subscriptionId=%d,subscriptionKey=%d",
		     refToNode(signal->theSendersBlockRef),
3553
		     subscriptionId,subscriptionKey));
3554
  m_waiter.signal(NO_WAIT);
3555
  DBUG_VOID_RETURN;
3556 3557 3558 3559 3560 3561
}

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

3564 3565 3566 3567 3568
  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
3569 3570
  if (m_error.code == CreateEvntRef::NotMaster)
    m_masterNodeId = ref->getMasterNode();
3571 3572
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
3573 3574 3575 3576 3577 3578
}

void
NdbDictInterface::execSUB_STOP_CONF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
3579 3580 3581
  DBUG_ENTER("NdbDictInterface::execSUB_STOP_CONF");
  const SubStopConf * const subStopConf=
    CAST_CONSTPTR(SubStopConf, signal->getDataPtr());
3582

3583 3584 3585
  Uint32 subscriptionId = subStopConf->subscriptionId;
  Uint32 subscriptionKey = subStopConf->subscriptionKey;
  Uint32 subscriberData = subStopConf->subscriberData;
3586

3587 3588
  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d",
		     subscriptionId,subscriptionKey,subscriberData));
3589
  m_waiter.signal(NO_WAIT);
3590
  DBUG_VOID_RETURN;
3591 3592 3593 3594 3595 3596
}

void
NdbDictInterface::execSUB_STOP_REF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
3597
  DBUG_ENTER("NdbDictInterface::execSUB_STOP_REF");
3598 3599
  const SubStopRef * const subStopRef=
    CAST_CONSTPTR(SubStopRef, signal->getDataPtr());
3600

3601 3602 3603 3604
  Uint32 subscriptionId = subStopRef->subscriptionId;
  Uint32 subscriptionKey = subStopRef->subscriptionKey;
  Uint32 subscriberData = subStopRef->subscriberData;
  m_error.code= subStopRef->errorCode;
3605

3606 3607
  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
3608 3609
  if (m_error.code == SubStopRef::NotMaster)
    m_masterNodeId = subStopRef->m_masterNodeId;
3610
  m_waiter.signal(NO_WAIT);
3611
  DBUG_VOID_RETURN;
3612 3613 3614 3615 3616 3617
}

void
NdbDictInterface::execSUB_START_CONF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
3618 3619 3620
  DBUG_ENTER("NdbDictInterface::execSUB_START_CONF");
  const SubStartConf * const subStartConf=
    CAST_CONSTPTR(SubStartConf, signal->getDataPtr());
3621

3622 3623
  Uint32 subscriptionId = subStartConf->subscriptionId;
  Uint32 subscriptionKey = subStartConf->subscriptionKey;
3624
  SubscriptionData::Part part = 
3625 3626
    (SubscriptionData::Part)subStartConf->part;
  Uint32 subscriberData = subStartConf->subscriberData;
3627 3628 3629

  switch(part) {
  case SubscriptionData::MetaData: {
3630 3631
    DBUG_PRINT("error",("SubscriptionData::MetaData"));
    m_error.code= 1;
3632 3633 3634
    break;
  }
  case SubscriptionData::TableData: {
3635
    DBUG_PRINT("info",("SubscriptionData::TableData"));
3636 3637 3638
    break;
  }
  default: {
3639 3640
    DBUG_PRINT("error",("wrong data"));
    m_error.code= 2;
3641 3642 3643
    break;
  }
  }
3644 3645
  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d",
		     subscriptionId,subscriptionKey,subscriberData));
3646
  m_waiter.signal(NO_WAIT);
3647
  DBUG_VOID_RETURN;
3648 3649 3650 3651 3652 3653
}

void
NdbDictInterface::execSUB_START_REF(NdbApiSignal * signal,
				    LinearSectionPtr ptr[3])
{
3654 3655 3656 3657
  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
3658 3659
  if (m_error.code == SubStartRef::NotMaster)
    m_masterNodeId = subStartRef->m_masterNodeId;
3660 3661
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
3662 3663 3664 3665 3666 3667 3668 3669
}

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

3673 3674 3675 3676 3677
  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);
3678
    DBUG_PRINT("info", ("no table err=%d, drop by name alone", m_error.code));
3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714
    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--;
      char bename[MAX_TAB_NAME_SIZE];
      NdbBlob::getBlobEventName(bename, &evnt, &c);
      (void)dropEvent(bename);
    }
  } else {
3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
    // loop over MAX_ATTRIBUTES_IN_TABLE ...
    Uint32 i;
    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;
    }
3726 3727
  }
  DBUG_RETURN(0);
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
}

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);

3745
  w.add(SimpleProperties::StringValue, evnt.m_name.c_str());
3746 3747 3748 3749 3750

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

3751 3752 3753 3754
  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
3755
		    0, -1);
3756
}
3757

3758 3759 3760 3761
void
NdbDictInterface::execDROP_EVNT_CONF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
3762
  DBUG_ENTER("NdbDictInterface::execDROP_EVNT_CONF");
3763
  m_waiter.signal(NO_WAIT);  
3764
  DBUG_VOID_RETURN;
3765 3766 3767 3768 3769 3770
}

void
NdbDictInterface::execDROP_EVNT_REF(NdbApiSignal * signal,
				    LinearSectionPtr ptr[3])
{
3771 3772 3773 3774
  DBUG_ENTER("NdbDictInterface::execDROP_EVNT_REF");
  const DropEvntRef* const ref=
    CAST_CONSTPTR(DropEvntRef, signal->getDataPtr());
  m_error.code= ref->getErrorCode();
3775

3776 3777
  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
3778 3779
  if (m_error.code == DropEvntRef::NotMaster)
    m_masterNodeId = ref->getMasterNode();
3780 3781
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
}

/*****************************************************************
 * 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);
3794
  return m_receiver.listObjects(list, req.requestData, m_ndb.usingFullyQualifiedNames());
3795 3796 3797
}

int
joreland@mysql.com's avatar
joreland@mysql.com committed
3798
NdbDictionaryImpl::listIndexes(List& list, Uint32 indexId)
3799
{
3800
  ListTablesReq req;
3801
  req.requestData = 0;
joreland@mysql.com's avatar
joreland@mysql.com committed
3802
  req.setTableId(indexId);
3803 3804
  req.setListNames(true);
  req.setListIndexes(true);
3805
  return m_receiver.listObjects(list, req.requestData, m_ndb.usingFullyQualifiedNames());
3806 3807 3808 3809
}

int
NdbDictInterface::listObjects(NdbDictionary::Dictionary::List& list,
3810
			      Uint32 requestData, bool fullyQualifiedNames)
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
{
  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
3846
    m_error.code= 4213;
3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872
    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);
3873
      objectName = BaseString(Ndb::externalizeIndexName(indexName, fullyQualifiedNames));
3874 3875 3876 3877 3878 3879 3880
      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);
3881
      objectName = BaseString(Ndb::externalizeTableName(tableName, fullyQualifiedNames));
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
      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
3909 3910 3911 3912 3913 3914 3915
    /*
      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));
3916 3917
    Uint16 aNodeId = m_transporter->get_an_alive_node();
    if (aNodeId == 0) {
3918
      m_error.code= 4009;
3919 3920 3921 3922 3923
      return -1;
    }
    if (m_transporter->sendSignal(signal, aNodeId) != 0) {
      continue;
    }
3924
    m_error.code= 0;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
3925 3926
    int ret_val= poll_guard.wait_n_unlock(WAITFOR_RESPONSE_TIMEOUT,
                                          aNodeId, WAIT_LIST_TABLES_CONF);
3927
    // end protected
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
3928
    if (ret_val == 0 && m_error.code == 0)
3929
      return 0;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
3930
    if (ret_val == -2) //WAIT_NODE_FAILURE
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
      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);
  }
}
3949

3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008
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;
    m_waiter.wait(WAITFOR_RESPONSE_TIMEOUT);
    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);
}

4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
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(){
}

4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
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;
}

4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065
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(){
}

4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
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;
}

4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
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(){
}

4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
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);
}

4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
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(){
}

4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
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);
}

4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 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 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 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
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;

  int err[] = { CreateFileRef::Busy, 0};
  /*
    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;

  int err[] = { DropFileRef::Busy, 0};
  DBUG_RETURN(dictSignal(&tSignal, 0, 0,
	                 0, // master
		         WAIT_CREATE_INDX_REQ,
		         WAITFOR_RESPONSE_TIMEOUT, 100,
		         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,
		         WAITFOR_RESPONSE_TIMEOUT, 100,
		         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,
		         WAITFOR_RESPONSE_TIMEOUT, 100,
		         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){
4473
  DBUG_ENTER("NdbDictInterface::get_filegroup");
4474 4475
  NdbApiSignal tSignal(m_reference);
  GetTabInfoReq * req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
4476

4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490
  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;
4491

4492 4493 4494 4495 4496 4497 4498 4499 4500
  int r = dictSignal(&tSignal, ptr, 1,
		     -1, // any node
		     WAIT_GET_TAB_INFO_REQ,
		     WAITFOR_RESPONSE_TIMEOUT, 100);
  if (r)
  {
    DBUG_PRINT("info", ("get_filegroup failed dictSignal"));
    DBUG_RETURN(-1);
  }
4501 4502 4503

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

4506 4507 4508 4509 4510 4511 4512
  if(m_error.code)
  {
    DBUG_PRINT("info", ("get_filegroup failed parseFilegroupInfo %d",
                         m_error.code));
    DBUG_RETURN(m_error.code);
  }

4513 4514 4515 4516 4517 4518 4519 4520 4521
  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());
  }
  
4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557
  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;
4558 4559 4560
  dst.m_undo_free_words= ((Uint64)fg.LF_UndoFreeWordsHi << 32)
    | (fg.LF_UndoFreeWordsLo);

4561 4562 4563
  return 0;
}

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
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,
		     WAITFOR_RESPONSE_TIMEOUT, 100);
  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);
}

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 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
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;

  int r = dictSignal(&tSignal, ptr, 1,
		     node,
		     WAIT_GET_TAB_INFO_REQ,
		     WAITFOR_RESPONSE_TIMEOUT, 100);
  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);
  }

4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674
  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");
  
4675 4676 4677 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 4704
  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;
  dst.m_id= f.FileNo;

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

4706 4707
  dst.m_filegroup_id= f.FilegroupId;
  dst.m_filegroup_version= f.FilegroupVersion;
4708
  dst.m_free=  f.FileFreeExtents;
4709 4710 4711
  return 0;
}

4712 4713 4714 4715 4716 4717
// XXX temp
void
NdbDictionaryImpl::fix_blob_events(const NdbDictionary::Table* table, const char* ev_name)
{
  const NdbTableImpl& t = table->m_impl;
  const NdbEventImpl* ev = getEvent(ev_name);
4718
  assert(ev != NULL);
4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735
  Uint32 i;
  for (i = 0; i < t.m_columns.size(); i++) {
    assert(t.m_columns[i] != NULL);
    const NdbColumnImpl& c = *t.m_columns[i];
    if (! c.getBlobType() || c.getPartSize() == 0)
      continue;
    char bename[200];
    NdbBlob::getBlobEventName(bename, ev, &c);
    // following fixes dict cache blob table
    NdbEventImpl* bev = getEvent(bename);
    if (c.m_blobTable != bev->m_tableImpl) {
      // XXX const violation
      ((NdbColumnImpl*)&c)->m_blobTable = bev->m_tableImpl;
    }
  }
}

4736
template class Vector<int>;
4737
template class Vector<Uint16>;
4738 4739
template class Vector<Uint32>;
template class Vector<Vector<Uint32> >;
4740 4741
template class Vector<NdbTableImpl*>;
template class Vector<NdbColumnImpl*>;
4742

4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
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;