Enforce one open checkout per device with a SQLite partial unique index
Guard equipment checkout with a partial unique index and verify that a repeated return leaves a newer checkout alone.
In this article
Model the current holder of one device
A university laboratory lends measurement devices to several teams. The application retains each checkout, its end time, and the team responsible for it. A checkout here represents current possession of the device. Reservations for future time intervals would require a different rule. Each device can have one open checkout while other devices can have their own open checkouts. The management screen can show which devices appeared available when it loaded. Two operators can nevertheless select the same device before either request reaches the server. Put the invariant beside the data so that the main endpoint, another operator tool, and a later import all encounter the same constraint. Keep the closed history in the same table and index the open subset. A checkout has its own identifier. A later assignment of the same device creates a new row and therefore a new checkout identifier.
Use a predicate that describes open rows
An open checkout has no end time. Represent that state with a NULL ended_at column. A partial unique index with the predicate WHERE ended_at IS NULL includes the currently open checkouts and uses equipment_id as its key. There can be only one matching key for each device. When an end time is recorded, the row no longer satisfies the predicate and remains as part of the history. Mark equipment_id NOT NULL as well. SQLite treats NULL values as distinct for uniqueness checks, so a missing identifier would otherwise evade the intended rule. In a production schema, a foreign key can also ensure that a checkout refers to an existing device. Use a consistent UTC representation for timestamps and define any additional ordering rule that the application needs. In particular, the uniqueness constraint does not validate which team is authorized to take or return the device.
Return the checkout identified by the original request
The SQL opens one checkout and closes it by its row identifier. The UPDATE also checks that ended_at is NULL. If a response is lost and a return request is repeated, that statement affects zero rows. Closing by equipment ID alone would let a late retry interfere with a newer checkout started after the original return. By using the stable checkout identifier, the retry only addresses its original row. The surrounding API still needs to check authorization. A zero-row update could mean the return already happened, the record is absent, or the request cannot act on it. Decide what the caller is allowed to learn. Read the authorized row when a repeated return must yield a consistent reply. If a receipt or notification is part of the workflow, establish its delivery rule separately and publish it after the database operation succeeds.
CREATE TABLE equipment_checkout (
id INTEGER PRIMARY KEY,
equipment_id INTEGER NOT NULL,
team TEXT NOT NULL,
ended_at TEXT
);
CREATE UNIQUE INDEX equipment_checkout_one_open
ON equipment_checkout(equipment_id)
WHERE ended_at IS NULL;
INSERT INTO equipment_checkout(id, equipment_id, team) VALUES (?, ?, ?);
UPDATE equipment_checkout
SET ended_at = ?
WHERE id = ? AND ended_at IS NULL;
Verify the results with a small fixture
The empty test database accepts open checkouts 101 and 102 for devices 7 and 8. A second open checkout for device 7 fails with a uniqueness constraint. The original open checkouts remain present. Returning checkout 101 affects one row and allows checkout 103 to open for the same device. Repeating the return for 101 affects zero rows. The historical listing contains 101, 102, and 103. The open listing contains 103 for device 7 and 102 for device 8. The example exercises these outcomes against the local SQLite engine. Test the client as well if it retries requests. A lost response after a successful checkout leaves the client uncertain about which row it owns. A request identifier can let it retrieve the prior success. The unique index protects the invariant while the API resolves that ambiguity.
Distinguish a write lock from an occupied device
A second SQLite connection can encounter SQLITE_BUSY when another connection holds a write lock. Handle the transient access problem separately from a constraint error that means the business rule blocked a new checkout. Interpret the driver error in the context of the operation being attempted and the constraint it may have hit. A preliminary read can help display availability, but the INSERT and its index enforce the final result. When a checkout requires several durable changes, give them a short explicit transaction and handle rollback appropriately on error. Avoid waiting for remote services or a user confirmation while holding a write transaction open. A successful return to the caller should follow a completed database operation. Store the checkout identifier in the client so it can reference the right row when handing the device back.
Reconcile existing records before adding the index
Before adding this index to an existing table, group the open rows by equipment_id and find counts above one. Reconcile those rows against the operational record before choosing which checkout stays open. Keep a backup of any affected rows and verify the index during the migration. A query for the open checkout can state both equipment_id and ended_at IS NULL, which lets the planner consider the partial index. Use EXPLAIN QUERY PLAN with realistic data and inspect the historical listing separately. Monitor uniqueness errors, busy errors, and return requests that affect zero rows with separate counters. A regression test should allow two different devices, reject a second open checkout for one device, and prove that a late return cannot close the newer checkout. These cases exercise the persistent invariant and the identifier used at the application boundary.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment