Anda di halaman 1dari 15

Data Warehousing > Database

User-dened Types
Modeling the Real World with UDTs

By George Lawandus July 19, 2005

User-dened Types
Table of Contents
Executive Overview The Benefits of User-defined Types UDTs Defined Components of a UDT Two Flavors of UDTs Distinct Type Structured Type Creating User-defined Methods UDT Security and Access Rights Execution Modes Build Real-World Objects with UDTs The UDT Advantage About the Author 2 3 3 4 6 6 7 10 13 14 14 15 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 les, 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 common 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 Userdefined Types (UDTs).

EB-4622

>

1105

>

PAGE 2 OF 15

User-dened Types
The Benets of User-defined Types
User-defined Types enable Teradata Database users to develop objects that can model business processes and entities that typically 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 specic benets include: Extensibility UDTs make it possible to dene custom data types and extend the existing types supported by the Teradata Database. These new data types can have user-dened names that intuitively represent their function and use. UDTs are globally accessible and can be specied anywhere a Teradata predened (built-in) type is used. Data previously stored in multiple table columns can now be represented by a single data type. Developers can leverage data already stored in a Teradata Warehouse by using UDTs to dene 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-dened 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. UDTs can be used in essentially the same way as Teradata predened types. They can appear as column types, arguments to User-defined Functions, in stored procedures, macros or triggers. Security Security of data and other intellectual property is enhanced through the use of User-defined Types. Access to the data encapsulated 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 Userdefined Types. UDTs are true objects with an external interface implemented with a collection of user and system dened methods. A UDM can be written in either the C or C++ languages.

UDTs Dened
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 specic capabilities that are not offered by conventional data types. A Teradata UDT can have one or more data attributes which can be based on a predened type or another UDT. The number of attributes is dependant on whether the UDT exists as a Distinct or Structured type. The differences between these two types of UDTs will be discussed after the components are explained.

EB-4622

>

1105

>

PAGE 3 OF 15

User-dened Types
A UDT is strongly typed. This means that, by default, a UDT is considered separate and distinct from Teradata predened types as well as other UDTs. At rst 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 developers do have the capability to make their types compatible with other types by dening CAST routines. The To-SQL routine is used to transform an external or Teradata predened 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 dened as type

The From-SQL routine is responsible for transforming the UDT into a Teradata predened type and is implicitly invoked for export operations and queries that reference a column dened 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 EuroColumn 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 TableName;.

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 predened and userdened) 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 predened 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 methods called a transform group. These functions are usually referred to as To-SQL and From-SQL to indicate the direction of data ow to and from the database. A transform group is required if the type is to be used in a table.

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 developer complete control over what Teradata predened 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 dened 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.

EB-4622

>

1105

>

PAGE 4 OF 15

User-dened Types
Ordering An ordering species how UDTs are relationally compared with each other or how the UDT appears within the result set of a query that species 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. In the rst example, the user-defined cast is implicitly called to Relational comparisons such as: SELECT Video1 from SurveillanceCamera WHERE Video1 > Video2; will implicitly invoke

enable implicit or explicit conversions to other data types that are natural 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 implementations are user-dened. If such a conversion were required, a developer could create cast routines to allow this to happen. If the appropriate casts are dened, statements such as the following are now possible:
UPDATE Sales SET Euro_Column = UsDollar_Column; UPDATE Sales SET Euro_Column = CAST(UsDollar_Column AS Euro); INSERT into Sales VALUES(1,10.50);

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 created and 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 dene 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 realworld counterpart. The basic denition 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 predened methods when a UDT is created and also supports a mechanism for allowing

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 denition, a UDT is considered distinct and separate from all other 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. Teradata does not require that a cast exist for a UDT to be used in a table. However, dening casts for a UDT is desirable because they can

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

EB-4622

>

1105

>

PAGE 5 OF 15

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

structured UDT during its construction or instantiation. This allows 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.

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;

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 avors of UDTs: Distinct and Structured. The differences between these two are important and determine how the UDTs are developed and used. Distinct Type A distinct UDT shares its internal implementation with a single Teradata predened 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 dened for it cannot be directly applied to other UDTs or predened 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 DECIMAL(10,2) FINAL; creates a distinct UDT (without methods)

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 rst 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 dene a functional interface to a UDT. This provides the type developer with an efcient mechanism to control how the content and functionality of the UDT is exposed to the end user. Instance methods can be dened with zero or more parameters and can return a value which can be a Teradata predened type or a UDT. Like instance methods, constructor methods can be dened with or without parameters but can only return the UDT of the type with which the constructor method is associated. Constructor methods are typically used to initialize the data attributes of a

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 predened type as its source type but cannot specify another UDT for this purpose.

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

EB-4622

>

1105

>

PAGE 6 OF 15

User-dened Types
Characteristics of a Distinct Type Just 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. Characteristics of a Structured Type Similar to distinct types, a structured types data attributes can also be based on Teradata predened types. Whats different is that a structured type attribute can also be declared as a distinct or a structured UDT. This kind of conguration 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 dened 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 represented. As with distinct types, a transform group and an ordering must be dened before the type can be used in a table. Casts are not required but are recommended in order to have a completely functional type. The Teradata implementation for distinct UDTs allows the type developer to drop these system generated components and dene 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 automatically 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.

EB-4622

>

1105

>

PAGE 7 OF 15

