Documentation Home
MySQL NDB Cluster API Developer Guide
Related Documentation Download this Manual
PDF (US Ltr) - 3.6Mb
PDF (A4) - 3.6Mb


2.3.11 The Ndb Class

This section provides information about the Ndb class, which models the NDB kernel; it is the primary class of the NDB API.

Ndb Class Overview

Parent class

None

Child classes

None

Description

Any nontrivial NDB API program makes use of at least one instance of Ndb. By using several Ndb objects, it is possible to implement a multithreaded application. You should remember that one Ndb object cannot be shared between threads; however, it is possible for a single thread to use multiple Ndb objects. A single application process can support a maximum of 4711 Ndb objects.

Methods

The following table lists the public methods of this class and the purpose or use of each method:

Table 2.26 Ndb class methods and descriptions

Name Description
Ndb() Class constructor; represents a connection to an NDB Cluster.
~Ndb() Class destructor; terminates a Cluster connection when it is no longer to be used
closeTransaction() Closes a transaction.
computeHash() Computes a distribution hash value.
createEventOperation() Creates a subscription to a database event. (See Section 2.3.16, “The NdbEventOperation Class”.)
dropEventOperation() Drops a subscription to a database event.
getDictionary() Gets a dictionary, which is used for working with database schema information.
getDatabaseName() Gets the name of the current database.
getDatabaseSchemaName() Gets the name of the current database schema.
get_eventbuf_max_alloc() Gets the current allocated maximum size of the event buffer.
get_eventbuffer_free_percent() Gets the percentage of event buffer memory that should be available before buffering resumes, once the limit has been reached. Added in NDB 7.4.
get_event_buffer_memory_usage() Provides event buffer memory usage information. Added in NDB 7.4.
getGCIEventOperations() Gets the next event operation from a GCI. Deprecated in NDB 7.4.
getHighestQueuedEpoch() Gets the latest epoch in the event queue. Added in NDB 7.4.
getLatestGCI() Gets the most recent GCI. Deprecated in NDB 7.4.
getNdbError() Retrieves an error. (See Section 2.3.15, “The NdbError Structure”.)
getNdbErrorDetail() Retrieves extra error details.
getNdbObjectName() Retrieves the Ndb object name if one was set.
getNextEventOpInEpoch2() Gets the next event operation in this global checkpoint.
getNextEventOpInEpoch3() Gets the next event operation in this global checkpoint, showing any received anyvalues. Added in NDB 7.4.18 and 7.5.9.
getReference() Retrieves a reference or identifier for the Ndb object instance.
init() Initializes an Ndb object and makes it ready for use.
isConsistent() Whether all received events are consistent. Deprecated in NDB 7.4.
isConsistentGCI() Whether all received events for a given global checkpoint are consistent. Deprecated in NDB 7.4.
isExpectingHigherQueuedEpochs() Check whether there are new queued epochs, or there was a cluster failure event. Added in NDB 7.4.7.
nextEvent() Gets the next event from the queue. Deprecated in NDB 7.4.
nextEvent2() Gets the next event from the queue. Added in NDB 7.4.
pollEvents() Waits for an event to occur. Deprecated in NDB 7.4.
pollEvents2() Waits for an event to occur. Added in NDB 7.4.
setDatabaseName() Sets the name of the current database.
setDatabaseSchemaName() Sets the name of the current database schema.
setEventBufferQueueEmptyEpoch() Enables queuing of empty events. Added in NDB 7.4.11.
set_eventbuf_max_alloc() Sets the current allocated maximum size of the event buffer.
set_eventbuffer_free_percent() Sets the percentage of event buffer memory that should be available before buffering resumes, once the limit has been reached. Added in NDB 7.4.
setNdbObjectName() For debugging purposes: sets an arbitrary name for this Ndb object.
startTransaction() Begins a transaction. (See Section 2.3.25, “The NdbTransaction Class”.)

Types

The Ndb class does not define any public typesbut does define three data structures, which are listed here:

Resource consumption by Ndb objects.  An Ndb object consumes memory in proportion to the size of the largest operation performed over the lifetime of the object. This is particularly noticeable in cases of large transactions, use of blob columns, or both. This memory is held for the lifetime of the object, and once used in this way by the Ndb object, the only way to free this memory is to destroy the object (and then to create a new instance if desired).

Note

The Ndb object is multithread safe in that each Ndb object can be handled by one thread at a time. If an Ndb object is handed over to another thread, then the application must ensure that a memory barrier is used to ensure that the new thread sees all updates performed by the previous thread.

Semaphores and mutexes are examples of easy ways to provide memory barriers without having to bother about the memory barrier concept.

