NdbScanOperation.cpp 42.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (C) 2003 MySQL AB

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

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

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

17
#include <ndb_global.h>
18 19
#include <Ndb.hpp>
#include <NdbScanOperation.hpp>
unknown's avatar
unknown committed
20
#include <NdbIndexScanOperation.hpp>
21 22 23 24 25 26
#include <NdbConnection.hpp>
#include <NdbResultSet.hpp>
#include "NdbApiSignal.hpp"
#include <NdbOut.hpp>
#include "NdbDictionaryImpl.hpp"

unknown's avatar
unknown committed
27 28 29 30 31 32 33 34
#include <NdbRecAttr.hpp>
#include <NdbReceiver.hpp>

#include <stdlib.h>
#include <NdbSqlUtil.hpp>

#include <signaldata/ScanTab.hpp>
#include <signaldata/KeyInfo.hpp>
35
#include <signaldata/AttrInfo.hpp>
unknown's avatar
unknown committed
36 37
#include <signaldata/TcKeyReq.hpp>

38
NdbScanOperation::NdbScanOperation(Ndb* aNdb) :
unknown's avatar
unknown committed
39 40 41
  NdbOperation(aNdb),
  m_resultSet(0),
  m_transConnection(NULL)
42
{
unknown's avatar
unknown committed
43 44 45 46 47 48 49
  theParallelism = 0;
  m_allocated_receivers = 0;
  m_prepared_receivers = 0;
  m_api_receivers = 0;
  m_conf_receivers = 0;
  m_sent_receivers = 0;
  m_receivers = 0;
unknown's avatar
unknown committed
50
  m_array = new Uint32[1]; // skip if on delete in fix_receivers
unknown's avatar
unknown committed
51
  theSCAN_TABREQ = 0;
52 53 54 55
}

NdbScanOperation::~NdbScanOperation()
{
unknown's avatar
unknown committed
56
  for(Uint32 i = 0; i<m_allocated_receivers; i++){
unknown's avatar
unknown committed
57
    m_receivers[i]->release();
unknown's avatar
unknown committed
58 59 60
    theNdb->releaseNdbScanRec(m_receivers[i]);
  }
  delete[] m_array;
unknown's avatar
unknown committed
61 62
  if (m_resultSet)
    delete m_resultSet;
63 64
}

unknown's avatar
unknown committed
65 66
NdbResultSet* 
NdbScanOperation::getResultSet()
67
{
unknown's avatar
unknown committed
68 69 70 71
  if (!m_resultSet)
    m_resultSet = new NdbResultSet(this);

  return m_resultSet;
72 73
}

unknown's avatar
unknown committed
74 75


76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
void
NdbScanOperation::setErrorCode(int aErrorCode){
  NdbConnection* tmp = theNdbCon;
  theNdbCon = m_transConnection;
  NdbOperation::setErrorCode(aErrorCode);
  theNdbCon = tmp;
}

void
NdbScanOperation::setErrorCodeAbort(int aErrorCode){
  NdbConnection* tmp = theNdbCon;
  theNdbCon = m_transConnection;
  NdbOperation::setErrorCodeAbort(aErrorCode);
  theNdbCon = tmp;
}

  
/*****************************************************************************
 * int init();
 *
 * Return Value:  Return 0 : init was successful.
 *                Return -1: In all other case.  
 * Remark:        Initiates operation record after allocation.
 *****************************************************************************/
int
unknown's avatar
unknown committed
101
NdbScanOperation::init(const NdbTableImpl* tab, NdbConnection* myConnection)
102 103 104 105
{
  m_transConnection = myConnection;
  //NdbConnection* aScanConnection = theNdb->startTransaction(myConnection);
  NdbConnection* aScanConnection = theNdb->hupp(myConnection);
106 107
  if (!aScanConnection){
    setErrorCodeAbort(theNdb->getNdbError().code);
108
    return -1;
109
  }
110

unknown's avatar
unknown committed
111 112
  // NOTE! The hupped trans becomes the owner of the operation
  if(NdbOperation::init(tab, aScanConnection) != 0){
113 114
    return -1;
  }
unknown's avatar
unknown committed
115 116 117 118 119
  
  initInterpreter();
  
  theStatus = GetValue;
  theOperationType = OpenScanRequest;
unknown's avatar
unknown committed
120 121
  theNdbCon->theMagicNumber = 0xFE11DF;

122 123 124
  return 0;
}

unknown's avatar
unknown committed
125 126
NdbResultSet* NdbScanOperation::readTuples(NdbScanOperation::LockMode lm,
					   Uint32 batch, 
unknown's avatar
unknown committed
127
					   Uint32 parallel)
128
{
unknown's avatar
unknown committed
129
  m_ordered = 0;
130

unknown's avatar
unknown committed
131
  Uint32 fragCount = m_currentTable->m_fragmentCount;
132

unknown's avatar
unknown committed
133
  if (parallel > fragCount || parallel == 0) {
unknown's avatar
unknown committed
134
     parallel = fragCount;
unknown's avatar
unknown committed
135
  }
unknown's avatar
unknown committed
136 137 138 139 140 141 142 143 144

  // It is only possible to call openScan if 
  //  1. this transcation don't already  contain another scan operation
  //  2. this transaction don't already contain other operations
  //  3. theScanOp contains a NdbScanOperation
  if (theNdbCon->theScanningOp != NULL){
    setErrorCode(4605);
    return 0;
  }
145

unknown's avatar
unknown committed
146
  theNdbCon->theScanningOp = this;
unknown's avatar
unknown committed
147
  theLockMode = lm;
148

unknown's avatar
unknown committed
149 150 151 152 153 154 155 156 157 158 159 160
  bool lockExcl, lockHoldMode, readCommitted;
  switch(lm){
  case NdbScanOperation::LM_Read:
    lockExcl = false;
    lockHoldMode = true;
    readCommitted = false;
    break;
  case NdbScanOperation::LM_Exclusive:
    lockExcl = true;
    lockHoldMode = true;
    readCommitted = false;
    break;
unknown's avatar
unknown committed
161
  case NdbScanOperation::LM_CommittedRead:
unknown's avatar
unknown committed
162 163 164 165 166 167 168 169
    lockExcl = false;
    lockHoldMode = false;
    readCommitted = true;
    break;
  default:
    setErrorCode(4003);
    return 0;
  }
170

unknown's avatar
unknown committed
171
  m_keyInfo = lockExcl ? 1 : 0;
unknown's avatar
unknown committed
172 173

  bool range = false;
174 175 176 177 178 179 180 181 182
  if (m_accessTable->m_indexType == NdbDictionary::Index::OrderedIndex ||
      m_accessTable->m_indexType == NdbDictionary::Index::UniqueOrderedIndex){
    if (m_currentTable == m_accessTable){
      // Old way of scanning indexes, should not be allowed
      m_currentTable = theNdb->theDictionary->
	getTable(m_currentTable->m_primaryTable.c_str());
      assert(m_currentTable != NULL);
    }
    assert (m_currentTable != m_accessTable);
unknown's avatar
unknown committed
183
    // Modify operation state
184
    theStatus = GetValue;
unknown's avatar
unknown committed
185 186 187 188
    theOperationType  = OpenRangeScanRequest;
    range = true;
  }
  
unknown's avatar
unknown committed
189
  theParallelism = parallel;
190

unknown's avatar
unknown committed
191
  if(fix_receivers(parallel) == -1){
unknown's avatar
unknown committed
192 193 194 195
    setErrorCodeAbort(4000);
    return 0;
  }
  
unknown's avatar
unknown committed
196
  theSCAN_TABREQ = (!theSCAN_TABREQ ? theNdb->getSignal() : theSCAN_TABREQ);
unknown's avatar
unknown committed
197 198 199 200 201 202 203 204 205 206 207 208 209
  if (theSCAN_TABREQ == NULL) {
    setErrorCodeAbort(4000);
    return 0;
  }//if
  
  ScanTabReq * req = CAST_PTR(ScanTabReq, theSCAN_TABREQ->getDataPtrSend());
  req->apiConnectPtr = theNdbCon->theTCConPtr;
  req->tableId = m_accessTable->m_tableId;
  req->tableSchemaVersion = m_accessTable->m_version;
  req->storedProcId = 0xFFFF;
  req->buddyConPtr = theNdbCon->theBuddyConPtr;
  
  Uint32 reqInfo = 0;
unknown's avatar
unknown committed
210
  ScanTabReq::setParallelism(reqInfo, parallel);
unknown's avatar
unknown committed
211
  ScanTabReq::setScanBatch(reqInfo, 0);
unknown's avatar
unknown committed
212 213 214 215 216
  ScanTabReq::setLockMode(reqInfo, lockExcl);
  ScanTabReq::setHoldLockFlag(reqInfo, lockHoldMode);
  ScanTabReq::setReadCommittedFlag(reqInfo, readCommitted);
  ScanTabReq::setRangeScanFlag(reqInfo, range);
  req->requestInfo = reqInfo;
217

unknown's avatar
unknown committed
218 219 220
  Uint64 transId = theNdbCon->getTransactionId();
  req->transId1 = (Uint32) transId;
  req->transId2 = (Uint32) (transId >> 32);
221

222
  NdbApiSignal* tSignal = 
unknown's avatar
unknown committed
223 224 225 226
    theFirstKEYINFO;

  theFirstKEYINFO = (tSignal ? tSignal : tSignal = theNdb->getSignal());
  theLastKEYINFO = tSignal;
227 228 229 230
  
  tSignal->setSignal(GSN_KEYINFO);
  theKEYINFOptr = ((KeyInfo*)tSignal->getDataPtrSend())->keyData;
  theTotalNrOfKeyWordInSignal= 0;
231

232
  getFirstATTRINFOScan();
unknown's avatar
unknown committed
233
  return getResultSet();
234 235
}

