Skip to main content

Iterate over Composition

Iterate and retrieve data from a composition based on primary index. Complete the following steps to iterate, retrieve and print data from the container indexed composition.

Define The getter Action

Add a getter action to the container indexed composition. The getter action takes an account name as a parameter.

[[inery::action]] void getter( name owner );
tip

Optionally, for ease of use add the action wrapper definition as well.

[[inery::action]] void getter( name owner );

using getter_action = action_wrapper<"getter"_n, &database::getter>;

Implement The getter Action

Search for the owner name in the indexed composition using the primary index. If found, print out the value of field data. Otherwise raise an error with a custom message. In the contract definition add the following implementation for getter action:

  [[inery::action]] void database::getter( name owner ) {
// searches for the row that corresponds to the owner parameter
auto itr = container.find(owner.value);

// asserts if the row was found for owner parameter, if fails use the given message
check( itr != container.end(), "owner does not exist in composition" );

// prints the owner and data fields stored for owner parameter
inery::print_f("Test Table : {%, %}\n", itr->owner, itr->data);
}

Put It All Together

The full definition and implementation files for the contract should look like this

#include <inery/inery.hpp>
using namespace inery;

// multi-index example contract class
class [[inery::contract]] database : public contract {
public:
using contract::contract;

// contract class constructor
database( name receiver, name code, datastream<const char*> ds ) :
// contract base class contructor
contract(receiver, code, ds),
// instantiate multi-index instance as data member (find it defined below)
container(receiver, receiver.value)
{ }

// the row structure of the indexed composition, that is, each row of the composition
// will contain an instance of this type of structure
struct [[inery::table]] data_structure {
// this data member stores a name for each row of the indexed composition
name owner;
// additional data stored in composition row
uint64_t data;
// mandatory definition for primary key getter
uint64_t primary_key( ) const { return owner.value; }
};

// the multi-index type definition, for ease of use define a type alias `data_structure_t`,
// based on the multi_index template type, parametarized with a random name and
// the data_structure data structure
typedef inery::multi_index<"container"_n, data_structure> data_structure_t;

// the indexed composition instance declared as a data member of type data_structure_t
data_structure_t container;

[[inery::action]] void set( name owner );
[[inery::action]] void getter( name owner );

using set_action = action_wrapper<"set"_n, &database::set>;
using getter_action = action_wrapper<"getter"_n, &database::getter>;
};