is it possible to add a custom constraint in PostgreSQL

All we need is an easy explanation of the problem, so here it is.

Now I have a table store some rss subscribe url, sometimes the url end with ‘/’, now I replace all url without end with ‘/’. to make sure the sub url did not end with ‘/’. I want to add a custom constraint in the rss sub source table. If the sub url end with ‘/’, throw error to the app. I have read the PostgreSQL 13 docs, and found it have many constraint like uniq constraint check constraint with the int data type. but how to add an constraint with a string data type and make sure the string did not end with ‘/’? is there any way to do this action?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

ALTER TABLE t ADD CONSTRAINT c
    CHECK ( url NOT LIKE '%/');

As suggested by Vérace in comment, an alternative would be a generated column as:

ALTER TABLE T ADD COLUMN proper_url TEXT 
    GENERATED ALWAYS AS ( regexp_replace(url, '/$', '')) STORED;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply