| From: | John Havard <enigma(at)sevensages(dot)org> | 
|---|---|
| To: | pgsql-general(at)postgresql(dot)org | 
| Cc: | John Havard <enigma(at)sevensages(dot)org>, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> | 
| Subject: | Re: Using pl/pgsql or sql for in/out functions for types | 
| Date: | 2001-04-13 22:30:12 | 
| Message-ID: | 108660000.987201012@samurai.corp.netdoor.com | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-general | 
--On Friday, April 13, 2001 12:50:12 PM -0400 Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> 
wrote:
> John Havard <enigma(at)sevensages(dot)org> writes:
>> Is there anyway to do this without having to resort to writing the
>> functions in C or some other language?
>
> You really cannot write datatype I/O functions in anything but C,
> because the I/O functions have to deal in C-style strings, which are
> not a SQL datatype; so there is no way to describe the necessary
> behavior in any PL language.
>
After thinking for less than a minute, I realized I can use views and rules 
to do this.  Much easier than doing it in C, especially seeing as how all 
I'm doing is just formatting another type.
First, create a table:
CREATE TABLE foo (asdf int, bb numeric(9));
Then, create the necessary funtions:
CREATE FUNCTION ssn_in (char) RETURNS numeric(9) AS '
   SELECT to_number($1, \'000 00 0000\')
  ' LANGUAGE 'sql';
CREATE FUNCTION ssn_out(numeric(9,0)) RETURNS char AS '
   SELECT to_char($1, \'000-00-0000\')::char
  ' LANGUAGE 'sql';
Next we need a view:
CREATE VIEW blah AS select asdf, ssn_out(bb) from foo;
After that, create a rule
CREATE RULE blah_insert as on INSERT TO blah DO INSTEAD insert into foo 
values (NEW.asdf, ssn_in(NEW.bb));
Then, just do inserts and selects as normal.  Well, there is a problem. 
When I  query by the ssn field (bb) on the view, but get nothing returned. 
Any ideas?  EXPLAIN says it simply does a sequential scan on foo.
Also, on a different note, is there any particular reason why tab 
completion for views doesn't work in psql?  It sure would make me a happier 
person, especially with having wasted 1.5 hours of my life, and a few bucks 
on some pepperoni pizza croiscant pockets that burned last night because 
3com moved  and hid things on their web site (thanks 3com!).
Regards,
John Havard
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Jeff Eckermann | 2001-04-13 23:27:49 | Backend sent D message without prior T | 
| Previous Message | Jason Larke | 2001-04-13 22:26:33 | Timestamps for BLOB fields |