unknown's avatar
unknown committed
236
int
unknown's avatar
unknown committed
237 238 239 240 241 242 243 244 245 246
NdbScanOperation::fix_receivers(Uint32 parallel){
  assert(parallel > 0);
  if(parallel > m_allocated_receivers){
    const Uint32 sz = parallel * (4*sizeof(char*)+sizeof(Uint32));

    Uint32 * tmp = new Uint32[(sz+3)/4];
    // Save old receivers
    memcpy(tmp+parallel, m_receivers, m_allocated_receivers*sizeof(char*));
    delete[] m_array;
    m_array = tmp;
unknown's avatar
unknown committed
247
    
unknown's avatar
unknown committed
248 249 250 251 252
    m_prepared_receivers = tmp;
    m_receivers = (NdbReceiver**)(tmp + parallel);
    m_api_receivers = m_receivers + parallel;
    m_conf_receivers = m_api_receivers + parallel;
    m_sent_receivers = m_conf_receivers + parallel;
unknown's avatar
unknown committed
253

unknown's avatar
unknown committed
254
    // Only get/init "new" receivers
unknown's avatar
unknown committed
255
    NdbReceiver* tScanRec;
unknown's avatar
unknown committed
256
    for (Uint32 i = m_allocated_receivers; i < parallel; i ++) {
unknown's avatar
unknown committed
257 258 259 260 261 262
      tScanRec = theNdb->getNdbScanRec();
      if (tScanRec == NULL) {
	setErrorCodeAbort(4000);
	return -1;
      }//if
      m_receivers[i] = tScanRec;
unknown's avatar
unknown committed
263
      tScanRec->init(NdbReceiver::NDB_SCANRECEIVER, this);
unknown's avatar
unknown committed
264
    }
unknown's avatar
unknown committed
265
    m_allocated_receivers = parallel;
unknown's avatar
unknown committed
266
  }
unknown's avatar
unknown committed
267
  
unknown's avatar
unknown committed
268
  reset_receivers(parallel, 0);
269 270 271
  return 0;
}

unknown's avatar
unknown committed
272 273 274 275 276
/**
 * Move receiver from send array to conf:ed array
 */
void
NdbScanOperation::receiver_delivered(NdbReceiver* tRec){
unknown's avatar
unknown committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  if(theError.code == 0){
    Uint32 idx = tRec->m_list_index;
    Uint32 last = m_sent_receivers_count - 1;
    if(idx != last){
      NdbReceiver * move = m_sent_receivers[last];
      m_sent_receivers[idx] = move;
      move->m_list_index = idx;
    }
    m_sent_receivers_count = last;
    
    last = m_conf_receivers_count;
    m_conf_receivers[last] = tRec;
    m_conf_receivers_count = last + 1;
    tRec->m_list_index = last;
    tRec->m_current_row = 0;
unknown's avatar
unknown committed
292
  }
293 294
}

unknown's avatar
unknown committed
295 296 297 298 299
/**
 * Remove receiver as it's completed
 */
void
NdbScanOperation::receiver_completed(NdbReceiver* tRec){
unknown's avatar
unknown committed
300 301 302 303 304 305 306 307 308
  if(theError.code == 0){
    Uint32 idx = tRec->m_list_index;
    Uint32 last = m_sent_receivers_count - 1;
    if(idx != last){
      NdbReceiver * move = m_sent_receivers[last];
      m_sent_receivers[idx] = move;
      move->m_list_index = idx;
    }
    m_sent_receivers_count = last;
unknown's avatar
unknown committed
309
  }
310 311
}

unknown's avatar
unknown committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325
/*****************************************************************************
 * int getFirstATTRINFOScan( U_int32 aData )
 *
 * Return Value:  Return 0:   Successful
 *      	  Return -1:  All other cases
 * Parameters:    None: 	   Only allocate the first signal.
 * Remark:        When a scan is defined we need to use this method instead 
 *                of insertATTRINFO for the first signal. 
 *                This is because we need not to mess up the code in 
 *                insertATTRINFO with if statements since we are not 
 *                interested in the TCKEYREQ signal.
 *****************************************************************************/
int
NdbScanOperation::getFirstATTRINFOScan()
326
{
unknown's avatar
unknown committed
327
  NdbApiSignal* tSignal;
328

unknown's avatar
unknown committed
329 330 331 332 333 334 335 336 337 338 339
  tSignal = theNdb->getSignal();
  if (tSignal == NULL){
    setErrorCodeAbort(4000);      
    return -1;    
  }
  tSignal->setSignal(m_attrInfoGSN);
  theAI_LenInCurrAI = 8;
  theATTRINFOptr = &tSignal->getDataPtrSend()[8];
  theFirstATTRINFO = tSignal;
  theCurrentATTRINFO = tSignal;
  theCurrentATTRINFO->next(NULL);
340 341 342 343

  return 0;
}

unknown's avatar
unknown committed
344 345 346 347 348 349
/**
 * Constats for theTupleKeyDefined[][0]
 */
#define SETBOUND_EQ 1
#define FAKE_PTR 2
#define API_PTR 3
350 351


unknown's avatar
unknown committed
352 353 354 355
/*
 * After setBound() are done, move the accumulated ATTRINFO signals to
 * a separate list.  Then continue with normal scan.
 */
356
#if 0
unknown's avatar
unknown committed
357
int
358
NdbIndexScanOperation::saveBoundATTRINFO()
359
{
unknown's avatar
unknown committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  theCurrentATTRINFO->setLength(theAI_LenInCurrAI);
  theBoundATTRINFO = theFirstATTRINFO;
  theTotalBoundAI_Len = theTotalCurrAI_Len;
  theTotalCurrAI_Len = 5;
  theBoundATTRINFO->setData(theTotalBoundAI_Len, 4);
  theBoundATTRINFO->setData(0, 5);
  theBoundATTRINFO->setData(0, 6);
  theBoundATTRINFO->setData(0, 7);
  theBoundATTRINFO->setData(0, 8);
  theStatus = GetValue;

  int res = getFirstATTRINFOScan();

  /**
   * Define each key with getValue (if ordered)
   *   unless the one's with EqBound
   */
  if(!res && m_ordered){
378 379 380 381 382 383 384 385 386 387 388 389

    /**
     * If setBound EQ
     */
    Uint32 i = 0;
    while(theTupleKeyDefined[i][0] == SETBOUND_EQ)
      i++;
    
    
    Uint32 cnt = m_accessTable->getNoOfColumns() - 1;
    m_sort_columns = cnt - i;
    for(; i<cnt; i++){
unknown's avatar
unknown committed
390 391
      const NdbColumnImpl* key = m_accessTable->m_index->m_columns[i];
      const NdbColumnImpl* col = m_currentTable->getColumn(key->m_keyInfoPos);
unknown's avatar
unknown committed
392 393
      NdbRecAttr* tmp = NdbScanOperation::getValue_impl(col, (char*)-1);
      UintPtr newVal = UintPtr(tmp);
394 395
      theTupleKeyDefined[i][0] = FAKE_PTR;
      theTupleKeyDefined[i][1] = (newVal & 0xFFFFFFFF);
unknown's avatar
unknown committed
396
#if (SIZEOF_CHARP == 8)
397
      theTupleKeyDefined[i][2] = (newVal >> 32);
unknown's avatar
unknown committed
398 399 400 401
#endif
    }
  }
  return res;
402
}
403
#endif
404

