NdbDictionaryImpl.cpp 82.5 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 32 33 34 35 36
/* 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>
#include <SimpleProperties.hpp>
#include <Bitmask.hpp>
#include <AttributeList.hpp>
#include <NdbEventOperation.hpp>
#include "NdbEventOperationImpl.hpp"
37 38
#include <NdbBlob.hpp>
#include "NdbBlobImpl.hpp"
unknown's avatar
unknown committed
39
#include <AttributeHeader.hpp>
unknown's avatar
unknown committed
40
#include <my_sys.h>
41 42 43 44 45 46 47 48 49 50

#define DEBUG_PRINT 0
#define INCOMPATIBLE_VERSION -2

//#define EVENT_DEBUG

/**
 * Column
 */
NdbColumnImpl::NdbColumnImpl()
51
  : NdbDictionary::Column(* this), m_attrId(-1), m_facade(this)
52 53 54 55 56
{
  init();
}

NdbColumnImpl::NdbColumnImpl(NdbDictionary::Column & f)
57
  : NdbDictionary::Column(* this), m_attrId(-1), m_facade(&f)
58 59 60 61
{
  init();
}

unknown's avatar
unknown committed
62 63
NdbColumnImpl&
NdbColumnImpl::operator=(const NdbColumnImpl& col)
64 65 66 67 68
{
  m_attrId = col.m_attrId;
  m_name = col.m_name;
  m_type = col.m_type;
  m_precision = col.m_precision;
unknown's avatar
unknown committed
69
  m_cs = col.m_cs;
70 71 72 73 74 75 76 77 78 79 80
  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;
  m_keyInfoPos = col.m_keyInfoPos;
unknown's avatar
unknown committed
81
  m_blobTable = col.m_blobTable;
82 83 84 85 86 87
  // Do not copy m_facade !!

  return *this;
}

void
88
NdbColumnImpl::init(Type t)
89
{
unknown's avatar
unknown committed
90 91
  // do not use default_charset_info as it may not be initialized yet
  // use binary collation until NDB tests can handle charsets
92
  CHARSET_INFO* default_cs = &my_charset_bin;
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  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;
unknown's avatar
unknown committed
110
    m_cs = NULL;
111
    break;
112 113
  case Olddecimal:
  case Olddecimalunsigned:
114 115
  case Decimal:
  case Decimalunsigned:
116 117 118
    m_precision = 10;
    m_scale = 0;
    m_length = 1;
unknown's avatar
unknown committed
119
    m_cs = NULL;
120 121 122 123 124 125
    break;
  case Char:
  case Varchar:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
unknown's avatar
unknown committed
126
    m_cs = default_cs;
127 128 129 130
    break;
  case Binary:
  case Varbinary:
  case Datetime:
unknown's avatar
unknown committed
131
  case Date:
132 133 134
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
unknown's avatar
unknown committed
135
    m_cs = NULL;
136 137 138 139 140
    break;
  case Blob:
    m_precision = 256;
    m_scale = 8000;
    m_length = 4;
unknown's avatar
unknown committed
141
    m_cs = NULL;
142 143 144 145 146
    break;
  case Text:
    m_precision = 256;
    m_scale = 8000;
    m_length = 4;
unknown's avatar
unknown committed
147
    m_cs = default_cs;
148
    break;
unknown's avatar
unknown committed
149
  case Time:
150 151
  case Year:
  case Timestamp:
unknown's avatar
unknown committed
152 153 154 155 156
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
    break;
unknown's avatar
unknown committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  case Bit:
    m_precision = 0;
    m_scale = 0;
    m_length = 1;
    m_cs = NULL;
    break;
  case Longvarchar:
    m_precision = 0;
    m_scale = 0;
    m_length = 1; // legal
    m_cs = default_cs;
    break;
  case Longvarbinary:
    m_precision = 0;
    m_scale = 0;
    m_length = 1; // legal
    m_cs = NULL;
    break;
unknown's avatar
unknown committed
175
  default:
unknown's avatar
unknown committed
176
  case Undefined:
177
    assert(false);
unknown's avatar
unknown committed
178
    break;
179
  }
180 181 182 183
  m_pk = false;
  m_nullable = false;
  m_distributionKey = false;
  m_keyInfoPos = 0;
184 185 186
  // next 2 are set at run time
  m_attrSize = 0;
  m_arraySize = 0;
187 188
  m_autoIncrement = false;
  m_autoIncrementInitialValue = 1;
unknown's avatar
unknown committed
189
  m_blobTable = NULL;
190 191 192 193 194 195 196 197 198
}

NdbColumnImpl::~NdbColumnImpl()
{
}

bool
NdbColumnImpl::equal(const NdbColumnImpl& col) const 
{
unknown's avatar
unknown committed
199
  DBUG_ENTER("NdbColumnImpl::equal");
200
  if(strcmp(m_name.c_str(), col.m_name.c_str()) != 0){
unknown's avatar
unknown committed
201
    DBUG_RETURN(false);
202 203
  }
  if(m_type != col.m_type){
unknown's avatar
unknown committed
204
    DBUG_RETURN(false);
205 206
  }
  if(m_pk != col.m_pk){
unknown's avatar
unknown committed
207
    DBUG_RETURN(false);
208 209
  }
  if(m_nullable != col.m_nullable){
unknown's avatar
unknown committed
210
    DBUG_RETURN(false);
211
  }
212
#ifdef ndb_dictionary_dkey_fixed
213 214
  if(m_pk){
    if(m_distributionKey != col.m_distributionKey){
unknown's avatar
unknown committed
215
      DBUG_RETURN(false);
216 217
    }
  }
218
#endif
unknown's avatar
unknown committed
219 220 221 222
  if (m_precision != col.m_precision ||
      m_scale != col.m_scale ||
      m_length != col.m_length ||
      m_cs != col.m_cs) {
unknown's avatar
unknown committed
223
    DBUG_RETURN(false);
224 225
  }
  if (m_autoIncrement != col.m_autoIncrement){
unknown's avatar
unknown committed
226
    DBUG_RETURN(false);
227 228
  }
  if(strcmp(m_defaultValue.c_str(), col.m_defaultValue.c_str()) != 0){
unknown's avatar
unknown committed
229
    DBUG_RETURN(false);
230
  }
unknown's avatar
unknown committed
231

unknown's avatar
unknown committed
232
  DBUG_RETURN(true);
233 234
}

unknown's avatar
unknown committed
235 236 237 238 239 240 241
NdbDictionary::Column *
NdbColumnImpl::create_psuedo(const char * name){
  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;
242 243
    col->m_impl.m_attrSize = 4;
    col->m_impl.m_arraySize = 1;
244 245 246 247 248
  } 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;
unknown's avatar
unknown committed
249 250 251
  } else if(!strcmp(name, "NDB$ROW_COUNT")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::ROW_COUNT;
unknown's avatar
unknown committed
252
    col->m_impl.m_attrSize = 8;
253
    col->m_impl.m_arraySize = 1;
unknown's avatar
unknown committed
254 255 256
  } else if(!strcmp(name, "NDB$COMMIT_COUNT")){
    col->setType(NdbDictionary::Column::Bigunsigned);
    col->m_impl.m_attrId = AttributeHeader::COMMIT_COUNT;
unknown's avatar
unknown committed
257
    col->m_impl.m_attrSize = 8;
258
    col->m_impl.m_arraySize = 1;
259 260 261 262 263
  } 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;
264 265 266 267 268
  } 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;
unknown's avatar
unknown committed
269 270 271
  } else {
    abort();
  }
unknown's avatar
unknown committed
272
  return col;
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
}

/**
 * NdbTableImpl
 */

NdbTableImpl::NdbTableImpl()
  : NdbDictionary::Table(* this), m_facade(this)
{
  init();
}

