PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Colonna di testo Postgres che consente/converte solo in minuscolo e nessun carattere speciale come:Ñöáè

Inserisci i caratteri desiderati nel secondo parametro di questo translate() chiama:

CREATE TABLE lawyer (
  id SERIAL PRIMARY KEY,
  name VARCHAR NOT NULL,
  url_name VARCHAR check(translate(url_name, 'abcdefghijklmnopqrstuvwxyz', '') = '') NOT NULL,
  gender VARCHAR(1) check (gender in ('m','f')) NOT NULL
);

insert into lawyer
values (default, 'Adam Smith', 'domain', 'f');

INSERT 0 1

insert into lawyer
values (default, 'Adam Smith', 'dömain', 'f');

ERROR:  new row for relation "lawyer" violates check constraint "lawyer_url_name_check"
DETAIL:  Failing row contains (3, Adam Smith, dömain, f).

In alternativa puoi creare un trigger, che modifica al volo il valore:

create or replace function lawyer_before_insert_or_update()
returns trigger language plpgsql as $$
begin
    new.url_name := lower(new.url_name);
    if translate(new.url_name, 'abcdefghijklmnopqrstuvwxyz', '') <> '' then
        raise exception 'Incorrect url name.';
    end if;
    return new;
end $$;

create trigger lawyer_before_insert_or_update
before insert or update on lawyer
for each row execute procedure lawyer_before_insert_or_update();

insert into lawyer
values (default, 'Adam Smith', 'DOMAIN', 'f')
returning *;

 id |    name    | url_name | gender 
----+------------+----------+--------
  4 | Adam Smith | domain   | f
(1 row)

INSERT 0 1

insert into lawyer
values (default, 'Adam Smith', 'dömain', 'f');

ERROR:  Incorrect url name.