unknown's avatar
unknown committed
405
#define WAITFOR_SCAN_TIMEOUT 120000
406

unknown's avatar
unknown committed
407 408 409 410 411
int
NdbScanOperation::executeCursor(int nodeId){
  NdbConnection * tCon = theNdbCon;
  TransporterFacade* tp = TransporterFacade::instance();
  Guard guard(tp->theMutexPtr);
unknown's avatar
unknown committed
412 413

  Uint32 magic = tCon->theMagicNumber;
unknown's avatar
unknown committed
414
  Uint32 seq = tCon->theNodeSequence;
unknown's avatar
unknown committed
415

unknown's avatar
unknown committed
416 417 418
  if (tp->get_node_alive(nodeId) &&
      (tp->getNodeSequence(nodeId) == seq)) {

unknown's avatar
unknown committed
419 420 421 422
    /**
     * Only call prepareSendScan first time (incase of restarts)
     *   - check with theMagicNumber
     */
unknown's avatar
unknown committed
423
    tCon->theMagicNumber = 0x37412619;
unknown's avatar
unknown committed
424 425 426 427
    if(magic != 0x37412619 && 
       prepareSendScan(tCon->theTCConPtr, tCon->theTransactionId) == -1)
      return -1;
    
unknown's avatar
unknown committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    
    if (doSendScan(nodeId) == -1)
      return -1;

    return 0;
  } else {
    if (!(tp->get_node_stopping(nodeId) &&
	  (tp->getNodeSequence(nodeId) == seq))){
      TRACE_DEBUG("The node is hard dead when attempting to start a scan");
      setErrorCode(4029);
      tCon->theReleaseOnClose = true;
    } else {
      TRACE_DEBUG("The node is stopping when attempting to start a scan");
      setErrorCode(4030);
    }//if
unknown's avatar
unknown committed
443
    tCon->theCommitStatus = NdbConnection::Aborted;
unknown's avatar
unknown committed
444 445
  }//if
  return -1;
446 447
}

448 449
#define DEBUG_NEXT_RESULT 0

unknown's avatar
unknown committed
450
int NdbScanOperation::nextResult(bool fetchAllowed)
451
{
unknown's avatar
unknown committed
452 453 454 455 456 457 458 459 460
  if(m_ordered)
    return ((NdbIndexScanOperation*)this)->next_result_ordered(fetchAllowed);
  
  /**
   * Check current receiver
   */
  int retVal = 2;
  Uint32 idx = m_current_api_receiver;
  Uint32 last = m_api_receivers_count;
461 462 463

  if(DEBUG_NEXT_RESULT)
    ndbout_c("nextResult(%d) idx=%d last=%d", fetchAllowed, idx, last);
unknown's avatar
unknown committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  
  /**
   * Check next buckets
   */
  for(; idx < last; idx++){
    NdbReceiver* tRec = m_api_receivers[idx];
    if(tRec->nextResult()){
      tRec->copyout(theReceiver);      
      retVal = 0;
      break;
    }
  }
    
  /**
   * We have advanced atleast one bucket
   */
unknown's avatar
unknown committed
480
  if(!fetchAllowed || !retVal){
unknown's avatar
unknown committed
481
    m_current_api_receiver = idx;
unknown's avatar
unknown committed
482
    if(DEBUG_NEXT_RESULT) ndbout_c("return %d", retVal);
unknown's avatar
unknown committed
483 484
    return retVal;
  }
unknown's avatar
unknown committed
485
  
unknown's avatar
unknown committed
486 487 488 489 490 491 492 493 494 495
  Uint32 nodeId = theNdbCon->theDBnode;
  TransporterFacade* tp = TransporterFacade::instance();
  Guard guard(tp->theMutexPtr);
  Uint32 seq = theNdbCon->theNodeSequence;
  if(seq == tp->getNodeSequence(nodeId) && send_next_scan(idx, false) == 0){
      
    idx = m_current_api_receiver;
    last = m_api_receivers_count;
      
    do {
unknown's avatar
unknown committed
496 497
      if(theError.code){
	setErrorCode(theError.code);
unknown's avatar
unknown committed
498
	if(DEBUG_NEXT_RESULT) ndbout_c("return -1");
unknown's avatar
unknown committed
499 500 501
	return -1;
      }
      
unknown's avatar
unknown committed
502 503
      Uint32 cnt = m_conf_receivers_count;
      Uint32 sent = m_sent_receivers_count;
504 505 506

      if(DEBUG_NEXT_RESULT)
	ndbout_c("idx=%d last=%d cnt=%d sent=%d", idx, last, cnt, sent);
unknown's avatar
unknown committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
	
      if(cnt > 0){
	/**
	 * Just move completed receivers
	 */
	memcpy(m_api_receivers+last, m_conf_receivers, cnt * sizeof(char*));
	last += cnt;
	m_conf_receivers_count = 0;
      } else if(retVal == 2 && sent > 0){
	/**
	 * No completed...
	 */
	theNdb->theWaiter.m_node = nodeId;
	theNdb->theWaiter.m_state = WAIT_SCAN;
	int return_code = theNdb->receiveResponse(WAITFOR_SCAN_TIMEOUT);
	if (return_code == 0 && seq == tp->getNodeSequence(nodeId)) {
	  continue;
	} else {
	  idx = last;
unknown's avatar
unknown committed
526
	  retVal = -2; //return_code;
unknown's avatar
unknown committed
527 528 529 530 531
	}
      } else if(retVal == 2){
	/**
	 * No completed & no sent -> EndOfData
	 */
unknown's avatar
unknown committed
532 533 534
	theError.code = -1; // make sure user gets error if he tries again
	if(DEBUG_NEXT_RESULT) ndbout_c("return 1");
	return 1;
535
      }
unknown's avatar
unknown committed
536 537 538 539 540 541 542 543 544 545 546
	
      if(retVal == 0)
	break;
	
      for(; idx < last; idx++){
	NdbReceiver* tRec = m_api_receivers[idx];
	if(tRec->nextResult()){
	  tRec->copyout(theReceiver);      
	  retVal = 0;
	  break;
	}
547
      }
unknown's avatar
unknown committed
548 549 550
    } while(retVal == 2);
  } else {
    retVal = -3;
551
  }
unknown's avatar
unknown committed
552 553 554 555 556 557 558 559
    
  m_api_receivers_count = last;
  m_current_api_receiver = idx;
    
  switch(retVal){
  case 0:
  case 1:
  case 2:
unknown's avatar
unknown committed
560
    if(DEBUG_NEXT_RESULT) ndbout_c("return %d", retVal);
unknown's avatar
unknown committed
561 562 563 564 565 566 567 568
    return retVal;
  case -1:
    setErrorCode(4008); // Timeout
    break;
  case -2:
    setErrorCode(4028); // Node fail
    break;
  case -3: // send_next_scan -> return fail (set error-code self)
unknown's avatar
unknown committed
569 570
    if(theError.code == 0)
      setErrorCode(4028); // seq changed = Node fail
unknown's avatar
unknown committed
571 572 573 574 575
    break;
  }
    
  theNdbCon->theTransactionIsStarted = false;
  theNdbCon->theReleaseOnClose = true;
unknown's avatar
unknown committed
576
  if(DEBUG_NEXT_RESULT) ndbout_c("return -1", retVal);
unknown's avatar
unknown committed
577
  return -1;
578 579
}

unknown's avatar
unknown committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
int
NdbScanOperation::send_next_scan(Uint32 cnt, bool stopScanFlag){  
  if(cnt > 0 || stopScanFlag){
    NdbApiSignal tSignal(theNdb->theMyRef);
    tSignal.setSignal(GSN_SCAN_NEXTREQ);
    
    Uint32* theData = tSignal.getDataPtrSend();
    theData[0] = theNdbCon->theTCConPtr;
    theData[1] = stopScanFlag == true ? 1 : 0;
    Uint64 transId = theNdbCon->theTransactionId;
    theData[2] = transId;
    theData[3] = (Uint32) (transId >> 32);
    
    /**
     * Prepare ops
     */
    Uint32 last = m_sent_receivers_count;
    Uint32 * prep_array = (cnt > 21 ? m_prepared_receivers : theData + 4);
    for(Uint32 i = 0; i<cnt; i++){
      NdbReceiver * tRec = m_api_receivers[i];
      m_sent_receivers[last+i] = tRec;
      tRec->m_list_index = last+i;
      prep_array[i] = tRec->m_tcPtrI;
      tRec->prepareSend();
    }
    memcpy(&m_api_receivers[0], &m_api_receivers[cnt], cnt * sizeof(char*));
    
    Uint32 nodeId = theNdbCon->theDBnode;
    TransporterFacade * tp = TransporterFacade::instance();
    int ret;
    if(cnt > 21){
      tSignal.setLength(4);
      LinearSectionPtr ptr[3];
      ptr[0].p = prep_array;
      ptr[0].sz = cnt;
      ret = tp->sendFragmentedSignal(&tSignal, nodeId, ptr, 1);
    } else {
      tSignal.setLength(4+cnt);
      ret = tp->sendSignal(&tSignal, nodeId);
    }

    m_sent_receivers_count = last + cnt + stopScanFlag;
    m_api_receivers_count -= cnt;
    m_current_api_receiver = 0;

    return ret;
626
  }
unknown's avatar
unknown committed
627
  return 0;
628 629 630 631 632 633
}

