Using Database Constraints Wisely

Using Database Constraints Wisely

A70410682bd132d5edf76b42189ebb45?s=128

Barun Singh

December 13, 2011
Tweet

Transcript

  1. Using database constraints wisely Barun Singh bsingh@wegowise.com Founder & CTO

  2. What is a database? A collection of data that you

    can read, write, and organize The software tools that let you do this
  3. What do we want from a database? It should be

    … •  Reliable •  Fast •  Secure •  …
  4. A relational database is not the same as a generic

    data store
  5. A relational database is not the same as a generic

    data store
  6. What do we want from a relational database? It should

    be … •  Reliable •  Fast •  Secure •  Sensible •  …
  7. Wait a minute… Is this Rails approved™ ?

  8. The Rails way says… •  You should be database agnostic

    •  Application layer is the only really important part
  9. The database is important

  10. But why? Because you make mistakes.

  11. What’s the worst that can happen? •  Feature doesn’t work

    •  Site goes down •  Irrecoverable data loss
  12. I write tests. Why bother with database constraints? I test

    my entire application flow through integration tests. Why write unit tests?
  13. I write tests. Why bother with database constraints? My application

    requires Javascript, and I have JS validations. Why bother with model-level validations?
  14. Your database has an interface.

  15. How? •  Simple constraints: [not null] •  Unique indices • 

    Foreign keys [foreigner gem]
  16. It’s not always that simple

  17. Polymorphism Imageable Picture Employee Product

  18. Polymorphism What does this reference?

  19. Polymorphism

  20. Polymorpheus

  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. Polymorpheus The gem takes care of all of this for

    you through a simple migration method
  23. Polymorpheus The gem takes care of all of this for

    you through a simple migration method
  24. Polymorpheus

  25. Polymorpheus Also provides a validation method, model level validations are

    still important
  26. You can keep your application logic clean and set up

    your database properly
  27. Questions? bsingh@wegowise.com