1
0

More than 1 year has passed since last update.

PostgreSQL チート・カラムにユニーク制約をつける

Last updated at Posted at 2022-08-19

やりたいこと

ユーザプロフィールテーブルのユーザ名はユニーク制約をつけて同一のユーザ名の登録を受け付けないようにしたい

tl;dr

PostgreSQL のカラムにユニーク制約をつける

ALTER TABLE "(テーブル名)" add constraint "(制約名)" unique "(カラム名)";

実際にやってみる

ユーザプロフィールテーブルのスキーマ

Supabase の SQL Editor で以下を投入

select column_name, ordinal_position, data_type from information_schema.columns where table_schema = 'public' and table_name = 'profiles' order by ordinal_position;

以下が返される

column_name ordinal_position data_type
id 1 uuid
created_at 2 timestamp with time zone
updated_at 3 timestamp with time zone
username 4 text
avatar_url 5 text
plan 6 text
contact_madd 7 text
year_of_birth 8 text
zip 9 text
job 10 text
facebook 11 text
twitter 12 text
homepage 13 text
blog 14 text
gender 15 text
score 16 numeric

ユニーク制約をつける

Supabase の SQL Editor で以下を投入

ALTER TABLE "profiles" add constraint "profiles_username_constraint" unique ("username");

動作確認

Supabase の SQL Editor で以下を投入

select id, username from profiles;

以下が返される

id username
d35b807f-ab47-4173-a50c-cd16032bbdca yuta
df971572-8be0-42e2-8246-52b6ab65383f
0b0393b1-cdb5-47de-a0ca-b2b15d0751b2 mike
1a679275-2447-4a02-9230-b95e850a22c9 sirokuro公式

Supabase の SQL Editor で以下を投入

update profiles set username = 'mike' where id = 'df971572-8be0-42e2-8246-52b6ab65383f';

以下が返される

Failed to run sql query: duplicate key value violates unique constraint "profiles_username_constraint"

「duplicate key value violates unique constraint "profiles_username_constraint"」を含む文字列が返却された場合は「指定のユーザ名は既に登録されています」といったメッセージをユーザに通知できればよさそうだ。

念のために初めの select を再度実行

select id, username from profiles;

問題なさそう

id username
d35b807f-ab47-4173-a50c-cd16032bbdca yuta
df971572-8be0-42e2-8246-52b6ab65383f
0b0393b1-cdb5-47de-a0ca-b2b15d0751b2 mike
1a679275-2447-4a02-9230-b95e850a22c9 sirokuro公式
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0