Upgrade to Pro — share decks privately, control downloads, hide ads and more …

NOT VALIDな検査制約 / check constraint that is not v...

Yasuo Honda
December 20, 2024

NOT VALIDな検査制約 / check constraint that is not valid

Yasuo Honda

December 20, 2024
Tweet

More Decks by Yasuo Honda

Other Decks in Technology

Transcript

  1. • Yasuo Honda @yahonda ◦ Rails committer ◦ 第46回 PostgreSQLアンカンファレンス

    以来4回目の参加です ▪ PostgreSQL 15とRailsと - Speaker Deck ▪ 遅延可能な一意性制約 - Speaker Deck ▪ pg_stat_statementsで inの数が違うSQLをまとめて ほしい - Speaker Deck 自己紹介
  2. • Ruby on Railsのmigration DSLで検査制約を作る2つの方法 ◦ テーブル作成後に、`add_check_constraint`で作成 ◦ テーブル作成時に`t.check_constraint`で作成 •

    いずれも`:validate` 引数を設定可能(デフォルトはtrue) ◦ falseを渡すと、無効な検査制約として作成される意図(NOT VALID) だった意図通りは`add_check_constraint`のみ ◦ https://api.rubyonrails.org/classes/ActiveRecord/Connecti onAdapters/SchemaStatements.html#method-i-add_chec k_constraint 背景
  3. • add_check_constraint ◦ CREATE TABLE "posts" ("id" bigserial primary key,

    "title" character varying); ◦ ALTER TABLE "posts" ADD CONSTRAINT posts_const CHECK (char_length(title) >= 5) NOT VALID; • check_constraint ◦ CREATE TABLE "comments" ("id" bigserial primary key, "body" text, CONSTRAINT comments_const CHECK (char_length(body) >= 5) NOT VALID); 発行されていた SQL https://gist.github.com/yahonda/7e61f3f71 681cfa03111fed55714b0b4
  4. • 検査制約のNOT VALIDをalter tableのみで追加できるのは意図した振 る舞いのよう(フォント赤字は筆者) • https://www.postgresql.org/docs/current/sql-altertable.html ◦ > This

    form adds a new constraint to a table using the same constraint syntax as CREATE TABLE, plus the option NOT VALID, which is currently only allowed for foreign key and CHECK constraints. • https://www.postgresql.org/docs/9.2/release-9-2.html で追加 解釈
  5. • PostgreSQL 18 devel(資料作成時のmasterブランチ) ◦ https://github.com/postgres/postgres/commit/39240bcad 56dc51a7896d04a1e066efcf988b58f • Rails main

    ◦ https://github.com/rails/rails/commit/3a91006d22fa465fb ce41370bbe66aa332bdcc2d • Red Hat Enterprise Linux release 9.5 (Plow) 環境
  6. • https://github.com/rails/rails/pull/40192 • https://github.com/rails/rails/issues/53732 • https://github.com/rails/rails/pull/53735 • https://www.postgresql.org/docs/current/catalog-pg-constrai nt.html •

    https://www.postgresql.org/message-id/E1QcJd3-0001HT-91% 40gemulon.postgresql.org • https://github.com/postgres/postgres/commit/897795240cfaa ed724af2f53ed2c50c9862f951f • 参照