Advanced EOS Series — Part 4 — Table Uniqueness
Welcome back to the Advanced EOS development series, here I’ll be touching on advanced techniques and functionality which is rarely covered by tutorials or courses. The purpose of this series is to bring together the missing pieces you’ll need to complete your skills as a distributed application developer on the EOS network. Each post is ordered by difficulty, so if you’d like a general overview I’d recommend starting with Part 1 and working your way up. The full code for these examples can be found here on GitHub.
As these are advanced or extended topics, I’m dangerously assuming you already know the basics and are looking to further your knowledge. For that reason, the code shared in these articles will be concise only to the purpose being discussed.
This post will be relatively short, but cover a fundamental and seemingly uncovered method with multi index tables, unique primary indexes.
Unique Indexes
By now we’re able to create rows in our tables indexed by our unique account_name
identifiers, but how do we use a different primary_key
and ensure it's unique? Fortunately the developers at EOSio have provided us with the available_primary_key()
function.
Let’s begin by creating a struct to define an Item
in our items
table. We’ll use a uint64_t
like normal to specify our primary key called id
.
// @abi table items i64
struct Item {
uint64_t id;
string name;
uint64_t attack;
account_name owner;
auto primary_key() const { return id; };
EOSLIB_SERIALIZE(Item, (id)(name)(attack));
};
typedef multi_index<N(items), Item> items_table;
You’ll notice this is the same table struct we used in Advanced EOS Series — Part 3 — Secondary Indexes. Let’s now update our actions to generate a unique primary key, instead of requiring them as an argument.
void inventory::create(const account_name account, const string name, const uint64_t attack) {
items_table items(_self, _self);
items.emplace(account, account, [&](auto& item) {
item.id = items.available_primary_key();
item.name = name;
item.attack = attack;
item.owner = account;
});
}
We’ve removed the uint64_t index
from our action void post(const account_name username, uint64_t index const string& msg_str)
, and we’ve replaced the index
with items.available_primary_key()
to set the primary key id
when we’re creating a new item.