Using PL/Perl for datatype abstraction

As stated already in this chapter, functions in PostgreSQL are pretty universal and can be used in many different contexts. If you want to use functions to improve data quality, you can use a CREATE DOMAIN clause:

test=# h CREATE DOMAIN
Command: CREATE DOMAIN
Description: define a new domain
Syntax:
CREATE DOMAIN name [ AS ] data_type
[ COLLATE collation ]
[ DEFAULT expression ]
[ constraint [ ... ] ]

where constraint is:

[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | CHECK (expression) }

In this example, the PL/Perl function will be used to create a domain called email, which in turn can be used as a data type.

The following listing shows how the domain can be created:

test=# CREATE DOMAIN email AS text 
       CHECK (verify_email(VALUE) = true);  
CREATE DOMAIN 

As mentioned previously, the domain functions just like a normal data type:

test=# CREATE TABLE t_email (id serial, data  email);  
CREATE TABLE 

The Perl function ensures that nothing violating our checks can be inserted into the database, as the following example demonstrates successfully:

test=# INSERT INTO t_email (data) 
       VALUES ('[email protected]'); 
INSERT 0 1 
test=# INSERT INTO  t_email (data) 
       VALUES ('somewhere_wrong_example.com');  
ERROR:  value  for domain email  violates check     constraint "email_check" 

Perl might be a good option to do string crunching but, as always, you have to decide whether you want this code in the database directly or not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset