PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Postgres-Textspalte, die nur Kleinbuchstaben erlaubt/konvertiert und keine Sonderzeichen wie:Ñöáè

Setzen Sie die gewünschten Zeichen in den zweiten Parameter dieses translate() Aufruf:

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).

Alternativ können Sie einen Trigger erstellen, der den Wert spontan ändert:

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.