User Defined Types

download User Defined Types

of 15

Transcript of User Defined Types

  • 7/30/2019 User Defined Types

    1/15

    User-defined TypesModeling the Real World with UDTs

    By George Lawandus

    July 19, 2005

    Data Warehousing > Database

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    2/15

    User-defined Types

    EB-4622 > 1105 > PAGE 2 OF 15

    Executive Overview

    Object-oriented technology has made it easier for a software

    developer to design data objects that model the structure and

    the behavior of real-world entities, such as multimedia files,

    XML documents, currency, and geospatial applications.

    Functionality and data can be encapsulated within an object

    making it a discrete, self-contained entity that can be queried

    to reveal information about its content and provides a set of

    methods that operate on that content.

    Historically, it has been a nontrivial effort for a database

    administrator to design and implement database applications

    that emulate real-world objects or processes using the com-

    mon structures and data types available in a relational

    database. For example, one way to represent an MPEG video

    clip might be to create a table with a column for the binary

    data and other columns that contain values that represent the

    various attributes of the video. This kind of representation is

    somewhat linear and requires a separate column for the binary

    video data and each attribute.

    A more concise approach would be to directly abstract the

    video clip as an object (similar to a C++ class) complete with

    operations and attributes that can more closely represent how

    a video clip would exist in real life. Teradata Database now

    facilitates this object-oriented approach by supporting User-

    defined Types (UDTs).

    Executive Overview 2

    The Benefits of User-defined Types 3

    UDTs Defined 3

    Components of a UDT 4

    Two Flavors of UDTs 6Distinct Type 6

    Structured Type 7

    Creating User-defined Methods 10

    UDT Security and Access Rights 13

    Execution Modes 14

    Build Real-World Objects with UDTs 14

    The UDT Advantage 15

    About the Author 15

    Table of Contents

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    3/15

    The Benefits of User-defined TypesUser-defined Types enable Teradata Database users to develop

    objects that can model business processes and entities that typi-

    cally occur throughout the enterprise. Database developers can

    now add objects such as Euro, polygon, patient record, XML

    document and MPEG video, directly to relational tables. These

    objects can emulate much of the structure and behavior of their

    real-world counterparts while being completely integrated within

    the Teradata Database. Some specific benefits include:

    Extensibility

    UDTs make it possible to define custom data types and extend the

    existing types supported by the Teradata Database. These new data

    types can have user-defined names that intuitively represent their

    function and use. UDTs are globally accessible and can be specified

    anywhere a Teradatapredefined(built-in) type is used. Data

    previously stored in multiple table columns can now be repre-

    sented by a single data type.

    Developers can leverage data already stored in a Teradata Ware-

    house by using UDTs to define new data models and provide

    functionality that does not currently exist within the Teradata SQL

    language.

    Consistency and Control

    In addition to a unique name, behavior and content can also be

    associated with the UDT, thereby differentiating it from other data

    types in the database. This is accomplished through the use of

    User-defined Methods (UDMs). UDMs provide a public user

    interface and a representation of the data type that is external to

    the Teradata Database. This ensures that the functionality of the

    object and the data encapsulated within it remain consistent

    regardless of the application that uses it. Interaction with other

    types and usage of the UDT itself can be strictly controlled by the

    DBA and the type developer.

    SecuritySecurity of data and other intellectual property is enhanced

    through the use of User-defined Types. Access to the data encapsu-

    lated within the UDT can be strictly controlled through the

    methods and database access rights associated with the type.

    Encapsulated data can be encrypted within a UDT, or methods

    can be employed that return only unsecured data or just an

    interpretation of the data.

    Object-oriented Technology

    Teradatas implementation of User-defined Types leverages true

    object-oriented technology which enables developers to apply

    current methodologies and techniques when designing User-

    defined Types. UDTs are true objects with an external interface

    implemented with a collection of user and system defined meth-

    ods. A UDM can be written in either the C or C++ languages.

    UDTs Defined

    A UDT can be defined simply as a custom collection of one or

    more data values that can be organized into a single type and a set

    of methods that operates on those data values. As mentioned

    earlier, UDTs are typically used to model real-world objects, but

    can be used for just about any application that requires a custom

    data type with specific capabilities that are not offered by conven-

    tional data types.

    A Teradata UDT can have one or more data attributes which can

    be based on a predefined type or another UDT. The number of

    attributes is dependant on whether the UDT exists as a Distinctor

    Structuredtype. The differences between these two types of UDTs

    will be discussed after the components are explained.

    UDTs can be used in essentially the same way as Teradata

    predefined types. They can appear as column types, arguments to

    User-defined Functions, in stored procedures, macros or triggers.

    User-defined Types

    EB-4622 > 1105 > PAGE 3 OF 15

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    4/15

    A UDT is strongly typed. This means that, by default, a UDT isconsidered separate and distinct from Teradata predefined types as

    well as other UDTs. At first glance, this may seem counter intuitive

    for database applications, but this design ensures that the type can

    only be used as the developer intended and that its behavior

    remains consistent regardless of where it is used.

    For example, if two columns based on a decimal type were used to

    store values for Euro and U.S. dollars, one could compare and

    interchange these values without any restrictions; however, the

    result would be meaningless. If the same columns were based on

    UDTs, the Euro column cannot be directly added to a Dollar

    column because these are considered different types. UDT devel-

    opers do have the capability to make their types compatible with

    other types by defining CAST routines.

    Components of a UDT

    Both kinds of Teradata UDTs share the same basic components

    and functionality that was derived from the SQL-99 standard.

    These components determine the behavior of the UDT as well as

    how it interacts with other types (both predefined and user-

    defined) within the Teradata Database. The following components

    are essential to developing a useful and fully functional UDT.

    Transforms

    A transform is a mechanism for transforming the value of the

    UDT to and from a Teradata predefined type. In this sense, it

    allows the type developer to create an external representation of

    the UDT that is used when exporting and importing data between

    the client and the Teradata server. This mechanism allows most

    Teradata client utilities and open APIs to transparently move data

    to and from a UDT without the need for special logic or metadata.

    Transforms usually appear as a named pair of functions or meth-

    ods called a transform group. These functions are usually referredto as To-SQL and From-SQL to indicate the direction of data flow

    to and from the database. A transform group is required if the

    type is to be used in a table.

    The From-SQL routine is responsible for transforming the UDTinto a Teradata predefined type and is implicitly invoked for

    export operations and queries that reference a column defined as

    this UDT. For example, suppose a UDT called Euro is used as the

    data type for a table column and its From-SQL routine declared a

    return type of DECIMAL(10,2). The query: SELECT EuroCol-

    umn from Currency; will return a value of the type

    DECIMAL(10,2). This will also hold true for queries that generate

    implicit column lists as in the case of SELECT * from Table-

    Name;.

    The To-SQL routine is used to transform an external or Teradata

    predefined type into the UDT and is implicitly invoked during an

    import operation which is usually initiated by a client utility or an

    open API that does not support client side UDT representations.

    Regular insert operations do not use the To-SQL transform.

    Referring to the previous example, if a data value of the type

    DECIMAL(10,2) is imported into a table column defined as type

    Euro, the To-SQL routine is called to convert this value into the

    Euro UDT which will then be inserted into the table.

    Teradatas implementation of transforms allows the UDT devel-

    oper complete control over what Teradata predefined types the

    From-SQL routine returns and To-SQL routine accepts. The only

    requirement is that these data types must match. Typically the

    From-SQL value is representative of the data encapsulated within

    the UDT and the To-SQL value represents the same value as it

    exists external to the Teradata Database.

    A Teradata UDT can only have one transform group associated

    with it at any one time. However, a library of transform routines

    can be defined for a particular UDT and then paired together as

    new transform groups. By substituting one transform group for

    another, UDT developers can exercise precise control over how

    data values are exported or imported and what value is returned as

    a result of a query.

    User-defined Types

    EB-4622 > 1105 > PAGE 4 OF 15

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    5/15

    OrderingAn ordering specifies how UDTs are relationally compared with

    each other or how the UDT appears within the result set of a query

    that specifies ordering, grouping or set operations. Orderings are

    required if the UDT is to be used as a data type for a table column.

    Queries that specify a UDT in a WHERE, ORDER BY or GROUP

    BY clause are some examples of where the orderings are used.

    Like transforms, the Teradata implementation of orderings allows

    the UDT developer to determine what value is returned by the

    ordering routine. This value would typically represent the data

    encapsulated within the UDT in some meaningful way. This allows

    control over how the UDT behaves in SQL expressions that

    compare UDTs of the same type and queries that specify ordering,

    set operations, exclusions, and groups.

    Relational comparisons such as: SELECT Video1 from Surveil-

    lanceCamera WHERE Video1 > Video2; will implicitly invoke

    the ordering for the UDT. This type of query is possible because

    the ordering routines for the UDTs in this expression return a

    value that can be compared and ordered.

    Casts

    By definition, a UDT is considered distinct and separate from allother data types or other UDTs. This implies that a UDT cannot

    be assigned to, or interact with, data types other than itself. If

    desired, this default behavior can be used as a mechanism to

    restrict the usage of a UDT. If interaction with other data types is

    necessary, a UDT can be associated with one or more user-defined

    cast routines.

    A cast is a construct that supports the conversions between

    different UDTs and other data types. This allows the developer to

    create UDTs that can freely interact with other data types and

    appear in SQL expressions that involve mixed data types. Teradatadoes not require that a cast exist for a UDT to be used in a table.

    However, defining casts for a UDT is desirable because they can

    enable implicit or explicit conversions to other data types that arenatural or logical for the entity that the UDT represents.1

    By default, the value of a Euro column cannot be assigned to a

    UsDollar column because no implicit conversion exists between a

    Euro UDT and a UsDollar UDT. This is because their implementa-

    tions are user-defined. If such a conversion were required, a

    developer could create cast routines to allow this to happen. If the

    appropriate casts are defined, statements such as the following are

    now possible:

    UPDATE Sales SET Euro_Column = UsDollar_Column;

    UPDATE Sales SET Euro_Column = CAST(UsDollar_ColumnAS Euro);

    INSERT into Sales VALUES(1,10.50);

    In the first example, the user-defined cast is implicitly called to

    convert the UDT stored in the UsDollar_Column UDT to a Euro

    UDT with its data converted to the equivalent Euro denomination.

    The second statement uses an explicit cast to perform the same

    operation. The last statement illustrates an implicit cast from a

    numeric literal to a UDT. A cast from this data type to the UDT

    must exist in order for this kind of conversion to take place. For

    example, the cast: (DECIMAL(4,2) AS UsDollar) must be createdand associated with the UsDollar UDT.

    Methods

    The ability to create and associate methods with an object is one

    of the most powerful aspects of the object-oriented paradigm.

    Methods not only define the behavior of the object but how it is

    used and viewed by the end user of that object. Methods are what

    make it possible to design a UDT that behaves similarly to its real-

    world counterpart. The basic definition of a method is a custom

    operation or procedure that can operate on the data encapsulated

    within a UDT and return some value.

    The Teradata Database generates certain predefined methods when

    a UDT is created and also supports a mechanism for allowing

    User-defined Types

    EB-4622 > 1105 > PAGE 5 OF 15

    1 Refer to Teradata SQL Reference: Data Definition Statements for rules regarding implicit and explicit casting.

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    6/15

    developers to create their own methods. These are usually referredto as a User-defined Method (UDM)2. For example, the Euro UDT

    might have UDMs that return the equivalent value in some other

    currency, the current exchange rates for different currencies, and

    the value of the Euro itself.

    There might also be methods, for updating these attributes, which

    can be invoked in real-time to keep these values up-to-date.

    Methods make it possible for the Euro UDT to have the same

    attributes and behavior as its real-world counterpart as it exists in

    the world markets. Queries like the following are possible:

    SELECT EuroDollar.UsExchangeRate() from CurrencyTable;

    SELECT SUM(EuropeanSales.UsDollarValue()) from

    SalesTable;

    These queries illustrate how methods can be used to query the

    content or data attribute of a UDT and how they can be used to

    calculate values derived from the data. The first query returns the

    current U.S. exchange rate for the Euro and the second returns the

    sum of European sales (in Euros) converted to the equivalent U.S.

    dollar value.

    There are currently two kinds of User-defined Methods supported

    by Teradata: instance and constructor methods. The previous

    examples illustrate the use of the instance or regular method. Type

    developers use instance methods to define a functional interface to

    a UDT. This provides the type developer with an efficient mecha-

    nism to control how the content and functionality of the UDT is

    exposed to the end user. Instance methods can be defined with

    zero or more parameters and can return a value which can be a

    Teradata predefined type or a UDT.

    Like instance methods, constructor methods can be defined with

    or without parameters but can only return the UDT of the type

    with which the constructor method is associated. Constructormethods are typically used to initialize the data attributes of a

    structured UDT during its construction or instantiation. Thisallows the developer to easily determine what initial data values

    the UDT will have after it is inserted into a table. Distinct UDTs

    do not have constructor methods as such.

    Two Flavors of UDTs

    Now that we understand the major components of a UDT, we can

    discuss what kinds are supported by the Teradata Database and

    how they are implemented. The Teradata Database supports two

    flavors of UDTs: Distinct and Structured. The differences between

    these two are important and determine how the UDTs are devel-

    oped and used.

    Distinct Type

    A distinct UDT shares its internal implementation with a single

    Teradata predefined type which is commonly referred to as the

    UDTs source type. Distinct UDTs adhere to the concept of strict

    typing which means that even though a distinct UDT is based on a

    Teradata integer, for example, it is considered a separate type from

    integer and is incompatible (by default) for many operations that

    involve integers. This concept assures that the UDT exists as an

    independent entity and that methods defined for it cannot be

    directly applied to other UDTs or predefined data types. The UDT

    essentially assumes an identity that is unique throughout the

    Teradata Database and is only truly compatible with another UDT

    of the same type name.

    For example, the statement: CREATE TYPE Euro as DECI-

    MAL(10,2) FINAL; creates a distinct UDT (without methods)

    that is based on the DECIMAL(10,2) data type. Although this

    UDT is internally represented as a decimal type it is considered a

    Euro type, not a decimal type, because its structure and behavior is

    user-defined and is not part of the decimal family. A distinct UDT

    can specify any Teradata predefined type as its source type butcannot specify another UDT for this purpose.

    User-defined Types

    EB-4622 > 1105 > PAGE 6 OF 15

    2 Refer to Teradata SQL Reference: UDF, UDM and External Stored Procedures for more information regarding the creation and use of UDMs.

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    7/15

    Characteristics of a Distinct TypeJust because the UDT is a unique type doesnt mean that it has to

    live in abject isolation. As mentioned earlier, a UDT can interact

    with other types via its transforms, ordering, casts and instance

    methods. In adherence with the SQL-99 standard, the Teradata

    Database will auto-generate the To-SQL and From-SQL transform,

    the ordering, and a set of casts for a distinct UDT in response to

    issuing the CREATE TYPE statement. These constructs are based

    on the source type of the UDT.

    The following functionality is auto-generated for DISTINCT

    types:

    > To-SQL Transform Accepts the source type and returns a UDT

    > From-SQL Transform Accepts a UDT and returns the

    source type

    > CAST (Source Type AS UDT) Converts from the source type

    to the UDT

    > CAST (UDT AS Source Type) Converts from the UDT to the

    source type

    > Ordering Returns the source type

    Note: Orderings are not automatically generated for UDTs with

    large object (LOB) source types.

    If the UDTs source type was INTEGER, the default behavior for

    this UDT would be:

    The To-SQL transform accepts an integer value for an import

    operation and returns a distinct UDT which is inserted into a

    table. The From-SQL transform returns an integer value in

    response to a SELECT or other queries. Casts convert the UDT to

    and from an integer value either implicitly or explicitly depending

    on where it is applied. The ordering will return an integer value

    when used in a comparison or an operation that requires an

    ordering.

    The Teradata implementation for distinct UDTs allows the typedeveloper to drop these system generated components and define

    their own. This is extremely useful if the default behavior of the

    distinct type is not adequate for a particular application. It should

    be noted that orderings for distinct LOB types are not automati-

    cally generated and must be created by the type developer.

    Remember that an ordering is required if the UDT is to be used

    in a table.

    Structured Type

    A structured UDT shares some of the characteristics of the distinct

    type but differs in terms of structure and functionality. Similar

    to a structure used in the C language, the structured UDT is

    essentially a collection or series of named attributes, each of which

    is assigned a data type.

    Characteristics of a Structured Type

    Similar to distinct types, a structured types data attributes can

    also be based on Teradata predefined types. Whats different is that

    a structured type attribute can also be declared as a distinct or a

    structured UDT. This kind of configuration is usually referred to

    as a nested type.

    Another important distinction of a structured type is that the

    SQL-99 standard does not specify methodologies for system

    generated transforms, orderings and casts as with distinct types.

    All these components must be defined by the type developer.

    Since structured types are essentially an arbitrary collection of

    user-defined data attributes, the Teradata Database cannot make

    any assumptions as to how these attributes are externally repre-

    sented. As with distinct types, a transform group and an ordering

    must be defined before the type can be used in a table. Casts are

    not required but are recommended in order to have a completely

    functional type.

    User-defined Types

    EB-4622 > 1105 > PAGE 7 OF 15

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    8/15

    Observer MethodsBecause instance methods are also not required for structured

    types, two special methods are provided to allow the data attrib-

    utes to be queried and updated. These are commonly referred to as

    observerand mutatormethods. When the type is created, a pair of

    observer and mutator methods is auto-generated for each of the

    data attributes defined for the type. The observer method is used

    to observe or query the value of the data attribute while the mutator

    is used for mutating or changing the attributes current value.

    The following CREATE TYPE statement creates a structured type

    called Address.

    CREATE TYPE Address AS (

    Street VARCHAR(20),

    City VARCHAR(20),

    State CHAR(2),

    Zip CHAR(5) )

    NOT FINAL;

    In addition to the type, one observer and one mutator method is

    auto-generated for each of the Street, City, State and Zip attrib-

    utes. These methods are assigned the same name as the attribute to

    make referencing them as intuitive as possible. When an observer

    is used to retrieve the data stored in a UDT attribute, the Teradata

    Database returns this value as separate column which has the same

    name and data type as the attribute.

    Assuming that the Address UDT was used in a table, the followingqueries are some examples of how observers and mutators would

    be used to query and update the data attributes of this type.

    1. SELECT EmployeeAddress.Street() from Personnel;

    2. SELECT EmployeeAddress.ALL from Personnel;

    3. SELECT *.ALL from Personnel;

    The first query calls the Street() observer method for the Address

    UDT. This returns a single column called Streetwhich contains the

    value of the Street attribute, with one occurrence per row.

    SELECT EmployeeAddress.Street() from Personnel;

    EmployeeAddress.Street()

    ----------------------------

    1919 Peach Way

    245 E. Montgomery Ave.

    7516 Cherry Ave

    15602 Prickly Pear Way

    3800 Victory Parkway

    140 Seventh Avenue South

    55 West Main Street

    601 Colorado Street

    User-defined Types

    EB-4622 > 1105 > PAGE 8 OF 15

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    9/15

    The third query (output not shown) uses the * operator with

    the .ALL qualifier to retrieve all of the columns in the table and

    causes the expansion of any UDT column into a list of its attrib-

    utes. As in the second query, all UDT attributes are retrieved asseparate columns.

    Mutator Methods

    Mutator methods are typically used to modify the values of an

    existing UDTs data attributes but they can also be used during the

    creation of the UDT. The following examples assume that the

    EmployeeAddress column is defined as type Address. These

    UPDATE queries accomplish the same thing but use slightly

    different syntax.

    UPDATE Personnel

    SET EmployeeAddress =

    EmployeeAddress.Street(Sepulveda).Zip(92045)

    WHERE

    EmployeeAddress.City() = El Segundo;

    UPDATE Personnel

    SET EmployeeAddress.Street = Sepulveda,

    EmployeeAddress.Zip = 92045

    WHERE

    EmployeeAddress.City() = El Segundo;

    The first example illustrates a conventional UPDATE statement

    that uses mutator methods to update the street and zip code

    attributes in the EmployeeAddress column. Using this chained

    syntax can become quite tedious and cumbersome for types that

    have a large number of attributes. To simplify complex updates,

    the Teradata Database now supports the more intuitive and

    shorter SQL-99 syntax referred to as the mutated set clause.

    User-defined Types

    EB-4622 > 1105 > PAGE 9 OF 15

    The second query uses the new .ALL column qualifier syntax to retrieve all of the data attributes ofAddress as one column per attributein the same order in which they appear in the CREATE TYPE statement. The default column titles will be identical to the first example

    except for the attribute name.

    SELECT EmployeeAddress.ALL from Personnel;

    EmployeeAddress.Street() EmployeeAddress.City() EmployeeAddress.State()

    ----------------------------- --------------------------- ----------------------------

    1919 Peach Way Athens GA

    245 E. Montgomery Ave. Ardmore PA

    7516 Cherry Ave Kingston RI

    15602 Prickly Pear Way Tucson AZ

    3800 Victory Parkway Cincinnati OH

    140 Seventh Avenue South St. Petersburg FL

    55 West Main Street Waterbury CT

    601 Colorado Street Austin TX

    The output of this query was truncated for readability.

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    10/15

    This query uses a mutator invocation to update the Street and Zipattributes after the UDT is constructed.

    UPDATE Personnel

    SET EmployeeAddress =

    NEW Address().Street(Sepulveda).Zip(92045)

    WHERE

    EmployeeAddress.City() = El Segundo;

    At first glance this query might appear to accomplish the same

    update operations as the previous examples. However, careful

    examination reveals that a NEW instance of the UDT is created

    and assigned to EmployeeAddress rather than just updating the

    Street and Zip attributes of an existing UDT.

    Constructor Methods

    Structured types support the concept of a special kind of method

    called a constructor method. Default constructor methods are

    auto-generated when the structured type is created and are

    automatically invoked when the type is created (instantiated). The

    functions of the default constructor are to instantiate the type and

    initialize all of the data attributes to NULL. Type developers can

    also write their own constructor methods to initialize data attrib-

    utes and perform other tasks after the UDT is instantiated.

    The following INSERT statement is one example of how a user-

    defined constructor method can be used.

    INSERT INTO Personnel values

    (1, NEW Address(17905 Via Del Campo,San

    Diego,CA,92917));

    In this example, the keyword NEW is used to indicate that a new

    instance of the Address UDT is to be constructed by first calling

    the default constructor Address() and then initiating a call to the

    user-defined constructor method Address() to initialize thevalues of the data attributes passed as arguments. The Address

    UDT is then inserted into the table. Just like its C ++ counterpart,

    the user-defined constructor function is always the same name as

    the UDT. Constructor methods are defined in the same way as

    instance methods and always have the same name as the type.

    Creating User-defined Methods

    Although not required, a UDT without methods is not very

    interesting and does very little to extend the SQL language or

    model a real-world object. The definition and procedure for

    creating user-defined methods is essentially the same for distinct

    and structured types. The main difference is that constructor

    methods cannot be defined for distinct types. Only instance

    methods can be defined.

    Creating a UDM is similar to creating a User-defined Function in

    that it involves the creation of C or C++ code to define a callable

    function that contains the executable program logic.3 UDMs and

    UDFs also share the same execution models. The difference is that

    a UDM is always associated with a particular UDT and is not

    executed as a separate function.

    Creating methods for UDTs requires two steps as opposed to a

    single step for a UDF. The first step requires that we first define the

    method prototype or signature. This signature is used by the

    Teradata Database to associate the UDM with a particular UDT

    and to differentiate it from other UDMs when it is called in a SQL

    query or expression. If there is more than one UDM with the same

    name (when a method is overloaded) defined for a particular

    UDT, the Teradata Database uses the number of arguments and

    their data types to uniquely identify which UDM to call.

    User-defined Types

    EB-4622 > 1105 > PAGE 10 OF 15

    3 Refer to Teradata SQL Reference: UDF, UDM and External Stored Procedure Programming for more information regarding the definition and creation of UDMs and UDFs.

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    11/15

    Referring back to the Euro example, methods that will operate onthis type can be defined by first modifying the CREATE TYPE

    statement to include the method prototypes.

    CREATE TYPE Euro

    AS DECIMAL(10, 2)

    FINAL

    METHOD UsDollarValue ()

    RETURNS DECIMAL(10,2)

    LANGUAGE C

    DETERMINISTIC

    NO SQL

    RETURNS NULL ON NULL INPUT,

    METHOD UsExchangeRate ()

    RETURNS FLOAT

    LANGUAGE C

    DETERMINISTIC

    NO SQL

    RETURNS NULL ON NULL INPUT;

    These declarations may look very much like those used for UDFsand follow the same basic rules and syntax.4 In this example, two

    methods are declared: UsDollarValue() and UsExchangeRate().

    Notice that these methods do not have any declared arguments

    and both return a Teradata predefined type. The UsDollarValue()

    method returns the U.S. dollar equivalent of the Euro as a DECI-

    MAL(10,2) and the UsExchangeRate() returns the exchange rate as

    a FLOAT. Since UDTs are considered real data types, they could

    have also been declared as data types in the method argument lists

    and as the returned type.

    The CREATE METHOD DDL statement completes the UDM

    creation process by compiling the source code and associating the

    executable with the UDT.

    CREATE METHOD UsDollarValue ()

    RETURNS DECIMAL(10,2)

    FOR Euro

    EXTERNAL NAME 'CS!UsDollarValue!UsDollarValue.c!F!To

    UsDollar';

    User-defined Types

    EB-4622 > 1105 > PAGE 11 OF 15

    4 A complete discussion of the CREATE TYPE, METHOD and FUNCTION syntax is beyond the scope of this document.

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    12/15

    User-defined Types

    EB-4622 > 1105 > PAGE 12 OF 15

    User-defined constructor methods are defined and created inexactly the same way as instance methods except that the keyword

    CONSTRUCTOR is used to differentiate it from an instance

    method. Constructor methods always return the associated UDT

    as their return type.

    CREATE TYPE PatientRecord AS (

    Name VARCHAR(50),

    Address Address, -- This is the Address UDT

    Birthdate DATE,

    SSN CHAR(10),

    Xray BLOB AS LOCATOR)NOT FINAL

    CONSTRUCTOR METHOD PatientRecord (

    Name VARCHAR(50),

    Address Address,

    Birthdate DATE,

    SSN CHAR(10))

    RETURNS PatientRecord

    SELF AS RESULT

    LANGUAGE C

    NO SQL

    PARAMETER STYLE TD_GENERAL

    DETERMINISTIC

    RETURNS NULL ON NULL INPUT;

    The previous example defines a constructor (PatientRecord)

    method that can be used to initialize the Name, Address, Birth-

    date, and SSN attributes of the PatientRecord UDT as the record is

    being inserted into a table. The Xray attribute might be updated

    after the PatientRecord is inserted into a table. The CREATE

    CONSTRUCTOR METHOD DDL syntax is identical to the

    CREATE METHOD except that the RETURNS clause always

    specifies the UDT.

    This example can be made more interesting by adding instance

    methods that model some aspects of an actual patient record.

    CREATE TYPE PatientRecord AS (Name VARCHAR(50),

    Address Address,

    Birthdate DATE,

    SSN CHAR(10),

    Xray BLOB(128k))

    NOT FINAL

    CONSTRUCTOR METHOD PatientRecord (

    Name VARCHAR(50),

    Address Address, -- This is the Address UDT

    Birthdate DATE,

    SSN CHAR(10),

    Xray BLOB )

    RETURNS PatientRecord

    SELF AS RESULT

    LANGUAGE C

    NO SQL

    PARAMETER STYLE TD_GENERAL

    DETERMINISTIC

    RETURNS NULL ON NULL INPUT ,

    INSTANCE METHOD Decrypt_SSN (Decrypt_Key VARCHAR(20))

    RETURNS CHAR(10)

    SPECIFIC patient_decrypt_SSN

    LANGUAGE C

    NO SQL

    PARAMETER STYLE TD_GENERAL

    DETERMINISTIC

    RETURNS NULL ON NULL INPUT,

    INSTANCE METHOD Decompress_Xray()

    RETURNS BLOB(256k)

    SPECIFIC patient_decompress_xray

    LANGUAGE C

    NO SQL

    PARAMETER STYLE TD_GENERAL

    DETERMINISTIC

    RETURNS NULL ON NULL INPUT;

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    13/15

    In addition to initializing some of the patient data, the Patien-tRecord constructor method is used to automatically encrypt the

    social security number (with a private encryption key) when the

    record is inserted into the table. The patients social security

    number is now only viewable by authorized personnel that use the

    Decrypt_SSN() method and a public encryption key passed as an

    argument.

    An unauthorized user that does not have the public key might try

    to view the patients SSN by using the observer method. However,

    the user will only be able to view the encrypted data. Another

    feature of this UDT is that a compressed Xray is decompressed

    and returned to the user by the Decompress_Xray() method. This

    Xray could have been compressed outside of the Teradata Data-

    base, by a UDF or by another method associated with this type.

    Teradata provides a library of C functions that are used to pro-

    grammatically interface with the UDT and are callable from

    UDMs, UDFs, and external stored procedures. The primary

    function of this interface is to facilitate the movement of data

    between user written programs5 and UDT attributes. This library

    completes the UDT feature and provides a powerful set of tools

    that allows the type developer to design and implement UDTs that

    can model complex real-world objects.

    UDT Security and Access Rights

    Just like regular data types, UDTs are globally accessible and

    useable by all database users. Unlike regular data types, the behav-

    ior and structure of UDTs can be changed. While this capability

    provides power and flexibility, it could also have adverse or

    unwanted consequences for any database object or application that

    references this type. Because of this possibility, Teradata supports a

    scaled set of three access levels that allow the DBA to strictly

    control how database users can modify and use UDTs.

    These privileges are not automatic; they must be explicitly grantedor acquired through a role. An individual user can have privileges

    granted or revoked on all UDTs within the Teradata Database or

    on a particular UDT. Please note that even if a user has the highest

    level of access, most operations that alter the structure and behav-

    ior of the UDT are not allowed if the UDT is a column in a table

    or is referenced by another object anywhere within the Teradata

    Database.

    UDTUSAGE

    The UDTUSAGEprivilege allows a user to use a UDT and to

    execute all methods associated with that UDT. However, the user is

    prohibited from creating or deleting UDTs as well as creating,

    altering, or deleting methods.

    UDTTYPE

    The UDTTYPEprivilege includes all of the privileges associated

    with UDTUSAGE. In addition, it allows a user to change the

    structure of a type but does not allow that user to add a new

    method or change existing methods. This privilege allows the user

    to create, alter, and drop types as well as create or drop an order-

    ing, transform, or a cast. The distinction here is that the user

    cannot change the method interface of the UDT.

    UDTMETHOD

    The UDTMETHOD privilege grants the highest level of UDT

    access and includes those privileges granted by UDTUSAGE and

    UDTTYPE. A user with this access level can add new methods or

    modify existing methods. This level of access control is important

    because UDMs share the same execution model as UDFs and

    execute in a Teradata supervisor mode. A misbehaved UDM or a

    malicious programmer could compromise the stability and

    integrity of the Teradata Database so this access level should only

    be granted to trusted developers who write well tested code.

    User-defined Types

    EB-4622 > 1105 > PAGE 13 OF 15

    5 Only available to programs that execute within the Teradata Database.

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    14/15

    Execution ModesAs mentioned previously, user-defined instance and constructor

    methods share the same execution model as User-defined Func-

    tions. The Teradata Database currently provides two modes of UDF

    execution: Protected and NOT Protected. Authorized users are

    allowed to alter the method or function to execute in either of these

    modes.

    Protected Mode

    Protected mode is the default execution mode for a UDM or UDF

    and is set during the creation process. In protected mode, the

    method or function runs in a process that is separate from the

    Teradata server. Although this mode has a slight impact on

    performance, memory violations or other system errors are

    isolated within the process and the transaction is aborted along

    with an appropriate error message.

    Unprotected Mode

    Methods and functions can be altered to run in an unprotected

    mode via theALTER METHOD orALTER FUNCTION DDL

    statements. In this mode the executable code is called directly by

    the Teradata Database rather than run in a separate process. While

    maximizing performance, a direct method or function call doesnot provide an environment that is as safe as protected mode.

    Once a user written method or function has been thoroughly

    tested however, it is recommended that it be altered to run in

    unprotected mode to maximize its performance.

    In general, all user written code should be thoroughly tested and

    its safety well established if it will be running in protected or

    unprotected mode. If the function or method fails and causes a

    runtime exception, it may cause the Teradata Database to restart.

    Build Real-world Objects with UDTsUDTs support the construction of nonstandard data types and

    allow the application of object-oriented design principles while

    leveraging the advanced relational capabilities of Teradata. These

    complex data types can then be used to model objects and

    processes commonly found in areas such as business, science,academics, and entertainment. Objects represented by UDTs can

    then participate in relational queries and can be used just like

    other data types. Some of the potential uses of this feature as

    examples of what is possible with UDTs are listed.

    Data Encryption and Intellectual Property

    UDTs can be used to encapsulate and manage sensitive data or

    intellectual property. Referring back to the patient record example,

    a UDT can be self-encrypting by using the To-SQL transform and

    constructor methods to encrypt plain text or binary data as the

    data are imported or inserted into the column.

    A private encryption key could be embedded within the program

    code or passed as an argument to the constructor method. An

    authorized user would then decrypt the data with a public key

    passed as an argument to a UDM. Unauthorized users would not

    be able to decrypt the data without a public key. Users could also

    be given limited access by supplying a method that returns only a

    sanitized version of the data.

    Inventory Tracking

    Rather than using several table columns to track a single item, a

    single column based on a generic inventory object can be created.This UDT would represent an inventory item and could be updated

    via point-of-sales devices or SQL queries. The data attributes

    might include: Name, stock number, UPC code, price, quantity

    on hand, and quantity on order.

    Multimedia Applications

    A UDT could represent a multimedia object such as a movie clip.

    This could be accomplished with a distinct or structured UDT.

    The movie clip could be based on a BLOB type and would contain

    an MPEG video file. Methods could be written to analyze the

    movie and return various data points. Another method couldreturn particular frames. Columns based on this UDT could

    participate in queries and be relationally compared based on a

    value returned by the ordering. Finally, the entire video could be

    returned via the From-SQL transform or a method.

    User-defined Types

    EB-4622 > 1105 > PAGE 14 OF 15

    http://www.teradata.com/
  • 7/30/2019 User Defined Types

    15/15

    Corporate SecurityA structured UDT could be used to represent an employee file.

    Beyond the usual employee related data, attributes could also

    include a thumbprint image and the employees picture. The

    UDTs instance methods, transform and ordering could return

    relevant information about the employee, thumbprint, and picture

    that can be used for identification and relational comparisons. For

    example, the employee would enter a secure entrance that uses a

    print scanner. The scanned print could then be automatically

    compared to the information in the database. A security guard

    would then be able to identify the employee with a picture or

    other information.

    Real-Time Applications

    Columns based on these UDTs can be updated by external, event-

    driven processes that result in update or trigger actions applied

    to the column value. These table columns can now represent

    real-world objects or entities that are updated in real time. If a

    specialized client is used to query the column based on the active

    data type, real-time data can be superimposed onto an image to

    graphically represent the state of the object. For example, a digital

    image of a weather or geographical map could have values super-

    imposed at the proper coordinates.

    Scientific Applications

    A generic weather station UDT could be used to represent the

    current weather conditions at a specific location. Its attributes

    could include: location, temperature, humidity, wind velocity,

    barometric pressure, and satellite image of location being tracked.

    A table can then be created to represent the conditions at various

    cities by simply creating a column for each city with a data type of

    WeatherStation. These columns can now be compared and ana-

    lyzed in relational queries.

    A geospatial tracking UDT could be used to represent some objectthat is being tracked in real time: for example, a delivery truck.

    The attributes of this structured UDT could be current GPS

    coordinates, License Plate, Truck Number, or Driver Name. This

    UDT could also have a BLOB attribute that would contain a road

    map image that represents some radius around the current GPS

    coordinates. If a column of this data type was updated in real

    time, the delivery truck could be tracked and its current location

    marked on the map.

    The UDT Advantage

    Use UDTs to unlock the potential of the Teradata Database and

    leverage data that already exists in the data warehouse. What

    makes UDTs so powerful is that they can be used to extend the

    SQL language and build object relational applications that are fully

    integrated with the Teradata Database. UDTs add true object

    relational technology to the Teradata Database and offer almost

    unlimited potential to create applications that model real-world

    objects and processes that are more intuitive and easy to use.

    Effective data management and access can lead to a significant

    competitive advantage.

    About the Author

    George Lawandus is a senior developer atNCR and has worked

    with the Teradata Database since he joined Teradata Corporation

    in 1988. He is currently developing testing models and authoring

    Teradata technical publications.

    User-defined Types

    EB-4622 > 1105 > PAGE 15 OF 15

    Teradata and NCR are registered trademarks of NCR Corporation. NCR continually enhances products as new technologies and components become available.

    NCR, therefore, reserves the right to change specifications without prior notice. All features, functions, and operations described herein may not be marketed in

    all parts of the world. Consult your Teradata representative or Teradata.com for more information. No part of this publication may be reprinted or otherwise

    reproduced without permission from Teradata.

    2005 NCR Corporation Dayton, OH U.S.A. Produced in U.S.A. All Rights Reserved.

    Teradata.com

    http://www.teradata.com/http://www.teradata.com/http://www.teradata.com/