NdbTableImpl::NdbTableImpl(NdbDictionary::Table & f)
  : NdbDictionary::Table(* this), m_facade(&f)
{
  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(){
unknown's avatar
unknown committed
303 304
  m_changeMask= 0;
  m_tableId= RNIL;
305
  m_frm.clear();
unknown's avatar
unknown committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  m_fragmentType= NdbDictionary::Object::FragAllSmall;
  m_hashValueMask= 0;
  m_hashpointerValue= 0;
  m_logging= true;
  m_kvalue= 6;
  m_minLoadFactor= 78;
  m_maxLoadFactor= 80;
  m_keyLenInWords= 0;
  m_fragmentCount= 0;
  m_dictionary= NULL;
  m_index= NULL;
  m_indexType= NdbDictionary::Index::Undefined;
  m_noOfKeys= 0;
  m_noOfDistributionKeys= 0;
  m_noOfBlobs= 0;
  m_replicaCount= 0;
322 323 324 325 326
}

bool
NdbTableImpl::equal(const NdbTableImpl& obj) const 
{
unknown's avatar
unknown committed
327
  DBUG_ENTER("NdbTableImpl::equal");
328 329 330 331 332 333
  if ((m_internalName.c_str() == NULL) || 
      (strcmp(m_internalName.c_str(), "") == 0) ||
      (obj.m_internalName.c_str() == NULL) || 
      (strcmp(obj.m_internalName.c_str(), "") == 0)) {
    // Shallow equal
    if(strcmp(getName(), obj.getName()) != 0){
unknown's avatar
unknown committed
334 335
      DBUG_PRINT("info",("name %s != %s",getName(),obj.getName()));
      DBUG_RETURN(false);    
336 337 338 339
    }
  } else 
    // Deep equal
    if(strcmp(m_internalName.c_str(), obj.m_internalName.c_str()) != 0){
unknown's avatar
unknown committed
340 341 342 343 344
    {
      DBUG_PRINT("info",("m_internalName %s != %s",
			 m_internalName.c_str(),obj.m_internalName.c_str()));
      DBUG_RETURN(false);
    }
345 346
  }
  if(m_fragmentType != obj.m_fragmentType){
unknown's avatar
unknown committed
347 348
    DBUG_PRINT("info",("m_fragmentType %d != %d",m_fragmentType,obj.m_fragmentType));
    DBUG_RETURN(false);
349 350
  }
  if(m_columns.size() != obj.m_columns.size()){
unknown's avatar
unknown committed
351 352
    DBUG_PRINT("info",("m_columns.size %d != %d",m_columns.size(),obj.m_columns.size()));
    DBUG_RETURN(false);
353 354 355 356
  }

  for(unsigned i = 0; i<obj.m_columns.size(); i++){
    if(!m_columns[i]->equal(* obj.m_columns[i])){
unknown's avatar
unknown committed
357 358
      DBUG_PRINT("info",("m_columns [%d] != [%d]",i,i));
      DBUG_RETURN(false);
359 360 361 362
    }
  }
  
  if(m_logging != obj.m_logging){
unknown's avatar
unknown committed
363 364
    DBUG_PRINT("info",("m_logging %d != %d",m_logging,obj.m_logging));
    DBUG_RETURN(false);
365 366 367
  }

  if(m_kvalue != obj.m_kvalue){
unknown's avatar
unknown committed
368 369
    DBUG_PRINT("info",("m_kvalue %d != %d",m_kvalue,obj.m_kvalue));
    DBUG_RETURN(false);
370 371 372
  }

  if(m_minLoadFactor != obj.m_minLoadFactor){
unknown's avatar
unknown committed
373 374
    DBUG_PRINT("info",("m_minLoadFactor %d != %d",m_minLoadFactor,obj.m_minLoadFactor));
    DBUG_RETURN(false);
375 376 377
  }

  if(m_maxLoadFactor != obj.m_maxLoadFactor){
unknown's avatar
unknown committed
378 379
    DBUG_PRINT("info",("m_maxLoadFactor %d != %d",m_maxLoadFactor,obj.m_maxLoadFactor));
    DBUG_RETURN(false);
380 381
  }
  
unknown's avatar
unknown committed
382
   DBUG_RETURN(true);
383 384 385 386 387 388 389 390 391 392 393
}

void
NdbTableImpl::assign(const NdbTableImpl& org)
{
  m_tableId = org.m_tableId;
  m_internalName.assign(org.m_internalName);
  m_externalName.assign(org.m_externalName);
  m_newExternalName.assign(org.m_newExternalName);
  m_frm.assign(org.m_frm.get_data(), org.m_frm.length());
  m_fragmentType = org.m_fragmentType;
unknown's avatar
unknown committed
394
  m_fragmentCount = org.m_fragmentCount;
395 396 397 398

  for(unsigned i = 0; i<org.m_columns.size(); i++){
    NdbColumnImpl * col = new NdbColumnImpl();
    const NdbColumnImpl * iorg = org.m_columns[i];
unknown's avatar
unknown committed
399
    (* col) = (* iorg);
400 401 402 403 404 405 406 407 408 409 410 411
    m_columns.push_back(col);
  }

  m_logging = org.m_logging;
  m_kvalue = org.m_kvalue;
  m_minLoadFactor = org.m_minLoadFactor;
  m_maxLoadFactor = org.m_maxLoadFactor;
  
  if (m_index != 0)
    delete m_index;
  m_index = org.m_index;
  
412
  m_noOfDistributionKeys = org.m_noOfDistributionKeys;
413
  m_noOfKeys = org.m_noOfKeys;
414
  m_keyLenInWords = org.m_keyLenInWords;
unknown's avatar
unknown committed
415
  m_noOfBlobs = org.m_noOfBlobs;
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

  m_version = org.m_version;
  m_status = org.m_status;
}

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


void
NdbTableImpl::buildColumnHash(){
  const Uint32 size = m_columns.size();

unknown's avatar
unknown committed
440
  int i;
unknown's avatar
unknown committed
441
  for(i = 31; i >= 0; i--){
442 443 444 445 446 447 448 449
    if(((1 << i) & size) != 0){
      m_columnHashMask = (1 << (i + 1)) - 1;
      break;
    }
  }

  Vector<Uint32> hashValues;
  Vector<Vector<Uint32> > chains; chains.fill(size, hashValues);
unknown's avatar
unknown committed
450
  for(i = 0; i< (int) size; i++){
451 452 453 454 455 456 457 458 459 460 461 462 463
    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
unknown's avatar
unknown committed
464
  for(i = 0; i< (int) size; i++){
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
    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
}
unknown's avatar
unknown committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

Uint32
NdbTableImpl::get_nodes(Uint32 hashValue, const Uint16 ** nodes) const
{
  if(m_replicaCount > 0)
  {
    Uint32 fragmentId = hashValue & m_hashValueMask;
    if(fragmentId < m_hashpointerValue) 
    {
      fragmentId = hashValue & ((m_hashValueMask << 1) + 1);
    }
    Uint32 pos = fragmentId * m_replicaCount;
    if(pos + m_replicaCount <= m_fragments.size())
    {
      * nodes = m_fragments.getBase()+pos;
      return m_replicaCount;
    }
  }
  return 0;
}
522 523 524 525 526 527 528 529 530
  
/**
 * NdbIndexImpl
 */

NdbIndexImpl::NdbIndexImpl() : 
  NdbDictionary::Index(* this), 
  m_facade(this)
{
unknown's avatar
unknown committed
531
  init();
532 533 534 535 536 537
}

NdbIndexImpl::NdbIndexImpl(NdbDictionary::Index & f) : 
  NdbDictionary::Index(* this), 
  m_facade(&f)
{
unknown's avatar
unknown committed
538 539 540 541 542 543 544 545 546
  init();
}

void NdbIndexImpl::init()
{
  m_indexId= RNIL;
  m_type= NdbDictionary::Index::Undefined;
  m_logging= true;
  m_table= NULL;
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
}

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

577 578 579 580 581 582
const NdbTableImpl *
NdbIndexImpl::getIndexTable() const
{
  return m_table;
}

583 584 585 586 587 588 589 590
/**
 * NdbEventImpl
 */

NdbEventImpl::NdbEventImpl() : 
  NdbDictionary::Event(* this),
  m_facade(this)
{
unknown's avatar
unknown committed
591
  init();
592 593 594 595 596 597
}

NdbEventImpl::NdbEventImpl(NdbDictionary::Event & f) : 
  NdbDictionary::Event(* this),
  m_facade(&f)
{
unknown's avatar
unknown committed
598 599 600 601 602 603 604 605 606 607 608 609 610
  init();
}

void NdbEventImpl::init()
{
  m_eventId= RNIL;
  m_eventKey= RNIL;
  m_tableId= RNIL;
  mi_type= 0;
  m_dur= NdbDictionary::Event::ED_UNDEFINED;
  m_tableImpl= NULL;
  m_bufferId= RNIL;
  eventOp= NULL;
611 612 613 614 615 616 617 618 619 620 621 622 623
}

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

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

unknown's avatar
unknown committed
624 625 626 627 628
const char *NdbEventImpl::getName() const
{
  return m_externalName.c_str();
}

629 630 631 632 633 634 635
void 
NdbEventImpl::setTable(const NdbDictionary::Table& table)
{
  m_tableImpl= &NdbTableImpl::getImpl(table);
  m_tableName.assign(m_tableImpl->getName());
}

636 637 638 639 640 641
void 
NdbEventImpl::setTable(const char * table)
{
  m_tableName.assign(table);
}

unknown's avatar
unknown committed
642 643
const char *
NdbEventImpl::getTableName() const
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
{
  return m_tableName.c_str();
}

void
NdbEventImpl::addTableEvent(const NdbDictionary::Event::TableEvent t =  NdbDictionary::Event::TE_ALL)
{
  switch (t) {
  case NdbDictionary::Event::TE_INSERT : mi_type |= 1; break;
  case NdbDictionary::Event::TE_DELETE : mi_type |= 2; break;
  case NdbDictionary::Event::TE_UPDATE : mi_type |= 4; break;
  default: mi_type = 4 | 2 | 1; // all types
  }
}

void
unknown's avatar
unknown committed
660
NdbEventImpl::setDurability(NdbDictionary::Event::EventDurability d)
661 662 663 664
{
  m_dur = d;
}

unknown's avatar
unknown committed
665 666 667 668 669 670 671 672 673 674 675
NdbDictionary::Event::EventDurability
NdbEventImpl::getDurability() const
{
  return m_dur;
}

int NdbEventImpl::getNoOfEventColumns() const
{
  return m_attrIds.size() + m_columns.size();
}

676 677 678 679 680 681 682 683 684 685 686
/**
 * NdbDictionaryImpl
 */

NdbDictionaryImpl::NdbDictionaryImpl(Ndb &ndb)
  : NdbDictionary::Dictionary(* this), 
    m_facade(this), 
    m_receiver(m_error),
    m_ndb(ndb)
{
  m_globalHash = 0;
unknown's avatar
unknown committed
687
  m_local_table_data_size= 0;
688 689 690 691 692 693 694 695 696 697
}

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

unknown's avatar
unknown committed
701 702
static int f_dictionary_count = 0;

703 704
NdbDictionaryImpl::~NdbDictionaryImpl()
{
705
  NdbElement_t<Ndb_local_table_info> * curr = m_localHash.m_tableHash.getNext(0);
706 707 708
  if(m_globalHash){
    while(curr != 0){
      m_globalHash->lock();
709
      m_globalHash->release(curr->theData->m_table_impl);
710
      Ndb_local_table_info::destroy(curr->theData);
711 712 713 714 715
      m_globalHash->unlock();
      
      curr = m_localHash.m_tableHash.getNext(curr);
    }
    
716
    m_globalHash->lock();
717 718
    if(--f_dictionary_count == 0){
      delete NdbDictionary::Column::FRAGMENT; 
719
      delete NdbDictionary::Column::FRAGMENT_MEMORY;
720 721
      delete NdbDictionary::Column::ROW_COUNT;
      delete NdbDictionary::Column::COMMIT_COUNT;
722
      delete NdbDictionary::Column::ROW_SIZE;
unknown's avatar
unknown committed
723
      delete NdbDictionary::Column::RANGE_NO;
724
      NdbDictionary::Column::FRAGMENT= 0;
725
      NdbDictionary::Column::FRAGMENT_MEMORY= 0;
726 727
      NdbDictionary::Column::ROW_COUNT= 0;
      NdbDictionary::Column::COMMIT_COUNT= 0;
728
      NdbDictionary::Column::ROW_SIZE= 0;
unknown's avatar
unknown committed
729
      NdbDictionary::Column::RANGE_NO= 0;
730
    }
731
    m_globalHash->unlock();
732 733
  } else {
    assert(curr == 0);
unknown's avatar
unknown committed
734
  }
735 736
}

737
Ndb_local_table_info *
738
NdbDictionaryImpl::fetchGlobalTableImpl(const BaseString& internalTableName)
739 740
{
  NdbTableImpl *impl;
741

742
  m_globalHash->lock();
743
  impl = m_globalHash->get(internalTableName.c_str());
744 745 746
  m_globalHash->unlock();

  if (impl == 0){
747 748
    impl = m_receiver.getTable(internalTableName,
			       m_ndb.usingFullyQualifiedNames());
749
    m_globalHash->lock();
750
    m_globalHash->put(internalTableName.c_str(), impl);
751 752 753 754 755 756 757
    m_globalHash->unlock();
    
    if(impl == 0){
      return 0;
    }
  }

758 759
  Ndb_local_table_info *info=
    Ndb_local_table_info::create(impl, m_local_table_data_size);
760

761
  m_localHash.put(internalTableName.c_str(), info);
762 763 764 765 766 767

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

unknown's avatar
unknown committed
769
#if 0
770 771 772 773 774 775 776 777 778 779
bool
NdbDictionaryImpl::setTransporter(class TransporterFacade * tf)
{
  if(tf != 0){
    m_globalHash = &tf->m_globalDictCache;
    return m_receiver.setTransporter(tf);
  }
  
  return false;
}
unknown's avatar
unknown committed
780
#endif
781 782 783 784 785 786

bool
NdbDictionaryImpl::setTransporter(class Ndb* ndb, 
				  class TransporterFacade * tf)
{
  m_globalHash = &tf->m_globalDictCache;
unknown's avatar
unknown committed
787 788 789 790 791
  if(m_receiver.setTransporter(ndb, tf)){
    m_globalHash->lock();
    if(f_dictionary_count++ == 0){
      NdbDictionary::Column::FRAGMENT= 
	NdbColumnImpl::create_psuedo("NDB$FRAGMENT");
792 793
      NdbDictionary::Column::FRAGMENT_MEMORY= 
	NdbColumnImpl::create_psuedo("NDB$FRAGMENT_MEMORY");
unknown's avatar
unknown committed
794 795 796 797
      NdbDictionary::Column::ROW_COUNT= 
	NdbColumnImpl::create_psuedo("NDB$ROW_COUNT");
      NdbDictionary::Column::COMMIT_COUNT= 
	NdbColumnImpl::create_psuedo("NDB$COMMIT_COUNT");
798 799
      NdbDictionary::Column::ROW_SIZE=
	NdbColumnImpl::create_psuedo("NDB$ROW_SIZE");
800 801
      NdbDictionary::Column::RANGE_NO= 
	NdbColumnImpl::create_psuedo("NDB$RANGE_NO");
unknown's avatar
unknown committed
802 803
    }
    m_globalHash->unlock();
unknown's avatar
unknown committed
804
    return true;
unknown's avatar
unknown committed
805
  }
unknown's avatar
unknown committed
806
  return false;
807 808
}

809 810
NdbTableImpl *
NdbDictionaryImpl::getIndexTable(NdbIndexImpl * index,
811 812
				 NdbTableImpl * table)
{
813 814 815
  const BaseString internalName(
    m_ndb.internalize_index_name(table, index->getName()));
  return getTable(m_ndb.externalizeTableName(internalName.c_str()));
816 817
}

818
#if 0
819 820 821 822 823 824 825 826 827 828 829 830 831
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 ) {
832
    m_error.code= 4105;
833 834 835 836 837 838 839 840 841
    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;
}
842
#endif
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 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941

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_TABLE_DATA:
    tmp->execSUB_TABLE_DATA(signal, ptr);
    break;
  case GSN_SUB_GCP_COMPLETE_REP:
    tmp->execSUB_GCP_COMPLETE_REP(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;
  default:
    abort();
  }
}

void
942
NdbDictInterface::execNodeStatus(void* dictImpl, Uint32 aNode,
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
				 bool alive, bool nfCompleted)
{
  NdbDictInterface * tmp = (NdbDictInterface*)dictImpl;
  
  if(!alive && !nfCompleted){
    return;
  }
  
  if (!alive && nfCompleted){
    tmp->m_waiter.nodeFail(aNode);
  }
}

int
NdbDictInterface::dictSignal(NdbApiSignal* signal, 
			     LinearSectionPtr ptr[3],int noLSP,
			     const int useMasterNodeId,
			     const Uint32 RETRIES,
			     const WaitSignalType wst,
			     const int theWait,
			     const int *errcodes,
			     const int noerrcodes,
			     const int temporaryMask)
{
unknown's avatar
unknown committed
967 968
  DBUG_ENTER("NdbDictInterface::dictSignal");
  DBUG_PRINT("enter", ("useMasterNodeId: %d", useMasterNodeId));
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  for(Uint32 i = 0; i<RETRIES; i++){
    //if (useMasterNodeId == 0)
    m_buffer.clear();

    // Protected area
    m_transporter->lock_mutex();
    Uint32 aNodeId;
    if (useMasterNodeId) {
      if ((m_masterNodeId == 0) ||
	  (!m_transporter->get_node_alive(m_masterNodeId))) {
	m_masterNodeId = m_transporter->get_an_alive_node();
      }//if
      aNodeId = m_masterNodeId;
    } else {
      aNodeId = m_transporter->get_an_alive_node();
    }
    if(aNodeId == 0){
986
      m_error.code= 4009;
987
      m_transporter->unlock_mutex();
unknown's avatar
unknown committed
988
      DBUG_RETURN(-1);
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    }
    {
      int r;
      if (ptr) {
#ifdef EVENT_DEBUG
	printf("Long signal %d ptr", noLSP);
	for (int q=0;q<noLSP;q++) {
	  printf(" sz %d", ptr[q].sz);
	}
	printf("\n");
#endif
	r = m_transporter->sendFragmentedSignal(signal, aNodeId, ptr, noLSP);
      } else {
#ifdef EVENT_DEBUG
	printf("Short signal\n");
#endif
	r = m_transporter->sendSignal(signal, aNodeId);
      }
      if(r != 0){
	m_transporter->unlock_mutex();
	continue;
      }
    }
    
1013
    m_error.code= 0;
1014 1015 1016 1017 1018
    
    m_waiter.m_node = aNodeId;
    m_waiter.m_state = wst;

    m_waiter.wait(theWait);
unknown's avatar
unknown committed
1019
    m_transporter->unlock_mutex();    
1020 1021 1022 1023
    // End of Protected area  
    
    if(m_waiter.m_state == NO_WAIT && m_error.code == 0){
      // Normal return
unknown's avatar
unknown committed
1024
      DBUG_RETURN(0);
1025 1026 1027 1028 1029 1030 1031 1032
    }
    
    /**
     * Handle error codes
     */
    if(m_waiter.m_state == WAIT_NODE_FAILURE)
      continue;

1033 1034 1035 1036 1037 1038
    if(m_waiter.m_state == WST_WAIT_TIMEOUT)
    {
      m_error.code = 4008;
      DBUG_RETURN(-1);
    }
    
1039 1040 1041 1042 1043 1044 1045 1046
    if ( (temporaryMask & m_error.code) != 0 ) {
      continue;
    }
    if (errcodes) {
      int doContinue = 0;
      for (int j=0; j < noerrcodes; j++)
	if(m_error.code == errcodes[j]) {
	  doContinue = 1;
unknown's avatar
unknown committed
1047
	  break;
1048 1049 1050 1051 1052
	}
      if (doContinue)
	continue;
    }

unknown's avatar
unknown committed
1053
    DBUG_RETURN(-1);
1054
  }
unknown's avatar
unknown committed
1055
  DBUG_RETURN(-1);
1056
}
1057
#if 0
unknown's avatar
unknown committed
1058 1059 1060 1061 1062
/*
  Get dictionary information for a table using table id as reference

  DESCRIPTION
    Sends a GET_TABINFOREQ signal containing the table id
1063
 */
unknown's avatar
unknown committed
1064
NdbTableImpl *
1065
NdbDictInterface::getTable(int tableId, bool fullyQualifiedNames)
1066 1067
{
  NdbApiSignal tSignal(m_reference);
unknown's avatar
unknown committed
1068 1069
  GetTabInfoReq* const req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());

1070 1071
  req->senderRef = m_reference;
  req->senderData = 0;
unknown's avatar
unknown committed
1072
  req->requestType =
1073 1074 1075 1076 1077
    GetTabInfoReq::RequestById | GetTabInfoReq::LongSignalConf;
  req->tableId = tableId;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_GET_TABINFOREQ;
  tSignal.theLength = GetTabInfoReq::SignalLength;
unknown's avatar
unknown committed
1078

1079
  return getTable(&tSignal, 0, 0, fullyQualifiedNames);
1080
}
1081
#endif
1082

unknown's avatar
unknown committed
1083 1084 1085 1086 1087 1088 1089 1090

/*
  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
*/
unknown's avatar
unknown committed
1091

unknown's avatar
unknown committed
1092
NdbTableImpl *
1093
NdbDictInterface::getTable(const BaseString& name, bool fullyQualifiedNames)
1094 1095
{
  NdbApiSignal tSignal(m_reference);
unknown's avatar
unknown committed
1096
  GetTabInfoReq* const req = CAST_PTR(GetTabInfoReq, tSignal.getDataPtrSend());
1097

1098 1099
  const Uint32 namelen= name.length() + 1; // NULL terminated
  const Uint32 namelen_words= (namelen + 3) >> 2; // Size in words
unknown's avatar
unknown committed
1100 1101 1102 1103

  req->senderRef= m_reference;
  req->senderData= 0;
  req->requestType=
1104
    GetTabInfoReq::RequestByName | GetTabInfoReq::LongSignalConf;
1105
  req->tableNameLen= namelen;
unknown's avatar
unknown committed
1106 1107 1108 1109
  tSignal.theReceiversBlockNumber= DBDICT;
  tSignal.theVerId_signalNumber= GSN_GET_TABINFOREQ;
  tSignal.theLength= GetTabInfoReq::SignalLength;

1110 1111 1112 1113 1114
  // 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);

1115
  LinearSectionPtr ptr[1];
1116 1117
  ptr[0].p= (Uint32*)m_buffer.get_data();
  ptr[0].sz= namelen_words;
unknown's avatar
unknown committed
1118

1119
  return getTable(&tSignal, ptr, 1, fullyQualifiedNames);
1120 1121
}

unknown's avatar
unknown committed
1122

1123
NdbTableImpl *
unknown's avatar
unknown committed
1124
NdbDictInterface::getTable(class NdbApiSignal * signal,
1125
			   LinearSectionPtr ptr[3],
1126
			   Uint32 noOfSections, bool fullyQualifiedNames)
1127
{
unknown's avatar
unknown committed
1128 1129
  int errCodes[] = {GetTabInfoRef::Busy };

1130 1131 1132 1133 1134
  int r = dictSignal(signal,ptr,noOfSections,
		     0/*do not use masternode id*/,
		     100,
		     WAIT_GET_TAB_INFO_REQ,
		     WAITFOR_RESPONSE_TIMEOUT,
unknown's avatar
unknown committed
1135
		     errCodes, 1);
1136 1137 1138
  if (r) return 0;

  NdbTableImpl * rt = 0;
1139 1140 1141
  m_error.code= parseTableInfo(&rt, 
			       (Uint32*)m_buffer.get_data(), 
			       m_buffer.length() / 4, fullyQualifiedNames);
1142 1143
  if (rt != 0)
    rt->buildColumnHash();
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
  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])
{
  const GetTabInfoRef* ref = CAST_CONSTPTR(GetTabInfoRef, signal->getDataPtr());

1177
  m_error.code= ref->errorCode;
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
  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 },
  { -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 },
  { -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 },
