ha_ndbcluster.cc 95.6 KB
Newer Older
unknown's avatar
unknown committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/* Copyright (C) 2000-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 
*/

/*
  This file defines the NDB Cluster handler: the interface between MySQL and
  NDB Cluster
*/


#ifdef __GNUC__
#pragma implementation                          // gcc: Class implementation
#endif

#include "mysql_priv.h"

#ifdef HAVE_NDBCLUSTER_DB
#include <my_dir.h>
#include "ha_ndbcluster.h"
#include <ndbapi/NdbApi.hpp>
#include <ndbapi/NdbScanFilter.hpp>

#define USE_DISCOVER_ON_STARTUP
//#define USE_NDB_POOL

// Default value for parallelism
static const int parallelism= 240;

42 43
// Default value for max number of transactions
// createable against NDB from this handler
44 45 46 47
static const int max_transactions= 256;

// Default value for prefetch of autoincrement values
static const ha_rows autoincrement_prefetch= 32;
48

49
// connectstring to cluster if given by mysqld
unknown's avatar
unknown committed
50
const char *ndbcluster_connectstring= 0;
51

unknown's avatar
unknown committed
52
#define NDB_HIDDEN_PRIMARY_KEY_LENGTH 8
53

unknown's avatar
unknown committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

#define ERR_PRINT(err) \
  DBUG_PRINT("error", ("Error: %d  message: %s", err.code, err.message))

#define ERR_RETURN(err)		         \
{				         \
  ERR_PRINT(err);		         \
  DBUG_RETURN(ndb_to_mysql_error(&err)); \
}

// Typedefs for long names
typedef NdbDictionary::Column NDBCOL;
typedef NdbDictionary::Table  NDBTAB;
typedef NdbDictionary::Index  NDBINDEX;
typedef NdbDictionary::Dictionary  NDBDICT;

bool ndbcluster_inited= false;

72 73
static Ndb* g_ndb= NULL;

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 101 102 103 104
// Handler synchronization
pthread_mutex_t ndbcluster_mutex;

// Table lock handling
static HASH ndbcluster_open_tables;

static byte *ndbcluster_get_key(NDB_SHARE *share,uint *length,
                                my_bool not_used __attribute__((unused)));
static NDB_SHARE *get_share(const char *table_name);
static void free_share(NDB_SHARE *share);

static int packfrm(const void *data, uint len, const void **pack_data, uint *pack_len);
static int unpackfrm(const void **data, uint *len,
		     const void* pack_data);

/*
  Error handling functions
*/

struct err_code_mapping
{
  int ndb_err;
  int my_err;
};

static const err_code_mapping err_map[]= 
{
  { 626, HA_ERR_KEY_NOT_FOUND },
  { 630, HA_ERR_FOUND_DUPP_KEY },
  { 893, HA_ERR_FOUND_DUPP_UNIQUE },
  { 721, HA_ERR_TABLE_EXIST },
105
  { 4244, HA_ERR_TABLE_EXIST },
unknown's avatar
unknown committed
106
  { 241, HA_ERR_OLD_METADATA },
107 108 109 110 111 112 113 114 115 116 117 118 119 120

  { 266, HA_ERR_LOCK_WAIT_TIMEOUT },
  { 274, HA_ERR_LOCK_WAIT_TIMEOUT },
  { 296, HA_ERR_LOCK_WAIT_TIMEOUT },
  { 297, HA_ERR_LOCK_WAIT_TIMEOUT },
  { 237, HA_ERR_LOCK_WAIT_TIMEOUT },

  { 623, HA_ERR_RECORD_FILE_FULL },
  { 624, HA_ERR_RECORD_FILE_FULL },
  { 625, HA_ERR_RECORD_FILE_FULL },
  { 826, HA_ERR_RECORD_FILE_FULL },
  { 827, HA_ERR_RECORD_FILE_FULL },
  { 832, HA_ERR_RECORD_FILE_FULL },

unknown's avatar
unknown committed
121 122 123 124 125 126 127 128 129 130
  { -1, -1 }
};


static int ndb_to_mysql_error(const NdbError *err)
{
  uint i;
  for (i=0 ; err_map[i].ndb_err != err->code ; i++)
  {
    if (err_map[i].my_err == -1)
131
      return err->code;
unknown's avatar
unknown committed
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
  }
  return err_map[i].my_err;
}


/*
  Take care of the error that occured in NDB
  
  RETURN
    0	No error
    #   The mapped error code
*/

int ha_ndbcluster::ndb_err(NdbConnection *trans)
{
  const NdbError err= trans->getNdbError();
  if (!err.code)
    return 0;			// Don't log things to DBUG log if no error
  DBUG_ENTER("ndb_err");
  
  ERR_PRINT(err);
  switch (err.classification) {
  case NdbError::SchemaError:
  {
    NDBDICT *dict= m_ndb->getDictionary();
    DBUG_PRINT("info", ("invalidateTable %s", m_tabname));
    dict->invalidateTable(m_tabname);
    break;
  }
  default:
    break;
  }
  DBUG_RETURN(ndb_to_mysql_error(&err));
}


168
/*
169
  Override the default get_error_message in order to add the 
170 171 172
  error message of NDB 
 */

173 174
bool ha_ndbcluster::get_error_message(int error, 
				      String *buf)
175
{
176
  DBUG_ENTER("ha_ndbcluster::get_error_message");
177
  DBUG_PRINT("enter", ("error: %d", error));
178

179 180
  if (!m_ndb)
    DBUG_RETURN(false);
181 182

  const NdbError err= m_ndb->getNdbError(error);
183 184 185 186
  bool temporary= err.status==NdbError::TemporaryError;
  buf->set(err.message, strlen(err.message), &my_charset_bin);
  DBUG_PRINT("exit", ("message: %s, temporary: %d", buf->ptr(), temporary));
  DBUG_RETURN(temporary);
187 188 189
}


unknown's avatar
unknown committed
190 191
/*
  Check if type is supported by NDB.
unknown's avatar
unknown committed
192
  TODO Use this once, not in every operation
unknown's avatar
unknown committed
193 194 195 196 197
*/

static inline bool ndb_supported_type(enum_field_types type)
{
  switch (type) {
unknown's avatar
unknown committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
  case MYSQL_TYPE_DECIMAL:    
  case MYSQL_TYPE_TINY:        
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_INT24:       
  case MYSQL_TYPE_LONGLONG:
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
  case MYSQL_TYPE_TIMESTAMP:
  case MYSQL_TYPE_DATETIME:    
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_TIME:        
  case MYSQL_TYPE_YEAR:        
  case MYSQL_TYPE_STRING:      
  case MYSQL_TYPE_VAR_STRING:
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_BLOB:    
  case MYSQL_TYPE_MEDIUM_BLOB:   
  case MYSQL_TYPE_LONG_BLOB:  
  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_SET:         
    return true;
unknown's avatar
unknown committed
221 222
  case MYSQL_TYPE_NULL:   
  case MYSQL_TYPE_GEOMETRY:
unknown's avatar
unknown committed
223
    break;
unknown's avatar
unknown committed
224
  }
unknown's avatar
unknown committed
225
  return false;
unknown's avatar
unknown committed
226 227 228
}


unknown's avatar
unknown committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
/*
  Instruct NDB to set the value of the hidden primary key
*/

bool ha_ndbcluster::set_hidden_key(NdbOperation *ndb_op,
				   uint fieldnr, const byte *field_ptr)
{
  DBUG_ENTER("set_hidden_key");
  DBUG_RETURN(ndb_op->equal(fieldnr, (char*)field_ptr,
			    NDB_HIDDEN_PRIMARY_KEY_LENGTH) != 0);
}


/*
  Instruct NDB to set the value of one primary key attribute
*/

int ha_ndbcluster::set_ndb_key(NdbOperation *ndb_op, Field *field,
                               uint fieldnr, const byte *field_ptr)
{
  uint32 pack_len= field->pack_length();
  DBUG_ENTER("set_ndb_key");
  DBUG_PRINT("enter", ("%d: %s, ndb_type: %u, len=%d", 
                       fieldnr, field->field_name, field->type(),
                       pack_len));
  DBUG_DUMP("key", (char*)field_ptr, pack_len);
  
unknown's avatar
unknown committed
256 257 258 259 260
  if (ndb_supported_type(field->type()))
  {
    if (! (field->flags & BLOB_FLAG))
      // Common implementation for most field types
      DBUG_RETURN(ndb_op->equal(fieldnr, (char*) field_ptr, pack_len) != 0);
unknown's avatar
unknown committed
261
  }
unknown's avatar
unknown committed
262 263 264
  // Unhandled field types
  DBUG_PRINT("error", ("Field type %d not supported", field->type()));
  DBUG_RETURN(2);
unknown's avatar
unknown committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
}


/*
 Instruct NDB to set the value of one attribute
*/

int ha_ndbcluster::set_ndb_value(NdbOperation *ndb_op, Field *field, 
                                 uint fieldnr)
{
  const byte* field_ptr= field->ptr;
  uint32 pack_len=  field->pack_length();
  DBUG_ENTER("set_ndb_value");
  DBUG_PRINT("enter", ("%d: %s, type: %u, len=%d, is_null=%s", 
                       fieldnr, field->field_name, field->type(), 
                       pack_len, field->is_null()?"Y":"N"));
  DBUG_DUMP("value", (char*) field_ptr, pack_len);
unknown's avatar
unknown committed
282 283

  if (ndb_supported_type(field->type()))
unknown's avatar
unknown committed
284
  {
unknown's avatar
unknown committed
285 286 287 288 289 290 291 292 293 294
    if (! (field->flags & BLOB_FLAG))
    {
      if (field->is_null())
        // Set value to NULL
        DBUG_RETURN((ndb_op->setValue(fieldnr, (char*)NULL, pack_len) != 0));
      // Common implementation for most field types
      DBUG_RETURN(ndb_op->setValue(fieldnr, (char*)field_ptr, pack_len) != 0);
    }

    // Blob type
295
    NdbBlob *ndb_blob= ndb_op->getBlobHandle(fieldnr);
unknown's avatar
unknown committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    if (ndb_blob != NULL)
    {
      if (field->is_null())
        DBUG_RETURN(ndb_blob->setNull() != 0);

      Field_blob *field_blob= (Field_blob*)field;

      // Get length and pointer to data
      uint32 blob_len= field_blob->get_length(field_ptr);
      char* blob_ptr= NULL;
      field_blob->get_ptr(&blob_ptr);

      // Looks like NULL blob can also be signaled in this way
      if (blob_ptr == NULL)
        DBUG_RETURN(ndb_blob->setNull() != 0);

      DBUG_PRINT("value", ("set blob ptr=%x len=%u",
                           (unsigned)blob_ptr, blob_len));
      DBUG_DUMP("value", (char*)blob_ptr, min(blob_len, 26));

      // No callback needed to write value
      DBUG_RETURN(ndb_blob->setValue(blob_ptr, blob_len) != 0);
    }
    DBUG_RETURN(1);
unknown's avatar
unknown committed
320
  }
unknown's avatar
unknown committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  // Unhandled field types
  DBUG_PRINT("error", ("Field type %d not supported", field->type()));
  DBUG_RETURN(2);
}


/*
  Callback to read all blob values.
  - not done in unpack_record because unpack_record is valid
    after execute(Commit) but reading blobs is not
  - may only generate read operations; they have to be executed
    somewhere before the data is available
  - due to single buffer for all blobs, we let the last blob
    process all blobs (last so that all are active)
  - null bit is still set in unpack_record
  - TODO allocate blob part aligned buffers
*/

unknown's avatar
unknown committed
339
NdbBlob::ActiveHook g_get_ndb_blobs_value;
unknown's avatar
unknown committed
340

unknown's avatar
unknown committed
341
int g_get_ndb_blobs_value(NdbBlob *ndb_blob, void *arg)
unknown's avatar
unknown committed
342
{
unknown's avatar
unknown committed
343
  DBUG_ENTER("g_get_ndb_blobs_value");
unknown's avatar
unknown committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  if (ndb_blob->blobsNextBlob() != NULL)
    DBUG_RETURN(0);
  ha_ndbcluster *ha= (ha_ndbcluster *)arg;
  DBUG_RETURN(ha->get_ndb_blobs_value(ndb_blob));
}

int ha_ndbcluster::get_ndb_blobs_value(NdbBlob *last_ndb_blob)
{
  DBUG_ENTER("get_ndb_blobs_value");

  // Field has no field number so cannot use TABLE blob_field
  // Loop twice, first only counting total buffer size
  for (int loop= 0; loop <= 1; loop++)
  {
    uint32 offset= 0;
    for (uint i= 0; i < table->fields; i++)
    {
      Field *field= table->field[i];
      NdbValue value= m_value[i];
      if (value.ptr != NULL && (field->flags & BLOB_FLAG))
      {
        Field_blob *field_blob= (Field_blob *)field;
        NdbBlob *ndb_blob= value.blob;
        Uint64 blob_len= 0;
        if (ndb_blob->getLength(blob_len) != 0)
          DBUG_RETURN(-1);
        // Align to Uint64
        uint32 blob_size= blob_len;
        if (blob_size % 8 != 0)
          blob_size+= 8 - blob_size % 8;
        if (loop == 1)
        {
          char *buf= blobs_buffer + offset;
          uint32 len= 0xffffffff;  // Max uint32
          DBUG_PRINT("value", ("read blob ptr=%x len=%u",
                               (uint)buf, (uint)blob_len));
          if (ndb_blob->readData(buf, len) != 0)
            DBUG_RETURN(-1);
          DBUG_ASSERT(len == blob_len);
          field_blob->set_ptr(len, buf);
        }
        offset+= blob_size;
      }
    }
    if (loop == 0 && offset > blobs_buffer_size)
    {
      my_free(blobs_buffer, MYF(MY_ALLOW_ZERO_PTR));
      blobs_buffer_size= 0;
      DBUG_PRINT("value", ("allocate blobs buffer size %u", offset));
      blobs_buffer= my_malloc(offset, MYF(MY_WME));
      if (blobs_buffer == NULL)
        DBUG_RETURN(-1);
      blobs_buffer_size= offset;
    }
unknown's avatar
unknown committed
398
  }
unknown's avatar
unknown committed
399
  DBUG_RETURN(0);
unknown's avatar
unknown committed
400 401 402 403 404
}


/*
  Instruct NDB to fetch one field
unknown's avatar
unknown committed
405 406
  - data is read directly into buffer provided by field
    if field is NULL, data is read into memory provided by NDBAPI
unknown's avatar
unknown committed
407 408
*/

unknown's avatar
unknown committed
409 410
int ha_ndbcluster::get_ndb_value(NdbOperation *ndb_op, Field *field,
                                 uint fieldnr)
unknown's avatar
unknown committed
411 412
{
  DBUG_ENTER("get_ndb_value");
unknown's avatar
unknown committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
  DBUG_PRINT("enter", ("fieldnr: %d flags: %o", fieldnr,
                       (int)(field != NULL ? field->flags : 0)));

  if (field != NULL)
  {
    if (ndb_supported_type(field->type()))
    {
      DBUG_ASSERT(field->ptr != NULL);
      if (! (field->flags & BLOB_FLAG))
      {
        m_value[fieldnr].rec= ndb_op->getValue(fieldnr, field->ptr);
        DBUG_RETURN(m_value[fieldnr].rec == NULL);
      }

      // Blob type
      NdbBlob *ndb_blob= ndb_op->getBlobHandle(fieldnr);
      m_value[fieldnr].blob= ndb_blob;
      if (ndb_blob != NULL)
      {
        // Set callback
        void *arg= (void *)this;
unknown's avatar
unknown committed
434
        DBUG_RETURN(ndb_blob->setActiveHook(g_get_ndb_blobs_value, arg) != 0);
unknown's avatar
unknown committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
      }
      DBUG_RETURN(1);
    }
    // Unhandled field types
    DBUG_PRINT("error", ("Field type %d not supported", field->type()));
    DBUG_RETURN(2);
  }

  // Used for hidden key only
  m_value[fieldnr].rec= ndb_op->getValue(fieldnr, NULL);
  DBUG_RETURN(m_value[fieldnr].rec == NULL);
}


/*
  Check if any set or get of blob value in current query.
*/
bool ha_ndbcluster::uses_blob_value(bool all_fields)
{
  if (table->blob_fields == 0)
    return false;
  if (all_fields)
    return true;
  {
    uint no_fields= table->fields;
    int i;
    THD *thd= current_thd;
    // They always put blobs at the end..
    for (i= no_fields - 1; i >= 0; i--)
    {
      Field *field= table->field[i];
      if (thd->query_id == field->query_id)
      {
        return true;
      }
    }
  }
  return false;
unknown's avatar
unknown committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
}


