Chapter 6 — No Double Bookings#
PostgreSQL makes double bookings impossible inside the primary key itself.
TemporalPrimaryKeyWITHOUT OVERLAPSRange[date]ExclusionViolationErrorexamples/173_temporal_bookings.pyWeek 2, Friday 22:10. Two elephants stand outside Room 304 holding identical brass keys.
Jumbo: I booked the penthouse from July 10 to July 13.
Bram: And I booked July 12 to July 14! That's only one night of overlap — I'll take the top bunk!
Maya: There IS no top bunk! How did both bookings pass our availability check?
The mission#
Checking "is this room free?" in Python before inserting a booking is a classic race condition: two receptionists both check at 22:10, both see an empty room, and both insert. Maya needs PostgreSQL itself to enforce two temporal invariants:
- No room double bookings: back-to-back stays that share a checkout/check-in day (
[Jul 10, Jul 13)and[Jul 13, Jul 16)) are allowed, while any overlapping stay ([Jul 12, Jul 14)) is rejected inside the primary key. - No overlapping seasonal rates: Summer and Autumn rates can touch on September 1, but a rogue August–September promo rate cannot overlap either.
The Panda's plan
"Before every INSERT, run SELECT count(*) FROM room_assignment WHERE room_id = $1 AND start_date < $3 AND end_date > $2. If it's zero, insert!"
Under concurrent check-ins, both transactions run that SELECT at the exact same millisecond, both see 0, and both INSERT succeed. You've now put five tons of Savanna elephant and eight tons of woolly mammoth into one penthouse.
1. PostgreSQL WITHOUT OVERLAPS primary keys#
Note
The btree_gist extension, handled for you: a WITHOUT OVERLAPS key that combines a scalar column (room_id) with a range (stay) needs PostgreSQL's btree_gist extension. create_all() and planned migrations install it automatically (CREATE EXTENSION IF NOT EXISTS, which needs no superuser for this extension). Ordinary tables need no extensions at all.
Look at RoomAssignment and Rate in examples/schema.py:
class RoomAssignment(pg.Table):
room_id: Col[int] = pg.fk(Room, on_delete=pg.enums.OnDelete.CASCADE)
stay: Col[Range[date]]
booking_id: Col[int] = pg.fk(Booking, on_delete=pg.enums.OnDelete.CASCADE)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (pg.TemporalPrimaryKey(cls.room_id, cls.stay),)
class Rate(pg.Table):
rate_id: Col[int] = pg.pk(default=pg.identity())
dormitory_id: Col[int] = pg.fk(Dormitory, on_delete=pg.enums.OnDelete.CASCADE)
category: Col[RoomCategory] = pg.fk(RoomCategoryType)
valid_during: Col[Range[date]]
nightly_price: Col[Money]
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (pg.TemporalUnique(cls.dormitory_id, cls.category, cls.valid_during),)
pg.TemporalPrimaryKey(room_id, stay) compiles to PostgreSQL's native PRIMARY KEY ("room_id", "stay" WITHOUT OVERLAPS), backed automatically by a GiST index. pg.TemporalUnique(...) does the same for UNIQUE (... WITHOUT OVERLAPS) on Rate.
async def guard_room_assignments(
pool: pg.Pool, dorm: Dormitory, penthouse: Room, guests: list[Guest]
) -> None:
jumbo, pip, bram = guests
# Half-open [check_in, check_out) date ranges let back-to-back guests share a turnover day.
july_10_to_13 = pg.Range(lower=date(2026, 7, 10), upper=date(2026, 7, 13))
july_13_to_16 = pg.Range(lower=date(2026, 7, 13), upper=date(2026, 7, 16))
july_12_to_14 = pg.Range(lower=date(2026, 7, 12), upper=date(2026, 7, 14))
b1, b2, b3 = await pool.all(
pg.insert_many(
Booking,
[
Booking(
dormitory_id=dorm.dormitory_id,
primary_guest_id=jumbo.guest_id,
stay=july_10_to_13,
reference_code="TMP-001",
),
Booking(
dormitory_id=dorm.dormitory_id,
primary_guest_id=pip.guest_id,
stay=july_13_to_16,
reference_code="TMP-002",
),
Booking(
dormitory_id=dorm.dormitory_id,
primary_guest_id=bram.guest_id,
stay=july_12_to_14,
reference_code="TMP-003",
),
],
).returning(Booking)
)
await pool.execute(
pg.insert(RoomAssignment).values(
RoomAssignment(room_id=penthouse.room_id, stay=july_10_to_13, booking_id=b1.booking_id)
)
)
# Adjacent stay starting on July 13 succeeds because [10, 13) and [13, 16) do not overlap.
await pool.execute(
pg.insert(RoomAssignment).values(
RoomAssignment(room_id=penthouse.room_id, stay=july_13_to_16, booking_id=b2.booking_id)
)
)
print(f"room {penthouse.number} booked back-to-back: [Jul 10, Jul 13) and [Jul 13, Jul 16)")
# => room 304 booked back-to-back: [Jul 10, Jul 13) and [Jul 13, Jul 16)
# Bram tries to book [Jul 12, Jul 14) on the same room — rejected by WITHOUT OVERLAPS.
try:
await pool.execute(
pg.insert(RoomAssignment).values(
RoomAssignment(
room_id=penthouse.room_id,
stay=july_12_to_14,
booking_id=b3.booking_id,
)
)
)
except pg.ExclusionViolationError as err:
print(f"double booking blocked: sqlstate={err.sqlstate} constraint={err.constraint}")
# => double booking blocked: sqlstate=23P01 constraint=tp_wzmntgpa
# Overlap search (`&&`) hits the GiST temporal PK index directly.
conflicts_q = (
pg.select(RoomAssignment)
.join(Booking, require_using=True)
.columns(Booking.reference_code, RoomAssignment.stay)
.where(
(RoomAssignment.room_id == penthouse.room_id)
& RoomAssignment.stay.overlaps(july_12_to_14)
)
.order_by(Booking.reference_code.asc())
)
conflicts = await pool.all(conflicts_q)
print("conflicting bookings:", [ref for ref, _ in conflicts])
# => conflicting bookings: ['TMP-001', 'TMP-002']
tpk_name = RoomAssignment.__pg_resolved_temporal__[0].name
assert tpk_name is not None
plan = await pool.explain(conflicts_q, disable_seqscan=True)
plan.assert_uses_index(tpk_name)
print(f"overlap query used temporal PK index: {tpk_name in plan.summary()}")
# => overlap query used temporal PK index: True
What just happened
pg.Range(lower=date(2026, 7, 10), upper=date(2026, 7, 13))defaults to half-open[lower, upper)bounds, the exact mathematical match for hotel nights: Jumbo checks out on July 13 morning, Pip checks in on July 13 afternoon, and[10, 13)does not overlap[13, 16).- When Bram tries
[Jul 12, Jul 14), PostgreSQL rejects theINSERTwith SQLSTATE23P01onroom_assignment_pkey, which pgdorm surfaces aspg.ExclusionViolationError. No Python lock, no race window. - Searching for conflicting stays uses
RoomAssignment.stay.overlaps(...)(&&), andpool.explain(..., disable_seqscan=True)proves the query hits the very same GiST index backing the temporal primary key.
2. Non-overlapping seasonal rates#
The same temporal engine guards pricing tables so a room category can never have two active prices on the same night:
async def guard_seasonal_rates(pool: pg.Pool, dorm: Dormitory) -> None:
summer = pg.Range(lower=date(2026, 6, 1), upper=date(2026, 9, 1))
autumn = pg.Range(lower=date(2026, 9, 1), upper=date(2026, 12, 1))
overlapping_august = pg.Range(lower=date(2026, 8, 15), upper=date(2026, 9, 15))
await pool.execute(
pg.insert_many(
Rate,
[
Rate(
dormitory_id=dorm.dormitory_id,
category=RoomCategory.PENTHOUSE,
valid_during=summer,
nightly_price=Decimal("240.00"),
),
Rate(
dormitory_id=dorm.dormitory_id,
category=RoomCategory.PENTHOUSE,
valid_during=autumn,
nightly_price=Decimal("180.00"),
),
],
)
)
print("published non-overlapping Summer (240.00) and Autumn (180.00) rates")
# => published non-overlapping Summer (240.00) and Autumn (180.00) rates
try:
await pool.execute(
pg.insert(Rate).values(
Rate(
dormitory_id=dorm.dormitory_id,
category=RoomCategory.PENTHOUSE,
valid_during=overlapping_august,
nightly_price=Decimal("299.00"),
)
)
)
except pg.ExclusionViolationError as err:
print(f"overlapping seasonal rate blocked: {err.sqlstate}")
# => overlapping seasonal rate blocked: 23P01
What just happened
- Summer (
[Jun 1, Sep 1)) and Autumn ([Sep 1, Dec 1)) meet seamlessly at September 1 with zero gap and zero overlap. - Inserting an overlapping August 15 – September 15 rate trips
pg.TemporalUniqueand raisespg.ExclusionViolationError(23P01).
Ferris' basement: why PostgreSQL temporal keys are a big deal
In older PostgreSQL releases, preventing overlapping ranges meant writing EXCLUDE USING gist (room_id WITH =, stay WITH &&) — and you still couldn't make it a real PRIMARY KEY or UNIQUE constraint. PostgreSQL implements SQL:2011 PRIMARY KEY (..., range WITHOUT OVERLAPS) natively (requiring the built-in btree_gist extension shown above for the scalar room_id key column). Better still, the GiST index enforces uniqueness and accelerates && overlap queries in one structure.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 12 statements in 11 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/temporal_bookings.sql
-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row
-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
($1, $2, $3, $4, $5, $6, $7, $8),
($9, $10, $11, $12, $13, $14, $15, $16),
($17, $18, $19, $20, $21, $22, $23, $24),
($25, $26, $27, $28, $29, $30, $31, $32),
($33, $34, $35, $36, $37, $38, $39, $40),
($41, $42, $43, $44, $45, $46, $47, $48),
($49, $50, $51, $52, $53, $54, $55, $56),
($57, $58, $59, $60, $61, $62, $63, $64),
($65, $66, $67, $68, $69, $70, $71, $72),
($73, $74, $75, $76, $77, $78, $79, $80),
($81, $82, $83, $84, $85, $86, $87, $88),
($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows
-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows
-- ── round trip 4 ──
COMMIT;
-- ── round trip 5 ──
INSERT INTO "booking" ("dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5
FROM unnest($1, $2, $3, $4, $5, $6) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, ord)
ORDER BY u.ord
RETURNING "booking_id", "dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code", "created_at";
-- → 3 rows
-- ── round trip 6 ──
INSERT INTO "room_assignment" ("room_id", "stay", "booking_id")
VALUES ($1, $2, $3);
-- → 1 affected
-- ── round trip 7 ──
INSERT INTO "room_assignment" ("room_id", "stay", "booking_id")
VALUES ($1, $2, $3);
-- → 1 affected
-- ── round trip 8 ──
INSERT INTO "room_assignment" ("room_id", "stay", "booking_id")
VALUES ($1, $2, $3);
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 23P01
-- ── round trip 9 ──
SELECT "booking"."reference_code", "room_assignment"."stay"
FROM "room_assignment"
INNER JOIN "booking" USING ("booking_id")
WHERE "room_assignment"."room_id" = $1 AND "room_assignment"."stay" && $2
ORDER BY "booking"."reference_code" ASC;
-- → 2 rows
-- ── round trip 10 ──
INSERT INTO "rate" ("dormitory_id", "category", "valid_during", "nightly_price")
SELECT u.c0, u.c1, u.c2, u.c3
FROM unnest($1, $2, $3, $4) WITH ORDINALITY AS u(c0, c1, c2, c3, ord)
ORDER BY u.ord;
-- → 2 affected
-- ── round trip 11 ──
INSERT INTO "rate" ("dormitory_id", "category", "valid_during", "nightly_price")
VALUES ($1, $2, $3, $4);
-- ✗ PostgreSQL rejected this round trip: SQLSTATE 23P01
Shift report
- Represented stays and rate windows with half-open
pg.Range[date]values - Enforced non-overlapping room assignments inside
PRIMARY KEY (… WITHOUT OVERLAPS) - Caught overlap conflicts cleanly as
pg.ExclusionViolationError(23P01) - Verified that
.overlaps(...)queries hit the temporal primary key's GiST index - Protected seasonal pricing with
pg.TemporalUnique
Try it yourself
Change july_13_to_16 in guard_room_assignments to pg.Range(lower=date(2026, 7, 13), upper=date(2026, 7, 16), lower_inc=True) and july_10_to_13 to upper_inc=True (closed [Jul 10, Jul 13]). Run the script — why does Pip's back-to-back check-in now get rejected?
Go deeper: tests/integration/features/pg18/test_pg18.py (live PostgreSQL test suites & snapshots)
Sticky note from Management
"Guests are paying by card, bank transfer AND peanut vouchers. Also, Bram broke a bunk ladder and Room 101 needs bamboo pillows. Track payments AND chores — NO magic string types!"
← PreviousChapter 5 · Group Bookings & FoliosChapter 5 · FK Joins, USING & split_load
Next →Chapter 7 · Payments & ChoresChapter 7 · STI & CTI Polymorphism