Using Steem-API with Ruby Part 14 — Query specific rows from a Steem Engine Table

in utopian-io •  7 days ago  (edited)

Steemit_Ruby_Engine.jpg

Repositories

SteemRubyTutorial

All examples from this tutorial can be found as fully functional scripts on GitHub:

radiator

Steem Engine

steem-engine_logo-horizontal-dark.png

What Will I Learn?

This tutorial shows how to interact with the Steem blockchain, Steem database and Steem Engine using Ruby. When accessing Steem Engine using Ruby their only one APIs available to chose: radiator.

img_train-dark.png

In this particular chapter you learn how to read a create a query and return all row from the Steem Engine database tables which matches this query.

Requirements

Basic knowledge of Ruby programming is needed. It is necessary to install at least Ruby 2.5 as well as the following ruby gems:

gem install bundler
gem install colorize
gem install contracts
gem install radiator

Difficulty

For reader with programming experience this tutorial is basic level.

Tutorial Contents

Steem Engine allows users to add tokens and contacts to the steem block chain. Currently three predefined contracts are know: "tokens", "market", and "steempegged". Each contract has one or more database table to store their data. Currently 10 tables are known:

Unique nameContactTable
market_buyBookmarketbuyBook
market_metricsmarketmetrics
market_sellBookmarketsellBook
market_tradesHistorymarkettradesHistory
steempegged_withdrawalssteempeggedwithdrawals
tokens_balancestokensbalances
tokens_contractsBalancestokenscontractsBalances
tokens_paramstokensparams
tokens_pendingUnstakestokenspendingUnstakes
tokens_tokenstokenstokens

Implementation using radiator

As mentioned only radiator offers an API to access Steem Engine. For this radiator offerers a name space called Radiator::SSC. To access the database tables there are two methods: Contracts.find_one and Contracts.find. The former was described in the previous part of the tutorial.

Im this part of the tutorial Contracts.find is used to access a selection of rows of any table. The method has three mandatory parameters: contract, table and query and three optional parameter limit, offset and descending:

parameterdescription
contractThe name of the contract.
tableThe name of the tables to query.
queryA list of column names and values.
limitmaximum amount of rows to be returned.
offsetoffset of the first row to be returned.
descendingset order to ascending or descending.

The amount of rows read from database in a single query. If the overall results exceeds this limit then additional queries are made to get the full result set. One thousand seem to be the standard for Steem queries.

Query_Limit = 1000

Read arguments from command line. There are two options:

  • When two parameter are given then print all rows from a database table.
  • When more then two parameter are given then print the rows from database which match the criteria given.
   _contract = ARGV.shift
   _table = ARGV.shift
   _query = {}

   while ARGV.length >= 2 do
      # the query parameter is a hash table with column
      # names as key and column values as value.
      #
      _query[ARGV.shift] = ARGV.shift
   end

Steem Engine uses a simpler but more error prone numeric index to load the rows in batches. It's easier as only a numeric index is used to keep track of the start row. But it will lead to duplicate and missing rows when rows are added or deleted while iterating over the result set.

   _current = 0
   loop do
      _rows = Contracts.find(
         contract: _contract,
         table: _table,
         query: _query,
         limit: Query_Limit,
         offset: _current,
         descending: false
      )

      # exit loop when no result set is returned
      #
   break if (not _rows) || (_rows.length == 0)
      pp _rows

      # Move current by the actual amount of rows returned
      #
      _current = _current + _rows.length
   end

   # at the end of the loop _current holds the total amount
   # of rows returned. If nothing was found _current is 0.
   #
   if _current == 0 then
      puts "No data found, possible reasons:".red + "
   ⑴ The contract doesn't exist
   ⑵ The table doesn't exist
   ⑶ The query doesn't match any rows
   ⑷ The table is empty"
   else
      puts "Found %1$d rows".green % _current
   end
end

Hint: Follow this link to Github for the complete script with comments and syntax highlighting : Steem-Print-SSC-Table-All.rb.

A closer look at the results

The Steem-Print-SSC-Table-All.rb script is a quite powerfull script which allows for a large variety of queries.

The »params« table

The »params« table only contains a single row with the current price in STEEM for creating a new token which is currently 100 STEEM.

Screenshot at Jun 11 16-06-21.png

The »tokens« table

The »tokens« table contains the parameters of Steem Engine Token like the token distributed and maximum amount of token which can be distributed.

Screenshot at Jun 12 09-49-02.png

I have chosen the BEER token from @beerlover as it's the only token I hold.

beertoken%20by%20beerlover.png

The »balances« table

The »balances« table holds the current token in the users wallets. The balances can be queried by account and by token.

query balances by account name

To get all balances of an account you you query by column name account.

Screenshot at Jun 12 10-12-35.png

query balances by token

To get all balances of an account you query by column name symbol. For the sample query is further restricted by current balance of 10 token.

Screenshot at Jun 12 10-09-20.png

The »metrics« table

The »metrics« table holds the current value in STEEM of the token on the Steem Engine Market.

Screenshot at Jun 12 10-14-37.png

Steem Engine Market.png

A future tutorial will show how to combine all these information to further improve Steem-Print-Balances.rb so that Steem Engine token held are be printed as well.

Curriculum

First tutorial

Previous tutorial

Next tutorial

Proof of Work

Image Source

Beneficiary

comment votes posts level payout commented voted

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for your contribution @krischik.
After analyzing your tutorial we suggest the following points below:

  • Your tutorial is very well explained and structured. Good work on the development of this contribution.

  • Thank you for following our suggestions in your previous tutorial.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

·

Thank you for your review, @portugalcoin! Keep up the good work!

Congratulations @krischik! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 400 comments. Your next target is to reach 500 comments.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

You can upvote this notification to help all Steem users. Learn how here!

Hi, @krischik!

You just got a 6.22% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.

Hi @krischik!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @krischik!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!