User-dened Types
Observer Methods Because instance methods are also not required for structured types, two special methods are provided to allow the data attributes to be queried and updated. These are commonly referred to as observer and mutator methods. When the type is created, a pair of observer and mutator methods is auto-generated for each of the data attributes dened 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;

Assuming that the Address UDT was used in a table, the following queries 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 rst query calls the Street() observer method for the Address UDT. This returns a single column called Street which 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

In addition to the type, one observer and one mutator method is auto-generated for each of the Street, City, State and Zip attributes. 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.

EB-4622

>

1105

>

PAGE 8 OF 15

User-dened Types
The second query uses the new .ALL column qualier syntax to retrieve all of the data attributes of Address as one column per attribute in the same order in which they appear in the CREATE TYPE statement. The default column titles will be identical to the rst example except for the attribute name.
SELECT EmployeeAddress.ALL 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 EmployeeAddress.City() --------------------------Athens Ardmore Kingston Tucson Cincinnati St. Petersburg Waterbury Austin EmployeeAddress.State() ---------------------------GA PA RI AZ OH FL CT TX

The output of this query was truncated for readability.

The third query (output not shown) uses the * operator with the .ALL qualier to retrieve all of the columns in the table and causes the expansion of any UDT column into a list of its attributes. As in the second query, all UDT attributes are retrieved as separate 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 dened 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 rst 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.

EB-4622

>

1105

>

PAGE 9 OF 15

User-dened Types
This query uses a mutator invocation to update the Street and Zip attributes after the UDT is constructed.
UPDATE Personnel SET EmployeeAddress = NEW Address().Street(Sepulveda).Zip(92045) WHERE EmployeeAddress.City() = El Segundo;

user-defined constructor method Address() to initialize the values 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 dened 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 denition 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 dened for distinct types. Only instance methods can be dened. Creating a UDM is similar to creating a User-defined Function in that it involves the creation of C or C++ code to dene 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

At rst 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 attributes and perform other tasks after the UDT is instantiated. The following INSERT statement is one example of how a userdefined constructor method can be used.
INSERT INTO Personnel values (1, NEW Address(17905 Via Del Campo,San Diego,CA,92917));

single step for a UDF. The rst step requires that we rst dene 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) dened for a particular UDT, the Teradata Database uses the number of arguments and their data types to uniquely identify which UDM to call.

In this example, the keyword NEW is used to indicate that a new instance of the Address UDT is to be constructed by rst calling the default constructor Address() and then initiating a call to the

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

EB-4622

>

1105

>

PAGE 10 OF 15

User-dened Types
Referring back to the Euro example, methods that will operate on this type can be dened by rst 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 UDFs and 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 predened type. The UsDollarValue() method returns the U.S. dollar equivalent of the Euro as a DECIMAL(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';

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

EB-4622

>

1105

>

PAGE 11 OF 15

User-dened Types
User-defined constructor methods are dened and created in exactly 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 Address Birthdate SSN Xray VARCHAR(50), Address, -- This is the Address UDT DATE, CHAR(10), BLOB AS LOCATOR) NOT FINAL CONSTRUCTOR METHOD PatientRecord ( Name Address Birthdate SSN VARCHAR(50), Address, DATE, CHAR(10)) CREATE TYPE PatientRecord AS ( Name Address Birthdate SSN Xray VARCHAR(50), Address, DATE, CHAR(10), 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

RETURNS PatientRecord SELF AS RESULT LANGUAGE C NO SQL PARAMETER STYLE TD_GENERAL DETERMINISTIC RETURNS NULL ON NULL INPUT;

The previous example denes a constructor (PatientRecord) method that can be used to initialize the Name, Address, Birthdate, 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 species the UDT. This example can be made more interesting by adding instance methods that model some aspects of an actual patient record.

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;

EB-4622

>

1105

>

PAGE 12 OF 15

User-dened Types
In addition to initializing some of the patient data, the PatientRecord 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 Database, by a UDF or by another method associated with this type. UDTTYPE Teradata provides a library of C functions that are used to programmatically 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 programs and UDT attributes. This library
5

These privileges are not automatic; they must be explicitly granted or 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 behavior 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 UDTUSAGE privilege 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.

The UDTTYPE privilege 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 ordering, transform, or a cast. The distinction here is that the user cannot change the method interface of the UDT. UDTMETHOD

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 behavior and structure of UDTs can be changed. While this capability provides power and exibility, 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.

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.

Only available to programs that execute within the Teradata Database.

EB-4622

>

1105

>

PAGE 13 OF 15

User-dened Types
Execution Modes
As mentioned previously, user-defined instance and constructor methods share the same execution model as User-defined Functions. 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 the ALTER METHOD or ALTER 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 does not 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. 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 le. Methods could be written to analyze the movie and return various data points. Another method could return 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.

Build Real-world Objects with UDTs


UDTs 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

EB-4622

>

1105

>

PAGE 14 OF 15

User-dened Types
Teradata.com
Corporate Security A structured UDT could be used to represent an employee le. 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 identication 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, eventdriven 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 superimposed at the proper coordinates. Scientic Applications A generic weather station UDT could be used to represent the current weather conditions at a specic 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 analyzed in relational queries. A geospatial tracking UDT could be used to represent some object that 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 signicant 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.

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 specications 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.

EB-4622

>

1105

>

PAGE 15 OF 15

Anda mungkin juga menyukai