Dbdict.cpp 493 KB
Newer Older
1 2 3 4
/* 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
5
   the Free Software Foundation; version 2 of the License.
6 7 8 9 10 11 12 13 14 15

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

16
#include <ndb_global.h>
17
#include <my_sys.h>
18

19 20
#define DBDICT_C
#include "Dbdict.hpp"
21
#include "diskpage.hpp"
22 23 24 25 26 27 28 29

#include <ndb_limits.h>
#include <NdbOut.hpp>
#include <Properties.hpp>
#include <Configuration.hpp>
#include <SectionReader.hpp>
#include <SimpleProperties.hpp>
#include <AttributeHeader.hpp>
30
#include <KeyDescriptor.hpp>
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <signaldata/DictSchemaInfo.hpp>
#include <signaldata/DictTabInfo.hpp>
#include <signaldata/DropTabFile.hpp>

#include <signaldata/EventReport.hpp>
#include <signaldata/FsCloseReq.hpp>
#include <signaldata/FsConf.hpp>
#include <signaldata/FsOpenReq.hpp>
#include <signaldata/FsReadWriteReq.hpp>
#include <signaldata/FsRef.hpp>
#include <signaldata/GetTabInfo.hpp>
#include <signaldata/GetTableId.hpp>
#include <signaldata/HotSpareRep.hpp>
#include <signaldata/NFCompleteRep.hpp>
#include <signaldata/NodeFailRep.hpp>
#include <signaldata/ReadNodesConf.hpp>
#include <signaldata/RelTabMem.hpp>
#include <signaldata/WaitGCP.hpp>
#include <signaldata/ListTables.hpp>

#include <signaldata/CreateTrig.hpp>
#include <signaldata/AlterTrig.hpp>
#include <signaldata/DropTrig.hpp>
#include <signaldata/CreateIndx.hpp>
#include <signaldata/DropIndx.hpp>
#include <signaldata/BuildIndx.hpp>

58 59 60 61
#include <signaldata/DropFilegroup.hpp>
#include <signaldata/CreateFilegroup.hpp>
#include <signaldata/CreateFilegroupImpl.hpp>

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#include <signaldata/CreateEvnt.hpp>
#include <signaldata/UtilPrepare.hpp>
#include <signaldata/UtilExecute.hpp>
#include <signaldata/UtilRelease.hpp>
#include <signaldata/SumaImpl.hpp> 

#include <signaldata/LqhFrag.hpp>

#include <signaldata/DiAddTab.hpp>
#include <signaldata/DihStartTab.hpp>

#include <signaldata/DropTable.hpp>
#include <signaldata/DropTab.hpp>
#include <signaldata/PrepDropTab.hpp>

#include <signaldata/CreateTable.hpp>
#include <signaldata/AlterTable.hpp>
#include <signaldata/AlterTab.hpp>
#include <signaldata/CreateFragmentation.hpp>
#include <signaldata/CreateTab.hpp>
#include <NdbSleep.h>
83
#include <signaldata/ApiBroadcast.hpp>
84

85 86 87 88
#include <signaldata/DropObj.hpp>
#include <signaldata/CreateObj.hpp>
#include <SLList.hpp>

89 90 91
#include <EventLogger.hpp>
extern EventLogger g_eventLogger;

92 93 94 95 96 97 98
#define ZNOT_FOUND 626
#define ZALREADYEXIST 630

//#define EVENT_PH2_DEBUG
//#define EVENT_PH3_DEBUG
//#define EVENT_DEBUG

99 100
static const char EVENT_SYSTEM_TABLE_NAME[] = "sys/def/NDB$EVENTS_0";

101 102 103 104
#define EVENT_TRACE \
//  ndbout_c("Event debug trace: File: %s Line: %u", __FILE__, __LINE__)

#define DIV(x,y) (((x)+(y)-1)/(y))
105
#define WORDS2PAGES(x) DIV(x, (ZSIZE_OF_PAGES_IN_WORDS - ZPAGE_HEADER_SIZE))
106 107
#include <ndb_version.h>

108
static
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
struct {
  Uint32 m_gsn_user_req;
  Uint32 m_gsn_req;
  Uint32 m_gsn_ref;
  Uint32 m_gsn_conf;
  void (Dbdict::* m_trans_commit_start)(Signal*, Dbdict::SchemaTransaction*);
  void (Dbdict::* m_trans_commit_complete)(Signal*,Dbdict::SchemaTransaction*);
  void (Dbdict::* m_trans_abort_start)(Signal*, Dbdict::SchemaTransaction*);
  void (Dbdict::* m_trans_abort_complete)(Signal*, Dbdict::SchemaTransaction*);

  void (Dbdict::* m_prepare_start)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_prepare_complete)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_commit)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_commit_start)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_commit_complete)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_abort)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_abort_start)(Signal*, Dbdict::SchemaOp*);
  void (Dbdict::* m_abort_complete)(Signal*, Dbdict::SchemaOp*);
  
} f_dict_op[] = {
  /**
   * Create filegroup
   */
  { 
    GSN_CREATE_FILEGROUP_REQ,
    GSN_CREATE_OBJ_REQ, GSN_CREATE_OBJ_REF, GSN_CREATE_OBJ_CONF,
    0, 0, 0, 0,
    &Dbdict::create_fg_prepare_start, &Dbdict::create_fg_prepare_complete,
    &Dbdict::createObj_commit,
    0, 0,
    &Dbdict::createObj_abort,
    &Dbdict::create_fg_abort_start, &Dbdict::create_fg_abort_complete,
  }

  /**
   * Create file
   */
  ,{ 
    GSN_CREATE_FILE_REQ,
    GSN_CREATE_OBJ_REQ, GSN_CREATE_OBJ_REF, GSN_CREATE_OBJ_CONF,
    0, 0, 0, 0,
    &Dbdict::create_file_prepare_start, &Dbdict::create_file_prepare_complete,
    &Dbdict::createObj_commit,
    &Dbdict::create_file_commit_start, 0,
    &Dbdict::createObj_abort,
    &Dbdict::create_file_abort_start, &Dbdict::create_file_abort_complete,
  }

  /**
   * Drop file
   */
  ,{ 
    GSN_DROP_FILE_REQ,
    GSN_DROP_OBJ_REQ, GSN_DROP_OBJ_REF, GSN_DROP_OBJ_CONF,
    0, 0, 0, 0,
    &Dbdict::drop_file_prepare_start, 0,
    &Dbdict::dropObj_commit,
    &Dbdict::drop_file_commit_start, &Dbdict::drop_file_commit_complete,
    &Dbdict::dropObj_abort,
    &Dbdict::drop_file_abort_start, 0
  }

  /**
   * Drop filegroup
   */
  ,{ 
    GSN_DROP_FILEGROUP_REQ,
    GSN_DROP_OBJ_REQ, GSN_DROP_OBJ_REF, GSN_DROP_OBJ_CONF,
    0, 0, 0, 0,
    &Dbdict::drop_fg_prepare_start, 0,
    &Dbdict::dropObj_commit,
    &Dbdict::drop_fg_commit_start, &Dbdict::drop_fg_commit_complete,
    &Dbdict::dropObj_abort,
    &Dbdict::drop_fg_abort_start, 0
  }

  /**
   * Drop undofile
   */
  ,{ 
    GSN_DROP_FILE_REQ,
    GSN_DROP_OBJ_REQ, GSN_DROP_OBJ_REF, GSN_DROP_OBJ_CONF,
    0, 0, 0, 0,
    &Dbdict::drop_undofile_prepare_start, 0,
    0,
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
194
    0, &Dbdict::drop_undofile_commit_complete,
195
    0, 0, 0
196 197 198
  }
};

199
Uint32
200
alter_obj_inc_schema_version(Uint32 old)
201 202 203 204 205 206
{
   return (old & 0x00FFFFFF) + ((old + 0x1000000) & 0xFF000000);
}

static
Uint32
207
alter_obj_dec_schema_version(Uint32 old)
208 209 210 211 212 213
{
  return (old & 0x00FFFFFF) + ((old - 0x1000000) & 0xFF000000);
}

static
Uint32
214
create_obj_inc_schema_version(Uint32 old)
215 216 217 218
{
  return (old + 0x00000001) & 0x00FFFFFF;
}

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          GENERAL MODULE -------------------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains general stuff. Mostly debug signals and     */
/* general signals that go into a specific module after checking a  */
/* state variable. Also general subroutines used by many.           */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

/* ---------------------------------------------------------------- */
// This signal is used to dump states of various variables in the
// block by command.
/* ---------------------------------------------------------------- */
void
Dbdict::execDUMP_STATE_ORD(Signal* signal)
{
  jamEntry();

autotest@mc01.ndb.mysql.com's avatar
autotest@mc01.ndb.mysql.com committed
239
#ifdef VM_TRACE
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  if(signal->theData[0] == 1222){
    const Uint32 tab = signal->theData[1];
    PrepDropTabReq* req = (PrepDropTabReq*)signal->getDataPtr();
    req->senderRef = reference();
    req->senderData = 1222;
    req->tableId = tab;
    sendSignal(DBLQH_REF, GSN_PREP_DROP_TAB_REQ, signal,
	       PrepDropTabReq::SignalLength, JBB);
  }

  if(signal->theData[0] == 1223){
    const Uint32 tab = signal->theData[1];
    PrepDropTabReq* req = (PrepDropTabReq*)signal->getDataPtr();
    req->senderRef = reference();
    req->senderData = 1222;
    req->tableId = tab;
    sendSignal(DBTC_REF, GSN_PREP_DROP_TAB_REQ, signal,
	       PrepDropTabReq::SignalLength, JBB);
  }

  if(signal->theData[0] == 1224){
    const Uint32 tab = signal->theData[1];
    PrepDropTabReq* req = (PrepDropTabReq*)signal->getDataPtr();
    req->senderRef = reference();
    req->senderData = 1222;
    req->tableId = tab;
    sendSignal(DBDIH_REF, GSN_PREP_DROP_TAB_REQ, signal,
	       PrepDropTabReq::SignalLength, JBB);
  }

  if(signal->theData[0] == 1225){
    const Uint32 tab = signal->theData[1];
    const Uint32 ver = signal->theData[2];
    TableRecordPtr tabRecPtr;
    c_tableRecordPool.getPtr(tabRecPtr, tab);
    DropTableReq * req = (DropTableReq*)signal->getDataPtr();
    req->senderData = 1225;
    req->senderRef = numberToRef(1,1);
    req->tableId = tab;
    req->tableVersion = tabRecPtr.p->tableVersion + ver;
    sendSignal(DBDICT_REF, GSN_DROP_TABLE_REQ, signal,
	       DropTableReq::SignalLength, JBB);
  }
#endif  
284 285 286 287 288 289
#define MEMINFO(x, y) infoEvent(x ": %d %d", y.getSize(), y.getNoOfFree())
  if(signal->theData[0] == 1226){
    MEMINFO("c_obj_pool", c_obj_pool);
    MEMINFO("c_opRecordPool", c_opRecordPool);
    MEMINFO("c_rope_pool", c_rope_pool);
  }
290 291 292 293 294 295 296 297 298 299 300 301 302

  if (signal->theData[0] == 1227)
  {
    DLHashTable<DictObject>::Iterator iter;
    bool ok = c_obj_hash.first(iter);
    for(; ok; ok = c_obj_hash.next(iter))
    {
      Rope name(c_rope_pool, iter.curr.p->m_name);
      char buf[1024];
      name.copy(buf);
      ndbout_c("%s m_ref_count: %d", buf, iter.curr.p->m_ref_count); 
    }
  }    
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  
  return;
}//Dbdict::execDUMP_STATE_ORD()

/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */
// CONTINUEB is used when a real-time break is needed for long
// processes.
/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */
void Dbdict::execCONTINUEB(Signal* signal) 
{
  jamEntry();
  switch (signal->theData[0]) {
  case ZPACK_TABLE_INTO_PAGES :
    jam();
319
    packTableIntoPages(signal);
320 321 322 323 324 325 326
    break;

  case ZSEND_GET_TAB_RESPONSE :
    jam();
    sendGetTabResponse(signal);
    break;

327 328
  case ZDICT_LOCK_POLL:
    jam();
329
    checkDictLockQueue(signal, true);
330 331
    break;

332 333 334 335 336 337 338 339 340 341 342 343 344
  default :
    ndbrequire(false);
    break;
  }//switch
  return;
}//execCONTINUEB()

/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */
// Routine to handle pack table into pages.
/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */

345
void Dbdict::packTableIntoPages(Signal* signal)
346
{
347 348 349
  const Uint32 tableId= signal->theData[1];
  const Uint32 type= signal->theData[2];
  const Uint32 pageId= signal->theData[3];
350 351 352

  PageRecordPtr pagePtr;
  c_pageRecordArray.getPtr(pagePtr, pageId);
353

354 355
  memset(&pagePtr.p->word[0], 0, 4 * ZPAGE_HEADER_SIZE);
  LinearWriter w(&pagePtr.p->word[ZPAGE_HEADER_SIZE], 
356
		 ZMAX_PAGES_OF_TABLE_DEFINITION * ZSIZE_OF_PAGES_IN_WORDS);
357
  w.first();
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
  switch((DictTabInfo::TableType)type) {
  case DictTabInfo::SystemTable:
  case DictTabInfo::UserTable:
  case DictTabInfo::UniqueHashIndex:
  case DictTabInfo::HashIndex:
  case DictTabInfo::UniqueOrderedIndex:
  case DictTabInfo::OrderedIndex:{
    jam();
    TableRecordPtr tablePtr;
    c_tableRecordPool.getPtr(tablePtr, tableId);
    packTableIntoPages(w, tablePtr, signal);
    break;
  }
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:{
    FilegroupPtr fg_ptr;
    ndbrequire(c_filegroup_hash.find(fg_ptr, tableId));
375 376 377
    const Uint32 free_hi= signal->theData[4];
    const Uint32 free_lo= signal->theData[5];
    packFilegroupIntoPages(w, fg_ptr, free_hi, free_lo);
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    break;
  }
  case DictTabInfo::Datafile:{
    FilePtr fg_ptr;
    ndbrequire(c_file_hash.find(fg_ptr, tableId));
    const Uint32 free_extents= signal->theData[4];
    packFileIntoPages(w, fg_ptr, free_extents);
    break;
  }
  case DictTabInfo::Undofile:{
    FilePtr fg_ptr;
    ndbrequire(c_file_hash.find(fg_ptr, tableId));
    packFileIntoPages(w, fg_ptr, 0);
    break;
  }
  case DictTabInfo::UndefTableType:
  case DictTabInfo::HashIndexTrigger:
  case DictTabInfo::SubscriptionTrigger:
  case DictTabInfo::ReadOnlyConstraint:
  case DictTabInfo::IndexTrigger:
    ndbrequire(false);
  }
  
401
  Uint32 wordsOfTable = w.getWordsUsed();
402
  Uint32 pagesUsed = WORDS2PAGES(wordsOfTable);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  pagePtr.p->word[ZPOS_CHECKSUM] = 
    computeChecksum(&pagePtr.p->word[0], pagesUsed * ZSIZE_OF_PAGES_IN_WORDS);
  
  switch (c_packTable.m_state) {
  case PackTable::PTS_IDLE:
    ndbrequire(false);
    break;
  case PackTable::PTS_GET_TAB:
    jam();
    c_retrieveRecord.retrievedNoOfPages = pagesUsed;
    c_retrieveRecord.retrievedNoOfWords = wordsOfTable;
    sendGetTabResponse(signal);
    return;
    break;
  }//switch
  ndbrequire(false);
  return;
}//packTableIntoPages()

void
423
Dbdict::packTableIntoPages(SimpleProperties::Writer & w,
424 425
			       TableRecordPtr tablePtr,
			       Signal* signal){
426
  
427 428 429
  union {
    char tableName[MAX_TAB_NAME_SIZE];
    char frmData[MAX_FRM_DATA_SIZE];
430 431 432
    char rangeData[16*MAX_NDB_PARTITIONS];
    char ngData[2*MAX_NDB_PARTITIONS];
    char tsData[2*2*MAX_NDB_PARTITIONS];
433 434 435 436 437 438
    char defaultValue[MAX_ATTR_DEFAULT_VALUE_SIZE];
    char attributeName[MAX_ATTR_NAME_SIZE];
  };
  ConstRope r(c_rope_pool, tablePtr.p->tableName);
  r.copy(tableName);
  w.add(DictTabInfo::TableName, tableName);
439 440 441 442 443 444 445 446
  w.add(DictTabInfo::TableId, tablePtr.i);
  w.add(DictTabInfo::TableVersion, tablePtr.p->tableVersion);
  w.add(DictTabInfo::NoOfKeyAttr, tablePtr.p->noOfPrimkey);
  w.add(DictTabInfo::NoOfAttributes, tablePtr.p->noOfAttributes);
  w.add(DictTabInfo::NoOfNullable, tablePtr.p->noOfNullAttr);
  w.add(DictTabInfo::NoOfVariable, (Uint32)0);
  w.add(DictTabInfo::KeyLength, tablePtr.p->tupKeyLength);
  
447 448 449 450 451 452
  w.add(DictTabInfo::TableLoggedFlag, 
	!!(tablePtr.p->m_bits & TableRecord::TR_Logged));
  w.add(DictTabInfo::RowGCIFlag, 
	!!(tablePtr.p->m_bits & TableRecord::TR_RowGCI));
  w.add(DictTabInfo::RowChecksumFlag, 
	!!(tablePtr.p->m_bits & TableRecord::TR_RowChecksum));
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
453 454
  w.add(DictTabInfo::TableTemporaryFlag, 
	!!(tablePtr.p->m_bits & TableRecord::TR_Temporary));
455 456
  w.add(DictTabInfo::ForceVarPartFlag,
	!!(tablePtr.p->m_bits & TableRecord::TR_ForceVarPart));
457
  
458 459 460 461 462
  w.add(DictTabInfo::MinLoadFactor, tablePtr.p->minLoadFactor);
  w.add(DictTabInfo::MaxLoadFactor, tablePtr.p->maxLoadFactor);
  w.add(DictTabInfo::TableKValue, tablePtr.p->kValue);
  w.add(DictTabInfo::FragmentTypeVal, tablePtr.p->fragmentType);
  w.add(DictTabInfo::TableTypeVal, tablePtr.p->tableType);
463 464 465
  w.add(DictTabInfo::MaxRowsLow, tablePtr.p->maxRowsLow);
  w.add(DictTabInfo::MaxRowsHigh, tablePtr.p->maxRowsHigh);
  w.add(DictTabInfo::DefaultNoPartFlag, tablePtr.p->defaultNoPartFlag);
466
  w.add(DictTabInfo::LinearHashFlag, tablePtr.p->linearHashFlag);
467
  w.add(DictTabInfo::FragmentCount, tablePtr.p->fragmentCount);
468 469
  w.add(DictTabInfo::MinRowsLow, tablePtr.p->minRowsLow);
  w.add(DictTabInfo::MinRowsHigh, tablePtr.p->minRowsHigh);
470
  w.add(DictTabInfo::SingleUserMode, tablePtr.p->singleUserMode);
471 472

  if(signal)
473
  {
474 475
    /* Denna branch krs vid GET_TABINFOREQ */

476 477 478 479 480 481 482 483 484
    Uint32 * theData = signal->getDataPtrSend();
    CreateFragmentationReq * const req = (CreateFragmentationReq*)theData;
    req->senderRef = 0;
    req->senderData = RNIL;
    req->fragmentationType = tablePtr.p->fragmentType;
    req->noOfFragments = 0;
    req->primaryTableId = tablePtr.i;
    EXECUTE_DIRECT(DBDIH, GSN_CREATE_FRAGMENTATION_REQ, signal,
		   CreateFragmentationReq::SignalLength);
485 486
    ndbrequire(signal->theData[0] == 0);
    Uint16 *data = (Uint16*)&signal->theData[25];
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
487
    Uint32 count = 2 + (1 + data[0]) * data[1];
488
    w.add(DictTabInfo::ReplicaDataLen, 2*count);
489 490
    for (Uint32 i = 0; i < count; i++)
      data[i] = htons(data[i]);
491 492 493 494 495 496
    w.add(DictTabInfo::ReplicaData, data, 2*count);
  }
  else
  {
    /* Denna del krs vid CREATE_TABLEREQ, ALTER_TABLEREQ */
    ;
497
  }
498 499 500 501
  
  if (tablePtr.p->primaryTableId != RNIL){
    TableRecordPtr primTab;
    c_tableRecordPool.getPtr(primTab, tablePtr.p->primaryTableId);
502 503 504
    ConstRope r2(c_rope_pool, primTab.p->tableName);
    r2.copy(tableName);
    w.add(DictTabInfo::PrimaryTable, tableName);
505 506 507 508 509 510 511
    w.add(DictTabInfo::PrimaryTableId, tablePtr.p->primaryTableId);
    w.add(DictTabInfo::IndexState, tablePtr.p->indexState);
    w.add(DictTabInfo::InsertTriggerId, tablePtr.p->insertTriggerId);
    w.add(DictTabInfo::UpdateTriggerId, tablePtr.p->updateTriggerId);
    w.add(DictTabInfo::DeleteTriggerId, tablePtr.p->deleteTriggerId);
    w.add(DictTabInfo::CustomTriggerId, tablePtr.p->customTriggerId);
  }
512 513 514 515 516 517

  ConstRope frm(c_rope_pool, tablePtr.p->frmData);
  frm.copy(frmData);
  w.add(DictTabInfo::FrmLen, frm.size());
  w.add(DictTabInfo::FrmData, frmData, frm.size());

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
  {
    jam();
    ConstRope ts(c_rope_pool, tablePtr.p->tsData);
    ts.copy(tsData);
    w.add(DictTabInfo::TablespaceDataLen, ts.size());
    w.add(DictTabInfo::TablespaceData, tsData, ts.size());

    ConstRope ng(c_rope_pool, tablePtr.p->ngData);
    ng.copy(ngData);
    w.add(DictTabInfo::FragmentDataLen, ng.size());
    w.add(DictTabInfo::FragmentData, ngData, ng.size());

    ConstRope range(c_rope_pool, tablePtr.p->rangeData);
    range.copy(rangeData);
    w.add(DictTabInfo::RangeListDataLen, range.size());
    w.add(DictTabInfo::RangeListData, rangeData, range.size());
  }

536 537 538 539 540 541 542 543
  if(tablePtr.p->m_tablespace_id != RNIL)
  {
    w.add(DictTabInfo::TablespaceId, tablePtr.p->m_tablespace_id);
    FilegroupPtr tsPtr;
    ndbrequire(c_filegroup_hash.find(tsPtr, tablePtr.p->m_tablespace_id));
    w.add(DictTabInfo::TablespaceVersion, tsPtr.p->m_version);
  }

544
  AttributeRecordPtr attrPtr;
545 546 547
  LocalDLFifoList<AttributeRecord> list(c_attributeRecordPool, 
				    tablePtr.p->m_attributes);
  for(list.first(attrPtr); !attrPtr.isNull(); list.next(attrPtr)){
548
    jam();
549 550 551 552 553

    ConstRope name(c_rope_pool, attrPtr.p->attributeName);
    name.copy(attributeName);

    w.add(DictTabInfo::AttributeName, attributeName);
554 555 556 557 558 559 560
    w.add(DictTabInfo::AttributeId, attrPtr.p->attributeId);
    w.add(DictTabInfo::AttributeKeyFlag, attrPtr.p->tupleKey > 0);
    
    const Uint32 desc = attrPtr.p->attributeDescriptor;
    const Uint32 attrType = AttributeDescriptor::getType(desc);
    const Uint32 attrSize = AttributeDescriptor::getSize(desc);
    const Uint32 arraySize = AttributeDescriptor::getArraySize(desc);
561
    const Uint32 arrayType = AttributeDescriptor::getArrayType(desc);
562 563
    const Uint32 nullable = AttributeDescriptor::getNullable(desc);
    const Uint32 DKey = AttributeDescriptor::getDKey(desc);
564 565
    const Uint32 disk= AttributeDescriptor::getDiskBased(desc);
    
566

567
    // AttributeType deprecated
568 569
    w.add(DictTabInfo::AttributeSize, attrSize);
    w.add(DictTabInfo::AttributeArraySize, arraySize);
570
    w.add(DictTabInfo::AttributeArrayType, arrayType);
571 572
    w.add(DictTabInfo::AttributeNullableFlag, nullable);
    w.add(DictTabInfo::AttributeDKey, DKey);
573
    w.add(DictTabInfo::AttributeExtType, attrType);
574 575 576 577 578
    w.add(DictTabInfo::AttributeExtPrecision, attrPtr.p->extPrecision);
    w.add(DictTabInfo::AttributeExtScale, attrPtr.p->extScale);
    w.add(DictTabInfo::AttributeExtLength, attrPtr.p->extLength);
    w.add(DictTabInfo::AttributeAutoIncrement, 
	  (Uint32)attrPtr.p->autoIncrement);
579 580 581 582 583 584 585 586 587

    if(disk)
      w.add(DictTabInfo::AttributeStorageType, (Uint32)NDB_STORAGETYPE_DISK);
    else
      w.add(DictTabInfo::AttributeStorageType, (Uint32)NDB_STORAGETYPE_MEMORY);
    
    ConstRope def(c_rope_pool, attrPtr.p->defaultValue);
    def.copy(defaultValue);
    w.add(DictTabInfo::AttributeDefaultValue, defaultValue);
588 589
    
    w.add(DictTabInfo::AttributeEnd, 1);
590
  }
591 592 593 594
  
  w.add(DictTabInfo::TableEnd, 1);
}

595 596
void
Dbdict::packFilegroupIntoPages(SimpleProperties::Writer & w,
597 598 599
			       FilegroupPtr fg_ptr,
			       const Uint32 undo_free_hi,
			       const Uint32 undo_free_lo){
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
  
  DictFilegroupInfo::Filegroup fg; fg.init();
  ConstRope r(c_rope_pool, fg_ptr.p->m_name);
  r.copy(fg.FilegroupName);

  fg.FilegroupId = fg_ptr.p->key;
  fg.FilegroupType = fg_ptr.p->m_type;
  fg.FilegroupVersion = fg_ptr.p->m_version;

  switch(fg.FilegroupType){
  case DictTabInfo::Tablespace:
    //fg.TS_DataGrow = group.m_grow_spec;
    fg.TS_ExtentSize = fg_ptr.p->m_tablespace.m_extent_size;
    fg.TS_LogfileGroupId = fg_ptr.p->m_tablespace.m_default_logfile_group_id;
    FilegroupPtr lfg_ptr;
    ndbrequire(c_filegroup_hash.find(lfg_ptr, fg.TS_LogfileGroupId));
    fg.TS_LogfileGroupVersion = lfg_ptr.p->m_version;
    break;
  case DictTabInfo::LogfileGroup:
    fg.LF_UndoBufferSize = fg_ptr.p->m_logfilegroup.m_undo_buffer_size;
620 621
    fg.LF_UndoFreeWordsHi= undo_free_hi;
    fg.LF_UndoFreeWordsLo= undo_free_lo;
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    //fg.LF_UndoGrow = ;
    break;
  default:
    ndbrequire(false);
  }
  
  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
			     &fg,
			     DictFilegroupInfo::Mapping, 
			     DictFilegroupInfo::MappingSize, true);
  
  ndbrequire(s == SimpleProperties::Eof);
}

void
Dbdict::packFileIntoPages(SimpleProperties::Writer & w,
			  FilePtr f_ptr, const Uint32 free_extents){
  
  DictFilegroupInfo::File f; f.init();
  ConstRope r(c_rope_pool, f_ptr.p->m_path);
  r.copy(f.FileName);

  f.FileType = f_ptr.p->m_type;
  f.FilegroupId = f_ptr.p->m_filegroup_id;; //group.m_id;
  f.FileSizeHi = (f_ptr.p->m_file_size >> 32);
  f.FileSizeLo = (f_ptr.p->m_file_size & 0xFFFFFFFF);
  f.FileFreeExtents= free_extents;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
650 651
  f.FileId =  f_ptr.p->key;
  f.FileVersion = f_ptr.p->m_version;
652 653 654 655 656 657 658 659 660 661 662 663 664 665

  FilegroupPtr lfg_ptr;
  ndbrequire(c_filegroup_hash.find(lfg_ptr, f.FilegroupId));
  f.FilegroupVersion = lfg_ptr.p->m_version;

  SimpleProperties::UnpackStatus s;
  s = SimpleProperties::pack(w, 
			     &f,
			     DictFilegroupInfo::FileMapping, 
			     DictFilegroupInfo::FileMappingSize, true);
  
  ndbrequire(s == SimpleProperties::Eof);
}

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */
// The routines to handle responses from file system.
/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */

/* ---------------------------------------------------------------- */
// A file was successfully closed.
/* ---------------------------------------------------------------- */
void Dbdict::execFSCLOSECONF(Signal* signal) 
{
  FsConnectRecordPtr fsPtr;
  FsConf * const fsConf = (FsConf *)&signal->theData[0];
  jamEntry();
  c_fsConnectRecordPool.getPtr(fsPtr, fsConf->userPointer);
  switch (fsPtr.p->fsState) {
  case FsConnectRecord::CLOSE_WRITE_SCHEMA:
    jam();
    closeWriteSchemaConf(signal, fsPtr);
    break;
  case FsConnectRecord::CLOSE_READ_SCHEMA:
    jam();
    closeReadSchemaConf(signal, fsPtr);
    break;
  case FsConnectRecord::CLOSE_READ_TAB_FILE:
    jam();
    closeReadTableConf(signal, fsPtr);
    break;
  case FsConnectRecord::CLOSE_WRITE_TAB_FILE:
    jam();
    closeWriteTableConf(signal, fsPtr);
    break;
698
  case FsConnectRecord::OPEN_READ_SCHEMA2:
699
    openSchemaFile(signal, 1, fsPtr.i, false, false);
jonas@eel.(none)'s avatar
jonas@eel.(none) committed
700
    break;
701 702 703
  case FsConnectRecord::OPEN_READ_TAB_FILE2:
    openTableFile(signal, 1, fsPtr.i, c_readTableRecord.tableId, false);
    break;
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
  default:
    jamLine((fsPtr.p->fsState & 0xFFF));
    ndbrequire(false);
    break;
  }//switch
}//execFSCLOSECONF()


/* ---------------------------------------------------------------- */
// A file was successfully opened.
/* ---------------------------------------------------------------- */
void Dbdict::execFSOPENCONF(Signal* signal) 
{
  FsConnectRecordPtr fsPtr;
  jamEntry();
  FsConf * const fsConf = (FsConf *)&signal->theData[0];
  c_fsConnectRecordPool.getPtr(fsPtr, fsConf->userPointer);

  Uint32 filePointer = fsConf->filePointer;
  fsPtr.p->filePtr = filePointer;
  switch (fsPtr.p->fsState) {
  case FsConnectRecord::OPEN_WRITE_SCHEMA:
    jam();
    fsPtr.p->fsState = FsConnectRecord::WRITE_SCHEMA;
    writeSchemaFile(signal, filePointer, fsPtr.i);
    break;
  case FsConnectRecord::OPEN_READ_SCHEMA1:
    jam();
    fsPtr.p->fsState = FsConnectRecord::READ_SCHEMA1;
    readSchemaFile(signal, filePointer, fsPtr.i);
    break;
  case FsConnectRecord::OPEN_READ_SCHEMA2:
    jam();
    fsPtr.p->fsState = FsConnectRecord::READ_SCHEMA2;
    readSchemaFile(signal, filePointer, fsPtr.i);
    break;
  case FsConnectRecord::OPEN_READ_TAB_FILE1:
    jam();
    fsPtr.p->fsState = FsConnectRecord::READ_TAB_FILE1;
    readTableFile(signal, filePointer, fsPtr.i);
    break;
  case FsConnectRecord::OPEN_READ_TAB_FILE2:
    jam();
    fsPtr.p->fsState = FsConnectRecord::READ_TAB_FILE2;
    readTableFile(signal, filePointer, fsPtr.i);
    break;
  case FsConnectRecord::OPEN_WRITE_TAB_FILE:
    jam();
    fsPtr.p->fsState = FsConnectRecord::WRITE_TAB_FILE;
    writeTableFile(signal, filePointer, fsPtr.i);
    break;
  default:
    jamLine((fsPtr.p->fsState & 0xFFF));
    ndbrequire(false);
    break;
  }//switch
}//execFSOPENCONF()

/* ---------------------------------------------------------------- */
// An open file was refused.
/* ---------------------------------------------------------------- */
void Dbdict::execFSOPENREF(Signal* signal) 
{
  jamEntry();
  FsRef * const fsRef = (FsRef *)&signal->theData[0];
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.getPtr(fsPtr, fsRef->userPointer);
  switch (fsPtr.p->fsState) {
  case FsConnectRecord::OPEN_READ_SCHEMA1:
773
    jam();
774
    openReadSchemaRef(signal, fsPtr);
775
    return;
776 777 778
  case FsConnectRecord::OPEN_READ_TAB_FILE1:
    jam();
    openReadTableRef(signal, fsPtr);
779
    return;
780 781 782
  default:
    break;
  }//switch
783 784 785 786 787
  {
    char msg[100];
    sprintf(msg, "File system open failed during FsConnectRecord state %d", (Uint32)fsPtr.p->fsState);
    fsRefError(signal,__LINE__,msg);
  }
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
}//execFSOPENREF()

/* ---------------------------------------------------------------- */
// A file was successfully read.
/* ---------------------------------------------------------------- */
void Dbdict::execFSREADCONF(Signal* signal) 
{
  jamEntry();
  FsConf * const fsConf = (FsConf *)&signal->theData[0];
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.getPtr(fsPtr, fsConf->userPointer);
  switch (fsPtr.p->fsState) {
  case FsConnectRecord::READ_SCHEMA1:
  case FsConnectRecord::READ_SCHEMA2:
    readSchemaConf(signal ,fsPtr);
    break;
  case FsConnectRecord::READ_TAB_FILE1:
805 806 807 808 809 810 811 812 813
    if(ERROR_INSERTED(6007)){
      jam();
      FsRef * const fsRef = (FsRef *)&signal->theData[0];
      fsRef->userPointer = fsConf->userPointer;
      fsRef->setErrorCode(fsRef->errorCode, NDBD_EXIT_AFS_UNKNOWN);
      fsRef->osErrorCode = ~0; // Indicate local error
      execFSREADREF(signal);
      return;
    }//Testing how DICT behave if read of file 1 fails (Bug#28770)
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
  case FsConnectRecord::READ_TAB_FILE2:
    jam();
    readTableConf(signal ,fsPtr);
    break;
  default:
    jamLine((fsPtr.p->fsState & 0xFFF));
    ndbrequire(false);
    break;
  }//switch
}//execFSREADCONF()

/* ---------------------------------------------------------------- */
// A read file was refused.
/* ---------------------------------------------------------------- */
void Dbdict::execFSREADREF(Signal* signal) 
{
  jamEntry();
  FsRef * const fsRef = (FsRef *)&signal->theData[0];
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.getPtr(fsPtr, fsRef->userPointer);
  switch (fsPtr.p->fsState) {
  case FsConnectRecord::READ_SCHEMA1:
836
    jam();
837
    readSchemaRef(signal, fsPtr);
838
    return;
839 840 841
  case FsConnectRecord::READ_TAB_FILE1:
    jam();
    readTableRef(signal, fsPtr);
842
    return;
843 844 845
  default:
    break;
  }//switch
846 847 848 849 850
  {
    char msg[100];
    sprintf(msg, "File system read failed during FsConnectRecord state %d", (Uint32)fsPtr.p->fsState);
    fsRefError(signal,__LINE__,msg);
  }
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
}//execFSREADREF()

/* ---------------------------------------------------------------- */
// A file was successfully written.
/* ---------------------------------------------------------------- */
void Dbdict::execFSWRITECONF(Signal* signal) 
{
  FsConf * const fsConf = (FsConf *)&signal->theData[0];
  FsConnectRecordPtr fsPtr;
  jamEntry();
  c_fsConnectRecordPool.getPtr(fsPtr, fsConf->userPointer);
  switch (fsPtr.p->fsState) {
  case FsConnectRecord::WRITE_TAB_FILE:
    writeTableConf(signal, fsPtr);
    break;
  case FsConnectRecord::WRITE_SCHEMA:
    jam();
    writeSchemaConf(signal, fsPtr);
    break;
  default:
    jamLine((fsPtr.p->fsState & 0xFFF));
    ndbrequire(false);
    break;
  }//switch
}//execFSWRITECONF()


/* ---------------------------------------------------------------- */
// Routines to handle Read/Write of Table Files
/* ---------------------------------------------------------------- */
void
Dbdict::writeTableFile(Signal* signal, Uint32 tableId, 
		       SegmentedSectionPtr tabInfoPtr, Callback* callback){
  
  ndbrequire(c_writeTableRecord.tableWriteState == WriteTableRecord::IDLE);
  
887 888
  Uint32 pages = WORDS2PAGES(tabInfoPtr.sz);
  c_writeTableRecord.no_of_words = tabInfoPtr.sz;
889
  c_writeTableRecord.tableWriteState = WriteTableRecord::TWR_CALLBACK;
890 891 892
  c_writeTableRecord.m_callback = * callback;

  c_writeTableRecord.pageId = 0;
893 894
  ndbrequire(pages == 1);
  
895 896 897 898 899 900 901
  PageRecordPtr pageRecPtr;
  c_pageRecordArray.getPtr(pageRecPtr, c_writeTableRecord.pageId);
  copy(&pageRecPtr.p->word[ZPAGE_HEADER_SIZE], tabInfoPtr);
  
  memset(&pageRecPtr.p->word[0], 0, 4 * ZPAGE_HEADER_SIZE);
  pageRecPtr.p->word[ZPOS_CHECKSUM] = 
    computeChecksum(&pageRecPtr.p->word[0], 
902
		    pages * ZSIZE_OF_PAGES_IN_WORDS);
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 942 943
  
  startWriteTableFile(signal, tableId);
}

void Dbdict::startWriteTableFile(Signal* signal, Uint32 tableId)
{
  FsConnectRecordPtr fsPtr;
  c_writeTableRecord.tableId = tableId;
  c_fsConnectRecordPool.getPtr(fsPtr, getFsConnRecord());
  fsPtr.p->fsState = FsConnectRecord::OPEN_WRITE_TAB_FILE;
  openTableFile(signal, 0, fsPtr.i, tableId, true);
  c_writeTableRecord.noOfTableFilesHandled = 0;
}//Dbdict::startWriteTableFile()

void Dbdict::openTableFile(Signal* signal,
                           Uint32 fileNo,
                           Uint32 fsConPtr,
                           Uint32 tableId,
                           bool   writeFlag) 
{
  FsOpenReq * const fsOpenReq = (FsOpenReq *)&signal->theData[0];

  fsOpenReq->userReference = reference();
  fsOpenReq->userPointer = fsConPtr;
  if (writeFlag) {
    jam();
    fsOpenReq->fileFlags = 
      FsOpenReq::OM_WRITEONLY | 
      FsOpenReq::OM_TRUNCATE | 
      FsOpenReq::OM_CREATE | 
      FsOpenReq::OM_SYNC;
  } else {
    jam();
    fsOpenReq->fileFlags = FsOpenReq::OM_READONLY;
  }//if
  fsOpenReq->fileNumber[3] = 0; // Initialise before byte changes
  FsOpenReq::setVersion(fsOpenReq->fileNumber, 1);
  FsOpenReq::setSuffix(fsOpenReq->fileNumber, FsOpenReq::S_TABLELIST);
  FsOpenReq::v1_setDisk(fsOpenReq->fileNumber, (fileNo + 1));
  FsOpenReq::v1_setTable(fsOpenReq->fileNumber, tableId);
  FsOpenReq::v1_setFragment(fsOpenReq->fileNumber, (Uint32)-1);
944
  FsOpenReq::v1_setS(fsOpenReq->fileNumber, 0);
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
  FsOpenReq::v1_setP(fsOpenReq->fileNumber, 255);
/* ---------------------------------------------------------------- */
// File name : D1/DBDICT/T0/S1.TableList
// D1 means Disk 1 (set by fileNo + 1)
// T0 means table id = 0
// S1 means tableVersion 1
// TableList indicates that this is a file for a table description.
/* ---------------------------------------------------------------- */
  sendSignal(NDBFS_REF, GSN_FSOPENREQ, signal, FsOpenReq::SignalLength, JBA);
}//openTableFile()

void Dbdict::writeTableFile(Signal* signal, Uint32 filePtr, Uint32 fsConPtr) 
{
  FsReadWriteReq * const fsRWReq = (FsReadWriteReq *)&signal->theData[0];

  fsRWReq->filePointer = filePtr;
  fsRWReq->userReference = reference();
  fsRWReq->userPointer = fsConPtr;
  fsRWReq->operationFlag = 0; // Initialise before bit changes
  FsReadWriteReq::setSyncFlag(fsRWReq->operationFlag, 1);
  FsReadWriteReq::setFormatFlag(fsRWReq->operationFlag, 
                                FsReadWriteReq::fsFormatArrayOfPages);
967
  fsRWReq->varIndex = ZBAT_TABLE_FILE;
968
  fsRWReq->numberOfPages = WORDS2PAGES(c_writeTableRecord.no_of_words);
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
  fsRWReq->data.arrayOfPages.varIndex = c_writeTableRecord.pageId;
  fsRWReq->data.arrayOfPages.fileOffset = 0; // Write to file page 0
  sendSignal(NDBFS_REF, GSN_FSWRITEREQ, signal, 8, JBA);
}//writeTableFile()

void Dbdict::writeTableConf(Signal* signal,
                                FsConnectRecordPtr fsPtr)
{
  fsPtr.p->fsState = FsConnectRecord::CLOSE_WRITE_TAB_FILE;
  closeFile(signal, fsPtr.p->filePtr, fsPtr.i);
  return;
}//Dbdict::writeTableConf()

void Dbdict::closeWriteTableConf(Signal* signal,
                                 FsConnectRecordPtr fsPtr)
{
  c_writeTableRecord.noOfTableFilesHandled++;
  if (c_writeTableRecord.noOfTableFilesHandled < 2) {
    jam();
    fsPtr.p->fsState = FsConnectRecord::OPEN_WRITE_TAB_FILE;
    openTableFile(signal, 1, fsPtr.i, c_writeTableRecord.tableId, true);
    return;
  } 
  ndbrequire(c_writeTableRecord.noOfTableFilesHandled == 2);
  c_fsConnectRecordPool.release(fsPtr);
  WriteTableRecord::TableWriteState state = c_writeTableRecord.tableWriteState;
  c_writeTableRecord.tableWriteState = WriteTableRecord::IDLE;
  switch (state) {
  case WriteTableRecord::IDLE:
  case WriteTableRecord::WRITE_ADD_TABLE_MASTER :
  case WriteTableRecord::WRITE_ADD_TABLE_SLAVE :
  case WriteTableRecord::WRITE_RESTART_FROM_MASTER :
  case WriteTableRecord::WRITE_RESTART_FROM_OWN :
    ndbrequire(false);
    break;
1004
  case WriteTableRecord::TWR_CALLBACK:
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    jam();
    execute(signal, c_writeTableRecord.m_callback, 0);
    return;
  }
  ndbrequire(false);
}//Dbdict::closeWriteTableConf()

void Dbdict::startReadTableFile(Signal* signal, Uint32 tableId)
{
  //globalSignalLoggers.log(number(), "startReadTableFile");
  ndbrequire(!c_readTableRecord.inUse);
  
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.getPtr(fsPtr, getFsConnRecord());
  c_readTableRecord.inUse = true;
  c_readTableRecord.tableId = tableId;
  fsPtr.p->fsState = FsConnectRecord::OPEN_READ_TAB_FILE1;
  openTableFile(signal, 0, fsPtr.i, tableId, false);
}//Dbdict::startReadTableFile()

void Dbdict::openReadTableRef(Signal* signal,
                              FsConnectRecordPtr fsPtr) 
{
  fsPtr.p->fsState = FsConnectRecord::OPEN_READ_TAB_FILE2;
  openTableFile(signal, 1, fsPtr.i, c_readTableRecord.tableId, false);
  return;
}//Dbdict::openReadTableConf()

void Dbdict::readTableFile(Signal* signal, Uint32 filePtr, Uint32 fsConPtr) 
{
  FsReadWriteReq * const fsRWReq = (FsReadWriteReq *)&signal->theData[0];

  fsRWReq->filePointer = filePtr;
  fsRWReq->userReference = reference();
  fsRWReq->userPointer = fsConPtr;
  fsRWReq->operationFlag = 0; // Initialise before bit changes
  FsReadWriteReq::setSyncFlag(fsRWReq->operationFlag, 0);
  FsReadWriteReq::setFormatFlag(fsRWReq->operationFlag, 
                                FsReadWriteReq::fsFormatArrayOfPages);
1044
  fsRWReq->varIndex = ZBAT_TABLE_FILE;
1045
  fsRWReq->numberOfPages = WORDS2PAGES(c_readTableRecord.no_of_words);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  fsRWReq->data.arrayOfPages.varIndex = c_readTableRecord.pageId;
  fsRWReq->data.arrayOfPages.fileOffset = 0; // Write to file page 0
  sendSignal(NDBFS_REF, GSN_FSREADREQ, signal, 8, JBA);
}//readTableFile()

void Dbdict::readTableConf(Signal* signal,
			   FsConnectRecordPtr fsPtr)
{
  /* ---------------------------------------------------------------- */
  // Verify the data read from disk
  /* ---------------------------------------------------------------- */
  bool crashInd;
  if (fsPtr.p->fsState == FsConnectRecord::READ_TAB_FILE1) {
    jam();
    crashInd = false;
  } else {
    jam();
    crashInd = true;
  }//if

  PageRecordPtr tmpPagePtr;
  c_pageRecordArray.getPtr(tmpPagePtr, c_readTableRecord.pageId);
1068 1069
  Uint32 sz = 
    WORDS2PAGES(c_readTableRecord.no_of_words)*ZSIZE_OF_PAGES_IN_WORDS;
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  Uint32 chk = computeChecksum((const Uint32*)tmpPagePtr.p, sz);
  
  ndbrequire((chk == 0) || !crashInd);
  if(chk != 0){
    jam();
    ndbrequire(fsPtr.p->fsState == FsConnectRecord::READ_TAB_FILE1);
    readTableRef(signal, fsPtr);
    return;
  }//if
  
  fsPtr.p->fsState = FsConnectRecord::CLOSE_READ_TAB_FILE;
  closeFile(signal, fsPtr.p->filePtr, fsPtr.i);
  return;
}//Dbdict::readTableConf()

void Dbdict::readTableRef(Signal* signal,
                          FsConnectRecordPtr fsPtr)
{
1088 1089 1090
  /**
   * First close corrupt file
   */
1091
  fsPtr.p->fsState = FsConnectRecord::OPEN_READ_TAB_FILE2;
1092
  closeFile(signal, fsPtr.p->filePtr, fsPtr.i);
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
  return;
}//Dbdict::readTableRef()

void Dbdict::closeReadTableConf(Signal* signal,
                                FsConnectRecordPtr fsPtr)
{
  c_fsConnectRecordPool.release(fsPtr);
  c_readTableRecord.inUse = false;
  
  execute(signal, c_readTableRecord.m_callback, 0);
  return;
}//Dbdict::closeReadTableConf()

/* ---------------------------------------------------------------- */
// Routines to handle Read/Write of Schema Files
/* ---------------------------------------------------------------- */
void
Dbdict::updateSchemaState(Signal* signal, Uint32 tableId, 
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
1111 1112
			  SchemaFile::TableEntry* te, Callback* callback,
                          bool savetodisk){
1113
  jam();
1114 1115
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry * tableEntry = getTableEntry(xsf, tableId);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
  
  SchemaFile::TableState newState = 
    (SchemaFile::TableState)te->m_tableState;
  SchemaFile::TableState oldState = 
    (SchemaFile::TableState)tableEntry->m_tableState;
  
  Uint32 newVersion = te->m_tableVersion;
  Uint32 oldVersion = tableEntry->m_tableVersion;
  
  bool ok = false;
  switch(newState){
  case SchemaFile::ADD_STARTED:
    jam();
    ok = true;
1130
    ndbrequire(create_obj_inc_schema_version(oldVersion) == newVersion);
1131 1132 1133 1134 1135 1136 1137
    ndbrequire(oldState == SchemaFile::INIT ||
	       oldState == SchemaFile::DROP_TABLE_COMMITTED);
    break;
  case SchemaFile::TABLE_ADD_COMMITTED:
    jam();
    ok = true;
    ndbrequire(newVersion == oldVersion);
1138 1139
    ndbrequire(oldState == SchemaFile::ADD_STARTED ||
	       oldState == SchemaFile::DROP_TABLE_STARTED);
1140 1141 1142 1143
    break;
  case SchemaFile::ALTER_TABLE_COMMITTED:
    jam();
    ok = true;
1144
    ndbrequire(alter_obj_inc_schema_version(oldVersion) == newVersion);
1145 1146 1147 1148 1149 1150 1151 1152 1153
    ndbrequire(oldState == SchemaFile::TABLE_ADD_COMMITTED ||
	       oldState == SchemaFile::ALTER_TABLE_COMMITTED);
    break;
  case SchemaFile::DROP_TABLE_STARTED:
    jam();
  case SchemaFile::DROP_TABLE_COMMITTED:
    jam();
    ok = true;
    break;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
1154 1155 1156 1157 1158 1159
  case SchemaFile::TEMPORARY_TABLE_COMMITTED:
    jam();
    ndbrequire(oldState == SchemaFile::ADD_STARTED ||
               oldState == SchemaFile::TEMPORARY_TABLE_COMMITTED);
    ok = true;
    break;
1160 1161 1162 1163 1164 1165 1166 1167
  case SchemaFile::INIT:
    jam();
    ok = true;
    ndbrequire((oldState == SchemaFile::ADD_STARTED));
  }//if
  ndbrequire(ok);
  
  * tableEntry = * te;
1168
  computeChecksum(xsf, tableId / NDB_SF_PAGE_ENTRIES);
1169

knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
  if (savetodisk)
  {
    ndbrequire(c_writeSchemaRecord.inUse == false);
    c_writeSchemaRecord.inUse = true;
    
    c_writeSchemaRecord.pageId = c_schemaRecord.schemaPage;
    c_writeSchemaRecord.newFile = false;
    c_writeSchemaRecord.firstPage = tableId / NDB_SF_PAGE_ENTRIES;
    c_writeSchemaRecord.noOfPages = 1;
    c_writeSchemaRecord.m_callback = * callback;
    
    startWriteSchemaFile(signal);
  }
  else
  {
    execute(signal, *callback, 0);
  }
1187 1188 1189 1190 1191 1192 1193
}

void Dbdict::startWriteSchemaFile(Signal* signal)
{
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.getPtr(fsPtr, getFsConnRecord());
  fsPtr.p->fsState = FsConnectRecord::OPEN_WRITE_SCHEMA;
1194
  openSchemaFile(signal, 0, fsPtr.i, true, c_writeSchemaRecord.newFile);
1195 1196 1197 1198 1199 1200
  c_writeSchemaRecord.noOfSchemaFilesHandled = 0;
}//Dbdict::startWriteSchemaFile()

void Dbdict::openSchemaFile(Signal* signal,
                            Uint32 fileNo,
                            Uint32 fsConPtr,
1201 1202
                            bool writeFlag,
                            bool newFile)
1203 1204 1205 1206 1207 1208 1209 1210 1211
{
  FsOpenReq * const fsOpenReq = (FsOpenReq *)&signal->theData[0];
  fsOpenReq->userReference = reference();
  fsOpenReq->userPointer = fsConPtr;
  if (writeFlag) {
    jam();
    fsOpenReq->fileFlags = 
      FsOpenReq::OM_WRITEONLY | 
      FsOpenReq::OM_SYNC;
1212 1213 1214 1215
    if (newFile)
      fsOpenReq->fileFlags |=
        FsOpenReq::OM_TRUNCATE | 
        FsOpenReq::OM_CREATE;
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
  } else {
    jam();
    fsOpenReq->fileFlags = FsOpenReq::OM_READONLY;
  }//if
  fsOpenReq->fileNumber[3] = 0; // Initialise before byte changes
  FsOpenReq::setVersion(fsOpenReq->fileNumber, 1);
  FsOpenReq::setSuffix(fsOpenReq->fileNumber, FsOpenReq::S_SCHEMALOG);
  FsOpenReq::v1_setDisk(fsOpenReq->fileNumber, (fileNo + 1));
  FsOpenReq::v1_setTable(fsOpenReq->fileNumber, (Uint32)-1);
  FsOpenReq::v1_setFragment(fsOpenReq->fileNumber, (Uint32)-1);
  FsOpenReq::v1_setS(fsOpenReq->fileNumber, (Uint32)-1);
  FsOpenReq::v1_setP(fsOpenReq->fileNumber, 0);
/* ---------------------------------------------------------------- */
// File name : D1/DBDICT/P0.SchemaLog
// D1 means Disk 1 (set by fileNo + 1). Writes to both D1 and D2
// SchemaLog indicates that this is a file giving a list of current tables.
/* ---------------------------------------------------------------- */
  sendSignal(NDBFS_REF, GSN_FSOPENREQ, signal, FsOpenReq::SignalLength, JBA);
}//openSchemaFile()

void Dbdict::writeSchemaFile(Signal* signal, Uint32 filePtr, Uint32 fsConPtr) 
{
  FsReadWriteReq * const fsRWReq = (FsReadWriteReq *)&signal->theData[0];

1240 1241 1242 1243 1244 1245
  // check write record
  WriteSchemaRecord & wr = c_writeSchemaRecord;
  ndbrequire(wr.pageId == (wr.pageId != 0) * NDB_SF_MAX_PAGES);
  ndbrequire(wr.noOfPages != 0);
  ndbrequire(wr.firstPage + wr.noOfPages <= NDB_SF_MAX_PAGES);

1246 1247 1248 1249 1250 1251 1252
  fsRWReq->filePointer = filePtr;
  fsRWReq->userReference = reference();
  fsRWReq->userPointer = fsConPtr;
  fsRWReq->operationFlag = 0; // Initialise before bit changes
  FsReadWriteReq::setSyncFlag(fsRWReq->operationFlag, 1);
  FsReadWriteReq::setFormatFlag(fsRWReq->operationFlag, 
                                FsReadWriteReq::fsFormatArrayOfPages);
1253 1254 1255 1256 1257
  fsRWReq->varIndex = ZBAT_SCHEMA_FILE;
  fsRWReq->numberOfPages = wr.noOfPages;
  // Write from memory page
  fsRWReq->data.arrayOfPages.varIndex = wr.pageId + wr.firstPage;
  fsRWReq->data.arrayOfPages.fileOffset = wr.firstPage;
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
  sendSignal(NDBFS_REF, GSN_FSWRITEREQ, signal, 8, JBA);
}//writeSchemaFile()

void Dbdict::writeSchemaConf(Signal* signal,
                                FsConnectRecordPtr fsPtr)
{
  fsPtr.p->fsState = FsConnectRecord::CLOSE_WRITE_SCHEMA;
  closeFile(signal, fsPtr.p->filePtr, fsPtr.i);
  return;
}//Dbdict::writeSchemaConf()

void Dbdict::closeFile(Signal* signal, Uint32 filePtr, Uint32 fsConPtr) 
{
  FsCloseReq * const fsCloseReq = (FsCloseReq *)&signal->theData[0];
  fsCloseReq->filePointer = filePtr;
  fsCloseReq->userReference = reference();
  fsCloseReq->userPointer = fsConPtr;
  FsCloseReq::setRemoveFileFlag(fsCloseReq->fileFlag, false);
  sendSignal(NDBFS_REF, GSN_FSCLOSEREQ, signal, FsCloseReq::SignalLength, JBA);
  return;
}//closeFile()

void Dbdict::closeWriteSchemaConf(Signal* signal,
                                     FsConnectRecordPtr fsPtr)
{
  c_writeSchemaRecord.noOfSchemaFilesHandled++;
  if (c_writeSchemaRecord.noOfSchemaFilesHandled < 2) {
    jam();
    fsPtr.p->fsState = FsConnectRecord::OPEN_WRITE_SCHEMA;
1287
    openSchemaFile(signal, 1, fsPtr.i, true, c_writeSchemaRecord.newFile);
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    return;
  } 
  ndbrequire(c_writeSchemaRecord.noOfSchemaFilesHandled == 2);
  
  c_fsConnectRecordPool.release(fsPtr);

  c_writeSchemaRecord.inUse = false;
  execute(signal, c_writeSchemaRecord.m_callback, 0);
  return;
}//Dbdict::closeWriteSchemaConf()

void Dbdict::startReadSchemaFile(Signal* signal)
{
  //globalSignalLoggers.log(number(), "startReadSchemaFile");
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.getPtr(fsPtr, getFsConnRecord());
  fsPtr.p->fsState = FsConnectRecord::OPEN_READ_SCHEMA1;
1305
  openSchemaFile(signal, 0, fsPtr.i, false, false);
1306 1307 1308 1309 1310 1311
}//Dbdict::startReadSchemaFile()

void Dbdict::openReadSchemaRef(Signal* signal,
                               FsConnectRecordPtr fsPtr) 
{
  fsPtr.p->fsState = FsConnectRecord::OPEN_READ_SCHEMA2;
1312
  openSchemaFile(signal, 1, fsPtr.i, false, false);
1313 1314 1315 1316 1317 1318
}//Dbdict::openReadSchemaRef()

void Dbdict::readSchemaFile(Signal* signal, Uint32 filePtr, Uint32 fsConPtr) 
{
  FsReadWriteReq * const fsRWReq = (FsReadWriteReq *)&signal->theData[0];

1319 1320 1321 1322 1323 1324
  // check read record
  ReadSchemaRecord & rr = c_readSchemaRecord;
  ndbrequire(rr.pageId == (rr.pageId != 0) * NDB_SF_MAX_PAGES);
  ndbrequire(rr.noOfPages != 0);
  ndbrequire(rr.firstPage + rr.noOfPages <= NDB_SF_MAX_PAGES);

1325 1326 1327 1328 1329 1330 1331
  fsRWReq->filePointer = filePtr;
  fsRWReq->userReference = reference();
  fsRWReq->userPointer = fsConPtr;
  fsRWReq->operationFlag = 0; // Initialise before bit changes
  FsReadWriteReq::setSyncFlag(fsRWReq->operationFlag, 0);
  FsReadWriteReq::setFormatFlag(fsRWReq->operationFlag, 
                                FsReadWriteReq::fsFormatArrayOfPages);
1332 1333 1334 1335
  fsRWReq->varIndex = ZBAT_SCHEMA_FILE;
  fsRWReq->numberOfPages = rr.noOfPages;
  fsRWReq->data.arrayOfPages.varIndex = rr.pageId + rr.firstPage;
  fsRWReq->data.arrayOfPages.fileOffset = rr.firstPage;
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
  sendSignal(NDBFS_REF, GSN_FSREADREQ, signal, 8, JBA);
}//readSchemaFile()

void Dbdict::readSchemaConf(Signal* signal,
                            FsConnectRecordPtr fsPtr)
{
/* ---------------------------------------------------------------- */
// Verify the data read from disk
/* ---------------------------------------------------------------- */
  bool crashInd;
  if (fsPtr.p->fsState == FsConnectRecord::READ_SCHEMA1) {
    jam();
    crashInd = false;
  } else {
    jam();
    crashInd = true;
  }//if

1354 1355
  ReadSchemaRecord & rr = c_readSchemaRecord;
  XSchemaFile * xsf = &c_schemaFile[rr.pageId != 0];
1356

1357 1358 1359 1360 1361
  if (rr.schemaReadState == ReadSchemaRecord::INITIAL_READ_HEAD) {
    jam();
    ndbrequire(rr.firstPage == 0);
    SchemaFile * sf = &xsf->schemaPage[0];
    Uint32 noOfPages;
1362
    if (sf->NdbVersion < NDB_SF_VERSION_5_0_6) {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
      jam();
      const Uint32 pageSize_old = 32 * 1024;
      noOfPages = pageSize_old / NDB_SF_PAGE_SIZE - 1;
    } else {
      noOfPages = sf->FileSize / NDB_SF_PAGE_SIZE - 1;
    }
    rr.schemaReadState = ReadSchemaRecord::INITIAL_READ;
    if (noOfPages != 0) {
      rr.firstPage = 1;
      rr.noOfPages = noOfPages;
      readSchemaFile(signal, fsPtr.p->filePtr, fsPtr.i);
      return;
    }
  }
1377

1378 1379 1380
  SchemaFile * sf0 = &xsf->schemaPage[0];
  xsf->noOfPages = sf0->FileSize / NDB_SF_PAGE_SIZE;

1381 1382
  if (sf0->NdbVersion < NDB_SF_VERSION_5_0_6 &&
      ! convertSchemaFileTo_5_0_6(xsf)) {
1383
    jam();
1384
    ndbrequire(! crashInd);
1385 1386 1387
    ndbrequire(fsPtr.p->fsState == FsConnectRecord::READ_SCHEMA1);
    readSchemaRef(signal, fsPtr);
    return;
1388 1389 1390 1391
  }

  for (Uint32 n = 0; n < xsf->noOfPages; n++) {
    SchemaFile * sf = &xsf->schemaPage[n];
1392
    bool ok = false;
1393
    const char *reason;
1394
    if (memcmp(sf->Magic, NDB_SF_MAGIC, sizeof(sf->Magic)) != 0)
1395
    { jam(); reason = "magic code"; }
1396
    else if (sf->FileSize == 0)
1397
    { jam(); reason = "file size == 0"; }
1398
    else if (sf->FileSize % NDB_SF_PAGE_SIZE != 0)
1399
    { jam(); reason = "invalid size multiple"; }
1400
    else if (sf->FileSize != sf0->FileSize)
1401
    { jam(); reason = "invalid size"; }
1402
    else if (sf->PageNumber != n)
1403
    { jam(); reason = "invalid page number"; }
1404
    else if (computeChecksum((Uint32*)sf, NDB_SF_PAGE_SIZE_IN_WORDS) != 0)
1405
    { jam(); reason = "invalid checksum"; }
1406 1407
    else
      ok = true;
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417

    if (!ok)
    {
      char reason_msg[128];
      snprintf(reason_msg, sizeof(reason_msg),
               "schema file corrupt, page %u (%s, "
               "sz=%u sz0=%u pn=%u)",
               n, reason, sf->FileSize, sf0->FileSize, sf->PageNumber);
      if (crashInd)
        progError(__LINE__, NDBD_EXIT_SR_SCHEMAFILE, reason_msg);
1418 1419
      ndbrequireErr(fsPtr.p->fsState == FsConnectRecord::READ_SCHEMA1,
                    NDBD_EXIT_SR_SCHEMAFILE);
1420
      jam();
1421
      infoEvent("primary %s, trying backup", reason_msg);
1422 1423 1424 1425 1426
      readSchemaRef(signal, fsPtr);
      return;
    }
  }

1427 1428 1429 1430 1431 1432 1433 1434
  fsPtr.p->fsState = FsConnectRecord::CLOSE_READ_SCHEMA;
  closeFile(signal, fsPtr.p->filePtr, fsPtr.i);
  return;
}//Dbdict::readSchemaConf()

void Dbdict::readSchemaRef(Signal* signal,
                           FsConnectRecordPtr fsPtr)
{
jonas@eel.(none)'s avatar
jonas@eel.(none) committed
1435 1436 1437
  /**
   * First close corrupt file
   */
1438
  fsPtr.p->fsState = FsConnectRecord::OPEN_READ_SCHEMA2;
jonas@eel.(none)'s avatar
jonas@eel.(none) committed
1439
  closeFile(signal, fsPtr.p->filePtr, fsPtr.i);
1440
  return;
jonas@eel.(none)'s avatar
jonas@eel.(none) committed
1441
}
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452

void Dbdict::closeReadSchemaConf(Signal* signal,
                                 FsConnectRecordPtr fsPtr)
{
  c_fsConnectRecordPool.release(fsPtr);
  ReadSchemaRecord::SchemaReadState state = c_readSchemaRecord.schemaReadState;
  c_readSchemaRecord.schemaReadState = ReadSchemaRecord::IDLE;

  switch(state) {
  case ReadSchemaRecord::INITIAL_READ :
    jam();
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    {
      // write back both copies
      
      ndbrequire(c_writeSchemaRecord.inUse == false);
      XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.oldSchemaPage != 0 ];
      Uint32 noOfPages =
        (c_tableRecordPool.getSize() + NDB_SF_PAGE_ENTRIES - 1) /
        NDB_SF_PAGE_ENTRIES;
      resizeSchemaFile(xsf, noOfPages);

      c_writeSchemaRecord.inUse = true;
      c_writeSchemaRecord.pageId = c_schemaRecord.oldSchemaPage;
      c_writeSchemaRecord.newFile = true;
      c_writeSchemaRecord.firstPage = 0;
      c_writeSchemaRecord.noOfPages = xsf->noOfPages;

      c_writeSchemaRecord.m_callback.m_callbackFunction = 
        safe_cast(&Dbdict::initSchemaFile_conf);

      startWriteSchemaFile(signal);
    }
1474 1475 1476 1477 1478 1479 1480 1481 1482
    break;

  default :
    ndbrequire(false);
    break;

  }//switch
}//Dbdict::closeReadSchemaConf()

1483
bool
1484
Dbdict::convertSchemaFileTo_5_0_6(XSchemaFile * xsf)
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
{
  const Uint32 pageSize_old = 32 * 1024;
  Uint32 page_old[pageSize_old >> 2];
  SchemaFile * sf_old = (SchemaFile *)page_old;

  if (xsf->noOfPages * NDB_SF_PAGE_SIZE != pageSize_old)
    return false;
  SchemaFile * sf0 = &xsf->schemaPage[0];
  memcpy(sf_old, sf0, pageSize_old);

  // init max number new pages needed
  xsf->noOfPages = (sf_old->NoOfTableEntries + NDB_SF_PAGE_ENTRIES - 1) /
                   NDB_SF_PAGE_ENTRIES;
  initSchemaFile(xsf, 0, xsf->noOfPages, true);

  Uint32 noOfPages = 1;
  Uint32 n, i, j;
  for (n = 0; n < xsf->noOfPages; n++) {
1503
    jam();
1504 1505 1506 1507 1508 1509
    for (i = 0; i < NDB_SF_PAGE_ENTRIES; i++) {
      j = n * NDB_SF_PAGE_ENTRIES + i;
      if (j >= sf_old->NoOfTableEntries)
        continue;
      const SchemaFile::TableEntry_old & te_old = sf_old->TableEntries_old[j];
      if (te_old.m_tableState == SchemaFile::INIT ||
1510 1511
          te_old.m_tableState == SchemaFile::DROP_TABLE_COMMITTED ||
          te_old.m_noOfPages == 0)
1512 1513 1514 1515 1516 1517
        continue;
      SchemaFile * sf = &xsf->schemaPage[n];
      SchemaFile::TableEntry & te = sf->TableEntries[i];
      te.m_tableState = te_old.m_tableState;
      te.m_tableVersion = te_old.m_tableVersion;
      te.m_tableType = te_old.m_tableType;
1518 1519
      te.m_info_words = te_old.m_noOfPages * ZSIZE_OF_PAGES_IN_WORDS -
                        ZPAGE_HEADER_SIZE;
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
      te.m_gcp = te_old.m_gcp;
      if (noOfPages < n)
        noOfPages = n;
    }
  }
  xsf->noOfPages = noOfPages;
  initSchemaFile(xsf, 0, xsf->noOfPages, false);

  return true;
}

1531 1532 1533 1534 1535 1536 1537 1538 1539
/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          INITIALISATION MODULE ------------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains initialisation of data at start/restart.    */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

1540 1541
Dbdict::Dbdict(Block_context& ctx):
  SimulatedBlock(DBDICT, ctx),
1542
  c_attributeRecordHash(c_attributeRecordPool),
1543 1544 1545
  c_file_hash(c_file_pool),
  c_filegroup_hash(c_filegroup_pool),
  c_obj_hash(c_obj_pool),
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
  c_opCreateTable(c_opRecordPool),
  c_opDropTable(c_opRecordPool),
  c_opCreateIndex(c_opRecordPool),
  c_opDropIndex(c_opRecordPool),
  c_opAlterIndex(c_opRecordPool),
  c_opBuildIndex(c_opRecordPool),
  c_opCreateEvent(c_opRecordPool),
  c_opSubEvent(c_opRecordPool),
  c_opDropEvent(c_opRecordPool),
  c_opSignalUtil(c_opRecordPool),
  c_opCreateTrigger(c_opRecordPool),
  c_opDropTrigger(c_opRecordPool),
  c_opAlterTrigger(c_opRecordPool),
1559 1560 1561 1562
  c_schemaOp(c_opRecordPool),
  c_Trans(c_opRecordPool),
  c_opCreateObj(c_schemaOp),
  c_opDropObj(c_schemaOp),
1563 1564 1565
  c_opRecordSequence(0),
  c_dictLockQueue(c_dictLockPool),
  c_dictLockPoll(false)
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
{
  BLOCK_CONSTRUCTOR(Dbdict);
  
  // Transit signals
  addRecSignal(GSN_DUMP_STATE_ORD, &Dbdict::execDUMP_STATE_ORD);
  addRecSignal(GSN_GET_TABINFOREQ, &Dbdict::execGET_TABINFOREQ);
  addRecSignal(GSN_GET_TABLEID_REQ, &Dbdict::execGET_TABLEDID_REQ);
  addRecSignal(GSN_GET_TABINFO_CONF, &Dbdict::execGET_TABINFO_CONF);
  addRecSignal(GSN_CONTINUEB, &Dbdict::execCONTINUEB);

  addRecSignal(GSN_CREATE_TABLE_REQ, &Dbdict::execCREATE_TABLE_REQ);
  addRecSignal(GSN_CREATE_TAB_REQ, &Dbdict::execCREATE_TAB_REQ);
  addRecSignal(GSN_CREATE_TAB_REF, &Dbdict::execCREATE_TAB_REF);
  addRecSignal(GSN_CREATE_TAB_CONF, &Dbdict::execCREATE_TAB_CONF);
  addRecSignal(GSN_CREATE_FRAGMENTATION_REF, &Dbdict::execCREATE_FRAGMENTATION_REF);
  addRecSignal(GSN_CREATE_FRAGMENTATION_CONF, &Dbdict::execCREATE_FRAGMENTATION_CONF);
  addRecSignal(GSN_DIADDTABCONF, &Dbdict::execDIADDTABCONF);
  addRecSignal(GSN_DIADDTABREF, &Dbdict::execDIADDTABREF);
  addRecSignal(GSN_ADD_FRAGREQ, &Dbdict::execADD_FRAGREQ);
  addRecSignal(GSN_TAB_COMMITCONF, &Dbdict::execTAB_COMMITCONF);
  addRecSignal(GSN_TAB_COMMITREF, &Dbdict::execTAB_COMMITREF);
  addRecSignal(GSN_ALTER_TABLE_REQ, &Dbdict::execALTER_TABLE_REQ);
  addRecSignal(GSN_ALTER_TAB_REQ, &Dbdict::execALTER_TAB_REQ);
  addRecSignal(GSN_ALTER_TAB_REF, &Dbdict::execALTER_TAB_REF);
  addRecSignal(GSN_ALTER_TAB_CONF, &Dbdict::execALTER_TAB_CONF);

  // Index signals
  addRecSignal(GSN_CREATE_INDX_REQ, &Dbdict::execCREATE_INDX_REQ);
  addRecSignal(GSN_CREATE_INDX_CONF, &Dbdict::execCREATE_INDX_CONF);
  addRecSignal(GSN_CREATE_INDX_REF, &Dbdict::execCREATE_INDX_REF);

  addRecSignal(GSN_ALTER_INDX_REQ, &Dbdict::execALTER_INDX_REQ);
  addRecSignal(GSN_ALTER_INDX_CONF, &Dbdict::execALTER_INDX_CONF);
  addRecSignal(GSN_ALTER_INDX_REF, &Dbdict::execALTER_INDX_REF);

  addRecSignal(GSN_CREATE_TABLE_CONF, &Dbdict::execCREATE_TABLE_CONF);
  addRecSignal(GSN_CREATE_TABLE_REF, &Dbdict::execCREATE_TABLE_REF);

  addRecSignal(GSN_DROP_INDX_REQ, &Dbdict::execDROP_INDX_REQ);
  addRecSignal(GSN_DROP_INDX_CONF, &Dbdict::execDROP_INDX_CONF);
  addRecSignal(GSN_DROP_INDX_REF, &Dbdict::execDROP_INDX_REF);

  addRecSignal(GSN_DROP_TABLE_CONF, &Dbdict::execDROP_TABLE_CONF);
  addRecSignal(GSN_DROP_TABLE_REF, &Dbdict::execDROP_TABLE_REF);

  addRecSignal(GSN_BUILDINDXREQ, &Dbdict::execBUILDINDXREQ);
  addRecSignal(GSN_BUILDINDXCONF, &Dbdict::execBUILDINDXCONF);
  addRecSignal(GSN_BUILDINDXREF, &Dbdict::execBUILDINDXREF);

  // Util signals
  addRecSignal(GSN_UTIL_PREPARE_CONF, &Dbdict::execUTIL_PREPARE_CONF);
  addRecSignal(GSN_UTIL_PREPARE_REF,  &Dbdict::execUTIL_PREPARE_REF);

  addRecSignal(GSN_UTIL_EXECUTE_CONF, &Dbdict::execUTIL_EXECUTE_CONF);
  addRecSignal(GSN_UTIL_EXECUTE_REF,  &Dbdict::execUTIL_EXECUTE_REF);

  addRecSignal(GSN_UTIL_RELEASE_CONF, &Dbdict::execUTIL_RELEASE_CONF);
  addRecSignal(GSN_UTIL_RELEASE_REF,  &Dbdict::execUTIL_RELEASE_REF);

  // Event signals
  addRecSignal(GSN_CREATE_EVNT_REQ,  &Dbdict::execCREATE_EVNT_REQ);
  addRecSignal(GSN_CREATE_EVNT_CONF, &Dbdict::execCREATE_EVNT_CONF);
  addRecSignal(GSN_CREATE_EVNT_REF,  &Dbdict::execCREATE_EVNT_REF);

  addRecSignal(GSN_CREATE_SUBID_CONF, &Dbdict::execCREATE_SUBID_CONF);
  addRecSignal(GSN_CREATE_SUBID_REF,  &Dbdict::execCREATE_SUBID_REF);

  addRecSignal(GSN_SUB_CREATE_CONF, &Dbdict::execSUB_CREATE_CONF);
  addRecSignal(GSN_SUB_CREATE_REF,  &Dbdict::execSUB_CREATE_REF);

  addRecSignal(GSN_SUB_START_REQ,  &Dbdict::execSUB_START_REQ);
  addRecSignal(GSN_SUB_START_CONF,  &Dbdict::execSUB_START_CONF);
  addRecSignal(GSN_SUB_START_REF,  &Dbdict::execSUB_START_REF);

  addRecSignal(GSN_SUB_STOP_REQ,  &Dbdict::execSUB_STOP_REQ);
  addRecSignal(GSN_SUB_STOP_CONF,  &Dbdict::execSUB_STOP_CONF);
  addRecSignal(GSN_SUB_STOP_REF,  &Dbdict::execSUB_STOP_REF);

  addRecSignal(GSN_DROP_EVNT_REQ,  &Dbdict::execDROP_EVNT_REQ);

  addRecSignal(GSN_SUB_REMOVE_REQ, &Dbdict::execSUB_REMOVE_REQ);
  addRecSignal(GSN_SUB_REMOVE_CONF, &Dbdict::execSUB_REMOVE_CONF);
  addRecSignal(GSN_SUB_REMOVE_REF,  &Dbdict::execSUB_REMOVE_REF);

  // Trigger signals
  addRecSignal(GSN_CREATE_TRIG_REQ, &Dbdict::execCREATE_TRIG_REQ);
  addRecSignal(GSN_CREATE_TRIG_CONF, &Dbdict::execCREATE_TRIG_CONF);
  addRecSignal(GSN_CREATE_TRIG_REF, &Dbdict::execCREATE_TRIG_REF);
  addRecSignal(GSN_ALTER_TRIG_REQ, &Dbdict::execALTER_TRIG_REQ);
  addRecSignal(GSN_ALTER_TRIG_CONF, &Dbdict::execALTER_TRIG_CONF);
  addRecSignal(GSN_ALTER_TRIG_REF, &Dbdict::execALTER_TRIG_REF);
  addRecSignal(GSN_DROP_TRIG_REQ, &Dbdict::execDROP_TRIG_REQ);
  addRecSignal(GSN_DROP_TRIG_CONF, &Dbdict::execDROP_TRIG_CONF);
  addRecSignal(GSN_DROP_TRIG_REF, &Dbdict::execDROP_TRIG_REF);

  // Received signals
  addRecSignal(GSN_HOT_SPAREREP, &Dbdict::execHOT_SPAREREP);
  addRecSignal(GSN_GET_SCHEMA_INFOREQ, &Dbdict::execGET_SCHEMA_INFOREQ);
  addRecSignal(GSN_SCHEMA_INFO, &Dbdict::execSCHEMA_INFO);
  addRecSignal(GSN_SCHEMA_INFOCONF, &Dbdict::execSCHEMA_INFOCONF);
  addRecSignal(GSN_DICTSTARTREQ, &Dbdict::execDICTSTARTREQ);
  addRecSignal(GSN_READ_NODESCONF, &Dbdict::execREAD_NODESCONF);
  addRecSignal(GSN_FSOPENCONF, &Dbdict::execFSOPENCONF);
1669
  addRecSignal(GSN_FSOPENREF, &Dbdict::execFSOPENREF, true);
1670 1671 1672
  addRecSignal(GSN_FSCLOSECONF, &Dbdict::execFSCLOSECONF);
  addRecSignal(GSN_FSWRITECONF, &Dbdict::execFSWRITECONF);
  addRecSignal(GSN_FSREADCONF, &Dbdict::execFSREADCONF);
1673
  addRecSignal(GSN_FSREADREF, &Dbdict::execFSREADREF, true);
1674 1675 1676 1677 1678
  addRecSignal(GSN_LQHFRAGCONF, &Dbdict::execLQHFRAGCONF);
  addRecSignal(GSN_LQHADDATTCONF, &Dbdict::execLQHADDATTCONF);
  addRecSignal(GSN_LQHADDATTREF, &Dbdict::execLQHADDATTREF);
  addRecSignal(GSN_LQHFRAGREF, &Dbdict::execLQHFRAGREF);
  addRecSignal(GSN_NDB_STTOR, &Dbdict::execNDB_STTOR);
1679
  addRecSignal(GSN_READ_CONFIG_REQ, &Dbdict::execREAD_CONFIG_REQ, true);
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
  addRecSignal(GSN_STTOR, &Dbdict::execSTTOR);
  addRecSignal(GSN_TC_SCHVERCONF, &Dbdict::execTC_SCHVERCONF);
  addRecSignal(GSN_NODE_FAILREP, &Dbdict::execNODE_FAILREP);
  addRecSignal(GSN_INCL_NODEREQ, &Dbdict::execINCL_NODEREQ);
  addRecSignal(GSN_API_FAILREQ, &Dbdict::execAPI_FAILREQ);

  addRecSignal(GSN_WAIT_GCP_REF, &Dbdict::execWAIT_GCP_REF);
  addRecSignal(GSN_WAIT_GCP_CONF, &Dbdict::execWAIT_GCP_CONF);

  addRecSignal(GSN_LIST_TABLES_REQ, &Dbdict::execLIST_TABLES_REQ);

  addRecSignal(GSN_DROP_TABLE_REQ, &Dbdict::execDROP_TABLE_REQ);
  
  addRecSignal(GSN_PREP_DROP_TAB_REQ, &Dbdict::execPREP_DROP_TAB_REQ);
  addRecSignal(GSN_PREP_DROP_TAB_REF, &Dbdict::execPREP_DROP_TAB_REF);
  addRecSignal(GSN_PREP_DROP_TAB_CONF, &Dbdict::execPREP_DROP_TAB_CONF);
  
  addRecSignal(GSN_DROP_TAB_REQ, &Dbdict::execDROP_TAB_REQ);
  addRecSignal(GSN_DROP_TAB_REF, &Dbdict::execDROP_TAB_REF);
  addRecSignal(GSN_DROP_TAB_CONF, &Dbdict::execDROP_TAB_CONF);
joreland@mysql.com's avatar
joreland@mysql.com committed
1700

1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
  addRecSignal(GSN_CREATE_FILE_REQ, &Dbdict::execCREATE_FILE_REQ);
  addRecSignal(GSN_CREATE_FILEGROUP_REQ, &Dbdict::execCREATE_FILEGROUP_REQ);

  addRecSignal(GSN_DROP_FILE_REQ, &Dbdict::execDROP_FILE_REQ);
  addRecSignal(GSN_DROP_FILE_REF, &Dbdict::execDROP_FILE_REF);
  addRecSignal(GSN_DROP_FILE_CONF, &Dbdict::execDROP_FILE_CONF);

  addRecSignal(GSN_DROP_FILEGROUP_REQ, &Dbdict::execDROP_FILEGROUP_REQ);
  addRecSignal(GSN_DROP_FILEGROUP_REF, &Dbdict::execDROP_FILEGROUP_REF);
  addRecSignal(GSN_DROP_FILEGROUP_CONF, &Dbdict::execDROP_FILEGROUP_CONF);
  
  addRecSignal(GSN_CREATE_OBJ_REQ, &Dbdict::execCREATE_OBJ_REQ);
  addRecSignal(GSN_CREATE_OBJ_REF, &Dbdict::execCREATE_OBJ_REF);
  addRecSignal(GSN_CREATE_OBJ_CONF, &Dbdict::execCREATE_OBJ_CONF);
  addRecSignal(GSN_DROP_OBJ_REQ, &Dbdict::execDROP_OBJ_REQ);
  addRecSignal(GSN_DROP_OBJ_REF, &Dbdict::execDROP_OBJ_REF);
  addRecSignal(GSN_DROP_OBJ_CONF, &Dbdict::execDROP_OBJ_CONF);

  addRecSignal(GSN_CREATE_FILE_REF, &Dbdict::execCREATE_FILE_REF);
  addRecSignal(GSN_CREATE_FILE_CONF, &Dbdict::execCREATE_FILE_CONF);
  addRecSignal(GSN_CREATE_FILEGROUP_REF, &Dbdict::execCREATE_FILEGROUP_REF);
  addRecSignal(GSN_CREATE_FILEGROUP_CONF, &Dbdict::execCREATE_FILEGROUP_CONF);

joreland@mysql.com's avatar
joreland@mysql.com committed
1724
  addRecSignal(GSN_BACKUP_FRAGMENT_REQ, &Dbdict::execBACKUP_FRAGMENT_REQ);
1725 1726 1727 1728 1729 1730 1731 1732 1733

  addRecSignal(GSN_DICT_COMMIT_REQ, &Dbdict::execDICT_COMMIT_REQ);
  addRecSignal(GSN_DICT_COMMIT_REF, &Dbdict::execDICT_COMMIT_REF);
  addRecSignal(GSN_DICT_COMMIT_CONF, &Dbdict::execDICT_COMMIT_CONF);

  addRecSignal(GSN_DICT_ABORT_REQ, &Dbdict::execDICT_ABORT_REQ);
  addRecSignal(GSN_DICT_ABORT_REF, &Dbdict::execDICT_ABORT_REF);
  addRecSignal(GSN_DICT_ABORT_CONF, &Dbdict::execDICT_ABORT_CONF);

1734 1735
  addRecSignal(GSN_DICT_LOCK_REQ, &Dbdict::execDICT_LOCK_REQ);
  addRecSignal(GSN_DICT_UNLOCK_ORD, &Dbdict::execDICT_UNLOCK_ORD);
1736 1737 1738 1739 1740 1741
}//Dbdict::Dbdict()

Dbdict::~Dbdict() 
{
}//Dbdict::~Dbdict()

1742
BLOCK_FUNCTIONS(Dbdict)
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 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 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792

void Dbdict::initCommonData() 
{
/* ---------------------------------------------------------------- */
// Initialise all common variables.
/* ---------------------------------------------------------------- */
  initRetrieveRecord(0, 0, 0);
  initSchemaRecord();
  initRestartRecord();
  initSendSchemaRecord();
  initReadTableRecord();
  initWriteTableRecord();
  initReadSchemaRecord();
  initWriteSchemaRecord();

  c_masterNodeId = ZNIL;
  c_numberNode = 0;
  c_noNodesFailed = 0;
  c_failureNr = 0;
  c_blockState = BS_IDLE;
  c_packTable.m_state = PackTable::PTS_IDLE;
  c_startPhase = 0;
  c_restartType = 255; //Ensure not used restartType
  c_tabinfoReceived = 0;
  c_initialStart = false;
  c_systemRestart = false;
  c_initialNodeRestart = false;
  c_nodeRestart = false;
}//Dbdict::initCommonData()

void Dbdict::initRecords() 
{
  initNodeRecords();
  initPageRecords();
  initTableRecords();
  initTriggerRecords();
}//Dbdict::initRecords()

void Dbdict::initSendSchemaRecord() 
{
  c_sendSchemaRecord.noOfWords = (Uint32)-1;
  c_sendSchemaRecord.pageId = RNIL;
  c_sendSchemaRecord.noOfWordsCurrentlySent = 0;
  c_sendSchemaRecord.noOfSignalsSentSinceDelay = 0;
  c_sendSchemaRecord.inUse = false;
  //c_sendSchemaRecord.sendSchemaState = SendSchemaRecord::IDLE;
}//initSendSchemaRecord()

void Dbdict::initReadTableRecord() 
{
1793
  c_readTableRecord.no_of_words= 0;
1794 1795 1796 1797 1798 1799 1800
  c_readTableRecord.pageId = RNIL;
  c_readTableRecord.tableId = ZNIL;
  c_readTableRecord.inUse = false;
}//initReadTableRecord()

void Dbdict::initWriteTableRecord() 
{
1801
  c_writeTableRecord.no_of_words= 0;
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
  c_writeTableRecord.pageId = RNIL;
  c_writeTableRecord.noOfTableFilesHandled = 3;
  c_writeTableRecord.tableId = ZNIL;
  c_writeTableRecord.tableWriteState = WriteTableRecord::IDLE;
}//initWriteTableRecord()

void Dbdict::initReadSchemaRecord() 
{
  c_readSchemaRecord.pageId = RNIL;
  c_readSchemaRecord.schemaReadState = ReadSchemaRecord::IDLE;
}//initReadSchemaRecord()

void Dbdict::initWriteSchemaRecord() 
{
  c_writeSchemaRecord.inUse = false;
  c_writeSchemaRecord.pageId = RNIL;
  c_writeSchemaRecord.noOfSchemaFilesHandled = 3;
}//initWriteSchemaRecord()

void Dbdict::initRetrieveRecord(Signal* signal, Uint32 i, Uint32 returnCode) 
{
  c_retrieveRecord.busyState = false;
  c_retrieveRecord.blockRef = 0;
  c_retrieveRecord.m_senderData = RNIL;
  c_retrieveRecord.tableId = RNIL;
  c_retrieveRecord.currentSent = 0;
  c_retrieveRecord.retrievedNoOfPages = 0;
  c_retrieveRecord.retrievedNoOfWords = 0;
  c_retrieveRecord.m_useLongSig = false;
}//initRetrieveRecord()

void Dbdict::initSchemaRecord() 
{
  c_schemaRecord.schemaPage = RNIL;
1836
  c_schemaRecord.oldSchemaPage = RNIL;
1837 1838 1839 1840 1841 1842
}//Dbdict::initSchemaRecord()

void Dbdict::initRestartRecord() 
{
  c_restartRecord.gciToRestart = 0;
  c_restartRecord.activeTable = ZNIL;
1843
  c_restartRecord.m_pass = 0;
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
}//Dbdict::initRestartRecord()

void Dbdict::initNodeRecords() 
{
  jam();
  for (unsigned i = 1; i < MAX_NODES; i++) {
    NodeRecordPtr nodePtr;
    c_nodes.getPtr(nodePtr, i);
    nodePtr.p->hotSpare = false;
    nodePtr.p->nodeState = NodeRecord::API_NODE;
  }//for
}//Dbdict::initNodeRecords()

void Dbdict::initPageRecords() 
{
1859 1860 1861 1862
  c_retrieveRecord.retrievePage =  ZMAX_PAGES_OF_TABLE_DEFINITION;
  ndbrequire(ZNUMBER_OF_PAGES >= (ZMAX_PAGES_OF_TABLE_DEFINITION + 1));
  c_schemaRecord.schemaPage = 0;
  c_schemaRecord.oldSchemaPage = NDB_SF_MAX_PAGES;
1863 1864 1865 1866 1867 1868 1869
}//Dbdict::initPageRecords()

void Dbdict::initTableRecords() 
{
  TableRecordPtr tablePtr;
  while (1) {
    jam();
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
1870
    refresh_watch_dog();
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
    c_tableRecordPool.seize(tablePtr);
    if (tablePtr.i == RNIL) {
      jam();
      break;
    }//if
    initialiseTableRecord(tablePtr);
  }//while
}//Dbdict::initTableRecords()

void Dbdict::initialiseTableRecord(TableRecordPtr tablePtr) 
{
1882
  new (tablePtr.p) TableRecord();
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
  tablePtr.p->activePage = RNIL;
  tablePtr.p->filePtr[0] = RNIL;
  tablePtr.p->filePtr[1] = RNIL;
  tablePtr.p->firstPage = RNIL;
  tablePtr.p->tableId = tablePtr.i;
  tablePtr.p->tableVersion = (Uint32)-1;
  tablePtr.p->tabState = TableRecord::NOT_DEFINED;
  tablePtr.p->tabReturnState = TableRecord::TRS_IDLE;
  tablePtr.p->fragmentType = DictTabInfo::AllNodesSmallTable;
  tablePtr.p->gciTableCreated = 0;
  tablePtr.p->noOfAttributes = ZNIL;
  tablePtr.p->noOfNullAttr = 0;
1895
  tablePtr.p->fragmentCount = 0;
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
  /*
    tablePtr.p->lh3PageIndexBits = 0;
    tablePtr.p->lh3DistrBits = 0;
    tablePtr.p->lh3PageBits = 6;
  */
  tablePtr.p->kValue = 6;
  tablePtr.p->localKeyLen = 1;
  tablePtr.p->maxLoadFactor = 80;
  tablePtr.p->minLoadFactor = 70;
  tablePtr.p->noOfPrimkey = 1;
  tablePtr.p->tupKeyLength = 1;
1907 1908 1909
  tablePtr.p->maxRowsLow = 0;
  tablePtr.p->maxRowsHigh = 0;
  tablePtr.p->defaultNoPartFlag = true;
1910
  tablePtr.p->linearHashFlag = true;
1911
  tablePtr.p->m_bits = 0;
1912 1913
  tablePtr.p->minRowsLow = 0;
  tablePtr.p->minRowsHigh = 0;
1914
  tablePtr.p->singleUserMode = 0;
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
  tablePtr.p->tableType = DictTabInfo::UserTable;
  tablePtr.p->primaryTableId = RNIL;
  // volatile elements
  tablePtr.p->indexState = TableRecord::IS_UNDEFINED;
  tablePtr.p->insertTriggerId = RNIL;
  tablePtr.p->updateTriggerId = RNIL;
  tablePtr.p->deleteTriggerId = RNIL;
  tablePtr.p->customTriggerId = RNIL;
  tablePtr.p->buildTriggerId = RNIL;
  tablePtr.p->indexLocal = 0;
}//Dbdict::initialiseTableRecord()

void Dbdict::initTriggerRecords()
{
  TriggerRecordPtr triggerPtr;
  while (1) {
    jam();
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
1932
    refresh_watch_dog();
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
    c_triggerRecordPool.seize(triggerPtr);
    if (triggerPtr.i == RNIL) {
      jam();
      break;
    }//if
    initialiseTriggerRecord(triggerPtr);
  }//while
}

void Dbdict::initialiseTriggerRecord(TriggerRecordPtr triggerPtr)
{
1944
  new (triggerPtr.p) TriggerRecord();
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
  triggerPtr.p->triggerState = TriggerRecord::TS_NOT_DEFINED;
  triggerPtr.p->triggerLocal = 0;
  triggerPtr.p->triggerId = RNIL;
  triggerPtr.p->tableId = RNIL;
  triggerPtr.p->triggerType = (TriggerType::Value)~0;
  triggerPtr.p->triggerActionTime = (TriggerActionTime::Value)~0;
  triggerPtr.p->triggerEvent = (TriggerEvent::Value)~0;
  triggerPtr.p->monitorReplicas = false;
  triggerPtr.p->monitorAllAttributes = false;
  triggerPtr.p->attributeMask.clear();
  triggerPtr.p->indexId = RNIL;
}

Uint32 Dbdict::getFsConnRecord() 
{
  FsConnectRecordPtr fsPtr;
  c_fsConnectRecordPool.seize(fsPtr);
  ndbrequire(fsPtr.i != RNIL);
  fsPtr.p->filePtr = (Uint32)-1;
  fsPtr.p->ownerPtr = RNIL;
  fsPtr.p->fsState = FsConnectRecord::IDLE;
  return fsPtr.i;
}//Dbdict::getFsConnRecord()

1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
/*
 * Search schemafile for free entry.  Its index is used as 'logical id'
 * of new disk-stored object.
 */
Uint32 Dbdict::getFreeObjId(Uint32 minId)
{
  const XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  Uint32 noOfPages = xsf->noOfPages;
  Uint32 n, i;
  for (n = 0; n < noOfPages; n++) {
    jam();
    const SchemaFile * sf = &xsf->schemaPage[n];
    for (i = 0; i < NDB_SF_PAGE_ENTRIES; i++) {
      const SchemaFile::TableEntry& te = sf->TableEntries[i];
      if (te.m_tableState == (Uint32)SchemaFile::INIT ||
          te.m_tableState == (Uint32)SchemaFile::DROP_TABLE_COMMITTED) {
        // minId is obsolete anyway
        if (minId <= n * NDB_SF_PAGE_ENTRIES + i)
          return n * NDB_SF_PAGE_ENTRIES + i;
      }
    }
  }
  return RNIL;
}

1994 1995 1996
Uint32 Dbdict::getFreeTableRecord(Uint32 primaryTableId) 
{
  Uint32 minId = (primaryTableId == RNIL ? 0 : primaryTableId + 1);
1997 1998
  Uint32 i = getFreeObjId(minId);
  if (i == RNIL) {
1999 2000
    jam();
    return RNIL;
2001 2002
  }
  if (i >= c_tableRecordPool.getSize()) {
2003 2004
    jam();
    return RNIL;
2005 2006 2007 2008 2009 2010 2011 2012
  }
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, i);
  ndbrequire(tablePtr.p->tabState == TableRecord::NOT_DEFINED);
  initialiseTableRecord(tablePtr);
  tablePtr.p->tabState = TableRecord::DEFINING;
  return i;
}
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074

Uint32 Dbdict::getFreeTriggerRecord()
{
  const Uint32 size = c_triggerRecordPool.getSize();
  TriggerRecordPtr triggerPtr;
  for (triggerPtr.i = 0; triggerPtr.i < size; triggerPtr.i++) {
    jam();
    c_triggerRecordPool.getPtr(triggerPtr);
    if (triggerPtr.p->triggerState == TriggerRecord::TS_NOT_DEFINED) {
      jam();
      initialiseTriggerRecord(triggerPtr);
      return triggerPtr.i;
    }
  }
  return RNIL;
}

/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          START/RESTART HANDLING ------------------------ */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains the code that is common for all             */
/* start/restart types.                                             */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

/* ---------------------------------------------------------------- */
// This is sent as the first signal during start/restart.
/* ---------------------------------------------------------------- */
void Dbdict::execSTTOR(Signal* signal) 
{
  jamEntry();
  c_startPhase = signal->theData[1];
  switch (c_startPhase) {
  case 1:
    break;
  case 3:
    c_restartType = signal->theData[7];         /* valid if 3 */
    ndbrequire(c_restartType == NodeState::ST_INITIAL_START ||
               c_restartType == NodeState::ST_SYSTEM_RESTART ||
               c_restartType == NodeState::ST_INITIAL_NODE_RESTART ||
               c_restartType == NodeState::ST_NODE_RESTART);
    break;
  }
  sendSTTORRY(signal);
}//execSTTOR()

void Dbdict::sendSTTORRY(Signal* signal)
{
  signal->theData[0] = 0;       /* garbage SIGNAL KEY */
  signal->theData[1] = 0;       /* garbage SIGNAL VERSION NUMBER  */
  signal->theData[2] = 0;       /* garbage */
  signal->theData[3] = 1;       /* first wanted start phase */
  signal->theData[4] = 3;       /* get type of start */
  signal->theData[5] = ZNOMOREPHASES;
  sendSignal(NDBCNTR_REF, GSN_STTORRY, signal, 6, JBB);
}

/* ---------------------------------------------------------------- */
// We receive information about sizes of records.
/* ---------------------------------------------------------------- */
2075
void Dbdict::execREAD_CONFIG_REQ(Signal* signal) 
2076
{
2077 2078 2079 2080 2081
  const ReadConfigReq * req = (ReadConfigReq*)signal->getDataPtr();
  Uint32 ref = req->senderRef;
  Uint32 senderData = req->senderData;
  ndbrequire(req->noOfParameters == 0);

2082
  jamEntry();
2083 2084
 
  const ndb_mgm_configuration_iterator * p = 
2085
    m_ctx.m_config.getOwnConfigIterator();
2086 2087 2088
  ndbrequire(p != 0);
  
  Uint32 attributesize, tablerecSize;
2089 2090
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DB_NO_TRIGGERS, 
					&c_maxNoOfTriggers));
2091 2092
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DICT_ATTRIBUTE,&attributesize));
  ndbrequire(!ndb_mgm_get_int_parameter(p, CFG_DICT_TABLE, &tablerecSize));
2093 2094 2095 2096 2097 2098

  c_attributeRecordPool.setSize(attributesize);
  c_attributeRecordHash.setSize(64);
  c_fsConnectRecordPool.setSize(ZFS_CONNECT_SIZE);
  c_nodes.setSize(MAX_NODES);
  c_pageRecordArray.setSize(ZNUMBER_OF_PAGES);
2099
  c_schemaPageRecordArray.setSize(2 * NDB_SF_MAX_PAGES);
2100
  c_tableRecordPool.setSize(tablerecSize);
2101
  g_key_descriptor_pool.setSize(tablerecSize);
2102
  c_triggerRecordPool.setSize(c_maxNoOfTriggers);
2103 2104 2105 2106
  
  c_obj_pool.setSize(tablerecSize+c_maxNoOfTriggers);
  c_obj_hash.setSize((tablerecSize+c_maxNoOfTriggers+1)/2);

2107 2108 2109
  Pool_context pc;
  pc.m_block = this;

2110 2111
  c_file_hash.setSize(16);
  c_filegroup_hash.setSize(16);
2112 2113 2114

  c_file_pool.init(RT_DBDICT_FILE, pc);
  c_filegroup_pool.init(RT_DBDICT_FILEGROUP, pc);
2115
  
2116 2117 2118 2119
  c_opRecordPool.setSize(256);   // XXX need config params
  c_opCreateTable.setSize(8);
  c_opDropTable.setSize(8);
  c_opCreateIndex.setSize(8);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2120 2121 2122
  c_opCreateEvent.setSize(2);
  c_opSubEvent.setSize(2);
  c_opDropEvent.setSize(2);
2123 2124 2125 2126 2127 2128 2129
  c_opSignalUtil.setSize(8);
  c_opDropIndex.setSize(8);
  c_opAlterIndex.setSize(8);
  c_opBuildIndex.setSize(8);
  c_opCreateTrigger.setSize(8);
  c_opDropTrigger.setSize(8);
  c_opAlterTrigger.setSize(8);
2130 2131

  c_dictLockPool.setSize(32);
2132 2133 2134 2135 2136 2137 2138 2139
  
  // Initialize schema file copies
  c_schemaFile[0].schemaPage =
    (SchemaFile*)c_schemaPageRecordArray.getPtr(0 * NDB_SF_MAX_PAGES);
  c_schemaFile[0].noOfPages = 0;
  c_schemaFile[1].schemaPage =
    (SchemaFile*)c_schemaPageRecordArray.getPtr(1 * NDB_SF_MAX_PAGES);
  c_schemaFile[1].noOfPages = 0;
2140

2141 2142 2143 2144
  c_schemaOp.setSize(8);
  //c_opDropObj.setSize(8);
  c_Trans.setSize(8);

2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
  Uint32 rps = 0;
  rps += tablerecSize * (MAX_TAB_NAME_SIZE + MAX_FRM_DATA_SIZE);
  rps += attributesize * (MAX_ATTR_NAME_SIZE + MAX_ATTR_DEFAULT_VALUE_SIZE);
  rps += c_maxNoOfTriggers * MAX_TAB_NAME_SIZE;
  rps += (10 + 10) * MAX_TAB_NAME_SIZE;

  Uint32 sm = 5;
  ndb_mgm_get_int_parameter(p, CFG_DB_STRING_MEMORY, &sm);
  if (sm == 0)
    sm = 5;
  
  Uint32 sb = 0;
  if (sm < 100)
  {
    sb = (rps * sm) / 100;
  }
  else
  {
    sb = sm;
  }
  
  c_rope_pool.setSize(sb/28 + 100);
  
2168 2169
  // Initialize BAT for interface to file system
  NewVARIABLE* bat = allocateBat(2);
2170 2171 2172 2173 2174 2175
  bat[0].WA = &c_schemaPageRecordArray.getPtr(0)->word[0];
  bat[0].nrr = 2 * NDB_SF_MAX_PAGES;
  bat[0].ClusterSize = NDB_SF_PAGE_SIZE;
  bat[0].bits.q = NDB_SF_PAGE_SIZE_IN_WORDS_LOG2;
  bat[0].bits.v = 5;  // 32 bits per element
  bat[1].WA = &c_pageRecordArray.getPtr(0)->word[0];
2176 2177 2178 2179 2180
  bat[1].nrr = ZNUMBER_OF_PAGES;
  bat[1].ClusterSize = ZSIZE_OF_PAGES_IN_WORDS * 4;
  bat[1].bits.q = ZLOG_SIZE_OF_PAGES_IN_WORDS; // 2**13 = 8192 elements
  bat[1].bits.v = 5;  // 32 bits per element

2181
  initCommonData();
2182
  initRecords();
2183 2184 2185 2186 2187 2188

  ReadConfigConf * conf = (ReadConfigConf*)signal->getDataPtrSend();
  conf->senderRef = reference();
  conf->senderData = senderData;
  sendSignal(ref, GSN_READ_CONFIG_CONF, signal, 
	     ReadConfigConf::SignalLength, JBB);
2189 2190 2191 2192 2193 2194 2195 2196

  {
    Ptr<DictObject> ptr;
    SLList<DictObject> objs(c_obj_pool);
    while(objs.seize(ptr))
      new (ptr.p) DictObject();
    objs.release();
  }
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
}//execSIZEALT_REP()

/* ---------------------------------------------------------------- */
// Start phase signals sent by CNTR. We reply with NDB_STTORRY when
// we completed this phase.
/* ---------------------------------------------------------------- */
void Dbdict::execNDB_STTOR(Signal* signal) 
{
  jamEntry();
  c_startPhase = signal->theData[2];
  const Uint32 restartType = signal->theData[3];
  if (restartType == NodeState::ST_INITIAL_START) {
    jam();
    c_initialStart = true;
  } else if (restartType == NodeState::ST_SYSTEM_RESTART) {
    jam();
    c_systemRestart = true;
  } else if (restartType == NodeState::ST_INITIAL_NODE_RESTART) {
    jam();
    c_initialNodeRestart = true;
  } else if (restartType == NodeState::ST_NODE_RESTART) {
    jam();
    c_nodeRestart = true;
  } else {
    ndbrequire(false);
  }//if
  switch (c_startPhase) {
  case 1:
    jam();
    initSchemaFile(signal);
    break;
  case 3:
    jam();
    signal->theData[0] = reference();
    sendSignal(NDBCNTR_REF, GSN_READ_NODESREQ, signal, 1, JBB);
    break;
  case 6:
    jam();
    c_initialStart = false;
    c_systemRestart = false;
    c_initialNodeRestart = false;
    c_nodeRestart = false;
    sendNDB_STTORRY(signal);
    break;
  case 7:
    // uses c_restartType
    if(restartType == NodeState::ST_SYSTEM_RESTART &&
       c_masterNodeId == getOwnNodeId()){
      rebuildIndexes(signal, 0);
      return;
    }
    sendNDB_STTORRY(signal);
    break;
  default:
    jam();
    sendNDB_STTORRY(signal);
    break;
  }//switch
}//execNDB_STTOR()

void Dbdict::sendNDB_STTORRY(Signal* signal) 
{
  signal->theData[0] = reference();
  sendSignal(NDBCNTR_REF, GSN_NDB_STTORRY, signal, 1, JBB);
  return;
}//sendNDB_STTORRY()

/* ---------------------------------------------------------------- */
// We receive the information about which nodes that are up and down.
/* ---------------------------------------------------------------- */
void Dbdict::execREAD_NODESCONF(Signal* signal) 
{
  jamEntry();

  ReadNodesConf * const readNodes = (ReadNodesConf *)&signal->theData[0];
  c_numberNode   = readNodes->noOfNodes;
  c_masterNodeId = readNodes->masterNodeId;

  c_noNodesFailed = 0;
  c_aliveNodes.clear();
  for (unsigned i = 1; i < MAX_NDB_NODES; i++) {
    jam();
    NodeRecordPtr nodePtr;
    c_nodes.getPtr(nodePtr, i);

    if (NodeBitmask::get(readNodes->allNodes, i)) {
      jam();
      nodePtr.p->nodeState = NodeRecord::NDB_NODE_ALIVE;
      if (NodeBitmask::get(readNodes->inactiveNodes, i)) {
	jam();
	/**-------------------------------------------------------------------
	 *
	 * THIS NODE IS DEFINED IN THE CLUSTER BUT IS NOT ALIVE CURRENTLY.
	 * WE ADD THE NODE TO THE SET OF FAILED NODES AND ALSO SET THE
	 * BLOCKSTATE TO BUSY TO AVOID ADDING TABLES WHILE NOT ALL NODES ARE
	 * ALIVE.
	 *------------------------------------------------------------------*/
        nodePtr.p->nodeState = NodeRecord::NDB_NODE_DEAD;
	c_noNodesFailed++;
      } else {
	c_aliveNodes.set(i);
      }
    }//if
  }//for
  sendNDB_STTORRY(signal);
}//execREAD_NODESCONF()

/* ---------------------------------------------------------------- */
// HOT_SPAREREP informs DBDICT about which nodes that have become
// hot spare nodes.
/* ---------------------------------------------------------------- */
void Dbdict::execHOT_SPAREREP(Signal* signal) 
{
  Uint32 hotSpareNodes = 0;
  jamEntry();
  HotSpareRep * const hotSpare = (HotSpareRep*)&signal->theData[0];
  for (unsigned i = 1; i < MAX_NDB_NODES; i++) {
    if (NodeBitmask::get(hotSpare->theHotSpareNodes, i)) {
      NodeRecordPtr nodePtr;
      c_nodes.getPtr(nodePtr, i);
      nodePtr.p->hotSpare = true;
      hotSpareNodes++;
    }//if
  }//for
  ndbrequire(hotSpareNodes == hotSpare->noHotSpareNodes);
  c_noHotSpareNodes = hotSpareNodes;
  return;
}//execHOT_SPAREREP()

void Dbdict::initSchemaFile(Signal* signal) 
{
2328 2329 2330 2331 2332 2333 2334 2335
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  xsf->noOfPages = (c_tableRecordPool.getSize() + NDB_SF_PAGE_ENTRIES - 1)
                   / NDB_SF_PAGE_ENTRIES;
  initSchemaFile(xsf, 0, xsf->noOfPages, true);
  // init alt copy too for INR
  XSchemaFile * oldxsf = &c_schemaFile[c_schemaRecord.oldSchemaPage != 0];
  oldxsf->noOfPages = xsf->noOfPages;
  memcpy(&oldxsf->schemaPage[0], &xsf->schemaPage[0], xsf->schemaPage[0].FileSize);
2336 2337 2338 2339 2340 2341
  
  if (c_initialStart || c_initialNodeRestart) {    
    jam();
    ndbrequire(c_writeSchemaRecord.inUse == false);
    c_writeSchemaRecord.inUse = true;
    c_writeSchemaRecord.pageId = c_schemaRecord.schemaPage;
2342 2343 2344
    c_writeSchemaRecord.newFile = true;
    c_writeSchemaRecord.firstPage = 0;
    c_writeSchemaRecord.noOfPages = xsf->noOfPages;
2345 2346 2347 2348 2349 2350 2351 2352 2353

    c_writeSchemaRecord.m_callback.m_callbackFunction = 
      safe_cast(&Dbdict::initSchemaFile_conf);
    
    startWriteSchemaFile(signal);
  } else if (c_systemRestart || c_nodeRestart) {
    jam();
    ndbrequire(c_readSchemaRecord.schemaReadState == ReadSchemaRecord::IDLE);
    c_readSchemaRecord.pageId = c_schemaRecord.oldSchemaPage;
2354 2355 2356
    c_readSchemaRecord.firstPage = 0;
    c_readSchemaRecord.noOfPages = 1;
    c_readSchemaRecord.schemaReadState = ReadSchemaRecord::INITIAL_READ_HEAD;
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
    startReadSchemaFile(signal);
  } else {
    ndbrequire(false);
  }//if
}//Dbdict::initSchemaFile()

void
Dbdict::initSchemaFile_conf(Signal* signal, Uint32 callbackData, Uint32 rv){
  jam();
  sendNDB_STTORRY(signal);
}

void
Dbdict::activateIndexes(Signal* signal, Uint32 i)
{
  AlterIndxReq* req = (AlterIndxReq*)signal->getDataPtrSend();
  TableRecordPtr tablePtr;
  for (; i < c_tableRecordPool.getSize(); i++) {
    tablePtr.i = i;
    c_tableRecordPool.getPtr(tablePtr);
    if (tablePtr.p->tabState != TableRecord::DEFINED)
      continue;
    if (! tablePtr.p->isIndex())
      continue;
    jam();
    req->setUserRef(reference());
    req->setConnectionPtr(i);
    req->setTableId(tablePtr.p->primaryTableId);
    req->setIndexId(tablePtr.i);
    req->setIndexVersion(tablePtr.p->tableVersion);
    req->setOnline(true);
    if (c_restartType == NodeState::ST_SYSTEM_RESTART) {
      if (c_masterNodeId != getOwnNodeId())
        continue;
      // from file index state is not defined currently
      req->setRequestType(AlterIndxReq::RT_SYSTEMRESTART);
      req->addRequestFlag((Uint32)RequestFlag::RF_NOBUILD);
    }
    else if (
        c_restartType == NodeState::ST_NODE_RESTART ||
        c_restartType == NodeState::ST_INITIAL_NODE_RESTART) {
      // from master index must be online
      if (tablePtr.p->indexState != TableRecord::IS_ONLINE)
        continue;
      req->setRequestType(AlterIndxReq::RT_NODERESTART);
      // activate locally, rebuild not needed
      req->addRequestFlag((Uint32)RequestFlag::RF_LOCAL);
      req->addRequestFlag((Uint32)RequestFlag::RF_NOBUILD);
    } else {
      ndbrequire(false);
    }
    sendSignal(reference(), GSN_ALTER_INDX_REQ,
      signal, AlterIndxReq::SignalLength, JBB);
    return;
  }
  signal->theData[0] = reference();
  sendSignal(c_restartRecord.returnBlockRef, GSN_DICTSTARTCONF,
	     signal, 1, JBB);
}

void
Dbdict::rebuildIndexes(Signal* signal, Uint32 i){
  BuildIndxReq* const req = (BuildIndxReq*)signal->getDataPtrSend();
  
  TableRecordPtr indexPtr;
  for (; i < c_tableRecordPool.getSize(); i++) {
    indexPtr.i = i;
    c_tableRecordPool.getPtr(indexPtr);
    if (indexPtr.p->tabState != TableRecord::DEFINED)
      continue;
    if (! indexPtr.p->isIndex())
      continue;

    jam();

    req->setUserRef(reference());
    req->setConnectionPtr(i);
    req->setRequestType(BuildIndxReq::RT_SYSTEMRESTART);
    req->setBuildId(0);   // not used
    req->setBuildKey(0);  // not used
    req->setIndexType(indexPtr.p->tableType);
    req->setIndexId(indexPtr.i);
    req->setTableId(indexPtr.p->primaryTableId);
    req->setParallelism(16);

    // from file index state is not defined currently
2443
    if (indexPtr.p->m_bits & TableRecord::TR_Logged) {
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 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
      // rebuild not needed
      req->addRequestFlag((Uint32)RequestFlag::RF_NOBUILD);
    }
    
    // send
    sendSignal(reference(), GSN_BUILDINDXREQ,
	       signal, BuildIndxReq::SignalLength, JBB);
    return;
  }
  sendNDB_STTORRY(signal);
}


/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          SYSTEM RESTART MODULE ------------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains code specific for system restart            */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

/* ---------------------------------------------------------------- */
// DIH asks DICT to read in table data from disk during system
// restart. DIH also asks DICT to send information about which
// tables that should be started as part of this system restart.
// DICT will also activate the tables in TC as part of this process.
/* ---------------------------------------------------------------- */
void Dbdict::execDICTSTARTREQ(Signal* signal) 
{
  jamEntry();
  c_restartRecord.gciToRestart = signal->theData[0];
  c_restartRecord.returnBlockRef = signal->theData[1];
  if (c_nodeRestart || c_initialNodeRestart) {
    jam();   

    CRASH_INSERTION(6000);

    BlockReference dictRef = calcDictBlockRef(c_masterNodeId);
    signal->theData[0] = getOwnNodeId();
    sendSignal(dictRef, GSN_GET_SCHEMA_INFOREQ, signal, 1, JBB);
    return;
  }
  ndbrequire(c_systemRestart);
  ndbrequire(c_masterNodeId == getOwnNodeId());

  c_schemaRecord.m_callback.m_callbackData = 0;
  c_schemaRecord.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::masterRestart_checkSchemaStatusComplete);

2494
  c_restartRecord.m_pass = 0;
2495
  c_restartRecord.activeTable = 0;
2496
  c_schemaRecord.schemaPage = c_schemaRecord.oldSchemaPage; // ugly
2497 2498 2499 2500 2501 2502 2503 2504
  checkSchemaStatus(signal);
}//execDICTSTARTREQ()

void
Dbdict::masterRestart_checkSchemaStatusComplete(Signal* signal,
						Uint32 callbackData,
						Uint32 returnCode){

2505 2506 2507
  c_schemaRecord.schemaPage = 0; // ugly
  XSchemaFile * oldxsf = &c_schemaFile[c_schemaRecord.oldSchemaPage != 0];
  ndbrequire(oldxsf->noOfPages != 0);
2508 2509

  LinearSectionPtr ptr[3];
2510 2511
  ptr[0].p = (Uint32*)&oldxsf->schemaPage[0];
  ptr[0].sz = oldxsf->noOfPages * NDB_SF_PAGE_SIZE_IN_WORDS;
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526

  c_sendSchemaRecord.m_SCHEMAINFO_Counter = c_aliveNodes;
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);

  rg.m_nodes.clear(getOwnNodeId());
  Callback c = { 0, 0 };
  sendFragmentedSignal(rg,
		       GSN_SCHEMA_INFO,
		       signal, 
		       1, //SchemaInfo::SignalLength,
		       JBB,
		       ptr,
		       1,
		       c);

2527 2528 2529 2530
  XSchemaFile * newxsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  newxsf->noOfPages = oldxsf->noOfPages;
  memcpy(&newxsf->schemaPage[0], &oldxsf->schemaPage[0],
         oldxsf->noOfPages * NDB_SF_PAGE_SIZE);
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546

  signal->theData[0] = getOwnNodeId();
  sendSignal(reference(), GSN_SCHEMA_INFOCONF, signal, 1, JBB);
}

void 
Dbdict::execGET_SCHEMA_INFOREQ(Signal* signal){

  const Uint32 ref = signal->getSendersBlockRef();
  //const Uint32 senderData = signal->theData[0];
  
  ndbrequire(c_sendSchemaRecord.inUse == false);
  c_sendSchemaRecord.inUse = true;

  LinearSectionPtr ptr[3];
  
2547 2548
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  ndbrequire(xsf->noOfPages != 0);
2549
  
2550 2551
  ptr[0].p = (Uint32*)&xsf->schemaPage[0];
  ptr[0].sz = xsf->noOfPages * NDB_SF_PAGE_SIZE_IN_WORDS;
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 2588 2589 2590 2591 2592

  Callback c = { safe_cast(&Dbdict::sendSchemaComplete), 0 };
  sendFragmentedSignal(ref,
		       GSN_SCHEMA_INFO,
		       signal, 
		       1, //GetSchemaInfoConf::SignalLength,
		       JBB,
		       ptr,
		       1,
		       c);
}//Dbdict::execGET_SCHEMA_INFOREQ()

void
Dbdict::sendSchemaComplete(Signal * signal, 
			   Uint32 callbackData,
			   Uint32 returnCode){
  ndbrequire(c_sendSchemaRecord.inUse == true);
  c_sendSchemaRecord.inUse = false;

}


/* ---------------------------------------------------------------- */
// We receive the schema info from master as part of all restarts
// except the initial start where no tables exists.
/* ---------------------------------------------------------------- */
void Dbdict::execSCHEMA_INFO(Signal* signal) 
{
  jamEntry();
  if(!assembleFragments(signal)){
    jam();
    return;
  }

  if(getNodeState().getNodeRestartInProgress()){
    CRASH_INSERTION(6001);
  }

  SegmentedSectionPtr schemaDataPtr;
  signal->getSection(schemaDataPtr, 0);

2593 2594 2595 2596
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  ndbrequire(schemaDataPtr.sz % NDB_SF_PAGE_SIZE_IN_WORDS == 0);
  xsf->noOfPages = schemaDataPtr.sz / NDB_SF_PAGE_SIZE_IN_WORDS;
  copy((Uint32*)&xsf->schemaPage[0], schemaDataPtr);
2597
  releaseSections(signal);
2598 2599
  
  SchemaFile * sf0 = &xsf->schemaPage[0];
2600 2601
  if (sf0->NdbVersion < NDB_SF_VERSION_5_0_6) {
    bool ok = convertSchemaFileTo_5_0_6(xsf);
2602 2603
    ndbrequire(ok);
  }
2604
    
2605 2606 2607 2608
  validateChecksum(xsf);

  XSchemaFile * oldxsf = &c_schemaFile[c_schemaRecord.oldSchemaPage != 0];
  resizeSchemaFile(xsf, oldxsf->noOfPages);
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621

  ndbrequire(signal->getSendersBlockRef() != reference());
    
  /* ---------------------------------------------------------------- */
  // Synchronise our view on data with other nodes in the cluster.
  // This is an important part of restart handling where we will handle
  // cases where the table have been added but only partially, where
  // tables have been deleted but not completed the deletion yet and
  // other scenarios needing synchronisation.
  /* ---------------------------------------------------------------- */
  c_schemaRecord.m_callback.m_callbackData = 0;
  c_schemaRecord.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restart_checkSchemaStatusComplete);
2622 2623

  c_restartRecord.m_pass= 0;
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
  c_restartRecord.activeTable = 0;
  checkSchemaStatus(signal);
}//execSCHEMA_INFO()

void
Dbdict::restart_checkSchemaStatusComplete(Signal * signal, 
					  Uint32 callbackData,
					  Uint32 returnCode){

  ndbrequire(c_writeSchemaRecord.inUse == false);
  c_writeSchemaRecord.inUse = true;
2635
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
2636
  c_writeSchemaRecord.pageId = c_schemaRecord.schemaPage;
2637 2638 2639
  c_writeSchemaRecord.newFile = true;
  c_writeSchemaRecord.firstPage = 0;
  c_writeSchemaRecord.noOfPages = xsf->noOfPages;
2640 2641 2642 2643
  c_writeSchemaRecord.m_callback.m_callbackData = 0;
  c_writeSchemaRecord.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restart_writeSchemaConf);
  
2644 2645 2646
  for(Uint32 i = 0; i<xsf->noOfPages; i++)
    computeChecksum(xsf, i);  

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 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
  startWriteSchemaFile(signal);
}

void
Dbdict::restart_writeSchemaConf(Signal * signal, 
				Uint32 callbackData,
				Uint32 returnCode){

  if(c_systemRestart){
    jam();
    signal->theData[0] = getOwnNodeId();
    sendSignal(calcDictBlockRef(c_masterNodeId), GSN_SCHEMA_INFOCONF,
	       signal, 1, JBB);
    return;
  }
  
  ndbrequire(c_nodeRestart || c_initialNodeRestart);
  c_blockState = BS_IDLE;
  activateIndexes(signal, 0);
  return;
}

void Dbdict::execSCHEMA_INFOCONF(Signal* signal) 
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);

/* ---------------------------------------------------------------- */
// This signal is received in the master as part of system restart
// from all nodes (including the master) after they have synchronised
// their data with the master node's schema information.
/* ---------------------------------------------------------------- */
  const Uint32 nodeId = signal->theData[0];
  c_sendSchemaRecord.m_SCHEMAINFO_Counter.clearWaitingFor(nodeId);

  if (!c_sendSchemaRecord.m_SCHEMAINFO_Counter.done()){
    jam();
    return;
  }//if
  activateIndexes(signal, 0);
}//execSCHEMA_INFOCONF()

2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
static bool 
checkSchemaStatus(Uint32 tableType, Uint32 pass)
{
  switch(tableType){
  case DictTabInfo::UndefTableType:
    return true;
  case DictTabInfo::HashIndexTrigger:
  case DictTabInfo::SubscriptionTrigger:
  case DictTabInfo::ReadOnlyConstraint:
  case DictTabInfo::IndexTrigger:
    return false;
  case DictTabInfo::LogfileGroup:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2701
    return pass == 0 || pass == 9 || pass == 10;
2702
  case DictTabInfo::Tablespace:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2703
    return pass == 1 || pass == 8 || pass == 11;
2704 2705
  case DictTabInfo::Datafile:
  case DictTabInfo::Undofile:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2706
    return pass == 2 || pass == 7 || pass == 12;
2707 2708
  case DictTabInfo::SystemTable:
  case DictTabInfo::UserTable:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2709
    return /* pass == 3 || pass == 6 || */ pass == 13;
2710 2711 2712 2713
  case DictTabInfo::UniqueHashIndex:
  case DictTabInfo::HashIndex:
  case DictTabInfo::UniqueOrderedIndex:
  case DictTabInfo::OrderedIndex:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2714
    return /* pass == 4 || pass == 5 || */ pass == 14;
2715 2716 2717 2718 2719
  }
  
  return false;
}

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
static const Uint32 CREATE_OLD_PASS = 4;
static const Uint32 DROP_OLD_PASS = 9;
static const Uint32 CREATE_NEW_PASS = 14;
static const Uint32 LAST_PASS = 14;

NdbOut&
operator<<(NdbOut& out, const SchemaFile::TableEntry entry)
{
  out << "[";
  out << " state: " << entry.m_tableState;
  out << " version: " << hex << entry.m_tableVersion << dec;
  out << " type: " << entry.m_tableType;
  out << " words: " << entry.m_info_words;
  out << " gcp: " << entry.m_gcp;
  out << " ]";
  return out;
}

/**
 * Pass 0  Create old LogfileGroup
 * Pass 1  Create old Tablespace
 * Pass 2  Create old Datafile/Undofile
 * Pass 3  Create old Table           // NOT DONE DUE TO DIH
 * Pass 4  Create old Index           // NOT DONE DUE TO DIH
 
 * Pass 5  Drop old Index             // NOT DONE DUE TO DIH
 * Pass 6  Drop old Table             // NOT DONE DUE TO DIH
 * Pass 7  Drop old Datafile/Undofile
 * Pass 8  Drop old Tablespace
 * Pass 9  Drop old Logfilegroup
 
 * Pass 10 Create new LogfileGroup
 * Pass 11 Create new Tablespace
 * Pass 12 Create new Datafile/Undofile
 * Pass 13 Create new Table
 * Pass 14 Create new Index
 */

2758 2759
void Dbdict::checkSchemaStatus(Signal* signal) 
{
2760 2761 2762 2763
  XSchemaFile * newxsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  XSchemaFile * oldxsf = &c_schemaFile[c_schemaRecord.oldSchemaPage != 0];
  ndbrequire(newxsf->noOfPages == oldxsf->noOfPages);
  const Uint32 noOfEntries = newxsf->noOfPages * NDB_SF_PAGE_ENTRIES;
2764

2765
  for (; c_restartRecord.activeTable < noOfEntries;
2766 2767 2768 2769
       c_restartRecord.activeTable++) {
    jam();

    Uint32 tableId = c_restartRecord.activeTable;
2770 2771
    SchemaFile::TableEntry *newEntry = getTableEntry(newxsf, tableId);
    SchemaFile::TableEntry *oldEntry = getTableEntry(oldxsf, tableId);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2772
    SchemaFile::TableState newSchemaState = 
2773 2774 2775 2776 2777 2778
      (SchemaFile::TableState)newEntry->m_tableState;
    SchemaFile::TableState oldSchemaState = 
      (SchemaFile::TableState)oldEntry->m_tableState;

    if (c_restartRecord.activeTable >= c_tableRecordPool.getSize()) {
      jam();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2779
      ndbrequire(newSchemaState == SchemaFile::INIT);
2780 2781 2782 2783
      ndbrequire(oldSchemaState == SchemaFile::INIT);
      continue;
    }//if

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2784 2785 2786 2787 2788 2789
//#define PRINT_SCHEMA_RESTART
#ifdef PRINT_SCHEMA_RESTART
    char buf[100];
    snprintf(buf, sizeof(buf), "checkSchemaStatus: pass: %d table: %d", 
             c_restartRecord.m_pass, tableId);
#endif
2790
    
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2791 2792 2793 2794
    if (c_restartRecord.m_pass <= CREATE_OLD_PASS)
    {
      if (!::checkSchemaStatus(oldEntry->m_tableType, c_restartRecord.m_pass))
        continue;
2795

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2796 2797 2798 2799 2800 2801 2802 2803 2804
      switch(oldSchemaState){
      case SchemaFile::INIT: jam();
      case SchemaFile::DROP_TABLE_COMMITTED: jam();
      case SchemaFile::ADD_STARTED: jam();
      case SchemaFile::DROP_TABLE_STARTED: jam();
      case SchemaFile::TEMPORARY_TABLE_COMMITTED: jam();
	continue;
      case SchemaFile::TABLE_ADD_COMMITTED: jam();
      case SchemaFile::ALTER_TABLE_COMMITTED: jam();
2805
	jam();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2806 2807 2808 2809 2810 2811
#ifdef PRINT_SCHEMA_RESTART
        ndbout_c("%s -> restartCreateTab", buf);
        ndbout << *newEntry << " " << *oldEntry << endl;
#endif
	restartCreateTab(signal, tableId, oldEntry, oldEntry, true);        
        return;
2812 2813 2814
      }
    }

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
    if (c_restartRecord.m_pass <= DROP_OLD_PASS)
    {
      if (!::checkSchemaStatus(oldEntry->m_tableType, c_restartRecord.m_pass))
        continue;

      switch(oldSchemaState){
      case SchemaFile::INIT: jam();
      case SchemaFile::DROP_TABLE_COMMITTED: jam();
      case SchemaFile::TEMPORARY_TABLE_COMMITTED: jam();
        continue;
      case SchemaFile::ADD_STARTED: jam();
      case SchemaFile::DROP_TABLE_STARTED: jam();
#ifdef PRINT_SCHEMA_RESTART
        ndbout_c("%s -> restartDropTab", buf);
        ndbout << *newEntry << " " << *oldEntry << endl;
#endif
	restartDropTab(signal, tableId, oldEntry, newEntry);
        return;
      case SchemaFile::TABLE_ADD_COMMITTED: jam();
      case SchemaFile::ALTER_TABLE_COMMITTED: jam();
        if (! (* oldEntry == * newEntry))
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2836
        {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2837 2838 2839 2840 2841
#ifdef PRINT_SCHEMA_RESTART
          ndbout_c("%s -> restartDropTab", buf);
          ndbout << *newEntry << " " << *oldEntry << endl;
#endif
          restartDropTab(signal, tableId, oldEntry, newEntry);
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2842 2843
          return;
        }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2844
        continue;
2845 2846
      }
    }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860

    if (c_restartRecord.m_pass <= CREATE_NEW_PASS)
    {
      if (!::checkSchemaStatus(newEntry->m_tableType, c_restartRecord.m_pass))
        continue;
      
      switch(newSchemaState){
      case SchemaFile::INIT: jam();
      case SchemaFile::DROP_TABLE_COMMITTED: jam();
      case SchemaFile::TEMPORARY_TABLE_COMMITTED: jam();
        * oldEntry = * newEntry;
        continue;
      case SchemaFile::ADD_STARTED: jam();
      case SchemaFile::DROP_TABLE_STARTED: jam();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2861 2862 2863 2864
        ndbrequire(DictTabInfo::isTable(newEntry->m_tableType) ||
                   DictTabInfo::isIndex(newEntry->m_tableType));
        newEntry->m_tableState = SchemaFile::INIT;
        continue;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2865 2866 2867 2868
      case SchemaFile::TABLE_ADD_COMMITTED: jam();
      case SchemaFile::ALTER_TABLE_COMMITTED: jam();
        if (DictTabInfo::isIndex(newEntry->m_tableType) ||
            DictTabInfo::isTable(newEntry->m_tableType))
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2869
        {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2870 2871 2872 2873 2874 2875 2876 2877 2878
          bool file = * oldEntry == *newEntry &&
            (!DictTabInfo::isIndex(newEntry->m_tableType) || c_systemRestart);

#ifdef PRINT_SCHEMA_RESTART          
          ndbout_c("%s -> restartCreateTab (file: %d)", buf, file);
          ndbout << *newEntry << " " << *oldEntry << endl;
#endif
          restartCreateTab(signal, tableId, newEntry, newEntry, file);        
          * oldEntry = * newEntry;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2879 2880
          return;
        }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2881
        else if (! (* oldEntry == *newEntry))
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2882
        {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2883 2884 2885 2886 2887 2888
#ifdef PRINT_SCHEMA_RESTART
          ndbout_c("%s -> restartCreateTab", buf);
          ndbout << *newEntry << " " << *oldEntry << endl;
#endif
          restartCreateTab(signal, tableId, oldEntry, newEntry, false);        
          * oldEntry = * newEntry;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2889
          return;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2890 2891 2892
        }
        * oldEntry = * newEntry;
        continue;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
2893
      }
2894 2895 2896
    }
  }
  
2897 2898
  c_restartRecord.m_pass++;
  c_restartRecord.activeTable= 0;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2899
  if(c_restartRecord.m_pass <= LAST_PASS)
2900 2901 2902 2903 2904 2905 2906
  {
    checkSchemaStatus(signal);
  }
  else
  {
    execute(signal, c_schemaRecord.m_callback, 0);
  }
2907 2908 2909 2910
}//checkSchemaStatus()

void
Dbdict::restartCreateTab(Signal* signal, Uint32 tableId, 
2911 2912 2913
			 const SchemaFile::TableEntry * old_entry, 
			 const SchemaFile::TableEntry * new_entry, 
			 bool file){
2914
  jam();
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936

  switch(new_entry->m_tableType){
  case DictTabInfo::UndefTableType:
  case DictTabInfo::HashIndexTrigger:
  case DictTabInfo::SubscriptionTrigger:
  case DictTabInfo::ReadOnlyConstraint:
  case DictTabInfo::IndexTrigger:
    ndbrequire(false);
  case DictTabInfo::SystemTable:
  case DictTabInfo::UserTable:
  case DictTabInfo::UniqueHashIndex:
  case DictTabInfo::HashIndex:
  case DictTabInfo::UniqueOrderedIndex:
  case DictTabInfo::OrderedIndex:
    break;
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:
  case DictTabInfo::Datafile:
  case DictTabInfo::Undofile:
    restartCreateObj(signal, tableId, old_entry, new_entry, file);
    return;
  }
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
  
  CreateTableRecordPtr createTabPtr;  
  c_opCreateTable.seize(createTabPtr);
  ndbrequire(!createTabPtr.isNull());

  createTabPtr.p->key = ++c_opRecordSequence;
  c_opCreateTable.add(createTabPtr);
  
  createTabPtr.p->m_errorCode = 0;
  createTabPtr.p->m_tablePtrI = tableId;
  createTabPtr.p->m_coordinatorRef = reference();
  createTabPtr.p->m_senderRef = 0;
  createTabPtr.p->m_senderData = RNIL;
  createTabPtr.p->m_tabInfoPtrI = RNIL;
  createTabPtr.p->m_dihAddFragPtr = RNIL;

  if(file && !ERROR_INSERTED(6002)){
    jam();
    
2956
    c_readTableRecord.no_of_words = old_entry->m_info_words;
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
    c_readTableRecord.pageId = 0;
    c_readTableRecord.m_callback.m_callbackData = createTabPtr.p->key;
    c_readTableRecord.m_callback.m_callbackFunction = 
      safe_cast(&Dbdict::restartCreateTab_readTableConf);
    
    startReadTableFile(signal, tableId);
    return;
  } else {
    
    ndbrequire(c_masterNodeId != getOwnNodeId());
    
    /**
     * Get from master
     */
    GetTabInfoReq * const req = (GetTabInfoReq *)&signal->theData[0];
    req->senderRef = reference();
    req->senderData = createTabPtr.p->key;
    req->requestType = GetTabInfoReq::RequestById |
      GetTabInfoReq::LongSignalConf;
    req->tableId = tableId;
    sendSignal(calcDictBlockRef(c_masterNodeId), GSN_GET_TABINFOREQ, signal,
	       GetTabInfoReq::SignalLength, JBB);

    if(ERROR_INSERTED(6002)){
      NdbSleep_MilliSleep(10);
      CRASH_INSERTION(6002);
    }
  }
}

void
Dbdict::restartCreateTab_readTableConf(Signal* signal, 
				       Uint32 callbackData,
				       Uint32 returnCode){
  jam();
  
  PageRecordPtr pageRecPtr;
  c_pageRecordArray.getPtr(pageRecPtr, c_readTableRecord.pageId);

  ParseDictTabInfoRecord parseRecord;
  parseRecord.requestType = DictTabInfo::GetTabInfoConf;
  parseRecord.errorCode = 0;
  
3000 3001
  Uint32 sz = c_readTableRecord.no_of_words;
  SimplePropertiesLinearReader r(pageRecPtr.p->word+ZPAGE_HEADER_SIZE, sz);
3002
  handleTabInfoInit(r, &parseRecord);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3003 3004 3005 3006 3007
  if (parseRecord.errorCode != 0)
  {
    char buf[255];
    BaseString::snprintf(buf, sizeof(buf), 
			 "Unable to restart, fail while creating table %d"
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3008
			 " error: %d. Most likely change of configuration",
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3009 3010 3011
			 c_readTableRecord.tableId,
			 parseRecord.errorCode);
    progError(__LINE__, 
jonas@perch.ndb.mysql.com's avatar
merge  
jonas@perch.ndb.mysql.com committed
3012
	      NDBD_EXIT_INVALID_CONFIG,
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3013 3014 3015
	      buf);
    ndbrequire(parseRecord.errorCode == 0);
  }
3016

3017 3018 3019 3020 3021
  /* ---------------------------------------------------------------- */
  // We have read the table description from disk as part of system restart.
  // We will also write it back again to ensure that both copies are ok.
  /* ---------------------------------------------------------------- */
  ndbrequire(c_writeTableRecord.tableWriteState == WriteTableRecord::IDLE);
3022
  c_writeTableRecord.no_of_words = c_readTableRecord.no_of_words;
3023
  c_writeTableRecord.pageId = c_readTableRecord.pageId;
3024
  c_writeTableRecord.tableWriteState = WriteTableRecord::TWR_CALLBACK;
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
  c_writeTableRecord.m_callback.m_callbackData = callbackData;
  c_writeTableRecord.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateTab_writeTableConf);
  startWriteTableFile(signal, c_readTableRecord.tableId);
}

void
Dbdict::execGET_TABINFO_CONF(Signal* signal){
  jamEntry();

  if(!assembleFragments(signal)){
    jam();
    return;
  }
  
  GetTabInfoConf * const conf = (GetTabInfoConf*)signal->getDataPtr();

3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
  switch(conf->tableType){
  case DictTabInfo::UndefTableType:
  case DictTabInfo::HashIndexTrigger:
  case DictTabInfo::SubscriptionTrigger:
  case DictTabInfo::ReadOnlyConstraint:
  case DictTabInfo::IndexTrigger:
    ndbrequire(false);
  case DictTabInfo::SystemTable:
  case DictTabInfo::UserTable:
  case DictTabInfo::UniqueHashIndex:
  case DictTabInfo::HashIndex:
  case DictTabInfo::UniqueOrderedIndex:
  case DictTabInfo::OrderedIndex:
    break;
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:
  case DictTabInfo::Datafile:
  case DictTabInfo::Undofile:
    if(refToBlock(conf->senderRef) == TSMAN
       && (refToNode(conf->senderRef) == 0
	   || refToNode(conf->senderRef) == getOwnNodeId()))
    {
      jam();
      FilePtr fg_ptr;
      ndbrequire(c_file_hash.find(fg_ptr, conf->tableId));
      const Uint32 free_extents= conf->freeExtents;
      const Uint32 id= conf->tableId;
      const Uint32 type= conf->tableType;
      const Uint32 data= conf->senderData;
      signal->theData[0]= ZPACK_TABLE_INTO_PAGES;
      signal->theData[1]= id;
      signal->theData[2]= type;
      signal->theData[3]= data;
      signal->theData[4]= free_extents;
      sendSignal(reference(), GSN_CONTINUEB, signal, 5, JBB);
    }
3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
    else if(refToBlock(conf->senderRef) == LGMAN
	    && (refToNode(conf->senderRef) == 0
		|| refToNode(conf->senderRef) == getOwnNodeId()))
    {
      jam();
      FilegroupPtr fg_ptr;
      ndbrequire(c_filegroup_hash.find(fg_ptr, conf->tableId));
      const Uint32 free_hi= conf->freeWordsHi;
      const Uint32 free_lo= conf->freeWordsLo;
      const Uint32 id= conf->tableId;
      const Uint32 type= conf->tableType;
      const Uint32 data= conf->senderData;
      signal->theData[0]= ZPACK_TABLE_INTO_PAGES;
      signal->theData[1]= id;
      signal->theData[2]= type;
      signal->theData[3]= data;
      signal->theData[4]= free_hi;
      signal->theData[5]= free_lo;
      sendSignal(reference(), GSN_CONTINUEB, signal, 6, JBB);
    }
3098 3099 3100 3101 3102 3103 3104 3105
    else
    {
      jam();
      restartCreateObj_getTabInfoConf(signal);
    }
    return;
  }
  
3106 3107
  const Uint32 tableId = conf->tableId;
  const Uint32 senderData = conf->senderData;
3108

3109 3110
  SegmentedSectionPtr tabInfoPtr;
  signal->getSection(tabInfoPtr, GetTabInfoConf::DICT_TAB_INFO);
3111

3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, senderData));
  ndbrequire(!createTabPtr.isNull());
  ndbrequire(createTabPtr.p->m_tablePtrI == tableId);

  /**
   * Put data into table record
   */
  ParseDictTabInfoRecord parseRecord;
  parseRecord.requestType = DictTabInfo::GetTabInfoConf;
  parseRecord.errorCode = 0;
  
  SimplePropertiesSectionReader r(tabInfoPtr, getSectionSegmentPool());
  handleTabInfoInit(r, &parseRecord);
  ndbrequire(parseRecord.errorCode == 0);
3127

knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
3128 3129
  // save to disk

3130 3131 3132 3133
  ndbrequire(tableId < c_tableRecordPool.getSize());
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry * tableEntry = getTableEntry(xsf, tableId);
  tableEntry->m_info_words= tabInfoPtr.sz;
3134 3135 3136 3137 3138 3139
  
  Callback callback;
  callback.m_callbackData = createTabPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateTab_writeTableConf);
  
3140
  signal->header.m_noOfSections = 0;
3141
  writeTableFile(signal, createTabPtr.p->m_tablePtrI, tabInfoPtr, &callback);
3142 3143
  signal->setSection(tabInfoPtr, 0);
  releaseSections(signal);
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
}

void
Dbdict::restartCreateTab_writeTableConf(Signal* signal, 
					Uint32 callbackData,
					Uint32 returnCode){
  jam();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));

  Callback callback;
  callback.m_callbackData = callbackData;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateTab_dihComplete);
  
mskold@mysql.com's avatar
mskold@mysql.com committed
3160 3161 3162
  SegmentedSectionPtr fragDataPtr; 
  fragDataPtr.sz = 0;
  fragDataPtr.setNull();
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173
  createTab_dih(signal, createTabPtr, fragDataPtr, &callback);
}

void
Dbdict::restartCreateTab_dihComplete(Signal* signal, 
				     Uint32 callbackData,
				     Uint32 returnCode){
  jam();
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));
3174 3175 3176 3177 3178 3179 3180 3181 3182

  if(createTabPtr.p->m_errorCode)
  {
    char buf[100];
    BaseString::snprintf(buf, sizeof(buf), "Failed to create table during"
                         " restart, Error: %u",
                         createTabPtr.p->m_errorCode);
    progError(__LINE__, NDBD_EXIT_RESOURCE_ALLOC_ERROR, buf);
  }
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204

  Callback callback;
  callback.m_callbackData = callbackData;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateTab_activateComplete);
  
  alterTab_activate(signal, createTabPtr, &callback);
}

void
Dbdict::restartCreateTab_activateComplete(Signal* signal, 
					  Uint32 callbackData,
					  Uint32 returnCode){
  jam();
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));

  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  tabPtr.p->tabState = TableRecord::DEFINED;
  
3205
  releaseCreateTableOp(signal,createTabPtr);
3206 3207 3208 3209 3210

  c_restartRecord.activeTable++;
  checkSchemaStatus(signal);
}

3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
void
Dbdict::releaseCreateTableOp(Signal* signal, CreateTableRecordPtr createTabPtr)
{
  if (createTabPtr.p->m_tabInfoPtrI != RNIL)
  {
    jam();
    SegmentedSectionPtr tabInfoPtr;
    getSection(tabInfoPtr, createTabPtr.p->m_tabInfoPtrI);
    signal->setSection(tabInfoPtr, 0);
    releaseSections(signal);
  }
  c_opCreateTable.release(createTabPtr);
}

3225
void
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
Dbdict::restartDropTab(Signal* signal, Uint32 tableId,
                       const SchemaFile::TableEntry * old_entry, 
                       const SchemaFile::TableEntry * new_entry)
{
  switch(old_entry->m_tableType){
  case DictTabInfo::UndefTableType:
  case DictTabInfo::HashIndexTrigger:
  case DictTabInfo::SubscriptionTrigger:
  case DictTabInfo::ReadOnlyConstraint:
  case DictTabInfo::IndexTrigger:
    ndbrequire(false);
  case DictTabInfo::SystemTable:
  case DictTabInfo::UserTable:
  case DictTabInfo::UniqueHashIndex:
  case DictTabInfo::HashIndex:
  case DictTabInfo::UniqueOrderedIndex:
  case DictTabInfo::OrderedIndex:
    break;
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:
  case DictTabInfo::Datafile:
  case DictTabInfo::Undofile:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3248
    restartDropObj(signal, tableId, old_entry);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3249 3250
    return;
  }
3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283

  const Uint32 key = ++c_opRecordSequence;

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.seize(dropTabPtr));
  
  dropTabPtr.p->key = key;
  c_opDropTable.add(dropTabPtr);
  
  dropTabPtr.p->m_errorCode = 0;
  dropTabPtr.p->m_request.tableId = tableId;
  dropTabPtr.p->m_coordinatorRef = 0;
  dropTabPtr.p->m_requestType = DropTabReq::RestartDropTab;
  dropTabPtr.p->m_participantData.m_gsn = GSN_DROP_TAB_REQ;

  dropTabPtr.p->m_participantData.m_block = 0;
  dropTabPtr.p->m_participantData.m_callback.m_callbackData = key;
  dropTabPtr.p->m_participantData.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartDropTab_complete);
  dropTab_nextStep(signal, dropTabPtr);  
}

void
Dbdict::restartDropTab_complete(Signal* signal, 
				Uint32 callbackData,
				Uint32 returnCode){
  jam();

  DropTableRecordPtr dropTabPtr;
  ndbrequire(c_opDropTable.find(dropTabPtr, callbackData));
  
  //@todo check error

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3284
  releaseTableObject(c_restartRecord.activeTable);
3285 3286 3287 3288 3289 3290
  c_opDropTable.release(dropTabPtr);

  c_restartRecord.activeTable++;
  checkSchemaStatus(signal);
}

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3291 3292 3293
/**
 * Create Obj during NR/SR
 */
3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
void
Dbdict::restartCreateObj(Signal* signal, 
			 Uint32 tableId, 
			 const SchemaFile::TableEntry * old_entry,
			 const SchemaFile::TableEntry * new_entry,
			 bool file){
  jam();
  
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.seize(createObjPtr));
  
  const Uint32 key = ++c_opRecordSequence;
  createObjPtr.p->key = key;
  c_opCreateObj.add(createObjPtr);
  createObjPtr.p->m_errorCode = 0;
  createObjPtr.p->m_senderRef = reference();
  createObjPtr.p->m_senderData = tableId;
  createObjPtr.p->m_clientRef = reference();
  createObjPtr.p->m_clientData = tableId;
  
  createObjPtr.p->m_obj_id = tableId;
  createObjPtr.p->m_obj_type = new_entry->m_tableType;
  createObjPtr.p->m_obj_version = new_entry->m_tableVersion;

  createObjPtr.p->m_callback.m_callbackData = key;
  createObjPtr.p->m_callback.m_callbackFunction= 
    safe_cast(&Dbdict::restartCreateObj_prepare_start_done);
  
  createObjPtr.p->m_restart= file ? 1 : 2;
  switch(new_entry->m_tableType){
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:
    createObjPtr.p->m_vt_index = 0;
    break;
  case DictTabInfo::Datafile:
  case DictTabInfo::Undofile:
    createObjPtr.p->m_vt_index = 1;
    break;
  default:
    ndbrequire(false);
  }
  
  createObjPtr.p->m_obj_info_ptr_i = RNIL;
  if(file)
  {
    c_readTableRecord.no_of_words = old_entry->m_info_words;
    c_readTableRecord.pageId = 0;
    c_readTableRecord.m_callback.m_callbackData = key;
    c_readTableRecord.m_callback.m_callbackFunction = 
      safe_cast(&Dbdict::restartCreateObj_readConf);
    
    startReadTableFile(signal, tableId);
  }
  else
  {
    /**
     * Get from master
     */
    GetTabInfoReq * const req = (GetTabInfoReq *)&signal->theData[0];
    req->senderRef = reference();
    req->senderData = key;
    req->requestType = GetTabInfoReq::RequestById |
      GetTabInfoReq::LongSignalConf;
    req->tableId = tableId;
    sendSignal(calcDictBlockRef(c_masterNodeId), GSN_GET_TABINFOREQ, signal,
	       GetTabInfoReq::SignalLength, JBB);
  }
}
3362

3363 3364
void
Dbdict::restartCreateObj_getTabInfoConf(Signal* signal)
3365
{
3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
  jam();

  GetTabInfoConf * const conf = (GetTabInfoConf*)signal->getDataPtr();

  const Uint32 objId = conf->tableId;
  const Uint32 senderData = conf->senderData;
  
  SegmentedSectionPtr objInfoPtr;
  signal->getSection(objInfoPtr, GetTabInfoConf::DICT_TAB_INFO);
  
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, senderData));
  ndbrequire(createObjPtr.p->m_obj_id == objId);
  
  createObjPtr.p->m_obj_info_ptr_i= objInfoPtr.i;
  signal->header.m_noOfSections = 0;
  
  (this->*f_dict_op[createObjPtr.p->m_vt_index].m_prepare_start)
    (signal, createObjPtr.p);
}

void
Dbdict::restartCreateObj_readConf(Signal* signal,
				  Uint32 callbackData, 
				  Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  ndbrequire(createObjPtr.p->m_errorCode == 0);

  PageRecordPtr pageRecPtr;
  c_pageRecordArray.getPtr(pageRecPtr, c_readTableRecord.pageId);
  
  Uint32 sz = c_readTableRecord.no_of_words;

  Ptr<SectionSegment> ptr;
  ndbrequire(import(ptr, pageRecPtr.p->word+ZPAGE_HEADER_SIZE, sz));
  createObjPtr.p->m_obj_info_ptr_i= ptr.i;  
  
  if (f_dict_op[createObjPtr.p->m_vt_index].m_prepare_start)
    (this->*f_dict_op[createObjPtr.p->m_vt_index].m_prepare_start)
      (signal, createObjPtr.p);
  else
    execute(signal, createObjPtr.p->m_callback, 0);
}

void
Dbdict::restartCreateObj_prepare_start_done(Signal* signal,
					    Uint32 callbackData, 
					    Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  ndbrequire(createObjPtr.p->m_errorCode == 0);

  Callback callback;
  callback.m_callbackData = callbackData;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateObj_write_complete);
  
  SegmentedSectionPtr objInfoPtr;
  getSection(objInfoPtr, createObjPtr.p->m_obj_info_ptr_i);

  writeTableFile(signal, createObjPtr.p->m_obj_id, objInfoPtr, &callback);
}

void
Dbdict::restartCreateObj_write_complete(Signal* signal,
					Uint32 callbackData, 
					Uint32 returnCode)
{
  ndbrequire(returnCode == 0);
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  ndbrequire(createObjPtr.p->m_errorCode == 0);
  
  SegmentedSectionPtr objInfoPtr;
  getSection(objInfoPtr, createObjPtr.p->m_obj_info_ptr_i);
  signal->setSection(objInfoPtr, 0);
  releaseSections(signal);
  createObjPtr.p->m_obj_info_ptr_i = RNIL;
  
  createObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateObj_prepare_complete_done);
  
  if (f_dict_op[createObjPtr.p->m_vt_index].m_prepare_complete)
    (this->*f_dict_op[createObjPtr.p->m_vt_index].m_prepare_complete)
      (signal, createObjPtr.p);
  else
    execute(signal, createObjPtr.p->m_callback, 0);
}

void
Dbdict::restartCreateObj_prepare_complete_done(Signal* signal,
					       Uint32 callbackData, 
					       Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  ndbrequire(createObjPtr.p->m_errorCode == 0);

  createObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateObj_commit_start_done);

  if (f_dict_op[createObjPtr.p->m_vt_index].m_commit_start)
    (this->*f_dict_op[createObjPtr.p->m_vt_index].m_commit_start)
      (signal, createObjPtr.p);
  else
    execute(signal, createObjPtr.p->m_callback, 0);
}

void
Dbdict::restartCreateObj_commit_start_done(Signal* signal,
					   Uint32 callbackData, 
					   Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  ndbrequire(createObjPtr.p->m_errorCode == 0);

  createObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartCreateObj_commit_complete_done);

  if (f_dict_op[createObjPtr.p->m_vt_index].m_commit_complete)
    (this->*f_dict_op[createObjPtr.p->m_vt_index].m_commit_complete)
      (signal, createObjPtr.p);
  else
    execute(signal, createObjPtr.p->m_callback, 0);
}  


void
Dbdict::restartCreateObj_commit_complete_done(Signal* signal,
					      Uint32 callbackData, 
					      Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  ndbrequire(createObjPtr.p->m_errorCode == 0);
  
  c_opCreateObj.release(createObjPtr);

  c_restartRecord.activeTable++;
  checkSchemaStatus(signal);
}

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
/**
 * Drop object during NR/SR
 */
void
Dbdict::restartDropObj(Signal* signal, 
                       Uint32 tableId, 
                       const SchemaFile::TableEntry * entry)
{
  jam();
  
  DropObjRecordPtr dropObjPtr;  
  ndbrequire(c_opDropObj.seize(dropObjPtr));
  
  const Uint32 key = ++c_opRecordSequence;
  dropObjPtr.p->key = key;
  c_opDropObj.add(dropObjPtr);
  dropObjPtr.p->m_errorCode = 0;
  dropObjPtr.p->m_senderRef = reference();
  dropObjPtr.p->m_senderData = tableId;
  dropObjPtr.p->m_clientRef = reference();
  dropObjPtr.p->m_clientData = tableId;
  
  dropObjPtr.p->m_obj_id = tableId;
  dropObjPtr.p->m_obj_type = entry->m_tableType;
  dropObjPtr.p->m_obj_version = entry->m_tableVersion;

  dropObjPtr.p->m_callback.m_callbackData = key;
  dropObjPtr.p->m_callback.m_callbackFunction= 
    safe_cast(&Dbdict::restartDropObj_prepare_start_done);

  ndbout_c("Dropping %d %d", tableId, entry->m_tableType);
  switch(entry->m_tableType){
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:{
    jam();
    Ptr<Filegroup> fg_ptr;
    ndbrequire(c_filegroup_hash.find(fg_ptr, tableId));
    dropObjPtr.p->m_obj_ptr_i = fg_ptr.i;
    dropObjPtr.p->m_vt_index = 3;
    break;
  }
  case DictTabInfo::Datafile:{
    jam();
    Ptr<File> file_ptr;
    dropObjPtr.p->m_vt_index = 2;
    ndbrequire(c_file_hash.find(file_ptr, tableId));
    dropObjPtr.p->m_obj_ptr_i = file_ptr.i;
    break;
  }
  case DictTabInfo::Undofile:{
    jam();    
    Ptr<File> file_ptr;
    dropObjPtr.p->m_vt_index = 4;
    ndbrequire(c_file_hash.find(file_ptr, tableId));
    dropObjPtr.p->m_obj_ptr_i = file_ptr.i;

    /**
     * Undofiles are only removed from logfile groups file list
     *   as drop undofile is currently not supported...
     *   file will be dropped by lgman when dropping filegroup
     */
    dropObjPtr.p->m_callback.m_callbackFunction= 
      safe_cast(&Dbdict::restartDropObj_commit_complete_done);
    
    if (f_dict_op[dropObjPtr.p->m_vt_index].m_commit_complete)
      (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_commit_complete)
        (signal, dropObjPtr.p);
    else
      execute(signal, dropObjPtr.p->m_callback, 0);
    return;
  }
  default:
    jamLine(entry->m_tableType);
    ndbrequire(false);
  }
  
  if (f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_start)
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_start)
      (signal, dropObjPtr.p);
  else
    execute(signal, dropObjPtr.p->m_callback, 0);
}

void
Dbdict::restartDropObj_prepare_start_done(Signal* signal,
                                          Uint32 callbackData, 
                                          Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  DropObjRecordPtr dropObjPtr;  
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  ndbrequire(dropObjPtr.p->m_errorCode == 0);
  
  dropObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartDropObj_prepare_complete_done);
  
  if (f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_complete)
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_complete)
      (signal, dropObjPtr.p);
  else
    execute(signal, dropObjPtr.p->m_callback, 0);
}

void
Dbdict::restartDropObj_prepare_complete_done(Signal* signal,
                                             Uint32 callbackData, 
                                             Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  DropObjRecordPtr dropObjPtr;  
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  ndbrequire(dropObjPtr.p->m_errorCode == 0);
  
  dropObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartDropObj_commit_start_done);
  
  if (f_dict_op[dropObjPtr.p->m_vt_index].m_commit_start)
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_commit_start)
      (signal, dropObjPtr.p);
  else
    execute(signal, dropObjPtr.p->m_callback, 0);
}

void
Dbdict::restartDropObj_commit_start_done(Signal* signal,
                                         Uint32 callbackData, 
                                         Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  DropObjRecordPtr dropObjPtr;  
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  ndbrequire(dropObjPtr.p->m_errorCode == 0);
  
  dropObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::restartDropObj_commit_complete_done);

  if (f_dict_op[dropObjPtr.p->m_vt_index].m_commit_complete)
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_commit_complete)
      (signal, dropObjPtr.p);
  else
    execute(signal, dropObjPtr.p->m_callback, 0);
}  


void
Dbdict::restartDropObj_commit_complete_done(Signal* signal,
                                            Uint32 callbackData, 
                                            Uint32 returnCode)
{
  jam();
  ndbrequire(returnCode == 0);
  DropObjRecordPtr dropObjPtr;  
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  ndbrequire(dropObjPtr.p->m_errorCode == 0);
  
  c_opDropObj.release(dropObjPtr);

  c_restartRecord.activeTable++;
  checkSchemaStatus(signal);
}

3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          NODE FAILURE HANDLING ------------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains the code that is used when nodes            */
/* (kernel/api) fails.                                              */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

/* ---------------------------------------------------------------- */
// We receive a report of an API that failed.
/* ---------------------------------------------------------------- */
void Dbdict::execAPI_FAILREQ(Signal* signal) 
{
  jamEntry();
  Uint32 failedApiNode = signal->theData[0];
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
  BlockReference retRef = signal->theData[1];

#if 0
  Uint32 userNode = refToNode(c_connRecord.userBlockRef);
  if (userNode == failedApiNode) {
    jam();
    c_connRecord.userBlockRef = (Uint32)-1;
  }//if
#endif

  signal->theData[0] = failedApiNode;
  signal->theData[1] = reference();
  sendSignal(retRef, GSN_API_FAILCONF, signal, 2, JBB);
}//execAPI_FAILREQ()

/* ---------------------------------------------------------------- */
// We receive a report of one or more node failures of kernel nodes.
/* ---------------------------------------------------------------- */
void Dbdict::execNODE_FAILREP(Signal* signal) 
{
  jamEntry();
  NodeFailRep * const nodeFail = (NodeFailRep *)&signal->theData[0];

  c_failureNr    = nodeFail->failNo;
  const Uint32 numberOfFailedNodes  = nodeFail->noOfNodes;
  const bool masterFailed = (c_masterNodeId != nodeFail->masterNodeId);
  c_masterNodeId = nodeFail->masterNodeId;

  c_noNodesFailed += numberOfFailedNodes;
  Uint32 theFailedNodes[NodeBitmask::Size];
  memcpy(theFailedNodes, nodeFail->theNodes, sizeof(theFailedNodes));

  c_counterMgr.execNODE_FAILREP(signal);
  
  bool ok = false;
  switch(c_blockState){
  case BS_IDLE:
    jam();
    ok = true;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3742 3743 3744 3745 3746
    if(c_opRecordPool.getSize() != 
       (c_opRecordPool.getNoOfFree() + 
	c_opSubEvent.get_count() + c_opCreateEvent.get_count() +
	c_opDropEvent.get_count() + c_opSignalUtil.get_count()))
    {
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762
      jam();
      c_blockState = BS_NODE_FAILURE;
    }
    break;
  case BS_CREATE_TAB:
    jam();
    ok = true;
    if(!masterFailed)
      break;
    // fall through
  case BS_BUSY:
  case BS_NODE_FAILURE:
    jam();
    c_blockState = BS_NODE_FAILURE;
    ok = true;
    break;
3763 3764 3765 3766
  case BS_NODE_RESTART:
    jam();
    ok = true;
    break;
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788
  }
  ndbrequire(ok);
  
  for(unsigned i = 1; i < MAX_NDB_NODES; i++) {
    jam();
    if(NodeBitmask::get(theFailedNodes, i)) {
      jam();
      NodeRecordPtr nodePtr;
      c_nodes.getPtr(nodePtr, i);

      nodePtr.p->nodeState = NodeRecord::NDB_NODE_DEAD;
      NFCompleteRep * const nfCompRep = (NFCompleteRep *)&signal->theData[0];
      nfCompRep->blockNo      = DBDICT;
      nfCompRep->nodeId       = getOwnNodeId();
      nfCompRep->failedNodeId = nodePtr.i;
      sendSignal(DBDIH_REF, GSN_NF_COMPLETEREP, signal, 
		 NFCompleteRep::SignalLength, JBB);
      
      c_aliveNodes.clear(i);
    }//if
  }//for

3789 3790 3791 3792 3793 3794 3795 3796 3797
  /*
   * NODE_FAILREP guarantees that no "in flight" signal from
   * a dead node is accepted, and also that the job buffer contains
   * no such (un-executed) signals.  Therefore no DICT_UNLOCK_ORD
   * from a dead node (leading to master crash) is possible after
   * this clean-up removes the lock record.
   */
  removeStaleDictLocks(signal, theFailedNodes);

3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
}//execNODE_FAILREP()


/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          NODE START HANDLING --------------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains the code that is used when kernel nodes     */
/* starts.                                                          */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

/* ---------------------------------------------------------------- */
// Include a starting node in list of nodes to be part of adding
// and dropping tables.
/* ---------------------------------------------------------------- */
void Dbdict::execINCL_NODEREQ(Signal* signal) 
{
  jamEntry();
  NodeRecordPtr nodePtr;
  BlockReference retRef = signal->theData[0];
  nodePtr.i = signal->theData[1];

  ndbrequire(c_noNodesFailed > 0);
  c_noNodesFailed--;

  c_nodes.getPtr(nodePtr);
3826
  ndbrequire(nodePtr.p->nodeState == NodeRecord::NDB_NODE_DEAD);
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
  nodePtr.p->nodeState = NodeRecord::NDB_NODE_ALIVE;
  signal->theData[0] = reference();
  sendSignal(retRef, GSN_INCL_NODECONF, signal, 1, JBB);

  c_aliveNodes.set(nodePtr.i);
}//execINCL_NODEREQ()

/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          ADD TABLE HANDLING ---------------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains the code that is used when adding a table.  */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

/* ---------------------------------------------------------------- */
// This signal receives information about a table from either:
// API, Ndbcntr or from other DICT.
/* ---------------------------------------------------------------- */
void
Dbdict::execCREATE_TABLE_REQ(Signal* signal){
  jamEntry();
  if(!assembleFragments(signal)){
    return;
  }
  
  CreateTableReq* const req = (CreateTableReq*)signal->getDataPtr();
  const Uint32 senderRef = req->senderRef;
  const Uint32 senderData = req->senderData;
  
  ParseDictTabInfoRecord parseRecord;
  do {
    if(getOwnNodeId() != c_masterNodeId){
      jam();
      parseRecord.errorCode = CreateTableRef::NotMaster;
      break;
    }
    
3866 3867 3868 3869 3870 3871
    if (c_blockState == BS_NODE_RESTART){
      jam();
      parseRecord.errorCode = CreateTableRef::BusyWithNR;
      break;
    }
    
3872 3873 3874 3875 3876 3877
    if (c_blockState != BS_IDLE){
      jam();
      parseRecord.errorCode = CreateTableRef::Busy;
      break;
    }

3878
    if (checkSingleUserMode(signal->getSendersBlockRef()))
3879 3880 3881 3882 3883 3884
    {
      jam();
      parseRecord.errorCode = CreateTableRef::SingleUser;
      break;
    }

3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
    CreateTableRecordPtr createTabPtr;
    c_opCreateTable.seize(createTabPtr);
    
    if(createTabPtr.isNull()){
      jam();
      parseRecord.errorCode = CreateTableRef::Busy;
      break;
    }
    
    parseRecord.requestType = DictTabInfo::CreateTableFromAPI;
    parseRecord.errorCode = 0;
    
    SegmentedSectionPtr ptr;
    signal->getSection(ptr, CreateTableReq::DICT_TAB_INFO);
    SimplePropertiesSectionReader r(ptr, getSectionSegmentPool());
    
    handleTabInfoInit(r, &parseRecord);
    releaseSections(signal);
    
    if(parseRecord.errorCode != 0){
      jam();
      c_opCreateTable.release(createTabPtr);
      break;
    }
    
    createTabPtr.p->m_errorCode = 0;
    createTabPtr.p->m_senderRef = senderRef;
    createTabPtr.p->m_senderData = senderData;
    createTabPtr.p->m_tablePtrI = parseRecord.tablePtr.i;
    createTabPtr.p->m_coordinatorRef = reference();
    createTabPtr.p->m_fragmentsPtrI = RNIL;
    createTabPtr.p->m_dihAddFragPtr = RNIL;

3918
    Uint32 key = c_opRecordSequence + 1;
3919
    Uint32 *theData = signal->getDataPtrSend();
3920
    Uint16 *frag_data= (Uint16*)&signal->theData[25];
3921 3922
    CreateFragmentationReq * const req = (CreateFragmentationReq*)theData;
    req->senderRef = reference();
3923
    req->senderData = key;
3924
    req->primaryTableId = parseRecord.tablePtr.p->primaryTableId;
3925
    req->noOfFragments = parseRecord.tablePtr.p->fragmentCount;
3926
    req->fragmentationType = parseRecord.tablePtr.p->fragmentType;
3927 3928
    MEMCOPY_NO_WORDS(frag_data, c_fragData, c_fragDataLen);

3929
    if (parseRecord.tablePtr.p->isOrderedIndex()) {
3930
      jam();
3931
      // ordered index has same fragmentation as the table
3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
      req->primaryTableId = parseRecord.tablePtr.p->primaryTableId;
      req->fragmentationType = DictTabInfo::DistrKeyOrderedIndex;
    }
    else if (parseRecord.tablePtr.p->isHashIndex())
    {
      jam();
      /*
        Unique hash indexes has same amount of fragments as primary table
        and distributed in the same manner but has always a normal hash
        fragmentation.
      */
      req->primaryTableId = parseRecord.tablePtr.p->primaryTableId;
      req->fragmentationType = DictTabInfo::DistrKeyUniqueHashIndex;
    }
    else
    {
      jam();
      /*
        Blob tables come here with primaryTableId != RNIL but we only need
        it for creating the fragments so we set it to RNIL now that we got
        what we wanted from it to avoid other side effects.
      */
      parseRecord.tablePtr.p->primaryTableId = RNIL;
    }
    EXECUTE_DIRECT(DBDIH, GSN_CREATE_FRAGMENTATION_REQ, signal,
		   CreateFragmentationReq::SignalLength);
    jamEntry();
    if (signal->theData[0] != 0)
    {
      jam();
      parseRecord.errorCode= signal->theData[0];
3963 3964
      c_opCreateTable.release(createTabPtr);
      releaseTableObject(parseRecord.tablePtr.i, true);
3965 3966
      break;
    }
3967 3968 3969
    createTabPtr.p->key = key;
    c_opRecordSequence++;
    c_opCreateTable.add(createTabPtr);
3970 3971 3972 3973 3974 3975 3976 3977
    c_blockState = BS_CREATE_TAB;
    return;
  } while(0);
  
  /**
   * Something went wrong
   */

3978
  releaseSections(signal);
3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990
  CreateTableRef * ref = (CreateTableRef*)signal->getDataPtrSend();
  ref->senderData = senderData;
  ref->senderRef = reference();
  ref->masterNodeId = c_masterNodeId;
  ref->errorCode = parseRecord.errorCode;
  ref->errorLine = parseRecord.errorLine;
  ref->errorKey = parseRecord.errorKey;
  ref->status = parseRecord.status;
  sendSignal(senderRef, GSN_CREATE_TABLE_REF, signal, 
	     CreateTableRef::SignalLength, JBB);
}

joreland@mysql.com's avatar
joreland@mysql.com committed
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005
void
Dbdict::execBACKUP_FRAGMENT_REQ(Signal* signal)
{
  jamEntry();
  Uint32 tableId = signal->theData[0];
  Uint32 lock = signal->theData[1];

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId, true);

  if(lock)
  {
    ndbrequire(tablePtr.p->tabState == TableRecord::DEFINED);
    tablePtr.p->tabState = TableRecord::BACKUP_ONGOING;
  }
4006
  else if(tablePtr.p->tabState == TableRecord::BACKUP_ONGOING)
joreland@mysql.com's avatar
joreland@mysql.com committed
4007 4008 4009 4010 4011
  {
    tablePtr.p->tabState = TableRecord::DEFINED;
  }
}

4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
bool
Dbdict::check_ndb_versions() const
{
  Uint32 node = 0;
  Uint32 version = getNodeInfo(getOwnNodeId()).m_version;
  while((node = c_aliveNodes.find(node + 1)) != BitmaskImpl::NotFound)
  {
    if(getNodeInfo(node).m_version != version)
    {
      return false;
    }
  }
  return true;
}

4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057
void
Dbdict::execALTER_TABLE_REQ(Signal* signal)
{
  // Received by master
  jamEntry();
  if(!assembleFragments(signal)){
    return;
  }
  AlterTableReq* const req = (AlterTableReq*)signal->getDataPtr();
  const Uint32 senderRef = req->senderRef;
  const Uint32 senderData = req->senderData;
  const Uint32 changeMask = req->changeMask;
  const Uint32 tableId = req->tableId;
  const Uint32 tableVersion = req->tableVersion;
  ParseDictTabInfoRecord* aParseRecord;
  
  // Get table definition
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId, false);
  if(tablePtr.isNull()){
    jam();
    alterTableRef(signal, req, AlterTableRef::NoSuchTable);
    return;
  }
  
  if(getOwnNodeId() != c_masterNodeId){
    jam();
    alterTableRef(signal, req, AlterTableRef::NotMaster);
    return;
  }
  
4058 4059 4060 4061 4062 4063
  if(c_blockState == BS_NODE_RESTART){
    jam();
    alterTableRef(signal, req, AlterTableRef::BusyWithNR);
    return;
  }
  
4064 4065 4066 4067 4068
  if(c_blockState != BS_IDLE){
    jam();
    alterTableRef(signal, req, AlterTableRef::Busy);
    return;
  }
4069 4070 4071 4072 4073 4074 4075

  if (!check_ndb_versions())
  {
    jam();
    alterTableRef(signal, req, AlterTableRef::IncompatibleVersions);
    return;
  }
4076
  
4077
  if (checkSingleUserMode(signal->getSendersBlockRef()))
4078 4079 4080 4081 4082 4083
  {
    jam();
    alterTableRef(signal, req, AlterTableRef::SingleUser);
    return;
  }

4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
  const TableRecord::TabState tabState = tablePtr.p->tabState;
  bool ok = false;
  switch(tabState){
  case TableRecord::NOT_DEFINED:
  case TableRecord::REORG_TABLE_PREPARED:
  case TableRecord::DEFINING:
  case TableRecord::CHECKED:
    jam();
    alterTableRef(signal, req, AlterTableRef::NoSuchTable);
    return;
  case TableRecord::DEFINED:
    ok = true;
    jam();
    break;
joreland@mysql.com's avatar
joreland@mysql.com committed
4098 4099 4100 4101
  case TableRecord::BACKUP_ONGOING:
    jam();
    alterTableRef(signal, req, AlterTableRef::BackupInProgress);
    return;
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
  case TableRecord::PREPARE_DROPPING:
  case TableRecord::DROPPING:
    jam();
    alterTableRef(signal, req, AlterTableRef::DropInProgress);
    return;
  }
  ndbrequire(ok);

  if(tablePtr.p->tableVersion != tableVersion){
    jam();
    alterTableRef(signal, req, AlterTableRef::InvalidTableVersion);
    return;
  }
  // Parse new table defintion
  ParseDictTabInfoRecord parseRecord;
  aParseRecord = &parseRecord;
    
  CreateTableRecordPtr alterTabPtr; // Reuse create table records
  c_opCreateTable.seize(alterTabPtr);
  
  if(alterTabPtr.isNull()){
    jam();
    alterTableRef(signal, req, AlterTableRef::Busy);
    return;
  }

joreland@mysql.com's avatar
joreland@mysql.com committed
4128
  alterTabPtr.p->m_changeMask = changeMask;
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
  parseRecord.requestType = DictTabInfo::AlterTableFromAPI;
  parseRecord.errorCode = 0;
  
  SegmentedSectionPtr ptr;
  signal->getSection(ptr, AlterTableReq::DICT_TAB_INFO);
  SimplePropertiesSectionReader r(ptr, getSectionSegmentPool());

  handleTabInfoInit(r, &parseRecord, false); // Will not save info
  
  if(parseRecord.errorCode != 0){
    jam();
    c_opCreateTable.release(alterTabPtr);
    alterTableRef(signal, req, 
		  (AlterTableRef::ErrorCode) parseRecord.errorCode, 
		  aParseRecord);
    return;
  }
  
  releaseSections(signal);
joreland@mysql.com's avatar
joreland@mysql.com committed
4148
  alterTabPtr.p->key = ++c_opRecordSequence;
4149
  c_opCreateTable.add(alterTabPtr);
joreland@mysql.com's avatar
joreland@mysql.com committed
4150 4151 4152 4153 4154 4155 4156 4157 4158
  ndbrequire(c_opCreateTable.find(alterTabPtr, alterTabPtr.p->key));
  alterTabPtr.p->m_errorCode = 0;
  alterTabPtr.p->m_senderRef = senderRef;
  alterTabPtr.p->m_senderData = senderData;
  alterTabPtr.p->m_tablePtrI = parseRecord.tablePtr.i;
  alterTabPtr.p->m_alterTableFailed = false;
  alterTabPtr.p->m_coordinatorRef = reference();
  alterTabPtr.p->m_fragmentsPtrI = RNIL;
  alterTabPtr.p->m_dihAddFragPtr = RNIL;
4159
  alterTabPtr.p->m_alterTableId = tablePtr.p->tableId;
4160 4161 4162

  // Send prepare request to all alive nodes
  SimplePropertiesSectionWriter w(getSectionSegmentPool());
4163
  packTableIntoPages(w, parseRecord.tablePtr);
4164 4165 4166
  
  SegmentedSectionPtr tabInfoPtr;
  w.getPtr(tabInfoPtr);
joreland@mysql.com's avatar
joreland@mysql.com committed
4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
  
  alterTabPtr.p->m_tabInfoPtrI = tabInfoPtr.i;

  // Alter table on all nodes
  c_blockState = BS_BUSY;

  Mutex mutex(signal, c_mutexMgr, alterTabPtr.p->m_startLcpMutex);
  Callback c = { safe_cast(&Dbdict::alterTable_backup_mutex_locked),
		 alterTabPtr.p->key };
  
  ndbrequire(mutex.lock(c));
}

void
Dbdict::alterTable_backup_mutex_locked(Signal* signal,
				       Uint32 callbackData,
				       Uint32 retValue)
{
  jamEntry();
  
  ndbrequire(retValue == 0);
  
  CreateTableRecordPtr alterTabPtr;
  ndbrequire(c_opCreateTable.find(alterTabPtr, callbackData));

  TableRecordPtr tablePtr;
4193
  c_tableRecordPool.getPtr(tablePtr, alterTabPtr.p->m_alterTableId, true);
joreland@mysql.com's avatar
joreland@mysql.com committed
4194 4195 4196 4197 4198 4199

  Mutex mutex(signal, c_mutexMgr, alterTabPtr.p->m_startLcpMutex);
  mutex.unlock(); // ignore response

  SegmentedSectionPtr tabInfoPtr;
  getSection(tabInfoPtr, alterTabPtr.p->m_tabInfoPtrI);
4200 4201
  signal->setSection(tabInfoPtr, AlterTabReq::DICT_TAB_INFO);
  
joreland@mysql.com's avatar
joreland@mysql.com committed
4202 4203 4204 4205 4206 4207 4208 4209 4210
  alterTabPtr.p->m_tabInfoPtrI = RNIL;
  
  if(tablePtr.p->tabState == TableRecord::BACKUP_ONGOING)
  {
    jam();
    AlterTableReq* req = (AlterTableReq*)signal->getDataPtr();
    req->senderData = alterTabPtr.p->m_senderData;
    req->senderRef = alterTabPtr.p->m_senderRef;
    alterTableRef(signal, req, AlterTableRef::BackupInProgress);
4211 4212 4213 4214

    c_tableRecordPool.getPtr(tablePtr, alterTabPtr.p->m_tablePtrI);  
    releaseTableObject(tablePtr.i, false);

joreland@mysql.com's avatar
joreland@mysql.com committed
4215 4216 4217 4218 4219
    c_opCreateTable.release(alterTabPtr);
    c_blockState = BS_IDLE;
    return;
  }
  
4220
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
joreland@mysql.com's avatar
joreland@mysql.com committed
4221 4222 4223 4224
  alterTabPtr.p->m_coordinatorData.m_gsn = GSN_ALTER_TAB_REQ;
  SafeCounter safeCounter(c_counterMgr, 
			  alterTabPtr.p->m_coordinatorData.m_counter);
  safeCounter.init<AlterTabRef>(rg, alterTabPtr.p->key);
4225 4226 4227

  AlterTabReq * const lreq = (AlterTabReq*)signal->getDataPtrSend();
  lreq->senderRef = reference();
joreland@mysql.com's avatar
joreland@mysql.com committed
4228 4229 4230 4231 4232
  lreq->senderData = alterTabPtr.p->key;
  lreq->clientRef = alterTabPtr.p->m_senderRef;
  lreq->clientData = alterTabPtr.p->m_senderData;
  lreq->changeMask = alterTabPtr.p->m_changeMask;
  lreq->tableId = tablePtr.p->tableId;
4233
  lreq->tableVersion = alter_obj_inc_schema_version(tablePtr.p->tableVersion);
4234 4235 4236
  lreq->gci = tablePtr.p->gciTableCreated;
  lreq->requestType = AlterTabReq::AlterTablePrepare;
  
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
4237 4238
  sendFragmentedSignal(rg, GSN_ALTER_TAB_REQ, signal, 
		       AlterTabReq::SignalLength, JBB);
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312
}

void Dbdict::alterTableRef(Signal * signal, 
			   AlterTableReq * req, 
			   AlterTableRef::ErrorCode errCode,
			   ParseDictTabInfoRecord* parseRecord)
{
  jam();
  releaseSections(signal);
  AlterTableRef * ref = (AlterTableRef*)signal->getDataPtrSend();
  Uint32 senderRef = req->senderRef;
  ref->senderData = req->senderData;
  ref->senderRef = reference();
  ref->masterNodeId = c_masterNodeId;
  if (parseRecord) {
    ref->errorCode = parseRecord->errorCode;
    ref->errorLine = parseRecord->errorLine;
    ref->errorKey = parseRecord->errorKey;
    ref->status = parseRecord->status;
  }
  else {
    ref->errorCode = errCode;
    ref->errorLine = 0;
    ref->errorKey = 0;
    ref->status = 0;
  }
  sendSignal(senderRef, GSN_ALTER_TABLE_REF, signal, 
	     AlterTableRef::SignalLength, JBB);
}

void
Dbdict::execALTER_TAB_REQ(Signal * signal) 
{
  // Received in all nodes to handle change locally
  jamEntry();

  if(!assembleFragments(signal)){
    return;
  }
  AlterTabReq* const req = (AlterTabReq*)signal->getDataPtr();
  const Uint32 senderRef = req->senderRef;
  const Uint32 senderData = req->senderData;
  const Uint32 changeMask = req->changeMask;
  const Uint32 tableId = req->tableId;
  const Uint32 tableVersion = req->tableVersion;
  const Uint32 gci = req->gci;
  AlterTabReq::RequestType requestType = 
    (AlterTabReq::RequestType) req->requestType;

  SegmentedSectionPtr tabInfoPtr;
  signal->getSection(tabInfoPtr, AlterTabReq::DICT_TAB_INFO);

  CreateTableRecordPtr alterTabPtr; // Reuse create table records

  if (senderRef != reference()) {
    jam();
    c_blockState = BS_BUSY;
  }
  if ((requestType == AlterTabReq::AlterTablePrepare)
      && (senderRef != reference())) {
    jam();
    c_opCreateTable.seize(alterTabPtr);
    if(!alterTabPtr.isNull())
      alterTabPtr.p->m_changeMask = changeMask;
  }
  else {
    jam();
    ndbrequire(c_opCreateTable.find(alterTabPtr, senderData));
  }
  if(alterTabPtr.isNull()){
    jam();
    alterTabRef(signal, req, AlterTableRef::Busy);
    return;
  }
4313 4314 4315 4316 4317 4318 4319 4320

  if (!check_ndb_versions())
  {
    jam();
    alterTabRef(signal, req, AlterTableRef::IncompatibleVersions);
    return;
  }

joreland@mysql.com's avatar
joreland@mysql.com committed
4321 4322
  alterTabPtr.p->m_alterTableId = tableId;
  alterTabPtr.p->m_coordinatorRef = senderRef;
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
  
  // Get table definition
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId, false);
  if(tablePtr.isNull()){
    jam();
    alterTabRef(signal, req, AlterTableRef::NoSuchTable);
    return;
  }
    
  switch(requestType) {
  case(AlterTabReq::AlterTablePrepare): {
    ParseDictTabInfoRecord* aParseRecord;
  
    const TableRecord::TabState tabState = tablePtr.p->tabState;
    bool ok = false;
    switch(tabState){
    case TableRecord::NOT_DEFINED:
    case TableRecord::REORG_TABLE_PREPARED:
    case TableRecord::DEFINING:
    case TableRecord::CHECKED:
      jam();
      alterTabRef(signal, req, AlterTableRef::NoSuchTable);
      return;
    case TableRecord::DEFINED:
      ok = true;
      jam();
      break;
    case TableRecord::PREPARE_DROPPING:
    case TableRecord::DROPPING:
      jam();
      alterTabRef(signal, req, AlterTableRef::DropInProgress);
      return;
joreland@mysql.com's avatar
joreland@mysql.com committed
4356 4357 4358 4359
    case TableRecord::BACKUP_ONGOING:
      jam();
      alterTabRef(signal, req, AlterTableRef::BackupInProgress);
      return;
4360 4361 4362
    }
    ndbrequire(ok);

4363
    if(alter_obj_inc_schema_version(tablePtr.p->tableVersion) != tableVersion){
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389
      jam();
      alterTabRef(signal, req, AlterTableRef::InvalidTableVersion);
      return;
    }
    TableRecordPtr newTablePtr;
    if (senderRef  != reference()) {
      jam();
      // Parse altered table defintion
      ParseDictTabInfoRecord parseRecord;
      aParseRecord = &parseRecord;
      
      parseRecord.requestType = DictTabInfo::AlterTableFromAPI;
      parseRecord.errorCode = 0;
      
      SimplePropertiesSectionReader r(tabInfoPtr, getSectionSegmentPool());
      
      handleTabInfoInit(r, &parseRecord, false); // Will not save info
      
      if(parseRecord.errorCode != 0){
	jam();
	c_opCreateTable.release(alterTabPtr);
	alterTabRef(signal, req, 
		    (AlterTableRef::ErrorCode) parseRecord.errorCode, 
		    aParseRecord);
	return;
      }
joreland@mysql.com's avatar
joreland@mysql.com committed
4390
      alterTabPtr.p->key = senderData;
4391
      c_opCreateTable.add(alterTabPtr);
joreland@mysql.com's avatar
joreland@mysql.com committed
4392 4393 4394 4395 4396 4397
      alterTabPtr.p->m_errorCode = 0;
      alterTabPtr.p->m_senderRef = senderRef;
      alterTabPtr.p->m_senderData = senderData;
      alterTabPtr.p->m_tablePtrI = parseRecord.tablePtr.i;
      alterTabPtr.p->m_fragmentsPtrI = RNIL;
      alterTabPtr.p->m_dihAddFragPtr = RNIL;
4398 4399 4400 4401 4402
      newTablePtr = parseRecord.tablePtr;
      newTablePtr.p->tableVersion = tableVersion;
    }
    else { // (req->senderRef  == reference())
      jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
4403
      c_tableRecordPool.getPtr(newTablePtr, alterTabPtr.p->m_tablePtrI);
4404 4405
      newTablePtr.p->tableVersion = tableVersion;
    }
joreland@mysql.com's avatar
joreland@mysql.com committed
4406
    if (handleAlterTab(req, alterTabPtr.p, tablePtr, newTablePtr) == -1) {
4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430
      jam();
      c_opCreateTable.release(alterTabPtr);
      alterTabRef(signal, req, AlterTableRef::UnsupportedChange);
      return;
    }
    releaseSections(signal);
    // Propagate alter table to other local blocks
    AlterTabReq * req = (AlterTabReq*)signal->getDataPtrSend();
    req->senderRef = reference();
    req->senderData = senderData;
    req->changeMask = changeMask;
    req->tableId = tableId;
    req->tableVersion = tableVersion;
    req->gci = gci;
    req->requestType = requestType;
    sendSignal(DBLQH_REF, GSN_ALTER_TAB_REQ, signal, 
	       AlterTabReq::SignalLength, JBB);	
    return;
  }
  case(AlterTabReq::AlterTableCommit): {
    jam();
    // Write schema for altered table to disk
    SegmentedSectionPtr tabInfoPtr;
    signal->getSection(tabInfoPtr, AlterTabReq::DICT_TAB_INFO);
joreland@mysql.com's avatar
joreland@mysql.com committed
4431
    alterTabPtr.p->m_tabInfoPtrI = tabInfoPtr.i;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
4432
    bool savetodisk = !(tablePtr.p->m_bits & TableRecord::TR_Temporary);
4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
    
    signal->header.m_noOfSections = 0;

    // Update table record
    tablePtr.p->packedSize = tabInfoPtr.sz;
    tablePtr.p->tableVersion = tableVersion;
    tablePtr.p->gciTableCreated = gci;

    SchemaFile::TableEntry tabEntry;
    tabEntry.m_tableVersion = tableVersion;
    tabEntry.m_tableType    = tablePtr.p->tableType;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
4444 4445 4446 4447
    if (savetodisk)
      tabEntry.m_tableState   = SchemaFile::ALTER_TABLE_COMMITTED;
    else
      tabEntry.m_tableState   = SchemaFile::TEMPORARY_TABLE_COMMITTED;
4448
    tabEntry.m_gcp          = gci;
4449
    tabEntry.m_info_words   = tabInfoPtr.sz;
4450
    memset(tabEntry.m_unused, 0, sizeof(tabEntry.m_unused));
4451 4452 4453 4454 4455 4456
    
    Callback callback;
    callback.m_callbackData = senderData;
    callback.m_callbackFunction = 
      safe_cast(&Dbdict::alterTab_writeSchemaConf);
    
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
4457
    updateSchemaState(signal, tableId, &tabEntry, &callback, savetodisk);
4458 4459 4460 4461 4462
    break;
  }
  case(AlterTabReq::AlterTableRevert): {
    jam();
    // Revert failed alter table
joreland@mysql.com's avatar
joreland@mysql.com committed
4463
    revertAlterTable(signal, changeMask, tableId, alterTabPtr.p);
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526
    // Acknowledge the reverted alter table
    AlterTabConf * conf = (AlterTabConf*)signal->getDataPtrSend();
    conf->senderRef = reference();
    conf->senderData = senderData;
    conf->changeMask = changeMask;
    conf->tableId = tableId;
    conf->tableVersion = tableVersion;
    conf->gci = gci;
    conf->requestType = requestType;
    sendSignal(senderRef, GSN_ALTER_TAB_CONF, signal, 
	       AlterTabConf::SignalLength, JBB);
    break;
  }
  default: ndbrequire(false);
  }
}

void Dbdict::alterTabRef(Signal * signal, 
			 AlterTabReq * req, 
			 AlterTableRef::ErrorCode errCode,
			 ParseDictTabInfoRecord* parseRecord)
{
  jam();
  releaseSections(signal);
  AlterTabRef * ref = (AlterTabRef*)signal->getDataPtrSend();
  Uint32 senderRef = req->senderRef;
  ref->senderData = req->senderData;
  ref->senderRef = reference();
  if (parseRecord) {
    jam();
    ref->errorCode = parseRecord->errorCode;
    ref->errorLine = parseRecord->errorLine;
    ref->errorKey = parseRecord->errorKey;
    ref->errorStatus = parseRecord->status;
  }
  else {
    jam();
    ref->errorCode = errCode;
    ref->errorLine = 0;
    ref->errorKey = 0;
    ref->errorStatus = 0;
  }
  sendSignal(senderRef, GSN_ALTER_TAB_REF, signal, 
	     AlterTabRef::SignalLength, JBB);
  
  c_blockState = BS_IDLE;
}

void Dbdict::execALTER_TAB_REF(Signal * signal){
  jamEntry();

  AlterTabRef * ref = (AlterTabRef*)signal->getDataPtr();

  Uint32 senderRef = ref->senderRef;
  Uint32 senderData = ref->senderData;
  Uint32 errorCode = ref->errorCode;
  Uint32 errorLine = ref->errorLine;
  Uint32 errorKey = ref->errorKey;
  Uint32 errorStatus = ref->errorStatus;
  AlterTabReq::RequestType requestType = 
    (AlterTabReq::RequestType) ref->requestType;
  CreateTableRecordPtr alterTabPtr;  
  ndbrequire(c_opCreateTable.find(alterTabPtr, senderData));
joreland@mysql.com's avatar
joreland@mysql.com committed
4527 4528
  Uint32 changeMask = alterTabPtr.p->m_changeMask;
  SafeCounter safeCounter(c_counterMgr, alterTabPtr.p->m_coordinatorData.m_counter);
4529 4530 4531 4532 4533 4534 4535
  safeCounter.clearWaitingFor(refToNode(senderRef));
  switch (requestType) {
  case(AlterTabReq::AlterTablePrepare): {
    if (safeCounter.done()) {
      jam();
      // Send revert request to all alive nodes
      TableRecordPtr tablePtr;
joreland@mysql.com's avatar
joreland@mysql.com committed
4536
      c_tableRecordPool.getPtr(tablePtr, alterTabPtr.p->m_alterTableId);
4537 4538 4539 4540
      Uint32 tableId = tablePtr.p->tableId;
      Uint32 tableVersion = tablePtr.p->tableVersion;
      Uint32 gci = tablePtr.p->gciTableCreated;
      SimplePropertiesSectionWriter w(getSectionSegmentPool());
4541
      packTableIntoPages(w, tablePtr);
4542 4543 4544 4545 4546
      SegmentedSectionPtr spDataPtr;
      w.getPtr(spDataPtr);
      signal->setSection(spDataPtr, AlterTabReq::DICT_TAB_INFO);
      
      NodeReceiverGroup rg(DBDICT, c_aliveNodes);
joreland@mysql.com's avatar
joreland@mysql.com committed
4547 4548
      alterTabPtr.p->m_coordinatorData.m_gsn = GSN_ALTER_TAB_REQ;
      safeCounter.init<AlterTabRef>(rg, alterTabPtr.p->key);
4549 4550 4551
  
      AlterTabReq * const lreq = (AlterTabReq*)signal->getDataPtrSend();
      lreq->senderRef = reference();
joreland@mysql.com's avatar
joreland@mysql.com committed
4552 4553 4554
      lreq->senderData = alterTabPtr.p->key;
      lreq->clientRef = alterTabPtr.p->m_senderRef;
      lreq->clientData = alterTabPtr.p->m_senderData;
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565
      lreq->changeMask = changeMask;
      lreq->tableId = tableId;
      lreq->tableVersion = tableVersion;
      lreq->gci = gci;
      lreq->requestType = AlterTabReq::AlterTableRevert;
      
      sendSignal(rg, GSN_ALTER_TAB_REQ, signal, 
		 AlterTabReq::SignalLength, JBB);
    }
    else {
      jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
4566
      alterTabPtr.p->m_alterTableFailed = true;
4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589
    }
    break;
  }
  case(AlterTabReq::AlterTableCommit):
    jam();
  case(AlterTabReq::AlterTableRevert): {
    AlterTableRef * apiRef = (AlterTableRef*)signal->getDataPtrSend();
    
    apiRef->senderData = senderData;
    apiRef->senderRef = reference();
    apiRef->masterNodeId = c_masterNodeId;
    apiRef->errorCode = errorCode;
    apiRef->errorLine = errorLine;
    apiRef->errorKey = errorKey;
    apiRef->status = errorStatus;
    if (safeCounter.done()) {
      jam();
      sendSignal(senderRef, GSN_ALTER_TABLE_REF, signal, 
		 AlterTableRef::SignalLength, JBB);
      c_blockState = BS_IDLE;
    }
    else {
      jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
4590 4591
      alterTabPtr.p->m_alterTableFailed = true;
      alterTabPtr.p->m_alterTableRef = *apiRef;
4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655
    }
    break;
  } 
  default: ndbrequire(false);
  }
}

void
Dbdict::execALTER_TAB_CONF(Signal * signal){
  jamEntry();
  AlterTabConf * const conf = (AlterTabConf*)signal->getDataPtr();
  Uint32 senderRef = conf->senderRef;
  Uint32 senderData = conf->senderData;
  Uint32 changeMask = conf->changeMask;
  Uint32 tableId = conf->tableId;
  Uint32 tableVersion = conf->tableVersion;
  Uint32 gci = conf->gci;
  AlterTabReq::RequestType requestType = 
    (AlterTabReq::RequestType) conf->requestType;
  CreateTableRecordPtr alterTabPtr;  
  ndbrequire(c_opCreateTable.find(alterTabPtr, senderData));

  switch (requestType) {
  case(AlterTabReq::AlterTablePrepare): {
    switch(refToBlock(signal->getSendersBlockRef())) {
    case DBLQH: {
      jam();
      AlterTabReq * req = (AlterTabReq*)signal->getDataPtrSend();
      req->senderRef = reference();
      req->senderData = senderData;
      req->changeMask = changeMask;
      req->tableId = tableId;
      req->tableVersion = tableVersion;
      req->gci = gci;
      req->requestType = requestType;
      sendSignal(DBDIH_REF, GSN_ALTER_TAB_REQ, signal, 
		 AlterTabReq::SignalLength, JBB);	
      return;
    }
    case DBDIH: {
      jam();
      AlterTabReq * req = (AlterTabReq*)signal->getDataPtrSend();
      req->senderRef = reference();
      req->senderData = senderData;
      req->changeMask = changeMask;
      req->tableId = tableId;
      req->tableVersion = tableVersion;
      req->gci = gci;
      req->requestType = requestType;
      sendSignal(DBTC_REF, GSN_ALTER_TAB_REQ, signal, 
		 AlterTabReq::SignalLength, JBB);	
      return;
    }
    case DBTC: {
      jam();
      // Participant is done with prepare phase, send conf to coordinator
      AlterTabConf * conf = (AlterTabConf*)signal->getDataPtrSend();
      conf->senderRef = reference();
      conf->senderData = senderData;
      conf->changeMask = changeMask;
      conf->tableId = tableId;
      conf->tableVersion = tableVersion;
      conf->gci = gci;
      conf->requestType = requestType;
joreland@mysql.com's avatar
joreland@mysql.com committed
4656
      sendSignal(alterTabPtr.p->m_coordinatorRef, GSN_ALTER_TAB_CONF, signal, 
4657 4658 4659 4660 4661 4662
		 AlterTabConf::SignalLength, JBB);
      return;
    }
    default :break;
    }
    // Coordinator only
joreland@mysql.com's avatar
joreland@mysql.com committed
4663
    SafeCounter safeCounter(c_counterMgr, alterTabPtr.p->m_coordinatorData.m_counter);
4664 4665 4666 4667
    safeCounter.clearWaitingFor(refToNode(senderRef));
    if (safeCounter.done()) {
      jam();
      // We have received all local confirmations
joreland@mysql.com's avatar
joreland@mysql.com committed
4668
      if (alterTabPtr.p->m_alterTableFailed) {
4669 4670 4671
	jam();
	// Send revert request to all alive nodes
	TableRecordPtr tablePtr;
joreland@mysql.com's avatar
joreland@mysql.com committed
4672
	c_tableRecordPool.getPtr(tablePtr, alterTabPtr.p->m_alterTableId);
4673 4674 4675 4676
	Uint32 tableId = tablePtr.p->tableId;
	Uint32 tableVersion = tablePtr.p->tableVersion;
	Uint32 gci = tablePtr.p->gciTableCreated;
	SimplePropertiesSectionWriter w(getSectionSegmentPool());
4677
	packTableIntoPages(w, tablePtr);
4678 4679 4680 4681 4682
	SegmentedSectionPtr spDataPtr;
	w.getPtr(spDataPtr);
	signal->setSection(spDataPtr, AlterTabReq::DICT_TAB_INFO);
	
	NodeReceiverGroup rg(DBDICT, c_aliveNodes);
joreland@mysql.com's avatar
joreland@mysql.com committed
4683 4684
	alterTabPtr.p->m_coordinatorData.m_gsn = GSN_ALTER_TAB_REQ;
	safeCounter.init<AlterTabRef>(rg, alterTabPtr.p->key);
4685 4686 4687
	
	AlterTabReq * const lreq = (AlterTabReq*)signal->getDataPtrSend();
	lreq->senderRef = reference();
joreland@mysql.com's avatar
joreland@mysql.com committed
4688 4689 4690
	lreq->senderData = alterTabPtr.p->key;
	lreq->clientRef = alterTabPtr.p->m_senderRef;
	lreq->clientData = alterTabPtr.p->m_senderData;
4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705
	lreq->changeMask = changeMask;
	lreq->tableId = tableId;
	lreq->tableVersion = tableVersion;
	lreq->gci = gci;
	lreq->requestType = AlterTabReq::AlterTableRevert;
	
	sendSignal(rg, GSN_ALTER_TAB_REQ, signal, 
		   AlterTabReq::SignalLength, JBB);
      }
      else {
	jam();
	// Send commit request to all alive nodes
	TableRecordPtr tablePtr;
	c_tableRecordPool.getPtr(tablePtr, tableId);
	SimplePropertiesSectionWriter w(getSectionSegmentPool());
4706
	packTableIntoPages(w, tablePtr);
4707 4708 4709 4710 4711
	SegmentedSectionPtr spDataPtr;
	w.getPtr(spDataPtr);
	signal->setSection(spDataPtr, AlterTabReq::DICT_TAB_INFO);
	
	NodeReceiverGroup rg(DBDICT, c_aliveNodes);
joreland@mysql.com's avatar
joreland@mysql.com committed
4712 4713
	alterTabPtr.p->m_coordinatorData.m_gsn = GSN_ALTER_TAB_REQ;
	safeCounter.init<AlterTabRef>(rg, alterTabPtr.p->key);
4714 4715 4716
  	
	AlterTabReq * const lreq = (AlterTabReq*)signal->getDataPtrSend();
	lreq->senderRef = reference();
joreland@mysql.com's avatar
joreland@mysql.com committed
4717 4718 4719
	lreq->senderData = alterTabPtr.p->key;
	lreq->clientRef = alterTabPtr.p->m_senderRef;
	lreq->clientData = alterTabPtr.p->m_senderData;
4720 4721 4722 4723 4724 4725
	lreq->changeMask = changeMask;
	lreq->tableId = tableId;
	lreq->tableVersion = tableVersion;
	lreq->gci = gci;
	lreq->requestType = AlterTabReq::AlterTableCommit;
	
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
4726 4727
	sendFragmentedSignal(rg, GSN_ALTER_TAB_REQ, signal, 
			     AlterTabReq::SignalLength, JBB);
4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
      }
    }
    else {
      // (!safeCounter.done())
      jam();
    }
    break;
  }
  case(AlterTabReq::AlterTableRevert):
    jam();
  case(AlterTabReq::AlterTableCommit): {
joreland@mysql.com's avatar
joreland@mysql.com committed
4739
    SafeCounter safeCounter(c_counterMgr, alterTabPtr.p->m_coordinatorData.m_counter);
4740 4741 4742 4743 4744
    safeCounter.clearWaitingFor(refToNode(senderRef));
    if (safeCounter.done()) {
      jam();
      // We have received all local confirmations
      releaseSections(signal);
joreland@mysql.com's avatar
joreland@mysql.com committed
4745
      if (alterTabPtr.p->m_alterTableFailed) {
4746 4747 4748
	jam();
	AlterTableRef * apiRef = 
	  (AlterTableRef*)signal->getDataPtrSend();
joreland@mysql.com's avatar
joreland@mysql.com committed
4749 4750
	*apiRef = alterTabPtr.p->m_alterTableRef;
	sendSignal(alterTabPtr.p->m_senderRef, GSN_ALTER_TABLE_REF, signal, 
4751 4752 4753 4754 4755 4756 4757 4758
		   AlterTableRef::SignalLength, JBB);	
      }
      else {
	jam();
	// Alter table completed, inform API
	AlterTableConf * const apiConf = 
	  (AlterTableConf*)signal->getDataPtrSend();
	apiConf->senderRef = reference();
joreland@mysql.com's avatar
joreland@mysql.com committed
4759
	apiConf->senderData = alterTabPtr.p->m_senderData;
4760 4761 4762 4763
	apiConf->tableId = tableId;
	apiConf->tableVersion = tableVersion;
	
	//@todo check api failed
joreland@mysql.com's avatar
joreland@mysql.com committed
4764
	sendSignal(alterTabPtr.p->m_senderRef, GSN_ALTER_TABLE_CONF, signal,
4765 4766 4767 4768 4769
		   AlterTableConf::SignalLength, JBB);
      }
      
      // Release resources
      TableRecordPtr tabPtr;
joreland@mysql.com's avatar
joreland@mysql.com committed
4770
      c_tableRecordPool.getPtr(tabPtr, alterTabPtr.p->m_tablePtrI);  
4771
      releaseTableObject(tabPtr.i, false);
4772
      releaseCreateTableOp(signal,alterTabPtr);
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788
      c_blockState = BS_IDLE;
    }
    else {
      // (!safeCounter.done())
      jam();
    }
    break;
  }
  default: ndbrequire(false);
  }
}

// For debugging
inline
void Dbdict::printTables()
{
4789 4790 4791 4792
  DLHashTable<DictObject>::Iterator iter;
  bool moreTables = c_obj_hash.first(iter);
  printf("OBJECTS IN DICT:\n");
  char name[MAX_TAB_NAME_SIZE];
4793
  while (moreTables) {
4794 4795 4796 4797 4798
    Ptr<DictObject> tablePtr = iter.curr;
    ConstRope r(c_rope_pool, tablePtr.p->m_name);
    r.copy(name);
    printf("%s ", name); 
    moreTables = c_obj_hash.next(iter);
4799 4800 4801 4802 4803
  }
  printf("\n");
}

int Dbdict::handleAlterTab(AlterTabReq * req,
joreland@mysql.com's avatar
joreland@mysql.com committed
4804
			   CreateTableRecord * alterTabPtrP,
4805 4806 4807
			   TableRecordPtr origTablePtr,
			   TableRecordPtr newTablePtr)
{
4808
  bool supportedAlteration = false;
4809 4810 4811 4812 4813
  Uint32 changeMask = req->changeMask;
  
  if (AlterTableReq::getNameFlag(changeMask)) {
    jam();
    // Table rename
4814
    supportedAlteration = true;
4815
    // Remove from hashtable
4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848
    Ptr<DictObject> obj_ptr;
    c_obj_pool.getPtr(obj_ptr, origTablePtr.p->m_obj_ptr_i);
    c_obj_hash.remove(obj_ptr);
    {
      Rope org(c_rope_pool, origTablePtr.p->tableName);
      org.copy(alterTabPtrP->previousTableName);
      
      ConstRope src(c_rope_pool, newTablePtr.p->tableName);
      char tmp[MAX_TAB_NAME_SIZE];
      const int len = src.size();
      src.copy(tmp);
      ndbrequire(org.assign(tmp, len));
    }
    obj_ptr.p->m_name = origTablePtr.p->tableName;
    // Put it back
    c_obj_hash.add(obj_ptr);
  }

  if (AlterTableReq::getFrmFlag(changeMask)) {
    // Table definition changed (new frm)
    supportedAlteration = true;
    // Save old definition
    Rope org(c_rope_pool, origTablePtr.p->frmData);
    org.copy(alterTabPtrP->previousFrmData);
    alterTabPtrP->previousFrmLen = org.size();

    // Set new definition
    ConstRope src(c_rope_pool, newTablePtr.p->frmData);
    char tmp[MAX_FRM_DATA_SIZE];
    src.copy(tmp);
    ndbrequire(org.assign(tmp, src.size()));
  }

4849 4850 4851
/*
  TODO RONM: Lite ny kod fr FragmentData och RangeOrListData
*/
4852 4853
  if (supportedAlteration)
  {
4854 4855 4856 4857
    // Set new schema version
    origTablePtr.p->tableVersion = newTablePtr.p->tableVersion;
    return 0;
  }
4858 4859 4860 4861 4862
  else
  {
    jam();
    return -1;
  }
4863 4864 4865 4866 4867
}

void Dbdict::revertAlterTable(Signal * signal, 
			      Uint32 changeMask, 
			      Uint32 tableId,
joreland@mysql.com's avatar
joreland@mysql.com committed
4868
			      CreateTableRecord * alterTabPtrP)
4869
{
4870 4871 4872 4873 4874
  bool supportedAlteration = false;

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId);
  
4875 4876 4877
  if (AlterTableReq::getNameFlag(changeMask)) {
    jam();
    // Table rename
4878
    supportedAlteration = true;
4879
    // Restore previous name
4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890

    Ptr<DictObject> obj_ptr;
    c_obj_pool.getPtr(obj_ptr, tablePtr.p->m_obj_ptr_i);
    c_obj_hash.remove(obj_ptr);

    {
      // Restore name
      Rope org(c_rope_pool, tablePtr.p->tableName);
      ndbrequire(org.assign(alterTabPtrP->previousTableName));
    }
    obj_ptr.p->m_name = tablePtr.p->tableName;
4891
    // Put it back
4892 4893
    c_obj_hash.add(obj_ptr);
  }
4894

4895 4896 4897 4898 4899 4900 4901 4902 4903 4904
  if (AlterTableReq::getFrmFlag(changeMask)) 
  {
    jam();
    // Table redefinition
    supportedAlteration = true;
    // Restore previous frm
    Rope org(c_rope_pool, tablePtr.p->tableName);
    ndbrequire(org.assign(alterTabPtrP->previousFrmData, 
			  alterTabPtrP->previousFrmLen));
    
4905
  }
4906
  
4907

4908 4909 4910 4911 4912 4913 4914
  if (supportedAlteration)
  {
    tablePtr.p->tableVersion = 
      alter_obj_dec_schema_version(tablePtr.p->tableVersion);
    return;
  }
  
4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926
  ndbrequire(false);
}

void
Dbdict::alterTab_writeSchemaConf(Signal* signal, 
				 Uint32 callbackData,
				 Uint32 returnCode)
{
  jam();
  Uint32 key = callbackData;
  CreateTableRecordPtr alterTabPtr;  
  ndbrequire(c_opCreateTable.find(alterTabPtr, key));
joreland@mysql.com's avatar
joreland@mysql.com committed
4927
  Uint32 tableId = alterTabPtr.p->m_alterTableId;
4928 4929

  Callback callback;
joreland@mysql.com's avatar
joreland@mysql.com committed
4930
  callback.m_callbackData = alterTabPtr.p->key;
4931 4932 4933
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::alterTab_writeTableConf);
  
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId);
  bool savetodisk = !(tablePtr.p->m_bits & TableRecord::TR_Temporary);
  if (savetodisk)
  {
    SegmentedSectionPtr tabInfoPtr;
    getSection(tabInfoPtr, alterTabPtr.p->m_tabInfoPtrI);
    writeTableFile(signal, tableId, tabInfoPtr, &callback);
  }
  else
  {
    execute(signal, callback, 0);
  }
4947 4948 4949 4950 4951 4952 4953 4954 4955 4956
}

void
Dbdict::alterTab_writeTableConf(Signal* signal, 
				Uint32 callbackData,
				Uint32 returnCode)
{
  jam();
  CreateTableRecordPtr alterTabPtr;  
  ndbrequire(c_opCreateTable.find(alterTabPtr, callbackData));
joreland@mysql.com's avatar
joreland@mysql.com committed
4957
  Uint32 coordinatorRef = alterTabPtr.p->m_coordinatorRef;
4958
  TableRecordPtr tabPtr;
joreland@mysql.com's avatar
joreland@mysql.com committed
4959
  c_tableRecordPool.getPtr(tabPtr, alterTabPtr.p->m_alterTableId);
4960
  // Alter table commit request handled successfully 
4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980
  // Inform Suma so it can send events to any subscribers of the table
  AlterTabReq * req = (AlterTabReq*)signal->getDataPtrSend();
  if (coordinatorRef == reference())
    req->senderRef = alterTabPtr.p->m_senderRef;
  else
    req->senderRef = 0;
  req->senderData = callbackData;
  req->tableId = tabPtr.p->tableId;
  req->tableVersion = tabPtr.p->tableVersion;
  req->gci = tabPtr.p->gciTableCreated;
  req->requestType = AlterTabReq::AlterTableCommit;
  req->changeMask = alterTabPtr.p->m_changeMask;
  SegmentedSectionPtr tabInfoPtr;
  getSection(tabInfoPtr, alterTabPtr.p->m_tabInfoPtrI);
  signal->setSection(tabInfoPtr, AlterTabReq::DICT_TAB_INFO);
  EXECUTE_DIRECT(SUMA, GSN_ALTER_TAB_REQ, signal,
                 AlterTabReq::SignalLength);
  releaseSections(signal);
  alterTabPtr.p->m_tabInfoPtrI = RNIL;
  jamEntry();
4981 4982 4983 4984 4985 4986 4987
  AlterTabConf * conf = (AlterTabConf*)signal->getDataPtrSend();
  conf->senderRef = reference();
  conf->senderData = callbackData;
  conf->tableId = tabPtr.p->tableId;
  conf->tableVersion = tabPtr.p->tableVersion;
  conf->gci = tabPtr.p->gciTableCreated;
  conf->requestType = AlterTabReq::AlterTableCommit;
4988
  conf->changeMask = alterTabPtr.p->m_changeMask;
4989 4990
  sendSignal(coordinatorRef, GSN_ALTER_TAB_CONF, signal, 
	       AlterTabConf::SignalLength, JBB);
4991 4992 4993 4994 4995 4996 4997 4998 4999


  {
    ApiBroadcastRep* api= (ApiBroadcastRep*)signal->getDataPtrSend();
    api->gsn = GSN_ALTER_TABLE_REP;
    api->minVersion = MAKE_VERSION(4,1,15);

    AlterTableRep* rep = (AlterTableRep*)api->theData;
    rep->tableId = tabPtr.p->tableId;
5000
    rep->tableVersion = alter_obj_dec_schema_version(tabPtr.p->tableVersion);
5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011
    rep->changeType = AlterTableRep::CT_ALTERED;
    
    LinearSectionPtr ptr[3];
    ptr[0].p = (Uint32*)alterTabPtr.p->previousTableName;
    ptr[0].sz = (sizeof(alterTabPtr.p->previousTableName) + 3) >> 2;
    
    sendSignal(QMGR_REF, GSN_API_BROADCAST_REP, signal, 
	       ApiBroadcastRep::SignalLength + AlterTableRep::SignalLength,
	       JBB, ptr,1);
  }

5012 5013 5014
  if(coordinatorRef != reference()) {
    jam();
    // Release resources
joreland@mysql.com's avatar
joreland@mysql.com committed
5015
    c_tableRecordPool.getPtr(tabPtr, alterTabPtr.p->m_tablePtrI);  
5016
    releaseTableObject(tabPtr.i, false);
5017
    releaseCreateTableOp(signal,alterTabPtr);
5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046
    c_blockState = BS_IDLE;
  }
}

void
Dbdict::execCREATE_FRAGMENTATION_REF(Signal * signal){
  jamEntry();
  const Uint32 * theData = signal->getDataPtr();
  CreateFragmentationRef * const ref = (CreateFragmentationRef*)theData;
  (void)ref;
  ndbrequire(false);
}

void
Dbdict::execCREATE_FRAGMENTATION_CONF(Signal* signal){
  jamEntry();
  const Uint32 * theData = signal->getDataPtr();
  CreateFragmentationConf * const conf = (CreateFragmentationConf*)theData;

  CreateTableRecordPtr createTabPtr;
  ndbrequire(c_opCreateTable.find(createTabPtr, conf->senderData));

  ndbrequire(signal->getNoOfSections() == 1);

  SegmentedSectionPtr fragDataPtr;
  signal->getSection(fragDataPtr, CreateFragmentationConf::FRAGMENTS);
  signal->header.m_noOfSections = 0;

  /**
joreland@mysql.com's avatar
joreland@mysql.com committed
5047
   * Get table
5048 5049 5050 5051
   */
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);

joreland@mysql.com's avatar
joreland@mysql.com committed
5052 5053 5054 5055 5056 5057 5058 5059
  /**
   * Save fragment count
   */
  tabPtr.p->fragmentCount = conf->noOfFragments;

  /**
   * Update table version
   */
5060 5061
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry * tabEntry = getTableEntry(xsf, tabPtr.i);
5062

5063 5064
  tabPtr.p->tableVersion = 
    create_obj_inc_schema_version(tabEntry->m_tableVersion);
joreland@mysql.com's avatar
joreland@mysql.com committed
5065

5066
  /**
joreland@mysql.com's avatar
joreland@mysql.com committed
5067
   * Pack
5068 5069
   */
  SimplePropertiesSectionWriter w(getSectionSegmentPool());
5070
  packTableIntoPages(w, tabPtr);
5071 5072 5073
  
  SegmentedSectionPtr spDataPtr;
  w.getPtr(spDataPtr);
joreland@mysql.com's avatar
joreland@mysql.com committed
5074
  
5075 5076
  signal->setSection(spDataPtr, CreateTabReq::DICT_TAB_INFO);
  signal->setSection(fragDataPtr, CreateTabReq::FRAGMENTATION);
5077
 
5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
  SafeCounter tmp(c_counterMgr, createTabPtr.p->m_coordinatorData.m_counter);
  createTabPtr.p->m_coordinatorData.m_gsn = GSN_CREATE_TAB_REQ;
  createTabPtr.p->m_coordinatorData.m_requestType = CreateTabReq::CreateTablePrepare;
  tmp.init<CreateTabRef>(rg, GSN_CREATE_TAB_REF, createTabPtr.p->key);
  
  CreateTabReq * const req = (CreateTabReq*)theData;
  req->senderRef = reference();
  req->senderData = createTabPtr.p->key;
  req->clientRef = createTabPtr.p->m_senderRef;
  req->clientData = createTabPtr.p->m_senderData;
  req->requestType = CreateTabReq::CreateTablePrepare;

  req->gci = 0;
  req->tableId = tabPtr.i;
5093
  req->tableVersion = create_obj_inc_schema_version(tabEntry->m_tableVersion);
5094
  
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5095 5096
  sendFragmentedSignal(rg, GSN_CREATE_TAB_REQ, signal, 
		       CreateTabReq::SignalLength, JBB);
5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199

  return;
}

void
Dbdict::execCREATE_TAB_REF(Signal* signal){
  jamEntry();

  CreateTabRef * const ref = (CreateTabRef*)signal->getDataPtr();
  
  CreateTableRecordPtr createTabPtr;
  ndbrequire(c_opCreateTable.find(createTabPtr, ref->senderData));
  
  ndbrequire(createTabPtr.p->m_coordinatorRef == reference());
  ndbrequire(createTabPtr.p->m_coordinatorData.m_gsn == GSN_CREATE_TAB_REQ);

  if(ref->errorCode != CreateTabRef::NF_FakeErrorREF){
    createTabPtr.p->setErrorCode(ref->errorCode);
  }
  createTab_reply(signal, createTabPtr, refToNode(ref->senderRef));
}

void
Dbdict::execCREATE_TAB_CONF(Signal* signal){
  jamEntry();

  ndbrequire(signal->getNoOfSections() == 0);

  CreateTabConf * const conf = (CreateTabConf*)signal->getDataPtr();
  
  CreateTableRecordPtr createTabPtr;
  ndbrequire(c_opCreateTable.find(createTabPtr, conf->senderData));
  
  ndbrequire(createTabPtr.p->m_coordinatorRef == reference());
  ndbrequire(createTabPtr.p->m_coordinatorData.m_gsn == GSN_CREATE_TAB_REQ);

  createTab_reply(signal, createTabPtr, refToNode(conf->senderRef));
}

void
Dbdict::createTab_reply(Signal* signal, 
			CreateTableRecordPtr createTabPtr, 
			Uint32 nodeId)
{

  SafeCounter tmp(c_counterMgr, createTabPtr.p->m_coordinatorData.m_counter);
  if(!tmp.clearWaitingFor(nodeId)){
    jam();
    return;
  }
  
  switch(createTabPtr.p->m_coordinatorData.m_requestType){
  case CreateTabReq::CreateTablePrepare:{

    if(createTabPtr.p->m_errorCode != 0){
      jam();
      /**
       * Failed to prepare on atleast one node -> abort on all
       */
      NodeReceiverGroup rg(DBDICT, c_aliveNodes);
      createTabPtr.p->m_coordinatorData.m_gsn = GSN_CREATE_TAB_REQ;
      createTabPtr.p->m_coordinatorData.m_requestType = CreateTabReq::CreateTableDrop;
      ndbrequire(tmp.init<CreateTabRef>(rg, createTabPtr.p->key));
      
      CreateTabReq * const req = (CreateTabReq*)signal->getDataPtrSend();
      req->senderRef = reference();
      req->senderData = createTabPtr.p->key;
      req->requestType = CreateTabReq::CreateTableDrop;
      
      sendSignal(rg, GSN_CREATE_TAB_REQ, signal, 
		 CreateTabReq::SignalLength, JBB);
      return;
    }
    
    /**
     * Lock mutex before commiting table
     */
    Mutex mutex(signal, c_mutexMgr, createTabPtr.p->m_startLcpMutex);
    Callback c = { safe_cast(&Dbdict::createTab_startLcpMutex_locked),
		   createTabPtr.p->key};

    ndbrequire(mutex.lock(c));
    return;
  }
  case CreateTabReq::CreateTableCommit:{
    jam();
    ndbrequire(createTabPtr.p->m_errorCode == 0);
    
    /**
     * Unlock mutex before commiting table
     */
    Mutex mutex(signal, c_mutexMgr, createTabPtr.p->m_startLcpMutex);
    Callback c = { safe_cast(&Dbdict::createTab_startLcpMutex_unlocked),
		   createTabPtr.p->key};
    mutex.unlock(c);
    return;
  }
  case CreateTabReq::CreateTableDrop:{
    jam();
    CreateTableRef * const ref = (CreateTableRef*)signal->getDataPtr();
    ref->senderRef = reference();
    ref->senderData = createTabPtr.p->m_senderData;
    ref->errorCode = createTabPtr.p->m_errorCode;
5200 5201 5202 5203
    ref->masterNodeId = c_masterNodeId;
    ref->status = 0;
    ref->errorKey = 0;
    ref->errorLine = 0;
5204 5205 5206 5207
    
    //@todo check api failed
    sendSignal(createTabPtr.p->m_senderRef, GSN_CREATE_TABLE_REF, signal, 
	       CreateTableRef::SignalLength, JBB);
5208
    releaseCreateTableOp(signal,createTabPtr);
5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266
    c_blockState = BS_IDLE;
    return;
  }
  }
  ndbrequire(false);
}

void
Dbdict::createTab_startLcpMutex_locked(Signal* signal, 
				       Uint32 callbackData,
				       Uint32 retValue){
  jamEntry();

  ndbrequire(retValue == 0);
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));
  
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
  createTabPtr.p->m_coordinatorData.m_gsn = GSN_CREATE_TAB_REQ;
  createTabPtr.p->m_coordinatorData.m_requestType = CreateTabReq::CreateTableCommit;
  SafeCounter tmp(c_counterMgr, createTabPtr.p->m_coordinatorData.m_counter);
  tmp.init<CreateTabRef>(rg, GSN_CREATE_TAB_REF, createTabPtr.p->key);
  
  CreateTabReq * const req = (CreateTabReq*)signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = createTabPtr.p->key;
  req->requestType = CreateTabReq::CreateTableCommit;
  
  sendSignal(rg, GSN_CREATE_TAB_REQ, signal, 
	     CreateTabReq::SignalLength, JBB);
}

void
Dbdict::createTab_startLcpMutex_unlocked(Signal* signal, 
					 Uint32 callbackData,
					 Uint32 retValue){
  jamEntry();
  
  ndbrequire(retValue == 0);
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));

  createTabPtr.p->m_startLcpMutex.release(c_mutexMgr);
  
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  
  CreateTableConf * const conf = (CreateTableConf*)signal->getDataPtr();
  conf->senderRef = reference();
  conf->senderData = createTabPtr.p->m_senderData;
  conf->tableId = createTabPtr.p->m_tablePtrI;
  conf->tableVersion = tabPtr.p->tableVersion;
  
  //@todo check api failed
  sendSignal(createTabPtr.p->m_senderRef, GSN_CREATE_TABLE_CONF, signal, 
	     CreateTableConf::SignalLength, JBB);
5267
  releaseCreateTableOp(signal,createTabPtr);
5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288
  c_blockState = BS_IDLE;
  return;
}

/***********************************************************
 * CreateTable participant code
 **********************************************************/
void
Dbdict::execCREATE_TAB_REQ(Signal* signal){
  jamEntry();

  if(!assembleFragments(signal)){
    jam();
    return;
  }

  CreateTabReq * const req = (CreateTabReq*)signal->getDataPtr();

  CreateTabReq::RequestType rt = (CreateTabReq::RequestType)req->requestType;
  switch(rt){
  case CreateTabReq::CreateTablePrepare:
5289
    CRASH_INSERTION2(6003, getOwnNodeId() != c_masterNodeId);
5290 5291 5292
    createTab_prepare(signal, req);
    return;
  case CreateTabReq::CreateTableCommit:
5293
    CRASH_INSERTION2(6004, getOwnNodeId() != c_masterNodeId);
5294 5295 5296
    createTab_commit(signal, req);
    return;
  case CreateTabReq::CreateTableDrop:
5297
    CRASH_INSERTION2(6005, getOwnNodeId() != c_masterNodeId);
5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367
    createTab_drop(signal, req);
    return;
  }
  ndbrequire(false);
}

void
Dbdict::createTab_prepare(Signal* signal, CreateTabReq * req){

  const Uint32 gci = req->gci;
  const Uint32 tableId = req->tableId;
  const Uint32 tableVersion = req->tableVersion;

  SegmentedSectionPtr tabInfoPtr;
  signal->getSection(tabInfoPtr, CreateTabReq::DICT_TAB_INFO);
  
  CreateTableRecordPtr createTabPtr;  
  if(req->senderRef == reference()){
    jam();
    ndbrequire(c_opCreateTable.find(createTabPtr, req->senderData));
  } else {
    jam();
    c_opCreateTable.seize(createTabPtr);
    
    ndbrequire(!createTabPtr.isNull());
    
    createTabPtr.p->key = req->senderData;
    c_opCreateTable.add(createTabPtr);
    createTabPtr.p->m_errorCode = 0;
    createTabPtr.p->m_tablePtrI = tableId;
    createTabPtr.p->m_coordinatorRef = req->senderRef;
    createTabPtr.p->m_senderRef = req->clientRef;
    createTabPtr.p->m_senderData = req->clientData;
    createTabPtr.p->m_dihAddFragPtr = RNIL;
    
    /**
     * Put data into table record
     */
    ParseDictTabInfoRecord parseRecord;
    parseRecord.requestType = DictTabInfo::AddTableFromDict;
    parseRecord.errorCode = 0;
    
    SimplePropertiesSectionReader r(tabInfoPtr, getSectionSegmentPool());
    
    handleTabInfoInit(r, &parseRecord);

    ndbrequire(parseRecord.errorCode == 0);
  }
  
  ndbrequire(!createTabPtr.isNull());

  SegmentedSectionPtr fragPtr;
  signal->getSection(fragPtr, CreateTabReq::FRAGMENTATION);

  createTabPtr.p->m_tabInfoPtrI = tabInfoPtr.i;
  createTabPtr.p->m_fragmentsPtrI = fragPtr.i;
  
  signal->header.m_noOfSections = 0;
  
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, tableId);
  tabPtr.p->packedSize = tabInfoPtr.sz;
  tabPtr.p->tableVersion = tableVersion;
  tabPtr.p->gciTableCreated = gci;

  SchemaFile::TableEntry tabEntry;
  tabEntry.m_tableVersion = tableVersion;
  tabEntry.m_tableType    = tabPtr.p->tableType;
  tabEntry.m_tableState   = SchemaFile::ADD_STARTED;
  tabEntry.m_gcp          = gci;
5368
  tabEntry.m_info_words   = tabInfoPtr.sz;
5369
  memset(tabEntry.m_unused, 0, sizeof(tabEntry.m_unused));
5370 5371 5372 5373 5374 5375
  
  Callback callback;
  callback.m_callbackData = createTabPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::createTab_writeSchemaConf1);
  
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5376 5377
  bool savetodisk = !(tabPtr.p->m_bits & TableRecord::TR_Temporary);
  updateSchemaState(signal, tableId, &tabEntry, &callback, savetodisk);
5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395
}

void getSection(SegmentedSectionPtr & ptr, Uint32 i);

void
Dbdict::createTab_writeSchemaConf1(Signal* signal, 
				   Uint32 callbackData,
				   Uint32 returnCode){
  jam();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));

  Callback callback;
  callback.m_callbackData = createTabPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::createTab_writeTableConf);
  
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  bool savetodisk = !(tabPtr.p->m_bits & TableRecord::TR_Temporary);
  if (savetodisk)
  {
    SegmentedSectionPtr tabInfoPtr;
    getSection(tabInfoPtr, createTabPtr.p->m_tabInfoPtrI);
    writeTableFile(signal, createTabPtr.p->m_tablePtrI, tabInfoPtr, &callback);
  }
  else
  {
    execute(signal, callback, 0);
  }
5409
#if 0
5410
  createTabPtr.p->m_tabInfoPtrI = RNIL;
5411 5412
  signal->setSection(tabInfoPtr, 0);
  releaseSections(signal);
5413
#endif
5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453
}

void
Dbdict::createTab_writeTableConf(Signal* signal, 
				 Uint32 callbackData,
				 Uint32 returnCode){
  jam();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));

  SegmentedSectionPtr fragDataPtr;
  getSection(fragDataPtr, createTabPtr.p->m_fragmentsPtrI);
  
  Callback callback;
  callback.m_callbackData = callbackData;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::createTab_dihComplete);
  
  createTab_dih(signal, createTabPtr, fragDataPtr, &callback);
}

void
Dbdict::createTab_dih(Signal* signal, 
		      CreateTableRecordPtr createTabPtr, 
		      SegmentedSectionPtr fragDataPtr,
		      Callback * c){
  jam();
  
  createTabPtr.p->m_callback = * c;

  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  
  DiAddTabReq * req = (DiAddTabReq*)signal->getDataPtrSend();
  req->connectPtr = createTabPtr.p->key;
  req->tableId = tabPtr.i;
  req->fragType = tabPtr.p->fragmentType;
  req->kValue = tabPtr.p->kValue;
  req->noOfReplicas = 0;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5454
  req->loggedTable = !!(tabPtr.p->m_bits & TableRecord::TR_Logged);
5455 5456 5457
  req->tableType = tabPtr.p->tableType;
  req->schemaVersion = tabPtr.p->tableVersion;
  req->primaryTableId = tabPtr.p->primaryTableId;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5458
  req->temporaryTable = !!(tabPtr.p->m_bits & TableRecord::TR_Temporary);
5459

5460 5461 5462
/*
  Behver fiska upp fragDataPtr frn table object istllet
*/
5463 5464 5465 5466 5467 5468
  if(!fragDataPtr.isNull()){
    signal->setSection(fragDataPtr, DiAddTabReq::FRAGMENTATION);
  }

  sendSignal(DBDIH_REF, GSN_DIADDTABREQ, signal, 
	     DiAddTabReq::SignalLength, JBB);
5469 5470 5471 5472 5473 5474 5475 5476

  /**
   * Create KeyDescriptor
   */
  KeyDescriptor* desc= g_key_descriptor_pool.getPtr(tabPtr.i);
  new (desc) KeyDescriptor();

  Uint32 key = 0;
5477 5478 5479 5480
  Ptr<AttributeRecord> attrPtr;
  LocalDLFifoList<AttributeRecord> list(c_attributeRecordPool,
                                        tabPtr.p->m_attributes);
  for(list.first(attrPtr); !attrPtr.isNull(); list.next(attrPtr))
5481
  {
5482 5483
    AttributeRecord* aRec = attrPtr.p;
    if (aRec->tupleKey)
5484
    {
5485 5486
      Uint32 attr = aRec->attributeDescriptor;

5487
      desc->noOfKeyAttr ++;
5488
      desc->keyAttr[key].attributeDescriptor = attr;
5489
      Uint32 csNumber = (aRec->extPrecision >> 16);
5490
      if (csNumber)
5491
      {
5492 5493 5494
        desc->keyAttr[key].charsetInfo = all_charsets[csNumber];
        ndbrequire(all_charsets[csNumber] != 0);
        desc->hasCharAttr = 1;
5495 5496 5497
      }
      else
      {
5498
        desc->keyAttr[key].charsetInfo = 0;
5499
      }
5500
      if (AttributeDescriptor::getDKey(attr))
5501
      {
5502 5503 5504 5505 5506
        desc->noOfDistrKeys ++;
      }
      if (AttributeDescriptor::getArrayType(attr) != NDB_ARRAYTYPE_FIXED)
      {
        desc->noOfVarKeys ++;
5507 5508 5509 5510 5511
      }
      key++;
    }
  }
  ndbrequire(key == tabPtr.p->noOfPrimkey);
5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527
}

static
void
calcLHbits(Uint32 * lhPageBits, Uint32 * lhDistrBits, 
	   Uint32 fid, Uint32 totalFragments) 
{
  Uint32 distrBits = 0;
  Uint32 pageBits = 0;
  
  Uint32 tmp = 1;
  while (tmp < totalFragments) {
    jam();
    tmp <<= 1;
    distrBits++;
  }//while
pekka@mysql.com's avatar
pekka@mysql.com committed
5528
#ifdef ndb_classical_lhdistrbits
5529 5530 5531 5532 5533 5534
  if (tmp != totalFragments) {
    tmp >>= 1;
    if ((fid >= (totalFragments - tmp)) && (fid < (tmp - 1))) {
      distrBits--;
    }//if
  }//if
pekka@mysql.com's avatar
pekka@mysql.com committed
5535
#endif
5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556
  * lhPageBits = pageBits;
  * lhDistrBits = distrBits;

}//calcLHbits()


void 
Dbdict::execADD_FRAGREQ(Signal* signal) {
  jamEntry();

  AddFragReq * const req = (AddFragReq*)signal->getDataPtr();
  
  Uint32 dihPtr = req->dihPtr;
  Uint32 senderData = req->senderData;
  Uint32 tableId = req->tableId;
  Uint32 fragId = req->fragmentId;
  Uint32 node = req->nodeId;
  Uint32 lcpNo = req->nextLCP;
  Uint32 fragCount = req->totalFragments;
  Uint32 requestInfo = req->requestInfo;
  Uint32 startGci = req->startGci;
5557
  Uint32 logPart = req->logPartId;
5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580

  ndbrequire(node == getOwnNodeId());

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, senderData));
  
  createTabPtr.p->m_dihAddFragPtr = dihPtr;
  
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, tableId);

#if 0
  tabPtr.p->gciTableCreated = (startGci > tabPtr.p->gciTableCreated ? startGci:
			       startGci > tabPtr.p->gciTableCreated);
#endif
  
  /**
   * Calc lh3PageBits
   */
  Uint32 lhDistrBits = 0;
  Uint32 lhPageBits = 0;
  ::calcLHbits(&lhPageBits, &lhDistrBits, fragId, fragCount);

5581 5582 5583 5584 5585 5586 5587
  Uint64 maxRows = tabPtr.p->maxRowsLow +
    (((Uint64)tabPtr.p->maxRowsHigh) << 32);
  Uint64 minRows = tabPtr.p->minRowsLow +
    (((Uint64)tabPtr.p->minRowsHigh) << 32);
  maxRows = (maxRows + fragCount - 1) / fragCount;
  minRows = (minRows + fragCount - 1) / fragCount;

5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598
  {  
    LqhFragReq* req = (LqhFragReq*)signal->getDataPtrSend();
    req->senderData = senderData;
    req->senderRef = reference();
    req->fragmentId = fragId;
    req->requestInfo = requestInfo;
    req->tableId = tableId;
    req->localKeyLength = tabPtr.p->localKeyLen;
    req->maxLoadFactor = tabPtr.p->maxLoadFactor;
    req->minLoadFactor = tabPtr.p->minLoadFactor;
    req->kValue = tabPtr.p->kValue;
joreland@mysql.com's avatar
joreland@mysql.com committed
5599 5600
    req->lh3DistrBits = 0; //lhDistrBits;
    req->lh3PageBits = 0; //lhPageBits;
5601
    req->noOfAttributes = tabPtr.p->noOfAttributes;
5602
    req->noOfNullAttributes = tabPtr.p->noOfNullBits;
5603 5604 5605 5606
    req->maxRowsLow = maxRows & 0xFFFFFFFF;
    req->maxRowsHigh = maxRows >> 32;
    req->minRowsLow = minRows & 0xFFFFFFFF;
    req->minRowsHigh = minRows >> 32;
5607 5608
    req->schemaVersion = tabPtr.p->tableVersion;
    Uint32 keyLen = tabPtr.p->tupKeyLength;
5609
    req->keyLength = keyLen; // wl-2066 no more "long keys"
5610 5611 5612
    req->nextLCP = lcpNo;

    req->noOfKeyAttr = tabPtr.p->noOfPrimkey;
5613
    req->noOfCharsets = tabPtr.p->noOfCharsets;
5614
    req->checksumIndicator = 1;
5615
    req->GCPIndicator = 1;
5616 5617 5618
    req->startGci = startGci;
    req->tableType = tabPtr.p->tableType;
    req->primaryTableId = tabPtr.p->primaryTableId;
5619
    req->tablespace_id= tabPtr.p->m_tablespace_id;
5620
    req->logPartId = logPart;
5621
    req->forceVarPartFlag = !!(tabPtr.p->m_bits& TableRecord::TR_ForceVarPart);
5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656
    sendSignal(DBLQH_REF, GSN_LQHFRAGREQ, signal, 
	       LqhFragReq::SignalLength, JBB);
  }
}

void
Dbdict::execLQHFRAGREF(Signal * signal){
  jamEntry();
  LqhFragRef * const ref = (LqhFragRef*)signal->getDataPtr();
 
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, ref->senderData));
  
  createTabPtr.p->setErrorCode(ref->errorCode);
  
  {
    AddFragRef * const ref = (AddFragRef*)signal->getDataPtr();
    ref->dihPtr = createTabPtr.p->m_dihAddFragPtr;
    sendSignal(DBDIH_REF, GSN_ADD_FRAGREF, signal, 
	       AddFragRef::SignalLength, JBB);
  }
}

void
Dbdict::execLQHFRAGCONF(Signal * signal){
  jamEntry();
  LqhFragConf * const conf = (LqhFragConf*)signal->getDataPtr();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, conf->senderData));
  
  createTabPtr.p->m_lqhFragPtr = conf->lqhFragPtr;
  
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
5657
  sendLQHADDATTRREQ(signal, createTabPtr, tabPtr.p->m_attributes.firstItem);
5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675
}

void
Dbdict::sendLQHADDATTRREQ(Signal* signal,
			  CreateTableRecordPtr createTabPtr,
			  Uint32 attributePtrI){
  jam();
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  LqhAddAttrReq * const req = (LqhAddAttrReq*)signal->getDataPtrSend();
  Uint32 i = 0;
  for(i = 0; i<LqhAddAttrReq::MAX_ATTRIBUTES && attributePtrI != RNIL; i++){
    jam();
    AttributeRecordPtr attrPtr;
    c_attributeRecordPool.getPtr(attrPtr, attributePtrI);
    LqhAddAttrReq::Entry& entry = req->attributes[i];
    entry.attrId = attrPtr.p->attributeId;
    entry.attrDescriptor = attrPtr.p->attributeDescriptor;
5676
    entry.extTypeInfo = 0;
5677 5678
    // charset number passed to TUP, TUX in upper half
    entry.extTypeInfo |= (attrPtr.p->extPrecision & ~0xFFFF);
5679 5680
    if (tabPtr.p->isIndex()) {
      Uint32 primaryAttrId;
5681
      if (attrPtr.p->nextList != RNIL) {
5682 5683 5684 5685 5686 5687 5688 5689
        getIndexAttr(tabPtr, attributePtrI, &primaryAttrId);
      } else {
        primaryAttrId = ZNIL;
        if (tabPtr.p->isOrderedIndex())
          entry.attrId = 0;     // attribute goes to TUP
      }
      entry.attrId |= (primaryAttrId << 16);
    }
5690
    attributePtrI = attrPtr.p->nextList;
5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782
  }
  req->lqhFragPtr = createTabPtr.p->m_lqhFragPtr;
  req->senderData = createTabPtr.p->key;
  req->senderAttrPtr = attributePtrI;
  req->noOfAttributes = i;
  
  sendSignal(DBLQH_REF, GSN_LQHADDATTREQ, signal, 
	     LqhAddAttrReq::HeaderLength + LqhAddAttrReq::EntryLength * i, JBB);
}

void
Dbdict::execLQHADDATTREF(Signal * signal){
  jamEntry();
  LqhAddAttrRef * const ref = (LqhAddAttrRef*)signal->getDataPtr();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, ref->senderData));
  
  createTabPtr.p->setErrorCode(ref->errorCode);
  
  {
    AddFragRef * const ref = (AddFragRef*)signal->getDataPtr();
    ref->dihPtr = createTabPtr.p->m_dihAddFragPtr;
    sendSignal(DBDIH_REF, GSN_ADD_FRAGREF, signal, 
	       AddFragRef::SignalLength, JBB);
  }
  
}

void
Dbdict::execLQHADDATTCONF(Signal * signal){
  jamEntry();
  LqhAddAttrConf * const conf = (LqhAddAttrConf*)signal->getDataPtr();

  CreateTableRecordPtr createTabPtr;
  ndbrequire(c_opCreateTable.find(createTabPtr, conf->senderData));
  
  const Uint32 fragId = conf->fragId;
  const Uint32 nextAttrPtr = conf->senderAttrPtr;
  if(nextAttrPtr != RNIL){
    jam();
    sendLQHADDATTRREQ(signal, createTabPtr, nextAttrPtr);
    return;
  }

  {
    AddFragConf * const conf = (AddFragConf*)signal->getDataPtr();
    conf->dihPtr = createTabPtr.p->m_dihAddFragPtr;
    conf->fragId = fragId;
    sendSignal(DBDIH_REF, GSN_ADD_FRAGCONF, signal, 
	       AddFragConf::SignalLength, JBB);
  }
}

void
Dbdict::execDIADDTABREF(Signal* signal){
  jam();
  
  DiAddTabRef * const ref = (DiAddTabRef*)signal->getDataPtr();
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, ref->senderData));
  
  createTabPtr.p->setErrorCode(ref->errorCode);  
  execute(signal, createTabPtr.p->m_callback, 0);
}

void
Dbdict::execDIADDTABCONF(Signal* signal){
  jam();
  
  DiAddTabConf * const conf = (DiAddTabConf*)signal->getDataPtr();
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, conf->senderData));

  signal->theData[0] = createTabPtr.p->key;
  signal->theData[1] = reference();
  signal->theData[2] = createTabPtr.p->m_tablePtrI;

  if(createTabPtr.p->m_dihAddFragPtr != RNIL){
    jam();

    /**
     * We did perform at least one LQHFRAGREQ
     */
    sendSignal(DBLQH_REF, GSN_TAB_COMMITREQ, signal, 3, JBB);
    return;
  } else {
    /**
     * No local fragment (i.e. no LQHFRAGREQ)
     */
joreland@mysql.com's avatar
joreland@mysql.com committed
5783 5784 5785
    execute(signal, createTabPtr.p->m_callback, 0);
    return;
    //sendSignal(DBDIH_REF, GSN_TAB_COMMITREQ, signal, 3, JBB);
5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813
  }
}

void 
Dbdict::execTAB_COMMITREF(Signal* signal) {
  jamEntry();
  ndbrequire(false);
}//execTAB_COMMITREF()

void
Dbdict::execTAB_COMMITCONF(Signal* signal){
  jamEntry();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, signal->theData[0]));
  
  if(refToBlock(signal->getSendersBlockRef()) == DBLQH){

    execute(signal, createTabPtr.p->m_callback, 0);
    return;
  }

  if(refToBlock(signal->getSendersBlockRef()) == DBDIH){
    TableRecordPtr tabPtr;
    c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
    
    signal->theData[0] = tabPtr.i;
    signal->theData[1] = tabPtr.p->tableVersion;
5814
    signal->theData[2] = (Uint32)!!(tabPtr.p->m_bits & TableRecord::TR_Logged);
5815 5816 5817
    signal->theData[3] = reference();
    signal->theData[4] = (Uint32)tabPtr.p->tableType;
    signal->theData[5] = createTabPtr.p->key;
5818
    signal->theData[6] = (Uint32)tabPtr.p->noOfPrimkey;
5819 5820 5821
    signal->theData[7] = (Uint32)tabPtr.p->singleUserMode;

    sendSignal(DBTC_REF, GSN_TC_SCHVERREQ, signal, 8, JBB);
5822 5823
    return;
  }
5824
  
5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870
  ndbrequire(false);
}

void
Dbdict::createTab_dihComplete(Signal* signal, 
			      Uint32 callbackData,
			      Uint32 returnCode){
  jam();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));

  //@todo check for master failed
  
  if(createTabPtr.p->m_errorCode == 0){
    jam();

    CreateTabConf * const conf = (CreateTabConf*)signal->getDataPtr();
    conf->senderRef = reference();
    conf->senderData = createTabPtr.p->key;
    sendSignal(createTabPtr.p->m_coordinatorRef, GSN_CREATE_TAB_CONF,
	       signal, CreateTabConf::SignalLength, JBB);
    return;
  }

  CreateTabRef * const ref = (CreateTabRef*)signal->getDataPtr();
  ref->senderRef = reference();
  ref->senderData = createTabPtr.p->key;
  ref->errorCode = createTabPtr.p->m_errorCode;
  ref->errorLine = 0;
  ref->errorKey = 0;
  ref->errorStatus = 0;

  sendSignal(createTabPtr.p->m_coordinatorRef, GSN_CREATE_TAB_REF,
	     signal, CreateTabRef::SignalLength, JBB);
}

void
Dbdict::createTab_commit(Signal * signal, CreateTabReq * req){
  jam();
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, req->senderData));

  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5871 5872
  bool savetodisk = !(tabPtr.p->m_bits & TableRecord::TR_Temporary);

5873 5874 5875
  SchemaFile::TableEntry tabEntry;
  tabEntry.m_tableVersion = tabPtr.p->tableVersion;
  tabEntry.m_tableType    = tabPtr.p->tableType;
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5876 5877 5878 5879 5880
  if (savetodisk)
    tabEntry.m_tableState   = SchemaFile::TABLE_ADD_COMMITTED;
  else
    tabEntry.m_tableState   = SchemaFile::TEMPORARY_TABLE_COMMITTED;
    
5881
  tabEntry.m_gcp          = tabPtr.p->gciTableCreated;
5882
  tabEntry.m_info_words   = tabPtr.p->packedSize;
5883
  memset(tabEntry.m_unused, 0, sizeof(tabEntry.m_unused));
5884 5885 5886 5887 5888 5889
  
  Callback callback;
  callback.m_callbackData = createTabPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::createTab_writeSchemaConf2);
  
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
5890
  updateSchemaState(signal, tabPtr.i, &tabEntry, &callback, savetodisk);
5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926
}

void
Dbdict::createTab_writeSchemaConf2(Signal* signal, 
				   Uint32 callbackData,
				   Uint32 returnCode){
  jam();
  
  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));
  
  Callback c;
  c.m_callbackData = callbackData;
  c.m_callbackFunction = safe_cast(&Dbdict::createTab_alterComplete);
  alterTab_activate(signal, createTabPtr, &c);
}

void
Dbdict::createTab_alterComplete(Signal* signal, 
				Uint32 callbackData,
				Uint32 returnCode){
  jam();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));
  
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  tabPtr.p->tabState = TableRecord::DEFINED;
  
  //@todo check error
  //@todo check master failed
  
  CreateTabConf * const conf = (CreateTabConf*)signal->getDataPtr();
  conf->senderRef = reference();
  conf->senderData = createTabPtr.p->key;
5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942
  {
    CreateTabConf tmp= *conf;
    conf->senderData = createTabPtr.p->m_tablePtrI;
#if 0
    signal->header.m_noOfSections = 1;
    SegmentedSectionPtr tabInfoPtr;
    getSection(tabInfoPtr, createTabPtr.p->m_tabInfoPtrI);
    signal->setSection(tabInfoPtr, 0);
#endif
    sendSignal(SUMA_REF, GSN_CREATE_TAB_CONF, signal,
		CreateTabConf::SignalLength, JBB);
    *conf= tmp;
#if 0
    signal->header.m_noOfSections = 0;
#endif
  }
5943 5944 5945 5946 5947
  sendSignal(createTabPtr.p->m_coordinatorRef, GSN_CREATE_TAB_CONF,
	     signal, CreateTabConf::SignalLength, JBB);

  if(createTabPtr.p->m_coordinatorRef != reference()){
    jam();
5948
    releaseCreateTableOp(signal,createTabPtr);
5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981
  }
}

void
Dbdict::createTab_drop(Signal* signal, CreateTabReq * req){
  jam();

  const Uint32 key = req->senderData;

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, key));
  
  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  tabPtr.p->tabState = TableRecord::DROPPING;

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.seize(dropTabPtr));
  
  dropTabPtr.p->key = key;
  c_opDropTable.add(dropTabPtr);
  
  dropTabPtr.p->m_errorCode = 0;
  dropTabPtr.p->m_request.tableId = createTabPtr.p->m_tablePtrI;
  dropTabPtr.p->m_requestType = DropTabReq::CreateTabDrop;
  dropTabPtr.p->m_coordinatorRef = createTabPtr.p->m_coordinatorRef;
  dropTabPtr.p->m_participantData.m_gsn = GSN_DROP_TAB_REQ;
  
  dropTabPtr.p->m_participantData.m_block = 0;
  dropTabPtr.p->m_participantData.m_callback.m_callbackData = req->senderData;
  dropTabPtr.p->m_participantData.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::createTab_dropComplete);
  dropTab_nextStep(signal, dropTabPtr);  
5982 5983 5984 5985 5986 5987 5988

  if (tabPtr.p->m_tablespace_id != RNIL)
  {
    FilegroupPtr ptr;
    ndbrequire(c_filegroup_hash.find(ptr, tabPtr.p->m_tablespace_id));
    decrease_ref_count(ptr.p->m_obj_ptr_i);
  }
5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007
}

void
Dbdict::createTab_dropComplete(Signal* signal, 
			       Uint32 callbackData,
			       Uint32 returnCode){
  jam();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, callbackData));
  
  DropTableRecordPtr dropTabPtr;
  ndbrequire(c_opDropTable.find(dropTabPtr, callbackData));

  TableRecordPtr tabPtr;
  c_tableRecordPool.getPtr(tabPtr, createTabPtr.p->m_tablePtrI);
  
  releaseTableObject(tabPtr.i);

6008 6009
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry * tableEntry = getTableEntry(xsf, tabPtr.i);
6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022
  tableEntry->m_tableState = SchemaFile::DROP_TABLE_COMMITTED;
  
  //@todo check error
  //@todo check master failed
  
  CreateTabConf * const conf = (CreateTabConf*)signal->getDataPtr();
  conf->senderRef = reference();
  conf->senderData = createTabPtr.p->key;
  sendSignal(createTabPtr.p->m_coordinatorRef, GSN_CREATE_TAB_CONF,
	     signal, CreateTabConf::SignalLength, JBB);

  if(createTabPtr.p->m_coordinatorRef != reference()){
    jam();
6023
    releaseCreateTableOp(signal,createTabPtr);
6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060
  }

  c_opDropTable.release(dropTabPtr);
}

void
Dbdict::alterTab_activate(Signal* signal, CreateTableRecordPtr createTabPtr,
			  Callback * c){

  createTabPtr.p->m_callback = * c;
  
  signal->theData[0] = createTabPtr.p->key;
  signal->theData[1] = reference();
  signal->theData[2] = createTabPtr.p->m_tablePtrI;
  sendSignal(DBDIH_REF, GSN_TAB_COMMITREQ, signal, 3, JBB);
}

void
Dbdict::execTC_SCHVERCONF(Signal* signal){
  jamEntry();

  CreateTableRecordPtr createTabPtr;  
  ndbrequire(c_opCreateTable.find(createTabPtr, signal->theData[1]));

  execute(signal, createTabPtr.p->m_callback, 0);
}

#define tabRequire(cond, error) \
  if (!(cond)) { \
    jam();    \
    parseP->errorCode = error; parseP->errorLine = __LINE__; \
    parseP->errorKey = it.getKey(); \
    return;   \
  }//if

// handleAddTableFailure(signal, __LINE__, allocatedTable);

6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096
Dbdict::DictObject *
Dbdict::get_object(const char * name, Uint32 len, Uint32 hash){
  DictObject key;
  key.m_key.m_name_ptr = name;
  key.m_key.m_name_len = len;
  key.m_key.m_pool = &c_rope_pool;
  key.m_name.m_hash = hash;
  Ptr<DictObject> old_ptr;
  c_obj_hash.find(old_ptr, key);
  return old_ptr.p;
}

void
Dbdict::release_object(Uint32 obj_ptr_i, DictObject* obj_ptr_p){
  Rope name(c_rope_pool, obj_ptr_p->m_name);
  name.erase();

  Ptr<DictObject> ptr = { obj_ptr_p, obj_ptr_i };
  c_obj_hash.release(ptr);
}

void
Dbdict::increase_ref_count(Uint32 obj_ptr_i)
{
  DictObject* ptr = c_obj_pool.getPtr(obj_ptr_i);
  ptr->m_ref_count++;  
}

void
Dbdict::decrease_ref_count(Uint32 obj_ptr_i)
{
  DictObject* ptr = c_obj_pool.getPtr(obj_ptr_i);
  ndbrequire(ptr->m_ref_count);
  ptr->m_ref_count--;  
}

6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109
void Dbdict::handleTabInfoInit(SimpleProperties::Reader & it,
			       ParseDictTabInfoRecord * parseP,
			       bool checkExist) 
{
/* ---------------------------------------------------------------- */
// We always start by handling table name since this must be the first
// item in the list. Through the table name we can derive if it is a
// correct name, a new name or an already existing table.
/* ---------------------------------------------------------------- */

  it.first();

  SimpleProperties::UnpackStatus status;
6110 6111
  c_tableDesc.init();
  status = SimpleProperties::unpack(it, &c_tableDesc, 
6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122
				    DictTabInfo::TableMapping, 
				    DictTabInfo::TableMappingSize, 
				    true, true);
  
  if(status != SimpleProperties::Break){
    parseP->errorCode = CreateTableRef::InvalidFormat;
    parseP->status    = status;
    parseP->errorKey  = it.getKey();
    parseP->errorLine = __LINE__;
    return;
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
6123 6124 6125 6126 6127 6128 6129 6130 6131

  if(parseP->requestType == DictTabInfo::AlterTableFromAPI)
  {  
    ndbrequire(!checkExist);
  }
  if(!checkExist)
  {
    ndbrequire(parseP->requestType == DictTabInfo::AlterTableFromAPI);
  }
6132 6133 6134 6135 6136
  
  /* ---------------------------------------------------------------- */
  // Verify that table name is an allowed table name.
  // TODO
  /* ---------------------------------------------------------------- */
6137 6138
  const Uint32 tableNameLength = strlen(c_tableDesc.TableName) + 1;
  const Uint32 name_hash = Rope::hash(c_tableDesc.TableName, tableNameLength);
6139

6140
  if(checkExist){
6141
    jam();
6142
    tabRequire(get_object(c_tableDesc.TableName, tableNameLength) == 0, 
6143
	       CreateTableRef::TableAlreadyExist);
joreland@mysql.com's avatar
joreland@mysql.com committed
6144
  }
6145 6146
  
  TableRecordPtr tablePtr;
6147 6148 6149 6150 6151 6152
  switch (parseP->requestType) {
  case DictTabInfo::CreateTableFromAPI: {
    jam();
  }
  case DictTabInfo::AlterTableFromAPI:{
    jam();
6153
    tablePtr.i = getFreeTableRecord(c_tableDesc.PrimaryTableId);
6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168
    /* ---------------------------------------------------------------- */
    // Check if no free tables existed.
    /* ---------------------------------------------------------------- */
    tabRequire(tablePtr.i != RNIL, CreateTableRef::NoMoreTableRecords);
    
    c_tableRecordPool.getPtr(tablePtr);
    break;
  }
  case DictTabInfo::AddTableFromDict:
  case DictTabInfo::ReadTableFromDiskSR:
  case DictTabInfo::GetTabInfoConf:
  {
/* ---------------------------------------------------------------- */
// Get table id and check that table doesn't already exist
/* ---------------------------------------------------------------- */
6169
    tablePtr.i = c_tableDesc.TableId;
6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186
    
    if (parseP->requestType == DictTabInfo::ReadTableFromDiskSR) {
      ndbrequire(tablePtr.i == c_restartRecord.activeTable);
    }//if
    if (parseP->requestType == DictTabInfo::GetTabInfoConf) {
      ndbrequire(tablePtr.i == c_restartRecord.activeTable);
    }//if
    
    c_tableRecordPool.getPtr(tablePtr);
    ndbrequire(tablePtr.p->tabState == TableRecord::NOT_DEFINED);
    
    //Uint32 oldTableVersion = tablePtr.p->tableVersion;
    initialiseTableRecord(tablePtr);
    if (parseP->requestType == DictTabInfo::AddTableFromDict) {
      jam();
      tablePtr.p->tabState = TableRecord::DEFINING;
    }//if
6187

6188 6189 6190
/* ---------------------------------------------------------------- */
// Set table version
/* ---------------------------------------------------------------- */
6191
    Uint32 tableVersion = c_tableDesc.TableVersion;
6192 6193 6194 6195 6196 6197 6198 6199 6200 6201
    tablePtr.p->tableVersion = tableVersion;
    
    break;
  }
  default:
    ndbrequire(false);
    break;
  }//switch
  parseP->tablePtr = tablePtr;
  
6202 6203
  { 
    Rope name(c_rope_pool, tablePtr.p->tableName);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
6204
    tabRequire(name.assign(c_tableDesc.TableName, tableNameLength, name_hash),
6205
	       CreateTableRef::OutOfStringBuffer);
6206 6207 6208
  }

  Ptr<DictObject> obj_ptr;
6209 6210
  if (parseP->requestType != DictTabInfo::AlterTableFromAPI) {
    jam();
6211 6212
    ndbrequire(c_obj_hash.seize(obj_ptr));
    obj_ptr.p->m_id = tablePtr.i;
6213
    obj_ptr.p->m_type = c_tableDesc.TableType;
6214 6215 6216 6217 6218
    obj_ptr.p->m_name = tablePtr.p->tableName;
    obj_ptr.p->m_ref_count = 0;
    c_obj_hash.add(obj_ptr);
    tablePtr.p->m_obj_ptr_i = obj_ptr.i;

6219
#ifdef VM_TRACE
6220
    ndbout_c("Dbdict: name=%s,id=%u,obj_ptr_i=%d", 
6221
	     c_tableDesc.TableName, tablePtr.i, tablePtr.p->m_obj_ptr_i);
6222
#endif
joreland@mysql.com's avatar
joreland@mysql.com committed
6223
  }
6224
  
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
6225 6226 6227 6228
  // Disallow logging of a temporary table.
  tabRequire(!(c_tableDesc.TableTemporaryFlag && c_tableDesc.TableLoggedFlag),
             CreateTableRef::NoLoggingTemporaryTable);

6229
  tablePtr.p->noOfAttributes = c_tableDesc.NoOfAttributes;
6230
  tablePtr.p->m_bits |= 
6231
    (c_tableDesc.TableLoggedFlag ? TableRecord::TR_Logged : 0);
6232
  tablePtr.p->m_bits |= 
6233
    (c_tableDesc.RowChecksumFlag ? TableRecord::TR_RowChecksum : 0);
6234
  tablePtr.p->m_bits |= 
6235
    (c_tableDesc.RowGCIFlag ? TableRecord::TR_RowGCI : 0);
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
6236 6237
  tablePtr.p->m_bits |= 
    (c_tableDesc.TableTemporaryFlag ? TableRecord::TR_Temporary : 0);
6238 6239
  tablePtr.p->m_bits |=
    (c_tableDesc.ForceVarPartFlag ? TableRecord::TR_ForceVarPart : 0);
6240 6241 6242 6243 6244 6245 6246 6247 6248
  tablePtr.p->minLoadFactor = c_tableDesc.MinLoadFactor;
  tablePtr.p->maxLoadFactor = c_tableDesc.MaxLoadFactor;
  tablePtr.p->fragmentType = (DictTabInfo::FragmentType)c_tableDesc.FragmentType;
  tablePtr.p->tableType = (DictTabInfo::TableType)c_tableDesc.TableType;
  tablePtr.p->kValue = c_tableDesc.TableKValue;
  tablePtr.p->fragmentCount = c_tableDesc.FragmentCount;
  tablePtr.p->m_tablespace_id = c_tableDesc.TablespaceId; 
  tablePtr.p->maxRowsLow = c_tableDesc.MaxRowsLow; 
  tablePtr.p->maxRowsHigh = c_tableDesc.MaxRowsHigh; 
6249 6250
  tablePtr.p->minRowsLow = c_tableDesc.MinRowsLow;
  tablePtr.p->minRowsHigh = c_tableDesc.MinRowsHigh;
6251
  tablePtr.p->defaultNoPartFlag = c_tableDesc.DefaultNoPartFlag; 
6252
  tablePtr.p->linearHashFlag = c_tableDesc.LinearHashFlag; 
6253
  tablePtr.p->singleUserMode = c_tableDesc.SingleUserMode;
6254 6255 6256
  
  {
    Rope frm(c_rope_pool, tablePtr.p->frmData);
6257 6258
    tabRequire(frm.assign(c_tableDesc.FrmData, c_tableDesc.FrmLen),
	       CreateTableRef::OutOfStringBuffer);
6259
    Rope range(c_rope_pool, tablePtr.p->rangeData);
6260 6261 6262
    tabRequire(range.assign(c_tableDesc.RangeListData,
               c_tableDesc.RangeListDataLen),
	      CreateTableRef::OutOfStringBuffer);
6263
    Rope fd(c_rope_pool, tablePtr.p->ngData);
6264 6265 6266
    tabRequire(fd.assign((const char*)c_tableDesc.FragmentData,
                         c_tableDesc.FragmentDataLen),
	       CreateTableRef::OutOfStringBuffer);
6267
    Rope ts(c_rope_pool, tablePtr.p->tsData);
6268 6269
    tabRequire(ts.assign((const char*)c_tableDesc.TablespaceData,
                         c_tableDesc.TablespaceDataLen),
6270
	       CreateTableRef::OutOfStringBuffer);
6271 6272 6273 6274 6275 6276 6277
  }
  
  c_fragDataLen = c_tableDesc.FragmentDataLen;
  memcpy(c_fragData, c_tableDesc.FragmentData,
         c_tableDesc.FragmentDataLen);

  if(c_tableDesc.PrimaryTableId != RNIL) {
6278
    
6279 6280 6281 6282 6283 6284
    tablePtr.p->primaryTableId = c_tableDesc.PrimaryTableId;
    tablePtr.p->indexState = (TableRecord::IndexState)c_tableDesc.IndexState;
    tablePtr.p->insertTriggerId = c_tableDesc.InsertTriggerId;
    tablePtr.p->updateTriggerId = c_tableDesc.UpdateTriggerId;
    tablePtr.p->deleteTriggerId = c_tableDesc.DeleteTriggerId;
    tablePtr.p->customTriggerId = c_tableDesc.CustomTriggerId;
6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295
  } else {
    tablePtr.p->primaryTableId = RNIL;
    tablePtr.p->indexState = TableRecord::IS_UNDEFINED;
    tablePtr.p->insertTriggerId = RNIL;
    tablePtr.p->updateTriggerId = RNIL;
    tablePtr.p->deleteTriggerId = RNIL;
    tablePtr.p->customTriggerId = RNIL;
  }
  tablePtr.p->buildTriggerId = RNIL;
  tablePtr.p->indexLocal = 0;
  
6296
  handleTabInfo(it, parseP, c_tableDesc);
6297
  
joreland@mysql.com's avatar
joreland@mysql.com committed
6298 6299
  if(parseP->errorCode != 0)
  {
6300 6301 6302
    /**
     * Release table
     */
6303
    releaseTableObject(tablePtr.i, checkExist);
6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314
    return;
  }

  if (checkExist && tablePtr.p->m_tablespace_id != RNIL)
  {
    /**
     * Increase ref count
     */
    FilegroupPtr ptr;
    ndbrequire(c_filegroup_hash.find(ptr, tablePtr.p->m_tablespace_id));
    increase_ref_count(ptr.p->m_obj_ptr_i);
6315 6316 6317 6318
  }
}//handleTabInfoInit()

void Dbdict::handleTabInfo(SimpleProperties::Reader & it,
6319
			   ParseDictTabInfoRecord * parseP,
6320
			   DictTabInfo::Table &tableDesc)
6321 6322 6323 6324 6325 6326 6327 6328 6329
{
  TableRecordPtr tablePtr = parseP->tablePtr;
  
  SimpleProperties::UnpackStatus status;
  
  Uint32 keyCount = 0;
  Uint32 keyLength = 0;
  Uint32 attrCount = tablePtr.p->noOfAttributes;
  Uint32 nullCount = 0;
6330
  Uint32 nullBits = 0;
6331 6332
  Uint32 noOfCharsets = 0;
  Uint16 charsets[128];
6333 6334 6335
  Uint32 recordLength = 0;
  AttributeRecordPtr attrPtr;
  c_attributeRecordHash.removeAll();
6336 6337 6338 6339 6340

  LocalDLFifoList<AttributeRecord> list(c_attributeRecordPool, 
					tablePtr.p->m_attributes);

  Uint32 counts[] = {0,0,0,0,0};
6341 6342 6343 6344 6345 6346 6347 6348 6349 6350
  
  for(Uint32 i = 0; i<attrCount; i++){
    /**
     * Attribute Name
     */
    DictTabInfo::Attribute attrDesc; attrDesc.init();
    status = SimpleProperties::unpack(it, &attrDesc, 
				      DictTabInfo::AttributeMapping, 
				      DictTabInfo::AttributeMappingSize, 
				      true, true);
6351
    
6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362
    if(status != SimpleProperties::Break){
      parseP->errorCode = CreateTableRef::InvalidFormat;
      parseP->status    = status;
      parseP->errorKey  = it.getKey();
      parseP->errorLine = __LINE__;
      return;
    }

    /**
     * Check that attribute is not defined twice
     */
6363 6364
    const size_t len = strlen(attrDesc.AttributeName)+1;
    const Uint32 name_hash = Rope::hash(attrDesc.AttributeName, len);
6365
    {
6366 6367 6368 6369 6370 6371 6372
      AttributeRecord key;
      key.m_key.m_name_ptr = attrDesc.AttributeName;
      key.m_key.m_name_len = len;
      key.attributeName.m_hash = name_hash;
      key.m_key.m_pool = &c_rope_pool;
      Ptr<AttributeRecord> old_ptr;
      c_attributeRecordHash.find(old_ptr, key);
6373
      
6374
      if(old_ptr.i != RNIL){
6375 6376 6377 6378 6379
	parseP->errorCode = CreateTableRef::AttributeNameTwice;
	return;
      }
    }
    
6380 6381
    list.seize(attrPtr);
    if(attrPtr.i == RNIL){
6382 6383 6384 6385 6386
      jam();
      parseP->errorCode = CreateTableRef::NoMoreAttributeRecords;
      return;
    }
    
6387 6388 6389 6390
    new (attrPtr.p) AttributeRecord();
    attrPtr.p->attributeDescriptor = 0x00012255; //Default value
    attrPtr.p->tupleKey = 0;
    
6391 6392 6393
    /**
     * TmpAttrib to Attribute mapping
     */
6394 6395
    {
      Rope name(c_rope_pool, attrPtr.p->attributeName);
6396 6397 6398 6399 6400 6401 6402
      if (!name.assign(attrDesc.AttributeName, len, name_hash))
      {
	jam();
	parseP->errorCode = CreateTableRef::OutOfStringBuffer;
	parseP->errorLine = __LINE__;
	return;
      }
6403 6404 6405
    }
    attrPtr.p->attributeId = i;
    //attrPtr.p->attributeId = attrDesc.AttributeId;
6406
    attrPtr.p->tupleKey = (keyCount + 1) * attrDesc.AttributeKeyFlag;
6407
    
6408 6409 6410
    attrPtr.p->extPrecision = attrDesc.AttributeExtPrecision;
    attrPtr.p->extScale = attrDesc.AttributeExtScale;
    attrPtr.p->extLength = attrDesc.AttributeExtLength;
6411 6412 6413
    // charset in upper half of precision
    unsigned csNumber = (attrPtr.p->extPrecision >> 16);
    if (csNumber != 0) {
6414 6415 6416 6417
      /*
       * A new charset is first accessed here on this node.
       * TODO use separate thread (e.g. via NDBFS) if need to load from file
       */
6418 6419 6420 6421 6422 6423
      CHARSET_INFO* cs = get_charset(csNumber, MYF(0));
      if (cs == NULL) {
        parseP->errorCode = CreateTableRef::InvalidCharset;
        parseP->errorLine = __LINE__;
        return;
      }
6424 6425
      // XXX should be done somewhere in mysql
      all_charsets[cs->number] = cs;
6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441
      unsigned i = 0;
      while (i < noOfCharsets) {
        if (charsets[i] == csNumber)
          break;
        i++;
      }
      if (i == noOfCharsets) {
        noOfCharsets++;
        if (noOfCharsets > sizeof(charsets)/sizeof(charsets[0])) {
          parseP->errorCode = CreateTableRef::InvalidFormat;
          parseP->errorLine = __LINE__;
          return;
        }
        charsets[i] = csNumber;
      }
    }
6442

pekka@mysql.com's avatar
pekka@mysql.com committed
6443
    // compute attribute size and array size
6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454
    bool translateOk = attrDesc.translateExtType();
    tabRequire(translateOk, CreateTableRef::Inconsistency);

    if(attrDesc.AttributeArraySize > 65535){
      parseP->errorCode = CreateTableRef::ArraySizeTooBig;
      parseP->status    = status;
      parseP->errorKey  = it.getKey();
      parseP->errorLine = __LINE__;
      return;
    }
    
6455 6456 6457 6458 6459 6460 6461 6462
    // XXX old test option, remove
    if(!attrDesc.AttributeKeyFlag && 
       tablePtr.i > 1 &&
       !tablePtr.p->isIndex())
    {
      //attrDesc.AttributeStorageType= NDB_STORAGETYPE_DISK;
    }

6463
    Uint32 desc = 0;
6464
    AttributeDescriptor::setType(desc, attrDesc.AttributeExtType);
6465
    AttributeDescriptor::setSize(desc, attrDesc.AttributeSize);
6466 6467
    AttributeDescriptor::setArraySize(desc, attrDesc.AttributeArraySize);
    AttributeDescriptor::setArrayType(desc, attrDesc.AttributeArrayType);
6468 6469 6470
    AttributeDescriptor::setNullable(desc, attrDesc.AttributeNullableFlag);
    AttributeDescriptor::setDKey(desc, attrDesc.AttributeDKey);
    AttributeDescriptor::setPrimaryKey(desc, attrDesc.AttributeKeyFlag);
6471
    AttributeDescriptor::setDiskBased(desc, attrDesc.AttributeStorageType == NDB_STORAGETYPE_DISK);
6472 6473
    attrPtr.p->attributeDescriptor = desc;
    attrPtr.p->autoIncrement = attrDesc.AttributeAutoIncrement;
6474 6475 6476 6477
    {
      Rope defaultValue(c_rope_pool, attrPtr.p->defaultValue);
      defaultValue.assign(attrDesc.AttributeDefaultValue);
    }
6478 6479 6480 6481 6482
    
    keyCount += attrDesc.AttributeKeyFlag;
    nullCount += attrDesc.AttributeNullableFlag;
    
    const Uint32 aSz = (1 << attrDesc.AttributeSize);
6483 6484 6485 6486 6487 6488 6489 6490
    Uint32 sz;
    if(aSz != 1)
    {
      sz = ((aSz * attrDesc.AttributeArraySize) + 31) >> 5;
    }    
    else
    {
      sz = 0;
6491
      nullBits += attrDesc.AttributeArraySize;      
6492
    }
6493
    
6494 6495 6496 6497 6498 6499 6500 6501 6502
    if(attrDesc.AttributeArraySize == 0)
    {
      parseP->errorCode = CreateTableRef::InvalidArraySize;
      parseP->status    = status;
      parseP->errorKey  = it.getKey();
      parseP->errorLine = __LINE__;
      return;
    }
    
6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515
    recordLength += sz;
    if(attrDesc.AttributeKeyFlag){
      keyLength += sz;

      if(attrDesc.AttributeNullableFlag){
	parseP->errorCode = CreateTableRef::NullablePrimaryKey;
	parseP->status    = status;
	parseP->errorKey  = it.getKey();
	parseP->errorLine = __LINE__;
	return;
      }
    }
    
6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530
    c_attributeRecordHash.add(attrPtr);

    int a= AttributeDescriptor::getDiskBased(desc);
    int b= AttributeDescriptor::getArrayType(desc);
    Uint32 pos= 2*(a ? 1 : 0) + (b == NDB_ARRAYTYPE_FIXED ? 0 : 1);
    counts[pos+1]++;

    if(b != NDB_ARRAYTYPE_FIXED && sz == 0)
    {
      parseP->errorCode = CreateTableRef::VarsizeBitfieldNotSupported;
      parseP->status    = status;
      parseP->errorKey  = it.getKey();
      parseP->errorLine = __LINE__;
      return;
    }
6531 6532 6533 6534 6535 6536 6537 6538 6539 6540
    
    if(!it.next())
      break;
    
    if(it.getKey() != DictTabInfo::AttributeName)
      break;
  }//while
  
  tablePtr.p->noOfPrimkey = keyCount;
  tablePtr.p->noOfNullAttr = nullCount;
6541
  tablePtr.p->noOfCharsets = noOfCharsets;
6542
  tablePtr.p->tupKeyLength = keyLength;
6543
  tablePtr.p->noOfNullBits = nullCount + nullBits;
6544 6545 6546 6547 6548 6549 6550

  tabRequire(recordLength<= MAX_TUPLE_SIZE_IN_WORDS, 
	     CreateTableRef::RecordTooBig);
  tabRequire(keyLength <= MAX_KEY_SIZE_IN_WORDS, 
	     CreateTableRef::InvalidPrimaryKeySize);
  tabRequire(keyLength > 0, 
	     CreateTableRef::InvalidPrimaryKeySize);
6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564

  if(tablePtr.p->m_tablespace_id != RNIL || counts[3] || counts[4])
  {
    FilegroupPtr tablespacePtr;
    if(!c_filegroup_hash.find(tablespacePtr, tablePtr.p->m_tablespace_id))
    {
      tabRequire(false, CreateTableRef::InvalidTablespace);
    }
    
    if(tablespacePtr.p->m_type != DictTabInfo::Tablespace)
    {
      tabRequire(false, CreateTableRef::NotATablespace);
    }
    
6565
    if(tablespacePtr.p->m_version != tableDesc.TablespaceVersion)
6566 6567 6568
    {
      tabRequire(false, CreateTableRef::InvalidTablespaceVersion);
    }
6569
  }
6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634
}//handleTabInfo()


/* ---------------------------------------------------------------- */
// DICTTABCONF is sent when participants have received all DICTTABINFO
// and successfully handled it.
// Also sent to self (DICT master) when index table creation ready.
/* ---------------------------------------------------------------- */
void Dbdict::execCREATE_TABLE_CONF(Signal* signal) 
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);

  CreateTableConf * const conf = (CreateTableConf *)signal->getDataPtr();
  // assume part of create index operation
  OpCreateIndexPtr opPtr;
  c_opCreateIndex.find(opPtr, conf->senderData);
  ndbrequire(! opPtr.isNull());
  opPtr.p->m_request.setIndexId(conf->tableId);
  opPtr.p->m_request.setIndexVersion(conf->tableVersion);
  createIndex_fromCreateTable(signal, opPtr);
}//execCREATE_TABLE_CONF()

void Dbdict::execCREATE_TABLE_REF(Signal* signal) 
{
  jamEntry();

  CreateTableRef * const ref = (CreateTableRef *)signal->getDataPtr();
  // assume part of create index operation
  OpCreateIndexPtr opPtr;
  c_opCreateIndex.find(opPtr, ref->senderData);
  ndbrequire(! opPtr.isNull());
  opPtr.p->setError(ref);
  createIndex_fromCreateTable(signal, opPtr);
}//execCREATE_TABLE_REF()

/* ---------------------------------------------------------------- */
// New global checkpoint created.
/* ---------------------------------------------------------------- */
void Dbdict::execWAIT_GCP_CONF(Signal* signal) 
{
#if 0
  TableRecordPtr tablePtr;
  jamEntry();
  WaitGCPConf* const conf = (WaitGCPConf*)&signal->theData[0];
  c_tableRecordPool.getPtr(tablePtr, c_connRecord.connTableId);
  tablePtr.p->gciTableCreated = conf->gcp;
  sendUpdateSchemaState(signal,
                        tablePtr.i,
                        SchemaFile::TABLE_ADD_COMMITTED,
                        c_connRecord.noOfPagesForTable,
                        conf->gcp);
#endif
}//execWAIT_GCP_CONF()

/* ---------------------------------------------------------------- */
// Refused new global checkpoint.
/* ---------------------------------------------------------------- */
void Dbdict::execWAIT_GCP_REF(Signal* signal) 
{
  jamEntry();
  WaitGCPRef* const ref = (WaitGCPRef*)&signal->theData[0];
/* ---------------------------------------------------------------- */
// Error Handling code needed
/* ---------------------------------------------------------------- */
6635 6636 6637 6638
  char buf[32];
  BaseString::snprintf(buf, sizeof(buf), "WAIT_GCP_REF ErrorCode=%d",
		       ref->errorCode);
  progError(__LINE__, NDBD_EXIT_NDBREQUIRE, buf);
6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668
}//execWAIT_GCP_REF()


/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          DROP TABLE                 -------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains the code used to drop a table.              */
/* ---------------------------------------------------------------- */
/* **************************************************************** */
void
Dbdict::execDROP_TABLE_REQ(Signal* signal){
  jamEntry();
  DropTableReq* req = (DropTableReq*)signal->getDataPtr();

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, req->tableId, false);
  if(tablePtr.isNull()){
    jam();
    dropTableRef(signal, req, DropTableRef::NoSuchTable);
    return;
  }

  if(getOwnNodeId() != c_masterNodeId){
    jam();
    dropTableRef(signal, req, DropTableRef::NotMaster);
    return;
  }

6669 6670 6671 6672 6673 6674
  if(c_blockState == BS_NODE_RESTART){
    jam();
    dropTableRef(signal, req, DropTableRef::BusyWithNR);
    return;
  }

6675 6676 6677 6678 6679 6680
  if(c_blockState != BS_IDLE){
    jam();
    dropTableRef(signal, req, DropTableRef::Busy);
    return;
  }
  
6681
  if (checkSingleUserMode(signal->getSendersBlockRef()))
6682 6683 6684 6685 6686 6687
  {
    jam();
    dropTableRef(signal, req, DropTableRef::SingleUser);
    return;
  }

6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706
  const TableRecord::TabState tabState = tablePtr.p->tabState;
  bool ok = false;
  switch(tabState){
  case TableRecord::NOT_DEFINED:
  case TableRecord::REORG_TABLE_PREPARED:
  case TableRecord::DEFINING:
  case TableRecord::CHECKED:
    jam();
    dropTableRef(signal, req, DropTableRef::NoSuchTable);
    return;
  case TableRecord::DEFINED:
    ok = true;
    jam();
    break;
  case TableRecord::PREPARE_DROPPING:
  case TableRecord::DROPPING:
    jam();
    dropTableRef(signal, req, DropTableRef::DropInProgress);
    return;
joreland@mysql.com's avatar
joreland@mysql.com committed
6707 6708 6709 6710
  case TableRecord::BACKUP_ONGOING:
    jam();
    dropTableRef(signal, req, DropTableRef::BackupInProgress);
    return;
6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742
  }
  ndbrequire(ok);

  if(tablePtr.p->tableVersion != req->tableVersion){
    jam();
    dropTableRef(signal, req, DropTableRef::InvalidTableVersion);
    return;
  }

  /**
   * Seems ok
   */
  DropTableRecordPtr dropTabPtr;
  c_opDropTable.seize(dropTabPtr);
  
  if(dropTabPtr.isNull()){
    jam();
    dropTableRef(signal, req, DropTableRef::NoDropTableRecordAvailable);
    return;
  }

  c_blockState = BS_BUSY;
  
  dropTabPtr.p->key = ++c_opRecordSequence;
  c_opDropTable.add(dropTabPtr);

  dropTabPtr.p->m_request = * req;
  dropTabPtr.p->m_errorCode = 0;
  dropTabPtr.p->m_requestType = DropTabReq::OnlineDropTab;
  dropTabPtr.p->m_coordinatorRef = reference();
  dropTabPtr.p->m_coordinatorData.m_gsn = GSN_PREP_DROP_TAB_REQ;
  dropTabPtr.p->m_coordinatorData.m_block = 0;
joreland@mysql.com's avatar
joreland@mysql.com committed
6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783
  
  Mutex mutex(signal, c_mutexMgr, dropTabPtr.p->m_define_backup_mutex);
  Callback c = { safe_cast(&Dbdict::dropTable_backup_mutex_locked),
		 dropTabPtr.p->key};
  
  ndbrequire(mutex.lock(c));

}

void
Dbdict::dropTable_backup_mutex_locked(Signal* signal, 
				      Uint32 callbackData,
				      Uint32 retValue){
  jamEntry();
  
  ndbrequire(retValue == 0);
  
  DropTableRecordPtr dropTabPtr;
  ndbrequire(c_opDropTable.find(dropTabPtr, callbackData));
  
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, dropTabPtr.p->m_request.tableId, true);
  
  Mutex mutex(signal, c_mutexMgr, dropTabPtr.p->m_define_backup_mutex);
  mutex.unlock(); // ignore response
  
  if(tablePtr.p->tabState == TableRecord::BACKUP_ONGOING)
  {
    jam();
    dropTableRef(signal, &dropTabPtr.p->m_request,
		 DropTableRef::BackupInProgress);
    
    c_blockState = BS_IDLE;
    c_opDropTable.release(dropTabPtr);
  }
  else
  {
    jam();
    tablePtr.p->tabState = TableRecord::PREPARE_DROPPING;
    prepDropTab_nextStep(signal, dropTabPtr);
  }
6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900
}

void
Dbdict::dropTableRef(Signal * signal, 
		     DropTableReq * req, DropTableRef::ErrorCode errCode){

  Uint32 tableId = req->tableId;
  Uint32 tabVersion = req->tableVersion;
  Uint32 senderData = req->senderData;
  Uint32 senderRef = req->senderRef;
  
  DropTableRef * ref = (DropTableRef*)signal->getDataPtrSend();
  ref->tableId = tableId;
  ref->tableVersion = tabVersion;
  ref->senderData = senderData;
  ref->senderRef = reference();
  ref->errorCode = errCode;
  ref->masterNodeId = c_masterNodeId;
  sendSignal(senderRef, GSN_DROP_TABLE_REF, signal, 
	     DropTableRef::SignalLength, JBB);
}

void
Dbdict::prepDropTab_nextStep(Signal* signal, DropTableRecordPtr dropTabPtr){
  
  /**
   * No errors currently allowed
   */
  ndbrequire(dropTabPtr.p->m_errorCode == 0);

  Uint32 block = 0;
  switch(dropTabPtr.p->m_coordinatorData.m_block){
  case 0:
    jam();
    block = dropTabPtr.p->m_coordinatorData.m_block = DBDICT;
    break;
  case DBDICT:
    jam();
    block = dropTabPtr.p->m_coordinatorData.m_block = DBLQH;
    break;
  case DBLQH:
    jam();
    block = dropTabPtr.p->m_coordinatorData.m_block = DBTC;
    break;
  case DBTC:
    jam();
    block = dropTabPtr.p->m_coordinatorData.m_block = DBDIH;
    break;
  case DBDIH:
    jam();
    prepDropTab_complete(signal, dropTabPtr);
    return;
  default:
    ndbrequire(false);
  }

  PrepDropTabReq * prep = (PrepDropTabReq*)signal->getDataPtrSend();
  prep->senderRef = reference();
  prep->senderData = dropTabPtr.p->key;
  prep->tableId = dropTabPtr.p->m_request.tableId;
  prep->requestType = dropTabPtr.p->m_requestType;
  
  dropTabPtr.p->m_coordinatorData.m_signalCounter = c_aliveNodes;
  NodeReceiverGroup rg(block, c_aliveNodes);
  sendSignal(rg, GSN_PREP_DROP_TAB_REQ, signal, 
	     PrepDropTabReq::SignalLength, JBB);
  
#if 0  
  for (Uint32 i = 1; i < MAX_NDB_NODES; i++){
    if(c_aliveNodes.get(i)){
      jam();
      BlockReference ref = numberToRef(block, i);
      
      dropTabPtr.p->m_coordinatorData.m_signalCounter.setWaitingFor(i);
    }
  }
#endif
}

void
Dbdict::execPREP_DROP_TAB_CONF(Signal * signal){
  jamEntry();

  PrepDropTabConf * prep = (PrepDropTabConf*)signal->getDataPtr();

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, prep->senderData));
  
  ndbrequire(dropTabPtr.p->m_coordinatorRef == reference());
  ndbrequire(dropTabPtr.p->m_request.tableId == prep->tableId);
  ndbrequire(dropTabPtr.p->m_coordinatorData.m_gsn == GSN_PREP_DROP_TAB_REQ);
  
  Uint32 nodeId = refToNode(prep->senderRef);
  dropTabPtr.p->m_coordinatorData.m_signalCounter.clearWaitingFor(nodeId);
  
  if(!dropTabPtr.p->m_coordinatorData.m_signalCounter.done()){
    jam();
    return;
  }
  prepDropTab_nextStep(signal, dropTabPtr);
}

void
Dbdict::execPREP_DROP_TAB_REF(Signal* signal){
  jamEntry();

  PrepDropTabRef * prep = (PrepDropTabRef*)signal->getDataPtr();

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, prep->senderData));
  
  ndbrequire(dropTabPtr.p->m_coordinatorRef == reference());
  ndbrequire(dropTabPtr.p->m_request.tableId == prep->tableId);
  ndbrequire(dropTabPtr.p->m_coordinatorData.m_gsn == GSN_PREP_DROP_TAB_REQ);
  
  Uint32 nodeId = refToNode(prep->senderRef);
  dropTabPtr.p->m_coordinatorData.m_signalCounter.clearWaitingFor(nodeId);
joreland@mysql.com's avatar
joreland@mysql.com committed
6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914
  
  Uint32 block = refToBlock(prep->senderRef);
  if((prep->errorCode == PrepDropTabRef::NoSuchTable && block == DBLQH) ||
     (prep->errorCode == PrepDropTabRef::NF_FakeErrorREF)){
    jam();
    /**
     * Ignore errors:
     * 1) no such table and LQH, it might not exists in different LQH's
     * 2) node failure...
     */
  } else {
    dropTabPtr.p->setErrorCode((Uint32)prep->errorCode);
  }
  
6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944
  if(!dropTabPtr.p->m_coordinatorData.m_signalCounter.done()){
    jam();
    return;
  }
  prepDropTab_nextStep(signal, dropTabPtr);
}

void
Dbdict::prepDropTab_complete(Signal* signal, DropTableRecordPtr dropTabPtr){
  jam();

  dropTabPtr.p->m_coordinatorData.m_gsn = GSN_DROP_TAB_REQ;
  dropTabPtr.p->m_coordinatorData.m_block = DBDICT;
  
  DropTabReq * req = (DropTabReq*)signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = dropTabPtr.p->key;
  req->tableId = dropTabPtr.p->m_request.tableId;
  req->requestType = dropTabPtr.p->m_requestType;

  dropTabPtr.p->m_coordinatorData.m_signalCounter = c_aliveNodes;
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
  sendSignal(rg, GSN_DROP_TAB_REQ, signal, 
	     DropTabReq::SignalLength, JBB);
}

void
Dbdict::execDROP_TAB_REF(Signal* signal){
  jamEntry();

joreland@mysql.com's avatar
joreland@mysql.com committed
6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957
  DropTabRef * const req = (DropTabRef*)signal->getDataPtr();

  Uint32 block = refToBlock(req->senderRef);
  ndbrequire(req->errorCode == DropTabRef::NF_FakeErrorREF ||
	     (req->errorCode == DropTabRef::NoSuchTable &&
	      (block == DBTUP || block == DBACC || block == DBLQH)));
  
  if(block != DBDICT){
    jam();
    ndbrequire(refToNode(req->senderRef) == getOwnNodeId());
    dropTab_localDROP_TAB_CONF(signal);
    return;
  }
6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038
  ndbrequire(false);
}

void
Dbdict::execDROP_TAB_CONF(Signal* signal){
  jamEntry();

  DropTabConf * const req = (DropTabConf*)signal->getDataPtr();

  if(refToBlock(req->senderRef) != DBDICT){
    jam();
    ndbrequire(refToNode(req->senderRef) == getOwnNodeId());
    dropTab_localDROP_TAB_CONF(signal);
    return;
  }

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, req->senderData));
  
  ndbrequire(dropTabPtr.p->m_coordinatorRef == reference());
  ndbrequire(dropTabPtr.p->m_request.tableId == req->tableId);
  ndbrequire(dropTabPtr.p->m_coordinatorData.m_gsn == GSN_DROP_TAB_REQ);

  Uint32 nodeId = refToNode(req->senderRef);
  dropTabPtr.p->m_coordinatorData.m_signalCounter.clearWaitingFor(nodeId);
  
  if(!dropTabPtr.p->m_coordinatorData.m_signalCounter.done()){
    jam();
    return;
  }
  
  DropTableConf* conf = (DropTableConf*)signal->getDataPtrSend();
  conf->senderRef = reference();
  conf->senderData = dropTabPtr.p->m_request.senderData;
  conf->tableId = dropTabPtr.p->m_request.tableId;
  conf->tableVersion = dropTabPtr.p->m_request.tableVersion;
  Uint32 ref = dropTabPtr.p->m_request.senderRef;
  sendSignal(ref, GSN_DROP_TABLE_CONF, signal, 
	     DropTableConf::SignalLength, JBB);

  c_opDropTable.release(dropTabPtr);
  c_blockState = BS_IDLE;
}

/**
 * DROP TABLE PARTICIPANT CODE
 */
void
Dbdict::execPREP_DROP_TAB_REQ(Signal* signal){
  jamEntry();
  PrepDropTabReq * prep = (PrepDropTabReq*)signal->getDataPtrSend();  

  DropTableRecordPtr dropTabPtr;  
  if(prep->senderRef == reference()){
    jam();
    ndbrequire(c_opDropTable.find(dropTabPtr, prep->senderData));
    ndbrequire(dropTabPtr.p->m_requestType == prep->requestType);
  } else {
    jam();
    c_opDropTable.seize(dropTabPtr);
    if(!dropTabPtr.isNull()){
      dropTabPtr.p->key = prep->senderData;
      c_opDropTable.add(dropTabPtr);
    }
  }
  
  ndbrequire(!dropTabPtr.isNull());

  dropTabPtr.p->m_errorCode = 0;
  dropTabPtr.p->m_request.tableId = prep->tableId;
  dropTabPtr.p->m_requestType = prep->requestType;
  dropTabPtr.p->m_coordinatorRef = prep->senderRef;
  dropTabPtr.p->m_participantData.m_gsn = GSN_PREP_DROP_TAB_REQ;

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, prep->tableId);
  tablePtr.p->tabState = TableRecord::PREPARE_DROPPING;
  
  /**
   * Modify schema
   */
7039 7040
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry * tableEntry = getTableEntry(xsf, tablePtr.i);
7041 7042 7043
  SchemaFile::TableState tabState = 
    (SchemaFile::TableState)tableEntry->m_tableState;
  ndbrequire(tabState == SchemaFile::TABLE_ADD_COMMITTED ||
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7044 7045
             tabState == SchemaFile::ALTER_TABLE_COMMITTED ||
             tabState == SchemaFile::TEMPORARY_TABLE_COMMITTED);
7046
  tableEntry->m_tableState   = SchemaFile::DROP_TABLE_STARTED;
7047
  computeChecksum(xsf, tablePtr.i / NDB_SF_PAGE_ENTRIES);
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068

  bool savetodisk = !(tablePtr.p->m_bits & TableRecord::TR_Temporary);
  Callback callback;
  callback.m_callbackData = dropTabPtr.p->key;
  callback.m_callbackFunction = safe_cast(&Dbdict::prepDropTab_writeSchemaConf);
  if (savetodisk)
  {
    ndbrequire(c_writeSchemaRecord.inUse == false);
    c_writeSchemaRecord.inUse = true;

    c_writeSchemaRecord.pageId = c_schemaRecord.schemaPage;
    c_writeSchemaRecord.newFile = false;
    c_writeSchemaRecord.firstPage = tablePtr.i / NDB_SF_PAGE_ENTRIES;
    c_writeSchemaRecord.noOfPages = 1;
    c_writeSchemaRecord.m_callback = callback;
    startWriteSchemaFile(signal);
  }
  else
  {
    execute(signal, callback, 0);
  }
7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119
}

void
Dbdict::prepDropTab_writeSchemaConf(Signal* signal, 
				    Uint32 dropTabPtrI,
				    Uint32 returnCode){
  jam();

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, dropTabPtrI));

  ndbrequire(dropTabPtr.p->m_participantData.m_gsn == GSN_PREP_DROP_TAB_REQ);
  
  /**
   * There probably should be node fail handlign here
   *
   * To check that coordinator hasn't died
   */
  
  PrepDropTabConf * prep = (PrepDropTabConf*)signal->getDataPtr();  
  prep->senderRef = reference();
  prep->senderData = dropTabPtrI;
  prep->tableId = dropTabPtr.p->m_request.tableId;
  
  dropTabPtr.p->m_participantData.m_gsn = GSN_PREP_DROP_TAB_CONF;
  sendSignal(dropTabPtr.p->m_coordinatorRef, GSN_PREP_DROP_TAB_CONF, signal, 
	     PrepDropTabConf::SignalLength, JBB);
}

void
Dbdict::execDROP_TAB_REQ(Signal* signal){
  jamEntry();
  DropTabReq * req = (DropTabReq*)signal->getDataPtrSend();  

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, req->senderData));

  ndbrequire(dropTabPtr.p->m_participantData.m_gsn == GSN_PREP_DROP_TAB_CONF);
  dropTabPtr.p->m_participantData.m_gsn = GSN_DROP_TAB_REQ;

  ndbrequire(dropTabPtr.p->m_requestType == req->requestType);

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, dropTabPtr.p->m_request.tableId);
  tablePtr.p->tabState = TableRecord::DROPPING;

  dropTabPtr.p->m_participantData.m_block = 0;
  dropTabPtr.p->m_participantData.m_callback.m_callbackData = dropTabPtr.p->key;
  dropTabPtr.p->m_participantData.m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropTab_complete);
  dropTab_nextStep(signal, dropTabPtr);  
7120 7121 7122 7123 7124 7125 7126

  if (tablePtr.p->m_tablespace_id != RNIL)
  {
    FilegroupPtr ptr;
    ndbrequire(c_filegroup_hash.find(ptr, tablePtr.p->m_tablespace_id));
    decrease_ref_count(ptr.p->m_obj_ptr_i);
  }
7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231
}

#include <DebuggerNames.hpp>

void
Dbdict::dropTab_nextStep(Signal* signal, DropTableRecordPtr dropTabPtr){

  /**
   * No errors currently allowed
   */
  ndbrequire(dropTabPtr.p->m_errorCode == 0);

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, dropTabPtr.p->m_request.tableId);

  Uint32 block = 0;
  switch(dropTabPtr.p->m_participantData.m_block){
  case 0:
    jam();
    block = DBTC;
    break;
  case DBTC:
    jam();
    if (tablePtr.p->isTable() || tablePtr.p->isHashIndex())
      block = DBACC;
    if (tablePtr.p->isOrderedIndex())
      block = DBTUP;
    break;
  case DBACC:
    jam();
    block = DBTUP;
    break;
  case DBTUP:
    jam();
    if (tablePtr.p->isTable() || tablePtr.p->isHashIndex())
      block = DBLQH;
    if (tablePtr.p->isOrderedIndex())
      block = DBTUX;
    break;
  case DBTUX:
    jam();
    block = DBLQH;
    break;
  case DBLQH:
    jam();
    block = DBDIH;
    break;
  case DBDIH:
    jam();
    execute(signal, dropTabPtr.p->m_participantData.m_callback, 0);
    return;
  }
  ndbrequire(block != 0);
  dropTabPtr.p->m_participantData.m_block = block;

  DropTabReq * req = (DropTabReq*)signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = dropTabPtr.p->key;
  req->tableId = dropTabPtr.p->m_request.tableId;
  req->requestType = dropTabPtr.p->m_requestType;
  
  const Uint32 nodeId = getOwnNodeId();
  dropTabPtr.p->m_participantData.m_signalCounter.clearWaitingFor();
  dropTabPtr.p->m_participantData.m_signalCounter.setWaitingFor(nodeId);
  BlockReference ref = numberToRef(block, 0);
  sendSignal(ref, GSN_DROP_TAB_REQ, signal, DropTabReq::SignalLength, JBB);
}

void
Dbdict::dropTab_localDROP_TAB_CONF(Signal* signal){
  jamEntry();
  
  DropTabConf * conf = (DropTabConf*)signal->getDataPtr();

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, conf->senderData));
  
  ndbrequire(dropTabPtr.p->m_request.tableId == conf->tableId);
  ndbrequire(dropTabPtr.p->m_participantData.m_gsn == GSN_DROP_TAB_REQ);
  
  Uint32 nodeId = refToNode(conf->senderRef);
  dropTabPtr.p->m_participantData.m_signalCounter.clearWaitingFor(nodeId);
  
  if(!dropTabPtr.p->m_participantData.m_signalCounter.done()){
    jam();
    ndbrequire(false);
    return;
  }
  dropTab_nextStep(signal, dropTabPtr);
}

void
Dbdict::dropTab_complete(Signal* signal, 
			 Uint32 dropTabPtrI,
			 Uint32 returnCode){
  jam();

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, dropTabPtrI));
  
  Uint32 tableId = dropTabPtr.p->m_request.tableId;
  
  /**
   * Write to schema file
   */
7232 7233
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry * tableEntry = getTableEntry(xsf, tableId);
7234 7235 7236 7237
  SchemaFile::TableState tabState = 
    (SchemaFile::TableState)tableEntry->m_tableState;
  ndbrequire(tabState == SchemaFile::DROP_TABLE_STARTED);
  tableEntry->m_tableState = SchemaFile::DROP_TABLE_COMMITTED;
7238
  computeChecksum(xsf, tableId / NDB_SF_PAGE_ENTRIES);
7239

knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId);
  bool savetodisk = !(tablePtr.p->m_bits & TableRecord::TR_Temporary);
  Callback callback;
  callback.m_callbackData = dropTabPtr.p->key;
  callback.m_callbackFunction = safe_cast(&Dbdict::dropTab_writeSchemaConf);
  if (savetodisk)
  {
    ndbrequire(c_writeSchemaRecord.inUse == false);
    c_writeSchemaRecord.inUse = true;
    
    c_writeSchemaRecord.pageId = c_schemaRecord.schemaPage;
    c_writeSchemaRecord.firstPage = tableId / NDB_SF_PAGE_ENTRIES;
    c_writeSchemaRecord.noOfPages = 1;
    c_writeSchemaRecord.m_callback = callback;
    startWriteSchemaFile(signal);
  }
  else
  {
    execute(signal, callback, 0); 
  }
7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281
}

void
Dbdict::dropTab_writeSchemaConf(Signal* signal, 
				Uint32 dropTabPtrI,
				Uint32 returnCode){
  jam();

  DropTableRecordPtr dropTabPtr;  
  ndbrequire(c_opDropTable.find(dropTabPtr, dropTabPtrI));

  ndbrequire(dropTabPtr.p->m_participantData.m_gsn == GSN_DROP_TAB_REQ);

  dropTabPtr.p->m_participantData.m_gsn = GSN_DROP_TAB_CONF;

  releaseTableObject(dropTabPtr.p->m_request.tableId);

  DropTabConf * conf = (DropTabConf*)signal->getDataPtr();  
  conf->senderRef = reference();
  conf->senderData = dropTabPtrI;
  conf->tableId = dropTabPtr.p->m_request.tableId;
7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292
  {
    DropTabConf tmp= *conf;
    if (dropTabPtr.p->m_coordinatorRef == reference())
      conf->senderRef = dropTabPtr.p->m_request.senderRef;
    else
      conf->senderRef = 0;
    EXECUTE_DIRECT(SUMA, GSN_DROP_TAB_CONF, signal,
		   DropTabConf::SignalLength);
    jamEntry();
    *conf= tmp;
  }
7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305
  dropTabPtr.p->m_participantData.m_gsn = GSN_DROP_TAB_CONF;
  sendSignal(dropTabPtr.p->m_coordinatorRef, GSN_DROP_TAB_CONF, signal, 
	     DropTabConf::SignalLength, JBB);
  
  if(dropTabPtr.p->m_coordinatorRef != reference()){
    c_opDropTable.release(dropTabPtr);
  }
}

void Dbdict::releaseTableObject(Uint32 tableId, bool removeFromHash) 
{
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
7306 7307
  if (removeFromHash)
  {
7308 7309
    jam();
    release_object(tablePtr.p->m_obj_ptr_i);
7310
  }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
7311 7312 7313 7314 7315
  else
  {
    Rope tmp(c_rope_pool, tablePtr.p->tableName);
    tmp.erase();
  }
7316
  
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336
  {
    Rope tmp(c_rope_pool, tablePtr.p->frmData);
    tmp.erase();
  }

  {
    Rope tmp(c_rope_pool, tablePtr.p->tsData);
    tmp.erase();
  }

  {
    Rope tmp(c_rope_pool, tablePtr.p->ngData);
    tmp.erase();
  }

  {
    Rope tmp(c_rope_pool, tablePtr.p->rangeData);
    tmp.erase();
  }

joreland@mysql.com's avatar
joreland@mysql.com committed
7337
  tablePtr.p->tabState = TableRecord::NOT_DEFINED;
7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348
  
  LocalDLFifoList<AttributeRecord> list(c_attributeRecordPool, 
					tablePtr.p->m_attributes);
  AttributeRecordPtr attrPtr;
  for(list.first(attrPtr); !attrPtr.isNull(); list.next(attrPtr)){
    Rope name(c_rope_pool, attrPtr.p->attributeName);
    Rope def(c_rope_pool, attrPtr.p->defaultValue);
    name.erase();
    def.erase();
  }
  list.release();
7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415
}//releaseTableObject()

/**
 * DICT receives these on index create and drop.
 */
void Dbdict::execDROP_TABLE_CONF(Signal* signal) 
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);

  DropTableConf * const conf = (DropTableConf *)signal->getDataPtr();
  // assume part of drop index operation
  OpDropIndexPtr opPtr;
  c_opDropIndex.find(opPtr, conf->senderData);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_request.getIndexId() == conf->tableId);
  ndbrequire(opPtr.p->m_request.getIndexVersion() == conf->tableVersion);
  dropIndex_fromDropTable(signal, opPtr);
}

void Dbdict::execDROP_TABLE_REF(Signal* signal) 
{
  jamEntry();

  DropTableRef * const ref = (DropTableRef *)signal->getDataPtr();
  // assume part of drop index operation
  OpDropIndexPtr opPtr;
  c_opDropIndex.find(opPtr, ref->senderData);
  ndbrequire(! opPtr.isNull());
  opPtr.p->setError(ref);
  opPtr.p->m_errorLine = __LINE__;
  dropIndex_fromDropTable(signal, opPtr);
}

/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          EXTERNAL INTERFACE TO DATA -------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* This module contains the code that is used by other modules to.  */
/* access the data within DBDICT.                                   */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

void Dbdict::execGET_TABLEDID_REQ(Signal * signal) 
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 1);  
  GetTableIdReq const * req = (GetTableIdReq *)signal->getDataPtr();
  Uint32 senderData = req->senderData;
  Uint32 senderRef = req->senderRef;
  Uint32 len = req->len;

  if(len>MAX_TAB_NAME_SIZE)
  {
    jam();
    sendGET_TABLEID_REF((Signal*)signal, 
			(GetTableIdReq *)req, 
			GetTableIdRef::TableNameTooLong);
    return;
  }

  char tableName[MAX_TAB_NAME_SIZE];
  SegmentedSectionPtr ssPtr;
  signal->getSection(ssPtr,GetTableIdReq::TABLE_NAME);
  copy((Uint32*)tableName, ssPtr);
  releaseSections(signal);
7416 7417 7418
    
  DictObject * obj_ptr_p = get_object(tableName, len);
  if(obj_ptr_p == 0 || !DictTabInfo::isTable(obj_ptr_p->m_type)){
7419
    jam();
7420
    sendGET_TABLEID_REF(signal, 
7421 7422 7423 7424
			(GetTableIdReq *)req, 
			GetTableIdRef::TableNotDefined);
    return;
  }
7425 7426 7427 7428

  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, obj_ptr_p->m_id); 
  
7429
  GetTableIdConf * conf = (GetTableIdConf *)req;
7430 7431 7432
  conf->tableId = tablePtr.p->tableId;
  conf->schemaVersion = tablePtr.p->tableVersion;
  conf->senderData = senderData;
7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446
  sendSignal(senderRef, GSN_GET_TABLEID_CONF, signal,
	     GetTableIdConf::SignalLength, JBB);  
}


void Dbdict::sendGET_TABLEID_REF(Signal* signal, 
				 GetTableIdReq * req,
				 GetTableIdRef::ErrorCode errorCode) 
{
  GetTableIdRef * const ref = (GetTableIdRef *)req;
  /**
   * The format of GetTabInfo Req/Ref is the same
   */
  BlockReference retRef = req->senderRef;
7447
  ref->err = errorCode;
7448 7449 7450 7451 7452 7453 7454 7455 7456 7457
  sendSignal(retRef, GSN_GET_TABLEID_REF, signal, 
	     GetTableIdRef::SignalLength, JBB);
}//sendGET_TABINFOREF()

/* ---------------------------------------------------------------- */
// Get a full table description.
/* ---------------------------------------------------------------- */
void Dbdict::execGET_TABINFOREQ(Signal* signal) 
{
  jamEntry();
7458 7459 7460 7461
  if(!assembleFragments(signal)) 
  { 
    return;
  }  
7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491

  GetTabInfoReq * const req = (GetTabInfoReq *)&signal->theData[0];

  /**
   * If I get a GET_TABINFO_REQ from myself
   * it's is a one from the time queue
   */
  bool fromTimeQueue = (signal->senderBlockRef() == reference());
  
  if (c_retrieveRecord.busyState && fromTimeQueue == true) {
    jam();
    
    sendSignalWithDelay(reference(), GSN_GET_TABINFOREQ, signal, 30, 
			signal->length());
    return;
  }//if

  const Uint32 MAX_WAITERS = 5;
  
  if(c_retrieveRecord.busyState && fromTimeQueue == false){
    jam();
    if(c_retrieveRecord.noOfWaiters < MAX_WAITERS){
      jam();
      c_retrieveRecord.noOfWaiters++;
      
      sendSignalWithDelay(reference(), GSN_GET_TABINFOREQ, signal, 30, 
			  signal->length());
      return;
    }
    
7492
    sendGET_TABINFOREF(signal, req, GetTabInfoRef::Busy);
7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
    return;
  }
  
  if(fromTimeQueue){
    jam();
    c_retrieveRecord.noOfWaiters--;
  } 

  const bool useLongSig = (req->requestType & GetTabInfoReq::LongSignalConf);
  const Uint32 reqType = req->requestType & (~GetTabInfoReq::LongSignalConf);
7503 7504

  Uint32 obj_id = RNIL;
7505 7506 7507 7508 7509
  if(reqType == GetTabInfoReq::RequestByName){
    jam();
    ndbrequire(signal->getNoOfSections() == 1);  
    const Uint32 len = req->tableNameLen;
    
7510
    if(len > MAX_TAB_NAME_SIZE){
7511 7512
      jam();
      releaseSections(signal);
7513
      sendGET_TABINFOREF(signal, req, GetTabInfoRef::TableNameTooLong);
7514 7515 7516 7517 7518 7519 7520 7521
      return;
    }

    char tableName[MAX_TAB_NAME_SIZE];
    SegmentedSectionPtr ssPtr;
    signal->getSection(ssPtr,GetTabInfoReq::TABLE_NAME);
    SimplePropertiesSectionReader r0(ssPtr, getSectionSegmentPool());
    r0.reset(); // undo implicit first()
7522
    if(!r0.getWords((Uint32*)tableName, (len+3)/4)){
7523 7524
      jam();
      releaseSections(signal);
7525
      sendGET_TABINFOREF(signal, req, GetTabInfoRef::TableNotDefined);
7526 7527 7528
      return;
    }
    releaseSections(signal);
7529 7530 7531 7532
    
    DictObject * old_ptr_p = old_ptr_p = get_object(tableName, len);
    if(old_ptr_p)
      obj_id = old_ptr_p->m_id;
7533 7534
  } else {
    jam();
7535
    obj_id = req->tableId;
7536
  }
7537 7538 7539 7540 7541 7542 7543

  SchemaFile::TableEntry *objEntry = 0;
  if(obj_id != RNIL){
    XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
    objEntry = getTableEntry(xsf, obj_id);      
  }

7544
  // The table seached for was not found
7545
  if(objEntry == 0){
7546
    jam();
7547
    sendGET_TABINFOREF(signal, req, GetTabInfoRef::TableNotDefined);
7548 7549
    return;
  }//if
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7550 7551 7552

  // If istable/index, allow ADD_STARTED (not to ref)

7553
  if (objEntry->m_tableState != SchemaFile::TABLE_ADD_COMMITTED &&
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7554 7555
      objEntry->m_tableState != SchemaFile::ALTER_TABLE_COMMITTED &&
      objEntry->m_tableState != SchemaFile::TEMPORARY_TABLE_COMMITTED){
7556
    jam();
7557
    sendGET_TABINFOREF(signal, req, GetTabInfoRef::TableNotDefined);
7558 7559
    return;
  }//if
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7560 7561 7562 7563 7564 7565 7566

  if (DictTabInfo::isTable(objEntry->m_tableType) || 
      DictTabInfo::isIndex(objEntry->m_tableType))
  {
    jam();
    TableRecordPtr tabPtr;
    c_tableRecordPool.getPtr(tabPtr, obj_id);
7567 7568
    if (tabPtr.p->tabState != TableRecord::DEFINED &&
	tabPtr.p->tabState != TableRecord::BACKUP_ONGOING)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7569 7570
    {
      jam();
7571
      sendGET_TABINFOREF(signal, req, GetTabInfoRef::TableNotDefined);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7572 7573
      return;
    }
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7574 7575
    ndbrequire(objEntry->m_tableState == SchemaFile::TEMPORARY_TABLE_COMMITTED ||
               !(tabPtr.p->m_bits & TableRecord::TR_Temporary));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7576
  }
7577 7578 7579 7580
  
  c_retrieveRecord.busyState = true;
  c_retrieveRecord.blockRef = req->senderRef;
  c_retrieveRecord.m_senderData = req->senderData;
7581
  c_retrieveRecord.tableId = obj_id;
7582 7583
  c_retrieveRecord.currentSent = 0;
  c_retrieveRecord.m_useLongSig = useLongSig;
7584
  c_retrieveRecord.m_table_type = objEntry->m_tableType;
7585
  c_packTable.m_state = PackTable::PTS_GET_TAB;
7586 7587 7588 7589

  if(objEntry->m_tableType==DictTabInfo::Datafile)
  {
    jam();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
7590
    GetTabInfoReq *req= (GetTabInfoReq*)signal->getDataPtrSend();
7591 7592 7593 7594 7595 7596 7597 7598
    req->senderData= c_retrieveRecord.retrievePage;
    req->senderRef= reference();
    req->requestType= GetTabInfoReq::RequestById;
    req->tableId= obj_id;

    sendSignal(TSMAN_REF, GSN_GET_TABINFOREQ, signal,
	       GetTabInfoReq::SignalLength, JBB);
  }
7599 7600 7601
  else if(objEntry->m_tableType==DictTabInfo::LogfileGroup)
  {
    jam();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
7602
    GetTabInfoReq *req= (GetTabInfoReq*)signal->getDataPtrSend();
7603 7604 7605 7606 7607 7608 7609 7610
    req->senderData= c_retrieveRecord.retrievePage;
    req->senderRef= reference();
    req->requestType= GetTabInfoReq::RequestById;
    req->tableId= obj_id;

    sendSignal(LGMAN_REF, GSN_GET_TABINFOREQ, signal,
	       GetTabInfoReq::SignalLength, JBB);
  }
7611 7612 7613 7614 7615 7616 7617 7618 7619 7620
  else
  {
    jam();
    signal->theData[0] = ZPACK_TABLE_INTO_PAGES;
    signal->theData[1] = obj_id;
    signal->theData[2] = objEntry->m_tableType;
    signal->theData[3] = c_retrieveRecord.retrievePage;
    sendSignal(reference(), GSN_CONTINUEB, signal, 4, JBB);
  }
  jam();
7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641
}//execGET_TABINFOREQ()

void Dbdict::sendGetTabResponse(Signal* signal) 
{
  PageRecordPtr pagePtr;
  DictTabInfo * const conf = (DictTabInfo *)&signal->theData[0];
  conf->senderRef   = reference();
  conf->senderData  = c_retrieveRecord.m_senderData;
  conf->requestType = DictTabInfo::GetTabInfoConf;
  conf->totalLen    = c_retrieveRecord.retrievedNoOfWords;

  c_pageRecordArray.getPtr(pagePtr, c_retrieveRecord.retrievePage);
  Uint32* pagePointer = (Uint32*)&pagePtr.p->word[0] + ZPAGE_HEADER_SIZE;
  
  if(c_retrieveRecord.m_useLongSig){
    jam();
    GetTabInfoConf* conf = (GetTabInfoConf*)signal->getDataPtr();
    conf->gci = 0;
    conf->tableId = c_retrieveRecord.tableId;
    conf->senderData = c_retrieveRecord.m_senderData;
    conf->totalLen = c_retrieveRecord.retrievedNoOfWords;
7642 7643
    conf->tableType = c_retrieveRecord.m_table_type;

7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663
    Callback c = { safe_cast(&Dbdict::initRetrieveRecord), 0 };
    LinearSectionPtr ptr[3];
    ptr[0].p = pagePointer;
    ptr[0].sz = c_retrieveRecord.retrievedNoOfWords;
    sendFragmentedSignal(c_retrieveRecord.blockRef,
			 GSN_GET_TABINFO_CONF,
			 signal, 
			 GetTabInfoConf::SignalLength,
			 JBB,
			 ptr,
			 1,
			 c);
    return;
  }

  ndbrequire(false);
}//sendGetTabResponse()

void Dbdict::sendGET_TABINFOREF(Signal* signal, 
				GetTabInfoReq * req,
7664
				GetTabInfoRef::ErrorCode errorCode) 
7665 7666 7667 7668 7669 7670 7671 7672
{
  jamEntry();
  GetTabInfoRef * const ref = (GetTabInfoRef *)&signal->theData[0];
  /**
   * The format of GetTabInfo Req/Ref is the same
   */
  BlockReference retRef = req->senderRef;
  ref->errorCode = errorCode;
7673 7674
  
  sendSignal(retRef, GSN_GET_TABINFOREF, signal, signal->length(), JBB);
7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694
}//sendGET_TABINFOREF()

void
Dbdict::execLIST_TABLES_REQ(Signal* signal)
{
  jamEntry();
  ListTablesReq * req = (ListTablesReq*)signal->getDataPtr();
  Uint32 senderRef  = req->senderRef;
  Uint32 senderData = req->senderData;
  // save req flags
  const Uint32 reqTableId = req->getTableId();
  const Uint32 reqTableType = req->getTableType();
  const bool reqListNames = req->getListNames();
  const bool reqListIndexes = req->getListIndexes();
  // init the confs
  ListTablesConf * conf = (ListTablesConf *)signal->getDataPtrSend();
  conf->senderData = senderData;
  conf->counter = 0;
  Uint32 pos = 0;

7695 7696 7697 7698 7699
  DLHashTable<DictObject>::Iterator iter;
  bool ok = c_obj_hash.first(iter);
  for(; ok; ok = c_obj_hash.next(iter)){
    Uint32 type = iter.curr.p->m_type;
    if ((reqTableType != (Uint32)0) && (reqTableType != type))
7700
      continue;
7701 7702

    if (reqListIndexes && !DictTabInfo::isIndex(type))
7703
      continue;
7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736

    TableRecordPtr tablePtr;
    if (DictTabInfo::isTable(type) || DictTabInfo::isIndex(type)){
      c_tableRecordPool.getPtr(tablePtr, iter.curr.p->m_id);

      if(reqListIndexes && (reqTableId != tablePtr.p->primaryTableId))
	continue;
      
      conf->tableData[pos] = 0;
      conf->setTableId(pos, tablePtr.i); // id
      conf->setTableType(pos, type); // type
      // state

      if(DictTabInfo::isTable(type)){
	switch (tablePtr.p->tabState) {
	case TableRecord::DEFINING:
	case TableRecord::CHECKED:
	  conf->setTableState(pos, DictTabInfo::StateBuilding);
	  break;
	case TableRecord::PREPARE_DROPPING:
	case TableRecord::DROPPING:
	  conf->setTableState(pos, DictTabInfo::StateDropping);
	  break;
	case TableRecord::DEFINED:
	  conf->setTableState(pos, DictTabInfo::StateOnline);
	  break;
	case TableRecord::BACKUP_ONGOING:
	  conf->setTableState(pos, DictTabInfo::StateBackup);
	  break;
	default:
	  conf->setTableState(pos, DictTabInfo::StateBroken);
	  break;
	}
7737
      }
7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756
      if (tablePtr.p->isIndex()) {
	switch (tablePtr.p->indexState) {
	case TableRecord::IS_OFFLINE:
	  conf->setTableState(pos, DictTabInfo::StateOffline);
	  break;
	case TableRecord::IS_BUILDING:
	  conf->setTableState(pos, DictTabInfo::StateBuilding);
	  break;
	case TableRecord::IS_DROPPING:
	  conf->setTableState(pos, DictTabInfo::StateDropping);
	  break;
	case TableRecord::IS_ONLINE:
	  conf->setTableState(pos, DictTabInfo::StateOnline);
	  break;
	default:
	  conf->setTableState(pos, DictTabInfo::StateBroken);
	  break;
	}
      }
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7757
      // Logging status
7758
      if (! (tablePtr.p->m_bits & TableRecord::TR_Logged)) {
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7759
	conf->setTableStore(pos, DictTabInfo::StoreNotLogged);
7760 7761 7762
      } else {
	conf->setTableStore(pos, DictTabInfo::StorePermanent);
      }
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7763 7764 7765 7766 7767 7768
      // Temporary status
      if (tablePtr.p->m_bits & TableRecord::TR_Temporary) {
	conf->setTableTemp(pos, NDB_TEMP_TAB_TEMPORARY);
      } else {
	conf->setTableTemp(pos, NDB_TEMP_TAB_PERMANENT);
      }
7769
      pos++;
7770
    }
7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784
    if(DictTabInfo::isTrigger(type)){
      TriggerRecordPtr triggerPtr;
      c_triggerRecordPool.getPtr(triggerPtr, iter.curr.p->m_id);

      conf->tableData[pos] = 0;
      conf->setTableId(pos, triggerPtr.i);
      conf->setTableType(pos, type);
      switch (triggerPtr.p->triggerState) {
      case TriggerRecord::TS_OFFLINE:
	conf->setTableState(pos, DictTabInfo::StateOffline);
	break;
      case TriggerRecord::TS_ONLINE:
	conf->setTableState(pos, DictTabInfo::StateOnline);
	break;
7785
      default:
7786 7787
	conf->setTableState(pos, DictTabInfo::StateBroken);
	break;
7788
      }
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7789
      conf->setTableStore(pos, DictTabInfo::StoreNotLogged);
7790
      pos++;
7791
    }
7792 7793 7794 7795 7796
    if (DictTabInfo::isFilegroup(type)){
      jam();
      conf->tableData[pos] = 0;
      conf->setTableId(pos, iter.curr.p->m_id);
      conf->setTableType(pos, type); // type
7797
      conf->setTableState(pos, DictTabInfo::StateOnline);  // XXX todo
7798 7799
      pos++;
    }
7800 7801 7802 7803 7804
    if (DictTabInfo::isFile(type)){
      jam();
      conf->tableData[pos] = 0;
      conf->setTableId(pos, iter.curr.p->m_id);
      conf->setTableType(pos, type); // type
7805
      conf->setTableState(pos, DictTabInfo::StateOnline); // XXX todo
7806
      pos++;
7807
    }
7808
    
7809 7810
    if (pos >= ListTablesConf::DataLength) {
      sendSignal(senderRef, GSN_LIST_TABLES_CONF, signal,
7811
		 ListTablesConf::SignalLength, JBB);
7812 7813 7814
      conf->counter++;
      pos = 0;
    }
7815
    
7816 7817
    if (! reqListNames)
      continue;
7818 7819 7820
    
    Rope name(c_rope_pool, iter.curr.p->m_name);
    const Uint32 size = name.size();
7821 7822 7823 7824 7825 7826 7827 7828
    conf->tableData[pos] = size;
    pos++;
    if (pos >= ListTablesConf::DataLength) {
      sendSignal(senderRef, GSN_LIST_TABLES_CONF, signal,
		 ListTablesConf::SignalLength, JBB);
      conf->counter++;
      pos = 0;
    }
7829 7830 7831 7832
    Uint32 i = 0;
    char tmp[MAX_TAB_NAME_SIZE];
    name.copy(tmp);
    while (i < size) {
7833 7834
      char* p = (char*)&conf->tableData[pos];
      for (Uint32 j = 0; j < 4; j++) {
7835 7836 7837 7838
	if (i < size)
	  *p++ = tmp[i++];
	else
	  *p++ = 0;
7839 7840 7841
      }
      pos++;
      if (pos >= ListTablesConf::DataLength) {
7842 7843 7844 7845
	sendSignal(senderRef, GSN_LIST_TABLES_CONF, signal,
		   ListTablesConf::SignalLength, JBB);
	conf->counter++;
	pos = 0;
7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883
      }
    }
  }
  // last signal must have less than max length
  sendSignal(senderRef, GSN_LIST_TABLES_CONF, signal,
	     ListTablesConf::HeaderLength + pos, JBB);
}

/**
 * MODULE: Create index
 *
 * Create index in DICT via create table operation.  Then invoke alter
 * index opearation to online the index.
 *
 * Request type in CREATE_INDX signals:
 *
 * RT_USER - from API to DICT master
 * RT_DICT_PREPARE - prepare participants
 * RT_DICT_COMMIT - commit participants
 * RT_TC - create index in TC (part of alter index operation)
 */

void
Dbdict::execCREATE_INDX_REQ(Signal* signal)
{
  jamEntry();
  CreateIndxReq* const req = (CreateIndxReq*)signal->getDataPtrSend();
  OpCreateIndexPtr opPtr;
  const Uint32 senderRef = signal->senderBlockRef();
  const CreateIndxReq::RequestType requestType = req->getRequestType();
  if (requestType == CreateIndxReq::RT_USER) {
    jam();
    if (! assembleFragments(signal)) {
      jam();
      return;
    }
    if (signal->getLength() == CreateIndxReq::SignalLength) {
      jam();
7884
      CreateIndxRef::ErrorCode tmperr = CreateIndxRef::NoError;
7885 7886
      if (getOwnNodeId() != c_masterNodeId) {
        jam();
7887 7888 7889 7890 7891 7892 7893 7894
        tmperr = CreateIndxRef::NotMaster;
      } else if (c_blockState == BS_NODE_RESTART) {
        jam();
        tmperr = CreateIndxRef::BusyWithNR;
      } else if (c_blockState != BS_IDLE) {
        jam();
        tmperr = CreateIndxRef::Busy;
      }
7895
      else if (checkSingleUserMode(senderRef))
7896 7897 7898 7899
      {
        jam();
        tmperr = CreateIndxRef::SingleUser;
      }
7900
      if (tmperr != CreateIndxRef::NoError) {
7901 7902 7903 7904 7905 7906 7907
	releaseSections(signal);
	OpCreateIndex opBusy;
	opPtr.p = &opBusy;
	opPtr.p->save(req);
	opPtr.p->m_isMaster = (senderRef == reference());
	opPtr.p->key = 0;
	opPtr.p->m_requestType = CreateIndxReq::RT_DICT_PREPARE;
7908
	opPtr.p->m_errorCode = tmperr;
7909 7910 7911 7912
	opPtr.p->m_errorLine = __LINE__;
	opPtr.p->m_errorNode = c_masterNodeId;
	createIndex_sendReply(signal, opPtr, true);
	return;
7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957
      }
      // forward initial request plus operation key to all
      req->setOpKey(++c_opRecordSequence);
      NodeReceiverGroup rg(DBDICT, c_aliveNodes);
      sendSignal(rg, GSN_CREATE_INDX_REQ,
          signal, CreateIndxReq::SignalLength + 1, JBB);
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == CreateIndxReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpCreateIndex opBusy;
    if (! c_opCreateIndex.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = CreateIndxReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = CreateIndxRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      releaseSections(signal);
      createIndex_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opCreateIndex.add(opPtr);
    // save attribute list
    SegmentedSectionPtr ssPtr;
    signal->getSection(ssPtr, CreateIndxReq::ATTRIBUTE_LIST_SECTION);
    SimplePropertiesSectionReader r0(ssPtr, getSectionSegmentPool());
    r0.reset(); // undo implicit first()
    if (! r0.getWord(&opPtr.p->m_attrList.sz) ||
        ! r0.getWords(opPtr.p->m_attrList.id, opPtr.p->m_attrList.sz)) {
      jam();
      opPtr.p->m_errorCode = CreateIndxRef::InvalidName;
      opPtr.p->m_errorLine = __LINE__;
      releaseSections(signal);
      createIndex_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    // save name and index table properties
    signal->getSection(ssPtr, CreateIndxReq::INDEX_NAME_SECTION);
    SimplePropertiesSectionReader r1(ssPtr, getSectionSegmentPool());
7958
    c_tableDesc.init();
7959
    SimpleProperties::UnpackStatus status = SimpleProperties::unpack(
7960
        r1, &c_tableDesc,
7961 7962 7963 7964 7965 7966 7967 7968 7969
        DictTabInfo::TableMapping, DictTabInfo::TableMappingSize,
        true, true);
    if (status != SimpleProperties::Eof) {
      opPtr.p->m_errorCode = CreateIndxRef::InvalidName;
      opPtr.p->m_errorLine = __LINE__;
      releaseSections(signal);
      createIndex_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
7970
    memcpy(opPtr.p->m_indexName, c_tableDesc.TableName, MAX_TAB_NAME_SIZE);
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
7971 7972
    opPtr.p->m_loggedIndex = c_tableDesc.TableLoggedFlag;
    opPtr.p->m_temporaryIndex = c_tableDesc.TableTemporaryFlag;
7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090
    releaseSections(signal);
    // master expects to hear from all
    if (opPtr.p->m_isMaster)
      opPtr.p->m_signalCounter = c_aliveNodes;
    createIndex_slavePrepare(signal, opPtr);
    createIndex_sendReply(signal, opPtr, false);
    return;
  }
  c_opCreateIndex.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == CreateIndxReq::RT_DICT_COMMIT ||
        requestType == CreateIndxReq::RT_DICT_ABORT) {
      jam();
      if (requestType == CreateIndxReq::RT_DICT_COMMIT) {
        opPtr.p->m_request.setIndexId(req->getIndexId());
        opPtr.p->m_request.setIndexVersion(req->getIndexVersion());
        createIndex_slaveCommit(signal, opPtr);
      } else {
        createIndex_slaveAbort(signal, opPtr);
      }
      createIndex_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
        c_opCreateIndex.release(opPtr);
      return;
    }
  }
  jam();
  // return to sender
  releaseSections(signal);
  OpCreateIndex opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
  opPtr.p->m_errorCode = CreateIndxRef::BadRequestType;
  opPtr.p->m_errorLine = __LINE__;
  createIndex_sendReply(signal, opPtr, true);
}

void
Dbdict::execCREATE_INDX_CONF(Signal* signal)
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);
  CreateIndxConf* conf = (CreateIndxConf*)signal->getDataPtrSend();
  createIndex_recvReply(signal, conf, 0);
}

void
Dbdict::execCREATE_INDX_REF(Signal* signal) 
{
  jamEntry();      
  CreateIndxRef* ref = (CreateIndxRef*)signal->getDataPtrSend();
  createIndex_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::createIndex_recvReply(Signal* signal, const CreateIndxConf* conf,
    const CreateIndxRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const CreateIndxReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == CreateIndxReq::RT_TC) {
    jam();
    // part of alter index operation
    OpAlterIndexPtr opPtr;
    c_opAlterIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterIndex_fromCreateTc(signal, opPtr);
    return;
  }
  OpCreateIndexPtr opPtr;
  c_opCreateIndex.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  opPtr.p->setError(ref);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == CreateIndxReq::RT_DICT_COMMIT ||
      requestType == CreateIndxReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    createIndex_sendReply(signal, opPtr, true);
    c_opCreateIndex.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = CreateIndxReq::RT_DICT_ABORT;
    createIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  if (requestType == CreateIndxReq::RT_DICT_PREPARE) {
    jam();
    // start index table create
    createIndex_toCreateTable(signal, opPtr);
    if (opPtr.p->hasError()) {
      jam();
      opPtr.p->m_requestType = CreateIndxReq::RT_DICT_ABORT;
      createIndex_sendSlaveReq(signal, opPtr);
      return;
    }
    return;
  }
  ndbrequire(false);
}

void
Dbdict::createIndex_slavePrepare(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
pekka@mysql.com's avatar
pekka@mysql.com committed
8091 8092 8093
  if (ERROR_INSERTED(6006) && ! opPtr.p->m_isMaster) {
    ndbrequire(false);
  }
8094 8095 8096 8097 8098
}

void
Dbdict::createIndex_toCreateTable(Signal* signal, OpCreateIndexPtr opPtr)
{
8099 8100 8101 8102
  union {
    char tableName[MAX_TAB_NAME_SIZE];
    char attributeName[MAX_ATTR_NAME_SIZE];
  };
8103
  Uint32 k;
8104 8105
  Uint32 attrid_map[MAX_ATTRIBUTES_IN_INDEX];

8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120
  jam();
  const CreateIndxReq* const req = &opPtr.p->m_request;
  // signal data writer
  Uint32* wbuffer = &c_indexPage.word[0];
  LinearWriter w(wbuffer, sizeof(c_indexPage) >> 2);
  w.first();
  // get table being indexed
  if (! (req->getTableId() < c_tableRecordPool.getSize())) {
    jam();
    opPtr.p->m_errorCode = CreateIndxRef::InvalidPrimaryTable;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, req->getTableId());
joreland@mysql.com's avatar
joreland@mysql.com committed
8121 8122
  if (tablePtr.p->tabState != TableRecord::DEFINED &&
      tablePtr.p->tabState != TableRecord::BACKUP_ONGOING) {
8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133
    jam();
    opPtr.p->m_errorCode = CreateIndxRef::InvalidPrimaryTable;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  if (! tablePtr.p->isTable()) {
    jam();
    opPtr.p->m_errorCode = CreateIndxRef::InvalidPrimaryTable;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161

  // Check that the temporary status of index is compatible with table.
  if (!opPtr.p->m_temporaryIndex &&
      tablePtr.p->m_bits & TableRecord::TR_Temporary)
  {
    jam();
    opPtr.p->m_errorCode= CreateIndxRef::TableIsTemporary;
    opPtr.p->m_errorLine= __LINE__;
    return;
  }
  if (opPtr.p->m_temporaryIndex &&
      !(tablePtr.p->m_bits & TableRecord::TR_Temporary))
  {
    // This could be implemented later, but mysqld does currently not detect
    // that the index disappears after SR, and it appears not too useful.
    jam();
    opPtr.p->m_errorCode= CreateIndxRef::TableIsNotTemporary;
    opPtr.p->m_errorLine= __LINE__;
    return;
  }
  if (opPtr.p->m_temporaryIndex && opPtr.p->m_loggedIndex)
  {
    jam();
    opPtr.p->m_errorCode= CreateIndxRef::NoLoggingTemporaryIndex;
    opPtr.p->m_errorLine= __LINE__;
    return;
  }

8162 8163 8164 8165 8166 8167
  // compute index table record
  TableRecord indexRec;
  TableRecordPtr indexPtr;
  indexPtr.i = RNIL;            // invalid
  indexPtr.p = &indexRec;
  initialiseTableRecord(indexPtr);
8168
  indexPtr.p->m_bits = TableRecord::TR_RowChecksum;
8169
  if (req->getIndexType() == DictTabInfo::UniqueHashIndex) {
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
8170 8171 8172
    indexPtr.p->m_bits |= (opPtr.p->m_loggedIndex ? TableRecord::TR_Logged:0);
    indexPtr.p->m_bits |=
      (opPtr.p->m_temporaryIndex ? TableRecord::TR_Temporary : 0);
8173
    indexPtr.p->fragmentType = DictTabInfo::DistrKeyUniqueHashIndex;
8174 8175
  } else if (req->getIndexType() == DictTabInfo::OrderedIndex) {
    // first version will not supported logging
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
8176
    if (opPtr.p->m_loggedIndex) {
8177 8178 8179 8180 8181
      jam();
      opPtr.p->m_errorCode = CreateIndxRef::InvalidIndexType;
      opPtr.p->m_errorLine = __LINE__;
      return;
    }
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
8182 8183
    indexPtr.p->m_bits |=
      (opPtr.p->m_temporaryIndex ? TableRecord::TR_Temporary : 0);
8184
    indexPtr.p->fragmentType = DictTabInfo::DistrKeyOrderedIndex;
8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200
  } else {
    jam();
    opPtr.p->m_errorCode = CreateIndxRef::InvalidIndexType;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  indexPtr.p->tableType = (DictTabInfo::TableType)req->getIndexType();
  indexPtr.p->primaryTableId = req->getTableId();
  indexPtr.p->noOfAttributes = opPtr.p->m_attrList.sz;
  indexPtr.p->tupKeyLength = 0;
  if (indexPtr.p->noOfAttributes == 0) {
    jam();
    opPtr.p->m_errorCode = CreateIndxRef::InvalidIndexType;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
8201

8202 8203 8204 8205
  if (indexPtr.p->isOrderedIndex()) {
    // tree node size in words (make configurable later)
    indexPtr.p->tupKeyLength = MAX_TTREE_NODE_SIZE;
  }
8206 8207 8208

  AttributeMask mask;
  mask.clear();
8209
  for (k = 0; k < opPtr.p->m_attrList.sz; k++) {
8210
    jam();
8211
    unsigned current_id= opPtr.p->m_attrList.id[k];
8212 8213 8214
    Uint32 tAttr = tablePtr.p->m_attributes.firstItem;
    AttributeRecord* aRec = NULL;
    for (; tAttr != RNIL; )
8215 8216 8217
    {
      aRec = c_attributeRecordPool.getPtr(tAttr);
      if (aRec->attributeId != current_id)
8218 8219 8220 8221
      {
	tAttr= aRec->nextList;
	continue;
      }
8222
      jam();
8223
      break;
8224
    }
8225
    if (tAttr == RNIL) {
8226 8227 8228 8229 8230
      jam();
      opPtr.p->m_errorCode = CreateIndxRef::BadRequestType;
      opPtr.p->m_errorLine = __LINE__;
      return;
    }
8231 8232
    if (mask.get(current_id))
    {
8233
      jam();
8234
      opPtr.p->m_errorCode = CreateIndxRef::DuplicateAttributes;
8235 8236 8237
      opPtr.p->m_errorLine = __LINE__;
      return;
    }
8238
    const Uint32 a = aRec->attributeDescriptor;
8239 8240 8241 8242 8243 8244 8245 8246 8247 8248

    if (AttributeDescriptor::getDiskBased(a))
    {
      jam();
      opPtr.p->m_errorCode = CreateIndxRef::IndexOnDiskAttributeError;
      opPtr.p->m_errorLine = __LINE__;
      return;
    }
    
    mask.set(current_id);
8249 8250 8251 8252 8253
    unsigned kk= k;
    if (indexPtr.p->isHashIndex()) {
      const Uint32 s1 = AttributeDescriptor::getSize(a);
      const Uint32 s2 = AttributeDescriptor::getArraySize(a);
      indexPtr.p->tupKeyLength += ((1 << s1) * s2 + 31) >> 5;
8254

8255 8256 8257 8258
      for (; kk > 0 && current_id < attrid_map[kk-1]>>16; kk--)
	attrid_map[kk]= attrid_map[kk-1];
    }
    attrid_map[kk]= k | (current_id << 16);
8259
  }
8260

8261 8262 8263 8264 8265 8266
  indexPtr.p->noOfPrimkey = indexPtr.p->noOfAttributes;
  // plus concatenated primary table key attribute
  indexPtr.p->noOfAttributes += 1;
  indexPtr.p->noOfNullAttr = 0;
  // write index table
  w.add(DictTabInfo::TableName, opPtr.p->m_indexName);
8267
  w.add(DictTabInfo::TableLoggedFlag, !!(indexPtr.p->m_bits & TableRecord::TR_Logged));
knielsen@ymer.(none)'s avatar
knielsen@ymer.(none) committed
8268
  w.add(DictTabInfo::TableTemporaryFlag, !!(indexPtr.p->m_bits & TableRecord::TR_Temporary));
8269 8270
  w.add(DictTabInfo::FragmentTypeVal, indexPtr.p->fragmentType);
  w.add(DictTabInfo::TableTypeVal, indexPtr.p->tableType);
8271 8272 8273
  Rope name(c_rope_pool, tablePtr.p->tableName);
  name.copy(tableName);
  w.add(DictTabInfo::PrimaryTable, tableName);
8274 8275 8276 8277 8278
  w.add(DictTabInfo::PrimaryTableId, tablePtr.i);
  w.add(DictTabInfo::NoOfAttributes, indexPtr.p->noOfAttributes);
  w.add(DictTabInfo::NoOfKeyAttr, indexPtr.p->noOfPrimkey);
  w.add(DictTabInfo::NoOfNullable, indexPtr.p->noOfNullAttr);
  w.add(DictTabInfo::KeyLength, indexPtr.p->tupKeyLength);
8279
  w.add(DictTabInfo::SingleUserMode, (Uint32)NDB_SUM_READ_WRITE);
8280
  // write index key attributes
8281
  for (k = 0; k < opPtr.p->m_attrList.sz; k++) {
8282 8283 8284 8285 8286
    // insert the attributes in the order decided above in attrid_map
    // k is new order, current_id is in previous order
    // ToDo: make sure "current_id" is stored with the table and
    // passed up to NdbDictionary
    unsigned current_id= opPtr.p->m_attrList.id[attrid_map[k] & 0xffff];
8287
    jam();
8288
    for (Uint32 tAttr = tablePtr.p->m_attributes.firstItem; tAttr != RNIL; ) {
8289
      AttributeRecord* aRec = c_attributeRecordPool.getPtr(tAttr);
8290
      tAttr = aRec->nextList;
8291
      if (aRec->attributeId != current_id)
8292 8293 8294 8295
        continue;
      jam();
      const Uint32 a = aRec->attributeDescriptor;
      bool isNullable = AttributeDescriptor::getNullable(a);
8296 8297 8298 8299
      Uint32 arrayType = AttributeDescriptor::getArrayType(a);
      Rope attrName(c_rope_pool, aRec->attributeName);
      attrName.copy(attributeName);
      w.add(DictTabInfo::AttributeName, attributeName);
8300
      Uint32 attrType = AttributeDescriptor::getType(a);
8301
      // computed
8302 8303 8304 8305 8306 8307 8308 8309 8310
      w.add(DictTabInfo::AttributeId, k);
      if (indexPtr.p->isHashIndex()) {
        w.add(DictTabInfo::AttributeKeyFlag, (Uint32)true);
        w.add(DictTabInfo::AttributeNullableFlag, (Uint32)false);
      }
      if (indexPtr.p->isOrderedIndex()) {
        w.add(DictTabInfo::AttributeKeyFlag, (Uint32)false);
        w.add(DictTabInfo::AttributeNullableFlag, (Uint32)isNullable);
      }
8311
      w.add(DictTabInfo::AttributeArrayType, arrayType);
8312
      w.add(DictTabInfo::AttributeExtType, attrType);
pekka@mysql.com's avatar
pekka@mysql.com committed
8313 8314
      w.add(DictTabInfo::AttributeExtPrecision, aRec->extPrecision);
      w.add(DictTabInfo::AttributeExtScale, aRec->extScale);
8315 8316 8317 8318 8319 8320
      w.add(DictTabInfo::AttributeExtLength, aRec->extLength);
      w.add(DictTabInfo::AttributeEnd, (Uint32)true);
    }
  }
  if (indexPtr.p->isHashIndex()) {
    jam();
8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337
    
    Uint32 key_type = NDB_ARRAYTYPE_FIXED;
    AttributeRecordPtr attrPtr;
    LocalDLFifoList<AttributeRecord> alist(c_attributeRecordPool,
					   tablePtr.p->m_attributes);
    for (alist.first(attrPtr); !attrPtr.isNull(); alist.next(attrPtr)) 
    {
      const Uint32 desc = attrPtr.p->attributeDescriptor;
      if (AttributeDescriptor::getPrimaryKey(desc) &&
	  AttributeDescriptor::getArrayType(desc) != NDB_ARRAYTYPE_FIXED)
      {
	key_type = NDB_ARRAYTYPE_MEDIUM_VAR;
	break;
      }
    }
    
    // write concatenated primary table key attribute i.e. keyinfo
8338 8339
    w.add(DictTabInfo::AttributeName, "NDB$PK");
    w.add(DictTabInfo::AttributeId, opPtr.p->m_attrList.sz);
8340
    w.add(DictTabInfo::AttributeArrayType, key_type);
8341 8342 8343
    w.add(DictTabInfo::AttributeKeyFlag, (Uint32)false);
    w.add(DictTabInfo::AttributeNullableFlag, (Uint32)false);
    w.add(DictTabInfo::AttributeExtType, (Uint32)DictTabInfo::ExtUnsigned);
8344
    w.add(DictTabInfo::AttributeExtLength, tablePtr.p->tupKeyLength+1);
8345 8346 8347 8348 8349 8350 8351
    w.add(DictTabInfo::AttributeEnd, (Uint32)true);
  }
  if (indexPtr.p->isOrderedIndex()) {
    jam();
    // write index tree node as Uint32 array attribute
    w.add(DictTabInfo::AttributeName, "NDB$TNODE");
    w.add(DictTabInfo::AttributeId, opPtr.p->m_attrList.sz);
8352 8353
    // should not matter but VAR crashes in TUP
    w.add(DictTabInfo::AttributeArrayType, (Uint32)NDB_ARRAYTYPE_FIXED);
8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481
    w.add(DictTabInfo::AttributeKeyFlag, (Uint32)true);
    w.add(DictTabInfo::AttributeNullableFlag, (Uint32)false);
    w.add(DictTabInfo::AttributeExtType, (Uint32)DictTabInfo::ExtUnsigned);
    w.add(DictTabInfo::AttributeExtLength, indexPtr.p->tupKeyLength);
    w.add(DictTabInfo::AttributeEnd, (Uint32)true);
  }
  // finish
  w.add(DictTabInfo::TableEnd, (Uint32)true);
  // remember to...
  releaseSections(signal);
  // send create index table request
  CreateTableReq * const cre = (CreateTableReq*)signal->getDataPtrSend();
  cre->senderRef = reference();
  cre->senderData = opPtr.p->key;
  LinearSectionPtr lsPtr[3];
  lsPtr[0].p = wbuffer;
  lsPtr[0].sz = w.getWordsUsed();
  sendSignal(DBDICT_REF, GSN_CREATE_TABLE_REQ,
      signal, CreateTableReq::SignalLength, JBB, lsPtr, 1);
}

void
Dbdict::createIndex_fromCreateTable(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = CreateIndxReq::RT_DICT_ABORT;
    createIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  if (! opPtr.p->m_request.getOnline()) {
    jam();
    opPtr.p->m_requestType = CreateIndxReq::RT_DICT_COMMIT;
    createIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  createIndex_toAlterIndex(signal, opPtr);
}

void
Dbdict::createIndex_toAlterIndex(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
  AlterIndxReq* const req = (AlterIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(AlterIndxReq::RT_CREATE_INDEX);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  req->setTableId(opPtr.p->m_request.getTableId());
  req->setIndexId(opPtr.p->m_request.getIndexId());
  req->setIndexVersion(opPtr.p->m_request.getIndexVersion());
  req->setOnline(true);
  sendSignal(reference(), GSN_ALTER_INDX_REQ,
      signal, AlterIndxReq::SignalLength, JBB);
}

void
Dbdict::createIndex_fromAlterIndex(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = CreateIndxReq::RT_DICT_ABORT;
    createIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  opPtr.p->m_requestType = CreateIndxReq::RT_DICT_COMMIT;
  createIndex_sendSlaveReq(signal, opPtr);
}

void
Dbdict::createIndex_slaveCommit(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
  const Uint32 indexId = opPtr.p->m_request.getIndexId();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, indexId);
  if (! opPtr.p->m_request.getOnline()) {
    ndbrequire(indexPtr.p->indexState == TableRecord::IS_UNDEFINED);
    indexPtr.p->indexState = TableRecord::IS_OFFLINE;
  } else {
    ndbrequire(indexPtr.p->indexState == TableRecord::IS_ONLINE);
  }
}

void
Dbdict::createIndex_slaveAbort(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
  CreateIndxReq* const req = &opPtr.p->m_request;
  const Uint32 indexId = req->getIndexId();
  if (indexId >= c_tableRecordPool.getSize()) {
    jam();
    return;
  }
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, indexId);
  if (! indexPtr.p->isIndex()) {
    jam();
    return;
  }
  indexPtr.p->indexState = TableRecord::IS_BROKEN;
}

void
Dbdict::createIndex_sendSlaveReq(Signal* signal, OpCreateIndexPtr opPtr)
{
  jam();
  CreateIndxReq* const req = (CreateIndxReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  opPtr.p->m_signalCounter = c_aliveNodes;
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
  sendSignal(rg, GSN_CREATE_INDX_REQ,
      signal, CreateIndxReq::SignalLength, JBB);
}

void
Dbdict::createIndex_sendReply(Signal* signal, OpCreateIndexPtr opPtr,
    bool toUser)
{
  CreateIndxRef* rep = (CreateIndxRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_CREATE_INDX_CONF;
  Uint32 length = CreateIndxConf::InternalLength;
8482
  bool sendRef;
8483
  if (! toUser) {
8484
    sendRef = opPtr.p->hasLastError();
8485 8486 8487 8488 8489 8490
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == CreateIndxReq::RT_DICT_ABORT)
      sendRef = false;
  } else {
8491
    sendRef = opPtr.p->hasError();
8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = CreateIndxConf::SignalLength;
  }
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setIndexId(opPtr.p->m_request.getIndexId());
  rep->setIndexVersion(opPtr.p->m_request.getIndexVersion());
  if (sendRef) {
    if (opPtr.p->m_errorNode == 0)
      opPtr.p->m_errorNode = getOwnNodeId();
    rep->setErrorCode(opPtr.p->m_errorCode);
    rep->setErrorLine(opPtr.p->m_errorLine);
    rep->setErrorNode(opPtr.p->m_errorNode);
    gsn = GSN_CREATE_INDX_REF;
    length = CreateIndxRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/**
 * MODULE: Drop index.
 *
 * Drop index.  First alters the index offline (i.e.  drops metadata in
 * other blocks) and then drops the index table.
 */

void
Dbdict::execDROP_INDX_REQ(Signal* signal)
{
  jamEntry();
  DropIndxReq* const req = (DropIndxReq*)signal->getDataPtrSend();
  OpDropIndexPtr opPtr;
joreland@mysql.com's avatar
joreland@mysql.com committed
8525 8526

  int err = DropIndxRef::BadRequestType;
8527 8528 8529 8530 8531 8532
  const Uint32 senderRef = signal->senderBlockRef();
  const DropIndxReq::RequestType requestType = req->getRequestType();
  if (requestType == DropIndxReq::RT_USER) {
    jam();
    if (signal->getLength() == DropIndxReq::SignalLength) {
      jam();
8533
      DropIndxRef::ErrorCode tmperr = DropIndxRef::NoError;
8534 8535
      if (getOwnNodeId() != c_masterNodeId) {
        jam();
8536 8537 8538 8539 8540 8541 8542 8543
        tmperr = DropIndxRef::NotMaster;
      } else if (c_blockState == BS_NODE_RESTART) {
        jam();
        tmperr = DropIndxRef::BusyWithNR;
      } else if (c_blockState != BS_IDLE) {
        jam();
        tmperr = DropIndxRef::Busy;
      }
8544
      else if (checkSingleUserMode(senderRef))
8545 8546 8547 8548
      {
        jam();
        tmperr = DropIndxRef::SingleUser;
      }
8549 8550
      if (tmperr != DropIndxRef::NoError) {
	err = tmperr;
8551
	goto error;
8552 8553
      }
      // forward initial request plus operation key to all
joreland@mysql.com's avatar
joreland@mysql.com committed
8554 8555
      Uint32 indexId= req->getIndexId();
      Uint32 indexVersion= req->getIndexVersion();
8556 8557 8558

      if(indexId >= c_tableRecordPool.getSize())
      {
joreland@mysql.com's avatar
joreland@mysql.com committed
8559
	err = DropIndxRef::IndexNotFound;
joreland@mysql.com's avatar
joreland@mysql.com committed
8560
	goto error;
8561 8562 8563 8564 8565 8566 8567
      }

      TableRecordPtr tmp;
      c_tableRecordPool.getPtr(tmp, indexId);
      if(tmp.p->tabState == TableRecord::NOT_DEFINED ||
	 tmp.p->tableVersion != indexVersion)
      {
joreland@mysql.com's avatar
joreland@mysql.com committed
8568 8569 8570
	err = DropIndxRef::InvalidIndexVersion;
	goto error;
      }
8571
      
joreland@mysql.com's avatar
joreland@mysql.com committed
8572 8573 8574 8575 8576
      if (! tmp.p->isIndex()) {
	jam();
	err = DropIndxRef::NotAnIndex;
	goto error;
      }
8577
      
8578 8579
      if (tmp.p->indexState != TableRecord::IS_ONLINE)
        req->addRequestFlag(RequestFlag::RF_FORCE);
joreland@mysql.com's avatar
joreland@mysql.com committed
8580 8581 8582

      tmp.p->indexState = TableRecord::IS_DROPPING;

8583 8584 8585
      req->setOpKey(++c_opRecordSequence);
      NodeReceiverGroup rg(DBDICT, c_aliveNodes);
      sendSignal(rg, GSN_DROP_INDX_REQ,
8586
		 signal, DropIndxReq::SignalLength + 1, JBB);
8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == DropIndxReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpDropIndex opBusy;
    if (! c_opDropIndex.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = DropIndxReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = DropIndxRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      dropIndex_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opDropIndex.add(opPtr);
    // master expects to hear from all
    if (opPtr.p->m_isMaster)
      opPtr.p->m_signalCounter = c_aliveNodes;
    dropIndex_slavePrepare(signal, opPtr);
    dropIndex_sendReply(signal, opPtr, false);
    return;
  }
  c_opDropIndex.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == DropIndxReq::RT_DICT_COMMIT ||
        requestType == DropIndxReq::RT_DICT_ABORT) {
      jam();
      if (requestType == DropIndxReq::RT_DICT_COMMIT)
        dropIndex_slaveCommit(signal, opPtr);
      else
        dropIndex_slaveAbort(signal, opPtr);
      dropIndex_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
        c_opDropIndex.release(opPtr);
      return;
    }
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
8632
error:
8633 8634 8635 8636 8637
  jam();
  // return to sender
  OpDropIndex opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
joreland@mysql.com's avatar
joreland@mysql.com committed
8638
  opPtr.p->m_errorCode = (DropIndxRef::ErrorCode)err;
8639
  opPtr.p->m_errorLine = __LINE__;
8640
  opPtr.p->m_errorNode = c_masterNodeId;
8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841
  dropIndex_sendReply(signal, opPtr, true);
}

void
Dbdict::execDROP_INDX_CONF(Signal* signal)
{
  jamEntry();
  DropIndxConf* conf = (DropIndxConf*)signal->getDataPtrSend();
  dropIndex_recvReply(signal, conf, 0);
}

void
Dbdict::execDROP_INDX_REF(Signal* signal) 
{
  jamEntry();
  DropIndxRef* ref = (DropIndxRef*)signal->getDataPtrSend();
  dropIndex_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::dropIndex_recvReply(Signal* signal, const DropIndxConf* conf,
    const DropIndxRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const DropIndxReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == DropIndxReq::RT_TC) {
    jam();
    // part of alter index operation
    OpAlterIndexPtr opPtr;
    c_opAlterIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterIndex_fromDropTc(signal, opPtr);
    return;
  }
  OpDropIndexPtr opPtr;
  c_opDropIndex.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  opPtr.p->setError(ref);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == DropIndxReq::RT_DICT_COMMIT ||
      requestType == DropIndxReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    dropIndex_sendReply(signal, opPtr, true);
    c_opDropIndex.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = DropIndxReq::RT_DICT_ABORT;
    dropIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  if (requestType == DropIndxReq::RT_DICT_PREPARE) {
    jam();
    // start alter offline
    dropIndex_toAlterIndex(signal, opPtr);
    return;
  }
  ndbrequire(false);
}

void
Dbdict::dropIndex_slavePrepare(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
  DropIndxReq* const req = &opPtr.p->m_request;
  // check index exists
  TableRecordPtr indexPtr;
  if (! (req->getIndexId() < c_tableRecordPool.getSize())) {
    jam();
    opPtr.p->m_errorCode = DropIndxRef::IndexNotFound;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  c_tableRecordPool.getPtr(indexPtr, req->getIndexId());
  if (indexPtr.p->tabState != TableRecord::DEFINED) {
    jam();
    opPtr.p->m_errorCode = DropIndxRef::IndexNotFound;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  if (! indexPtr.p->isIndex()) {
    jam();
    opPtr.p->m_errorCode = DropIndxRef::NotAnIndex;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  // ignore incoming primary table id
  req->setTableId(indexPtr.p->primaryTableId);
}

void
Dbdict::dropIndex_toAlterIndex(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
  AlterIndxReq* const req = (AlterIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(AlterIndxReq::RT_DROP_INDEX);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  req->setTableId(opPtr.p->m_request.getTableId());
  req->setIndexId(opPtr.p->m_request.getIndexId());
  req->setIndexVersion(opPtr.p->m_request.getIndexVersion());
  req->setOnline(false);
  sendSignal(reference(), GSN_ALTER_INDX_REQ,
      signal, AlterIndxReq::SignalLength, JBB);
}

void
Dbdict::dropIndex_fromAlterIndex(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = DropIndxReq::RT_DICT_ABORT;
    dropIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  dropIndex_toDropTable(signal, opPtr);
}

void
Dbdict::dropIndex_toDropTable(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
  DropTableReq* const req = (DropTableReq*)signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = opPtr.p->key;
  req->tableId = opPtr.p->m_request.getIndexId();
  req->tableVersion = opPtr.p->m_request.getIndexVersion();
  sendSignal(reference(), GSN_DROP_TABLE_REQ,
      signal,DropTableReq::SignalLength, JBB);
}

void
Dbdict::dropIndex_fromDropTable(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = DropIndxReq::RT_DICT_ABORT;
    dropIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  opPtr.p->m_requestType = DropIndxReq::RT_DICT_COMMIT;
  dropIndex_sendSlaveReq(signal, opPtr);
}

void
Dbdict::dropIndex_slaveCommit(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
}

void
Dbdict::dropIndex_slaveAbort(Signal* signal, OpDropIndexPtr opPtr)
{
  jam();
  DropIndxReq* const req = &opPtr.p->m_request;
  const Uint32 indexId = req->getIndexId();
  if (indexId >= c_tableRecordPool.getSize()) {
    jam();
    return;
  }
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, indexId);
  indexPtr.p->indexState = TableRecord::IS_BROKEN;
}

void
Dbdict::dropIndex_sendSlaveReq(Signal* signal, OpDropIndexPtr opPtr)
{
  DropIndxReq* const req = (DropIndxReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  opPtr.p->m_signalCounter = c_aliveNodes;
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
  sendSignal(rg, GSN_DROP_INDX_REQ,
      signal, DropIndxReq::SignalLength, JBB);
}

void
Dbdict::dropIndex_sendReply(Signal* signal, OpDropIndexPtr opPtr,
    bool toUser)
{
  DropIndxRef* rep = (DropIndxRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_DROP_INDX_CONF;
  Uint32 length = DropIndxConf::InternalLength;
8842
  bool sendRef;
8843
  if (! toUser) {
8844
    sendRef = opPtr.p->hasLastError();
8845 8846 8847 8848 8849 8850
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == DropIndxReq::RT_DICT_ABORT)
      sendRef = false;
  } else {
8851
    sendRef = opPtr.p->hasError();
8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = DropIndxConf::SignalLength;
  }
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setIndexId(opPtr.p->m_request.getIndexId());
  rep->setIndexVersion(opPtr.p->m_request.getIndexVersion());
  if (sendRef) {
    if (opPtr.p->m_errorNode == 0)
      opPtr.p->m_errorNode = getOwnNodeId();
    rep->setErrorCode(opPtr.p->m_errorCode);
    rep->setErrorLine(opPtr.p->m_errorLine);
    rep->setErrorNode(opPtr.p->m_errorNode);
    gsn = GSN_DROP_INDX_REF;
    length = DropIndxRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/*****************************************************
 *
 * Util signalling
 *
 *****************************************************/

int
Dbdict::sendSignalUtilReq(Callback *pcallback,
			  BlockReference ref, 
			  GlobalSignalNumber gsn, 
			  Signal* signal, 
			  Uint32 length, 
			  JobBufferLevel jbuf,
			  LinearSectionPtr ptr[3],
			  Uint32 noOfSections)
{
  jam();
  EVENT_TRACE;
  OpSignalUtilPtr utilRecPtr;

  // Seize a Util Send record
  if (!c_opSignalUtil.seize(utilRecPtr)) {
    // Failed to allocate util record
    return -1;
  }
  utilRecPtr.p->m_callback = *pcallback;

  // should work for all util signal classes
  UtilPrepareReq *req = (UtilPrepareReq*)signal->getDataPtrSend();
  utilRecPtr.p->m_userData = req->getSenderData();
  req->setSenderData(utilRecPtr.i);

  if (ptr) {
    jam();
    sendSignal(ref, gsn, signal, length, jbuf, ptr, noOfSections);
  } else {
    jam();
    sendSignal(ref, gsn, signal, length, jbuf);
  }

  return 0;
}

int
Dbdict::recvSignalUtilReq(Signal* signal, Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  UtilPrepareConf * const req = (UtilPrepareConf*)signal->getDataPtr();
  OpSignalUtilPtr utilRecPtr;
  utilRecPtr.i = req->getSenderData();
  if ((utilRecPtr.p = c_opSignalUtil.getPtr(utilRecPtr.i)) == NULL) {
    jam();
    return -1;
  }

  req->setSenderData(utilRecPtr.p->m_userData);
  Callback c = utilRecPtr.p->m_callback;
  c_opSignalUtil.release(utilRecPtr);

  execute(signal, c, returnCode);
  return 0;
}

void Dbdict::execUTIL_PREPARE_CONF(Signal *signal)
{
  jamEntry();
  EVENT_TRACE;
  ndbrequire(recvSignalUtilReq(signal, 0) == 0);
}

void
Dbdict::execUTIL_PREPARE_REF(Signal *signal)
{
  jamEntry();
  EVENT_TRACE;
  ndbrequire(recvSignalUtilReq(signal, 1) == 0);
}

void Dbdict::execUTIL_EXECUTE_CONF(Signal *signal)
{
  jamEntry();
  EVENT_TRACE;
   ndbrequire(recvSignalUtilReq(signal, 0) == 0);
}

void Dbdict::execUTIL_EXECUTE_REF(Signal *signal)
{
  jamEntry();
  EVENT_TRACE;

#ifdef EVENT_DEBUG
  UtilExecuteRef * ref = (UtilExecuteRef *)signal->getDataPtrSend();

  ndbout_c("execUTIL_EXECUTE_REF");
  ndbout_c("senderData %u",ref->getSenderData());
  ndbout_c("errorCode %u",ref->getErrorCode());
  ndbout_c("TCErrorCode %u",ref->getTCErrorCode());
#endif
  
  ndbrequire(recvSignalUtilReq(signal, 1) == 0);
}
void Dbdict::execUTIL_RELEASE_CONF(Signal *signal)
{
  jamEntry();
  EVENT_TRACE;
  ndbrequire(false);
  ndbrequire(recvSignalUtilReq(signal, 0) == 0);
}
void Dbdict::execUTIL_RELEASE_REF(Signal *signal)
{
  jamEntry();
  EVENT_TRACE;
  ndbrequire(false);
  ndbrequire(recvSignalUtilReq(signal, 1) == 0);
}

/**
 * MODULE: Create event
 *
 * Create event in DICT.
 * 
 *
 * Request type in CREATE_EVNT signals:
 *
 * Signalflow see Dbdict.txt
 *
 */

/*****************************************************************
 *
 * Systable stuff
 *
 */

const Uint32 Dbdict::sysTab_NDBEVENTS_0_szs[EVENT_SYSTEM_TABLE_LENGTH] = {
  sizeof(((sysTab_NDBEVENTS_0*)0)->NAME),
  sizeof(((sysTab_NDBEVENTS_0*)0)->EVENT_TYPE),
9010 9011
  sizeof(((sysTab_NDBEVENTS_0*)0)->TABLEID),
  sizeof(((sysTab_NDBEVENTS_0*)0)->TABLEVERSION),
9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024
  sizeof(((sysTab_NDBEVENTS_0*)0)->TABLE_NAME),
  sizeof(((sysTab_NDBEVENTS_0*)0)->ATTRIBUTE_MASK),
  sizeof(((sysTab_NDBEVENTS_0*)0)->SUBID),
  sizeof(((sysTab_NDBEVENTS_0*)0)->SUBKEY)
};

void
Dbdict::prepareTransactionEventSysTable (Callback *pcallback,
					 Signal* signal,
					 Uint32 senderData,
					 UtilPrepareReq::OperationTypeValue prepReq)
{
  // find table id for event system table
9025 9026
  DictObject * opj_ptr_p = get_object(EVENT_SYSTEM_TABLE_NAME,
				      sizeof(EVENT_SYSTEM_TABLE_NAME));
9027

9028
  ndbrequire(opj_ptr_p != 0);
9029
  TableRecordPtr tablePtr;
9030
  c_tableRecordPool.getPtr(tablePtr, opj_ptr_p->m_id);
9031
  ndbrequire(tablePtr.i != RNIL); // system table must exist
9032
  
9033 9034 9035
  Uint32 tableId = tablePtr.p->tableId; /* System table */
  Uint32 noAttr = tablePtr.p->noOfAttributes;
  ndbrequire(noAttr == EVENT_SYSTEM_TABLE_LENGTH);
9036
  
9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219
  switch (prepReq) {
  case UtilPrepareReq::Update:
  case UtilPrepareReq::Insert:
  case UtilPrepareReq::Write:
  case UtilPrepareReq::Read:
    jam();
    break;
  case UtilPrepareReq::Delete:
    jam();
    noAttr = 1; // only involves Primary key which should be the first
    break;
  }
  prepareUtilTransaction(pcallback, signal, senderData, tableId, NULL,
		      prepReq, noAttr, NULL, NULL);
}

void
Dbdict::prepareUtilTransaction(Callback *pcallback,
			       Signal* signal,
			       Uint32 senderData,
			       Uint32 tableId,
			       const char* tableName,
			       UtilPrepareReq::OperationTypeValue prepReq,
			       Uint32 noAttr,
			       Uint32 attrIds[],
			       const char *attrNames[])
{
  jam();
  EVENT_TRACE;

  UtilPrepareReq * utilPrepareReq = 
    (UtilPrepareReq *)signal->getDataPtrSend();
  
  utilPrepareReq->setSenderRef(reference());
  utilPrepareReq->setSenderData(senderData);

  const Uint32 pageSizeInWords = 128;
  Uint32 propPage[pageSizeInWords];
  LinearWriter w(&propPage[0],128);
  w.first();
  w.add(UtilPrepareReq::NoOfOperations, 1);
  w.add(UtilPrepareReq::OperationType, prepReq);
  if (tableName) {
    jam();
    w.add(UtilPrepareReq::TableName, tableName);
  } else {
    jam();
    w.add(UtilPrepareReq::TableId, tableId);
  }
  for(Uint32 i = 0; i < noAttr; i++)
    if (tableName) {
      jam();
      w.add(UtilPrepareReq::AttributeName, attrNames[i]);
    } else {
      if (attrIds) {
	jam();
	w.add(UtilPrepareReq::AttributeId, attrIds[i]);
      } else {
	jam();
	w.add(UtilPrepareReq::AttributeId, i);
      }
    }
#ifdef EVENT_DEBUG
  // Debugging
  SimplePropertiesLinearReader reader(propPage, w.getWordsUsed());
  printf("Dict::prepareInsertTransactions: Sent SimpleProperties:\n");
  reader.printAll(ndbout);
#endif

  struct LinearSectionPtr sectionsPtr[UtilPrepareReq::NoOfSections];
  sectionsPtr[UtilPrepareReq::PROPERTIES_SECTION].p = propPage;
  sectionsPtr[UtilPrepareReq::PROPERTIES_SECTION].sz = w.getWordsUsed();

  sendSignalUtilReq(pcallback, DBUTIL_REF, GSN_UTIL_PREPARE_REQ, signal,
		    UtilPrepareReq::SignalLength, JBB, 
		    sectionsPtr, UtilPrepareReq::NoOfSections);
}

/*****************************************************************
 *
 * CREATE_EVNT_REQ has three types RT_CREATE, RT_GET (from user)
 * and RT_DICT_AFTER_GET send from master DICT to slaves
 *
 * This function just dscpaches these to
 *
 * createEvent_RT_USER_CREATE
 * createEvent_RT_USER_GET
 * createEvent_RT_DICT_AFTER_GET
 *
 * repectively
 *
 */

void
Dbdict::execCREATE_EVNT_REQ(Signal* signal)
{
  jamEntry();

#if 0
  {
    SafeCounterHandle handle;
    {
      SafeCounter tmp(c_counterMgr, handle);
      tmp.init<CreateEvntRef>(CMVMI, GSN_DUMP_STATE_ORD, /* senderData */ 13);
      tmp.clearWaitingFor();
      tmp.setWaitingFor(3);
      ndbrequire(!tmp.done());
      ndbout_c("Allocted");
    }
    ndbrequire(!handle.done());
    {
      SafeCounter tmp(c_counterMgr, handle);
      tmp.clearWaitingFor(3);
      ndbrequire(tmp.done());
      ndbout_c("Deallocted");
    }
    ndbrequire(handle.done());
  }
  {
    NodeBitmask nodes;
    nodes.clear();

    nodes.set(2);
    nodes.set(3);
    nodes.set(4);
    nodes.set(5);

    {
      Uint32 i = 0;
      while((i = nodes.find(i)) != NodeBitmask::NotFound){
	ndbout_c("1 Node id = %u", i);
	i++;
      }
    }

    NodeReceiverGroup rg(DBDICT, nodes);
    RequestTracker rt2;
    ndbrequire(rt2.done());
    ndbrequire(!rt2.hasRef());
    ndbrequire(!rt2.hasConf());
    rt2.init<CreateEvntRef>(c_counterMgr, rg, GSN_CREATE_EVNT_REF, 13);

    RequestTracker rt3;
    rt3.init<CreateEvntRef>(c_counterMgr, rg, GSN_CREATE_EVNT_REF, 13);

    ndbrequire(!rt2.done());
    ndbrequire(!rt3.done());

    rt2.reportRef(c_counterMgr, 2);
    rt3.reportConf(c_counterMgr, 2);

    ndbrequire(!rt2.done());
    ndbrequire(!rt3.done());

    rt2.reportConf(c_counterMgr, 3);
    rt3.reportConf(c_counterMgr, 3);

    ndbrequire(!rt2.done());
    ndbrequire(!rt3.done());

    rt2.reportConf(c_counterMgr, 4);
    rt3.reportConf(c_counterMgr, 4);

    ndbrequire(!rt2.done());
    ndbrequire(!rt3.done());

    rt2.reportConf(c_counterMgr, 5);
    rt3.reportConf(c_counterMgr, 5);

    ndbrequire(rt2.done());
    ndbrequire(rt3.done());
  }
#endif

  if (! assembleFragments(signal)) {
    jam();
    return;
  }

  CreateEvntReq *req = (CreateEvntReq*)signal->getDataPtr();
  const CreateEvntReq::RequestType requestType = req->getRequestType();
  const Uint32                     requestFlag = req->getRequestFlag();

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236
  if (refToBlock(signal->senderBlockRef()) != DBDICT &&
      getOwnNodeId() != c_masterNodeId)
  {
    jam();
    releaseSections(signal);
    
    CreateEvntRef * ref = (CreateEvntRef *)signal->getDataPtrSend();
    ref->setUserRef(reference());
    ref->setErrorCode(CreateEvntRef::NotMaster);
    ref->setErrorLine(__LINE__);
    ref->setErrorNode(reference());
    ref->setMasterNode(c_masterNodeId);
    sendSignal(signal->senderBlockRef(), GSN_CREATE_EVNT_REF, signal,
	       CreateEvntRef::SignalLength2, JBB);
    return;
  }

9237 9238 9239 9240 9241 9242 9243 9244 9245
  OpCreateEventPtr evntRecPtr;
  // Seize a Create Event record
  if (!c_opCreateEvent.seize(evntRecPtr)) {
    // Failed to allocate event record
    jam();
    releaseSections(signal);

    CreateEvntRef * ret = (CreateEvntRef *)signal->getDataPtrSend();
    ret->senderRef = reference();
9246
    ret->setErrorCode(747);
9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286
    ret->setErrorLine(__LINE__);
    ret->setErrorNode(reference());
    sendSignal(signal->senderBlockRef(), GSN_CREATE_EVNT_REF, signal,
	       CreateEvntRef::SignalLength, JBB);
    return;
  }

#ifdef EVENT_DEBUG
  ndbout_c("DBDICT::execCREATE_EVNT_REQ from %u evntRecId = (%d)", refToNode(signal->getSendersBlockRef()), evntRecPtr.i);
#endif
  
  ndbrequire(req->getUserRef() == signal->getSendersBlockRef());

  evntRecPtr.p->init(req,this);

  if (requestFlag & (Uint32)CreateEvntReq::RT_DICT_AFTER_GET) {
    jam();
    EVENT_TRACE;
    createEvent_RT_DICT_AFTER_GET(signal, evntRecPtr);
    return;
  }
  if (requestType == CreateEvntReq::RT_USER_GET) {
    jam();
    EVENT_TRACE;
    createEvent_RT_USER_GET(signal, evntRecPtr);
    return;
  }
  if (requestType == CreateEvntReq::RT_USER_CREATE) {
    jam();
    EVENT_TRACE;
    createEvent_RT_USER_CREATE(signal, evntRecPtr);
    return;
  }

#ifdef EVENT_DEBUG
  ndbout << "Dbdict.cpp: Dbdict::execCREATE_EVNT_REQ other" << endl;
#endif
  jam();
  releaseSections(signal);
    
9287
  evntRecPtr.p->m_errorCode = 1;
9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300
  evntRecPtr.p->m_errorLine = __LINE__;
  evntRecPtr.p->m_errorNode = reference();
  
  createEvent_sendReply(signal, evntRecPtr);
}

/********************************************************************
 *
 * Event creation
 *
 *****************************************************************/

void
9301 9302
Dbdict::createEvent_RT_USER_CREATE(Signal* signal, OpCreateEventPtr evntRecPtr)
{
9303
  jam();
9304
  DBUG_ENTER("Dbdict::createEvent_RT_USER_CREATE");
9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331
  evntRecPtr.p->m_request.setUserRef(signal->senderBlockRef());

#ifdef EVENT_DEBUG
  ndbout << "Dbdict.cpp: Dbdict::execCREATE_EVNT_REQ RT_USER" << endl;
  char buf[128] = {0};
  AttributeMask mask = evntRecPtr.p->m_request.getAttrListBitmask(); 
  mask.getText(buf);
  ndbout_c("mask = %s", buf);
#endif

  // Interpret the long signal

  SegmentedSectionPtr ssPtr;
  // save name and event properties
  signal->getSection(ssPtr, CreateEvntReq::EVENT_NAME_SECTION);

  SimplePropertiesSectionReader r0(ssPtr, getSectionSegmentPool());
#ifdef EVENT_DEBUG
  r0.printAll(ndbout);
#endif
    // event name
  if ((!r0.first()) ||
      (r0.getValueType() != SimpleProperties::StringValue) ||
      (r0.getValueLen() <= 0)) {
    jam();
    releaseSections(signal);

9332
    evntRecPtr.p->m_errorCode = 1;
9333 9334 9335 9336
    evntRecPtr.p->m_errorLine = __LINE__;
    evntRecPtr.p->m_errorNode = reference();

    createEvent_sendReply(signal, evntRecPtr);
9337
    DBUG_VOID_RETURN;
9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357
  }
  r0.getString(evntRecPtr.p->m_eventRec.NAME);
  {
    int len = strlen(evntRecPtr.p->m_eventRec.NAME);
    memset(evntRecPtr.p->m_eventRec.NAME+len, 0, MAX_TAB_NAME_SIZE-len);
#ifdef EVENT_DEBUG
    printf("CreateEvntReq::RT_USER_CREATE; EventName %s, len %u\n",
	   evntRecPtr.p->m_eventRec.NAME, len);
    for(int i = 0; i < MAX_TAB_NAME_SIZE/4; i++)
      printf("H'%.8x ", ((Uint32*)evntRecPtr.p->m_eventRec.NAME)[i]);
    printf("\n");
#endif
  }
  // table name
  if ((!r0.next()) ||
      (r0.getValueType() != SimpleProperties::StringValue) ||
      (r0.getValueLen() <= 0)) {
    jam();
    releaseSections(signal);
    
9358
    evntRecPtr.p->m_errorCode = 1;
9359 9360 9361 9362
    evntRecPtr.p->m_errorLine = __LINE__;
    evntRecPtr.p->m_errorNode = reference();
    
    createEvent_sendReply(signal, evntRecPtr);
9363
    DBUG_VOID_RETURN;
9364 9365 9366 9367 9368 9369
  }
  r0.getString(evntRecPtr.p->m_eventRec.TABLE_NAME);
  {
    int len = strlen(evntRecPtr.p->m_eventRec.TABLE_NAME);
    memset(evntRecPtr.p->m_eventRec.TABLE_NAME+len, 0, MAX_TAB_NAME_SIZE-len);
  }
9370

9371 9372 9373 9374 9375 9376 9377 9378
  releaseSections(signal);
  
  // Send request to SUMA

  CreateSubscriptionIdReq * sumaIdReq =
    (CreateSubscriptionIdReq *)signal->getDataPtrSend();
  
  // make sure we save the original sender for later
9379
  sumaIdReq->senderRef  = reference();
9380 9381 9382 9383 9384 9385 9386 9387
  sumaIdReq->senderData = evntRecPtr.i;
#ifdef EVENT_DEBUG
  ndbout << "sumaIdReq->senderData = " << sumaIdReq->senderData << endl;
#endif
  sendSignal(SUMA_REF, GSN_CREATE_SUBID_REQ, signal, 
	     CreateSubscriptionIdReq::SignalLength, JBB);
  // we should now return in either execCREATE_SUBID_CONF
  // or execCREATE_SUBID_REF
9388
  DBUG_VOID_RETURN;
9389 9390 9391 9392
}

void Dbdict::execCREATE_SUBID_REF(Signal* signal)
{
9393 9394
  jamEntry();
  DBUG_ENTER("Dbdict::execCREATE_SUBID_REF");
9395 9396 9397 9398 9399 9400 9401
  CreateSubscriptionIdRef * const ref =
    (CreateSubscriptionIdRef *)signal->getDataPtr();
  OpCreateEventPtr evntRecPtr;

  evntRecPtr.i = ref->senderData;
  ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);

9402 9403 9404 9405 9406 9407 9408 9409 9410 9411
  if (ref->errorCode)
  {
    evntRecPtr.p->m_errorCode = ref->errorCode;
    evntRecPtr.p->m_errorLine = __LINE__;
  }
  else
  {
    evntRecPtr.p->m_errorCode = 1;
    evntRecPtr.p->m_errorLine = __LINE__;
  }
9412 9413 9414
  evntRecPtr.p->m_errorNode = reference();

  createEvent_sendReply(signal, evntRecPtr);
9415
  DBUG_VOID_RETURN;
9416 9417 9418 9419 9420
}

void Dbdict::execCREATE_SUBID_CONF(Signal* signal)
{
  jamEntry();
9421
  DBUG_ENTER("Dbdict::execCREATE_SUBID_CONF");
9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439

  CreateSubscriptionIdConf const * sumaIdConf =
    (CreateSubscriptionIdConf *)signal->getDataPtr();

  Uint32 evntRecId = sumaIdConf->senderData;
  OpCreateEvent *evntRec;

  ndbrequire((evntRec = c_opCreateEvent.getPtr(evntRecId)) != NULL);

  evntRec->m_request.setEventId(sumaIdConf->subscriptionId);
  evntRec->m_request.setEventKey(sumaIdConf->subscriptionKey);

  releaseSections(signal);

  Callback c = { safe_cast(&Dbdict::createEventUTIL_PREPARE), 0 };

  prepareTransactionEventSysTable(&c, signal, evntRecId,
				  UtilPrepareReq::Insert);
9440
  DBUG_VOID_RETURN;
9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457
}

void
Dbdict::createEventComplete_RT_USER_CREATE(Signal* signal,
					   OpCreateEventPtr evntRecPtr){
  jam();
  createEvent_sendReply(signal, evntRecPtr);
}

/*********************************************************************
 *
 * UTIL_PREPARE, UTIL_EXECUTE
 *
 * insert or read systable NDB$EVENTS_0
 */

void interpretUtilPrepareErrorCode(UtilPrepareRef::ErrorCode errorCode,
9458
				   Uint32& error, Uint32& line)
9459
{
9460
  DBUG_ENTER("interpretUtilPrepareErrorCode");
9461 9462 9463
  switch (errorCode) {
  case UtilPrepareRef::NO_ERROR:
    jam();
9464
    error = 1;
9465
    line = __LINE__;
9466
    DBUG_VOID_RETURN;
9467 9468
  case UtilPrepareRef::PREPARE_SEIZE_ERROR:
    jam();
9469
    error = 748;
9470
    line = __LINE__;
9471
    DBUG_VOID_RETURN;
9472 9473
  case UtilPrepareRef::PREPARE_PAGES_SEIZE_ERROR:
    jam();
9474
    error = 1;
9475
    line = __LINE__;
9476
    DBUG_VOID_RETURN;
9477 9478
  case UtilPrepareRef::PREPARED_OPERATION_SEIZE_ERROR:
    jam();
9479
    error = 1;
9480
    line = __LINE__;
9481
    DBUG_VOID_RETURN;
9482 9483
  case UtilPrepareRef::DICT_TAB_INFO_ERROR:
    jam();
9484
    error = 1;
9485
    line = __LINE__;
9486
    DBUG_VOID_RETURN;
9487 9488
  case UtilPrepareRef::MISSING_PROPERTIES_SECTION:
    jam();
9489
    error = 1;
9490
    line = __LINE__;
9491
    DBUG_VOID_RETURN;
9492 9493
  default:
    jam();
9494
    error = 1;
9495
    line = __LINE__;
9496
    DBUG_VOID_RETURN;
9497
  }
9498
  DBUG_VOID_RETURN;
9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527
}

void 
Dbdict::createEventUTIL_PREPARE(Signal* signal,
				Uint32 callbackData,
				Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  if (returnCode == 0) {
    UtilPrepareConf* const req = (UtilPrepareConf*)signal->getDataPtr();
    OpCreateEventPtr evntRecPtr;
    jam();
    evntRecPtr.i = req->getSenderData();
    const Uint32 prepareId = req->getPrepareId();
    
    ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);
    
    Callback c = { safe_cast(&Dbdict::createEventUTIL_EXECUTE), 0 };

    switch (evntRecPtr.p->m_requestType) {
    case CreateEvntReq::RT_USER_GET:
      jam();
      executeTransEventSysTable(&c, signal,
				evntRecPtr.i, evntRecPtr.p->m_eventRec,
				prepareId, UtilPrepareReq::Read);
      break;
    case CreateEvntReq::RT_USER_CREATE:
      {
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9528 9529
	evntRecPtr.p->m_eventRec.EVENT_TYPE =
          evntRecPtr.p->m_request.getEventType() | evntRecPtr.p->m_request.getReportFlags();
9530 9531
	evntRecPtr.p->m_eventRec.TABLEID  = evntRecPtr.p->m_request.getTableId();
	evntRecPtr.p->m_eventRec.TABLEVERSION=evntRecPtr.p->m_request.getTableVersion();
9532 9533 9534 9535 9536
	AttributeMask m = evntRecPtr.p->m_request.getAttrListBitmask();
	memcpy(evntRecPtr.p->m_eventRec.ATTRIBUTE_MASK, &m,
	       sizeof(evntRecPtr.p->m_eventRec.ATTRIBUTE_MASK));
	evntRecPtr.p->m_eventRec.SUBID  = evntRecPtr.p->m_request.getEventId();
	evntRecPtr.p->m_eventRec.SUBKEY = evntRecPtr.p->m_request.getEventKey();
9537 9538 9539 9540 9541 9542 9543
	DBUG_PRINT("info",
		   ("CREATE: event name: %s table name: %s table id: %u table version: %u",
		    evntRecPtr.p->m_eventRec.NAME,
		    evntRecPtr.p->m_eventRec.TABLE_NAME,
		    evntRecPtr.p->m_eventRec.TABLEID,
		    evntRecPtr.p->m_eventRec.TABLEVERSION));
  
9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567
      }
      jam();
      executeTransEventSysTable(&c, signal,
				evntRecPtr.i, evntRecPtr.p->m_eventRec,
				prepareId, UtilPrepareReq::Insert);
      break;
    default:
#ifdef EVENT_DEBUG
      printf("type = %d\n", evntRecPtr.p->m_requestType);
      printf("bet type = %d\n", CreateEvntReq::RT_USER_GET);
      printf("create type = %d\n", CreateEvntReq::RT_USER_CREATE);
#endif
      ndbrequire(false);
    }
  } else { // returnCode != 0
    UtilPrepareRef* const ref = (UtilPrepareRef*)signal->getDataPtr();

    const UtilPrepareRef::ErrorCode errorCode =
      (UtilPrepareRef::ErrorCode)ref->getErrorCode();

    OpCreateEventPtr evntRecPtr;
    evntRecPtr.i = ref->getSenderData();
    ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);

9568 9569
    interpretUtilPrepareErrorCode(errorCode, evntRecPtr.p->m_errorCode,
				  evntRecPtr.p->m_errorLine);
9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591
    evntRecPtr.p->m_errorNode = reference();

    createEvent_sendReply(signal, evntRecPtr);
  }
}

void Dbdict::executeTransEventSysTable(Callback *pcallback, Signal *signal,
				       const Uint32 ptrI,
				       sysTab_NDBEVENTS_0& m_eventRec,
				       const Uint32 prepareId,
				       UtilPrepareReq::OperationTypeValue prepReq)
{
  jam();
  const Uint32 noAttr = EVENT_SYSTEM_TABLE_LENGTH;
  Uint32 total_len = 0;

  Uint32* attrHdr = signal->theData + 25;
  Uint32* attrPtr = attrHdr;

  Uint32 id=0;
  // attribute 0 event name: Primary Key
  {
9592
    AttributeHeader::init(attrPtr, id, sysTab_NDBEVENTS_0_szs[id]);
9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609
    total_len += sysTab_NDBEVENTS_0_szs[id];
    attrPtr++; id++;
  }

  switch (prepReq) {
  case UtilPrepareReq::Read:
    jam();
    EVENT_TRACE;
    // no more
    while ( id < noAttr )
      AttributeHeader::init(attrPtr++, id++, 0);
    ndbrequire(id == (Uint32) noAttr);
    break;
  case UtilPrepareReq::Insert:
    jam();
    EVENT_TRACE;
    while ( id < noAttr ) {
9610
      AttributeHeader::init(attrPtr, id, sysTab_NDBEVENTS_0_szs[id]);
9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742
      total_len += sysTab_NDBEVENTS_0_szs[id];
      attrPtr++; id++;
    }
    ndbrequire(id == (Uint32) noAttr);
    break;
  case UtilPrepareReq::Delete:
    ndbrequire(id == 1);
    break;
  default:
    ndbrequire(false);
  }
    
  LinearSectionPtr headerPtr;
  LinearSectionPtr dataPtr;
    
  headerPtr.p = attrHdr;
  headerPtr.sz = noAttr;
    
  dataPtr.p = (Uint32*)&m_eventRec;
  dataPtr.sz = total_len/4;

  ndbrequire((total_len == sysTab_NDBEVENTS_0_szs[0]) ||
	     (total_len == sizeof(sysTab_NDBEVENTS_0)));

#if 0
    printf("Header size %u\n", headerPtr.sz);
    for(int i = 0; i < (int)headerPtr.sz; i++)
      printf("H'%.8x ", attrHdr[i]);
    printf("\n");
    
    printf("Data size %u\n", dataPtr.sz);
    for(int i = 0; i < (int)dataPtr.sz; i++)
      printf("H'%.8x ", dataPage[i]);
    printf("\n");
#endif

  executeTransaction(pcallback, signal, 
		     ptrI,
		     prepareId,
		     id,
		     headerPtr,
		     dataPtr);
}

void Dbdict::executeTransaction(Callback *pcallback,
				Signal* signal, 
				Uint32 senderData,
				Uint32 prepareId,
				Uint32 noAttr,
				LinearSectionPtr headerPtr,
				LinearSectionPtr dataPtr)
{
  jam();
  EVENT_TRACE;

  UtilExecuteReq * utilExecuteReq = 
    (UtilExecuteReq *)signal->getDataPtrSend();

  utilExecuteReq->setSenderRef(reference());
  utilExecuteReq->setSenderData(senderData);
  utilExecuteReq->setPrepareId(prepareId);
  utilExecuteReq->setReleaseFlag(); // must be done after setting prepareId

#if 0
  printf("Header size %u\n", headerPtr.sz);
  for(int i = 0; i < (int)headerPtr.sz; i++)
    printf("H'%.8x ", headerBuffer[i]);
  printf("\n");
  
  printf("Data size %u\n", dataPtr.sz);
  for(int i = 0; i < (int)dataPtr.sz; i++)
    printf("H'%.8x ", dataBuffer[i]);
  printf("\n");
#endif

  struct LinearSectionPtr sectionsPtr[UtilExecuteReq::NoOfSections];
  sectionsPtr[UtilExecuteReq::HEADER_SECTION].p = headerPtr.p;
  sectionsPtr[UtilExecuteReq::HEADER_SECTION].sz = noAttr;
  sectionsPtr[UtilExecuteReq::DATA_SECTION].p = dataPtr.p;
  sectionsPtr[UtilExecuteReq::DATA_SECTION].sz = dataPtr.sz;

  sendSignalUtilReq(pcallback, DBUTIL_REF, GSN_UTIL_EXECUTE_REQ, signal,
		    UtilExecuteReq::SignalLength, JBB,
		    sectionsPtr, UtilExecuteReq::NoOfSections);
}

void Dbdict::parseReadEventSys(Signal* signal, sysTab_NDBEVENTS_0& m_eventRec)
{
  SegmentedSectionPtr headerPtr, dataPtr;
  jam();
  signal->getSection(headerPtr, UtilExecuteReq::HEADER_SECTION);
  SectionReader headerReader(headerPtr, getSectionSegmentPool());
      
  signal->getSection(dataPtr, UtilExecuteReq::DATA_SECTION);
  SectionReader dataReader(dataPtr, getSectionSegmentPool());
  
  AttributeHeader header;
  Uint32 *dst = (Uint32*)&m_eventRec;

  for (int i = 0; i < EVENT_SYSTEM_TABLE_LENGTH; i++) {
    headerReader.getWord((Uint32 *)&header);
    int sz = header.getDataSize();
    for (int i=0; i < sz; i++)
      dataReader.getWord(dst++);
  }

  ndbrequire( ((char*)dst-(char*)&m_eventRec) == sizeof(m_eventRec) );

  releaseSections(signal);
}
    
void Dbdict::createEventUTIL_EXECUTE(Signal *signal, 
				     Uint32 callbackData,
				     Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  if (returnCode == 0) {
    // Entry into system table all set
    UtilExecuteConf* const conf = (UtilExecuteConf*)signal->getDataPtr();
    jam();
    OpCreateEventPtr evntRecPtr;
    evntRecPtr.i = conf->getSenderData();
    
    ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);
    OpCreateEvent *evntRec = evntRecPtr.p;
    
    switch (evntRec->m_requestType) {
    case CreateEvntReq::RT_USER_GET: {
      parseReadEventSys(signal, evntRecPtr.p->m_eventRec);

      evntRec->m_request.setEventType(evntRecPtr.p->m_eventRec.EVENT_TYPE);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9743
      evntRec->m_request.setReportFlags(evntRecPtr.p->m_eventRec.EVENT_TYPE);
9744 9745 9746 9747
      evntRec->m_request.setTableId(evntRecPtr.p->m_eventRec.TABLEID);
      evntRec->m_request.setTableVersion(evntRecPtr.p->m_eventRec.TABLEVERSION);
      evntRec->m_request.setAttrListBitmask(*(AttributeMask*)
					    evntRecPtr.p->m_eventRec.ATTRIBUTE_MASK);
9748 9749 9750
      evntRec->m_request.setEventId(evntRecPtr.p->m_eventRec.SUBID);
      evntRec->m_request.setEventKey(evntRecPtr.p->m_eventRec.SUBKEY);

9751 9752 9753 9754 9755 9756
      DBUG_PRINT("info",
		 ("GET: event name: %s table name: %s table id: %u table version: %u",
		  evntRecPtr.p->m_eventRec.NAME,
		  evntRecPtr.p->m_eventRec.TABLE_NAME,
		  evntRecPtr.p->m_eventRec.TABLEID,
		  evntRecPtr.p->m_eventRec.TABLEVERSION));
9757 9758
      
      // find table id for event table
9759 9760
      DictObject* obj_ptr_p = get_object(evntRecPtr.p->m_eventRec.TABLE_NAME);
      if(!obj_ptr_p){
9761
	jam();
9762
	evntRecPtr.p->m_errorCode = 723;
9763 9764 9765 9766 9767 9768 9769
	evntRecPtr.p->m_errorLine = __LINE__;
	evntRecPtr.p->m_errorNode = reference();
	
	createEvent_sendReply(signal, evntRecPtr);
	return;
      }
      
9770 9771
      TableRecordPtr tablePtr;
      c_tableRecordPool.getPtr(tablePtr, obj_ptr_p->m_id);
9772
      evntRec->m_request.setTableId(tablePtr.p->tableId);
9773
      evntRec->m_request.setTableVersion(tablePtr.p->tableVersion);
9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803
      
      createEventComplete_RT_USER_GET(signal, evntRecPtr);
      return;
    }
    case CreateEvntReq::RT_USER_CREATE: {
#ifdef EVENT_DEBUG
      printf("create type = %d\n", CreateEvntReq::RT_USER_CREATE);
#endif
      jam();
      createEventComplete_RT_USER_CREATE(signal, evntRecPtr);
      return;
    }
      break;
    default:
      ndbrequire(false);
    }
  } else { // returnCode != 0
    UtilExecuteRef * const ref = (UtilExecuteRef *)signal->getDataPtr();
    OpCreateEventPtr evntRecPtr;
    evntRecPtr.i = ref->getSenderData();
    ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);
    jam();
    evntRecPtr.p->m_errorNode = reference();
    evntRecPtr.p->m_errorLine = __LINE__;

    switch (ref->getErrorCode()) {
    case UtilExecuteRef::TCError:
      switch (ref->getTCErrorCode()) {
      case ZNOT_FOUND:
	jam();
9804
	evntRecPtr.p->m_errorCode = 4710;
9805 9806 9807
	break;
      case ZALREADYEXIST:
	jam();
9808
	evntRecPtr.p->m_errorCode = 746;
9809 9810 9811
	break;
      default:
	jam();
9812
	evntRecPtr.p->m_errorCode = ref->getTCErrorCode();
9813 9814 9815 9816 9817
	break;
      }
      break;
    default:
      jam();
9818
      evntRecPtr.p->m_errorCode = ref->getErrorCode();
9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853
      break;
    }
    
    createEvent_sendReply(signal, evntRecPtr);
  }
}

/***********************************************************************
 *
 * NdbEventOperation, reading systable, creating event in suma
 *
 */

void
Dbdict::createEvent_RT_USER_GET(Signal* signal, OpCreateEventPtr evntRecPtr){
  jam();
  EVENT_TRACE;
#ifdef EVENT_PH2_DEBUG
  ndbout_c("DBDICT(Coordinator) got GSN_CREATE_EVNT_REQ::RT_USER_GET evntRecPtr.i = (%d), ref = %u", evntRecPtr.i, evntRecPtr.p->m_request.getUserRef());
#endif

  SegmentedSectionPtr ssPtr;

  signal->getSection(ssPtr, 0);

  SimplePropertiesSectionReader r0(ssPtr, getSectionSegmentPool());
#ifdef EVENT_DEBUG
  r0.printAll(ndbout);
#endif
  if ((!r0.first()) ||
      (r0.getValueType() != SimpleProperties::StringValue) ||
      (r0.getValueLen() <= 0)) {
    jam();
    releaseSections(signal);

9854
    evntRecPtr.p->m_errorCode = 1;
9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896
    evntRecPtr.p->m_errorLine = __LINE__;
    evntRecPtr.p->m_errorNode = reference();

    createEvent_sendReply(signal, evntRecPtr);
    return;
  }

  r0.getString(evntRecPtr.p->m_eventRec.NAME);
  int len = strlen(evntRecPtr.p->m_eventRec.NAME);
  memset(evntRecPtr.p->m_eventRec.NAME+len, 0, MAX_TAB_NAME_SIZE-len);
  
  releaseSections(signal);
  
  Callback c = { safe_cast(&Dbdict::createEventUTIL_PREPARE), 0 };
  
  prepareTransactionEventSysTable(&c, signal, evntRecPtr.i,
				  UtilPrepareReq::Read);
  /* 
   * Will read systable and fill an OpCreateEventPtr
   * and return below
   */
}

void
Dbdict::createEventComplete_RT_USER_GET(Signal* signal,
					OpCreateEventPtr evntRecPtr){
  jam();

  // Send to oneself and the other DICT's
  CreateEvntReq * req = (CreateEvntReq *)signal->getDataPtrSend();
      
  *req = evntRecPtr.p->m_request;
  req->senderRef = reference();
  req->senderData = evntRecPtr.i;
      
  req->addRequestFlag(CreateEvntReq::RT_DICT_AFTER_GET);
      
#ifdef EVENT_PH2_DEBUG
  ndbout_c("DBDICT(Coordinator) sending GSN_CREATE_EVNT_REQ::RT_DICT_AFTER_GET to DBDICT participants evntRecPtr.i = (%d)", evntRecPtr.i);
#endif

  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
9897
  RequestTracker & p = evntRecPtr.p->m_reqTracker;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9898 9899 9900 9901 9902 9903 9904 9905
  if (!p.init<CreateEvntRef>(c_counterMgr, rg, GSN_CREATE_EVNT_REF, 
			     evntRecPtr.i))
  {
    jam();
    evntRecPtr.p->m_errorCode = 701;
    createEvent_sendReply(signal, evntRecPtr);
    return;
  }
mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
9906

9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981
  sendSignal(rg, GSN_CREATE_EVNT_REQ, signal, CreateEvntReq::SignalLength, JBB);
}

void
Dbdict::createEvent_nodeFailCallback(Signal* signal, Uint32 eventRecPtrI,
				     Uint32 returnCode){
  OpCreateEventPtr evntRecPtr;
  c_opCreateEvent.getPtr(evntRecPtr, eventRecPtrI);
  createEvent_sendReply(signal, evntRecPtr);
}

void Dbdict::execCREATE_EVNT_REF(Signal* signal) 
{
  jamEntry();      
  EVENT_TRACE;
  CreateEvntRef * const ref = (CreateEvntRef *)signal->getDataPtr();
  OpCreateEventPtr evntRecPtr;

  evntRecPtr.i = ref->getUserData();

  ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);

#ifdef EVENT_PH2_DEBUG
  ndbout_c("DBDICT(Coordinator) got GSN_CREATE_EVNT_REF evntRecPtr.i = (%d)", evntRecPtr.i);
#endif

  if (ref->errorCode == CreateEvntRef::NF_FakeErrorREF){
    jam();
    evntRecPtr.p->m_reqTracker.ignoreRef(c_counterMgr, refToNode(ref->senderRef));
  } else {
    jam();
    evntRecPtr.p->m_reqTracker.reportRef(c_counterMgr, refToNode(ref->senderRef));
  }
  createEvent_sendReply(signal, evntRecPtr);

  return;
}

void Dbdict::execCREATE_EVNT_CONF(Signal* signal)
{
  jamEntry();
  EVENT_TRACE;
  CreateEvntConf * const conf = (CreateEvntConf *)signal->getDataPtr();
  OpCreateEventPtr evntRecPtr;

  evntRecPtr.i = conf->getUserData();

  ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);

#ifdef EVENT_PH2_DEBUG
  ndbout_c("DBDICT(Coordinator) got GSN_CREATE_EVNT_CONF evntRecPtr.i = (%d)", evntRecPtr.i);
#endif

  evntRecPtr.p->m_reqTracker.reportConf(c_counterMgr, refToNode(conf->senderRef));

  // we will only have a valid tablename if it the master DICT sending this
  // but that's ok
  LinearSectionPtr ptr[1];
  ptr[0].p = (Uint32 *)evntRecPtr.p->m_eventRec.TABLE_NAME;
  ptr[0].sz =
    (strlen(evntRecPtr.p->m_eventRec.TABLE_NAME)+4)/4; // to make sure we have a null

  createEvent_sendReply(signal, evntRecPtr, ptr, 1);
    
  return;
}

/************************************************
 *
 * Participant stuff
 *
 */

void
Dbdict::createEvent_RT_DICT_AFTER_GET(Signal* signal, OpCreateEventPtr evntRecPtr){
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9982
  DBUG_ENTER("Dbdict::createEvent_RT_DICT_AFTER_GET");
9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995
  jam();
  evntRecPtr.p->m_request.setUserRef(signal->senderBlockRef());
  
#ifdef EVENT_PH2_DEBUG
  ndbout_c("DBDICT(Participant) got CREATE_EVNT_REQ::RT_DICT_AFTER_GET evntRecPtr.i = (%d)", evntRecPtr.i);
#endif

  // the signal comes from the DICT block that got the first user request!
  // This code runs on all DICT nodes, including oneself

  // Seize a Create Event record, the Coordinator will now have two seized
  // but that's ok, it's like a recursion

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9996 9997
  CRASH_INSERTION2(6009, getOwnNodeId() != c_masterNodeId);

9998 9999
  SubCreateReq * sumaReq = (SubCreateReq *)signal->getDataPtrSend();
  
10000 10001
  sumaReq->senderRef        = reference(); // reference to DICT
  sumaReq->senderData       = evntRecPtr.i;
10002 10003 10004
  sumaReq->subscriptionId   = evntRecPtr.p->m_request.getEventId();
  sumaReq->subscriptionKey  = evntRecPtr.p->m_request.getEventKey();
  sumaReq->subscriptionType = SubCreateReq::TableEvent;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
10005 10006 10007 10008
  if (evntRecPtr.p->m_request.getReportAll())
    sumaReq->subscriptionType|= SubCreateReq::ReportAll;
  if (evntRecPtr.p->m_request.getReportSubscribe())
    sumaReq->subscriptionType|= SubCreateReq::ReportSubscribe;
10009 10010 10011 10012 10013 10014 10015
  sumaReq->tableId          = evntRecPtr.p->m_request.getTableId();
    
#ifdef EVENT_PH2_DEBUG
  ndbout_c("sending GSN_SUB_CREATE_REQ");
#endif

  sendSignal(SUMA_REF, GSN_SUB_CREATE_REQ, signal,
10016
	     SubCreateReq::SignalLength, JBB);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
10017
  DBUG_VOID_RETURN;
10018 10019 10020 10021 10022
}

void Dbdict::execSUB_CREATE_REF(Signal* signal)
{
  jamEntry();
10023 10024
  DBUG_ENTER("Dbdict::execSUB_CREATE_REF");

10025 10026 10027
  SubCreateRef * const ref = (SubCreateRef *)signal->getDataPtr();
  OpCreateEventPtr evntRecPtr;

10028
  evntRecPtr.i = ref->senderData;
10029 10030
  ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);

10031
  if (ref->errorCode == 1415) {
10032 10033
    jam();
    createEvent_sendReply(signal, evntRecPtr);
10034
    DBUG_VOID_RETURN;
10035 10036
  }

10037 10038 10039 10040 10041 10042 10043 10044 10045 10046
  if (ref->errorCode)
  {
    evntRecPtr.p->m_errorCode = ref->errorCode;
    evntRecPtr.p->m_errorLine = __LINE__;
  }
  else
  {
    evntRecPtr.p->m_errorCode = 1;
    evntRecPtr.p->m_errorLine = __LINE__;
  }
10047 10048 10049
  evntRecPtr.p->m_errorNode = reference();

  createEvent_sendReply(signal, evntRecPtr);
10050
  DBUG_VOID_RETURN;
10051 10052 10053 10054 10055
}

void Dbdict::execSUB_CREATE_CONF(Signal* signal)
{
  jamEntry();
10056
  DBUG_ENTER("Dbdict::execSUB_CREATE_CONF");
10057 10058 10059 10060
  EVENT_TRACE;

  SubCreateConf * const sumaConf = (SubCreateConf *)signal->getDataPtr();
  OpCreateEventPtr evntRecPtr;
10061
  evntRecPtr.i = sumaConf->senderData;
10062 10063 10064 10065
  ndbrequire((evntRecPtr.p = c_opCreateEvent.getPtr(evntRecPtr.i)) != NULL);

  createEvent_sendReply(signal, evntRecPtr);

10066
  DBUG_VOID_RETURN;
10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092
}

/****************************************************
 *
 * common create reply method
 *
 *******************************************************/

void Dbdict::createEvent_sendReply(Signal* signal,
				   OpCreateEventPtr evntRecPtr,
				   LinearSectionPtr *ptr, int noLSP)
{
  jam();
  EVENT_TRACE;

  // check if we're ready to sent reply
  // if we are the master dict we might be waiting for conf/ref

  if (!evntRecPtr.p->m_reqTracker.done()) {
    jam();
    return; // there's more to come
  }

  if (evntRecPtr.p->m_reqTracker.hasRef()) {
    ptr = NULL; // we don't want to return anything if there's an error
    if (!evntRecPtr.p->hasError()) {
10093
      evntRecPtr.p->m_errorCode = 1;
10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116
      evntRecPtr.p->m_errorLine = __LINE__;
      evntRecPtr.p->m_errorNode = reference();
      jam();
    } else 
      jam();
  }

  // reference to API if master DICT
  // else reference to master DICT
  Uint32 senderRef = evntRecPtr.p->m_request.getUserRef();
  Uint32 signalLength;
  Uint32 gsn;

  if (evntRecPtr.p->hasError()) {
    jam();
    EVENT_TRACE;
    CreateEvntRef * ret = (CreateEvntRef *)signal->getDataPtrSend();
    
    ret->setEventId(evntRecPtr.p->m_request.getEventId());
    ret->setEventKey(evntRecPtr.p->m_request.getEventKey());
    ret->setUserData(evntRecPtr.p->m_request.getUserData());
    ret->senderRef = reference();
    ret->setTableId(evntRecPtr.p->m_request.getTableId());
10117
    ret->setTableVersion(evntRecPtr.p->m_request.getTableVersion());
10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142
    ret->setEventType(evntRecPtr.p->m_request.getEventType());
    ret->setRequestType(evntRecPtr.p->m_request.getRequestType());

    ret->setErrorCode(evntRecPtr.p->m_errorCode);
    ret->setErrorLine(evntRecPtr.p->m_errorLine);
    ret->setErrorNode(evntRecPtr.p->m_errorNode);

    signalLength = CreateEvntRef::SignalLength;
#ifdef EVENT_PH2_DEBUG
    ndbout_c("DBDICT sending GSN_CREATE_EVNT_REF to evntRecPtr.i = (%d) node = %u ref = %u", evntRecPtr.i, refToNode(senderRef), senderRef);
    ndbout_c("errorCode = %u", evntRecPtr.p->m_errorCode);
    ndbout_c("errorLine = %u", evntRecPtr.p->m_errorLine);
#endif
    gsn = GSN_CREATE_EVNT_REF;

  } else {
    jam();
    EVENT_TRACE;
    CreateEvntConf * evntConf = (CreateEvntConf *)signal->getDataPtrSend();
    
    evntConf->setEventId(evntRecPtr.p->m_request.getEventId());
    evntConf->setEventKey(evntRecPtr.p->m_request.getEventKey());
    evntConf->setUserData(evntRecPtr.p->m_request.getUserData());
    evntConf->senderRef = reference();
    evntConf->setTableId(evntRecPtr.p->m_request.getTableId());
10143
    evntConf->setTableVersion(evntRecPtr.p->m_request.getTableVersion());
10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179
    evntConf->setAttrListBitmask(evntRecPtr.p->m_request.getAttrListBitmask());
    evntConf->setEventType(evntRecPtr.p->m_request.getEventType());
    evntConf->setRequestType(evntRecPtr.p->m_request.getRequestType());

    signalLength = CreateEvntConf::SignalLength;
#ifdef EVENT_PH2_DEBUG
    ndbout_c("DBDICT sending GSN_CREATE_EVNT_CONF to evntRecPtr.i = (%d) node = %u ref = %u", evntRecPtr.i, refToNode(senderRef), senderRef);
#endif
    gsn = GSN_CREATE_EVNT_CONF;
  }

  if (ptr) {
    jam();
    sendSignal(senderRef, gsn, signal, signalLength, JBB, ptr, noLSP);
  } else {
    jam();
    sendSignal(senderRef, gsn, signal, signalLength, JBB);
  }

  c_opCreateEvent.release(evntRecPtr);
}

/*************************************************************/

/********************************************************************
 *
 * Start event
 *
 *******************************************************************/

void Dbdict::execSUB_START_REQ(Signal* signal)
{
  jamEntry();

  Uint32 origSenderRef = signal->senderBlockRef();

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193
  if (refToBlock(origSenderRef) != DBDICT &&
      getOwnNodeId() != c_masterNodeId)
  {
    /*
     * Coordinator but not master
     */
    SubStartRef * ref = (SubStartRef *)signal->getDataPtrSend();
    ref->senderRef = reference();
    ref->errorCode = SubStartRef::NotMaster;
    ref->m_masterNodeId = c_masterNodeId;
    sendSignal(origSenderRef, GSN_SUB_START_REF, signal,
	       SubStartRef::SignalLength2, JBB);
    return;
  }
10194
  OpSubEventPtr subbPtr;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10195
  Uint32 errCode = 0;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10196 10197 10198 10199 10200 10201 10202 10203 10204 10205

  DictLockPtr loopPtr;
  if (c_dictLockQueue.first(loopPtr) &&
      loopPtr.p->lt->lockType == DictLockReq::NodeRestartLock)
  {
    jam();
    errCode = 1405;
    goto busy;
  }

10206
  if (!c_opSubEvent.seize(subbPtr)) {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10207 10208
    errCode = SubStartRef::Busy;
busy:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10209
    jam();
10210
    SubStartRef * ref = (SubStartRef *)signal->getDataPtrSend();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10211

10212 10213 10214 10215 10216 10217 10218 10219 10220
    { // fix
      Uint32 subcriberRef = ((SubStartReq*)signal->getDataPtr())->subscriberRef;
      ref->subscriberRef = subcriberRef;
    }
    jam();
    //      ret->setErrorCode(SubStartRef::SeizeError);
    //      ret->setErrorLine(__LINE__);
    //      ret->setErrorNode(reference());
    ref->senderRef = reference();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10221
    ref->errorCode = errCode;
10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242

    sendSignal(origSenderRef, GSN_SUB_START_REF, signal,
	       SubStartRef::SignalLength2, JBB);
    return;
  }

  {
    const SubStartReq* req = (SubStartReq*) signal->getDataPtr();
    subbPtr.p->m_senderRef = req->senderRef;
    subbPtr.p->m_senderData = req->senderData;
    subbPtr.p->m_errorCode = 0;
  }
  
  if (refToBlock(origSenderRef) != DBDICT) {
    /*
     * Coordinator
     */
    jam();
    
    subbPtr.p->m_senderRef = origSenderRef; // not sure if API sets correctly
    NodeReceiverGroup rg(DBDICT, c_aliveNodes);
mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
10243
    RequestTracker & p = subbPtr.p->m_reqTracker;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10244 10245 10246 10247 10248 10249
    if (!p.init<SubStartRef>(c_counterMgr, rg, GSN_SUB_START_REF, subbPtr.i))
    {
      c_opSubEvent.release(subbPtr);
      errCode = SubStartRef::Busy;
      goto busy;
    }
10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266
    
    SubStartReq* req = (SubStartReq*) signal->getDataPtrSend();
    
    req->senderRef  = reference();
    req->senderData = subbPtr.i;
    
#ifdef EVENT_PH3_DEBUG
    ndbout_c("DBDICT(Coordinator) sending GSN_SUB_START_REQ to DBDICT participants subbPtr.i = (%d)", subbPtr.i);
#endif

    sendSignal(rg, GSN_SUB_START_REQ, signal, SubStartReq::SignalLength2, JBB);
    return;
  }
  /*
   * Participant
   */
  ndbrequire(refToBlock(origSenderRef) == DBDICT);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10267 10268

  CRASH_INSERTION(6007);
10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288
  
  {
    SubStartReq* req = (SubStartReq*) signal->getDataPtrSend();
    
    req->senderRef = reference();
    req->senderData = subbPtr.i;
    
#ifdef EVENT_PH3_DEBUG
    ndbout_c("DBDICT(Participant) sending GSN_SUB_START_REQ to SUMA subbPtr.i = (%d)", subbPtr.i);
#endif
    sendSignal(SUMA_REF, GSN_SUB_START_REQ, signal, SubStartReq::SignalLength2, JBB);
  }
}

void Dbdict::execSUB_START_REF(Signal* signal)
{
  jamEntry();

  const SubStartRef* ref = (SubStartRef*) signal->getDataPtr();
  Uint32 senderRef  = ref->senderRef;
10289
  Uint32 err = ref->errorCode;
10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303

  OpSubEventPtr subbPtr;
  c_opSubEvent.getPtr(subbPtr, ref->senderData);

  if (refToBlock(senderRef) == SUMA) {
    /*
     * Participant
     */
    jam();

#ifdef EVENT_PH3_DEBUG
    ndbout_c("DBDICT(Participant) got GSN_SUB_START_REF = (%d)", subbPtr.i);
#endif

10304 10305 10306 10307
    jam();
    SubStartRef* ref = (SubStartRef*) signal->getDataPtrSend();
    ref->senderRef = reference();
    ref->senderData = subbPtr.p->m_senderData;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10308
    ref->errorCode = err;
10309 10310 10311
    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_START_REF,
	       signal, SubStartRef::SignalLength2, JBB);
    c_opSubEvent.release(subbPtr);
10312 10313 10314 10315 10316 10317 10318 10319 10320
    return;
  }
  /*
   * Coordinator
   */
  ndbrequire(refToBlock(senderRef) == DBDICT);
#ifdef EVENT_PH3_DEBUG
  ndbout_c("DBDICT(Coordinator) got GSN_SUB_START_REF = (%d)", subbPtr.i);
#endif
10321
  if (err == SubStartRef::NF_FakeErrorREF){
10322 10323 10324 10325
    jam();
    subbPtr.p->m_reqTracker.ignoreRef(c_counterMgr, refToNode(senderRef));
  } else {
    jam();
10326 10327 10328 10329
    if (subbPtr.p->m_errorCode == 0)
    {
      subbPtr.p->m_errorCode= err ? err : 1;
    }
10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370
    subbPtr.p->m_reqTracker.reportRef(c_counterMgr, refToNode(senderRef));
  }
  completeSubStartReq(signal,subbPtr.i,0);
}

void Dbdict::execSUB_START_CONF(Signal* signal)
{
  jamEntry();

  const SubStartConf* conf = (SubStartConf*) signal->getDataPtr();
  Uint32 senderRef  = conf->senderRef;

  OpSubEventPtr subbPtr;
  c_opSubEvent.getPtr(subbPtr, conf->senderData);

  if (refToBlock(senderRef) == SUMA) {
    /*
     * Participant
     */
    jam();
    SubStartConf* conf = (SubStartConf*) signal->getDataPtrSend();

#ifdef EVENT_PH3_DEBUG
  ndbout_c("DBDICT(Participant) got GSN_SUB_START_CONF = (%d)", subbPtr.i);
#endif

    conf->senderRef = reference();
    conf->senderData = subbPtr.p->m_senderData;

    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_START_CONF,
	       signal, SubStartConf::SignalLength2, JBB);
    c_opSubEvent.release(subbPtr);
    return;
  }
  /*
   * Coordinator
   */
  ndbrequire(refToBlock(senderRef) == DBDICT);
#ifdef EVENT_PH3_DEBUG
  ndbout_c("DBDICT(Coordinator) got GSN_SUB_START_CONF = (%d)", subbPtr.i);
#endif
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10371
  subbPtr.p->m_sub_start_conf = *conf;
10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396
  subbPtr.p->m_reqTracker.reportConf(c_counterMgr, refToNode(senderRef));
  completeSubStartReq(signal,subbPtr.i,0);
}

/*
 * Coordinator
 */
void Dbdict::completeSubStartReq(Signal* signal,
				 Uint32 ptrI,
				 Uint32 returnCode){
  jam();

  OpSubEventPtr subbPtr;
  c_opSubEvent.getPtr(subbPtr, ptrI);

  if (!subbPtr.p->m_reqTracker.done()){
    jam();
    return;
  }

  if (subbPtr.p->m_reqTracker.hasRef()) {
    jam();
#ifdef EVENT_DEBUG
    ndbout_c("SUB_START_REF");
#endif
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
10397 10398 10399
    SubStartRef * ref = (SubStartRef *)signal->getDataPtrSend();
    ref->senderRef = reference();
    ref->errorCode = subbPtr.p->m_errorCode;
10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410
    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_START_REF,
	       signal, SubStartRef::SignalLength, JBB);
    if (subbPtr.p->m_reqTracker.hasConf()) {
      //  stopStartedNodes(signal);
    }
    c_opSubEvent.release(subbPtr);
    return;
  }
#ifdef EVENT_DEBUG
  ndbout_c("SUB_START_CONF");
#endif
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10411 10412 10413
  
  SubStartConf* conf = (SubStartConf*)signal->getDataPtrSend();
  * conf = subbPtr.p->m_sub_start_conf;
10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430
  sendSignal(subbPtr.p->m_senderRef, GSN_SUB_START_CONF,
	     signal, SubStartConf::SignalLength, JBB);
  c_opSubEvent.release(subbPtr);
}

/********************************************************************
 *
 * Stop event
 *
 *******************************************************************/

void Dbdict::execSUB_STOP_REQ(Signal* signal)
{
  jamEntry();

  Uint32 origSenderRef = signal->senderBlockRef();

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444
  if (refToBlock(origSenderRef) != DBDICT &&
      getOwnNodeId() != c_masterNodeId)
  {
    /*
     * Coordinator but not master
     */
    SubStopRef * ref = (SubStopRef *)signal->getDataPtrSend();
    ref->senderRef = reference();
    ref->errorCode = SubStopRef::NotMaster;
    ref->m_masterNodeId = c_masterNodeId;
    sendSignal(origSenderRef, GSN_SUB_STOP_REF, signal,
	       SubStopRef::SignalLength2, JBB);
    return;
  }
10445
  OpSubEventPtr subbPtr;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10446
  Uint32 errCode = 0;
10447
  if (!c_opSubEvent.seize(subbPtr)) {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10448 10449
    errCode = SubStopRef::Busy;
busy:
10450 10451 10452 10453 10454 10455
    SubStopRef * ref = (SubStopRef *)signal->getDataPtrSend();
    jam();
    //      ret->setErrorCode(SubStartRef::SeizeError);
    //      ret->setErrorLine(__LINE__);
    //      ret->setErrorNode(reference());
    ref->senderRef = reference();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10456
    ref->errorCode = errCode;
10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479

    sendSignal(origSenderRef, GSN_SUB_STOP_REF, signal,
	       SubStopRef::SignalLength, JBB);
    return;
  }

  {
    const SubStopReq* req = (SubStopReq*) signal->getDataPtr();
    subbPtr.p->m_senderRef = req->senderRef;
    subbPtr.p->m_senderData = req->senderData;
    subbPtr.p->m_errorCode = 0;
  }
  
  if (refToBlock(origSenderRef) != DBDICT) {
    /*
     * Coordinator
     */
    jam();
#ifdef EVENT_DEBUG
    ndbout_c("SUB_STOP_REQ 1");
#endif
    subbPtr.p->m_senderRef = origSenderRef; // not sure if API sets correctly
    NodeReceiverGroup rg(DBDICT, c_aliveNodes);
mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
10480
    RequestTracker & p = subbPtr.p->m_reqTracker;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10481 10482 10483 10484 10485 10486 10487 10488
    if (!p.init<SubStopRef>(c_counterMgr, rg, GSN_SUB_STOP_REF, subbPtr.i))
    {
      jam();
      c_opSubEvent.release(subbPtr);
      errCode = SubStopRef::Busy;
      goto busy;
    }
    
10489
    SubStopReq* req = (SubStopReq*) signal->getDataPtrSend();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10490
    
10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503
    req->senderRef  = reference();
    req->senderData = subbPtr.i;
    
    sendSignal(rg, GSN_SUB_STOP_REQ, signal, SubStopReq::SignalLength, JBB);
    return;
  }
  /*
   * Participant
   */
#ifdef EVENT_DEBUG
  ndbout_c("SUB_STOP_REQ 2");
#endif
  ndbrequire(refToBlock(origSenderRef) == DBDICT);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10504 10505 10506

  CRASH_INSERTION(6008);

10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521
  {
    SubStopReq* req = (SubStopReq*) signal->getDataPtrSend();
    
    req->senderRef = reference();
    req->senderData = subbPtr.i;
    
    sendSignal(SUMA_REF, GSN_SUB_STOP_REQ, signal, SubStopReq::SignalLength, JBB);
  }
}

void Dbdict::execSUB_STOP_REF(Signal* signal)
{
  jamEntry();
  const SubStopRef* ref = (SubStopRef*) signal->getDataPtr();
  Uint32 senderRef  = ref->senderRef;
10522
  Uint32 err = ref->errorCode;
10523 10524 10525 10526 10527 10528 10529 10530 10531

  OpSubEventPtr subbPtr;
  c_opSubEvent.getPtr(subbPtr, ref->senderData);

  if (refToBlock(senderRef) == SUMA) {
    /*
     * Participant
     */
    jam();
10532 10533 10534
    SubStopRef* ref = (SubStopRef*) signal->getDataPtrSend();
    ref->senderRef = reference();
    ref->senderData = subbPtr.p->m_senderData;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10535
    ref->errorCode = err;
10536 10537 10538
    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_STOP_REF,
	       signal, SubStopRef::SignalLength, JBB);
    c_opSubEvent.release(subbPtr);
10539 10540 10541 10542 10543 10544
    return;
  }
  /*
   * Coordinator
   */
  ndbrequire(refToBlock(senderRef) == DBDICT);
10545
  if (err == SubStopRef::NF_FakeErrorREF){
10546 10547 10548 10549
    jam();
    subbPtr.p->m_reqTracker.ignoreRef(c_counterMgr, refToNode(senderRef));
  } else {
    jam();
10550 10551 10552 10553
    if (subbPtr.p->m_errorCode == 0)
    {
      subbPtr.p->m_errorCode= err ? err : 1;
    }
10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587
    subbPtr.p->m_reqTracker.reportRef(c_counterMgr, refToNode(senderRef));
  }
  completeSubStopReq(signal,subbPtr.i,0);
}

void Dbdict::execSUB_STOP_CONF(Signal* signal)
{
  jamEntry();

  const SubStopConf* conf = (SubStopConf*) signal->getDataPtr();
  Uint32 senderRef  = conf->senderRef;

  OpSubEventPtr subbPtr;
  c_opSubEvent.getPtr(subbPtr, conf->senderData);

  if (refToBlock(senderRef) == SUMA) {
    /*
     * Participant
     */
    jam();
    SubStopConf* conf = (SubStopConf*) signal->getDataPtrSend();

    conf->senderRef = reference();
    conf->senderData = subbPtr.p->m_senderData;

    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_STOP_CONF,
	       signal, SubStopConf::SignalLength, JBB);
    c_opSubEvent.release(subbPtr);
    return;
  }
  /*
   * Coordinator
   */
  ndbrequire(refToBlock(senderRef) == DBDICT);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10588
  subbPtr.p->m_sub_stop_conf = *conf;
10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613
  subbPtr.p->m_reqTracker.reportConf(c_counterMgr, refToNode(senderRef));
  completeSubStopReq(signal,subbPtr.i,0);
}

/*
 * Coordinator
 */
void Dbdict::completeSubStopReq(Signal* signal,
				Uint32 ptrI,
				Uint32 returnCode){
  OpSubEventPtr subbPtr;
  c_opSubEvent.getPtr(subbPtr, ptrI);

  if (!subbPtr.p->m_reqTracker.done()){
    jam();
    return;
  }

  if (subbPtr.p->m_reqTracker.hasRef()) {
    jam();
#ifdef EVENT_DEBUG
    ndbout_c("SUB_STOP_REF");
#endif
    SubStopRef* ref = (SubStopRef*)signal->getDataPtrSend();

10614 10615 10616
    ref->senderRef  = reference();
    ref->senderData = subbPtr.p->m_senderData;
    ref->errorCode  = subbPtr.p->m_errorCode;
10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628

    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_STOP_REF,
	       signal, SubStopRef::SignalLength, JBB);
    if (subbPtr.p->m_reqTracker.hasConf()) {
      //  stopStartedNodes(signal);
    }
    c_opSubEvent.release(subbPtr);
    return;
  }
#ifdef EVENT_DEBUG
  ndbout_c("SUB_STOP_CONF");
#endif
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10629 10630
  SubStopConf* conf = (SubStopConf*)signal->getDataPtrSend();
  * conf = subbPtr.p->m_sub_stop_conf;
10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647
  sendSignal(subbPtr.p->m_senderRef, GSN_SUB_STOP_CONF,
	     signal, SubStopConf::SignalLength, JBB);
  c_opSubEvent.release(subbPtr);
}

/***************************************************************
 * MODULE: Drop event.
 *
 * Drop event.
 * 
 * TODO
 */

void
Dbdict::execDROP_EVNT_REQ(Signal* signal)
{
  jamEntry();
10648
  DBUG_ENTER("Dbdict::execDROP_EVNT_REQ");
10649 10650 10651 10652 10653

  DropEvntReq *req = (DropEvntReq*)signal->getDataPtr();
  const Uint32 senderRef = signal->senderBlockRef();
  OpDropEventPtr evntRecPtr;

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670
  if (refToBlock(senderRef) != DBDICT &&
      getOwnNodeId() != c_masterNodeId)
  {
    jam();
    releaseSections(signal);

    DropEvntRef * ref = (DropEvntRef *)signal->getDataPtrSend();
    ref->setUserRef(reference());
    ref->setErrorCode(DropEvntRef::NotMaster);
    ref->setErrorLine(__LINE__);
    ref->setErrorNode(reference());
    ref->setMasterNode(c_masterNodeId);
    sendSignal(senderRef, GSN_DROP_EVNT_REF, signal,
	       DropEvntRef::SignalLength2, JBB);
    return;
  }

10671 10672 10673 10674 10675 10676 10677
  // Seize a Create Event record
  if (!c_opDropEvent.seize(evntRecPtr)) {
    // Failed to allocate event record
    jam();
    releaseSections(signal);
 
    DropEvntRef * ret = (DropEvntRef *)signal->getDataPtrSend();
10678
    ret->setErrorCode(747);
10679 10680 10681 10682
    ret->setErrorLine(__LINE__);
    ret->setErrorNode(reference());
    sendSignal(senderRef, GSN_DROP_EVNT_REF, signal,
	       DropEvntRef::SignalLength, JBB);
10683
    DBUG_VOID_RETURN;
10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707
  }

#ifdef EVENT_DEBUG
  ndbout_c("DBDICT::execDROP_EVNT_REQ evntRecId = (%d)", evntRecPtr.i);
#endif

  OpDropEvent* evntRec = evntRecPtr.p;
  evntRec->init(req);

  SegmentedSectionPtr ssPtr;

  signal->getSection(ssPtr, 0);

  SimplePropertiesSectionReader r0(ssPtr, getSectionSegmentPool());
#ifdef EVENT_DEBUG
  r0.printAll(ndbout);
#endif
  // event name
  if ((!r0.first()) ||
      (r0.getValueType() != SimpleProperties::StringValue) ||
      (r0.getValueLen() <= 0)) {
    jam();
    releaseSections(signal);

10708
    evntRecPtr.p->m_errorCode = 1;
10709 10710 10711 10712
    evntRecPtr.p->m_errorLine = __LINE__;
    evntRecPtr.p->m_errorNode = reference();

    dropEvent_sendReply(signal, evntRecPtr);
10713
    DBUG_VOID_RETURN;
10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733
  }
  r0.getString(evntRecPtr.p->m_eventRec.NAME);
  {
    int len = strlen(evntRecPtr.p->m_eventRec.NAME);
    memset(evntRecPtr.p->m_eventRec.NAME+len, 0, MAX_TAB_NAME_SIZE-len);
#ifdef EVENT_DEBUG
    printf("DropEvntReq; EventName %s, len %u\n",
	   evntRecPtr.p->m_eventRec.NAME, len);
    for(int i = 0; i < MAX_TAB_NAME_SIZE/4; i++)
      printf("H'%.8x ", ((Uint32*)evntRecPtr.p->m_eventRec.NAME)[i]);
    printf("\n");
#endif
  }
  
  releaseSections(signal);

  Callback c = { safe_cast(&Dbdict::dropEventUTIL_PREPARE_READ), 0 };

  prepareTransactionEventSysTable(&c, signal, evntRecPtr.i,
				  UtilPrepareReq::Read);
10734
  DBUG_VOID_RETURN;
10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785
}

void 
Dbdict::dropEventUTIL_PREPARE_READ(Signal* signal,
				   Uint32 callbackData,
				   Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  if (returnCode != 0) {
    EVENT_TRACE;
    dropEventUtilPrepareRef(signal, callbackData, returnCode);
    return;
  }

  UtilPrepareConf* const req = (UtilPrepareConf*)signal->getDataPtr();
  OpDropEventPtr evntRecPtr;
  evntRecPtr.i = req->getSenderData();
  const Uint32 prepareId = req->getPrepareId();

  ndbrequire((evntRecPtr.p = c_opDropEvent.getPtr(evntRecPtr.i)) != NULL);

  Callback c = { safe_cast(&Dbdict::dropEventUTIL_EXECUTE_READ), 0 };

  executeTransEventSysTable(&c, signal,
			    evntRecPtr.i, evntRecPtr.p->m_eventRec,
			    prepareId, UtilPrepareReq::Read);
}

void 
Dbdict::dropEventUTIL_EXECUTE_READ(Signal* signal,
				   Uint32 callbackData,
				   Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  if (returnCode != 0) {
    EVENT_TRACE;
    dropEventUtilExecuteRef(signal, callbackData, returnCode);
    return;
  }

  OpDropEventPtr evntRecPtr;
  UtilExecuteConf * const ref = (UtilExecuteConf *)signal->getDataPtr();
  jam();
  evntRecPtr.i = ref->getSenderData();
  ndbrequire((evntRecPtr.p = c_opDropEvent.getPtr(evntRecPtr.i)) != NULL);

  parseReadEventSys(signal, evntRecPtr.p->m_eventRec);

  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
mysqldev@mysql.com's avatar
mysqldev@mysql.com committed
10786
  RequestTracker & p = evntRecPtr.p->m_reqTracker;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10787 10788 10789 10790 10791 10792 10793 10794
  if (!p.init<SubRemoveRef>(c_counterMgr, rg, GSN_SUB_REMOVE_REF,
			    evntRecPtr.i))
  {
    evntRecPtr.p->m_errorCode = 701;
    dropEvent_sendReply(signal, evntRecPtr);
    return;
  }
  
10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812
  SubRemoveReq* req = (SubRemoveReq*) signal->getDataPtrSend();

  req->senderRef       = reference();
  req->senderData      = evntRecPtr.i;
  req->subscriptionId  = evntRecPtr.p->m_eventRec.SUBID;
  req->subscriptionKey = evntRecPtr.p->m_eventRec.SUBKEY;

  sendSignal(rg, GSN_SUB_REMOVE_REQ, signal, SubRemoveReq::SignalLength, JBB);
}

/*
 * Participant
 */

void
Dbdict::execSUB_REMOVE_REQ(Signal* signal)
{
  jamEntry();
10813
  DBUG_ENTER("Dbdict::execSUB_REMOVE_REQ");
10814 10815 10816 10817 10818 10819 10820 10821

  Uint32 origSenderRef = signal->senderBlockRef();

  OpSubEventPtr subbPtr;
  if (!c_opSubEvent.seize(subbPtr)) {
    SubRemoveRef * ref = (SubRemoveRef *)signal->getDataPtrSend();
    jam();
    ref->senderRef = reference();
10822
    ref->errorCode = SubRemoveRef::Busy;
10823 10824 10825

    sendSignal(origSenderRef, GSN_SUB_REMOVE_REF, signal,
	       SubRemoveRef::SignalLength, JBB);
10826
    DBUG_VOID_RETURN;
10827 10828 10829 10830 10831 10832 10833 10834 10835
  }

  {
    const SubRemoveReq* req = (SubRemoveReq*) signal->getDataPtr();
    subbPtr.p->m_senderRef = req->senderRef;
    subbPtr.p->m_senderData = req->senderData;
    subbPtr.p->m_errorCode = 0;
  }

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10836 10837
  CRASH_INSERTION2(6010, getOwnNodeId() != c_masterNodeId);
  
10838 10839 10840 10841 10842
  SubRemoveReq* req = (SubRemoveReq*) signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = subbPtr.i;

  sendSignal(SUMA_REF, GSN_SUB_REMOVE_REQ, signal, SubRemoveReq::SignalLength, JBB);
10843
  DBUG_VOID_RETURN;
10844 10845 10846 10847 10848 10849 10850 10851 10852 10853
}

/*
 * Coordintor/Participant
 */

void
Dbdict::execSUB_REMOVE_REF(Signal* signal)
{
  jamEntry();
10854 10855
  DBUG_ENTER("Dbdict::execSUB_REMOVE_REF");

10856 10857
  const SubRemoveRef* ref = (SubRemoveRef*) signal->getDataPtr();
  Uint32 senderRef = ref->senderRef;
10858
  Uint32 err= ref->errorCode;
10859 10860 10861 10862 10863 10864 10865 10866

  if (refToBlock(senderRef) == SUMA) {
    /*
     * Participant
     */
    jam();
    OpSubEventPtr subbPtr;
    c_opSubEvent.getPtr(subbPtr, ref->senderData);
10867 10868
    if (err == 1407) {
      // conf this since this may occur if a nodefailure has occured
10869 10870 10871 10872 10873 10874 10875 10876 10877 10878
      // earlier so that the systable was not cleared
      SubRemoveConf* conf = (SubRemoveConf*) signal->getDataPtrSend();
      conf->senderRef  = reference();
      conf->senderData = subbPtr.p->m_senderData;
      sendSignal(subbPtr.p->m_senderRef, GSN_SUB_REMOVE_CONF,
		 signal, SubRemoveConf::SignalLength, JBB);
    } else {
      SubRemoveRef* ref = (SubRemoveRef*) signal->getDataPtrSend();
      ref->senderRef = reference();
      ref->senderData = subbPtr.p->m_senderData;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10879
      ref->errorCode = err;
10880 10881 10882 10883
      sendSignal(subbPtr.p->m_senderRef, GSN_SUB_REMOVE_REF,
		 signal, SubRemoveRef::SignalLength, JBB);
    }
    c_opSubEvent.release(subbPtr);
10884
    DBUG_VOID_RETURN;
10885 10886 10887 10888 10889 10890 10891
  }
  /*
   * Coordinator
   */
  ndbrequire(refToBlock(senderRef) == DBDICT);
  OpDropEventPtr eventRecPtr;
  c_opDropEvent.getPtr(eventRecPtr, ref->senderData);
10892
  if (err == SubRemoveRef::NF_FakeErrorREF){
10893 10894 10895 10896
    jam();
    eventRecPtr.p->m_reqTracker.ignoreRef(c_counterMgr, refToNode(senderRef));
  } else {
    jam();
10897 10898 10899 10900 10901 10902
    if (eventRecPtr.p->m_errorCode == 0)
    {
      eventRecPtr.p->m_errorCode= err ? err : 1;
      eventRecPtr.p->m_errorLine= __LINE__;
      eventRecPtr.p->m_errorNode= reference();
    }
10903 10904 10905
    eventRecPtr.p->m_reqTracker.reportRef(c_counterMgr, refToNode(senderRef));
  }
  completeSubRemoveReq(signal,eventRecPtr.i,0);
10906
  DBUG_VOID_RETURN;
10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953
}

void
Dbdict::execSUB_REMOVE_CONF(Signal* signal)
{
  jamEntry();
  const SubRemoveConf* conf = (SubRemoveConf*) signal->getDataPtr();
  Uint32 senderRef = conf->senderRef;

  if (refToBlock(senderRef) == SUMA) {
    /*
     * Participant
     */
    jam();
    OpSubEventPtr subbPtr;
    c_opSubEvent.getPtr(subbPtr, conf->senderData);
    SubRemoveConf* conf = (SubRemoveConf*) signal->getDataPtrSend();
    conf->senderRef = reference();
    conf->senderData = subbPtr.p->m_senderData;
    sendSignal(subbPtr.p->m_senderRef, GSN_SUB_REMOVE_CONF,
	       signal, SubRemoveConf::SignalLength, JBB);
    c_opSubEvent.release(subbPtr);
    return;
  }
  /*
   * Coordinator
   */
  ndbrequire(refToBlock(senderRef) == DBDICT);
  OpDropEventPtr eventRecPtr;
  c_opDropEvent.getPtr(eventRecPtr, conf->senderData);
  eventRecPtr.p->m_reqTracker.reportConf(c_counterMgr, refToNode(senderRef));
  completeSubRemoveReq(signal,eventRecPtr.i,0);
}

void
Dbdict::completeSubRemoveReq(Signal* signal, Uint32 ptrI, Uint32 xxx)
{
  OpDropEventPtr evntRecPtr;
  c_opDropEvent.getPtr(evntRecPtr, ptrI);

  if (!evntRecPtr.p->m_reqTracker.done()){
    jam();
    return;
  }

  if (evntRecPtr.p->m_reqTracker.hasRef()) {
    jam();
10954 10955 10956 10957 10958 10959
    if ( evntRecPtr.p->m_errorCode == 0 )
    {
      evntRecPtr.p->m_errorNode = reference();
      evntRecPtr.p->m_errorLine = __LINE__;
      evntRecPtr.p->m_errorCode = 1;
    }
10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035
    dropEvent_sendReply(signal, evntRecPtr);
    return;
  }

  Callback c = { safe_cast(&Dbdict::dropEventUTIL_PREPARE_DELETE), 0 };

  prepareTransactionEventSysTable(&c, signal, evntRecPtr.i,
				  UtilPrepareReq::Delete);
}

void 
Dbdict::dropEventUTIL_PREPARE_DELETE(Signal* signal,
				     Uint32 callbackData,
				     Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  if (returnCode != 0) {
    EVENT_TRACE;
    dropEventUtilPrepareRef(signal, callbackData, returnCode);
    return;
  }

  UtilPrepareConf* const req = (UtilPrepareConf*)signal->getDataPtr();
  OpDropEventPtr evntRecPtr;
  jam();
  evntRecPtr.i = req->getSenderData();
  const Uint32 prepareId = req->getPrepareId();
  
  ndbrequire((evntRecPtr.p = c_opDropEvent.getPtr(evntRecPtr.i)) != NULL);
#ifdef EVENT_DEBUG
  printf("DropEvntUTIL_PREPARE; evntRecPtr.i len %u\n",evntRecPtr.i);
#endif    

  Callback c = { safe_cast(&Dbdict::dropEventUTIL_EXECUTE_DELETE), 0 };

  executeTransEventSysTable(&c, signal,
			    evntRecPtr.i, evntRecPtr.p->m_eventRec,
			    prepareId, UtilPrepareReq::Delete);
}

void 
Dbdict::dropEventUTIL_EXECUTE_DELETE(Signal* signal,
				     Uint32 callbackData,
				     Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  if (returnCode != 0) {
    EVENT_TRACE;
    dropEventUtilExecuteRef(signal, callbackData, returnCode);
    return;
  }

  OpDropEventPtr evntRecPtr;
  UtilExecuteConf * const ref = (UtilExecuteConf *)signal->getDataPtr();
  jam();
  evntRecPtr.i = ref->getSenderData();
  ndbrequire((evntRecPtr.p = c_opDropEvent.getPtr(evntRecPtr.i)) != NULL);

  dropEvent_sendReply(signal, evntRecPtr);
}

void
Dbdict::dropEventUtilPrepareRef(Signal* signal,
				Uint32 callbackData,
				Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  UtilPrepareRef * const ref = (UtilPrepareRef *)signal->getDataPtr();
  OpDropEventPtr evntRecPtr;
  evntRecPtr.i = ref->getSenderData();
  ndbrequire((evntRecPtr.p = c_opDropEvent.getPtr(evntRecPtr.i)) != NULL);

  interpretUtilPrepareErrorCode((UtilPrepareRef::ErrorCode)ref->getErrorCode(),
11036
				evntRecPtr.p->m_errorCode, evntRecPtr.p->m_errorLine);
11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062
  evntRecPtr.p->m_errorNode = reference();

  dropEvent_sendReply(signal, evntRecPtr);
}

void
Dbdict::dropEventUtilExecuteRef(Signal* signal,
				Uint32 callbackData,
				Uint32 returnCode)
{
  jam();
  EVENT_TRACE;
  OpDropEventPtr evntRecPtr;
  UtilExecuteRef * const ref = (UtilExecuteRef *)signal->getDataPtr();
  jam();
  evntRecPtr.i = ref->getSenderData();
  ndbrequire((evntRecPtr.p = c_opDropEvent.getPtr(evntRecPtr.i)) != NULL);
    
  evntRecPtr.p->m_errorNode = reference();
  evntRecPtr.p->m_errorLine = __LINE__;

  switch (ref->getErrorCode()) {
  case UtilExecuteRef::TCError:
    switch (ref->getTCErrorCode()) {
    case ZNOT_FOUND:
      jam();
11063
      evntRecPtr.p->m_errorCode = 4710;
11064 11065 11066
      break;
    default:
      jam();
11067
      evntRecPtr.p->m_errorCode = ref->getTCErrorCode();
11068 11069 11070 11071 11072
      break;
    }
    break;
  default:
    jam();
11073
    evntRecPtr.p->m_errorCode = ref->getErrorCode();
11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155
    break;
  }
  dropEvent_sendReply(signal, evntRecPtr);
}

void Dbdict::dropEvent_sendReply(Signal* signal,
				 OpDropEventPtr evntRecPtr)
{
  jam();
  EVENT_TRACE;
  Uint32 senderRef = evntRecPtr.p->m_request.getUserRef();

  if (evntRecPtr.p->hasError()) {
    jam();
    DropEvntRef * ret = (DropEvntRef *)signal->getDataPtrSend();
    
    ret->setUserData(evntRecPtr.p->m_request.getUserData());
    ret->setUserRef(evntRecPtr.p->m_request.getUserRef());

    ret->setErrorCode(evntRecPtr.p->m_errorCode);
    ret->setErrorLine(evntRecPtr.p->m_errorLine);
    ret->setErrorNode(evntRecPtr.p->m_errorNode);

    sendSignal(senderRef, GSN_DROP_EVNT_REF, signal,
	       DropEvntRef::SignalLength, JBB);
  } else {
    jam();
    DropEvntConf * evntConf = (DropEvntConf *)signal->getDataPtrSend();
    
    evntConf->setUserData(evntRecPtr.p->m_request.getUserData());
    evntConf->setUserRef(evntRecPtr.p->m_request.getUserRef());

    sendSignal(senderRef, GSN_DROP_EVNT_CONF, signal,
	       DropEvntConf::SignalLength, JBB);
  }

  c_opDropEvent.release(evntRecPtr);
}

/**
 * MODULE: Alter index
 *
 * Alter index state.  Alter online creates the index in each TC and
 * then invokes create trigger and alter trigger protocols to activate
 * the 3 triggers.  Alter offline does the opposite.
 *
 * Request type received in REQ and returned in CONF/REF:
 *
 * RT_USER - from API to DICT master
 * RT_CREATE_INDEX - part of create index operation
 * RT_DROP_INDEX - part of drop index operation
 * RT_NODERESTART - node restart, activate locally only
 * RT_SYSTEMRESTART - system restart, activate and build if not logged
 * RT_DICT_PREPARE - prepare participants
 * RT_DICT_TC - to local TC via each participant
 * RT_DICT_COMMIT - commit in each participant
 */

void
Dbdict::execALTER_INDX_REQ(Signal* signal)
{
  jamEntry();
  AlterIndxReq* const req = (AlterIndxReq*)signal->getDataPtrSend();
  OpAlterIndexPtr opPtr;
  const Uint32 senderRef = signal->senderBlockRef();
  const AlterIndxReq::RequestType requestType = req->getRequestType();
  if (requestType == AlterIndxReq::RT_USER ||
      requestType == AlterIndxReq::RT_CREATE_INDEX ||
      requestType == AlterIndxReq::RT_DROP_INDEX ||
      requestType == AlterIndxReq::RT_NODERESTART ||
      requestType == AlterIndxReq::RT_SYSTEMRESTART) {
    jam();
    const bool isLocal = req->getRequestFlag() & RequestFlag::RF_LOCAL;
    NdbNodeBitmask receiverNodes = c_aliveNodes;
    if (isLocal) {
      receiverNodes.clear();
      receiverNodes.set(getOwnNodeId());
    }
    if (signal->getLength() == AlterIndxReq::SignalLength) {
      jam();
      if (! isLocal && getOwnNodeId() != c_masterNodeId) {
        jam();
11156 11157 11158 11159 11160 11161 11162 11163 11164

	releaseSections(signal);
	OpAlterIndex opBad;
	opPtr.p = &opBad;
	opPtr.p->save(req);
	opPtr.p->m_errorCode = AlterIndxRef::NotMaster;
	opPtr.p->m_errorLine = __LINE__;
	opPtr.p->m_errorNode = c_masterNodeId;
	alterIndex_sendReply(signal, opPtr, true);
11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442
        return;
      }
      // forward initial request plus operation key to all
      req->setOpKey(++c_opRecordSequence);
      NodeReceiverGroup rg(DBDICT, receiverNodes);
      sendSignal(rg, GSN_ALTER_INDX_REQ,
          signal, AlterIndxReq::SignalLength + 1, JBB);
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == AlterIndxReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpAlterIndex opBusy;
    if (! c_opAlterIndex.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = AlterIndxReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = AlterIndxRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      alterIndex_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opAlterIndex.add(opPtr);
    // master expects to hear from all
    if (opPtr.p->m_isMaster)
      opPtr.p->m_signalCounter = receiverNodes;
    // check request in all participants
    alterIndex_slavePrepare(signal, opPtr);
    alterIndex_sendReply(signal, opPtr, false);
    return;
  }
  c_opAlterIndex.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == AlterIndxReq::RT_DICT_TC) {
      jam();
      if (opPtr.p->m_request.getOnline())
        alterIndex_toCreateTc(signal, opPtr);
      else
        alterIndex_toDropTc(signal, opPtr);
      return;
    }
    if (requestType == AlterIndxReq::RT_DICT_COMMIT ||
        requestType == AlterIndxReq::RT_DICT_ABORT) {
      jam();
      if (requestType == AlterIndxReq::RT_DICT_COMMIT)
        alterIndex_slaveCommit(signal, opPtr);
      else
        alterIndex_slaveAbort(signal, opPtr);
      alterIndex_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
        c_opAlterIndex.release(opPtr);
      return;
    }
  }
  jam();
  // return to sender
  OpAlterIndex opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
  opPtr.p->m_errorCode = AlterIndxRef::BadRequestType;
  opPtr.p->m_errorLine = __LINE__;
  alterIndex_sendReply(signal, opPtr, true);
}

void
Dbdict::execALTER_INDX_CONF(Signal* signal)
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);
  AlterIndxConf* conf = (AlterIndxConf*)signal->getDataPtrSend();
  alterIndex_recvReply(signal, conf, 0);
}

void
Dbdict::execALTER_INDX_REF(Signal* signal)
{
  jamEntry();
  AlterIndxRef* ref = (AlterIndxRef*)signal->getDataPtrSend();
  alterIndex_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::alterIndex_recvReply(Signal* signal, const AlterIndxConf* conf,
    const AlterIndxRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const AlterIndxReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == AlterIndxReq::RT_CREATE_INDEX) {
    jam();
    // part of create index operation
    OpCreateIndexPtr opPtr;
    c_opCreateIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    createIndex_fromAlterIndex(signal, opPtr);
    return;
  }
  if (requestType == AlterIndxReq::RT_DROP_INDEX) {
    jam();
    // part of drop index operation
    OpDropIndexPtr opPtr;
    c_opDropIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    dropIndex_fromAlterIndex(signal, opPtr);
    return;
  }
  if (requestType == AlterIndxReq::RT_TC ||
      requestType == AlterIndxReq::RT_TUX) {
    jam();
    // part of build index operation
    OpBuildIndexPtr opPtr;
    c_opBuildIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    buildIndex_fromOnline(signal, opPtr);
    return;
  }
  if (requestType == AlterIndxReq::RT_NODERESTART) {
    jam();
    if (ref == 0) {
      infoEvent("DICT: index %u activated", (unsigned)key);
    } else {
      warningEvent("DICT: index %u activation failed: code=%d line=%d",
          (unsigned)key,
          ref->getErrorCode(), ref->getErrorLine());
    }
    activateIndexes(signal, key + 1);
    return;
  }
  if (requestType == AlterIndxReq::RT_SYSTEMRESTART) {
    jam();
    if (ref == 0) {
      infoEvent("DICT: index %u activated done", (unsigned)key);
    } else {
      warningEvent("DICT: index %u activated failed: code=%d line=%d node=%d",
          (unsigned)key,
          ref->getErrorCode(), ref->getErrorLine(), ref->getErrorNode());
    }
    activateIndexes(signal, key + 1);
    return;
  }
  OpAlterIndexPtr opPtr;
  c_opAlterIndex.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  opPtr.p->setError(ref);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == AlterIndxReq::RT_DICT_COMMIT ||
      requestType == AlterIndxReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    alterIndex_sendReply(signal, opPtr, true);
    c_opAlterIndex.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = AlterIndxReq::RT_DICT_ABORT;
    alterIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  if (indexPtr.p->isHashIndex()) {
    if (requestType == AlterIndxReq::RT_DICT_PREPARE) {
      jam();
      if (opPtr.p->m_request.getOnline()) {
        opPtr.p->m_requestType = AlterIndxReq::RT_DICT_TC;
        alterIndex_sendSlaveReq(signal, opPtr);
      } else {
        // start drop triggers
        alterIndex_toDropTrigger(signal, opPtr);
      }
      return;
    }
    if (requestType == AlterIndxReq::RT_DICT_TC) {
      jam();
      if (opPtr.p->m_request.getOnline()) {
        // start create triggers
        alterIndex_toCreateTrigger(signal, opPtr);
      } else {
        opPtr.p->m_requestType = AlterIndxReq::RT_DICT_COMMIT;
        alterIndex_sendSlaveReq(signal, opPtr);
      }
      return;
    }
  }
  if (indexPtr.p->isOrderedIndex()) {
    if (requestType == AlterIndxReq::RT_DICT_PREPARE) {
      jam();
      if (opPtr.p->m_request.getOnline()) {
        // start create triggers
        alterIndex_toCreateTrigger(signal, opPtr);
      } else {
        // start drop triggers
        alterIndex_toDropTrigger(signal, opPtr);
      }
      return;
    }
  }
  ndbrequire(false);
}

void
Dbdict::alterIndex_slavePrepare(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  const AlterIndxReq* const req = &opPtr.p->m_request;
  if (! (req->getIndexId() < c_tableRecordPool.getSize())) {
    jam();
    opPtr.p->m_errorCode = AlterIndxRef::Inconsistency;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, req->getIndexId());
  if (indexPtr.p->tabState != TableRecord::DEFINED) {
    jam();
    opPtr.p->m_errorCode = AlterIndxRef::IndexNotFound;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  if (! indexPtr.p->isIndex()) {
    jam();
    opPtr.p->m_errorCode = AlterIndxRef::NotAnIndex;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  if (req->getOnline())
    indexPtr.p->indexState = TableRecord::IS_BUILDING;
  else
    indexPtr.p->indexState = TableRecord::IS_DROPPING;
}

void
Dbdict::alterIndex_toCreateTc(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  // request to create index in local TC
  CreateIndxReq* const req = (CreateIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(CreateIndxReq::RT_TC);
  req->setIndexType(indexPtr.p->tableType);
  req->setTableId(indexPtr.p->primaryTableId);
  req->setIndexId(indexPtr.i);
  req->setOnline(true);
  getIndexAttrList(indexPtr, opPtr.p->m_attrList);
  // send
  LinearSectionPtr lsPtr[3];
  lsPtr[0].p = (Uint32*)&opPtr.p->m_attrList;
  lsPtr[0].sz = 1 + opPtr.p->m_attrList.sz;
  sendSignal(calcTcBlockRef(getOwnNodeId()), GSN_CREATE_INDX_REQ,
      signal, CreateIndxReq::SignalLength, JBB, lsPtr, 1);
}

void
Dbdict::alterIndex_fromCreateTc(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  // mark created in local TC
11443
  if (! opPtr.p->hasLastError()) {
11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458
    TableRecordPtr indexPtr;
    c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
    indexPtr.p->indexLocal |= TableRecord::IL_CREATED_TC;
  }
  // forward CONF or REF to master
  ndbrequire(opPtr.p->m_requestType == AlterIndxReq::RT_DICT_TC);
  alterIndex_sendReply(signal, opPtr, false);
}

void
Dbdict::alterIndex_toDropTc(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
11459
  // broken index allowed if force
11460 11461
  if (! (indexPtr.p->indexLocal & TableRecord::IL_CREATED_TC)) {
    jam();
pekka@mysql.com's avatar
pekka@mysql.com committed
11462
    ndbassert(opPtr.p->m_requestFlag & RequestFlag::RF_FORCE);
11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483
    alterIndex_sendReply(signal, opPtr, false);
    return;
  }
  // request to drop in local TC
  DropIndxReq* const req = (DropIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(DropIndxReq::RT_TC);
  req->setTableId(indexPtr.p->primaryTableId);
  req->setIndexId(indexPtr.i);
  req->setIndexVersion(indexPtr.p->tableVersion);
  // send
  sendSignal(calcTcBlockRef(getOwnNodeId()), GSN_DROP_INDX_REQ,
      signal, DropIndxReq::SignalLength, JBB);
}

void
Dbdict::alterIndex_fromDropTc(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  ndbrequire(opPtr.p->m_requestType == AlterIndxReq::RT_DICT_TC);
11484 11485
  // mark dropped locally
  if (! opPtr.p->hasLastError()) {
11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521
    TableRecordPtr indexPtr;
    c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
    indexPtr.p->indexLocal &= ~TableRecord::IL_CREATED_TC;
  }
  // forward CONF or REF to master
  alterIndex_sendReply(signal, opPtr, false);
}

void
Dbdict::alterIndex_toCreateTrigger(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  // start creation of index triggers
  CreateTrigReq* const req = (CreateTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(CreateTrigReq::RT_ALTER_INDEX);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  req->setTableId(opPtr.p->m_request.getTableId());
  req->setIndexId(opPtr.p->m_request.getIndexId());
  req->setTriggerId(RNIL);
  req->setTriggerActionTime(TriggerActionTime::TA_AFTER);
  req->setMonitorAllAttributes(false);
  req->setOnline(true);         // alter online after create
  req->setReceiverRef(0);       // implicit for index triggers
  getIndexAttrMask(indexPtr, req->getAttributeMask());
  // name section
  char triggerName[MAX_TAB_NAME_SIZE];
  Uint32 buffer[2 + ((MAX_TAB_NAME_SIZE + 3) >> 2)];    // SP string
  LinearWriter w(buffer, sizeof(buffer) >> 2);
  LinearSectionPtr lsPtr[3];
  if (indexPtr.p->isHashIndex()) {
    req->setTriggerType(TriggerType::SECONDARY_INDEX);
    req->setMonitorReplicas(false);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
11522
    req->setReportAllMonitoredAttributes(true);
11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564
    // insert
    if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL)
      req->setTriggerId(indexPtr.p->insertTriggerId);
    req->setTriggerEvent(TriggerEvent::TE_INSERT);
    sprintf(triggerName, "NDB$INDEX_%u_INSERT", opPtr.p->m_request.getIndexId());
    w.reset();
    w.add(CreateTrigReq::TriggerNameKey, triggerName);
    lsPtr[0].p = buffer;
    lsPtr[0].sz = w.getWordsUsed();
    sendSignal(reference(), GSN_CREATE_TRIG_REQ, 
        signal, CreateTrigReq::SignalLength, JBB, lsPtr, 1);
    // update
    if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL)
      req->setTriggerId(indexPtr.p->updateTriggerId);
    req->setTriggerEvent(TriggerEvent::TE_UPDATE);
    sprintf(triggerName, "NDB$INDEX_%u_UPDATE", opPtr.p->m_request.getIndexId());
    w.reset();
    w.add(CreateTrigReq::TriggerNameKey, triggerName);
    lsPtr[0].p = buffer;
    lsPtr[0].sz = w.getWordsUsed();
    sendSignal(reference(), GSN_CREATE_TRIG_REQ, 
        signal, CreateTrigReq::SignalLength, JBB, lsPtr, 1);
    // delete
    if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL)
      req->setTriggerId(indexPtr.p->deleteTriggerId);
    req->setTriggerEvent(TriggerEvent::TE_DELETE);
    sprintf(triggerName, "NDB$INDEX_%u_DELETE", opPtr.p->m_request.getIndexId());
    w.reset();
    w.add(CreateTrigReq::TriggerNameKey, triggerName);
    lsPtr[0].p = buffer;
    lsPtr[0].sz = w.getWordsUsed();
    sendSignal(reference(), GSN_CREATE_TRIG_REQ, 
        signal, CreateTrigReq::SignalLength, JBB, lsPtr, 1);
    // triggers left to create
    opPtr.p->m_triggerCounter = 3;
    return;
  }
  if (indexPtr.p->isOrderedIndex()) {
    req->addRequestFlag(RequestFlag::RF_NOTCTRIGGER);
    req->setTriggerType(TriggerType::ORDERED_INDEX);
    req->setTriggerActionTime(TriggerActionTime::TA_CUSTOM);
    req->setMonitorReplicas(true);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
11565
    req->setReportAllMonitoredAttributes(true);
11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624
    // one trigger for 5 events (insert, update, delete, commit, abort)
    if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL)
      req->setTriggerId(indexPtr.p->customTriggerId);
    req->setTriggerEvent(TriggerEvent::TE_CUSTOM);
    sprintf(triggerName, "NDB$INDEX_%u_CUSTOM", opPtr.p->m_request.getIndexId());
    w.reset();
    w.add(CreateTrigReq::TriggerNameKey, triggerName);
    lsPtr[0].p = buffer;
    lsPtr[0].sz = w.getWordsUsed();
    sendSignal(reference(), GSN_CREATE_TRIG_REQ, 
        signal, CreateTrigReq::SignalLength, JBB, lsPtr, 1);
    // triggers left to create
    opPtr.p->m_triggerCounter = 1;
    return;
  }
  ndbrequire(false);
}

void
Dbdict::alterIndex_fromCreateTrigger(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  ndbrequire(opPtr.p->m_triggerCounter != 0);
  if (--opPtr.p->m_triggerCounter != 0) {
    jam();
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = AlterIndxReq::RT_DICT_ABORT;
    alterIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  if(opPtr.p->m_requestType != AlterIndxReq::RT_SYSTEMRESTART){
    // send build request
    alterIndex_toBuildIndex(signal, opPtr);
    return;
  }
  
  /**
   * During system restart, 
   *   leave index in activated but not build state.
   *
   * Build a bit later when REDO has been run
   */
  alterIndex_sendReply(signal, opPtr, true);
}

void
Dbdict::alterIndex_toDropTrigger(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  // start drop of index triggers
  DropTrigReq* const req = (DropTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(DropTrigReq::RT_ALTER_INDEX);
11625
  req->addRequestFlag(opPtr.p->m_requestFlag);
11626 11627 11628 11629
  req->setTableId(opPtr.p->m_request.getTableId());
  req->setIndexId(opPtr.p->m_request.getIndexId());
  req->setTriggerInfo(0);       // not used
  opPtr.p->m_triggerCounter = 0;
11630 11631
  if (indexPtr.p->isHashIndex()) {
    // insert
11632 11633 11634 11635
    req->setTriggerId(indexPtr.p->insertTriggerId);
    sendSignal(reference(), GSN_DROP_TRIG_REQ, 
        signal, DropTrigReq::SignalLength, JBB);
    opPtr.p->m_triggerCounter++;
11636
    // update
11637 11638 11639 11640
    req->setTriggerId(indexPtr.p->updateTriggerId);
    sendSignal(reference(), GSN_DROP_TRIG_REQ, 
        signal, DropTrigReq::SignalLength, JBB);
    opPtr.p->m_triggerCounter++;
11641
    // delete
11642 11643 11644 11645
    req->setTriggerId(indexPtr.p->deleteTriggerId);
    sendSignal(reference(), GSN_DROP_TRIG_REQ, 
        signal, DropTrigReq::SignalLength, JBB);
    opPtr.p->m_triggerCounter++;
11646 11647 11648 11649 11650 11651 11652 11653
    // build
    if (indexPtr.p->buildTriggerId != RNIL) {
      req->setTriggerId(indexPtr.p->buildTriggerId);
      sendSignal(reference(), GSN_DROP_TRIG_REQ, 
          signal, DropTrigReq::SignalLength, JBB);
      opPtr.p->m_triggerCounter++;
    }
    return;
11654
  }
11655 11656 11657
  if (indexPtr.p->isOrderedIndex()) {
    // custom
    req->addRequestFlag(RequestFlag::RF_NOTCTRIGGER);
11658 11659 11660 11661
    req->setTriggerId(indexPtr.p->customTriggerId);
    sendSignal(reference(), GSN_DROP_TRIG_REQ, 
        signal, DropTrigReq::SignalLength, JBB);
    opPtr.p->m_triggerCounter++;
11662
    return;
11663
  }
11664
  ndbrequire(false);
11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781
}

void
Dbdict::alterIndex_fromDropTrigger(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  ndbrequire(opPtr.p->m_triggerCounter != 0);
  if (--opPtr.p->m_triggerCounter != 0) {
    jam();
    return;
  }
  // finally drop index in each TC
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  const bool isHashIndex = indexPtr.p->isHashIndex();
  const bool isOrderedIndex = indexPtr.p->isOrderedIndex();
  ndbrequire(isHashIndex != isOrderedIndex);    // xor
  if (isHashIndex)
    opPtr.p->m_requestType = AlterIndxReq::RT_DICT_TC;
  if (isOrderedIndex)
    opPtr.p->m_requestType = AlterIndxReq::RT_DICT_COMMIT;
  alterIndex_sendSlaveReq(signal, opPtr);
}

void
Dbdict::alterIndex_toBuildIndex(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  // get index and table records
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, indexPtr.p->primaryTableId);
  // build request to self (short signal)
  BuildIndxReq* const req = (BuildIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(BuildIndxReq::RT_ALTER_INDEX);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  req->setBuildId(0);   // not used
  req->setBuildKey(0);  // not used
  req->setIndexType(indexPtr.p->tableType);
  req->setIndexId(indexPtr.i);
  req->setTableId(indexPtr.p->primaryTableId);
  req->setParallelism(16);
  // send
  sendSignal(reference(), GSN_BUILDINDXREQ,
      signal, BuildIndxReq::SignalLength, JBB);
}

void
Dbdict::alterIndex_fromBuildIndex(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = AlterIndxReq::RT_DICT_ABORT;
    alterIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  opPtr.p->m_requestType = AlterIndxReq::RT_DICT_COMMIT;
  alterIndex_sendSlaveReq(signal, opPtr);
}

void
Dbdict::alterIndex_slaveCommit(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  // get index record
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  indexPtr.p->indexState = TableRecord::IS_ONLINE;
}

void
Dbdict::alterIndex_slaveAbort(Signal* signal, OpAlterIndexPtr opPtr)
{
  jam();
  // find index record
  const Uint32 indexId = opPtr.p->m_request.getIndexId();
  if (indexId >= c_tableRecordPool.getSize())
    return;
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, indexId);
  if (! indexPtr.p->isIndex())
    return;
  // mark broken
  indexPtr.p->indexState = TableRecord::IS_BROKEN;
}

void
Dbdict::alterIndex_sendSlaveReq(Signal* signal, OpAlterIndexPtr opPtr)
{
  AlterIndxReq* const req = (AlterIndxReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  NdbNodeBitmask receiverNodes = c_aliveNodes;
  if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL) {
    receiverNodes.clear();
    receiverNodes.set(getOwnNodeId());
  }
  opPtr.p->m_signalCounter = receiverNodes;
  NodeReceiverGroup rg(DBDICT, receiverNodes);
  sendSignal(rg, GSN_ALTER_INDX_REQ,
      signal, AlterIndxReq::SignalLength, JBB);
}

void
Dbdict::alterIndex_sendReply(Signal* signal, OpAlterIndexPtr opPtr,
    bool toUser)
{
  AlterIndxRef* rep = (AlterIndxRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_ALTER_INDX_CONF;
  Uint32 length = AlterIndxConf::InternalLength;
11782
  bool sendRef;
11783
  if (! toUser) {
11784
    sendRef = opPtr.p->hasLastError();
11785 11786 11787 11788 11789 11790
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == AlterIndxReq::RT_DICT_ABORT)
      sendRef = false;
  } else {
11791
    sendRef = opPtr.p->hasError();
11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = AlterIndxConf::SignalLength;
  }
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setIndexId(opPtr.p->m_request.getIndexId());
  if (sendRef) {
    if (opPtr.p->m_errorNode == 0)
      opPtr.p->m_errorNode = getOwnNodeId();
    rep->setErrorCode(opPtr.p->m_errorCode);
    rep->setErrorLine(opPtr.p->m_errorLine);
    rep->setErrorNode(opPtr.p->m_errorNode);
    gsn = GSN_ALTER_INDX_REF;
    length = AlterIndxRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/**
 * MODULE: Build index
 *
 * Build index or all indexes on a table.  Request type:
 *
 * RT_USER - normal user request, not yet used
 * RT_ALTER_INDEX - from alter index
 * RT_SYSTEM_RESTART - 
 * RT_DICT_PREPARE - prepare participants
 * RT_DICT_TRIX - to participant on way to local TRIX
 * RT_DICT_COMMIT - commit in each participant
 * RT_DICT_ABORT - abort
 * RT_TRIX - to local TRIX
 */

void
Dbdict::execBUILDINDXREQ(Signal* signal)
{
  jamEntry();
  BuildIndxReq* const req = (BuildIndxReq*)signal->getDataPtrSend();
  OpBuildIndexPtr opPtr;
  const Uint32 senderRef = signal->senderBlockRef();
  const BuildIndxReq::RequestType requestType = req->getRequestType();
  if (requestType == BuildIndxReq::RT_USER ||
      requestType == BuildIndxReq::RT_ALTER_INDEX ||
      requestType == BuildIndxReq::RT_SYSTEMRESTART) {
    jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
11838 11839 11840 11841 11842 11843 11844 11845

    const bool isLocal = req->getRequestFlag() & RequestFlag::RF_LOCAL;
    NdbNodeBitmask receiverNodes = c_aliveNodes;
    if (isLocal) {
      receiverNodes.clear();
      receiverNodes.set(getOwnNodeId());
    }
    
11846 11847
    if (signal->getLength() == BuildIndxReq::SignalLength) {
      jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
11848 11849
      
      if (!isLocal && getOwnNodeId() != c_masterNodeId) {
11850
        jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
11851
	
11852 11853 11854 11855 11856 11857 11858 11859
	releaseSections(signal);
	OpBuildIndex opBad;
	opPtr.p = &opBad;
	opPtr.p->save(req);
	opPtr.p->m_errorCode = BuildIndxRef::NotMaster;
	opPtr.p->m_errorLine = __LINE__;
	opPtr.p->m_errorNode = c_masterNodeId;
	buildIndex_sendReply(signal, opPtr, true);
11860 11861 11862 11863
        return;
      }
      // forward initial request plus operation key to all
      req->setOpKey(++c_opRecordSequence);
joreland@mysql.com's avatar
joreland@mysql.com committed
11864
      NodeReceiverGroup rg(DBDICT, receiverNodes);
11865
      sendSignal(rg, GSN_BUILDINDXREQ,
joreland@mysql.com's avatar
joreland@mysql.com committed
11866
		 signal, BuildIndxReq::SignalLength + 1, JBB);
11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == BuildIndxReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpBuildIndex opBusy;
    if (! c_opBuildIndex.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = BuildIndxReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = BuildIndxRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      buildIndex_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opBuildIndex.add(opPtr);
    // master expects to hear from all
joreland@mysql.com's avatar
joreland@mysql.com committed
11889
    opPtr.p->m_signalCounter = receiverNodes;
11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081
    buildIndex_sendReply(signal, opPtr, false);
    return;
  }
  c_opBuildIndex.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == BuildIndxReq::RT_DICT_TRIX) {
      jam();
      buildIndex_buildTrix(signal, opPtr);
      return;
    }
    if (requestType == BuildIndxReq::RT_DICT_TC ||
        requestType == BuildIndxReq::RT_DICT_TUX) {
      jam();
      buildIndex_toOnline(signal, opPtr);
      return;
    }
    if (requestType == BuildIndxReq::RT_DICT_COMMIT ||
        requestType == BuildIndxReq::RT_DICT_ABORT) {
      jam();
      buildIndex_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
        c_opBuildIndex.release(opPtr);
      return;
    }
  }
  jam();
  // return to sender
  OpBuildIndex opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
  opPtr.p->m_errorCode = BuildIndxRef::BadRequestType;
  opPtr.p->m_errorLine = __LINE__;
  buildIndex_sendReply(signal, opPtr, true);
}

void
Dbdict::execBUILDINDXCONF(Signal* signal)
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);
  BuildIndxConf* conf = (BuildIndxConf*)signal->getDataPtrSend();
  buildIndex_recvReply(signal, conf, 0);
}

void
Dbdict::execBUILDINDXREF(Signal* signal)
{
  jamEntry();
  BuildIndxRef* ref = (BuildIndxRef*)signal->getDataPtrSend();
  buildIndex_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::buildIndex_recvReply(Signal* signal, const BuildIndxConf* conf,
    const BuildIndxRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const BuildIndxReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == BuildIndxReq::RT_ALTER_INDEX) {
    jam();
    // part of alter index operation
    OpAlterIndexPtr opPtr;
    c_opAlterIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterIndex_fromBuildIndex(signal, opPtr);
    return;
  }

  if (requestType == BuildIndxReq::RT_SYSTEMRESTART) {
    jam();
    if (ref == 0) {
      infoEvent("DICT: index %u rebuild done", (unsigned)key);
    } else {
      warningEvent("DICT: index %u rebuild failed: code=%d line=%d node=%d",
		   (unsigned)key, ref->getErrorCode());
    }
    rebuildIndexes(signal, key + 1);
    return;
  }

  OpBuildIndexPtr opPtr;
  c_opBuildIndex.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  opPtr.p->setError(ref);
  if (requestType == BuildIndxReq::RT_TRIX) {
    jam();
    // forward to master
    opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TRIX;
    buildIndex_sendReply(signal, opPtr, false);
    return;
  }
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == BuildIndxReq::RT_DICT_COMMIT ||
      requestType == BuildIndxReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    buildIndex_sendReply(signal, opPtr, true);
    c_opBuildIndex.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = BuildIndxReq::RT_DICT_ABORT;
    buildIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  if (indexPtr.p->isHashIndex()) {
    if (requestType == BuildIndxReq::RT_DICT_PREPARE) {
      jam();
      if (! (opPtr.p->m_requestFlag & RequestFlag::RF_NOBUILD)) {
        buildIndex_toCreateConstr(signal, opPtr);
      } else {
        opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TC;
        buildIndex_sendSlaveReq(signal, opPtr);
      }
      return;
    }
    if (requestType == BuildIndxReq::RT_DICT_TRIX) {
      jam();
      ndbrequire(! (opPtr.p->m_requestFlag & RequestFlag::RF_NOBUILD));
      buildIndex_toDropConstr(signal, opPtr);
      return;
    }
    if (requestType == BuildIndxReq::RT_DICT_TC) {
      jam();
      opPtr.p->m_requestType = BuildIndxReq::RT_DICT_COMMIT;
      buildIndex_sendSlaveReq(signal, opPtr);
      return;
    }
  }
  if (indexPtr.p->isOrderedIndex()) {
    if (requestType == BuildIndxReq::RT_DICT_PREPARE) {
      jam();
      if (! (opPtr.p->m_requestFlag & RequestFlag::RF_NOBUILD)) {
        opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TRIX;
        buildIndex_sendSlaveReq(signal, opPtr);
      } else {
        opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TUX;
        buildIndex_sendSlaveReq(signal, opPtr);
      }
      return;
    }
    if (requestType == BuildIndxReq::RT_DICT_TRIX) {
      jam();
      ndbrequire(! (opPtr.p->m_requestFlag & RequestFlag::RF_NOBUILD));
      opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TUX;
      buildIndex_sendSlaveReq(signal, opPtr);
      return;
    }
    if (requestType == BuildIndxReq::RT_DICT_TUX) {
      jam();
      opPtr.p->m_requestType = BuildIndxReq::RT_DICT_COMMIT;
      buildIndex_sendSlaveReq(signal, opPtr);
      return;
    }
  }
  ndbrequire(false);
} 

void
Dbdict::buildIndex_toCreateConstr(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  // request to create constraint trigger
  CreateTrigReq* req = (CreateTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(CreateTrigReq::RT_BUILD_INDEX);
  req->addRequestFlag(0);       // none
  req->setTableId(indexPtr.i);
  req->setIndexId(RNIL);
  req->setTriggerId(RNIL);
  req->setTriggerType(TriggerType::READ_ONLY_CONSTRAINT);
  req->setTriggerActionTime(TriggerActionTime::TA_AFTER);
  req->setTriggerEvent(TriggerEvent::TE_UPDATE);
  req->setMonitorReplicas(false);
  req->setMonitorAllAttributes(false);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
12082
  req->setReportAllMonitoredAttributes(true);
12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204
  req->setOnline(true);         // alter online after create
  req->setReceiverRef(0);       // no receiver, REF-ed by TUP
  req->getAttributeMask().clear();
  // NDB$PK is last attribute
  req->getAttributeMask().set(indexPtr.p->noOfAttributes - 1);
  // name section
  char triggerName[MAX_TAB_NAME_SIZE];
  Uint32 buffer[2 + ((MAX_TAB_NAME_SIZE + 3) >> 2)];    // SP string
  LinearWriter w(buffer, sizeof(buffer) >> 2);
  LinearSectionPtr lsPtr[3];
  sprintf(triggerName, "NDB$INDEX_%u_BUILD", indexPtr.i);
  w.reset();
  w.add(CreateTrigReq::TriggerNameKey, triggerName);
  lsPtr[0].p = buffer;
  lsPtr[0].sz = w.getWordsUsed();
  sendSignal(reference(), GSN_CREATE_TRIG_REQ,
      signal, CreateTrigReq::SignalLength, JBB, lsPtr, 1);
}

void
Dbdict::buildIndex_fromCreateConstr(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = BuildIndxReq::RT_DICT_ABORT;
    buildIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TRIX;
  buildIndex_sendSlaveReq(signal, opPtr);
}

void
Dbdict::buildIndex_buildTrix(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, indexPtr.p->primaryTableId);
  // build request
  BuildIndxReq* const req = (BuildIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(BuildIndxReq::RT_TRIX);
  req->setBuildId(0);   // not yet..
  req->setBuildKey(0);  // ..in use
  req->setIndexType(indexPtr.p->tableType);
  req->setIndexId(indexPtr.i);
  req->setTableId(indexPtr.p->primaryTableId);
  req->setParallelism(16);
  if (indexPtr.p->isHashIndex()) {
    jam();
    getIndexAttrList(indexPtr, opPtr.p->m_attrList);
    getTableKeyList(tablePtr, opPtr.p->m_tableKeyList);
    // send
    LinearSectionPtr lsPtr[3];
    lsPtr[0].sz = opPtr.p->m_attrList.sz;
    lsPtr[0].p = opPtr.p->m_attrList.id;
    lsPtr[1].sz = opPtr.p->m_tableKeyList.sz;
    lsPtr[1].p = opPtr.p->m_tableKeyList.id;
    sendSignal(calcTrixBlockRef(getOwnNodeId()), GSN_BUILDINDXREQ,
        signal, BuildIndxReq::SignalLength, JBB, lsPtr, 2);
    return;
  }
  if (indexPtr.p->isOrderedIndex()) {
    jam();
    sendSignal(calcTupBlockRef(getOwnNodeId()), GSN_BUILDINDXREQ,
        signal, BuildIndxReq::SignalLength, JBB);
    return;
  }
  ndbrequire(false);
}

void
Dbdict::buildIndex_toDropConstr(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  // request to drop constraint trigger
  DropTrigReq* req = (DropTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(DropTrigReq::RT_BUILD_INDEX);
  req->addRequestFlag(0);       // none
  req->setTableId(indexPtr.i);
  req->setIndexId(RNIL);
  req->setTriggerId(opPtr.p->m_constrTriggerId);
  req->setTriggerInfo(0);       // not used
  sendSignal(reference(), GSN_DROP_TRIG_REQ,
      signal, DropTrigReq::SignalLength, JBB);
}

void
Dbdict::buildIndex_fromDropConstr(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = BuildIndxReq::RT_DICT_ABORT;
    buildIndex_sendSlaveReq(signal, opPtr);
    return;
  }
  opPtr.p->m_requestType = BuildIndxReq::RT_DICT_TC;
  buildIndex_sendSlaveReq(signal, opPtr);
}

void
Dbdict::buildIndex_toOnline(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  TableRecordPtr indexPtr;
  c_tableRecordPool.getPtr(indexPtr, opPtr.p->m_request.getIndexId());
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, indexPtr.p->primaryTableId);
  // request to set index online in TC or TUX
  AlterIndxReq* const req = (AlterIndxReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  if (opPtr.p->m_requestType == BuildIndxReq::RT_DICT_TC) {
12205
    jam();
12206 12207
    req->setRequestType(AlterIndxReq::RT_TC);
  } else if (opPtr.p->m_requestType == BuildIndxReq::RT_DICT_TUX) {
12208
    jam();
12209 12210 12211 12212 12213 12214 12215 12216 12217 12218
    req->setRequestType(AlterIndxReq::RT_TUX);
  } else {
    ndbrequire(false);
  }
  req->setTableId(tablePtr.i);
  req->setIndexId(indexPtr.i);
  req->setIndexVersion(indexPtr.p->tableVersion);
  req->setOnline(true);
  BlockReference blockRef = 0;
  if (opPtr.p->m_requestType == BuildIndxReq::RT_DICT_TC) {
12219
    jam();
12220 12221
    blockRef = calcTcBlockRef(getOwnNodeId());
  } else if (opPtr.p->m_requestType == BuildIndxReq::RT_DICT_TUX) {
12222
    jam();
12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248
    blockRef = calcTuxBlockRef(getOwnNodeId());
  } else {
    ndbrequire(false);
  }
  // send
  sendSignal(blockRef, GSN_ALTER_INDX_REQ,
      signal, BuildIndxReq::SignalLength, JBB);
}

void
Dbdict::buildIndex_fromOnline(Signal* signal, OpBuildIndexPtr opPtr)
{
  jam();
  // forward to master
  buildIndex_sendReply(signal, opPtr, false);
}

void
Dbdict::buildIndex_sendSlaveReq(Signal* signal, OpBuildIndexPtr opPtr)
{
  BuildIndxReq* const req = (BuildIndxReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
12249 12250
  if(opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL) {
    jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
12251 12252 12253 12254
    opPtr.p->m_signalCounter.clearWaitingFor();
    opPtr.p->m_signalCounter.setWaitingFor(getOwnNodeId());
    sendSignal(reference(), GSN_BUILDINDXREQ,
	       signal, BuildIndxReq::SignalLength, JBB);
12255 12256
  } else {
    jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
12257 12258 12259 12260 12261
    opPtr.p->m_signalCounter = c_aliveNodes;
    NodeReceiverGroup rg(DBDICT, c_aliveNodes);
    sendSignal(rg, GSN_BUILDINDXREQ,
	       signal, BuildIndxReq::SignalLength, JBB);
  }
12262 12263 12264 12265 12266 12267 12268 12269 12270
}

void
Dbdict::buildIndex_sendReply(Signal* signal, OpBuildIndexPtr opPtr,
    bool toUser)
{
  BuildIndxRef* rep = (BuildIndxRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_BUILDINDXCONF;
  Uint32 length = BuildIndxConf::InternalLength;
12271
  bool sendRef;
12272
  if (! toUser) {
12273
    sendRef = opPtr.p->hasLastError();
12274 12275 12276 12277 12278 12279
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == BuildIndxReq::RT_DICT_ABORT)
      sendRef = false;
  } else {
12280
    sendRef = opPtr.p->hasError();
12281 12282 12283 12284 12285 12286 12287 12288 12289 12290
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = BuildIndxConf::SignalLength;
  }
  rep->setIndexType(opPtr.p->m_request.getIndexType());
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setIndexId(opPtr.p->m_request.getIndexId());
  if (sendRef) {
    rep->setErrorCode(opPtr.p->m_errorCode);
12291
    rep->masterNodeId = opPtr.p->m_errorNode;
12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339
    gsn = GSN_BUILDINDXREF;
    length = BuildIndxRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/**
 * MODULE: Create trigger
 *
 * Create trigger in all DICT blocks.  Optionally start alter trigger
 * operation to set the trigger online.
 *
 * Request type received in REQ and returned in CONF/REF:
 *
 * RT_USER - normal user e.g. BACKUP
 * RT_ALTER_INDEX - from alter index online
 * RT_DICT_PREPARE - seize operation in each DICT
 * RT_DICT_COMMIT - commit create in each DICT
 * RT_TC - sending to TC (operation alter trigger)
 * RT_LQH - sending to LQH (operation alter trigger)
 */

void
Dbdict::execCREATE_TRIG_REQ(Signal* signal) 
{
  jamEntry();
  CreateTrigReq* const req = (CreateTrigReq*)signal->getDataPtrSend();
  OpCreateTriggerPtr opPtr;
  const Uint32 senderRef = signal->senderBlockRef();
  const CreateTrigReq::RequestType requestType = req->getRequestType();
  if (requestType == CreateTrigReq::RT_USER ||
      requestType == CreateTrigReq::RT_ALTER_INDEX ||
      requestType == CreateTrigReq::RT_BUILD_INDEX) {
    jam();
    if (! assembleFragments(signal)) {
      jam();
      return;
    }
    const bool isLocal = req->getRequestFlag() & RequestFlag::RF_LOCAL;
    NdbNodeBitmask receiverNodes = c_aliveNodes;
    if (isLocal) {
      receiverNodes.clear();
      receiverNodes.set(getOwnNodeId());
    }
    if (signal->getLength() == CreateTrigReq::SignalLength) {
      jam();
      if (! isLocal && getOwnNodeId() != c_masterNodeId) {
        jam();
12340 12341 12342 12343 12344 12345 12346 12347 12348

	releaseSections(signal);
	OpCreateTrigger opBad;
	opPtr.p = &opBad;
	opPtr.p->save(req);
	opPtr.p->m_errorCode = CreateTrigRef::NotMaster;
	opPtr.p->m_errorLine = __LINE__;
	opPtr.p->m_errorNode = c_masterNodeId;
	createTrigger_sendReply(signal,  opPtr, true);
12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393
        return;
      }
      // forward initial request plus operation key to all
      req->setOpKey(++c_opRecordSequence);
      NodeReceiverGroup rg(DBDICT, receiverNodes);
      sendSignal(rg, GSN_CREATE_TRIG_REQ,
          signal, CreateTrigReq::SignalLength + 1, JBB);
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == CreateTrigReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpCreateTrigger opBusy;
    if (! c_opCreateTrigger.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = CreateTrigReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = CreateTrigRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      releaseSections(signal);
      createTrigger_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opCreateTrigger.add(opPtr);
    {
      // save name
      SegmentedSectionPtr ssPtr;
      signal->getSection(ssPtr, CreateTrigReq::TRIGGER_NAME_SECTION);
      SimplePropertiesSectionReader ssReader(ssPtr, getSectionSegmentPool());
      if (ssReader.getKey() != CreateTrigReq::TriggerNameKey ||
	  ! ssReader.getString(opPtr.p->m_triggerName)) {
	jam();
	opPtr.p->m_errorCode = CreateTrigRef::InvalidName;
	opPtr.p->m_errorLine = __LINE__;
	releaseSections(signal);
	createTrigger_sendReply(signal, opPtr, opPtr.p->m_isMaster);
	return;
      }
    }
    releaseSections(signal);
12394 12395 12396 12397 12398 12399
    if(get_object(opPtr.p->m_triggerName) != 0){
      jam();
      opPtr.p->m_errorCode = CreateTrigRef::TriggerExists;
      opPtr.p->m_errorLine = __LINE__;
      createTrigger_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
12400
    }
12401
    
12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588
    // master expects to hear from all
    if (opPtr.p->m_isMaster)
      opPtr.p->m_signalCounter = receiverNodes;
    // check request in all participants
    createTrigger_slavePrepare(signal, opPtr);
    createTrigger_sendReply(signal, opPtr, false);
    return;
  }
  c_opCreateTrigger.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == CreateTrigReq::RT_DICT_CREATE) {
      jam();
      // master has set trigger id
      opPtr.p->m_request.setTriggerId(req->getTriggerId());
      createTrigger_slaveCreate(signal, opPtr);
      createTrigger_sendReply(signal, opPtr, false);
      return;
    }
    if (requestType == CreateTrigReq::RT_DICT_COMMIT ||
        requestType == CreateTrigReq::RT_DICT_ABORT) {
      jam();
      if (requestType == CreateTrigReq::RT_DICT_COMMIT)
        createTrigger_slaveCommit(signal, opPtr);
      else
        createTrigger_slaveAbort(signal, opPtr);
      createTrigger_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
        c_opCreateTrigger.release(opPtr);
      return;
    }
  }
  jam();
  // return to sender
  releaseSections(signal);
  OpCreateTrigger opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
  opPtr.p->m_errorCode = CreateTrigRef::BadRequestType;
  opPtr.p->m_errorLine = __LINE__;
  createTrigger_sendReply(signal,  opPtr, true);
}

void
Dbdict::execCREATE_TRIG_CONF(Signal* signal) 
{
  jamEntry();
  ndbrequire(signal->getNoOfSections() == 0);
  CreateTrigConf* conf = (CreateTrigConf*)signal->getDataPtrSend();
  createTrigger_recvReply(signal, conf, 0);
}

void
Dbdict::execCREATE_TRIG_REF(Signal* signal) 
{
  jamEntry();
  CreateTrigRef* ref = (CreateTrigRef*)signal->getDataPtrSend();
  createTrigger_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::createTrigger_recvReply(Signal* signal, const CreateTrigConf* conf,
    const CreateTrigRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const CreateTrigReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == CreateTrigReq::RT_ALTER_INDEX) {
    jam();
    // part of alter index operation
    OpAlterIndexPtr opPtr;
    c_opAlterIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterIndex_fromCreateTrigger(signal, opPtr);
    return;
  }
  if (requestType == CreateTrigReq::RT_BUILD_INDEX) {
    jam();
    // part of build index operation
    OpBuildIndexPtr opPtr;
    c_opBuildIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    // fill in trigger id
    opPtr.p->m_constrTriggerId = conf->getTriggerId();
    buildIndex_fromCreateConstr(signal, opPtr);
    return;
  }
  if (requestType == CreateTrigReq::RT_TC ||
      requestType == CreateTrigReq::RT_LQH) {
    jam();
    // part of alter trigger operation
    OpAlterTriggerPtr opPtr;
    c_opAlterTrigger.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterTrigger_fromCreateLocal(signal, opPtr);
    return;
  }
  OpCreateTriggerPtr opPtr;
  c_opCreateTrigger.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  opPtr.p->setError(ref);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == CreateTrigReq::RT_DICT_COMMIT ||
      requestType == CreateTrigReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    createTrigger_sendReply(signal, opPtr, true);
    c_opCreateTrigger.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = CreateTrigReq::RT_DICT_ABORT;
    createTrigger_sendSlaveReq(signal, opPtr);
    return;
  }
  if (requestType == CreateTrigReq::RT_DICT_PREPARE) {
    jam();
    // seize trigger id in master
    createTrigger_masterSeize(signal, opPtr);
    if (opPtr.p->hasError()) {
      jam();
      opPtr.p->m_requestType = CreateTrigReq::RT_DICT_ABORT;
      createTrigger_sendSlaveReq(signal, opPtr);
      return;
    }
    opPtr.p->m_requestType = CreateTrigReq::RT_DICT_CREATE;
    createTrigger_sendSlaveReq(signal, opPtr);
    return;
  }
  if (requestType == CreateTrigReq::RT_DICT_CREATE) {
    jam();
    if (opPtr.p->m_request.getOnline()) {
      jam();
      // start alter online
      createTrigger_toAlterTrigger(signal, opPtr);
      return;
    }
    opPtr.p->m_requestType = CreateTrigReq::RT_DICT_COMMIT;
    createTrigger_sendSlaveReq(signal, opPtr);
    return;
  }
  ndbrequire(false);
}

void
Dbdict::createTrigger_slavePrepare(Signal* signal, OpCreateTriggerPtr opPtr)
{
  jam();
  const CreateTrigReq* const req = &opPtr.p->m_request;
  // check trigger type
  if (req->getRequestType() == CreateTrigReq::RT_USER &&
      req->getTriggerType() == TriggerType::SUBSCRIPTION ||
      req->getRequestType() == CreateTrigReq::RT_ALTER_INDEX &&
      req->getTriggerType() == TriggerType::SECONDARY_INDEX ||
      req->getRequestType() == CreateTrigReq::RT_ALTER_INDEX &&
      req->getTriggerType() == TriggerType::ORDERED_INDEX ||
      req->getRequestType() == CreateTrigReq::RT_BUILD_INDEX &&
      req->getTriggerType() == TriggerType::READ_ONLY_CONSTRAINT) {
    ;
  } else {
    jam();
    opPtr.p->m_errorCode = CreateTrigRef::UnsupportedTriggerType;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  // check the table
  const Uint32 tableId = req->getTableId();
  if (! (tableId < c_tableRecordPool.getSize())) {
    jam();
    opPtr.p->m_errorCode = CreateTrigRef::InvalidTable;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  TableRecordPtr tablePtr;
  c_tableRecordPool.getPtr(tablePtr, tableId);
joreland@mysql.com's avatar
joreland@mysql.com committed
12589 12590
  if (tablePtr.p->tabState != TableRecord::DEFINED &&
      tablePtr.p->tabState != TableRecord::BACKUP_ONGOING) {
12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629
    jam();
    opPtr.p->m_errorCode = CreateTrigRef::InvalidTable;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
}

void
Dbdict::createTrigger_masterSeize(Signal* signal, OpCreateTriggerPtr opPtr)
{
  TriggerRecordPtr triggerPtr;
  if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL) {
    triggerPtr.i = opPtr.p->m_request.getTriggerId();
  } else {
    triggerPtr.i = getFreeTriggerRecord();
    if (triggerPtr.i == RNIL) {
      jam();
      opPtr.p->m_errorCode = CreateTrigRef::TooManyTriggers;
      opPtr.p->m_errorLine = __LINE__;
      return;
    }
  }
  c_triggerRecordPool.getPtr(triggerPtr);
  initialiseTriggerRecord(triggerPtr);
  triggerPtr.p->triggerState = TriggerRecord::TS_DEFINING;
  opPtr.p->m_request.setTriggerId(triggerPtr.i);
}

void
Dbdict::createTrigger_slaveCreate(Signal* signal, OpCreateTriggerPtr opPtr)
{
  jam();
  const CreateTrigReq* const req = &opPtr.p->m_request;
  // get the trigger record
  const Uint32 triggerId = req->getTriggerId();
  TriggerRecordPtr triggerPtr;
  c_triggerRecordPool.getPtr(triggerPtr, triggerId);
  initialiseTriggerRecord(triggerPtr);
  // fill in trigger data
12630 12631
  {
    Rope name(c_rope_pool, triggerPtr.p->triggerName);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
12632 12633 12634 12635 12636
    if(!name.assign(opPtr.p->m_triggerName))
    {
      opPtr.p->m_errorCode = (CreateTrigRef::ErrorCode)CreateTableRef::OutOfStringBuffer;
      return;
    }
12637
  }
12638 12639 12640 12641 12642 12643 12644 12645
  triggerPtr.p->triggerId = triggerId;
  triggerPtr.p->tableId = req->getTableId();
  triggerPtr.p->indexId = RNIL;
  triggerPtr.p->triggerType = req->getTriggerType();
  triggerPtr.p->triggerActionTime = req->getTriggerActionTime();
  triggerPtr.p->triggerEvent = req->getTriggerEvent();
  triggerPtr.p->monitorReplicas = req->getMonitorReplicas();
  triggerPtr.p->monitorAllAttributes = req->getMonitorAllAttributes();
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
12646
  triggerPtr.p->reportAllMonitoredAttributes = req->getReportAllMonitoredAttributes();
12647 12648 12649 12650
  triggerPtr.p->attributeMask = req->getAttributeMask();
  triggerPtr.p->triggerState = TriggerRecord::TS_OFFLINE;
  // add to hash table
  //  ndbout_c("++++++++++++ Adding trigger id %u, %s", triggerPtr.p->triggerId, triggerPtr.p->triggerName);
12651 12652 12653 12654 12655 12656 12657 12658 12659 12660
  {
    Ptr<DictObject> obj_ptr;
    ndbrequire(c_obj_hash.seize(obj_ptr));
    obj_ptr.p->m_name = triggerPtr.p->triggerName;
    obj_ptr.p->m_id = triggerId;
    obj_ptr.p->m_type = triggerPtr.p->triggerType;
    obj_ptr.p->m_ref_count = 0;
    c_obj_hash.add(obj_ptr);
    triggerPtr.p->m_obj_ptr_i = obj_ptr.i;
  }
12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776
  if (triggerPtr.p->triggerType == TriggerType::SECONDARY_INDEX ||
      triggerPtr.p->triggerType == TriggerType::ORDERED_INDEX) {
    jam();
    // connect to index record  XXX should be done in caller instead
    triggerPtr.p->indexId = req->getIndexId();
    TableRecordPtr indexPtr;
    c_tableRecordPool.getPtr(indexPtr, triggerPtr.p->indexId);
    switch (triggerPtr.p->triggerEvent) {
    case TriggerEvent::TE_INSERT:
      indexPtr.p->insertTriggerId = triggerPtr.p->triggerId;
      break;
    case TriggerEvent::TE_UPDATE:
      indexPtr.p->updateTriggerId = triggerPtr.p->triggerId;
      break;
    case TriggerEvent::TE_DELETE:
      indexPtr.p->deleteTriggerId = triggerPtr.p->triggerId;
      break;
    case TriggerEvent::TE_CUSTOM:
      indexPtr.p->customTriggerId = triggerPtr.p->triggerId;
      break;
    default:
      ndbrequire(false);
      break;
    }
  }
  if (triggerPtr.p->triggerType == TriggerType::READ_ONLY_CONSTRAINT) {
    jam();
    // connect to index record  XXX should be done in caller instead
    triggerPtr.p->indexId = req->getTableId();
    TableRecordPtr indexPtr;
    c_tableRecordPool.getPtr(indexPtr, triggerPtr.p->indexId);
    indexPtr.p->buildTriggerId = triggerPtr.p->triggerId;
  }
}

void
Dbdict::createTrigger_toAlterTrigger(Signal* signal, OpCreateTriggerPtr opPtr)
{
  jam();
  AlterTrigReq* req = (AlterTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(AlterTrigReq::RT_CREATE_TRIGGER);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  req->setTableId(opPtr.p->m_request.getTableId());
  req->setTriggerId(opPtr.p->m_request.getTriggerId());
  req->setTriggerInfo(0);       // not used
  req->setOnline(true);
  req->setReceiverRef(opPtr.p->m_request.getReceiverRef());
  sendSignal(reference(), GSN_ALTER_TRIG_REQ,
      signal, AlterTrigReq::SignalLength, JBB);
}

void
Dbdict::createTrigger_fromAlterTrigger(Signal* signal, OpCreateTriggerPtr opPtr)
{
  jam();
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = CreateTrigReq::RT_DICT_ABORT;
    createTrigger_sendSlaveReq(signal, opPtr);
    return;
  }
  opPtr.p->m_requestType = CreateTrigReq::RT_DICT_COMMIT;
  createTrigger_sendSlaveReq(signal, opPtr);
}

void
Dbdict::createTrigger_slaveCommit(Signal* signal, OpCreateTriggerPtr opPtr)
{
  jam();
  const CreateTrigReq* const req = &opPtr.p->m_request;
  // get the trigger record
  const Uint32 triggerId = req->getTriggerId();
  TriggerRecordPtr triggerPtr;
  c_triggerRecordPool.getPtr(triggerPtr, triggerId);
  if (! req->getOnline()) {
    triggerPtr.p->triggerState = TriggerRecord::TS_OFFLINE;
  } else {
    ndbrequire(triggerPtr.p->triggerState == TriggerRecord::TS_ONLINE);
  }
}

void
Dbdict::createTrigger_slaveAbort(Signal* signal, OpCreateTriggerPtr opPtr)
{
  jam();
}

void
Dbdict::createTrigger_sendSlaveReq(Signal* signal, OpCreateTriggerPtr opPtr)
{
  CreateTrigReq* const req = (CreateTrigReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  NdbNodeBitmask receiverNodes = c_aliveNodes;
  if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL) {
    receiverNodes.clear();
    receiverNodes.set(getOwnNodeId());
  }
  opPtr.p->m_signalCounter = receiverNodes;
  NodeReceiverGroup rg(DBDICT, receiverNodes);
  sendSignal(rg, GSN_CREATE_TRIG_REQ,
      signal, CreateTrigReq::SignalLength, JBB);
}

void
Dbdict::createTrigger_sendReply(Signal* signal, OpCreateTriggerPtr opPtr,
    bool toUser)
{
  CreateTrigRef* rep = (CreateTrigRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_CREATE_TRIG_CONF;
  Uint32 length = CreateTrigConf::InternalLength;
12777
  bool sendRef;
12778
  if (! toUser) {
12779
    sendRef = opPtr.p->hasLastError();
12780 12781 12782 12783 12784 12785
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == CreateTrigReq::RT_DICT_ABORT)
      sendRef = false;
  } else {
12786
    sendRef = opPtr.p->hasError();
12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = CreateTrigConf::SignalLength;
  }
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setIndexId(opPtr.p->m_request.getIndexId());
  rep->setTriggerId(opPtr.p->m_request.getTriggerId());
  rep->setTriggerInfo(opPtr.p->m_request.getTriggerInfo());
  if (sendRef) {
    if (opPtr.p->m_errorNode == 0)
      opPtr.p->m_errorNode = getOwnNodeId();
    rep->setErrorCode(opPtr.p->m_errorCode);
    rep->setErrorLine(opPtr.p->m_errorLine);
    rep->setErrorNode(opPtr.p->m_errorNode);
    gsn = GSN_CREATE_TRIG_REF;
    length = CreateTrigRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/**
 * MODULE: Drop trigger.
 */

void
Dbdict::execDROP_TRIG_REQ(Signal* signal) 
{
  jamEntry();
  DropTrigReq* const req = (DropTrigReq*)signal->getDataPtrSend();
  OpDropTriggerPtr opPtr;
  const Uint32 senderRef = signal->senderBlockRef();
  const DropTrigReq::RequestType requestType = req->getRequestType();

  if (signal->getNoOfSections() > 0) {
    ndbrequire(signal->getNoOfSections() == 1);
    jam();
12824
    char triggerName[MAX_TAB_NAME_SIZE];
12825 12826 12827 12828 12829 12830 12831
    OpDropTrigger opTmp;
    opPtr.p=&opTmp;

    SegmentedSectionPtr ssPtr;
    signal->getSection(ssPtr, DropTrigReq::TRIGGER_NAME_SECTION);
    SimplePropertiesSectionReader ssReader(ssPtr, getSectionSegmentPool());
    if (ssReader.getKey() != DropTrigReq::TriggerNameKey ||
12832
	! ssReader.getString(triggerName)) {
12833 12834 12835 12836 12837 12838 12839 12840 12841
      jam();
      opPtr.p->m_errorCode = DropTrigRef::InvalidName;
      opPtr.p->m_errorLine = __LINE__;
      releaseSections(signal);
      dropTrigger_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    releaseSections(signal);

12842 12843 12844
    //ndbout_c("++++++++++++++ Looking for trigger %s", keyRecord.triggerName);
    DictObject * obj_ptr_p = get_object(triggerName);
    if (obj_ptr_p == 0){
12845 12846 12847 12848
      jam();
      req->setTriggerId(RNIL);
    } else {
      jam();
12849 12850 12851
      //ndbout_c("++++++++++ Found trigger %s", triggerPtr.p->triggerName);
      TriggerRecordPtr triggerPtr;
      c_triggerRecordPool.getPtr(triggerPtr, obj_ptr_p->m_id);
12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873
      req->setTriggerId(triggerPtr.p->triggerId);
      req->setTableId(triggerPtr.p->tableId);
    }
  }
  if (requestType == DropTrigReq::RT_USER ||
      requestType == DropTrigReq::RT_ALTER_INDEX ||
      requestType == DropTrigReq::RT_BUILD_INDEX) {
    jam();
    if (signal->getLength() == DropTrigReq::SignalLength) {
      if (getOwnNodeId() != c_masterNodeId) {
	jam();
	// forward to DICT master
	sendSignal(calcDictBlockRef(c_masterNodeId), GSN_DROP_TRIG_REQ,
		   signal, signal->getLength(), JBB);
	return;
      }
      if (!c_triggerRecordPool.findId(req->getTriggerId())) {
	jam();
	// return to sender
	OpDropTrigger opBad;
	opPtr.p = &opBad;
	opPtr.p->save(req);
12874 12875 12876 12877
        if (! (req->getRequestFlag() & RequestFlag::RF_FORCE)) {
          opPtr.p->m_errorCode = DropTrigRef::TriggerNotFound;
          opPtr.p->m_errorLine = __LINE__;
        }
12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043
	dropTrigger_sendReply(signal,  opPtr, true);
	return;
      }
      // forward initial request plus operation key to all
      req->setOpKey(++c_opRecordSequence);
      NodeReceiverGroup rg(DBDICT, c_aliveNodes);
      sendSignal(rg, GSN_DROP_TRIG_REQ,
		 signal, DropTrigReq::SignalLength + 1, JBB);
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == DropTrigReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpDropTrigger opBusy;
    if (! c_opDropTrigger.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = DropTrigReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = DropTrigRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      dropTrigger_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opDropTrigger.add(opPtr);
      // master expects to hear from all
    if (opPtr.p->m_isMaster)
	opPtr.p->m_signalCounter = c_aliveNodes;
    dropTrigger_slavePrepare(signal, opPtr);
    dropTrigger_sendReply(signal, opPtr, false);
    return;
  }
  c_opDropTrigger.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == DropTrigReq::RT_DICT_COMMIT ||
	requestType == DropTrigReq::RT_DICT_ABORT) {
      jam();
      if (requestType == DropTrigReq::RT_DICT_COMMIT)
	dropTrigger_slaveCommit(signal, opPtr);
      else
	dropTrigger_slaveAbort(signal, opPtr);
      dropTrigger_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
	c_opDropTrigger.release(opPtr);
      return;
    }
  }
  jam();
  // return to sender
  OpDropTrigger opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
  opPtr.p->m_errorCode = DropTrigRef::BadRequestType;
  opPtr.p->m_errorLine = __LINE__;
  dropTrigger_sendReply(signal,  opPtr, true);
}

void
Dbdict::execDROP_TRIG_CONF(Signal* signal) 
{
  jamEntry();
  DropTrigConf* conf = (DropTrigConf*)signal->getDataPtrSend();
  dropTrigger_recvReply(signal, conf, 0);
}

void
Dbdict::execDROP_TRIG_REF(Signal* signal) 
{
  jamEntry();
  DropTrigRef* ref = (DropTrigRef*)signal->getDataPtrSend();
  dropTrigger_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::dropTrigger_recvReply(Signal* signal, const DropTrigConf* conf,
    const DropTrigRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const DropTrigReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == DropTrigReq::RT_ALTER_INDEX) {
    jam();
    // part of alter index operation
    OpAlterIndexPtr opPtr;
    c_opAlterIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterIndex_fromDropTrigger(signal, opPtr);
    return;
  }
  if (requestType == DropTrigReq::RT_BUILD_INDEX) {
    jam();
    // part of build index operation
    OpBuildIndexPtr opPtr;
    c_opBuildIndex.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    buildIndex_fromDropConstr(signal, opPtr);
    return;
  }
  if (requestType == DropTrigReq::RT_TC ||
      requestType == DropTrigReq::RT_LQH) {
    jam();
    // part of alter trigger operation
    OpAlterTriggerPtr opPtr;
    c_opAlterTrigger.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    alterTrigger_fromDropLocal(signal, opPtr);
    return;
  }
  OpDropTriggerPtr opPtr;
  c_opDropTrigger.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  opPtr.p->setError(ref);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == DropTrigReq::RT_DICT_COMMIT ||
      requestType == DropTrigReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    dropTrigger_sendReply(signal, opPtr, true);
    c_opDropTrigger.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = DropTrigReq::RT_DICT_ABORT;
    dropTrigger_sendSlaveReq(signal, opPtr);
    return;
  }
  if (requestType == DropTrigReq::RT_DICT_PREPARE) {
    jam();
    // start alter offline
    dropTrigger_toAlterTrigger(signal, opPtr);
    return;
  }
  ndbrequire(false);
}

void
Dbdict::dropTrigger_slavePrepare(Signal* signal, OpDropTriggerPtr opPtr)
{
  jam();
}

void
Dbdict::dropTrigger_toAlterTrigger(Signal* signal, OpDropTriggerPtr opPtr)
{
  jam();
  AlterTrigReq* req = (AlterTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(AlterTrigReq::RT_DROP_TRIGGER);
13044
  req->addRequestFlag(opPtr.p->m_requestFlag);
13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120
  req->setTableId(opPtr.p->m_request.getTableId());
  req->setTriggerId(opPtr.p->m_request.getTriggerId());
  req->setTriggerInfo(0);       // not used
  req->setOnline(false);
  req->setReceiverRef(0);
  sendSignal(reference(), GSN_ALTER_TRIG_REQ,
      signal, AlterTrigReq::SignalLength, JBB);
}

void
Dbdict::dropTrigger_fromAlterTrigger(Signal* signal, OpDropTriggerPtr opPtr)
{
  jam();
  // remove in all
  opPtr.p->m_requestType = DropTrigReq::RT_DICT_COMMIT;
  dropTrigger_sendSlaveReq(signal, opPtr);
}

void
Dbdict::dropTrigger_sendSlaveReq(Signal* signal, OpDropTriggerPtr opPtr)
{
  DropTrigReq* const req = (DropTrigReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  opPtr.p->m_signalCounter = c_aliveNodes;
  NodeReceiverGroup rg(DBDICT, c_aliveNodes);
  sendSignal(rg, GSN_DROP_TRIG_REQ,
      signal, DropTrigReq::SignalLength, JBB);
}

void
Dbdict::dropTrigger_slaveCommit(Signal* signal, OpDropTriggerPtr opPtr)
{
  jam();
  const DropTrigReq* const req = &opPtr.p->m_request;
  // get trigger record
  const Uint32 triggerId = req->getTriggerId();
  TriggerRecordPtr triggerPtr;
  c_triggerRecordPool.getPtr(triggerPtr, triggerId);
  if (triggerPtr.p->triggerType == TriggerType::SECONDARY_INDEX ||
      triggerPtr.p->triggerType == TriggerType::ORDERED_INDEX) {
    jam();
    // disconnect from index if index trigger  XXX move to drop index
    triggerPtr.p->indexId = req->getIndexId();
    TableRecordPtr indexPtr;
    c_tableRecordPool.getPtr(indexPtr, triggerPtr.p->indexId);
    ndbrequire(! indexPtr.isNull());
    switch (triggerPtr.p->triggerEvent) {
    case TriggerEvent::TE_INSERT:
      indexPtr.p->insertTriggerId = RNIL;
      break;
    case TriggerEvent::TE_UPDATE:
      indexPtr.p->updateTriggerId = RNIL;
      break;
    case TriggerEvent::TE_DELETE:
      indexPtr.p->deleteTriggerId = RNIL;
      break;
    case TriggerEvent::TE_CUSTOM:
      indexPtr.p->customTriggerId = RNIL;
      break;
    default:
      ndbrequire(false);
      break;
    }
  }
  if (triggerPtr.p->triggerType == TriggerType::READ_ONLY_CONSTRAINT) {
    jam();
    // disconnect from index record  XXX should be done in caller instead
    triggerPtr.p->indexId = req->getTableId();
    TableRecordPtr indexPtr;
    c_tableRecordPool.getPtr(indexPtr, triggerPtr.p->indexId);
    indexPtr.p->buildTriggerId = RNIL;
  }
13121 13122 13123
  //remove trigger
  //ndbout_c("++++++++++++ Removing trigger id %u, %s", triggerPtr.p->triggerId, triggerPtr.p->triggerName);
  release_object(triggerPtr.p->m_obj_ptr_i);
13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139
  triggerPtr.p->triggerState = TriggerRecord::TS_NOT_DEFINED;
}

void
Dbdict::dropTrigger_slaveAbort(Signal* signal, OpDropTriggerPtr opPtr)
{
  jam();
}

void
Dbdict::dropTrigger_sendReply(Signal* signal, OpDropTriggerPtr opPtr,
    bool toUser)
{
  DropTrigRef* rep = (DropTrigRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_DROP_TRIG_CONF;
  Uint32 length = DropTrigConf::InternalLength;
13140
  bool sendRef;
13141
  if (! toUser) {
13142
    sendRef = opPtr.p->hasLastError();
13143 13144 13145 13146 13147 13148
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == DropTrigReq::RT_DICT_ABORT)
      sendRef = false;
  } else {
13149
    sendRef = opPtr.p->hasError();
13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = DropTrigConf::SignalLength;
  }
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setIndexId(opPtr.p->m_request.getIndexId());
  rep->setTriggerId(opPtr.p->m_request.getTriggerId());
  if (sendRef) {
    if (opPtr.p->m_errorNode == 0)
      opPtr.p->m_errorNode = getOwnNodeId();
    rep->setErrorCode(opPtr.p->m_errorCode);
    rep->setErrorLine(opPtr.p->m_errorLine);
    rep->setErrorNode(opPtr.p->m_errorNode);
    gsn = GSN_DROP_TRIG_REF;
    length = CreateTrigRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/**
 * MODULE: Alter trigger.
 *
 * Alter trigger state.  Alter online creates the trigger first in all
 * TC (if index trigger) and then in all LQH-TUP.
 *
 * Request type received in REQ and returned in CONF/REF:
 *
 * RT_USER - normal user e.g. BACKUP
 * RT_CREATE_TRIGGER - from create trigger
 * RT_DROP_TRIGGER - from drop trigger
 * RT_DICT_PREPARE - seize operations and check request
 * RT_DICT_TC - master to each DICT on way to TC
 * RT_DICT_LQH - master to each DICT on way to LQH-TUP
 * RT_DICT_COMMIT - commit state change in each DICT (no reply)
 */

void
Dbdict::execALTER_TRIG_REQ(Signal* signal) 
{
  jamEntry();
  AlterTrigReq* const req = (AlterTrigReq*)signal->getDataPtrSend();
  OpAlterTriggerPtr opPtr;
  const Uint32 senderRef = signal->senderBlockRef();
  const AlterTrigReq::RequestType requestType = req->getRequestType();
  if (requestType == AlterTrigReq::RT_USER ||
      requestType == AlterTrigReq::RT_CREATE_TRIGGER ||
      requestType == AlterTrigReq::RT_DROP_TRIGGER) {
    jam();
    const bool isLocal = req->getRequestFlag() & RequestFlag::RF_LOCAL;
    NdbNodeBitmask receiverNodes = c_aliveNodes;
    if (isLocal) {
      receiverNodes.clear();
      receiverNodes.set(getOwnNodeId());
    }
    if (signal->getLength() == AlterTrigReq::SignalLength) {
      jam();
      if (! isLocal && getOwnNodeId() != c_masterNodeId) {
        jam();
        // forward to DICT master
        sendSignal(calcDictBlockRef(c_masterNodeId), GSN_ALTER_TRIG_REQ,
            signal, AlterTrigReq::SignalLength, JBB);
        return;
      }
      // forward initial request plus operation key to all
      req->setOpKey(++c_opRecordSequence);
      NodeReceiverGroup rg(DBDICT, receiverNodes);
      sendSignal(rg, GSN_ALTER_TRIG_REQ,
          signal, AlterTrigReq::SignalLength + 1, JBB);
      return;
    }
    // seize operation record
    ndbrequire(signal->getLength() == AlterTrigReq::SignalLength + 1);
    const Uint32 opKey = req->getOpKey();
    OpAlterTrigger opBusy;
    if (! c_opAlterTrigger.seize(opPtr))
      opPtr.p = &opBusy;
    opPtr.p->save(req);
    opPtr.p->m_coordinatorRef = senderRef;
    opPtr.p->m_isMaster = (senderRef == reference());
    opPtr.p->key = opKey;
    opPtr.p->m_requestType = AlterTrigReq::RT_DICT_PREPARE;
    if (opPtr.p == &opBusy) {
      jam();
      opPtr.p->m_errorCode = AlterTrigRef::Busy;
      opPtr.p->m_errorLine = __LINE__;
      alterTrigger_sendReply(signal, opPtr, opPtr.p->m_isMaster);
      return;
    }
    c_opAlterTrigger.add(opPtr);
    // master expects to hear from all
    if (opPtr.p->m_isMaster) {
      opPtr.p->m_nodes = receiverNodes;
      opPtr.p->m_signalCounter = receiverNodes;
    }
    alterTrigger_slavePrepare(signal, opPtr);
    alterTrigger_sendReply(signal, opPtr, false);
    return;
  }
  c_opAlterTrigger.find(opPtr, req->getConnectionPtr());
  if (! opPtr.isNull()) {
    opPtr.p->m_requestType = requestType;
    if (requestType == AlterTrigReq::RT_DICT_TC ||
        requestType == AlterTrigReq::RT_DICT_LQH) {
      jam();
      if (req->getOnline())
        alterTrigger_toCreateLocal(signal, opPtr);
      else
        alterTrigger_toDropLocal(signal, opPtr);
      return;
    }
    if (requestType == AlterTrigReq::RT_DICT_COMMIT ||
        requestType == AlterTrigReq::RT_DICT_ABORT) {
      jam();
      if (requestType == AlterTrigReq::RT_DICT_COMMIT)
        alterTrigger_slaveCommit(signal, opPtr);
      else
        alterTrigger_slaveAbort(signal, opPtr);
      alterTrigger_sendReply(signal, opPtr, false);
      // done in slave
      if (! opPtr.p->m_isMaster)
        c_opAlterTrigger.release(opPtr);
      return;
    }
  }
  jam();
  // return to sender
  OpAlterTrigger opBad;
  opPtr.p = &opBad;
  opPtr.p->save(req);
  opPtr.p->m_errorCode = AlterTrigRef::BadRequestType;
  opPtr.p->m_errorLine = __LINE__;
  alterTrigger_sendReply(signal, opPtr, true);
  return;
}

void
Dbdict::execALTER_TRIG_CONF(Signal* signal) 
{
  jamEntry();
  AlterTrigConf* conf = (AlterTrigConf*)signal->getDataPtrSend();
  alterTrigger_recvReply(signal, conf, 0);
}

void
Dbdict::execALTER_TRIG_REF(Signal* signal) 
{
  jamEntry();
  AlterTrigRef* ref = (AlterTrigRef*)signal->getDataPtrSend();
  alterTrigger_recvReply(signal, ref->getConf(), ref);
}

void
Dbdict::alterTrigger_recvReply(Signal* signal, const AlterTrigConf* conf,
    const AlterTrigRef* ref)
{
  jam();
  const Uint32 senderRef = signal->senderBlockRef();
  const AlterTrigReq::RequestType requestType = conf->getRequestType();
  const Uint32 key = conf->getConnectionPtr();
  if (requestType == AlterTrigReq::RT_CREATE_TRIGGER) {
    jam();
    // part of create trigger operation
    OpCreateTriggerPtr opPtr;
    c_opCreateTrigger.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    createTrigger_fromAlterTrigger(signal, opPtr);
    return;
  }
  if (requestType == AlterTrigReq::RT_DROP_TRIGGER) {
    jam();
    // part of drop trigger operation
    OpDropTriggerPtr opPtr;
    c_opDropTrigger.find(opPtr, key);
    ndbrequire(! opPtr.isNull());
    opPtr.p->setError(ref);
    dropTrigger_fromAlterTrigger(signal, opPtr);
    return;
  }
  OpAlterTriggerPtr opPtr;
  c_opAlterTrigger.find(opPtr, key);
  ndbrequire(! opPtr.isNull());
  ndbrequire(opPtr.p->m_isMaster);
  ndbrequire(opPtr.p->m_requestType == requestType);
  /* 
   * If refuse on drop trig, because of non-existent trigger,
   * comes from anyone but the master node - ignore it and
   * remove the node from forter ALTER_TRIG communication
   * This will happen if a new node has started since the
   * trigger whas created.
   */
  if (ref &&
      refToNode(senderRef) != refToNode(reference()) &&
      opPtr.p->m_request.getRequestType() == AlterTrigReq::RT_DROP_TRIGGER &&
      ref->getErrorCode() == AlterTrigRef::TriggerNotFound) {
    jam();
    ref = 0;                                      // ignore this error
    opPtr.p->m_nodes.clear(refToNode(senderRef)); // remove this from group
  }
  opPtr.p->setError(ref);
  opPtr.p->m_signalCounter.clearWaitingFor(refToNode(senderRef));
  if (! opPtr.p->m_signalCounter.done()) {
    jam();
    return;
  }
  if (requestType == AlterTrigReq::RT_DICT_COMMIT ||
      requestType == AlterTrigReq::RT_DICT_ABORT) {
    jam();
    // send reply to user
    alterTrigger_sendReply(signal, opPtr, true);
    c_opAlterTrigger.release(opPtr);
    return;
  }
  if (opPtr.p->hasError()) {
    jam();
    opPtr.p->m_requestType = AlterTrigReq::RT_DICT_ABORT;
    alterTrigger_sendSlaveReq(signal, opPtr);
    return;
  }
  if (! (opPtr.p->m_request.getRequestFlag() & RequestFlag::RF_NOTCTRIGGER)) {
    if (requestType == AlterTrigReq::RT_DICT_PREPARE) {
      jam();
13373 13374
      if (opPtr.p->m_request.getOnline()) {
        jam();
13375
        opPtr.p->m_requestType = AlterTrigReq::RT_DICT_TC;
13376 13377
      } else {
        jam();
13378
        opPtr.p->m_requestType = AlterTrigReq::RT_DICT_LQH;
13379
      }
13380 13381 13382 13383 13384
      alterTrigger_sendSlaveReq(signal, opPtr);
      return;
    }
    if (requestType == AlterTrigReq::RT_DICT_TC) {
      jam();
13385 13386
      if (opPtr.p->m_request.getOnline()) {
        jam();
13387
        opPtr.p->m_requestType = AlterTrigReq::RT_DICT_LQH;
13388 13389
      } else {
        jam();
13390
        opPtr.p->m_requestType = AlterTrigReq::RT_DICT_COMMIT;
13391
      }
13392 13393 13394 13395 13396
      alterTrigger_sendSlaveReq(signal, opPtr);
      return;
    }
    if (requestType == AlterTrigReq::RT_DICT_LQH) {
      jam();
13397 13398
      if (opPtr.p->m_request.getOnline()) {
        jam();
13399
        opPtr.p->m_requestType = AlterTrigReq::RT_DICT_COMMIT;
13400 13401
      } else {
        jam();
13402
        opPtr.p->m_requestType = AlterTrigReq::RT_DICT_TC;
13403
      }
13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443
      alterTrigger_sendSlaveReq(signal, opPtr);
      return;
    }
  } else {
    if (requestType == AlterTrigReq::RT_DICT_PREPARE) {
      jam();
      opPtr.p->m_requestType = AlterTrigReq::RT_DICT_LQH;
      alterTrigger_sendSlaveReq(signal, opPtr);
      return;
    }
    if (requestType == AlterTrigReq::RT_DICT_LQH) {
      jam();
      opPtr.p->m_requestType = AlterTrigReq::RT_DICT_COMMIT;
      alterTrigger_sendSlaveReq(signal, opPtr);
      return;
    }
  }
  ndbrequire(false);
}

void
Dbdict::alterTrigger_slavePrepare(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
  const AlterTrigReq* const req = &opPtr.p->m_request;
  const Uint32 triggerId = req->getTriggerId();
  TriggerRecordPtr triggerPtr;
  if (! (triggerId < c_triggerRecordPool.getSize())) {
    jam();
    opPtr.p->m_errorCode = AlterTrigRef::TriggerNotFound;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
  c_triggerRecordPool.getPtr(triggerPtr, triggerId);
  if (triggerPtr.p->triggerState == TriggerRecord::TS_NOT_DEFINED) {
    jam();
    opPtr.p->m_errorCode = AlterTrigRef::TriggerNotFound;
    opPtr.p->m_errorLine = __LINE__;
    return;
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
13444 13445 13446 13447 13448

  if (triggerPtr.p->triggerType == TriggerType::SUBSCRIPTION)
  {
    opPtr.p->m_request.addRequestFlag(RequestFlag::RF_NOTCTRIGGER);
  }
13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462
}

void
Dbdict::alterTrigger_toCreateLocal(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
  // find trigger record
  const Uint32 triggerId = opPtr.p->m_request.getTriggerId();
  TriggerRecordPtr triggerPtr;
  c_triggerRecordPool.getPtr(triggerPtr, triggerId);
  CreateTrigReq* const req = (CreateTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_TC) {
13463
    jam();
13464 13465
    req->setRequestType(CreateTrigReq::RT_TC);
  } else if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_LQH) {
13466
    jam();
13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478
    req->setRequestType(CreateTrigReq::RT_LQH);
  } else {
    ndbassert(false);
  }
  req->setTableId(triggerPtr.p->tableId);
  req->setIndexId(triggerPtr.p->indexId);
  req->setTriggerId(triggerPtr.i);
  req->setTriggerType(triggerPtr.p->triggerType);
  req->setTriggerActionTime(triggerPtr.p->triggerActionTime);
  req->setTriggerEvent(triggerPtr.p->triggerEvent);
  req->setMonitorReplicas(triggerPtr.p->monitorReplicas);
  req->setMonitorAllAttributes(triggerPtr.p->monitorAllAttributes);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
13479
  req->setReportAllMonitoredAttributes(triggerPtr.p->reportAllMonitoredAttributes);
13480 13481 13482 13483
  req->setOnline(true);
  req->setReceiverRef(opPtr.p->m_request.getReceiverRef());
  BlockReference blockRef = 0;
  if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_TC) {
13484
    jam();
13485 13486
    blockRef = calcTcBlockRef(getOwnNodeId());
  } else if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_LQH) {
13487
    jam();
13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500
    blockRef = calcLqhBlockRef(getOwnNodeId());
  } else {
    ndbassert(false);
  }
  req->setAttributeMask(triggerPtr.p->attributeMask);
  sendSignal(blockRef, GSN_CREATE_TRIG_REQ,
      signal, CreateTrigReq::SignalLength, JBB);
}

void
Dbdict::alterTrigger_fromCreateLocal(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
13501
  if (! opPtr.p->hasLastError()) {
13502 13503 13504 13505
    // mark created locally
    TriggerRecordPtr triggerPtr;
    c_triggerRecordPool.getPtr(triggerPtr, opPtr.p->m_request.getTriggerId());
    if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_TC) {
13506
      jam();
13507 13508
      triggerPtr.p->triggerLocal |= TriggerRecord::TL_CREATED_TC;
    } else if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_LQH) {
13509
      jam();
13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528
      triggerPtr.p->triggerLocal |= TriggerRecord::TL_CREATED_LQH;
    } else {
      ndbrequire(false);
    }
  }
  // forward CONF or REF to master
  alterTrigger_sendReply(signal, opPtr, false);
}

void
Dbdict::alterTrigger_toDropLocal(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
  TriggerRecordPtr triggerPtr;
  c_triggerRecordPool.getPtr(triggerPtr, opPtr.p->m_request.getTriggerId());
  DropTrigReq* const req = (DropTrigReq*)signal->getDataPtrSend();
  req->setUserRef(reference());
  req->setConnectionPtr(opPtr.p->key);
  if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_TC) {
13529 13530
    jam();
    // broken trigger allowed if force
13531 13532
    if (! (triggerPtr.p->triggerLocal & TriggerRecord::TL_CREATED_TC)) {
      jam();
pekka@mysql.com's avatar
pekka@mysql.com committed
13533
      ndbassert(opPtr.p->m_requestFlag & RequestFlag::RF_FORCE);
13534 13535 13536 13537 13538
      alterTrigger_sendReply(signal, opPtr, false);
      return;
    }
    req->setRequestType(DropTrigReq::RT_TC);
  } else if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_LQH) {
13539 13540
    jam();
    // broken trigger allowed if force
13541 13542
    if (! (triggerPtr.p->triggerLocal & TriggerRecord::TL_CREATED_LQH)) {
      jam();
pekka@mysql.com's avatar
pekka@mysql.com committed
13543
      ndbassert(opPtr.p->m_requestFlag & RequestFlag::RF_FORCE);
13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560
      alterTrigger_sendReply(signal, opPtr, false);
      return;
    }
    req->setRequestType(DropTrigReq::RT_LQH);
  } else {
    ndbassert(false);
  }
  req->setTableId(triggerPtr.p->tableId);
  req->setIndexId(triggerPtr.p->indexId);
  req->setTriggerId(triggerPtr.i);
  req->setTriggerType(triggerPtr.p->triggerType);
  req->setTriggerActionTime(triggerPtr.p->triggerActionTime);
  req->setTriggerEvent(triggerPtr.p->triggerEvent);
  req->setMonitorReplicas(triggerPtr.p->monitorReplicas);
  req->setMonitorAllAttributes(triggerPtr.p->monitorAllAttributes);
  BlockReference blockRef = 0;
  if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_TC) {
13561
    jam();
13562 13563
    blockRef = calcTcBlockRef(getOwnNodeId());
  } else if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_LQH) {
13564
    jam();
13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576
    blockRef = calcLqhBlockRef(getOwnNodeId());
  } else {
    ndbassert(false);
  }
  sendSignal(blockRef, GSN_DROP_TRIG_REQ,
      signal, DropTrigReq::SignalLength, JBB);
}

void
Dbdict::alterTrigger_fromDropLocal(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
13577
  if (! opPtr.p->hasLastError()) {
13578 13579 13580 13581
    // mark dropped locally
    TriggerRecordPtr triggerPtr;
    c_triggerRecordPool.getPtr(triggerPtr, opPtr.p->m_request.getTriggerId());
    if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_TC) {
13582
      jam();
13583 13584
      triggerPtr.p->triggerLocal &= ~TriggerRecord::TL_CREATED_TC;
    } else if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_LQH) {
13585
      jam();
13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641
      triggerPtr.p->triggerLocal &= ~TriggerRecord::TL_CREATED_LQH;
    } else {
      ndbrequire(false);
    }
  }
  // forward CONF or REF to master
  alterTrigger_sendReply(signal, opPtr, false);
}

void
Dbdict::alterTrigger_slaveCommit(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
  TriggerRecordPtr triggerPtr;
  c_triggerRecordPool.getPtr(triggerPtr, opPtr.p->m_request.getTriggerId());
  // set state
  triggerPtr.p->triggerState = TriggerRecord::TS_ONLINE;
}

void
Dbdict::alterTrigger_slaveAbort(Signal* signal, OpAlterTriggerPtr opPtr)
{
  jam();
}

void
Dbdict::alterTrigger_sendSlaveReq(Signal* signal, OpAlterTriggerPtr opPtr)
{
  AlterTrigReq* const req = (AlterTrigReq*)signal->getDataPtrSend();
  *req = opPtr.p->m_request;
  req->setUserRef(opPtr.p->m_coordinatorRef);
  req->setConnectionPtr(opPtr.p->key);
  req->setRequestType(opPtr.p->m_requestType);
  req->addRequestFlag(opPtr.p->m_requestFlag);
  NdbNodeBitmask receiverNodes = c_aliveNodes;
  if (opPtr.p->m_requestFlag & RequestFlag::RF_LOCAL) {
    receiverNodes.clear();
    receiverNodes.set(getOwnNodeId());
  } else {
    opPtr.p->m_nodes.bitAND(receiverNodes);
    receiverNodes = opPtr.p->m_nodes;
  }
  opPtr.p->m_signalCounter = receiverNodes;
  NodeReceiverGroup rg(DBDICT, receiverNodes);
  sendSignal(rg, GSN_ALTER_TRIG_REQ,
      signal, AlterTrigReq::SignalLength, JBB);
}

void
Dbdict::alterTrigger_sendReply(Signal* signal, OpAlterTriggerPtr opPtr,
    bool toUser)
{
  jam();
  AlterTrigRef* rep = (AlterTrigRef*)signal->getDataPtrSend();
  Uint32 gsn = GSN_ALTER_TRIG_CONF;
  Uint32 length = AlterTrigConf::InternalLength;
13642
  bool sendRef;
13643
  if (! toUser) {
13644
    sendRef = opPtr.p->hasLastError();
13645 13646 13647 13648 13649 13650 13651 13652 13653 13654
    rep->setUserRef(opPtr.p->m_coordinatorRef);
    rep->setConnectionPtr(opPtr.p->key);
    rep->setRequestType(opPtr.p->m_requestType);
    if (opPtr.p->m_requestType == AlterTrigReq::RT_DICT_ABORT) {
      jam();
      sendRef = false;
    } else {
      jam();
    }
  } else {
13655
    sendRef = opPtr.p->hasError();
13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683
    jam();
    rep->setUserRef(opPtr.p->m_request.getUserRef());
    rep->setConnectionPtr(opPtr.p->m_request.getConnectionPtr());
    rep->setRequestType(opPtr.p->m_request.getRequestType());
    length = AlterTrigConf::SignalLength;
  }
  rep->setTableId(opPtr.p->m_request.getTableId());
  rep->setTriggerId(opPtr.p->m_request.getTriggerId());
  if (sendRef) {
    if (opPtr.p->m_errorNode == 0) {
      jam();
      opPtr.p->m_errorNode = getOwnNodeId();
    } else {
      jam();
    }
    rep->setErrorCode(opPtr.p->m_errorCode);
    rep->setErrorLine(opPtr.p->m_errorLine);
    rep->setErrorNode(opPtr.p->m_errorNode);
    gsn = GSN_ALTER_TRIG_REF;
    length = AlterTrigRef::SignalLength;
  }
  sendSignal(rep->getUserRef(), gsn, signal, length, JBB);
}

/**
 * MODULE: Support routines for index and trigger.
 */

13684 13685 13686 13687 13688 13689 13690
/*
  This routine is used to set-up the primary key attributes of the unique
  hash index. Since we store fragment id as part of the primary key here
  we insert the pseudo column for getting fragment id first in the array.
  This routine is used as part of the building of the index.
*/

13691
void
13692 13693
Dbdict::getTableKeyList(TableRecordPtr tablePtr, 
			Id_array<MAX_ATTRIBUTES_IN_INDEX+1>& list)
13694 13695 13696
{
  jam();
  list.sz = 0;
13697
  list.id[list.sz++] = AttributeHeader::FRAGMENT;
13698 13699 13700 13701 13702 13703 13704
  LocalDLFifoList<AttributeRecord> alist(c_attributeRecordPool,
                                         tablePtr.p->m_attributes);
  AttributeRecordPtr attrPtr;
  for (alist.first(attrPtr); !attrPtr.isNull(); alist.next(attrPtr)) {
    if (attrPtr.p->tupleKey) {
      list.id[list.sz++] = attrPtr.p->attributeId;
    }
13705
  }
13706
  ndbrequire(list.sz == (uint)(tablePtr.p->noOfPrimkey + 1));
13707
  ndbrequire(list.sz <= MAX_ATTRIBUTES_IN_INDEX + 1);
13708 13709 13710 13711 13712 13713 13714
}

// XXX should store the primary attribute id
void
Dbdict::getIndexAttr(TableRecordPtr indexPtr, Uint32 itAttr, Uint32* id)
{
  jam();
13715 13716 13717

  Uint32 len;
  char name[MAX_ATTR_NAME_SIZE];
13718
  TableRecordPtr tablePtr;
13719 13720
  AttributeRecordPtr attrPtr;

13721 13722
  c_tableRecordPool.getPtr(tablePtr, indexPtr.p->primaryTableId);
  AttributeRecord* iaRec = c_attributeRecordPool.getPtr(itAttr);
13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733
  {
    ConstRope tmp(c_rope_pool, iaRec->attributeName);
    tmp.copy(name);
    len = tmp.size();
  }
  LocalDLFifoList<AttributeRecord> alist(c_attributeRecordPool, 
					 tablePtr.p->m_attributes);
  for (alist.first(attrPtr); !attrPtr.isNull(); alist.next(attrPtr)){
    ConstRope tmp(c_rope_pool, attrPtr.p->attributeName);
    if(tmp.compare(name, len) == 0){
      id[0] = attrPtr.p->attributeId;
13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746
      return;
    }
  }
  ndbrequire(false);
}

void
Dbdict::getIndexAttrList(TableRecordPtr indexPtr, AttributeList& list)
{
  jam();
  list.sz = 0;
  memset(list.id, 0, sizeof(list.id));
  ndbrequire(indexPtr.p->noOfAttributes >= 2);
13747 13748 13749 13750 13751 13752 13753 13754 13755 13756

  LocalDLFifoList<AttributeRecord> alist(c_attributeRecordPool,
                                         indexPtr.p->m_attributes);
  AttributeRecordPtr attrPtr;
  for (alist.first(attrPtr); !attrPtr.isNull(); alist.next(attrPtr)) {
    // skip last
    AttributeRecordPtr tempPtr = attrPtr;
    if (! alist.next(tempPtr))
      break;
    getIndexAttr(indexPtr, attrPtr.i, &list.id[list.sz++]);
13757
  }
13758
  ndbrequire(indexPtr.p->noOfAttributes == list.sz + 1);
13759 13760 13761 13762 13763 13764 13765 13766
}

void
Dbdict::getIndexAttrMask(TableRecordPtr indexPtr, AttributeMask& mask)
{
  jam();
  mask.clear();
  ndbrequire(indexPtr.p->noOfAttributes >= 2);
13767 13768 13769 13770 13771 13772 13773
  
  AttributeRecordPtr attrPtr, currPtr;
  LocalDLFifoList<AttributeRecord> alist(c_attributeRecordPool, 
					 indexPtr.p->m_attributes);
  
  
  for (alist.first(attrPtr); currPtr = attrPtr, alist.next(attrPtr); ){
13774
    Uint32 id;
13775
    getIndexAttr(indexPtr, currPtr.i, &id);
13776 13777 13778 13779
    mask.set(id);
  }
}

13780 13781 13782 13783 13784
// DICT lock master

const Dbdict::DictLockType*
Dbdict::getDictLockType(Uint32 lockType)
{
13785
  static const DictLockType lt[] = {
13786 13787
    { DictLockReq::NodeRestartLock, BS_NODE_RESTART, "NodeRestart" }
  };
13788 13789
  for (unsigned int i = 0; i < sizeof(lt)/sizeof(lt[0]); i++) {
    if ((Uint32) lt[i].lockType == lockType)
13790 13791 13792 13793 13794
      return &lt[i];
  }
  return NULL;
}

13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822
void
Dbdict::sendDictLockInfoEvent(Uint32 pollCount)
{
  DictLockPtr loopPtr;
  c_dictLockQueue.first(loopPtr);
  unsigned count = 0;

  char queue_buf[100];
  char *p = &queue_buf[0];
  const char *const q = &queue_buf[sizeof(queue_buf)];
  *p = 0;

  while (loopPtr.i != RNIL) {
    jam();
    my_snprintf(p, q-p, "%s%u%s",
                ++count == 1 ? "" : " ",
                (unsigned)refToNode(loopPtr.p->req.userRef),
                loopPtr.p->locked ? "L" : "");
    p += strlen(p);
    c_dictLockQueue.next(loopPtr);
  }

  infoEvent("DICT: lock bs: %d ops: %d poll: %d cnt: %d queue: %s",
      (int)c_blockState,
      c_opRecordPool.getSize() - c_opRecordPool.getNoOfFree(),
      c_dictLockPoll, (int)pollCount, queue_buf);
}

13823 13824 13825 13826 13827
void
Dbdict::sendDictLockInfoEvent(DictLockPtr lockPtr, const char* text)
{
  infoEvent("DICT: %s %u for %s",
      text,
13828
      (unsigned)refToNode(lockPtr.p->req.userRef), lockPtr.p->lt->text);
13829 13830 13831 13832 13833 13834 13835 13836
}

void
Dbdict::execDICT_LOCK_REQ(Signal* signal)
{
  jamEntry();
  const DictLockReq* req = (const DictLockReq*)&signal->theData[0];

13837 13838
  // make sure bad request crashes slave, not master (us)

13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851
  if (getOwnNodeId() != c_masterNodeId) {
    jam();
    sendDictLockRef(signal, *req, DictLockRef::NotMaster);
    return;
  }

  const DictLockType* lt = getDictLockType(req->lockType);
  if (lt == NULL) {
    jam();
    sendDictLockRef(signal, *req, DictLockRef::InvalidLockType);
    return;
  }

13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864
  if (req->userRef != signal->getSendersBlockRef() ||
      getNodeInfo(refToNode(req->userRef)).m_type != NodeInfo::DB) {
    jam();
    sendDictLockRef(signal, *req, DictLockRef::BadUserRef);
    return;
  }

  if (c_aliveNodes.get(refToNode(req->userRef))) {
    jam();
    sendDictLockRef(signal, *req, DictLockRef::TooLate);
    return;
  }

13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875
  DictLockPtr lockPtr;
  if (! c_dictLockQueue.seize(lockPtr)) {
    jam();
    sendDictLockRef(signal, *req, DictLockRef::TooManyRequests);
    return;
  }

  lockPtr.p->req = *req;
  lockPtr.p->locked = false;
  lockPtr.p->lt = lt;

13876
  checkDictLockQueue(signal, false);
13877 13878 13879 13880 13881

  if (! lockPtr.p->locked)
    sendDictLockInfoEvent(lockPtr, "lock request by node");
}

13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892
// only table and index ops are checked
bool
Dbdict::hasDictLockSchemaOp()
{
  return
    ! c_opCreateTable.isEmpty() ||
    ! c_opDropTable.isEmpty() ||
    ! c_opCreateIndex.isEmpty() ||
    ! c_opDropIndex.isEmpty();
}

13893
void
13894
Dbdict::checkDictLockQueue(Signal* signal, bool poll)
13895
{
13896 13897
  Uint32 pollCount = ! poll ? 0 : signal->theData[1];

13898 13899 13900 13901 13902
  DictLockPtr lockPtr;

  do {
    if (! c_dictLockQueue.first(lockPtr)) {
      jam();
13903
      setDictLockPoll(signal, false, pollCount);
13904 13905 13906 13907 13908 13909 13910 13911 13912
      return;
    }

    if (lockPtr.p->locked) {
      jam();
      ndbrequire(c_blockState == lockPtr.p->lt->blockState);
      break;
    }

13913
    if (hasDictLockSchemaOp()) {
13914 13915 13916 13917
      jam();
      break;
    }

13918 13919 13920 13921 13922 13923 13924 13925 13926
    if (c_blockState != BS_IDLE)
    {
      /**
       * If state is BS_NODE_FAILURE, it might be that no op is running
       */
      jam();
      break;
    }

13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938
    ndbrequire(c_blockState == BS_IDLE);
    lockPtr.p->locked = true;
    c_blockState = lockPtr.p->lt->blockState;
    sendDictLockConf(signal, lockPtr);

    sendDictLockInfoEvent(lockPtr, "locked by node");
  } while (0);

  // poll while first request is open
  // this routine is called again when it is removed for any reason

  bool on = ! lockPtr.p->locked;
13939
  setDictLockPoll(signal, on, pollCount);
13940 13941 13942 13943 13944 13945 13946 13947 13948 13949
}

void
Dbdict::execDICT_UNLOCK_ORD(Signal* signal)
{
  jamEntry();
  const DictUnlockOrd* ord = (const DictUnlockOrd*)&signal->theData[0];

  DictLockPtr lockPtr;
  c_dictLockQueue.getPtr(lockPtr, ord->lockPtr);
13950
  ndbrequire((Uint32) lockPtr.p->lt->lockType == ord->lockType);
13951 13952 13953 13954

  if (lockPtr.p->locked) {
    jam();
    ndbrequire(c_blockState == lockPtr.p->lt->blockState);
13955
    ndbrequire(! hasDictLockSchemaOp());
13956 13957 13958 13959 13960 13961 13962 13963 13964 13965
    ndbrequire(! c_dictLockQueue.hasPrev(lockPtr));

    c_blockState = BS_IDLE;
    sendDictLockInfoEvent(lockPtr, "unlocked by node");
  } else {
    sendDictLockInfoEvent(lockPtr, "lock request removed by node");
  }

  c_dictLockQueue.release(lockPtr);

13966
  checkDictLockQueue(signal, false);
13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998
}

void
Dbdict::sendDictLockConf(Signal* signal, DictLockPtr lockPtr)
{
  DictLockConf* conf = (DictLockConf*)&signal->theData[0];
  const DictLockReq& req = lockPtr.p->req;

  conf->userPtr = req.userPtr;
  conf->lockType = req.lockType;
  conf->lockPtr = lockPtr.i;

  sendSignal(req.userRef, GSN_DICT_LOCK_CONF, signal,
      DictLockConf::SignalLength, JBB);
}

void
Dbdict::sendDictLockRef(Signal* signal, DictLockReq req, Uint32 errorCode)
{
  DictLockRef* ref = (DictLockRef*)&signal->theData[0];

  ref->userPtr = req.userPtr;
  ref->lockType = req.lockType;
  ref->errorCode = errorCode;

  sendSignal(req.userRef, GSN_DICT_LOCK_REF, signal,
      DictLockRef::SignalLength, JBB);
}

// control polling

void
13999
Dbdict::setDictLockPoll(Signal* signal, bool on, Uint32 pollCount)
14000 14001 14002 14003
{
  if (on) {
    jam();
    signal->theData[0] = ZDICT_LOCK_POLL;
14004 14005
    signal->theData[1] = pollCount + 1;
    sendSignalWithDelay(reference(), GSN_CONTINUEB, signal, 100, 2);
14006 14007
  }

14008 14009 14010
  bool change = (c_dictLockPoll != on);

  if (change) {
14011 14012 14013
    jam();
    c_dictLockPoll = on;
  }
14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024

  // avoid too many messages if master is stuck busy (BS_NODE_FAILURE)
  bool periodic =
    pollCount < 8 ||
    pollCount < 64 && pollCount % 8 == 0 ||
    pollCount < 512 && pollCount % 64 == 0 ||
    pollCount < 4096 && pollCount % 512 == 0 ||
    pollCount % 4096 == 0; // about every 6 minutes

  if (change || periodic)
    sendDictLockInfoEvent(pollCount);
14025 14026 14027 14028 14029 14030 14031 14032 14033 14034
}

// NF handling

void
Dbdict::removeStaleDictLocks(Signal* signal, const Uint32* theFailedNodes)
{
  DictLockPtr loopPtr;
  c_dictLockQueue.first(loopPtr);

14035 14036 14037 14038 14039
  if (getOwnNodeId() != c_masterNodeId) {
    ndbrequire(loopPtr.i == RNIL);
    return;
  }

14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050
  while (loopPtr.i != RNIL) {
    jam();
    DictLockPtr lockPtr = loopPtr;
    c_dictLockQueue.next(loopPtr);

    Uint32 nodeId = refToNode(lockPtr.p->req.userRef);

    if (NodeBitmask::get(theFailedNodes, nodeId)) {
      if (lockPtr.p->locked) {
        jam();
        ndbrequire(c_blockState == lockPtr.p->lt->blockState);
14051
        ndbrequire(! hasDictLockSchemaOp());
14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064
        ndbrequire(! c_dictLockQueue.hasPrev(lockPtr));

        c_blockState = BS_IDLE;

        sendDictLockInfoEvent(lockPtr, "remove lock by failed node");
      } else {
        sendDictLockInfoEvent(lockPtr, "remove lock request by failed node");
      }

      c_dictLockQueue.release(lockPtr);
    }
  }

14065
  checkDictLockQueue(signal, false);
14066 14067 14068
}


14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079
/* **************************************************************** */
/* ---------------------------------------------------------------- */
/* MODULE:          STORE/RESTORE SCHEMA FILE---------------------- */
/* ---------------------------------------------------------------- */
/*                                                                  */
/* General module used to store the schema file on disk and         */
/* similar function to restore it from disk.                        */
/* ---------------------------------------------------------------- */
/* **************************************************************** */

void
14080 14081 14082 14083 14084 14085 14086 14087
Dbdict::initSchemaFile(XSchemaFile * xsf, Uint32 firstPage, Uint32 lastPage,
                       bool initEntries)
{
  ndbrequire(lastPage <= xsf->noOfPages);
  for (Uint32 n = firstPage; n < lastPage; n++) {
    SchemaFile * sf = &xsf->schemaPage[n];
    if (initEntries)
      memset(sf, 0, NDB_SF_PAGE_SIZE);
14088

14089
    Uint32 ndb_version = NDB_VERSION;
14090 14091
    if (ndb_version < NDB_SF_VERSION_5_0_6)
      ndb_version = NDB_SF_VERSION_5_0_6;
14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102

    memcpy(sf->Magic, NDB_SF_MAGIC, sizeof(sf->Magic));
    sf->ByteOrder = 0x12345678;
    sf->NdbVersion =  ndb_version;
    sf->FileSize = xsf->noOfPages * NDB_SF_PAGE_SIZE;
    sf->PageNumber = n;
    sf->CheckSum = 0;
    sf->NoOfTableEntries = NDB_SF_PAGE_ENTRIES;

    computeChecksum(xsf, n);
  }
14103 14104 14105
}

void
14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134
Dbdict::resizeSchemaFile(XSchemaFile * xsf, Uint32 noOfPages)
{
  ndbrequire(noOfPages <= NDB_SF_MAX_PAGES);
  if (xsf->noOfPages < noOfPages) {
    jam();
    Uint32 firstPage = xsf->noOfPages;
    xsf->noOfPages = noOfPages;
    initSchemaFile(xsf, 0, firstPage, false);
    initSchemaFile(xsf, firstPage, xsf->noOfPages, true);
  }
  if (xsf->noOfPages > noOfPages) {
    jam();
    Uint32 tableId = noOfPages * NDB_SF_PAGE_ENTRIES;
    while (tableId < xsf->noOfPages * NDB_SF_PAGE_ENTRIES) {
      SchemaFile::TableEntry * te = getTableEntry(xsf, tableId);
      if (te->m_tableState != SchemaFile::INIT &&
          te->m_tableState != SchemaFile::DROP_TABLE_COMMITTED) {
        ndbrequire(false);
      }
      tableId++;
    }
    xsf->noOfPages = noOfPages;
    initSchemaFile(xsf, 0, xsf->noOfPages, false);
  }
}

void
Dbdict::computeChecksum(XSchemaFile * xsf, Uint32 pageNo){ 
  SchemaFile * sf = &xsf->schemaPage[pageNo];
14135
  sf->CheckSum = 0;
14136
  sf->CheckSum = computeChecksum((Uint32*)sf, NDB_SF_PAGE_SIZE_IN_WORDS);
14137 14138 14139
}

bool 
14140
Dbdict::validateChecksum(const XSchemaFile * xsf){
14141
  
14142 14143 14144 14145 14146 14147 14148
  for (Uint32 n = 0; n < xsf->noOfPages; n++) {
    SchemaFile * sf = &xsf->schemaPage[n];
    Uint32 c = computeChecksum((Uint32*)sf, NDB_SF_PAGE_SIZE_IN_WORDS);
    if ( c != 0)
      return false;
  }
  return true;
14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159
}

Uint32
Dbdict::computeChecksum(const Uint32 * src, Uint32 len){
  Uint32 ret = 0;
  for(Uint32 i = 0; i<len; i++)
    ret ^= src[i];
  return ret;
}

SchemaFile::TableEntry * 
14160 14161 14162 14163 14164 14165 14166 14167
Dbdict::getTableEntry(XSchemaFile * xsf, Uint32 tableId)
{
  Uint32 n = tableId / NDB_SF_PAGE_ENTRIES;
  Uint32 i = tableId % NDB_SF_PAGE_ENTRIES;
  ndbrequire(n < xsf->noOfPages);

  SchemaFile * sf = &xsf->schemaPage[n];
  return &sf->TableEntries[i];
14168 14169
}

14170 14171
//******************************************
void
14172 14173
Dbdict::execCREATE_FILE_REQ(Signal* signal)
{
14174 14175 14176 14177 14178
  jamEntry();
  
  if(!assembleFragments(signal)){
    jam();
    return;
14179
  }
14180 14181 14182 14183 14184 14185 14186 14187 14188
  
  CreateFileReq * req = (CreateFileReq*)signal->getDataPtr();
  CreateFileRef * ref = (CreateFileRef*)signal->getDataPtrSend();
  Uint32 senderRef = req->senderRef;
  Uint32 senderData = req->senderData;
  Uint32 type = req->objType;
  Uint32 requestInfo = req->requestInfo;
  
  do {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206
    if(getOwnNodeId() != c_masterNodeId){
      jam();
      ref->errorCode = CreateFileRef::NotMaster;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
    
    if (c_blockState != BS_IDLE){
      jam();
      ref->errorCode = CreateFileRef::Busy;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }

14207 14208 14209 14210 14211 14212 14213 14214 14215
    if (checkSingleUserMode(senderRef))
    {
      ref->errorCode = CreateFileRef::SingleUser;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }

14216 14217
    Ptr<SchemaTransaction> trans_ptr;
    if (! c_Trans.seize(trans_ptr)){
14218
      jam();
14219 14220 14221 14222 14223 14224
      ref->errorCode = CreateFileRef::Busy;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
14225
    jam(); 
14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249
    const Uint32 trans_key = ++c_opRecordSequence;
    trans_ptr.p->key = trans_key;
    trans_ptr.p->m_senderRef = senderRef;
    trans_ptr.p->m_senderData = senderData;
    trans_ptr.p->m_nodes = c_aliveNodes;
    trans_ptr.p->m_errorCode = 0;
//    trans_ptr.p->m_nodes.clear(); 
//    trans_ptr.p->m_nodes.set(getOwnNodeId());
    c_Trans.add(trans_ptr);
    
    const Uint32 op_key = ++c_opRecordSequence;
    trans_ptr.p->m_op.m_key = op_key;
    trans_ptr.p->m_op.m_vt_index = 1;
    trans_ptr.p->m_op.m_state = DictObjOp::Preparing;
    
    CreateObjReq* create_obj = (CreateObjReq*)signal->getDataPtrSend();
    create_obj->op_key = op_key;
    create_obj->senderRef = reference();
    create_obj->senderData = trans_key;
    create_obj->clientRef = senderRef;
    create_obj->clientData = senderData;
    
    create_obj->objType = type;
    create_obj->requestInfo = requestInfo;
14250

14251 14252 14253
    {
      Uint32 objId = getFreeObjId(0);
      if (objId == RNIL) {
14254
        jam();
14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276
        ref->errorCode = CreateFileRef::NoMoreObjectRecords;
        ref->status    = 0;
        ref->errorKey  = 0;
        ref->errorLine = __LINE__;
        break;
      }
      
      create_obj->objId = objId;
      trans_ptr.p->m_op.m_obj_id = objId;
      create_obj->gci = 0;
      
      XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
      SchemaFile::TableEntry *objEntry = getTableEntry(xsf, objId);      
      create_obj->objVersion = 
	create_obj_inc_schema_version(objEntry->m_tableVersion);
    }
    
    NodeReceiverGroup rg(DBDICT, trans_ptr.p->m_nodes);
    SafeCounter tmp(c_counterMgr, trans_ptr.p->m_counter);
    tmp.init<CreateObjRef>(rg, GSN_CREATE_OBJ_REF, trans_key);
    sendSignal(rg, GSN_CREATE_OBJ_REQ, signal, 
	       CreateObjReq::SignalLength, JBB);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14277 14278

    c_blockState = BS_CREATE_TAB;
14279 14280 14281 14282 14283 14284 14285
    return;
  } while(0);
  
  ref->senderData = senderData;
  ref->masterNodeId = c_masterNodeId;
  sendSignal(senderRef, GSN_CREATE_FILE_REF,signal,
	     CreateFileRef::SignalLength, JBB);
14286 14287
}

14288
void
14289 14290
Dbdict::execCREATE_FILEGROUP_REQ(Signal* signal)
{
14291 14292 14293 14294 14295
  jamEntry();
  
  if(!assembleFragments(signal)){
    jam();
    return;
14296
  }
14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321
  
  CreateFilegroupReq * req = (CreateFilegroupReq*)signal->getDataPtr();
  CreateFilegroupRef * ref = (CreateFilegroupRef*)signal->getDataPtrSend();
  Uint32 senderRef = req->senderRef;
  Uint32 senderData = req->senderData;
  Uint32 type = req->objType;
  
  do {
    if(getOwnNodeId() != c_masterNodeId){
      jam();
      ref->errorCode = CreateFilegroupRef::NotMaster;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
    
    if (c_blockState != BS_IDLE){
      jam();
      ref->errorCode = CreateFilegroupRef::Busy;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14322

14323 14324 14325 14326 14327 14328 14329 14330 14331
    if (checkSingleUserMode(senderRef))
    {
      ref->errorCode = CreateFilegroupRef::SingleUser;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }

jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14332 14333
    Ptr<SchemaTransaction> trans_ptr;
    if (! c_Trans.seize(trans_ptr)){
14334
      jam();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14335 14336 14337 14338 14339 14340
      ref->errorCode = CreateFilegroupRef::Busy;
      ref->status    = 0;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
14341
    jam(); 
14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366
    const Uint32 trans_key = ++c_opRecordSequence;
    trans_ptr.p->key = trans_key;
    trans_ptr.p->m_senderRef = senderRef;
    trans_ptr.p->m_senderData = senderData;
    trans_ptr.p->m_nodes = c_aliveNodes;
    trans_ptr.p->m_errorCode = 0;
    c_Trans.add(trans_ptr);
    
    const Uint32 op_key = ++c_opRecordSequence;
    trans_ptr.p->m_op.m_key = op_key;
    trans_ptr.p->m_op.m_vt_index = 0;
    trans_ptr.p->m_op.m_state = DictObjOp::Preparing;
    
    CreateObjReq* create_obj = (CreateObjReq*)signal->getDataPtrSend();
    create_obj->op_key = op_key;
    create_obj->senderRef = reference();
    create_obj->senderData = trans_key;
    create_obj->clientRef = senderRef;
    create_obj->clientData = senderData;
    
    create_obj->objType = type;
    
    {
      Uint32 objId = getFreeObjId(0);
      if (objId == RNIL) {
14367
        jam();
14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389
        ref->errorCode = CreateFilegroupRef::NoMoreObjectRecords;
        ref->status    = 0;
        ref->errorKey  = 0;
        ref->errorLine = __LINE__;
        break;
      }
      
      create_obj->objId = objId;
      trans_ptr.p->m_op.m_obj_id = objId;
      create_obj->gci = 0;
      
      XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
      SchemaFile::TableEntry *objEntry = getTableEntry(xsf, objId);      
      create_obj->objVersion = 
	create_obj_inc_schema_version(objEntry->m_tableVersion);
    }
    
    NodeReceiverGroup rg(DBDICT, trans_ptr.p->m_nodes);
    SafeCounter tmp(c_counterMgr, trans_ptr.p->m_counter);
    tmp.init<CreateObjRef>(rg, GSN_CREATE_OBJ_REF, trans_key);
    sendSignal(rg, GSN_CREATE_OBJ_REQ, signal, 
	       CreateObjReq::SignalLength, JBB);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14390 14391

    c_blockState = BS_CREATE_TAB;
14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418
    return;
  } while(0);
  
  ref->senderData = senderData;
  ref->masterNodeId = c_masterNodeId;
  sendSignal(senderRef, GSN_CREATE_FILEGROUP_REF,signal,
	     CreateFilegroupRef::SignalLength, JBB);
}

void
Dbdict::execDROP_FILE_REQ(Signal* signal)
{
  jamEntry();
  
  if(!assembleFragments(signal)){
    jam();
    return;
  }
  
  DropFileReq * req = (DropFileReq*)signal->getDataPtr();
  DropFileRef * ref = (DropFileRef*)signal->getDataPtrSend();
  Uint32 senderRef = req->senderRef;
  Uint32 senderData = req->senderData;
  Uint32 objId = req->file_id;
  Uint32 version = req->file_version;
  
  do {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14419 14420 14421 14422 14423 14424 14425 14426
    if(getOwnNodeId() != c_masterNodeId){
      jam();
      ref->errorCode = DropFileRef::NotMaster;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
    
14427 14428
    if (c_blockState != BS_IDLE)
    {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14429 14430 14431 14432 14433 14434 14435
      jam();
      ref->errorCode = DropFileRef::Busy;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }

14436 14437
    if (checkSingleUserMode(senderRef))
    {
14438
      jam();
14439 14440 14441 14442 14443 14444
      ref->errorCode = DropFileRef::SingleUser;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }

14445 14446 14447
    Ptr<File> file_ptr;
    if (!c_file_hash.find(file_ptr, objId))
    {
14448
      jam();
14449 14450 14451 14452 14453
      ref->errorCode = DropFileRef::NoSuchFile;
      ref->errorLine = __LINE__;
      break;
    }
    
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14454 14455
    if (file_ptr.p->m_version != version)
    {
14456
      jam();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14457 14458 14459 14460 14461
      ref->errorCode = DropFileRef::InvalidSchemaObjectVersion;
      ref->errorLine = __LINE__;
      break;
    }

14462 14463 14464
    Ptr<SchemaTransaction> trans_ptr;
    if (! c_Trans.seize(trans_ptr))
    {
14465
      jam();
14466
      ref->errorCode = DropFileRef::Busy;
14467 14468 14469
      ref->errorLine = __LINE__;
      break;
    }
14470
    jam();
14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503
    
    const Uint32 trans_key = ++c_opRecordSequence;
    trans_ptr.p->key = trans_key;
    trans_ptr.p->m_senderRef = senderRef;
    trans_ptr.p->m_senderData = senderData;
    trans_ptr.p->m_nodes = c_aliveNodes;
    trans_ptr.p->m_errorCode = 0;
    c_Trans.add(trans_ptr);
    
    const Uint32 op_key = ++c_opRecordSequence;
    trans_ptr.p->m_op.m_key = op_key;
    trans_ptr.p->m_op.m_vt_index = 2;
    trans_ptr.p->m_op.m_state = DictObjOp::Preparing;
    
    DropObjReq* drop_obj = (DropObjReq*)signal->getDataPtrSend();
    drop_obj->op_key = op_key;
    drop_obj->objVersion = version;
    drop_obj->objId = objId;
    drop_obj->objType = file_ptr.p->m_type;
    trans_ptr.p->m_op.m_obj_id = objId;

    drop_obj->senderRef = reference();
    drop_obj->senderData = trans_key;
    drop_obj->clientRef = senderRef;
    drop_obj->clientData = senderData;

    drop_obj->requestInfo = 0;
    
    NodeReceiverGroup rg(DBDICT, trans_ptr.p->m_nodes);
    SafeCounter tmp(c_counterMgr, trans_ptr.p->m_counter);
    tmp.init<CreateObjRef>(rg, GSN_DROP_OBJ_REF, trans_key);
    sendSignal(rg, GSN_DROP_OBJ_REQ, signal, 
	       DropObjReq::SignalLength, JBB);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14504 14505

    c_blockState = BS_CREATE_TAB;
14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532
    return;
  } while(0);
  
  ref->senderData = senderData;
  ref->masterNodeId = c_masterNodeId;
  sendSignal(senderRef, GSN_DROP_FILE_REF,signal,
	     DropFileRef::SignalLength, JBB);
}

void
Dbdict::execDROP_FILEGROUP_REQ(Signal* signal)
{
  jamEntry();
  
  if(!assembleFragments(signal)){
    jam();
    return;
  }
  
  DropFilegroupReq * req = (DropFilegroupReq*)signal->getDataPtr();
  DropFilegroupRef * ref = (DropFilegroupRef*)signal->getDataPtrSend();
  Uint32 senderRef = req->senderRef;
  Uint32 senderData = req->senderData;
  Uint32 objId = req->filegroup_id;
  Uint32 version = req->filegroup_version;
  
  do {
14533 14534
    if(getOwnNodeId() != c_masterNodeId)
    {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14535 14536 14537 14538 14539 14540 14541
      jam();
      ref->errorCode = DropFilegroupRef::NotMaster;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
    
14542 14543
    if (c_blockState != BS_IDLE)
    {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14544 14545 14546 14547 14548 14549 14550
      jam();
      ref->errorCode = DropFilegroupRef::Busy;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }
    
14551 14552
    if (checkSingleUserMode(senderRef))
    {
14553
      jam();
14554 14555 14556 14557 14558 14559
      ref->errorCode = DropFilegroupRef::SingleUser;
      ref->errorKey  = 0;
      ref->errorLine = __LINE__;
      break;
    }

14560 14561 14562
    Ptr<Filegroup> filegroup_ptr;
    if (!c_filegroup_hash.find(filegroup_ptr, objId))
    {
14563
      jam();
14564 14565 14566 14567
      ref->errorCode = DropFilegroupRef::NoSuchFilegroup;
      ref->errorLine = __LINE__;
      break;
    }
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14568 14569 14570

    if (filegroup_ptr.p->m_version != version)
    {
14571
      jam();
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14572 14573 14574 14575
      ref->errorCode = DropFilegroupRef::InvalidSchemaObjectVersion;
      ref->errorLine = __LINE__;
      break;
    }
14576 14577 14578 14579
    
    Ptr<SchemaTransaction> trans_ptr;
    if (! c_Trans.seize(trans_ptr))
    {
14580
      jam();
14581
      ref->errorCode = DropFilegroupRef::Busy;
14582 14583 14584
      ref->errorLine = __LINE__;
      break;
    }
14585
    jam();
14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618
    
    const Uint32 trans_key = ++c_opRecordSequence;
    trans_ptr.p->key = trans_key;
    trans_ptr.p->m_senderRef = senderRef;
    trans_ptr.p->m_senderData = senderData;
    trans_ptr.p->m_nodes = c_aliveNodes;
    trans_ptr.p->m_errorCode = 0;
    c_Trans.add(trans_ptr);
    
    const Uint32 op_key = ++c_opRecordSequence;
    trans_ptr.p->m_op.m_key = op_key;
    trans_ptr.p->m_op.m_vt_index = 3;
    trans_ptr.p->m_op.m_state = DictObjOp::Preparing;
    
    DropObjReq* drop_obj = (DropObjReq*)signal->getDataPtrSend();
    drop_obj->op_key = op_key;
    drop_obj->objVersion = version;
    drop_obj->objId = objId;
    drop_obj->objType = filegroup_ptr.p->m_type;
    trans_ptr.p->m_op.m_obj_id = objId;
    
    drop_obj->senderRef = reference();
    drop_obj->senderData = trans_key;
    drop_obj->clientRef = senderRef;
    drop_obj->clientData = senderData;
    
    drop_obj->requestInfo = 0;
    
    NodeReceiverGroup rg(DBDICT, trans_ptr.p->m_nodes);
    SafeCounter tmp(c_counterMgr, trans_ptr.p->m_counter);
    tmp.init<CreateObjRef>(rg, GSN_DROP_OBJ_REF, trans_key);
    sendSignal(rg, GSN_DROP_OBJ_REQ, signal, 
	       DropObjReq::SignalLength, JBB);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14619 14620

    c_blockState = BS_CREATE_TAB;
14621 14622 14623 14624 14625 14626 14627 14628 14629 14630
    return;
  } while(0);
  
  ref->senderData = senderData;
  ref->masterNodeId = c_masterNodeId;
  sendSignal(senderRef, GSN_DROP_FILEGROUP_REF,signal,
	     DropFilegroupRef::SignalLength, JBB);
}

void
14631 14632
Dbdict::execCREATE_OBJ_REF(Signal* signal)
{
14633 14634
  CreateObjRef * const ref = (CreateObjRef*)signal->getDataPtr();
  Ptr<SchemaTransaction> trans_ptr;
14635 14636

  jamEntry();
14637 14638
  ndbrequire(c_Trans.find(trans_ptr, ref->senderData));
  if(ref->errorCode != CreateObjRef::NF_FakeErrorREF){
14639
    jam();
14640 14641 14642 14643 14644 14645 14646
    trans_ptr.p->setErrorCode(ref->errorCode);
  }
  Uint32 node = refToNode(ref->senderRef);
  schemaOp_reply(signal, trans_ptr.p, node);
}

void
14647 14648
Dbdict::execCREATE_OBJ_CONF(Signal* signal)
{
14649
  Ptr<SchemaTransaction> trans_ptr;
14650 14651 14652
  CreateObjConf * const conf = (CreateObjConf*)signal->getDataPtr();

  jamEntry();
14653 14654 14655 14656 14657 14658 14659 14660 14661
  ndbrequire(c_Trans.find(trans_ptr, conf->senderData));
  schemaOp_reply(signal, trans_ptr.p, refToNode(conf->senderRef));
}

void
Dbdict::schemaOp_reply(Signal* signal, 
		       SchemaTransaction * trans_ptr_p, 
		       Uint32 nodeId)
{
14662
  jam();
14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683
  {
    SafeCounter tmp(c_counterMgr, trans_ptr_p->m_counter);
    if(!tmp.clearWaitingFor(nodeId)){
      jam();
      return;
    }
  }
  
  switch(trans_ptr_p->m_op.m_state){
  case DictObjOp::Preparing:{
    if(trans_ptr_p->m_errorCode != 0)
    {
      /**
       * Failed to prepare on atleast one node -> abort on all
       */
      trans_ptr_p->m_op.m_state = DictObjOp::Aborting;
      trans_ptr_p->m_callback.m_callbackData = trans_ptr_p->key;
      trans_ptr_p->m_callback.m_callbackFunction= 
	safe_cast(&Dbdict::trans_abort_start_done);
      
      if(f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_abort_start)
14684 14685
      {
        jam();
14686 14687
	(this->*f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_abort_start)
	  (signal, trans_ptr_p);
14688
      }
14689
      else
14690 14691
      {
        jam();
14692
	execute(signal, trans_ptr_p->m_callback, 0);
14693
      }
14694 14695 14696 14697 14698 14699 14700 14701 14702
      return;
    }
    
    trans_ptr_p->m_op.m_state = DictObjOp::Prepared;
    trans_ptr_p->m_callback.m_callbackData = trans_ptr_p->key;
    trans_ptr_p->m_callback.m_callbackFunction= 
      safe_cast(&Dbdict::trans_commit_start_done);
    
    if(f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_commit_start)
14703 14704
    {
      jam();
14705 14706
      (this->*f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_commit_start)
	(signal, trans_ptr_p);
14707
    }
14708
    else
14709 14710
    {
      jam();
14711
      execute(signal, trans_ptr_p->m_callback, 0);
14712
    }
14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723
    return;
  }
  case DictObjOp::Committing: {
    ndbrequire(trans_ptr_p->m_errorCode == 0);

    trans_ptr_p->m_op.m_state = DictObjOp::Committed;
    trans_ptr_p->m_callback.m_callbackData = trans_ptr_p->key;
    trans_ptr_p->m_callback.m_callbackFunction= 
      safe_cast(&Dbdict::trans_commit_complete_done);
    
    if(f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_commit_complete)
14724 14725
    {
      jam();
14726 14727
      (this->*f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_commit_complete)
	(signal, trans_ptr_p);
14728
    }
14729
    else
14730 14731 14732 14733
    {
      jam();
      execute(signal, trans_ptr_p->m_callback, 0);
    }
14734 14735 14736 14737 14738 14739 14740 14741 14742
    return;
  }
  case DictObjOp::Aborting:{
    trans_ptr_p->m_op.m_state = DictObjOp::Committed;
    trans_ptr_p->m_callback.m_callbackData = trans_ptr_p->key;
    trans_ptr_p->m_callback.m_callbackFunction= 
      safe_cast(&Dbdict::trans_abort_complete_done);

    if(f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_abort_complete)
14743 14744
    {
      jam();
14745 14746
      (this->*f_dict_op[trans_ptr_p->m_op.m_vt_index].m_trans_abort_complete)
	(signal, trans_ptr_p);
14747
    }
14748
    else
14749 14750 14751 14752
    {
      jam();
      execute(signal, trans_ptr_p->m_callback, 0);
    }
14753 14754 14755 14756 14757 14758
    return;
  }
  case DictObjOp::Defined:
  case DictObjOp::Prepared:
  case DictObjOp::Committed:
  case DictObjOp::Aborted:
14759
    jam();
14760 14761 14762 14763 14764 14765 14766 14767
    break;
  }
  ndbrequire(false);
}

void
Dbdict::trans_commit_start_done(Signal* signal, 
				Uint32 callbackData,
14768 14769
				Uint32 retValue)
{
14770
  Ptr<SchemaTransaction> trans_ptr;
14771 14772 14773

  jam();
  ndbrequire(retValue == 0);
14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790
  ndbrequire(c_Trans.find(trans_ptr, callbackData));
  NodeReceiverGroup rg(DBDICT, trans_ptr.p->m_nodes);
  SafeCounter tmp(c_counterMgr, trans_ptr.p->m_counter);
  tmp.init<DictCommitRef>(rg, GSN_DICT_COMMIT_REF, trans_ptr.p->key);
  
  DictCommitReq * const req = (DictCommitReq*)signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = trans_ptr.p->key;
  req->op_key = trans_ptr.p->m_op.m_key;
  sendSignal(rg, GSN_DICT_COMMIT_REQ, signal, DictCommitReq::SignalLength, 
	     JBB);
  trans_ptr.p->m_op.m_state = DictObjOp::Committing;
}

void
Dbdict::trans_commit_complete_done(Signal* signal, 
				   Uint32 callbackData,
14791 14792
				   Uint32 retValue)
{
14793
  Ptr<SchemaTransaction> trans_ptr;
14794 14795 14796

  jam();
  ndbrequire(retValue == 0);
14797 14798 14799 14800 14801
  ndbrequire(c_Trans.find(trans_ptr, callbackData));

  switch(f_dict_op[trans_ptr.p->m_op.m_vt_index].m_gsn_user_req){
  case GSN_CREATE_FILEGROUP_REQ:{
    FilegroupPtr fg_ptr;
14802
    jam();
14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817
    ndbrequire(c_filegroup_hash.find(fg_ptr, trans_ptr.p->m_op.m_obj_id));
    
    CreateFilegroupConf * conf = (CreateFilegroupConf*)signal->getDataPtr();
    conf->senderRef = reference();
    conf->senderData = trans_ptr.p->m_senderData;
    conf->filegroupId = fg_ptr.p->key;
    conf->filegroupVersion = fg_ptr.p->m_version;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_CREATE_FILEGROUP_CONF, signal, 
	       CreateFilegroupConf::SignalLength, JBB);
    break;
  }
  case GSN_CREATE_FILE_REQ:{
    FilePtr f_ptr;
14818
    jam();
14819 14820 14821 14822 14823
    ndbrequire(c_file_hash.find(f_ptr, trans_ptr.p->m_op.m_obj_id));
    CreateFileConf * conf = (CreateFileConf*)signal->getDataPtr();
    conf->senderRef = reference();
    conf->senderData = trans_ptr.p->m_senderData;
    conf->fileId = f_ptr.p->key;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
14824 14825
    conf->fileVersion = f_ptr.p->m_version;

14826 14827 14828 14829 14830 14831 14832
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_CREATE_FILE_CONF, signal, 
	       CreateFileConf::SignalLength, JBB);
    break;
  }
  case GSN_DROP_FILE_REQ:{
    DropFileConf * conf = (DropFileConf*)signal->getDataPtr();
14833
    jam();
14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844
    conf->senderRef = reference();
    conf->senderData = trans_ptr.p->m_senderData;
    conf->fileId = trans_ptr.p->m_op.m_obj_id;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_DROP_FILE_CONF, signal, 
	       DropFileConf::SignalLength, JBB);
    break;
  }
  case GSN_DROP_FILEGROUP_REQ:{
    DropFilegroupConf * conf = (DropFilegroupConf*)signal->getDataPtr();
14845
    jam();
14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859
    conf->senderRef = reference();
    conf->senderData = trans_ptr.p->m_senderData;
    conf->filegroupId = trans_ptr.p->m_op.m_obj_id;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_DROP_FILEGROUP_CONF, signal, 
	       DropFilegroupConf::SignalLength, JBB);
    break;
  }
  default:
    ndbrequire(false);
  }
  
  c_Trans.release(trans_ptr);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14860
  ndbrequire(c_blockState == BS_CREATE_TAB);
14861 14862 14863 14864 14865 14866 14867
  c_blockState = BS_IDLE;
  return;
}

void
Dbdict::trans_abort_start_done(Signal* signal, 
			       Uint32 callbackData,
14868 14869
			       Uint32 retValue)
{
14870
  Ptr<SchemaTransaction> trans_ptr;
14871 14872 14873

  jam();
  ndbrequire(retValue == 0);
14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890
  ndbrequire(c_Trans.find(trans_ptr, callbackData));
  
  NodeReceiverGroup rg(DBDICT, trans_ptr.p->m_nodes);
  SafeCounter tmp(c_counterMgr, trans_ptr.p->m_counter);
  ndbrequire(tmp.init<DictAbortRef>(rg, trans_ptr.p->key));
  
  DictAbortReq * const req = (DictAbortReq*)signal->getDataPtrSend();
  req->senderRef = reference();
  req->senderData = trans_ptr.p->key;
  req->op_key = trans_ptr.p->m_op.m_key;
  
  sendSignal(rg, GSN_DICT_ABORT_REQ, signal, DictAbortReq::SignalLength, JBB);
}

void
Dbdict::trans_abort_complete_done(Signal* signal, 
				  Uint32 callbackData,
14891 14892
				  Uint32 retValue)
{
14893
  Ptr<SchemaTransaction> trans_ptr;
14894 14895 14896

  jam();
  ndbrequire(retValue == 0);
14897 14898 14899 14900 14901 14902 14903
  ndbrequire(c_Trans.find(trans_ptr, callbackData));

  switch(f_dict_op[trans_ptr.p->m_op.m_vt_index].m_gsn_user_req){
  case GSN_CREATE_FILEGROUP_REQ:
  {
    //
    CreateFilegroupRef * ref = (CreateFilegroupRef*)signal->getDataPtr();
14904
    jam();
14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920
    ref->senderRef = reference();
    ref->senderData = trans_ptr.p->m_senderData;
    ref->masterNodeId = c_masterNodeId;
    ref->errorCode = trans_ptr.p->m_errorCode;
    ref->errorLine = 0;
    ref->errorKey = 0;
    ref->status = 0;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_CREATE_FILEGROUP_REF, signal, 
	       CreateFilegroupRef::SignalLength, JBB);
    break;
  }
  case GSN_CREATE_FILE_REQ:
  {
    CreateFileRef * ref = (CreateFileRef*)signal->getDataPtr();
14921
    jam();
14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937
    ref->senderRef = reference();
    ref->senderData = trans_ptr.p->m_senderData;
    ref->masterNodeId = c_masterNodeId;
    ref->errorCode = trans_ptr.p->m_errorCode;
    ref->errorLine = 0;
    ref->errorKey = 0;
    ref->status = 0;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_CREATE_FILE_REF, signal, 
	       CreateFileRef::SignalLength, JBB);
    break;
  }
  case GSN_DROP_FILE_REQ:
  {
    DropFileRef * ref = (DropFileRef*)signal->getDataPtr();
14938
    jam();
14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954
    ref->senderRef = reference();
    ref->senderData = trans_ptr.p->m_senderData;
    ref->masterNodeId = c_masterNodeId;
    ref->errorCode = trans_ptr.p->m_errorCode;
    ref->errorLine = 0;
    ref->errorKey = 0;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_DROP_FILE_REF, signal, 
	       DropFileRef::SignalLength, JBB);
    break;
  }
  case GSN_DROP_FILEGROUP_REQ:
  {
    //
    DropFilegroupRef * ref = (DropFilegroupRef*)signal->getDataPtr();
14955
    jam();
14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972
    ref->senderRef = reference();
    ref->senderData = trans_ptr.p->m_senderData;
    ref->masterNodeId = c_masterNodeId;
    ref->errorCode = trans_ptr.p->m_errorCode;
    ref->errorLine = 0;
    ref->errorKey = 0;
    
    //@todo check api failed
    sendSignal(trans_ptr.p->m_senderRef, GSN_DROP_FILEGROUP_REF, signal, 
	       DropFilegroupRef::SignalLength, JBB);
    break;
  }
  default:
    ndbrequire(false);
  }
  
  c_Trans.release(trans_ptr);
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
14973
  ndbrequire(c_blockState == BS_CREATE_TAB);
14974 14975 14976 14977 14978
  c_blockState = BS_IDLE;
  return;
}

void
14979 14980
Dbdict::execCREATE_OBJ_REQ(Signal* signal)
{
14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014
  jamEntry();

  if(!assembleFragments(signal)){
    jam();
    return;
  }

  CreateObjReq * const req = (CreateObjReq*)signal->getDataPtr();
  const Uint32 gci = req->gci;
  const Uint32 objId = req->objId;
  const Uint32 objVersion = req->objVersion;
  const Uint32 objType = req->objType;
  const Uint32 requestInfo = req->requestInfo;

  SegmentedSectionPtr objInfoPtr;
  signal->getSection(objInfoPtr, CreateObjReq::DICT_OBJ_INFO);
  
  CreateObjRecordPtr createObjPtr;  
  ndbrequire(c_opCreateObj.seize(createObjPtr));
  
  const Uint32 key = req->op_key;
  createObjPtr.p->key = key;
  c_opCreateObj.add(createObjPtr);
  createObjPtr.p->m_errorCode = 0;
  createObjPtr.p->m_senderRef = req->senderRef;
  createObjPtr.p->m_senderData = req->senderData;
  createObjPtr.p->m_clientRef = req->clientRef;
  createObjPtr.p->m_clientData = req->clientData;
  
  createObjPtr.p->m_gci = gci;
  createObjPtr.p->m_obj_id = objId;
  createObjPtr.p->m_obj_type = objType;
  createObjPtr.p->m_obj_version = objVersion;
  createObjPtr.p->m_obj_info_ptr_i = objInfoPtr.i;
15015
  createObjPtr.p->m_obj_ptr_i = RNIL;
15016 15017 15018 15019 15020 15021 15022 15023 15024

  createObjPtr.p->m_callback.m_callbackData = key;
  createObjPtr.p->m_callback.m_callbackFunction= 
    safe_cast(&Dbdict::createObj_prepare_start_done);

  createObjPtr.p->m_restart= 0;
  switch(objType){
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:
15025
    jam();
15026 15027 15028 15029 15030 15031 15032 15033
    createObjPtr.p->m_vt_index = 0;
    break;
  case DictTabInfo::Datafile:
  case DictTabInfo::Undofile:
    /**
     * Use restart code to impl. ForceCreateFile
     */
    if (requestInfo & CreateFileReq::ForceCreateFile)
15034 15035 15036 15037 15038
    {
      jam();
      createObjPtr.p->m_restart= 2;
    }
    jam();
15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055
    createObjPtr.p->m_vt_index = 1;
    break;
  default:
    ndbrequire(false);
  }
  
  signal->header.m_noOfSections = 0;
  (this->*f_dict_op[createObjPtr.p->m_vt_index].m_prepare_start)
    (signal, createObjPtr.p);
}

void
Dbdict::execDICT_COMMIT_REQ(Signal* signal)
{
  DictCommitReq* req = (DictCommitReq*)signal->getDataPtr();
  Ptr<SchemaOp> op;

15056 15057
  jamEntry();
  ndbrequire(c_schemaOp.find(op, req->op_key));
15058 15059 15060 15061 15062 15063 15064 15065 15066
  (this->*f_dict_op[op.p->m_vt_index].m_commit)(signal, op.p);
}

void
Dbdict::execDICT_ABORT_REQ(Signal* signal)
{
  DictAbortReq* req = (DictAbortReq*)signal->getDataPtr();
  Ptr<SchemaOp> op;

15067 15068
  jamEntry();
  ndbrequire(c_schemaOp.find(op, req->op_key));
15069 15070 15071 15072
  (this->*f_dict_op[op.p->m_vt_index].m_abort)(signal, op.p);
}

void
15073 15074
Dbdict::execDICT_COMMIT_REF(Signal* signal)
{
15075 15076
  DictCommitRef * const ref = (DictCommitRef*)signal->getDataPtr();
  Ptr<SchemaTransaction> trans_ptr;
15077 15078

  jamEntry();
15079 15080
  ndbrequire(c_Trans.find(trans_ptr, ref->senderData));
  if(ref->errorCode != DictCommitRef::NF_FakeErrorREF){
15081
    jam();
15082 15083 15084 15085 15086 15087 15088
    trans_ptr.p->setErrorCode(ref->errorCode);
  }
  Uint32 node = refToNode(ref->senderRef);
  schemaOp_reply(signal, trans_ptr.p, node);
}

void
15089 15090
Dbdict::execDICT_COMMIT_CONF(Signal* signal)
{
15091
  Ptr<SchemaTransaction> trans_ptr;
15092 15093 15094
  DictCommitConf * const conf = (DictCommitConf*)signal->getDataPtr();

  jamEntry();
15095 15096 15097 15098 15099
  ndbrequire(c_Trans.find(trans_ptr, conf->senderData));
  schemaOp_reply(signal, trans_ptr.p, refToNode(conf->senderRef));
}

void
15100 15101
Dbdict::execDICT_ABORT_REF(Signal* signal)
{
15102 15103
  DictAbortRef * const ref = (DictAbortRef*)signal->getDataPtr();
  Ptr<SchemaTransaction> trans_ptr;
15104 15105

  jamEntry();
15106 15107
  ndbrequire(c_Trans.find(trans_ptr, ref->senderData));
  if(ref->errorCode != DictAbortRef::NF_FakeErrorREF){
15108
    jam();
15109 15110 15111 15112 15113 15114 15115
    trans_ptr.p->setErrorCode(ref->errorCode);
  }
  Uint32 node = refToNode(ref->senderRef);
  schemaOp_reply(signal, trans_ptr.p, node);
}

void
15116 15117
Dbdict::execDICT_ABORT_CONF(Signal* signal)
{
15118 15119
  DictAbortConf * const conf = (DictAbortConf*)signal->getDataPtr();
  Ptr<SchemaTransaction> trans_ptr;
15120 15121

  jamEntry();
15122 15123 15124 15125 15126 15127 15128
  ndbrequire(c_Trans.find(trans_ptr, conf->senderData));
  schemaOp_reply(signal, trans_ptr.p, refToNode(conf->senderRef));
}

void
Dbdict::createObj_prepare_start_done(Signal* signal,
				     Uint32 callbackData, 
15129 15130 15131 15132
				     Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;  
  SegmentedSectionPtr objInfoPtr;
15133 15134 15135
  
  ndbrequire(returnCode == 0);
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
15136
  jam();
15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164
  getSection(objInfoPtr, createObjPtr.p->m_obj_info_ptr_i);
  if(createObjPtr.p->m_errorCode != 0){
    jam();
    createObjPtr.p->m_obj_info_ptr_i= RNIL;
    signal->setSection(objInfoPtr, 0);
    releaseSections(signal);
    createObj_prepare_complete_done(signal, callbackData, 0);
    return;
  }
  
  SchemaFile::TableEntry tabEntry;
  bzero(&tabEntry, sizeof(tabEntry));
  tabEntry.m_tableVersion = createObjPtr.p->m_obj_version;
  tabEntry.m_tableType    = createObjPtr.p->m_obj_type;
  tabEntry.m_tableState   = SchemaFile::ADD_STARTED;
  tabEntry.m_gcp          = createObjPtr.p->m_gci;
  tabEntry.m_info_words   = objInfoPtr.sz;
  
  Callback cb;
  cb.m_callbackData = createObjPtr.p->key;
  cb.m_callbackFunction = safe_cast(&Dbdict::createObj_writeSchemaConf1);
  
  updateSchemaState(signal, createObjPtr.p->m_obj_id, &tabEntry, &cb);
}

void
Dbdict::createObj_writeSchemaConf1(Signal* signal, 
				   Uint32 callbackData,
15165 15166 15167 15168 15169
				   Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;  
  Callback callback;
  SegmentedSectionPtr objInfoPtr;
15170

15171
  jam();
15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188
  ndbrequire(returnCode == 0);
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  
  callback.m_callbackData = createObjPtr.p->key;
  callback.m_callbackFunction = safe_cast(&Dbdict::createObj_writeObjConf);
  
  getSection(objInfoPtr, createObjPtr.p->m_obj_info_ptr_i);
  writeTableFile(signal, createObjPtr.p->m_obj_id, objInfoPtr, &callback);
  
  signal->setSection(objInfoPtr, 0);
  releaseSections(signal);
  createObjPtr.p->m_obj_info_ptr_i = RNIL;
}

void
Dbdict::createObj_writeObjConf(Signal* signal, 
			       Uint32 callbackData,
15189 15190 15191
			       Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;
15192

15193
  jam();
15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204
  ndbrequire(returnCode == 0);
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  createObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_prepare_complete_done);
  (this->*f_dict_op[createObjPtr.p->m_vt_index].m_prepare_complete)
    (signal, createObjPtr.p);
}

void
Dbdict::createObj_prepare_complete_done(Signal* signal, 
					Uint32 callbackData,
15205 15206 15207 15208
					Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;

15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238
  jam();
  ndbrequire(returnCode == 0);
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  
  //@todo check for master failed
  
  if(createObjPtr.p->m_errorCode == 0){
    jam();
    
    CreateObjConf * const conf = (CreateObjConf*)signal->getDataPtr();
    conf->senderRef = reference();
    conf->senderData = createObjPtr.p->m_senderData;
    sendSignal(createObjPtr.p->m_senderRef, GSN_CREATE_OBJ_CONF,
	       signal, CreateObjConf::SignalLength, JBB);
    return;
  }
  
  CreateObjRef * const ref = (CreateObjRef*)signal->getDataPtr();
  ref->senderRef = reference();
  ref->senderData = createObjPtr.p->m_senderData;
  ref->errorCode = createObjPtr.p->m_errorCode;
  ref->errorLine = 0;
  ref->errorKey = 0;
  ref->errorStatus = 0;
  
  sendSignal(createObjPtr.p->m_senderRef, GSN_CREATE_OBJ_REF,
	     signal, CreateObjRef::SignalLength, JBB);
}

void
15239 15240
Dbdict::createObj_commit(Signal * signal, SchemaOp * op)
{
15241
  OpCreateObj * createObj = (OpCreateObj*)op;
15242

15243 15244 15245
  createObj->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_commit_start_done);
  if (f_dict_op[createObj->m_vt_index].m_commit_start)
15246 15247
  {
    jam();
15248
    (this->*f_dict_op[createObj->m_vt_index].m_commit_start)(signal, createObj);
15249
  }
15250
  else
15251 15252
  {
    jam();
15253
    execute(signal, createObj->m_callback, 0);
15254
  }
15255 15256 15257 15258 15259
}

void
Dbdict::createObj_commit_start_done(Signal* signal, 
				    Uint32 callbackData,
15260 15261 15262
				    Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;  
15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284
  
  jam();
  ndbrequire(returnCode == 0);
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  
  Uint32 objId = createObjPtr.p->m_obj_id;
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry objEntry = * getTableEntry(xsf, objId);
  objEntry.m_tableState = SchemaFile::TABLE_ADD_COMMITTED;
  
  Callback callback;
  callback.m_callbackData = createObjPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_writeSchemaConf2);
  
  updateSchemaState(signal, createObjPtr.p->m_obj_id, &objEntry, &callback);

}

void
Dbdict::createObj_writeSchemaConf2(Signal* signal, 
				   Uint32 callbackData,
15285 15286 15287
				   Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;
15288

15289
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
15290 15291 15292
  createObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_commit_complete_done);
  if (f_dict_op[createObjPtr.p->m_vt_index].m_commit_complete)
15293 15294
  {
    jam();
15295 15296
    (this->*f_dict_op[createObjPtr.p->m_vt_index].m_commit_complete)
      (signal, createObjPtr.p);
15297
  }
15298
  else
15299 15300
  {
    jam();
15301
    execute(signal, createObjPtr.p->m_callback, 0);
15302
  }
15303 15304 15305 15306 15307 15308
  
}

void
Dbdict::createObj_commit_complete_done(Signal* signal, 
				       Uint32 callbackData,
15309 15310 15311 15312
				       Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;

15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335
  jam();
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  
  //@todo check error
  //@todo check master failed
  
  DictCommitConf * const conf = (DictCommitConf*)signal->getDataPtr();
  conf->senderRef = reference();
  conf->senderData = createObjPtr.p->m_senderData;
  sendSignal(createObjPtr.p->m_senderRef, GSN_DICT_COMMIT_CONF,
	     signal, DictCommitConf::SignalLength, JBB);
  
  c_opCreateObj.release(createObjPtr);
}

void
Dbdict::createObj_abort(Signal* signal, SchemaOp* op)
{
  OpCreateObj * createObj = (OpCreateObj*)op;
  
  createObj->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_abort_start_done);
  if (f_dict_op[createObj->m_vt_index].m_abort_start)
15336 15337
  {
    jam();
15338
    (this->*f_dict_op[createObj->m_vt_index].m_abort_start)(signal, createObj);
15339
  }
15340
  else
15341 15342
  {
    jam();
15343
    execute(signal, createObj->m_callback, 0);
15344
  }
15345 15346 15347 15348 15349
}

void
Dbdict::createObj_abort_start_done(Signal* signal, 
				   Uint32 callbackData,
15350 15351 15352 15353
				   Uint32 returnCode)
{
  CreateObjRecordPtr createObjPtr;

15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373
  jam();
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry objEntry = * getTableEntry(xsf, 
						    createObjPtr.p->m_obj_id);
  objEntry.m_tableState = SchemaFile::DROP_TABLE_COMMITTED;
  
  Callback callback;
  callback.m_callbackData = createObjPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_abort_writeSchemaConf);
  
  updateSchemaState(signal, createObjPtr.p->m_obj_id, &objEntry, &callback);
}

void
Dbdict::createObj_abort_writeSchemaConf(Signal* signal, 
					Uint32 callbackData,
					Uint32 returnCode)
{
15374
  CreateObjRecordPtr createObjPtr;
15375 15376 15377 15378 15379 15380

  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));
  createObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::createObj_abort_complete_done);
  
  if (f_dict_op[createObjPtr.p->m_vt_index].m_abort_complete)
15381 15382
  {
    jam();
15383 15384
    (this->*f_dict_op[createObjPtr.p->m_vt_index].m_abort_complete)
      (signal, createObjPtr.p);
15385
  }
15386
  else
15387 15388
  {
    jam();
15389
    execute(signal, createObjPtr.p->m_callback, 0);
15390
  }
15391 15392 15393 15394 15395 15396 15397
}

void
Dbdict::createObj_abort_complete_done(Signal* signal, 
				      Uint32 callbackData,
				      Uint32 returnCode)
{
15398
  CreateObjRecordPtr createObjPtr;
15399

15400
  jam();
15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412
  ndbrequire(c_opCreateObj.find(createObjPtr, callbackData));

  DictAbortConf * const conf = (DictAbortConf*)signal->getDataPtr();
  conf->senderRef = reference();
  conf->senderData = createObjPtr.p->m_senderData;
  sendSignal(createObjPtr.p->m_senderRef, GSN_DICT_ABORT_CONF,
	     signal, DictAbortConf::SignalLength, JBB);
  
  c_opCreateObj.release(createObjPtr);
}

void
15413 15414
Dbdict::execDROP_OBJ_REQ(Signal* signal)
{
15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452
  jamEntry();

  if(!assembleFragments(signal)){
    jam();
    return;
  }
  
  DropObjReq * const req = (DropObjReq*)signal->getDataPtr();

  const Uint32 objId = req->objId;
  const Uint32 objVersion = req->objVersion;
  const Uint32 objType = req->objType;
  
  DropObjRecordPtr dropObjPtr;  
  ndbrequire(c_opDropObj.seize(dropObjPtr));
  
  const Uint32 key = req->op_key;
  dropObjPtr.p->key = key;
  c_opDropObj.add(dropObjPtr);
  dropObjPtr.p->m_errorCode = 0;
  dropObjPtr.p->m_senderRef = req->senderRef;
  dropObjPtr.p->m_senderData = req->senderData;
  dropObjPtr.p->m_clientRef = req->clientRef;
  dropObjPtr.p->m_clientData = req->clientData;
  
  dropObjPtr.p->m_obj_id = objId;
  dropObjPtr.p->m_obj_type = objType;
  dropObjPtr.p->m_obj_version = objVersion;

  dropObjPtr.p->m_callback.m_callbackData = key;
  dropObjPtr.p->m_callback.m_callbackFunction= 
    safe_cast(&Dbdict::dropObj_prepare_start_done);

  switch(objType){
  case DictTabInfo::Tablespace:
  case DictTabInfo::LogfileGroup:
  {
    Ptr<Filegroup> fg_ptr;
15453 15454
    jam();
    dropObjPtr.p->m_vt_index = 3;
15455 15456 15457 15458 15459 15460 15461 15462
    ndbrequire(c_filegroup_hash.find(fg_ptr, objId));
    dropObjPtr.p->m_obj_ptr_i = fg_ptr.i;
    break;
  
  }
  case DictTabInfo::Datafile:
  {
    Ptr<File> file_ptr;
15463 15464
    jam();
    dropObjPtr.p->m_vt_index = 2;
15465 15466 15467 15468 15469
    ndbrequire(c_file_hash.find(file_ptr, objId));
    dropObjPtr.p->m_obj_ptr_i = file_ptr.i;
    break;
  }
  case DictTabInfo::Undofile:
15470 15471
  {
    jam();
15472 15473
    dropObjPtr.p->m_vt_index = 4;
    return;
15474
  }
15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488
  default:
    ndbrequire(false);
  }
  
  signal->header.m_noOfSections = 0;
  (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_start)
    (signal, dropObjPtr.p);
}

void
Dbdict::dropObj_prepare_start_done(Signal* signal, 
				   Uint32 callbackData,
				   Uint32 returnCode)
{
15489 15490
  DropObjRecordPtr dropObjPtr;
  Callback cb;
15491

15492
  ndbrequire(returnCode == 0);
15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));

  cb.m_callbackData = callbackData;
  cb.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_prepare_writeSchemaConf);

  if(dropObjPtr.p->m_errorCode != 0)
  {
    jam();
    dropObj_prepare_complete_done(signal, callbackData, 0);
    return;
  }
15505
  jam();  
15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517
  Uint32 objId = dropObjPtr.p->m_obj_id;
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry objEntry = *getTableEntry(xsf, objId);
  objEntry.m_tableState = SchemaFile::DROP_TABLE_STARTED;
  updateSchemaState(signal, objId, &objEntry, &cb);
}

void
Dbdict::dropObj_prepare_writeSchemaConf(Signal* signal, 
					Uint32 callbackData,
					Uint32 returnCode)
{
15518
  DropObjRecordPtr dropObjPtr;
15519

15520
  ndbrequire(returnCode == 0);
15521 15522 15523 15524
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  dropObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_prepare_complete_done);
  if(f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_complete)
15525 15526
  {
    jam();
15527 15528
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_prepare_complete)
      (signal, dropObjPtr.p);
15529
  }
15530
  else
15531 15532
  {
    jam();
15533
    execute(signal, dropObjPtr.p->m_callback, 0);
15534
  }
15535 15536 15537 15538 15539 15540 15541
}

void
Dbdict::dropObj_prepare_complete_done(Signal* signal, 
				      Uint32 callbackData,
				      Uint32 returnCode)
{
15542 15543
  DropObjRecordPtr dropObjPtr;

15544 15545
  ndbrequire(returnCode == 0);
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
15546
  jam();
15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571
  
  //@todo check for master failed
  
  if(dropObjPtr.p->m_errorCode == 0){
    jam();
    
    DropObjConf * const conf = (DropObjConf*)signal->getDataPtr();
    conf->senderRef = reference();
    conf->senderData = dropObjPtr.p->m_senderData;
    sendSignal(dropObjPtr.p->m_senderRef, GSN_DROP_OBJ_CONF,
	       signal, DropObjConf::SignalLength, JBB);
    return;
  }
  
  DropObjRef * const ref = (DropObjRef*)signal->getDataPtr();
  ref->senderRef = reference();
  ref->senderData = dropObjPtr.p->m_senderData;
  ref->errorCode = dropObjPtr.p->m_errorCode;
  
  sendSignal(dropObjPtr.p->m_senderRef, GSN_DROP_OBJ_REF,
	     signal, DropObjRef::SignalLength, JBB);

}

void
15572 15573
Dbdict::dropObj_commit(Signal * signal, SchemaOp * op)
{
15574
  OpDropObj * dropObj = (OpDropObj*)op;
15575

15576 15577 15578
  dropObj->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_commit_start_done);
  if (f_dict_op[dropObj->m_vt_index].m_commit_start)
15579 15580
  {
    jam();
15581
    (this->*f_dict_op[dropObj->m_vt_index].m_commit_start)(signal, dropObj);
15582
  }
15583
  else
15584 15585
  {
    jam();
15586
    execute(signal, dropObj->m_callback, 0);
15587
  }
15588 15589 15590 15591 15592 15593 15594
}

void
Dbdict::dropObj_commit_start_done(Signal* signal, 
				  Uint32 callbackData,
				  Uint32 returnCode)
{
15595 15596
  DropObjRecordPtr dropObjPtr;

15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618
  jam();
  ndbrequire(returnCode == 0);
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  
  Uint32 objId = dropObjPtr.p->m_obj_id;
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry objEntry = * getTableEntry(xsf, objId);
  objEntry.m_tableState = SchemaFile::DROP_TABLE_COMMITTED;
  
  Callback callback;
  callback.m_callbackData = dropObjPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_commit_writeSchemaConf);
  
  updateSchemaState(signal, objId, &objEntry, &callback);
}

void
Dbdict::dropObj_commit_writeSchemaConf(Signal* signal, 
				       Uint32 callbackData,
				       Uint32 returnCode)
{
15619 15620
  DropObjRecordPtr dropObjPtr;

15621 15622 15623 15624 15625 15626 15627
  jam();
  ndbrequire(returnCode == 0);
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  dropObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_commit_complete_done);
  
  if(f_dict_op[dropObjPtr.p->m_vt_index].m_commit_complete)
15628 15629
  {
    jam();
15630 15631
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_commit_complete)
      (signal, dropObjPtr.p);
15632
  }
15633
  else
15634 15635
  {
    jam();
15636
    execute(signal, dropObjPtr.p->m_callback, 0);
15637
  }
15638 15639 15640 15641 15642 15643 15644
}

void
Dbdict::dropObj_commit_complete_done(Signal* signal, 
				     Uint32 callbackData,
				     Uint32 returnCode)
{
15645 15646 15647
  DropObjRecordPtr dropObjPtr;

  jam();
15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  
  //@todo check error
  //@todo check master failed
  
  DictCommitConf * const conf = (DictCommitConf*)signal->getDataPtr();
  conf->senderRef = reference();
  conf->senderData = dropObjPtr.p->m_senderData;
  sendSignal(dropObjPtr.p->m_senderRef, GSN_DICT_COMMIT_CONF,
	     signal, DictCommitConf::SignalLength, JBB);
  c_opDropObj.release(dropObjPtr);
}

void
15662 15663
Dbdict::dropObj_abort(Signal * signal, SchemaOp * op)
{
15664
  OpDropObj * dropObj = (OpDropObj*)op;
15665

15666 15667 15668
  dropObj->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_abort_start_done);
  if (f_dict_op[dropObj->m_vt_index].m_abort_start)
15669 15670
  {
    jam();
15671
    (this->*f_dict_op[dropObj->m_vt_index].m_abort_start)(signal, dropObj);
15672
  }
15673
  else
15674 15675
  {
    jam();
15676
    execute(signal, dropObj->m_callback, 0);
15677
  }
15678 15679 15680 15681 15682 15683 15684
}

void
Dbdict::dropObj_abort_start_done(Signal* signal, 
				 Uint32 callbackData,
				 Uint32 returnCode)
{
15685 15686
  DropObjRecordPtr dropObjPtr;

15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708
  jam();
  ndbrequire(returnCode == 0);
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  
  XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
  SchemaFile::TableEntry objEntry = * getTableEntry(xsf, 
						    dropObjPtr.p->m_obj_id);

  Callback callback;
  callback.m_callbackData = dropObjPtr.p->key;
  callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_abort_writeSchemaConf);
  
  if (objEntry.m_tableState == SchemaFile::DROP_TABLE_STARTED)
  {
    jam();
    objEntry.m_tableState = SchemaFile::TABLE_ADD_COMMITTED;
        
    updateSchemaState(signal, dropObjPtr.p->m_obj_id, &objEntry, &callback);
  }
  else
  {
15709
    jam();
15710 15711 15712 15713 15714 15715 15716 15717 15718
    execute(signal, callback, 0);
  }
}

void
Dbdict::dropObj_abort_writeSchemaConf(Signal* signal, 
				      Uint32 callbackData,
				      Uint32 returnCode)
{
15719 15720
  DropObjRecordPtr dropObjPtr;

15721 15722 15723 15724 15725 15726
  ndbrequire(returnCode == 0);
  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  dropObjPtr.p->m_callback.m_callbackFunction = 
    safe_cast(&Dbdict::dropObj_abort_complete_done);
  
  if(f_dict_op[dropObjPtr.p->m_vt_index].m_abort_complete)
15727 15728
  {
    jam();
15729 15730
    (this->*f_dict_op[dropObjPtr.p->m_vt_index].m_abort_complete)
      (signal, dropObjPtr.p);
15731
  }
15732
  else
15733 15734
  {
    jam();
15735
    execute(signal, dropObjPtr.p->m_callback, 0);
15736
  }
15737 15738 15739 15740 15741 15742 15743
}

void
Dbdict::dropObj_abort_complete_done(Signal* signal, 
				    Uint32 callbackData,
				    Uint32 returnCode)
{
15744
  DropObjRecordPtr dropObjPtr;
15745
  DictAbortConf * const conf = (DictAbortConf*)signal->getDataPtr();
15746 15747 15748

  ndbrequire(c_opDropObj.find(dropObjPtr, callbackData));
  jam();
15749 15750 15751 15752 15753 15754 15755 15756
  conf->senderRef = reference();
  conf->senderData = dropObjPtr.p->m_senderData;
  sendSignal(dropObjPtr.p->m_senderRef, GSN_DICT_ABORT_CONF,
	     signal, DictAbortConf::SignalLength, JBB);
  c_opDropObj.release(dropObjPtr);
}

void 
15757 15758
Dbdict::create_fg_prepare_start(Signal* signal, SchemaOp* op)
{
15759 15760 15761 15762
  /**
   * Put data into table record
   */
  SegmentedSectionPtr objInfoPtr;
15763
  jam();
15764 15765
  getSection(objInfoPtr, ((OpCreateObj*)op)->m_obj_info_ptr_i);
  SimplePropertiesSectionReader it(objInfoPtr, getSectionSegmentPool());
15766 15767 15768

  Ptr<DictObject> obj_ptr; obj_ptr.setNull();
  FilegroupPtr fg_ptr; fg_ptr.setNull();
15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779
  
  SimpleProperties::UnpackStatus status;
  DictFilegroupInfo::Filegroup fg; fg.init();
  do {
    status = SimpleProperties::unpack(it, &fg, 
				      DictFilegroupInfo::Mapping, 
				      DictFilegroupInfo::MappingSize, 
				      true, true);
    
    if(status != SimpleProperties::Eof)
    {
15780
      jam();
15781 15782 15783 15784 15785 15786 15787 15788
      op->m_errorCode = CreateTableRef::InvalidFormat;
      break;
    }

    if(fg.FilegroupType == DictTabInfo::Tablespace)
    {
      if(!fg.TS_ExtentSize)
      {
15789
        jam();
15790 15791 15792 15793 15794 15795
	op->m_errorCode = CreateFilegroupRef::InvalidExtentSize;
	break;
      }
    } 
    else if(fg.FilegroupType == DictTabInfo::LogfileGroup)
    {
15796 15797 15798 15799
      /**
       * undo_buffer_size can't be less than 96KB in LGMAN block 
       */
      if(fg.LF_UndoBufferSize < 3 * File_formats::NDB_PAGE_SIZE)
15800
      {
15801
        jam();
15802 15803 15804 15805 15806 15807 15808 15809
	op->m_errorCode = CreateFilegroupRef::InvalidUndoBufferSize;
	break;
      }
    }
    
    Uint32 len = strlen(fg.FilegroupName) + 1;
    Uint32 hash = Rope::hash(fg.FilegroupName, len);
    if(get_object(fg.FilegroupName, len, hash) != 0){
15810
      jam();
15811 15812 15813 15814 15815
      op->m_errorCode = CreateTableRef::TableAlreadyExist;
      break;
    }
    
    if(!c_obj_pool.seize(obj_ptr)){
15816
      jam();
15817 15818 15819 15820 15821
      op->m_errorCode = CreateTableRef::NoMoreTableRecords;
      break;
    }
    
    if(!c_filegroup_pool.seize(fg_ptr)){
15822
      jam();
15823 15824 15825 15826
      op->m_errorCode = CreateTableRef::NoMoreTableRecords;
      break;
    }
  
15827 15828
    new (fg_ptr.p) Filegroup();

15829 15830 15831
    {
      Rope name(c_rope_pool, obj_ptr.p->m_name);
      if(!name.assign(fg.FilegroupName, len, hash)){
15832
        jam();
15833
	op->m_errorCode = CreateTableRef::OutOfStringBuffer;
15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845
	break;
      }
    }
    
    fg_ptr.p->key = op->m_obj_id;
    fg_ptr.p->m_obj_ptr_i = obj_ptr.i;
    fg_ptr.p->m_type = fg.FilegroupType;
    fg_ptr.p->m_version = op->m_obj_version;
    fg_ptr.p->m_name = obj_ptr.p->m_name;

    switch(fg.FilegroupType){
    case DictTabInfo::Tablespace:
15846
    {
15847 15848 15849 15850 15851 15852 15853
      //fg.TS_DataGrow = group.m_grow_spec;
      fg_ptr.p->m_tablespace.m_extent_size = fg.TS_ExtentSize;
      fg_ptr.p->m_tablespace.m_default_logfile_group_id = fg.TS_LogfileGroupId;

      Ptr<Filegroup> lg_ptr;
      if (!c_filegroup_hash.find(lg_ptr, fg.TS_LogfileGroupId))
      {
15854
        jam();
15855 15856 15857 15858 15859 15860
	op->m_errorCode = CreateFilegroupRef::NoSuchLogfileGroup;
	goto error;
      }

      if (lg_ptr.p->m_version != fg.TS_LogfileGroupVersion)
      {
15861
        jam();
15862 15863 15864 15865 15866
	op->m_errorCode = CreateFilegroupRef::InvalidFilegroupVersion;
	goto error;
      }
      increase_ref_count(lg_ptr.p->m_obj_ptr_i);
      break;
15867
    }
15868
    case DictTabInfo::LogfileGroup:
15869 15870
    {
      jam();
15871 15872 15873 15874
      fg_ptr.p->m_logfilegroup.m_undo_buffer_size = fg.LF_UndoBufferSize;
      fg_ptr.p->m_logfilegroup.m_files.init();
      //fg.LF_UndoGrow = ;
      break;
15875
    }
15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887
    default:
      ndbrequire(false);
    }

    obj_ptr.p->m_id = op->m_obj_id;
    obj_ptr.p->m_type = fg.FilegroupType;
    obj_ptr.p->m_ref_count = 0;
    c_obj_hash.add(obj_ptr);
    c_filegroup_hash.add(fg_ptr);
    
    op->m_obj_ptr_i = fg_ptr.i;
  } while(0);
15888

15889
error:
15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905
  if (op->m_errorCode)
  {
    jam();
    if (!fg_ptr.isNull())
    {
      jam();
      c_filegroup_pool.release(fg_ptr);
    }

    if (!obj_ptr.isNull())
    {
      jam();
      c_obj_pool.release(obj_ptr);
    }
  }
  
15906 15907 15908 15909
  execute(signal, op->m_callback, 0);
}

void
15910 15911
Dbdict::create_fg_prepare_complete(Signal* signal, SchemaOp* op)
{
15912 15913 15914 15915 15916
  /**
   * CONTACT TSMAN LGMAN PGMAN 
   */
  CreateFilegroupImplReq* req = 
    (CreateFilegroupImplReq*)signal->getDataPtrSend();
15917
  jam();
15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929
  req->senderData = op->key;
  req->senderRef = reference();
  req->filegroup_id = op->m_obj_id;
  req->filegroup_version = op->m_obj_version;

  FilegroupPtr fg_ptr;
  c_filegroup_pool.getPtr(fg_ptr, op->m_obj_ptr_i);
  
  Uint32 ref= 0;
  Uint32 len= 0;
  switch(op->m_obj_type){
  case DictTabInfo::Tablespace:
15930 15931
  {
    jam();
15932 15933 15934 15935 15936 15937
    ref = TSMAN_REF;
    len = CreateFilegroupImplReq::TablespaceLength;
    req->tablespace.extent_size = fg_ptr.p->m_tablespace.m_extent_size;
    req->tablespace.logfile_group_id = 
      fg_ptr.p->m_tablespace.m_default_logfile_group_id;
    break;
15938
  }
15939
  case DictTabInfo::LogfileGroup:
15940 15941
  {
    jam();
15942 15943 15944 15945 15946
    ref = LGMAN_REF;
    len = CreateFilegroupImplReq::LogfileGroupLength;
    req->logfile_group.buffer_size = 
      fg_ptr.p->m_logfilegroup.m_undo_buffer_size;
    break;
15947
  }
15948 15949 15950 15951 15952 15953 15954 15955
  default:
    ndbrequire(false);
  }
  
  sendSignal(ref, GSN_CREATE_FILEGROUP_REQ, signal, len, JBB);
}

void
15956 15957
Dbdict::execCREATE_FILEGROUP_REF(Signal* signal)
{
15958 15959
  CreateFilegroupImplRef * ref = (CreateFilegroupImplRef*)signal->getDataPtr();
  CreateObjRecordPtr op_ptr;
15960
  jamEntry();
15961 15962 15963 15964 15965 15966 15967
  ndbrequire(c_opCreateObj.find(op_ptr, ref->senderData));
  op_ptr.p->m_errorCode = ref->errorCode;

  execute(signal, op_ptr.p->m_callback, 0);  
}  

void
15968 15969
Dbdict::execCREATE_FILEGROUP_CONF(Signal* signal)
{
15970 15971 15972
  CreateFilegroupImplConf * rep = 
    (CreateFilegroupImplConf*)signal->getDataPtr();
  CreateObjRecordPtr op_ptr;
15973
  jamEntry();
15974 15975 15976 15977 15978 15979 15980
  ndbrequire(c_opCreateObj.find(op_ptr, rep->senderData));
  
  execute(signal, op_ptr.p->m_callback, 0);  
}

void
Dbdict::create_fg_abort_start(Signal* signal, SchemaOp* op){
15981
  (void) signal->getDataPtrSend();
15982 15983 15984 15985 15986 15987 15988

  if (op->m_obj_ptr_i != RNIL)
  {
    jam();
    send_drop_fg(signal, op, DropFilegroupImplReq::Commit);
    return;
  }
15989
  jam();  
15990
  execute(signal, op->m_callback, 0);  
15991 15992 15993
}

void
15994 15995
Dbdict::create_fg_abort_complete(Signal* signal, SchemaOp* op)
{
15996 15997 15998 15999 16000 16001 16002 16003 16004
  if (op->m_obj_ptr_i != RNIL)
  {
    jam();
    FilegroupPtr fg_ptr;
    c_filegroup_pool.getPtr(fg_ptr, op->m_obj_ptr_i);
    
    release_object(fg_ptr.p->m_obj_ptr_i);
    c_filegroup_hash.release(fg_ptr);
  }
16005
  jam();  
16006 16007 16008 16009
  execute(signal, op->m_callback, 0);
}

void 
16010 16011
Dbdict::create_file_prepare_start(Signal* signal, SchemaOp* op)
{
16012 16013 16014 16015 16016 16017 16018
  /**
   * Put data into table record
   */
  SegmentedSectionPtr objInfoPtr;
  getSection(objInfoPtr, ((OpCreateObj*)op)->m_obj_info_ptr_i);
  SimplePropertiesSectionReader it(objInfoPtr, getSectionSegmentPool());
  
16019 16020 16021
  Ptr<DictObject> obj_ptr; obj_ptr.setNull();
  FilePtr filePtr; filePtr.setNull();

16022 16023 16024 16025 16026 16027 16028 16029 16030
  DictFilegroupInfo::File f; f.init();
  SimpleProperties::UnpackStatus status;
  status = SimpleProperties::unpack(it, &f, 
				    DictFilegroupInfo::FileMapping, 
				    DictFilegroupInfo::FileMappingSize, 
				    true, true);
  
  do {
    if(status != SimpleProperties::Eof){
16031
      jam();
16032
      op->m_errorCode = CreateFileRef::InvalidFormat;
16033
      break;
16034 16035 16036 16037 16038
    }

    // Get Filegroup
    FilegroupPtr fg_ptr;
    if(!c_filegroup_hash.find(fg_ptr, f.FilegroupId)){
16039
      jam();
16040 16041 16042 16043 16044
      op->m_errorCode = CreateFileRef::NoSuchFilegroup;
      break;
    }
    
    if(fg_ptr.p->m_version != f.FilegroupVersion){
16045
      jam();
16046 16047 16048 16049 16050 16051
      op->m_errorCode = CreateFileRef::InvalidFilegroupVersion;
      break;
    }

    switch(f.FileType){
    case DictTabInfo::Datafile:
16052
    {
16053
      if(fg_ptr.p->m_type != DictTabInfo::Tablespace)
16054 16055
      {
        jam();
16056
	op->m_errorCode = CreateFileRef::InvalidFileType;
16057 16058
      }
      jam();
16059
      break;
16060
    }
16061
    case DictTabInfo::Undofile:
16062
    {
16063
      if(fg_ptr.p->m_type != DictTabInfo::LogfileGroup)
16064 16065
      {
        jam();
16066
	op->m_errorCode = CreateFileRef::InvalidFileType;
16067 16068
      }
      jam();
16069
      break;
16070
    }
16071
    default:
16072
      jam();
16073 16074 16075 16076
      op->m_errorCode = CreateFileRef::InvalidFileType;
    }
    
    if(op->m_errorCode)
16077 16078
    {
      jam();
16079
      break;
16080
    }
16081 16082 16083 16084

    Uint32 len = strlen(f.FileName) + 1;
    Uint32 hash = Rope::hash(f.FileName, len);
    if(get_object(f.FileName, len, hash) != 0){
16085
      jam();
16086 16087 16088 16089
      op->m_errorCode = CreateFileRef::FilenameAlreadyExists;
      break;
    }
    
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
16090 16091 16092 16093 16094 16095
    {
      Uint32 dl;
      const ndb_mgm_configuration_iterator * p = 
	m_ctx.m_config.getOwnConfigIterator();
      if(!ndb_mgm_get_int_parameter(p, CFG_DB_DISCLESS, &dl) && dl)
      {
16096
        jam();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
16097 16098 16099 16100 16101
	op->m_errorCode = CreateFileRef::NotSupportedWhenDiskless;
	break;
      }
    }
    
16102 16103
    // Loop through all filenames...
    if(!c_obj_pool.seize(obj_ptr)){
16104
      jam();
16105 16106 16107 16108 16109
      op->m_errorCode = CreateTableRef::NoMoreTableRecords;
      break;
    }
    
    if (! c_file_pool.seize(filePtr)){
16110
      jam();
16111 16112 16113 16114
      op->m_errorCode = CreateFileRef::OutOfFileRecords;
      break;
    }

16115 16116
    new (filePtr.p) File();

16117 16118 16119
    {
      Rope name(c_rope_pool, obj_ptr.p->m_name);
      if(!name.assign(f.FileName, len, hash)){
16120
        jam();
16121
	op->m_errorCode = CreateTableRef::OutOfStringBuffer;
16122 16123 16124 16125 16126 16127
	break;
      }
    }

    switch(fg_ptr.p->m_type){
    case DictTabInfo::Tablespace:
16128 16129
    {
      jam();
16130 16131
      increase_ref_count(fg_ptr.p->m_obj_ptr_i);
      break;
16132
    }
16133 16134
    case DictTabInfo::LogfileGroup:
    {
16135
      jam();
16136
      Local_file_list list(c_file_pool, fg_ptr.p->m_logfilegroup.m_files);
16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152
      list.add(filePtr);
      break;
    }
    default:
      ndbrequire(false);
    }
    
    /**
     * Init file
     */
    filePtr.p->key = op->m_obj_id;
    filePtr.p->m_file_size = ((Uint64)f.FileSizeHi) << 32 | f.FileSizeLo;
    filePtr.p->m_path = obj_ptr.p->m_name;
    filePtr.p->m_obj_ptr_i = obj_ptr.i;
    filePtr.p->m_filegroup_id = f.FilegroupId;
    filePtr.p->m_type = f.FileType;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
16153
    filePtr.p->m_version = op->m_obj_version;
16154 16155 16156 16157 16158 16159 16160 16161 16162
    
    obj_ptr.p->m_id = op->m_obj_id;
    obj_ptr.p->m_type = f.FileType;
    obj_ptr.p->m_ref_count = 0;
    c_obj_hash.add(obj_ptr);
    c_file_hash.add(filePtr);

    op->m_obj_ptr_i = filePtr.i;
  } while(0);
16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178

  if (op->m_errorCode)
  {
    jam();
    if (!filePtr.isNull())
    {
      jam();
      c_file_pool.release(filePtr);
    }

    if (!obj_ptr.isNull())
    {
      jam();
      c_obj_pool.release(obj_ptr);
    }
  }
16179 16180 16181 16182 16183
  execute(signal, op->m_callback, 0);
}


void
16184 16185
Dbdict::create_file_prepare_complete(Signal* signal, SchemaOp* op)
{
16186 16187 16188 16189 16190 16191
  /**
   * CONTACT TSMAN LGMAN PGMAN 
   */
  CreateFileImplReq* req = (CreateFileImplReq*)signal->getDataPtrSend();
  FilePtr f_ptr;
  FilegroupPtr fg_ptr;
16192 16193 16194

  jam();
  c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
16195 16196 16197 16198 16199 16200
  ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));

  req->senderData = op->key;
  req->senderRef = reference();
  switch(((OpCreateObj*)op)->m_restart){
  case 0:
16201 16202
  {
    jam();
16203 16204
    req->requestInfo = CreateFileImplReq::Create;
    break;
16205
  }
16206
  case 1:
16207 16208
  {
    jam();
16209 16210
    req->requestInfo = CreateFileImplReq::Open;
    break;
16211
  }
16212
  case 2:
16213 16214
  {
    jam();
16215 16216
    req->requestInfo = CreateFileImplReq::CreateForce;
    break;
16217
  }
16218
  }
16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229
	 
  req->file_id = f_ptr.p->key;
  req->filegroup_id = f_ptr.p->m_filegroup_id;
  req->filegroup_version = fg_ptr.p->m_version;
  req->file_size_hi = f_ptr.p->m_file_size >> 32;
  req->file_size_lo = f_ptr.p->m_file_size & 0xFFFFFFFF;

  Uint32 ref= 0;
  Uint32 len= 0;
  switch(op->m_obj_type){
  case DictTabInfo::Datafile:
16230 16231
  {
    jam();
16232 16233 16234 16235
    ref = TSMAN_REF;
    len = CreateFileImplReq::DatafileLength;
    req->tablespace.extent_size = fg_ptr.p->m_tablespace.m_extent_size;
    break;
16236
  }
16237
  case DictTabInfo::Undofile:
16238 16239
  {
    jam();
16240 16241 16242
    ref = LGMAN_REF;
    len = CreateFileImplReq::UndofileLength;
    break;
16243
  }
16244 16245
  default:
    ndbrequire(false);
16246
  }
16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257
  
  char name[MAX_TAB_NAME_SIZE];
  ConstRope tmp(c_rope_pool, f_ptr.p->m_path);
  tmp.copy(name);
  LinearSectionPtr ptr[3];
  ptr[0].p = (Uint32*)&name[0];
  ptr[0].sz = (strlen(name)+1+3)/4;
  sendSignal(ref, GSN_CREATE_FILE_REQ, signal, len, JBB, ptr, 1);
}

void
16258 16259
Dbdict::execCREATE_FILE_REF(Signal* signal)
{
16260 16261
  CreateFileImplRef * ref = (CreateFileImplRef*)signal->getDataPtr();
  CreateObjRecordPtr op_ptr;
16262 16263

  jamEntry();
16264 16265 16266 16267 16268 16269
  ndbrequire(c_opCreateObj.find(op_ptr, ref->senderData));
  op_ptr.p->m_errorCode = ref->errorCode;
  execute(signal, op_ptr.p->m_callback, 0);  
}  

void
16270 16271
Dbdict::execCREATE_FILE_CONF(Signal* signal)
{
16272 16273 16274
  CreateFileImplConf * rep = 
    (CreateFileImplConf*)signal->getDataPtr();
  CreateObjRecordPtr op_ptr;
16275 16276

  jamEntry();
16277 16278 16279 16280 16281
  ndbrequire(c_opCreateObj.find(op_ptr, rep->senderData));
  execute(signal, op_ptr.p->m_callback, 0);  
}

void
16282 16283
Dbdict::create_file_commit_start(Signal* signal, SchemaOp* op)
{
16284 16285 16286 16287 16288 16289
  /**
   * CONTACT TSMAN LGMAN PGMAN 
   */
  CreateFileImplReq* req = (CreateFileImplReq*)signal->getDataPtrSend();
  FilePtr f_ptr;
  FilegroupPtr fg_ptr;
16290 16291 16292

  jam();
  c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305
  ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));

  req->senderData = op->key;
  req->senderRef = reference();
  req->requestInfo = CreateFileImplReq::Commit;
  
  req->file_id = f_ptr.p->key;
  req->filegroup_id = f_ptr.p->m_filegroup_id;
  req->filegroup_version = fg_ptr.p->m_version;

  Uint32 ref= 0;
  switch(op->m_obj_type){
  case DictTabInfo::Datafile:
16306 16307
  {
    jam();
16308 16309
    ref = TSMAN_REF;
    break;
16310
  }
16311
  case DictTabInfo::Undofile:
16312 16313
  {
    jam();
16314 16315
    ref = LGMAN_REF;
    break;
16316
  }
16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328
  default:
    ndbrequire(false);
  }
  sendSignal(ref, GSN_CREATE_FILE_REQ, signal, 
	     CreateFileImplReq::CommitLength, JBB);
}

void
Dbdict::create_file_abort_start(Signal* signal, SchemaOp* op)
{
  CreateFileImplReq* req = (CreateFileImplReq*)signal->getDataPtrSend();

16329 16330 16331
  if (op->m_obj_ptr_i != RNIL)
  {
    FilePtr f_ptr;
16332 16333 16334
    FilegroupPtr fg_ptr;

    jam();
16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349
    c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
    
    ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));
    
    req->senderData = op->key;
    req->senderRef = reference();
    req->requestInfo = CreateFileImplReq::Abort;
    
    req->file_id = f_ptr.p->key;
    req->filegroup_id = f_ptr.p->m_filegroup_id;
    req->filegroup_version = fg_ptr.p->m_version;
    
    Uint32 ref= 0;
    switch(op->m_obj_type){
    case DictTabInfo::Datafile:
16350 16351
    {
      jam();
16352 16353
      ref = TSMAN_REF;
      break;
16354
    }
16355
    case DictTabInfo::Undofile:
16356 16357
    {
      jam();
16358 16359
      ref = LGMAN_REF;
      break;
16360
    }
16361 16362 16363 16364 16365 16366
    default:
      ndbrequire(false);
    }
    sendSignal(ref, GSN_CREATE_FILE_REQ, signal, 
	       CreateFileImplReq::AbortLength, JBB);
    return;
16367
  }
16368
  execute(signal, op->m_callback, 0);
16369 16370 16371 16372 16373
}

void
Dbdict::create_file_abort_complete(Signal* signal, SchemaOp* op)
{
16374
  if (op->m_obj_ptr_i != RNIL)
16375
  {
16376 16377
    FilePtr f_ptr;
    FilegroupPtr fg_ptr;
16378 16379 16380

    jam();
    c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
16381 16382 16383
    ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));
    switch(fg_ptr.p->m_type){
    case DictTabInfo::Tablespace:
16384 16385
    {
      jam();
16386 16387
      decrease_ref_count(fg_ptr.p->m_obj_ptr_i);
      break;
16388
    }
16389 16390
    case DictTabInfo::LogfileGroup:
    {
16391
      jam();
16392
      Local_file_list list(c_file_pool, fg_ptr.p->m_logfilegroup.m_files);
16393 16394 16395 16396 16397 16398 16399 16400
      list.remove(f_ptr);
      break;
    }
    default:
      ndbrequire(false);
    }
    
    release_object(f_ptr.p->m_obj_ptr_i);
16401
    c_file_hash.release(f_ptr);
16402 16403
  }
  execute(signal, op->m_callback, 0);
16404
}
16405

16406 16407 16408
void
Dbdict::drop_file_prepare_start(Signal* signal, SchemaOp* op)
{
16409
  jam();
16410 16411 16412 16413 16414 16415
  send_drop_file(signal, op, DropFileImplReq::Prepare);
}

void
Dbdict::drop_undofile_prepare_start(Signal* signal, SchemaOp* op)
{
16416
  jam();
16417 16418 16419 16420 16421 16422 16423
  op->m_errorCode = DropFileRef::DropUndoFileNotSupported;
  execute(signal, op->m_callback, 0);  
}

void
Dbdict::drop_file_commit_start(Signal* signal, SchemaOp* op)
{
16424
  jam();
16425 16426 16427 16428 16429 16430 16431 16432 16433
  send_drop_file(signal, op, DropFileImplReq::Commit);
}

void
Dbdict::drop_file_commit_complete(Signal* signal, SchemaOp* op)
{
  FilePtr f_ptr;
  FilegroupPtr fg_ptr;

16434 16435 16436
  jam();
  c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
  ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));
16437 16438
  decrease_ref_count(fg_ptr.p->m_obj_ptr_i);
  release_object(f_ptr.p->m_obj_ptr_i);
16439
  c_file_hash.release(f_ptr);
16440
  execute(signal, op->m_callback, 0);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456
}

void
Dbdict::drop_undofile_commit_complete(Signal* signal, SchemaOp* op)
{
  FilePtr f_ptr;
  FilegroupPtr fg_ptr;

  jam();
  c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
  ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));
  Local_file_list list(c_file_pool, fg_ptr.p->m_logfilegroup.m_files);
  list.remove(f_ptr);
  release_object(f_ptr.p->m_obj_ptr_i);
  c_file_hash.release(f_ptr);
  execute(signal, op->m_callback, 0);
16457 16458 16459 16460 16461
}

void
Dbdict::drop_file_abort_start(Signal* signal, SchemaOp* op)
{
16462
  jam();
16463 16464 16465 16466 16467 16468 16469 16470 16471 16472
  send_drop_file(signal, op, DropFileImplReq::Abort);
}

void
Dbdict::send_drop_file(Signal* signal, SchemaOp* op, 
		       DropFileImplReq::RequestInfo type)
{
  DropFileImplReq* req = (DropFileImplReq*)signal->getDataPtrSend();
  FilePtr f_ptr;
  FilegroupPtr fg_ptr;
16473 16474 16475

  jam();
  c_file_pool.getPtr(f_ptr, op->m_obj_ptr_i);
16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488
  ndbrequire(c_filegroup_hash.find(fg_ptr, f_ptr.p->m_filegroup_id));
  
  req->senderData = op->key;
  req->senderRef = reference();
  req->requestInfo = type;
  
  req->file_id = f_ptr.p->key;
  req->filegroup_id = f_ptr.p->m_filegroup_id;
  req->filegroup_version = fg_ptr.p->m_version;
  
  Uint32 ref= 0;
  switch(op->m_obj_type){
  case DictTabInfo::Datafile:
16489 16490
  {
    jam();
16491 16492
    ref = TSMAN_REF;
    break;
16493
  }
16494
  case DictTabInfo::Undofile:
16495 16496
  {
    jam();
16497 16498
    ref = LGMAN_REF;
    break;
16499
  }
16500 16501 16502 16503 16504 16505 16506 16507
  default:
    ndbrequire(false);
  }
  sendSignal(ref, GSN_DROP_FILE_REQ, signal, 
	     DropFileImplReq::SignalLength, JBB);
}

void
16508 16509
Dbdict::execDROP_OBJ_REF(Signal* signal)
{
16510 16511
  DropObjRef * const ref = (DropObjRef*)signal->getDataPtr();
  Ptr<SchemaTransaction> trans_ptr;
16512 16513

  jamEntry();
16514 16515
  ndbrequire(c_Trans.find(trans_ptr, ref->senderData));
  if(ref->errorCode != DropObjRef::NF_FakeErrorREF){
16516
    jam();
16517 16518 16519 16520 16521 16522 16523
    trans_ptr.p->setErrorCode(ref->errorCode);
  }
  Uint32 node = refToNode(ref->senderRef);
  schemaOp_reply(signal, trans_ptr.p, node);
}

void
16524 16525
Dbdict::execDROP_OBJ_CONF(Signal* signal)
{
16526 16527
  DropObjConf * const conf = (DropObjConf*)signal->getDataPtr();
  Ptr<SchemaTransaction> trans_ptr;
16528 16529

  jamEntry();
16530 16531 16532 16533 16534
  ndbrequire(c_Trans.find(trans_ptr, conf->senderData));
  schemaOp_reply(signal, trans_ptr.p, refToNode(conf->senderRef));
}

void
16535 16536
Dbdict::execDROP_FILE_REF(Signal* signal)
{
16537 16538
  DropFileImplRef * ref = (DropFileImplRef*)signal->getDataPtr();
  DropObjRecordPtr op_ptr;
16539 16540

  jamEntry();
16541 16542 16543 16544 16545 16546
  ndbrequire(c_opDropObj.find(op_ptr, ref->senderData));
  op_ptr.p->m_errorCode = ref->errorCode;
  execute(signal, op_ptr.p->m_callback, 0);  
}  

void
16547 16548
Dbdict::execDROP_FILE_CONF(Signal* signal)
{
16549 16550 16551
  DropFileImplConf * rep = 
    (DropFileImplConf*)signal->getDataPtr();
  DropObjRecordPtr op_ptr;
16552 16553

  jamEntry();
16554 16555 16556 16557 16558
  ndbrequire(c_opDropObj.find(op_ptr, rep->senderData));
  execute(signal, op_ptr.p->m_callback, 0);  
}

void
16559 16560
Dbdict::execDROP_FILEGROUP_REF(Signal* signal)
{
16561 16562
  DropFilegroupImplRef * ref = (DropFilegroupImplRef*)signal->getDataPtr();
  DropObjRecordPtr op_ptr;
16563 16564

  jamEntry();
16565 16566 16567 16568 16569 16570
  ndbrequire(c_opDropObj.find(op_ptr, ref->senderData));
  op_ptr.p->m_errorCode = ref->errorCode;
  execute(signal, op_ptr.p->m_callback, 0);  
}  

void
16571 16572
Dbdict::execDROP_FILEGROUP_CONF(Signal* signal)
{
16573 16574 16575
  DropFilegroupImplConf * rep = 
    (DropFilegroupImplConf*)signal->getDataPtr();
  DropObjRecordPtr op_ptr;
16576 16577

  jamEntry();
16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590
  ndbrequire(c_opDropObj.find(op_ptr, rep->senderData));
  execute(signal, op_ptr.p->m_callback, 0);  
}

void
Dbdict::drop_fg_prepare_start(Signal* signal, SchemaOp* op)
{
  FilegroupPtr fg_ptr;
  c_filegroup_pool.getPtr(fg_ptr, op->m_obj_ptr_i);
  
  DictObject * obj = c_obj_pool.getPtr(fg_ptr.p->m_obj_ptr_i);
  if (obj->m_ref_count)
  {
16591
    jam();
16592 16593 16594 16595 16596
    op->m_errorCode = DropFilegroupRef::FilegroupInUse;
    execute(signal, op->m_callback, 0);  
  }
  else
  {
16597
    jam();
16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608
    send_drop_fg(signal, op, DropFilegroupImplReq::Prepare);
  }
}

void
Dbdict::drop_fg_commit_start(Signal* signal, SchemaOp* op)
{
  FilegroupPtr fg_ptr;
  c_filegroup_pool.getPtr(fg_ptr, op->m_obj_ptr_i);
  if (op->m_obj_type == DictTabInfo::LogfileGroup)
  {
16609
    jam(); 
16610 16611 16612 16613
    /**
     * Mark all undofiles as dropped
     */
    Ptr<File> filePtr;
16614
    Local_file_list list(c_file_pool, fg_ptr.p->m_logfilegroup.m_files);
16615 16616 16617
    XSchemaFile * xsf = &c_schemaFile[c_schemaRecord.schemaPage != 0];
    for(list.first(filePtr); !filePtr.isNull(); list.next(filePtr))
    {
16618
      jam();
16619 16620 16621 16622 16623
      Uint32 objId = filePtr.p->key;
      SchemaFile::TableEntry * tableEntry = getTableEntry(xsf, objId);
      tableEntry->m_tableState = SchemaFile::DROP_TABLE_COMMITTED;
      computeChecksum(xsf, objId / NDB_SF_PAGE_ENTRIES);
      release_object(filePtr.p->m_obj_ptr_i);
16624
      c_file_hash.remove(filePtr);
16625 16626 16627 16628 16629 16630
    }
    list.release();
  }
  else if(op->m_obj_type == DictTabInfo::Tablespace)
  {
    FilegroupPtr lg_ptr;
16631
    jam();
16632 16633 16634 16635 16636 16637
    ndbrequire(c_filegroup_hash.
	       find(lg_ptr, 
		    fg_ptr.p->m_tablespace.m_default_logfile_group_id));
    
    decrease_ref_count(lg_ptr.p->m_obj_ptr_i);
  }
16638
  jam(); 
16639 16640 16641 16642 16643 16644 16645 16646
  send_drop_fg(signal, op, DropFilegroupImplReq::Commit);
}

void
Dbdict::drop_fg_commit_complete(Signal* signal, SchemaOp* op)
{
  FilegroupPtr fg_ptr;
  c_filegroup_pool.getPtr(fg_ptr, op->m_obj_ptr_i);
16647 16648

  jam();
16649
  release_object(fg_ptr.p->m_obj_ptr_i);
16650
  c_filegroup_hash.release(fg_ptr);
16651 16652 16653 16654 16655 16656
  execute(signal, op->m_callback, 0);
}

void
Dbdict::drop_fg_abort_start(Signal* signal, SchemaOp* op)
{
16657
  jam();
16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692
  send_drop_fg(signal, op, DropFilegroupImplReq::Abort);
}

void
Dbdict::send_drop_fg(Signal* signal, SchemaOp* op, 
		     DropFilegroupImplReq::RequestInfo type)
{
  DropFilegroupImplReq* req = (DropFilegroupImplReq*)signal->getDataPtrSend();
  
  FilegroupPtr fg_ptr;
  c_filegroup_pool.getPtr(fg_ptr, op->m_obj_ptr_i);
  
  req->senderData = op->key;
  req->senderRef = reference();
  req->requestInfo = type;
  
  req->filegroup_id = fg_ptr.p->key;
  req->filegroup_version = fg_ptr.p->m_version;
  
  Uint32 ref= 0;
  switch(op->m_obj_type){
  case DictTabInfo::Tablespace:
    ref = TSMAN_REF;
    break;
  case DictTabInfo::LogfileGroup:
    ref = LGMAN_REF;
    break;
  default:
    ndbrequire(false);
  }
  
  sendSignal(ref, GSN_DROP_FILEGROUP_REQ, signal, 
	     DropFilegroupImplReq::SignalLength, JBB);
}

16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707
/*
  return 1 if all of the below is true
  a) node in single user mode
  b) senderRef is not a db node
  c) senderRef nodeid is not the singleUserApi
*/
int Dbdict::checkSingleUserMode(Uint32 senderRef)
{
  Uint32 nodeId = refToNode(senderRef);
  return
    getNodeState().getSingleUserMode() &&
    (getNodeInfo(nodeId).m_type != NodeInfo::DB) &&
    (nodeId != getNodeState().getSingleUserApi());
}