Using database
constraints wisely
         Barun Singh
    bsingh@wegowise.com

       Founder & CTO
What is a database?
  A collection of data that you can
      read, write, and organize

The software tools that let you do this
What do we want from a
            database?
It should be …

•    Reliable
•    Fast
•    Secure
•    …
A relational database
  is not the same as
 a generic data store
A relational database
  is not the same as
 a generic data store
What do we want from a
       relational database?
It should be …

•    Reliable
•    Fast
•    Secure
•    Sensible
•    …
Wait a minute…
Is this Rails approved™ ?
The Rails way says…
•  You should be database agnostic
•  Application layer is the only really important
   part
The database is important
But why?
Because you make mistakes.
What’s the worst that can
          happen?
•  Feature doesn’t work
•  Site goes down
•  Irrecoverable data loss
I write tests. Why bother
with database constraints?
I test my entire application flow through
integration tests.

Why write unit tests?
I write tests. Why bother
with database constraints?
My application requires Javascript, and I have
JS validations.

Why bother with model-level validations?
Your database has an
      interface.
How?
•  Simple constraints: [not null]
•  Unique indices
•  Foreign keys [foreigner gem]
It’s not always that simple
Polymorphism


           Imageable
           Employee
Picture
           Product
Polymorphism




         What does
         this
         reference?
Polymorphism
Polymorpheus
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?
Polymorpheus
The gem takes care of all of this for you
  through a simple migration method
Polymorpheus
The gem takes care of all of this for you
  through a simple migration method
Polymorpheus
Polymorpheus
  Also provides a validation method,
model level validations are still important
You can keep your
application logic clean
          and
set up your database
       properly
Questions?


bsingh@wegowise.com

Using Database Constraints Wisely