unknown's avatar
unknown committed
1248
  { DictTabInfo::StateBackup,        NdbDictionary::Object::StateBackup },
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
  { 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,
1271 1272
				 const Uint32 * data, Uint32 len,
				 bool fullyQualifiedNames)
1273
{
unknown's avatar
unknown committed
1274 1275
  DBUG_ENTER("NdbDictInterface::parseTableInfo");

1276 1277 1278 1279 1280 1281 1282 1283 1284
  SimplePropertiesLinearReader it(data, len);
  DictTabInfo::Table tableDesc; tableDesc.init();
  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::unpack(it, &tableDesc, 
			       DictTabInfo::TableMapping, 
			       DictTabInfo::TableMappingSize, 
			       true, true);
  
  if(s != SimpleProperties::Break){
unknown's avatar
unknown committed
1285
    DBUG_RETURN(703);
1286 1287
  }
  const char * internalName = tableDesc.TableName;
1288
  const char * externalName = Ndb::externalizeTableName(internalName, fullyQualifiedNames);
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

  NdbTableImpl * impl = new NdbTableImpl();
  impl->m_tableId = tableDesc.TableId;
  impl->m_version = tableDesc.TableVersion;
  impl->m_status = NdbDictionary::Object::Retrieved;
  impl->m_internalName.assign(internalName);
  impl->m_externalName.assign(externalName);

  impl->m_frm.assign(tableDesc.FrmData, tableDesc.FrmLen);
  
  impl->m_fragmentType = (NdbDictionary::Object::FragmentType)
    getApiConstant(tableDesc.FragmentType, 
		   fragmentTypeMapping, 
		   (Uint32)NdbDictionary::Object::FragUndefined);
  
  impl->m_logging = tableDesc.TableLoggedFlag;
  impl->m_kvalue = tableDesc.TableKValue;
  impl->m_minLoadFactor = tableDesc.MinLoadFactor;
  impl->m_maxLoadFactor = tableDesc.MaxLoadFactor;

  impl->m_indexType = (NdbDictionary::Index::Type)
    getApiConstant(tableDesc.TableType,
		   indexTypeMapping,
		   NdbDictionary::Index::Undefined);
  
  if(impl->m_indexType == NdbDictionary::Index::Undefined){
  } else {
    const char * externalPrimary = 
1317
      Ndb::externalizeTableName(tableDesc.PrimaryTable, fullyQualifiedNames);
1318 1319 1320 1321 1322
    impl->m_primaryTable.assign(externalPrimary);
  }
  
  Uint32 keyInfoPos = 0;
  Uint32 keyCount = 0;
unknown's avatar
unknown committed
1323
  Uint32 blobCount = 0;
1324
  Uint32 distKeys = 0;
1325
  
1326 1327
  Uint32 i;
  for(i = 0; i < tableDesc.NoOfAttributes; i++) {
1328 1329 1330 1331 1332 1333 1334 1335
    DictTabInfo::Attribute attrDesc; attrDesc.init();
    s = SimpleProperties::unpack(it, 
				 &attrDesc, 
				 DictTabInfo::AttributeMapping, 
				 DictTabInfo::AttributeMappingSize, 
				 true, true);
    if(s != SimpleProperties::Break){
      delete impl;
unknown's avatar
unknown committed
1336
      DBUG_RETURN(703);
1337 1338 1339 1340 1341
    }
    
    NdbColumnImpl * col = new NdbColumnImpl();
    col->m_attrId = attrDesc.AttributeId;
    col->setName(attrDesc.AttributeName);
unknown's avatar
unknown committed
1342 1343 1344

    // check type and compute attribute size and array size
    if (! attrDesc.translateExtType()) {
1345
      delete impl;
unknown's avatar
unknown committed
1346
      DBUG_RETURN(703);
1347
    }
1348
    col->m_type = (NdbDictionary::Column::Type)attrDesc.AttributeExtType;
unknown's avatar
unknown committed
1349
    col->m_precision = (attrDesc.AttributeExtPrecision & 0xFFFF);
1350 1351
    col->m_scale = attrDesc.AttributeExtScale;
    col->m_length = attrDesc.AttributeExtLength;
unknown's avatar
unknown committed
1352 1353 1354 1355 1356
    // 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;
unknown's avatar
unknown committed
1357
      DBUG_RETURN(703);
unknown's avatar
unknown committed
1358 1359 1360 1361 1362
    }
    if (col->getCharType()) {
      col->m_cs = get_charset(cs_number, MYF(0));
      if (col->m_cs == NULL) {
        delete impl;
unknown's avatar
unknown committed
1363
        DBUG_RETURN(743);
unknown's avatar
unknown committed
1364 1365
      }
    }
1366 1367
    col->m_attrSize = (1 << attrDesc.AttributeSize) / 8;
    col->m_arraySize = attrDesc.AttributeArraySize;
1368 1369 1370 1371 1372
    if(attrDesc.AttributeSize == 0)
    {
      col->m_attrSize = 4;
      col->m_arraySize = (attrDesc.AttributeArraySize + 31) >> 5;
    }
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
    
    col->m_pk = attrDesc.AttributeKeyFlag;
    col->m_distributionKey = attrDesc.AttributeDKey;
    col->m_nullable = attrDesc.AttributeNullableFlag;
    col->m_autoIncrement = (attrDesc.AttributeAutoIncrement ? true : false);
    col->m_autoIncrementInitialValue = ~0;
    col->m_defaultValue.assign(attrDesc.AttributeDefaultValue);

    if(attrDesc.AttributeKeyFlag){
      col->m_keyInfoPos = keyInfoPos + 1;
      keyInfoPos += ((col->m_attrSize * col->m_arraySize + 3) / 4);
      keyCount++;
1385 1386 1387
      
      if(attrDesc.AttributeDKey)
	distKeys++;
1388 1389 1390
    } else {
      col->m_keyInfoPos = 0;
    }
unknown's avatar
unknown committed
1391 1392
    if (col->getBlobType())
      blobCount++;
1393 1394 1395 1396 1397
    NdbColumnImpl * null = 0;
    impl->m_columns.fill(attrDesc.AttributeId, null);
    if(impl->m_columns[attrDesc.AttributeId] != 0){
      delete col;
      delete impl;
unknown's avatar
unknown committed
1398
      DBUG_RETURN(703);
1399 1400 1401 1402
    }
    impl->m_columns[attrDesc.AttributeId] = col;
    it.next();
  }
unknown's avatar
unknown committed
1403

1404
  impl->m_noOfKeys = keyCount;
unknown's avatar
unknown committed
1405
  impl->m_keyLenInWords = keyInfoPos;
unknown's avatar
unknown committed
1406
  impl->m_noOfBlobs = blobCount;
1407
  impl->m_noOfDistributionKeys = distKeys;
unknown's avatar
unknown committed
1408 1409 1410

  if(tableDesc.FragmentDataLen > 0)
  {
1411 1412 1413
    Uint32 replicaCount = tableDesc.FragmentData[0];
    Uint32 fragCount = tableDesc.FragmentData[1];

unknown's avatar
unknown committed
1414 1415 1416 1417 1418 1419 1420 1421 1422
    impl->m_replicaCount = replicaCount;
    impl->m_fragmentCount = fragCount;

    for(i = 0; i<(fragCount*replicaCount); i++)
    {
      impl->m_fragments.push_back(tableDesc.FragmentData[i+2]);
    }

    Uint32 topBit = (1 << 31);
unknown's avatar
unknown committed
1423
    for(; topBit && !(fragCount & topBit); ){
unknown's avatar
unknown committed
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
      topBit >>= 1;
    }
    impl->m_hashValueMask = topBit - 1;
    impl->m_hashpointerValue = fragCount - (impl->m_hashValueMask + 1);
  }
  else
  {
    impl->m_fragmentCount = tableDesc.FragmentCount;
    impl->m_replicaCount = 0;
    impl->m_hashValueMask = 0;
    impl->m_hashpointerValue = 0;
  }

1437 1438 1439 1440 1441 1442 1443 1444 1445
  if(distKeys == 0)
  {
    for(i = 0; i < tableDesc.NoOfAttributes; i++)
    {
      if(impl->m_columns[i]->getPrimaryKey())
	impl->m_columns[i]->m_distributionKey = true;
    }
  }
  
1446
  * ret = impl;
unknown's avatar
unknown committed
1447

unknown's avatar
unknown committed
1448
  DBUG_RETURN(0);
1449 1450 1451 1452 1453
}

/*****************************************************************
 * Create table and alter table
 */
unknown's avatar
unknown committed
1454 1455 1456 1457 1458 1459 1460 1461
int
NdbDictionaryImpl::createTable(NdbTableImpl &t)
{ 
  if (m_receiver.createTable(m_ndb, t) != 0)
    return -1;
  if (t.m_noOfBlobs == 0)
    return 0;
  // update table def from DICT
1462
  Ndb_local_table_info *info=
1463
    get_local_table_info(t.m_internalName,false);
1464
  if (info == NULL) {
1465
    m_error.code= 709;
unknown's avatar
unknown committed
1466 1467
    return -1;
  }
1468
  if (createBlobTables(*(info->m_table_impl)) != 0) {
unknown's avatar
unknown committed
1469 1470
    int save_code = m_error.code;
    (void)dropTable(t);
1471
    m_error.code= save_code;
unknown's avatar
unknown committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    return -1;
  }
  return 0;
}

int
NdbDictionaryImpl::createBlobTables(NdbTableImpl &t)
{
  for (unsigned i = 0; i < t.m_columns.size(); i++) {
    NdbColumnImpl & c = *t.m_columns[i];
unknown's avatar
unknown committed
1482
    if (! c.getBlobType() || c.getPartSize() == 0)
unknown's avatar
unknown committed
1483 1484 1485 1486 1487
      continue;
    NdbTableImpl bt;
    NdbBlob::getBlobTable(bt, &t, &c);
    if (createTable(bt) != 0)
      return -1;
unknown's avatar
unknown committed
1488
    // Save BLOB table handle
1489
    Ndb_local_table_info *info=
1490
      get_local_table_info(bt.m_internalName, false);
1491 1492 1493 1494
    if (info == 0) {
      return -1;
    }
    c.m_blobTable = info->m_table_impl;
unknown's avatar
unknown committed
1495
  }
unknown's avatar
unknown committed
1496 1497 1498 1499 1500 1501 1502
  
  return 0;
}

int
NdbDictionaryImpl::addBlobTables(NdbTableImpl &t)
{
1503 1504 1505 1506 1507
  unsigned n= t.m_noOfBlobs;
  // 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--;
unknown's avatar
unknown committed
1508 1509 1510
    NdbColumnImpl & c = *t.m_columns[i];
    if (! c.getBlobType() || c.getPartSize() == 0)
      continue;
1511
    n--;
1512
    char btname[NdbBlobImpl::BlobTableNameSize];
unknown's avatar
unknown committed
1513 1514
    NdbBlob::getBlobTableName(btname, &t, &c);
    // Save BLOB table handle
1515 1516 1517 1518
    NdbTableImpl * cachedBlobTable = getTable(btname);
    if (cachedBlobTable == 0) {
      return -1;
    }
unknown's avatar
unknown committed
1519 1520 1521
    c.m_blobTable = cachedBlobTable;
  }
  
unknown's avatar
unknown committed
1522 1523 1524
  return 0;
}

1525 1526 1527 1528 1529 1530 1531 1532 1533
int 
NdbDictInterface::createTable(Ndb & ndb,
			      NdbTableImpl & impl)
{
  return createOrAlterTable(ndb, impl, false);
}

int NdbDictionaryImpl::alterTable(NdbTableImpl &impl)
{
1534
  BaseString internalName(impl.m_internalName);
1535
  const char * originalInternalName = internalName.c_str();
1536 1537

  DBUG_ENTER("NdbDictionaryImpl::alterTable");
1538 1539 1540
  Ndb_local_table_info * local = 0;
  if((local= get_local_table_info(originalInternalName, false)) == 0)
  {
1541
    m_error.code = 709;
1542
    DBUG_RETURN(-1);
1543
  }
1544

1545 1546 1547 1548
  // 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
1549 1550 1551 1552 1553
    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);
1554
  }
unknown's avatar
unknown committed
1555
  DBUG_RETURN(ret);
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
}

int 
NdbDictInterface::alterTable(Ndb & ndb,
			      NdbTableImpl & impl)
{
  return createOrAlterTable(ndb, impl, true);
}

int 
NdbDictInterface::createOrAlterTable(Ndb & ndb,
				     NdbTableImpl & impl,
				     bool alter)
{
1570
  DBUG_ENTER("NdbDictInterface::createOrAlterTable");
unknown's avatar
unknown committed
1571
  unsigned i;
1572
  if((unsigned)impl.getNoOfPrimaryKeys() > NDB_MAX_NO_OF_ATTRIBUTES_IN_KEY){
1573
    m_error.code= 4317;
1574
    DBUG_RETURN(-1);
1575 1576 1577
  }
  unsigned sz = impl.m_columns.size();
  if (sz > NDB_MAX_ATTRIBUTES_IN_TABLE){
1578
    m_error.code= 4318;
1579
    DBUG_RETURN(-1);
1580 1581
  }

unknown's avatar
unknown committed
1582 1583 1584 1585 1586
  if (!impl.m_newExternalName.empty()) {
    impl.m_externalName.assign(impl.m_newExternalName);
    AlterTableReq::setNameFlag(impl.m_changeMask, true);
  }

1587 1588 1589
  //validate();
  //aggregate();

1590 1591
  const BaseString internalName(
    ndb.internalize_table_name(impl.m_externalName.c_str()));
1592 1593 1594
  impl.m_internalName.assign(internalName);
  UtilBufferWriter w(m_buffer);
  DictTabInfo::Table tmpTab; tmpTab.init();
1595 1596 1597
  BaseString::snprintf(tmpTab.TableName,
	   sizeof(tmpTab.TableName),
	   internalName.c_str());
1598 1599

  bool haveAutoIncrement = false;
unknown's avatar
unknown committed
1600
  Uint64 autoIncrementValue = 0;
1601
  Uint32 distKeys= 0;
unknown's avatar
unknown committed
1602
  for(i = 0; i<sz; i++){
1603 1604 1605 1606 1607
    const NdbColumnImpl * col = impl.m_columns[i];
    if(col == 0)
      continue;
    if (col->m_autoIncrement) {
      if (haveAutoIncrement) {
1608
        m_error.code= 4335;
unknown's avatar
unknown committed
1609
        DBUG_RETURN(-1);
1610 1611 1612
      }
      haveAutoIncrement = true;
      autoIncrementValue = col->m_autoIncrementInitialValue;
1613 1614 1615
    }
    if (col->m_distributionKey)
      distKeys++;
1616 1617 1618 1619
  }

  // Check max length of frm data
  if (impl.m_frm.length() > MAX_FRM_DATA_SIZE){
1620
    m_error.code= 1229;
1621
    DBUG_RETURN(-1);
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
  }
  tmpTab.FrmLen = impl.m_frm.length();
  memcpy(tmpTab.FrmData, impl.m_frm.get_data(), impl.m_frm.length());

  tmpTab.TableLoggedFlag = impl.m_logging;
  tmpTab.TableKValue = impl.m_kvalue;
  tmpTab.MinLoadFactor = impl.m_minLoadFactor;
  tmpTab.MaxLoadFactor = impl.m_maxLoadFactor;
  tmpTab.TableType = DictTabInfo::UserTable;
  tmpTab.NoOfAttributes = sz;
  
  tmpTab.FragmentType = getKernelConstant(impl.m_fragmentType,
					  fragmentTypeMapping,
					  DictTabInfo::AllNodesSmallTable);
  tmpTab.TableVersion = rand();

  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
			     &tmpTab,
			     DictTabInfo::TableMapping, 
			     DictTabInfo::TableMappingSize, true);
  
  if(s != SimpleProperties::Eof){
    abort();
  }
  
