Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is balance_for_locked_account necessary? #223

Open
ghiculescu opened this issue Feb 14, 2025 · 3 comments
Open

Is balance_for_locked_account necessary? #223

ghiculescu opened this issue Feb 14, 2025 · 3 comments

Comments

@ghiculescu
Copy link

Thanks for sharing this great gem. I have been diving deep into the code and trying to understand its internals. One question I can't work out is is if balance_for_locked_account is necessary.

diff --git a/lib/double_entry/transfer.rb b/lib/double_entry/transfer.rb
index a846f90..4eb1de4 100644
--- a/lib/double_entry/transfer.rb
+++ b/lib/double_entry/transfer.rb
@@ -98,8 +98,8 @@ module DoubleEntry
     def create_lines(amount, code, detail, from_account, to_account, metadata)
       credit, debit = Line.new, Line.new

-      credit_balance = Locking.balance_for_locked_account(from_account)
-      debit_balance  = Locking.balance_for_locked_account(to_account)
+      credit_balance = AccountBalance.find_by_account(from_account, lock: true)
+      debit_balance  = AccountBalance.find_by_account(to_account, lock: true)

       credit_balance.update_attribute :balance, credit_balance.balance - amount
       debit_balance.update_attribute :balance, debit_balance.balance + amount

With this change, on Ruby 3.3, all tests and the jackhammer pass for me, using Postgres. (I ran the jackhammer with threads, I couldn't get it to run with processes, maybe the issue is there.)

It's obviously not a critical part of the code but it does add a little bit of extra indirection, and as far as I can tell it's not necessary, as long as Locking.lock_accounts wraps around this code.

@runlevel5
Copy link

@ghiculescu I am new to the lock property so unsure how it works. One way to find out, could you please check the SQL they AR generated? If the SQL queries are the same, I think we do not need Locking.balance_for_locked_account

@ghiculescu
Copy link
Author

The same SQL would get run either way, because I just lifted that method from here:

account_balances = @accounts.map { |account| AccountBalance.find_by_account(account, lock: true) }

@runlevel5
Copy link

@ghiculescu I guess the intention is to use one centralised helper for the job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants