sql >> Databasteknik >  >> RDS >> PostgreSQL

Postgres textkolumn som endast tillåter/konverterar till gemener och inga specialtecken som:Ñöáè

Sätt de önskade tecknen i den andra parametern i denna translate() ring:

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

Alternativt kan du skapa en trigger, som ändrar värdet i farten:

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.


  1. Tabellen är "skrivskyddad"

  2. Timeout för Oracle-anslutning/fråga

  3. Möjliga PDOException-fel (MySQL 5)?

  4. Snabbstart databasmigrering med Talend