1648 1649 1650
  if (distKeys == impl.m_noOfKeys)
    distKeys= 0;
  impl.m_noOfDistributionKeys= distKeys;
unknown's avatar
unknown committed
1651
  
unknown's avatar
unknown committed
1652
  for(i = 0; i<sz; i++){
1653 1654 1655 1656 1657
    const NdbColumnImpl * col = impl.m_columns[i];
    if(col == 0)
      continue;
    
    DictTabInfo::Attribute tmpAttr; tmpAttr.init();
1658
    BaseString::snprintf(tmpAttr.AttributeName, sizeof(tmpAttr.AttributeName), 
1659 1660
	     col->m_name.c_str());
    tmpAttr.AttributeId = i;
unknown's avatar
unknown committed
1661
    tmpAttr.AttributeKeyFlag = col->m_pk;
1662
    tmpAttr.AttributeNullableFlag = col->m_nullable;
1663
    tmpAttr.AttributeDKey = distKeys ? col->m_distributionKey : 0;
1664

1665
    tmpAttr.AttributeExtType = (Uint32)col->m_type;
unknown's avatar
unknown committed
1666
    tmpAttr.AttributeExtPrecision = ((unsigned)col->m_precision & 0xFFFF);
1667 1668
    tmpAttr.AttributeExtScale = col->m_scale;
    tmpAttr.AttributeExtLength = col->m_length;
unknown's avatar
unknown committed
1669 1670 1671

    // check type and compute attribute size and array size
    if (! tmpAttr.translateExtType()) {
1672
      m_error.code= 703;
unknown's avatar
unknown committed
1673 1674
      DBUG_RETURN(-1);
    }
unknown's avatar
unknown committed
1675 1676
    // charset is defined exactly for char types
    if (col->getCharType() != (col->m_cs != NULL)) {
1677
      m_error.code= 703;
1678
      DBUG_RETURN(-1);
unknown's avatar
unknown committed
1679 1680 1681
    }
    // primary key type check
    if (col->m_pk && ! NdbSqlUtil::usable_in_pk(col->m_type, col->m_cs)) {
unknown's avatar
unknown committed
1682
      m_error.code= (col->m_cs != 0 ? 743 : 739);
1683
      DBUG_RETURN(-1);
unknown's avatar
unknown committed
1684
    }
unknown's avatar
unknown committed
1685
    // distribution key not supported for Char attribute
unknown's avatar
unknown committed
1686
    if (distKeys && col->m_distributionKey && col->m_cs != NULL) {
1687
      m_error.code= 745;
unknown's avatar
unknown committed
1688
      DBUG_RETURN(-1);
unknown's avatar
unknown committed
1689
    }
unknown's avatar
unknown committed
1690 1691 1692 1693
    // charset in upper half of precision
    if (col->getCharType()) {
      tmpAttr.AttributeExtPrecision |= (col->m_cs->number << 16);
    }
1694 1695

    tmpAttr.AttributeAutoIncrement = col->m_autoIncrement;
1696
    BaseString::snprintf(tmpAttr.AttributeDefaultValue, 
1697 1698 1699 1700 1701
	     sizeof(tmpAttr.AttributeDefaultValue),
	     col->m_defaultValue.c_str());
    s = SimpleProperties::pack(w, 
			       &tmpAttr,
			       DictTabInfo::AttributeMapping, 
unknown's avatar
unknown committed
1702
			       DictTabInfo::AttributeMappingSize, true);
1703 1704 1705 1706 1707
    w.add(DictTabInfo::AttributeEnd, 1);
  }

  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
1708
  
unknown's avatar
unknown committed
1709
  LinearSectionPtr ptr[1];
1710 1711 1712 1713 1714
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = m_buffer.length() / 4;
  int ret;
  if (alter)
  {
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
    AlterTableReq * const req = 
      CAST_PTR(AlterTableReq, tSignal.getDataPtrSend());
    
    req->senderRef = m_reference;
    req->senderData = 0;
    req->changeMask = impl.m_changeMask;
    req->tableId = impl.m_tableId;
    req->tableVersion = impl.m_version;;
    tSignal.theVerId_signalNumber   = GSN_ALTER_TABLE_REQ;
    tSignal.theLength = AlterTableReq::SignalLength;
1725
    ret= alterTable(&tSignal, ptr);
1726
  }
1727 1728
  else
  {
1729 1730 1731 1732 1733 1734 1735
    CreateTableReq * const req = 
      CAST_PTR(CreateTableReq, tSignal.getDataPtrSend());
    
    req->senderRef = m_reference;
    req->senderData = 0;
    tSignal.theVerId_signalNumber   = GSN_CREATE_TABLE_REQ;
    tSignal.theLength = CreateTableReq::SignalLength;
1736 1737 1738
    ret= createTable(&tSignal, ptr);

    if (ret)
unknown's avatar
unknown committed
1739
      DBUG_RETURN(ret);
1740 1741 1742 1743 1744

    if (haveAutoIncrement) {
      if (!ndb.setAutoIncrementValue(impl.m_externalName.c_str(),
				     autoIncrementValue)) {
	if (ndb.theError.code == 0) {
1745
	  m_error.code= 4336;
1746 1747 1748 1749 1750
	  ndb.theError = m_error;
	} else
	  m_error= ndb.theError;
	ret = -1; // errorcode set in initialize_autoincrement
      }
1751 1752
    }
  }
1753
  DBUG_RETURN(ret);
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
}

int
NdbDictInterface::createTable(NdbApiSignal* signal, LinearSectionPtr ptr[3])
{
#if DEBUG_PRINT
  ndbout_c("BufferLen = %d", ptr[0].sz);
  SimplePropertiesLinearReader r(ptr[0].p, ptr[0].sz);
  r.printAll(ndbout);
#endif
  const int noErrCodes = 2;
  int errCodes[noErrCodes] = 
     {CreateTableRef::Busy,
      CreateTableRef::NotMaster};
  return dictSignal(signal,ptr,1,
		    1/*use masternode id*/,
		    100,
		    WAIT_CREATE_INDX_REQ,
		    WAITFOR_RESPONSE_TIMEOUT,
		    errCodes,noErrCodes);
}


void
NdbDictInterface::execCREATE_TABLE_CONF(NdbApiSignal * signal,
					LinearSectionPtr ptr[3])
{
1781
#if 0
1782 1783 1784 1785
  const CreateTableConf* const conf=
    CAST_CONSTPTR(CreateTableConf, signal->getDataPtr());
  Uint32 tableId= conf->tableId;
  Uint32 tableVersion= conf->tableVersion;
1786
#endif
1787 1788 1789 1790 1791 1792 1793
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execCREATE_TABLE_REF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
1794 1795
  const CreateTableRef* const ref=
    CAST_CONSTPTR(CreateTableRef, signal->getDataPtr());
1796
  m_error.code= ref->errorCode;
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
}

int
NdbDictInterface::alterTable(NdbApiSignal* signal, LinearSectionPtr ptr[3])
{
#if DEBUG_PRINT
  ndbout_c("BufferLen = %d", ptr[0].sz);
  SimplePropertiesLinearReader r(ptr[0].p, ptr[0].sz);
  r.printAll(ndbout);
#endif
  const int noErrCodes = 2;
  int errCodes[noErrCodes] =
    {AlterTableRef::NotMaster,
     AlterTableRef::Busy};
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
  int r = dictSignal(signal,ptr,1,
		     1/*use masternode id*/,
		     100,WAIT_ALTER_TAB_REQ,
		     WAITFOR_RESPONSE_TIMEOUT,
		     errCodes, noErrCodes);
  if(m_error.code == AlterTableRef::InvalidTableVersion) {
    // Clear caches and try again
    return INCOMPATIBLE_VERSION;
  }

  return r;
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
}

void
NdbDictInterface::execALTER_TABLE_CONF(NdbApiSignal * signal,
                                       LinearSectionPtr ptr[3])
{
  //AlterTableConf* const conf = CAST_CONSTPTR(AlterTableConf, signal->getDataPtr());
  m_waiter.signal(NO_WAIT);
}

void
NdbDictInterface::execALTER_TABLE_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
  const AlterTableRef * const ref = 
    CAST_CONSTPTR(AlterTableRef, signal->getDataPtr());
1840
  m_error.code= ref->errorCode;
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);
}

/*****************************************************************
 * Drop table
 */
int
NdbDictionaryImpl::dropTable(const char * name)
{
unknown's avatar
unknown committed
1851 1852
  DBUG_ENTER("NdbDictionaryImpl::dropTable");
  DBUG_PRINT("enter",("name: %s", name));
1853 1854
  NdbTableImpl * tab = getTable(name);
  if(tab == 0){
1855
    DBUG_RETURN(-1);
1856 1857 1858 1859 1860
  }
  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) {
1861
    const BaseString internalTableName(m_ndb.internalize_table_name(name));
1862

1863 1864
    DBUG_PRINT("info",("INCOMPATIBLE_VERSION internal_name: %s", internalTableName.c_str()));
    m_localHash.drop(internalTableName.c_str());
1865
    m_globalHash->lock();
1866
    tab->m_status = NdbDictionary::Object::Invalid;
1867
    m_globalHash->drop(tab);
1868
    m_globalHash->unlock();
unknown's avatar
unknown committed
1869
    DBUG_RETURN(dropTable(name));
1870 1871
  }

unknown's avatar
unknown committed
1872
  DBUG_RETURN(ret);
1873 1874 1875 1876 1877
}

int
NdbDictionaryImpl::dropTable(NdbTableImpl & impl)
{
unknown's avatar
unknown committed
1878
  int res;
1879 1880 1881 1882 1883 1884
  const char * name = impl.getName();
  if(impl.m_status == NdbDictionary::Object::New){
    return dropTable(name);
  }

  if (impl.m_indexType != NdbDictionary::Index::Undefined) {
1885
    m_receiver.m_error.code= 1228;
1886 1887 1888 1889
    return -1;
  }

  List list;
unknown's avatar
unknown committed
1890
  if ((res = listIndexes(list, impl.m_tableId)) == -1){
1891
    return -1;
unknown's avatar
unknown committed
1892
  }
1893 1894
  for (unsigned i = 0; i < list.count; i++) {
    const List::Element& element = list.elements[i];
unknown's avatar
unknown committed
1895 1896
    if ((res = dropIndex(element.name, name)) == -1)
    {
1897
      return -1;
unknown's avatar
unknown committed
1898
    }
1899
  }
unknown's avatar
unknown committed
1900
  
unknown's avatar
unknown committed
1901
  if (impl.m_noOfBlobs != 0) {
unknown's avatar
unknown committed
1902
    if (dropBlobTables(impl) != 0){
unknown's avatar
unknown committed
1903
      return -1;
unknown's avatar
unknown committed
1904
    }
unknown's avatar
unknown committed
1905
  }
unknown's avatar
unknown committed
1906
  
1907
  int ret = m_receiver.dropTable(impl);  
unknown's avatar
unknown committed
1908
  if(ret == 0 || m_error.code == 709){
1909
    const char * internalTableName = impl.m_internalName.c_str();
1910

unknown's avatar
unknown committed
1911
    
1912 1913
    m_localHash.drop(internalTableName);
    m_globalHash->lock();
1914
    impl.m_status = NdbDictionary::Object::Invalid;
1915 1916
    m_globalHash->drop(&impl);
    m_globalHash->unlock();
unknown's avatar
unknown committed
1917 1918

    return 0;
1919 1920 1921 1922 1923
  }
  
  return ret;
}

