Validating delivery lines with PostgreSQL 17 JSON_TABLE
A PostgreSQL workflow that expands nested supplier JSON packages while keeping absent item lists and invalid quantities visible.
Archive retrospective · Topic year 2024
In this article
Project supplier documents into delivery lines
A supplier sends one JSON document per delivery with a header and a list of products. Keeping the document makes the original notification available for review, while warehouse checks need rows at product and quantity level. PostgreSQL 17 introduced JSON_TABLE in the release dated September 26, 2024. The function uses JSON paths and typed columns to present document content in relational form. This example extracts both the order identifier and the nested product lines. It also retains evidence about quantities that fail validation. A supplier can omit a key, write JSON null, or provide text that cannot be converted to an integer. The typed result alone can leave each of those values empty. Checking key presence separately makes part of the difference visible. The fixture assumes one document per delivery and one product array per document.
Distinguish empty arrays and invalid quantities
The outer JSON path selects a header. NESTED PATH expands the lines array and FOR ORDINALITY preserves a line position for troubleshooting. A supplier may reorder an array when sending a correction, so that position is insufficient as a durable business identity. A delivery without product entries retains a parent row with empty child columns. The query assigns it empty_lines. An EXISTS column tells us whether the quantity key is present. An otherwise valid object with no key receives missing_qty. Conversion failures and an explicit JSON null both produce invalid_qty in this example. The fixture also requires a positive value. Returns or adjustments could require another document type with a different rule. Keep the input available when returning data to a supplier or reviewing a mapping issue so the operator can compare the output row and source object.
Reproduce five output rows
Order A carries four products. X has quantity two and is usable. Y omits the quantity key, Z supplies unconvertible text, and N contains an explicit JSON null. The latter two end up in the invalid quantity group. Order B has an empty product array. The query retains its delivery with no product data, which is useful for counting received deliveries. Expect one usable row, one missing quantity, two invalid quantities, and one empty array. The usable quantity total is two. Assigning zero to failed amount fields would hide those important distinctions. PostgreSQL 17 or later is required. The values in the query are fabricated and need no file or private data. Repeat this fixture after changing type conversion, key-presence checks, or the range of acceptable quantities to see which classifications move. The empty array provides a separate check on the result shape.
WITH deliveries(delivery_id, payload) AS (
VALUES
(1, '{"order":"A","lines":[{"sku":"X","qty":2},{"sku":"Y"},{"sku":"Z","qty":"oops"},{"sku":"N","qty":null}]}'::jsonb),
(2, '{"order":"B","lines":[]}'::jsonb)
)
SELECT d.delivery_id, j.order_id, j.line_no, j.sku, j.qty,
CASE
WHEN j.line_no IS NULL THEN 'empty_lines'
WHEN NOT j.qty_present THEN 'missing_qty'
WHEN j.qty IS NULL OR j.qty <= 0 THEN 'invalid_qty'
ELSE 'usable'
END AS quality
FROM deliveries d
CROSS JOIN LATERAL JSON_TABLE(
d.payload, '$'
COLUMNS (
order_id text PATH '$.order',
NESTED PATH '$.lines[*]' COLUMNS (
line_no FOR ORDINALITY,
sku text PATH '$.sku',
qty_present boolean EXISTS PATH '$.qty',
qty integer PATH '$.qty' NULL ON EMPTY NULL ON ERROR
)
)
) AS j
ORDER BY d.delivery_id, j.line_no;
Validate the input shape before projection
The query assumes each input is already a parsed JSON object with an array-shaped lines field. Malformed raw JSON can fail before JSON_TABLE runs. Preserve a loading record and decide whether parsing failures block a whole file or are isolated. JSON path evaluation can handle some shape variations. If the contract requires an array, check its type explicitly and distinguish a wrong type from an empty array. A numeric-looking string may convert to an integer. Store or check the original JSON type when the supplier promises JSON numbers. Required product codes and sensible quantity bounds belong in separate validation rules. Use delivery identity and ordinal position for troubleshooting. A stable supplier line ID is preferable when a downstream change must update an existing record after the source array has been reordered.
Measure usable rows and quarantine together
Record both received deliveries and actual product lines for each load. The placeholder for an empty delivery should not count as a product line. Sum quantity from validated records while keeping an audit total for problematic lines and their deliveries. This makes a supplier's correction visible when a load is compared with its previous run. Downstream stock movements can use a stable line identity and document revision to define replay behavior. Operations should decide whether one unusable line blocks an entire delivery or only that line. The example creates a classification output and leaves the decision explicit. A large document can expand to thousands of rows, so assess representative files as well as outliers. Keep counts by supplier and schema version to isolate changes. Measure memory and execution time on that workload before turning a five-row fixture into a deployment estimate.
Reader discussion
Which bottleneck would you expect as this solution scales?
No comments yet. Be the first to contribute.
Write a comment