# SQL diagnostics for purchase_trade business rules These scripts are read-only diagnostics for a PostgreSQL test database. They exist to support the same business rules enforced by Python guards. The expected workflow is: 1. write the consultant/developer rule in the thematic documentation; 2. enforce the invariant in the application code when feasible; 3. provide a read-only SQL diagnostic to audit existing data. ## quantity_consistency_checks.sql Checks the two core lot quantity invariants documented in `lots-and-quantities.md` and `lots-and-quantities.en.md`. Zero `lot_qt` rows are ignored completely. They are treated as legitimate memory of an open quantity consumed by a physical lot. This is required because `lot_qt` represents usable open forecast and stops at zero, while the virtual lot may become negative to compensate the difference between theoretical and executed quantity. A non-zero `lot_qt` row without both `lot_p` and `lot_s` is reported as anomalous. Run it on a restored test database:
\i modules/purchase_trade/docs/business/sql/quantity_consistency_checks.sql
The script returns rows only when it finds a potential issue. Main columns: Cross-category UoM rows are reported as manual-review diagnostics because the Python code may pass explicit conversion factors that cannot be inferred safely from SQL alone.