mod.rs
Overview
This file defines the GraphQL query root and associated types for querying blockchain-related data, accounts, messages, transactions, and blocks from a database. It provides the main entry points for GraphQL queries, implementing filtering, ordering, and pagination capabilities with asynchronous database access. The file leverages the async-graphql library to expose these queries in a GraphQL API, and integrates with a SQLite database through the sqlx crate. It also includes support for DataLoader batching and caching to optimize loading related entities such as messages and transactions.
Enumerations
QueryOrderByDirection
pub enum QueryOrderByDirection {
ASC,
DESC,
}
Purpose: Specifies the direction of sorting when querying documents.
Variants:
ASC: Sorts documents in ascending order (e.g., A to Z).DESC: Sorts documents in descending order (e.g., Z to A).
Traits: Implements
Debug,Copy,Clone,Eq, andPartialEq.Display Implementation: Formats the enum variant as its name string, e.g.,
"ASC"or"DESC".
Usage Example:
let direction = QueryOrderByDirection::ASC;
println!("Sort direction: {}", direction); // Output: Sort direction: ASC
Structs
QueryOrderBy
pub struct QueryOrderBy {
pub path: Option<String>,
pub direction: Option<QueryOrderByDirection>,
}
Purpose: Specifies sorting criteria for query results, including the path to a field and the direction.
Fields:
path: Optional string representing the path to the field used for sorting. Supports nested fields separated by dots (e.g.,"foo.bar.baz").direction: OptionalQueryOrderByDirectionindicating ascending or descending order.
Traits: Implements
InputObject(for GraphQL input) andDebug.
Usage Example:
GraphQL query input might specify:
orderBy: [{ path: "timestamp", direction: ASC }]
Main Struct: QueryRoot
pub struct QueryRoot;
Purpose: Serves as the root object for all GraphQL queries exposed by this schema module.
Methods: Implements various asynchronous GraphQL query methods annotated with
#[Object].
QueryRoot Methods
info
async fn info(&self, ctx: &Context<'_>) -> FieldResult<Option<Info>>
Purpose: Returns general blockchain-related information.
Parameters:
ctx: GraphQL context, providing access to database pool and field lookahead.
Returns: An optional
Infoobject wrapped in aFieldResult.Behavior:
Checks if the client requested the
last_block_timefield.If yes, queries the latest block from the database and extracts its generation time.
Returns an
Infoobject withlast_block_timeset or default otherwise.
account
async fn account(&self, address: String) -> Option<AccountQuery>
Purpose: Retrieves account information by address.
Parameters:
address: The account address string.
Returns: An
AccountQueryobject wrapping the address for further querying.
blocks
async fn blocks(
&self,
ctx: &Context<'_>,
filter: Option<BlockFilter>,
order_by: Option<Vec<Option<QueryOrderBy>>>,
limit: Option<i32>,
_timeout: Option<f64>,
) -> FieldResult<Option<Vec<Option<Block>>>>
Purpose: Queries blocks from the database with optional filtering, ordering, and limiting.
Parameters:
ctx: GraphQL context.filter: OptionalBlockFilterinput to specify filtering conditions.order_by: Optional list of optionalQueryOrderByobjects for sorting.limit: Optional limit on number of blocks returned._timeout: Optional timeout parameter (currently unused).
Returns: A list of optional
Blockinstances wrapped inFieldResult.Behavior:
Converts filters and order instructions into SQL WHERE and ORDER BY clauses.
Queries blocks asynchronously from the
db::Blockmodel.If the client requested inbound message descriptions (
in_msg_descr), fetches inbound messages for each block.If outbound messages are requested, uses
MessageLoaderDataLoader to batch load message data asynchronously.Returns the enriched block list.
accounts
async fn accounts(
&self,
ctx: &Context<'_>,
filter: Option<AccountFilter>,
order_by: Option<Vec<Option<QueryOrderBy>>>,
limit: Option<i32>,
_timeout: Option<f64>,
) -> FieldResult<Option<Vec<Option<Account>>>>
Purpose: Queries account data with support for filtering, ordering, and limiting.
Parameters: Similar to
blocks.Returns: List of optional
Accountobjects.Behavior:
Processes filters and orders.
Queries accounts from
db::Account.Converts database entities into GraphQL
Accountobjects.
messages
async fn messages(
&self,
ctx: &Context<'_>,
filter: Option<MessageFilter>,
order_by: Option<Vec<Option<QueryOrderBy>>>,
limit: Option<i32>,
_timeout: Option<f64>,
) -> FieldResult<Option<Vec<Option<Message>>>>
Purpose: Retrieves messages with optional filters, ordering, and limits.
Parameters: Similar to above.
Returns: List of optional
Messageobjects.Behavior:
Queries messages from database.
Uses
TransactionLoaderDataLoader to batch-load related transactions if requested by the client:Loads the source transaction (
src_transaction) if requested.Loads the destination transaction (
dst_transaction) by querying the database and then loading transaction details.
Returns enriched message list.
transactions
async fn transactions(
&self,
ctx: &Context<'_>,
filter: Option<TransactionFilter>,
order_by: Option<Vec<Option<QueryOrderBy>>>,
limit: Option<i32>,
_timeout: Option<f64>,
) -> FieldResult<Option<Vec<Option<Transaction>>>>
Purpose: Queries blockchain transactions with filtering, sorting, and limits.
Parameters: Similar to above.
Returns: List of optional
Transactionobjects.Behavior:
Queries transactions from database.
Loads related messages using
MessageLoaderDataLoader if requested:Loads inbound message (
in_message).Loads outbound messages (
out_messages) as a list.
Returns enriched transaction list.
blockchain
async fn blockchain<'ctx>(
&'ctx self,
ctx: &'ctx Context<'ctx>,
) -> FieldResult<Option<BlockchainQuery<'ctx>>>
Purpose: Provides access to blockchain-specific queries grouped under
BlockchainQuery.Parameters:
ctx: GraphQL context.
Returns: An optional
BlockchainQueryobject for further blockchain queries.
Important Implementation Details
DataLoader Integration: The file leverages
DataLoaderinstances (MessageLoader,TransactionLoader) to batch and cache requests for related entities, improving performance by avoiding repeated database hits.Filtering and Sorting: Custom
Filterstructs (BlockFilter,AccountFilter, etc.) are converted to SQL WHERE clauses via theirto_where()methods. Sorting instructions are converted using a helperquery_order_by_str.Lookahead Optimization: Uses GraphQL's field lookahead (
ctx.look_ahead()) to conditionally load related data only if requested by the client, minimizing unnecessary database queries.Async Database Access: All data queries are asynchronous, leveraging
async/awaitand thesqlxcrate to interact with a SQLite database.Conversion Between DB and GraphQL Types: The file converts database models (
db::Block,db::Account, etc.) into GraphQL schema types (Block,Account, etc.) usingIntoandFromtrait implementations.
Interaction With Other Modules
Database Layer: Uses
dbmodule entities (db::Block,db::Account,db::Message,db::Transaction) for querying persistent data.GraphQL Schema Types: References GraphQL schema objects and input types from sibling modules in
crate::schema::graphqlandcrate::schema::graphql_ext.Helpers: Uses a helper function
query_order_by_strto convert order instructions into SQL clauses.Blockchain API: Exposes nested blockchain queries via the
blockchain_api::BlockchainQuerystruct.Message and Transaction Loaders: Uses
MessageLoaderandTransactionLoaderto batch-load related entities efficiently.
Mermaid Diagram: Structure of mod.rs (Class Diagram)
classDiagram
class QueryRoot {
+info(ctx)
+account(address)
+blocks(ctx, filter, order_by, limit, timeout)
+accounts(ctx, filter, order_by, limit, timeout)
+messages(ctx, filter, order_by, limit, timeout)
+transactions(ctx, filter, order_by, limit, timeout)
+blockchain(ctx)
}
class QueryOrderBy {
+path: Option<String>
+direction: Option<QueryOrderByDirection>
}
class QueryOrderByDirection {
<<enum>>
+ASC
+DESC
}
QueryRoot --> QueryOrderBy
QueryRoot --> QueryOrderByDirection
This diagram represents the main types in this file, showing QueryRoot as the principal class exposing multiple asynchronous query methods. The sorting enum QueryOrderByDirection and sorting criteria struct QueryOrderBy are related as inputs to these queries.