1

I would like to ALTER my existing table by adding CONSTRAINT to specific column to respect some regex.

I try to normalize phone prefix number by executing:

ALTER TABLE users
    ADD CONSTRAINT users_prefix_constraint 
        CHECK (users.phone_prefix ~ '^\+\d{1,3}$');

And it's working correctly.

But I would like to use it more generic and define DOMAIN which holds regex pattern, to use the same pattern in different places (i.e. in triggers). That's why I imagine to do something like:

CREATE DOMAIN ph_prefix AS TEXT CHECK (VALUE ~'^\+\d{1,3}$');

ADD CONSTRAINT users_prefix_constraint CHECK (users.phone_prefix :: ph_prefix);

Problem here is, that CHECK part expects some function returning boolean, and casting doesn't.

  1. Is there a way to do it?
  2. Is that a good way to define constraint? Maybe it's not preferred way.

2 Answers 2

2

I think you are missing the point of domains.

You would not add a domain as a constraint, but you would use it as the data type for a column:

ALTER TABLE users ALTER phone_prefix TYPE ph_prefix;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I missed the clearest solution.
2

If you have a reason to define a domain but not use it as a data type of users.phone_prefix column then create this simple function

create or replace function ph_prefix_valid(s text) returns boolean as
$$
begin
 perform s::ph_prefix;
 return true;
exception when others then
 return false;
end;
$$ language plpgsql;

and then

ADD CONSTRAINT users_prefix_constraint CHECK (ph_prefix_valid(users.phone_prefix));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.