
Why Constraints Belong in the Database Even When Your App Validates
- كاتب موثّق
محتويات المقال
mona@example.com. Wrapping each session's check and insert in a transaction at the default isolation level didn't help: the same interleaving committed two rows again.
The common misconception
UNIQUE, FOREIGN KEY and CHECK constraints are redundant.
What actually happens
A check and a write are two separate moments
READ COMMITTED, SQL Server's default: Microsoft's table lists phantoms as allowed at that level, and a row that appears after you looked for it is exactly that. A UNIQUE constraint closes the gap because the database checks uniqueness as part of the insert itself, against a unique index it creates for the constraint. In the test, with the constraint in place, the second session's insert failed with error 2627 and the table kept one row.
Your application isn't the only writer
What each constraint guarantees
PRIMARY KEYandUNIQUE: no two rows share the key. SQL Server creates a unique index to enforce each one.FOREIGN KEY: . In the test, inserting an order for a missing customer and deleting a customer who still had orders both failed with error 547.CHECK: a condition each row must meet. In the test,CHECK (Quantity > 0)rejected a quantity of 0 with error 547.NOT NULL: the column always has a value.
Where constraints stop
CHECK rejects only expressions that evaluate to false, and a comparison with NULL evaluates to unknown, so NULL passes. A CHECK also sees one row at a time: SQL Server doesn't validate CHECK constraints on DELETE, and PostgreSQL doesn't support CHECK constraints that read other rows. Rules across rows, like "the order total equals the sum of its lines", stay in your code. NULL in a unique column differs by database: SQL Server allowed one NULL and rejected the second with error 2627 in the test, while PostgreSQL treats nulls as distinct unless you add NULLS NOT DISTINCT. And neither database creates an index on the referencing columns of a foreign key. The PostgreSQL behavior here comes from its docs; only SQL Server ran for this article.
Keep the validation, add the guarantee
using Microsoft.EntityFrameworkCore;static async Task<IResult> SignUp(SignUpRequest req, AppDb db){ // Check, then insert: two concurrent requests both pass the check if (await db.Users.AnyAsync(u => u.Email == req.Email)) return Results.Conflict("Email already registered"); db.Users.Add(new User { Email = req.Email }); await db.SaveChangesAsync(); // SQL test: both inserts succeeded return Results.Created();}using Microsoft.Data.SqlClient;using Microsoft.EntityFrameworkCore;static async Task<IResult> SignUp(SignUpRequest req, AppDb db){ // The check gives a friendly message; the unique index is the guarantee if (await db.Users.AnyAsync(u => u.Email == req.Email)) return Results.Conflict("Email already registered"); db.Users.Add(new User { Email = req.Email }); try { await db.SaveChangesAsync(); } catch (DbUpdateException e) when (e.InnerException is SqlException { Number: 2601 or 2627 }) // unique index or UNIQUE constraint { return Results.Conflict("Email already registered"); } return Results.Created();}HasIndex(u => u.Email).IsUnique() creates a unique index rather than a constraint, so SQL Server reports error 2601 instead of 2627; the test produced both, and the filter catches either. For a table that already exists, find the violations before you add the rule:
-- Adding the constraint over duplicates failed in the test with Msg 1505SELECT Email, COUNT(*) AS CopiesFROM dbo.Users GROUP BY Email HAVING COUNT(*) > 1;ALTER TABLE dbo.Users ADD CONSTRAINT UQ_Users_Email UNIQUE (Email);ALTER TABLE dbo.OrderLines ADD CONSTRAINT CK_OrderLines_Quantity CHECK (Quantity > 0);ALTER TABLE dbo.Orders ADD CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerId) REFERENCES dbo.Customers (Id);CHECK, plus UNIQUE and foreign keys | ||
How to apply it in your project
List the invariants of each table Write down what must always be true: unique emails, positive quantities, orders that point at real customers, an end date after the start date. Each one is a candidate for UNIQUE,CHECK,FOREIGN KEYorNOT NULL.Find existing violations first By default, adding a constraint checks the rows already there: in the test, UNIQUEfailed on a duplicate, andCHECKandFOREIGN KEYfailed on a bad row. Query for duplicates, orphans and out-of-range values, and clean them up in the same migration.Declare the rules where the schema lives In EF Core, use HasIndex(...).IsUnique()andToTable(t => t.HasCheckConstraint(...)). A foreign key constraint doesn't index its column; EF Core adds that index by convention, but hand-written schemas need their own.Translate violations into responses Catch unique violations (2601, 2627) and turn them into a 409 Conflict, and map error 547 by constraint name. Keep the friendly validation in front; the constraint is the backstop.
Key takeaways
Validation and constraints aren't duplicates: one explains errors to users, the other keeps the data true for every writer. A check followed by an insert is a race; in the test, two sessions both inserted the same email, even inside transactions. A UNIQUEconstraint checks during the insert itself, so the second session failed with error 2627.Constraints have limits: CHECKpassesNULLand sees one row, andNULLin a unique column differs between SQL Server and PostgreSQL.Add constraints after cleaning existing violations, name them, and map their errors to clear responses.
التعليقات (0)