ha_ndbcluster.cc 287 KB
Newer Older
1
/* Copyright (C) 2000-2003 MySQL AB
2 3 4

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
5
  the Free Software Foundation; version 2 of the License.
6 7 8 9 10 11 12 13

  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
14
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15 16 17 18 19 20 21
*/

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

22
#ifdef USE_PRAGMA_IMPLEMENTATION
23
#pragma implementation				// gcc: Class implementation
24 25 26 27 28
#endif

#include "mysql_priv.h"

#include <my_dir.h>
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
29
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
30 31
#include "ha_ndbcluster.h"
#include <ndbapi/NdbApi.hpp>
32
#include "ha_ndbcluster_cond.h"
33
#include <../util/Bitmask.hpp>
34
#include <ndbapi/NdbIndexStat.hpp>
35

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
36
#include "ha_ndbcluster_binlog.h"
37
#include "ha_ndbcluster_tables.h"
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
38

acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
39 40
#include <mysql/plugin.h>

41 42 43 44 45
#ifdef ndb_dynamite
#undef assert
#define assert(x) do { if(x) break; ::printf("%s %d: assert failed: %s\n", __FILE__, __LINE__, #x); ::fflush(stdout); ::signal(SIGABRT,SIG_DFL); ::abort(); ::kill(::getpid(),6); ::kill(::getpid(),9); } while (0)
#endif

46 47 48
// options from from mysqld.cc
extern my_bool opt_ndb_optimized_node_selection;
extern const char *opt_ndbcluster_connectstring;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
49
extern ulong opt_ndb_cache_check_time;
50

51 52 53 54 55 56 57 58 59 60
// ndb interface initialization/cleanup
#ifdef  __cplusplus
extern "C" {
#endif
extern void ndb_init_internal();
extern void ndb_end_internal();
#ifdef  __cplusplus
}
#endif

61 62 63 64 65 66
const char *ndb_distribution_names[]= {"KEYHASH", "LINHASH", NullS};
TYPELIB ndb_distribution_typelib= { array_elements(ndb_distribution_names)-1,
                                    "", ndb_distribution_names, NULL };
const char *opt_ndb_distribution= ndb_distribution_names[ND_KEYHASH];
enum ndb_distribution opt_ndb_distribution_id= ND_KEYHASH;

67
// Default value for parallelism
68
static const int parallelism= 0;
69

70 71
// Default value for max number of transactions
// createable against NDB from this handler
tulin@dl145b.mysql.com's avatar
tulin@dl145b.mysql.com committed
72
static const int max_transactions= 3; // should really be 2 but there is a transaction to much allocated when loch table is used
73

74 75
static uint ndbcluster_partition_flags();
static uint ndbcluster_alter_table_flags(uint flags);
76
static int ndbcluster_init(void *);
77 78 79 80 81 82 83 84 85 86 87
static int ndbcluster_end(handlerton *hton, ha_panic_function flag);
static bool ndbcluster_show_status(handlerton *hton, THD*,
                                   stat_print_fn *,
                                   enum ha_stat_type);
static int ndbcluster_alter_tablespace(handlerton *hton,
                                       THD* thd, 
                                       st_alter_tablespace *info);
static int ndbcluster_fill_files_table(handlerton *hton,
                                       THD *thd, 
                                       TABLE_LIST *tables, 
                                       COND *cond);
88

89
handlerton *ndbcluster_hton;
90

91 92
static handler *ndbcluster_create_handler(handlerton *hton,
                                          TABLE_SHARE *table,
93
                                          MEM_ROOT *mem_root)
94
{
95
  return new (mem_root) ha_ndbcluster(hton, table);
96 97
}

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
static uint ndbcluster_partition_flags()
{
  return (HA_CAN_PARTITION | HA_CAN_UPDATE_PARTITION_KEY |
          HA_CAN_PARTITION_UNIQUE | HA_USE_AUTO_PARTITION);
}

static uint ndbcluster_alter_table_flags(uint flags)
{
  if (flags & ALTER_DROP_PARTITION)
    return 0;
  else
    return (HA_ONLINE_ADD_INDEX | HA_ONLINE_DROP_INDEX |
            HA_ONLINE_ADD_UNIQUE_INDEX | HA_ONLINE_DROP_UNIQUE_INDEX |
            HA_PARTITION_FUNCTION_SUPPORTED);

}

115
#define NDB_AUTO_INCREMENT_RETRIES 10
116 117

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

120 121
#define ERR_RETURN(err)                  \
{                                        \
122
  const NdbError& tmp= err;              \
123
  ERR_PRINT(tmp);                        \
124
  DBUG_RETURN(ndb_to_mysql_error(&tmp)); \
125 126
}

127 128 129 130 131 132 133 134
#define ERR_BREAK(err, code)             \
{                                        \
  const NdbError& tmp= err;              \
  ERR_PRINT(tmp);                        \
  code= ndb_to_mysql_error(&tmp);        \
  break;                                 \
}

135
static int ndbcluster_inited= 0;
136
static int ndbcluster_terminating= 0;
137

138
static Ndb* g_ndb= NULL;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
139
Ndb_cluster_connection* g_ndb_cluster_connection= NULL;
monty@mysql.com's avatar
monty@mysql.com committed
140
uchar g_node_id_map[max_ndb_nodes];
141

142 143 144 145
// Handler synchronization
pthread_mutex_t ndbcluster_mutex;

// Table lock handling
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
146
HASH ndbcluster_open_tables;
147 148 149

static byte *ndbcluster_get_key(NDB_SHARE *share,uint *length,
                                my_bool not_used __attribute__((unused)));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
150 151 152
#ifdef HAVE_NDB_BINLOG
static int rename_share(NDB_SHARE *share, const char *new_key);
#endif
153
static int ndb_get_table_statistics(ha_ndbcluster*, bool, Ndb*, const NDBTAB *, 
154
                                    struct Ndb_statistics *);
155

156

mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
157
// Util thread variables
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
158
pthread_t ndb_util_thread;
159
int ndb_util_thread_running= 0;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
160 161
pthread_mutex_t LOCK_ndb_util_thread;
pthread_cond_t COND_ndb_util_thread;
162
pthread_cond_t COND_ndb_util_ready;
163
pthread_handler_t ndb_util_thread_func(void *arg);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
164
ulong ndb_cache_check_time;
165

166 167 168 169
/*
  Dummy buffer to read zero pack_length fields
  which are mapped to 1 char
*/
170
static uint32 dummy_buf;
171

172 173 174 175 176 177 178 179 180 181 182
/*
  Stats that can be retrieved from ndb
*/

struct Ndb_statistics {
  Uint64 row_count;
  Uint64 commit_count;
  Uint64 row_size;
  Uint64 fragment_memory;
};

183 184 185 186 187 188
/* Status variables shown with 'show status like 'Ndb%' */

static long ndb_cluster_node_id= 0;
static const char * ndb_connected_host= 0;
static long ndb_connected_port= 0;
static long ndb_number_of_replicas= 0;
189 190
long ndb_number_of_data_nodes= 0;
long ndb_number_of_ready_data_nodes= 0;
191
long ndb_connect_count= 0;
192 193 194 195 196 197 198

static int update_status_variables(Ndb_cluster_connection *c)
{
  ndb_cluster_node_id=         c->node_id();
  ndb_connected_port=          c->get_connected_port();
  ndb_connected_host=          c->get_connected_host();
  ndb_number_of_replicas=      0;
199
  ndb_number_of_ready_data_nodes= c->get_no_ready();
justin.he@qa3-104.qa.cn.tlan's avatar
justin.he@qa3-104.qa.cn.tlan committed
200
  ndb_number_of_data_nodes=     c->no_db_nodes();
201
  ndb_connect_count= c->get_connect_count();
202 203 204
  return 0;
}

serg@serg.mylan's avatar
serg@serg.mylan committed
205
SHOW_VAR ndb_status_variables[]= {
206
  {"cluster_node_id",        (char*) &ndb_cluster_node_id,         SHOW_LONG},
207 208
  {"config_from_host",         (char*) &ndb_connected_host,      SHOW_CHAR_PTR},
  {"config_from_port",         (char*) &ndb_connected_port,          SHOW_LONG},
209
//  {"number_of_replicas",     (char*) &ndb_number_of_replicas,      SHOW_LONG},
210
  {"number_of_data_nodes",(char*) &ndb_number_of_data_nodes, SHOW_LONG},
211 212 213
  {NullS, NullS, SHOW_LONG}
};

214 215 216 217
/*
  Error handling functions
*/

218
/* Note for merge: old mapping table, moved to storage/ndb/ndberror.c */
219

220
static int ndb_to_mysql_error(const NdbError *ndberr)
221
{
222 223
  /* read the mysql mapped error code */
  int error= ndberr->mysql_code;
224

225 226 227 228 229 230 231 232 233 234 235 236 237
  switch (error)
  {
    /* errors for which we do not add warnings, just return mapped error code
    */
  case HA_ERR_NO_SUCH_TABLE:
  case HA_ERR_KEY_NOT_FOUND:
  case HA_ERR_FOUND_DUPP_KEY:
    return error;

    /* Mapping missing, go with the ndb error code*/
  case -1:
    error= ndberr->code;
    break;
238

239 240 241 242
    /* Mapping exists, go with the mapped code */
  default:
    break;
  }
243

244 245 246 247 248 249
  /*
    Push the NDB error message as warning
    - Used to be able to use SHOW WARNINGS toget more info on what the error is
    - Used by replication to see if the error was temporary
  */
  if (ndberr->status == NdbError::TemporaryError)
250
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
251 252 253 254 255 256 257
			ER_GET_TEMPORARY_ERRMSG, ER(ER_GET_TEMPORARY_ERRMSG),
			ndberr->code, ndberr->message, "NDB");
  else
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
			ER_GET_ERRMSG, ER(ER_GET_ERRMSG),
			ndberr->code, ndberr->message, "NDB");
  return error;
258 259
}

260 261
int execute_no_commit_ignore_no_key(ha_ndbcluster *h, NdbTransaction *trans)
{
262 263 264
  if (trans->execute(NdbTransaction::NoCommit,
                     NdbOperation::AO_IgnoreError,
                     h->m_force_send) == -1)
265
    return -1;
266 267

  const NdbError &err= trans->getNdbError();
268 269
  if (err.classification != NdbError::NoError &&
      err.classification != NdbError::ConstraintViolation &&
270
      err.classification != NdbError::NoDataFound)
271
    return -1;
272

273 274
  return 0;
}
275 276

inline
277
int execute_no_commit(ha_ndbcluster *h, NdbTransaction *trans,
278
		      bool force_release)
279
{
280
#ifdef NOT_USED
281
  int m_batch_execute= 0;
282
  if (m_batch_execute)
283
    return 0;
284
#endif
285
  h->release_completed_operations(trans, force_release);
286 287 288
  return h->m_ignore_no_key ?
    execute_no_commit_ignore_no_key(h,trans) :
    trans->execute(NdbTransaction::NoCommit,
289
		   NdbOperation::AbortOnError,
290
		   h->m_force_send);
291 292 293
}

inline
294
int execute_commit(ha_ndbcluster *h, NdbTransaction *trans)
295
{
296
#ifdef NOT_USED
297
  int m_batch_execute= 0;
298
  if (m_batch_execute)
299
    return 0;
300
#endif
301
  return trans->execute(NdbTransaction::Commit,
302
                        NdbOperation::AbortOnError,
303
                        h->m_force_send);
304 305 306
}

inline
307
int execute_commit(THD *thd, NdbTransaction *trans)
308 309
{
#ifdef NOT_USED
310
  int m_batch_execute= 0;
311 312 313
  if (m_batch_execute)
    return 0;
#endif
314
  return trans->execute(NdbTransaction::Commit,
315
                        NdbOperation::AbortOnError,
316
                        thd->variables.ndb_force_send);
317 318 319
}

inline
320
int execute_no_commit_ie(ha_ndbcluster *h, NdbTransaction *trans,
321
			 bool force_release)
322
{
323
#ifdef NOT_USED
324
  int m_batch_execute= 0;
325
  if (m_batch_execute)
326
    return 0;
327
#endif
328
  h->release_completed_operations(trans, force_release);
329
  return trans->execute(NdbTransaction::NoCommit,
330
                        NdbOperation::AO_IgnoreError,
331
                        h->m_force_send);
332 333
}

334 335 336
/*
  Place holder for ha_ndbcluster thread specific data
*/
337 338 339 340 341
static
byte *thd_ndb_share_get_key(THD_NDB_SHARE *thd_ndb_share, uint *length,
                            my_bool not_used __attribute__((unused)))
{
  *length= sizeof(thd_ndb_share->key);
342
  return (byte*) &thd_ndb_share->key;
343 344
}

345 346
Thd_ndb::Thd_ndb()
{
347
  ndb= new Ndb(g_ndb_cluster_connection, "");
348 349
  lock_count= 0;
  count= 0;
350 351
  all= NULL;
  stmt= NULL;
352
  error= 0;
353
  query_state&= NDB_QUERY_NORMAL;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
354
  options= 0;
355
  (void) hash_init(&open_tables, &my_charset_bin, 5, 0, 0,
356
                   (hash_get_key)thd_ndb_share_get_key, 0, 0);
357 358 359 360
}

Thd_ndb::~Thd_ndb()
{
361
  if (ndb)
362 363
  {
#ifndef DBUG_OFF
364 365
    Ndb::Free_list_usage tmp;
    tmp.m_name= 0;
366 367 368 369 370 371 372 373 374 375
    while (ndb->get_free_list_usage(&tmp))
    {
      uint leaked= (uint) tmp.m_created - tmp.m_free;
      if (leaked)
        fprintf(stderr, "NDB: Found %u %s%s that %s not been released\n",
                leaked, tmp.m_name,
                (leaked == 1)?"":"'s",
                (leaked == 1)?"has":"have");
    }
#endif
376
    delete ndb;
377
    ndb= NULL;
378
  }
379
  changed_tables.empty();
380 381 382 383 384 385
  hash_free(&open_tables);
}

void
Thd_ndb::init_open_tables()
{
386 387
  count= 0;
  error= 0;
388 389 390 391 392 393 394
  my_hash_reset(&open_tables);
}

THD_NDB_SHARE *
Thd_ndb::get_open_table(THD *thd, const void *key)
{
  DBUG_ENTER("Thd_ndb::get_open_table");
395
  HASH_SEARCH_STATE state;
396
  THD_NDB_SHARE *thd_ndb_share=
397
    (THD_NDB_SHARE*)hash_first(&open_tables, (byte *)&key, sizeof(key), &state);
398
  while (thd_ndb_share && thd_ndb_share->key != key)
399
    thd_ndb_share= (THD_NDB_SHARE*)hash_next(&open_tables, (byte *)&key, sizeof(key), &state);
400 401 402 403 404
  if (thd_ndb_share == 0)
  {
    thd_ndb_share= (THD_NDB_SHARE *) alloc_root(&thd->transaction.mem_root,
                                                sizeof(THD_NDB_SHARE));
    thd_ndb_share->key= key;
405 406
    thd_ndb_share->stat.last_count= count;
    thd_ndb_share->stat.no_uncommitted_rows_count= 0;
407
    thd_ndb_share->stat.records= ~(ha_rows)0;
408 409
    my_hash_insert(&open_tables, (byte *)thd_ndb_share);
  }
410 411 412 413
  else if (thd_ndb_share->stat.last_count != count)
  {
    thd_ndb_share->stat.last_count= count;
    thd_ndb_share->stat.no_uncommitted_rows_count= 0;
414
    thd_ndb_share->stat.records= ~(ha_rows)0;
415
  }
416 417
  DBUG_PRINT("exit", ("thd_ndb_share: 0x%lx  key: 0x%lx",
                      (long) thd_ndb_share, (long) key));
418
  DBUG_RETURN(thd_ndb_share);
419 420
}

421 422 423
inline
Ndb *ha_ndbcluster::get_ndb()
{
424
  return get_thd_ndb(current_thd)->ndb;
425 426 427 428 429 430
}

/*
 * manage uncommitted insert/deletes during transactio to get records correct
 */

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
431 432 433
void ha_ndbcluster::set_rec_per_key()
{
  DBUG_ENTER("ha_ndbcluster::get_status_const");
434
  for (uint i=0 ; i < table_share->keys ; i++)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
435 436 437 438 439 440
  {
    table->key_info[i].rec_per_key[table->key_info[i].key_parts-1]= 1;
  }
  DBUG_VOID_RETURN;
}

441 442 443 444
ha_rows ha_ndbcluster::records()
{
  ha_rows retval;
  DBUG_ENTER("ha_ndbcluster::records");
445
  struct Ndb_local_table_statistics *local_info= m_table_info;
446 447
  DBUG_PRINT("info", ("id=%d, no_uncommitted_rows_count=%d",
                      ((const NDBTAB *)m_table)->getTableId(),
448
                      local_info->no_uncommitted_rows_count));
449 450 451 452

  Ndb *ndb= get_ndb();
  ndb->setDatabaseName(m_dbname);
  struct Ndb_statistics stat;
453
  if (ndb_get_table_statistics(this, TRUE, ndb, m_table, &stat) == 0)
454 455 456
  {
    retval= stat.row_count;
  }
457 458
  else
  {
459
    DBUG_RETURN(HA_POS_ERROR);
460
  }
461 462 463

  THD *thd= current_thd;
  if (get_thd_ndb(thd)->error)
464
    local_info->no_uncommitted_rows_count= 0;
465

466
  DBUG_RETURN(retval + local_info->no_uncommitted_rows_count);
467 468
}

469
int ha_ndbcluster::records_update()
470
{
471
  if (m_ha_not_exact_count)
472
    return 0;
473
  DBUG_ENTER("ha_ndbcluster::records_update");
474 475
  int result= 0;

476
  struct Ndb_local_table_statistics *local_info= m_table_info;
477
  DBUG_PRINT("info", ("id=%d, no_uncommitted_rows_count=%d",
478
                      ((const NDBTAB *)m_table)->getTableId(),
479
                      local_info->no_uncommitted_rows_count));
480
  {
481
    Ndb *ndb= get_ndb();
482
    struct Ndb_statistics stat;
483 484 485 486
    if (ndb->setDatabaseName(m_dbname))
    {
      return my_errno= HA_ERR_OUT_OF_MEM;
    }
487
    result= ndb_get_table_statistics(this, TRUE, ndb, m_table, &stat);
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
488
    if (result == 0)
489 490 491
    {
      stats.mean_rec_length= stat.row_size;
      stats.data_file_length= stat.fragment_memory;
492
      local_info->records= stat.row_count;
493 494
    }
  }
495 496
  {
    THD *thd= current_thd;
497
    if (get_thd_ndb(thd)->error)
498
      local_info->no_uncommitted_rows_count= 0;
499
  }
500 501
  if (result == 0)
    stats.records= local_info->records+ local_info->no_uncommitted_rows_count;
502
  DBUG_RETURN(result);
503 504
}

505 506
void ha_ndbcluster::no_uncommitted_rows_execute_failure()
{
507 508
  if (m_ha_not_exact_count)
    return;
509
  DBUG_ENTER("ha_ndbcluster::no_uncommitted_rows_execute_failure");
510
  get_thd_ndb(current_thd)->error= 1;
511 512 513
  DBUG_VOID_RETURN;
}

514 515
void ha_ndbcluster::no_uncommitted_rows_update(int c)
{
516 517
  if (m_ha_not_exact_count)
    return;
518
  DBUG_ENTER("ha_ndbcluster::no_uncommitted_rows_update");
519
  struct Ndb_local_table_statistics *local_info= m_table_info;
520
  local_info->no_uncommitted_rows_count+= c;
521
  DBUG_PRINT("info", ("id=%d, no_uncommitted_rows_count=%d",
522
                      ((const NDBTAB *)m_table)->getTableId(),
523
                      local_info->no_uncommitted_rows_count));
524 525 526 527 528
  DBUG_VOID_RETURN;
}

void ha_ndbcluster::no_uncommitted_rows_reset(THD *thd)
{
529 530
  if (m_ha_not_exact_count)
    return;
531
  DBUG_ENTER("ha_ndbcluster::no_uncommitted_rows_reset");
532 533 534
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
  thd_ndb->count++;
  thd_ndb->error= 0;
535 536 537
  DBUG_VOID_RETURN;
}

538
int ha_ndbcluster::ndb_err(NdbTransaction *trans)
539
{
540
  int res;
541
  NdbError err= trans->getNdbError();
542 543 544 545 546
  DBUG_ENTER("ndb_err");
  
  ERR_PRINT(err);
  switch (err.classification) {
  case NdbError::SchemaError:
547
  {
548 549
    // TODO perhaps we need to do more here, invalidate also in the cache
    m_table->setStatusInvalid();
550 551 552 553 554 555
    /* Close other open handlers not used by any thread */
    TABLE_LIST table_list;
    bzero((char*) &table_list,sizeof(table_list));
    table_list.db= m_dbname;
    table_list.alias= table_list.table_name= m_tabname;
    close_cached_tables(current_thd, 0, &table_list);
556
    break;
557
  }
558 559 560
  default:
    break;
  }
561 562
  res= ndb_to_mysql_error(&err);
  DBUG_PRINT("info", ("transformed ndbcluster error %d to mysql error %d", 
563
                      err.code, res));
564
  if (res == HA_ERR_FOUND_DUPP_KEY)
565 566
  {
    if (m_rows_to_insert == 1)
567 568 569 570 571 572
    {
      /*
	We can only distinguish between primary and non-primary
	violations here, so we need to return MAX_KEY for non-primary
	to signal that key is unknown
      */
573
      m_dupkey= err.code == 630 ? table_share->primary_key : MAX_KEY; 
574
    }
575
    else
monty@mishka.local's avatar
monty@mishka.local committed
576 577
    {
      /* We are batching inserts, offending key is not available */
578
      m_dupkey= (uint) -1;
monty@mishka.local's avatar
monty@mishka.local committed
579
    }
580
  }
581
  DBUG_RETURN(res);
582 583 584
}


585
/*
586
  Override the default get_error_message in order to add the 
587 588 589
  error message of NDB 
 */

590
bool ha_ndbcluster::get_error_message(int error, 
591
                                      String *buf)
592
{
593
  DBUG_ENTER("ha_ndbcluster::get_error_message");
594
  DBUG_PRINT("enter", ("error: %d", error));
595

596
  Ndb *ndb= get_ndb();
597
  if (!ndb)
598
    DBUG_RETURN(FALSE);
599

600
  const NdbError err= ndb->getNdbError(error);
601 602 603 604
  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);
605 606 607
}


tulin@dl145c.mysql.com's avatar
tulin@dl145c.mysql.com committed
608
#ifndef DBUG_OFF
pekka@mysql.com's avatar
pekka@mysql.com committed
609 610 611 612
/*
  Check if type is supported by NDB.
*/

tulin@dl145c.mysql.com's avatar
tulin@dl145c.mysql.com committed
613
static bool ndb_supported_type(enum_field_types type)
pekka@mysql.com's avatar
pekka@mysql.com committed
614 615
{
  switch (type) {
pekka@mysql.com's avatar
pekka@mysql.com committed
616 617 618 619 620 621 622
  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:
623 624
  case MYSQL_TYPE_DECIMAL:    
  case MYSQL_TYPE_NEWDECIMAL:
pekka@mysql.com's avatar
pekka@mysql.com committed
625 626 627 628 629 630 631 632
  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:
pekka@mysql.com's avatar
pekka@mysql.com committed
633
  case MYSQL_TYPE_VARCHAR:
pekka@mysql.com's avatar
pekka@mysql.com committed
634 635 636 637 638 639
  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:         
640
  case MYSQL_TYPE_BIT:
641
  case MYSQL_TYPE_GEOMETRY:
642
    return TRUE;
pekka@mysql.com's avatar
pekka@mysql.com committed
643
  case MYSQL_TYPE_NULL:   
pekka@mysql.com's avatar
pekka@mysql.com committed
644
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
645
  }
646
  return FALSE;
pekka@mysql.com's avatar
pekka@mysql.com committed
647
}
tulin@dl145c.mysql.com's avatar
tulin@dl145c.mysql.com committed
648
#endif /* !DBUG_OFF */
pekka@mysql.com's avatar
pekka@mysql.com committed
649 650


651 652 653 654 655
/*
  Instruct NDB to set the value of the hidden primary key
*/

bool ha_ndbcluster::set_hidden_key(NdbOperation *ndb_op,
656
                                   uint fieldnr, const byte *field_ptr)
657 658
{
  DBUG_ENTER("set_hidden_key");
659
  DBUG_RETURN(ndb_op->equal(fieldnr, (char*)field_ptr) != 0);
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
}


/*
  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);
  
tulin@dl145c.mysql.com's avatar
tulin@dl145c.mysql.com committed
677 678 679 680
  DBUG_ASSERT(ndb_supported_type(field->type()));
  DBUG_ASSERT(! (field->flags & BLOB_FLAG));
  // Common implementation for most field types
  DBUG_RETURN(ndb_op->equal(fieldnr, (char*) field_ptr, pack_len) != 0);
681 682 683 684 685 686 687 688
}


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

int ha_ndbcluster::set_ndb_value(NdbOperation *ndb_op, Field *field, 
689 690
                                 uint fieldnr, int row_offset,
                                 bool *set_blob_value)
691
{
692 693
  const byte* field_ptr= field->ptr + row_offset;
  uint32 pack_len= field->pack_length();
694
  DBUG_ENTER("set_ndb_value");
695
  DBUG_PRINT("enter", ("%d: %s  type: %u  len=%d  is_null=%s", 
696
                       fieldnr, field->field_name, field->type(), 
697
                       pack_len, field->is_null(row_offset) ? "Y" : "N"));
698
  DBUG_DUMP("value", (char*) field_ptr, pack_len);
pekka@mysql.com's avatar
pekka@mysql.com committed
699

tulin@dl145c.mysql.com's avatar
tulin@dl145c.mysql.com committed
700
  DBUG_ASSERT(ndb_supported_type(field->type()));
701
  {
702
    // ndb currently does not support size 0
703
    uint32 empty_field;
704 705
    if (pack_len == 0)
    {
706 707
      pack_len= sizeof(empty_field);
      field_ptr= (byte *)&empty_field;
708
      if (field->is_null(row_offset))
709
        empty_field= 0;
710
      else
711
        empty_field= 1;
712
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
713 714
    if (! (field->flags & BLOB_FLAG))
    {
715 716
      if (field->type() != MYSQL_TYPE_BIT)
      {
717 718 719
        if (field->is_null(row_offset))
        {
          DBUG_PRINT("info", ("field is NULL"));
720
          // Set value to NULL
721
          DBUG_RETURN((ndb_op->setValue(fieldnr, (char*)NULL) != 0));
722
	}
723
        // Common implementation for most field types
724
        DBUG_RETURN(ndb_op->setValue(fieldnr, (char*)field_ptr) != 0);
725 726 727
      }
      else // if (field->type() == MYSQL_TYPE_BIT)
      {
728
        longlong bits= field->val_int();
729
 
730 731
        // Round up bit field length to nearest word boundry
        pack_len= ((pack_len + 3) >> 2) << 2;
732
        DBUG_ASSERT(pack_len <= 8);
733
        if (field->is_null(row_offset))
734
          // Set value to NULL
735
          DBUG_RETURN((ndb_op->setValue(fieldnr, (char*)NULL) != 0));
736
        DBUG_PRINT("info", ("bit field"));
737
        DBUG_DUMP("value", (char*)&bits, pack_len);
738
#ifdef WORDS_BIGENDIAN
739
        /* store lsw first */
740 741
        bits = ((bits >> 32) & 0x00000000FFFFFFFF)
          |    ((bits << 32) & 0xFFFFFFFF00000000);
742
#endif
743
        DBUG_RETURN(ndb_op->setValue(fieldnr, (char*)&bits) != 0);
744
      }
pekka@mysql.com's avatar
pekka@mysql.com committed
745 746
    }
    // Blob type
747
    NdbBlob *ndb_blob= ndb_op->getBlobHandle(fieldnr);
pekka@mysql.com's avatar
pekka@mysql.com committed
748 749
    if (ndb_blob != NULL)
    {
750
      if (field->is_null(row_offset))
pekka@mysql.com's avatar
pekka@mysql.com committed
751 752 753 754 755 756 757 758 759
        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);

760 761 762
      // Looks like NULL ptr signals length 0 blob
      if (blob_ptr == NULL) {
        DBUG_ASSERT(blob_len == 0);
763
        blob_ptr= (char*)"";
764
      }
pekka@mysql.com's avatar
pekka@mysql.com committed
765

766 767
      DBUG_PRINT("value", ("set blob ptr: 0x%lx  len: %u",
                           (long) blob_ptr, blob_len));
pekka@mysql.com's avatar
pekka@mysql.com committed
768 769
      DBUG_DUMP("value", (char*)blob_ptr, min(blob_len, 26));

770
      if (set_blob_value)
771
        *set_blob_value= TRUE;
pekka@mysql.com's avatar
pekka@mysql.com committed
772 773 774 775
      // No callback needed to write value
      DBUG_RETURN(ndb_blob->setValue(blob_ptr, blob_len) != 0);
    }
    DBUG_RETURN(1);
776
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
}


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

792
NdbBlob::ActiveHook g_get_ndb_blobs_value;
pekka@mysql.com's avatar
pekka@mysql.com committed
793

794
int g_get_ndb_blobs_value(NdbBlob *ndb_blob, void *arg)
pekka@mysql.com's avatar
pekka@mysql.com committed
795
{
796
  DBUG_ENTER("g_get_ndb_blobs_value");
pekka@mysql.com's avatar
pekka@mysql.com committed
797 798 799
  if (ndb_blob->blobsNextBlob() != NULL)
    DBUG_RETURN(0);
  ha_ndbcluster *ha= (ha_ndbcluster *)arg;
800 801
  int ret= get_ndb_blobs_value(ha->table, ha->m_value,
                               ha->m_blobs_buffer, ha->m_blobs_buffer_size,
802
                               ha->m_blobs_offset);
803
  DBUG_RETURN(ret);
pekka@mysql.com's avatar
pekka@mysql.com committed
804 805
}

806 807 808 809 810 811 812 813
/*
  This routine is shared by injector.  There is no common blobs buffer
  so the buffer and length are passed by reference.  Injector also
  passes a record pointer diff.
 */
int get_ndb_blobs_value(TABLE* table, NdbValue* value_array,
                        byte*& buffer, uint& buffer_size,
                        my_ptrdiff_t ptrdiff)
pekka@mysql.com's avatar
pekka@mysql.com committed
814 815 816 817 818 819 820 821
{
  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;
822
    for (uint i= 0; i < table->s->fields; i++)
pekka@mysql.com's avatar
pekka@mysql.com committed
823 824
    {
      Field *field= table->field[i];
825
      NdbValue value= value_array[i];
826 827 828
      if (! (field->flags & BLOB_FLAG))
        continue;
      if (value.blob == NULL)
pekka@mysql.com's avatar
pekka@mysql.com committed
829
      {
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
        DBUG_PRINT("info",("[%u] skipped", i));
        continue;
      }
      Field_blob *field_blob= (Field_blob *)field;
      NdbBlob *ndb_blob= value.blob;
      int isNull;
      if (ndb_blob->getNull(isNull) != 0)
        ERR_RETURN(ndb_blob->getNdbError());
      if (isNull == 0) {
        Uint64 len64= 0;
        if (ndb_blob->getLength(len64) != 0)
          ERR_RETURN(ndb_blob->getNdbError());
        // Align to Uint64
        uint32 size= len64;
        if (size % 8 != 0)
          size+= 8 - size % 8;
        if (loop == 1)
847
        {
848 849 850 851
          char *buf= buffer + offset;
          uint32 len= 0xffffffff;  // Max uint32
          if (ndb_blob->readData(buf, len) != 0)
            ERR_RETURN(ndb_blob->getNdbError());
852 853
          DBUG_PRINT("info", ("[%u] offset: %u  buf: 0x%lx  len=%u  [ptrdiff=%d]",
                              i, offset, (long) buf, len, (int)ptrdiff));
854 855 856 857 858
          DBUG_ASSERT(len == len64);
          // Ugly hack assumes only ptr needs to be changed
          field_blob->ptr+= ptrdiff;
          field_blob->set_ptr(len, buf);
          field_blob->ptr-= ptrdiff;
859
        }
860 861 862 863 864 865 866 867 868 869 870
        offset+= size;
      }
      else if (loop == 1) // undefined or null
      {
        // have to set length even in this case
        char *buf= buffer + offset; // or maybe NULL
        uint32 len= 0;
        field_blob->ptr+= ptrdiff;
        field_blob->set_ptr(len, buf);
        field_blob->ptr-= ptrdiff;
        DBUG_PRINT("info", ("[%u] isNull=%d", i, isNull));
pekka@mysql.com's avatar
pekka@mysql.com committed
871 872
      }
    }
873
    if (loop == 0 && offset > buffer_size)
pekka@mysql.com's avatar
pekka@mysql.com committed
874
    {
875 876 877 878 879
      my_free(buffer, MYF(MY_ALLOW_ZERO_PTR));
      buffer_size= 0;
      DBUG_PRINT("info", ("allocate blobs buffer size %u", offset));
      buffer= my_malloc(offset, MYF(MY_WME));
      if (buffer == NULL)
880 881 882
      {
        sql_print_error("ha_ndbcluster::get_ndb_blobs_value: "
                        "my_malloc(%u) failed", offset);
pekka@mysql.com's avatar
pekka@mysql.com committed
883
        DBUG_RETURN(-1);
884
      }
885
      buffer_size= offset;
pekka@mysql.com's avatar
pekka@mysql.com committed
886
    }
887
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
888
  DBUG_RETURN(0);
889 890 891 892 893
}


/*
  Instruct NDB to fetch one field
pekka@mysql.com's avatar
pekka@mysql.com committed
894 895
  - data is read directly into buffer provided by field
    if field is NULL, data is read into memory provided by NDBAPI
896 897
*/

pekka@mysql.com's avatar
pekka@mysql.com committed
898
int ha_ndbcluster::get_ndb_value(NdbOperation *ndb_op, Field *field,
899
                                 uint fieldnr, byte* buf)
900 901
{
  DBUG_ENTER("get_ndb_value");
pekka@mysql.com's avatar
pekka@mysql.com committed
902 903 904 905 906
  DBUG_PRINT("enter", ("fieldnr: %d flags: %o", fieldnr,
                       (int)(field != NULL ? field->flags : 0)));

  if (field != NULL)
  {
tulin@dl145c.mysql.com's avatar
tulin@dl145c.mysql.com committed
907 908
      DBUG_ASSERT(buf);
      DBUG_ASSERT(ndb_supported_type(field->type()));
pekka@mysql.com's avatar
pekka@mysql.com committed
909 910
      DBUG_ASSERT(field->ptr != NULL);
      if (! (field->flags & BLOB_FLAG))
911
      { 
912 913
        if (field->type() != MYSQL_TYPE_BIT)
        {
914 915 916 917 918 919 920 921
          byte *field_buf;
          if (field->pack_length() != 0)
            field_buf= buf + (field->ptr - table->record[0]);
          else
            field_buf= (byte *)&dummy_buf;
          m_value[fieldnr].rec= ndb_op->getValue(fieldnr, 
                                                 field_buf);
        }
922 923 924 925
        else // if (field->type() == MYSQL_TYPE_BIT)
        {
          m_value[fieldnr].rec= ndb_op->getValue(fieldnr);
        }
pekka@mysql.com's avatar
pekka@mysql.com committed
926 927 928 929 930 931 932 933 934
        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
935
	m_blobs_offset= buf - (byte*) table->record[0];
pekka@mysql.com's avatar
pekka@mysql.com committed
936
        void *arg= (void *)this;
937
        DBUG_RETURN(ndb_blob->setActiveHook(g_get_ndb_blobs_value, arg) != 0);
pekka@mysql.com's avatar
pekka@mysql.com committed
938 939 940 941 942
      }
      DBUG_RETURN(1);
  }

  // Used for hidden key only
943
  m_value[fieldnr].rec= ndb_op->getValue(fieldnr, m_ref);
pekka@mysql.com's avatar
pekka@mysql.com committed
944 945 946
  DBUG_RETURN(m_value[fieldnr].rec == NULL);
}

947 948 949 950 951 952
/*
  Instruct NDB to fetch the partition id (fragment id)
*/
int ha_ndbcluster::get_ndb_partition_id(NdbOperation *ndb_op)
{
  DBUG_ENTER("get_ndb_partition_id");
953 954
  DBUG_RETURN(ndb_op->getValue(NdbDictionary::Column::FRAGMENT, 
                               (char *)&m_part_id) == NULL);
955
}
pekka@mysql.com's avatar
pekka@mysql.com committed
956 957 958 959

/*
  Check if any set or get of blob value in current query.
*/
960

961
bool ha_ndbcluster::uses_blob_value()
pekka@mysql.com's avatar
pekka@mysql.com committed
962
{
963 964
  MY_BITMAP *bitmap;
  uint *blob_index, *blob_index_end;
965
  if (table_share->blob_fields == 0)
966
    return FALSE;
967 968 969 970 971

  bitmap= m_write_op ? table->write_set : table->read_set;
  blob_index=     table_share->blob_field;
  blob_index_end= blob_index + table_share->blob_fields;
  do
pekka@mysql.com's avatar
pekka@mysql.com committed
972
  {
973
    if (bitmap_is_set(bitmap, table->field[*blob_index]->field_index))
974 975
      return TRUE;
  } while (++blob_index != blob_index_end);
976
  return FALSE;
977 978 979 980 981 982 983 984 985
}


/*
  Get metadata for this table from NDB 

  IMPLEMENTATION
    - check that frm-file on disk is equal to frm-file
      of table accessed in NDB
986 987 988 989

  RETURN
    0    ok
    -2   Meta data has changed; Re-read data and try again
990 991
*/

992 993
int cmp_frm(const NDBTAB *ndbtab, const void *pack_data,
            uint pack_length)
994 995 996 997 998 999 1000 1001 1002 1003 1004
{
  DBUG_ENTER("cmp_frm");
  /*
    Compare FrmData in NDB with frm file from disk.
  */
  if ((pack_length != ndbtab->getFrmLength()) || 
      (memcmp(pack_data, ndbtab->getFrmData(), pack_length)))
    DBUG_RETURN(1);
  DBUG_RETURN(0);
}

1005 1006
int ha_ndbcluster::get_metadata(const char *path)
{
1007 1008
  Ndb *ndb= get_ndb();
  NDBDICT *dict= ndb->getDictionary();
1009 1010 1011 1012 1013
  const NDBTAB *tab;
  int error;
  DBUG_ENTER("get_metadata");
  DBUG_PRINT("enter", ("m_tabname: %s, path: %s", m_tabname, path));

1014 1015
  DBUG_ASSERT(m_table == NULL);
  DBUG_ASSERT(m_table_info == NULL);
1016

1017
  const void *data= NULL, *pack_data= NULL;
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
  uint length, pack_length;

  /*
    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);
  }
1031
    
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
  Ndb_table_guard ndbtab_g(dict, m_tabname);
  if (!(tab= ndbtab_g.get_table()))
    ERR_RETURN(dict->getNdbError());

  if (get_ndb_share_state(m_share) != NSS_ALTERED 
      && cmp_frm(tab, pack_data, 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_TABLE_DEF_CHANGED;
  }
  my_free((char*)data, MYF(0));
  my_free((char*)pack_data, MYF(0));
1049

1050
  if (error)
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    goto err;

  DBUG_PRINT("info", ("fetched table %s", tab->getName()));
  m_table= tab;
  if ((error= open_indexes(ndb, table, FALSE)) == 0)
  {
    ndbtab_g.release();
    DBUG_RETURN(0);
  }
err:
  ndbtab_g.invalidate();
  m_table= NULL;
  DBUG_RETURN(error);
1064
}
1065

1066
static int fix_unique_index_attr_order(NDB_INDEX_DATA &data,
1067 1068
                                       const NDBINDEX *index,
                                       KEY *key_info)
1069 1070 1071 1072 1073 1074
{
  DBUG_ENTER("fix_unique_index_attr_order");
  unsigned sz= index->getNoOfIndexColumns();

  if (data.unique_index_attrid_map)
    my_free((char*)data.unique_index_attrid_map, MYF(0));
monty@mysql.com's avatar
monty@mysql.com committed
1075
  data.unique_index_attrid_map= (uchar*)my_malloc(sz,MYF(MY_WME));
1076 1077 1078 1079 1080 1081
  if (data.unique_index_attrid_map == 0)
  {
    sql_print_error("fix_unique_index_attr_order: my_malloc(%u) failure",
                    (unsigned int)sz);
    DBUG_RETURN(HA_ERR_OUT_OF_MEM);
  }
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
  DBUG_ASSERT(key_info->key_parts == sz);
  for (unsigned i= 0; key_part != end; key_part++, i++) 
  {
    const char *field_name= key_part->field->field_name;
#ifndef DBUG_OFF
   data.unique_index_attrid_map[i]= 255;
#endif
    for (unsigned j= 0; j < sz; j++)
    {
1094
      const NDBCOL *c= index->getColumn(j);
msvensson@neptunus.(none)'s avatar
msvensson@neptunus.(none) committed
1095
      if (strcmp(field_name, c->getName()) == 0)
1096
      {
1097 1098
        data.unique_index_attrid_map[i]= j;
        break;
1099 1100 1101 1102 1103 1104
      }
    }
    DBUG_ASSERT(data.unique_index_attrid_map[i] != 255);
  }
  DBUG_RETURN(0);
}
1105

1106 1107 1108 1109 1110 1111
/*
  Create all the indexes for a table.
  If any index should fail to be created,
  the error is returned immediately
*/
int ha_ndbcluster::create_indexes(Ndb *ndb, TABLE *tab)
1112
{
1113
  uint i;
1114
  int error= 0;
1115
  const char *index_name;
1116
  KEY* key_info= tab->key_info;
1117
  const char **key_name= tab->s->keynames.type_names;
1118
  DBUG_ENTER("ha_ndbcluster::create_indexes");
1119

1120
  for (i= 0; i < tab->s->keys; i++, key_info++, key_name++)
1121
  {
1122
    index_name= *key_name;
1123
    NDB_INDEX_TYPE idx_type= get_index_type_from_table(i);
1124 1125
    error= create_index(index_name, key_info, idx_type, i);
    if (error)
1126
    {
1127 1128
      DBUG_PRINT("error", ("Failed to create index %u", i));
      break;
1129
    }
1130 1131 1132 1133 1134
  }

  DBUG_RETURN(error);
}

tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
1135
static void ndb_init_index(NDB_INDEX_DATA &data)
1136
{
tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
1137 1138 1139 1140 1141 1142 1143 1144 1145
  data.type= UNDEFINED_INDEX;
  data.status= UNDEFINED;
  data.unique_index= NULL;
  data.index= NULL;
  data.unique_index_attrid_map= NULL;
  data.index_stat=NULL;
  data.index_stat_cache_entries=0;
  data.index_stat_update_freq=0;
  data.index_stat_query_count=0;
1146 1147
}

tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
1148
static void ndb_clear_index(NDB_INDEX_DATA &data)
1149
{
tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
1150 1151 1152 1153 1154 1155 1156 1157 1158
  if (data.unique_index_attrid_map)
  {
    my_free((char*)data.unique_index_attrid_map, MYF(0));
  }
  if (data.index_stat)
  {
    delete data.index_stat;
  }
  ndb_init_index(data);
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
}

/*
  Associate a direct reference to an index handle
  with an index (for faster access)
 */
int ha_ndbcluster::add_index_handle(THD *thd, NDBDICT *dict, KEY *key_info,
                                    const char *index_name, uint index_no)
{
  int error= 0;
  NDB_INDEX_TYPE idx_type= get_index_type_from_table(index_no);
  m_index[index_no].type= idx_type;
1171 1172
  DBUG_ENTER("ha_ndbcluster::add_index_handle");
  DBUG_PRINT("enter", ("table %s", m_tabname));
1173 1174 1175 1176

  if (idx_type != PRIMARY_KEY_INDEX && idx_type != UNIQUE_INDEX)
  {
    DBUG_PRINT("info", ("Get handle to index %s", index_name));
1177 1178 1179
    const NDBINDEX *index;
    do
    {
1180
      index= dict->getIndexGlobal(index_name, *m_table);
1181 1182
      if (!index)
        ERR_RETURN(dict->getNdbError());
1183 1184
      DBUG_PRINT("info", ("index: 0x%lx  id: %d  version: %d.%d  status: %d",
                          (long) index,
1185 1186 1187 1188
                          index->getObjectId(),
                          index->getObjectVersion() & 0xFFFFFF,
                          index->getObjectVersion() >> 24,
                          index->getObjectStatus()));
1189 1190
      DBUG_ASSERT(index->getObjectStatus() ==
                  NdbDictionary::Object::Retrieved);
1191 1192
      break;
    } while (1);
1193
    m_index[index_no].index= index;
1194 1195 1196 1197 1198
    // ordered index - add stats
    NDB_INDEX_DATA& d=m_index[index_no];
    delete d.index_stat;
    d.index_stat=NULL;
    if (thd->variables.ndb_index_stat_enable)
1199
    {
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
      d.index_stat=new NdbIndexStat(index);
      d.index_stat_cache_entries=thd->variables.ndb_index_stat_cache_entries;
      d.index_stat_update_freq=thd->variables.ndb_index_stat_update_freq;
      d.index_stat_query_count=0;
      d.index_stat->alloc_cache(d.index_stat_cache_entries);
      DBUG_PRINT("info", ("index %s stat=on cache_entries=%u update_freq=%u",
                          index->getName(),
                          d.index_stat_cache_entries,
                          d.index_stat_update_freq));
    } else
    {
      DBUG_PRINT("info", ("index %s stat=off", index->getName()));
    }
  }
  if (idx_type == UNIQUE_ORDERED_INDEX || idx_type == UNIQUE_INDEX)
  {
    char unique_index_name[FN_LEN];
    static const char* unique_suffix= "$unique";
1218
    m_has_unique_index= TRUE;
1219 1220
    strxnmov(unique_index_name, FN_LEN, index_name, unique_suffix, NullS);
    DBUG_PRINT("info", ("Get handle to unique_index %s", unique_index_name));
1221 1222 1223
    const NDBINDEX *index;
    do
    {
1224
      index= dict->getIndexGlobal(unique_index_name, *m_table);
1225 1226
      if (!index)
        ERR_RETURN(dict->getNdbError());
1227 1228
      DBUG_PRINT("info", ("index: 0x%lx  id: %d  version: %d.%d  status: %d",
                          (long) index,
1229 1230 1231 1232
                          index->getObjectId(),
                          index->getObjectVersion() & 0xFFFFFF,
                          index->getObjectVersion() >> 24,
                          index->getObjectStatus()));
1233 1234
      DBUG_ASSERT(index->getObjectStatus() ==
                  NdbDictionary::Object::Retrieved);
1235 1236
      break;
    } while (1);
1237
    m_index[index_no].unique_index= index;
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    error= fix_unique_index_attr_order(m_index[index_no], index, key_info);
  }
  if (!error)
    m_index[index_no].status= ACTIVE;
  
  DBUG_RETURN(error);
}

/*
  Associate index handles for each index of a table
*/
1249
int ha_ndbcluster::open_indexes(Ndb *ndb, TABLE *tab, bool ignore_error)
1250 1251 1252 1253 1254 1255 1256 1257
{
  uint i;
  int error= 0;
  THD *thd=current_thd;
  NDBDICT *dict= ndb->getDictionary();
  KEY* key_info= tab->key_info;
  const char **key_name= tab->s->keynames.type_names;
  DBUG_ENTER("ha_ndbcluster::open_indexes");
1258
  m_has_unique_index= FALSE;
1259 1260 1261
  for (i= 0; i < tab->s->keys; i++, key_info++, key_name++)
  {
    if ((error= add_index_handle(thd, dict, key_info, *key_name, i)))
1262 1263 1264 1265
      if (ignore_error)
        m_index[i].index= m_index[i].unique_index= NULL;
      else
        break;
1266
    m_index[i].null_in_unique_index= FALSE;
1267
    if (check_index_fields_not_null(key_info))
1268
      m_index[i].null_in_unique_index= TRUE;
1269
  }
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

  if (error && !ignore_error)
  {
    while (i > 0)
    {
      i--;
      if (m_index[i].index)
      {
         dict->removeIndexGlobal(*m_index[i].index, 1);
         m_index[i].index= NULL;
      }
      if (m_index[i].unique_index)
      {
         dict->removeIndexGlobal(*m_index[i].unique_index, 1);
         m_index[i].unique_index= NULL;
      }
    }
  }

  DBUG_ASSERT(error == 0 || error == 4243);

1291 1292 1293 1294 1295 1296 1297
  DBUG_RETURN(error);
}

/*
  Renumber indexes in index list by shifting out
  indexes that are to be dropped
 */
1298
void ha_ndbcluster::renumber_indexes(Ndb *ndb, TABLE *tab)
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
{
  uint i;
  const char *index_name;
  KEY* key_info= tab->key_info;
  const char **key_name= tab->s->keynames.type_names;
  DBUG_ENTER("ha_ndbcluster::renumber_indexes");
  
  for (i= 0; i < tab->s->keys; i++, key_info++, key_name++)
  {
    index_name= *key_name;
    NDB_INDEX_TYPE idx_type= get_index_type_from_table(i);
    m_index[i].type= idx_type;
    if (m_index[i].status == TO_BE_DROPPED) 
    {
      DBUG_PRINT("info", ("Shifting index %s(%i) out of the list", 
                          index_name, i));
      NDB_INDEX_DATA tmp;
      uint j= i + 1;
      // Shift index out of list
      while(j != MAX_KEY && m_index[j].status != UNDEFINED)
1319
      {
1320 1321 1322 1323
        tmp=  m_index[j - 1];
        m_index[j - 1]= m_index[j];
        m_index[j]= tmp;
        j++;
1324 1325
      }
    }
1326 1327
  }

1328
  DBUG_VOID_RETURN;
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
}

/*
  Drop all indexes that are marked for deletion
*/
int ha_ndbcluster::drop_indexes(Ndb *ndb, TABLE *tab)
{
  uint i;
  int error= 0;
  const char *index_name;
  KEY* key_info= tab->key_info;
  NDBDICT *dict= ndb->getDictionary();
  DBUG_ENTER("ha_ndbcluster::drop_indexes");
  
1343
  for (i= 0; i < tab->s->keys; i++, key_info++)
1344 1345 1346 1347
  {
    NDB_INDEX_TYPE idx_type= get_index_type_from_table(i);
    m_index[i].type= idx_type;
    if (m_index[i].status == TO_BE_DROPPED)
1348
    {
1349 1350
      const NdbDictionary::Index *index= m_index[i].index;
      const NdbDictionary::Index *unique_index= m_index[i].unique_index;
1351 1352
      
      if (index)
1353
      {
1354 1355 1356
        index_name= index->getName();
        DBUG_PRINT("info", ("Dropping index %u: %s", i, index_name));  
        // Drop ordered index from ndb
1357 1358 1359 1360 1361 1362
        error= dict->dropIndexGlobal(*index);
        if (!error)
        {
          dict->removeIndexGlobal(*index, 1);
          m_index[i].index= NULL;
        }
1363 1364
      }
      if (!error && unique_index)
1365
      {
1366 1367
        index_name= unique_index->getName();
        DBUG_PRINT("info", ("Dropping unique index %u: %s", i, index_name));
1368
        // Drop unique index from ndb
1369 1370 1371 1372 1373 1374
        error= dict->dropIndexGlobal(*unique_index);
        if (!error)
        {
          dict->removeIndexGlobal(*unique_index, 1);
          m_index[i].unique_index= NULL;
        }
1375
      }
1376 1377
      if (error)
        DBUG_RETURN(error);
tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
1378
      ndb_clear_index(m_index[i]);
1379
      continue;
1380
    }
1381
  }
1382 1383
  
  DBUG_RETURN(error);
1384 1385
}

1386 1387 1388 1389
/*
  Decode the type of an index from information 
  provided in table object
*/
1390
NDB_INDEX_TYPE ha_ndbcluster::get_index_type_from_table(uint inx) const
1391
{
1392 1393
  return get_index_type_from_key(inx, table_share->key_info,
                                 inx == table_share->primary_key);
1394 1395 1396
}

NDB_INDEX_TYPE ha_ndbcluster::get_index_type_from_key(uint inx,
1397 1398
                                                      KEY *key_info,
                                                      bool primary) const
1399 1400
{
  bool is_hash_index=  (key_info[inx].algorithm == 
1401
                        HA_KEY_ALG_HASH);
1402
  if (primary)
1403
    return is_hash_index ? PRIMARY_KEY_INDEX : PRIMARY_KEY_ORDERED_INDEX;
1404 1405
  
  return ((key_info[inx].flags & HA_NOSAME) ? 
1406 1407
          (is_hash_index ? UNIQUE_INDEX : UNIQUE_ORDERED_INDEX) :
          ORDERED_INDEX);
1408
} 
1409

1410
bool ha_ndbcluster::check_index_fields_not_null(KEY* key_info)
1411 1412 1413
{
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
1414
  DBUG_ENTER("ha_ndbcluster::check_index_fields_not_null");
1415 1416 1417 1418 1419
  
  for (; key_part != end; key_part++) 
    {
      Field* field= key_part->field;
      if (field->maybe_null())
1420
	DBUG_RETURN(TRUE);
1421 1422
    }
  
1423
  DBUG_RETURN(FALSE);
1424
}
1425

1426
void ha_ndbcluster::release_metadata(THD *thd, Ndb *ndb)
1427
{
1428
  uint i;
1429

1430 1431 1432
  DBUG_ENTER("release_metadata");
  DBUG_PRINT("enter", ("m_tabname: %s", m_tabname));

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
  NDBDICT *dict= ndb->getDictionary();
  int invalidate_indexes= 0;
  if (thd && thd->lex && thd->lex->sql_command == SQLCOM_FLUSH)
  {
    invalidate_indexes = 1;
  }
  if (m_table != NULL)
  {
    if (m_table->getObjectStatus() == NdbDictionary::Object::Invalid)
      invalidate_indexes= 1;
    dict->removeTableGlobal(*m_table, invalidate_indexes);
  }
  // TODO investigate
  DBUG_ASSERT(m_table_info == NULL);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1447
  m_table_info= NULL;
1448

1449
  // Release index list 
1450 1451
  for (i= 0; i < MAX_KEY; i++)
  {
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    if (m_index[i].unique_index)
    {
      DBUG_ASSERT(m_table != NULL);
      dict->removeIndexGlobal(*m_index[i].unique_index, invalidate_indexes);
    }
    if (m_index[i].index)
    {
      DBUG_ASSERT(m_table != NULL);
      dict->removeIndexGlobal(*m_index[i].index, invalidate_indexes);
    }
tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
1462
    ndb_clear_index(m_index[i]);
1463 1464
  }

1465
  m_table= NULL;
1466 1467 1468
  DBUG_VOID_RETURN;
}

pekka@mysql.com's avatar
pekka@mysql.com committed
1469
int ha_ndbcluster::get_ndb_lock_type(enum thr_lock_type type)
1470
{
1471
  if (type >= TL_WRITE_ALLOW_WRITE)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1472
    return NdbOperation::LM_Exclusive;
mskold@mysql.com's avatar
mskold@mysql.com committed
1473 1474
  if (type ==  TL_READ_WITH_SHARED_LOCKS ||
      uses_blob_value())
1475
    return NdbOperation::LM_Read;
1476
  return NdbOperation::LM_CommittedRead;
1477 1478
}

1479 1480 1481 1482 1483 1484
static const ulong index_type_flags[]=
{
  /* UNDEFINED_INDEX */
  0,                         

  /* PRIMARY_KEY_INDEX */
1485
  HA_ONLY_WHOLE_INDEX, 
1486 1487

  /* PRIMARY_KEY_ORDERED_INDEX */
1488
  /* 
mskold@mysql.com's avatar
mskold@mysql.com committed
1489
     Enable HA_KEYREAD_ONLY when "sorted" indexes are supported, 
1490 1491 1492
     thus ORDERD BY clauses can be optimized by reading directly 
     through the index.
  */
mskold@mysql.com's avatar
mskold@mysql.com committed
1493
  // HA_KEYREAD_ONLY | 
1494
  HA_READ_NEXT |
1495
  HA_READ_PREV |
1496 1497
  HA_READ_RANGE |
  HA_READ_ORDER,
1498 1499

  /* UNIQUE_INDEX */
1500
  HA_ONLY_WHOLE_INDEX,
1501

1502
  /* UNIQUE_ORDERED_INDEX */
1503
  HA_READ_NEXT |
1504
  HA_READ_PREV |
1505 1506
  HA_READ_RANGE |
  HA_READ_ORDER,
1507

1508
  /* ORDERED_INDEX */
1509
  HA_READ_NEXT |
1510
  HA_READ_PREV |
1511 1512
  HA_READ_RANGE |
  HA_READ_ORDER
1513 1514 1515 1516 1517 1518 1519
};

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

inline NDB_INDEX_TYPE ha_ndbcluster::get_index_type(uint idx_no) const
{
  DBUG_ASSERT(idx_no < MAX_KEY);
1520
  return m_index[idx_no].type;
1521 1522
}

1523 1524 1525 1526 1527 1528
inline bool ha_ndbcluster::has_null_in_unique_index(uint idx_no) const
{
  DBUG_ASSERT(idx_no < MAX_KEY);
  return m_index[idx_no].null_in_unique_index;
}

1529 1530 1531 1532 1533 1534 1535 1536

/*
  Get the flags for an index

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

1537 1538
inline ulong ha_ndbcluster::index_flags(uint idx_no, uint part,
                                        bool all_parts) const 
1539
{ 
1540
  DBUG_ENTER("ha_ndbcluster::index_flags");
1541
  DBUG_PRINT("enter", ("idx_no: %u", idx_no));
1542
  DBUG_ASSERT(get_index_type_from_table(idx_no) < index_flags_size);
1543 1544
  DBUG_RETURN(index_type_flags[get_index_type_from_table(idx_no)] | 
              HA_KEY_SCAN_NOT_ROR);
1545 1546
}

pekka@mysql.com's avatar
pekka@mysql.com committed
1547 1548
static void shrink_varchar(Field* field, const byte* & ptr, char* buf)
{
1549
  if (field->type() == MYSQL_TYPE_VARCHAR && ptr != NULL) {
pekka@mysql.com's avatar
pekka@mysql.com committed
1550
    Field_varstring* f= (Field_varstring*)field;
pekka@mysql.com's avatar
pekka@mysql.com committed
1551
    if (f->length_bytes == 1) {
pekka@mysql.com's avatar
pekka@mysql.com committed
1552 1553 1554 1555 1556
      uint pack_len= field->pack_length();
      DBUG_ASSERT(1 <= pack_len && pack_len <= 256);
      if (ptr[1] == 0) {
        buf[0]= ptr[0];
      } else {
1557
        DBUG_ASSERT(FALSE);
pekka@mysql.com's avatar
pekka@mysql.com committed
1558 1559 1560 1561 1562 1563 1564
        buf[0]= 255;
      }
      memmove(buf + 1, ptr + 2, pack_len - 1);
      ptr= buf;
    }
  }
}
1565 1566 1567

int ha_ndbcluster::set_primary_key(NdbOperation *op, const byte *key)
{
1568
  KEY* key_info= table->key_info + table_share->primary_key;
1569 1570 1571 1572 1573 1574 1575
  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;
pekka@mysql.com's avatar
pekka@mysql.com committed
1576 1577 1578
    const byte* ptr= key;
    char buf[256];
    shrink_varchar(field, ptr, buf);
1579
    if (set_ndb_key(op, field, 
1580
                    key_part->fieldnr-1, ptr))
1581
      ERR_RETURN(op->getNdbError());
pekka@mysql.com's avatar
pekka@mysql.com committed
1582
    key += key_part->store_length;
1583 1584 1585 1586 1587
  }
  DBUG_RETURN(0);
}


1588
int ha_ndbcluster::set_primary_key_from_record(NdbOperation *op, const byte *record)
1589
{
1590
  KEY* key_info= table->key_info + table_share->primary_key;
1591 1592
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
1593
  DBUG_ENTER("set_primary_key_from_record");
1594 1595 1596 1597 1598

  for (; key_part != end; key_part++) 
  {
    Field* field= key_part->field;
    if (set_ndb_key(op, field, 
1599
		    key_part->fieldnr-1, record+key_part->offset))
1600 1601 1602 1603 1604
      ERR_RETURN(op->getNdbError());
  }
  DBUG_RETURN(0);
}

1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
int ha_ndbcluster::set_index_key_from_record(NdbOperation *op, 
                                             const byte *record, uint keyno)
{
  KEY* key_info= table->key_info + keyno;
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
  uint i;
  DBUG_ENTER("set_index_key_from_record");
                                                                                
  for (i= 0; key_part != end; key_part++, i++)
  {
    Field* field= key_part->field;
    if (set_ndb_key(op, field, m_index[keyno].unique_index_attrid_map[i],
                    record+key_part->offset))
      ERR_RETURN(m_active_trans->getNdbError());
  }
  DBUG_RETURN(0);
}

1624 1625
int 
ha_ndbcluster::set_index_key(NdbOperation *op, 
1626 1627
                             const KEY *key_info, 
                             const byte * key_ptr)
1628
{
1629
  DBUG_ENTER("ha_ndbcluster::set_index_key");
1630 1631 1632 1633 1634 1635
  uint i;
  KEY_PART_INFO* key_part= key_info->key_part;
  KEY_PART_INFO* end= key_part+key_info->key_parts;
  
  for (i= 0; key_part != end; key_part++, i++) 
  {
pekka@mysql.com's avatar
pekka@mysql.com committed
1636 1637 1638 1639
    Field* field= key_part->field;
    const byte* ptr= key_part->null_bit ? key_ptr + 1 : key_ptr;
    char buf[256];
    shrink_varchar(field, ptr, buf);
tomas@poseidon.ndb.mysql.com's avatar
Merge  
tomas@poseidon.ndb.mysql.com committed
1640
    if (set_ndb_key(op, field, m_index[active_index].unique_index_attrid_map[i], ptr))
1641 1642 1643 1644 1645
      ERR_RETURN(m_active_trans->getNdbError());
    key_ptr+= key_part->store_length;
  }
  DBUG_RETURN(0);
}
1646

1647 1648 1649 1650 1651 1652 1653
inline 
int ha_ndbcluster::define_read_attrs(byte* buf, NdbOperation* op)
{
  uint i;
  DBUG_ENTER("define_read_attrs");  

  // Define attributes to read
1654
  for (i= 0; i < table_share->fields; i++) 
1655 1656
  {
    Field *field= table->field[i];
1657
    if (bitmap_is_set(table->read_set, i) ||
1658
        ((field->flags & PRI_KEY_FLAG)))
1659 1660
    {      
      if (get_ndb_value(op, field, i, buf))
1661
        ERR_RETURN(op->getNdbError());
1662
    } 
1663
    else
1664 1665 1666 1667 1668
    {
      m_value[i].ptr= NULL;
    }
  }
    
1669
  if (table_share->primary_key == MAX_KEY) 
1670 1671 1672
  {
    DBUG_PRINT("info", ("Getting hidden key"));
    // Scanning table with no primary key
1673
    int hidden_no= table_share->fields;      
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
#ifndef DBUG_OFF
    const NDBTAB *tab= (const NDBTAB *) m_table;    
    if (!tab->getColumn(hidden_no))
      DBUG_RETURN(1);
#endif
    if (get_ndb_value(op, NULL, hidden_no, NULL))
      ERR_RETURN(op->getNdbError());
  }
  DBUG_RETURN(0);
} 

tomas@poseidon.ndb.mysql.com's avatar
Merge  
tomas@poseidon.ndb.mysql.com committed
1685

1686 1687 1688 1689
/*
  Read one record from NDB using primary key
*/

1690 1691
int ha_ndbcluster::pk_read(const byte *key, uint key_len, byte *buf,
                           uint32 part_id)
1692
{
1693
  uint no_fields= table_share->fields;
1694 1695
  NdbConnection *trans= m_active_trans;
  NdbOperation *op;
1696

1697 1698 1699 1700
  int res;
  DBUG_ENTER("pk_read");
  DBUG_PRINT("enter", ("key_len: %u", key_len));
  DBUG_DUMP("key", (char*)key, key_len);
1701
  m_write_op= FALSE;
1702

1703 1704
  NdbOperation::LockMode lm=
    (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
joreland@mysql.com's avatar
joreland@mysql.com committed
1705
  if (!(op= trans->getNdbOperation((const NDBTAB *) m_table)) || 
1706
      op->readTuple(lm) != 0)
1707
    ERR_RETURN(trans->getNdbError());
1708
  
1709
  if (table_share->primary_key == MAX_KEY) 
1710 1711 1712 1713 1714
  {
    // 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))
1715
      ERR_RETURN(trans->getNdbError());
1716
    
1717
    // Read key at the same time, for future reference
1718
    if (get_ndb_value(op, NULL, no_fields, NULL))
1719
      ERR_RETURN(trans->getNdbError());
1720 1721 1722 1723 1724 1725 1726
  } 
  else 
  {
    if ((res= set_primary_key(op, key)))
      return res;
  }
  
1727
  if ((res= define_read_attrs(buf, op)))
1728
    DBUG_RETURN(res);
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740

  if (m_use_partition_function)
  {
    op->setPartitionId(part_id);
    // If table has user defined partitioning
    // and no indexes, we need to read the partition id
    // to support ORDER BY queries
    if (table_share->primary_key == MAX_KEY &&
        get_ndb_partition_id(op))
      ERR_RETURN(trans->getNdbError());
  }

1741
  if ((res = execute_no_commit_ie(this,trans,FALSE)) != 0 ||
1742
      op->getNdbError().code) 
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  {
    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);
}

1754 1755
/*
  Read one complementing record from NDB using primary key from old_data
1756
  or hidden key
1757 1758
*/

1759 1760
int ha_ndbcluster::complemented_read(const byte *old_data, byte *new_data,
                                     uint32 old_part_id)
1761
{
1762
  uint no_fields= table_share->fields, i;
1763
  NdbTransaction *trans= m_active_trans;
1764
  NdbOperation *op;
1765
  DBUG_ENTER("complemented_read");
1766
  m_write_op= FALSE;
1767

1768
  if (bitmap_is_set_all(table->read_set))
1769
  {
1770 1771
    // We have allready retrieved all fields, nothing to complement
    DBUG_RETURN(0);
1772
  }
1773

1774 1775
  NdbOperation::LockMode lm=
    (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
joreland@mysql.com's avatar
joreland@mysql.com committed
1776
  if (!(op= trans->getNdbOperation((const NDBTAB *) m_table)) || 
1777
      op->readTuple(lm) != 0)
1778
    ERR_RETURN(trans->getNdbError());
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
  if (table_share->primary_key != MAX_KEY) 
  {
    if (set_primary_key_from_record(op, old_data))
      ERR_RETURN(trans->getNdbError());
  } 
  else 
  {
    // This table has no primary key, use "hidden" primary key
    if (set_hidden_key(op, table->s->fields, m_ref))
      ERR_RETURN(op->getNdbError());
  }
1790 1791 1792 1793

  if (m_use_partition_function)
    op->setPartitionId(old_part_id);
  
1794 1795 1796 1797
  // Read all unreferenced non-key field(s)
  for (i= 0; i < no_fields; i++) 
  {
    Field *field= table->field[i];
1798
    if (!((field->flags & PRI_KEY_FLAG) ||
1799 1800
          bitmap_is_set(table->read_set, i)) &&
        !bitmap_is_set(table->write_set, i))
1801
    {
1802
      if (get_ndb_value(op, field, i, new_data))
1803
        ERR_RETURN(trans->getNdbError());
1804 1805 1806
    }
  }
  
1807
  if (execute_no_commit(this,trans,FALSE) != 0) 
1808 1809 1810 1811 1812 1813 1814 1815
  {
    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;     
1816 1817 1818 1819 1820 1821 1822 1823

  /**
   * restore m_value
   */
  for (i= 0; i < no_fields; i++) 
  {
    Field *field= table->field[i];
    if (!((field->flags & PRI_KEY_FLAG) ||
1824
          bitmap_is_set(table->read_set, i)))
1825 1826 1827 1828 1829
    {
      m_value[i].ptr= NULL;
    }
  }
  
1830 1831 1832
  DBUG_RETURN(0);
}

1833
/*
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
 * Check that all operations between first and last all
 * have gotten the errcode
 * If checking for HA_ERR_KEY_NOT_FOUND then update m_dupkey
 * for all succeeding operations
 */
bool ha_ndbcluster::check_all_operations_for_error(NdbTransaction *trans,
                                                   const NdbOperation *first,
                                                   const NdbOperation *last,
                                                   uint errcode)
{
  const NdbOperation *op= first;
  DBUG_ENTER("ha_ndbcluster::check_all_operations_for_error");

  while(op)
  {
    NdbError err= op->getNdbError();
    if (err.status != NdbError::Success)
    {
      if (ndb_to_mysql_error(&err) != (int) errcode)
1853
        DBUG_RETURN(FALSE);
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
      if (op == last) break;
      op= trans->getNextCompletedOperation(op);
    }
    else
    {
      // We found a duplicate
      if (op->getType() == NdbOperation::UniqueIndexAccess)
      {
        if (errcode == HA_ERR_KEY_NOT_FOUND)
        {
          NdbIndexOperation *iop= (NdbIndexOperation *) op;
          const NDBINDEX *index= iop->getIndex();
          // Find the key_no of the index
          for(uint i= 0; i<table->s->keys; i++)
          {
            if (m_index[i].unique_index == index)
            {
              m_dupkey= i;
              break;
            }
          }
        }
      }
      else
      {
        // Must have been primary key access
        DBUG_ASSERT(op->getType() == NdbOperation::PrimaryKeyAccess);
        if (errcode == HA_ERR_KEY_NOT_FOUND)
          m_dupkey= table->s->primary_key;
      }
1884
      DBUG_RETURN(FALSE);      
1885 1886
    }
  }
1887
  DBUG_RETURN(TRUE);
1888 1889 1890 1891 1892 1893
}


/*
 * Peek to check if any rows already exist with conflicting
 * primary key or unique index values
1894 1895
*/

1896 1897
int ha_ndbcluster::peek_indexed_rows(const byte *record,
				     bool check_pk)
1898
{
1899
  NdbTransaction *trans= m_active_trans;
1900
  NdbOperation *op;
1901 1902
  const NdbOperation *first, *last;
  uint i;
1903
  int res;
1904
  DBUG_ENTER("peek_indexed_rows");
1905

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
1906
  NdbOperation::LockMode lm=
1907
      (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
1908
  first= NULL;
1909
  if (check_pk && table->s->primary_key != MAX_KEY)
1910
  {
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
    /*
     * Fetch any row with colliding primary key
     */
    if (!(op= trans->getNdbOperation((const NDBTAB *) m_table)) ||
        op->readTuple(lm) != 0)
      ERR_RETURN(trans->getNdbError());
    
    first= op;
    if ((res= set_primary_key_from_record(op, record)))
      ERR_RETURN(trans->getNdbError());

    if (m_use_partition_function)
1923
    {
1924 1925 1926
      uint32 part_id;
      int error;
      longlong func_value;
1927 1928 1929 1930
      my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
      error= m_part_info->get_partition_id(m_part_info, &part_id, &func_value);
      dbug_tmp_restore_column_map(table->read_set, old_map);
      if (error)
1931 1932
      {
        m_part_info->err_value= func_value;
1933
        DBUG_RETURN(error);
1934
      }
1935
      op->setPartitionId(part_id);
1936 1937
    }
  }
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
  /*
   * Fetch any rows with colliding unique indexes
   */
  KEY* key_info;
  KEY_PART_INFO *key_part, *end;
  for (i= 0, key_info= table->key_info; i < table->s->keys; i++, key_info++)
  {
    if (i != table->s->primary_key &&
        key_info->flags & HA_NOSAME)
    {
      // A unique index is defined on table
      NdbIndexOperation *iop;
1950
      const NDBINDEX *unique_index = m_index[i].unique_index;
1951 1952
      key_part= key_info->key_part;
      end= key_part + key_info->key_parts;
1953
      if (!(iop= trans->getNdbIndexOperation(unique_index, m_table)) ||
1954 1955
          iop->readTuple(lm) != 0)
        ERR_RETURN(trans->getNdbError());
1956

1957 1958 1959 1960 1961 1962 1963 1964
      if (!first)
        first= iop;
      if ((res= set_index_key_from_record(iop, record, i)))
        ERR_RETURN(trans->getNdbError());
    }
  }
  last= trans->getLastDefinedOperation();
  if (first)
1965
    res= execute_no_commit_ie(this,trans,FALSE);
1966 1967 1968 1969 1970 1971 1972 1973
  else
  {
    // Table has no keys
    table->status= STATUS_NOT_FOUND;
    DBUG_RETURN(HA_ERR_KEY_NOT_FOUND);
  }
  if (check_all_operations_for_error(trans, first, last, 
                                     HA_ERR_KEY_NOT_FOUND))
1974 1975 1976 1977
  {
    table->status= STATUS_NOT_FOUND;
    DBUG_RETURN(ndb_err(trans));
  } 
1978 1979 1980 1981
  else
  {
    DBUG_PRINT("info", ("m_dupkey %d", m_dupkey));
  }
1982 1983
  DBUG_RETURN(0);
}
1984

1985

1986 1987 1988 1989 1990
/*
  Read one record from NDB using unique secondary index
*/

int ha_ndbcluster::unique_index_read(const byte *key,
1991
                                     uint key_len, byte *buf)
1992
{
1993
  int res;
1994
  NdbTransaction *trans= m_active_trans;
1995
  NdbIndexOperation *op;
1996
  DBUG_ENTER("ha_ndbcluster::unique_index_read");
1997 1998 1999
  DBUG_PRINT("enter", ("key_len: %u, index: %u", key_len, active_index));
  DBUG_DUMP("key", (char*)key, key_len);
  
2000 2001
  NdbOperation::LockMode lm=
    (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
2002 2003
  if (!(op= trans->getNdbIndexOperation(m_index[active_index].unique_index, 
                                        m_table)) ||
2004
      op->readTuple(lm) != 0)
2005 2006 2007
    ERR_RETURN(trans->getNdbError());
  
  // Set secondary index key(s)
2008
  if ((res= set_index_key(op, table->key_info + active_index, key)))
2009 2010
    DBUG_RETURN(res);
  
2011
  if ((res= define_read_attrs(buf, op)))
2012
    DBUG_RETURN(res);
2013

2014
  if (execute_no_commit_ie(this,trans,FALSE) != 0 ||
2015
      op->getNdbError().code) 
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
  {
    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);
}

2026
inline int ha_ndbcluster::fetch_next(NdbScanOperation* cursor)
2027 2028
{
  DBUG_ENTER("fetch_next");
2029
  int local_check;
2030
  NdbTransaction *trans= m_active_trans;
2031
  
mskold@mysql.com's avatar
mskold@mysql.com committed
2032 2033 2034 2035 2036 2037 2038 2039
  if (m_lock_tuple)
  {
    /*
      Lock level m_lock.type either TL_WRITE_ALLOW_WRITE
      (SELECT FOR UPDATE) or TL_READ_WITH_SHARED_LOCKS (SELECT
      LOCK WITH SHARE MODE) and row was not explictly unlocked 
      with unlock_row() call
    */
2040
      NdbConnection *con_trans= m_active_trans;
mskold@mysql.com's avatar
mskold@mysql.com committed
2041 2042 2043 2044 2045 2046
      NdbOperation *op;
      // Lock row
      DBUG_PRINT("info", ("Keeping lock on scanned row"));
      
      if (!(op= m_active_cursor->lockCurrentTuple()))
      {
2047
        /* purecov: begin inspected */
2048
	m_lock_tuple= FALSE;
2049 2050
	ERR_RETURN(con_trans->getNdbError());
        /* purecov: end */    
mskold@mysql.com's avatar
mskold@mysql.com committed
2051 2052 2053
      }
      m_ops_pending++;
  }
2054
  m_lock_tuple= FALSE;
mskold@mysql.com's avatar
mskold@mysql.com committed
2055 2056 2057
  
  bool contact_ndb= m_lock.type < TL_WRITE_ALLOW_WRITE &&
                    m_lock.type != TL_READ_WITH_SHARED_LOCKS;;
2058 2059
  do {
    DBUG_PRINT("info", ("Call nextResult, contact_ndb: %d", contact_ndb));
pekka@mysql.com's avatar
pekka@mysql.com committed
2060 2061 2062
    /*
      We can only handle one tuple with blobs at a time.
    */
2063
    if (m_ops_pending && m_blobs_pending)
pekka@mysql.com's avatar
pekka@mysql.com committed
2064
    {
2065
      if (execute_no_commit(this,trans,FALSE) != 0)
2066
        DBUG_RETURN(ndb_err(trans));
2067 2068
      m_ops_pending= 0;
      m_blobs_pending= FALSE;
pekka@mysql.com's avatar
pekka@mysql.com committed
2069
    }
2070
    
2071
    if ((local_check= cursor->nextResult(contact_ndb, m_force_send)) == 0)
2072
    {
mskold@mysql.com's avatar
mskold@mysql.com committed
2073 2074 2075 2076 2077 2078 2079
      /*
	Explicitly lock tuple if "select for update" or
	"select lock in share mode"
      */
      m_lock_tuple= (m_lock.type == TL_WRITE_ALLOW_WRITE
		     || 
		     m_lock.type == TL_READ_WITH_SHARED_LOCKS);
2080 2081
      DBUG_RETURN(0);
    } 
2082
    else if (local_check == 1 || local_check == 2)
2083 2084 2085
    {
      // 1: No more records
      // 2: No more cached records
2086
      
2087
      /*
2088 2089 2090
        Before fetching more rows and releasing lock(s),
        all pending update or delete operations should 
        be sent to NDB
2091
      */
2092
      DBUG_PRINT("info", ("ops_pending: %ld", (long) m_ops_pending));    
2093
      if (m_ops_pending)
2094
      {
2095 2096
        if (m_transaction_on)
        {
2097
          if (execute_no_commit(this,trans,FALSE) != 0)
2098 2099 2100 2101 2102 2103
            DBUG_RETURN(-1);
        }
        else
        {
          if  (execute_commit(this,trans) != 0)
            DBUG_RETURN(-1);
2104
          if (trans->restart() != 0)
2105 2106 2107 2108 2109 2110
          {
            DBUG_ASSERT(0);
            DBUG_RETURN(-1);
          }
        }
        m_ops_pending= 0;
2111
      }
2112
      contact_ndb= (local_check == 2);
2113
    }
2114 2115 2116 2117
    else
    {
      DBUG_RETURN(-1);
    }
2118
  } while (local_check == 2);
2119

2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
  DBUG_RETURN(1);
}

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

2132 2133 2134 2135 2136 2137 2138
*/

inline int ha_ndbcluster::next_result(byte *buf)
{  
  int res;
  DBUG_ENTER("next_result");
    
2139 2140 2141
  if (!m_active_cursor)
    DBUG_RETURN(HA_ERR_END_OF_FILE);
  
2142
  if ((res= fetch_next(m_active_cursor)) == 0)
2143 2144 2145 2146 2147 2148 2149
  {
    DBUG_PRINT("info", ("One more record found"));    
    
    unpack_record(buf);
    table->status= 0;
    DBUG_RETURN(0);
  }
2150
  else if (res == 1)
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
  {
    // No more records
    table->status= STATUS_NOT_FOUND;
    
    DBUG_PRINT("info", ("No more records"));
    DBUG_RETURN(HA_ERR_END_OF_FILE);
  }
  else
  {
    DBUG_RETURN(ndb_err(m_active_trans));
  }
2162 2163
}

2164
/*
2165
  Set bounds for ordered index scan.
2166 2167
*/

joreland@mysql.com's avatar
joreland@mysql.com committed
2168
int ha_ndbcluster::set_bounds(NdbIndexScanOperation *op,
2169 2170
                              uint inx,
                              bool rir,
2171 2172
                              const key_range *keys[2],
                              uint range_no)
2173
{
2174
  const KEY *const key_info= table->key_info + inx;
2175 2176 2177
  const uint key_parts= key_info->key_parts;
  uint key_tot_len[2];
  uint tot_len;
2178
  uint i, j;
2179 2180

  DBUG_ENTER("set_bounds");
2181
  DBUG_PRINT("info", ("key_parts=%d", key_parts));
2182

2183
  for (j= 0; j <= 1; j++)
2184
  {
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
    const key_range *key= keys[j];
    if (key != NULL)
    {
      // for key->flag see ha_rkey_function
      DBUG_PRINT("info", ("key %d length=%d flag=%d",
                          j, key->length, key->flag));
      key_tot_len[j]= key->length;
    }
    else
    {
      DBUG_PRINT("info", ("key %d not present", j));
      key_tot_len[j]= 0;
    }
2198 2199
  }
  tot_len= 0;
2200

2201 2202 2203 2204
  for (i= 0; i < key_parts; i++)
  {
    KEY_PART_INFO *key_part= &key_info->key_part[i];
    Field *field= key_part->field;
2205
#ifndef DBUG_OFF
2206
    uint part_len= key_part->length;
2207
#endif
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    uint part_store_len= key_part->store_length;
    // Info about each key part
    struct part_st {
      bool part_last;
      const key_range *key;
      const byte *part_ptr;
      bool part_null;
      int bound_type;
      const char* bound_ptr;
    };
    struct part_st part[2];

    for (j= 0; j <= 1; j++)
    {
2222
      struct part_st &p= part[j];
2223 2224 2225 2226 2227 2228 2229
      p.key= NULL;
      p.bound_type= -1;
      if (tot_len < key_tot_len[j])
      {
        p.part_last= (tot_len + part_store_len >= key_tot_len[j]);
        p.key= keys[j];
        p.part_ptr= &p.key->key[tot_len];
joreland@mysql.com's avatar
joreland@mysql.com committed
2230
        p.part_null= key_part->null_bit && *p.part_ptr;
2231
        p.bound_ptr= (const char *)
joreland@mysql.com's avatar
joreland@mysql.com committed
2232
          p.part_null ? 0 : key_part->null_bit ? p.part_ptr + 1 : p.part_ptr;
2233 2234 2235 2236 2237 2238

        if (j == 0)
        {
          switch (p.key->flag)
          {
            case HA_READ_KEY_EXACT:
2239 2240 2241 2242
              if (! rir)
                p.bound_type= NdbIndexScanOperation::BoundEQ;
              else // differs for records_in_range
                p.bound_type= NdbIndexScanOperation::BoundLE;
2243
              break;
2244
            // ascending
2245 2246 2247 2248 2249 2250 2251 2252 2253
            case HA_READ_KEY_OR_NEXT:
              p.bound_type= NdbIndexScanOperation::BoundLE;
              break;
            case HA_READ_AFTER_KEY:
              if (! p.part_last)
                p.bound_type= NdbIndexScanOperation::BoundLE;
              else
                p.bound_type= NdbIndexScanOperation::BoundLT;
              break;
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
            // descending
            case HA_READ_PREFIX_LAST:           // weird
              p.bound_type= NdbIndexScanOperation::BoundEQ;
              break;
            case HA_READ_PREFIX_LAST_OR_PREV:   // weird
              p.bound_type= NdbIndexScanOperation::BoundGE;
              break;
            case HA_READ_BEFORE_KEY:
              if (! p.part_last)
                p.bound_type= NdbIndexScanOperation::BoundGE;
              else
                p.bound_type= NdbIndexScanOperation::BoundGT;
              break;
2267 2268 2269 2270 2271 2272 2273
            default:
              break;
          }
        }
        if (j == 1) {
          switch (p.key->flag)
          {
2274
            // ascending
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
            case HA_READ_BEFORE_KEY:
              if (! p.part_last)
                p.bound_type= NdbIndexScanOperation::BoundGE;
              else
                p.bound_type= NdbIndexScanOperation::BoundGT;
              break;
            case HA_READ_AFTER_KEY:     // weird
              p.bound_type= NdbIndexScanOperation::BoundGE;
              break;
            default:
              break;
2286
            // descending strangely sets no end key
2287 2288
          }
        }
2289

2290 2291 2292
        if (p.bound_type == -1)
        {
          DBUG_PRINT("error", ("key %d unknown flag %d", j, p.key->flag));
2293
          DBUG_ASSERT(FALSE);
2294
          // Stop setting bounds but continue with what we have
2295
          DBUG_RETURN(op->end_of_bound(range_no));
2296 2297 2298
        }
      }
    }
2299

2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
    // Seen with e.g. b = 1 and c > 1
    if (part[0].bound_type == NdbIndexScanOperation::BoundLE &&
        part[1].bound_type == NdbIndexScanOperation::BoundGE &&
        memcmp(part[0].part_ptr, part[1].part_ptr, part_store_len) == 0)
    {
      DBUG_PRINT("info", ("replace LE/GE pair by EQ"));
      part[0].bound_type= NdbIndexScanOperation::BoundEQ;
      part[1].bound_type= -1;
    }
    // Not seen but was in previous version
    if (part[0].bound_type == NdbIndexScanOperation::BoundEQ &&
        part[1].bound_type == NdbIndexScanOperation::BoundGE &&
        memcmp(part[0].part_ptr, part[1].part_ptr, part_store_len) == 0)
    {
      DBUG_PRINT("info", ("remove GE from EQ/GE pair"));
      part[1].bound_type= -1;
    }
2317

2318 2319
    for (j= 0; j <= 1; j++)
    {
2320
      struct part_st &p= part[j];
2321 2322 2323
      // Set bound if not done with this key
      if (p.key != NULL)
      {
2324
        DBUG_PRINT("info", ("key %d:%d  offset: %d  length: %d  last: %d  bound: %d",
2325 2326 2327 2328 2329
                            j, i, tot_len, part_len, p.part_last, p.bound_type));
        DBUG_DUMP("info", (const char*)p.part_ptr, part_store_len);

        // Set bound if not cancelled via type -1
        if (p.bound_type != -1)
2330
        {
pekka@mysql.com's avatar
pekka@mysql.com committed
2331 2332 2333
          const char* ptr= p.bound_ptr;
          char buf[256];
          shrink_varchar(field, ptr, buf);
tomas@poseidon.ndb.mysql.com's avatar
Merge  
tomas@poseidon.ndb.mysql.com committed
2334
          if (op->setBound(i, p.bound_type, ptr))
2335
            ERR_RETURN(op->getNdbError());
2336
        }
2337 2338 2339 2340
      }
    }

    tot_len+= part_store_len;
2341
  }
2342
  DBUG_RETURN(op->end_of_bound(range_no));
2343 2344
}

2345
/*
2346
  Start ordered index scan in NDB
2347 2348
*/

2349
int ha_ndbcluster::ordered_index_scan(const key_range *start_key,
2350
                                      const key_range *end_key,
2351 2352
                                      bool sorted, bool descending,
                                      byte* buf, part_id_range *part_spec)
2353
{  
2354
  int res;
joreland@mysql.com's avatar
joreland@mysql.com committed
2355
  bool restart;
2356
  NdbTransaction *trans= m_active_trans;
joreland@mysql.com's avatar
joreland@mysql.com committed
2357
  NdbIndexScanOperation *op;
2358

2359 2360 2361
  DBUG_ENTER("ha_ndbcluster::ordered_index_scan");
  DBUG_PRINT("enter", ("index: %u, sorted: %d, descending: %d",
             active_index, sorted, descending));  
2362
  DBUG_PRINT("enter", ("Starting new ordered scan on %s", m_tabname));
2363
  m_write_op= FALSE;
pekka@mysql.com's avatar
pekka@mysql.com committed
2364

2365 2366
  // Check that sorted seems to be initialised
  DBUG_ASSERT(sorted == 0 || sorted == 1);
2367
  
2368
  if (m_active_cursor == 0)
joreland@mysql.com's avatar
joreland@mysql.com committed
2369
  {
2370
    restart= FALSE;
joreland@mysql.com's avatar
joreland@mysql.com committed
2371 2372
    NdbOperation::LockMode lm=
      (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
mskold@mysql.com's avatar
mskold@mysql.com committed
2373
   bool need_pk = (lm == NdbOperation::LM_Read);
2374 2375
    if (!(op= trans->getNdbIndexScanOperation(m_index[active_index].index, 
                                              m_table)) ||
2376
        op->readTuples(lm, 0, parallelism, sorted, descending, FALSE, need_pk))
joreland@mysql.com's avatar
joreland@mysql.com committed
2377
      ERR_RETURN(trans->getNdbError());
2378 2379 2380
    if (m_use_partition_function && part_spec != NULL &&
        part_spec->start_part == part_spec->end_part)
      op->setPartitionId(part_spec->start_part);
2381
    m_active_cursor= op;
joreland@mysql.com's avatar
joreland@mysql.com committed
2382
  } else {
2383
    restart= TRUE;
2384
    op= (NdbIndexScanOperation*)m_active_cursor;
joreland@mysql.com's avatar
joreland@mysql.com committed
2385
    
2386 2387 2388
    if (m_use_partition_function && part_spec != NULL &&
        part_spec->start_part == part_spec->end_part)
      op->setPartitionId(part_spec->start_part);
joreland@mysql.com's avatar
joreland@mysql.com committed
2389 2390
    DBUG_ASSERT(op->getSorted() == sorted);
    DBUG_ASSERT(op->getLockMode() == 
2391
                (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type));
2392
    if (op->reset_bounds(m_force_send))
joreland@mysql.com's avatar
joreland@mysql.com committed
2393 2394
      DBUG_RETURN(ndb_err(m_active_trans));
  }
2395
  
2396
  {
2397
    const key_range *keys[2]= { start_key, end_key };
2398
    res= set_bounds(op, active_index, FALSE, keys);
2399 2400
    if (res)
      DBUG_RETURN(res);
2401
  }
2402

2403
  if (!restart)
2404
  {
2405
    if (m_cond && m_cond->generate_scan_filter(op))
2406 2407
      DBUG_RETURN(ndb_err(trans));

2408
    if ((res= define_read_attrs(buf, op)))
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
    {
      DBUG_RETURN(res);
    }
    
    // If table has user defined partitioning
    // and no primary key, we need to read the partition id
    // to support ORDER BY queries
    if (m_use_partition_function &&
        (table_share->primary_key == MAX_KEY) && 
        (get_ndb_partition_id(op)))
      ERR_RETURN(trans->getNdbError());
joreland@mysql.com's avatar
joreland@mysql.com committed
2420
  }
2421

2422
  if (execute_no_commit(this,trans,FALSE) != 0)
2423 2424 2425 2426
    DBUG_RETURN(ndb_err(trans));
  
  DBUG_RETURN(next_result(buf));
}
2427

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
static
int
guess_scan_flags(NdbOperation::LockMode lm, 
		 const NDBTAB* tab, const MY_BITMAP* readset)
{
  int flags= 0;
  flags|= (lm == NdbOperation::LM_Read) ? NdbScanOperation::SF_KeyInfo : 0;
  if (tab->checkColumns(0, 0) & 2)
  {
    int ret = tab->checkColumns(readset->bitmap, no_bytes_in_map(readset));
    
    if (ret & 2)
    { // If disk columns...use disk scan
      flags |= NdbScanOperation::SF_DiskScan;
    }
    else if ((ret & 4) == 0 && (lm == NdbOperation::LM_Exclusive))
    {
      // If no mem column is set and exclusive...guess disk scan
      flags |= NdbScanOperation::SF_DiskScan;
    }
  }
  return flags;
}

2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510

/*
  Unique index scan in NDB (full table scan with scan filter)
 */

int ha_ndbcluster::unique_index_scan(const KEY* key_info, 
				     const byte *key, 
				     uint key_len,
				     byte *buf)
{
  int res;
  NdbScanOperation *op;
  NdbTransaction *trans= m_active_trans;
  part_id_range part_spec;

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

  NdbOperation::LockMode lm=
    (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
  int flags= guess_scan_flags(lm, m_table, table->read_set);
  if (!(op=trans->getNdbScanOperation((const NDBTAB *) m_table)) ||
      op->readTuples(lm, flags, parallelism))
    ERR_RETURN(trans->getNdbError());
  m_active_cursor= op;

  if (m_use_partition_function)
  {
    part_spec.start_part= 0;
    part_spec.end_part= m_part_info->get_tot_partitions() - 1;
    prune_partition_set(table, &part_spec);
    DBUG_PRINT("info", ("part_spec.start_part = %u, part_spec.end_part = %u",
                        part_spec.start_part, part_spec.end_part));
    /*
      If partition pruning has found no partition in set
      we can return HA_ERR_END_OF_FILE
      If partition pruning has found exactly one partition in set
      we can optimize scan to run towards that partition only.
    */
    if (part_spec.start_part > part_spec.end_part)
    {
      DBUG_RETURN(HA_ERR_END_OF_FILE);
    }
    else if (part_spec.start_part == part_spec.end_part)
    {
      /*
        Only one partition is required to scan, if sorted is required we
        don't need it any more since output from one ordered partitioned
        index is always sorted.
      */
      m_active_cursor->setPartitionId(part_spec.start_part);
    }
    // If table has user defined partitioning
    // and no primary key, we need to read the partition id
    // to support ORDER BY queries
    if ((table_share->primary_key == MAX_KEY) && 
        (get_ndb_partition_id(op)))
      ERR_RETURN(trans->getNdbError());
  }
2511 2512 2513 2514 2515 2516 2517 2518
  if (!m_cond)
    m_cond= new ha_ndbcluster_cond;
  if (!m_cond)
  {
    my_errno= HA_ERR_OUT_OF_MEM;
    DBUG_RETURN(my_errno);
  }       
  if (m_cond->generate_scan_filter_from_key(op, key_info, key, key_len, buf))
2519 2520 2521 2522
    DBUG_RETURN(ndb_err(trans));
  if ((res= define_read_attrs(buf, op)))
    DBUG_RETURN(res);

2523
  if (execute_no_commit(this,trans,FALSE) != 0)
2524 2525 2526 2527 2528 2529
    DBUG_RETURN(ndb_err(trans));
  DBUG_PRINT("exit", ("Scan started successfully"));
  DBUG_RETURN(next_result(buf));
}


2530
/*
2531
  Start full table scan in NDB
2532 2533 2534 2535
 */

int ha_ndbcluster::full_table_scan(byte *buf)
{
2536
  int res;
2537
  NdbScanOperation *op;
2538
  NdbTransaction *trans= m_active_trans;
2539
  part_id_range part_spec;
2540 2541 2542

  DBUG_ENTER("full_table_scan");  
  DBUG_PRINT("enter", ("Starting new scan on %s", m_tabname));
2543
  m_write_op= FALSE;
2544

2545 2546
  NdbOperation::LockMode lm=
    (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2547
  int flags= guess_scan_flags(lm, m_table, table->read_set);
2548
  if (!(op=trans->getNdbScanOperation(m_table)) ||
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2549
      op->readTuples(lm, flags, parallelism))
2550
    ERR_RETURN(trans->getNdbError());
2551
  m_active_cursor= op;
2552 2553 2554 2555

  if (m_use_partition_function)
  {
    part_spec.start_part= 0;
2556
    part_spec.end_part= m_part_info->get_tot_partitions() - 1;
2557
    prune_partition_set(table, &part_spec);
2558
    DBUG_PRINT("info", ("part_spec.start_part: %u  part_spec.end_part: %u",
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
                        part_spec.start_part, part_spec.end_part));
    /*
      If partition pruning has found no partition in set
      we can return HA_ERR_END_OF_FILE
      If partition pruning has found exactly one partition in set
      we can optimize scan to run towards that partition only.
    */
    if (part_spec.start_part > part_spec.end_part)
    {
      DBUG_RETURN(HA_ERR_END_OF_FILE);
    }
    else if (part_spec.start_part == part_spec.end_part)
    {
      /*
        Only one partition is required to scan, if sorted is required we
        don't need it any more since output from one ordered partitioned
        index is always sorted.
      */
      m_active_cursor->setPartitionId(part_spec.start_part);
    }
2579 2580 2581 2582 2583 2584
    // If table has user defined partitioning
    // and no primary key, we need to read the partition id
    // to support ORDER BY queries
    if ((table_share->primary_key == MAX_KEY) && 
        (get_ndb_partition_id(op)))
      ERR_RETURN(trans->getNdbError());
2585 2586
  }

2587
  if (m_cond && m_cond->generate_scan_filter(op))
2588
    DBUG_RETURN(ndb_err(trans));
2589
  if ((res= define_read_attrs(buf, op)))
2590 2591
    DBUG_RETURN(res);

2592
  if (execute_no_commit(this,trans,FALSE) != 0)
2593 2594 2595
    DBUG_RETURN(ndb_err(trans));
  DBUG_PRINT("exit", ("Scan started successfully"));
  DBUG_RETURN(next_result(buf));
2596 2597
}

2598 2599 2600 2601 2602
/*
  Insert one record into NDB
*/
int ha_ndbcluster::write_row(byte *record)
{
mskold@mysql.com's avatar
mskold@mysql.com committed
2603
  bool has_auto_increment;
2604
  uint i;
2605
  NdbTransaction *trans= m_active_trans;
2606 2607
  NdbOperation *op;
  int res;
2608
  THD *thd= table->in_use;
2609 2610
  longlong func_value= 0;
  DBUG_ENTER("ha_ndbcluster::write_row");
2611

2612
  m_write_op= TRUE;
2613 2614 2615 2616 2617 2618 2619 2620
  has_auto_increment= (table->next_number_field && record == table->record[0]);
  if (table_share->primary_key != MAX_KEY)
  {
    /*
     * Increase any auto_incremented primary key
     */
    if (has_auto_increment) 
    {
2621
      int error;
2622 2623

      m_skip_auto_increment= FALSE;
2624 2625
      if ((error= update_auto_increment()))
        DBUG_RETURN(error);
2626
      m_skip_auto_increment= (insert_id_for_cur_row == 0);
2627 2628 2629 2630 2631 2632 2633
    }
  }

  /*
   * If IGNORE the ignore constraint violations on primary and unique keys
   */
  if (!m_use_write && m_ignore_dup_key)
2634
  {
2635 2636 2637 2638 2639
    /*
      compare if expression with that in start_bulk_insert()
      start_bulk_insert will set parameters to ensure that each
      write_row is committed individually
    */
2640
    int peek_res= peek_indexed_rows(record, TRUE);
2641 2642 2643 2644 2645 2646 2647
    
    if (!peek_res) 
    {
      DBUG_RETURN(HA_ERR_FOUND_DUPP_KEY);
    }
    if (peek_res != HA_ERR_KEY_NOT_FOUND)
      DBUG_RETURN(peek_res);
2648
  }
2649

2650
  statistic_increment(thd->status_var.ha_write_count, &LOCK_status);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2651 2652
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT)
    table->timestamp_field->set_time();
2653

2654
  if (!(op= trans->getNdbOperation(m_table)))
2655 2656 2657 2658 2659 2660
    ERR_RETURN(trans->getNdbError());

  res= (m_use_write) ? op->writeTuple() :op->insertTuple(); 
  if (res != 0)
    ERR_RETURN(trans->getNdbError());  
 
2661 2662 2663 2664
  if (m_use_partition_function)
  {
    uint32 part_id;
    int error;
2665 2666 2667 2668
    my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
    error= m_part_info->get_partition_id(m_part_info, &part_id, &func_value);
    dbug_tmp_restore_column_map(table->read_set, old_map);
    if (error)
2669 2670
    {
      m_part_info->err_value= func_value;
2671
      DBUG_RETURN(error);
2672
    }
2673 2674 2675
    op->setPartitionId(part_id);
  }

2676
  if (table_share->primary_key == MAX_KEY) 
2677 2678
  {
    // Table has hidden primary key
2679
    Ndb *ndb= get_ndb();
2680 2681
    int ret;
    Uint64 auto_value;
2682 2683
    uint retries= NDB_AUTO_INCREMENT_RETRIES;
    do {
2684 2685
      Ndb_tuple_id_range_guard g(m_share);
      ret= ndb->getAutoIncrementValue(m_table, g.range, auto_value, 1);
2686
    } while (ret == -1 && 
2687 2688
             --retries &&
             ndb->getNdbError().status == NdbError::TemporaryError);
2689
    if (ret == -1)
2690
      ERR_RETURN(ndb->getNdbError());
2691
    if (set_hidden_key(op, table_share->fields, (const byte*)&auto_value))
2692 2693 2694 2695
      ERR_RETURN(op->getNdbError());
  } 
  else 
  {
2696 2697 2698
    int error;
    if ((error= set_primary_key_from_record(op, record)))
      DBUG_RETURN(error);
2699 2700 2701
  }

  // Set non-key attribute(s)
2702
  bool set_blob_value= FALSE;
2703
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
2704
  for (i= 0; i < table_share->fields; i++) 
2705 2706 2707
  {
    Field *field= table->field[i];
    if (!(field->flags & PRI_KEY_FLAG) &&
2708
	(bitmap_is_set(table->write_set, i) || !m_use_write) &&
2709
        set_ndb_value(op, field, i, record-table->record[0], &set_blob_value))
2710
    {
2711
      m_skip_auto_increment= TRUE;
2712
      dbug_tmp_restore_column_map(table->read_set, old_map);
2713
      ERR_RETURN(op->getNdbError());
2714
    }
2715
  }
2716
  dbug_tmp_restore_column_map(table->read_set, old_map);
2717

2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
  if (m_use_partition_function)
  {
    /*
      We need to set the value of the partition function value in
      NDB since the NDB kernel doesn't have easy access to the function
      to calculate the value.
    */
    if (func_value >= INT_MAX32)
      func_value= INT_MAX32;
    uint32 part_func_value= (uint32)func_value;
    uint no_fields= table_share->fields;
    if (table_share->primary_key == MAX_KEY)
      no_fields++;
    op->setValue(no_fields, part_func_value);
  }

2734 2735 2736
  if (thd->slave_thread)
    op->setAnyValue(thd->server_id);

2737 2738
  m_rows_changed++;

2739 2740 2741 2742 2743 2744 2745
  /*
    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!
  */
2746
  m_rows_inserted++;
2747
  no_uncommitted_rows_update(1);
2748
  m_bulk_insert_not_flushed= TRUE;
2749
  if ((m_rows_to_insert == (ha_rows) 1) || 
2750
      ((m_rows_inserted % m_bulk_insert_rows) == 0) ||
2751
      m_primary_key_update ||
2752
      set_blob_value)
2753 2754 2755
  {
    // Send rows to NDB
    DBUG_PRINT("info", ("Sending inserts to NDB, "\
2756
                        "rows_inserted: %d  bulk_insert_rows: %d", 
2757
                        (int)m_rows_inserted, (int)m_bulk_insert_rows));
2758

2759
    m_bulk_insert_not_flushed= FALSE;
2760
    if (m_transaction_on)
2761
    {
2762
      if (execute_no_commit(this,trans,FALSE) != 0)
2763
      {
2764 2765 2766
        m_skip_auto_increment= TRUE;
        no_uncommitted_rows_execute_failure();
        DBUG_RETURN(ndb_err(trans));
2767
      }
2768 2769
    }
    else
2770
    {
2771
      if (execute_commit(this,trans) != 0)
2772
      {
2773 2774 2775
        m_skip_auto_increment= TRUE;
        no_uncommitted_rows_execute_failure();
        DBUG_RETURN(ndb_err(trans));
2776
      }
2777
      if (trans->restart() != 0)
2778
      {
2779 2780
        DBUG_ASSERT(0);
        DBUG_RETURN(-1);
2781
      }
2782
    }
2783
  }
2784
  if ((has_auto_increment) && (m_skip_auto_increment))
mskold@mysql.com's avatar
mskold@mysql.com committed
2785
  {
2786
    Ndb *ndb= get_ndb();
2787
    Uint64 next_val= (Uint64) table->next_number_field->val_int() + 1;
2788
#ifndef DBUG_OFF
2789
    char buff[22];
mskold@mysql.com's avatar
mskold@mysql.com committed
2790
    DBUG_PRINT("info", 
2791 2792
               ("Trying to set next auto increment value to %s",
                llstr(next_val, buff)));
2793
#endif
2794 2795
    Ndb_tuple_id_range_guard g(m_share);
    if (ndb->setAutoIncrementValue(m_table, g.range, next_val, TRUE)
2796
        == -1)
2797
      ERR_RETURN(ndb->getNdbError());
2798
  }
2799
  m_skip_auto_increment= TRUE;
2800

2801
  DBUG_PRINT("exit",("ok"));
2802 2803 2804 2805 2806 2807 2808
  DBUG_RETURN(0);
}


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

int ha_ndbcluster::key_cmp(uint keynr, const byte * old_row,
2809
                           const byte * new_row)
2810 2811 2812 2813 2814 2815 2816 2817 2818
{
  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) !=
2819 2820
          (new_row[key_part->null_offset] & key_part->null_bit))
        return 1;
2821
    }
2822
    if (key_part->key_part_flag & (HA_BLOB_PART | HA_VAR_LENGTH_PART))
2823 2824 2825
    {

      if (key_part->field->cmp_binary((char*) (old_row + key_part->offset),
2826 2827 2828
                                      (char*) (new_row + key_part->offset),
                                      (ulong) key_part->length))
        return 1;
2829 2830 2831 2832
    }
    else
    {
      if (memcmp(old_row+key_part->offset, new_row+key_part->offset,
2833 2834
                 key_part->length))
        return 1;
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
    }
  }
  return 0;
}

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

int ha_ndbcluster::update_row(const byte *old_data, byte *new_data)
{
2846
  THD *thd= table->in_use;
2847
  NdbTransaction *trans= m_active_trans;
2848
  NdbScanOperation* cursor= m_active_cursor;
2849 2850
  NdbOperation *op;
  uint i;
2851 2852
  uint32 old_part_id= 0, new_part_id= 0;
  int error;
2853
  longlong func_value;
2854 2855
  bool pk_update= (table_share->primary_key != MAX_KEY &&
		   key_cmp(table_share->primary_key, old_data, new_data));
2856
  DBUG_ENTER("update_row");
2857
  m_write_op= TRUE;
2858
  
2859
  /*
2860 2861
   * If IGNORE the ignore constraint violations on primary and unique keys,
   * but check that it is not part of INSERT ... ON DUPLICATE KEY UPDATE
2862
   */
2863
  if (m_ignore_dup_key && thd->lex->sql_command == SQLCOM_UPDATE)
2864
  {
2865
    int peek_res= peek_indexed_rows(new_data, pk_update);
2866 2867 2868 2869 2870 2871 2872 2873 2874
    
    if (!peek_res) 
    {
      DBUG_RETURN(HA_ERR_FOUND_DUPP_KEY);
    }
    if (peek_res != HA_ERR_KEY_NOT_FOUND)
      DBUG_RETURN(peek_res);
  }

2875
  statistic_increment(thd->status_var.ha_update_count, &LOCK_status);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2876
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
2877
  {
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2878
    table->timestamp_field->set_time();
2879
    bitmap_set_bit(table->write_set, table->timestamp_field->field_index);
2880
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2881

2882 2883
  if (m_use_partition_function &&
      (error= get_parts_for_update(old_data, new_data, table->record[0],
2884 2885
                                   m_part_info, &old_part_id, &new_part_id,
                                   &func_value)))
2886
  {
2887
    m_part_info->err_value= func_value;
2888 2889 2890
    DBUG_RETURN(error);
  }

2891 2892 2893 2894
  /*
   * Check for update of primary key or partition change
   * for special handling
   */  
2895
  if (pk_update || old_part_id != new_part_id)
2896
  {
2897
    int read_res, insert_res, delete_res, undo_res;
2898

2899 2900
    DBUG_PRINT("info", ("primary key update or partition change, "
                        "doing read+delete+insert"));
2901
    // Get all old fields, since we optimize away fields not in query
2902
    read_res= complemented_read(old_data, new_data, old_part_id);
2903 2904
    if (read_res)
    {
2905
      DBUG_PRINT("info", ("read failed"));
2906 2907
      DBUG_RETURN(read_res);
    }
2908
    // Delete old row
2909
    m_primary_key_update= TRUE;
2910
    delete_res= delete_row(old_data);
2911
    m_primary_key_update= FALSE;
2912 2913 2914
    if (delete_res)
    {
      DBUG_PRINT("info", ("delete failed"));
2915
      DBUG_RETURN(delete_res);
2916
    }     
2917 2918
    // Insert new row
    DBUG_PRINT("info", ("delete succeded"));
2919
    m_primary_key_update= TRUE;
2920
    insert_res= write_row(new_data);
2921
    m_primary_key_update= FALSE;
2922 2923 2924 2925 2926
    if (insert_res)
    {
      DBUG_PRINT("info", ("insert failed"));
      if (trans->commitStatus() == NdbConnection::Started)
      {
2927
        // Undo delete_row(old_data)
2928
        m_primary_key_update= TRUE;
2929 2930 2931 2932 2933 2934
        undo_res= write_row((byte *)old_data);
        if (undo_res)
          push_warning(current_thd, 
                       MYSQL_ERROR::WARN_LEVEL_WARN, 
                       undo_res, 
                       "NDB failed undoing delete at primary key update");
2935 2936 2937 2938 2939
        m_primary_key_update= FALSE;
      }
      DBUG_RETURN(insert_res);
    }
    DBUG_PRINT("info", ("delete+insert succeeded"));
2940
    DBUG_RETURN(0);
2941
  }
2942

2943
  if (cursor)
2944
  {
2945 2946 2947 2948 2949 2950 2951 2952
    /*
      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"));
2953
    if (!(op= cursor->updateCurrentTuple()))
2954
      ERR_RETURN(trans->getNdbError());
2955
    m_lock_tuple= FALSE;
2956
    m_ops_pending++;
2957
    if (uses_blob_value())
2958
      m_blobs_pending= TRUE;
2959 2960
    if (m_use_partition_function)
      cursor->setPartitionId(new_part_id);
2961 2962 2963
  }
  else
  {  
2964
    if (!(op= trans->getNdbOperation(m_table)) ||
2965
        op->updateTuple() != 0)
2966 2967
      ERR_RETURN(trans->getNdbError());  
    
2968 2969
    if (m_use_partition_function)
      op->setPartitionId(new_part_id);
2970
    if (table_share->primary_key == MAX_KEY) 
2971 2972 2973 2974 2975
    {
      // 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 
2976 2977
      // read into m_ref
      DBUG_DUMP("key", m_ref, NDB_HIDDEN_PRIMARY_KEY_LENGTH);
2978
      
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2979
      if (set_hidden_key(op, table->s->fields, m_ref))
2980
        ERR_RETURN(op->getNdbError());
2981 2982 2983 2984
    } 
    else 
    {
      int res;
2985
      if ((res= set_primary_key_from_record(op, old_data)))
2986
        DBUG_RETURN(res);
2987
    }
2988 2989
  }

2990 2991
  m_rows_changed++;

2992
  // Set non-key attribute(s)
2993
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
2994
  for (i= 0; i < table_share->fields; i++) 
2995 2996
  {
    Field *field= table->field[i];
2997
    if (bitmap_is_set(table->write_set, i) &&
2998
        (!(field->flags & PRI_KEY_FLAG)) &&
2999
        set_ndb_value(op, field, i, new_data - table->record[0]))
3000 3001
    {
      dbug_tmp_restore_column_map(table->read_set, old_map);
3002
      ERR_RETURN(op->getNdbError());
3003
    }
3004
  }
3005
  dbug_tmp_restore_column_map(table->read_set, old_map);
3006

3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
  if (m_use_partition_function)
  {
    if (func_value >= INT_MAX32)
      func_value= INT_MAX32;
    uint32 part_func_value= (uint32)func_value;
    uint no_fields= table_share->fields;
    if (table_share->primary_key == MAX_KEY)
      no_fields++;
    op->setValue(no_fields, part_func_value);
  }
3017 3018 3019 3020

  if (thd->slave_thread)
    op->setAnyValue(thd->server_id);

3021 3022 3023 3024 3025 3026 3027
  /*
    Execute update operation if we are not doing a scan for update
    and there exist UPDATE AFTER triggers
  */

  if ((!cursor || m_update_cannot_batch) && 
      execute_no_commit(this,trans,false) != 0) {
3028
    no_uncommitted_rows_execute_failure();
3029
    DBUG_RETURN(ndb_err(trans));
3030
  }
3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
  
  DBUG_RETURN(0);
}


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

int ha_ndbcluster::delete_row(const byte *record)
{
3042
  THD *thd= table->in_use;
3043
  NdbTransaction *trans= m_active_trans;
3044
  NdbScanOperation* cursor= m_active_cursor;
3045
  NdbOperation *op;
3046 3047
  uint32 part_id;
  int error;
3048
  DBUG_ENTER("delete_row");
3049
  m_write_op= TRUE;
3050

3051
  statistic_increment(thd->status_var.ha_delete_count,&LOCK_status);
3052
  m_rows_changed++;
3053

3054 3055 3056 3057 3058 3059 3060
  if (m_use_partition_function &&
      (error= get_part_for_delete(record, table->record[0], m_part_info,
                                  &part_id)))
  {
    DBUG_RETURN(error);
  }

3061
  if (cursor)
3062
  {
3063
    /*
3064
      We are scanning records and want to delete the record
3065
      that was just found, call deleteTuple on the cursor 
3066
      to take over the lock to a new delete operation
3067 3068 3069 3070
      And thus setting the primary key of the record from 
      the active record in cursor
    */
    DBUG_PRINT("info", ("Calling deleteTuple on cursor"));
3071
    if (cursor->deleteCurrentTuple() != 0)
3072
      ERR_RETURN(trans->getNdbError());     
3073
    m_lock_tuple= FALSE;
3074
    m_ops_pending++;
3075

3076 3077 3078
    if (m_use_partition_function)
      cursor->setPartitionId(part_id);

3079 3080
    no_uncommitted_rows_update(-1);

3081 3082 3083
    if (thd->slave_thread)
      ((NdbOperation *)trans->getLastDefinedOperation())->setAnyValue(thd->server_id);

3084
    if (!(m_primary_key_update || m_delete_cannot_batch))
3085 3086
      // If deleting from cursor, NoCommit will be handled in next_result
      DBUG_RETURN(0);
3087 3088
  }
  else
3089
  {
3090
    
3091
    if (!(op=trans->getNdbOperation(m_table)) || 
3092
        op->deleteTuple() != 0)
3093 3094
      ERR_RETURN(trans->getNdbError());
    
3095 3096 3097
    if (m_use_partition_function)
      op->setPartitionId(part_id);

3098 3099
    no_uncommitted_rows_update(-1);
    
3100
    if (table_share->primary_key == MAX_KEY) 
3101 3102 3103 3104
    {
      // This table has no primary key, use "hidden" primary key
      DBUG_PRINT("info", ("Using hidden key"));
      
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3105
      if (set_hidden_key(op, table->s->fields, m_ref))
3106
        ERR_RETURN(op->getNdbError());
3107 3108 3109
    } 
    else 
    {
3110 3111
      if ((error= set_primary_key_from_record(op, record)))
        DBUG_RETURN(error);
3112
    }
3113 3114 3115

    if (thd->slave_thread)
      op->setAnyValue(thd->server_id);
3116
  }
3117

3118
  // Execute delete operation
3119
  if (execute_no_commit(this,trans,FALSE) != 0) {
3120
    no_uncommitted_rows_execute_failure();
3121
    DBUG_RETURN(ndb_err(trans));
3122
  }
3123 3124
  DBUG_RETURN(0);
}
3125
  
3126 3127 3128 3129 3130
/*
  Unpack a record read from NDB 

  SYNOPSIS
    unpack_record()
3131
    buf                 Buffer to store read row
3132 3133 3134 3135 3136 3137 3138 3139

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

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3140 3141
void ndb_unpack_record(TABLE *table, NdbValue *value,
                       MY_BITMAP *defined, byte *buf)
3142
{
3143
  Field **p_field= table->field, *field= *p_field;
3144
  my_ptrdiff_t row_offset= (my_ptrdiff_t) (buf - table->record[0]);
3145
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
3146
  DBUG_ENTER("ndb_unpack_record");
3147

3148 3149 3150 3151 3152 3153
  /*
    Set the filler bits of the null byte, since they are
    not touched in the code below.
    
    The filler bits are the MSBs in the last null byte
  */ 
3154 3155 3156
  if (table->s->null_bytes > 0)
       buf[table->s->null_bytes - 1]|= 256U - (1U <<
					       table->s->last_null_bit_pos);
3157 3158 3159
  /*
    Set null flag(s)
  */
3160 3161
  for ( ; field;
       p_field++, value++, field= *p_field)
3162
  {
3163
    field->set_notnull(row_offset);       
pekka@mysql.com's avatar
pekka@mysql.com committed
3164 3165
    if ((*value).ptr)
    {
3166
      if (!(field->flags & BLOB_FLAG))
pekka@mysql.com's avatar
pekka@mysql.com committed
3167
      {
3168 3169
        int is_null= (*value).rec->isNULL();
        if (is_null)
3170
        {
3171 3172
          if (is_null > 0)
          {
3173
	    DBUG_PRINT("info",("[%u] NULL",
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
                               (*value).rec->getColumn()->getColumnNo()));
            field->set_null(row_offset);
          }
          else
          {
            DBUG_PRINT("info",("[%u] UNDEFINED",
                               (*value).rec->getColumn()->getColumnNo()));
            bitmap_clear_bit(defined,
                             (*value).rec->getColumn()->getColumnNo());
          }
        }
        else if (field->type() == MYSQL_TYPE_BIT)
        {
3187 3188 3189 3190 3191 3192 3193 3194
          Field_bit *field_bit= static_cast<Field_bit*>(field);

          /*
            Move internal field pointer to point to 'buf'.  Calling
            the correct member function directly since we know the
            type of the object.
           */
          field_bit->Field_bit::move_field_offset(row_offset);
3195
          if (field->pack_length() < 5)
3196 3197
          {
            DBUG_PRINT("info", ("bit field H'%.8X", 
3198
                                (*value).rec->u_32_value()));
3199 3200
            field_bit->Field_bit::store((longlong) (*value).rec->u_32_value(),
                                        FALSE);
3201 3202 3203 3204 3205 3206
          }
          else
          {
            DBUG_PRINT("info", ("bit field H'%.8X%.8X",
                                *(Uint32 *)(*value).rec->aRef(),
                                *((Uint32 *)(*value).rec->aRef()+1)));
3207 3208 3209
#ifdef WORDS_BIGENDIAN
            /* lsw is stored first */
            Uint32 *buf= (Uint32 *)(*value).rec->aRef();
3210 3211 3212 3213 3214 3215
            field_bit->Field_bit::store((((longlong)*buf)
                                         & 0x000000000FFFFFFFF)
                                        |
                                        ((((longlong)*(buf+1)) << 32)
                                         & 0xFFFFFFFF00000000),
                                        TRUE);
3216
#else
3217 3218
            field_bit->Field_bit::store((longlong)
                                        (*value).rec->u_64_value(), TRUE);
3219
#endif
3220
          }
3221 3222 3223 3224 3225
          /*
            Move back internal field pointer to point to original
            value (usually record[0]).
           */
          field_bit->Field_bit::move_field_offset(-row_offset);
3226 3227
          DBUG_PRINT("info",("[%u] SET",
                             (*value).rec->getColumn()->getColumnNo()));
3228
          DBUG_DUMP("info", (const char*) field->ptr, field->pack_length());
3229 3230 3231 3232 3233
        }
        else
        {
          DBUG_PRINT("info",("[%u] SET",
                             (*value).rec->getColumn()->getColumnNo()));
3234
          DBUG_DUMP("info", (const char*) field->ptr, field->pack_length());
3235
        }
pekka@mysql.com's avatar
pekka@mysql.com committed
3236 3237 3238
      }
      else
      {
3239
        NdbBlob *ndb_blob= (*value).blob;
3240
        uint col_no = ndb_blob->getColumn()->getColumnNo();
3241 3242
        int isNull;
        ndb_blob->getDefined(isNull);
3243
        if (isNull == 1)
3244
        {
serg@serg.mylan's avatar
serg@serg.mylan committed
3245
          DBUG_PRINT("info",("[%u] NULL", col_no));
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
          field->set_null(row_offset);
        }
        else if (isNull == -1)
        {
          DBUG_PRINT("info",("[%u] UNDEFINED", col_no));
          bitmap_clear_bit(defined, col_no);
        }
        else
        {
#ifndef DBUG_OFF
          // pointer vas set in get_ndb_blobs_value
          Field_blob *field_blob= (Field_blob*)field;
          char* ptr;
          field_blob->get_ptr(&ptr, row_offset);
          uint32 len= field_blob->get_length(row_offset);
3261 3262
          DBUG_PRINT("info",("[%u] SET ptr: 0x%lx  len: %u",
                             col_no, (long) ptr, len));
3263
#endif
3264
        }
pekka@mysql.com's avatar
pekka@mysql.com committed
3265 3266
      }
    }
3267
  }
3268
  dbug_tmp_restore_column_map(table->write_set, old_map);
3269 3270 3271 3272 3273 3274
  DBUG_VOID_RETURN;
}

void ha_ndbcluster::unpack_record(byte *buf)
{
  ndb_unpack_record(table, m_value, 0, buf);
3275 3276
#ifndef DBUG_OFF
  // Read and print all values that was fetched
3277
  if (table_share->primary_key == MAX_KEY)
3278 3279
  {
    // Table with hidden primary key
3280
    int hidden_no= table_share->fields;
3281
    const NDBTAB *tab= m_table;
3282
    char buff[22];
3283
    const NDBCOL *hidden_col= tab->getColumn(hidden_no);
3284
    const NdbRecAttr* rec= m_value[hidden_no].rec;
3285
    DBUG_ASSERT(rec);
3286
    DBUG_PRINT("hidden", ("%d: %s \"%s\"", hidden_no,
3287
			  hidden_col->getName(),
3288
                          llstr(rec->u_64_value(), buff)));
serg@serg.mylan's avatar
serg@serg.mylan committed
3289 3290
  }
  //DBUG_EXECUTE("value", print_results(););
3291 3292 3293 3294 3295
#endif
}

/*
  Utility function to print/dump the fetched field
serg@serg.mylan's avatar
serg@serg.mylan committed
3296 3297 3298
  to avoid unnecessary work, wrap in DBUG_EXECUTE as in:

    DBUG_EXECUTE("value", print_results(););
3299 3300 3301 3302 3303 3304 3305
 */

void ha_ndbcluster::print_results()
{
  DBUG_ENTER("print_results");

#ifndef DBUG_OFF
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
3306

3307
  char buf_type[MAX_FIELD_WIDTH], buf_val[MAX_FIELD_WIDTH];
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
3308
  String type(buf_type, sizeof(buf_type), &my_charset_bin);
3309
  String val(buf_val, sizeof(buf_val), &my_charset_bin);
3310
  for (uint f= 0; f < table_share->fields; f++)
3311
  {
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
3312
    /* Use DBUG_PRINT since DBUG_FILE cannot be filtered out */
3313
    char buf[2000];
3314
    Field *field;
3315
    void* ptr;
pekka@mysql.com's avatar
pekka@mysql.com committed
3316
    NdbValue value;
3317

3318
    buf[0]= 0;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
3319
    field= table->field[f];
pekka@mysql.com's avatar
pekka@mysql.com committed
3320
    if (!(value= m_value[f]).ptr)
3321
    {
3322
      strmov(buf, "not read");
3323
      goto print_value;
3324
    }
3325

3326
    ptr= field->ptr;
pekka@mysql.com's avatar
pekka@mysql.com committed
3327 3328

    if (! (field->flags & BLOB_FLAG))
3329
    {
pekka@mysql.com's avatar
pekka@mysql.com committed
3330 3331
      if (value.rec->isNULL())
      {
3332
        strmov(buf, "NULL");
3333
        goto print_value;
pekka@mysql.com's avatar
pekka@mysql.com committed
3334
      }
3335 3336 3337 3338 3339
      type.length(0);
      val.length(0);
      field->sql_type(type);
      field->val_str(&val);
      my_snprintf(buf, sizeof(buf), "%s %s", type.c_ptr(), val.c_ptr());
pekka@mysql.com's avatar
pekka@mysql.com committed
3340 3341 3342
    }
    else
    {
3343
      NdbBlob *ndb_blob= value.blob;
3344
      bool isNull= TRUE;
pekka@mysql.com's avatar
pekka@mysql.com committed
3345
      ndb_blob->getNull(isNull);
3346 3347
      if (isNull)
        strmov(buf, "NULL");
3348
    }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
3349

3350
print_value:
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
3351
    DBUG_PRINT("value", ("%u,%s: %s", f, field->field_name, buf));
3352 3353 3354 3355 3356 3357
  }
#endif
  DBUG_VOID_RETURN;
}


3358
int ha_ndbcluster::index_init(uint index, bool sorted)
3359
{
3360
  DBUG_ENTER("ha_ndbcluster::index_init");
3361 3362 3363
  DBUG_PRINT("enter", ("index: %u  sorted: %d", index, sorted));
  active_index= index;
  m_sorted= sorted;
mskold@mysql.com's avatar
mskold@mysql.com committed
3364 3365 3366 3367 3368
  /*
    Locks are are explicitly released in scan
    unless m_lock.type == TL_READ_HIGH_PRIORITY
    and no sub-sequent call to unlock_row()
  */
3369
  m_lock_tuple= FALSE;
3370
  DBUG_RETURN(0);
3371 3372 3373 3374 3375
}


int ha_ndbcluster::index_end()
{
3376
  DBUG_ENTER("ha_ndbcluster::index_end");
3377
  DBUG_RETURN(close_scan());
3378 3379
}

3380 3381 3382 3383 3384 3385 3386 3387
/**
 * Check if key contains null
 */
static
int
check_null_in_key(const KEY* key_info, const byte *key, uint key_len)
{
  KEY_PART_INFO *curr_part, *end_part;
3388
  const byte* end_ptr= key + key_len;
3389 3390 3391 3392 3393
  curr_part= key_info->key_part;
  end_part= curr_part + key_info->key_parts;

  for (; curr_part != end_part && key < end_ptr; curr_part++)
  {
3394
    if (curr_part->null_bit && *key)
3395 3396 3397 3398 3399 3400
      return 1;

    key += curr_part->store_length;
  }
  return 0;
}
3401 3402

int ha_ndbcluster::index_read(byte *buf,
3403 3404
                              const byte *key, uint key_len, 
                              enum ha_rkey_function find_flag)
3405
{
3406 3407
  key_range start_key;
  bool descending= FALSE;
3408
  DBUG_ENTER("ha_ndbcluster::index_read");
3409 3410 3411
  DBUG_PRINT("enter", ("active_index: %u, key_len: %u, find_flag: %d", 
                       active_index, key_len, find_flag));

3412 3413 3414
  start_key.key= key;
  start_key.length= key_len;
  start_key.flag= find_flag;
3415
  descending= FALSE;
3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
  switch (find_flag) {
  case HA_READ_KEY_OR_PREV:
  case HA_READ_BEFORE_KEY:
  case HA_READ_PREFIX_LAST:
  case HA_READ_PREFIX_LAST_OR_PREV:
    descending= TRUE;
    break;
  default:
    break;
  }
3426 3427
  DBUG_RETURN(read_range_first_to_buf(&start_key, 0, descending,
                                      m_sorted, buf));
3428 3429 3430 3431 3432
}


int ha_ndbcluster::index_next(byte *buf)
{
3433
  DBUG_ENTER("ha_ndbcluster::index_next");
3434
  statistic_increment(current_thd->status_var.ha_read_next_count,
3435
                      &LOCK_status);
3436
  DBUG_RETURN(next_result(buf));
3437 3438 3439 3440 3441
}


int ha_ndbcluster::index_prev(byte *buf)
{
3442
  DBUG_ENTER("ha_ndbcluster::index_prev");
3443
  statistic_increment(current_thd->status_var.ha_read_prev_count,
3444
                      &LOCK_status);
3445
  DBUG_RETURN(next_result(buf));
3446 3447 3448 3449 3450
}


int ha_ndbcluster::index_first(byte *buf)
{
3451
  DBUG_ENTER("ha_ndbcluster::index_first");
3452
  statistic_increment(current_thd->status_var.ha_read_first_count,
3453
                      &LOCK_status);
3454 3455 3456
  // Start the ordered index scan and fetch the first row

  // Only HA_READ_ORDER indexes get called by index_first
3457
  DBUG_RETURN(ordered_index_scan(0, 0, TRUE, FALSE, buf, NULL));
3458 3459 3460 3461 3462
}


int ha_ndbcluster::index_last(byte *buf)
{
3463
  DBUG_ENTER("ha_ndbcluster::index_last");
3464
  statistic_increment(current_thd->status_var.ha_read_last_count,&LOCK_status);
3465
  DBUG_RETURN(ordered_index_scan(0, 0, TRUE, TRUE, buf, NULL));
3466 3467
}

3468 3469 3470 3471 3472
int ha_ndbcluster::index_read_last(byte * buf, const byte * key, uint key_len)
{
  DBUG_ENTER("ha_ndbcluster::index_read_last");
  DBUG_RETURN(index_read(buf, key, key_len, HA_READ_PREFIX_LAST));
}
3473

3474
int ha_ndbcluster::read_range_first_to_buf(const key_range *start_key,
3475
                                           const key_range *end_key,
3476
                                           bool desc, bool sorted,
3477
                                           byte* buf)
3478
{
3479 3480 3481 3482
  part_id_range part_spec;
  ndb_index_type type= get_index_type(active_index);
  const KEY* key_info= table->key_info+active_index;
  int error; 
3483
  DBUG_ENTER("ha_ndbcluster::read_range_first_to_buf");
3484
  DBUG_PRINT("info", ("desc: %d, sorted: %d", desc, sorted));
3485

3486 3487 3488
  if (m_use_partition_function)
  {
    get_partition_set(table, buf, active_index, start_key, &part_spec);
3489
    DBUG_PRINT("info", ("part_spec.start_part: %u  part_spec.end_part: %u",
3490 3491 3492 3493 3494 3495 3496
                        part_spec.start_part, part_spec.end_part));
    /*
      If partition pruning has found no partition in set
      we can return HA_ERR_END_OF_FILE
      If partition pruning has found exactly one partition in set
      we can optimize scan to run towards that partition only.
    */
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
    if (part_spec.start_part > part_spec.end_part)
    {
      DBUG_RETURN(HA_ERR_END_OF_FILE);
    }
    else if (part_spec.start_part == part_spec.end_part)
    {
      /*
        Only one partition is required to scan, if sorted is required we
        don't need it any more since output from one ordered partitioned
        index is always sorted.
      */
      sorted= FALSE;
    }
  }
3511

3512 3513
  m_write_op= FALSE;
  switch (type){
3514
  case PRIMARY_KEY_ORDERED_INDEX:
3515
  case PRIMARY_KEY_INDEX:
3516
    if (start_key && 
3517 3518
        start_key->length == key_info->key_length &&
        start_key->flag == HA_READ_KEY_EXACT)
3519
    {
3520
      if (m_active_cursor && (error= close_scan()))
3521
        DBUG_RETURN(error);
3522 3523 3524
      error= pk_read(start_key->key, start_key->length, buf,
		     part_spec.start_part);
      DBUG_RETURN(error == HA_ERR_KEY_NOT_FOUND ? HA_ERR_END_OF_FILE : error);
3525
    }
3526
    break;
3527
  case UNIQUE_ORDERED_INDEX:
3528
  case UNIQUE_INDEX:
3529
    if (start_key && start_key->length == key_info->key_length &&
3530 3531
        start_key->flag == HA_READ_KEY_EXACT && 
        !check_null_in_key(key_info, start_key->key, start_key->length))
3532
    {
3533
      if (m_active_cursor && (error= close_scan()))
3534
        DBUG_RETURN(error);
3535 3536 3537

      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);
3538
    }
3539 3540 3541 3542 3543
    else if (type == UNIQUE_INDEX)
      DBUG_RETURN(unique_index_scan(key_info, 
				    start_key->key, 
				    start_key->length, 
				    buf));
3544 3545 3546 3547
    break;
  default:
    break;
  }
3548
  // Start the ordered index scan and fetch the first row
3549 3550
  DBUG_RETURN(ordered_index_scan(start_key, end_key, sorted, desc, buf,
                                 &part_spec));
3551 3552
}

joreland@mysql.com's avatar
joreland@mysql.com committed
3553
int ha_ndbcluster::read_range_first(const key_range *start_key,
3554 3555
                                    const key_range *end_key,
                                    bool eq_r, bool sorted)
joreland@mysql.com's avatar
joreland@mysql.com committed
3556 3557 3558
{
  byte* buf= table->record[0];
  DBUG_ENTER("ha_ndbcluster::read_range_first");
3559 3560
  DBUG_RETURN(read_range_first_to_buf(start_key, end_key, FALSE,
                                      sorted, buf));
joreland@mysql.com's avatar
joreland@mysql.com committed
3561 3562
}

3563
int ha_ndbcluster::read_range_next()
3564 3565 3566 3567 3568 3569
{
  DBUG_ENTER("ha_ndbcluster::read_range_next");
  DBUG_RETURN(next_result(table->record[0]));
}


3570 3571
int ha_ndbcluster::rnd_init(bool scan)
{
3572
  NdbScanOperation *cursor= m_active_cursor;
3573 3574
  DBUG_ENTER("rnd_init");
  DBUG_PRINT("enter", ("scan: %d", scan));
3575
  // Check if scan is to be restarted
mskold@mysql.com's avatar
mskold@mysql.com committed
3576 3577 3578 3579
  if (cursor)
  {
    if (!scan)
      DBUG_RETURN(1);
3580
    if (cursor->restart(m_force_send) != 0)
3581 3582 3583 3584
    {
      DBUG_ASSERT(0);
      DBUG_RETURN(-1);
    }
mskold@mysql.com's avatar
mskold@mysql.com committed
3585
  }
3586
  index_init(table_share->primary_key, 0);
3587 3588 3589
  DBUG_RETURN(0);
}

3590 3591
int ha_ndbcluster::close_scan()
{
3592
  NdbTransaction *trans= m_active_trans;
3593 3594
  DBUG_ENTER("close_scan");

3595 3596
  m_multi_cursor= 0;
  if (!m_active_cursor && !m_multi_cursor)
3597
    DBUG_RETURN(0);
3598

3599
  NdbScanOperation *cursor= m_active_cursor ? m_active_cursor : m_multi_cursor;
3600

3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
  if (m_lock_tuple)
  {
    /*
      Lock level m_lock.type either TL_WRITE_ALLOW_WRITE
      (SELECT FOR UPDATE) or TL_READ_WITH_SHARED_LOCKS (SELECT
      LOCK WITH SHARE MODE) and row was not explictly unlocked 
      with unlock_row() call
    */
      NdbOperation *op;
      // Lock row
      DBUG_PRINT("info", ("Keeping lock on scanned row"));
      
3613
      if (!(op= cursor->lockCurrentTuple()))
3614
      {
3615
	m_lock_tuple= FALSE;
3616 3617 3618 3619
	ERR_RETURN(trans->getNdbError());
      }
      m_ops_pending++;      
  }
3620
  m_lock_tuple= FALSE;
3621
  if (m_ops_pending)
3622 3623 3624 3625 3626
  {
    /*
      Take over any pending transactions to the 
      deleteing/updating transaction before closing the scan    
    */
3627
    DBUG_PRINT("info", ("ops_pending: %ld", (long) m_ops_pending));    
3628
    if (execute_no_commit(this,trans,FALSE) != 0) {
3629
      no_uncommitted_rows_execute_failure();
3630
      DBUG_RETURN(ndb_err(trans));
3631
    }
3632
    m_ops_pending= 0;
3633 3634
  }
  
3635
  cursor->close(m_force_send, TRUE);
3636
  m_active_cursor= m_multi_cursor= NULL;
mskold@mysql.com's avatar
mskold@mysql.com committed
3637
  DBUG_RETURN(0);
3638
}
3639 3640 3641 3642

int ha_ndbcluster::rnd_end()
{
  DBUG_ENTER("rnd_end");
3643
  DBUG_RETURN(close_scan());
3644 3645 3646 3647 3648 3649
}


int ha_ndbcluster::rnd_next(byte *buf)
{
  DBUG_ENTER("rnd_next");
3650
  statistic_increment(current_thd->status_var.ha_read_rnd_next_count,
3651
                      &LOCK_status);
3652

3653
  if (!m_active_cursor)
3654 3655
    DBUG_RETURN(full_table_scan(buf));
  DBUG_RETURN(next_result(buf));
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668
}


/*
  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");
3669
  statistic_increment(current_thd->status_var.ha_read_rnd_count,
3670
                      &LOCK_status);
3671 3672
  // The primary key for the record is stored in pos
  // Perform a pk_read using primary key "index"
3673 3674
  {
    part_id_range part_spec;
3675
    uint key_length= ref_length;
3676 3677
    if (m_use_partition_function)
    {
3678 3679 3680 3681 3682 3683
      if (table_share->primary_key == MAX_KEY)
      {
        /*
          The partition id has been fetched from ndb
          and has been stored directly after the hidden key
        */
3684
        DBUG_DUMP("key+part", (char *)pos, key_length);
3685
        key_length= ref_length - sizeof(m_part_id);
3686
        part_spec.start_part= part_spec.end_part= *(uint32 *)(pos + key_length);
3687 3688 3689 3690
      }
      else
      {
        key_range key_spec;
3691
        KEY *key_info= table->key_info + table_share->primary_key;
3692 3693 3694 3695 3696 3697 3698 3699
        key_spec.key= pos;
        key_spec.length= key_length;
        key_spec.flag= HA_READ_KEY_EXACT;
        get_full_part_id_from_key(table, buf, key_info, 
                                  &key_spec, &part_spec);
        DBUG_ASSERT(part_spec.start_part == part_spec.end_part);
      }
      DBUG_PRINT("info", ("partition id %u", part_spec.start_part));
3700
    }
3701
    DBUG_DUMP("key", (char *)pos, key_length);
3702
    DBUG_RETURN(pk_read(pos, key_length, buf, part_spec.start_part));
3703
  }
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718
}


/*
  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;
3719 3720
  uint key_length;

3721 3722
  DBUG_ENTER("position");

3723
  if (table_share->primary_key != MAX_KEY) 
3724
  {
3725
    key_length= ref_length;
3726
    key_info= table->key_info + table_share->primary_key;
3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
    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;
      }
3742 3743 3744 3745

      size_t len = key_part->length;
      const byte * ptr = record + key_part->offset;
      Field *field = key_part->field;
3746
      if (field->type() ==  MYSQL_TYPE_VARCHAR)
3747
      {
3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
        if (((Field_varstring*)field)->length_bytes == 1)
        {
          /**
           * Keys always use 2 bytes length
           */
          buff[0] = ptr[0];
          buff[1] = 0;
          memcpy(buff+2, ptr + 1, len);
        }
        else
        {
          memcpy(buff, ptr, len + 2);
        }
        len += 2;
3762 3763 3764
      }
      else
      {
3765
        memcpy(buff, ptr, len);
3766 3767
      }
      buff += len;
3768 3769 3770 3771 3772 3773
    }
  } 
  else 
  {
    // No primary key, get hidden key
    DBUG_PRINT("info", ("Getting hidden key"));
3774 3775 3776
    // If table has user defined partition save the partition id as well
    if(m_use_partition_function)
    {
3777
      DBUG_PRINT("info", ("Saving partition id %u", m_part_id));
3778 3779 3780
      key_length= ref_length - sizeof(m_part_id);
      memcpy(ref+key_length, (void *)&m_part_id, sizeof(m_part_id));
    }
3781 3782
    else
      key_length= ref_length;
3783
#ifndef DBUG_OFF
3784
    int hidden_no= table->s->fields;
3785
    const NDBTAB *tab= m_table;  
3786 3787 3788
    const NDBCOL *hidden_col= tab->getColumn(hidden_no);
    DBUG_ASSERT(hidden_col->getPrimaryKey() && 
                hidden_col->getAutoIncrement() &&
3789
                key_length == NDB_HIDDEN_PRIMARY_KEY_LENGTH);
3790
#endif
3791
    memcpy(ref, m_ref, key_length);
3792
  }
3793 3794 3795 3796
#ifndef DBUG_OFF
  if (table_share->primary_key == MAX_KEY && m_use_partition_function) 
    DBUG_DUMP("key+part", (char*)ref, key_length+sizeof(m_part_id));
#endif
3797
  DBUG_DUMP("ref", (char*)ref, key_length);
3798 3799 3800 3801
  DBUG_VOID_RETURN;
}


3802
int ha_ndbcluster::info(uint flag)
3803
{
3804
  int result= 0;
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814
  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_VARIABLE)
3815
  {
3816
    DBUG_PRINT("info", ("HA_STATUS_VARIABLE"));
3817 3818
    if (m_table_info)
    {
3819
      if (m_ha_not_exact_count)
3820
        stats.records= 100;
3821
      else
3822
	result= records_update();
3823 3824 3825
    }
    else
    {
3826
      if ((my_errno= check_ndb_connection()))
3827
        DBUG_RETURN(my_errno);
3828
      Ndb *ndb= get_ndb();
3829
      ndb->setDatabaseName(m_dbname);
3830
      struct Ndb_statistics stat;
3831 3832 3833 3834
      if (ndb->setDatabaseName(m_dbname))
      {
        DBUG_RETURN(my_errno= HA_ERR_OUT_OF_MEM);
      }
3835
      if (current_thd->variables.ndb_use_exact_count &&
3836
          (result= ndb_get_table_statistics(this, TRUE, ndb, m_table, &stat))
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
3837
          == 0)
3838
      {
3839 3840 3841
        stats.mean_rec_length= stat.row_size;
        stats.data_file_length= stat.fragment_memory;
        stats.records= stat.row_count;
3842 3843 3844
      }
      else
      {
3845 3846
        stats.mean_rec_length= 0;
        stats.records= 100;
3847
      }
3848
    }
3849
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3850 3851 3852 3853 3854
  if (flag & HA_STATUS_CONST)
  {
    DBUG_PRINT("info", ("HA_STATUS_CONST"));
    set_rec_per_key();
  }
3855
  if (flag & HA_STATUS_ERRKEY)
3856
  {
3857
    DBUG_PRINT("info", ("HA_STATUS_ERRKEY"));
3858
    errkey= m_dupkey;
3859
  }
3860
  if (flag & HA_STATUS_AUTO)
3861
  {
3862
    DBUG_PRINT("info", ("HA_STATUS_AUTO"));
3863
    if (m_table && table->found_next_number_field)
3864 3865
    {
      Ndb *ndb= get_ndb();
3866
      Ndb_tuple_id_range_guard g(m_share);
3867
      
3868
      Uint64 auto_increment_value64;
3869
      if (ndb->readAutoIncrementValue(m_table, g.range,
3870
                                      auto_increment_value64) == -1)
3871 3872 3873 3874
      {
        const NdbError err= ndb->getNdbError();
        sql_print_error("Error %lu in readAutoIncrementValue(): %s",
                        (ulong) err.code, err.message);
3875
        stats.auto_increment_value= ~(ulonglong)0;
3876
      }
3877
      else
3878
        stats.auto_increment_value= (ulonglong)auto_increment_value64;
3879 3880
    }
  }
3881 3882 3883 3884 3885

  if(result == -1)
    result= HA_ERR_NO_CONNECTION;

  DBUG_RETURN(result);
3886 3887
}

3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901

void ha_ndbcluster::get_dynamic_partition_info(PARTITION_INFO *stat_info,
                                               uint part_id)
{
  /* 
     This functions should be fixed. Suggested fix: to
     implement ndb function which retrives the statistics
     about ndb partitions.
  */
  bzero((char*) stat_info, sizeof(PARTITION_INFO));
  return;
}


3902 3903 3904 3905 3906 3907
int ha_ndbcluster::extra(enum ha_extra_function operation)
{
  DBUG_ENTER("extra");
  switch (operation) {
  case HA_EXTRA_IGNORE_DUP_KEY:       /* Dup keys don't rollback everything*/
    DBUG_PRINT("info", ("HA_EXTRA_IGNORE_DUP_KEY"));
3908 3909
    DBUG_PRINT("info", ("Ignoring duplicate key"));
    m_ignore_dup_key= TRUE;
3910 3911 3912
    break;
  case HA_EXTRA_NO_IGNORE_DUP_KEY:
    DBUG_PRINT("info", ("HA_EXTRA_NO_IGNORE_DUP_KEY"));
3913
    m_ignore_dup_key= FALSE;
3914
    break;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
  case HA_EXTRA_IGNORE_NO_KEY:
    DBUG_PRINT("info", ("HA_EXTRA_IGNORE_NO_KEY"));
    DBUG_PRINT("info", ("Turning on AO_IgnoreError at Commit/NoCommit"));
    m_ignore_no_key= TRUE;
    break;
  case HA_EXTRA_NO_IGNORE_NO_KEY:
    DBUG_PRINT("info", ("HA_EXTRA_NO_IGNORE_NO_KEY"));
    DBUG_PRINT("info", ("Turning on AO_IgnoreError at Commit/NoCommit"));
    m_ignore_no_key= FALSE;
    break;
3925 3926
  case HA_EXTRA_WRITE_CAN_REPLACE:
    DBUG_PRINT("info", ("HA_EXTRA_WRITE_CAN_REPLACE"));
3927 3928
    if (!m_has_unique_index ||
        current_thd->slave_thread) /* always set if slave, quick fix for bug 27378 */
3929 3930 3931 3932 3933 3934 3935 3936 3937 3938
    {
      DBUG_PRINT("info", ("Turning ON use of write instead of insert"));
      m_use_write= TRUE;
    }
    break;
  case HA_EXTRA_WRITE_CANNOT_REPLACE:
    DBUG_PRINT("info", ("HA_EXTRA_WRITE_CANNOT_REPLACE"));
    DBUG_PRINT("info", ("Turning OFF use of write instead of insert"));
    m_use_write= FALSE;
    break;
3939 3940 3941 3942 3943 3944 3945
  case HA_EXTRA_DELETE_CANNOT_BATCH:
    DBUG_PRINT("info", ("HA_EXTRA_DELETE_CANNOT_BATCH"));
    m_delete_cannot_batch= TRUE;
    break;
  case HA_EXTRA_UPDATE_CANNOT_BATCH:
    DBUG_PRINT("info", ("HA_EXTRA_UPDATE_CANNOT_BATCH"));
    m_update_cannot_batch= TRUE;
3946
    break;
3947 3948
  default:
    break;
3949 3950 3951 3952 3953
  }
  
  DBUG_RETURN(0);
}

3954 3955 3956 3957

int ha_ndbcluster::reset()
{
  DBUG_ENTER("ha_ndbcluster::reset");
3958 3959 3960 3961 3962
  if (m_cond)
  {
    m_cond->cond_clear();
  }

3963 3964 3965 3966 3967 3968 3969
  /*
    Regular partition pruning will set the bitmap appropriately.
    Some queries like ALTER TABLE doesn't use partition pruning and
    thus the 'used_partitions' bitmap needs to be initialized
  */
  if (m_part_info)
    bitmap_set_all(&m_part_info->used_partitions);
3970 3971 3972 3973

  /* reset flags set by extra calls */
  m_ignore_dup_key= FALSE;
  m_use_write= FALSE;
3974
  m_ignore_no_key= FALSE;
3975 3976
  m_delete_cannot_batch= FALSE;
  m_update_cannot_batch= FALSE;
3977

3978 3979 3980 3981
  DBUG_RETURN(0);
}


3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994
/* 
   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;
3995
  const NDBTAB *tab= m_table;    
3996 3997

  DBUG_ENTER("start_bulk_insert");
pekka@mysql.com's avatar
pekka@mysql.com committed
3998
  DBUG_PRINT("enter", ("rows: %d", (int)rows));
3999
  
4000
  m_rows_inserted= (ha_rows) 0;
4001
  if (!m_use_write && m_ignore_dup_key)
4002 4003 4004
  {
    /*
      compare if expression with that in write_row
4005
      we have a situation where peek_indexed_rows() will be called
4006 4007 4008 4009 4010 4011 4012 4013
      so we cannot batch
    */
    DBUG_PRINT("info", ("Batching turned off as duplicate key is "
                        "ignored by using peek_row"));
    m_rows_to_insert= 1;
    m_bulk_insert_rows= 1;
    DBUG_VOID_RETURN;
  }
4014
  if (rows == (ha_rows) 0)
4015
  {
4016 4017
    /* We don't know how many will be inserted, guess */
    m_rows_to_insert= m_autoincrement_prefetch;
4018
  }
4019 4020
  else
    m_rows_to_insert= rows; 
4021 4022 4023 4024 4025 4026 4027 4028

  /* 
    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.   
  */
4029
  const int bytesperbatch= 8192;
4030
  bytes= 12 + tab->getRowSizeInBytes() + 4 * tab->getNoOfColumns();
4031
  batch= bytesperbatch/bytes;
4032 4033
  batch= batch == 0 ? 1 : batch;
  DBUG_PRINT("info", ("batch: %d, bytes: %d", batch, bytes));
4034
  m_bulk_insert_rows= batch;
4035 4036 4037 4038 4039 4040 4041 4042 4043

  DBUG_VOID_RETURN;
}

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

4046
  DBUG_ENTER("end_bulk_insert");
4047
  // Check if last inserts need to be flushed
4048
  if (m_bulk_insert_not_flushed)
4049
  {
4050
    NdbTransaction *trans= m_active_trans;
4051 4052
    // Send rows to NDB
    DBUG_PRINT("info", ("Sending inserts to NDB, "\
4053
                        "rows_inserted: %d  bulk_insert_rows: %d", 
4054
                        (int) m_rows_inserted, (int) m_bulk_insert_rows)); 
4055
    m_bulk_insert_not_flushed= FALSE;
4056 4057
    if (m_transaction_on)
    {
4058
      if (execute_no_commit(this, trans,FALSE) != 0)
4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072
      {
        no_uncommitted_rows_execute_failure();
        my_errno= error= ndb_err(trans);
      }
    }
    else
    {
      if (execute_commit(this, trans) != 0)
      {
        no_uncommitted_rows_execute_failure();
        my_errno= error= ndb_err(trans);
      }
      else
      {
4073
        IF_DBUG(int res=) trans->restart();
4074 4075
        DBUG_ASSERT(res == 0);
      }
4076
    }
4077 4078
  }

4079 4080
  m_rows_inserted= (ha_rows) 0;
  m_rows_to_insert= (ha_rows) 1;
4081
  DBUG_RETURN(error);
4082 4083
}

4084 4085 4086 4087

int ha_ndbcluster::extra_opt(enum ha_extra_function operation, ulong cache_size)
{
  DBUG_ENTER("extra_opt");
pekka@mysql.com's avatar
pekka@mysql.com committed
4088
  DBUG_PRINT("enter", ("cache_size: %lu", cache_size));
4089 4090 4091
  DBUG_RETURN(extra(operation));
}

4092 4093 4094 4095
static const char *ha_ndbcluster_exts[] = {
 ha_ndb_ext,
 NullS
};
4096

4097
const char** ha_ndbcluster::bas_ext() const
4098 4099 4100
{
  return ha_ndbcluster_exts;
}
4101 4102 4103 4104 4105 4106 4107 4108 4109

/*
  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()
{
4110
  DBUG_ENTER("ha_ndbcluster::scan_time()");
4111
  double res= rows2double(stats.records*1000);
4112
  DBUG_PRINT("exit", ("table: %s value: %f", 
4113
                      m_tabname, res));
4114
  DBUG_RETURN(res);
4115 4116
}

4117 4118 4119 4120 4121 4122 4123
/*
  Convert MySQL table locks into locks supported by Ndb Cluster.
  Note that MySQL Cluster does currently not support distributed
  table locks, so to be safe one should set cluster in Single
  User Mode, before relying on table locks when updating tables
  from several MySQL servers
*/
4124 4125 4126 4127 4128 4129 4130 4131

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) 
  {
4132

4133 4134 4135
    /* If we are not doing a LOCK TABLE, then allow multiple
       writers */
    
4136 4137 4138
    /* Since NDB does not currently have table locks
       this is treated as a ordinary lock */

4139
    if ((lock_type >= TL_WRITE_CONCURRENT_INSERT &&
4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
         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;
4155 4156

  DBUG_PRINT("exit", ("lock_type: %d", lock_type));
4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178
  
  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
4179
  for the statement, this will be stored in thd_ndb.stmt.
4180
  If not, we have to start a master transaction if there doesn't exist
4181
  one from before, this will be stored in thd_ndb.all
4182 4183 4184
 
  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  
4185
  If we are locking the table then:
4186
  - save the NdbDictionary::Table for easy access
4187 4188
  - save reference to table statistics
  - refresh list of the indexes for the table if needed (if altered)
4189 4190
 */

4191 4192 4193 4194
#ifdef HAVE_NDB_BINLOG
extern MASTER_INFO *active_mi;
static int ndbcluster_update_apply_status(THD *thd, int do_update)
{
4195 4196
  return 0;

4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
  Ndb *ndb= thd_ndb->ndb;
  NDBDICT *dict= ndb->getDictionary();
  const NDBTAB *ndbtab;
  NdbTransaction *trans= thd_ndb->all ? thd_ndb->all : thd_ndb->stmt;
  ndb->setDatabaseName(NDB_REP_DB);
  Ndb_table_guard ndbtab_g(dict, NDB_APPLY_TABLE);
  if (!(ndbtab= ndbtab_g.get_table()))
  {
    return -1;
  }
  NdbOperation *op= 0;
  int r= 0;
  r|= (op= trans->getNdbOperation(ndbtab)) == 0;
  DBUG_ASSERT(r == 0);
  if (do_update)
    r|= op->updateTuple();
  else
    r|= op->writeTuple();
  DBUG_ASSERT(r == 0);
  // server_id
4218
  r|= op->equal(0u, (Uint32)thd->server_id);
4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244
  DBUG_ASSERT(r == 0);
  if (!do_update)
  {
    // epoch
    r|= op->setValue(1u, (Uint64)0);
    DBUG_ASSERT(r == 0);
  }
  // log_name
  char tmp_buf[FN_REFLEN];
  ndb_pack_varchar(ndbtab->getColumn(2u), tmp_buf,
                   active_mi->rli.group_master_log_name,
                   strlen(active_mi->rli.group_master_log_name));
  r|= op->setValue(2u, tmp_buf);
  DBUG_ASSERT(r == 0);
  // start_pos
  r|= op->setValue(3u, (Uint64)active_mi->rli.group_master_log_pos);
  DBUG_ASSERT(r == 0);
  // end_pos
  r|= op->setValue(4u, (Uint64)active_mi->rli.group_master_log_pos + 
                   ((Uint64)active_mi->rli.future_event_relay_log_pos -
                    (Uint64)active_mi->rli.group_relay_log_pos));
  DBUG_ASSERT(r == 0);
  return 0;
}
#endif /* HAVE_NDB_BINLOG */

4245 4246 4247
int ha_ndbcluster::external_lock(THD *thd, int lock_type)
{
  int error=0;
4248
  NdbTransaction* trans= NULL;
4249
  DBUG_ENTER("external_lock");
4250

4251 4252 4253 4254
  /*
    Check that this handler instance has a connection
    set up to the Ndb object of thd
   */
4255
  if (check_ndb_connection(thd))
4256
    DBUG_RETURN(1);
4257

4258
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
4259
  Ndb *ndb= thd_ndb->ndb;
4260

4261
  DBUG_PRINT("enter", ("this: 0x%lx  thd: 0x%lx  thd_ndb: %lx  "
4262
                       "thd_ndb->lock_count: %d",
4263 4264
                       (long) this, (long) thd, (long) thd_ndb,
                       thd_ndb->lock_count));
4265

4266 4267
  if (lock_type != F_UNLCK)
  {
4268
    DBUG_PRINT("info", ("lock_type != F_UNLCK"));
4269 4270 4271 4272 4273 4274 4275 4276
    if (thd->lex->sql_command == SQLCOM_LOAD)
    {
      m_transaction_on= FALSE;
      /* Would be simpler if has_transactions() didn't always say "yes" */
      thd->options|= OPTION_STATUS_NO_TRANS_UPDATE;
      thd->no_trans_update= TRUE;
    }
    else if (!thd->transaction.on)
4277 4278 4279
      m_transaction_on= FALSE;
    else
      m_transaction_on= thd->variables.ndb_use_transactions;
4280
    if (!thd_ndb->lock_count++)
4281 4282
    {
      PRINT_OPTION_FLAGS(thd);
4283
      if (!(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))) 
4284 4285
      {
        // Autocommit transaction
4286
        DBUG_ASSERT(!thd_ndb->stmt);
4287 4288
        DBUG_PRINT("trans",("Starting transaction stmt"));      

4289
        trans= ndb->startTransaction();
4290
        if (trans == NULL)
4291
          ERR_RETURN(ndb->getNdbError());
4292
        thd_ndb->init_open_tables();
4293
        thd_ndb->stmt= trans;
4294
	thd_ndb->query_state&= NDB_QUERY_NORMAL;
4295
        thd_ndb->trans_options= 0;
4296
        trans_register_ha(thd, FALSE, ndbcluster_hton);
4297 4298 4299
      } 
      else 
      { 
4300
        if (!thd_ndb->all)
4301
        {
4302 4303 4304 4305
          // Not autocommit transaction
          // A "master" transaction ha not been started yet
          DBUG_PRINT("trans",("starting transaction, all"));
          
4306
          trans= ndb->startTransaction();
4307
          if (trans == NULL)
4308
            ERR_RETURN(ndb->getNdbError());
4309
          thd_ndb->init_open_tables();
4310
          thd_ndb->all= trans; 
4311
	  thd_ndb->query_state&= NDB_QUERY_NORMAL;
4312
          thd_ndb->trans_options= 0;
4313
          trans_register_ha(thd, TRUE, ndbcluster_hton);
4314 4315 4316 4317 4318 4319 4320 4321

          /*
            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))
4322
          {
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341
            //lockThisTable();
            DBUG_PRINT("info", ("Locking the table..." ));
          }

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

4342 4343 4344
    // store thread specific data first to set the right context
    m_force_send=          thd->variables.ndb_force_send;
    m_ha_not_exact_count= !thd->variables.ndb_use_exact_count;
4345 4346
    m_autoincrement_prefetch= 
      (ha_rows) thd->variables.ndb_autoincrement_prefetch_sz;
4347

4348
    m_active_trans= thd_ndb->all ? thd_ndb->all : thd_ndb->stmt;
4349
    DBUG_ASSERT(m_active_trans);
4350
    // Start of transaction
4351 4352
    m_rows_changed= 0;
    m_ops_pending= 0;
4353 4354 4355 4356
#ifdef HAVE_NDB_BINLOG
    if (m_share == ndb_apply_status_share && thd->slave_thread)
      thd_ndb->trans_options|= TNTO_INJECTED_APPLY_STATUS;
#endif
4357
    // TODO remove double pointers...
4358 4359
    m_thd_ndb_share= thd_ndb->get_open_table(thd, m_table);
    m_table_info= &m_thd_ndb_share->stat;
4360 4361
  }
  else
4362
  {
4363
    DBUG_PRINT("info", ("lock_type == F_UNLCK"));
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381

    if (ndb_cache_check_time && m_rows_changed)
    {
      DBUG_PRINT("info", ("Rows has changed and util thread is running"));
      if (thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
      {
        DBUG_PRINT("info", ("Add share to list of tables to be invalidated"));
        /* NOTE push_back allocates memory using transactions mem_root! */
        thd_ndb->changed_tables.push_back(m_share, &thd->transaction.mem_root);
      }

      pthread_mutex_lock(&m_share->mutex);
      DBUG_PRINT("info", ("Invalidating commit_count"));
      m_share->commit_count= 0;
      m_share->commit_count_lock++;
      pthread_mutex_unlock(&m_share->mutex);
    }

4382
    if (!--thd_ndb->lock_count)
4383 4384 4385 4386
    {
      DBUG_PRINT("trans", ("Last external_lock"));
      PRINT_OPTION_FLAGS(thd);

4387
      if (thd_ndb->stmt)
4388 4389 4390 4391 4392 4393 4394
      {
        /*
          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"));
4395
        ndb->closeTransaction(m_active_trans);
4396
        thd_ndb->stmt= NULL;
4397 4398
      }
    }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
4399
    m_table_info= NULL;
4400

4401 4402 4403 4404 4405 4406 4407 4408 4409
    /*
      This is the place to make sure this handler instance
      no longer are connected to the active transaction.

      And since the handler is no longer part of the transaction 
      it can't have open cursors, ops or blobs pending.
    */
    m_active_trans= NULL;    

4410 4411
    if (m_active_cursor)
      DBUG_PRINT("warning", ("m_active_cursor != NULL"));
4412 4413
    m_active_cursor= NULL;

4414 4415 4416 4417
    if (m_multi_cursor)
      DBUG_PRINT("warning", ("m_multi_cursor != NULL"));
    m_multi_cursor= NULL;
    
4418
    if (m_blobs_pending)
4419
      DBUG_PRINT("warning", ("blobs_pending != 0"));
4420
    m_blobs_pending= 0;
4421
    
4422
    if (m_ops_pending)
4423
      DBUG_PRINT("warning", ("ops_pending != 0L"));
4424
    m_ops_pending= 0;
4425
  }
4426
  thd->set_current_stmt_binlog_row_based_if_mixed();
4427 4428 4429
  DBUG_RETURN(error);
}

mskold@mysql.com's avatar
mskold@mysql.com committed
4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441
/*
  Unlock the last row read in an open scan.
  Rows are unlocked by default in ndb, but
  for SELECT FOR UPDATE and SELECT LOCK WIT SHARE MODE
  locks are kept if unlock_row() is not called.
*/

void ha_ndbcluster::unlock_row() 
{
  DBUG_ENTER("unlock_row");

  DBUG_PRINT("info", ("Unlocking row"));
4442
  m_lock_tuple= FALSE;
mskold@mysql.com's avatar
mskold@mysql.com committed
4443 4444 4445
  DBUG_VOID_RETURN;
}

4446
/*
4447 4448 4449 4450 4451
  Start a transaction for running a statement if one is not
  already running in a transaction. This will be the case in
  a BEGIN; COMMIT; block
  When using LOCK TABLE's external_lock will start a transaction
  since ndb does not currently does not support table locking
4452 4453
*/

serg@serg.mylan's avatar
serg@serg.mylan committed
4454
int ha_ndbcluster::start_stmt(THD *thd, thr_lock_type lock_type)
4455 4456 4457 4458 4459
{
  int error=0;
  DBUG_ENTER("start_stmt");
  PRINT_OPTION_FLAGS(thd);

4460
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
4461
  NdbTransaction *trans= (thd_ndb->stmt)?thd_ndb->stmt:thd_ndb->all;
4462
  if (!trans){
4463
    Ndb *ndb= thd_ndb->ndb;
4464
    DBUG_PRINT("trans",("Starting transaction stmt"));  
4465
    trans= ndb->startTransaction();
4466
    if (trans == NULL)
4467
      ERR_RETURN(ndb->getNdbError());
4468
    no_uncommitted_rows_reset(thd);
4469
    thd_ndb->stmt= trans;
4470
    thd_ndb->query_state&= NDB_QUERY_NORMAL;
4471
    trans_register_ha(thd, FALSE, ndbcluster_hton);
4472 4473
  }
  m_active_trans= trans;
4474
  // Start of statement
4475
  m_ops_pending= 0;    
4476 4477
  thd->set_current_stmt_binlog_row_based_if_mixed();

4478 4479 4480 4481 4482
  DBUG_RETURN(error);
}


/*
4483
  Commit a transaction started in NDB
4484 4485
 */

4486
static int ndbcluster_commit(handlerton *hton, THD *thd, bool all)
4487 4488
{
  int res= 0;
4489 4490 4491
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
  Ndb *ndb= thd_ndb->ndb;
  NdbTransaction *trans= all ? thd_ndb->all : thd_ndb->stmt;
4492 4493 4494

  DBUG_ENTER("ndbcluster_commit");
  DBUG_PRINT("transaction",("%s",
4495
                            trans == thd_ndb->stmt ?
4496
                            "stmt" : "all"));
4497 4498 4499
  DBUG_ASSERT(ndb);
  if (trans == NULL)
    DBUG_RETURN(0);
4500

4501 4502 4503 4504 4505
#ifdef HAVE_NDB_BINLOG
  if (thd->slave_thread)
    ndbcluster_update_apply_status(thd, thd_ndb->trans_options & TNTO_INJECTED_APPLY_STATUS);
#endif /* HAVE_NDB_BINLOG */

4506
  if (execute_commit(thd,trans) != 0)
4507 4508
  {
    const NdbError err= trans->getNdbError();
4509
    const NdbOperation *error_op= trans->getNdbErrorOperation();
4510
    ERR_PRINT(err);
4511
    res= ndb_to_mysql_error(&err);
4512
    if (res != -1)
4513
      ndbcluster_print_error(res, error_op);
4514
  }
4515
  ndb->closeTransaction(trans);
4516

4517
  if (all)
4518 4519 4520
    thd_ndb->all= NULL;
  else
    thd_ndb->stmt= NULL;
4521 4522 4523 4524 4525 4526 4527

  /* Clear commit_count for tables changed by transaction */
  NDB_SHARE* share;
  List_iterator_fast<NDB_SHARE> it(thd_ndb->changed_tables);
  while ((share= it++))
  {
    pthread_mutex_lock(&share->mutex);
4528 4529
    DBUG_PRINT("info", ("Invalidate commit_count for %s, share->commit_count: %lu",
                        share->table_name, (ulong) share->commit_count));
4530 4531 4532 4533 4534 4535
    share->commit_count= 0;
    share->commit_count_lock++;
    pthread_mutex_unlock(&share->mutex);
  }
  thd_ndb->changed_tables.empty();

4536 4537 4538 4539 4540 4541 4542 4543
  DBUG_RETURN(res);
}


/*
  Rollback a transaction started in NDB
 */

4544
static int ndbcluster_rollback(handlerton *hton, THD *thd, bool all)
4545 4546
{
  int res= 0;
4547 4548 4549
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
  Ndb *ndb= thd_ndb->ndb;
  NdbTransaction *trans= all ? thd_ndb->all : thd_ndb->stmt;
4550 4551 4552

  DBUG_ENTER("ndbcluster_rollback");
  DBUG_PRINT("transaction",("%s",
4553
                            trans == thd_ndb->stmt ? 
4554 4555 4556
                            "stmt" : "all"));
  DBUG_ASSERT(ndb && trans);

4557
  if (trans->execute(NdbTransaction::Rollback) != 0)
4558 4559
  {
    const NdbError err= trans->getNdbError();
4560
    const NdbOperation *error_op= trans->getNdbErrorOperation();
4561 4562
    ERR_PRINT(err);     
    res= ndb_to_mysql_error(&err);
4563 4564
    if (res != -1) 
      ndbcluster_print_error(res, error_op);
4565 4566
  }
  ndb->closeTransaction(trans);
4567

4568
  if (all)
4569 4570 4571 4572
    thd_ndb->all= NULL;
  else
    thd_ndb->stmt= NULL;

4573 4574 4575
  /* Clear list of tables changed by transaction */
  thd_ndb->changed_tables.empty();

4576
  DBUG_RETURN(res);
4577 4578 4579 4580
}


/*
pekka@mysql.com's avatar
pekka@mysql.com committed
4581 4582 4583
  Define NDB column based on Field.
  Returns 0 or mysql error code.
  Not member of ha_ndbcluster because NDBCOL cannot be declared.
pekka@mysql.com's avatar
pekka@mysql.com committed
4584 4585 4586

  MySQL text types with character set "binary" are mapped to true
  NDB binary types without a character set.  This may change.
4587 4588
 */

pekka@mysql.com's avatar
pekka@mysql.com committed
4589 4590 4591
static int create_ndb_column(NDBCOL &col,
                             Field *field,
                             HA_CREATE_INFO *info)
4592
{
pekka@mysql.com's avatar
pekka@mysql.com committed
4593
  // Set name
4594 4595 4596 4597
  if (col.setName(field->field_name))
  {
    return (my_errno= errno);
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
4598 4599
  // Get char set
  CHARSET_INFO *cs= field->charset();
pekka@mysql.com's avatar
pekka@mysql.com committed
4600 4601 4602 4603
  // Set type and sizes
  const enum enum_field_types mysql_type= field->real_type();
  switch (mysql_type) {
  // Numeric types
4604
  case MYSQL_TYPE_TINY:        
pekka@mysql.com's avatar
pekka@mysql.com committed
4605 4606 4607 4608 4609 4610
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Tinyunsigned);
    else
      col.setType(NDBCOL::Tinyint);
    col.setLength(1);
    break;
4611
  case MYSQL_TYPE_SHORT:
pekka@mysql.com's avatar
pekka@mysql.com committed
4612 4613 4614 4615 4616 4617
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Smallunsigned);
    else
      col.setType(NDBCOL::Smallint);
    col.setLength(1);
    break;
4618
  case MYSQL_TYPE_LONG:
pekka@mysql.com's avatar
pekka@mysql.com committed
4619 4620 4621 4622 4623 4624
    if (field->flags & UNSIGNED_FLAG)
      col.setType(NDBCOL::Unsigned);
    else
      col.setType(NDBCOL::Int);
    col.setLength(1);
    break;
4625
  case MYSQL_TYPE_INT24:       
pekka@mysql.com's avatar
pekka@mysql.com committed
4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637
    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);
4638 4639
    break;
  case MYSQL_TYPE_FLOAT:
pekka@mysql.com's avatar
pekka@mysql.com committed
4640 4641 4642
    col.setType(NDBCOL::Float);
    col.setLength(1);
    break;
4643
  case MYSQL_TYPE_DOUBLE:
pekka@mysql.com's avatar
pekka@mysql.com committed
4644 4645 4646
    col.setType(NDBCOL::Double);
    col.setLength(1);
    break;
4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666
  case MYSQL_TYPE_DECIMAL:    
    {
      Field_decimal *f= (Field_decimal*)field;
      uint precision= f->pack_length();
      uint scale= f->decimals();
      if (field->flags & UNSIGNED_FLAG)
      {
        col.setType(NDBCOL::Olddecimalunsigned);
        precision-= (scale > 0);
      }
      else
      {
        col.setType(NDBCOL::Olddecimal);
        precision-= 1 + (scale > 0);
      }
      col.setPrecision(precision);
      col.setScale(scale);
      col.setLength(1);
    }
    break;
4667 4668 4669
  case MYSQL_TYPE_NEWDECIMAL:    
    {
      Field_new_decimal *f= (Field_new_decimal*)field;
4670
      uint precision= f->precision;
4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684
      uint scale= f->decimals();
      if (field->flags & UNSIGNED_FLAG)
      {
        col.setType(NDBCOL::Decimalunsigned);
      }
      else
      {
        col.setType(NDBCOL::Decimal);
      }
      col.setPrecision(precision);
      col.setScale(scale);
      col.setLength(1);
    }
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
4685 4686 4687 4688 4689
  // Date types
  case MYSQL_TYPE_DATETIME:    
    col.setType(NDBCOL::Datetime);
    col.setLength(1);
    break;
4690 4691 4692 4693
  case MYSQL_TYPE_DATE: // ?
    col.setType(NDBCOL::Char);
    col.setLength(field->pack_length());
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
4694
  case MYSQL_TYPE_NEWDATE:
4695 4696 4697
    col.setType(NDBCOL::Date);
    col.setLength(1);
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
4698
  case MYSQL_TYPE_TIME:        
4699 4700 4701
    col.setType(NDBCOL::Time);
    col.setLength(1);
    break;
4702 4703 4704 4705 4706 4707 4708
  case MYSQL_TYPE_YEAR:
    col.setType(NDBCOL::Year);
    col.setLength(1);
    break;
  case MYSQL_TYPE_TIMESTAMP:
    col.setType(NDBCOL::Timestamp);
    col.setLength(1);
pekka@mysql.com's avatar
pekka@mysql.com committed
4709 4710 4711
    break;
  // Char types
  case MYSQL_TYPE_STRING:      
4712
    if (field->pack_length() == 0)
4713 4714 4715 4716
    {
      col.setType(NDBCOL::Bit);
      col.setLength(1);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4717
    else if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
4718
    {
pekka@mysql.com's avatar
pekka@mysql.com committed
4719
      col.setType(NDBCOL::Binary);
4720
      col.setLength(field->pack_length());
pekka@mysql.com's avatar
pekka@mysql.com committed
4721
    }
4722
    else
4723 4724 4725
    {
      col.setType(NDBCOL::Char);
      col.setCharset(cs);
4726
      col.setLength(field->pack_length());
4727
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4728
    break;
pekka@mysql.com's avatar
pekka@mysql.com committed
4729 4730 4731 4732 4733 4734
  case MYSQL_TYPE_VAR_STRING: // ?
  case MYSQL_TYPE_VARCHAR:
    {
      Field_varstring* f= (Field_varstring*)field;
      if (f->length_bytes == 1)
      {
pekka@mysql.com's avatar
pekka@mysql.com committed
4735
        if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
pekka@mysql.com's avatar
pekka@mysql.com committed
4736 4737 4738 4739 4740 4741 4742 4743
          col.setType(NDBCOL::Varbinary);
        else {
          col.setType(NDBCOL::Varchar);
          col.setCharset(cs);
        }
      }
      else if (f->length_bytes == 2)
      {
pekka@mysql.com's avatar
pekka@mysql.com committed
4744
        if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
pekka@mysql.com's avatar
pekka@mysql.com committed
4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755
          col.setType(NDBCOL::Longvarbinary);
        else {
          col.setType(NDBCOL::Longvarchar);
          col.setCharset(cs);
        }
      }
      else
      {
        return HA_ERR_UNSUPPORTED;
      }
      col.setLength(field->field_length);
pekka@mysql.com's avatar
pekka@mysql.com committed
4756
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4757 4758 4759 4760
    break;
  // Blob types (all come in as MYSQL_TYPE_BLOB)
  mysql_type_tiny_blob:
  case MYSQL_TYPE_TINY_BLOB:
pekka@mysql.com's avatar
pekka@mysql.com committed
4761
    if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
pekka@mysql.com's avatar
pekka@mysql.com committed
4762
      col.setType(NDBCOL::Blob);
pekka@mysql.com's avatar
pekka@mysql.com committed
4763
    else {
pekka@mysql.com's avatar
pekka@mysql.com committed
4764
      col.setType(NDBCOL::Text);
pekka@mysql.com's avatar
pekka@mysql.com committed
4765 4766
      col.setCharset(cs);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4767 4768 4769 4770 4771
    col.setInlineSize(256);
    // No parts
    col.setPartSize(0);
    col.setStripeSize(0);
    break;
4772
  //mysql_type_blob:
4773
  case MYSQL_TYPE_GEOMETRY:
pekka@mysql.com's avatar
pekka@mysql.com committed
4774
  case MYSQL_TYPE_BLOB:    
pekka@mysql.com's avatar
pekka@mysql.com committed
4775
    if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
pekka@mysql.com's avatar
pekka@mysql.com committed
4776
      col.setType(NDBCOL::Blob);
pekka@mysql.com's avatar
pekka@mysql.com committed
4777
    else {
pekka@mysql.com's avatar
pekka@mysql.com committed
4778
      col.setType(NDBCOL::Text);
pekka@mysql.com's avatar
pekka@mysql.com committed
4779 4780
      col.setCharset(cs);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4781
    {
4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
      Field_blob *field_blob= (Field_blob *)field;
      /*
       * max_data_length is 2^8-1, 2^16-1, 2^24-1 for tiny, blob, medium.
       * Tinyblob gets no blob parts.  The other cases are just a crude
       * way to control part size and striping.
       *
       * In mysql blob(256) is promoted to blob(65535) so it does not
       * in fact fit "inline" in NDB.
       */
      if (field_blob->max_data_length() < (1 << 8))
        goto mysql_type_tiny_blob;
      else if (field_blob->max_data_length() < (1 << 16))
      {
        col.setInlineSize(256);
        col.setPartSize(2000);
        col.setStripeSize(16);
      }
      else if (field_blob->max_data_length() < (1 << 24))
        goto mysql_type_medium_blob;
      else
        goto mysql_type_long_blob;
pekka@mysql.com's avatar
pekka@mysql.com committed
4803 4804 4805 4806
    }
    break;
  mysql_type_medium_blob:
  case MYSQL_TYPE_MEDIUM_BLOB:   
pekka@mysql.com's avatar
pekka@mysql.com committed
4807
    if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
pekka@mysql.com's avatar
pekka@mysql.com committed
4808
      col.setType(NDBCOL::Blob);
pekka@mysql.com's avatar
pekka@mysql.com committed
4809
    else {
pekka@mysql.com's avatar
pekka@mysql.com committed
4810
      col.setType(NDBCOL::Text);
pekka@mysql.com's avatar
pekka@mysql.com committed
4811 4812
      col.setCharset(cs);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4813 4814 4815 4816 4817 4818
    col.setInlineSize(256);
    col.setPartSize(4000);
    col.setStripeSize(8);
    break;
  mysql_type_long_blob:
  case MYSQL_TYPE_LONG_BLOB:  
pekka@mysql.com's avatar
pekka@mysql.com committed
4819
    if ((field->flags & BINARY_FLAG) && cs == &my_charset_bin)
pekka@mysql.com's avatar
pekka@mysql.com committed
4820
      col.setType(NDBCOL::Blob);
pekka@mysql.com's avatar
pekka@mysql.com committed
4821
    else {
pekka@mysql.com's avatar
pekka@mysql.com committed
4822
      col.setType(NDBCOL::Text);
pekka@mysql.com's avatar
pekka@mysql.com committed
4823 4824
      col.setCharset(cs);
    }
pekka@mysql.com's avatar
pekka@mysql.com committed
4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
    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;
4838 4839
  case MYSQL_TYPE_BIT:
  {
4840
    int no_of_bits= field->field_length;
4841 4842 4843 4844 4845 4846 4847
    col.setType(NDBCOL::Bit);
    if (!no_of_bits)
      col.setLength(1);
      else
        col.setLength(no_of_bits);
    break;
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
4848 4849 4850 4851 4852
  case MYSQL_TYPE_NULL:        
    goto mysql_type_unsupported;
  mysql_type_unsupported:
  default:
    return HA_ERR_UNSUPPORTED;
4853
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
4854 4855 4856 4857 4858 4859
  // Set nullable and pk
  col.setNullable(field->maybe_null());
  col.setPrimaryKey(field->flags & PRI_KEY_FLAG);
  // Set autoincrement
  if (field->flags & AUTO_INCREMENT_FLAG) 
  {
4860
#ifndef DBUG_OFF
4861
    char buff[22];
4862
#endif
pekka@mysql.com's avatar
pekka@mysql.com committed
4863 4864
    col.setAutoIncrement(TRUE);
    ulonglong value= info->auto_increment_value ?
4865
      info->auto_increment_value : (ulonglong) 1;
4866
    DBUG_PRINT("info", ("Autoincrement key, initial: %s", llstr(value, buff)));
pekka@mysql.com's avatar
pekka@mysql.com committed
4867
    col.setAutoIncrementInitialValue(value);
4868
  }
pekka@mysql.com's avatar
pekka@mysql.com committed
4869
  else
4870
    col.setAutoIncrement(FALSE);
pekka@mysql.com's avatar
pekka@mysql.com committed
4871
  return 0;
4872 4873
}

4874 4875 4876 4877
/*
  Create a table in NDB Cluster
*/

4878
int ha_ndbcluster::create(const char *name, 
4879
                          TABLE *form, 
4880
                          HA_CREATE_INFO *create_info)
4881
{
4882
  THD *thd= current_thd;
4883 4884
  NDBTAB tab;
  NDBCOL col;
joreland@mysql.com's avatar
joreland@mysql.com committed
4885
  uint pack_length, length, i, pk_length= 0;
4886
  const void *data= NULL, *pack_data= NULL;
4887
  bool create_from_engine= (create_info->table_options & HA_OPTION_CREATE_FROM_ENGINE);
4888
  bool is_truncate= (thd->lex->sql_command == SQLCOM_TRUNCATE);
4889
  char tablespace[FN_LEN];
4890
  NdbDictionary::Table::SingleUserMode single_user_mode= NdbDictionary::Table::SingleUserModeLocked;
4891

pekka@mysql.com's avatar
pekka@mysql.com committed
4892
  DBUG_ENTER("ha_ndbcluster::create");
4893
  DBUG_PRINT("enter", ("name: %s", name));
4894

4895 4896 4897
  DBUG_ASSERT(*fn_rext((char*)name) == 0);
  set_dbname(name);
  set_tabname(name);
4898

4899 4900 4901 4902 4903 4904
  if ((my_errno= check_ndb_connection()))
    DBUG_RETURN(my_errno);
  
  Ndb *ndb= get_ndb();
  NDBDICT *dict= ndb->getDictionary();

mskold@mysql.com's avatar
mskold@mysql.com committed
4905 4906
  if (is_truncate)
  {
4907 4908 4909 4910 4911
    {
      Ndb_table_guard ndbtab_g(dict, m_tabname);
      if (!(m_table= ndbtab_g.get_table()))
	ERR_RETURN(dict->getNdbError());
      if ((get_tablespace_name(thd, tablespace, FN_LEN)))
4912
	create_info->tablespace= tablespace;    
4913 4914
      m_table= NULL;
    }
mskold@mysql.com's avatar
mskold@mysql.com committed
4915 4916 4917 4918
    DBUG_PRINT("info", ("Dropping and re-creating table for TRUNCATE"));
    if ((my_errno= delete_table(name)))
      DBUG_RETURN(my_errno);
  }
4919
  table= form;
4920 4921 4922
  if (create_from_engine)
  {
    /*
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
4923
      Table already exists in NDB and frm file has been created by 
4924 4925 4926
      caller.
      Do Ndb specific stuff, such as create a .ndb file
    */
4927
    if ((my_errno= write_ndb_file(name)))
4928
      DBUG_RETURN(my_errno);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
4929
#ifdef HAVE_NDB_BINLOG
4930
    ndbcluster_create_binlog_setup(get_ndb(), name, strlen(name),
4931
                                   m_dbname, m_tabname, FALSE);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
4932
#endif /* HAVE_NDB_BINLOG */
4933 4934
    DBUG_RETURN(my_errno);
  }
4935

4936 4937 4938 4939 4940 4941
#ifdef HAVE_NDB_BINLOG
  /*
    Don't allow table creation unless
    schema distribution table is setup
    ( unless it is a creation of the schema dist table itself )
  */
4942
  if (!ndb_schema_share)
4943
  {
4944 4945 4946 4947 4948 4949 4950
    if (!(strcmp(m_dbname, NDB_REP_DB) == 0 &&
          strcmp(m_tabname, NDB_SCHEMA_TABLE) == 0))
    {
      DBUG_PRINT("info", ("Schema distribution table not setup"));
      DBUG_RETURN(HA_ERR_NO_CONNECTION);
    }
    single_user_mode = NdbDictionary::Table::SingleUserModeReadWrite;
4951 4952 4953
  }
#endif /* HAVE_NDB_BINLOG */

4954
  DBUG_PRINT("table", ("name: %s", m_tabname));  
4955
  if (tab.setName(m_tabname))
4956 4957 4958
  {
    DBUG_RETURN(my_errno= errno);
  }
4959
  tab.setLogging(!(create_info->options & HA_LEX_CREATE_TMP_TABLE));    
4960 4961
  tab.setSingleUserMode(single_user_mode);

4962 4963 4964 4965
  // Save frm data for this table
  if (readfrm(name, &data, &length))
    DBUG_RETURN(1);
  if (packfrm(data, length, &pack_data, &pack_length))
4966 4967
  {
    my_free((char*)data, MYF(0));
4968
    DBUG_RETURN(2);
4969
  }
4970
  DBUG_PRINT("info", ("setFrm data: 0x%lx  len: %d", (long) pack_data, pack_length));
4971 4972 4973 4974
  tab.setFrm(pack_data, pack_length);      
  my_free((char*)data, MYF(0));
  my_free((char*)pack_data, MYF(0));
  
4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
  if (create_info->storage_media == HA_SM_DISK)
  { 
    if (create_info->tablespace)
      tab.setTablespaceName(create_info->tablespace);
    else
      tab.setTablespaceName("DEFAULT-TS");
  }
  else if (create_info->tablespace)
  {
    if (create_info->storage_media == HA_SM_MEMORY)
    {
      push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
			  ER_ILLEGAL_HA_CREATE_OPTION,
			  ER(ER_ILLEGAL_HA_CREATE_OPTION),
			  ndbcluster_hton_name,
			  "TABLESPACE currently only supported for "
			  "STORAGE DISK"); 
      DBUG_RETURN(HA_ERR_UNSUPPORTED);
    }
    tab.setTablespaceName(create_info->tablespace);
    create_info->storage_media = HA_SM_DISK;  //if use tablespace, that also means store on disk
  }

4998
  for (i= 0; i < form->s->fields; i++) 
4999 5000 5001 5002
  {
    Field *field= form->field[i];
    DBUG_PRINT("info", ("name: %s, type: %u, pack_length: %d", 
                        field->field_name, field->real_type(),
5003
                        field->pack_length()));
5004
    if ((my_errno= create_ndb_column(col, field, create_info)))
pekka@mysql.com's avatar
pekka@mysql.com committed
5005
      DBUG_RETURN(my_errno);
5006
 
5007 5008
    if (create_info->storage_media == HA_SM_DISK ||
        create_info->tablespace)
5009 5010 5011 5012
      col.setStorageType(NdbDictionary::Column::StorageTypeDisk);
    else
      col.setStorageType(NdbDictionary::Column::StorageTypeMemory);

5013 5014 5015 5016
    if (tab.addColumn(col))
    {
      DBUG_RETURN(my_errno= errno);
    }
5017
    if (col.getPrimaryKey())
joreland@mysql.com's avatar
joreland@mysql.com committed
5018
      pk_length += (field->pack_length() + 3) / 4;
5019
  }
5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030

  KEY* key_info;
  for (i= 0, key_info= form->key_info; i < form->s->keys; i++, key_info++)
  {
    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++)
      tab.getColumn(key_part->fieldnr-1)->setStorageType(
                             NdbDictionary::Column::StorageTypeMemory);
  }

5031
  // No primary key, create shadow key as 64 bit, auto increment  
5032
  if (form->s->primary_key == MAX_KEY) 
5033 5034
  {
    DBUG_PRINT("info", ("Generating shadow key"));
5035 5036 5037 5038
    if (col.setName("$PK"))
    {
      DBUG_RETURN(my_errno= errno);
    }
5039 5040
    col.setType(NdbDictionary::Column::Bigunsigned);
    col.setLength(1);
5041
    col.setNullable(FALSE);
5042 5043
    col.setPrimaryKey(TRUE);
    col.setAutoIncrement(TRUE);
5044 5045 5046 5047
    if (tab.addColumn(col))
    {
      DBUG_RETURN(my_errno= errno);
    }
joreland@mysql.com's avatar
joreland@mysql.com committed
5048 5049
    pk_length += 2;
  }
5050
 
joreland@mysql.com's avatar
joreland@mysql.com committed
5051
  // Make sure that blob tables don't have to big part size
5052
  for (i= 0; i < form->s->fields; i++) 
joreland@mysql.com's avatar
joreland@mysql.com committed
5053 5054 5055 5056 5057 5058 5059
  {
    /**
     * The extra +7 concists
     * 2 - words from pk in blob table
     * 5 - from extra words added by tup/dict??
     */
    switch (form->field[i]->real_type()) {
5060
    case MYSQL_TYPE_GEOMETRY:
joreland@mysql.com's avatar
joreland@mysql.com committed
5061 5062 5063 5064
    case MYSQL_TYPE_BLOB:    
    case MYSQL_TYPE_MEDIUM_BLOB:   
    case MYSQL_TYPE_LONG_BLOB: 
    {
5065 5066
      NdbDictionary::Column * column= tab.getColumn(i);
      int size= pk_length + (column->getPartSize()+3)/4 + 7;
5067
      if (size > NDB_MAX_TUPLE_SIZE_IN_WORDS && 
5068
         (pk_length+7) < NDB_MAX_TUPLE_SIZE_IN_WORDS)
joreland@mysql.com's avatar
joreland@mysql.com committed
5069
      {
5070
        size= NDB_MAX_TUPLE_SIZE_IN_WORDS - pk_length - 7;
5071
        column->setPartSize(4*size);
joreland@mysql.com's avatar
joreland@mysql.com committed
5072 5073 5074 5075 5076 5077 5078 5079 5080 5081
      }
      /**
       * If size > NDB_MAX and pk_length+7 >= NDB_MAX
       *   then the table can't be created anyway, so skip
       *   changing part size, and have error later
       */ 
    }
    default:
      break;
    }
5082
  }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
5083

5084
  // Check partition info
5085
  partition_info *part_info= form->part_info;
5086
  if ((my_errno= set_up_partition_info(part_info, form, (void*)&tab)))
5087
  {
5088
    DBUG_RETURN(my_errno);
5089 5090
  }

5091
  // Create the table in NDB     
5092
  if (dict->createTable(tab) != 0) 
5093 5094 5095 5096 5097 5098
  {
    const NdbError err= dict->getNdbError();
    ERR_PRINT(err);
    my_errno= ndb_to_mysql_error(&err);
    DBUG_RETURN(my_errno);
  }
5099 5100 5101 5102 5103 5104

  Ndb_table_guard ndbtab_g(dict, m_tabname);
  // temporary set m_table during create
  // reset at return
  m_table= ndbtab_g.get_table();
  // TODO check also that we have the same frm...
5105 5106 5107 5108 5109 5110 5111 5112 5113
  if (!m_table)
  {
    /* purecov: begin deadcode */
    const NdbError err= dict->getNdbError();
    ERR_PRINT(err);
    my_errno= ndb_to_mysql_error(&err);
    DBUG_RETURN(my_errno);
    /* purecov: end */
  }
5114

5115 5116
  DBUG_PRINT("info", ("Table %s/%s created successfully", 
                      m_dbname, m_tabname));
5117

5118
  // Create secondary indexes
5119
  my_errno= create_indexes(ndb, form);
5120

5121
  if (!my_errno)
5122
    my_errno= write_ndb_file(name);
5123 5124 5125 5126 5127 5128
  else
  {
    /*
      Failed to create an index,
      drop the table (and all it's indexes)
    */
5129
    while (dict->dropTableGlobal(*m_table))
5130
    {
5131 5132 5133 5134 5135 5136 5137 5138 5139
      switch (dict->getNdbError().status)
      {
        case NdbError::TemporaryError:
          if (!thd->killed) 
            continue; // retry indefinitly
          break;
        default:
          break;
      }
5140
      break;
5141
    }
5142 5143
    m_table = 0;
    DBUG_RETURN(my_errno);
5144
  }
5145

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5146 5147 5148 5149 5150 5151 5152 5153 5154
#ifdef HAVE_NDB_BINLOG
  if (!my_errno)
  {
    NDB_SHARE *share= 0;
    pthread_mutex_lock(&ndbcluster_mutex);
    /*
      First make sure we get a "fresh" share here, not an old trailing one...
    */
    {
5155
      uint length= (uint) strlen(name);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5156
      if ((share= (NDB_SHARE*) hash_search(&ndbcluster_open_tables,
5157
                                           (byte*) name, length)))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5158 5159 5160 5161 5162
        handle_trailing_share(share);
    }
    /*
      get a new share
    */
5163

5164
    /* ndb_share reference create */
5165
    if (!(share= get_share(name, form, TRUE, TRUE)))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5166
    {
5167
      sql_print_error("NDB: allocating table share for %s failed", name);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5168 5169
      /* my_errno is set */
    }
5170 5171 5172 5173 5174
    else
    {
      DBUG_PRINT("NDB_SHARE", ("%s binlog create  use_count: %u",
                               share->key, share->use_count));
    }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5175 5176 5177 5178 5179 5180
    pthread_mutex_unlock(&ndbcluster_mutex);

    while (!IS_TMP_PREFIX(m_tabname))
    {
      String event_name(INJECTOR_EVENT_LEN);
      ndb_rep_event_name(&event_name,m_dbname,m_tabname);
5181 5182
      int do_event_op= ndb_binlog_running;

5183
      if (!ndb_schema_share &&
5184 5185 5186
          strcmp(share->db, NDB_REP_DB) == 0 &&
          strcmp(share->table_name, NDB_SCHEMA_TABLE) == 0)
        do_event_op= 1;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5187 5188 5189 5190 5191

      /*
        Always create an event for the table, as other mysql servers
        expect it to be there.
      */
5192
      if (!ndbcluster_create_event(ndb, m_table, event_name.c_ptr(), share,
5193
                                   share && do_event_op ? 2 : 1/* push warning */))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5194
      {
5195 5196 5197
        if (ndb_extra_logging)
          sql_print_information("NDB Binlog: CREATE TABLE Event: %s",
                                event_name.c_ptr());
5198
        if (share && 
5199
            ndbcluster_create_event_ops(share, m_table, event_name.c_ptr()))
5200 5201 5202 5203 5204
        {
          sql_print_error("NDB Binlog: FAILED CREATE TABLE event operations."
                          " Event: %s", name);
          /* a warning has been issued to the client */
        }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5205
      }
5206 5207 5208 5209
      /*
        warning has been issued if ndbcluster_create_event failed
        and (share && do_event_op)
      */
5210
      if (share && !do_event_op)
5211
        share->flags|= NSF_NO_BINLOG;
5212 5213
      ndbcluster_log_schema_op(thd, share,
                               thd->query, thd->query_length,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5214
                               share->db, share->table_name,
5215 5216
                               m_table->getObjectId(),
                               m_table->getObjectVersion(),
mskold@mysql.com's avatar
mskold@mysql.com committed
5217 5218 5219
                               (is_truncate) ?
			       SOT_TRUNCATE_TABLE : SOT_CREATE_TABLE, 
			       0, 0, 1);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5220 5221 5222 5223 5224
      break;
    }
  }
#endif /* HAVE_NDB_BINLOG */

5225
  m_table= 0;
5226 5227 5228
  DBUG_RETURN(my_errno);
}

5229 5230
int ha_ndbcluster::create_handler_files(const char *file,
                                        const char *old_name,
5231
                                        int action_flag,
5232
                                        HA_CREATE_INFO *create_info)
5233 5234 5235
{ 
  Ndb* ndb;
  const NDBTAB *tab;
5236
  const void *data= NULL, *pack_data= NULL;
5237 5238 5239 5240 5241
  uint length, pack_length;
  int error= 0;

  DBUG_ENTER("create_handler_files");

5242
  if (action_flag != CHF_INDEX_FLAG)
5243 5244 5245
  {
    DBUG_RETURN(FALSE);
  }
5246
  DBUG_PRINT("enter", ("file: %s", file));
5247 5248 5249 5250
  if (!(ndb= get_ndb()))
    DBUG_RETURN(HA_ERR_NO_CONNECTION);

  NDBDICT *dict= ndb->getDictionary();
5251
  if (!create_info->frm_only)
5252
    DBUG_RETURN(0); // Must be a create, ignore since frm is saved in create
5253 5254 5255 5256

  // TODO handle this
  DBUG_ASSERT(m_table != 0);

5257 5258
  set_dbname(file);
  set_tabname(file);
5259
  Ndb_table_guard ndbtab_g(dict, m_tabname);
5260
  DBUG_PRINT("info", ("m_dbname: %s, m_tabname: %s", m_dbname, m_tabname));
5261
  if (!(tab= ndbtab_g.get_table()))
5262 5263
    DBUG_RETURN(0); // Unkown table, must be temporary table

5264
  DBUG_ASSERT(get_ndb_share_state(m_share) == NSS_ALTERED);
5265
  if (readfrm(file, &data, &length) ||
5266 5267 5268 5269 5270
      packfrm(data, length, &pack_data, &pack_length))
  {
    DBUG_PRINT("info", ("Missing frm for %s", m_tabname));
    my_free((char*)data, MYF(MY_ALLOW_ZERO_PTR));
    my_free((char*)pack_data, MYF(MY_ALLOW_ZERO_PTR));
5271
    error= 1;
5272
  }
5273 5274
  else
  {
5275 5276
    DBUG_PRINT("info", ("Table %s has changed, altering frm in ndb", 
                        m_tabname));
5277 5278 5279 5280 5281 5282
    NdbDictionary::Table new_tab= *tab;
    new_tab.setFrm(pack_data, pack_length);
    if (dict->alterTableGlobal(*tab, new_tab))
    {
      error= ndb_to_mysql_error(&dict->getNdbError());
    }
5283 5284
    my_free((char*)data, MYF(MY_ALLOW_ZERO_PTR));
    my_free((char*)pack_data, MYF(MY_ALLOW_ZERO_PTR));
5285
  }
5286
  
5287
  set_ndb_share_state(m_share, NSS_INITIAL);
5288 5289 5290
  /* ndb_share reference schema(?) free */
  DBUG_PRINT("NDB_SHARE", ("%s binlog schema(?) free  use_count: %u",
                           m_share->key, m_share->use_count));
5291
  free_share(&m_share); // Decrease ref_count
5292 5293 5294 5295

  DBUG_RETURN(error);
}

5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323
int ha_ndbcluster::create_index(const char *name, KEY *key_info, 
                                NDB_INDEX_TYPE idx_type, uint idx_no)
{
  int error= 0;
  char unique_name[FN_LEN];
  static const char* unique_suffix= "$unique";
  DBUG_ENTER("ha_ndbcluster::create_ordered_index");
  DBUG_PRINT("info", ("Creating index %u: %s", idx_no, name));  

  if (idx_type == UNIQUE_ORDERED_INDEX || idx_type == UNIQUE_INDEX)
  {
    strxnmov(unique_name, FN_LEN, name, unique_suffix, NullS);
    DBUG_PRINT("info", ("Created unique index name \'%s\' for index %d",
                        unique_name, idx_no));
  }
    
  switch (idx_type){
  case PRIMARY_KEY_INDEX:
    // Do nothing, already created
    break;
  case PRIMARY_KEY_ORDERED_INDEX:
    error= create_ordered_index(name, key_info);
    break;
  case UNIQUE_ORDERED_INDEX:
    if (!(error= create_ordered_index(name, key_info)))
      error= create_unique_index(unique_name, key_info);
    break;
  case UNIQUE_INDEX:
5324 5325 5326 5327 5328 5329 5330
    if (check_index_fields_not_null(key_info))
    {
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			  ER_NULL_COLUMN_IN_INDEX,
			  "Ndb does not support unique index on NULL valued attributes, index access with NULL value will become full table scan");
    }
    error= create_unique_index(unique_name, key_info);
5331 5332
    break;
  case ORDERED_INDEX:
5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343
    if (key_info->algorithm == HA_KEY_ALG_HASH)
    {
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
			  ER_ILLEGAL_HA_CREATE_OPTION,
			  ER(ER_ILLEGAL_HA_CREATE_OPTION),
			  ndbcluster_hton_name,
			  "Ndb does not support non-unique "
			  "hash based indexes");
      error= HA_ERR_UNSUPPORTED;
      break;
    }
5344 5345 5346 5347 5348 5349 5350 5351 5352
    error= create_ordered_index(name, key_info);
    break;
  default:
    DBUG_ASSERT(FALSE);
    break;
  }
  
  DBUG_RETURN(error);
}
5353

5354
int ha_ndbcluster::create_ordered_index(const char *name, 
5355
                                        KEY *key_info)
5356
{
5357
  DBUG_ENTER("ha_ndbcluster::create_ordered_index");
5358
  DBUG_RETURN(create_ndb_index(name, key_info, FALSE));
5359 5360 5361
}

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

5365
  DBUG_ENTER("ha_ndbcluster::create_unique_index");
5366
  DBUG_RETURN(create_ndb_index(name, key_info, TRUE));
5367 5368 5369
}


5370 5371 5372 5373
/*
  Create an index in NDB Cluster
 */

5374 5375 5376
int ha_ndbcluster::create_ndb_index(const char *name, 
                                     KEY *key_info,
                                     bool unique)
5377
{
5378 5379
  Ndb *ndb= get_ndb();
  NdbDictionary::Dictionary *dict= ndb->getDictionary();
5380 5381 5382
  KEY_PART_INFO *key_part= key_info->key_part;
  KEY_PART_INFO *end= key_part + key_info->key_parts;
  
5383
  DBUG_ENTER("ha_ndbcluster::create_index");
5384
  DBUG_PRINT("enter", ("name: %s ", name));
5385

5386
  NdbDictionary::Index ndb_index(name);
5387
  if (unique)
5388 5389 5390 5391 5392
    ndb_index.setType(NdbDictionary::Index::UniqueHashIndex);
  else 
  {
    ndb_index.setType(NdbDictionary::Index::OrderedIndex);
    // TODO Only temporary ordered indexes supported
5393
    ndb_index.setLogging(FALSE); 
5394
  }
5395 5396 5397 5398
  if (ndb_index.setTable(m_tabname))
  {
    DBUG_RETURN(my_errno= errno);
  }
5399 5400 5401 5402 5403

  for (; key_part != end; key_part++) 
  {
    Field *field= key_part->field;
    DBUG_PRINT("info", ("attr: %s", field->field_name));
5404 5405 5406 5407
    if (ndb_index.addColumnName(field->field_name))
    {
      DBUG_RETURN(my_errno= errno);
    }
5408 5409
  }
  
5410
  if (dict->createIndex(ndb_index, *m_table))
5411 5412 5413 5414 5415 5416 5417
    ERR_RETURN(dict->getNdbError());

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

5418 5419 5420 5421 5422
/*
 Prepare for an on-line alter table
*/ 
void ha_ndbcluster::prepare_for_alter()
{
5423
  /* ndb_share reference schema */
5424
  ndbcluster_get_share(m_share); // Increase ref_count
5425 5426
  DBUG_PRINT("NDB_SHARE", ("%s binlog schema  use_count: %u",
                           m_share->key, m_share->use_count));
5427 5428 5429
  set_ndb_share_state(m_share, NSS_ALTERED);
}

5430 5431 5432 5433 5434 5435 5436 5437
/*
  Add an index on-line to a table
*/
int ha_ndbcluster::add_index(TABLE *table_arg, 
                             KEY *key_info, uint num_of_keys)
{
  int error= 0;
  uint idx;
5438 5439
  DBUG_ENTER("ha_ndbcluster::add_index");
  DBUG_PRINT("enter", ("table %s", table_arg->s->table_name.str));
5440
  DBUG_ASSERT(m_share->state == NSS_ALTERED);
5441

5442 5443 5444 5445 5446
  for (idx= 0; idx < num_of_keys; idx++)
  {
    KEY *key= key_info + idx;
    KEY_PART_INFO *key_part= key->key_part;
    KEY_PART_INFO *end= key_part + key->key_parts;
5447
    NDB_INDEX_TYPE idx_type= get_index_type_from_key(idx, key_info, false);
5448 5449 5450 5451 5452 5453 5454 5455 5456
    DBUG_PRINT("info", ("Adding index: '%s'", key_info[idx].name));
    // Add fields to key_part struct
    for (; key_part != end; key_part++)
      key_part->field= table->field[key_part->fieldnr];
    // Check index type
    // Create index in ndb
    if((error= create_index(key_info[idx].name, key, idx_type, idx)))
      break;
  }
5457
  if (error)
5458
  {
5459
    set_ndb_share_state(m_share, NSS_INITIAL);
5460 5461 5462
    /* ndb_share reference schema free */
    DBUG_PRINT("NDB_SHARE", ("%s binlog schema free  use_count: %u",
                             m_share->key, m_share->use_count));
5463
    free_share(&m_share); // Decrease ref_count
5464
  }
5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475
  DBUG_RETURN(error);  
}

/*
  Mark one or several indexes for deletion. and
  renumber the remaining indexes
*/
int ha_ndbcluster::prepare_drop_index(TABLE *table_arg, 
                                      uint *key_num, uint num_of_keys)
{
  DBUG_ENTER("ha_ndbcluster::prepare_drop_index");
5476
  DBUG_ASSERT(m_share->state == NSS_ALTERED);
5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487
  // Mark indexes for deletion
  uint idx;
  for (idx= 0; idx < num_of_keys; idx++)
  {
    DBUG_PRINT("info", ("ha_ndbcluster::prepare_drop_index %u", *key_num));
    m_index[*key_num++].status= TO_BE_DROPPED;
  }
  // Renumber indexes
  THD *thd= current_thd;
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
  Ndb *ndb= thd_ndb->ndb;
5488 5489
  renumber_indexes(ndb, table_arg);
  DBUG_RETURN(0);
5490 5491 5492 5493 5494 5495 5496
}
 
/*
  Really drop all indexes marked for deletion
*/
int ha_ndbcluster::final_drop_index(TABLE *table_arg)
{
5497
  int error;
5498 5499 5500 5501 5502 5503
  DBUG_ENTER("ha_ndbcluster::final_drop_index");
  DBUG_PRINT("info", ("ha_ndbcluster::final_drop_index"));
  // Really drop indexes
  THD *thd= current_thd;
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
  Ndb *ndb= thd_ndb->ndb;
5504 5505 5506
  if((error= drop_indexes(ndb, table_arg)))
  {
    m_share->state= NSS_INITIAL;
5507 5508 5509
    /* ndb_share reference schema free */
    DBUG_PRINT("NDB_SHARE", ("%s binlog schema free  use_count: %u",
                             m_share->key, m_share->use_count));
5510 5511 5512
    free_share(&m_share); // Decrease ref_count
  }
  DBUG_RETURN(error);
5513 5514
}

5515 5516 5517 5518 5519 5520
/*
  Rename a table in NDB Cluster
*/

int ha_ndbcluster::rename_table(const char *from, const char *to)
{
5521
  NDBDICT *dict;
5522
  char old_dbname[FN_HEADLEN];
5523
  char new_dbname[FN_HEADLEN];
5524
  char new_tabname[FN_HEADLEN];
5525 5526
  const NDBTAB *orig_tab;
  int result;
5527 5528
  bool recreate_indexes= FALSE;
  NDBDICT::List index_list;
5529 5530

  DBUG_ENTER("ha_ndbcluster::rename_table");
5531
  DBUG_PRINT("info", ("Renaming %s to %s", from, to));
5532
  set_dbname(from, old_dbname);
5533
  set_dbname(to, new_dbname);
5534 5535 5536
  set_tabname(from);
  set_tabname(to, new_tabname);

5537 5538 5539
  if (check_ndb_connection())
    DBUG_RETURN(my_errno= HA_ERR_NO_CONNECTION);

mskold@mysql.com's avatar
mskold@mysql.com committed
5540
  Ndb *ndb= get_ndb();
5541
  ndb->setDatabaseName(old_dbname);
mskold@mysql.com's avatar
mskold@mysql.com committed
5542
  dict= ndb->getDictionary();
5543 5544
  Ndb_table_guard ndbtab_g(dict, m_tabname);
  if (!(orig_tab= ndbtab_g.get_table()))
5545
    ERR_RETURN(dict->getNdbError());
5546

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5547
#ifdef HAVE_NDB_BINLOG
5548 5549 5550
  int ndb_table_id= orig_tab->getObjectId();
  int ndb_table_version= orig_tab->getObjectVersion();

5551
  /* ndb_share reference temporary */
5552
  NDB_SHARE *share= get_share(from, 0, FALSE);
5553
  if (share)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5554
  {
5555 5556
    DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                             share->key, share->use_count));
5557
    IF_DBUG(int r=) rename_share(share, to);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5558 5559 5560
    DBUG_ASSERT(r == 0);
  }
#endif
5561 5562 5563 5564 5565
  if (my_strcasecmp(system_charset_info, new_dbname, old_dbname))
  {
    dict->listIndexes(index_list, *orig_tab);    
    recreate_indexes= TRUE;
  }
5566 5567
  // Change current database to that of target table
  set_dbname(to);
5568 5569 5570 5571
  if (ndb->setDatabaseName(m_dbname))
  {
    ERR_RETURN(ndb->getNdbError());
  }
5572

5573 5574 5575
  NdbDictionary::Table new_tab= *orig_tab;
  new_tab.setName(new_tabname);
  if (dict->alterTableGlobal(*orig_tab, new_tab) != 0)
5576
  {
5577
    NdbError ndb_error= dict->getNdbError();
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5578 5579 5580
#ifdef HAVE_NDB_BINLOG
    if (share)
    {
5581 5582
      IF_DBUG(int ret=) rename_share(share, from);
      DBUG_ASSERT(ret == 0);
5583 5584 5585
      /* ndb_share reference temporary free */
      DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                               share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5586 5587 5588
      free_share(&share);
    }
#endif
5589
    ERR_RETURN(ndb_error);
5590 5591 5592 5593
  }
  
  // Rename .ndb file
  if ((result= handler::rename_table(from, to)))
5594
  {
5595
    // ToDo in 4.1 should rollback alter table...
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5596 5597
#ifdef HAVE_NDB_BINLOG
    if (share)
5598 5599 5600 5601
    {
      /* ndb_share reference temporary free */
      DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                               share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5602
      free_share(&share);
5603
    }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5604
#endif
5605
    DBUG_RETURN(result);
5606
  }
5607

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618
#ifdef HAVE_NDB_BINLOG
  int is_old_table_tmpfile= 1;
  if (share && share->op)
    dict->forceGCPWait();

  /* handle old table */
  if (!IS_TMP_PREFIX(m_tabname))
  {
    is_old_table_tmpfile= 0;
    String event_name(INJECTOR_EVENT_LEN);
    ndb_rep_event_name(&event_name, from + sizeof(share_prefix) - 1, 0);
5619 5620
    ndbcluster_handle_drop_table(ndb, event_name.c_ptr(), share,
                                 "rename table");
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5621 5622 5623 5624 5625 5626 5627
  }

  if (!result && !IS_TMP_PREFIX(new_tabname))
  {
    /* always create an event for the table */
    String event_name(INJECTOR_EVENT_LEN);
    ndb_rep_event_name(&event_name, to + sizeof(share_prefix) - 1, 0);
5628 5629
    Ndb_table_guard ndbtab_g2(dict, new_tabname);
    const NDBTAB *ndbtab= ndbtab_g2.get_table();
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5630

5631
    if (!ndbcluster_create_event(ndb, ndbtab, event_name.c_ptr(), share,
5632
                                 share && ndb_binlog_running ? 2 : 1/* push warning */))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5633 5634 5635 5636
    {
      if (ndb_extra_logging)
        sql_print_information("NDB Binlog: RENAME Event: %s",
                              event_name.c_ptr());
5637
      if (share &&
5638
          ndbcluster_create_event_ops(share, ndbtab, event_name.c_ptr()))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5639
      {
5640 5641 5642
        sql_print_error("NDB Binlog: FAILED create event operations "
                        "during RENAME. Event %s", event_name.c_ptr());
        /* a warning has been issued to the client */
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5643 5644
      }
    }
5645 5646 5647 5648
    /*
      warning has been issued if ndbcluster_create_event failed
      and (share && ndb_binlog_running)
    */
5649
    if (!is_old_table_tmpfile)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5650 5651
      ndbcluster_log_schema_op(current_thd, share,
                               current_thd->query, current_thd->query_length,
5652 5653
                               old_dbname, m_tabname,
                               ndb_table_id, ndb_table_version,
5654
                               SOT_RENAME_TABLE,
5655
                               m_dbname, new_tabname, 1);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5656
  }
5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681

  // If we are moving tables between databases, we need to recreate
  // indexes
  if (recreate_indexes)
  {
    for (unsigned i = 0; i < index_list.count; i++) 
    {
        NDBDICT::List::Element& index_el = index_list.elements[i];
	// Recreate any indexes not stored in the system database
	if (my_strcasecmp(system_charset_info, 
			  index_el.database, NDB_SYSTEM_DATABASE))
	{
	  set_dbname(from);
	  ndb->setDatabaseName(m_dbname);
	  const NDBINDEX * index= dict->getIndexGlobal(index_el.name,  new_tab);
	  DBUG_PRINT("info", ("Creating index %s/%s",
			      index_el.database, index->getName()));
	  dict->createIndex(*index, new_tab);
	  DBUG_PRINT("info", ("Dropping index %s/%s",
			      index_el.database, index->getName()));
	  set_dbname(from);
	  ndb->setDatabaseName(m_dbname);
	  dict->dropIndexGlobal(*index);
	}
    }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5682 5683
  }
  if (share)
5684 5685 5686 5687
  {
    /* ndb_share reference temporary free */
    DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                             share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5688
    free_share(&share);
5689
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5690 5691
#endif

5692 5693 5694 5695 5696
  DBUG_RETURN(result);
}


/*
5697 5698
  Delete table from NDB Cluster

5699 5700
 */

5701 5702 5703 5704 5705 5706 5707 5708
/* static version which does not need a handler */

int
ha_ndbcluster::delete_table(ha_ndbcluster *h, Ndb *ndb,
                            const char *path,
                            const char *db,
                            const char *table_name)
{
5709
  THD *thd= current_thd;
5710 5711
  DBUG_ENTER("ha_ndbcluster::ndbcluster_delete_table");
  NDBDICT *dict= ndb->getDictionary();
5712 5713
  int ndb_table_id= 0;
  int ndb_table_version= 0;
5714
#ifdef HAVE_NDB_BINLOG
5715 5716 5717 5718
  /*
    Don't allow drop table unless
    schema distribution table is setup
  */
5719
  if (!ndb_schema_share)
5720 5721 5722 5723
  {
    DBUG_PRINT("info", ("Schema distribution table not setup"));
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
  }
5724
  /* ndb_share reference temporary */
5725
  NDB_SHARE *share= get_share(path, 0, FALSE);
5726 5727 5728 5729 5730
  if (share)
  {
    DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                             share->key, share->use_count));
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5731
#endif
5732 5733 5734

  /* Drop the table from NDB */
  
5735
  int res= 0;
5736
  if (h && h->m_table)
5737
  {
5738 5739
retry_temporary_error1:
    if (dict->dropTableGlobal(*h->m_table) == 0)
5740 5741 5742
    {
      ndb_table_id= h->m_table->getObjectId();
      ndb_table_version= h->m_table->getObjectVersion();
5743
      DBUG_PRINT("info", ("success 1"));
5744
    }
5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756
    else
    {
      switch (dict->getNdbError().status)
      {
        case NdbError::TemporaryError:
          if (!thd->killed) 
            goto retry_temporary_error1; // retry indefinitly
          break;
        default:
          break;
      }
      res= ndb_to_mysql_error(&dict->getNdbError());
5757
      DBUG_PRINT("info", ("error(1) %u", res));
5758
    }
5759
    h->release_metadata(thd, ndb);
5760 5761 5762 5763
  }
  else
  {
    ndb->setDatabaseName(db);
5764 5765 5766 5767 5768
    while (1)
    {
      Ndb_table_guard ndbtab_g(dict, table_name);
      if (ndbtab_g.get_table())
      {
5769
    retry_temporary_error2:
5770 5771 5772 5773
        if (dict->dropTableGlobal(*ndbtab_g.get_table()) == 0)
        {
          ndb_table_id= ndbtab_g.get_table()->getObjectId();
          ndb_table_version= ndbtab_g.get_table()->getObjectVersion();
5774 5775
          DBUG_PRINT("info", ("success 2"));
          break;
5776
        }
5777
        else
5778
        {
5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792
          switch (dict->getNdbError().status)
          {
            case NdbError::TemporaryError:
              if (!thd->killed) 
                goto retry_temporary_error2; // retry indefinitly
              break;
            default:
              if (dict->getNdbError().code == NDB_INVALID_SCHEMA_OBJECT)
              {
                ndbtab_g.invalidate();
                continue;
              }
              break;
          }
5793 5794
        }
      }
5795 5796
      res= ndb_to_mysql_error(&dict->getNdbError());
      DBUG_PRINT("info", ("error(2) %u", res));
5797 5798
      break;
    }
5799 5800 5801 5802
  }

  if (res)
  {
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813
#ifdef HAVE_NDB_BINLOG
    /* the drop table failed for some reason, drop the share anyways */
    if (share)
    {
      pthread_mutex_lock(&ndbcluster_mutex);
      if (share->state != NSS_DROPPED)
      {
        /*
          The share kept by the server has not been freed, free it
        */
        share->state= NSS_DROPPED;
5814 5815 5816
        /* ndb_share reference create free */
        DBUG_PRINT("NDB_SHARE", ("%s create free  use_count: %u",
                                 share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5817 5818
        free_share(&share, TRUE);
      }
5819 5820 5821
      /* ndb_share reference temporary free */
      DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                               share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5822 5823 5824 5825
      free_share(&share, TRUE);
      pthread_mutex_unlock(&ndbcluster_mutex);
    }
#endif
5826 5827 5828
    DBUG_RETURN(res);
  }

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839
#ifdef HAVE_NDB_BINLOG
  /* stop the logging of the dropped table, and cleanup */

  /*
    drop table is successful even if table does not exist in ndb
    and in case table was actually not dropped, there is no need
    to force a gcp, and setting the event_name to null will indicate
    that there is no event to be dropped
  */
  int table_dropped= dict->getNdbError().code != 709;

mskold@mysql.com's avatar
mskold@mysql.com committed
5840 5841
  if (!IS_TMP_PREFIX(table_name) && share &&
      current_thd->lex->sql_command != SQLCOM_TRUNCATE)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5842
  {
5843 5844
    ndbcluster_log_schema_op(thd, share,
                             thd->query, thd->query_length,
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5845
                             share->db, share->table_name,
5846
                             ndb_table_id, ndb_table_version,
5847
                             SOT_DROP_TABLE, 0, 0, 1);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858
  }
  else if (table_dropped && share && share->op) /* ndbcluster_log_schema_op
                                                   will do a force GCP */
    dict->forceGCPWait();

  if (!IS_TMP_PREFIX(table_name))
  {
    String event_name(INJECTOR_EVENT_LEN);
    ndb_rep_event_name(&event_name, path + sizeof(share_prefix) - 1, 0);
    ndbcluster_handle_drop_table(ndb,
                                 table_dropped ? event_name.c_ptr() : 0,
5859
                                 share, "delete table");
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870
  }

  if (share)
  {
    pthread_mutex_lock(&ndbcluster_mutex);
    if (share->state != NSS_DROPPED)
    {
      /*
        The share kept by the server has not been freed, free it
      */
      share->state= NSS_DROPPED;
5871 5872 5873
      /* ndb_share reference create free */
      DBUG_PRINT("NDB_SHARE", ("%s create free  use_count: %u",
                               share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5874 5875
      free_share(&share, TRUE);
    }
5876 5877 5878
    /* ndb_share reference temporary free */
    DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                             share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5879 5880 5881 5882
    free_share(&share, TRUE);
    pthread_mutex_unlock(&ndbcluster_mutex);
  }
#endif
5883 5884 5885
  DBUG_RETURN(0);
}

5886 5887
int ha_ndbcluster::delete_table(const char *name)
{
5888
  DBUG_ENTER("ha_ndbcluster::delete_table");
5889 5890 5891
  DBUG_PRINT("enter", ("name: %s", name));
  set_dbname(name);
  set_tabname(name);
5892

5893 5894 5895 5896 5897
#ifdef HAVE_NDB_BINLOG
  /*
    Don't allow drop table unless
    schema distribution table is setup
  */
5898
  if (!ndb_schema_share)
5899 5900 5901 5902 5903 5904
  {
    DBUG_PRINT("info", ("Schema distribution table not setup"));
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
  }
#endif

5905 5906
  if (check_ndb_connection())
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
5907 5908

  /* Call ancestor function to delete .ndb file */
5909
  handler::delete_table(name);
5910 5911

  DBUG_RETURN(delete_table(this, get_ndb(),name, m_dbname, m_tabname));
5912 5913 5914
}


5915 5916 5917 5918
void ha_ndbcluster::get_auto_increment(ulonglong offset, ulonglong increment,
                                       ulonglong nb_desired_values,
                                       ulonglong *first_value,
                                       ulonglong *nb_reserved_values)
5919
{  
5920 5921
  int cache_size;
  Uint64 auto_value;
5922 5923
  DBUG_ENTER("get_auto_increment");
  DBUG_PRINT("enter", ("m_tabname: %s", m_tabname));
5924
  Ndb *ndb= get_ndb();
5925
   
5926
  if (m_rows_inserted > m_rows_to_insert)
5927
  {
5928 5929
    /* We guessed too low */
    m_rows_to_insert+= m_autoincrement_prefetch;
5930
  }
serg@serg.mylan's avatar
serg@serg.mylan committed
5931
  cache_size= 
5932 5933 5934 5935
    (int) ((m_rows_to_insert - m_rows_inserted < m_autoincrement_prefetch) ?
           m_rows_to_insert - m_rows_inserted :
           ((m_rows_to_insert > m_autoincrement_prefetch) ?
            m_rows_to_insert : m_autoincrement_prefetch));
5936
  int ret;
5937 5938
  uint retries= NDB_AUTO_INCREMENT_RETRIES;
  do {
5939
    Ndb_tuple_id_range_guard g(m_share);
5940 5941
    ret=
      m_skip_auto_increment ? 
5942 5943
      ndb->readAutoIncrementValue(m_table, g.range, auto_value) :
      ndb->getAutoIncrementValue(m_table, g.range, auto_value, cache_size);
5944
  } while (ret == -1 && 
5945 5946
           --retries &&
           ndb->getNdbError().status == NdbError::TemporaryError);
5947
  if (ret == -1)
5948 5949 5950 5951
  {
    const NdbError err= ndb->getNdbError();
    sql_print_error("Error %lu in ::get_auto_increment(): %s",
                    (ulong) err.code, err.message);
5952 5953
    *first_value= ~(ulonglong) 0;
    DBUG_VOID_RETURN;
5954
  }
5955 5956 5957 5958
  *first_value= (longlong)auto_value;
  /* From the point of view of MySQL, NDB reserves one row at a time */
  *nb_reserved_values= 1;
  DBUG_VOID_RETURN;
5959 5960 5961 5962 5963 5964 5965
}


/*
  Constructor for the NDB Cluster table handler 
 */

5966 5967 5968 5969 5970 5971 5972
#define HA_NDBCLUSTER_TABLE_FLAGS \
                HA_REC_NOT_IN_SEQ | \
                HA_NULL_IN_KEY | \
                HA_AUTO_PART_KEY | \
                HA_NO_PREFIX_CHAR_KEYS | \
                HA_NEED_READ_RANGE_BUFFER | \
                HA_CAN_GEOMETRY | \
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
5973
                HA_CAN_BIT_FIELD | \
5974 5975
                HA_PRIMARY_KEY_REQUIRED_FOR_POSITION | \
                HA_PRIMARY_KEY_REQUIRED_FOR_DELETE | \
5976
                HA_PARTIAL_COLUMN_READ | \
5977 5978
                HA_HAS_OWN_BINLOGGING | \
                HA_HAS_RECORDS
5979

5980 5981
ha_ndbcluster::ha_ndbcluster(handlerton *hton, TABLE_SHARE *table_arg):
  handler(hton, table_arg),
5982 5983 5984
  m_active_trans(NULL),
  m_active_cursor(NULL),
  m_table(NULL),
5985
  m_table_info(NULL),
5986
  m_table_flags(HA_NDBCLUSTER_TABLE_FLAGS),
5987
  m_share(0),
5988 5989 5990
  m_part_info(NULL),
  m_use_partition_function(FALSE),
  m_sorted(FALSE),
5991
  m_use_write(FALSE),
5992
  m_ignore_dup_key(FALSE),
5993
  m_has_unique_index(FALSE),
5994
  m_primary_key_update(FALSE),
5995
  m_ignore_no_key(FALSE),
5996 5997 5998
  m_rows_to_insert((ha_rows) 1),
  m_rows_inserted((ha_rows) 0),
  m_bulk_insert_rows((ha_rows) 1024),
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
5999
  m_rows_changed((ha_rows) 0),
6000
  m_bulk_insert_not_flushed(FALSE),
6001 6002
  m_delete_cannot_batch(FALSE),
  m_update_cannot_batch(FALSE),
6003 6004 6005
  m_ops_pending(0),
  m_skip_auto_increment(TRUE),
  m_blobs_pending(0),
6006
  m_blobs_offset(0),
6007 6008
  m_blobs_buffer(0),
  m_blobs_buffer_size(0),
6009 6010 6011
  m_dupkey((uint) -1),
  m_ha_not_exact_count(FALSE),
  m_force_send(TRUE),
6012
  m_autoincrement_prefetch((ha_rows) 32),
6013
  m_transaction_on(TRUE),
6014
  m_cond(NULL),
mskold@mysql.com's avatar
mskold@mysql.com committed
6015
  m_multi_cursor(NULL)
6016
{
6017
  int i;
6018
 
6019 6020 6021 6022 6023
  DBUG_ENTER("ha_ndbcluster");

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

6024 6025
  stats.records= ~(ha_rows)0; // uninitialized
  stats.block_size= 1024;
6026

tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
6027 6028
  for (i= 0; i < MAX_KEY; i++)
    ndb_init_index(m_index[i]);
6029

6030 6031 6032 6033
  DBUG_VOID_RETURN;
}


6034 6035 6036 6037 6038 6039 6040 6041 6042 6043
int ha_ndbcluster::ha_initialise()
{
  DBUG_ENTER("ha_ndbcluster::ha_initialise");
  if (check_ndb_in_thd(current_thd))
  {
    DBUG_RETURN(FALSE);
  }
  DBUG_RETURN(TRUE);
}

6044 6045 6046 6047 6048 6049
/*
  Destructor for NDB Cluster table handler
 */

ha_ndbcluster::~ha_ndbcluster() 
{
6050 6051
  THD *thd= current_thd;
  Ndb *ndb= thd ? check_ndb_in_thd(thd) : g_ndb;
6052 6053
  DBUG_ENTER("~ha_ndbcluster");

6054
  if (m_share)
6055
  {
6056 6057 6058
    /* ndb_share reference handler free */
    DBUG_PRINT("NDB_SHARE", ("%s handler free  use_count: %u",
                             m_share->key, m_share->use_count));
6059 6060
    free_share(&m_share);
  }
6061
  release_metadata(thd, ndb);
6062 6063
  my_free(m_blobs_buffer, MYF(MY_ALLOW_ZERO_PTR));
  m_blobs_buffer= 0;
6064 6065

  // Check for open cursor/transaction
6066 6067
  if (m_active_cursor) {
  }
6068
  DBUG_ASSERT(m_active_cursor == NULL);
6069 6070
  if (m_active_trans) {
  }
6071 6072
  DBUG_ASSERT(m_active_trans == NULL);

6073 6074 6075 6076 6077 6078 6079
  // Discard any generated condition
  DBUG_PRINT("info", ("Deleting generated condition"));
  if (m_cond)
  {
    delete m_cond;
    m_cond= NULL;
  }
6080

6081 6082 6083 6084
  DBUG_VOID_RETURN;
}


mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
6085

6086 6087 6088 6089
/*
  Open a table for further use
  - fetch metadata for this table from NDB
  - check that table exists
6090 6091 6092 6093

  RETURN
    0    ok
    < 0  Table has changed
6094 6095 6096 6097
*/

int ha_ndbcluster::open(const char *name, int mode, uint test_if_locked)
{
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6098
  int res;
6099
  KEY *key;
6100 6101 6102
  DBUG_ENTER("ha_ndbcluster::open");
  DBUG_PRINT("enter", ("name: %s  mode: %d  test_if_locked: %d",
                       name, mode, test_if_locked));
6103
  
6104 6105 6106 6107
  /*
    Setup ref_length to make room for the whole 
    primary key to be written in the ref variable
  */
6108
  
6109
  if (table_share->primary_key != MAX_KEY) 
6110
  {
6111
    key= table->key_info+table_share->primary_key;
6112 6113
    ref_length= key->key_length;
  }
6114 6115 6116 6117 6118 6119 6120 6121 6122 6123
  else // (table_share->primary_key == MAX_KEY) 
  {
    if (m_use_partition_function)
    {
      ref_length+= sizeof(m_part_id);
    }
  }

  DBUG_PRINT("info", ("ref_length: %d", ref_length));

6124
  // Init table lock structure 
6125
  /* ndb_share reference handler */
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6126
  if (!(m_share=get_share(name, table)))
6127
    DBUG_RETURN(1);
6128 6129
  DBUG_PRINT("NDB_SHARE", ("%s handler  use_count: %u",
                           m_share->key, m_share->use_count));
6130 6131 6132 6133 6134
  thr_lock_data_init(&m_share->lock,&m_lock,(void*) 0);
  
  set_dbname(name);
  set_tabname(name);
  
6135 6136 6137 6138 6139
  if (check_ndb_connection())
  {
    /* ndb_share reference handler free */
    DBUG_PRINT("NDB_SHARE", ("%s handler free  use_count: %u",
                             m_share->key, m_share->use_count));
6140 6141
    free_share(&m_share);
    m_share= 0;
6142
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
6143
  }
6144
  
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6145 6146
  res= get_metadata(name);
  if (!res)
6147 6148
  {
    Ndb *ndb= get_ndb();
6149 6150 6151 6152
    if (ndb->setDatabaseName(m_dbname))
    {
      ERR_RETURN(ndb->getNdbError());
    }
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
6153
    struct Ndb_statistics stat;
6154
    res= ndb_get_table_statistics(NULL, FALSE, ndb, m_table, &stat);
6155 6156 6157
    stats.mean_rec_length= stat.row_size;
    stats.data_file_length= stat.fragment_memory;
    stats.records= stat.row_count;
6158 6159 6160
    if(!res)
      res= info(HA_STATUS_CONST);
  }
6161

6162 6163 6164 6165 6166
#ifdef HAVE_NDB_BINLOG
  if (!ndb_binlog_tables_inited && ndb_binlog_running)
    table->db_stat|= HA_READ_ONLY;
#endif

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6167
  DBUG_RETURN(res);
6168 6169
}

6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183
/*
  Set partition info

  SYNOPSIS
    set_part_info()
    part_info

  RETURN VALUE
    NONE

  DESCRIPTION
    Set up partition info when handler object created
*/

6184 6185 6186 6187 6188
void ha_ndbcluster::set_part_info(partition_info *part_info)
{
  m_part_info= part_info;
  if (!(m_part_info->part_type == HASH_PARTITION &&
        m_part_info->list_of_part_fields &&
6189
        !m_part_info->is_sub_partitioned()))
6190 6191
    m_use_partition_function= TRUE;
}
6192 6193 6194 6195 6196 6197 6198 6199

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

int ha_ndbcluster::close(void)
{
6200
  DBUG_ENTER("close");
6201
  THD *thd= table->in_use;
6202
  Ndb *ndb= thd ? check_ndb_in_thd(thd) : g_ndb;
6203 6204 6205
  /* ndb_share reference handler free */
  DBUG_PRINT("NDB_SHARE", ("%s handler free  use_count: %u",
                           m_share->key, m_share->use_count));
6206 6207
  free_share(&m_share);
  m_share= 0;
6208
  release_metadata(thd, ndb);
6209 6210 6211 6212
  DBUG_RETURN(0);
}


6213
Thd_ndb* ha_ndbcluster::seize_thd_ndb()
6214
{
6215 6216
  Thd_ndb *thd_ndb;
  DBUG_ENTER("seize_thd_ndb");
6217

6218
  thd_ndb= new Thd_ndb();
6219 6220 6221 6222 6223
  if (thd_ndb == NULL)
  {
    my_errno= HA_ERR_OUT_OF_MEM;
    return NULL;
  }
6224
  if (thd_ndb->ndb->init(max_transactions) != 0)
6225
  {
6226
    ERR_PRINT(thd_ndb->ndb->getNdbError());
6227 6228 6229 6230 6231 6232
    /*
      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 
    */
6233 6234
    delete thd_ndb;
    thd_ndb= NULL;
6235
  }
6236
  DBUG_RETURN(thd_ndb);
6237 6238 6239
}


6240
void ha_ndbcluster::release_thd_ndb(Thd_ndb* thd_ndb)
6241
{
6242 6243
  DBUG_ENTER("release_thd_ndb");
  delete thd_ndb;
6244 6245 6246 6247 6248
  DBUG_VOID_RETURN;
}


/*
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
6249
  If this thread already has a Thd_ndb object allocated
6250
  in current THD, reuse it. Otherwise
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
6251
  seize a Thd_ndb object, assign it to current THD and use it.
6252 6253 6254
 
*/

6255
Ndb* check_ndb_in_thd(THD* thd)
6256
{
6257
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
6258
  if (!thd_ndb)
6259
  {
magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
6260
    if (!(thd_ndb= ha_ndbcluster::seize_thd_ndb()))
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
6261
      return NULL;
6262
    set_thd_ndb(thd, thd_ndb);
6263
  }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
6264
  return thd_ndb->ndb;
6265 6266
}

magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
6267

6268

6269
int ha_ndbcluster::check_ndb_connection(THD* thd)
6270
{
6271
  Ndb *ndb;
6272 6273
  DBUG_ENTER("check_ndb_connection");
  
6274
  if (!(ndb= check_ndb_in_thd(thd)))
6275
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
6276 6277 6278 6279
  if (ndb->setDatabaseName(m_dbname))
  {
    ERR_RETURN(ndb->getNdbError());
  }
6280 6281 6282
  DBUG_RETURN(0);
}

magnus@neptunus.(none)'s avatar
magnus@neptunus.(none) committed
6283

6284
static int ndbcluster_close_connection(handlerton *hton, THD *thd)
6285
{
6286
  Thd_ndb *thd_ndb= get_thd_ndb(thd);
6287
  DBUG_ENTER("ndbcluster_close_connection");
6288 6289
  if (thd_ndb)
  {
6290
    ha_ndbcluster::release_thd_ndb(thd_ndb);
6291
    set_thd_ndb(thd, NULL); // not strictly required but does not hurt either
6292
  }
6293
  DBUG_RETURN(0);
6294 6295 6296 6297 6298 6299 6300
}


/*
  Try to discover one table from NDB
 */

6301 6302 6303 6304
int ndbcluster_discover(handlerton *hton, THD* thd, const char *db, 
                        const char *name,
                        const void** frmblob, 
                        uint* frmlen)
6305
{
6306 6307
  int error= 0;
  NdbError ndb_error;
6308
  uint len;
6309
  const void* data= NULL;
6310
  Ndb* ndb;
6311
  char key[FN_REFLEN];
6312
  DBUG_ENTER("ndbcluster_discover");
6313
  DBUG_PRINT("enter", ("db: %s, name: %s", db, name)); 
6314

6315 6316
  if (!(ndb= check_ndb_in_thd(thd)))
    DBUG_RETURN(HA_ERR_NO_CONNECTION);  
6317 6318 6319 6320
  if (ndb->setDatabaseName(db))
  {
    ERR_RETURN(ndb->getNdbError());
  }
6321
  NDBDICT* dict= ndb->getDictionary();
6322
  build_table_filename(key, sizeof(key), db, name, "", 0);
6323
  /* ndb_share reference temporary */
6324
  NDB_SHARE *share= get_share(key, 0, FALSE);
6325 6326 6327 6328 6329
  if (share)
  {
    DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                             share->key, share->use_count));
  }
6330
  if (share && get_ndb_share_state(share) == NSS_ALTERED)
6331
  {
6332 6333 6334 6335
    // Frm has been altered on disk, but not yet written to ndb
    if (readfrm(key, &data, &len))
    {
      DBUG_PRINT("error", ("Could not read frm"));
6336 6337
      error= 1;
      goto err;
6338
    }
6339
  }
6340
  else
6341
  {
6342 6343 6344 6345
    Ndb_table_guard ndbtab_g(dict, name);
    const NDBTAB *tab= ndbtab_g.get_table();
    if (!tab)
    {
6346 6347
      const NdbError err= dict->getNdbError();
      if (err.code == 709 || err.code == 723)
6348
      {
6349
        error= -1;
6350 6351
        DBUG_PRINT("info", ("ndb_error.code: %u", ndb_error.code));
      }
6352
      else
6353 6354
      {
        error= -1;
6355
        ndb_error= err;
6356 6357
        DBUG_PRINT("info", ("ndb_error.code: %u", ndb_error.code));
      }
6358
      goto err;
6359 6360 6361 6362 6363 6364 6365
    }
    DBUG_PRINT("info", ("Found table %s", tab->getName()));
    
    len= tab->getFrmLength();  
    if (len == 0 || tab->getFrmData() == NULL)
    {
      DBUG_PRINT("error", ("No frm data found."));
6366 6367
      error= 1;
      goto err;
6368 6369 6370 6371 6372
    }
    
    if (unpackfrm(&data, &len, tab->getFrmData()))
    {
      DBUG_PRINT("error", ("Could not unpack table"));
6373 6374
      error= 1;
      goto err;
6375
    }
6376
  }
6377 6378 6379 6380

  *frmlen= len;
  *frmblob= data;
  
6381
  if (share)
6382 6383 6384 6385
  {
    /* ndb_share reference temporary free */
    DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                             share->key, share->use_count));
6386
    free_share(&share);
6387
  }
6388

6389
  DBUG_RETURN(0);
6390
err:
6391
  my_free((char*)data, MYF(MY_ALLOW_ZERO_PTR));
6392
  if (share)
6393 6394 6395 6396
  {
    /* ndb_share reference temporary free */
    DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                             share->key, share->use_count));
6397
    free_share(&share);
6398
  }
6399 6400 6401 6402 6403
  if (ndb_error.code)
  {
    ERR_RETURN(ndb_error);
  }
  DBUG_RETURN(error);
6404 6405 6406
}

/*
6407
  Check if a table exists in NDB
6408

6409
 */
6410

6411 6412
int ndbcluster_table_exists_in_engine(handlerton *hton, THD* thd, 
                                      const char *db,
6413
                                      const char *name)
6414 6415
{
  Ndb* ndb;
6416
  DBUG_ENTER("ndbcluster_table_exists_in_engine");
6417
  DBUG_PRINT("enter", ("db: %s  name: %s", db, name));
6418 6419

  if (!(ndb= check_ndb_in_thd(thd)))
6420
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
6421
  NDBDICT* dict= ndb->getDictionary();
6422 6423 6424
  NdbDictionary::Dictionary::List list;
  if (dict->listObjects(list, NdbDictionary::Object::UserTable) != 0)
    ERR_RETURN(dict->getNdbError());
6425
  for (uint i= 0 ; i < list.count ; i++)
6426
  {
6427 6428 6429 6430 6431 6432 6433
    NdbDictionary::Dictionary::List::Element& elmt= list.elements[i];
    if (my_strcasecmp(system_charset_info, elmt.database, db))
      continue;
    if (my_strcasecmp(system_charset_info, elmt.name, name))
      continue;
    DBUG_PRINT("info", ("Found table"));
    DBUG_RETURN(1);
6434
  }
6435
  DBUG_RETURN(0);
6436 6437
}

6438 6439


6440
extern "C" byte* tables_get_key(const char *entry, uint *length,
6441
                                my_bool not_used __attribute__((unused)))
6442 6443 6444 6445 6446 6447
{
  *length= strlen(entry);
  return (byte*) entry;
}


6448 6449
/*
  Drop a database in NDB Cluster
6450 6451
  NOTE add a dummy void function, since stupid handlerton is returning void instead of int...
*/
6452

6453
int ndbcluster_drop_database_impl(const char *path)
6454 6455 6456 6457 6458 6459 6460 6461 6462
{
  DBUG_ENTER("ndbcluster_drop_database");
  THD *thd= current_thd;
  char dbname[FN_HEADLEN];
  Ndb* ndb;
  NdbDictionary::Dictionary::List list;
  uint i;
  char *tabname;
  List<char> drop_list;
6463
  int ret= 0;
6464 6465 6466 6467
  ha_ndbcluster::set_dbname(path, (char *)&dbname);
  DBUG_PRINT("enter", ("db: %s", dbname));
  
  if (!(ndb= check_ndb_in_thd(thd)))
6468
    DBUG_RETURN(-1);
6469 6470 6471 6472 6473
  
  // List tables in NDB
  NDBDICT *dict= ndb->getDictionary();
  if (dict->listObjects(list, 
                        NdbDictionary::Object::UserTable) != 0)
6474
    DBUG_RETURN(-1);
6475 6476
  for (i= 0 ; i < list.count ; i++)
  {
6477 6478
    NdbDictionary::Dictionary::List::Element& elmt= list.elements[i];
    DBUG_PRINT("info", ("Found %s/%s in NDB", elmt.database, elmt.name));     
6479 6480
    
    // Add only tables that belongs to db
6481
    if (my_strcasecmp(system_charset_info, elmt.database, dbname))
6482
      continue;
6483 6484
    DBUG_PRINT("info", ("%s must be dropped", elmt.name));     
    drop_list.push_back(thd->strdup(elmt.name));
6485 6486
  }
  // Drop any tables belonging to database
6487
  char full_path[FN_REFLEN];
6488
  char *tmp= full_path +
6489
    build_table_filename(full_path, sizeof(full_path), dbname, "", "", 0);
6490 6491 6492 6493
  if (ndb->setDatabaseName(dbname))
  {
    ERR_RETURN(ndb->getNdbError());
  }
6494 6495
  List_iterator_fast<char> it(drop_list);
  while ((tabname=it++))
6496
  {
6497
    tablename_to_filename(tabname, tmp, FN_REFLEN - (tmp - full_path)-1);
6498
    VOID(pthread_mutex_lock(&LOCK_open));
6499
    if (ha_ndbcluster::delete_table(0, ndb, full_path, dbname, tabname))
6500 6501
    {
      const NdbError err= dict->getNdbError();
6502
      if (err.code != 709 && err.code != 723)
6503 6504
      {
        ERR_PRINT(err);
6505
        ret= ndb_to_mysql_error(&err);
6506
      }
6507
    }
6508
    VOID(pthread_mutex_unlock(&LOCK_open));
6509 6510
  }
  DBUG_RETURN(ret);      
6511 6512
}

6513
static void ndbcluster_drop_database(handlerton *hton, char *path)
6514
{
6515 6516 6517 6518 6519 6520
  DBUG_ENTER("ndbcluster_drop_database");
#ifdef HAVE_NDB_BINLOG
  /*
    Don't allow drop database unless
    schema distribution table is setup
  */
6521
  if (!ndb_schema_share)
6522 6523 6524 6525 6526 6527
  {
    DBUG_PRINT("info", ("Schema distribution table not setup"));
    DBUG_VOID_RETURN;
    //DBUG_RETURN(HA_ERR_NO_CONNECTION);
  }
#endif
6528
  ndbcluster_drop_database_impl(path);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6529 6530
#ifdef HAVE_NDB_BINLOG
  char db[FN_REFLEN];
6531
  THD *thd= current_thd;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6532
  ha_ndbcluster::set_dbname(path, db);
6533 6534
  ndbcluster_log_schema_op(thd, 0,
                           thd->query, thd->query_length,
6535
                           db, "", 0, 0, SOT_DROP_DB, 0, 0, 0);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6536
#endif
6537
  DBUG_VOID_RETURN;
6538
}
6539

6540 6541 6542 6543 6544 6545
int ndb_create_table_from_engine(THD *thd, const char *db,
                                 const char *table_name)
{
  LEX *old_lex= thd->lex, newlex;
  thd->lex= &newlex;
  newlex.current_select= NULL;
6546
  lex_start(thd, "", 0);
6547 6548 6549 6550 6551
  int res= ha_create_table_from_engine(thd, db, table_name);
  thd->lex= old_lex;
  return res;
}

6552 6553 6554
/*
  find all tables in ndb and discover those needed
*/
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6555
int ndbcluster_find_all_files(THD *thd)
6556 6557 6558
{
  Ndb* ndb;
  char key[FN_REFLEN];
6559 6560 6561
  NDBDICT *dict;
  int unhandled, retries= 5, skipped;
  DBUG_ENTER("ndbcluster_find_all_files");
6562 6563 6564 6565

  if (!(ndb= check_ndb_in_thd(thd)))
    DBUG_RETURN(HA_ERR_NO_CONNECTION);

6566
  dict= ndb->getDictionary();
6567

6568 6569
  LINT_INIT(unhandled);
  LINT_INIT(skipped);
6570 6571
  do
  {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
6572
    NdbDictionary::Dictionary::List list;
6573 6574 6575
    if (dict->listObjects(list, NdbDictionary::Object::UserTable) != 0)
      ERR_RETURN(dict->getNdbError());
    unhandled= 0;
6576 6577
    skipped= 0;
    retries--;
6578 6579 6580
    for (uint i= 0 ; i < list.count ; i++)
    {
      NDBDICT::List::Element& elmt= list.elements[i];
6581
      if (IS_TMP_PREFIX(elmt.name) || IS_NDB_BLOB_PREFIX(elmt.name))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6582 6583 6584 6585
      {
        DBUG_PRINT("info", ("Skipping %s.%s in NDB", elmt.database, elmt.name));
        continue;
      }
6586
      DBUG_PRINT("info", ("Found %s.%s in NDB", elmt.database, elmt.name));
6587 6588 6589
      if (elmt.state != NDBOBJ::StateOnline &&
          elmt.state != NDBOBJ::StateBackup &&
          elmt.state != NDBOBJ::StateBuilding)
6590 6591 6592
      {
        sql_print_information("NDB: skipping setup table %s.%s, in state %d",
                              elmt.database, elmt.name, elmt.state);
6593
        skipped++;
6594 6595 6596 6597
        continue;
      }

      ndb->setDatabaseName(elmt.database);
6598 6599 6600
      Ndb_table_guard ndbtab_g(dict, elmt.name);
      const NDBTAB *ndbtab= ndbtab_g.get_table();
      if (!ndbtab)
6601
      {
6602
        if (retries == 0)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6603 6604 6605 6606
          sql_print_error("NDB: failed to setup table %s.%s, error: %d, %s",
                          elmt.database, elmt.name,
                          dict->getNdbError().code,
                          dict->getNdbError().message);
6607 6608 6609 6610 6611 6612 6613
        unhandled++;
        continue;
      }

      if (ndbtab->getFrmLength() == 0)
        continue;
    
6614
      /* check if database exists */
6615
      char *end= key +
6616
        build_table_filename(key, sizeof(key), elmt.database, "", "", 0);
6617 6618 6619 6620 6621
      if (my_access(key, F_OK))
      {
        /* no such database defined, skip table */
        continue;
      }
6622 6623 6624
      /* finalize construction of path */
      end+= tablename_to_filename(elmt.name, end,
                                  sizeof(key)-(end-key));
6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636
      const void *data= 0, *pack_data= 0;
      uint length, pack_length;
      int discover= 0;
      if (readfrm(key, &data, &length) ||
          packfrm(data, length, &pack_data, &pack_length))
      {
        discover= 1;
        sql_print_information("NDB: missing frm for %s.%s, discovering...",
                              elmt.database, elmt.name);
      }
      else if (cmp_frm(ndbtab, pack_data, pack_length))
      {
6637
        /* ndb_share reference temporary */
6638
        NDB_SHARE *share= get_share(key, 0, FALSE);
6639 6640 6641 6642 6643
        if (share)
        {
          DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                                   share->key, share->use_count));
        }
6644
        if (!share || get_ndb_share_state(share) != NSS_ALTERED)
6645 6646 6647 6648 6649
        {
          discover= 1;
          sql_print_information("NDB: mismatch in frm for %s.%s, discovering...",
                                elmt.database, elmt.name);
        }
6650
        if (share)
6651 6652 6653 6654
        {
          /* ndb_share reference temporary free */
          DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                                   share->key, share->use_count));
6655
          free_share(&share);
6656
        }
6657 6658 6659 6660
      }
      my_free((char*) data, MYF(MY_ALLOW_ZERO_PTR));
      my_free((char*) pack_data, MYF(MY_ALLOW_ZERO_PTR));

6661
      pthread_mutex_lock(&LOCK_open);
6662 6663 6664
      if (discover)
      {
        /* ToDo 4.1 database needs to be created if missing */
6665
        if (ndb_create_table_from_engine(thd, elmt.database, elmt.name))
6666 6667 6668 6669
        {
          /* ToDo 4.1 handle error */
        }
      }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6670
#ifdef HAVE_NDB_BINLOG
6671
      else
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6672 6673
      {
        /* set up replication for this table */
6674 6675 6676
        ndbcluster_create_binlog_setup(ndb, key, end-key,
                                       elmt.database, elmt.name,
                                       TRUE);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6677 6678
      }
#endif
6679
      pthread_mutex_unlock(&LOCK_open);
6680 6681
    }
  }
6682
  while (unhandled && retries);
6683

6684
  DBUG_RETURN(-(skipped + unhandled));
6685
}
6686

6687 6688 6689
int ndbcluster_find_files(handlerton *hton, THD *thd,
                          const char *db,
                          const char *path,
6690
                          const char *wild, bool dir, List<char> *files)
6691
{
6692 6693 6694
  DBUG_ENTER("ndbcluster_find_files");
  DBUG_PRINT("enter", ("db: %s", db));
  { // extra bracket to avoid gcc 2.95.3 warning
6695
  uint i;
6696
  Ndb* ndb;
6697
  char name[FN_REFLEN];
6698
  HASH ndb_tables, ok_tables;
6699
  NDBDICT::List list;
6700 6701 6702 6703

  if (!(ndb= check_ndb_in_thd(thd)))
    DBUG_RETURN(HA_ERR_NO_CONNECTION);

6704
  if (dir)
6705
    DBUG_RETURN(0); // Discover of databases not yet supported
6706

6707
  // List tables in NDB
6708
  NDBDICT *dict= ndb->getDictionary();
6709
  if (dict->listObjects(list, 
6710
                        NdbDictionary::Object::UserTable) != 0)
6711
    ERR_RETURN(dict->getNdbError());
6712

6713
  if (hash_init(&ndb_tables, system_charset_info,list.count,0,0,
6714
                (hash_get_key)tables_get_key,0,0))
6715 6716 6717 6718 6719 6720
  {
    DBUG_PRINT("error", ("Failed to init HASH ndb_tables"));
    DBUG_RETURN(-1);
  }

  if (hash_init(&ok_tables, system_charset_info,32,0,0,
6721
                (hash_get_key)tables_get_key,0,0))
6722 6723 6724 6725 6726 6727
  {
    DBUG_PRINT("error", ("Failed to init HASH ok_tables"));
    hash_free(&ndb_tables);
    DBUG_RETURN(-1);
  }  

6728 6729
  for (i= 0 ; i < list.count ; i++)
  {
6730
    NDBDICT::List::Element& elmt= list.elements[i];
6731
    if (IS_TMP_PREFIX(elmt.name) || IS_NDB_BLOB_PREFIX(elmt.name))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6732 6733 6734 6735
    {
      DBUG_PRINT("info", ("Skipping %s.%s in NDB", elmt.database, elmt.name));
      continue;
    }
6736
    DBUG_PRINT("info", ("Found %s/%s in NDB", elmt.database, elmt.name));
6737

6738
    // Add only tables that belongs to db
6739
    if (my_strcasecmp(system_charset_info, elmt.database, db))
6740
      continue;
6741

6742
    // Apply wildcard to list of tables in NDB
6743
    if (wild)
6744
    {
6745 6746
      if (lower_case_table_names)
      {
6747
        if (wild_case_compare(files_charset_info, elmt.name, wild))
6748
          continue;
6749
      }
6750
      else if (wild_compare(elmt.name,wild,0))
6751
        continue;
6752
    }
6753 6754
    DBUG_PRINT("info", ("Inserting %s into ndb_tables hash", elmt.name));     
    my_hash_insert(&ndb_tables, (byte*)thd->strdup(elmt.name));
6755 6756
  }

6757 6758 6759 6760 6761
  char *file_name;
  List_iterator<char> it(*files);
  List<char> delete_list;
  while ((file_name=it++))
  {
6762
    bool file_on_disk= FALSE;
6763 6764 6765 6766
    DBUG_PRINT("info", ("%s", file_name));     
    if (hash_search(&ndb_tables, file_name, strlen(file_name)))
    {
      DBUG_PRINT("info", ("%s existed in NDB _and_ on disk ", file_name));
6767
      file_on_disk= TRUE;
6768 6769
    }
    
6770
    // Check for .ndb file with this name
6771
    build_table_filename(name, sizeof(name), db, file_name, ha_ndb_ext, 0);
6772
    DBUG_PRINT("info", ("Check access for %s", name));
6773
    if (my_access(name, F_OK))
6774 6775 6776
    {
      DBUG_PRINT("info", ("%s did not exist on disk", name));     
      // .ndb file did not exist on disk, another table type
6777
      if (file_on_disk)
6778 6779 6780 6781 6782
      {
	// Ignore this ndb table
	gptr record=  hash_search(&ndb_tables, file_name, strlen(file_name));
	DBUG_ASSERT(record);
	hash_delete(&ndb_tables, record);
6783 6784 6785 6786
	push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
			    ER_TABLE_EXISTS_ERROR,
			    "Local table %s.%s shadows ndb table",
			    db, file_name);
6787
      }
6788 6789 6790 6791
      continue;
    }
    if (file_on_disk) 
    {
6792
      // File existed in NDB and as frm file, put in ok_tables list
6793
      my_hash_insert(&ok_tables, (byte*)file_name);
6794
      continue;
6795
    }
6796 6797 6798
    DBUG_PRINT("info", ("%s existed on disk", name));     
    // The .ndb file exists on disk, but it's not in list of tables in ndb
    // Verify that handler agrees table is gone.
6799
    if (ndbcluster_table_exists_in_engine(hton, thd, db, file_name) == 0)    
6800 6801 6802 6803 6804 6805 6806
    {
      DBUG_PRINT("info", ("NDB says %s does not exists", file_name));     
      it.remove();
      // Put in list of tables to remove from disk
      delete_list.push_back(thd->strdup(file_name));
    }
  }
6807

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6808 6809 6810
#ifdef HAVE_NDB_BINLOG
  /* setup logging to binlog for all discovered tables */
  {
6811
    char *end, *end1= name +
6812
      build_table_filename(name, sizeof(name), db, "", "", 0);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6813 6814 6815
    for (i= 0; i < ok_tables.records; i++)
    {
      file_name= (char*)hash_element(&ok_tables, i);
6816 6817
      end= end1 +
        tablename_to_filename(file_name, end1, sizeof(name) - (end1 - name));
6818 6819 6820 6821
      pthread_mutex_lock(&LOCK_open);
      ndbcluster_create_binlog_setup(ndb, name, end-name,
                                     db, file_name, TRUE);
      pthread_mutex_unlock(&LOCK_open);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6822 6823 6824 6825
    }
  }
#endif

6826 6827 6828 6829
  // Check for new files to discover
  DBUG_PRINT("info", ("Checking for new files to discover"));       
  List<char> create_list;
  for (i= 0 ; i < ndb_tables.records ; i++)
6830
  {
6831 6832
    file_name= hash_element(&ndb_tables, i);
    if (!hash_search(&ok_tables, file_name, strlen(file_name)))
6833
    {
6834
      build_table_filename(name, sizeof(name), db, file_name, reg_ext, 0);
6835
      if (my_access(name, F_OK))
6836 6837 6838 6839 6840 6841
      {
        DBUG_PRINT("info", ("%s must be discovered", file_name));
        // File is in list of ndb tables and not in ok_tables
        // This table need to be created
        create_list.push_back(thd->strdup(file_name));
      }
6842 6843
    }
  }
6844

6845 6846
  // Lock mutex before deleting and creating frm files
  pthread_mutex_lock(&LOCK_open);
6847

6848 6849 6850 6851 6852
  if (!global_read_lock)
  {
    // Delete old files
    List_iterator_fast<char> it3(delete_list);
    while ((file_name=it3++))
6853 6854
    {
      DBUG_PRINT("info", ("Remove table %s/%s", db, file_name));
6855 6856 6857 6858
      // Delete the table and all related files
      TABLE_LIST table_list;
      bzero((char*) &table_list,sizeof(table_list));
      table_list.db= (char*) db;
6859
      table_list.alias= table_list.table_name= (char*)file_name;
6860
      (void)mysql_rm_table_part2(thd, &table_list,
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
6861 6862 6863 6864
                                                                 /* if_exists */ FALSE,
                                                                 /* drop_temporary */ FALSE,
                                                                 /* drop_view */ FALSE,
                                                                 /* dont_log_query*/ TRUE);
6865 6866
      /* Clear error message that is returned when table is deleted */
      thd->clear_error();
6867 6868 6869
    }
  }

6870 6871 6872 6873
  // Create new files
  List_iterator_fast<char> it2(create_list);
  while ((file_name=it2++))
  {  
6874
    DBUG_PRINT("info", ("Table %s need discovery", file_name));
6875
    if (ndb_create_table_from_engine(thd, db, file_name) == 0)
6876
      files->push_back(thd->strdup(file_name)); 
6877 6878
  }

6879
  pthread_mutex_unlock(&LOCK_open);
6880 6881
  
  hash_free(&ok_tables);
6882
  hash_free(&ndb_tables);
6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899

  // Delete schema file from files
  if (!strcmp(db, NDB_REP_DB))
  {
    uint count = 0;
    while (count++ < files->elements)
    {
      file_name = (char *)files->pop();
      if (!strcmp(file_name, NDB_SCHEMA_TABLE))
      {
        DBUG_PRINT("info", ("skip %s.%s table, it should be hidden to user",
                   NDB_REP_DB, NDB_SCHEMA_TABLE));
        continue;
      }
      files->push_back(file_name); 
    }
  }
6900
  } // extra bracket to avoid gcc 2.95.3 warning
6901
  DBUG_RETURN(0);    
6902 6903 6904 6905 6906 6907 6908 6909
}


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

6910 6911 6912
/* Call back after cluster connect */
static int connect_callback()
{
6913
  pthread_mutex_lock(&LOCK_ndb_util_thread);
6914
  update_status_variables(g_ndb_cluster_connection);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6915 6916 6917 6918 6919 6920 6921

  uint node_id, i= 0;
  Ndb_cluster_connection_node_iter node_iter;
  memset((void *)g_node_id_map, 0xFFFF, sizeof(g_node_id_map));
  while ((node_id= g_ndb_cluster_connection->get_next_node(node_iter)))
    g_node_id_map[node_id]= i++;

6922
  pthread_cond_signal(&COND_ndb_util_thread);
6923
  pthread_mutex_unlock(&LOCK_ndb_util_thread);
6924 6925 6926
  return 0;
}

6927
extern int ndb_dictionary_is_mysqld;
6928

6929
static int ndbcluster_init(void *p)
6930
{
6931
  int res;
6932
  DBUG_ENTER("ndbcluster_init");
6933

6934 6935 6936 6937 6938 6939 6940 6941 6942
  if (ndbcluster_inited)
    DBUG_RETURN(FALSE);

  pthread_mutex_init(&ndbcluster_mutex,MY_MUTEX_INIT_FAST);
  pthread_mutex_init(&LOCK_ndb_util_thread, MY_MUTEX_INIT_FAST);
  pthread_cond_init(&COND_ndb_util_thread, NULL);
  pthread_cond_init(&COND_ndb_util_ready, NULL);
  ndb_util_thread_running= -1;
  ndbcluster_terminating= 0;
6943
  ndb_dictionary_is_mysqld= 1;
6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960
  ndbcluster_hton= (handlerton *)p;

  {
    handlerton *h= ndbcluster_hton;
    h->state=            have_ndbcluster;
    h->db_type=          DB_TYPE_NDBCLUSTER;
    h->close_connection= ndbcluster_close_connection;
    h->commit=           ndbcluster_commit;
    h->rollback=         ndbcluster_rollback;
    h->create=           ndbcluster_create_handler; /* Create a new handler */
    h->drop_database=    ndbcluster_drop_database;  /* Drop a database */
    h->panic=            ndbcluster_end;            /* Panic call */
    h->show_status=      ndbcluster_show_status;    /* Show status */
    h->alter_tablespace= ndbcluster_alter_tablespace;    /* Show status */
    h->partition_flags=  ndbcluster_partition_flags; /* Partition flags */
    h->alter_table_flags=ndbcluster_alter_table_flags; /* Alter table flags */
    h->fill_files_table= ndbcluster_fill_files_table;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6961 6962 6963
#ifdef HAVE_NDB_BINLOG
    ndbcluster_binlog_init_handlerton();
#endif
6964 6965 6966 6967
    h->flags=            HTON_CAN_RECREATE | HTON_TEMPORARY_NOT_SUPPORTED;
    h->discover=         ndbcluster_discover;
    h->find_files= ndbcluster_find_files;
    h->table_exists_in_engine= ndbcluster_table_exists_in_engine;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
6968 6969
  }

6970 6971 6972
  if (have_ndbcluster != SHOW_OPTION_YES)
    DBUG_RETURN(0); // nothing else to do

6973 6974 6975
  // Initialize ndb interface
  ndb_init_internal();

6976
  // Set connectstring if specified
6977 6978
  if (opt_ndbcluster_connectstring != 0)
    DBUG_PRINT("connectstring", ("%s", opt_ndbcluster_connectstring));     
6979
  if ((g_ndb_cluster_connection=
6980
       new Ndb_cluster_connection(opt_ndbcluster_connectstring)) == 0)
6981
  {
6982
    DBUG_PRINT("error",("Ndb_cluster_connection(%s)",
6983
                        opt_ndbcluster_connectstring));
6984
    my_errno= HA_ERR_OUT_OF_MEM;
6985
    goto ndbcluster_init_error;
6986
  }
tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
6987 6988
  {
    char buf[128];
6989
    my_snprintf(buf, sizeof(buf), "mysqld --server-id=%lu", server_id);
tomas@poseidon.ndb.mysql.com's avatar
ndb:  
tomas@poseidon.ndb.mysql.com committed
6990 6991
    g_ndb_cluster_connection->set_name(buf);
  }
6992 6993 6994
  g_ndb_cluster_connection->set_optimized_node_selection
    (opt_ndb_optimized_node_selection);

6995
  // Create a Ndb object to open the connection  to NDB
6996 6997 6998
  if ( (g_ndb= new Ndb(g_ndb_cluster_connection, "sys")) == 0 )
  {
    DBUG_PRINT("error", ("failed to create global ndb object"));
6999
    my_errno= HA_ERR_OUT_OF_MEM;
7000 7001
    goto ndbcluster_init_error;
  }
7002 7003 7004
  if (g_ndb->init() != 0)
  {
    ERR_PRINT (g_ndb->getNdbError());
7005
    goto ndbcluster_init_error;
7006
  }
7007

7008
  if ((res= g_ndb_cluster_connection->connect(0,0,0)) == 0)
7009
  {
7010
    connect_callback();
7011
    DBUG_PRINT("info",("NDBCLUSTER storage engine at %s on port %d",
7012 7013
                       g_ndb_cluster_connection->get_connected_host(),
                       g_ndb_cluster_connection->get_connected_port()));
7014
    g_ndb_cluster_connection->wait_until_ready(10,3);
7015
  } 
7016
  else if (res == 1)
7017
  {
7018
    if (g_ndb_cluster_connection->start_connect_thread(connect_callback)) 
7019
    {
7020
      DBUG_PRINT("error", ("g_ndb_cluster_connection->start_connect_thread()"));
7021 7022
      goto ndbcluster_init_error;
    }
7023
#ifndef DBUG_OFF
7024 7025
    {
      char buf[1024];
7026
      DBUG_PRINT("info",
7027 7028 7029 7030
                 ("NDBCLUSTER storage engine not started, "
                  "will connect using %s",
                  g_ndb_cluster_connection->
                  get_connectstring(buf,sizeof(buf))));
7031
    }
7032
#endif
7033
  }
7034
  else
7035 7036 7037
  {
    DBUG_ASSERT(res == -1);
    DBUG_PRINT("error", ("permanent error"));
7038
    goto ndbcluster_init_error;
7039
  }
7040
  
7041 7042
  (void) hash_init(&ndbcluster_open_tables,system_charset_info,32,0,0,
                   (hash_get_key) ndbcluster_get_key,0,0);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7043 7044
#ifdef HAVE_NDB_BINLOG
  /* start the ndb injector thread */
7045 7046
  if (ndbcluster_binlog_start())
    goto ndbcluster_init_error;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7047
#endif /* HAVE_NDB_BINLOG */
7048

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
7049
  ndb_cache_check_time = opt_ndb_cache_check_time;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7050 7051 7052 7053 7054
  // Create utility thread
  pthread_t tmp;
  if (pthread_create(&tmp, &connection_attrib, ndb_util_thread_func, 0))
  {
    DBUG_PRINT("error", ("Could not create ndb utility thread"));
7055 7056 7057 7058
    hash_free(&ndbcluster_open_tables);
    pthread_mutex_destroy(&ndbcluster_mutex);
    pthread_mutex_destroy(&LOCK_ndb_util_thread);
    pthread_cond_destroy(&COND_ndb_util_thread);
7059
    pthread_cond_destroy(&COND_ndb_util_ready);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7060 7061
    goto ndbcluster_init_error;
  }
7062

7063 7064
  /* Wait for the util thread to start */
  pthread_mutex_lock(&LOCK_ndb_util_thread);
7065 7066
  while (ndb_util_thread_running < 0)
    pthread_cond_wait(&COND_ndb_util_ready, &LOCK_ndb_util_thread);
7067
  pthread_mutex_unlock(&LOCK_ndb_util_thread);
7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078
  
  if (!ndb_util_thread_running)
  {
    DBUG_PRINT("error", ("ndb utility thread exited prematurely"));
    hash_free(&ndbcluster_open_tables);
    pthread_mutex_destroy(&ndbcluster_mutex);
    pthread_mutex_destroy(&LOCK_ndb_util_thread);
    pthread_cond_destroy(&COND_ndb_util_thread);
    pthread_cond_destroy(&COND_ndb_util_ready);
    goto ndbcluster_init_error;
  }
7079

7080
  ndbcluster_inited= 1;
7081
  DBUG_RETURN(FALSE);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7082

7083
ndbcluster_init_error:
7084
  if (g_ndb)
7085 7086 7087 7088 7089
    delete g_ndb;
  g_ndb= NULL;
  if (g_ndb_cluster_connection)
    delete g_ndb_cluster_connection;
  g_ndb_cluster_connection= NULL;
7090
  have_ndbcluster= SHOW_OPTION_DISABLED;	// If we couldn't use handler
7091 7092
  ndbcluster_hton->state= SHOW_OPTION_DISABLED;               // If we couldn't use handler

7093
  DBUG_RETURN(TRUE);
7094 7095
}

7096
static int ndbcluster_end(handlerton *hton, ha_panic_function type)
7097 7098
{
  DBUG_ENTER("ndbcluster_end");
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7099

7100 7101
  if (!ndbcluster_inited)
    DBUG_RETURN(0);
7102 7103 7104
  ndbcluster_inited= 0;

  /* wait for util thread to finish */
7105
  sql_print_information("Stopping Cluster Utility thread");
7106
  pthread_mutex_lock(&LOCK_ndb_util_thread);
7107 7108 7109 7110
  ndbcluster_terminating= 1;
  pthread_cond_signal(&COND_ndb_util_thread);
  while (ndb_util_thread_running > 0)
    pthread_cond_wait(&COND_ndb_util_ready, &LOCK_ndb_util_thread);
7111 7112
  pthread_mutex_unlock(&LOCK_ndb_util_thread);

7113

7114 7115 7116
#ifdef HAVE_NDB_BINLOG
  {
    pthread_mutex_lock(&ndbcluster_mutex);
7117
    while (ndbcluster_open_tables.records)
7118 7119
    {
      NDB_SHARE *share=
7120
        (NDB_SHARE*) hash_element(&ndbcluster_open_tables, 0);
7121 7122 7123 7124
#ifndef DBUG_OFF
      fprintf(stderr, "NDB: table share %s with use_count %d not freed\n",
              share->key, share->use_count);
#endif
7125
      ndbcluster_real_free_share(&share);
7126 7127 7128 7129 7130 7131
    }
    pthread_mutex_unlock(&ndbcluster_mutex);
  }
#endif
  hash_free(&ndbcluster_open_tables);

7132
  if (g_ndb)
7133 7134
  {
#ifndef DBUG_OFF
7135 7136
    Ndb::Free_list_usage tmp;
    tmp.m_name= 0;
7137 7138 7139 7140 7141 7142 7143 7144 7145 7146
    while (g_ndb->get_free_list_usage(&tmp))
    {
      uint leaked= (uint) tmp.m_created - tmp.m_free;
      if (leaked)
        fprintf(stderr, "NDB: Found %u %s%s that %s not been released\n",
                leaked, tmp.m_name,
                (leaked == 1)?"":"'s",
                (leaked == 1)?"has":"have");
    }
#endif
7147
    delete g_ndb;
7148
    g_ndb= NULL;
7149
  }
7150
  delete g_ndb_cluster_connection;
7151
  g_ndb_cluster_connection= NULL;
7152

7153 7154 7155
  // cleanup ndb interface
  ndb_end_internal();

7156
  pthread_mutex_destroy(&ndbcluster_mutex);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7157 7158
  pthread_mutex_destroy(&LOCK_ndb_util_thread);
  pthread_cond_destroy(&COND_ndb_util_thread);
7159
  pthread_cond_destroy(&COND_ndb_util_ready);
7160 7161 7162
  DBUG_RETURN(0);
}

7163 7164 7165
void ha_ndbcluster::print_error(int error, myf errflag)
{
  DBUG_ENTER("ha_ndbcluster::print_error");
7166
  DBUG_PRINT("enter", ("error: %d", error));
7167 7168

  if (error == HA_ERR_NO_PARTITION_FOUND)
7169
    m_part_info->print_no_partition_found(table);
7170 7171 7172 7173 7174 7175
  else
    handler::print_error(error, errflag);
  DBUG_VOID_RETURN;
}


7176 7177 7178 7179 7180
/*
  Static error print function called from
  static handler method ndbcluster_commit
  and ndbcluster_rollback
*/
7181 7182

void ndbcluster_print_error(int error, const NdbOperation *error_op)
7183
{
7184
  DBUG_ENTER("ndbcluster_print_error");
7185
  TABLE_SHARE share;
7186
  const char *tab_name= (error_op) ? error_op->getTableName() : "";
7187 7188 7189 7190
  share.db.str= (char*) "";
  share.db.length= 0;
  share.table_name.str= (char *) tab_name;
  share.table_name.length= strlen(tab_name);
7191
  ha_ndbcluster error_handler(ndbcluster_hton, &share);
7192
  error_handler.print_error(error, MYF(0));
ndbdev@ndbmaster.mysql.com's avatar
ndbdev@ndbmaster.mysql.com committed
7193
  DBUG_VOID_RETURN;
7194
}
7195

7196 7197 7198
/**
 * Set a given location from full pathname to database name
 *
7199
 */
7200
void ha_ndbcluster::set_dbname(const char *path_name, char *dbname)
7201
{
7202 7203 7204 7205
  char *end, *ptr, *tmp_name;
  char tmp_buff[FN_REFLEN];
 
  tmp_name= tmp_buff;
7206
  /* Scan name from the end */
7207 7208 7209 7210 7211 7212
  ptr= strend(path_name)-1;
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
  ptr--;
  end= ptr;
7213 7214 7215 7216
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
  uint name_len= end - ptr;
7217 7218
  memcpy(tmp_name, ptr + 1, name_len);
  tmp_name[name_len]= '\0';
7219 7220
#ifdef __WIN__
  /* Put to lower case */
7221
  
7222
  ptr= tmp_name;
7223 7224
  
  while (*ptr != '\0') {
7225
    *ptr= tolower(*ptr);
7226 7227 7228
    ptr++;
  }
#endif
7229
  filename_to_tablename(tmp_name, dbname, FN_REFLEN);
7230 7231
}

7232 7233 7234 7235 7236 7237 7238 7239 7240
/*
  Set m_dbname from full pathname to table file
 */

void ha_ndbcluster::set_dbname(const char *path_name)
{
  set_dbname(path_name, m_dbname);
}

7241 7242 7243 7244 7245 7246 7247
/**
 * Set a given location from full pathname to table file
 *
 */
void
ha_ndbcluster::set_tabname(const char *path_name, char * tabname)
{
7248 7249 7250 7251
  char *end, *ptr, *tmp_name;
  char tmp_buff[FN_REFLEN];

  tmp_name= tmp_buff;
7252
  /* Scan name from the end */
7253 7254
  end= strend(path_name)-1;
  ptr= end;
7255 7256 7257
  while (ptr >= path_name && *ptr != '\\' && *ptr != '/') {
    ptr--;
  }
7258
  uint name_len= end - ptr;
7259 7260
  memcpy(tmp_name, ptr + 1, end - ptr);
  tmp_name[name_len]= '\0';
7261 7262
#ifdef __WIN__
  /* Put to lower case */
7263
  ptr= tmp_name;
7264 7265 7266 7267 7268 7269
  
  while (*ptr != '\0') {
    *ptr= tolower(*ptr);
    ptr++;
  }
#endif
7270
  filename_to_tablename(tmp_name, tabname, FN_REFLEN);
7271 7272 7273
}

/*
7274
  Set m_tabname from full pathname to table file 
7275 7276
 */

7277
void ha_ndbcluster::set_tabname(const char *path_name)
7278
{
7279
  set_tabname(path_name, m_tabname);
7280 7281 7282 7283
}


ha_rows 
7284 7285 7286 7287
ha_ndbcluster::records_in_range(uint inx, key_range *min_key,
                                key_range *max_key)
{
  KEY *key_info= table->key_info + inx;
7288
  uint key_length= key_info->key_length;
7289
  NDB_INDEX_TYPE idx_type= get_index_type(inx);  
7290 7291

  DBUG_ENTER("records_in_range");
7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304
  // 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);
  
7305 7306 7307 7308 7309 7310
  if ((idx_type == PRIMARY_KEY_ORDERED_INDEX ||
       idx_type == UNIQUE_ORDERED_INDEX ||
       idx_type == ORDERED_INDEX) &&
    m_index[inx].index_stat != NULL)
  {
    NDB_INDEX_DATA& d=m_index[inx];
7311
    const NDBINDEX* index= d.index;
7312 7313 7314 7315 7316 7317 7318 7319 7320 7321
    Ndb* ndb=get_ndb();
    NdbTransaction* trans=NULL;
    NdbIndexScanOperation* op=NULL;
    int res=0;
    Uint64 rows;

    do
    {
      // We must provide approx table rows
      Uint64 table_rows=0;
7322 7323
      Ndb_local_table_statistics *ndb_info= m_table_info;
      if (ndb_info->records != ~(ha_rows)0 && ndb_info->records != 0)
7324
      {
7325 7326
        table_rows = ndb_info->records;
        DBUG_PRINT("info", ("use info->records: %lu", (ulong) table_rows));
7327 7328 7329 7330
      }
      else
      {
        Ndb_statistics stat;
7331
        if ((res=ndb_get_table_statistics(this, TRUE, ndb, m_table, &stat)))
7332 7333
          break;
        table_rows=stat.row_count;
7334
        DBUG_PRINT("info", ("use db row_count: %lu", (ulong) table_rows));
7335 7336 7337 7338 7339 7340 7341 7342 7343 7344
        if (table_rows == 0) {
          // Problem if autocommit=0
#ifdef ndb_get_table_statistics_uses_active_trans
          rows=0;
          break;
#endif
        }
      }

      // Define scan op for the range
7345 7346
      if ((trans=m_active_trans) == NULL || 
	  trans->commitStatus() != NdbTransaction::Started)
7347 7348 7349 7350 7351 7352 7353 7354 7355 7356
      {
        DBUG_PRINT("info", ("no active trans"));
        if (! (trans=ndb->startTransaction()))
          ERR_BREAK(ndb->getNdbError(), res);
      }
      if (! (op=trans->getNdbIndexScanOperation(index, (NDBTAB*)m_table)))
        ERR_BREAK(trans->getNdbError(), res);
      if ((op->readTuples(NdbOperation::LM_CommittedRead)) == -1)
        ERR_BREAK(op->getNdbError(), res);
      const key_range *keys[2]={ min_key, max_key };
7357
      if ((res=set_bounds(op, inx, TRUE, keys)) != 0)
7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382
        break;

      // Decide if db should be contacted
      int flags=0;
      if (d.index_stat_query_count < d.index_stat_cache_entries ||
          (d.index_stat_update_freq != 0 &&
           d.index_stat_query_count % d.index_stat_update_freq == 0))
      {
        DBUG_PRINT("info", ("force stat from db"));
        flags|=NdbIndexStat::RR_UseDb;
      }
      if (d.index_stat->records_in_range(index, op, table_rows, &rows, flags) == -1)
        ERR_BREAK(d.index_stat->getNdbError(), res);
      d.index_stat_query_count++;
    } while (0);

    if (trans != m_active_trans && rows == 0)
      rows = 1;
    if (trans != m_active_trans && trans != NULL)
      ndb->closeTransaction(trans);
    if (res != 0)
      DBUG_RETURN(HA_POS_ERROR);
    DBUG_RETURN(rows);
  }

7383
  DBUG_RETURN(10); /* Good guess when you don't know anything */
7384 7385
}

7386
ulonglong ha_ndbcluster::table_flags(void) const
7387 7388
{
  if (m_ha_not_exact_count)
7389 7390
    return m_table_flags & ~HA_STATS_RECORDS_IS_EXACT;
  return m_table_flags;
7391 7392 7393
}
const char * ha_ndbcluster::table_type() const 
{
7394
  return("NDBCLUSTER");
7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411
}
uint ha_ndbcluster::max_supported_record_length() const
{ 
  return NDB_MAX_TUPLE_SIZE;
}
uint ha_ndbcluster::max_supported_keys() const
{
  return MAX_KEY;
}
uint ha_ndbcluster::max_supported_key_parts() const 
{
  return NDB_MAX_NO_OF_ATTRIBUTES_IN_KEY;
}
uint ha_ndbcluster::max_supported_key_length() const
{
  return NDB_MAX_KEY_SIZE;
}
pekka@mysql.com's avatar
pekka@mysql.com committed
7412 7413 7414 7415
uint ha_ndbcluster::max_supported_key_part_length() const
{
  return NDB_MAX_KEY_SIZE;
}
7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436
bool ha_ndbcluster::low_byte_first() const
{ 
#ifdef WORDS_BIGENDIAN
  return FALSE;
#else
  return TRUE;
#endif
}
const char* ha_ndbcluster::index_type(uint key_number)
{
  switch (get_index_type(key_number)) {
  case ORDERED_INDEX:
  case UNIQUE_ORDERED_INDEX:
  case PRIMARY_KEY_ORDERED_INDEX:
    return "BTREE";
  case UNIQUE_INDEX:
  case PRIMARY_KEY_INDEX:
  default:
    return "HASH";
  }
}
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7437

7438 7439
uint8 ha_ndbcluster::table_cache_type()
{
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7440 7441 7442 7443 7444 7445
  DBUG_ENTER("ha_ndbcluster::table_cache_type=HA_CACHE_TBL_ASKTRANSACT");
  DBUG_RETURN(HA_CACHE_TBL_ASKTRANSACT);
}


uint ndb_get_commitcount(THD *thd, char *dbname, char *tabname,
7446
                         Uint64 *commit_count)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7447
{
7448 7449
  char name[FN_REFLEN];
  NDB_SHARE *share;
7450 7451
  DBUG_ENTER("ndb_get_commitcount");

7452
  build_table_filename(name, sizeof(name), dbname, tabname, "", 0);
7453 7454 7455 7456 7457 7458 7459
  DBUG_PRINT("enter", ("name: %s", name));
  pthread_mutex_lock(&ndbcluster_mutex);
  if (!(share=(NDB_SHARE*) hash_search(&ndbcluster_open_tables,
                                       (byte*) name,
                                       strlen(name))))
  {
    pthread_mutex_unlock(&ndbcluster_mutex);
7460
    DBUG_PRINT("info", ("Table %s not found in ndbcluster_open_tables", name));
7461 7462
    DBUG_RETURN(1);
  }
7463
  /* ndb_share reference temporary, free below */
7464
  share->use_count++;
7465 7466
  DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                           share->key, share->use_count));
7467 7468 7469
  pthread_mutex_unlock(&ndbcluster_mutex);

  pthread_mutex_lock(&share->mutex);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7470 7471
  if (ndb_cache_check_time > 0)
  {
7472
    if (share->commit_count != 0)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7473
    {
7474
      *commit_count= share->commit_count;
7475
#ifndef DBUG_OFF
7476
      char buff[22];
7477
#endif
7478 7479
      DBUG_PRINT("info", ("Getting commit_count: %s from share",
                          llstr(share->commit_count, buff)));
7480
      pthread_mutex_unlock(&share->mutex);
7481 7482 7483
      /* ndb_share reference temporary free */
      DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                               share->key, share->use_count));
7484
      free_share(&share);
7485
      DBUG_RETURN(0);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7486 7487
    }
  }
7488
  DBUG_PRINT("info", ("Get commit_count from NDB"));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7489 7490 7491
  Ndb *ndb;
  if (!(ndb= check_ndb_in_thd(thd)))
    DBUG_RETURN(1);
7492 7493 7494 7495
  if (ndb->setDatabaseName(dbname))
  {
    ERR_RETURN(ndb->getNdbError());
  }
7496 7497
  uint lock= share->commit_count_lock;
  pthread_mutex_unlock(&share->mutex);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7498 7499

  struct Ndb_statistics stat;
7500
  {
7501 7502
    Ndb_table_guard ndbtab_g(ndb->getDictionary(), tabname);
    if (ndbtab_g.get_table() == 0
7503
        || ndb_get_table_statistics(NULL, FALSE, ndb, ndbtab_g.get_table(), &stat))
7504
    {
7505 7506 7507
      /* ndb_share reference temporary free */
      DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                               share->key, share->use_count));
7508 7509 7510
      free_share(&share);
      DBUG_RETURN(1);
    }
7511 7512 7513
  }

  pthread_mutex_lock(&share->mutex);
7514
  if (share->commit_count_lock == lock)
7515
  {
7516
#ifndef DBUG_OFF
7517
    char buff[22];
7518
#endif
7519 7520
    DBUG_PRINT("info", ("Setting commit_count to %s",
                        llstr(stat.commit_count, buff)));
7521 7522 7523 7524 7525 7526 7527 7528 7529
    share->commit_count= stat.commit_count;
    *commit_count= stat.commit_count;
  }
  else
  {
    DBUG_PRINT("info", ("Discarding commit_count, comit_count_lock changed"));
    *commit_count= 0;
  }
  pthread_mutex_unlock(&share->mutex);
7530 7531 7532
  /* ndb_share reference temporary free */
  DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                           share->key, share->use_count));
7533
  free_share(&share);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569
  DBUG_RETURN(0);
}


/*
  Check if a cached query can be used.
  This is done by comparing the supplied engine_data to commit_count of
  the table.
  The commit_count is either retrieved from the share for the table, where
  it has been cached by the util thread. If the util thread is not started,
  NDB has to be contacetd to retrieve the commit_count, this will introduce
  a small delay while waiting for NDB to answer.


  SYNOPSIS
  ndbcluster_cache_retrieval_allowed
    thd            thread handle
    full_name      concatenation of database name,
                   the null character '\0', and the table
                   name
    full_name_len  length of the full name,
                   i.e. len(dbname) + len(tablename) + 1

    engine_data    parameter retrieved when query was first inserted into
                   the cache. If the value of engine_data is changed,
                   all queries for this table should be invalidated.

  RETURN VALUE
    TRUE  Yes, use the query from cache
    FALSE No, don't use the cached query, and if engine_data
          has changed, all queries for this table should be invalidated

*/

static my_bool
ndbcluster_cache_retrieval_allowed(THD *thd,
7570 7571
                                   char *full_name, uint full_name_len,
                                   ulonglong *engine_data)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7572 7573 7574 7575 7576
{
  Uint64 commit_count;
  bool is_autocommit= !(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN));
  char *dbname= full_name;
  char *tabname= dbname+strlen(dbname)+1;
7577
#ifndef DBUG_OFF
7578
  char buff[22], buff2[22];
7579
#endif
7580
  DBUG_ENTER("ndbcluster_cache_retrieval_allowed");
7581 7582
  DBUG_PRINT("enter", ("dbname: %s, tabname: %s, is_autocommit: %d",
                       dbname, tabname, is_autocommit));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7583 7584

  if (!is_autocommit)
7585 7586
  {
    DBUG_PRINT("exit", ("No, don't use cache in transaction"));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7587
    DBUG_RETURN(FALSE);
7588
  }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7589 7590 7591

  if (ndb_get_commitcount(thd, dbname, tabname, &commit_count))
  {
7592 7593
    *engine_data= 0; /* invalidate */
    DBUG_PRINT("exit", ("No, could not retrieve commit_count"));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7594 7595
    DBUG_RETURN(FALSE);
  }
7596 7597
  DBUG_PRINT("info", ("*engine_data: %s, commit_count: %s",
                      llstr(*engine_data, buff), llstr(commit_count, buff2)));
7598
  if (commit_count == 0)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7599
  {
7600 7601
    *engine_data= 0; /* invalidate */
    DBUG_PRINT("exit", ("No, local commit has been performed"));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7602 7603
    DBUG_RETURN(FALSE);
  }
7604 7605 7606 7607 7608 7609
  else if (*engine_data != commit_count)
  {
    *engine_data= commit_count; /* invalidate */
     DBUG_PRINT("exit", ("No, commit_count has changed"));
     DBUG_RETURN(FALSE);
   }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7610

7611 7612
  DBUG_PRINT("exit", ("OK to use cache, engine_data: %s",
                      llstr(*engine_data, buff)));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640
  DBUG_RETURN(TRUE);
}


/**
   Register a table for use in the query cache. Fetch the commit_count
   for the table and return it in engine_data, this will later be used
   to check if the table has changed, before the cached query is reused.

   SYNOPSIS
   ha_ndbcluster::can_query_cache_table
    thd            thread handle
    full_name      concatenation of database name,
                   the null character '\0', and the table
                   name
    full_name_len  length of the full name,
                   i.e. len(dbname) + len(tablename) + 1
    qc_engine_callback  function to be called before using cache on this table
    engine_data    out, commit_count for this table

  RETURN VALUE
    TRUE  Yes, it's ok to cahce this query
    FALSE No, don't cach the query

*/

my_bool
ha_ndbcluster::register_query_cache_table(THD *thd,
7641 7642 7643
                                          char *full_name, uint full_name_len,
                                          qc_engine_callback *engine_callback,
                                          ulonglong *engine_data)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7644
{
7645
  Uint64 commit_count;
7646
#ifndef DBUG_OFF
7647
  char buff[22];
7648
#endif
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7649
  bool is_autocommit= !(thd->options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN));
7650
  DBUG_ENTER("ha_ndbcluster::register_query_cache_table");
7651 7652 7653
  DBUG_PRINT("enter",("dbname: %s, tabname: %s, is_autocommit: %d",
		      m_dbname, m_tabname, is_autocommit));

mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7654
  if (!is_autocommit)
7655
  {
serg@serg.mylan's avatar
serg@serg.mylan committed
7656
    DBUG_PRINT("exit", ("Can't register table during transaction"));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7657
    DBUG_RETURN(FALSE);
7658
  }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7659 7660 7661 7662

  if (ndb_get_commitcount(thd, m_dbname, m_tabname, &commit_count))
  {
    *engine_data= 0;
serg@serg.mylan's avatar
serg@serg.mylan committed
7663
    DBUG_PRINT("exit", ("Error, could not get commitcount"));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7664 7665 7666 7667
    DBUG_RETURN(FALSE);
  }
  *engine_data= commit_count;
  *engine_callback= ndbcluster_cache_retrieval_allowed;
7668
  DBUG_PRINT("exit", ("commit_count: %s", llstr(commit_count, buff)));
7669
  DBUG_RETURN(commit_count > 0);
7670
}
7671

mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7672

7673
/*
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
7674
  Handling the shared NDB_SHARE structure that is needed to
7675 7676 7677 7678 7679 7680
  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.
 */

7681
static byte *ndbcluster_get_key(NDB_SHARE *share,uint *length,
7682
                                my_bool not_used __attribute__((unused)))
7683
{
7684 7685 7686 7687
  *length= share->key_length;
  return (byte*) share->key;
}

7688

7689
#ifndef DBUG_OFF
7690 7691

static void print_share(const char* where, NDB_SHARE* share)
7692
{
7693
  fprintf(DBUG_FILE,
7694
          "%s %s.%s: use_count: %u, commit_count: %lu\n",
7695
          where, share->db, share->table_name, share->use_count,
7696
          (ulong) share->commit_count);
7697 7698 7699 7700
  fprintf(DBUG_FILE,
          "  - key: %s, key_length: %d\n",
          share->key, share->key_length);

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7701
#ifdef HAVE_NDB_BINLOG
7702 7703 7704 7705 7706
  if (share->table)
    fprintf(DBUG_FILE,
            "  - share->table: %p %s.%s\n",
            share->table, share->table->s->db.str,
            share->table->s->table_name.str);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7707
#endif
7708
}
7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721


static void print_ndbcluster_open_tables()
{
  DBUG_LOCK_FILE;
  fprintf(DBUG_FILE, ">ndbcluster_open_tables\n");
  for (uint i= 0; i < ndbcluster_open_tables.records; i++)
    print_share("",
                (NDB_SHARE*)hash_element(&ndbcluster_open_tables, i));
  fprintf(DBUG_FILE, "<ndbcluster_open_tables\n");
  DBUG_UNLOCK_FILE;
}

7722 7723
#endif

7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734

#define dbug_print_open_tables()                \
  DBUG_EXECUTE("info",                          \
               print_ndbcluster_open_tables(););

#define dbug_print_share(t, s)                  \
  DBUG_LOCK_FILE;                               \
  DBUG_EXECUTE("info",                          \
               print_share((t), (s)););         \
  DBUG_UNLOCK_FILE;

7735

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748
#ifdef HAVE_NDB_BINLOG
/*
  For some reason a share is still around, try to salvage the situation
  by closing all cached tables. If the share still exists, there is an
  error somewhere but only report this to the error log.  Keep this
  "trailing share" but rename it since there are still references to it
  to avoid segmentation faults.  There is a risk that the memory for
  this trailing share leaks.
  
  Must be called with previous pthread_mutex_lock(&ndbcluster_mutex)
*/
int handle_trailing_share(NDB_SHARE *share)
{
7749
  THD *thd= current_thd;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7750 7751 7752
  static ulong trailing_share_id= 0;
  DBUG_ENTER("handle_trailing_share");

7753
  /* ndb_share reference temporary, free below */
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7754
  ++share->use_count;
7755 7756
  DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                           share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7757 7758
  pthread_mutex_unlock(&ndbcluster_mutex);

7759 7760 7761 7762
  TABLE_LIST table_list;
  bzero((char*) &table_list,sizeof(table_list));
  table_list.db= share->db;
  table_list.alias= table_list.table_name= share->table_name;
7763
  safe_mutex_assert_owner(&LOCK_open);
7764
  close_cached_tables(thd, 0, &table_list, TRUE);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7765 7766

  pthread_mutex_lock(&ndbcluster_mutex);
7767 7768 7769
  /* ndb_share reference temporary free */
  DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                           share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7770 7771
  if (!--share->use_count)
  {
7772
    if (ndb_extra_logging)
7773 7774
      sql_print_information("NDB_SHARE: trailing share "
                            "%s(connect_count: %u) "
7775 7776 7777 7778 7779 7780
                            "released by close_cached_tables at "
                            "connect_count: %u",
                            share->key,
                            share->connect_count,
                            g_ndb_cluster_connection->get_connect_count());
    ndbcluster_real_free_share(&share);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7781 7782 7783 7784 7785 7786 7787
    DBUG_RETURN(0);
  }

  /*
    share still exists, if share has not been dropped by server
    release that share
  */
7788
  if (share->state != NSS_DROPPED)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7789
  {
7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808
    share->state= NSS_DROPPED;
    /* ndb_share reference create free */
    DBUG_PRINT("NDB_SHARE", ("%s create free  use_count: %u",
                             share->key, share->use_count));
    --share->use_count;

    if (share->use_count == 0)
    {
      if (ndb_extra_logging)
        sql_print_information("NDB_SHARE: trailing share "
                              "%s(connect_count: %u) "
                              "released after NSS_DROPPED check "
                              "at connect_count: %u",
                              share->key,
                              share->connect_count,
                              g_ndb_cluster_connection->get_connect_count());
      ndbcluster_real_free_share(&share);
      DBUG_RETURN(0);
    }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7809 7810 7811 7812 7813 7814 7815
  }

  sql_print_error("NDB_SHARE: %s already exists  use_count=%d."
                  " Moving away for safety, but possible memleak.",
                  share->key, share->use_count);
  dbug_print_open_tables();

7816 7817 7818
  /*
    Ndb share has not been released as it should
  */
7819
#ifdef NOT_YET
7820
  DBUG_ASSERT(FALSE);
7821
#endif
7822

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841
  /*
    This is probably an error.  We can however save the situation
    at the cost of a possible mem leak, by "renaming" the share
    - First remove from hash
  */
  hash_delete(&ndbcluster_open_tables, (byte*) share);

  /*
    now give it a new name, just a running number
    if space is not enough allocate some more
  */
  {
    const uint min_key_length= 10;
    if (share->key_length < min_key_length)
    {
      share->key= alloc_root(&share->mem_root, min_key_length + 1);
      share->key_length= min_key_length;
    }
    share->key_length=
7842
      my_snprintf(share->key, min_key_length + 1, "#leak%lu",
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904
                  trailing_share_id++);
  }
  /* Keep it for possible the future trailing free */
  my_hash_insert(&ndbcluster_open_tables, (byte*) share);

  DBUG_RETURN(0);
}

/*
  Rename share is used during rename table.
*/
static int rename_share(NDB_SHARE *share, const char *new_key)
{
  NDB_SHARE *tmp;
  pthread_mutex_lock(&ndbcluster_mutex);
  uint new_length= (uint) strlen(new_key);
  DBUG_PRINT("rename_share", ("old_key: %s  old__length: %d",
                              share->key, share->key_length));
  if ((tmp= (NDB_SHARE*) hash_search(&ndbcluster_open_tables,
                                     (byte*) new_key, new_length)))
    handle_trailing_share(tmp);

  /* remove the share from hash */
  hash_delete(&ndbcluster_open_tables, (byte*) share);
  dbug_print_open_tables();

  /* save old stuff if insert should fail */
  uint old_length= share->key_length;
  char *old_key= share->key;

  /*
    now allocate and set the new key, db etc
    enough space for key, db, and table_name
  */
  share->key= alloc_root(&share->mem_root, 2 * (new_length + 1));
  strmov(share->key, new_key);
  share->key_length= new_length;

  if (my_hash_insert(&ndbcluster_open_tables, (byte*) share))
  {
    // ToDo free the allocated stuff above?
    DBUG_PRINT("error", ("rename_share: my_hash_insert %s failed",
                         share->key));
    share->key= old_key;
    share->key_length= old_length;
    if (my_hash_insert(&ndbcluster_open_tables, (byte*) share))
    {
      sql_print_error("rename_share: failed to recover %s", share->key);
      DBUG_PRINT("error", ("rename_share: my_hash_insert %s failed",
                           share->key));
    }
    dbug_print_open_tables();
    pthread_mutex_unlock(&ndbcluster_mutex);
    return -1;
  }
  dbug_print_open_tables();

  share->db= share->key + new_length + 1;
  ha_ndbcluster::set_dbname(new_key, share->db);
  share->table_name= share->db + strlen(share->db) + 1;
  ha_ndbcluster::set_tabname(new_key, share->table_name);

7905
  dbug_print_share("rename_share:", share);
7906
  if (share->table)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7907
  {
7908 7909 7910 7911 7912 7913 7914
    if (share->op == 0)
    {
      share->table->s->db.str= share->db;
      share->table->s->db.length= strlen(share->db);
      share->table->s->table_name.str= share->table_name;
      share->table->s->table_name.length= strlen(share->table_name);
    }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7915 7916 7917 7918 7919 7920 7921 7922 7923 7924
  }
  /* else rename will be handled when the ALTER event comes */
  share->old_names= old_key;
  // ToDo free old_names after ALTER EVENT

  pthread_mutex_unlock(&ndbcluster_mutex);
  return 0;
}
#endif

7925 7926 7927 7928
/*
  Increase refcount on existing share.
  Always returns share and cannot fail.
*/
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7929
NDB_SHARE *ndbcluster_get_share(NDB_SHARE *share)
7930 7931
{
  pthread_mutex_lock(&ndbcluster_mutex);
7932 7933 7934
  share->use_count++;

  dbug_print_open_tables();
7935
  dbug_print_share("ndbcluster_get_share:", share);
7936 7937 7938 7939
  pthread_mutex_unlock(&ndbcluster_mutex);
  return share;
}

monty@mysql.com's avatar
monty@mysql.com committed
7940

7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954
/*
  Get a share object for key

  Returns share for key, and increases the refcount on the share.

  create_if_not_exists == TRUE:
    creates share if it does not alreade exist
    returns 0 only due to out of memory, and then sets my_error

  create_if_not_exists == FALSE:
    returns 0 if share does not exist

  have_lock == TRUE, pthread_mutex_lock(&ndbcluster_mutex) already taken
*/
monty@mysql.com's avatar
monty@mysql.com committed
7955

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
7956 7957 7958
NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table,
                                bool create_if_not_exists,
                                bool have_lock)
7959 7960
{
  NDB_SHARE *share;
monty@mysql.com's avatar
monty@mysql.com committed
7961 7962 7963 7964
  uint length= (uint) strlen(key);
  DBUG_ENTER("ndbcluster_get_share");
  DBUG_PRINT("enter", ("key: '%s'", key));

7965 7966 7967 7968 7969
  if (!have_lock)
    pthread_mutex_lock(&ndbcluster_mutex);
  if (!(share= (NDB_SHARE*) hash_search(&ndbcluster_open_tables,
                                        (byte*) key,
                                        length)))
7970
  {
7971 7972 7973 7974 7975
    if (!create_if_not_exists)
    {
      DBUG_PRINT("error", ("get_share: %s does not exist", key));
      if (!have_lock)
        pthread_mutex_unlock(&ndbcluster_mutex);
7976
      DBUG_RETURN(0);
7977 7978
    }
    if ((share= (NDB_SHARE*) my_malloc(sizeof(*share),
7979 7980
                                       MYF(MY_WME | MY_ZEROFILL))))
    {
7981 7982 7983 7984 7985
      MEM_ROOT **root_ptr=
        my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC);
      MEM_ROOT *old_root= *root_ptr;
      init_sql_alloc(&share->mem_root, 1024, 0);
      *root_ptr= &share->mem_root; // remember to reset before return
7986
      share->state= NSS_INITIAL;
7987 7988 7989 7990
      /* enough space for key, db, and table_name */
      share->key= alloc_root(*root_ptr, 2 * (length + 1));
      share->key_length= length;
      strmov(share->key, key);
7991 7992
      if (my_hash_insert(&ndbcluster_open_tables, (byte*) share))
      {
7993 7994 7995 7996 7997
        free_root(&share->mem_root, MYF(0));
        my_free((gptr) share, 0);
        *root_ptr= old_root;
        if (!have_lock)
          pthread_mutex_unlock(&ndbcluster_mutex);
7998
        DBUG_RETURN(0);
7999 8000
      }
      thr_lock_init(&share->lock);
8001
      pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8002
      share->commit_count= 0;
8003
      share->commit_count_lock= 0;
8004 8005 8006 8007
      share->db= share->key + length + 1;
      ha_ndbcluster::set_dbname(key, share->db);
      share->table_name= share->db + strlen(share->db) + 1;
      ha_ndbcluster::set_tabname(key, share->table_name);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8008 8009 8010
#ifdef HAVE_NDB_BINLOG
      ndbcluster_binlog_init_share(share, table);
#endif
8011
      *root_ptr= old_root;
8012 8013 8014
    }
    else
    {
8015 8016 8017 8018
      DBUG_PRINT("error", ("get_share: failed to alloc share"));
      if (!have_lock)
        pthread_mutex_unlock(&ndbcluster_mutex);
      my_error(ER_OUTOFMEMORY, MYF(0), sizeof(*share));
8019
      DBUG_RETURN(0);
8020 8021 8022
    }
  }
  share->use_count++;
8023

8024
  dbug_print_open_tables();
8025
  dbug_print_share("ndbcluster_get_share:", share);
8026 8027
  if (!have_lock)
    pthread_mutex_unlock(&ndbcluster_mutex);
8028
  DBUG_RETURN(share);
8029 8030
}

monty@mysql.com's avatar
monty@mysql.com committed
8031

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8032
void ndbcluster_real_free_share(NDB_SHARE **share)
8033
{
monty@mysql.com's avatar
monty@mysql.com committed
8034
  DBUG_ENTER("ndbcluster_real_free_share");
8035
  dbug_print_share("ndbcluster_real_free_share:", *share);
8036 8037 8038 8039 8040

  hash_delete(&ndbcluster_open_tables, (byte*) *share);
  thr_lock_delete(&(*share)->lock);
  pthread_mutex_destroy(&(*share)->mutex);

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8041 8042 8043
#ifdef HAVE_NDB_BINLOG
  if ((*share)->table)
  {
8044
    // (*share)->table->mem_root is freed by closefrm
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8045
    closefrm((*share)->table, 0);
8046 8047
    // (*share)->table_share->mem_root is freed by free_table_share
    free_table_share((*share)->table_share);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8048 8049 8050 8051 8052 8053 8054 8055
#ifndef DBUG_OFF
    bzero((gptr)(*share)->table_share, sizeof(*(*share)->table_share));
    bzero((gptr)(*share)->table, sizeof(*(*share)->table));
    (*share)->table_share= 0;
    (*share)->table= 0;
#endif
  }
#endif
monty@mysql.com's avatar
monty@mysql.com committed
8056
  free_root(&(*share)->mem_root, MYF(0));
8057 8058 8059 8060
  my_free((gptr) *share, MYF(0));
  *share= 0;

  dbug_print_open_tables();
monty@mysql.com's avatar
monty@mysql.com committed
8061
  DBUG_VOID_RETURN;
8062 8063
}

8064

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8065
void ndbcluster_free_share(NDB_SHARE **share, bool have_lock)
8066
{
8067 8068 8069 8070 8071
  if (!have_lock)
    pthread_mutex_lock(&ndbcluster_mutex);
  if ((*share)->util_lock == current_thd)
    (*share)->util_lock= 0;
  if (!--(*share)->use_count)
8072
  {
8073
    ndbcluster_real_free_share(share);
8074
  }
8075 8076 8077
  else
  {
    dbug_print_open_tables();
8078
    dbug_print_share("ndbcluster_free_share:", *share);
8079 8080 8081
  }
  if (!have_lock)
    pthread_mutex_unlock(&ndbcluster_mutex);
8082 8083 8084
}


8085 8086
static 
int
8087
ndb_get_table_statistics(ha_ndbcluster* file, bool report_error, Ndb* ndb, const NDBTAB *ndbtab,
8088
                         struct Ndb_statistics * ndbstat)
8089
{
8090
  NdbTransaction* pTrans;
8091
  NdbError error;
8092
  int retries= 10;
8093
  int reterr= 0;
8094
  int retry_sleep= 30 * 1000; /* 30 milliseconds */
8095
#ifndef DBUG_OFF
8096
  char buff[22], buff2[22], buff3[22], buff4[22];
8097
#endif
8098
  DBUG_ENTER("ndb_get_table_statistics");
kostja@bodhi.local's avatar
kostja@bodhi.local committed
8099
  DBUG_PRINT("enter", ("table: %s", ndbtab->getName()));
8100

8101 8102
  DBUG_ASSERT(ndbtab != 0);

8103
  do
8104
  {
8105
    Uint64 rows, commits, fixed_mem, var_mem;
8106
    Uint32 size;
8107
    Uint32 count= 0;
8108 8109
    Uint64 sum_rows= 0;
    Uint64 sum_commits= 0;
8110 8111
    Uint64 sum_row_size= 0;
    Uint64 sum_mem= 0;
8112 8113 8114 8115
    NdbScanOperation*pOp;
    int check;

    if ((pTrans= ndb->startTransaction()) == NULL)
8116
    {
8117 8118 8119
      error= ndb->getNdbError();
      goto retry;
    }
8120
      
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8121
    if ((pOp= pTrans->getNdbScanOperation(ndbtab)) == NULL)
8122 8123 8124
    {
      error= pTrans->getNdbError();
      goto retry;
8125
    }
8126
    
8127
    if (pOp->readTuples(NdbOperation::LM_CommittedRead))
8128 8129 8130 8131
    {
      error= pOp->getNdbError();
      goto retry;
    }
8132
    
8133 8134 8135 8136 8137
    if (pOp->interpret_exit_last_row() == -1)
    {
      error= pOp->getNdbError();
      goto retry;
    }
8138 8139 8140
    
    pOp->getValue(NdbDictionary::Column::ROW_COUNT, (char*)&rows);
    pOp->getValue(NdbDictionary::Column::COMMIT_COUNT, (char*)&commits);
8141
    pOp->getValue(NdbDictionary::Column::ROW_SIZE, (char*)&size);
8142 8143 8144 8145
    pOp->getValue(NdbDictionary::Column::FRAGMENT_FIXED_MEMORY, 
		  (char*)&fixed_mem);
    pOp->getValue(NdbDictionary::Column::FRAGMENT_VARSIZED_MEMORY, 
		  (char*)&var_mem);
8146
    
8147
    if (pTrans->execute(NdbTransaction::NoCommit,
8148
                        NdbOperation::AbortOnError,
8149
                        TRUE) == -1)
8150
    {
8151 8152
      error= pTrans->getNdbError();
      goto retry;
8153
    }
8154
    
monty@mishka.local's avatar
monty@mishka.local committed
8155
    while ((check= pOp->nextResult(TRUE, TRUE)) == 0)
8156 8157 8158
    {
      sum_rows+= rows;
      sum_commits+= commits;
8159
      if (sum_row_size < size)
8160
        sum_row_size= size;
8161
      sum_mem+= fixed_mem + var_mem;
8162
      count++;
8163 8164 8165
    }
    
    if (check == -1)
8166 8167 8168 8169
    {
      error= pOp->getNdbError();
      goto retry;
    }
8170

8171
    pOp->close(TRUE);
8172

8173
    ndb->closeTransaction(pTrans);
8174 8175 8176 8177 8178 8179

    ndbstat->row_count= sum_rows;
    ndbstat->commit_count= sum_commits;
    ndbstat->row_size= sum_row_size;
    ndbstat->fragment_memory= sum_mem;

8180 8181 8182 8183 8184 8185 8186
    DBUG_PRINT("exit", ("records: %s  commits: %s "
                        "row_size: %s  mem: %s count: %u",
			llstr(sum_rows, buff),
                        llstr(sum_commits, buff2),
                        llstr(sum_row_size, buff3),
                        llstr(sum_mem, buff4),
                        count));
8187

8188
    DBUG_RETURN(0);
8189
retry:
8190 8191
    if(report_error)
    {
8192
      if (file && pTrans)
8193 8194 8195 8196 8197 8198 8199 8200 8201 8202
      {
        reterr= file->ndb_err(pTrans);
      }
      else
      {
        const NdbError& tmp= error;
        ERR_PRINT(tmp);
        reterr= ndb_to_mysql_error(&tmp);
      }
    }
8203 8204 8205
    else
      reterr= error.code;

8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216
    if (pTrans)
    {
      ndb->closeTransaction(pTrans);
      pTrans= NULL;
    }
    if (error.status == NdbError::TemporaryError && retries--)
    {
      my_sleep(retry_sleep);
      continue;
    }
    break;
8217
  } while(1);
8218 8219 8220
  DBUG_PRINT("exit", ("failed, reterr: %u, NdbError %u(%s)", reterr,
                      error.code, error.message));
  DBUG_RETURN(reterr);
8221 8222
}

8223 8224 8225 8226 8227
/*
  Create a .ndb file to serve as a placeholder indicating 
  that the table with this name is a ndb table
*/

8228
int ha_ndbcluster::write_ndb_file(const char *name)
8229 8230 8231 8232 8233 8234
{
  File file;
  bool error=1;
  char path[FN_REFLEN];
  
  DBUG_ENTER("write_ndb_file");
8235
  DBUG_PRINT("enter", ("name: %s", name));
8236

8237
  (void)strxnmov(path, FN_REFLEN-1, 
8238
                 mysql_data_home,"/",name,ha_ndb_ext,NullS);
8239 8240 8241 8242 8243 8244 8245 8246 8247 8248

  if ((file=my_create(path, CREATE_MODE,O_RDWR | O_TRUNC,MYF(MY_WME))) >= 0)
  {
    // It's an empty file
    error=0;
    my_close(file,MYF(0));
  }
  DBUG_RETURN(error);
}

8249
void 
8250 8251
ha_ndbcluster::release_completed_operations(NdbTransaction *trans,
					    bool force_release)
8252 8253 8254 8255 8256 8257 8258 8259
{
  if (trans->hasBlobOperation())
  {
    /* We are reading/writing BLOB fields, 
       releasing operation records is unsafe
    */
    return;
  }
8260 8261 8262 8263 8264 8265 8266 8267 8268 8269
  if (!force_release)
  {
    if (get_thd_ndb(current_thd)->query_state & NDB_QUERY_MULTI_READ_RANGE)
    {
      /* We are batching reads and have not consumed all fetched
	 rows yet, releasing operation records is unsafe 
      */
      return;
    }
  }
8270
  trans->releaseCompletedOperations();
8271 8272
}

8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290
bool 
ha_ndbcluster::null_value_index_search(KEY_MULTI_RANGE *ranges,
				       KEY_MULTI_RANGE *end_range,
				       HANDLER_BUFFER *buffer)
{
  DBUG_ENTER("null_value_index_search");
  KEY* key_info= table->key_info + active_index;
  KEY_MULTI_RANGE *range= ranges;
  ulong reclength= table->s->reclength;
  byte *curr= (byte*)buffer->buffer;
  byte *end_of_buffer= (byte*)buffer->buffer_end;
  
  for (; range<end_range && curr+reclength <= end_of_buffer; 
       range++)
  {
    const byte *key= range->start_key.key;
    uint key_len= range->start_key.length;
    if (check_null_in_key(key_info, key, key_len))
8291
      DBUG_RETURN(TRUE);
8292 8293
    curr += reclength;
  }
8294
  DBUG_RETURN(FALSE);
8295 8296
}

8297
int
8298
ha_ndbcluster::read_multi_range_first(KEY_MULTI_RANGE **found_range_p,
8299 8300 8301 8302
                                      KEY_MULTI_RANGE *ranges, 
                                      uint range_count,
                                      bool sorted, 
                                      HANDLER_BUFFER *buffer)
8303
{
8304
  m_write_op= FALSE;
8305 8306
  int res;
  KEY* key_info= table->key_info + active_index;
8307
  NDB_INDEX_TYPE cur_index_type= get_index_type(active_index);
8308
  ulong reclength= table_share->reclength;
8309
  NdbOperation* op;
8310
  Thd_ndb *thd_ndb= get_thd_ndb(current_thd);
8311
  DBUG_ENTER("ha_ndbcluster::read_multi_range_first");
8312

8313 8314 8315 8316
  /**
   * blobs and unique hash index with NULL can't be batched currently
   */
  if (uses_blob_value() ||
8317
      (cur_index_type ==  UNIQUE_INDEX &&
8318 8319
       has_null_in_unique_index(active_index) &&
       null_value_index_search(ranges, ranges+range_count, buffer)))
8320
  {
8321
    m_disable_multi_read= TRUE;
8322
    DBUG_RETURN(handler::read_multi_range_first(found_range_p, 
8323 8324 8325 8326
                                                ranges, 
                                                range_count,
                                                sorted, 
                                                buffer));
8327
  }
8328
  thd_ndb->query_state|= NDB_QUERY_MULTI_READ_RANGE;
8329
  m_disable_multi_read= FALSE;
8330 8331 8332 8333

  /**
   * Copy arguments into member variables
   */
8334 8335 8336
  m_multi_ranges= ranges;
  multi_range_curr= ranges;
  multi_range_end= ranges+range_count;
8337 8338 8339
  multi_range_sorted= sorted;
  multi_range_buffer= buffer;

8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350
  /**
   * read multi range will read ranges as follows (if not ordered)
   *
   * input    read order
   * ======   ==========
   * pk-op 1  pk-op 1
   * pk-op 2  pk-op 2
   * range 3  range (3,5) NOTE result rows will be intermixed
   * pk-op 4  pk-op 4
   * range 5
   * pk-op 6  pk-ok 6
8351 8352
   */   

mskold@mysql.com's avatar
mskold@mysql.com committed
8353
  /**
8354 8355
   * Variables for loop
   */
8356 8357
  byte *curr= (byte*)buffer->buffer;
  byte *end_of_buffer= (byte*)buffer->buffer_end;
8358 8359
  NdbOperation::LockMode lm= 
    (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type);
mskold@mysql.com's avatar
mskold@mysql.com committed
8360
  bool need_pk = (lm == NdbOperation::LM_Read);
8361 8362 8363
  const NDBTAB *tab= m_table;
  const NDBINDEX *unique_idx= m_index[active_index].unique_index;
  const NDBINDEX *idx= m_index[active_index].index; 
8364 8365
  const NdbOperation* lastOp= m_active_trans->getLastDefinedOperation();
  NdbIndexScanOperation* scanOp= 0;
8366 8367
  for (; multi_range_curr<multi_range_end && curr+reclength <= end_of_buffer; 
       multi_range_curr++)
8368
  {
8369 8370 8371 8372 8373 8374
    part_id_range part_spec;
    if (m_use_partition_function)
    {
      get_partition_set(table, curr, active_index,
                        &multi_range_curr->start_key,
                        &part_spec);
8375
      DBUG_PRINT("info", ("part_spec.start_part: %u  part_spec.end_part: %u",
8376 8377 8378 8379 8380
                          part_spec.start_part, part_spec.end_part));
      /*
        If partition pruning has found no partition in set
        we can skip this scan
      */
8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391
      if (part_spec.start_part > part_spec.end_part)
      {
        /*
          We can skip this partition since the key won't fit into any
          partition
        */
        curr += reclength;
        multi_range_curr->range_flag |= SKIP_RANGE;
        continue;
      }
    }
8392
    switch (cur_index_type) {
8393 8394
    case PRIMARY_KEY_ORDERED_INDEX:
      if (!(multi_range_curr->start_key.length == key_info->key_length &&
8395 8396 8397
          multi_range_curr->start_key.flag == HA_READ_KEY_EXACT))
        goto range;
      // else fall through
8398
    case PRIMARY_KEY_INDEX:
8399
    {
8400
      multi_range_curr->range_flag |= UNIQUE_RANGE;
8401
      if ((op= m_active_trans->getNdbOperation(tab)) && 
8402 8403 8404
          !op->readTuple(lm) && 
          !set_primary_key(op, multi_range_curr->start_key.key) &&
          !define_read_attrs(curr, op) &&
8405
          (!m_use_partition_function ||
8406
           (op->setPartitionId(part_spec.start_part), TRUE)))
8407
        curr += reclength;
8408
      else
8409
        ERR_RETURN(op ? op->getNdbError() : m_active_trans->getNdbError());
8410
      break;
8411 8412
    }
    break;
8413 8414
    case UNIQUE_ORDERED_INDEX:
      if (!(multi_range_curr->start_key.length == key_info->key_length &&
8415 8416 8417 8418 8419
          multi_range_curr->start_key.flag == HA_READ_KEY_EXACT &&
          !check_null_in_key(key_info, multi_range_curr->start_key.key,
                             multi_range_curr->start_key.length)))
        goto range;
      // else fall through
8420
    case UNIQUE_INDEX:
8421
    {
8422
      multi_range_curr->range_flag |= UNIQUE_RANGE;
8423
      if ((op= m_active_trans->getNdbIndexOperation(unique_idx, tab)) && 
8424 8425
          !op->readTuple(lm) && 
          !set_index_key(op, key_info, multi_range_curr->start_key.key) &&
8426
          !define_read_attrs(curr, op))
8427
        curr += reclength;
8428
      else
8429
        ERR_RETURN(op ? op->getNdbError() : m_active_trans->getNdbError());
8430 8431
      break;
    }
8432
    case ORDERED_INDEX: {
8433
  range:
8434
      multi_range_curr->range_flag &= ~(uint)UNIQUE_RANGE;
8435 8436
      if (scanOp == 0)
      {
8437 8438 8439 8440 8441 8442
        if (m_multi_cursor)
        {
          scanOp= m_multi_cursor;
          DBUG_ASSERT(scanOp->getSorted() == sorted);
          DBUG_ASSERT(scanOp->getLockMode() == 
                      (NdbOperation::LockMode)get_ndb_lock_type(m_lock.type));
8443
          if (scanOp->reset_bounds(m_force_send))
8444 8445 8446 8447 8448
            DBUG_RETURN(ndb_err(m_active_trans));
          
          end_of_buffer -= reclength;
        }
        else if ((scanOp= m_active_trans->getNdbIndexScanOperation(idx, tab)) 
mskold@mysql.com's avatar
mskold@mysql.com committed
8449
                 &&!scanOp->readTuples(lm, 0, parallelism, sorted, 
8450
				       FALSE, TRUE, need_pk, TRUE)
8451
                 &&!(m_cond && m_cond->generate_scan_filter(scanOp))
8452 8453 8454 8455 8456 8457 8458 8459 8460 8461
                 &&!define_read_attrs(end_of_buffer-reclength, scanOp))
        {
          m_multi_cursor= scanOp;
          m_multi_range_cursor_result_ptr= end_of_buffer-reclength;
        }
        else
        {
          ERR_RETURN(scanOp ? scanOp->getNdbError() : 
                     m_active_trans->getNdbError());
        }
8462
      }
8463

8464
      const key_range *keys[2]= { &multi_range_curr->start_key, 
8465
                                  &multi_range_curr->end_key };
8466
      if ((res= set_bounds(scanOp, active_index, FALSE, keys,
8467
                           multi_range_curr-ranges)))
8468
        DBUG_RETURN(res);
8469
      break;
8470
    }
8471
    case UNDEFINED_INDEX:
mskold@mysql.com's avatar
mskold@mysql.com committed
8472 8473 8474 8475
      DBUG_ASSERT(FALSE);
      DBUG_RETURN(1);
      break;
    }
8476 8477
  }
  
8478
  if (multi_range_curr != multi_range_end)
8479
  {
8480 8481 8482 8483 8484 8485
    /**
     * Mark that we're using entire buffer (even if might not) as
     *   we haven't read all ranges for some reason
     * This as we don't want mysqld to reuse the buffer when we read
     *   the remaining ranges
     */
8486
    buffer->end_of_used_area= (byte*)buffer->buffer_end;
8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497
  }
  else
  {
    buffer->end_of_used_area= curr;
  }
  
  /**
   * Set first operation in multi range
   */
  m_current_multi_operation= 
    lastOp ? lastOp->next() : m_active_trans->getFirstDefinedOperation();
8498
  if (!(res= execute_no_commit_ie(this, m_active_trans,true)))
8499
  {
8500 8501
    m_multi_range_defined= multi_range_curr;
    multi_range_curr= ranges;
8502 8503
    m_multi_range_result_ptr= (byte*)buffer->buffer;
    DBUG_RETURN(read_multi_range_next(found_range_p));
8504 8505 8506 8507
  }
  ERR_RETURN(m_active_trans->getNdbError());
}

8508
#if 0
8509
#define DBUG_MULTI_RANGE(x) DBUG_PRINT("info", ("read_multi_range_next: case %d\n", x));
8510 8511 8512 8513
#else
#define DBUG_MULTI_RANGE(x)
#endif

8514
int
8515
ha_ndbcluster::read_multi_range_next(KEY_MULTI_RANGE ** multi_range_found_p)
8516 8517
{
  DBUG_ENTER("ha_ndbcluster::read_multi_range_next");
8518
  if (m_disable_multi_read)
8519
  {
8520
    DBUG_MULTI_RANGE(11);
8521
    DBUG_RETURN(handler::read_multi_range_next(multi_range_found_p));
8522
  }
8523
  
8524
  int res;
8525
  int range_no;
8526
  ulong reclength= table_share->reclength;
8527
  const NdbOperation* op= m_current_multi_operation;
8528
  for (;multi_range_curr < m_multi_range_defined; multi_range_curr++)
8529
  {
8530 8531 8532
    DBUG_MULTI_RANGE(12);
    if (multi_range_curr->range_flag & SKIP_RANGE)
      continue;
8533
    if (multi_range_curr->range_flag & UNIQUE_RANGE)
8534
    {
8535
      if (op->getNdbError().code == 0)
8536 8537
      {
        DBUG_MULTI_RANGE(13);
8538
        goto found_next;
8539
      }
8540 8541 8542
      
      op= m_active_trans->getNextCompletedOperation(op);
      m_multi_range_result_ptr += reclength;
8543
      continue;
8544
    } 
8545
    else if (m_multi_cursor && !multi_range_sorted)
8546
    {
8547 8548
      DBUG_MULTI_RANGE(1);
      if ((res= fetch_next(m_multi_cursor)) == 0)
8549
      {
8550 8551 8552
        DBUG_MULTI_RANGE(2);
        range_no= m_multi_cursor->get_range_no();
        goto found;
8553 8554 8555
      } 
      else
      {
8556
        DBUG_MULTI_RANGE(14);
8557
        goto close_scan;
8558 8559
      }
    }
8560
    else if (m_multi_cursor && multi_range_sorted)
8561
    {
8562 8563
      if (m_active_cursor && (res= fetch_next(m_multi_cursor)))
      {
8564 8565
        DBUG_MULTI_RANGE(3);
        goto close_scan;
8566
      }
8567
      
8568
      range_no= m_multi_cursor->get_range_no();
8569
      uint current_range_no= multi_range_curr - m_multi_ranges;
mskold@mysql.com's avatar
mskold@mysql.com committed
8570
      if ((uint) range_no == current_range_no)
8571
      {
8572
        DBUG_MULTI_RANGE(4);
8573
        // return current row
8574
        goto found;
8575
      }
8576
      else if (range_no > (int)current_range_no)
8577
      {
8578 8579 8580 8581
        DBUG_MULTI_RANGE(5);
        // wait with current row
        m_active_cursor= 0;
        continue;
8582 8583 8584
      }
      else 
      {
8585 8586 8587
        DBUG_MULTI_RANGE(6);
        // First fetch from cursor
        DBUG_ASSERT(range_no == -1);
8588
        if ((res= m_multi_cursor->nextResult(TRUE)))
8589
        {
8590
          DBUG_MULTI_RANGE(15);
8591 8592 8593 8594
          goto close_scan;
        }
        multi_range_curr--; // Will be increased in for-loop
        continue;
8595
      }
8596
    }
8597
    else /** m_multi_cursor == 0 */
8598
    {
8599
      DBUG_MULTI_RANGE(7);
8600 8601 8602 8603
      /**
       * Corresponds to range 5 in example in read_multi_range_first
       */
      (void)1;
8604
      continue;
8605
    }
8606
    
8607
    DBUG_ASSERT(FALSE); // Should only get here via goto's
8608 8609 8610
close_scan:
    if (res == 1)
    {
8611
      m_multi_cursor->close(FALSE, TRUE);
8612
      m_active_cursor= m_multi_cursor= 0;
8613
      DBUG_MULTI_RANGE(8);
8614 8615 8616 8617
      continue;
    } 
    else 
    {
8618
      DBUG_MULTI_RANGE(9);
8619 8620 8621
      DBUG_RETURN(ndb_err(m_active_trans));
    }
  }
8622
  
8623
  if (multi_range_curr == multi_range_end)
8624 8625
  {
    DBUG_MULTI_RANGE(16);
8626 8627
    Thd_ndb *thd_ndb= get_thd_ndb(current_thd);
    thd_ndb->query_state&= NDB_QUERY_NORMAL;
8628
    DBUG_RETURN(HA_ERR_END_OF_FILE);
8629
  }
8630
  
8631 8632 8633 8634
  /**
   * Read remaining ranges
   */
  DBUG_RETURN(read_multi_range_first(multi_range_found_p, 
8635 8636 8637 8638
                                     multi_range_curr,
                                     multi_range_end - multi_range_curr, 
                                     multi_range_sorted,
                                     multi_range_buffer));
8639 8640
  
found:
8641 8642 8643
  /**
   * Found a record belonging to a scan
   */
8644
  m_active_cursor= m_multi_cursor;
8645
  * multi_range_found_p= m_multi_ranges + range_no;
8646 8647
  memcpy(table->record[0], m_multi_range_cursor_result_ptr, reclength);
  setup_recattr(m_active_cursor->getFirstRecAttr());
8648 8649 8650
  unpack_record(table->record[0]);
  table->status= 0;     
  DBUG_RETURN(0);
8651
  
8652
found_next:
8653 8654 8655 8656
  /**
   * Found a record belonging to a pk/index op,
   *   copy result and move to next to prepare for next call
   */
8657
  * multi_range_found_p= multi_range_curr;
8658
  memcpy(table->record[0], m_multi_range_result_ptr, reclength);
8659
  setup_recattr(op->getFirstRecAttr());
8660
  unpack_record(table->record[0]);
8661 8662
  table->status= 0;
  
8663
  multi_range_curr++;
8664
  m_current_multi_operation= m_active_trans->getNextCompletedOperation(op);
8665 8666
  m_multi_range_result_ptr += reclength;
  DBUG_RETURN(0);
8667 8668
}

8669 8670 8671 8672 8673 8674 8675 8676
int
ha_ndbcluster::setup_recattr(const NdbRecAttr* curr)
{
  DBUG_ENTER("setup_recattr");

  Field **field, **end;
  NdbValue *value= m_value;
  
8677
  end= table->field + table_share->fields;
8678 8679 8680 8681 8682 8683
  
  for (field= table->field; field < end; field++, value++)
  {
    if ((* value).ptr)
    {
      DBUG_ASSERT(curr != 0);
8684 8685 8686
      NdbValue* val= m_value + curr->getColumn()->getColumnNo();
      DBUG_ASSERT(val->ptr);
      val->rec= curr;
8687
      curr= curr->next();
8688 8689 8690
    }
  }
  
8691
  DBUG_RETURN(0);
8692 8693
}

mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8694 8695
char*
ha_ndbcluster::update_table_comment(
8696 8697
                                /* out: table comment + additional */
        const char*     comment)/* in:  table comment defined by user */
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8698 8699
{
  uint length= strlen(comment);
8700
  if (length > 64000 - 3)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8701 8702 8703 8704 8705 8706 8707 8708 8709 8710
  {
    return((char*)comment); /* string too long */
  }

  Ndb* ndb;
  if (!(ndb= get_ndb()))
  {
    return((char*)comment);
  }

8711 8712 8713 8714
  if (ndb->setDatabaseName(m_dbname))
  {
    return((char*)comment);
  }
8715 8716
  const NDBTAB* tab= m_table;
  DBUG_ASSERT(tab != NULL);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8717 8718 8719 8720 8721 8722

  char *str;
  const char *fmt="%s%snumber_of_replicas: %d";
  const unsigned fmt_len_plus_extra= length + strlen(fmt);
  if ((str= my_malloc(fmt_len_plus_extra, MYF(0))) == NULL)
  {
8723 8724
    sql_print_error("ha_ndbcluster::update_table_comment: "
                    "my_malloc(%u) failed", (unsigned int)fmt_len_plus_extra);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8725 8726 8727
    return (char*)comment;
  }

8728 8729 8730
  my_snprintf(str,fmt_len_plus_extra,fmt,comment,
              length > 0 ? " ":"",
              tab->getReplicaCount());
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8731 8732 8733 8734 8735
  return str;
}


// Utility thread main loop
8736
pthread_handler_t ndb_util_thread_func(void *arg __attribute__((unused)))
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8737 8738 8739
{
  THD *thd; /* needs to be first for thread_stack */
  struct timespec abstime;
8740
  Thd_ndb *thd_ndb;
8741 8742
  uint share_list_size= 0;
  NDB_SHARE **share_list= NULL;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8743 8744 8745

  my_thread_init();
  DBUG_ENTER("ndb_util_thread");
8746
  DBUG_PRINT("enter", ("ndb_cache_check_time: %lu", ndb_cache_check_time));
8747 8748
 
   pthread_mutex_lock(&LOCK_ndb_util_thread);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8749 8750

  thd= new THD; /* note that contructor of THD uses DBUG_ */
8751 8752 8753 8754 8755
  if (thd == NULL)
  {
    my_errno= HA_ERR_OUT_OF_MEM;
    DBUG_RETURN(NULL);
  }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8756 8757 8758 8759 8760
  THD_CHECK_SENTRY(thd);
  pthread_detach_this_thread();
  ndb_util_thread= pthread_self();

  thd->thread_stack= (char*)&thd; /* remember where our stack is */
8761
  if (thd->store_globals())
8762
    goto ndb_util_thread_fail;
8763 8764 8765 8766 8767 8768 8769
  thd->init_for_queries();
  thd->version=refresh_version;
  thd->main_security_ctx.host_or_ip= "";
  thd->client_capabilities = 0;
  my_net_init(&thd->net, 0);
  thd->main_security_ctx.master_access= ~0;
  thd->main_security_ctx.priv_user = 0;
8770
  thd->current_stmt_binlog_row_based= TRUE;     // If in mixed mode
8771

8772
  /* Signal successful initialization */
8773
  ndb_util_thread_running= 1;
8774 8775
  pthread_cond_signal(&COND_ndb_util_ready);
  pthread_mutex_unlock(&LOCK_ndb_util_thread);
8776

8777 8778 8779 8780 8781
  /*
    wait for mysql server to start
  */
  pthread_mutex_lock(&LOCK_server_started);
  while (!mysqld_server_started)
8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792
  {
    set_timespec(abstime, 1);
    pthread_cond_timedwait(&COND_server_started, &LOCK_server_started,
	                       &abstime);
    if (ndbcluster_terminating)
    {
      pthread_mutex_unlock(&LOCK_server_started);
      pthread_mutex_lock(&LOCK_ndb_util_thread);
      goto ndb_util_thread_end;
    }
  }
8793 8794 8795 8796 8797 8798
  pthread_mutex_unlock(&LOCK_server_started);

  /*
    Wait for cluster to start
  */
  pthread_mutex_lock(&LOCK_ndb_util_thread);
8799
  while (!ndb_cluster_node_id && (ndbcluster_hton->slot != ~(uint)0))
8800 8801
  {
    /* ndb not connected yet */
8802 8803
    pthread_cond_wait(&COND_ndb_util_thread, &LOCK_ndb_util_thread);
    if (ndbcluster_terminating)
8804 8805 8806 8807
      goto ndb_util_thread_end;
  }
  pthread_mutex_unlock(&LOCK_ndb_util_thread);

8808 8809
  /* Get thd_ndb for this thread */
  if (!(thd_ndb= ha_ndbcluster::seize_thd_ndb()))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8810
  {
8811
    sql_print_error("Could not allocate Thd_ndb object");
8812
    pthread_mutex_lock(&LOCK_ndb_util_thread);
8813
    goto ndb_util_thread_end;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8814
  }
8815 8816
  set_thd_ndb(thd, thd_ndb);
  thd_ndb->options|= TNO_NO_LOG_SCHEMA_OP;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8817 8818

#ifdef HAVE_NDB_BINLOG
8819 8820
  if (ndb_extra_logging && ndb_binlog_running)
    sql_print_information("NDB Binlog: Ndb tables initially read only.");
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8821 8822 8823
  /* create tables needed by the replication */
  ndbcluster_setup_binlog_table_shares(thd);
#else
8824 8825 8826 8827
  /*
    Get all table definitions from the storage node
  */
  ndbcluster_find_all_files(thd);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8828
#endif
8829

8830
  set_timespec(abstime, 0);
8831
  for (;;)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8832 8833
  {
    pthread_mutex_lock(&LOCK_ndb_util_thread);
8834 8835 8836 8837 8838 8839
    if (!ndbcluster_terminating)
      pthread_cond_timedwait(&COND_ndb_util_thread,
                             &LOCK_ndb_util_thread,
                             &abstime);
    if (ndbcluster_terminating) /* Shutting down server */
      goto ndb_util_thread_end;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8840
    pthread_mutex_unlock(&LOCK_ndb_util_thread);
8841
#ifdef NDB_EXTRA_DEBUG_UTIL_THREAD
8842
    DBUG_PRINT("ndb_util_thread", ("Started, ndb_cache_check_time: %lu",
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8843
                                   ndb_cache_check_time));
8844
#endif
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8845

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8846 8847
#ifdef HAVE_NDB_BINLOG
    /*
8848 8849
      Check that the ndb_apply_status_share and ndb_schema_share 
      have been created.
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8850 8851
      If not try to create it
    */
8852
    if (!ndb_binlog_tables_inited)
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8853 8854 8855
      ndbcluster_setup_binlog_table_shares(thd);
#endif

mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8856 8857
    if (ndb_cache_check_time == 0)
    {
8858 8859
      /* Wake up in 1 second to check if value has changed */
      set_timespec(abstime, 1);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8860 8861 8862 8863 8864 8865
      continue;
    }

    /* Lock mutex and fill list with pointers to all open tables */
    NDB_SHARE *share;
    pthread_mutex_lock(&ndbcluster_mutex);
8866
    uint i, open_count, record_count= ndbcluster_open_tables.records;
8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880
    if (share_list_size < record_count)
    {
      NDB_SHARE ** new_share_list= new NDB_SHARE * [record_count];
      if (!new_share_list)
      {
        sql_print_warning("ndb util thread: malloc failure, "
                          "query cache not maintained properly");
        pthread_mutex_unlock(&ndbcluster_mutex);
        goto next;                               // At least do not crash
      }
      delete [] share_list;
      share_list_size= record_count;
      share_list= new_share_list;
    }
8881
    for (i= 0, open_count= 0; i < record_count; i++)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8882 8883
    {
      share= (NDB_SHARE *)hash_element(&ndbcluster_open_tables, i);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8884 8885 8886 8887 8888 8889
#ifdef HAVE_NDB_BINLOG
      if ((share->use_count - (int) (share->op != 0) - (int) (share->op != 0))
          <= 0)
        continue; // injector thread is the only user, skip statistics
      share->util_lock= current_thd; // Mark that util thread has lock
#endif /* HAVE_NDB_BINLOG */
8890
      /* ndb_share reference temporary, free below */
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8891
      share->use_count++; /* Make sure the table can't be closed */
8892 8893
      DBUG_PRINT("NDB_SHARE", ("%s temporary  use_count: %u",
                               share->key, share->use_count));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8894 8895 8896 8897 8898
      DBUG_PRINT("ndb_util_thread",
                 ("Found open table[%d]: %s, use_count: %d",
                  i, share->table_name, share->use_count));

      /* Store pointer to table */
8899
      share_list[open_count++]= share;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8900 8901 8902
    }
    pthread_mutex_unlock(&ndbcluster_mutex);

8903
    /* Iterate through the open files list */
8904
    for (i= 0; i < open_count; i++)
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8905
    {
8906
      share= share_list[i];
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8907 8908 8909 8910 8911 8912 8913
#ifdef HAVE_NDB_BINLOG
      if ((share->use_count - (int) (share->op != 0) - (int) (share->op != 0))
          <= 1)
      {
        /*
          Util thread and injector thread is the only user, skip statistics
	*/
8914 8915 8916
        /* ndb_share reference temporary free */
        DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                                 share->key, share->use_count));
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
8917 8918 8919 8920
        free_share(&share);
        continue;
      }
#endif /* HAVE_NDB_BINLOG */
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8921
      DBUG_PRINT("ndb_util_thread",
8922
                 ("Fetching commit count for: %s", share->key));
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8923

8924 8925 8926 8927 8928
      struct Ndb_statistics stat;
      uint lock;
      pthread_mutex_lock(&share->mutex);
      lock= share->commit_count_lock;
      pthread_mutex_unlock(&share->mutex);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8929
      {
8930 8931
        /* Contact NDB to get commit count for table */
        Ndb* ndb= thd_ndb->ndb;
8932 8933 8934 8935
        if (ndb->setDatabaseName(share->db))
        {
          goto loop_next;
        }
8936 8937
        Ndb_table_guard ndbtab_g(ndb->getDictionary(), share->table_name);
        if (ndbtab_g.get_table() &&
8938
            ndb_get_table_statistics(NULL, FALSE, ndb,
8939
                                     ndbtab_g.get_table(), &stat) == 0)
8940
        {
8941
#ifndef DBUG_OFF
8942
          char buff[22], buff2[22];
8943
#endif
8944 8945
          DBUG_PRINT("info",
                     ("Table: %s  commit_count: %s  rows: %s",
8946 8947
                      share->key,
                      llstr(stat.commit_count, buff),
kostja@bodhi.local's avatar
kostja@bodhi.local committed
8948
                      llstr(stat.row_count, buff2)));
8949 8950 8951 8952 8953 8954 8955 8956
        }
        else
        {
          DBUG_PRINT("ndb_util_thread",
                     ("Error: Could not get commit count for table %s",
                      share->key));
          stat.commit_count= 0;
        }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8957
      }
8958
  loop_next:
8959 8960 8961 8962 8963
      pthread_mutex_lock(&share->mutex);
      if (share->commit_count_lock == lock)
        share->commit_count= stat.commit_count;
      pthread_mutex_unlock(&share->mutex);

8964 8965 8966
      /* ndb_share reference temporary free */
      DBUG_PRINT("NDB_SHARE", ("%s temporary free  use_count: %u",
                               share->key, share->use_count));
8967
      free_share(&share);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8968
    }
8969
next:
8970 8971 8972 8973 8974 8975 8976 8977 8978
    /* Calculate new time to wake up */
    int secs= 0;
    int msecs= ndb_cache_check_time;

    struct timeval tick_time;
    gettimeofday(&tick_time, 0);
    abstime.tv_sec=  tick_time.tv_sec;
    abstime.tv_nsec= tick_time.tv_usec * 1000;

8979
    if (msecs >= 1000){
8980 8981 8982 8983 8984 8985 8986 8987 8988 8989
      secs=  msecs / 1000;
      msecs= msecs % 1000;
    }

    abstime.tv_sec+=  secs;
    abstime.tv_nsec+= msecs * 1000000;
    if (abstime.tv_nsec >= 1000000000) {
      abstime.tv_sec+=  1;
      abstime.tv_nsec-= 1000000000;
    }
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8990
  }
8991 8992 8993

  pthread_mutex_lock(&LOCK_ndb_util_thread);

8994 8995
ndb_util_thread_end:
  net_end(&thd->net);
8996
ndb_util_thread_fail:
8997 8998
  if (share_list)
    delete [] share_list;
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
8999 9000
  thd->cleanup();
  delete thd;
9001 9002
  
  /* signal termination */
9003
  ndb_util_thread_running= 0;
9004
  pthread_cond_signal(&COND_ndb_util_ready);
9005
  pthread_mutex_unlock(&LOCK_ndb_util_thread);
mskold@mysql.com's avatar
Merge  
mskold@mysql.com committed
9006 9007 9008 9009 9010 9011
  DBUG_PRINT("exit", ("ndb_util_thread"));
  my_thread_end();
  pthread_exit(0);
  DBUG_RETURN(NULL);
}

9012 9013 9014
/*
  Condition pushdown
*/
9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031
/*
  Push a condition to ndbcluster storage engine for evaluation 
  during table   and index scans. The conditions will be stored on a stack
  for possibly storing several conditions. The stack can be popped
  by calling cond_pop, handler::extra(HA_EXTRA_RESET) (handler::reset())
  will clear the stack.
  The current implementation supports arbitrary AND/OR nested conditions
  with comparisons between columns and constants (including constant
  expressions and function calls) and the following comparison operators:
  =, !=, >, >=, <, <=, "is null", and "is not null".
  
  RETURN
    NULL The condition was supported and will be evaluated for each 
    row found during the scan
    cond The condition was not supported and all rows will be returned from
         the scan for evaluation (and thus not saved on stack)
*/
9032 9033 9034 9035 9036
const 
COND* 
ha_ndbcluster::cond_push(const COND *cond) 
{ 
  DBUG_ENTER("cond_push");
9037 9038 9039
  if (!m_cond) 
    m_cond= new ha_ndbcluster_cond;
  if (!m_cond)
9040 9041 9042 9043
  {
    my_errno= HA_ERR_OUT_OF_MEM;
    DBUG_RETURN(NULL);
  }
9044
  DBUG_EXECUTE("where",print_where((COND *)cond, m_tabname););
9045
  DBUG_RETURN(m_cond->cond_push(cond, table, (NDBTAB *)m_table));
9046 9047
}

9048 9049 9050
/*
  Pop the top condition from the condition stack of the handler instance.
*/
9051 9052 9053
void 
ha_ndbcluster::cond_pop() 
{ 
9054 9055
  if (m_cond)
    m_cond->cond_pop();
9056 9057 9058
}


9059 9060 9061
/*
  get table space info for SHOW CREATE TABLE
*/
9062
char* ha_ndbcluster::get_tablespace_name(THD *thd, char* name, uint name_len)
9063
{
9064
  Ndb *ndb= check_ndb_in_thd(thd);
9065
  NDBDICT *ndbdict= ndb->getDictionary();
9066 9067
  NdbError ndberr;
  Uint32 id;
9068
  ndb->setDatabaseName(m_dbname);
9069 9070
  const NDBTAB *ndbtab= m_table;
  DBUG_ASSERT(ndbtab != NULL);
9071 9072
  if (!ndbtab->getTablespace(&id))
  {
9073
    return 0;
9074 9075 9076 9077
  }
  {
    NdbDictionary::Tablespace ts= ndbdict->getTablespace(id);
    ndberr= ndbdict->getNdbError();
9078
    if(ndberr.classification != NdbError::NoError)
9079
      goto err;
9080
    DBUG_PRINT("info", ("Found tablespace '%s'", ts.getName()));
9081 9082
    if (name)
    {
9083
      strxnmov(name, name_len, ts.getName(), NullS);
9084 9085 9086 9087
      return name;
    }
    else
      return (my_strdup(ts.getName(), MYF(0)));
9088 9089 9090
  }
err:
  if (ndberr.status == NdbError::TemporaryError)
9091
    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
9092 9093 9094
			ER_GET_TEMPORARY_ERRMSG, ER(ER_GET_TEMPORARY_ERRMSG),
			ndberr.code, ndberr.message, "NDB");
  else
9095
    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
9096 9097
			ER_GET_ERRMSG, ER(ER_GET_ERRMSG),
			ndberr.code, ndberr.message, "NDB");
9098 9099 9100
  return 0;
}

9101 9102 9103
/*
  Implements the SHOW NDB STATUS command.
*/
9104
bool
9105
ndbcluster_show_status(handlerton *hton, THD* thd, stat_print_fn *stat_print,
9106
                       enum ha_stat_type stat_type)
9107
{
9108
  char buf[IO_SIZE];
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9109
  uint buflen;
9110 9111 9112 9113
  DBUG_ENTER("ndbcluster_show_status");
  
  if (have_ndbcluster != SHOW_OPTION_YES) 
  {
9114 9115 9116 9117 9118
    DBUG_RETURN(FALSE);
  }
  if (stat_type != HA_ENGINE_STATUS)
  {
    DBUG_RETURN(FALSE);
9119
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9120 9121 9122 9123

  update_status_variables(g_ndb_cluster_connection);
  buflen=
    my_snprintf(buf, sizeof(buf),
9124
                "cluster_node_id=%ld, "
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9125
                "connected_host=%s, "
9126 9127 9128 9129
                "connected_port=%ld, "
                "number_of_data_nodes=%ld, "
                "number_of_ready_data_nodes=%ld, "
                "connect_count=%ld",
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9130 9131 9132
                ndb_cluster_node_id,
                ndb_connected_host,
                ndb_connected_port,
justin.he@qa3-104.qa.cn.tlan's avatar
justin.he@qa3-104.qa.cn.tlan committed
9133 9134
                ndb_number_of_data_nodes,
                ndb_number_of_ready_data_nodes,
9135
                ndb_connect_count);
9136 9137
  if (stat_print(thd, ndbcluster_hton_name, ndbcluster_hton_name_length,
                 STRING_WITH_LEN("connection"), buf, buflen))
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9138 9139
    DBUG_RETURN(TRUE);

9140
  if (get_thd_ndb(thd) && get_thd_ndb(thd)->ndb)
9141
  {
9142
    Ndb* ndb= (get_thd_ndb(thd))->ndb;
9143 9144
    Ndb::Free_list_usage tmp;
    tmp.m_name= 0;
9145 9146
    while (ndb->get_free_list_usage(&tmp))
    {
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9147
      buflen=
9148
        my_snprintf(buf, sizeof(buf),
9149 9150
                  "created=%u, free=%u, sizeof=%u",
                  tmp.m_created, tmp.m_free, tmp.m_sizeof);
9151
      if (stat_print(thd, ndbcluster_hton_name, ndbcluster_hton_name_length,
9152
                     tmp.m_name, strlen(tmp.m_name), buf, buflen))
9153
        DBUG_RETURN(TRUE);
9154 9155
    }
  }
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9156 9157 9158 9159
#ifdef HAVE_NDB_BINLOG
  ndbcluster_show_status_binlog(thd, stat_print, stat_type);
#endif

9160 9161
  DBUG_RETURN(FALSE);
}
9162

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
9163

9164 9165 9166
/*
  Create a table in NDB Cluster
 */
9167
static uint get_no_fragments(ulonglong max_rows)
9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204
{
#if MYSQL_VERSION_ID >= 50000
  uint acc_row_size= 25 + /*safety margin*/ 2;
#else
  uint acc_row_size= pk_length*4;
  /* add acc overhead */
  if (pk_length <= 8)  /* main page will set the limit */
    acc_row_size+= 25 + /*safety margin*/ 2;
  else                /* overflow page will set the limit */
    acc_row_size+= 4 + /*safety margin*/ 4;
#endif
  ulonglong acc_fragment_size= 512*1024*1024;
#if MYSQL_VERSION_ID >= 50100
  return (max_rows*acc_row_size)/acc_fragment_size+1;
#else
  return ((max_rows*acc_row_size)/acc_fragment_size+1
	  +1/*correct rounding*/)/2;
#endif
}


/*
  Routine to adjust default number of partitions to always be a multiple
  of number of nodes and never more than 4 times the number of nodes.

*/
static bool adjusted_frag_count(uint no_fragments, uint no_nodes,
                                uint &reported_frags)
{
  uint i= 0;
  reported_frags= no_nodes;
  while (reported_frags < no_fragments && ++i < 4 &&
         (reported_frags + no_nodes) < MAX_PARTITIONS) 
    reported_frags+= no_nodes;
  return (reported_frags < no_fragments);
}

9205
int ha_ndbcluster::get_default_no_partitions(HA_CREATE_INFO *create_info)
9206
{
9207
  ha_rows max_rows, min_rows;
9208
  if (create_info)
9209
  {
9210 9211
    max_rows= create_info->max_rows;
    min_rows= create_info->min_rows;
9212 9213 9214 9215 9216 9217
  }
  else
  {
    max_rows= table_share->max_rows;
    min_rows= table_share->min_rows;
  }
9218
  uint reported_frags;
9219 9220
  uint no_fragments=
    get_no_fragments(max_rows >= min_rows ? max_rows : min_rows);
9221
  uint no_nodes= g_ndb_cluster_connection->no_db_nodes();
9222 9223 9224 9225 9226 9227
  if (adjusted_frag_count(no_fragments, no_nodes, reported_frags))
  {
    push_warning(current_thd,
                 MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
    "Ndb might have problems storing the max amount of rows specified");
  }
9228 9229 9230 9231
  return (int)reported_frags;
}


9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273
/*
  Set-up auto-partitioning for NDB Cluster

  SYNOPSIS
    set_auto_partitions()
    part_info                  Partition info struct to set-up
 
  RETURN VALUE
    NONE

  DESCRIPTION
    Set-up auto partitioning scheme for tables that didn't define any
    partitioning. We'll use PARTITION BY KEY() in this case which
    translates into partition by primary key if a primary key exists
    and partition by hidden key otherwise.
*/

void ha_ndbcluster::set_auto_partitions(partition_info *part_info)
{
  DBUG_ENTER("ha_ndbcluster::set_auto_partitions");
  part_info->list_of_part_fields= TRUE;
  part_info->part_type= HASH_PARTITION;
  switch (opt_ndb_distribution_id)
  {
  case ND_KEYHASH:
    part_info->linear_hash_ind= FALSE;
    break;
  case ND_LINHASH:
    part_info->linear_hash_ind= TRUE;
    break;
  }
  DBUG_VOID_RETURN;
}


int ha_ndbcluster::set_range_data(void *tab_ref, partition_info *part_info)
{
  NDBTAB *tab= (NDBTAB*)tab_ref;
  int32 *range_data= (int32*)my_malloc(part_info->no_parts*sizeof(int32),
                                       MYF(0));
  uint i;
  int error= 0;
9274
  bool unsigned_flag= part_info->part_expr->unsigned_flag;
9275 9276 9277 9278 9279 9280 9281 9282 9283 9284
  DBUG_ENTER("set_range_data");

  if (!range_data)
  {
    mem_alloc_error(part_info->no_parts*sizeof(int32));
    DBUG_RETURN(1);
  }
  for (i= 0; i < part_info->no_parts; i++)
  {
    longlong range_val= part_info->range_int_array[i];
9285 9286
    if (unsigned_flag)
      range_val-= 0x8000000000000000ULL;
9287
    if (range_val < INT_MIN32 || range_val >= INT_MAX32)
9288
    {
9289 9290 9291 9292 9293 9294 9295 9296
      if ((i != part_info->no_parts - 1) ||
          (range_val != LONGLONG_MAX))
      {
        my_error(ER_LIMITED_PART_RANGE, MYF(0), "NDB");
        error= 1;
        goto error;
      }
      range_val= INT_MAX32;
9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312
    }
    range_data[i]= (int32)range_val;
  }
  tab->setRangeListData(range_data, sizeof(int32)*part_info->no_parts);
error:
  my_free((char*)range_data, MYF(0));
  DBUG_RETURN(error);
}

int ha_ndbcluster::set_list_data(void *tab_ref, partition_info *part_info)
{
  NDBTAB *tab= (NDBTAB*)tab_ref;
  int32 *list_data= (int32*)my_malloc(part_info->no_list_values * 2
                                      * sizeof(int32), MYF(0));
  uint32 *part_id, i;
  int error= 0;
9313
  bool unsigned_flag= part_info->part_expr->unsigned_flag;
9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324
  DBUG_ENTER("set_list_data");

  if (!list_data)
  {
    mem_alloc_error(part_info->no_list_values*2*sizeof(int32));
    DBUG_RETURN(1);
  }
  for (i= 0; i < part_info->no_list_values; i++)
  {
    LIST_PART_ENTRY *list_entry= &part_info->list_array[i];
    longlong list_val= list_entry->list_value;
9325 9326
    if (unsigned_flag)
      list_val-= 0x8000000000000000ULL;
9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342
    if (list_val < INT_MIN32 || list_val > INT_MAX32)
    {
      my_error(ER_LIMITED_PART_RANGE, MYF(0), "NDB");
      error= 1;
      goto error;
    }
    list_data[2*i]= (int32)list_val;
    part_id= (uint32*)&list_data[2*i+1];
    *part_id= list_entry->partition_id;
  }
  tab->setRangeListData(list_data, 2*sizeof(int32)*part_info->no_list_values);
error:
  my_free((char*)list_data, MYF(0));
  DBUG_RETURN(error);
}

9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359
/*
  User defined partitioning set-up. We need to check how many fragments the
  user wants defined and which node groups to put those into. Later we also
  want to attach those partitions to a tablespace.

  All the functionality of the partition function, partition limits and so
  forth are entirely handled by the MySQL Server. There is one exception to
  this rule for PARTITION BY KEY where NDB handles the hash function and
  this type can thus be handled transparently also by NDB API program.
  For RANGE, HASH and LIST and subpartitioning the NDB API programs must
  implement the function to map to a partition.
*/

uint ha_ndbcluster::set_up_partition_info(partition_info *part_info,
                                          TABLE *table,
                                          void *tab_par)
{
9360 9361
  uint16 frag_data[MAX_PARTITIONS];
  char *ts_names[MAX_PARTITIONS];
9362
  ulong fd_index= 0, i, j;
9363 9364 9365
  NDBTAB *tab= (NDBTAB*)tab_par;
  NDBTAB::FragmentType ftype= NDBTAB::UserDefined;
  partition_element *part_elem;
9366
  bool first= TRUE;
9367
  uint tot_ts_name_len;
9368 9369 9370
  List_iterator<partition_element> part_it(part_info->partitions);
  int error;
  DBUG_ENTER("ha_ndbcluster::set_up_partition_info");
9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383

  if (part_info->part_type == HASH_PARTITION &&
      part_info->list_of_part_fields == TRUE)
  {
    Field **fields= part_info->part_field_array;

    if (part_info->linear_hash_ind)
      ftype= NDBTAB::DistrKeyLin;
    else
      ftype= NDBTAB::DistrKeyHash;

    for (i= 0; i < part_info->part_field_list.elements; i++)
    {
9384
      NDBCOL *col= tab->getColumn(fields[i]->field_index);
9385 9386 9387 9388
      DBUG_PRINT("info",("setting dist key on %s", col->getName()));
      col->setPartitionKey(TRUE);
    }
  }
9389
  else 
9390
  {
9391 9392 9393 9394 9395 9396 9397 9398
    if (!current_thd->variables.new_mode)
    {
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
                          ER_ILLEGAL_HA_CREATE_OPTION,
                          ER(ER_ILLEGAL_HA_CREATE_OPTION),
                          ndbcluster_hton_name,
                          "LIST, RANGE and HASH partition disabled by default,"
                          " use --new option to enable");
9399
      DBUG_RETURN(HA_ERR_UNSUPPORTED);
9400 9401
    }
   /*
9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417
      Create a shadow field for those tables that have user defined
      partitioning. This field stores the value of the partition
      function such that NDB can handle reorganisations of the data
      even when the MySQL Server isn't available to assist with
      calculation of the partition function value.
    */
    NDBCOL col;
    DBUG_PRINT("info", ("Generating partition func value field"));
    col.setName("$PART_FUNC_VALUE");
    col.setType(NdbDictionary::Column::Int);
    col.setLength(1);
    col.setNullable(FALSE);
    col.setPrimaryKey(FALSE);
    col.setAutoIncrement(FALSE);
    tab->addColumn(col);
    if (part_info->part_type == RANGE_PARTITION)
9418
    {
9419 9420 9421 9422
      if ((error= set_range_data((void*)tab, part_info)))
      {
        DBUG_RETURN(error);
      }
9423
    }
9424
    else if (part_info->part_type == LIST_PARTITION)
9425
    {
9426 9427 9428 9429
      if ((error= set_list_data((void*)tab, part_info)))
      {
        DBUG_RETURN(error);
      }
9430 9431 9432
    }
  }
  tab->setFragmentType(ftype);
9433 9434 9435
  i= 0;
  tot_ts_name_len= 0;
  do
9436
  {
9437 9438
    uint ng;
    part_elem= part_it++;
9439
    if (!part_info->is_sub_partitioned())
9440
    {
9441 9442 9443 9444 9445
      ng= part_elem->nodegroup_id;
      if (first && ng == UNDEF_NODEGROUP)
        ng= 0;
      ts_names[fd_index]= part_elem->tablespace_name;
      frag_data[fd_index++]= ng;
9446
    }
9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463
    else
    {
      List_iterator<partition_element> sub_it(part_elem->subpartitions);
      j= 0;
      do
      {
        part_elem= sub_it++;
        ng= part_elem->nodegroup_id;
        if (first && ng == UNDEF_NODEGROUP)
          ng= 0;
        ts_names[fd_index]= part_elem->tablespace_name;
        frag_data[fd_index++]= ng;
      } while (++j < part_info->no_subparts);
    }
    first= FALSE;
  } while (++i < part_info->no_parts);
  tab->setDefaultNoPartitionsFlag(part_info->use_default_no_partitions);
9464
  tab->setLinearFlag(part_info->linear_hash_ind);
9465
  {
9466 9467
    ha_rows max_rows= table_share->max_rows;
    ha_rows min_rows= table_share->min_rows;
9468 9469 9470 9471 9472
    if (max_rows < min_rows)
      max_rows= min_rows;
    if (max_rows != (ha_rows)0) /* default setting, don't set fragmentation */
    {
      tab->setMaxRows(max_rows);
9473
      tab->setMinRows(min_rows);
9474 9475
    }
  }
9476 9477 9478 9479
  tab->setTablespaceNames(ts_names, fd_index*sizeof(char*));
  tab->setFragmentCount(fd_index);
  tab->setFragmentData(&frag_data, fd_index*2);
  DBUG_RETURN(0);
9480
}
9481

9482

9483
bool ha_ndbcluster::check_if_incompatible_data(HA_CREATE_INFO *create_info,
9484 9485
					       uint table_changes)
{
9486 9487 9488
  DBUG_ENTER("ha_ndbcluster::check_if_incompatible_data");
  uint i;
  const NDBTAB *tab= (const NDBTAB *) m_table;
marty@linux.site's avatar
marty@linux.site committed
9489

9490 9491 9492 9493 9494 9495
  if (current_thd->variables.ndb_use_copying_alter_table)
  {
    DBUG_PRINT("info", ("On-line alter table disabled"));
    DBUG_RETURN(COMPATIBLE_DATA_NO);
  }

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9496 9497
  int pk= 0;
  int ai= 0;
9498 9499 9500 9501 9502 9503

  if (create_info->tablespace)
    create_info->storage_media = HA_SM_DISK;
  else
    create_info->storage_media = HA_SM_MEMORY;

9504 9505 9506
  for (i= 0; i < table->s->fields; i++) 
  {
    Field *field= table->field[i];
9507
    const NDBCOL *col= tab->getColumn(i);
9508 9509 9510 9511 9512 9513 9514
    if (col->getStorageType() == NDB_STORAGETYPE_MEMORY && create_info->storage_media != HA_SM_MEMORY ||
        col->getStorageType() == NDB_STORAGETYPE_DISK && create_info->storage_media != HA_SM_DISK)
    {
      DBUG_PRINT("info", ("Column storage media is changed"));
      DBUG_RETURN(COMPATIBLE_DATA_NO);
    }
    
9515
    if (field->flags & FIELD_IS_RENAMED)
9516 9517 9518 9519
    {
      DBUG_PRINT("info", ("Field has been renamed, copy table"));
      DBUG_RETURN(COMPATIBLE_DATA_NO);
    }
9520
    if ((field->flags & FIELD_IN_ADD_INDEX) &&
9521 9522 9523 9524 9525
        col->getStorageType() == NdbDictionary::Column::StorageTypeDisk)
    {
      DBUG_PRINT("info", ("add/drop index not supported for disk stored column"));
      DBUG_RETURN(COMPATIBLE_DATA_NO);
    }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9526 9527 9528 9529 9530
    
    if (field->flags & PRI_KEY_FLAG)
      pk=1;
    if (field->flags & FIELD_IN_ADD_INDEX)
      ai=1;
9531
  }
9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561

  char tablespace_name[FN_LEN]; 
  if (get_tablespace_name(current_thd, tablespace_name, FN_LEN))
  {
    if (create_info->tablespace) 
    {
      if (strcmp(create_info->tablespace, tablespace_name))
      {
        DBUG_PRINT("info", ("storage media is changed, old tablespace=%s, new tablespace=%s",
          tablespace_name, create_info->tablespace));
        DBUG_RETURN(COMPATIBLE_DATA_NO);
      }
    }
    else
    {
      DBUG_PRINT("info", ("storage media is changed, old is DISK and tablespace=%s, new is MEM",
        tablespace_name));
      DBUG_RETURN(COMPATIBLE_DATA_NO);
    }
  }
  else
  {
    if (create_info->storage_media != HA_SM_MEMORY)
    {
      DBUG_PRINT("info", ("storage media is changed, old is MEM, new is DISK and tablespace=%s",
        create_info->tablespace));
      DBUG_RETURN(COMPATIBLE_DATA_NO);
    }
  }

9562
  if (table_changes != IS_EQUAL_YES)
9563
    DBUG_RETURN(COMPATIBLE_DATA_NO);
9564
  
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582
  /**
   * Changing from/to primary key
   *
   * This is _not_ correct, but check_if_incompatible_data-interface
   *   doesnt give more info, so I guess that we can't do any
   *   online add index if not using primary key
   *
   *   This as mysql will handle a unique not null index as primary 
   *     even wo/ user specifiying it... :-(
   *   
   */
  if ((table_share->primary_key == MAX_KEY && pk) ||
      (table_share->primary_key != MAX_KEY && !pk) ||
      (table_share->primary_key == MAX_KEY && !pk && ai))
  {
    DBUG_RETURN(COMPATIBLE_DATA_NO);
  }
  
9583
  /* Check that auto_increment value was not changed */
9584 9585
  if ((create_info->used_fields & HA_CREATE_USED_AUTO) &&
      create_info->auto_increment_value != 0)
9586
    DBUG_RETURN(COMPATIBLE_DATA_NO);
9587 9588
  
  /* Check that row format didn't change */
9589
  if ((create_info->used_fields & HA_CREATE_USED_AUTO) &&
9590
      get_row_type() != create_info->row_type)
9591
    DBUG_RETURN(COMPATIBLE_DATA_NO);
9592

9593
  DBUG_RETURN(COMPATIBLE_DATA_YES);
9594 9595
}

9596
bool set_up_tablespace(st_alter_tablespace *alter_info,
9597 9598
                       NdbDictionary::Tablespace *ndb_ts)
{
9599 9600 9601 9602
  ndb_ts->setName(alter_info->tablespace_name);
  ndb_ts->setExtentSize(alter_info->extent_size);
  ndb_ts->setDefaultLogfileGroup(alter_info->logfile_group_name);
  return FALSE;
9603 9604
}

9605
bool set_up_datafile(st_alter_tablespace *alter_info,
9606 9607
                     NdbDictionary::Datafile *ndb_df)
{
9608
  if (alter_info->max_size > 0)
9609 9610
  {
    my_error(ER_TABLESPACE_AUTO_EXTEND_ERROR, MYF(0));
9611
    return TRUE;
9612
  }
9613 9614 9615 9616
  ndb_df->setPath(alter_info->data_file_name);
  ndb_df->setSize(alter_info->initial_size);
  ndb_df->setTablespace(alter_info->tablespace_name);
  return FALSE;
9617 9618
}

9619
bool set_up_logfile_group(st_alter_tablespace *alter_info,
9620 9621
                          NdbDictionary::LogfileGroup *ndb_lg)
{
9622 9623 9624
  ndb_lg->setName(alter_info->logfile_group_name);
  ndb_lg->setUndoBufferSize(alter_info->undo_buffer_size);
  return FALSE;
9625 9626
}

9627
bool set_up_undofile(st_alter_tablespace *alter_info,
9628 9629
                     NdbDictionary::Undofile *ndb_uf)
{
9630 9631 9632 9633
  ndb_uf->setPath(alter_info->undo_file_name);
  ndb_uf->setSize(alter_info->initial_size);
  ndb_uf->setLogfileGroup(alter_info->logfile_group_name);
  return FALSE;
9634 9635
}

9636 9637
int ndbcluster_alter_tablespace(handlerton *hton,
                                THD* thd, st_alter_tablespace *alter_info)
9638
{
9639 9640 9641 9642 9643 9644
  int is_tablespace= 0;
  NdbError err;
  NDBDICT *dict;
  int error;
  const char *errmsg;
  Ndb *ndb;
9645
  DBUG_ENTER("ha_ndbcluster::alter_tablespace");
9646
  LINT_INIT(errmsg);
9647

9648
  ndb= check_ndb_in_thd(thd);
9649
  if (ndb == NULL)
9650
  {
9651
    DBUG_RETURN(HA_ERR_NO_CONNECTION);
9652
  }
9653
  dict= ndb->getDictionary();
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9654

9655
  switch (alter_info->ts_cmd_type){
9656 9657
  case (CREATE_TABLESPACE):
  {
9658
    error= ER_CREATE_FILEGROUP_FAILED;
9659
    
9660 9661
    NdbDictionary::Tablespace ndb_ts;
    NdbDictionary::Datafile ndb_df;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9662
    NdbDictionary::ObjectId objid;
9663
    if (set_up_tablespace(alter_info, &ndb_ts))
9664 9665 9666
    {
      DBUG_RETURN(1);
    }
9667
    if (set_up_datafile(alter_info, &ndb_df))
9668 9669 9670
    {
      DBUG_RETURN(1);
    }
9671
    errmsg= "TABLESPACE";
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9672
    if (dict->createTablespace(ndb_ts, &objid))
9673 9674
    {
      DBUG_PRINT("error", ("createTablespace returned %d", error));
9675
      goto ndberror;
9676
    }
9677
    DBUG_PRINT("alter_info", ("Successfully created Tablespace"));
9678 9679
    errmsg= "DATAFILE";
    if (dict->createDatafile(ndb_df))
9680
    {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9681 9682 9683 9684 9685 9686 9687 9688 9689
      err= dict->getNdbError();
      NdbDictionary::Tablespace tmp= dict->getTablespace(ndb_ts.getName());
      if (dict->getNdbError().code == 0 &&
	  tmp.getObjectId() == objid.getObjectId() &&
	  tmp.getObjectVersion() == objid.getObjectVersion())
      {
	dict->dropTablespace(tmp);
      }
      
9690
      DBUG_PRINT("error", ("createDatafile returned %d", error));
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9691
      goto ndberror2;
9692
    }
9693
    is_tablespace= 1;
9694 9695 9696 9697
    break;
  }
  case (ALTER_TABLESPACE):
  {
9698
    error= ER_ALTER_FILEGROUP_FAILED;
9699
    if (alter_info->ts_alter_tablespace_type == ALTER_TABLESPACE_ADD_FILE)
9700 9701
    {
      NdbDictionary::Datafile ndb_df;
9702
      if (set_up_datafile(alter_info, &ndb_df))
9703 9704 9705
      {
	DBUG_RETURN(1);
      }
9706 9707
      errmsg= " CREATE DATAFILE";
      if (dict->createDatafile(ndb_df))
9708
      {
9709
	goto ndberror;
9710 9711
      }
    }
9712
    else if(alter_info->ts_alter_tablespace_type == ALTER_TABLESPACE_DROP_FILE)
9713
    {
9714 9715
      NdbDictionary::Tablespace ts= dict->getTablespace(alter_info->tablespace_name);
      NdbDictionary::Datafile df= dict->getDatafile(0, alter_info->data_file_name);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9716 9717 9718
      NdbDictionary::ObjectId objid;
      df.getTablespaceId(&objid);
      if (ts.getObjectId() == objid.getObjectId() && 
9719
	  strcmp(df.getPath(), alter_info->data_file_name) == 0)
9720
      {
9721 9722
	errmsg= " DROP DATAFILE";
	if (dict->dropDatafile(df))
9723
	{
9724
	  goto ndberror;
9725 9726 9727 9728 9729
	}
      }
      else
      {
	DBUG_PRINT("error", ("No such datafile"));
9730
	my_error(ER_ALTER_FILEGROUP_FAILED, MYF(0), " NO SUCH FILE");
9731 9732 9733 9734 9735 9736
	DBUG_RETURN(1);
      }
    }
    else
    {
      DBUG_PRINT("error", ("Unsupported alter tablespace: %d", 
9737
			   alter_info->ts_alter_tablespace_type));
9738 9739
      DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
    }
9740
    is_tablespace= 1;
9741 9742 9743 9744
    break;
  }
  case (CREATE_LOGFILE_GROUP):
  {
9745
    error= ER_CREATE_FILEGROUP_FAILED;
9746 9747
    NdbDictionary::LogfileGroup ndb_lg;
    NdbDictionary::Undofile ndb_uf;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9748
    NdbDictionary::ObjectId objid;
9749
    if (alter_info->undo_file_name == NULL)
9750 9751 9752 9753 9754 9755
    {
      /*
	REDO files in LOGFILE GROUP not supported yet
      */
      DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
    }
9756
    if (set_up_logfile_group(alter_info, &ndb_lg))
9757 9758 9759
    {
      DBUG_RETURN(1);
    }
9760
    errmsg= "LOGFILE GROUP";
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9761
    if (dict->createLogfileGroup(ndb_lg, &objid))
9762
    {
9763
      goto ndberror;
9764
    }
9765 9766
    DBUG_PRINT("alter_info", ("Successfully created Logfile Group"));
    if (set_up_undofile(alter_info, &ndb_uf))
9767 9768 9769
    {
      DBUG_RETURN(1);
    }
9770 9771
    errmsg= "UNDOFILE";
    if (dict->createUndofile(ndb_uf))
9772
    {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9773 9774 9775 9776 9777 9778 9779 9780 9781
      err= dict->getNdbError();
      NdbDictionary::LogfileGroup tmp= dict->getLogfileGroup(ndb_lg.getName());
      if (dict->getNdbError().code == 0 &&
	  tmp.getObjectId() == objid.getObjectId() &&
	  tmp.getObjectVersion() == objid.getObjectVersion())
      {
	dict->dropLogfileGroup(tmp);
      }
      goto ndberror2;
9782 9783 9784 9785 9786
    }
    break;
  }
  case (ALTER_LOGFILE_GROUP):
  {
9787
    error= ER_ALTER_FILEGROUP_FAILED;
9788
    if (alter_info->undo_file_name == NULL)
9789 9790 9791 9792 9793 9794 9795
    {
      /*
	REDO files in LOGFILE GROUP not supported yet
      */
      DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
    }
    NdbDictionary::Undofile ndb_uf;
9796
    if (set_up_undofile(alter_info, &ndb_uf))
9797 9798 9799
    {
      DBUG_RETURN(1);
    }
9800 9801
    errmsg= "CREATE UNDOFILE";
    if (dict->createUndofile(ndb_uf))
9802
    {
9803
      goto ndberror;
9804 9805 9806 9807 9808
    }
    break;
  }
  case (DROP_TABLESPACE):
  {
9809
    error= ER_DROP_FILEGROUP_FAILED;
9810
    errmsg= "TABLESPACE";
9811
    if (dict->dropTablespace(dict->getTablespace(alter_info->tablespace_name)))
9812
    {
9813
      goto ndberror;
9814
    }
9815
    is_tablespace= 1;
9816 9817 9818 9819
    break;
  }
  case (DROP_LOGFILE_GROUP):
  {
9820
    error= ER_DROP_FILEGROUP_FAILED;
9821
    errmsg= "LOGFILE GROUP";
9822
    if (dict->dropLogfileGroup(dict->getLogfileGroup(alter_info->logfile_group_name)))
9823
    {
9824
      goto ndberror;
9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840
    }
    break;
  }
  case (CHANGE_FILE_TABLESPACE):
  {
    DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
  }
  case (ALTER_ACCESS_MODE_TABLESPACE):
  {
    DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
  }
  default:
  {
    DBUG_RETURN(HA_ADMIN_NOT_IMPLEMENTED);
  }
  }
9841
#ifdef HAVE_NDB_BINLOG
9842 9843 9844
  if (is_tablespace)
    ndbcluster_log_schema_op(thd, 0,
                             thd->query, thd->query_length,
9845
                             "", alter_info->tablespace_name,
9846
                             0, 0,
9847
                             SOT_TABLESPACE, 0, 0, 0);
9848 9849 9850
  else
    ndbcluster_log_schema_op(thd, 0,
                             thd->query, thd->query_length,
9851
                             "", alter_info->logfile_group_name,
9852
                             0, 0,
9853
                             SOT_LOGFILE_GROUP, 0, 0, 0);
9854
#endif
9855
  DBUG_RETURN(FALSE);
9856 9857

ndberror:
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
9858 9859
  err= dict->getNdbError();
ndberror2:
9860 9861 9862 9863 9864
  ERR_PRINT(err);
  ndb_to_mysql_error(&err);
  
  my_error(error, MYF(0), errmsg);
  DBUG_RETURN(1);
9865 9866
}

9867 9868 9869 9870 9871 9872 9873

bool ha_ndbcluster::get_no_parts(const char *name, uint *no_parts)
{
  Ndb *ndb;
  NDBDICT *dict;
  int err;
  DBUG_ENTER("ha_ndbcluster::get_no_parts");
9874
  LINT_INIT(err);
9875 9876 9877

  set_dbname(name);
  set_tabname(name);
9878
  for (;;)
9879 9880 9881 9882 9883 9884 9885
  {
    if (check_ndb_connection())
    {
      err= HA_ERR_NO_CONNECTION;
      break;
    }
    ndb= get_ndb();
9886
    ndb->setDatabaseName(m_dbname);
9887 9888
    Ndb_table_guard ndbtab_g(dict= ndb->getDictionary(), m_tabname);
    if (!ndbtab_g.get_table())
9889
      ERR_BREAK(dict->getNdbError(), err);
9890
    *no_parts= ndbtab_g.get_table()->getFragmentCount();
9891
    DBUG_RETURN(FALSE);
9892
  }
9893 9894 9895 9896 9897

  print_error(err, MYF(0));
  DBUG_RETURN(TRUE);
}

9898 9899 9900
static int ndbcluster_fill_files_table(handlerton *hton, 
                                       THD *thd, 
                                       TABLE_LIST *tables,
9901
                                       COND *cond)
9902 9903
{
  TABLE* table= tables->table;
9904
  Ndb *ndb= check_ndb_in_thd(thd);
9905 9906
  NdbDictionary::Dictionary* dict= ndb->getDictionary();
  NdbDictionary::Dictionary::List dflist;
9907
  NdbError ndberr;
9908
  uint i;
9909
  DBUG_ENTER("ndbcluster_fill_files_table");
9910

9911 9912
  dict->listObjects(dflist, NdbDictionary::Object::Datafile);
  ndberr= dict->getNdbError();
9913 9914
  if (ndberr.classification != NdbError::NoError)
    ERR_RETURN(ndberr);
9915

9916
  for (i= 0; i < dflist.count; i++)
9917 9918 9919
  {
    NdbDictionary::Dictionary::List::Element& elt = dflist.elements[i];
    Ndb_cluster_connection_node_iter iter;
9920 9921
    uint id;
    
9922 9923
    g_ndb_cluster_connection->init_get_next_node(iter);

9924
    while ((id= g_ndb_cluster_connection->get_next_node(iter)))
9925
    {
9926
      init_fill_schema_files_row(table);
9927
      NdbDictionary::Datafile df= dict->getDatafile(id, elt.name);
9928
      ndberr= dict->getNdbError();
9929 9930 9931 9932 9933 9934
      if(ndberr.classification != NdbError::NoError)
      {
        if (ndberr.classification == NdbError::SchemaError)
          continue;
        ERR_RETURN(ndberr);
      }
9935 9936
      NdbDictionary::Tablespace ts= dict->getTablespace(df.getTablespace());
      ndberr= dict->getNdbError();
9937 9938 9939 9940 9941 9942
      if (ndberr.classification != NdbError::NoError)
      {
        if (ndberr.classification == NdbError::SchemaError)
          continue;
        ERR_RETURN(ndberr);
      }
9943

9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980
      table->field[IS_FILES_FILE_NAME]->set_notnull();
      table->field[IS_FILES_FILE_NAME]->store(elt.name, strlen(elt.name),
                                              system_charset_info);
      table->field[IS_FILES_FILE_TYPE]->set_notnull();
      table->field[IS_FILES_FILE_TYPE]->store("DATAFILE",8,
                                              system_charset_info);
      table->field[IS_FILES_TABLESPACE_NAME]->set_notnull();
      table->field[IS_FILES_TABLESPACE_NAME]->store(df.getTablespace(),
                                                    strlen(df.getTablespace()),
                                                    system_charset_info);
      table->field[IS_FILES_LOGFILE_GROUP_NAME]->set_notnull();
      table->field[IS_FILES_LOGFILE_GROUP_NAME]->
        store(ts.getDefaultLogfileGroup(),
              strlen(ts.getDefaultLogfileGroup()),
              system_charset_info);
      table->field[IS_FILES_ENGINE]->set_notnull();
      table->field[IS_FILES_ENGINE]->store(ndbcluster_hton_name,
                                           ndbcluster_hton_name_length,
                                           system_charset_info);

      table->field[IS_FILES_FREE_EXTENTS]->set_notnull();
      table->field[IS_FILES_FREE_EXTENTS]->store(df.getFree()
                                                 / ts.getExtentSize());
      table->field[IS_FILES_TOTAL_EXTENTS]->set_notnull();
      table->field[IS_FILES_TOTAL_EXTENTS]->store(df.getSize()
                                                  / ts.getExtentSize());
      table->field[IS_FILES_EXTENT_SIZE]->set_notnull();
      table->field[IS_FILES_EXTENT_SIZE]->store(ts.getExtentSize());
      table->field[IS_FILES_INITIAL_SIZE]->set_notnull();
      table->field[IS_FILES_INITIAL_SIZE]->store(df.getSize());
      table->field[IS_FILES_MAXIMUM_SIZE]->set_notnull();
      table->field[IS_FILES_MAXIMUM_SIZE]->store(df.getSize());
      table->field[IS_FILES_VERSION]->set_notnull();
      table->field[IS_FILES_VERSION]->store(df.getObjectVersion());

      table->field[IS_FILES_ROW_FORMAT]->set_notnull();
      table->field[IS_FILES_ROW_FORMAT]->store("FIXED", 5, system_charset_info);
9981 9982

      char extra[30];
9983
      int len= my_snprintf(extra, sizeof(extra), "CLUSTER_NODE=%u", id);
9984 9985
      table->field[IS_FILES_EXTRA]->set_notnull();
      table->field[IS_FILES_EXTRA]->store(extra, len, system_charset_info);
9986 9987 9988 9989
      schema_table_store_record(thd, table);
    }
  }

jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
9990 9991
  NdbDictionary::Dictionary::List uflist;
  dict->listObjects(uflist, NdbDictionary::Object::Undofile);
9992
  ndberr= dict->getNdbError();
9993 9994
  if (ndberr.classification != NdbError::NoError)
    ERR_RETURN(ndberr);
9995

jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
9996
  for (i= 0; i < uflist.count; i++)
9997
  {
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
9998
    NdbDictionary::Dictionary::List::Element& elt= uflist.elements[i];
9999 10000 10001 10002 10003
    Ndb_cluster_connection_node_iter iter;
    unsigned id;

    g_ndb_cluster_connection->init_get_next_node(iter);

10004
    while ((id= g_ndb_cluster_connection->get_next_node(iter)))
10005 10006
    {
      NdbDictionary::Undofile uf= dict->getUndofile(id, elt.name);
10007
      ndberr= dict->getNdbError();
10008 10009 10010 10011 10012 10013
      if (ndberr.classification != NdbError::NoError)
      {
        if (ndberr.classification == NdbError::SchemaError)
          continue;
        ERR_RETURN(ndberr);
      }
10014 10015 10016
      NdbDictionary::LogfileGroup lfg=
        dict->getLogfileGroup(uf.getLogfileGroup());
      ndberr= dict->getNdbError();
10017 10018 10019 10020 10021 10022
      if (ndberr.classification != NdbError::NoError)
      {
        if (ndberr.classification == NdbError::SchemaError)
          continue;
        ERR_RETURN(ndberr);
      }
10023

10024 10025 10026 10027 10028 10029 10030
      init_fill_schema_files_row(table);
      table->field[IS_FILES_FILE_NAME]->set_notnull();
      table->field[IS_FILES_FILE_NAME]->store(elt.name, strlen(elt.name),
                                              system_charset_info);
      table->field[IS_FILES_FILE_TYPE]->set_notnull();
      table->field[IS_FILES_FILE_TYPE]->store("UNDO LOG", 8,
                                              system_charset_info);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
10031 10032
      NdbDictionary::ObjectId objid;
      uf.getLogfileGroupId(&objid);
10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055
      table->field[IS_FILES_LOGFILE_GROUP_NAME]->set_notnull();
      table->field[IS_FILES_LOGFILE_GROUP_NAME]->store(uf.getLogfileGroup(),
                                                  strlen(uf.getLogfileGroup()),
                                                       system_charset_info);
      table->field[IS_FILES_LOGFILE_GROUP_NUMBER]->set_notnull();
      table->field[IS_FILES_LOGFILE_GROUP_NUMBER]->store(objid.getObjectId());
      table->field[IS_FILES_ENGINE]->set_notnull();
      table->field[IS_FILES_ENGINE]->store(ndbcluster_hton_name,
                                           ndbcluster_hton_name_length,
                                           system_charset_info);

      table->field[IS_FILES_TOTAL_EXTENTS]->set_notnull();
      table->field[IS_FILES_TOTAL_EXTENTS]->store(uf.getSize()/4);
      table->field[IS_FILES_EXTENT_SIZE]->set_notnull();
      table->field[IS_FILES_EXTENT_SIZE]->store(4);

      table->field[IS_FILES_INITIAL_SIZE]->set_notnull();
      table->field[IS_FILES_INITIAL_SIZE]->store(uf.getSize());
      table->field[IS_FILES_MAXIMUM_SIZE]->set_notnull();
      table->field[IS_FILES_MAXIMUM_SIZE]->store(uf.getSize());

      table->field[IS_FILES_VERSION]->set_notnull();
      table->field[IS_FILES_VERSION]->store(uf.getObjectVersion());
10056

10057
      char extra[100];
10058 10059
      int len= my_snprintf(extra,sizeof(extra),"CLUSTER_NODE=%u;UNDO_BUFFER_SIZE=%lu",
                           id, (ulong) lfg.getUndoBufferSize());
10060 10061
      table->field[IS_FILES_EXTRA]->set_notnull();
      table->field[IS_FILES_EXTRA]->store(extra, len, system_charset_info);
10062 10063 10064
      schema_table_store_record(thd, table);
    }
  }
10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085

  // now for LFGs
  NdbDictionary::Dictionary::List lfglist;
  dict->listObjects(lfglist, NdbDictionary::Object::LogfileGroup);
  ndberr= dict->getNdbError();
  if (ndberr.classification != NdbError::NoError)
    ERR_RETURN(ndberr);

  for (i= 0; i < lfglist.count; i++)
  {
    NdbDictionary::Dictionary::List::Element& elt= lfglist.elements[i];

    NdbDictionary::LogfileGroup lfg= dict->getLogfileGroup(elt.name);
    ndberr= dict->getNdbError();
    if (ndberr.classification != NdbError::NoError)
    {
      if (ndberr.classification == NdbError::SchemaError)
        continue;
      ERR_RETURN(ndberr);
    }

10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108
    init_fill_schema_files_row(table);
    table->field[IS_FILES_FILE_TYPE]->set_notnull();
    table->field[IS_FILES_FILE_TYPE]->store("UNDO LOG", 8,
                                            system_charset_info);

    table->field[IS_FILES_LOGFILE_GROUP_NAME]->set_notnull();
    table->field[IS_FILES_LOGFILE_GROUP_NAME]->store(elt.name,
                                                     strlen(elt.name),
                                                     system_charset_info);
    table->field[IS_FILES_LOGFILE_GROUP_NUMBER]->set_notnull();
    table->field[IS_FILES_LOGFILE_GROUP_NUMBER]->store(lfg.getObjectId());
    table->field[IS_FILES_ENGINE]->set_notnull();
    table->field[IS_FILES_ENGINE]->store(ndbcluster_hton_name,
                                         ndbcluster_hton_name_length,
                                         system_charset_info);

    table->field[IS_FILES_FREE_EXTENTS]->set_notnull();
    table->field[IS_FILES_FREE_EXTENTS]->store(lfg.getUndoFreeWords());
    table->field[IS_FILES_EXTENT_SIZE]->set_notnull();
    table->field[IS_FILES_EXTENT_SIZE]->store(4);

    table->field[IS_FILES_VERSION]->set_notnull();
    table->field[IS_FILES_VERSION]->store(lfg.getObjectVersion());
10109 10110

    char extra[100];
10111 10112
    int len= my_snprintf(extra,sizeof(extra),
                         "UNDO_BUFFER_SIZE=%lu",
10113
                         (ulong) lfg.getUndoBufferSize());
10114 10115
    table->field[IS_FILES_EXTRA]->set_notnull();
    table->field[IS_FILES_EXTRA]->store(extra, len, system_charset_info);
10116 10117
    schema_table_store_record(thd, table);
  }
10118
  DBUG_RETURN(0);
10119
}
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
10120

brian@zim.(none)'s avatar
brian@zim.(none) committed
10121 10122 10123 10124 10125
SHOW_VAR ndb_status_variables_export[]= {
  {"Ndb",                      (char*) &ndb_status_variables,   SHOW_ARRAY},
  {NullS, NullS, SHOW_LONG}
};

10126
struct st_mysql_storage_engine ndbcluster_storage_engine=
10127
{ MYSQL_HANDLERTON_INTERFACE_VERSION };
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
10128 10129 10130 10131

mysql_declare_plugin(ndbcluster)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
10132
  &ndbcluster_storage_engine,
10133
  ndbcluster_hton_name,
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
10134
  "MySQL AB",
10135
  "Clustered, fault-tolerant tables",
10136
  PLUGIN_LICENSE_GPL,
10137
  ndbcluster_init, /* Plugin Init */
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
10138 10139
  NULL, /* Plugin Deinit */
  0x0100 /* 1.0 */,
10140 10141 10142
  ndb_status_variables_export,/* status variables                */
  NULL,                       /* system variables                */
  NULL                        /* config options                  */
acurtis@xiphis.org's avatar
acurtis@xiphis.org committed
10143 10144 10145 10146
}
mysql_declare_plugin_end;

#endif