int 
NdbScanOperation::prepareSend(Uint32  TC_ConnectPtr, Uint64  TransactionId)
{
  printf("NdbScanOperation::prepareSend\n");
unknown's avatar
unknown committed
634
  abort();
635 636 637 638 639 640 641 642 643 644 645 646
  return 0;
}

int 
NdbScanOperation::doSend(int ProcessorId)
{
  printf("NdbScanOperation::doSend\n");
  return 0;
}

void NdbScanOperation::closeScan()
{
647
  if(m_transConnection){
unknown's avatar
unknown committed
648 649 650 651 652 653 654 655 656 657
    if(DEBUG_NEXT_RESULT)
      ndbout_c("closeScan() theError.code = %d "
	       "m_api_receivers_count = %d "
	       "m_conf_receivers_count = %d "
	       "m_sent_receivers_count = %d",
	       theError.code, 
	       m_api_receivers_count,
	       m_conf_receivers_count,
	       m_sent_receivers_count);
    
unknown's avatar
unknown committed
658 659
    TransporterFacade* tp = TransporterFacade::instance();
    Guard guard(tp->theMutexPtr);
660
    close_impl(tp);
unknown's avatar
unknown committed
661
    
unknown's avatar
unknown committed
662
  } while(0);
unknown's avatar
unknown committed
663
  
unknown's avatar
unknown committed
664 665 666 667 668 669
  theNdbCon->theScanningOp = 0;
  theNdb->closeTransaction(theNdbCon);
  
  theNdbCon = 0;
  m_transConnection = NULL;
}
670

unknown's avatar
unknown committed
671
void
unknown's avatar
unknown committed
672
NdbScanOperation::execCLOSE_SCAN_REP(){
unknown's avatar
unknown committed
673 674 675
  m_api_receivers_count = 0;
  m_conf_receivers_count = 0;
  m_sent_receivers_count = 0;
676 677
}

unknown's avatar
unknown committed
678
void NdbScanOperation::release()
679
{
unknown's avatar
unknown committed
680 681 682 683 684
  if(theNdbCon != 0 || m_transConnection != 0){
    closeScan();
  }
  for(Uint32 i = 0; i<m_allocated_receivers; i++){
    m_receivers[i]->release();
685
  }
unknown's avatar
unknown committed
686 687 688 689 690 691
  if(theSCAN_TABREQ)
  {
    theNdb->releaseSignal(theSCAN_TABREQ);
    theSCAN_TABREQ = 0;
  }
  NdbOperation::release();
692 693
}

unknown's avatar
unknown committed
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
/***************************************************************************
int prepareSendScan(Uint32 aTC_ConnectPtr,
                    Uint64 aTransactionId)

Return Value:   Return 0 : preparation of send was succesful.
                Return -1: In all other case.   
Parameters:     aTC_ConnectPtr: the Connect pointer to TC.
		aTransactionId:	the Transaction identity of the transaction.
Remark:         Puts the the final data into ATTRINFO signal(s)  after this 
                we know the how many signal to send and their sizes
***************************************************************************/
int NdbScanOperation::prepareSendScan(Uint32 aTC_ConnectPtr,
				      Uint64 aTransactionId){

  if (theInterpretIndicator != 1 ||
      (theOperationType != OpenScanRequest &&
       theOperationType != OpenRangeScanRequest)) {
    setErrorCodeAbort(4005);
    return -1;
  }
714

unknown's avatar
unknown committed
715
  theErrorLine = 0;
716

unknown's avatar
unknown committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
  // In preapareSendInterpreted we set the sizes (word 4-8) in the
  // first ATTRINFO signal.
  if (prepareSendInterpreted() == -1)
    return -1;
  
  if(m_ordered){
    ((NdbIndexScanOperation*)this)->fix_get_values();
  }
  
  theCurrentATTRINFO->setLength(theAI_LenInCurrAI);

  /**
   * Prepare all receivers
   */
  theReceiver.prepareSend();
  bool keyInfo = m_keyInfo;
  Uint32 key_size = keyInfo ? m_currentTable->m_keyLenInWords : 0;
unknown's avatar
unknown committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
  /**
   * The number of records sent by each LQH is calculated and the kernel
   * is informed of this number by updating the SCAN_TABREQ signal
   */
  Uint32 batch_size, batch_byte_size, first_batch_size;
  theReceiver.calculate_batch_size(key_size,
                                   theParallelism,
                                   batch_size,
                                   batch_byte_size,
                                   first_batch_size);
  ScanTabReq * req = CAST_PTR(ScanTabReq, theSCAN_TABREQ->getDataPtrSend());
  ScanTabReq::setScanBatch(req->requestInfo, batch_size);
  req->batch_byte_size= batch_byte_size;
  req->first_batch_size= first_batch_size;

unknown's avatar
unknown committed
749 750 751 752 753 754 755 756
  /**
   * Set keyinfo flag
   *  (Always keyinfo when using blobs)
   */
  Uint32 reqInfo = req->requestInfo;
  ScanTabReq::setKeyinfoFlag(reqInfo, keyInfo);
  req->requestInfo = reqInfo;
  
unknown's avatar
unknown committed
757
  for(Uint32 i = 0; i<theParallelism; i++){
unknown's avatar
unknown committed
758
    m_receivers[i]->do_get_value(&theReceiver, batch_size, key_size);
759
  }
unknown's avatar
unknown committed
760
  return 0;
761 762
}

unknown's avatar
unknown committed
763
/*****************************************************************************
unknown's avatar
unknown committed
764 765 766 767 768 769
int doSend()

Return Value:   Return >0 : send was succesful, returns number of signals sent
                Return -1: In all other case.   
Parameters:     aProcessorId: Receiving processor node
Remark:         Sends the ATTRINFO signal(s)
unknown's avatar
unknown committed
770
*****************************************************************************/
unknown's avatar
unknown committed
771 772
int
NdbScanOperation::doSendScan(int aProcessorId)
773
{
unknown's avatar
unknown committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
  Uint32 tSignalCount = 0;
  NdbApiSignal* tSignal;
 
  if (theInterpretIndicator != 1 ||
      (theOperationType != OpenScanRequest &&
       theOperationType != OpenRangeScanRequest)) {
      setErrorCodeAbort(4005);
      return -1;
  }
  
  assert(theSCAN_TABREQ != NULL);
  tSignal = theSCAN_TABREQ;
  if (tSignal->setSignal(GSN_SCAN_TABREQ) == -1) {
    setErrorCode(4001);
    return -1;
  }
790 791 792 793 794 795
  
  Uint32 tupKeyLen = theTupKeyLen;
  Uint32 len = theTotalNrOfKeyWordInSignal;
  Uint32 aTC_ConnectPtr = theNdbCon->theTCConPtr;
  Uint64 transId = theNdbCon->theTransactionId;
  
unknown's avatar
unknown committed
796 797 798 799
  // Update the "attribute info length in words" in SCAN_TABREQ before 
  // sending it. This could not be done in openScan because 
  // we created the ATTRINFO signals after the SCAN_TABREQ signal.
  ScanTabReq * const req = CAST_PTR(ScanTabReq, tSignal->getDataPtrSend());
800 801
  req->attrLenKeyLen = (tupKeyLen << 16) | theTotalCurrAI_Len;
  
unknown's avatar
unknown committed
802
  TransporterFacade *tp = TransporterFacade::instance();
unknown's avatar
unknown committed
803 804 805 806 807 808 809
  LinearSectionPtr ptr[3];
  ptr[0].p = m_prepared_receivers;
  ptr[0].sz = theParallelism;
  if (tp->sendFragmentedSignal(tSignal, aProcessorId, ptr, 1) == -1) {
    setErrorCode(4002);
    return -1;
  } 
810 811

  if (tupKeyLen > 0){
unknown's avatar
unknown committed
812
    // must have at least one signal since it contains attrLen for bounds
813 814 815 816 817 818 819 820 821 822 823 824 825 826
    assert(theLastKEYINFO != NULL);
    tSignal = theLastKEYINFO;
    tSignal->setLength(KeyInfo::HeaderLength + theTotalNrOfKeyWordInSignal);
    
    assert(theFirstKEYINFO != NULL);
    tSignal = theFirstKEYINFO;
    
    NdbApiSignal* last;
    do {
      KeyInfo * keyInfo = CAST_PTR(KeyInfo, tSignal->getDataPtrSend());
      keyInfo->connectPtr = aTC_ConnectPtr;
      keyInfo->transId[0] = Uint32(transId);
      keyInfo->transId[1] = Uint32(transId >> 32);
      
unknown's avatar
unknown committed
827
      if (tp->sendSignal(tSignal,aProcessorId) == -1){
828 829
	setErrorCode(4002);
	return -1;
unknown's avatar
unknown committed
830
      }
831
      
unknown's avatar
unknown committed
832
      tSignalCount++;
833
      last = tSignal;
unknown's avatar
unknown committed
834
      tSignal = tSignal->next();
835
    } while(last != theLastKEYINFO);
836
  }
unknown's avatar
unknown committed
837 838 839
  
  tSignal = theFirstATTRINFO;
  while (tSignal != NULL) {
840 841 842 843 844
    AttrInfo * attrInfo = CAST_PTR(AttrInfo, tSignal->getDataPtrSend());
    attrInfo->connectPtr = aTC_ConnectPtr;
    attrInfo->transId[0] = Uint32(transId);
    attrInfo->transId[1] = Uint32(transId >> 32);
    
unknown's avatar
unknown committed
845 846 847 848 849 850 851 852 853 854 855
    if (tp->sendSignal(tSignal,aProcessorId) == -1){
      setErrorCode(4002);
      return -1;
    }
    tSignalCount++;
    tSignal = tSignal->next();
  }    
  theStatus = WaitResponse;  
  return tSignalCount;
}//NdbOperation::doSendScan()

