Contributions sometimes lack line items, leads to fatal error upon "Download Invoice"
Originally reported at https://civicrm.stackexchange.com/questions/44907/contribution-has-no-line-items-shouldnt-that-be-impossible
Problem and observation:
On several sites I have found contributions which have no line items -- that is, rows in civicrm_contribution that have no corresponding rows in civicrm_line_item.
Responses at the above-linked SE question indicate that this is not normal.
This situation leads to a fatal error ("Return value of CRM_Financial_BAO_Order::getPriceSetID() must be of the type int, null returned") when attempting to generate a PDF invoice with "Download Invoice" for the given contribution, apparently on the assumption that this situation is not expected by core code.
Detecting ffected sites:
I've observed this on several sites (all currently running CiviCRM 5.58.1 but all having existed much longer), including one local dev site that sees relatively light usage.
This SQL query identifies contributions lacking line items:
SELECT count(*)
FROM
civicrm_contribution ctr
left join civicrm_line_item li on li.contribution_id = ctr.id
where li.id is null;
Unable to repro:
I'm unable to reproduce this situation at will, except by manually deleting rows in civicrm_line_item via API or SQL. It seems any contribution record will, by design, have at least one line_item, even if using a quick-config contribution instead of a visible price set, or if manually creating even a zero-dollar contribution in the back-end.
Moving forward:
Until we have a solid set of steps to repro, I'm not sure there's much we can do here. Hopefully this issue can serve as a place for others to share their findings (and hopefully we'll get to some repro steps at some point).