It is also possible to use multiple Ndb objects to perform operations on different clusters in a single application. See Section 1.5, “Application-level partitioning”, for conditions and restrictions applying to such usage.

Ndb Class Constructor

Description

This creates an instance of Ndb, which represents a connection to the NDB Cluster. All NDB API applications should begin with the creation of at least one Ndb object. This requires the creation of at least one instance of Ndb_cluster_connection, which serves as a container for a cluster connection string.

Signature
Ndb
    (
      Ndb_cluster_connection* ndb_cluster_connection,
      const char*                    catalogName = "",
      const char*                    schemaName = "def"
    )
Parameters

The Ndb class constructor can take up to 3 parameters, of which only the first is required:

  • ndb_cluster_connection is an instance of Ndb_cluster_connection, which represents a cluster connection string. (See Section 2.3.12, “The Ndb_cluster_connection Class”.)

  • catalogName is an optional parameter providing a namespace for the tables and indexes created in any connection from the Ndb object.

    This is equivalent to what mysqld considers the database.

    The default value for this parameter is an empty string.

  • The optional schemaName provides an additional namespace for the tables and indexes created in a given catalog.

    The default value for this parameter is the string def.

Return value

An Ndb object.

Destructor

The destructor for the Ndb class should be called in order to terminate an instance of Ndb. It requires no arguments, nor any special handling.

Ndb::closeTransaction()

Description

This is one of two NDB API methods provided for closing a transaction (the other being NdbTransaction::close()). You must call one of these two methods to close the transaction once it has been completed, whether or not the transaction succeeded.

If the transaction has not yet been committed, it is aborted when this method is called. See Ndb::startTransaction().

Signature
void closeTransaction
    (
      NdbTransaction *transaction
    )
Parameters

This method takes a single argument, a pointer to the NdbTransaction to be closed.

Return value

None (void).

Ndb::computeHash()

Description

This method can be used to compute a distribution hash value, given a table and its keys.

computeHash() can be used only for tables that use native NDB partitioning.

Signature
static int computeHash
    (
      Uint32*                     hashvalueptr,
      const NdbDictionary::Table* table,
      const struct Key_part_ptr*  keyData,
      void*                       xfrmbuf = 0,
      Uint32                      xfrmbuflen = 0
    )
Parameters