unknown's avatar
unknown committed
856
/*****************************************************************************
unknown's avatar
unknown committed
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
 * NdbOperation* takeOverScanOp(NdbConnection* updateTrans);
 *
 * Parameters:     The update transactions NdbConnection pointer.
 * Return Value:   A reference to the transferred operation object 
 *                   or NULL if no success.
 * Remark:         Take over the scanning transactions NdbOperation 
 *                 object for a tuple to an update transaction, 
 *                 which is the last operation read in nextScanResult()
 *		   (theNdbCon->thePreviousScanRec)
 *
 *     FUTURE IMPLEMENTATION:   (This note was moved from header file.)
 *     In the future, it will even be possible to transfer 
 *     to a NdbConnection on another Ndb-object.  
 *     In this case the receiving NdbConnection-object must call 
 *     a method receiveOpFromScan to actually receive the information.  
 *     This means that the updating transactions can be placed
 *     in separate threads and thus increasing the parallelism during
 *     the scan process. 
unknown's avatar
unknown committed
875
 ****************************************************************************/
unknown's avatar
unknown committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
int
NdbScanOperation::getKeyFromKEYINFO20(Uint32* data, unsigned size)
{
  Uint32 idx = m_current_api_receiver;
  Uint32 last = m_api_receivers_count;

  Uint32 row;
  NdbReceiver * tRec;
  NdbRecAttr * tRecAttr;
  if(idx < last && (tRec = m_api_receivers[idx]) 
     && ((row = tRec->m_current_row) <= tRec->m_defined_rows)
     && (tRecAttr = tRec->m_rows[row-1])){

    const Uint32 * src = (Uint32*)tRecAttr->aRef();
    memcpy(data, src, 4*size);
    return 0;
  }
  return -1;
}

unknown's avatar
unknown committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
NdbOperation*
NdbScanOperation::takeOverScanOp(OperationType opType, NdbConnection* pTrans){
  
  Uint32 idx = m_current_api_receiver;
  Uint32 last = m_api_receivers_count;

  Uint32 row;
  NdbReceiver * tRec;
  NdbRecAttr * tRecAttr;
  if(idx < last && (tRec = m_api_receivers[idx]) 
     && ((row = tRec->m_current_row) <= tRec->m_defined_rows)
     && (tRecAttr = tRec->m_rows[row-1])){
    
    NdbOperation * newOp = pTrans->getNdbOperation(m_currentTable);
    if (newOp == NULL){
      return NULL;
    }
unknown's avatar
unknown committed
913
    pTrans->theSimpleState = 0;
unknown's avatar
unknown committed
914 915 916 917 918 919 920 921 922 923 924 925
    
    const Uint32 len = (tRecAttr->attrSize() * tRecAttr->arraySize() + 3)/4-1;

    newOp->theTupKeyLen = len;
    newOp->theOperationType = opType;
    if (opType == DeleteRequest) {
      newOp->theStatus = GetValue;  
    } else {
      newOp->theStatus = SetValue;  
    }
    
    const Uint32 * src = (Uint32*)tRecAttr->aRef();
unknown's avatar
unknown committed
926 927
    const Uint32 tScanInfo = src[len] & 0x3FFFF;
    const Uint32 tTakeOverNode = src[len] >> 20;
unknown's avatar
unknown committed
928 929 930 931 932 933 934
    {
      UintR scanInfo = 0;
      TcKeyReq::setTakeOverScanFlag(scanInfo, 1);
      TcKeyReq::setTakeOverScanNode(scanInfo, tTakeOverNode);
      TcKeyReq::setTakeOverScanInfo(scanInfo, tScanInfo);
      newOp->theScanInfo = scanInfo;
    }
935

unknown's avatar
unknown committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    // Copy the first 8 words of key info from KEYINF20 into TCKEYREQ
    TcKeyReq * tcKeyReq = CAST_PTR(TcKeyReq,newOp->theTCREQ->getDataPtrSend());
    Uint32 i = 0;
    for (i = 0; i < TcKeyReq::MaxKeyInfo && i < len; i++) {
      tcKeyReq->keyInfo[i] = * src++;
    }
    
    if(i < len){
      NdbApiSignal* tSignal = theNdb->getSignal();
      newOp->theFirstKEYINFO = tSignal;      
      
      Uint32 left = len - i;
      while(tSignal && left > KeyInfo::DataLength){
	tSignal->setSignal(GSN_KEYINFO);
	KeyInfo * keyInfo = CAST_PTR(KeyInfo, tSignal->getDataPtrSend());
	memcpy(keyInfo->keyData, src, 4 * KeyInfo::DataLength);
	src += KeyInfo::DataLength;
	left -= KeyInfo::DataLength;

	tSignal->next(theNdb->getSignal());
	tSignal = tSignal->next();
      }
958

unknown's avatar
unknown committed
959 960 961 962
      if(tSignal && left > 0){
	tSignal->setSignal(GSN_KEYINFO);
	KeyInfo * keyInfo = CAST_PTR(KeyInfo, tSignal->getDataPtrSend());
	memcpy(keyInfo->keyData, src, 4 * left);
unknown's avatar
unknown committed
963 964 965 966 967 968 969 970 971 972 973
      }      
    }
    // create blob handles automatically
    if (opType == DeleteRequest && m_currentTable->m_noOfBlobs != 0) {
      for (unsigned i = 0; i < m_currentTable->m_columns.size(); i++) {
	NdbColumnImpl* c = m_currentTable->m_columns[i];
	assert(c != 0);
	if (c->getBlobType()) {
	  if (newOp->getBlobHandle(pTrans, c) == NULL)
	    return NULL;
	}
unknown's avatar
unknown committed
974 975
      }
    }
unknown's avatar
unknown committed
976
    
unknown's avatar
unknown committed
977
    return newOp;
978
  }
unknown's avatar
unknown committed
979
  return 0;
980 981
}

unknown's avatar
unknown committed
982 983 984
NdbBlob*
NdbScanOperation::getBlobHandle(const char* anAttrName)
{
unknown's avatar
unknown committed
985
  m_keyInfo = 1;
unknown's avatar
unknown committed
986 987 988 989 990 991 992
  return NdbOperation::getBlobHandle(m_transConnection, 
				     m_currentTable->getColumn(anAttrName));
}

NdbBlob*
NdbScanOperation::getBlobHandle(Uint32 anAttrId)
{
unknown's avatar
unknown committed
993
  m_keyInfo = 1;
unknown's avatar
unknown committed
994 995 996 997
  return NdbOperation::getBlobHandle(m_transConnection, 
				     m_currentTable->getColumn(anAttrId));
}

