Saturday, 14 September 2013

Create a rule to automatically convert a column to lowercase or uppercase on insert

Create a rule to automatically convert a column to lowercase or uppercase
on insert

Using postgres, how would you create a rule to force lowercase or
uppercase on a given column when a new record is inserted. For example, so
that an insert like this:
INSERT INTO foobar (foo, bar) VALUES ('EXAMPLE', 2)
Gets converted to by a rule prior to inserting:
INSERT INTO foobar (foo, bar) VALUES ('example', 2)
This is what I came up with after looking at the documentation but was not
able to get it to work:
CREATE RULE "foo_to_lower" AS ON INSERT TO foobar
DO INSTEAD
INSERT INTO foobar VALUES (
lower(NEW.foo)
)
WHERE (ascii(foo) BETWEEN 65 AND 90);
Note, in the WHERE statement I'm trying to detect uppercase characters as
ascii characters between 65 and 90 are all uppercase.

No comments:

Post a Comment