↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

When to Use Constraints in Ecto

The post distinguishes validations from constraints by where they run: validations happen in application code, while constraints are checked by the database when data is inserted or updated. It uses event records to show which rules fit each approach and when both are needed.

Reading notes
#

  • Blank names can be handled with a validation, because the application can detect an empty string.
  • Uniqueness should be enforced with a database constraint, since a pre-insert query can race with another insert.
  • end_time > start_time can be checked with a validation and a check constraint, because the validation catches many cases and the constraint covers race conditions.
  • The post suggests optimistic_lock if the real issue is updating from stale data.
  • Overlap between events is presented as a rule that only the database can reliably check.
  • Ecto can map database constraint violations to user-friendly error messages in changesets.
  • Constraints are best for rules that must never be broken.
  • Validations should catch as many errors as possible first, because database constraints fail one at a time and can make form correction tedious.