unknown's avatar
unknown committed
998 999
NdbIndexScanOperation::NdbIndexScanOperation(Ndb* aNdb)
  : NdbScanOperation(aNdb)
1000
{
unknown's avatar
unknown committed
1001
}
1002

unknown's avatar
unknown committed
1003
NdbIndexScanOperation::~NdbIndexScanOperation(){
1004 1005
}

unknown's avatar
unknown committed
1006
int
unknown's avatar
unknown committed
1007 1008
NdbIndexScanOperation::setBound(const char* anAttrName, int type, 
				const void* aValue, Uint32 len)
1009
{
unknown's avatar
unknown committed
1010
  return setBound(m_accessTable->getColumn(anAttrName), type, aValue, len);
1011 1012
}

unknown's avatar
unknown committed
1013
int
unknown's avatar
unknown committed
1014 1015
NdbIndexScanOperation::setBound(Uint32 anAttrId, int type, 
				const void* aValue, Uint32 len)
1016
{
unknown's avatar
unknown committed
1017 1018
  return setBound(m_accessTable->getColumn(anAttrId), type, aValue, len);
}
1019

unknown's avatar
unknown committed
1020 1021 1022 1023 1024
int
NdbIndexScanOperation::equal_impl(const NdbColumnImpl* anAttrObject, 
				  const char* aValue, 
				  Uint32 len){
  return setBound(anAttrObject, BoundEQ, aValue, len);
1025 1026
}

unknown's avatar
unknown committed
1027 1028 1029
NdbRecAttr*
NdbIndexScanOperation::getValue_impl(const NdbColumnImpl* attrInfo, 
				     char* aValue){
1030
  if(!m_ordered){
unknown's avatar
unknown committed
1031 1032
    return NdbScanOperation::getValue_impl(attrInfo, aValue);
  }
1033 1034 1035 1036 1037 1038 1039 1040 1041
  
  int id = attrInfo->m_attrId;                // In "real" table
  assert(m_accessTable->m_index);
  int sz = (int)m_accessTable->m_index->m_key_ids.size();
  if(id >= sz || (id = m_accessTable->m_index->m_key_ids[id]) == -1){
    return NdbScanOperation::getValue_impl(attrInfo, aValue);
  }
  
  assert(id < NDB_MAX_NO_OF_ATTRIBUTES_IN_KEY);
unknown's avatar
unknown committed
1042
  Uint32 marker = theTupleKeyDefined[id][0];
1043
  
unknown's avatar
unknown committed
1044 1045 1046 1047
  if(marker == SETBOUND_EQ){
    return NdbScanOperation::getValue_impl(attrInfo, aValue);
  } else if(marker == API_PTR){
    return NdbScanOperation::getValue_impl(attrInfo, aValue);
1048
  }
unknown's avatar
unknown committed
1049
  
1050 1051
  assert(marker == FAKE_PTR);
  
unknown's avatar
unknown committed
1052 1053 1054 1055 1056 1057 1058 1059 1060
  UintPtr oldVal;
  oldVal = theTupleKeyDefined[id][1];
#if (SIZEOF_CHARP == 8)
  oldVal = oldVal | (((UintPtr)theTupleKeyDefined[id][2]) << 32);
#endif
  theTupleKeyDefined[id][0] = API_PTR;

  NdbRecAttr* tmp = (NdbRecAttr*)oldVal;
  tmp->setup(attrInfo, aValue);
1061

unknown's avatar
unknown committed
1062
  return tmp;
1063 1064
}

unknown's avatar
unknown committed
1065 1066 1067 1068 1069 1070 1071
#include <AttributeHeader.hpp>
/*
 * Define bound on index column in range scan.
 */
int
NdbIndexScanOperation::setBound(const NdbColumnImpl* tAttrInfo, 
				int type, const void* aValue, Uint32 len)
1072
{
unknown's avatar
unknown committed
1073 1074 1075
  if (theOperationType == OpenRangeScanRequest &&
      (0 <= type && type <= 4) &&
      len <= 8000) {
1076
    // insert bound type
1077 1078
    Uint32 currLen = theTotalNrOfKeyWordInSignal;
    Uint32 remaining = KeyInfo::DataLength - currLen;
unknown's avatar
unknown committed
1079
    Uint32 sizeInBytes = tAttrInfo->m_attrSize * tAttrInfo->m_arraySize;
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    // normalize char bound
    CHARSET_INFO* cs = tAttrInfo->m_cs;
    Uint32 xfrmData[2000];
    if (cs != NULL && aValue != NULL) {
      // current limitation: strxfrm does not increase length
      assert(cs->strxfrm_multiply == 1);
      unsigned n =
      (*cs->coll->strnxfrm)(cs,
                            (uchar*)xfrmData, sizeof(xfrmData),
                            (const uchar*)aValue, sizeInBytes);
      while (n < sizeInBytes)
        ((uchar*)xfrmData)[n++] = 0x20;
      aValue = (char*)xfrmData;
    }
unknown's avatar
unknown committed
1095 1096 1097 1098
    if (len != sizeInBytes && (len != 0)) {
      setErrorCodeAbort(4209);
      return -1;
    }
1099
    // insert attribute header
1100
    len = aValue != NULL ? sizeInBytes : 0;
unknown's avatar
unknown committed
1101 1102 1103
    Uint32 tIndexAttrId = tAttrInfo->m_attrId;
    Uint32 sizeInWords = (len + 3) / 4;
    AttributeHeader ah(tIndexAttrId, sizeInWords);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    const Uint32 ahValue = ah.m_value;

    const bool aligned = (UintPtr(aValue) & 3) == 0;
    const bool nobytes = (len & 0x3) == 0;
    const Uint32 totalLen = 2 + sizeInWords;
    Uint32 tupKeyLen = theTupKeyLen;
    if(remaining > totalLen &&  aligned && nobytes){
      Uint32 * dst = theKEYINFOptr + currLen;
      * dst ++ = type;
      * dst ++ = ahValue;
      memcpy(dst, aValue, 4 * sizeInWords);
      theTotalNrOfKeyWordInSignal = currLen + totalLen;
    } else {
      if(!aligned || !nobytes){
	Uint32 tempData[2002];
	tempData[0] = type;
	tempData[1] = ahValue;
        memcpy(tempData+2, aValue, len);
1122
        while ((len & 0x3) != 0)
1123 1124 1125 1126 1127 1128
          ((char*)&tempData[2])[len++] = 0;
	insertBOUNDS(tempData, 2+sizeInWords);
      } else {
	Uint32 buf[2] = { type, ahValue };
	insertBOUNDS(buf, 2);
	insertBOUNDS((Uint32*)aValue, sizeInWords);
1129
      }
unknown's avatar
unknown committed
1130
    }
1131
    theTupKeyLen = tupKeyLen + totalLen;
1132

unknown's avatar
unknown committed
1133 1134 1135 1136 1137 1138 1139 1140 1141
    /**
     * Do sorted stuff
     */

    /**
     * The primary keys for an ordered index is defined in the beginning
     * so it's safe to use [tIndexAttrId] 
     * (instead of looping as is NdbOperation::equal_impl)
     */
1142
    if(type == BoundEQ && !theTupleKeyDefined[tIndexAttrId][0]){
unknown's avatar
unknown committed
1143 1144 1145 1146 1147 1148 1149 1150
      theNoOfTupKeyDefined++;
      theTupleKeyDefined[tIndexAttrId][0] = SETBOUND_EQ;
    }
    
    return 0;
  } else {
    setErrorCodeAbort(4228);    // XXX wrong code
    return -1;
1151 1152 1153
  }
}

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
int
NdbIndexScanOperation::insertBOUNDS(Uint32 * data, Uint32 sz){
  Uint32 len;
  Uint32 remaining = KeyInfo::DataLength - theTotalNrOfKeyWordInSignal;
  Uint32 * dst = theKEYINFOptr + theTotalNrOfKeyWordInSignal;
  do {
    len = (sz < remaining ? sz : remaining);
    memcpy(dst, data, 4 * len);
    
    if(sz >= remaining){
      NdbApiSignal* tCurr = theLastKEYINFO;
      tCurr->setLength(KeyInfo::MaxSignalLength);
      NdbApiSignal* tSignal = tCurr->next();
      if(tSignal)
	;
      else if((tSignal = theNdb->getSignal()) != 0)
      {
	tCurr->next(tSignal);
	tSignal->setSignal(GSN_KEYINFO);
      } else {
	goto error;
      }
      theLastKEYINFO = tSignal;
      theKEYINFOptr = dst = ((KeyInfo*)tSignal->getDataPtrSend())->keyData;
      remaining = KeyInfo::DataLength;
      sz -= len;
      data += len;
    } else {
      len = (KeyInfo::DataLength - remaining) + len;
      break;
    }
  } while(sz >= 0);   
  theTotalNrOfKeyWordInSignal = len;
  return 0;

error:
  setErrorCodeAbort(4228);    // XXX wrong code
  return -1;
}

