programing

"삭제 캐스케이드" 제약 조건을 추가하는 방법은 무엇입니까?

itmemos 2023. 6. 26. 21:05
반응형

"삭제 캐스케이드" 제약 조건을 추가하는 방법은 무엇입니까?

포스트그레에서SQL 8을 추가할 수 있습니다.ON DELETE CASCADES다음 표에 있는 두 개의 외래 키 모두에 대해 후자를 삭제하지 않고 입력하시겠습니까?

# \d scores
        Table "public.scores"
 Column  |         Type          | Modifiers
---------+-----------------------+-----------
 id      | character varying(32) |
 gid     | integer               |
 money   | integer               | not null
 quit    | boolean               |
 last_ip | inet                  |
Foreign-key constraints:
   "scores_gid_fkey" FOREIGN KEY (gid) REFERENCES games(gid)
   "scores_id_fkey" FOREIGN KEY (id) REFERENCES users(id)

참조된 두 표는 다음과 같습니다.

# \d games
                                     Table "public.games"
  Column  |            Type             |                        Modifiers
----------+-----------------------------+----------------------------------------------------------
 gid      | integer                     | not null default nextval('games_gid_seq'::regclass)
 rounds   | integer                     | not null
 finished | timestamp without time zone | default now()
Indexes:
    "games_pkey" PRIMARY KEY, btree (gid)
Referenced by:
    TABLE "scores" CONSTRAINT "scores_gid_fkey" FOREIGN KEY (gid) REFERENCES games(gid)

그리고 여기:

# \d users
                Table "public.users"
   Column   |            Type             |   Modifiers
------------+-----------------------------+---------------
 id         | character varying(32)       | not null
 first_name | character varying(64)       |
 last_name  | character varying(64)       |
 female     | boolean                     |
 avatar     | character varying(128)      |
 city       | character varying(64)       |
 login      | timestamp without time zone | default now()
 last_ip    | inet                        |
 logout     | timestamp without time zone |
 vip        | timestamp without time zone |
 mail       | character varying(254)      |
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "cards" CONSTRAINT "cards_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "catch" CONSTRAINT "catch_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "chat" CONSTRAINT "chat_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "game" CONSTRAINT "game_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "hand" CONSTRAINT "hand_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "luck" CONSTRAINT "luck_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "match" CONSTRAINT "match_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "misere" CONSTRAINT "misere_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "money" CONSTRAINT "money_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "pass" CONSTRAINT "pass_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "payment" CONSTRAINT "payment_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "rep" CONSTRAINT "rep_author_fkey" FOREIGN KEY (author) REFERENCES users(id)
    TABLE "rep" CONSTRAINT "rep_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "scores" CONSTRAINT "scores_id_fkey" FOREIGN KEY (id) REFERENCES users(id)
    TABLE "status" CONSTRAINT "status_id_fkey" FOREIGN KEY (id) REFERENCES users(id)

그리고 이전 표에 인덱스 2개를 추가하는 것이 말이 되는지 궁금합니다.

업데이트: 감사합니다. 또한 메일링 목록에서 한 문장으로 관리할 수 있으므로 거래를 명시적으로 시작하지 않아도 된다는 조언을 받았습니다.

ALTER TABLE public.scores
DROP CONSTRAINT scores_gid_fkey,
ADD CONSTRAINT scores_gid_fkey
   FOREIGN KEY (gid)
   REFERENCES games(gid)
   ON DELETE CASCADE;

당신이 단순히 추가할 수 없다고 확신합니다.on delete cascade기존 외부 키 제약 조건으로.먼저 제약 조건을 삭제한 다음 올바른 버전을 추가해야 합니다.표준 SQL에서, 나는 이것을 하는 가장 쉬운 방법이

  • 거래를 시작합니다.
  • 외부 키를 놓습니다.
  • 외부 키 추가on delete cascade그리고 마지막으로
  • 거래를 저지르다

변경할 각 외래 키에 대해 이 과정을 반복합니다.

그러나 PostgreSQL에는 단일 SQL 문에 여러 제약 조건 절을 사용할 수 있는 비표준 확장자가 있습니다.예를들면

alter table public.scores
drop constraint scores_gid_fkey,
add constraint scores_gid_fkey
   foreign key (gid)
   references games(gid)
   on delete cascade;

삭제할 외부 키 제약 조건의 이름을 모를 경우 pgAdmin에서 검색할 수 있습니다.III(테이블 이름을 클릭하여 DDL을 보거나 "제약"이 표시될 때까지 계층을 확장) 또는 정보 스키마를 쿼리할있습니다.

select *
from information_schema.key_column_usage
where position_in_unique_constraint is not null

@Mike Sherrill Cat Recall의 답변을 바탕으로 저에게 효과가 있었던 것은 다음과 같습니다.

ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
  FOREIGN KEY ("parentId")
  REFERENCES "Parent"(id)
  ON DELETE CASCADE;

용도:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

기능:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

주의: 이 함수는 초기 외래 키의 속성을 복사하지 않습니다.외부 테이블 이름/열 이름만 사용하고 현재 키를 삭제한 후 새 키로 대체합니다.

다중 열 제약 조건에 대한 솔루션:

SELECT
    'ALTER TABLE myschema.' || cl.relname ||
    ' DROP CONSTRAINT ' || con.conname || ',' ||
    ' ADD CONSTRAINT ' || con.conname || ' ' || pg_get_constraintdef(con.oid) || ' ON DELETE CASCADE;'
FROM pg_constraint con, pg_class cl 
WHERE con.contype = 'f' AND con.connamespace = 'myschema'::regnamespace::oid AND con.conrelid = cl.oid

언급URL : https://stackoverflow.com/questions/10356484/how-to-add-on-delete-cascade-constraints

반응형