/*
  Get metadata for this table from NDB 

  IMPLEMENTATION
    - save the NdbDictionary::Table for easy access
    - check that frm-file on disk is equal to frm-file
      of table accessed in NDB
    - build a list of the indexes for the table
*/

int ha_ndbcluster::get_metadata(const char *path)
{
  NDBDICT *dict= m_ndb->getDictionary();
  const NDBTAB *tab;
  const void *data, *pack_data;
  const char **key_name;
492
  uint ndb_columns, mysql_columns, length, pack_length;
unknown's avatar
unknown committed
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
  int error;
  DBUG_ENTER("get_metadata");
  DBUG_PRINT("enter", ("m_tabname: %s, path: %s", m_tabname, path));

  if (!(tab= dict->getTable(m_tabname)))
    ERR_RETURN(dict->getNdbError());
  DBUG_PRINT("info", ("Table schema version: %d", tab->getObjectVersion()));
  
  /*
    This is the place to check that the table we got from NDB
    is equal to the one on local disk
  */
  ndb_columns=   (uint) tab->getNoOfColumns();
  mysql_columns= table->fields;
  if (table->primary_key == MAX_KEY)
    ndb_columns--;
  if (ndb_columns != mysql_columns)
  {
    DBUG_PRINT("error",
               ("Wrong number of columns, ndb: %d mysql: %d", 
                ndb_columns, mysql_columns));
    DBUG_RETURN(HA_ERR_OLD_METADATA);
  }
  
  /*
    Compare FrmData in NDB with frm file from disk.
  */
  error= 0;
  if (readfrm(path, &data, &length) ||
      packfrm(data, length, &pack_data, &pack_length))
  {
    my_free((char*)data, MYF(MY_ALLOW_ZERO_PTR));
    my_free((char*)pack_data, MYF(MY_ALLOW_ZERO_PTR));
    DBUG_RETURN(1);
  }
    
  if ((pack_length != tab->getFrmLength()) || 
      (memcmp(pack_data, tab->getFrmData(), pack_length)))
  {
    DBUG_PRINT("error", 
	       ("metadata, pack_length: %d getFrmLength: %d memcmp: %d", 
		pack_length, tab->getFrmLength(),
		memcmp(pack_data, tab->getFrmData(), pack_length)));      
    DBUG_DUMP("pack_data", (char*)pack_data, pack_length);
    DBUG_DUMP("frm", (char*)tab->getFrmData(), tab->getFrmLength());
    error= HA_ERR_OLD_METADATA;
  }
  my_free((char*)data, MYF(0));
  my_free((char*)pack_data, MYF(0));
  if (error)
    DBUG_RETURN(error);

  // All checks OK, lets use the table
  m_table= (void*)tab;

unknown's avatar
unknown committed
548
  DBUG_RETURN(build_index_list(table, ILBP_OPEN));  
549
}
unknown's avatar
unknown committed
550

unknown's avatar
unknown committed
551

unknown's avatar
unknown committed
552
int ha_ndbcluster::build_index_list(TABLE *tab, enum ILBP phase)
553
{
unknown's avatar
unknown committed
554
  int error= 0;
555 556 557 558
  char *name;
  const char *index_name;
  static const char* unique_suffix= "$unique";
  uint i, name_len;
unknown's avatar
unknown committed
559 560 561 562
  KEY* key_info= tab->key_info;
  const char **key_name= tab->keynames.type_names;
  NdbDictionary::Dictionary *dict= m_ndb->getDictionary();
  DBUG_ENTER("build_index_list");
563
  
unknown's avatar
unknown committed
564
  // Save information about all known indexes
unknown's avatar
unknown committed
565
  for (i= 0; i < tab->keys; i++, key_info++, key_name++)
566
  {
unknown's avatar
unknown committed
567
    index_name= *key_name;
568
    NDB_INDEX_TYPE idx_type= get_index_type_from_table(i);
569
    m_index[i].type= idx_type;
570
    if (idx_type == UNIQUE_ORDERED_INDEX || idx_type == UNIQUE_INDEX)
571
    {
572 573
      name_len= strlen(index_name)+strlen(unique_suffix)+1;
      // Create name for unique index by appending "$unique";     
574 575 576
      if (!(name= my_malloc(name_len, MYF(MY_WME))))
	DBUG_RETURN(2);
      strxnmov(name, name_len, index_name, unique_suffix, NullS);
unknown's avatar
unknown committed
577
      m_index[i].unique_name= name;
578 579 580
      DBUG_PRINT("info", ("Created unique index name: %s for index %d",
			  name, i));
    }
unknown's avatar
unknown committed
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
    // Create secondary indexes if in create phase
    if (phase == ILBP_CREATE)
    {
      DBUG_PRINT("info", ("Creating index %u: %s", i, index_name));
      
      switch (m_index[i].type){
	
      case PRIMARY_KEY_INDEX:
	// Do nothing, already created
	break;
      case PRIMARY_KEY_ORDERED_INDEX:
	error= create_ordered_index(index_name, key_info);
	break;
      case UNIQUE_ORDERED_INDEX:
	if (!(error= create_ordered_index(index_name, key_info)))
	  error= create_unique_index(get_unique_index_name(i), key_info);
	break;
      case UNIQUE_INDEX:
	error= create_unique_index(get_unique_index_name(i), key_info);
	break;
      case ORDERED_INDEX:
	error= create_ordered_index(index_name, key_info);
	break;
      default:
	DBUG_ASSERT(false);
	break;
      }
      if (error)
      {
	DBUG_PRINT("error", ("Failed to create index %u", i));
	drop_table();
	break;
      }
    }
    // Add handles to index objects
    DBUG_PRINT("info", ("Trying to add handle to index %s", index_name));
617 618 619
    if ((m_index[i].type != PRIMARY_KEY_INDEX) &&
	(m_index[i].type != UNIQUE_INDEX))
    {
unknown's avatar
unknown committed
620
      const NDBINDEX *index= dict->getIndex(index_name, m_tabname);
621
      if (!index) DBUG_RETURN(1);
unknown's avatar
unknown committed
622
      m_index[i].index= (void *) index;
623 624 625 626 627
    }
    if (m_index[i].unique_name)
    {
      const NDBINDEX *index= dict->getIndex(m_index[i].unique_name, m_tabname);
      if (!index) DBUG_RETURN(1);
unknown's avatar
unknown committed
628
      m_index[i].unique_index= (void *) index;
629
    }      
unknown's avatar
unknown committed
630
    DBUG_PRINT("info", ("Added handle to index %s", index_name));
631
  }
unknown's avatar
unknown committed
632 633
  
  DBUG_RETURN(error);
634 635
}

636

unknown's avatar
unknown committed
637 638 639 640
/*
  Decode the type of an index from information 
  provided in table object
*/
641
NDB_INDEX_TYPE ha_ndbcluster::get_index_type_from_table(uint inx) const
unknown's avatar
unknown committed
642
{
643 644 645
  bool is_hash_index=  (table->key_info[inx].algorithm == HA_KEY_ALG_HASH);
  if (inx == table->primary_key)
    return is_hash_index ? PRIMARY_KEY_INDEX : PRIMARY_KEY_ORDERED_INDEX;
unknown's avatar
unknown committed
646
  else
647 648
    return ((table->key_info[inx].flags & HA_NOSAME) ? 
	    (is_hash_index ? UNIQUE_INDEX : UNIQUE_ORDERED_INDEX) :
unknown's avatar
unknown committed
649 650
	    ORDERED_INDEX);
} 
651

unknown's avatar
unknown committed
652 653 654

