Fix fencepost bug with TrialBalancer.from_cached

This commit is contained in:
RunasSudo 2024-11-10 00:30:33 +11:00
parent 16534fc755
commit 1d2628850e
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A

View File

@ -241,12 +241,13 @@ class TrialBalancer:
# First SELECT the last applicable dt by account
# Then, among the transactions with that dt, SELECT the last applicable transaction_id
# Then extract the running_balance for each account at that transaction_id
# NB: We need to specify DATE(...) otherwise SQLite appears to do a string comparison which doesn't work properly with SQLAlchemy's prepared statement?
running_balances = db.session.execute('''
SELECT p3.account, running_balance FROM
(
SELECT p1.account, max(p2.transaction_id) AS max_tid FROM
(
SELECT account, max(dt) AS max_dt FROM postings JOIN transactions ON postings.transaction_id = transactions.id WHERE dt < :start_date GROUP BY account
SELECT account, max(dt) AS max_dt FROM postings JOIN transactions ON postings.transaction_id = transactions.id WHERE DATE(dt) < DATE(:start_date) GROUP BY account
) p1
JOIN postings p2 ON p1.account = p2.account AND p1.max_dt = transactions.dt JOIN transactions ON p2.transaction_id = transactions.id GROUP BY p2.account
) p3
@ -282,7 +283,7 @@ class TrialBalancer:
(
SELECT p1.account, max(p2.transaction_id) AS max_tid FROM
(
SELECT account, max(dt) AS max_dt FROM postings JOIN transactions ON postings.transaction_id = transactions.id WHERE dt <= :end_date GROUP BY account
SELECT account, max(dt) AS max_dt FROM postings JOIN transactions ON postings.transaction_id = transactions.id WHERE DATE(dt) <= DATE(:end_date) GROUP BY account
) p1
JOIN postings p2 ON p1.account = p2.account AND p1.max_dt = transactions.dt JOIN transactions ON p2.transaction_id = transactions.id GROUP BY p2.account
) p3