unknown's avatar
unknown committed
1194 1195 1196 1197 1198 1199 1200 1201
NdbResultSet*
NdbIndexScanOperation::readTuples(LockMode lm,
				  Uint32 batch,
				  Uint32 parallel,
				  bool order_by){
  NdbResultSet * rs = NdbScanOperation::readTuples(lm, batch, 0);
  if(rs && order_by){
    m_ordered = 1;
1202 1203
    Uint32 cnt = m_accessTable->getNoOfColumns() - 1;
    m_sort_columns = cnt; // -1 for NDB$NODE
unknown's avatar
unknown committed
1204
    m_current_api_receiver = m_sent_receivers_count;
1205
    m_api_receivers_count = m_sent_receivers_count;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    
    m_sort_columns = cnt;
    for(Uint32 i = 0; i<cnt; i++){
      const NdbColumnImpl* key = m_accessTable->m_index->m_columns[i];
      const NdbColumnImpl* col = m_currentTable->getColumn(key->m_keyInfoPos);
      NdbRecAttr* tmp = NdbScanOperation::getValue_impl(col, (char*)-1);
      UintPtr newVal = UintPtr(tmp);
      theTupleKeyDefined[i][0] = FAKE_PTR;
      theTupleKeyDefined[i][1] = (newVal & 0xFFFFFFFF);
#if (SIZEOF_CHARP == 8)
      theTupleKeyDefined[i][2] = (newVal >> 32);
#endif
    }
unknown's avatar
unknown committed
1219 1220 1221
  }
  return rs;
}
1222

unknown's avatar
unknown committed
1223 1224 1225 1226 1227 1228
void
NdbIndexScanOperation::fix_get_values(){
  /**
   * Loop through all getValues and set buffer pointer to "API" pointer
   */
  NdbRecAttr * curr = theReceiver.theFirstRecAttr;
1229
  Uint32 cnt = m_accessTable->getNoOfColumns() - 1;
unknown's avatar
unknown committed
1230
  assert(cnt <  NDB_MAX_NO_OF_ATTRIBUTES_IN_KEY);
1231
  
unknown's avatar
unknown committed
1232 1233
  const NdbIndexImpl * idx = m_accessTable->m_index;
  const NdbTableImpl * tab = m_currentTable;
1234 1235 1236
  for(Uint32 i = 0; i<cnt; i++){
    Uint32 val = theTupleKeyDefined[i][0];
    switch(val){
1237 1238
    case FAKE_PTR:
      curr->setup(curr->m_column, 0);
1239
    case API_PTR:
1240 1241
      curr = curr->next();
      break;
1242 1243
    case SETBOUND_EQ:
      break;
unknown's avatar
unknown committed
1244
#ifdef VM_TRACE
1245 1246
    default:
      abort();
unknown's avatar
unknown committed
1247 1248
#endif
    }
1249 1250 1251
  }
}

unknown's avatar
unknown committed
1252 1253 1254 1255 1256 1257 1258
int
NdbIndexScanOperation::compare(Uint32 skip, Uint32 cols, 
			       const NdbReceiver* t1, 
			       const NdbReceiver* t2){

  NdbRecAttr * r1 = t1->m_rows[t1->m_current_row];
  NdbRecAttr * r2 = t2->m_rows[t2->m_current_row];
1259

unknown's avatar
unknown committed
1260 1261 1262 1263 1264 1265 1266 1267
  r1 = (skip ? r1->next() : r1);
  r2 = (skip ? r2->next() : r2);
  
  while(cols > 0){
    Uint32 * d1 = (Uint32*)r1->aRef();
    Uint32 * d2 = (Uint32*)r2->aRef();
    unsigned r1_null = r1->isNULL();
    if((r1_null ^ (unsigned)r2->isNULL())){
1268
      return (r1_null ? -1 : 1);
unknown's avatar
unknown committed
1269
    }
1270
    const NdbColumnImpl & col = NdbColumnImpl::getImpl(* r1->m_column);
unknown's avatar
unknown committed
1271 1272
    Uint32 size = (r1->theAttrSize * r1->theArraySize + 3) / 4;
    if(!r1_null){
1273 1274
      const NdbSqlUtil::Type& sqlType = NdbSqlUtil::getType(col.m_extType);
      int r = (*sqlType.m_cmp)(col.m_cs, d1, d2, size, size);
unknown's avatar
unknown committed
1275 1276 1277 1278 1279 1280 1281 1282
      if(r){
	assert(r != NdbSqlUtil::CmpUnknown);
	return r;
      }
    }
    cols--;
    r1 = r1->next();
    r2 = r2->next();
1283
  }
unknown's avatar
unknown committed
1284
  return 0;
1285 1286
}

unknown's avatar
unknown committed
1287 1288 1289
int
NdbIndexScanOperation::next_result_ordered(bool fetchAllowed){
  
unknown's avatar
unknown committed
1290
  Uint32 u_idx = 0, u_last = 0;
1291
  Uint32 s_idx   = m_current_api_receiver; // first sorted
unknown's avatar
unknown committed
1292 1293 1294
  Uint32 s_last  = theParallelism;         // last sorted

  NdbReceiver** arr = m_api_receivers;
1295
  NdbReceiver* tRec = arr[s_idx];
unknown's avatar
unknown committed
1296 1297 1298
  
  if(DEBUG_NEXT_RESULT) ndbout_c("nextOrderedResult(%d) nextResult: %d",
				 fetchAllowed, 
1299
				 (s_idx < s_last ? tRec->nextResult() : 0));
unknown's avatar
unknown committed
1300 1301 1302 1303
  
  if(DEBUG_NEXT_RESULT) ndbout_c("u=[%d %d] s=[%d %d]", 
				 u_idx, u_last,
				 s_idx, s_last);
1304 1305 1306
  
  bool fetchNeeded = (s_idx == s_last) || !tRec->nextResult();
  
unknown's avatar
unknown committed
1307 1308 1309 1310 1311 1312 1313
  if(fetchNeeded){
    if(fetchAllowed){
      if(DEBUG_NEXT_RESULT) ndbout_c("performing fetch...");
      TransporterFacade* tp = TransporterFacade::instance();
      Guard guard(tp->theMutexPtr);
      Uint32 seq = theNdbCon->theNodeSequence;
      Uint32 nodeId = theNdbCon->theDBnode;
1314
      if(seq == tp->getNodeSequence(nodeId) && !send_next_scan_ordered(s_idx)){
unknown's avatar
unknown committed
1315
	Uint32 tmp = m_sent_receivers_count;
1316
	s_idx = m_current_api_receiver; 
unknown's avatar
unknown committed
1317
	while(m_sent_receivers_count > 0 && !theError.code){
unknown's avatar
unknown committed
1318 1319 1320 1321 1322 1323
	  theNdb->theWaiter.m_node = nodeId;
	  theNdb->theWaiter.m_state = WAIT_SCAN;
	  int return_code = theNdb->receiveResponse(WAITFOR_SCAN_TIMEOUT);
	  if (return_code == 0 && seq == tp->getNodeSequence(nodeId)) {
	    continue;
	  }
1324
	  if(DEBUG_NEXT_RESULT) ndbout_c("return -1");
unknown's avatar
unknown committed
1325 1326 1327 1328 1329 1330 1331 1332 1333
	  return -1;
	}
	
	u_idx = 0;
	u_last = m_conf_receivers_count;
	m_conf_receivers_count = 0;
	memcpy(arr, m_conf_receivers, u_last * sizeof(char*));
	
	if(DEBUG_NEXT_RESULT) ndbout_c("sent: %d recv: %d", tmp, u_last);
unknown's avatar
unknown committed
1334 1335
	if(theError.code){
	  setErrorCode(theError.code);
1336
	  if(DEBUG_NEXT_RESULT) ndbout_c("return -1");
unknown's avatar
unknown committed
1337 1338
	  return -1;
	}
unknown's avatar
unknown committed
1339 1340
      }
    } else {
1341
      if(DEBUG_NEXT_RESULT) ndbout_c("return 2");
unknown's avatar
unknown committed
1342 1343
      return 2;
    }
1344 1345 1346 1347
  } else {
    u_idx = s_idx;
    u_last = s_idx + 1;
    s_idx++;
unknown's avatar
unknown committed
1348
  }
unknown's avatar
unknown committed
1349
  
unknown's avatar
unknown committed
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
  if(DEBUG_NEXT_RESULT) ndbout_c("u=[%d %d] s=[%d %d]", 
				 u_idx, u_last,
				 s_idx, s_last);


  Uint32 cols = m_sort_columns;
  Uint32 skip = m_keyInfo;
  while(u_idx < u_last){
    u_last--;
    tRec = arr[u_last];
    
    // Do binary search instead to find place
    Uint32 place = s_idx;
    for(; place < s_last; place++){
      if(compare(skip, cols, tRec, arr[place]) <= 0){
	break;
      }
    }
    
    if(place != s_idx){
      if(DEBUG_NEXT_RESULT) 
	ndbout_c("memmove(%d, %d, %d)", s_idx-1, s_idx, (place - s_idx));
      memmove(arr+s_idx-1, arr+s_idx, sizeof(char*)*(place - s_idx));
    }
    
    if(DEBUG_NEXT_RESULT) ndbout_c("putting %d @ %d", u_last, place - 1);
    m_api_receivers[place-1] = tRec;
    s_idx--;
1378 1379
  }

unknown's avatar
unknown committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
  if(DEBUG_NEXT_RESULT) ndbout_c("u=[%d %d] s=[%d %d]", 
				 u_idx, u_last,
				 s_idx, s_last);
  
  m_current_api_receiver = s_idx;
  
  if(DEBUG_NEXT_RESULT)
    for(Uint32 i = s_idx; i<s_last; i++)
      ndbout_c("%p", arr[i]);
  
  tRec = m_api_receivers[s_idx];    
  if(s_idx < s_last && tRec->nextResult()){
    tRec->copyout(theReceiver);      
1393
    if(DEBUG_NEXT_RESULT) ndbout_c("return 0");
unknown's avatar
unknown committed
1394
    return 0;
1395 1396
  }

unknown's avatar
unknown committed
1397 1398 1399
  theError.code = -1;
  if(DEBUG_NEXT_RESULT) ndbout_c("return 1");
  return 1;
1400 1401
}

