views:

51

answers:

3

I want to disallow the use of spaces in some text/varchar fields.

Even more, it would be best to have only a set of characters that are allowed to use there, like:

[a-zA-Z0-9_\-]

And I want to make it as a rule to all VARCHAR fields that are members of primary key in their tables.

This should be done on the database level and could throw an exception when trying to insert a wrong record or update one with a change of a key field to invalid value.

Can this be done within the database level? Should I use Pl/Perl for that, or is there any simpler method?

+3  A: 

You can define a domain, look at http://www.postgresql.org/docs/current/interactive/sql-createdomain.html at the bottom, there is an example about US postal code.

This looks promising, but it requires altering all my existing data, which is quite a lot of tables. I was thinking more of a way to inject into my existing database, that's why I thought of a trigger and function first.
kender
this does NOT require altering all your data, only schema.DOMAINs are designed precisely for this.`ALTER TABLE foo ALTER bar TYPE my_domain;`
filiprem
+1  A: 

Seeing your latest comment you could perhaps use CHECK constraints and regex search? But you will have to modify the schema (tables) and insert it for each field.

Christian Vik
+4  A: 

You don't even need stored procedures:

alter table xxx add constraint check_valid_chars check ( your_column ~ '^[a-zA-Z0-9_\-]+$' );

should work.

depesz
Ok. Any way to automate this for N tables, each with 1+ fields to be altered? like: for each table { for each field in table that is a key { alter } }
kender
requires scripting but the key to your task is in the `information_schema.`
Evan Carroll
Check my blogpost on "grantall" : http://www.depesz.com/index.php/2007/10/19/grantall/ - the technique I used there can be applied in this case as well.
depesz