This method takes the following parameters:

  • If the method call is successful, hashvalueptr is set to the computed hash value.

  • A pointer to a table (see Section 2.3.27, “The Table Class”).

  • keyData is a null-terminated array of pointers to the key parts that are part of the table's distribution key. The length of each key part is read from metadata and checked against the passed value (see Ndb::Key_part_ptr).

  • xfrmbuf is a pointer to temporary buffer used to calculate the hash value.

  • xfrmbuflen is the length of this buffer.

    If xfrmbuf is NULL (the default), then a call to malloc() or free() is made automatically, as appropriate.

    Prior to NDB 7.5.30, 7.6.26, 8.0.33: computeHash() fails if xfrmbuf is not NULL and xfrmbuflen is too small.

    NDB 7.5.30 and later, 7.6.26 and later, 8.0.33 and later: If the buffer passed is not of sufficient size, a temporary buffer is allocated automatically. (Bug #103814, Bug #32959894)

    Note

    When malloc() provides a buffer to this method, the buffer is explicitly aligned after it is allocated, and before it is actually used. (Bug #16484617)

Return value

0 on success, an error code on failure. If the method call succeeds, the computed hash value is made available through hashvalueptr.

Ndb::createEventOperation()

Description

This method creates a subscription to a database event.

NDB API event subscriptions do not persist after an NDB Cluster has been restored using ndb_restore; in such cases, all of the subscriptions must be recreated explicitly.

Signature
NdbEventOperation* createEventOperation
    (
      const char *eventName
    )
Parameters

This method takes a single argument, the unique eventName identifying the event to which you wish to subscribe.

Return value

A pointer to an NdbEventOperation object (or NULL, in the event of failure). See Section 2.3.16, “The NdbEventOperation Class”.

Ndb::dropEventOperation()

Description

This method drops a subscription to a database event represented by an NdbEventOperation object.

Memory used by an event operation which has been dropped is not freed until the event buffer has been completely read. This means you must continue to call pollEvents() and nextEvent() in such cases until these methods return 0 and NULL, respectively in order for this memory to be freed.

Signature
int dropEventOperation
    (
      NdbEventOperation *eventOp
    )
Parameters

This method requires a single input parameter, a pointer to an instance of NdbEventOperation.

Return value

0 on success; any other result indicates failure.

Ndb::EventBufferMemoryUsage

This section describes the EventBufferMemoryUsage structure.

Parent class

Ndb

Description

This structure was added in NDB 7.4 for working with event buffer memory usage statistics. It is used as an argument to Ndb::get_event_buffer_memory_usage().

Attributes

EventBufferMemoryUsage has the attributes shown in the following table:

Table 2.27 EventBufferMemoryUsage structure attributes, with types, initial values, and descriptions

Name Type Initial Value Description
allocated_bytes unsigned none The total event buffer memory allocated, in bytes
used_bytes unsigned none The total memory used, in bytes
usage_percent unsigned none Event buffer memory usage, as a percent (100 * used_bytes / allocated_bytes)

Ndb::getDictionary()

Description

This method is used to obtain an object for retrieving or manipulating database schema information. This Dictionary object contains meta-information about all tables in the cluster.

The dictionary returned by this method operates independently of any transaction. See Section 2.3.3, “The Dictionary Class”, for more information.

Signature
NdbDictionary::Dictionary* getDictionary
    (
      void
    ) const
Parameters

None.

Return value

An instance of the Dictionary class.

Ndb::getDatabaseName()

Description

This method can be used to obtain the name of the current database.

Signature
const char* getDatabaseName
    (
      void
    )
Parameters

None.

Return value

The name of the current database.

Ndb::getDatabaseSchemaName()

Description

This method can be used to obtain the current database schema name.

Signature
const char* getDatabaseSchemaName
    (
      void
    )
Parameters

None.

Return value

The name of the current database schema.

Ndb::getGCIEventOperations() (DEPRECATED)

Description

Iterates over distinct event operations which are part of the current GCI, becoming valid after calling nextEvent(). You can use this method to obtain summary information for the epoch (such as a list of all tables) before processing the event data.

This method is deprecated, and subject to removal in a future release. Where possible, use getNextEventOpInEpoch2() instead.

Signature
const NdbEventOperation* getGCIEventOperations
    (
      Uint32* iter,
      Uint32* event_types
    )
Parameters

An iterator and a mask of event types. Set *iter=0 to start.

Return value

The next event operation; returns NULL when there are no more event operations. If event_types is not NULL, then after calling the method it contains a bitmask of the event types received. .

Ndb::get_eventbuf_max_alloc()

Description

Gets the maximum memory, in bytes, that can be used for the event buffer. This is the same as reading the value of the ndb_eventbuffer_max_alloc system variable in the MySQL Server.

Signature
unsigned get_eventbuf_max_alloc
    (
      void
    )
Parameters

None.

Return value

The mamximum memory available for the event buffer, in bytes.

Ndb::get_eventbuffer_free_percent()

Description

Gets ndb_eventbuffer_free_percent—that is, the percentage of event buffer memory that should be available before buffering resumes, once ndb_eventbuffer_max_alloc has been reached. This value is calculated as used * 100 / ndb_eventbuffer_max_alloc, where used is the amount of event buffer memory actually used, in bytes.

This method was added in NDB 7.4.

Signature
unsigned get_eventbuffer_free_percent
    (
      void
    )
Parameters

The percentage (pct) of event buffer memory that must be present. Valid range is 1 to 99 inclusive.

Return value

None.

Ndb::get_event_buffer_memory_usage()

Description

Gets event buffer usage as a percentage of ndb_eventbuffer_max_alloc. Unlike get_eventbuffer_free_percent(), this method makes complete usage information available in the form of an EventBufferMemoryUsage data structure.

This method was added in NDB 7.4.

Signature
void get_event_buffer_memory_usage
    (
      EventBufferMemoryUsage&
    )
Parameters

A reference to an EventBufferMemoryUsage structure, which receives the usage data.

Return value

None.

Ndb::getHighestQueuedEpoch()

Description

Added in NDB 7.4, this method supersedes getLatestGCI(), which is now deprecated and subject to removal in a future NDB Cluster release.

Prior to NDB 7.4.7, this method returned the highest epoch number in the event queue. In NDB 7.4.7 and later, it returns the highest epoch number found after calling pollEvents2() (Bug #20700220).

Signature
Uint64 getHighestQueuedEpoch
    (
      void
    )
Parameters

None.

Return value

The most recent epoch number, an integer.

Ndb::getLatestGCI() (DEPRECATED)

Description

Gets the index for the most recent global checkpoint.

This method is deprecated in NDB 7.4, and is subject to removal in a future release. In NDB 7.4 and later, you should use getHighestQueuedEpoch() instead.

Signature
Uint64 getLatestGCI
    (
      void
    )
Parameters

None.

Return value

The most recent GCI, an integer.

Ndb::getNdbError()

Description

This method provides you with two different ways to obtain an NdbError object representing an error condition. For more detailed information about error handling in the NDB API, see NDB Cluster API Errors.

Signature

The getNdbError() method actually has two variants.

The first of these simply gets the most recent error to have occurred:

const NdbError& getNdbError
    (
      void
    )

The second variant returns the error corresponding to a given error code:

const NdbError& getNdbError
    (
      int errorCode
    )

Regardless of which version of the method is used, the NdbError object returned persists until the next NDB API method is invoked.

Parameters

To obtain the most recent error, simply call getNdbError() without any parameters. To obtain the error matching a specific errorCode, invoke the method passing the code (an int) to it as a parameter. For a listing of NDB API error codes and corresponding error messages, see Section 2.4, “NDB API Errors and Error Handling”.

Return value

An NdbError object containing information about the error, including its type and, where applicable, contextual information as to how the error arose. See Section 2.3.15, “The NdbError Structure”, for details.

Ndb::getNdbErrorDetail()

Description

This method provides an easy and safe way to access any extra information about an error. Rather than reading these extra details from the NdbError object's details property (now now deprecated in favor of getNdbErrorDetail()‐see Bug #48851). This method enables storage of such details in a user-supplied buffer, returning a pointer to the beginning of this buffer. In the event that the string containing the details exceeds the length of the buffer, it is truncated to fit.

getErrorDetail() provides the source of an error in the form of a string. In the case of a unique constraint violation (error 893), this string supplies the fully qualified name of the index where the problem originated, in the format database-name/schema-name/table-name/index-name, (NdbError.details, on the other hand, supplies only an index ID, and it is often not readily apparent to which table this index belongs.) Regardless of the type of error and details concerning this error, the string retrieved by getErrorDetail() is always null-terminated.

Signature

The getNdbErrorDetail() method has the following signature:

const char* getNdbErrorDetail
            (
              const NdbError& error,
              char*           buffer,
              Uint32          bufferLength
            ) const
Parameters

To obtain detailed information about an error, call getNdbErrorDetail() with a reference to the corresponding NdbError object, a buffer, and the length of this buffer (expressed as an unsigned 32-bit integer).

Return value

When extra details about the error are available, this method returns a pointer to the beginning of the buffer supplied. As stated previously, if the string containing the details is longer than bufferLength, the string is truncated to fit. In the event that no addition details are available, getNdbErrorDetail() returns NULL.

Ndb::getNdbObjectName()

Description

If a name was set for the Ndb object prior to its initialization, you can retrieve it using this method. Used for debugging.

Signature
const char* getNdbObjectName
    (
      void
    ) const
Parameters

None.

Return value

The Ndb object name, if one has been set using setNdbObjectName(). Otherwise, this method returns 0.

Ndb::getNextEventOpInEpoch2()

Description

Iterates over individual event operations making up the current global checkpoint. Use following nextEvent2() to obtain summary information for the epoch, such as a listing of all tables, before processing event data.

Exceptional epochs do not have any event operations associated with them.

Signature
const NdbEventOperation* getNextEventOpInEpoch2
    (
      Uint32* iter,
      Uint32* event_types
    )
Parameters

Set iter to 0 initially; this is NULL when there are no more events within this epoch. If event_types is not NULL, it holds a bitmask of the event types received.

Return value

A pointer to the next NdbEventOperation, if there is one.

Ndb::getNextEventOpInEpoch3()

Description

Iterates over individual event operations making up the current global checkpoint. Use following nextEvent2() to obtain summary information for the epoch, such as a listing of all tables, before processing event data. Is the same as getNextEventOpInEpoch3() but with the addition of a third argument which holds the merger of all AnyValues received, showing which bits are set for all operations on a given table.

Exceptional epochs do not have any event operations associated with them.

This method was added in NDB 7.4.18 and 7.5.9. (Bug #26333981)

Signature
const NdbEventOperation* getNextEventOpInEpoch2
    (
      Uint32* iter,
      Uint32* event_types
      Uint32* cumulative_any_value
    )
Parameters

Set iter to 0 initially; this is NULL when there are no more events within this epoch. If event_types is not NULL, it holds a bitmask of the event types received. If cumulative_any_value is not NULL, it holds the merger of all AnyValues received.

Return value

A pointer to the next NdbEventOperation, if there is one.

Ndb::getReference()

Description

This method can be used to obtain a reference to a given Ndb object. This is the same value that is returned for a given operation corresponding to this object in the output of DUMP 2350.

Signature
Uint32 getReference
    (
      void
    )
Parameters

None.

Return value

A 32-bit unsigned integer.

Ndb::init()

Description

This method is used to initialize an Ndb object.

Signature
int init
    (
      int maxNoOfTransactions = 4
    )
Parameters

The init() method takes a single parameter maxNoOfTransactions of type integer. This parameter specifies the maximum number of parallel NdbTransaction objects that can be handled by this instance of Ndb. The maximum permitted value for maxNoOfTransactions is 1024; if not specified, it defaults to 4.

Each scan or index operation uses an extra NdbTransaction object.

Return value

This method returns an int, which can be either of the following two values:

  • 0: indicates that the Ndb object was initialized successfully.

  • -1: indicates failure.

Ndb::isConsistent() (DEPRECATED)

Description

Check if all events are consistent. If a node failure occurs when resources are exhausted, events may be lost and the delivered event data might thus be incomplete. This method makes it possible to determine if this is the case.

This method is deprecated in NDB 7.4, and is subject to removal in a future release. In NDB 7.4 and later, you should instead use NdbEventOperation::getEventType2() to determine the type of event—in this instance, whether the event is of type TE_INCONSISTENT. See Event::TableEvent.

Signature
bool isConsistent
    (
      Uint64& gci
    )
Parameters

A reference to a global checkpoint index. This is the first inconsistent GCI found, if any.

Return value

true if all events are consistent.

Ndb::isConsistentGCI() (DEPRECATED)

Description

If a node failure occurs when resources are exhausted, events may be lost and the delivered event data might thus be incomplete. This method makes it possible to determine if this is the case by checking whether all events in a given GCI are consistent.

This method is deprecated in NDB 7.4, and is subject to removal in a future release. In NDB 7.4 and later, you should instead use NdbEventOperation::getEventType2() to determine the type of event—in this instance, whether the event is of type TE_INCONSISTENT. See Event::TableEvent.

Signature
bool isConsistentGCI
    (
      Uint64 gci
    )
Parameters

A global checkpoint index.

Return value

true if this GCI is consistent; false indicates that the GCI may be possibly inconsistent.

Ndb::isExpectingHigherQueuedEpochs()

Description

Check whether higher queued epochs have been seen by the last invocation of Ndb::pollEvents2(), or whether a TE_CLUSTER_FAILURE event was found.

It is possible, after a cluster failure has been detected, for the highest queued epoch returned by pollEvents2() not to be increasing any longer. In this case, rather than poll for more events, you should instead consume events with nextEvent() until it detects a TE_CLUSTER_FAILURE is detected, then reconnect to the cluster when it becomes available again.

Signature
bool isExpectingHigherQueuedEpochs
      (
        void
      )
Parameters

None.

Return value

True if queued epochs were seen by the last pollEvents2() call or, in the event of cluster failure.

Ndb::Key_part_ptr

This section describes the Key_part_ptr structure.

Parent class

Ndb

Description

Key_part_ptr provides a convenient way to define key-part data when starting transactions and computing hash values, by passing in pointers to distribution key values. When the distribution key has multiple parts, they should be passed as an array, with the last part's pointer set equal to NULL. See Ndb::startTransaction(), and Ndb::computeHash(), for more information about how this structure is used.

Attributes

A Key_part_ptr has the attributes shown in the following table:

Table 2.28 Key_part_ptr structure attributes, with types, initial values, and descriptions

Attribute Type Initial Value Description
ptr const void* none Pointer to one or more distribution key values
len unsigned none The length of the pointer

Ndb::nextEvent() (DEPRECATED)

Description

Returns the next event operation having data from a subscription queue.

This method clears inconsistent data events from the event queue when processing them. In order to able to clear all such events, applications must call this method even in cases when pollEvents() has already returned 0.

This method is deprecated in NDB 7.4, and is subject to removal in a future release. In NDB 7.4 and later, you should use nextEvent2() instead.

Signature
NdbEventOperation* nextEvent
    (
      void
    )
Parameters

None.

Return value

This method returns an NdbEventOperation object representing the next event in a subscription queue, if there is such an event. If there is no event in the queue, it returns NULL instead.

Ndb::nextEvent2()

Description

Returns the event operation associated with the data dequeued from the event queue. This should be called repeatedly after pollEvents2() populates the queue, until the event queue is empty.

Added in NDB 7.4, this method supersedes nextEvent(), which is now deprecated and subject to removal in a future NDB Cluster release.

After calling this method, use NdbEventOperation::getEpoch() to determine the epoch, then check the type of the returned event data using NdbEventOperation::getEventType2(). Handling must be provided for all exceptional TableEvent types, including TE_EMPTY, TE_INCONSISTENT, and TE_OUT_OF_MEMORY (also introduced in NDB 7.4). No other NdbEventOperation methods than the two named here should be called for an exceptional epoch. Returning empty epochs (TE_EMPTY) may flood applications when data nodes are idle. If this is not desirable, applications should filter out any empty epochs.

Signature
NdbEventOperation* nextEvent2
    (
      void
    )
Parameters

None.

Return value

This method returns an NdbEventOperation object representing the next event in an event queue, if there is such an event. If there is no event in the queue, it returns NULL instead.

Ndb::PartitionSpec

This section provides information about the PartitionSpec structure.

Parent class

Ndb

Description

A PartitionSpec is used for describing a table partition using any one of the following criteria:

  • A specific partition ID for a table with user-defined partitioning.

  • An array made up of a table's distribution key values for a table with native partitioning.

  • A row in NdbRecord format containing a natively partitioned table's distribution key values.

Attributes

A PartitionSpec has two attributes, a SpecType and a Spec which is a data structure corresponding to that SpecType, as shown in the following table:

Table 2.29 PartitionSpec attributes with the SpecType values, data structures, and descriptions for each attribute.

SpecType Enumeration SpecType Value (Uint32) Data Structure Description
PS_NONE 0 none No partitioning information is provided.
PS_USER_DEFINED 1 Ndb::PartitionSpec::UserDefined For a table having user-defined partitioning, a specific partition is identified by its partition ID.
PS_DISTR_KEY_PART_PTR 2 Ndb::PartitionSpec::KeyPartPtr For a table having native partitioning, an array containing the table's distribution key values is used to identify the partition.
PS_DISTR_KEY_RECORD 3 Ndb::PartitionSpec::KeyRecord The partition is identified using a natively partitioned table's distribution key values, as contained in a row given in NdbRecord format.

UserDefined structure.  This structure is used when the SpecType is PS_USER_DEFINED.

Table 2.30 Attribute types of the partitionId attribute of the PS_USER_DEFINED SpecType

Attribute Type Description
partitionId Uint32 The partition ID for the desired table.

KeyPartPtr structure.  This structure is used when the SpecType is PS_DISTR_KEY_PART_PTR.

Table 2.31 Attributes of the PS_DISTR_KEY_PART_PTR SpecType, with attribute types and descriptions

Attribute Type Description
tableKeyParts Key_part_ptr Pointer to the distribution key values for a table having native partitioning.
xfrmbuf void* Pointer to a temporary buffer used for performing calculations.
xfrmbuflen Uint32 Length of the temporary buffer.

KeyRecord structure.  This structure is used when the SpecType is PS_DISTR_KEY_RECORD.

Table 2.32 PS_DISTR_KEY_RECORD SpecType attributes, with attribute types and descriptions

Attribute Type Description
keyRecord NdbRecord A row in NdbRecord format, containing a table's distribution keys.
keyRow const char* The distribution key data.
xfrmbuf void* Pointer to a temporary buffer used for performing calculations.
xfrmbuflen Uint32 Length of the temporary buffer.

Definition from Ndb.hpp Because this is a fairly complex structure, we here provide the original source-code definition of PartitionSpec, as given in storage/ndb/include/ndbapi/Ndb.hpp:

struct PartitionSpec
{
  /*
    Size of the PartitionSpec structure.
  */
  static inline Uint32 size()
  {
      return sizeof(PartitionSpec);
  }

  enum SpecType
  {
    PS_NONE                = 0,
    PS_USER_DEFINED        = 1,
    PS_DISTR_KEY_PART_PTR  = 2,
    PS_DISTR_KEY_RECORD    = 3
  };

  Uint32 type;
  
  union
  {
    struct {
      Uint32 partitionId;
    } UserDefined;
    
    struct {
      const Key_part_ptr* tableKeyParts;
      void* xfrmbuf;
      Uint32 xfrmbuflen;
    } KeyPartPtr;

    struct {
      const NdbRecord* keyRecord;
      const char* keyRow;
      void* xfrmbuf;
      Uint32 xfrmbuflen;
    } KeyRecord;
  };
};

Ndb::pollEvents()

Description

This method waits for a GCP to complete. It is used to determine whether any events are available in the subscription queue.

This method waits for the next epoch, rather than the next GCP. See Section 2.3.16, “The NdbEventOperation Class”, for more information.

This method is deprecated and subject to removal in a future NDB Cluster release; use pollEvents2() instead.

Signature
int pollEvents
    (
      int     maxTimeToWait,
      Uint64* latestGCI = 0
    )
Parameters

This method takes the two parameters listed here:

  • The maximum time to wait, in milliseconds, before giving up and reporting that no events were available (that is, before the method automatically returns 0).

    A negative value causes the wait to be indefinite and never time out. This is not recommended (and is not supported by the successor method pollEvents2()).

  • The index of the most recent global checkpoint. Normally, this may safely be permitted to assume its default value, which is 0.

Return value

pollEvents() returns a value of type int, which may be interpreted as follows:

  • > 0: There are events available in the queue.

  • 0: There are no events available.

  • In NDB 7.6.28, 8.0.35, 8.2.0, and later releases, a negative value indicates failure and NDB_FAILURE_GCI (~(Uint64)0) indicates cluster failure (Bug #35671818); 1 is returned when encountering an exceptional event, except when only TE_EMPTY events are found, as described later in this section.

When pollEvents() finds an exceptional event at the head of the event queue, the method returns 1 and otherwise behaves as follows:

  • Empty events (TE_EMPTY) are removed from the event queue head until an event containing data is found. When this results in the entire queue being processed without encountering any data, the method returns 0 (no events available) rather than 1. This behavior makes this event type transparent to an application using pollEvents().

  • After encountering an event containing inconsistent data (TE_INCONSISTENT) due to data node buffer overflow, the next call to nextEvent() call removes the inconsistent data event data from the event queue, and returns NULL. You should check the inconsistency by calling isConsistent() immediately thereafter.

    Important: Although the inconsistent event data is removed from the event queue by calling nextEvent(), information about the inconsistency is removed only by another nextEvent() call following this, that actually finds an event containing data.

  • When pollEvents() finds a data buffer overflow event (TE_OUT_OF_MEMORY), the event data is added to the event queue whenever event buffer usage exceeds ndb_eventbuffer_max_alloc. In this case, the next call to nextEvent() exits the process.

Ndb::pollEvents2()

Description

Waits for an event to occur. Returns as soon as any event data is available. This method also moves an epoch's complete event data to the event queue.

This method supersedes pollEvents(), which is now deprecated and subject to removal in a future NDB Cluster release.

Signature
int pollEvents2
    (
      int aMillisecondNumber,
      Uint64* highestQueuedEpoch = 0
    )
Parameters

This method takes the two parameters listed here:

  • The maximum time to wait, in milliseconds, before giving up and reporting that no events were available (that is, before the method automatically returns 0).

    Specifying a negative value for this argument causes pollEvents2() to return -1, indicating an error.

  • The index of the highest queued epoch. Normally, this may safely be permitted to assume its default value, which is 0. If this value is not NULL and new event data is available in the event queue, it is set to the highest epoch found in the available event data.

Return value

pollEvents2() returns an integer whose value can be interpreted as follows:

  • > 0: There are events available in the queue.

  • 0: There are no events available.

  • < 0: Indicates failure (possible error).

Ndb::setDatabaseName()

Description

This method is used to set the name of the current database.

Signature
void setDatabaseName
    (
      const char *databaseName
    )
Parameters

setDatabaseName() takes a single, required parameter, the name of the new database to be set as the current database.

Return value

None.

Ndb::setDatabaseSchemaName()

Description

This method sets the name of the current database schema.

Signature
void setDatabaseSchemaName
    (
      const char *databaseSchemaName
    )
Parameters

The name of the database schema.

Return value

None.

Ndb::setEventBufferQueueEmptyEpoch()

Description

Queuing of empty epochs is disabled by default. This method can be used to enable such queuing, in which case any new, empty epochs entering the event buffer following the method call are queued.

When queuing of empty epochs is enabled, nextEvent() associates an empty epoch to one and only one of the subscriptions (event operations) connected to the subscribing Ndb object. This means that there can be no more than one empty epoch per subscription, even though the user may have many subscriptions associated with the same Ndb object.

setEventBufferQueueEmptyEpoch() has no associated getter method. This is intentional, and is due to the fact this setter applies to queuing new epochs, whereas the queue itself may still reflect the state of affairs that existed prior to invoking the setter. Thus, during a transition period, an empty epoch might be found in the queue even if queuing is turned off.

setEventBufferQueueEmptyEpoch() was added in NDB 7.4.11.

Signature
void setEventBufferQueueEmptyEpoch
  (
    bool queue_empty_epoch
  )
Parameters

This method takes a single input parameter, a boolean. Invoking the method with true enables queuing of empty events; passing false to the method disables such queuing.

Return value

None.

Ndb::set_eventbuf_max_alloc()

Description

Sets the maximum memory, in bytes, that can be used for the event buffer. This has the same effect as setting the value of the ndb_eventbuffer_max_alloc system variable in the MySQL Server.

Signature
void set_eventbuf_max_alloc
    (
      unsigned size
    )
Parameters

The desired maximum size for the event buffer, in bytes.

Return value

None.

Ndb::set_eventbuffer_free_percent()

Description

Sets ndb_eventbuffer_free_percent—that is, the percentage of event buffer memory that should be available before buffering resumes, once ndb_eventbuffer_max_alloc has been reached.

This method was added in NDB 7.4.

Signature
int set_eventbuffer_free_percent
    (
      unsigned pct
    )
Parameters

The percentage (pct) of event buffer memory that must be present. Valid range is 1 to 99 inclusive.

Return value

The value that was set.

Ndb::setNdbObjectName()

Description

You can also set an arbitrary, human-readable name to identify an Ndb object for debugging purposes. This name can then be retrieved using getNdbObjectName(). This must be done prior to calling init() for this object; trying to set a name after initialization fails with an error.

You can set a name only once for a given Ndb object; subsequent attempts after the name has already been set fail with an error.

Signature
int setNdbObjectName
    (
      const char* name
    )
Parameters

A name that is intended to be human-readable.

Return value

0 on success.

Ndb::startTransaction()

Description

This method is used to begin a new transaction. There are three variants, the simplest of these using a table and a partition key or partition ID to specify the transaction coordinator (TC). The third variant makes it possible for you to specify the TC by means of a pointer to the data of the key.

When the transaction is completed it must be closed using NdbTransaction::close() or Ndb::closeTransaction(). Failure to do so aborts the transaction. This must be done regardless of the transaction's final outcome, even if it fails due to an error.

See Ndb::closeTransaction(), and NdbTransaction::close(), for more information.

Signature
NdbTransaction* startTransaction
    (
      const NdbDictionary::Table* table = 0,
      const char* keyData = 0,
      Uint32* keyLen = 0
    )
Parameters

This method takes the following three parameters:

  • table: A pointer to a Table object. This is used to determine on which node the transaction coordinator should run.

  • keyData: A pointer to a partition key corresponding to table.

  • keyLen: The length of the partition key, expressed in bytes.

Distribution-aware forms of startTransaction().  It is also possible to employ distribution awareness with this method; that is, to suggest which node should act as the transaction coordinator.

Signature
NdbTransaction* startTransaction
    (
      const NdbDictionary::Table* table,
      const struct Key_part_ptr*  keyData,
      void*                       xfrmbuf = 0,
      Uint32                      xfrmbuflen = 0
    )
Parameters

When specifying the transaction coordinator, this method takes the four parameters listed here:

  • A pointer to a table (Table object) used for deciding which node should act as the transaction coordinator.

  • A null-terminated array of pointers to the values of the distribution key columns. The length of the key part is read from metadata and checked against the passed value.

    An Ndb::Key_part_ptr is defined as shown in Ndb::Key_part_ptr.

  • A pointer to a temporary buffer, used to calculate the hash value.

    If xfrmbuf is NULL (the default), then a call to malloc() or free() is made automatically, as appropriate.

    Prior to NDB 7.5.30, 7.6.26, 8.0.33: startTransaction() fails if xfrmbuf is not NULL and xfrmbuflen is too small.

    NDB 7.5.30 and later, 7.6.26 and later, 8.0.33 and later: If the buffer passed is not of sufficient size, a temporary buffer is allocated automatically. (Bug #103814, Bug #32959894, Bug #34917498)

  • The length of the buffer.

Return value

On success, an NdbTransaction object. In the event of failure, NULL is returned.

Example

Suppose that the table's partition key is a single BIGINT column. Then you would declare the distribution key array as shown here:

Key_part_ptr distkey[2];

The value of the distribution key would be defined as shown here:

unsigned long long distkeyValue= 23;

The pointer to the distribution key array would be set as follows:

distkey[0].ptr= (const void*) &distkeyValue;

The length of this pointer would be set accordingly:

distkey[0].len= sizeof(distkeyValue);

The distribution key array must terminate with a NULL element. This is necessary to avoid to having an additional parameter providing the number of columns in the distribution key:

distkey[1].ptr= NULL;
distkey[1].len= NULL;

Setting the buffer to NULL permits startTransaction() to allocate and free memory automatically:

xfrmbuf= NULL;
xfrmbuflen= 0;

Now, when you start the transaction, you can access the node that contains the desired information directly.

Another distribution-aware version of this method makes it possible for you to specify a table and partition (using the partition ID) as a hint for selecting the transaction coordinator, and is defined as shown here:

NdbTransaction* startTransaction
    (
      const NdbDictionary::Table* table,
      Uint32 partitionId
    )

In the event that the cluster has the same number of data nodes as it has fragment replicas, specifying the transaction coordinator gains no improvement in performance, since each data node contains the entire database. However, where the number of data nodes is greater than the number of fragment replicas (for example, where NoOfReplicas is set equal to 2 in a cluster with four data nodes), you should see a marked improvement in performance by using the distribution-aware version of this method.

It is still possible to use this method as before, without specifying the transaction coordinator. In either case, you must still explicitly close the transaction, whether or not the call to startTransaction() was successful.