2021年4月6日星期二

Using regex in PSQL Case Statement

Working on a rails app with postgresql.

I am trying to implement a pg constraint using a case statement.

          ALTER TABLE geolocation_postcodes          ADD CONSTRAINT canadian_format CHECK (            CASE WHEN country_code = 'CA' AND code !~ '\A^[A-Z]\d[A-Z]\s\d[A-Z]\d\Z' THEN FALSE            END            );  

When trying to insert an instance (which should pass) it is stopped by the constraint every time:

Input:

Geolocation::Postcode.insert(code: "G6V 4C9", country_code: "CA", created_at: Time.now, updated_at: Time.now)  

Result:

ActiveRecord::StatementInvalid: PG::CheckViolation: ERROR:  new row for relation "geolocation_postcodes" violates check constraint "canadian_format" DETAIL:  Failing row contains (46, G6V 4C9, t, 2021-04-07 01:37:34.005891, 2021-04-07 01:37:34.005896, CA).  
https://stackoverflow.com/questions/66978648/using-regex-in-psql-case-statement April 07, 2021 at 10:06AM

没有评论:

发表评论