unknown's avatar
unknown committed
1924 1925 1926
int
NdbDictionaryImpl::dropBlobTables(NdbTableImpl & t)
{
unknown's avatar
unknown committed
1927
  DBUG_ENTER("NdbDictionaryImpl::dropBlobTables");
unknown's avatar
unknown committed
1928 1929
  for (unsigned i = 0; i < t.m_columns.size(); i++) {
    NdbColumnImpl & c = *t.m_columns[i];
unknown's avatar
unknown committed
1930
    if (! c.getBlobType() || c.getPartSize() == 0)
unknown's avatar
unknown committed
1931
      continue;
1932
    char btname[NdbBlobImpl::BlobTableNameSize];
unknown's avatar
unknown committed
1933 1934
    NdbBlob::getBlobTableName(btname, &t, &c);
    if (dropTable(btname) != 0) {
unknown's avatar
unknown committed
1935
      if (m_error.code != 709){
unknown's avatar
unknown committed
1936 1937
	DBUG_PRINT("exit",("error %u - exiting",m_error.code));
        DBUG_RETURN(-1);
unknown's avatar
unknown committed
1938
      }
unknown's avatar
unknown committed
1939
      DBUG_PRINT("info",("error %u - continuing",m_error.code));
unknown's avatar
unknown committed
1940 1941
    }
  }
unknown's avatar
unknown committed
1942
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1943 1944
}

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
int
NdbDictInterface::dropTable(const NdbTableImpl & impl)
{
  NdbApiSignal tSignal(m_reference);
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_DROP_TABLE_REQ;
  tSignal.theLength = DropTableReq::SignalLength;
  
  DropTableReq * const req = CAST_PTR(DropTableReq, tSignal.getDataPtrSend());
  req->senderRef = m_reference;
  req->senderData = 0;
  req->tableId = impl.m_tableId;
  req->tableVersion = impl.m_version;

  return dropTable(&tSignal, 0);
}

int
NdbDictInterface::dropTable(NdbApiSignal* signal, LinearSectionPtr ptr[3])
{
  const int noErrCodes = 3;
  int errCodes[noErrCodes] =
         {DropTableRef::NoDropTableRecordAvailable,
          DropTableRef::NotMaster,
          DropTableRef::Busy};
  int r = dictSignal(signal,NULL,0,
		     1/*use masternode id*/,
		     100,WAIT_DROP_TAB_REQ,
		     WAITFOR_RESPONSE_TIMEOUT,
		     errCodes, noErrCodes);
  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])
{
unknown's avatar
unknown committed
1986
  DBUG_ENTER("NdbDictInterface::execDROP_TABLE_CONF");
1987 1988 1989
  //DropTableConf* const conf = CAST_CONSTPTR(DropTableConf, signal->getDataPtr());

  m_waiter.signal(NO_WAIT);  
unknown's avatar
unknown committed
1990
  DBUG_VOID_RETURN;
1991 1992 1993 1994 1995 1996
}

void
NdbDictInterface::execDROP_TABLE_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
unknown's avatar
unknown committed
1997
  DBUG_ENTER("NdbDictInterface::execDROP_TABLE_REF");
1998
  const DropTableRef* const ref = CAST_CONSTPTR(DropTableRef, signal->getDataPtr());
1999
  m_error.code= ref->errorCode;
2000 2001
  m_masterNodeId = ref->masterNodeId;
  m_waiter.signal(NO_WAIT);  
unknown's avatar
unknown committed
2002
  DBUG_VOID_RETURN;
2003 2004 2005 2006 2007 2008
}

int
NdbDictionaryImpl::invalidateObject(NdbTableImpl & impl)
{
  const char * internalTableName = impl.m_internalName.c_str();
2009 2010 2011
  DBUG_ENTER("NdbDictionaryImpl::invalidateObject");
  DBUG_PRINT("enter", ("internal_name: %s", internalTableName));
  m_localHash.drop(internalTableName);
2012
  m_globalHash->lock();
2013
  impl.m_status = NdbDictionary::Object::Invalid;
2014 2015
  m_globalHash->drop(&impl);
  m_globalHash->unlock();
2016
  DBUG_RETURN(0);
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
}

int
NdbDictionaryImpl::removeCachedObject(NdbTableImpl & impl)
{
  const char * internalTableName = impl.m_internalName.c_str();

  m_localHash.drop(internalTableName);  
  m_globalHash->lock();
  m_globalHash->release(&impl);
  m_globalHash->unlock();
  return 0;
}

/*****************************************************************
 * Get index info
 */
NdbIndexImpl*
2035 2036
NdbDictionaryImpl::getIndexImpl(const char * externalName,
				const BaseString& internalName)
2037
{
2038 2039
  Ndb_local_table_info * info = get_local_table_info(internalName,
						     false);
2040
  if(info == 0){
2041 2042 2043
    m_error.code = 4243;
    return 0;
  }
2044
  NdbTableImpl * tab = info->m_table_impl;
2045 2046 2047 2048 2049 2050 2051

  if(tab->m_indexType == NdbDictionary::Index::Undefined){
    // Not an index
    m_error.code = 4243;
    return 0;
  }

2052 2053
  NdbTableImpl* prim = getTable(tab->m_primaryTable.c_str());
  if(prim == 0){
2054 2055 2056
    m_error.code = 4243;
    return 0;
  }
2057

2058 2059 2060
  /**
   * Create index impl
   */
2061 2062 2063
  NdbIndexImpl* idx;
  if(NdbDictInterface::create_index_obj_from_table(&idx, tab, prim) == 0){
    idx->m_table = tab;
unknown's avatar
unknown committed
2064
    idx->m_externalName.assign(externalName);
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
    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,
2076
					      NdbTableImpl* tab,
2077 2078
					      const NdbTableImpl* prim){
  NdbIndexImpl *idx = new NdbIndexImpl();
2079 2080 2081
  idx->m_version = tab->m_version;
  idx->m_status = tab->m_status;
  idx->m_indexId = tab->m_tableId;
2082
  idx->m_externalName.assign(tab->getName());
2083
  idx->m_tableName.assign(prim->m_externalName);
2084
  NdbDictionary::Index::Type type = idx->m_type = tab->m_indexType;
2085
  idx->m_logging = tab->m_logging;
2086
  // skip last attribute (NDB$PK or NDB$TNODE)
2087 2088 2089 2090 2091 2092

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

2095 2096
    NdbColumnImpl* col = new NdbColumnImpl;
    // Copy column definition
2097
    *col = * org;
2098
    idx->m_columns.push_back(col);
2099

2100 2101 2102
    /**
     * reverse map
     */
2103 2104
    const NdbColumnImpl* primCol = prim->getColumn(col->getName());
    int key_id = primCol->getColumnNo();
2105 2106 2107 2108
    int fill = -1;
    idx->m_key_ids.fill(key_id, fill);
    idx->m_key_ids[key_id] = i;
    col->m_keyInfoPos = key_id;
2109

2110 2111 2112
    if(type == NdbDictionary::Index::OrderedIndex && 
       (primCol->m_distributionKey ||
	(distKeys == 0 && primCol->getPrimaryKey())))
2113
    {
2114 2115
      keyCount--;
      org->m_distributionKey = 1;
2116
    }
2117
  }
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127

  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;
  }
2128 2129 2130

  * dst = idx;
  return 0;
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
}

/*****************************************************************
 * 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,
			      NdbIndexImpl & impl, 
			      const NdbTableImpl & table)
{
  //validate();
  //aggregate();
unknown's avatar
unknown committed
2155
  unsigned i;
2156 2157 2158 2159 2160 2161
  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;
  }
2162 2163
  const BaseString internalName(
    ndb.internalize_index_name(&table, impl.getName()));
2164 2165
  impl.m_internalName.assign(internalName);

2166
  w.add(DictTabInfo::TableName, internalName.c_str());
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
  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);
  
  req->setTableId(table.m_tableId);
  req->setOnline(true);
  AttributeList attributeList;
  attributeList.sz = impl.m_columns.size();
unknown's avatar
unknown committed
2194
  for(i = 0; i<attributeList.sz; i++){
2195 2196 2197 2198 2199 2200 2201 2202 2203
    const NdbColumnImpl* col = 
      table.getColumn(impl.m_columns[i]->m_name.c_str());
    if(col == 0){
      m_error.code = 4247;
      return -1;
    }
    // Copy column definition
    *impl.m_columns[i] = *col;

unknown's avatar
unknown committed
2204 2205 2206 2207 2208 2209 2210 2211
    // 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;
    }
2212 2213
    attributeList.id[i] = col->m_attrId;
  }
unknown's avatar
unknown committed
2214
  LinearSectionPtr ptr[2];
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
  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?
  return createIndex(&tSignal, ptr);
}

int
NdbDictInterface::createIndex(NdbApiSignal* signal, 
			      LinearSectionPtr ptr[3])
{
2226 2227
  const int noErrCodes = 2;
  int errCodes[noErrCodes] = {CreateIndxRef::Busy, CreateIndxRef::NotMaster};
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
  return dictSignal(signal,ptr,2,
		    1 /*use masternode id*/,
		    100,
		    WAIT_CREATE_INDX_REQ,
		    -1,
		    errCodes,noErrCodes);
}

void
NdbDictInterface::execCREATE_INDX_CONF(NdbApiSignal * signal,
				       LinearSectionPtr ptr[3])
{
  //CreateTableConf* const conf = CAST_CONSTPTR(CreateTableConf, signal->getDataPtr());
  
  m_waiter.signal(NO_WAIT);  
}

void
NdbDictInterface::execCREATE_INDX_REF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
  const CreateIndxRef* const ref = CAST_CONSTPTR(CreateIndxRef, signal->getDataPtr());
  m_error.code = ref->getErrorCode();
2251
  if(m_error.code == ref->NotMaster)
2252
    m_masterNodeId= ref->masterNodeId;
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
  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) {
2272
    const BaseString internalIndexName((tableName)
2273
      ?
2274
      m_ndb.internalize_index_name(getTable(tableName), indexName)
2275
      :
2276 2277 2278
      m_ndb.internalize_table_name(indexName)); // Index is also a table

    m_localHash.drop(internalIndexName.c_str());
2279
    m_globalHash->lock();
2280
    idx->m_table->m_status = NdbDictionary::Object::Invalid;
2281
    m_globalHash->drop(idx->m_table);
2282
    m_globalHash->unlock();
2283 2284
    return dropIndex(indexName, tableName);
  }
2285

2286 2287 2288 2289 2290 2291 2292
  return ret;
}

