美文网首页
EOSIO 升级数据表结构

EOSIO 升级数据表结构

作者: IT孤独者 | 来源:发表于2018-11-18 18:43 被阅读0次
#include <eosiolib/eosio.hpp>
#include <eosiolib/transaction.hpp>
#include <eosiolib/datastream.hpp>
using namespace eosio;

class hello : public eosio::contract
{
 public:
   using contract::contract;

   /// @abi action
   void hi(account_name user)
   {
      print("Hello, ", name{user});
   }

   /// @abi action
   void addstu(int64_t id)
   {
      students t(_self, _self);
      auto existing = t.find(id);
      eosio_assert(existing == t.end(), "id already exists");
      t.emplace(_self, [&](auto &r) {
         r.id = id;
      });
   }

   /// @abi action
   void update(std::string name)
   {
      students t(_self, _self);
      auto r = t.begin();
      if (r == t.end())
      {
         return; // 所有记录都已经更新完毕
      }

      students2 t2(_self, _self);
      auto existing = t2.find(r->id);
      if (existing == t2.end())
      {
         t2.emplace(_self, [&](auto &r2) {
            r2.id = r->id;
            r2.name = name;
         });
      }

      auto id = r->id; // 构造有效的id

      t.erase(r); // 删除对应的记录

      transaction trx; // 构造新的 trx
      trx.actions.emplace_back(std::move(action{permission_level{_self, N(active)}, _self, eosio::string_to_name("update"), std::tuple<std::string>{name}}));

      constexpr size_t max_stack_buffer_size = 512;
      size_t size = pack_size(trx);
      char *buff = (char *)(size < max_stack_buffer_size ? malloc(size) : alloca(size));
      datastream<const char *> ds(buff, size);
      ds << trx;

      send_deferred((uint128_t(id) << 64) | id, _self, buff, size); // 更新下一条记录
   }

 private:
   /// @abi table student i64
   struct student
   {
      int64_t id;

      auto primary_key() const { return id; }
   };

   /// @abi table student2 i64
   struct student2
   {
      int64_t id;
      std::string name;
      auto primary_key() const { return id; }
   };

   typedef eosio::multi_index<N(student), student> students;
   typedef eosio::multi_index<N(student2), student2> students2;
};

EOSIO_ABI(hello, (hi)(addstu)(update))

相关文章

网友评论

      本文标题:EOSIO 升级数据表结构

      本文链接:https://www.haomeiwen.com/subject/wcwgfqtx.html