Overview
This how-to provides instructions to delete an object from a Key-Value Table
(kv table
).
Use the method erase
defined by the eosio::kv::table
type to accomplish this task.
Before you begin
Make sure you have the following prerequisites in place:
- An EOSIO development environment, for details consult the Get Started Guide
- A smart contract named
smrtcontract
- A user defined type,
struct
orclass
, which defines the data stored in the map, namedperson
- A
kv table
data type,struct
orclass
, which inheritseosio::kv::table
, and stores objects of typeperson
, namedaddress_table
- A primary index is defined for the
kv table
for theperson::account_name
data member
Refer to the following reference implementation for your starting point:
smartcontract.hpp file
struct person {
eosio::name account_name;
std::string first_name;
std::string last_name;
std::string personal_id;
};
class [[eosio::contract]] smrtcontract : public contract {
struct [[eosio::table]] address_table : eosio::kv::table<person, "kvaddrbook"_n> {
index<name> account_name_uidx {
name{"accname"_n},
&person::account_name };
address_table(name contract_name) {
init(contract_name, account_name_uidx)
}
};
public:
using contract::contract;
};
Procedure
Complete the following steps to delete a person
object from address_table
:
- Create a new action
delete
, in a smart contract class, which takes as input parameters an account name, a first name, a last name and a personal id. - In the
delete
action access the instance ofaddress_table
by declaring a local variable ofaddress_table
type. - Call the
erase
method of theaddress_table
and pass to it the primary key for the object which is deleted. If you try to erase an object which is not present in thekv table
no error will be raised.
Refer to the following reference implementation to delete a person
object from address_table
:
smartcontract.hpp file
class [[eosio::contract]] smrtcontract : public contract {
struct [[eosio::table]] address_table : eosio::kv::table<person, "kvaddrbook"_n> {
index<name> account_name_uidx {
name{"accname"_n},
&person::account_name };
address_table(name contract_name) {
init(contract_name, account_name_uidx)
}
};
public:
using contract::contract;
// deletes a person based on primary key account_name
[[eosio::action]]
void del(eosio::name account_name);
using del_action = eosio::action_wrapper<"del"_n, &smrtcontract::del>;
};
smartcontract.cpp file
[[eosio::action]]
void smrtcontract::delete(eosio::name account_name) {
address_table addresses{"kvaddrbook"_n};
// delete from kv table
addresses.erase(account_name, get_self());
}
Summary
In conclusion, the above instructions show how to delete an object from a Key-Value Table
(kv table
).
Next Steps
- Check if the newly inserted
person
was actually deleted from the table. To accomplish this task, use theexists()
function of any index defined for the table.