Using Database Constraints Wisely

1,087 views

Published on

Presented at the December 13 Boston.rb meeting

Published in: Technology
  • Be the first to comment

Using Database Constraints Wisely

  1. 1. Using databaseconstraints wisely Barun Singh bsingh@wegowise.com Founder & CTO
  2. 2. What is a database? A collection of data that you can read, write, and organizeThe software tools that let you do this
  3. 3. What do we want from a database?It should be …•  Reliable•  Fast•  Secure•  …
  4. 4. A relational database is not the same as a generic data store
  5. 5. A relational database is not the same as a generic data store
  6. 6. What do we want from a relational database?It should be …•  Reliable•  Fast•  Secure•  Sensible•  …
  7. 7. Wait a minute…Is this Rails approved™ ?
  8. 8. The Rails way says…•  You should be database agnostic•  Application layer is the only really important part
  9. 9. The database is important
  10. 10. But why?Because you make mistakes.
  11. 11. What’s the worst that can happen?•  Feature doesn’t work•  Site goes down•  Irrecoverable data loss
  12. 12. I write tests. Why botherwith database constraints?I test my entire application flow throughintegration tests.Why write unit tests?
  13. 13. I write tests. Why botherwith database constraints?My application requires Javascript, and I haveJS validations.Why bother with model-level validations?
  14. 14. Your database has an interface.
  15. 15. How?•  Simple constraints: [not null]•  Unique indices•  Foreign keys [foreigner gem]
  16. 16. It’s not always that simple
  17. 17. Polymorphism Imageable EmployeePicture Product
  18. 18. Polymorphism What does this reference?
  19. 19. Polymorphism
  20. 20. Polymorpheus
  21. 21. A couple little snags… How can you make sure that one picture has only an employee_id or product_id but not both? (xor constraints are tough)And what if the polymorphic relationship has to be unique?
  22. 22. PolymorpheusThe gem takes care of all of this for you through a simple migration method
  23. 23. PolymorpheusThe gem takes care of all of this for you through a simple migration method
  24. 24. Polymorpheus
  25. 25. Polymorpheus Also provides a validation method,model level validations are still important
  26. 26. You can keep yourapplication logic clean andset up your database properly
  27. 27. Questions?bsingh@wegowise.com

×