Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Practical
object-oriented
models in SQL
Bill Karwin
PostgreSQL Conference West 09 • 2009/10/17
Me
• 20+ years experience
  •   Application/SDK developer
  •   Support, Training, Proj Mgmt
  •   C, Java, Perl, PHP

• S...
Object-Oriented vs. Relational


•   Impedance mismatch
•   OO operates on instances;
    RDBMS operates on sets
•   Compr...
Example database
Entity-Attribute-Value
If you try and take a cat apart to see how it works, the
first thing you have on your hands is a non...
Entity-Attribute-Value
 • Objective:          extensibility
    •    Variable sets of attributes

bug_id   bug_type   prio...
Entity-Attribute-Value

             Meta-Table


CREATE TABLE eav (

 bug_id

 
 INT NOT NULL,

 attr_name

 VARCHAR(20) ...
Entity-Attribute-Value

What does this look like?

bug_id   attr_name                   attr_value
 1234     priority     ...
Entity-Attribute-Value

         Problems: names


bug_id    attr_name                   attr_value
 1234       created   ...
Entity-Attribute-Value

         Problems: values


bug_id    attr_name                   attr_value
 1234     created_dat...
Entity-Attribute-Value

      Problems: constraints
                                           NOT NULL


• Difficult to en...
Entity-Attribute-Value

        Problems: constraints
• Difficult to use lookup tables
  bug_id        attr_name           ...
Entity-Attribute-Value

                     Problems: queries
    • Difficult to reconstruct a row of attributes:
        ...
Entity-Attribute-Value

        Solution?



Do it all in application logic?

      ☒☒☒
Entity-Attribute-Value

                 Solution


     Use metadata for metadata
•   Define attributes in columns

•   AL...
Entity-Attribute-Value

     Single Table Inheritance
• One table with many columns
• Inapplicable columns are NULL
  CREA...
Entity-Attribute-Value

       Concrete Table Inheritance
     • Define similar tables for similar types
     • Duplicate c...
Entity-Attribute-Value

 Concrete Table Inheritance
• Use UNION to search both tables:
    SELECT u.* FROM (
    
 SELECT ...
Entity-Attribute-Value

          Class Table Inheritance
   • Common columns in base table
   • Subtype-specific columns i...
Entity-Attribute-Value

     Class Table Inheritance
• Easy to query common columns:
    SELECT * FROM Issues
    WHERE de...
Entity-Attribute-Value

    Using EAV appropriately

• If attributes must be fully dynamic
• Enforce constraints in applic...
Polymorphic Associations
    Of course, some people do go both ways.
                        — The Scarecrow
Polymorphic Assocations
• Objective: reference multiple parents
                                  BUGS


  COMMENTS


    ...
Polymorphic Assocations

           What does this look like?


             comment                                      ...
Polymorphic Assocations

         Problem: constraints
• A FOREIGN KEY constraint
  can’t reference two tables:
  CREATE T...
Polymorphic Assocations

         Problem: constraints
• You have to define table with
  no referential integrity:
  CREATE...
Polymorphic Assocations

             Problem: queries
•   You can’t use a different table for each row.

    SELECT * FRO...
Polymorphic Assocations

              Problem: queries
•   You have to join to each parent table:
    SELECT *
    FROM C...
Polymorphic Assocations

               Solutions


• Exclusive arcs
• Reverse the relationship
• Base parent table
Polymorphic Assocations

            Exclusive Arcs

CREATE TABLE Comments (

 comment_id
 SERIAL PRIMARY KEY,

 comment
 ...
Polymorphic Assocations

             Exclusive Arcs
•   Referential integrity is enforced
•   But hard to ensure exactly ...
Polymorphic Assocations

   Reverse the relationship

             BUGS
           COMMENTS                   BUGS



COMM...
Polymorphic Assocations

   Reverse the relationship
CREATE TABLE BugsComments (

 comment_id
 INT NOT NULL,             n...
Polymorphic Assocations

     Reverse the relationship
• Referential integrity is enforced
• Query comments for a given bu...
Polymorphic Assocations

       Base parent table


BUGS            ISSUES              FEATURES




            COMMENTS
Polymorphic Assocations

                    Base parent table                         works great with
        
   
   CR...
Polymorphic Assocations

           Base parent table
•   Referential integrity is enforced
•   Queries are easier:
     S...
Polymorphic Assocations

 Enforcing disjoint subtypes
CREATE TABLE Issues (

 issue_id
 SERIAL PRIMARY KEY,
          

 i...
Naive Trees
A tree is a tree – how many more do you need to look at?
                                     — Ronald Reagan
Naive Trees


• Objective:        store & query hierarchical data
  •   Categories/subcategories

  •   Bill of materials
...
Naive Trees

What does this look like?
                              (1) Fran:
                           What’s the cause...
Naive Trees

          Adjacency List design
• Naive solution nearly everyone uses
• Each entry knows its immediate parent...
Naive Trees

   Adjacency List strengths

• Easy to inserting a new comment:
   INSERT INTO Comments (parent_id, author, c...
Naive Trees

     Adjacency List strengths

• Querying a node’s 
children is easy:
     SELECT * FROM Comments c1
     LEF...
Naive Trees

     Adjacency List problems
• Hard to query all descendants in a deep tree:
  SELECT * FROM Comments c1
  LE...
Naive Trees

      SQL-99 recursive syntax
WITH RECURSIVE CommentTree

 (comment_id, bug_id, parent_id, author, comment, d...
Naive Trees

          Path Enumeration
• Store chain of ancestors in each node
                                          ...
Naive Trees

  Path Enumeration strengths

• Easy to query ancestors of comment #7:
    SELECT * FROM Comments
    WHERE ‘...
Naive Trees

  Path Enumeration strengths

• Easy to add child of comment 7:
     INSERT INTO Comments (author, comment)
 ...
Naive Trees

                Nested Sets
• Each comment encodes its descendants
  using two numbers:
  •   A comment’s lef...
Naive Trees

Nested Sets illustration

                                        (1) Fran:
                                 ...
Naive Trees

             Nested Sets example

comment_id    nsleft   nsright     author             comment
    1        ...
Naive Trees

       Nested Sets strengths


• Easy to query all ancestors of comment #7:
     SELECT * FROM Comments child...
Naive Trees

Nested Sets strengths

                                       (1) Fran:
                                     ...
Naive Trees

      Nested Sets strengths


• Easy to query descendants of comment #4:
    SELECT * FROM Comments parent
  ...
Naive Trees

Nested Sets strengths

                                       (1) Fran:                                    pa...
Naive Trees

       Nested Sets problems
• Hard to insert a new child of comment #5:
     UPDATE Comments
     SET
nsleft ...
Naive Trees

Nested Sets problems

                                       (1) Fran:
                                    Wh...
Naive Trees

         Nested Sets problems
• Hard to query the parent of comment #6:
  SELECT parent.* FROM Comments AS c
...
Naive Trees

             Closure Tables
• Store every path from ancestors to
  descendants
• Requires an additional table...
Naive Trees

Closure Tables illustration

                                     (1) Fran:
                                 ...
Naive Trees

     Closure Tables example
                                                      ancestor descendant
       ...
Naive Trees

    Closure Tables strengths


• Easy to query descendants of comment #4:
    SELECT c.* FROM Comments c
    ...
Naive Trees

     Closure Tables strengths


• Easy to query ancestors of comment #6:
    SELECT c.* FROM Comments c
    J...
Naive Trees

     Closure Tables strengths

• Easy to insert a new child of comment #5:
     INSERT INTO Comments
     
 V...
Naive Trees

     Closure Tables strengths



• Easy to delete a child comment #7:
     DELETE FROM TreePaths
     WHERE d...
Naive Trees

     Closure Tables strengths
• Easy to delete subtree under comment #4:
    DELETE FROM TreePaths
    WHERE ...
Naive Trees

       Closure Tables depth
                                      ancestor descendant   depth
               ...
Naive Trees

                 Choose the right design

                        Query    Query Delete     Add   Move Refere...
Magic Beans
Essentially, all models are wrong, but some are useful.
                                  — George E. P. Box
Magic Beans



• Objective:
  •   Model-View-Controller application development

  •   Object-Relational Mapping (ORM)
Magic Beans

      Active Record

The Golden Hammer of database access
     in most MVC frameworks:
Magic Beans

Model is-a Active Record?
                 Active
                 Record
                                   ...
Magic Beans

        Problem: OO design

• “Model” : Active Record          inheritance
                                  ...
Magic Beans

        Problem: MVC design

• Controllers need to know              “T.M.I.” !!
    database structure

•   ...
Magic Beans

         Problem: testability

                                               tests are
• Harder to test Mode...
OO is about decoupling
Magic Beans

Model has-a Active Record(s)
                 Active
                 Record
                                ...
Magic Beans

       Model characteristics

• Extend no base class
• Abstract the database
• Expose only domain-specific int...
Magic Beans

              Model benefits

• Models are decoupled from DB
  •   Supports mock objects

  •   Supports depen...
Magic Beans

Decouple your Models
     You can use this design




 ...even in MVC frameworks that
     encourage the anti...
Copyright 2008-2009 Bill Karwin
        www.slideshare.net/billkarwin
              Released under a Creative Commons 3.0 ...
Upcoming SlideShare
Loading in …5
×

Polymorphic Associations Of course, some Practical Object Oriented Models In Sql

77,379 views

Published on

Polymorphic Associations
Of course, some people do go both ways.
— The Scarecrow

Published in: Technology
  • Any chance there is a video recording of this anywhere?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • I know this is now an old post but it is still very relevant. I was particularly interested in the topic of hierarchical data. Very helpful but I believe one common requirement was not discussed - querying the whole set of data to return the full hierarchy. It seems to me that the Path Enumeration approach would be best for that because a simple query or one table ordered by the path would give the required result.
    I am also wondering, as it would be a small overhead, whether combining the Path Enumeration and Adjacent List approaches might provide the best solution, with each resolving the the omission in the other.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Excellent treatment of solutions to Polymorphic associations (one column pointing to FKs in multiple tables)
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • thank you
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

×