1402
int
unknown's avatar
unknown committed
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
NdbIndexScanOperation::send_next_scan_ordered(Uint32 idx){  
  if(idx == theParallelism)
    return 0;
  
  NdbApiSignal tSignal(theNdb->theMyRef);
  tSignal.setSignal(GSN_SCAN_NEXTREQ);
  
  Uint32* theData = tSignal.getDataPtrSend();
  theData[0] = theNdbCon->theTCConPtr;
  theData[1] = 0;
  Uint64 transId = theNdbCon->theTransactionId;
  theData[2] = transId;
  theData[3] = (Uint32) (transId >> 32);
  
  /**
   * Prepare ops
   */
  Uint32 last = m_sent_receivers_count;
  Uint32 * prep_array = theData + 4;

  NdbReceiver * tRec = m_api_receivers[idx];
  m_sent_receivers[last] = tRec;
  tRec->m_list_index = last;
  prep_array[0] = tRec->m_tcPtrI;
  tRec->prepareSend();
  
  m_sent_receivers_count = last + 1;
1430 1431
  m_current_api_receiver = idx + 1;
  
unknown's avatar
unknown committed
1432 1433 1434 1435
  Uint32 nodeId = theNdbCon->theDBnode;
  TransporterFacade * tp = TransporterFacade::instance();
  tSignal.setLength(4+1);
  return tp->sendSignal(&tSignal, nodeId);
1436
}
unknown's avatar
unknown committed
1437 1438

int
1439
NdbScanOperation::close_impl(TransporterFacade* tp){
unknown's avatar
unknown committed
1440 1441 1442 1443 1444 1445 1446
  Uint32 seq = theNdbCon->theNodeSequence;
  Uint32 nodeId = theNdbCon->theDBnode;
  
  if(seq != tp->getNodeSequence(nodeId)){
    theNdbCon->theReleaseOnClose = true;
    return -1;
  }
1447 1448
  
  while(theError.code == 0 && m_sent_receivers_count){
unknown's avatar
unknown committed
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    theNdb->theWaiter.m_node = nodeId;
    theNdb->theWaiter.m_state = WAIT_SCAN;
    int return_code = theNdb->receiveResponse(WAITFOR_SCAN_TIMEOUT);
    switch(return_code){
    case 0:
      break;
    case -1:
      setErrorCode(4008);
    case -2:
      m_api_receivers_count = 0;
      m_conf_receivers_count = 0;
      m_sent_receivers_count = 0;
1461
      theNdbCon->theReleaseOnClose = true;
unknown's avatar
unknown committed
1462 1463 1464 1465 1466 1467
      return -1;
    }
  }

  if(m_api_receivers_count+m_conf_receivers_count){
    // Send close scan
1468 1469
    if(send_next_scan(0, true) == -1){ // Close scan
      theNdbCon->theReleaseOnClose = true;
unknown's avatar
unknown committed
1470
      return -1;
1471
    }
unknown's avatar
unknown committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
  }
  
  /**
   * wait for close scan conf
   */
  while(m_sent_receivers_count+m_api_receivers_count+m_conf_receivers_count){
    theNdb->theWaiter.m_node = nodeId;
    theNdb->theWaiter.m_state = WAIT_SCAN;
    int return_code = theNdb->receiveResponse(WAITFOR_SCAN_TIMEOUT);
    switch(return_code){
    case 0:
      break;
    case -1:
      setErrorCode(4008);
    case -2:
      m_api_receivers_count = 0;
      m_conf_receivers_count = 0;
      m_sent_receivers_count = 0;
1490
      theNdbCon->theReleaseOnClose = true;
unknown's avatar
unknown committed
1491 1492 1493
      return -1;
    }
  }
1494 1495
  return 0;
}
unknown's avatar
unknown committed
1496

1497 1498
void
NdbScanOperation::reset_receivers(Uint32 parallell, Uint32 ordered){
unknown's avatar
unknown committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
  for(Uint32 i = 0; i<parallell; i++){
    m_receivers[i]->m_list_index = i;
    m_prepared_receivers[i] = m_receivers[i]->getId();
    m_sent_receivers[i] = m_receivers[i];
    m_conf_receivers[i] = 0;
    m_api_receivers[i] = 0;
    m_receivers[i]->prepareSend();
  }
  
  m_api_receivers_count = 0;
  m_current_api_receiver = 0;
  m_sent_receivers_count = parallell;
  m_conf_receivers_count = 0;
  
1513
  if(ordered){
unknown's avatar
unknown committed
1514
    m_current_api_receiver = parallell;
unknown's avatar
unknown committed
1515
    m_api_receivers_count = parallell;
unknown's avatar
unknown committed
1516
  }
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
}

int
NdbScanOperation::restart()
{
  
  TransporterFacade* tp = TransporterFacade::instance();
  Guard guard(tp->theMutexPtr);
  Uint32 nodeId = theNdbCon->theDBnode;
  
  {
    int res;
    if((res= close_impl(tp)))
    {
      return res;
    }
  }
  
  /**
   * Reset receivers
   */
  reset_receivers(theParallelism, m_ordered);
unknown's avatar
unknown committed
1539
  
unknown's avatar
unknown committed
1540
  theError.code = 0;
unknown's avatar
unknown committed
1541 1542 1543 1544 1545
  if (doSendScan(nodeId) == -1)
    return -1;
  
  return 0;
}
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558

int
NdbIndexScanOperation::reset_bounds(){
  int res;
  
  {
    TransporterFacade* tp = TransporterFacade::instance();
    Guard guard(tp->theMutexPtr);
    res= close_impl(tp);
  }

  if(!res)
  {
unknown's avatar
unknown committed
1559
    theError.code = 0;
1560 1561 1562 1563
    reset_receivers(theParallelism, m_ordered);
    
    theLastKEYINFO = theFirstKEYINFO;
    theKEYINFOptr = ((KeyInfo*)theFirstKEYINFO->getDataPtrSend())->keyData;
unknown's avatar
unknown committed
1564 1565 1566
    theTupKeyLen = 0;
    theTotalNrOfKeyWordInSignal = 0;
    m_transConnection
unknown's avatar
unknown committed
1567
      ->remove_list((NdbOperation*&)m_transConnection->m_firstExecutedScanOp,
unknown's avatar
unknown committed
1568
		    this);
1569 1570 1571 1572 1573
    m_transConnection->define_scan_op(this);
    return 0;
  }
  return res;
}