fix(stock): guard batchwise valuation-rate division against a zero divisor (Postgres) (#56361)

fix(stock): guard batchwise valuation-rate division against a zero divisor

get_valuation_rate's batchwise fallback selects
Sum(stock_value_difference) / Sum(actual_qty). When a batch's non-current
Stock Ledger Entries net to zero quantity (equal received and issued) the
divisor Sum(actual_qty) is 0. On MariaDB x/0 yields NULL and the caller's
`if last_valuation_rate and last_valuation_rate[0][0] is not None` check
falls through to the next strategy; on PostgreSQL float division by zero
raises `division by zero`, aborting the query (and the transaction).

Wrap the divisor in NullIf(Sum(actual_qty), 0) so a zero divisor yields
NULL on both engines, matching MariaDB and preserving the caller's
is-not-None fall-through. (stock_value_difference is Currency and actual_qty
is Float, so the division was already float — no integer-truncation change.)
This commit is contained in:
Mihir Kandoi
2026-06-23 17:09:58 +05:30
committed by GitHub
parent 2f4e78f09e
commit 453b5cee21

View File

@@ -10,7 +10,7 @@ import frappe
from frappe import _, bold, scrub
from frappe.model.meta import get_field_precision
from frappe.query_builder import Order
from frappe.query_builder.functions import Lower, Sum
from frappe.query_builder.functions import Lower, NullIf, Sum
from frappe.utils import (
cint,
flt,
@@ -1975,7 +1975,7 @@ def get_valuation_rate(
table = frappe.qb.DocType("Stock Ledger Entry")
query = (
frappe.qb.from_(table)
.select(Sum(table.stock_value_difference) / Sum(table.actual_qty))
.select(Sum(table.stock_value_difference) / NullIf(Sum(table.actual_qty), 0))
.where(
(table.item_code == item_code)
& (table.warehouse == warehouse)