void ha_ndbcluster::release_metadata()
{
655
  uint i;
656

unknown's avatar
unknown committed
657 658 659 660 661
  DBUG_ENTER("release_metadata");
  DBUG_PRINT("enter", ("m_tabname: %s", m_tabname));

  m_table= NULL;

662
  // Release index list 
663 664
  for (i= 0; i < MAX_KEY; i++)
  {
665 666 667 668 669
    if (m_index[i].unique_name)
      my_free((char*)m_index[i].unique_name, MYF(0));
    m_index[i].unique_name= NULL;
    m_index[i].unique_index= NULL;      
    m_index[i].index= NULL;      
670 671
  }

unknown's avatar
unknown committed
672 673 674
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
675
int ha_ndbcluster::get_ndb_lock_type(enum thr_lock_type type)
676
{
unknown's avatar
unknown committed
677 678
  int lm;
  if (type == TL_WRITE_ALLOW_WRITE)
unknown's avatar
unknown committed
679
    lm= NdbScanOperation::LM_Exclusive;
unknown's avatar
unknown committed
680 681 682 683
  else if (uses_blob_value(retrieve_all_fields))
    /*
      TODO use a new scan mode to read + lock + keyinfo
    */
unknown's avatar
unknown committed
684
    lm= NdbScanOperation::LM_Exclusive;
unknown's avatar
unknown committed
685
  else
unknown's avatar
unknown committed
686
    lm= NdbScanOperation::LM_CommittedRead;
unknown's avatar
unknown committed
687
  return lm;
688 689
}

unknown's avatar
unknown committed
690 691 692 693 694 695
static const ulong index_type_flags[]=
{
  /* UNDEFINED_INDEX */
  0,                         

  /* PRIMARY_KEY_INDEX */
696
  HA_ONLY_WHOLE_INDEX, 
697 698

  /* PRIMARY_KEY_ORDERED_INDEX */
699
  /* 
unknown's avatar
unknown committed
700
     Enable HA_KEYREAD_ONLY when "sorted" indexes are supported, 
701 702 703
     thus ORDERD BY clauses can be optimized by reading directly 
     through the index.
  */
unknown's avatar
unknown committed
704
  // HA_KEYREAD_ONLY | 
705 706
  HA_READ_NEXT |              
  HA_READ_RANGE,
unknown's avatar
unknown committed
707 708

  /* UNIQUE_INDEX */
709
  HA_ONLY_WHOLE_INDEX,
unknown's avatar
unknown committed
710

711
  /* UNIQUE_ORDERED_INDEX */
712 713
  HA_READ_NEXT |              
  HA_READ_RANGE,
714

unknown's avatar
unknown committed
715 716
  /* ORDERED_INDEX */
  HA_READ_NEXT |              
717
  HA_READ_RANGE,
unknown's avatar
unknown committed
718 719 720 721 722 723 724 725 726
};

static const int index_flags_size= sizeof(index_type_flags)/sizeof(ulong);

inline const char* ha_ndbcluster::get_index_name(uint idx_no) const
{
  return table->keynames.type_names[idx_no];
}

727 728
inline const char* ha_ndbcluster::get_unique_index_name(uint idx_no) const
{
729
  return m_index[idx_no].unique_name;
730
}
731

unknown's avatar
unknown committed
732 733 734
inline NDB_INDEX_TYPE ha_ndbcluster::get_index_type(uint idx_no) const
{
  DBUG_ASSERT(idx_no < MAX_KEY);
735
  return m_index[idx_no].type;
unknown's avatar
unknown committed
736 737 738 739 740 741 742 743 744 745
}


/*
  Get the flags for an index

  RETURN
    flags depending on the type of the index.
*/

746 747
inline ulong ha_ndbcluster::index_flags(uint idx_no, uint part,
                                        bool all_parts) const 
unknown's avatar
unknown committed
748 749
{ 
  DBUG_ENTER("index_flags");
750
  DBUG_PRINT("info", ("idx_no: %d", idx_no));
unknown's avatar
unknown committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
  DBUG_ASSERT(get_index_type_from_table(idx_no) < index_flags_size);
  DBUG_RETURN(index_type_flags[get_index_type_from_table(idx_no)]);
}


int ha_ndbcluster::set_primary_key(NdbOperation *op, const byte *key)
{
  KEY* key_info= table->key_info + table->primary_key;
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
  DBUG_ENTER("set_primary_key");

  for (; key_part != end; key_part++) 
  {
    Field* field= key_part->field;
    if (set_ndb_key(op, field, 
		    key_part->fieldnr-1, key))
      ERR_RETURN(op->getNdbError());
    key += key_part->length;
  }
  DBUG_RETURN(0);
}


775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
int ha_ndbcluster::set_primary_key_from_old_data(NdbOperation *op, const byte *old_data)
{
  KEY* key_info= table->key_info + table->primary_key;
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
  DBUG_ENTER("set_primary_key_from_old_data");

  for (; key_part != end; key_part++) 
  {
    Field* field= key_part->field;
    if (set_ndb_key(op, field, 
		    key_part->fieldnr-1, old_data+key_part->offset))
      ERR_RETURN(op->getNdbError());
  }
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
int ha_ndbcluster::set_primary_key(NdbOperation *op)
{
  DBUG_ENTER("set_primary_key");
  KEY* key_info= table->key_info + table->primary_key;
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;

  for (; key_part != end; key_part++) 
  {
    Field* field= key_part->field;
    if (set_ndb_key(op, field, 
                    key_part->fieldnr-1, field->ptr))
      ERR_RETURN(op->getNdbError());
  }
  DBUG_RETURN(0);
}


/*
  Read one record from NDB using primary key
*/

815
int ha_ndbcluster::pk_read(const byte *key, uint key_len, byte *buf) 
unknown's avatar
unknown committed
816 817 818 819 820 821 822 823 824
{
  uint no_fields= table->fields, i;
  NdbConnection *trans= m_active_trans;
  NdbOperation *op;
  THD *thd= current_thd;
  DBUG_ENTER("pk_read");
  DBUG_PRINT("enter", ("key_len: %u", key_len));
  DBUG_DUMP("key", (char*)key, key_len);

825 826
  if (!(op= trans->getNdbOperation((NDBTAB *) m_table)) || 
      op->readTuple() != 0)
827
    ERR_RETURN(trans->getNdbError());
unknown's avatar
unknown committed
828 829 830 831 832 833 834

  if (table->primary_key == MAX_KEY) 
  {
    // This table has no primary key, use "hidden" primary key
    DBUG_PRINT("info", ("Using hidden key"));
    DBUG_DUMP("key", (char*)key, 8);    
    if (set_hidden_key(op, no_fields, key))
835 836
      ERR_RETURN(trans->getNdbError());

unknown's avatar
unknown committed
837
    // Read key at the same time, for future reference
unknown's avatar
unknown committed
838
    if (get_ndb_value(op, NULL, no_fields))
839
      ERR_RETURN(trans->getNdbError());
unknown's avatar
unknown committed
840 841 842 843 844 845 846 847
  } 
  else 
  {
    int res;
    if ((res= set_primary_key(op, key)))
      return res;
  }
  
848
  // Read all wanted non-key field(s) unless HA_EXTRA_RETRIEVE_ALL_COLS
unknown's avatar
unknown committed
849 850 851
  for (i= 0; i < no_fields; i++) 
  {
    Field *field= table->field[i];
852
    if ((thd->query_id == field->query_id) ||
unknown's avatar
unknown committed
853
	retrieve_all_fields)
unknown's avatar
unknown committed
854
    {
unknown's avatar
unknown committed
855
      if (get_ndb_value(op, field, i))
856
	ERR_RETURN(trans->getNdbError());
unknown's avatar
unknown committed
857 858 859 860
    }
    else
    {
      // Attribute was not to be read
unknown's avatar
unknown committed
861
      m_value[i].ptr= NULL;
unknown's avatar
unknown committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    }
  }
  
  if (trans->execute(NoCommit, IgnoreError) != 0) 
  {
    table->status= STATUS_NOT_FOUND;
    DBUG_RETURN(ndb_err(trans));
  }

  // The value have now been fetched from NDB  
  unpack_record(buf);
  table->status= 0;     
  DBUG_RETURN(0);
}


878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
/*
  Read one complementing record from NDB using primary key from old_data
*/

int ha_ndbcluster::complemented_pk_read(const byte *old_data, byte *new_data)
{
  uint no_fields= table->fields, i;
  NdbConnection *trans= m_active_trans;
  NdbOperation *op;
  THD *thd= current_thd;
  DBUG_ENTER("complemented_pk_read");

  if (retrieve_all_fields)
    // We have allready retrieved all fields, nothing to complement
    DBUG_RETURN(0);

894 895
  if (!(op= trans->getNdbOperation((NDBTAB *) m_table)) || 
      op->readTuple() != 0)
896
    ERR_RETURN(trans->getNdbError());
897 898

    int res;
899
    if ((res= set_primary_key_from_old_data(op, old_data)))
900
      ERR_RETURN(trans->getNdbError());
901 902 903 904 905 906 907 908
    
  // Read all unreferenced non-key field(s)
  for (i= 0; i < no_fields; i++) 
  {
    Field *field= table->field[i];
    if (!(field->flags & PRI_KEY_FLAG) &&
	(thd->query_id != field->query_id))
    {
unknown's avatar
unknown committed
909
      if (get_ndb_value(op, field, i))
910
	ERR_RETURN(trans->getNdbError());
911 912 913
    }
  }
  
914
  if (trans->execute(NoCommit) != 0) 
915 916 917 918 919 920 921 922 923 924 925 926
  {
    table->status= STATUS_NOT_FOUND;
    DBUG_RETURN(ndb_err(trans));
  }

  // The value have now been fetched from NDB  
  unpack_record(new_data);
  table->status= 0;     
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
/*
  Read one record from NDB using unique secondary index
*/

int ha_ndbcluster::unique_index_read(const byte *key,
				     uint key_len, byte *buf)
{
  NdbConnection *trans= m_active_trans;
  NdbIndexOperation *op;
  THD *thd= current_thd;
  byte *key_ptr;
  KEY* key_info;
  KEY_PART_INFO *key_part, *end;
  uint i;
  DBUG_ENTER("unique_index_read");
  DBUG_PRINT("enter", ("key_len: %u, index: %u", key_len, active_index));
  DBUG_DUMP("key", (char*)key, key_len);
944
  DBUG_PRINT("enter", ("name: %s", get_unique_index_name(active_index)));
unknown's avatar
unknown committed
945
  
946 947 948
  if (!(op= trans->getNdbIndexOperation((NDBINDEX *) 
					m_index[active_index].unique_index, 
                                        (NDBTAB *) m_table)) ||
unknown's avatar
unknown committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
      op->readTuple() != 0)
    ERR_RETURN(trans->getNdbError());
  
  // Set secondary index key(s)
  key_ptr= (byte *) key;
  key_info= table->key_info + active_index;
  DBUG_ASSERT(key_info->key_length == key_len);
  end= (key_part= key_info->key_part) + key_info->key_parts;

  for (i= 0; key_part != end; key_part++, i++) 
  {
    if (set_ndb_key(op, key_part->field, i, key_ptr))
      ERR_RETURN(trans->getNdbError());
    key_ptr+= key_part->length;
  }

  // Get non-index attribute(s)
  for (i= 0; i < table->fields; i++) 
  {
    Field *field= table->field[i];
    if ((thd->query_id == field->query_id) ||
        (field->flags & PRI_KEY_FLAG))
    {
unknown's avatar
unknown committed
972
      if (get_ndb_value(op, field, i))
unknown's avatar
unknown committed
973 974 975 976 977
        ERR_RETURN(op->getNdbError());
    }
    else
    {
      // Attribute was not to be read
unknown's avatar
unknown committed
978
      m_value[i].ptr= NULL;
unknown's avatar
unknown committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    }
  }

  if (trans->execute(NoCommit, IgnoreError) != 0) 
  {
    table->status= STATUS_NOT_FOUND;
    DBUG_RETURN(ndb_err(trans));
  }
  // The value have now been fetched from NDB
  unpack_record(buf);
  table->status= 0;
  DBUG_RETURN(0);
}

/*
994 995 996 997 998 999 1000 1001
  Get the next record of a started scan. Try to fetch
  it locally from NdbApi cached records if possible, 
  otherwise ask NDB for more.

  NOTE
  If this is a update/delete make sure to not contact 
  NDB before any pending ops have been sent to NDB.

unknown's avatar
unknown committed
1002 1003 1004 1005
*/

inline int ha_ndbcluster::next_result(byte *buf)
{  
1006
  int check;
unknown's avatar
unknown committed
1007 1008 1009
  NdbConnection *trans= m_active_trans;
  NdbResultSet *cursor= m_active_cursor; 
  DBUG_ENTER("next_result");
1010 1011 1012 1013 1014 1015 1016 1017

  if (!cursor)
    DBUG_RETURN(HA_ERR_END_OF_FILE);
    
  /* 
     If this an update or delete, call nextResult with false
     to process any records already cached in NdbApi
  */
1018
  bool contact_ndb= m_lock.type != TL_WRITE_ALLOW_WRITE;
1019 1020
  do {
    DBUG_PRINT("info", ("Call nextResult, contact_ndb: %d", contact_ndb));
unknown's avatar
unknown committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    /*
      We can only handle one tuple with blobs at a time.
    */
    if (ops_pending && blobs_pending)
    {
      if (trans->execute(NoCommit) != 0)
        DBUG_RETURN(ndb_err(trans));
      ops_pending= 0;
      blobs_pending= false;
    }
1031 1032 1033 1034 1035
    check= cursor->nextResult(contact_ndb);
    if (check == 0)
    {
      // One more record found
      DBUG_PRINT("info", ("One more record found"));    
unknown's avatar
unknown committed
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      unpack_record(buf);
      table->status= 0;
      DBUG_RETURN(0);
    } 
    else if (check == 1 || check == 2)
    {
      // 1: No more records
      // 2: No more cached records

      /*
	Before fetching more rows and releasing lock(s),
	all pending update or delete operations should 
	be sent to NDB
      */
      DBUG_PRINT("info", ("ops_pending: %d", ops_pending));    
1052
      if (ops_pending && (trans->execute(NoCommit) != 0))	
1053 1054 1055 1056 1057 1058 1059
	DBUG_RETURN(ndb_err(trans));
      ops_pending= 0;
      
      contact_ndb= (check == 2);
    }
  } while (check == 2);
    
unknown's avatar
unknown committed
1060
  table->status= STATUS_NOT_FOUND;
1061 1062
  if (check == -1)
    DBUG_RETURN(ndb_err(trans));
unknown's avatar
unknown committed
1063 1064 1065 1066 1067 1068 1069

  // No more records
  DBUG_PRINT("info", ("No more records"));
  DBUG_RETURN(HA_ERR_END_OF_FILE);
}


1070 1071 1072 1073
/*
  Set bounds for a ordered index scan, use key_range
*/

unknown's avatar
unknown committed
1074
int ha_ndbcluster::set_bounds(NdbIndexScanOperation *op,
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
			      const key_range *key,
			      int bound)
{
  uint i, tot_len;
  byte *key_ptr;
  KEY* key_info= table->key_info + active_index;
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;

  DBUG_ENTER("set_bounds");
  DBUG_PRINT("enter", ("bound: %d", bound));
  DBUG_PRINT("enter", ("key_parts: %d", key_info->key_parts));
  DBUG_PRINT("enter", ("key->length: %d", key->length));
  DBUG_PRINT("enter", ("key->flag: %d", key->flag));

  // Set bounds using key data
  tot_len= 0;
  key_ptr= (byte *) key->key;    
  for (; key_part != end; key_part++)
  {
    Field* field= key_part->field;
    uint32 field_len=  field->pack_length();
    tot_len+= field_len;

    const char* bounds[]= {"LE", "LT", "GE", "GT", "EQ"};
    DBUG_ASSERT(bound >= 0 && bound <= 4);    
    DBUG_PRINT("info", ("Set Bound%s on %s", 
			bounds[bound],
			field->field_name));
    DBUG_DUMP("key", (char*)key_ptr, field_len);
1105
    
1106 1107
    if (op->setBound(field->field_name,
		     bound, 
1108 1109
		     field->is_null() ? 0 : key_ptr,
		     field->is_null() ? 0 : field_len) != 0)
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
      ERR_RETURN(op->getNdbError());
    
    key_ptr+= field_len;
    
    if (tot_len >= key->length)
      break;

    /*
      Only one bound which is not EQ can be set
      so if this bound was not EQ, bail out and make 
      a best effort attempt
    */
unknown's avatar
unknown committed
1122
    if (bound != NdbIndexScanOperation::BoundEQ)
1123 1124 1125 1126 1127 1128 1129
      break;
  }

  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
1130
/*
1131
  Start ordered index scan in NDB
unknown's avatar
unknown committed
1132 1133
*/

1134 1135 1136
int ha_ndbcluster::ordered_index_scan(const key_range *start_key,
				      const key_range *end_key,
				      bool sorted, byte* buf)
unknown's avatar
unknown committed
1137 1138
{  
  NdbConnection *trans= m_active_trans;
1139
  NdbResultSet *cursor;
unknown's avatar
unknown committed
1140
  NdbIndexScanOperation *op;
unknown's avatar
unknown committed
1141
  const char *index_name;
1142

unknown's avatar
unknown committed
1143
  DBUG_ENTER("ordered_index_scan");
1144
  DBUG_PRINT("enter", ("index: %u, sorted: %d", active_index, sorted));  
unknown's avatar
unknown committed
1145 1146 1147
  DBUG_PRINT("enter", ("Starting new ordered scan on %s", m_tabname));
  
  index_name= get_index_name(active_index);
1148 1149 1150
  if (!(op= trans->getNdbIndexScanOperation((NDBINDEX *)
        				    m_index[active_index].index, 
					    (NDBTAB *) m_table)))
unknown's avatar
unknown committed
1151
    ERR_RETURN(trans->getNdbError());
unknown's avatar
unknown committed
1152 1153 1154 1155

  NdbScanOperation::LockMode lm= (NdbScanOperation::LockMode)
                                 get_ndb_lock_type(m_lock.type);
  if (!(cursor= op->readTuples(lm, 0, parallelism, sorted)))
unknown's avatar
unknown committed
1156 1157
    ERR_RETURN(trans->getNdbError());
  m_active_cursor= cursor;
1158 1159 1160 1161

  if (start_key && 
      set_bounds(op, start_key, 
		 (start_key->flag == HA_READ_KEY_EXACT) ? 
unknown's avatar
unknown committed
1162
		 NdbIndexScanOperation::BoundEQ :
1163
		 (start_key->flag == HA_READ_AFTER_KEY) ? 
unknown's avatar
unknown committed
1164 1165
		 NdbIndexScanOperation::BoundLT : 
		 NdbIndexScanOperation::BoundLE))
unknown's avatar
unknown committed
1166
    DBUG_RETURN(1);
1167

1168 1169 1170
  if (end_key)
  {
    if (start_key && start_key->flag == HA_READ_KEY_EXACT)
1171
    {
1172
      DBUG_PRINT("info", ("start_key is HA_READ_KEY_EXACT ignoring end_key"));
1173
    }
1174 1175
    else if (set_bounds(op, end_key, 
			(end_key->flag == HA_READ_AFTER_KEY) ? 
unknown's avatar
unknown committed
1176 1177
			NdbIndexScanOperation::BoundGE : 
			NdbIndexScanOperation::BoundGT))
1178 1179
      DBUG_RETURN(1);    
  }
1180
  DBUG_RETURN(define_read_attrs(buf, op));
unknown's avatar
unknown committed
1181 1182 1183 1184
} 


/*
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  Start a filtered scan in NDB.

  NOTE
  This function is here as an example of how to start a
  filtered scan. It should be possible to replace full_table_scan 
  with this function and make a best effort attempt 
  at filtering out the irrelevant data by converting the "items" 
  into interpreted instructions.
  This would speed up table scans where there is a limiting WHERE clause
  that doesn't match any index in the table.

unknown's avatar
unknown committed
1196 1197 1198 1199 1200 1201 1202
 */

int ha_ndbcluster::filtered_scan(const byte *key, uint key_len, 
				 byte *buf,
				 enum ha_rkey_function find_flag)
{  
  NdbConnection *trans= m_active_trans;
1203 1204
  NdbResultSet *cursor;
  NdbScanOperation *op;
unknown's avatar
unknown committed
1205 1206 1207 1208 1209 1210 1211

  DBUG_ENTER("filtered_scan");
  DBUG_PRINT("enter", ("key_len: %u, index: %u", 
                       key_len, active_index));
  DBUG_DUMP("key", (char*)key, key_len);  
  DBUG_PRINT("info", ("Starting a new filtered scan on %s",
		      m_tabname));
1212

1213
  if (!(op= trans->getNdbScanOperation((NDBTAB *) m_table)))
unknown's avatar
unknown committed
1214
    ERR_RETURN(trans->getNdbError());
unknown's avatar
unknown committed
1215 1216 1217
  NdbScanOperation::LockMode lm= (NdbScanOperation::LockMode)
                                 get_ndb_lock_type(m_lock.type);
  if (!(cursor= op->readTuples(lm, 0, parallelism)))
unknown's avatar
unknown committed
1218 1219
    ERR_RETURN(trans->getNdbError());
  m_active_cursor= cursor;
unknown's avatar
unknown committed
1220
  
unknown's avatar
unknown committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
  {
    // Start scan filter
    NdbScanFilter sf(op);
    sf.begin();
      
    // Set filter using the supplied key data
    byte *key_ptr= (byte *) key;    
    uint tot_len= 0;
    KEY* key_info= table->key_info + active_index;
    for (uint k= 0; k < key_info->key_parts; k++) 
    {
      KEY_PART_INFO* key_part= key_info->key_part+k;
      Field* field= key_part->field;
      uint ndb_fieldnr= key_part->fieldnr-1;
      DBUG_PRINT("key_part", ("fieldnr: %d", ndb_fieldnr));
      //      const NDBCOL *col= tab->getColumn(ndb_fieldnr);
      uint32 field_len=  field->pack_length();
      DBUG_DUMP("key", (char*)key, field_len);
	
      DBUG_PRINT("info", ("Column %s, type: %d, len: %d", 
			  field->field_name, field->real_type(), field_len));
	
      // Define scan filter
      if (field->real_type() == MYSQL_TYPE_STRING)
	sf.eq(ndb_fieldnr, key_ptr, field_len);
      else 
      {
	if (field_len == 8)
	  sf.eq(ndb_fieldnr, (Uint64)*key_ptr);
	else if (field_len <= 4)
	  sf.eq(ndb_fieldnr, (Uint32)*key_ptr);
	else 
	  DBUG_RETURN(1);
      }
	
      key_ptr += field_len;
      tot_len += field_len;
	
      if (tot_len >= key_len)
	break;
    }
    // End scan filter
    sf.end();
  }

1266
  DBUG_RETURN(define_read_attrs(buf, op));
unknown's avatar
unknown committed
1267 1268 1269 1270
} 


/*
1271
  Start full table scan in NDB
unknown's avatar
unknown committed
1272 1273 1274 1275 1276 1277 1278
 */

int ha_ndbcluster::full_table_scan(byte *buf)
{
  uint i;
  NdbResultSet *cursor;
  NdbScanOperation *op;
1279
  NdbConnection *trans= m_active_trans;
unknown's avatar
unknown committed
1280 1281 1282 1283

  DBUG_ENTER("full_table_scan");  
  DBUG_PRINT("enter", ("Starting new scan on %s", m_tabname));

1284
  if (!(op=trans->getNdbScanOperation((NDBTAB *) m_table)))
unknown's avatar
unknown committed
1285
    ERR_RETURN(trans->getNdbError());  
unknown's avatar
unknown committed
1286 1287 1288
  NdbScanOperation::LockMode lm= (NdbScanOperation::LockMode)
                                 get_ndb_lock_type(m_lock.type);
  if (!(cursor= op->readTuples(lm, 0, parallelism)))
unknown's avatar
unknown committed
1289 1290
    ERR_RETURN(trans->getNdbError());
  m_active_cursor= cursor;
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
  DBUG_RETURN(define_read_attrs(buf, op));
}


inline 
int ha_ndbcluster::define_read_attrs(byte* buf, NdbOperation* op)
{
  uint i;
  THD *thd= current_thd;
  NdbConnection *trans= m_active_trans;

  DBUG_ENTER("define_read_attrs");  

unknown's avatar
unknown committed
1304 1305 1306 1307 1308
  // Define attributes to read
  for (i= 0; i < table->fields; i++) 
  {
    Field *field= table->field[i];
    if ((thd->query_id == field->query_id) ||
1309 1310
	(field->flags & PRI_KEY_FLAG) || 
	retrieve_all_fields)
unknown's avatar
unknown committed
1311
    {      
unknown's avatar
unknown committed
1312
      if (get_ndb_value(op, field, i))
unknown's avatar
unknown committed
1313 1314 1315 1316
	ERR_RETURN(op->getNdbError());
    } 
    else 
    {
unknown's avatar
unknown committed
1317
      m_value[i].ptr= NULL;
unknown's avatar
unknown committed
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    }
  }
    
  if (table->primary_key == MAX_KEY) 
  {
    DBUG_PRINT("info", ("Getting hidden key"));
    // Scanning table with no primary key
    int hidden_no= table->fields;      
#ifndef DBUG_OFF
    const NDBTAB *tab= (NDBTAB *) m_table;    
    if (!tab->getColumn(hidden_no))
      DBUG_RETURN(1);
#endif
unknown's avatar
unknown committed
1331
    if (get_ndb_value(op, NULL, hidden_no))
unknown's avatar
unknown committed
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
      ERR_RETURN(op->getNdbError());
  }

  if (trans->execute(NoCommit) != 0)
    DBUG_RETURN(ndb_err(trans));
  DBUG_PRINT("exit", ("Scan started successfully"));
  DBUG_RETURN(next_result(buf));
} 


/*
  Insert one record into NDB
*/

int ha_ndbcluster::write_row(byte *record)
{
unknown's avatar
unknown committed
1348
  bool has_auto_increment;
unknown's avatar
unknown committed
1349 1350 1351 1352 1353 1354 1355 1356 1357
  uint i;
  NdbConnection *trans= m_active_trans;
  NdbOperation *op;
  int res;
  DBUG_ENTER("write_row");
  
  statistic_increment(ha_write_count,&LOCK_status);
  if (table->timestamp_default_now)
    update_timestamp(record+table->timestamp_default_now-1);
1358
  has_auto_increment= (table->next_number_field && record == table->record[0]);
unknown's avatar
unknown committed
1359
  skip_auto_increment= table->auto_increment_field_not_null;
unknown's avatar
unknown committed
1360

1361
  if (!(op= trans->getNdbOperation((NDBTAB *) m_table)))
unknown's avatar
unknown committed
1362 1363 1364 1365 1366 1367 1368 1369 1370
    ERR_RETURN(trans->getNdbError());

  res= (m_use_write) ? op->writeTuple() :op->insertTuple(); 
  if (res != 0)
    ERR_RETURN(trans->getNdbError());  
 
  if (table->primary_key == MAX_KEY) 
  {
    // Table has hidden primary key
1371
    Uint64 auto_value= m_ndb->getAutoIncrementValue((NDBTAB *) m_table);
unknown's avatar
unknown committed
1372 1373 1374 1375 1376 1377
    if (set_hidden_key(op, table->fields, (const byte*)&auto_value))
      ERR_RETURN(op->getNdbError());
  } 
  else 
  {
    int res;
1378 1379 1380 1381

    if ((has_auto_increment) && (!skip_auto_increment))
      update_auto_increment();

unknown's avatar
unknown committed
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    if ((res= set_primary_key(op)))
      return res;
  }

  // Set non-key attribute(s)
  for (i= 0; i < table->fields; i++) 
  {
    Field *field= table->field[i];
    if (!(field->flags & PRI_KEY_FLAG) &&
	set_ndb_value(op, field, i))
1392 1393
    {
      skip_auto_increment= true;
unknown's avatar
unknown committed
1394
      ERR_RETURN(op->getNdbError());
1395
    }
unknown's avatar
unknown committed
1396 1397 1398 1399 1400 1401 1402 1403 1404
  }

  /*
    Execute write operation
    NOTE When doing inserts with many values in 
    each INSERT statement it should not be necessary
    to NoCommit the transaction between each row.
    Find out how this is detected!
  */
1405
  rows_inserted++;
1406 1407
  bulk_insert_not_flushed= true;
  if ((rows_to_insert == 1) || 
unknown's avatar
unknown committed
1408 1409
      ((rows_inserted % bulk_insert_rows) == 0) ||
      uses_blob_value(false) != 0)
1410 1411 1412 1413
  {
    // Send rows to NDB
    DBUG_PRINT("info", ("Sending inserts to NDB, "\
			"rows_inserted:%d, bulk_insert_rows: %d", 
unknown's avatar
unknown committed
1414
			(int)rows_inserted, (int)bulk_insert_rows)); 
1415
    bulk_insert_not_flushed= false;
1416
    if (trans->execute(NoCommit) != 0)
1417 1418
    {
      skip_auto_increment= true;
1419
      DBUG_RETURN(ndb_err(trans));
1420
    }
1421
  }
unknown's avatar
unknown committed
1422
  if ((has_auto_increment) && (skip_auto_increment))
unknown's avatar
unknown committed
1423
  {
1424
    Uint64 next_val= (Uint64) table->next_number_field->val_int() + 1;
unknown's avatar
unknown committed
1425
    DBUG_PRINT("info", 
1426 1427
	       ("Trying to set next auto increment value to %lu",
                (ulong) next_val));
1428
    if (m_ndb->setAutoIncrementValue((NDBTAB *) m_table, next_val, true))
unknown's avatar
unknown committed
1429 1430
      DBUG_PRINT("info", 
		 ("Setting next auto increment value to %u", next_val));  
1431
  }
unknown's avatar
unknown committed
1432
  skip_auto_increment= true;
1433

unknown's avatar
unknown committed
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
  DBUG_RETURN(0);
}


/* Compare if a key in a row has changed */

int ha_ndbcluster::key_cmp(uint keynr, const byte * old_row,
			   const byte * new_row)
{
  KEY_PART_INFO *key_part=table->key_info[keynr].key_part;
  KEY_PART_INFO *end=key_part+table->key_info[keynr].key_parts;

  for (; key_part != end ; key_part++)
  {
    if (key_part->null_bit)
    {
      if ((old_row[key_part->null_offset] & key_part->null_bit) !=
	  (new_row[key_part->null_offset] & key_part->null_bit))
	return 1;
    }
    if (key_part->key_part_flag & (HA_BLOB_PART | HA_VAR_LENGTH))
    {

      if (key_part->field->cmp_binary((char*) (old_row + key_part->offset),
				      (char*) (new_row + key_part->offset),
				      (ulong) key_part->length))
	return 1;
    }
    else
    {
      if (memcmp(old_row+key_part->offset, new_row+key_part->offset,
		 key_part->length))
	return 1;
    }
  }
  return 0;
}

/*
  Update one record in NDB using primary key
*/

int ha_ndbcluster::update_row(const byte *old_data, byte *new_data)
{
  THD *thd= current_thd;
  NdbConnection *trans= m_active_trans;
1480
  NdbResultSet* cursor= m_active_cursor;
unknown's avatar
unknown committed
1481 1482 1483 1484 1485 1486 1487 1488
  NdbOperation *op;
  uint i;
  DBUG_ENTER("update_row");
  
  statistic_increment(ha_update_count,&LOCK_status);
  if (table->timestamp_on_update_now)
    update_timestamp(new_data+table->timestamp_on_update_now-1);
  
1489
  /* Check for update of primary key for special handling */  
1490 1491
  if ((table->primary_key != MAX_KEY) &&
      (key_cmp(table->primary_key, old_data, new_data)))
1492
  {
1493
    int read_res, insert_res, delete_res;
1494

1495
    DBUG_PRINT("info", ("primary key update, doing pk read+insert+delete"));
1496
    // Get all old fields, since we optimize away fields not in query
1497
    read_res= complemented_pk_read(old_data, new_data);
1498 1499 1500 1501 1502 1503
    if (read_res)
    {
      DBUG_PRINT("info", ("pk read failed"));
      DBUG_RETURN(read_res);
    }
    // Insert new row
1504 1505
    insert_res= write_row(new_data);
    if (insert_res)
1506 1507 1508 1509
    {
      DBUG_PRINT("info", ("insert failed"));
      DBUG_RETURN(insert_res);
    }
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
    // Delete old row
    DBUG_PRINT("info", ("insert succeded"));
    delete_res= delete_row(old_data);
    if (delete_res)
    {
      DBUG_PRINT("info", ("delete failed"));
      // Undo write_row(new_data)
      DBUG_RETURN(delete_row(new_data));
    }     
    DBUG_PRINT("info", ("insert+delete succeeded"));
    DBUG_RETURN(0);
1521
  }
1522

1523
  if (cursor)
unknown's avatar
unknown committed
1524
  {
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
    /*
      We are scanning records and want to update the record
      that was just found, call updateTuple on the cursor 
      to take over the lock to a new update operation
      And thus setting the primary key of the record from 
      the active record in cursor
    */
    DBUG_PRINT("info", ("Calling updateTuple on cursor"));
    if (!(op= cursor->updateTuple()))
      ERR_RETURN(trans->getNdbError());
    ops_pending++;
unknown's avatar
unknown committed
1536 1537
    if (uses_blob_value(false))
      blobs_pending= true;
1538 1539 1540
  }
  else
  {  
1541
    if (!(op= trans->getNdbOperation((NDBTAB *) m_table)) ||
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	op->updateTuple() != 0)
      ERR_RETURN(trans->getNdbError());  
    
    if (table->primary_key == MAX_KEY) 
    {
      // This table has no primary key, use "hidden" primary key
      DBUG_PRINT("info", ("Using hidden key"));
      
      // Require that the PK for this record has previously been 
      // read into m_value
      uint no_fields= table->fields;
unknown's avatar
unknown committed
1553
      NdbRecAttr* rec= m_value[no_fields].rec;
1554 1555 1556 1557 1558 1559 1560 1561 1562
      DBUG_ASSERT(rec);
      DBUG_DUMP("key", (char*)rec->aRef(), NDB_HIDDEN_PRIMARY_KEY_LENGTH);
      
      if (set_hidden_key(op, no_fields, rec->aRef()))
	ERR_RETURN(op->getNdbError());
    } 
    else 
    {
      int res;
1563
      if ((res= set_primary_key_from_old_data(op, old_data)))
1564 1565
	DBUG_RETURN(res);
    }
unknown's avatar
unknown committed
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  }

  // Set non-key attribute(s)
  for (i= 0; i < table->fields; i++) 
  {
    Field *field= table->field[i];
    if ((thd->query_id == field->query_id) &&
        (!(field->flags & PRI_KEY_FLAG)) &&
	set_ndb_value(op, field, i))
      ERR_RETURN(op->getNdbError());
  }
1577

unknown's avatar
unknown committed
1578
  // Execute update operation
1579
  if (!cursor && trans->execute(NoCommit) != 0)
unknown's avatar
unknown committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
    DBUG_RETURN(ndb_err(trans));
  
  DBUG_RETURN(0);
}


/*
  Delete one record from NDB, using primary key 
*/

int ha_ndbcluster::delete_row(const byte *record)
{
  NdbConnection *trans= m_active_trans;
1593
  NdbResultSet* cursor= m_active_cursor;
unknown's avatar
unknown committed
1594 1595 1596 1597 1598
  NdbOperation *op;
  DBUG_ENTER("delete_row");

  statistic_increment(ha_delete_count,&LOCK_status);

1599
  if (cursor)
unknown's avatar
unknown committed
1600
  {
1601
    /*
1602
      We are scanning records and want to delete the record
1603
      that was just found, call deleteTuple on the cursor 
1604
      to take over the lock to a new delete operation
1605 1606 1607 1608 1609 1610 1611
      And thus setting the primary key of the record from 
      the active record in cursor
    */
    DBUG_PRINT("info", ("Calling deleteTuple on cursor"));
    if (cursor->deleteTuple() != 0)
      ERR_RETURN(trans->getNdbError());     
    ops_pending++;
unknown's avatar
unknown committed
1612

1613 1614 1615 1616
    // If deleting from cursor, NoCommit will be handled in next_result
    DBUG_RETURN(0);
  }
  else
unknown's avatar
unknown committed
1617
  {
1618
    
1619
    if (!(op=trans->getNdbOperation((NDBTAB *) m_table)) || 
1620 1621 1622 1623 1624 1625 1626 1627
	op->deleteTuple() != 0)
      ERR_RETURN(trans->getNdbError());
    
    if (table->primary_key == MAX_KEY) 
    {
      // This table has no primary key, use "hidden" primary key
      DBUG_PRINT("info", ("Using hidden key"));
      uint no_fields= table->fields;
unknown's avatar
unknown committed
1628
      NdbRecAttr* rec= m_value[no_fields].rec;
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
      DBUG_ASSERT(rec != NULL);
      
      if (set_hidden_key(op, no_fields, rec->aRef()))
	ERR_RETURN(op->getNdbError());
    } 
    else 
    {
      int res;
      if ((res= set_primary_key(op)))
	return res;  
    }
unknown's avatar
unknown committed
1640
  }
1641
  
unknown's avatar
unknown committed
1642 1643 1644 1645 1646
  // Execute delete operation
  if (trans->execute(NoCommit) != 0)
    DBUG_RETURN(ndb_err(trans));
  DBUG_RETURN(0);
}
1647
  
unknown's avatar
unknown committed
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
/*
  Unpack a record read from NDB 

  SYNOPSIS
    unpack_record()
    buf			Buffer to store read row

  NOTE
    The data for each row is read directly into the
    destination buffer. This function is primarily 
    called in order to check if any fields should be 
    set to null.
*/

void ha_ndbcluster::unpack_record(byte* buf)
{
  uint row_offset= (uint) (buf - table->record[0]);
  Field **field, **end;
unknown's avatar
unknown committed
1666
  NdbValue *value= m_value;
unknown's avatar
unknown committed
1667 1668 1669 1670 1671 1672 1673 1674
  DBUG_ENTER("unpack_record");
  
  // Set null flag(s)
  bzero(buf, table->null_bytes);
  for (field= table->field, end= field+table->fields;
       field < end;
       field++, value++)
  {
unknown's avatar
unknown committed
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
    if ((*value).ptr)
    {
      if (! ((*field)->flags & BLOB_FLAG))
      {
        if ((*value).rec->isNULL())
         (*field)->set_null(row_offset);
      }
      else
      {
        NdbBlob* ndb_blob= (*value).blob;
        bool isNull= true;
        int ret= ndb_blob->getNull(isNull);
        DBUG_ASSERT(ret == 0);
        if (isNull)
         (*field)->set_null(row_offset);
      }
    }
unknown's avatar
unknown committed
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
  }

#ifndef DBUG_OFF
  // Read and print all values that was fetched
  if (table->primary_key == MAX_KEY)
  {
    // Table with hidden primary key
    int hidden_no= table->fields;
    const NDBTAB *tab= (NDBTAB *) m_table;
    const NDBCOL *hidden_col= tab->getColumn(hidden_no);
unknown's avatar
unknown committed
1702
    NdbRecAttr* rec= m_value[hidden_no].rec;
unknown's avatar
unknown committed
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    DBUG_ASSERT(rec);
    DBUG_PRINT("hidden", ("%d: %s \"%llu\"", hidden_no, 
                          hidden_col->getName(), rec->u_64_value()));
  } 
  print_results();
#endif
  DBUG_VOID_RETURN;
}

/*
  Utility function to print/dump the fetched field
 */

void ha_ndbcluster::print_results()
{
  const NDBTAB *tab= (NDBTAB*) m_table;
  DBUG_ENTER("print_results");

#ifndef DBUG_OFF
  if (!_db_on_)
    DBUG_VOID_RETURN;
  
  for (uint f=0; f<table->fields;f++)
  {
    Field *field;
    const NDBCOL *col;
unknown's avatar
unknown committed
1729
    NdbValue value;
unknown's avatar
unknown committed
1730

unknown's avatar
unknown committed
1731
    if (!(value= m_value[f]).ptr)
unknown's avatar
unknown committed
1732 1733 1734 1735 1736 1737 1738 1739
    {
      fprintf(DBUG_FILE, "Field %d was not read\n", f);
      continue;
    }
    field= table->field[f];
    DBUG_DUMP("field->ptr", (char*)field->ptr, field->pack_length());
    col= tab->getColumn(f);
    fprintf(DBUG_FILE, "%d: %s\t", f, col->getName());
unknown's avatar
unknown committed
1740 1741 1742

    NdbBlob *ndb_blob= NULL;
    if (! (field->flags & BLOB_FLAG))
unknown's avatar
unknown committed
1743
    {
unknown's avatar
unknown committed
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
      if (value.rec->isNULL())
      {
        fprintf(DBUG_FILE, "NULL\n");
        continue;
      }
    }
    else
    {
      ndb_blob= value.blob;
      bool isNull= true;
      ndb_blob->getNull(isNull);
      if (isNull) {
        fprintf(DBUG_FILE, "NULL\n");
        continue;
      }
unknown's avatar
unknown committed
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 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 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
    }

    switch (col->getType()) {
    case NdbDictionary::Column::Tinyint: {
      char value= *field->ptr;
      fprintf(DBUG_FILE, "Tinyint\t%d", value);
      break;
    }
    case NdbDictionary::Column::Tinyunsigned: {
      unsigned char value= *field->ptr;
      fprintf(DBUG_FILE, "Tinyunsigned\t%u", value);
      break;
    }
    case NdbDictionary::Column::Smallint: {
      short value= *field->ptr;
      fprintf(DBUG_FILE, "Smallint\t%d", value);
      break;
    }
    case NdbDictionary::Column::Smallunsigned: {
      unsigned short value= *field->ptr;
      fprintf(DBUG_FILE, "Smallunsigned\t%u", value);
      break;
    }
    case NdbDictionary::Column::Mediumint: {
      byte value[3];
      memcpy(value, field->ptr, 3);
      fprintf(DBUG_FILE, "Mediumint\t%d,%d,%d", value[0], value[1], value[2]);
      break;
    }
    case NdbDictionary::Column::Mediumunsigned: {
      byte value[3];
      memcpy(value, field->ptr, 3);
      fprintf(DBUG_FILE, "Mediumunsigned\t%u,%u,%u", value[0], value[1], value[2]);
      break;
    }
    case NdbDictionary::Column::Int: {
      fprintf(DBUG_FILE, "Int\t%lld", field->val_int());
      break;
    }
    case NdbDictionary::Column::Unsigned: {
      Uint32 value= (Uint32) *field->ptr;
      fprintf(DBUG_FILE, "Unsigned\t%u", value);
      break;
    }
    case NdbDictionary::Column::Bigint: {
      Int64 value= (Int64) *field->ptr;
      fprintf(DBUG_FILE, "Bigint\t%lld", value);
      break;
    }
    case NdbDictionary::Column::Bigunsigned: {
      Uint64 value= (Uint64) *field->ptr;
      fprintf(DBUG_FILE, "Bigunsigned\t%llu", value);
      break;
    }
    case NdbDictionary::Column::Float: {
      float value= (float) *field->ptr;
      fprintf(DBUG_FILE, "Float\t%f", value);
      break;
    }
    case NdbDictionary::Column::Double: {
      double value= (double) *field->ptr;
      fprintf(DBUG_FILE, "Double\t%f", value);
      break;
    }
    case NdbDictionary::Column::Decimal: {
      char *value= field->ptr;

      fprintf(DBUG_FILE, "Decimal\t'%-*s'", field->pack_length(), value);
      break;
    }
    case NdbDictionary::Column::Char:{
      char buf[field->pack_length()+1];
      char *value= (char *) field->ptr;
      snprintf(buf, field->pack_length(), "%s", value);
      fprintf(DBUG_FILE, "Char\t'%s'", buf);
      break;
    }
    case NdbDictionary::Column::Varchar:
    case NdbDictionary::Column::Binary:
    case NdbDictionary::Column::Varbinary: {
      char *value= (char *) field->ptr;
      fprintf(DBUG_FILE, "'%s'", value);
      break;
    }
    case NdbDictionary::Column::Datetime: {
      Uint64 value= (Uint64) *field->ptr;
      fprintf(DBUG_FILE, "Datetime\t%llu", value);
      break;
    }
    case NdbDictionary::Column::Timespec: {
      Uint64 value= (Uint64) *field->ptr;
      fprintf(DBUG_FILE, "Timespec\t%llu", value);
      break;
    }
unknown's avatar
unknown committed
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
    case NdbDictionary::Column::Blob: {
      Uint64 len= 0;
      ndb_blob->getLength(len);
      fprintf(DBUG_FILE, "Blob\t[len=%u]", (unsigned)len);
      break;
    }
    case NdbDictionary::Column::Text: {
      Uint64 len= 0;
      ndb_blob->getLength(len);
      fprintf(DBUG_FILE, "Text\t[len=%u]", (unsigned)len);
      break;
    }
    case NdbDictionary::Column::Undefined:
      fprintf(DBUG_FILE, "Unknown type: %d", col->getType());
      break;
unknown's avatar
unknown committed
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    }
    fprintf(DBUG_FILE, "\n");
    
  }
#endif
  DBUG_VOID_RETURN;
}


int ha_ndbcluster::index_init(uint index)
{
  DBUG_ENTER("index_init");
  DBUG_PRINT("enter", ("index: %u", index));
  DBUG_RETURN(handler::index_init(index));
}


int ha_ndbcluster::index_end()
{
  DBUG_ENTER("index_end");
1888
  DBUG_RETURN(close_scan());
unknown's avatar
unknown committed
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
}


int ha_ndbcluster::index_read(byte *buf,
			  const byte *key, uint key_len, 
			  enum ha_rkey_function find_flag)
{
  DBUG_ENTER("index_read");
  DBUG_PRINT("enter", ("active_index: %u, key_len: %u, find_flag: %d", 
                       active_index, key_len, find_flag));

1900 1901 1902 1903
  key_range start_key;
  start_key.key=    key;
  start_key.length= key_len;
  start_key.flag=   find_flag;
1904
  DBUG_RETURN(read_range_first(&start_key, NULL, false, true));
unknown's avatar
unknown committed
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
}


int ha_ndbcluster::index_read_idx(byte *buf, uint index_no, 
			      const byte *key, uint key_len, 
			      enum ha_rkey_function find_flag)
{
  statistic_increment(ha_read_key_count,&LOCK_status);
  DBUG_ENTER("index_read_idx");
  DBUG_PRINT("enter", ("index_no: %u, key_len: %u", index_no, key_len));  
  index_init(index_no);  
  DBUG_RETURN(index_read(buf, key, key_len, find_flag));
}


int ha_ndbcluster::index_next(byte *buf)
{
  DBUG_ENTER("index_next");

1924
  int error= 1;
unknown's avatar
unknown committed
1925
  statistic_increment(ha_read_next_count,&LOCK_status);
1926
  DBUG_RETURN(next_result(buf));
unknown's avatar
unknown committed
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
}


int ha_ndbcluster::index_prev(byte *buf)
{
  DBUG_ENTER("index_prev");
  statistic_increment(ha_read_prev_count,&LOCK_status);
  DBUG_RETURN(1);
}


int ha_ndbcluster::index_first(byte *buf)
{
  DBUG_ENTER("index_first");
  statistic_increment(ha_read_first_count,&LOCK_status);
  DBUG_RETURN(1);
}


int ha_ndbcluster::index_last(byte *buf)
{
  DBUG_ENTER("index_last");
  statistic_increment(ha_read_last_count,&LOCK_status);
  DBUG_RETURN(1);
}


1954 1955
int ha_ndbcluster::read_range_first(const key_range *start_key,
				    const key_range *end_key,
1956
				    bool eq_range, bool sorted)
1957
{
1958 1959
  KEY* key_info;
  int error= 1; 
1960
  byte* buf= table->record[0];
1961
  DBUG_ENTER("ha_ndbcluster::read_range_first");
1962
  DBUG_PRINT("info", ("eq_range: %d, sorted: %d", eq_range, sorted));
1963

1964 1965 1966
  if (m_active_cursor)
    close_scan();

1967
  switch (get_index_type(active_index)){
1968
  case PRIMARY_KEY_ORDERED_INDEX:
1969
  case PRIMARY_KEY_INDEX:
1970 1971 1972 1973
    key_info= table->key_info + active_index;
    if (start_key && 
	start_key->length == key_info->key_length &&
	start_key->flag == HA_READ_KEY_EXACT)
1974 1975 1976 1977
    {
      error= pk_read(start_key->key, start_key->length, buf);      
      DBUG_RETURN(error == HA_ERR_KEY_NOT_FOUND ? HA_ERR_END_OF_FILE : error);
    }
1978
    break;
1979
  case UNIQUE_ORDERED_INDEX:
1980
  case UNIQUE_INDEX:
1981 1982 1983 1984
    key_info= table->key_info + active_index;
    if (start_key && 
	start_key->length == key_info->key_length &&
	start_key->flag == HA_READ_KEY_EXACT)
1985 1986 1987 1988
    {
      error= unique_index_read(start_key->key, start_key->length, buf);
      DBUG_RETURN(error == HA_ERR_KEY_NOT_FOUND ? HA_ERR_END_OF_FILE : error);
    }
1989 1990 1991 1992
    break;
  default:
    break;
  }
1993

1994

1995 1996 1997
  // Start the ordered index scan and fetch the first row
  error= ordered_index_scan(start_key, end_key, sorted,
			    buf);
1998

1999 2000 2001
  DBUG_RETURN(error);
}

2002

2003
int ha_ndbcluster::read_range_next()
2004 2005 2006 2007 2008 2009
{
  DBUG_ENTER("ha_ndbcluster::read_range_next");
  DBUG_RETURN(next_result(table->record[0]));
}


unknown's avatar
unknown committed
2010 2011 2012 2013 2014
int ha_ndbcluster::rnd_init(bool scan)
{
  NdbResultSet *cursor= m_active_cursor;
  DBUG_ENTER("rnd_init");
  DBUG_PRINT("enter", ("scan: %d", scan));
2015
  // Check if scan is to be restarted
unknown's avatar
unknown committed
2016 2017 2018 2019
  if (cursor)
  {
    if (!scan)
      DBUG_RETURN(1);
2020
    cursor->restart();    
unknown's avatar
unknown committed
2021
  }
unknown's avatar
unknown committed
2022 2023 2024 2025
  index_init(table->primary_key);
  DBUG_RETURN(0);
}

2026 2027 2028
int ha_ndbcluster::close_scan()
{
  NdbResultSet *cursor= m_active_cursor;
unknown's avatar
unknown committed
2029
  NdbConnection *trans= m_active_trans;
2030 2031 2032 2033 2034
  DBUG_ENTER("close_scan");

  if (!cursor)
    DBUG_RETURN(1);

unknown's avatar
unknown committed
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
  
  if (ops_pending)
  {
    /*
      Take over any pending transactions to the 
      deleteing/updating transaction before closing the scan    
    */
    DBUG_PRINT("info", ("ops_pending: %d", ops_pending));    
    if (trans->execute(NoCommit) != 0)
      DBUG_RETURN(ndb_err(trans));
    ops_pending= 0;
  }
  
2048 2049
  cursor->close();
  m_active_cursor= NULL;
unknown's avatar
unknown committed
2050
  DBUG_RETURN(0);
2051
}
unknown's avatar
unknown committed
2052 2053 2054 2055

int ha_ndbcluster::rnd_end()
{
  DBUG_ENTER("rnd_end");
2056
  DBUG_RETURN(close_scan());
unknown's avatar
unknown committed
2057 2058 2059 2060 2061 2062 2063
}


int ha_ndbcluster::rnd_next(byte *buf)
{
  DBUG_ENTER("rnd_next");
  statistic_increment(ha_read_rnd_next_count, &LOCK_status);
2064

unknown's avatar
unknown committed
2065
  if (!m_active_cursor)
2066 2067
    DBUG_RETURN(full_table_scan(buf));
  DBUG_RETURN(next_result(buf));
unknown's avatar
unknown committed
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
}


/*
  An "interesting" record has been found and it's pk 
  retrieved by calling position
  Now it's time to read the record from db once 
  again
*/

int ha_ndbcluster::rnd_pos(byte *buf, byte *pos)
{
  DBUG_ENTER("rnd_pos");
  statistic_increment(ha_read_rnd_count,&LOCK_status);
  // The primary key for the record is stored in pos
  // Perform a pk_read using primary key "index"
  DBUG_RETURN(pk_read(pos, ref_length, buf));  
}


/*
  Store the primary key of this record in ref 
  variable, so that the row can be retrieved again later
  using "reference" in rnd_pos
*/

void ha_ndbcluster::position(const byte *record)
{
  KEY *key_info;
  KEY_PART_INFO *key_part;
  KEY_PART_INFO *end;
  byte *buff;
  DBUG_ENTER("position");

  if (table->primary_key != MAX_KEY) 
  {
    key_info= table->key_info + table->primary_key;
    key_part= key_info->key_part;
    end= key_part + key_info->key_parts;
    buff= ref;
    
    for (; key_part != end; key_part++) 
    {
      if (key_part->null_bit) {
        /* Store 0 if the key part is a NULL part */      
        if (record[key_part->null_offset]
            & key_part->null_bit) {
          *buff++= 1;
          continue;
        }      
        *buff++= 0;
      }
      memcpy(buff, record + key_part->offset, key_part->length);
      buff += key_part->length;
    }
  } 
  else 
  {
    // No primary key, get hidden key
    DBUG_PRINT("info", ("Getting hidden key"));
    int hidden_no= table->fields;
unknown's avatar
unknown committed
2129
    NdbRecAttr* rec= m_value[hidden_no].rec;
unknown's avatar
unknown committed
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 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
    const NDBTAB *tab= (NDBTAB *) m_table;  
    const NDBCOL *hidden_col= tab->getColumn(hidden_no);
    DBUG_ASSERT(hidden_col->getPrimaryKey() && 
                hidden_col->getAutoIncrement() &&
                rec != NULL && 
                ref_length == NDB_HIDDEN_PRIMARY_KEY_LENGTH);
    memcpy(ref, (const void*)rec->aRef(), ref_length);
  }
  
  DBUG_DUMP("ref", (char*)ref, ref_length);
  DBUG_VOID_RETURN;
}


void ha_ndbcluster::info(uint flag)
{
  DBUG_ENTER("info");
  DBUG_PRINT("enter", ("flag: %d", flag));
  
  if (flag & HA_STATUS_POS)
    DBUG_PRINT("info", ("HA_STATUS_POS"));
  if (flag & HA_STATUS_NO_LOCK)
    DBUG_PRINT("info", ("HA_STATUS_NO_LOCK"));
  if (flag & HA_STATUS_TIME)
    DBUG_PRINT("info", ("HA_STATUS_TIME"));
  if (flag & HA_STATUS_CONST)
    DBUG_PRINT("info", ("HA_STATUS_CONST"));
  if (flag & HA_STATUS_VARIABLE)
    DBUG_PRINT("info", ("HA_STATUS_VARIABLE"));
  if (flag & HA_STATUS_ERRKEY)
    DBUG_PRINT("info", ("HA_STATUS_ERRKEY"));
  if (flag & HA_STATUS_AUTO)
    DBUG_PRINT("info", ("HA_STATUS_AUTO"));
  DBUG_VOID_RETURN;
}


int ha_ndbcluster::extra(enum ha_extra_function operation)
{
  DBUG_ENTER("extra");
  switch (operation) {
  case HA_EXTRA_NORMAL:              /* Optimize for space (def) */
    DBUG_PRINT("info", ("HA_EXTRA_NORMAL"));
    break;
  case HA_EXTRA_QUICK:                 /* Optimize for speed */
    DBUG_PRINT("info", ("HA_EXTRA_QUICK"));
    break;
  case HA_EXTRA_RESET:                 /* Reset database to after open */
    DBUG_PRINT("info", ("HA_EXTRA_RESET"));
    break;
  case HA_EXTRA_CACHE:                 /* Cash record in HA_rrnd() */
    DBUG_PRINT("info", ("HA_EXTRA_CACHE"));
    break;
  case HA_EXTRA_NO_CACHE:              /* End cacheing of records (def) */
    DBUG_PRINT("info", ("HA_EXTRA_NO_CACHE"));
    break;
  case HA_EXTRA_NO_READCHECK:          /* No readcheck on update */
    DBUG_PRINT("info", ("HA_EXTRA_NO_READCHECK"));
    break;
  case HA_EXTRA_READCHECK:             /* Use readcheck (def) */
    DBUG_PRINT("info", ("HA_EXTRA_READCHECK"));
    break;
  case HA_EXTRA_KEYREAD:               /* Read only key to database */
    DBUG_PRINT("info", ("HA_EXTRA_KEYREAD"));
    break;
  case HA_EXTRA_NO_KEYREAD:            /* Normal read of records (def) */
    DBUG_PRINT("info", ("HA_EXTRA_NO_KEYREAD"));
    break;
  case HA_EXTRA_NO_USER_CHANGE:        /* No user is allowed to write */
    DBUG_PRINT("info", ("HA_EXTRA_NO_USER_CHANGE"));
    break;
  case HA_EXTRA_KEY_CACHE:
    DBUG_PRINT("info", ("HA_EXTRA_KEY_CACHE"));
    break;
  case HA_EXTRA_NO_KEY_CACHE:
    DBUG_PRINT("info", ("HA_EXTRA_NO_KEY_CACHE"));
    break;
  case HA_EXTRA_WAIT_LOCK:            /* Wait until file is avalably (def) */
    DBUG_PRINT("info", ("HA_EXTRA_WAIT_LOCK"));
    break;
  case HA_EXTRA_NO_WAIT_LOCK:         /* If file is locked, return quickly */
    DBUG_PRINT("info", ("HA_EXTRA_NO_WAIT_LOCK"));
    break;
  case HA_EXTRA_WRITE_CACHE:           /* Use write cache in ha_write() */
    DBUG_PRINT("info", ("HA_EXTRA_WRITE_CACHE"));
    break;
  case HA_EXTRA_FLUSH_CACHE:           /* flush write_record_cache */
    DBUG_PRINT("info", ("HA_EXTRA_FLUSH_CACHE"));
    break;
  case HA_EXTRA_NO_KEYS:               /* Remove all update of keys */
    DBUG_PRINT("info", ("HA_EXTRA_NO_KEYS"));
    break;
  case HA_EXTRA_KEYREAD_CHANGE_POS:         /* Keyread, but change pos */
    DBUG_PRINT("info", ("HA_EXTRA_KEYREAD_CHANGE_POS")); /* xxxxchk -r must be used */
    break;                                  
  case HA_EXTRA_REMEMBER_POS:          /* Remember pos for next/prev */
    DBUG_PRINT("info", ("HA_EXTRA_REMEMBER_POS"));
    break;
  case HA_EXTRA_RESTORE_POS:
    DBUG_PRINT("info", ("HA_EXTRA_RESTORE_POS"));
    break;
  case HA_EXTRA_REINIT_CACHE:          /* init cache from current record */
    DBUG_PRINT("info", ("HA_EXTRA_REINIT_CACHE"));
    break;
  case HA_EXTRA_FORCE_REOPEN:          /* Datafile have changed on disk */
    DBUG_PRINT("info", ("HA_EXTRA_FORCE_REOPEN"));
    break;
  case HA_EXTRA_FLUSH:                 /* Flush tables to disk */
    DBUG_PRINT("info", ("HA_EXTRA_FLUSH"));
    break;
  case HA_EXTRA_NO_ROWS:               /* Don't write rows */
    DBUG_PRINT("info", ("HA_EXTRA_NO_ROWS"));
    break;
  case HA_EXTRA_RESET_STATE:           /* Reset positions */
    DBUG_PRINT("info", ("HA_EXTRA_RESET_STATE"));
    break;
  case HA_EXTRA_IGNORE_DUP_KEY:       /* Dup keys don't rollback everything*/
    DBUG_PRINT("info", ("HA_EXTRA_IGNORE_DUP_KEY"));

    DBUG_PRINT("info", ("Turning ON use of write instead of insert"));
    m_use_write= TRUE;
    break;
  case HA_EXTRA_NO_IGNORE_DUP_KEY:
    DBUG_PRINT("info", ("HA_EXTRA_NO_IGNORE_DUP_KEY"));
    DBUG_PRINT("info", ("Turning OFF use of write instead of insert"));
    m_use_write= false;
    break;
  case HA_EXTRA_RETRIEVE_ALL_COLS:    /* Retrieve all columns, not just those
					 where field->query_id is the same as
					 the current query id */
    DBUG_PRINT("info", ("HA_EXTRA_RETRIEVE_ALL_COLS"));
2261
    retrieve_all_fields= TRUE;
unknown's avatar
unknown committed
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
    break;
  case HA_EXTRA_PREPARE_FOR_DELETE:
    DBUG_PRINT("info", ("HA_EXTRA_PREPARE_FOR_DELETE"));
    break;
  case HA_EXTRA_PREPARE_FOR_UPDATE:     /* Remove read cache if problems */
    DBUG_PRINT("info", ("HA_EXTRA_PREPARE_FOR_UPDATE"));
    break;
  case HA_EXTRA_PRELOAD_BUFFER_SIZE: 
    DBUG_PRINT("info", ("HA_EXTRA_PRELOAD_BUFFER_SIZE"));
    break;
  case HA_EXTRA_RETRIEVE_PRIMARY_KEY: 
    DBUG_PRINT("info", ("HA_EXTRA_RETRIEVE_PRIMARY_KEY"));
    break;
  case HA_EXTRA_CHANGE_KEY_TO_UNIQUE: 
    DBUG_PRINT("info", ("HA_EXTRA_CHANGE_KEY_TO_UNIQUE"));
    break;
  case HA_EXTRA_CHANGE_KEY_TO_DUP: 
    DBUG_PRINT("info", ("HA_EXTRA_CHANGE_KEY_TO_DUP"));
    break;

  }
  
  DBUG_RETURN(0);
}

2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
/* 
   Start of an insert, remember number of rows to be inserted, it will
   be used in write_row and get_autoincrement to send an optimal number
   of rows in each roundtrip to the server

   SYNOPSIS
   rows     number of rows to insert, 0 if unknown

*/

void ha_ndbcluster::start_bulk_insert(ha_rows rows)
{
  int bytes, batch;
  const NDBTAB *tab= (NDBTAB *) m_table;    

  DBUG_ENTER("start_bulk_insert");
unknown's avatar
unknown committed
2303
  DBUG_PRINT("enter", ("rows: %d", (int)rows));
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
  
  rows_inserted= 0;
  rows_to_insert= rows; 

  /* 
    Calculate how many rows that should be inserted
    per roundtrip to NDB. This is done in order to minimize the 
    number of roundtrips as much as possible. However performance will 
    degrade if too many bytes are inserted, thus it's limited by this 
    calculation.   
  */
2315
  const int bytesperbatch= 8192;
2316
  bytes= 12 + tab->getRowSizeInBytes() + 4 * tab->getNoOfColumns();
2317
  batch= bytesperbatch/bytes;
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
  batch= batch == 0 ? 1 : batch;
  DBUG_PRINT("info", ("batch: %d, bytes: %d", batch, bytes));
  bulk_insert_rows= batch;

  DBUG_VOID_RETURN;
}

/*
  End of an insert
 */
int ha_ndbcluster::end_bulk_insert()
{
2330 2331
  int error= 0;

2332
  DBUG_ENTER("end_bulk_insert");
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
  // Check if last inserts need to be flushed
  if (bulk_insert_not_flushed)
  {
    NdbConnection *trans= m_active_trans;
    // Send rows to NDB
    DBUG_PRINT("info", ("Sending inserts to NDB, "\
                        "rows_inserted:%d, bulk_insert_rows: %d", 
                        rows_inserted, bulk_insert_rows)); 
    bulk_insert_not_flushed= false;
    if (trans->execute(NoCommit) != 0)
      error= ndb_err(trans);
  }

2346 2347
  rows_inserted= 0;
  rows_to_insert= 1;
2348
  DBUG_RETURN(error);
2349 2350
}

unknown's avatar
unknown committed
2351 2352 2353 2354

int ha_ndbcluster::extra_opt(enum ha_extra_function operation, ulong cache_size)
{
  DBUG_ENTER("extra_opt");
unknown's avatar
unknown committed
2355
  DBUG_PRINT("enter", ("cache_size: %lu", cache_size));
unknown's avatar
unknown committed
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
  DBUG_RETURN(extra(operation));
}


int ha_ndbcluster::reset()
{
  DBUG_ENTER("reset");
  // Reset what?
  DBUG_RETURN(1);
}


const char **ha_ndbcluster::bas_ext() const
2369
{ static const char *ext[1]= { NullS }; return ext; }
unknown's avatar
unknown committed
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379


/*
  How many seeks it will take to read through the table
  This is to be comparable to the number returned by records_in_range so
  that we can decide if we should scan the table or use keys.
*/

double ha_ndbcluster::scan_time()
{
2380
  return rows2double(records*1000);
unknown's avatar
unknown committed
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
}


THR_LOCK_DATA **ha_ndbcluster::store_lock(THD *thd,
                                          THR_LOCK_DATA **to,
                                          enum thr_lock_type lock_type)
{
  DBUG_ENTER("store_lock");
  
  if (lock_type != TL_IGNORE && m_lock.type == TL_UNLOCK) 
  {
    
    /* If we are not doing a LOCK TABLE, then allow multiple
       writers */
    
    if ((lock_type >= TL_WRITE_CONCURRENT_INSERT &&
         lock_type <= TL_WRITE) && !thd->in_lock_tables)      
      lock_type= TL_WRITE_ALLOW_WRITE;
    
    /* In queries of type INSERT INTO t1 SELECT ... FROM t2 ...
       MySQL would use the lock TL_READ_NO_INSERT on t2, and that
       would conflict with TL_WRITE_ALLOW_WRITE, blocking all inserts
       to t2. Convert the lock to a normal read lock to allow
       concurrent inserts to t2. */
    
    if (lock_type == TL_READ_NO_INSERT && !thd->in_lock_tables)
      lock_type= TL_READ;
    
    m_lock.type=lock_type;
  }
  *to++= &m_lock;
2412 2413

  DBUG_PRINT("exit", ("lock_type: %d", lock_type));
unknown's avatar
unknown committed
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 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
  
  DBUG_RETURN(to);
}

#ifndef DBUG_OFF
#define PRINT_OPTION_FLAGS(t) { \
      if (t->options & OPTION_NOT_AUTOCOMMIT) \
        DBUG_PRINT("thd->options", ("OPTION_NOT_AUTOCOMMIT")); \
      if (t->options & OPTION_BEGIN) \
        DBUG_PRINT("thd->options", ("OPTION_BEGIN")); \
      if (t->options & OPTION_TABLE_LOCK) \
        DBUG_PRINT("thd->options", ("OPTION_TABLE_LOCK")); \
}
#else
#define PRINT_OPTION_FLAGS(t)
#endif


/*
  As MySQL will execute an external lock for every new table it uses
  we can use this to start the transactions.
  If we are in auto_commit mode we just need to start a transaction
  for the statement, this will be stored in transaction.stmt.
  If not, we have to start a master transaction if there doesn't exist
  one from before, this will be stored in transaction.all
 
  When a table lock is held one transaction will be started which holds
  the table lock and for each statement a hupp transaction will be started  
 */

int ha_ndbcluster::external_lock(THD *thd, int lock_type)
{
  int error=0;
  NdbConnection* trans= NULL;

  DBUG_ENTER("external_lock");
  DBUG_PRINT("enter", ("transaction.ndb_lock_count: %d", 
                       thd->transaction.ndb_lock_count));

  /*
    Check that this handler instance has a connection
    set up to the Ndb object of thd
   */
  if (check_ndb_connection())
    DBUG_RETURN(1);
 
  if (lock_type != F_UNLCK)
  {
2462
    DBUG_PRINT("info", ("lock_type != F_UNLCK"));
unknown's avatar
unknown committed
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 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    if (!thd->transaction.ndb_lock_count++)
    {
      PRINT_OPTION_FLAGS(thd);

      if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN | OPTION_TABLE_LOCK))) 
      {
        // Autocommit transaction
        DBUG_ASSERT(!thd->transaction.stmt.ndb_tid);
        DBUG_PRINT("trans",("Starting transaction stmt"));      

        trans= m_ndb->startTransaction();
        if (trans == NULL)
	{     
          thd->transaction.ndb_lock_count--;    // We didn't get the lock
          ERR_RETURN(m_ndb->getNdbError());
        }
        thd->transaction.stmt.ndb_tid= trans;
      } 
      else 
      { 
        if (!thd->transaction.all.ndb_tid)
	{
          // Not autocommit transaction
          // A "master" transaction ha not been started yet
          DBUG_PRINT("trans",("starting transaction, all"));
          
          trans= m_ndb->startTransaction();
          if (trans == NULL)
	  {   
            thd->transaction.ndb_lock_count--;  // We didn't get the lock
            ERR_RETURN(m_ndb->getNdbError());
          }       

          /*
            If this is the start of a LOCK TABLE, a table look 
            should be taken on the table in NDB
           
            Check if it should be read or write lock
           */
          if (thd->options & (OPTION_TABLE_LOCK))
	  {
            //lockThisTable();
            DBUG_PRINT("info", ("Locking the table..." ));
          }

          thd->transaction.all.ndb_tid= trans; 
        }
      }
    }
    /*
      This is the place to make sure this handler instance
      has a started transaction.
     
      The transaction is started by the first handler on which 
      MySQL Server calls external lock
     
      Other handlers in the same stmt or transaction should use 
      the same NDB transaction. This is done by setting up the m_active_trans
      pointer to point to the NDB transaction. 
     */

    m_active_trans= thd->transaction.all.ndb_tid ? 
      (NdbConnection*)thd->transaction.all.ndb_tid:
      (NdbConnection*)thd->transaction.stmt.ndb_tid;
    DBUG_ASSERT(m_active_trans);
2528

2529
    // Start of transaction
2530
    retrieve_all_fields= FALSE;
2531
    ops_pending= 0;    
unknown's avatar
unknown committed
2532 2533 2534
  } 
  else 
  {
2535
    DBUG_PRINT("info", ("lock_type == F_UNLCK"));
unknown's avatar
unknown committed
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
    if (!--thd->transaction.ndb_lock_count)
    {
      DBUG_PRINT("trans", ("Last external_lock"));
      PRINT_OPTION_FLAGS(thd);

      if (thd->transaction.stmt.ndb_tid)
      {
        /*
          Unlock is done without a transaction commit / rollback.
          This happens if the thread didn't update any rows
          We must in this case close the transaction to release resources
        */
        DBUG_PRINT("trans",("ending non-updating transaction"));
        m_ndb->closeTransaction(m_active_trans);
        thd->transaction.stmt.ndb_tid= 0;
      }
    }
    m_active_trans= NULL;
  }
  DBUG_RETURN(error);
}

/*
  When using LOCK TABLE's external_lock is only called when the actual
  TABLE LOCK is done.
  Under LOCK TABLES, each used tables will force a call to start_stmt.
*/

int ha_ndbcluster::start_stmt(THD *thd)
{
  int error=0;
  DBUG_ENTER("start_stmt");
  PRINT_OPTION_FLAGS(thd);

  NdbConnection *trans= (NdbConnection*)thd->transaction.stmt.ndb_tid;
  if (!trans){
    DBUG_PRINT("trans",("Starting transaction stmt"));  
    
    NdbConnection *tablock_trans= 
      (NdbConnection*)thd->transaction.all.ndb_tid;
unknown's avatar
unknown committed
2576
    DBUG_PRINT("info", ("tablock_trans: %x", (uint)tablock_trans));
unknown's avatar
unknown committed
2577 2578 2579 2580 2581 2582
    DBUG_ASSERT(tablock_trans);    trans= m_ndb->hupp(tablock_trans);
    if (trans == NULL)
      ERR_RETURN(m_ndb->getNdbError());
    thd->transaction.stmt.ndb_tid= trans;
  }
  m_active_trans= trans;
2583

2584
  // Start of statement
2585
  retrieve_all_fields= FALSE;
2586
  ops_pending= 0;    
unknown's avatar
unknown committed
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
  
  DBUG_RETURN(error);
}


/*
  Commit a transaction started in NDB 
 */

int ndbcluster_commit(THD *thd, void *ndb_transaction)
{
  int res= 0;
  Ndb *ndb= (Ndb*)thd->transaction.ndb;
  NdbConnection *trans= (NdbConnection*)ndb_transaction;

  DBUG_ENTER("ndbcluster_commit");
  DBUG_PRINT("transaction",("%s",
                            trans == thd->transaction.stmt.ndb_tid ? 
                            "stmt" : "all"));
  DBUG_ASSERT(ndb && trans);

  if (trans->execute(Commit) != 0)
  {
    const NdbError err= trans->getNdbError();
2611
    const NdbOperation *error_op= trans->getNdbErrorOperation();
unknown's avatar
unknown committed
2612 2613
    ERR_PRINT(err);     
    res= ndb_to_mysql_error(&err);
2614 2615
    if (res != -1)
      ndbcluster_print_error(res, error_op);
unknown's avatar
unknown committed
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
  }
  ndb->closeTransaction(trans);    
  DBUG_RETURN(res);
}


/*
  Rollback a transaction started in NDB
 */

int ndbcluster_rollback(THD *thd, void *ndb_transaction)
{
  int res= 0;
  Ndb *ndb= (Ndb*)thd->transaction.ndb;
  NdbConnection *trans= (NdbConnection*)ndb_transaction;

  DBUG_ENTER("ndbcluster_rollback");
  DBUG_PRINT("transaction",("%s",
                            trans == thd->transaction.stmt.ndb_tid ? 
                            "stmt" : "all"));
  DBUG_ASSERT(ndb && trans);

  if (trans->execute(Rollback) != 0)
  {
    const NdbError err= trans->getNdbError();
2641
    const NdbOperation *error_op= trans->getNdbErrorOperation();
unknown's avatar
unknown committed
2642 2643
    ERR_PRINT(err);     
    res= ndb_to_mysql_error(&err);
2644 2645
    if (res != -1) 
      ndbcluster_print_error(res, error_op);
unknown's avatar
unknown committed
2646 2647 2648 2649 2650 2651 2652
  }
  ndb->closeTransaction(trans);
  DBUG_RETURN(0);
}


/*
unknown's avatar
unknown committed
2653 2654 2655
  Define NDB column based on Field.
  Returns 0 or mysql error code.
  Not member of ha_ndbcluster because NDBCOL cannot be declared.
unknown's avatar
unknown committed
2656 2657
 */

unknown's avatar
unknown committed
2658 2659 2660
static int create_ndb_column(NDBCOL &col,
                             Field *field,
                             HA_CREATE_INFO *info)
unknown's avatar
unknown committed
2661
{
unknown's avatar
unknown committed
2662 2663 2664 2665 2666 2667
  // Set name
  col.setName(field->field_name);
  // Set type and sizes
  const enum enum_field_types mysql_type= field->real_type();
  switch (mysql_type) {
  // Numeric types
unknown's avatar
unknown committed
2668
  case MYSQL_TYPE_DECIMAL:    
unknown's avatar
unknown committed
2669 2670 2671
    col.setType(NDBCOL::Char);
    col.setLength(field->pack_length());
    break;
unknown's avatar
unknown committed
2672
  case MYSQL_TYPE_TINY:        
unknown's avatar
unknown committed
2673 2674 2675 2676 2677 2678
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Tinyunsigned);
    else
      col.setType(NDBCOL::Tinyint);
    col.setLength(1);
    break;
unknown's avatar
unknown committed
2679
  case MYSQL_TYPE_SHORT:
unknown's avatar
unknown committed
2680 2681 2682 2683 2684 2685
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Smallunsigned);
    else
      col.setType(NDBCOL::Smallint);
    col.setLength(1);
    break;
