diff --git a/src/tribler/core/components/bandwidth_accounting/db/database.py b/src/tribler/core/components/bandwidth_accounting/db/database.py index e0135777c06..434ec5caa21 100644 --- a/src/tribler/core/components/bandwidth_accounting/db/database.py +++ b/src/tribler/core/components/bandwidth_accounting/db/database.py @@ -1,7 +1,6 @@ from pathlib import Path from typing import List, Optional, Union -from pony import orm from pony.orm import Database, count, db_session, desc, select from tribler.core.components.bandwidth_accounting.db import history, misc, transaction as db_transaction @@ -93,12 +92,12 @@ def get_latest_transaction(self, public_key_a: bytes, public_key_b: bytes) -> Ba :param public_key_b: The public key of the party receiving the bandwidth. :return The latest transaction between the two specified parties, or None if no such transaction exists. """ - db_txs = select(tx for tx in self.BandwidthTransaction - if public_key_a == tx.public_key_a and public_key_b == tx.public_key_b) \ - .order_by(desc(self.BandwidthTransaction.timestamp)) \ - .limit(1) + db_tx = select(tx for tx in self.BandwidthTransaction + if public_key_a == tx.public_key_a and public_key_b == tx.public_key_b) \ + .order_by(lambda tx: desc(tx.sequence_number)) \ + .first() - return BandwidthTransactionData.from_db(db_txs[0]) if len(db_txs) == 1 else None + return BandwidthTransactionData.from_db(db_tx) if db_tx else None @db_session def get_latest_transactions(self, public_key: bytes, limit: Optional[int] = 100) -> List[BandwidthTransactionData]: @@ -120,8 +119,8 @@ def get_total_taken(self, public_key: bytes) -> int: :param public_key: The public key of the peer of which we want to determine the total taken. :return The total amount of bandwidth taken by the specified peer, in bytes. """ - return orm.sum(transaction.amount for transaction in self.BandwidthTransaction - if transaction.public_key_a == public_key) + return select(transaction.amount for transaction in self.BandwidthTransaction + if transaction.public_key_a == public_key).sum() @db_session def get_total_given(self, public_key: bytes) -> int: @@ -130,8 +129,8 @@ def get_total_given(self, public_key: bytes) -> int: :param public_key: The public key of the peer of which we want to determine the total given. :return The total amount of bandwidth given by the specified peer, in bytes. """ - return orm.sum(transaction.amount for transaction in self.BandwidthTransaction - if transaction.public_key_b == public_key) + return select(transaction.amount for transaction in self.BandwidthTransaction + if transaction.public_key_b == public_key).sum() @db_session def get_balance(self, public_key: bytes) -> int: