Skip to main content

Use TREAT to Access Attributes of Object Subtypes

The TREAT function comes in very handy when working with an object type hierarchy, and you need to access attributes or methods of a subtype of a row or column's declared type. This topic was covered in a PL/SQL Challenge quiz offered in March 2016. 

Suppose I have the following type hierarchy and  I use them as column types in my meals table:

CREATE TYPE food_t AS OBJECT (
   name VARCHAR2 (100),
   food_group VARCHAR2 (100),
   grown_in VARCHAR2 (100)
)
   NOT FINAL;
/

CREATE TYPE dessert_t UNDER food_t (
      contains_chocolate CHAR (1),
      year_created NUMBER (4)
   )
   NOT FINAL;
/

CREATE TYPE cake_t UNDER dessert_t (
      diameter NUMBER,
      inscription VARCHAR2 (200)
   );
/

CREATE TABLE meals
(
   served_on     DATE,
   appetizer     food_t,
   main_course   food_t,
   dessert       dessert_t
);

I then insert some rows into the table:

BEGIN
   INSERT INTO meals
        VALUES (SYSDATE + 1,
           food_t ('Shrimp cocktail', 'PROTEIN', 'Ocean'),
           food_t ('Stir fry tofu', 'PROTEIN', 'Vat'),
           cake_t ('Apple Pie',
                    'FRUIT', 'Baker''s Square',
                    'N', 2001, 8, NULL));

   INSERT INTO meals
        VALUES (SYSDATE + 1,
                food_t ('Fried Calamari', 'PROTEIN', 'Ocean'),
                dessert_t ('Butter cookie',
                   'CARBOHYDRATE', 'Oven', 'N', 2001),
                cake_t ('French Silk Pie',
                   'CARBOHYDRATE', 'Baker''s Square',
                   Y', 2001, 6, 'To My Favorite Frenchman'));

   INSERT INTO meals
        VALUES (SYSDATE + 1,
                food_t ('Fried Calamari', 'PROTEIN', 'Ocean'),
                cake_t ('French Silk Pie',
                        'CARBOHYDRATE', 'Baker''s Square',
                        'Y', 2001, 6, 'To My Favorite Frenchman'),
                dessert_t ('Butter cookie',
                           'CARBOHYDRATE', 'Oven', 'N', 2001));
   COMMIT;
END;
/

Notice that even though appetizer and main_course are defined as food_t, I can assign dessert_t and cake_t instances to those columns, because object types support substitutability (the best way to understand that is: every dessert is a food, but not every food is a dessert).

Let's take a look at some of the ways I can use TREAT.

1. I want to find all the meals in which the main course is actually a dessert.

SELECT *
  FROM meals
 WHERE TREAT (main_course AS dessert_t) IS NOT NULL


2. Show whether or not those dessert-centric meals contain chocolate. First with PL/SQL:


DECLARE
   l_dessert   dessert_t;
BEGIN
   FOR rec IN (
      SELECT * FROM meals
       WHERE TREAT (main_course AS dessert_t) IS NOT NULL)
   LOOP
      l_dessert := TREAT (rec.main_course AS dessert_t);

      DBMS_OUTPUT.put_line (
         rec.main_course.name || '-' || 
         l_dessert.contains_chocolate);
   END LOOP;
END;
/


And now with "pure" SQL:

SELECT TREAT (m.main_course AS dessert_t).contains_chocolate
  FROM meals m
 WHERE TREAT (main_course AS dessert_t) IS NOT NULL


The thing to realize in both these cases is that even though I have identified only those meals for which the main course is a dessert, I still must explicitly TREAT or narrow the main_course column to dessert_t, before I will be able to reference the contains_chocolate attribute.


If I forget the TREAT in the SELECT list, such as:

SELECT m.main_course.contains_chocolate
  FROM meals m
 WHERE TREAT (main_course AS dessert_t) IS NOT NULL

I will see this error:

ORA-00904: "M"."MAIN_COURSE"."CONTAINS_CHOCOLATE": invalid identifier

3. Set to NULL any desserts that are not cakes.

UPDATE meal
   SET dessert = TREAT (dessert AS cake_t);

Comments

Popular posts from this blog

Why DBMS_OUTPUT.PUT_LINE should not be in your application code

A database developer recently came across my  Bulletproof PL/SQL  presentation, which includes this slide. That first item in the list caught his attention: Never put calls to DBMS_OUTPUT.PUT_LINE in your application code. So he sent me an email asking why I would say that. Well, I suppose that is the problem with publishing slide decks. All the explanatory verbiage is missing. I suppose maybe I should do a video. :-) But in the meantime, allow me to explain. First, what does DBMS_OUTPUT.PUT_LINE do? It writes text out to a buffer, and when your current PL/SQL block terminates, the buffer is displayed on your screen. [Note: there can be more to it than that. For example, you could in your own code call DBMS_OUTPUT.GET_LINE(S) to get the contents of the buffer and do something with it, but I will keep things simple right now.] Second, if I am telling you not to use this built-in, how could text from your program be displayed on your screen? Not without a lot o...

How to Pick the Limit for BULK COLLECT

This question rolled into my In Box today: In the case of using the LIMIT clause of BULK COLLECT, how do we decide what value to use for the limit? First I give the quick answer, then I provide support for that answer Quick Answer Start with 100. That's the default (and only) setting for cursor FOR loop optimizations. It offers a sweet spot of improved performance over row-by-row and not-too-much PGA memory consumption. Test to see if that's fast enough (likely will be for many cases). If not, try higher values until you reach the performance level you need - and you are not consuming too much PGA memory.  Don't hard-code the limit value: make it a parameter to your subprogram or a constant in a package specification. Don't put anything in the collection you don't need. [from Giulio Dottorini] Remember: each session that runs this code will use that amount of memory. Background When you use BULK COLLECT, you retrieve more than row with each fetch, ...

Table Functions, Part 1: Introduction and Exploration

Please do feel encouraged to read this and my other posts on table functions, but you will learn much more about table functions by taking my Get Started with PL/SQL Table Functions class at the Oracle Dev Gym. Videos, tutorials and quizzes - then print a certificate when you are done! Table functions - functions that can be called in the FROM clause of a query from inside the TABLE operator - are fascinating and incredibly helpful constructs. So I've decided to write a series of blog posts on them: how to build them, how to use them, issues you might run into. Of course, I am not the first to do so. I encourage to check out the  documentation , as well as excellent posts from Adrian Billington (search for "table functions") and Tim Hall . Adrian and Tim mostly focus on pipelined table functions, a specialized variant of table functions designed to improve performance and reduce PGA consumption. I will take a look at pipelined table functions in the latter part...