unknown's avatar
unknown committed
2686
  case MYSQL_TYPE_LONG:
unknown's avatar
unknown committed
2687 2688 2689 2690 2691 2692
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Unsigned);
    else
      col.setType(NDBCOL::Int);
    col.setLength(1);
    break;
unknown's avatar
unknown committed
2693
  case MYSQL_TYPE_INT24:       
unknown's avatar
unknown committed
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Mediumunsigned);
    else
      col.setType(NDBCOL::Mediumint);
    col.setLength(1);
    break;
  case MYSQL_TYPE_LONGLONG:
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Bigunsigned);
    else
      col.setType(NDBCOL::Bigint);
    col.setLength(1);
unknown's avatar
unknown committed
2706 2707
    break;
  case MYSQL_TYPE_FLOAT:
unknown's avatar
unknown committed
2708 2709 2710
    col.setType(NDBCOL::Float);
    col.setLength(1);
    break;
unknown's avatar
unknown committed
2711
  case MYSQL_TYPE_DOUBLE:
unknown's avatar
unknown committed
2712 2713 2714 2715 2716 2717 2718 2719 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 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
    col.setType(NDBCOL::Double);
    col.setLength(1);
    break;
  // Date types
  case MYSQL_TYPE_TIMESTAMP:
    col.setType(NDBCOL::Unsigned);
    col.setLength(1);
    break;
  case MYSQL_TYPE_DATETIME:    
    col.setType(NDBCOL::Datetime);
    col.setLength(1);
    break;
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_TIME:        
  case MYSQL_TYPE_YEAR:        
    col.setType(NDBCOL::Char);
    col.setLength(field->pack_length());
    break;
  // Char types
  case MYSQL_TYPE_STRING:      
    if (field->flags & BINARY_FLAG)
      col.setType(NDBCOL::Binary);
    else
      col.setType(NDBCOL::Char);
    col.setLength(field->pack_length());
    break;
  case MYSQL_TYPE_VAR_STRING:
    if (field->flags & BINARY_FLAG)
      col.setType(NDBCOL::Varbinary);
    else
      col.setType(NDBCOL::Varchar);
    col.setLength(field->pack_length());
    break;
  // Blob types (all come in as MYSQL_TYPE_BLOB)
  mysql_type_tiny_blob:
  case MYSQL_TYPE_TINY_BLOB:
    if (field->flags & BINARY_FLAG)
      col.setType(NDBCOL::Blob);
    else
      col.setType(NDBCOL::Text);
    col.setInlineSize(256);
    // No parts
    col.setPartSize(0);
    col.setStripeSize(0);
    break;
  mysql_type_blob:
  case MYSQL_TYPE_BLOB:    
    if (field->flags & BINARY_FLAG)
      col.setType(NDBCOL::Blob);
    else
      col.setType(NDBCOL::Text);
    // Use "<=" even if "<" is the exact condition
    if (field->max_length() <= (1 << 8))
      goto mysql_type_tiny_blob;
    else if (field->max_length() <= (1 << 16))
    {
      col.setInlineSize(256);
      col.setPartSize(2000);
      col.setStripeSize(16);
    }
    else if (field->max_length() <= (1 << 24))
      goto mysql_type_medium_blob;
    else
      goto mysql_type_long_blob;
    break;
  mysql_type_medium_blob:
  case MYSQL_TYPE_MEDIUM_BLOB:   
    if (field->flags & BINARY_FLAG)
      col.setType(NDBCOL::Blob);
    else
      col.setType(NDBCOL::Text);
    col.setInlineSize(256);
    col.setPartSize(4000);
    col.setStripeSize(8);
    break;
  mysql_type_long_blob:
  case MYSQL_TYPE_LONG_BLOB:  
    if (field->flags & BINARY_FLAG)
      col.setType(NDBCOL::Blob);
    else
      col.setType(NDBCOL::Text);
    col.setInlineSize(256);
    col.setPartSize(8000);
    col.setStripeSize(4);
    break;
  // Other types
  case MYSQL_TYPE_ENUM:
    col.setType(NDBCOL::Char);
    col.setLength(field->pack_length());
    break;
  case MYSQL_TYPE_SET:         
    col.setType(NDBCOL::Char);
    col.setLength(field->pack_length());
    break;
  case MYSQL_TYPE_NULL:        
  case MYSQL_TYPE_GEOMETRY:
    goto mysql_type_unsupported;
  mysql_type_unsupported:
  default:
    return HA_ERR_UNSUPPORTED;
unknown's avatar
unknown committed
2813
  }
unknown's avatar
unknown committed
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
  // Set nullable and pk
  col.setNullable(field->maybe_null());
  col.setPrimaryKey(field->flags & PRI_KEY_FLAG);
  // Set autoincrement
  if (field->flags & AUTO_INCREMENT_FLAG) 
  {
    col.setAutoIncrement(TRUE);
    ulonglong value= info->auto_increment_value ?
      info->auto_increment_value -1 : (ulonglong) 0;
    DBUG_PRINT("info", ("Autoincrement key, initial: %llu", value));
    col.setAutoIncrementInitialValue(value);
unknown's avatar
unknown committed
2825
  }
unknown's avatar
unknown committed
2826 2827 2828
  else
    col.setAutoIncrement(false);
  return 0;
unknown's avatar
unknown committed
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
}

/*
  Create a table in NDB Cluster
 */

int ha_ndbcluster::create(const char *name, 
			  TABLE *form, 
			  HA_CREATE_INFO *info)
{
  NDBTAB tab;
  NDBCOL col;
  uint pack_length, length, i;
  const void *data, *pack_data;
2843
  const char **key_names= form->keynames.type_names;
unknown's avatar
unknown committed
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
  char name2[FN_HEADLEN];
   
  DBUG_ENTER("create");
  DBUG_PRINT("enter", ("name: %s", name));
  fn_format(name2, name, "", "",2);       // Remove the .frm extension
  set_dbname(name2);
  set_tabname(name2);  

  DBUG_PRINT("table", ("name: %s", m_tabname));  
  tab.setName(m_tabname);
  tab.setLogging(!(info->options & HA_LEX_CREATE_TMP_TABLE));    
   
  // Save frm data for this table
  if (readfrm(name, &data, &length))
    DBUG_RETURN(1);
  if (packfrm(data, length, &pack_data, &pack_length))
    DBUG_RETURN(2);
  
  DBUG_PRINT("info", ("setFrm data=%x, len=%d", pack_data, pack_length));
  tab.setFrm(pack_data, pack_length);      
  my_free((char*)data, MYF(0));
  my_free((char*)pack_data, MYF(0));
  
  for (i= 0; i < form->fields; i++) 
  {
    Field *field= form->field[i];
    DBUG_PRINT("info", ("name: %s, type: %u, pack_length: %d", 
                        field->field_name, field->real_type(),
			field->pack_length()));
2873
    if ((my_errno= create_ndb_column(col, field, info)))
unknown's avatar
unknown committed
2874
      DBUG_RETURN(my_errno);
unknown's avatar
unknown committed
2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
    tab.addColumn(col);
  }
  
  // No primary key, create shadow key as 64 bit, auto increment  
  if (form->primary_key == MAX_KEY) 
  {
    DBUG_PRINT("info", ("Generating shadow key"));
    col.setName("$PK");
    col.setType(NdbDictionary::Column::Bigunsigned);
    col.setLength(1);
    col.setNullable(false);
    col.setPrimaryKey(TRUE);
    col.setAutoIncrement(TRUE);
    tab.addColumn(col);
  }
  
  my_errno= 0;
  if (check_ndb_connection())
  {
    my_errno= HA_ERR_NO_CONNECTION;
    DBUG_RETURN(my_errno);
  }
  
  // Create the table in NDB     
  NDBDICT *dict= m_ndb->getDictionary();
  if (dict->createTable(tab)) 
  {
    const NdbError err= dict->getNdbError();
    ERR_PRINT(err);
    my_errno= ndb_to_mysql_error(&err);
    DBUG_RETURN(my_errno);
  }
  DBUG_PRINT("info", ("Table %s/%s created successfully", 
                      m_dbname, m_tabname));
2909

unknown's avatar
unknown committed
2910 2911
  // Create secondary indexes
  my_errno= build_index_list(form, ILBP_CREATE);
2912

unknown's avatar
unknown committed
2913 2914 2915 2916
  DBUG_RETURN(my_errno);
}


2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
int ha_ndbcluster::create_ordered_index(const char *name, 
					KEY *key_info)
{
  DBUG_ENTER("create_ordered_index");
  DBUG_RETURN(create_index(name, key_info, false));
}

int ha_ndbcluster::create_unique_index(const char *name, 
				       KEY *key_info)
{

2928 2929
  DBUG_ENTER("create_unique_index");
  DBUG_RETURN(create_index(name, key_info, true));
2930 2931 2932
}


unknown's avatar
unknown committed
2933 2934 2935 2936 2937
/*
  Create an index in NDB Cluster
 */

int ha_ndbcluster::create_index(const char *name, 
2938 2939 2940
				KEY *key_info,
				bool unique)
{
unknown's avatar
unknown committed
2941 2942 2943 2944 2945 2946
  NdbDictionary::Dictionary *dict= m_ndb->getDictionary();
  KEY_PART_INFO *key_part= key_info->key_part;
  KEY_PART_INFO *end= key_part + key_info->key_parts;
  
  DBUG_ENTER("create_index");
  DBUG_PRINT("enter", ("name: %s ", name));
2947

2948
  //  NdbDictionary::Index ndb_index(name);
unknown's avatar
unknown committed
2949
  NdbDictionary::Index ndb_index(name);
2950
  if (unique)
unknown's avatar
unknown committed
2951 2952 2953 2954 2955 2956 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 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
    ndb_index.setType(NdbDictionary::Index::UniqueHashIndex);
  else 
  {
    ndb_index.setType(NdbDictionary::Index::OrderedIndex);
    // TODO Only temporary ordered indexes supported
    ndb_index.setLogging(false); 
  }
  ndb_index.setTable(m_tabname);

  for (; key_part != end; key_part++) 
  {
    Field *field= key_part->field;
    DBUG_PRINT("info", ("attr: %s", field->field_name));
    ndb_index.addColumnName(field->field_name);
  }
  
  if (dict->createIndex(ndb_index))
    ERR_RETURN(dict->getNdbError());

  // Success
  DBUG_PRINT("info", ("Created index %s", name));
  DBUG_RETURN(0);  
}


/*
  Rename a table in NDB Cluster
*/

int ha_ndbcluster::rename_table(const char *from, const char *to)
{
  char new_tabname[FN_HEADLEN];

  DBUG_ENTER("ha_ndbcluster::rename_table");
  set_dbname(from);
  set_tabname(from);
  set_tabname(to, new_tabname);

  if (check_ndb_connection()) {
    my_errno= HA_ERR_NO_CONNECTION;
    DBUG_RETURN(my_errno);
  }

  int result= alter_table_name(m_tabname, new_tabname);
  if (result == 0)
    set_tabname(to);
  
  DBUG_RETURN(result);
}


/*
  Rename a table in NDB Cluster using alter table
 */

int ha_ndbcluster::alter_table_name(const char *from, const char *to)
{
  NDBDICT *dict= m_ndb->getDictionary();
  const NDBTAB *orig_tab;
  DBUG_ENTER("alter_table_name_table");
  DBUG_PRINT("enter", ("Renaming %s to %s", from, to));

  if (!(orig_tab= dict->getTable(from)))
    ERR_RETURN(dict->getNdbError());
      
  NdbDictionary::Table copy_tab= dict->getTableForAlteration(from);
  copy_tab.setName(to);
  if (dict->alterTable(copy_tab) != 0)
    ERR_RETURN(dict->getNdbError());

  m_table= NULL;
                                                                             
  DBUG_RETURN(0);
}


/*
  Delete a table from NDB Cluster
 */

int ha_ndbcluster::delete_table(const char *name)
{
  DBUG_ENTER("delete_table");
  DBUG_PRINT("enter", ("name: %s", name));
  set_dbname(name);
  set_tabname(name);
  
  if (check_ndb_connection())
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
  DBUG_RETURN(drop_table());
}


/*
  Drop a table in NDB Cluster
 */

int ha_ndbcluster::drop_table()
{
  NdbDictionary::Dictionary *dict= m_ndb->getDictionary();

  DBUG_ENTER("drop_table");
  DBUG_PRINT("enter", ("Deleting %s", m_tabname));
  
  if (dict->dropTable(m_tabname)) 
  {
    const NdbError err= dict->getNdbError();
    if (err.code == 709)
      ; // 709: No such table existed
    else 
      ERR_RETURN(dict->getNdbError());
  }  
  release_metadata();
  DBUG_RETURN(0);
}


/*
  Drop a database in NDB Cluster
 */

int ndbcluster_drop_database(const char *path)
{
  DBUG_ENTER("ndbcluster_drop_database");
  // TODO drop all tables for this database
  DBUG_RETURN(1);
}


longlong ha_ndbcluster::get_auto_increment()
3081
{  
unknown's avatar
unknown committed
3082 3083
  DBUG_ENTER("get_auto_increment");
  DBUG_PRINT("enter", ("m_tabname: %s", m_tabname));
3084 3085 3086 3087
  int cache_size= 
    (rows_to_insert > autoincrement_prefetch) ? 
    rows_to_insert 
    : autoincrement_prefetch;
3088
  Uint64 auto_value= 
unknown's avatar
unknown committed
3089
    (skip_auto_increment) ? 
3090 3091
    m_ndb->readAutoIncrementValue((NDBTAB *) m_table)
    : m_ndb->getAutoIncrementValue((NDBTAB *) m_table, cache_size);
unknown's avatar
unknown committed
3092
  DBUG_RETURN((longlong)auto_value);
unknown's avatar
unknown committed
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
}


/*
  Constructor for the NDB Cluster table handler 
 */

ha_ndbcluster::ha_ndbcluster(TABLE *table_arg):
  handler(table_arg),
  m_active_trans(NULL),
  m_active_cursor(NULL),
  m_ndb(NULL),
  m_table(NULL),
  m_table_flags(HA_REC_NOT_IN_SEQ |
3107
		//HA_NULL_IN_KEY |
unknown's avatar
unknown committed
3108
                HA_NOT_EXACT_COUNT |
unknown's avatar
unknown committed
3109
                HA_NO_PREFIX_CHAR_KEYS),
3110
  m_use_write(false),
3111
  retrieve_all_fields(FALSE),
3112
  rows_to_insert(1),
3113
  rows_inserted(0),
3114
  bulk_insert_rows(1024),
3115
  bulk_insert_not_flushed(false),
unknown's avatar
unknown committed
3116
  ops_pending(0),
unknown's avatar
unknown committed
3117
  skip_auto_increment(true),
unknown's avatar
unknown committed
3118 3119
  blobs_buffer(0),
  blobs_buffer_size(0)
unknown's avatar
unknown committed
3120
{ 
3121 3122
  int i;
  
unknown's avatar
unknown committed
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
  DBUG_ENTER("ha_ndbcluster");

  m_tabname[0]= '\0';
  m_dbname[0]= '\0';

  // TODO Adjust number of records and other parameters for proper 
  // selection of scan/pk access
  records= 100;
  block_size= 1024;

3133 3134
  for (i= 0; i < MAX_KEY; i++)
  {
3135 3136 3137 3138
    m_index[i].type= UNDEFINED_INDEX;   
    m_index[i].unique_name= NULL;      
    m_index[i].unique_index= NULL;      
    m_index[i].index= NULL;      
3139 3140
  }

unknown's avatar
unknown committed
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
  DBUG_VOID_RETURN;
}


/*
  Destructor for NDB Cluster table handler
 */

ha_ndbcluster::~ha_ndbcluster() 
{
  DBUG_ENTER("~ha_ndbcluster");

  release_metadata();
unknown's avatar
unknown committed
3154 3155
  my_free(blobs_buffer, MYF(MY_ALLOW_ZERO_PTR));
  blobs_buffer= 0;
unknown's avatar
unknown committed
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227

  // Check for open cursor/transaction
  DBUG_ASSERT(m_active_cursor == NULL);
  DBUG_ASSERT(m_active_trans == NULL);

  DBUG_VOID_RETURN;
}


/*
  Open a table for further use
  - fetch metadata for this table from NDB
  - check that table exists
*/

int ha_ndbcluster::open(const char *name, int mode, uint test_if_locked)
{
  KEY *key;
  DBUG_ENTER("open");
  DBUG_PRINT("enter", ("name: %s mode: %d test_if_locked: %d",
                       name, mode, test_if_locked));
  
  // Setup ref_length to make room for the whole 
  // primary key to be written in the ref variable
  
  if (table->primary_key != MAX_KEY) 
  {
    key= table->key_info+table->primary_key;
    ref_length= key->key_length;
    DBUG_PRINT("info", (" ref_length: %d", ref_length));
  }
  // Init table lock structure 
  if (!(m_share=get_share(name)))
    DBUG_RETURN(1);
  thr_lock_data_init(&m_share->lock,&m_lock,(void*) 0);
  
  set_dbname(name);
  set_tabname(name);
  
  if (check_ndb_connection())
    DBUG_RETURN(HA_ERR_NO_CONNECTION);

  DBUG_RETURN(get_metadata(name));
}


/*
  Close the table
  - release resources setup by open()
 */

int ha_ndbcluster::close(void)
{
  DBUG_ENTER("close");  
  free_share(m_share);
  release_metadata();
  m_ndb= NULL;
  DBUG_RETURN(0);
}


Ndb* ha_ndbcluster::seize_ndb()
{
  Ndb* ndb;
  DBUG_ENTER("seize_ndb");

#ifdef USE_NDB_POOL
  // Seize from pool
  ndb= Ndb::seize();
#else
  ndb= new Ndb("");  
#endif
3228
  if (ndb->init(max_transactions) != 0)
unknown's avatar
unknown committed
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 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 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
  {
    ERR_PRINT(ndb->getNdbError());
    /*
      TODO 
      Alt.1 If init fails because to many allocated Ndb 
      wait on condition for a Ndb object to be released.
      Alt.2 Seize/release from pool, wait until next release 
    */
    delete ndb;
    ndb= NULL;
  }
  DBUG_RETURN(ndb);
}


void ha_ndbcluster::release_ndb(Ndb* ndb)
{
  DBUG_ENTER("release_ndb");
#ifdef USE_NDB_POOL
  // Release to  pool
  Ndb::release(ndb);
#else
  delete ndb;
#endif
  DBUG_VOID_RETURN;
}


/*
  If this thread already has a Ndb object allocated
  in current THD, reuse it. Otherwise
  seize a Ndb object, assign it to current THD and use it.
 
  Having a Ndb object also means that a connection to 
  NDB cluster has been opened. The connection is 
  checked.
 
*/

int ha_ndbcluster::check_ndb_connection()
{
  THD* thd= current_thd;
  Ndb* ndb;
  DBUG_ENTER("check_ndb_connection");
  
  if (!thd->transaction.ndb)
  {
    ndb= seize_ndb();
    if (!ndb)
      DBUG_RETURN(2);
    thd->transaction.ndb= ndb;
  }
  m_ndb= (Ndb*)thd->transaction.ndb;
  m_ndb->setDatabaseName(m_dbname);
  DBUG_RETURN(0);
}

void ndbcluster_close_connection(THD *thd)
{
  Ndb* ndb;
  DBUG_ENTER("ndbcluster_close_connection");
  ndb= (Ndb*)thd->transaction.ndb;
  ha_ndbcluster::release_ndb(ndb);
  thd->transaction.ndb= NULL;
  DBUG_VOID_RETURN;
}


/*
  Try to discover one table from NDB
 */

int ndbcluster_discover(const char *dbname, const char *name,
			const void** frmblob, uint* frmlen)
{
  uint len;
  const void* data;
  const NDBTAB* tab;
  DBUG_ENTER("ndbcluster_discover");
  DBUG_PRINT("enter", ("db: %s, name: %s", dbname, name)); 

  Ndb ndb(dbname);
  if ((ndb.init() != 0) && (ndb.waitUntilReady() != 0))
    ERR_RETURN(ndb.getNdbError());
  
  if (!(tab= ndb.getDictionary()->getTable(name)))
  {
    DBUG_PRINT("info", ("Table %s not found", name));
    DBUG_RETURN(1);
  }
  
  DBUG_PRINT("info", ("Found table %s", tab->getName()));
  
  len= tab->getFrmLength();  
  if (len == 0 || tab->getFrmData() == NULL)
  {
    DBUG_PRINT("No frm data found",
               ("Table is probably created via NdbApi")); 
    DBUG_RETURN(2);
  }
  
  if (unpackfrm(&data, &len, tab->getFrmData()))
    DBUG_RETURN(3);

  *frmlen= len;
  *frmblob= data;
  
  DBUG_RETURN(0);
}


#ifdef USE_DISCOVER_ON_STARTUP
/*
  Dicover tables from NDB Cluster
  - fetch a list of tables from NDB 
  - store the frm file for each table on disk 
   - if the table has an attached frm file
   - if the database of the table exists
*/

int ndb_discover_tables()
{
  uint i;
  NdbDictionary::Dictionary::List list;
  NdbDictionary::Dictionary* dict;
  char  path[FN_REFLEN];
  DBUG_ENTER("ndb_discover_tables");
  
  /* List tables in NDB Cluster kernel    */  
  dict= g_ndb->getDictionary();
  if (dict->listObjects(list, 
			NdbDictionary::Object::UserTable) != 0)
    ERR_RETURN(g_ndb->getNdbError());
  
  for (i= 0 ; i < list.count ; i++)
  {
    NdbDictionary::Dictionary::List::Element& t= list.elements[i];

    DBUG_PRINT("discover", ("%d: %s/%s", t.id, t.database, t.name));     
    if (create_table_from_handler(t.database, t.name, true))
      DBUG_PRINT("info", ("Could not discover %s/%s", t.database, t.name));
  }
  DBUG_RETURN(0);  
}
#endif


/*
  Initialise all gloal variables before creating 
  a NDB Cluster table handler
 */

bool ndbcluster_init()
{
  DBUG_ENTER("ndbcluster_init");
3384
  // Set connectstring if specified
unknown's avatar
unknown committed
3385 3386
  if (ndbcluster_connectstring != 0)
  {
3387 3388 3389
    DBUG_PRINT("connectstring", ("%s", ndbcluster_connectstring));     
    Ndb::setConnectString(ndbcluster_connectstring);
  }
unknown's avatar
unknown committed
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
  // Create a Ndb object to open the connection  to NDB
  g_ndb= new Ndb("sys");
  if (g_ndb->init() != 0)
  {
    ERR_PRINT (g_ndb->getNdbError());
    DBUG_RETURN(TRUE);
  }
  if (g_ndb->waitUntilReady() != 0)
  {
    ERR_PRINT (g_ndb->getNdbError());
    DBUG_RETURN(TRUE);   
  }
  (void) hash_init(&ndbcluster_open_tables,system_charset_info,32,0,0,
                   (hash_get_key) ndbcluster_get_key,0,0);
  pthread_mutex_init(&ndbcluster_mutex,MY_MUTEX_INIT_FAST);
  ndbcluster_inited= 1;
#ifdef USE_DISCOVER_ON_STARTUP
  if (ndb_discover_tables() != 0)
    DBUG_RETURN(TRUE);    
#endif
  DBUG_RETURN(false);
}


/*
  End use of the NDB Cluster table handler
  - free all global variables allocated by 
    ndcluster_init()
*/

bool ndbcluster_end()
{
  DBUG_ENTER("ndbcluster_end");
3423

unknown's avatar
unknown committed
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436
  delete g_ndb;
  g_ndb= NULL;
  if (!ndbcluster_inited)
    DBUG_RETURN(0);
  hash_free(&ndbcluster_open_tables);
#ifdef USE_NDB_POOL
  ndb_pool_release();
#endif
  pthread_mutex_destroy(&ndbcluster_mutex);
  ndbcluster_inited= 0;
  DBUG_RETURN(0);
}

3437 3438 3439 3440 3441
/*
  Static error print function called from
  static handler method ndbcluster_commit
  and ndbcluster_rollback
*/
3442 3443

void ndbcluster_print_error(int error, const NdbOperation *error_op)
3444
{
3445 3446
  DBUG_ENTER("ndbcluster_print_error");
  TABLE tab;
3447 3448
  const char *tab_name= (error_op) ? error_op->getTableName() : "";
  tab.table_name= (char *) tab_name;
3449
  ha_ndbcluster error_handler(&tab);
3450
  tab.file= &error_handler;
3451
  error_handler.print_error(error, MYF(0));
unknown's avatar
unknown committed
3452
  DBUG_VOID_RETURN;
3453
}
unknown's avatar
unknown committed
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476

/*
  Set m_tabname from full pathname to table file 
 */

void ha_ndbcluster::set_tabname(const char *path_name)
{
  char *end, *ptr;
  
  /* Scan name from the end */
  end= strend(path_name)-1;
  ptr= end;
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
  uint name_len= end - ptr;
  memcpy(m_tabname, ptr + 1, end - ptr);
  m_tabname[name_len]= '\0';
#ifdef __WIN__
  /* Put to lower case */
  ptr= m_tabname;
  
  while (*ptr != '\0') {
3477
    *ptr= tolower(*ptr);
unknown's avatar
unknown committed
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
    ptr++;
  }
#endif
}

/**
 * Set a given location from full pathname to table file
 *
 */
void
ha_ndbcluster::set_tabname(const char *path_name, char * tabname)
{
  char *end, *ptr;
  
  /* Scan name from the end */
3493 3494
  end= strend(path_name)-1;
  ptr= end;
unknown's avatar
unknown committed
3495 3496 3497
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
3498
  uint name_len= end - ptr;
unknown's avatar
unknown committed
3499
  memcpy(tabname, ptr + 1, end - ptr);
3500
  tabname[name_len]= '\0';
unknown's avatar
unknown committed
3501 3502
#ifdef __WIN__
  /* Put to lower case */
3503
  ptr= tabname;
unknown's avatar
unknown committed
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 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
  
  while (*ptr != '\0') {
    *ptr= tolower(*ptr);
    ptr++;
  }
#endif
}


/*
  Set m_dbname from full pathname to table file
 
 */

void ha_ndbcluster::set_dbname(const char *path_name)
{
  char *end, *ptr;
  
  /* Scan name from the end */
  ptr= strend(path_name)-1;
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
  ptr--;
  end= ptr;
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
  uint name_len= end - ptr;
  memcpy(m_dbname, ptr + 1, name_len);
  m_dbname[name_len]= '\0';
#ifdef __WIN__
  /* Put to lower case */
  
  ptr= m_dbname;
  
  while (*ptr != '\0') {
    *ptr= tolower(*ptr);
    ptr++;
  }
#endif
}


ha_rows 
unknown's avatar
unknown committed
3549 3550 3551 3552
ha_ndbcluster::records_in_range(uint inx, key_range *min_key,
                                key_range *max_key)
{
  KEY *key_info= table->key_info + inx;
unknown's avatar
unknown committed
3553
  uint key_length= key_info->key_length;
3554
  NDB_INDEX_TYPE idx_type= get_index_type(inx);  
unknown's avatar
unknown committed
3555 3556

  DBUG_ENTER("records_in_range");
unknown's avatar
unknown committed
3557
  DBUG_PRINT("enter", ("inx: %u", inx));
unknown's avatar
unknown committed
3558

3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
  // Prevent partial read of hash indexes by returning HA_POS_ERROR
  if ((idx_type == UNIQUE_INDEX || idx_type == PRIMARY_KEY_INDEX) &&
      ((min_key && min_key->length < key_length) ||
       (max_key && max_key->length < key_length)))
    DBUG_RETURN(HA_POS_ERROR);
  
  // Read from hash index with full key
  // This is a "const" table which returns only one record!      
  if ((idx_type != ORDERED_INDEX) &&
      ((min_key && min_key->length == key_length) || 
       (max_key && max_key->length == key_length)))
    DBUG_RETURN(1);
  
  DBUG_RETURN(10); /* Good guess when you don't know anything */
unknown's avatar
unknown committed
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
}


/*
  Handling the shared NDB_SHARE structure that is needed to 
  provide table locking.
  It's also used for sharing data with other NDB handlers
  in the same MySQL Server. There is currently not much
  data we want to or can share.
 */

static byte* ndbcluster_get_key(NDB_SHARE *share,uint *length,
				my_bool not_used __attribute__((unused)))
{
  *length=share->table_name_length;
  return (byte*) share->table_name;
}

static NDB_SHARE* get_share(const char *table_name)
{
  NDB_SHARE *share;
  pthread_mutex_lock(&ndbcluster_mutex);
  uint length=(uint) strlen(table_name);
  if (!(share=(NDB_SHARE*) hash_search(&ndbcluster_open_tables,
                                       (byte*) table_name,
                                       length)))
  {
    if ((share=(NDB_SHARE *) my_malloc(sizeof(*share)+length+1,
                                       MYF(MY_WME | MY_ZEROFILL))))
    {
      share->table_name_length=length;
      share->table_name=(char*) (share+1);
      strmov(share->table_name,table_name);
      if (my_hash_insert(&ndbcluster_open_tables, (byte*) share))
      {
        pthread_mutex_unlock(&ndbcluster_mutex);
        my_free((gptr) share,0);
        return 0;
      }
      thr_lock_init(&share->lock);
      pthread_mutex_init(&share->mutex,MY_MUTEX_INIT_FAST);
    }
  }
  share->use_count++;
  pthread_mutex_unlock(&ndbcluster_mutex);
  return share;
}


static void free_share(NDB_SHARE *share)
{
  pthread_mutex_lock(&ndbcluster_mutex);
  if (!--share->use_count)
  {
    hash_delete(&ndbcluster_open_tables, (byte*) share);
    thr_lock_delete(&share->lock);
    pthread_mutex_destroy(&share->mutex);
    my_free((gptr) share, MYF(0));
  }
  pthread_mutex_unlock(&ndbcluster_mutex);
}



/*
  Internal representation of the frm blob
   
*/

struct frm_blob_struct 
{
  struct frm_blob_header 
  {
    uint ver;      // Version of header
    uint orglen;   // Original length of compressed data
    uint complen;  // Compressed length of data, 0=uncompressed
  } head;
  char data[1];  
};



static int packfrm(const void *data, uint len, 
		   const void **pack_data, uint *pack_len)
{
  int error;
  ulong org_len, comp_len;
  uint blob_len;
  frm_blob_struct* blob;
  DBUG_ENTER("packfrm");
  DBUG_PRINT("enter", ("data: %x, len: %d", data, len));
  
  error= 1;
3666
  org_len= len;
unknown's avatar
unknown committed
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
  if (my_compress((byte*)data, &org_len, &comp_len))
    goto err;
  
  DBUG_PRINT("info", ("org_len: %d, comp_len: %d", org_len, comp_len));
  DBUG_DUMP("compressed", (char*)data, org_len);
  
  error= 2;
  blob_len= sizeof(frm_blob_struct::frm_blob_header)+org_len;
  if (!(blob= (frm_blob_struct*) my_malloc(blob_len,MYF(MY_WME))))
    goto err;
  
  // Store compressed blob in machine independent format
  int4store((char*)(&blob->head.ver), 1);
  int4store((char*)(&blob->head.orglen), comp_len);
  int4store((char*)(&blob->head.complen), org_len);
  
  // Copy frm data into blob, already in machine independent format
  memcpy(blob->data, data, org_len);  
  
3686 3687 3688
  *pack_data= blob;
  *pack_len= blob_len;
  error= 0;
unknown's avatar
unknown committed
3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699
  
  DBUG_PRINT("exit", ("pack_data: %x, pack_len: %d", *pack_data, *pack_len));
err:
  DBUG_RETURN(error);
  
}


static int unpackfrm(const void **unpack_data, uint *unpack_len,
		    const void *pack_data)
{
3700
   const frm_blob_struct *blob= (frm_blob_struct*)pack_data;
unknown's avatar
unknown committed
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715
   byte *data;
   ulong complen, orglen, ver;
   DBUG_ENTER("unpackfrm");
   DBUG_PRINT("enter", ("pack_data: %x", pack_data));

   complen=	uint4korr((char*)&blob->head.complen);
   orglen=	uint4korr((char*)&blob->head.orglen);
   ver=		uint4korr((char*)&blob->head.ver);
 
   DBUG_PRINT("blob",("ver: %d complen: %d orglen: %d",
 		     ver,complen,orglen));
   DBUG_DUMP("blob->data", (char*) blob->data, complen);
 
   if (ver != 1)
     DBUG_RETURN(1);
3716
   if (!(data= my_malloc(max(orglen, complen), MYF(MY_WME))))
unknown's avatar
unknown committed
3717 3718 3719 3720 3721 3722 3723 3724 3725
     DBUG_RETURN(2);
   memcpy(data, blob->data, complen);
 
   if (my_uncompress(data, &complen, &orglen))
   {
     my_free((char*)data, MYF(0));
     DBUG_RETURN(3);
   }

3726 3727
   *unpack_data= data;
   *unpack_len= complen;
unknown's avatar
unknown committed
3728 3729 3730 3731 3732 3733

   DBUG_PRINT("exit", ("frmdata: %x, len: %d", *unpack_data, *unpack_len));

   DBUG_RETURN(0);
}
#endif /* HAVE_NDBCLUSTER_DB */