int
NdbDictionaryImpl::dropIndex(NdbIndexImpl & impl, const char * tableName)
{
  const char * indexName = impl.getName();
2293
  if (tableName || m_ndb.usingFullyQualifiedNames()) {
2294 2295 2296 2297 2298 2299 2300
    NdbTableImpl * timpl = impl.m_table;
    
    if (timpl == 0) {
      m_error.code = 709;
      return -1;
    }

2301
    const BaseString internalIndexName((tableName)
2302
      ?
2303
      m_ndb.internalize_index_name(getTable(tableName), indexName)
2304
      :
2305
      m_ndb.internalize_table_name(indexName)); // Index is also a table
2306 2307 2308 2309

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

2311 2312
    int ret = m_receiver.dropIndex(impl, *timpl);
    if(ret == 0){
2313
      m_localHash.drop(internalIndexName.c_str());
2314
      m_globalHash->lock();
2315
      impl.m_table->m_status = NdbDictionary::Object::Invalid;
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
      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
  req->setIndexId(timpl.m_tableId);
  req->setIndexVersion(timpl.m_version);

  return dropIndex(&tSignal, 0);
}

int
NdbDictInterface::dropIndex(NdbApiSignal* signal, LinearSectionPtr ptr[3])
{
2349 2350
  const int noErrCodes = 2;
  int errCodes[noErrCodes] = {DropIndxRef::Busy, DropIndxRef::NotMaster};
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
  int r = dictSignal(signal,NULL,0,
		     1/*Use masternode id*/,
		     100,
		     WAIT_DROP_INDX_REQ,
		     WAITFOR_RESPONSE_TIMEOUT,
		     errCodes,noErrCodes);
  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])
{
  const DropIndxRef* const ref = CAST_CONSTPTR(DropIndxRef, signal->getDataPtr());
  m_error.code = ref->getErrorCode();
2377
  if(m_error.code == ref->NotMaster)
2378
    m_masterNodeId= ref->masterNodeId;
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
  m_waiter.signal(NO_WAIT);  
}

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

int
NdbDictionaryImpl::createEvent(NdbEventImpl & evnt)
{
unknown's avatar
unknown committed
2389
  int i;
unknown's avatar
unknown committed
2390
  NdbTableImpl* tab = getTable(evnt.getTableName());
2391 2392 2393

  if(tab == 0){
#ifdef EVENT_DEBUG
unknown's avatar
unknown committed
2394
    ndbout_c("NdbDictionaryImpl::createEvent: table not found: %s",
unknown's avatar
unknown committed
2395
	     evnt.getTableName());
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
#endif
    return -1;
  }

  evnt.m_tableId = tab->m_tableId;
  evnt.m_tableImpl = tab;
#ifdef EVENT_DEBUG
  ndbout_c("Event on tableId=%d", evnt.m_tableId);
#endif

  NdbTableImpl &table = *evnt.m_tableImpl;


  int attributeList_sz = evnt.m_attrIds.size();

unknown's avatar
unknown committed
2411
  for (i = 0; i < attributeList_sz; i++) {
2412 2413 2414 2415 2416
    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],
unknown's avatar
unknown committed
2417 2418
	       evnt.getTableName());
      m_error.code= 4713;
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
      return -1;
    }
  }

  evnt.m_attrIds.clear();

  attributeList_sz = evnt.m_columns.size();
#ifdef EVENT_DEBUG
  ndbout_c("creating event %s", evnt.m_externalName.c_str());
  ndbout_c("no of columns %d", evnt.m_columns.size());
#endif
  int pk_count = 0;
  evnt.m_attrListBitmask.clear();

unknown's avatar
unknown committed
2433
  for(i = 0; i<attributeList_sz; i++){
2434 2435 2436
    const NdbColumnImpl* col = 
      table.getColumn(evnt.m_columns[i]->m_name.c_str());
    if(col == 0){
2437
      m_error.code= 4247;
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
      return -1;
    }
    // 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)
unknown's avatar
unknown committed
2451
  for(i = 1; i < attributeList_sz; i++) {
2452 2453 2454 2455 2456 2457 2458 2459 2460
    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
unknown's avatar
unknown committed
2461
  for(i = 1; i<attributeList_sz; i++) {
2462
    if (evnt.m_columns[i-1]->m_attrId == evnt.m_columns[i]->m_attrId) {
2463
      m_error.code= 4258;
2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
      return -1;
    }
  }
  
#ifdef EVENT_DEBUG
  char buf[128] = {0};
  evnt.m_attrListBitmask.getText(buf);
  ndbout_c("createEvent: mask = %s", buf);
#endif

  // NdbDictInterface m_receiver;
  return m_receiver.createEvent(m_ndb, evnt, 0 /* getFlag unset */);
}

int
NdbDictInterface::createEvent(class Ndb & ndb,
			      NdbEventImpl & evnt,
			      int getFlag)
{
  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 {
    // creating event in Dictionary
    req->setRequestType(CreateEvntReq::RT_USER_CREATE);
    req->setTableId(evnt.m_tableId);
    req->setAttrListBitmask(evnt.m_attrListBitmask);
    req->setEventType(evnt.mi_type);
  }

  UtilBufferWriter w(m_buffer);

  const size_t len = strlen(evnt.m_externalName.c_str()) + 1;
  if(len > MAX_TAB_NAME_SIZE) {
2511
    m_error.code= 4241;
2512 2513 2514 2515 2516 2517
    return -1;
  }

  w.add(SimpleProperties::StringValue, evnt.m_externalName.c_str());

  if (getFlag == 0)
2518 2519 2520
  {
    const BaseString internal_tabname(
      ndb.internalize_table_name(evnt.m_tableName.c_str()));
2521
    w.add(SimpleProperties::StringValue,
2522 2523
	 internal_tabname.c_str());
  }
2524

unknown's avatar
unknown committed
2525
  LinearSectionPtr ptr[1];
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
  ptr[0].p = (Uint32*)m_buffer.get_data();
  ptr[0].sz = (m_buffer.length()+3) >> 2;

  int ret = createEvent(&tSignal, ptr, 1);

  if (ret) {
    return ret;
  }

  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_tableId         = evntConf->getTableId();
    evnt.m_attrListBitmask = evntConf->getAttrListBitmask();
    evnt.mi_type           = evntConf->getEventType();
    evnt.setTable(dataPtr);
  } else {
    if (evnt.m_tableId         != evntConf->getTableId() ||
	//evnt.m_attrListBitmask != evntConf->getAttrListBitmask() ||
	evnt.mi_type           != evntConf->getEventType()) {
      ndbout_c("ERROR*************");
      return 1;
    }
  }

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

  return ret;
}

int
NdbDictInterface::createEvent(NdbApiSignal* signal,
			      LinearSectionPtr ptr[3], int noLSP)
{
  const int noErrCodes = 1;
  int errCodes[noErrCodes] = {CreateEvntRef::Busy};
  return dictSignal(signal,ptr,noLSP,
		    1 /*use masternode id*/,
		    100,
		    WAIT_CREATE_INDX_REQ /*WAIT_CREATE_EVNT_REQ*/,
		    -1,
		    errCodes,noErrCodes, CreateEvntRef::Temporary);
}

int
NdbDictionaryImpl::executeSubscribeEvent(NdbEventImpl & ev)
{
  // NdbDictInterface m_receiver;
  return m_receiver.executeSubscribeEvent(m_ndb, ev);
}

int
NdbDictInterface::executeSubscribeEvent(class Ndb & ndb,
				 NdbEventImpl & evnt)
{
unknown's avatar
unknown committed
2588
  DBUG_ENTER("NdbDictInterface::executeSubscribeEvent");
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
  NdbApiSignal tSignal(m_reference);
  //  tSignal.theReceiversBlockNumber = SUMA;
  tSignal.theReceiversBlockNumber = DBDICT;
  tSignal.theVerId_signalNumber   = GSN_SUB_START_REQ;
  tSignal.theLength = SubStartReq::SignalLength2;
  
  SubStartReq * sumaStart = CAST_PTR(SubStartReq, tSignal.getDataPtrSend());

  sumaStart->subscriptionId   = evnt.m_eventId;
  sumaStart->subscriptionKey  = evnt.m_eventKey;
  sumaStart->part             = SubscriptionData::TableData;
  sumaStart->subscriberData   = evnt.m_bufferId & 0xFF;
  sumaStart->subscriberRef    = m_reference;

unknown's avatar
unknown committed
2603
  DBUG_RETURN(executeSubscribeEvent(&tSignal, NULL));
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
}

int
NdbDictInterface::executeSubscribeEvent(NdbApiSignal* signal,
					LinearSectionPtr ptr[3])
{
  return dictSignal(signal,NULL,0,
		    1 /*use masternode id*/,
		    100,
		    WAIT_CREATE_INDX_REQ /*WAIT_CREATE_EVNT_REQ*/,
		    -1,
		    NULL,0);
}

int
NdbDictionaryImpl::stopSubscribeEvent(NdbEventImpl & ev)
{
  // NdbDictInterface m_receiver;
  return m_receiver.stopSubscribeEvent(m_ndb, ev);
}

int
NdbDictInterface::stopSubscribeEvent(class Ndb & ndb,
				     NdbEventImpl & evnt)
{
2629
  DBUG_ENTER("NdbDictInterface::stopSubscribeEvent");
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644

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

  sumaStop->subscriptionId  = evnt.m_eventId;
  sumaStop->subscriptionKey = evnt.m_eventKey;
  sumaStop->subscriberData  = evnt.m_bufferId & 0xFF;
  sumaStop->part            = (Uint32) SubscriptionData::TableData;
  sumaStop->subscriberRef   = m_reference;

2645
  DBUG_RETURN(stopSubscribeEvent(&tSignal, NULL));
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
}

int
NdbDictInterface::stopSubscribeEvent(NdbApiSignal* signal,
				     LinearSectionPtr ptr[3])
{
  return dictSignal(signal,NULL,0,
		    1 /*use masternode id*/,
		    100,
		    WAIT_CREATE_INDX_REQ /*WAIT_SUB_STOP__REQ*/,
		    -1,
		    NULL,0);
}

NdbEventImpl * 
NdbDictionaryImpl::getEvent(const char * eventName)
{
  NdbEventImpl *ev =  new NdbEventImpl();

  if (ev == NULL) {
    return NULL;
  }

  ev->setName(eventName);

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

  if (ret) {
    delete ev;
    return NULL;
  }

  // We only have the table name with internal name
unknown's avatar
unknown committed
2679 2680
  ev->setTable(m_ndb.externalizeTableName(ev->getTableName()));
  ev->m_tableImpl = getTable(ev->getTableName());
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704

  // get the columns from the attrListBitmask

  NdbTableImpl &table = *ev->m_tableImpl;
  AttributeMask & mask = ev->m_attrListBitmask;
  int attributeList_sz = mask.count();
  int id = -1;

#ifdef EVENT_DEBUG
  ndbout_c("NdbDictionaryImpl::getEvent attributeList_sz = %d",
	   attributeList_sz);
  char buf[128] = {0};
  mask.getText(buf);
  ndbout_c("mask = %s", buf);
#endif

  for(int i = 0; i < attributeList_sz; i++) {
    id++; while (!mask.get(id)) id++;

    const NdbColumnImpl* col = table.getColumn(id);
    if(col == 0) {
#ifdef EVENT_DEBUG
      ndbout_c("NdbDictionaryImpl::getEvent could not find column id %d", id);
#endif
2705
      m_error.code= 4247;
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
      delete ev;
      return NULL;
    }
    NdbColumnImpl* new_col = new NdbColumnImpl;
    // Copy column definition
    *new_col = *col;

    ev->m_columns.push_back(new_col);
  }

  return ev;
}

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

2725 2726 2727 2728 2729 2730 2731 2732 2733
  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);
  }

2734 2735 2736 2737 2738 2739 2740 2741
  const CreateEvntConf * const createEvntConf=
    CAST_CONSTPTR(CreateEvntConf, signal->getDataPtr());

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

  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d",
		     subscriptionId,subscriptionKey));
2742
  m_waiter.signal(NO_WAIT);
2743
  DBUG_VOID_RETURN;
2744 2745 2746 2747 2748 2749
}

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

2752 2753 2754 2755 2756 2757 2758
  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()));
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
2759 2760 2761 2762 2763 2764
}

void
NdbDictInterface::execSUB_STOP_CONF(NdbApiSignal * signal,
				      LinearSectionPtr ptr[3])
{
2765 2766 2767
  DBUG_ENTER("NdbDictInterface::execSUB_STOP_CONF");
  const SubStopConf * const subStopConf=
    CAST_CONSTPTR(SubStopConf, signal->getDataPtr());
2768

2769 2770 2771
  Uint32 subscriptionId = subStopConf->subscriptionId;
  Uint32 subscriptionKey = subStopConf->subscriptionKey;
  Uint32 subscriberData = subStopConf->subscriberData;
2772

2773 2774
  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d",
		     subscriptionId,subscriptionKey,subscriberData));
2775
  m_waiter.signal(NO_WAIT);
2776
  DBUG_VOID_RETURN;
2777 2778 2779 2780 2781 2782
}

void
NdbDictInterface::execSUB_STOP_REF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
2783
  DBUG_ENTER("NdbDictInterface::execSUB_STOP_REF");
2784 2785
  const SubStopRef * const subStopRef=
    CAST_CONSTPTR(SubStopRef, signal->getDataPtr());
2786

2787 2788 2789 2790
  Uint32 subscriptionId = subStopRef->subscriptionId;
  Uint32 subscriptionKey = subStopRef->subscriptionKey;
  Uint32 subscriberData = subStopRef->subscriberData;
  m_error.code= subStopRef->errorCode;
2791

2792 2793
  DBUG_PRINT("error",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d,error=%d",
		      subscriptionId,subscriptionKey,subscriberData,m_error.code));
2794
  m_waiter.signal(NO_WAIT);
2795
  DBUG_VOID_RETURN;
2796 2797 2798 2799 2800 2801
}

void
NdbDictInterface::execSUB_START_CONF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
2802 2803 2804
  DBUG_ENTER("NdbDictInterface::execSUB_START_CONF");
  const SubStartConf * const subStartConf=
    CAST_CONSTPTR(SubStartConf, signal->getDataPtr());
2805

2806 2807
  Uint32 subscriptionId = subStartConf->subscriptionId;
  Uint32 subscriptionKey = subStartConf->subscriptionKey;
2808
  SubscriptionData::Part part = 
2809 2810
    (SubscriptionData::Part)subStartConf->part;
  Uint32 subscriberData = subStartConf->subscriberData;
2811 2812 2813

  switch(part) {
  case SubscriptionData::MetaData: {
2814 2815
    DBUG_PRINT("error",("SubscriptionData::MetaData"));
    m_error.code= 1;
2816 2817 2818
    break;
  }
  case SubscriptionData::TableData: {
2819
    DBUG_PRINT("info",("SubscriptionData::TableData"));
2820 2821 2822
    break;
  }
  default: {
2823 2824
    DBUG_PRINT("error",("wrong data"));
    m_error.code= 2;
2825 2826 2827
    break;
  }
  }
2828 2829
  DBUG_PRINT("info",("subscriptionId=%d,subscriptionKey=%d,subscriberData=%d",
		     subscriptionId,subscriptionKey,subscriberData));
2830
  m_waiter.signal(NO_WAIT);
2831
  DBUG_VOID_RETURN;
2832 2833 2834 2835 2836 2837
}

void
NdbDictInterface::execSUB_START_REF(NdbApiSignal * signal,
				    LinearSectionPtr ptr[3])
{
2838 2839 2840 2841 2842 2843
  DBUG_ENTER("NdbDictInterface::execSUB_START_REF");
  const SubStartRef * const subStartRef=
    CAST_CONSTPTR(SubStartRef, signal->getDataPtr());
  m_error.code= subStartRef->errorCode;
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
2844 2845 2846 2847 2848
}
void
NdbDictInterface::execSUB_GCP_COMPLETE_REP(NdbApiSignal * signal,
					   LinearSectionPtr ptr[3])
{
2849 2850
  const SubGcpCompleteRep * const rep=
    CAST_CONSTPTR(SubGcpCompleteRep, signal->getDataPtr());
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860

  const Uint32 gci            = rep->gci;
  //  const Uint32 senderRef      = rep->senderRef;
  const Uint32 subscriberData = rep->subscriberData;

  const Uint32 bufferId = subscriberData;

  const Uint32 ref = signal->theSendersBlockRef;

  NdbApiSignal tSignal(m_reference);
2861 2862
  SubGcpCompleteAcc * acc=
    CAST_PTR(SubGcpCompleteAcc, tSignal.getDataPtrSend());
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919

  acc->rep = *rep;

  tSignal.theReceiversBlockNumber = refToBlock(ref);
  tSignal.theVerId_signalNumber   = GSN_SUB_GCP_COMPLETE_ACC;
  tSignal.theLength = SubGcpCompleteAcc::SignalLength;

  Uint32 aNodeId = refToNode(ref);

  //  m_transporter->lock_mutex();
  int r;
  r = m_transporter->sendSignal(&tSignal, aNodeId);
  //  m_transporter->unlock_mutex();

  NdbGlobalEventBufferHandle::latestGCI(bufferId, gci);
}

void
NdbDictInterface::execSUB_TABLE_DATA(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
#ifdef EVENT_DEBUG
  const char * FNAME = "NdbDictInterface::execSUB_TABLE_DATA";
#endif
  //TODO
  const SubTableData * const sdata = CAST_CONSTPTR(SubTableData, signal->getDataPtr());

  //  const Uint32 gci            = sdata->gci;
  //  const Uint32 operation      = sdata->operation;
  //  const Uint32 tableId        = sdata->tableId;
  //  const Uint32 noOfAttrs      = sdata->noOfAttributes;
  //  const Uint32 dataLen        = sdata->dataSize;
  const Uint32 subscriberData = sdata->subscriberData;
  //  const Uint32 logType        = sdata->logType;

  for (int i=signal->m_noOfSections;i < 3; i++) {
    ptr[i].p = NULL;
    ptr[i].sz = 0;
  }
#ifdef EVENT_DEBUG
  ndbout_c("%s: senderData %d, gci %d, operation %d, tableId %d, noOfAttrs %d, dataLen %d",
	   FNAME, subscriberData, gci, operation, tableId, noOfAttrs, dataLen);
  ndbout_c("ptr[0] %u %u ptr[1] %u %u ptr[2] %u %u\n",
	   ptr[0].p,ptr[0].sz,ptr[1].p,ptr[1].sz,ptr[2].p,ptr[2].sz);
#endif
  const Uint32 bufferId = subscriberData;

  NdbGlobalEventBufferHandle::insertDataL(bufferId,
					  sdata, ptr);
}

/*****************************************************************
 * Drop event
 */
int 
NdbDictionaryImpl::dropEvent(const char * eventName)
{
2920
  NdbEventImpl *ev= new NdbEventImpl();
2921
  ev->setName(eventName);
2922
  int ret= m_receiver.dropEvent(*ev);
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970
  delete ev;  

  //  printf("__________________RET %u\n", ret);
  return ret;
}

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

  w.add(SimpleProperties::StringValue, evnt.m_externalName.c_str());

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

  return dropEvent(&tSignal, ptr, 1);
}

int
NdbDictInterface::dropEvent(NdbApiSignal* signal,
			    LinearSectionPtr ptr[3], int noLSP)
{
  //TODO
  const int noErrCodes = 1;
  int errCodes[noErrCodes] = {DropEvntRef::Busy};
  return dictSignal(signal,ptr,noLSP,
		    1 /*use masternode id*/,
		    100,
		    WAIT_CREATE_INDX_REQ /*WAIT_CREATE_EVNT_REQ*/,
		    -1,
		    errCodes,noErrCodes, DropEvntRef::Temporary);
}
void
NdbDictInterface::execDROP_EVNT_CONF(NdbApiSignal * signal,
				     LinearSectionPtr ptr[3])
{
2971
  DBUG_ENTER("NdbDictInterface::execDROP_EVNT_CONF");
2972
  m_waiter.signal(NO_WAIT);  
2973
  DBUG_VOID_RETURN;
2974 2975 2976 2977 2978 2979
}

void
NdbDictInterface::execDROP_EVNT_REF(NdbApiSignal * signal,
				    LinearSectionPtr ptr[3])
{
2980 2981 2982 2983
  DBUG_ENTER("NdbDictInterface::execDROP_EVNT_REF");
  const DropEvntRef* const ref=
    CAST_CONSTPTR(DropEvntRef, signal->getDataPtr());
  m_error.code= ref->getErrorCode();
2984

2985 2986
  DBUG_PRINT("info",("ErrorCode=%u Errorline=%u ErrorNode=%u",
	     ref->getErrorCode(), ref->getErrorLine(), ref->getErrorNode()));
2987

2988 2989
  m_waiter.signal(NO_WAIT);
  DBUG_VOID_RETURN;
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001
}

/*****************************************************************
 * 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);
3002
  return m_receiver.listObjects(list, req.requestData, m_ndb.usingFullyQualifiedNames());
3003 3004 3005
}

int
unknown's avatar
unknown committed
3006
NdbDictionaryImpl::listIndexes(List& list, Uint32 indexId)
3007
{
3008
  ListTablesReq req;
3009
  req.requestData = 0;
unknown's avatar
unknown committed
3010
  req.setTableId(indexId);
3011 3012
  req.setListNames(true);
  req.setListIndexes(true);
3013
  return m_receiver.listObjects(list, req.requestData, m_ndb.usingFullyQualifiedNames());
3014 3015 3016 3017
}

int
NdbDictInterface::listObjects(NdbDictionary::Dictionary::List& list,
3018
			      Uint32 requestData, bool fullyQualifiedNames)
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
{
  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
3054
    m_error.code= 4213;
3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
    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);
3081
      objectName = BaseString(Ndb::externalizeIndexName(indexName, fullyQualifiedNames));
3082 3083 3084 3085 3086 3087 3088
      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);
3089
      objectName = BaseString(Ndb::externalizeTableName(tableName, fullyQualifiedNames));
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
      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
    m_transporter->lock_mutex();
    Uint16 aNodeId = m_transporter->get_an_alive_node();
    if (aNodeId == 0) {
3120
      m_error.code= 4009;
3121 3122 3123 3124 3125 3126 3127
      m_transporter->unlock_mutex();
      return -1;
    }
    if (m_transporter->sendSignal(signal, aNodeId) != 0) {
      m_transporter->unlock_mutex();
      continue;
    }
3128
    m_error.code= 0;
3129 3130 3131
    m_waiter.m_node = aNodeId;
    m_waiter.m_state = WAIT_LIST_TABLES_CONF;
    m_waiter.wait(WAITFOR_RESPONSE_TIMEOUT);
unknown's avatar
unknown committed
3132
    m_transporter->unlock_mutex();    
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
    // end protected
    if (m_waiter.m_state == NO_WAIT && m_error.code == 0)
      return 0;
    if (m_waiter.m_state == WAIT_NODE_FAILURE)
      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);
  }
}
unknown's avatar
unknown committed
3155

unknown's avatar
unknown committed
3156
template class Vector<int>;
unknown's avatar
unknown committed
3157
template class Vector<Uint16>;
unknown's avatar
unknown committed
3158 3159
template class Vector<Uint32>;
template class Vector<Vector<Uint32> >;
unknown's avatar
unknown committed
3160 3161 3162
template class Vector<NdbTableImpl*>;
template class Vector<NdbColumnImpl*>;