r/SQL • • 29d ago

PostgreSQL Is my relational model suitable for handling order changes and cancellations?

Post image

I'm designing a PostgreSQL system where customers order services requiring interchangeable physical resources.

The current model separates:

  • Orders: What the customer purchases (quantity and duration).
  • Commitments: Individual units of the obligation, independent of specific resources.
  • Reservations: Physical resources assigned to fulfill those commitments.
  • Resource units: Individually reservable components, with constraints preventing overlapping bookings.

At first glance, this structure seems reasonable, but it mainly represents a static state. In reality, orders can change throughout their lifecycle: quantities may be reduced, service periods shortened, or entire orders cancelled.

For example, a customer orders 3 resources for 6 months, then reduces the requirement to 2 for the remaining 3 months.

Is the current table structure and its relationships suitable for handling these changes while preserving historical accuracy and data consistency? Or are there missing entities or fundamental modeling issues?

I've attached a simplified ERD for context.

19 Upvotes

7 comments sorted by

4

u/MrRoy_SQL 28d ago

looks pretty solid tbh, you already have ended_at / end_reason / is_voided on allocations so youre most of the way there

the thing id add is an order_changes (or order_revisions) table instead of updating quantity / end_date on service_orders. each row = what changed, effective from when, why. then for your example (3 down to 2 after 3 months) you dont touch the order, you add a revision and end one commitment at the change date with end_reason = 'reduced'

that way "what did the customer have on date X" is just a query on effective dates, and you never lose history

3

u/DickBrainTime 28d ago

The separation between commitments and physical reservations looks sensible. One edge case I'd test before settling the model: reducing an order while a physical unit is already assigned. You'd want to close the affected commitment *and* reservation effective periods in one transaction, rather than deleting or orphaning the reservation, so history stays queryable and the unit becomes available at the right time. Also test that no two active reservations for the same unit overlap after the change. I'd write the “which units fulfilled this order on date X?” query first; if it works cleanly across a reduction and a cancellation, you're probably on the right track.

2

u/delsystem32exe 27d ago edited 27d ago

i remember in class i would have it all laid out and then in the job the program i designed from scratch i have like 40 tables with all pk, no fk constraint and it works just fine. i wouldnt worry too much about having the ERD be perfect, it just has to be good enough.

i have lots of json b columns so that helps a lot i would make more of those columns json b. the json_each and json_tree methods are real handy or joining on the json fields.

I think in real life all u need is 1NF and you are good.

1

u/Alternative_Pin9598 27d ago

The structure is right. What makes changes painless in Postgres is giving commitments and reservations a period (a daterange) instead of status flags, and letting exclusion constraints guard the invariants. Changes then become "close a period + insert a revision", never an UPDATE of the quantity.

CREATE EXTENSION IF NOT EXISTS btree_gist;

-- what the customer asked for, as of when (append-only)
CREATE TABLE order_revisions (
  id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id       bigint NOT NULL REFERENCES service_orders(id),
  effective_from date   NOT NULL,
  quantity       int    NOT NULL CHECK (quantity >= 0),
  service_end    date   NOT NULL,   -- first day NOT served
  reason         text   NOT NULL,   -- initial / reduced / shortened / cancelled
  recorded_at    timestamptz NOT NULL DEFAULT now(),
  UNIQUE (order_id, effective_from)
);

-- one row per unit "slot" of the obligation
CREATE TABLE commitments (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id   bigint    NOT NULL REFERENCES service_orders(id),
  slot       int       NOT NULL,          -- 1..quantity
  during     daterange NOT NULL,
  end_reason text,
  EXCLUDE USING gist (order_id WITH =, slot WITH =, during WITH &&)
);

CREATE TABLE reservations (
  id               bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  commitment_id    bigint    NOT NULL REFERENCES commitments(id),
  resource_unit_id bigint    NOT NULL REFERENCES resource_units(id),
  during           daterange NOT NULL,
  is_voided        boolean   NOT NULL DEFAULT false,
  EXCLUDE USING gist (resource_unit_id WITH =, during WITH &&) WHERE (NOT is_voided)
);

Your example (3 units → 2 from April 1) is one transaction:

BEGIN;
INSERT INTO order_revisions (order_id, effective_from, quantity, service_end, reason)
VALUES (42, '2027-04-01', 2, '2027-07-01', 'reduced');

UPDATE commitments
SET during = daterange(lower(during), '2027-04-01'), end_reason = 'reduced'
WHERE order_id = 42 AND slot = 3 AND during @> date '2027-04-01';

UPDATE reservations r
SET during = daterange(lower(r.during), '2027-04-01')
FROM commitments c
WHERE r.commitment_id = c.id AND c.order_id = 42 AND c.slot = 3
  AND r.during @> date '2027-04-01' AND NOT r.is_voided;
COMMIT;

The unit is free again from April 1 (ranges are [start, end), so there are no off-by-one days), and history is untouched. Shortening = the same thing on every slot. Cancelling = revision with quantity 0, and close everything at the cancel date. Reservations that hadn't started yet get is_voided = true instead of being trimmed to an empty range.

"What did order 42 have on May 15?" is then just:

SELECT c.slot, r.resource_unit_id
FROM commitments c
LEFT JOIN reservations r
  ON r.commitment_id = c.id AND NOT r.is_voided AND r.during @> date '2027-05-15'
WHERE c.order_id = 42 AND c.during @> date '2027-05-15';

Two things the constraints can't enforce on their own, so I'd put them in a nightly check query (or a constraint trigger):

  • a reservation's during must be inside its commitment's during (c.during @> r.during),
  • the number of commitments active on each revision's effective_from must equal that revision's quantity.

If both checks return zero rows after you replay a reduction, a shortening and a cancellation, the model holds.