07 / 26Part 1: Define your first entityBeginner
Query every book
Queries let you read data from the blockchain. This lesson walks you through writing a query and then testing it.
Define the query
Add the following Rell code to src/main/queries.rell:
query get_all_books() { return book @* { } ( .isbn, .title, .author );}Breakdown of the query
querykeyword: Declares a new query. It plays a role comparable to aSELECTstatement in SQL and returns data from the blockchain.@*operand: Writingbook @*tells Rell the query can return any number ofbookobjects, including none.- Filter criteria: You place query conditions inside the curly braces
{}. They are empty here, so every entry is returned. - Attributes: The part after the curly braces lists the attributes to return:
.isbn,.title, and.author.
The result is a collection of every book, where each item carries its isbn, title, and author.
Update the unit tests
Next, extend the tests so they verify the query's behavior.
Step 1: Update imports
In src/test/book_review_test.rell, change the import statement to the following:
import main.{ book, create_book, get_all_books };Step 2: Add the new test function
Add this test function to the same file:
function test_get_books() { rell.test.tx() .op(create_book("123", "Book1", "Author1")) .op(create_book("124", "Book2", "Author2")) .run(); val books = get_all_books(); assert_equals(books.size(), 2);}Breakdown of the test
- Transaction creation:
rell.test.tx()builds a transaction for testing. - Adding operations: The transaction receives two
create_bookoperations. - Execution: Calling
run()executes the transaction. - Query and assertions:
get_all_books()fetches the books, and the test asserts that exactly 2 were returned.
From your project folder, run the tests with this terminal command:
chr testTest on a local Chromia node
To check the query against a local Chromia node:
-
Update or start the local Chromia node:
-
If your node is running, update it with:
shell chr node update -
If your node is not running, start it with:
shell chr node start
-
-
Run the query: Open another terminal window or tab and run:
shell chr query get_all_booksThe output lists the books stored so far, such as any you added earlier with the
create_bookoperation. If you completed the previous steps, the result should resemble this:json [ { "author": "George Orwell", "isbn": "ISBN1234", "title": "1984" }]This output shows that the query returns the stored book from the blockchain as expected.
You have now stored entities on your test node's blockchain and written a query that returns a collection of all books.