guest@websec: ~/websec/r03-migrations/th — zsh — 100×40 เขียนโดย SaKKo YouTube ENTH

guest@websec ~ % man r03-migrations

Migration

migration คือไฟล์ Ruby เล็กๆ ที่เปลี่ยน schema ของฐานข้อมูลไปข้างหน้าหนึ่งขั้น และรู้วิธีถอยกลับ บทนี้ทั้งบทว่าด้วยการทำสิ่งนี้อย่างปลอดภัย

สร้าง migration แก้ไข รัน bin/rails db:migrate แล้ว commit ทั้งไฟล์ migration และ db/schema.rb ที่อัปเดตแล้ว เมื่อ migration ถูก merge ไปแล้ว ห้ามแก้ ให้เขียนไฟล์ใหม่

migration อยู่ที่ไหน

db/
├── migrate/
│   ├── 20261101090000_create_client_applications.rb
│   ├── 20261101090100_create_roles.rb
│   ├── 20261102100000_add_webhook_url_to_client_applications.rb
│   └── 20261103110000_add_active_name_index_to_roles.rb
├── schema.rb        # generated snapshot of the whole database; committed
└── seeds.rb         # sample data for bin/rails db:seed
ชื่อไฟล์YYYYMMDDHHMMSS_what_it_does.rb timestamp UTC 14 หลักคือเวอร์ชันของ migration ซึ่ง generator เขียนให้
ชื่อ classCamelCase ของชื่อไฟล์ส่วนที่เหลือ: add_webhook_url_to_client_applications.rb → AddWebhookUrlToClientApplications ถ้าไม่ตรงกันจะโหลดไม่ได้
Migration[8.1]เวอร์ชัน Rails ที่ใช้ตอนเขียน migration ทำให้ migration เก่ายังทำงานแบบเดิมหลังอัปเกรด
schema_migrationsตารางในแต่ละฐานข้อมูลที่มีหนึ่งแถวต่อเวอร์ชันที่รันแล้ว ตารางนี้ ไม่ใช่ไฟล์ เป็นตัวตัดสินว่าอะไร “up”
db/schema.rbถูกเขียนใหม่หลัง migrate/rollback ทุกครั้ง ฐานข้อมูลใหม่ถูกสร้างจากไฟล์นี้ (db:prepare, db:schema:load) ไม่ใช่การรัน migration ทุกไฟล์ซ้ำ

migrate และ rollback: ทีละขั้นหรือตามเวอร์ชัน

คำสั่งอะไรทำงาน
bin/rails db:migrateทุก migration ที่ค้าง เรียงจากเก่าไปใหม่
bin/rails db:rollbackdown ของ migration ล่าสุดที่ up อยู่
bin/rails db:rollback STEP=3down ของสามไฟล์ล่าสุด เริ่มจากไฟล์ใหม่สุด
bin/rails db:migrate:redo STEP=2rollback สองไฟล์ แล้ว migrate ใหม่
bin/rails db:migrate VERSION=20261102100000ย้าย schema ไปที่เวอร์ชันนั้น: up ไฟล์ที่ค้างจนถึงเวอร์ชันนั้น และ down ไฟล์ที่ใหม่กว่า
bin/rails db:migrate:up VERSION=…up เฉพาะไฟล์นั้นไฟล์เดียว
bin/rails db:migrate:down VERSION=…down เฉพาะไฟล์นั้น แม้ไฟล์ที่ใหม่กว่าจะ up อยู่
bin/rails db:migrate:redo VERSION=…down แล้ว up เฉพาะไฟล์นั้น
bin/rails db:migrate:statusสถานะ up/down ของทุกไฟล์
bin/rails RAILS_ENV=test db:migrateเหมือนกัน แต่ทำกับฐานข้อมูลของ environment อื่น
sim: migrate และ rollbackลอง STEP และ VERSION แล้วลองทำผิดลำดับ

ลองทำ: db:migrate แล้ว db:rollback STEP=2 (สองไฟล์ล่าสุดจะ down เริ่มจากไฟล์ใหม่สุด) จากนั้น db:migrate VERSION= ไฟล์ที่สาม (มีแค่ไฟล์นั้นที่กลับมา up) แล้วลอง db:migrate:down VERSION= create_client_applications ขณะที่ roles ยัง up อยู่: Postgres จะปฏิเสธ เพราะมี foreign key ที่ขึ้นกับตารางนี้ ลำดับจึงสำคัญ

สร้างตาราง

class CreateRoles < ActiveRecord::Migration[8.1]
  def change
    create_table :roles, id: :uuid do |t|           # uuidv7() default from our initializer
      t.references :client_application, null: false, foreign_key: true, type: :uuid
      t.text :name, null: false
      t.text :description, default: ""
      t.text :permissions, array: true, default: [], null: false
      t.text :status, default: "active"
      t.datetime :deleted_at                         # required by SoftDeletable

      t.timestamps                                   # created_at, updated_at
    end
    add_index :roles, :status
    add_index :roles, :deleted_at
  end
end
ทุกตารางต้องมี: id: :uuid, deleted_at พร้อม index และ timestamps คอลัมน์ที่จำเป็นใส่ null: false ส่วน boolean, array และคอลัมน์ status ใส่ default ฐานข้อมูลควรปฏิเสธข้อมูลผิดได้เอง แม้ validation ของ model จะถูกข้าม

แก้ไขตาราง

class AddWebhookUrlToClientApplications < ActiveRecord::Migration[8.1]
  def change
    add_column :client_applications, :webhook_url, :text, default: ""
  end
end

Rails ย้อนกลับคำสั่งส่วนใหญ่ใน change ได้เอง เช่น create_table, add_column, add_index, add_reference, rename_column, add_foreign_key แต่บางคำสั่งต้องช่วยบอก:

# remove_column: give the type so rollback can re-create it
remove_column :users, :legacy_code, :text

# change_column_default: give from/to
change_column_default :roles, :status, from: nil, to: "active"

# anything else: write up and down
def up
  change_column :users, :email, :citext
end

def down
  change_column :users, :email, :text
end

unique index หลายคอลัมน์

user หนึ่งคนถือ role หนึ่งได้ครั้งเดียว ไม่มีคอลัมน์ไหน unique ด้วยตัวเอง (user มีหลาย role และ role มีหลาย user) แต่คู่ของมัน unique ให้ใส่ทั้งสองคอลัมน์ไว้ใน unique index เดียว:

class CreateUserRoles < ActiveRecord::Migration[8.1]
  def change
    create_table :user_roles, id: :uuid do |t|
      t.references :user, null: false, foreign_key: true, type: :uuid   # index on user_id
      t.references :role, null: false, foreign_key: true, type: :uuid   # index on role_id
      t.text :status, default: "active"
      t.datetime :deleted_at
      t.timestamps
    end

    add_index :user_roles, [:user_id, :role_id],          # order matters (see below)
              unique: true,
              where: "deleted_at IS NULL",                 # only live rows must be unique
              name: "index_user_roles_on_user_id_role_id_where_active"
  end
end

# also valid, inside create_table:
#   t.index [:user_id, :role_id], unique: true
ทดลอง: ตาราง user_rolesเลือก index แล้ว insert, soft delete และ restore

ลองดู: insert alice + hr_viewer สองครั้งตอนไม่มี index (แถวซ้ำเข้าไปได้) แล้วเปลี่ยนเป็น unique index: Postgres จะไม่ยอมสร้าง index ขณะที่มีแถวซ้ำ ลอง soft delete หนึ่งแถว แล้วเทียบ index ธรรมดากับ partial index: แบบธรรมดายังนับแถวที่ถูกลบ ส่วนแบบ partial ให้ alice ได้ role นั้นอีกครั้ง และขวางการ restore ที่จะทำให้มีแถวที่ยังใช้งานซ้ำกันสองแถว

ลำดับคอลัมน์

index หลายคอลัมน์เรียงตามคอลัมน์แรกก่อน แล้วจึงคอลัมน์ที่สอง จึงใช้กับ query ที่กรอง user_id อย่างเดียวได้ (user.user_roles) แต่ใช้กับ role_id อย่างเดียวไม่ได้ นี่คือเหตุผลที่ t.references :role ยังมี index ของตัวเอง ให้วางคอลัมน์ที่ใช้กรองบ่อยที่สุดไว้ก่อน

ใช้คู่กับ validation

class UserRole < ApplicationRecord
  validates :role_id, uniqueness: {
                        scope: :user_id,                        # same columns as the index
                        conditions: -> { not_deleted },         # same WHERE as the index
                        message: "has already been assigned to this user",
                      }
end
  • validation ให้ error 400 ที่อ่านง่ายพร้อม details ส่วน index คือหลักประกันจริง: request สองตัวที่มาพร้อมกันอาจผ่าน validation ทั้งคู่ และมีแค่ index ที่หยุดการ insert ตัวที่สองได้ (raise ActiveRecord::RecordNotUnique)
  • ทำให้ทั้งสองตรงกันเสมอ uniqueness validator ไม่สนใจ default_scope ถ้าไม่มี conditions: -> { not_deleted } มันจะนับแถวที่ถูก soft delete และไม่ยอมให้เพิ่ม role กลับ ทั้งที่ partial index อนุญาต User ทำแบบนี้กับ username อยู่แล้ว ลองตรวจ UserRole ดู
  • ใน Postgres ค่า NULL ไม่ถือว่าซ้ำกัน: สองแถวที่ role_id = NULL ผ่าน unique index ได้ทั้งคู่ ให้ใช้ null: false หรือ nulls_not_distinct: true (Rails 7.1+, Postgres 15+)

index สำหรับ soft delete

เราไม่ลบแถวจริง แต่ตั้งค่า deleted_at ถ้าใช้ unique index ธรรมดาบน name จะสร้าง role ชื่อเดียวกับ role ที่ถูกลบไปแล้วไม่ได้ partial unique index ครอบคลุมเฉพาะแถวที่ยังไม่ถูกลบ:

class AddActiveNameIndexToRoles < ActiveRecord::Migration[8.1]
  def change
    add_index :roles, [:client_application_id, :name],
              unique: true,
              where: "deleted_at IS NULL",
              name: "index_roles_on_ca_id_name_where_active"
  end
end
ตั้งชื่อ index ที่ยาวเอง เพราะ Postgres จำกัดชื่อไว้ที่ 63 ตัวอักษร และชื่อที่ Rails สร้างอาจยาวเกิน

ตารางขนาดใหญ่

class AddIndexToUserRolesStatus < ActiveRecord::Migration[8.1]
  disable_ddl_transaction!          # CONCURRENTLY can't run inside a transaction

  def change
    add_index :user_roles, :status, algorithm: :concurrently
  end
end

การสร้าง index ปกติจะล็อกการเขียนตาราง ถ้าเป็นตารางใหญ่บน production ให้สร้างแบบ concurrently

ตัวอย่างการใช้งานจริงใน terminal

คำสั่งฐานข้อมูลอื่นๆ

คำสั่งใช้เมื่อ
bin/rails db:createตั้งค่าครั้งแรก
bin/rails db:prepareสร้างและโหลด schema หรือ migrate ถ้ามีอยู่แล้ว
bin/rails db:schema:loadสร้างฐานข้อมูลใหม่จาก schema.rb (เร็ว ห้ามใช้บน production)
bin/rails db:seedรัน db/seeds.rb
bin/rails db:resetลบ + สร้าง + โหลด + seed: ใช้ในเครื่องเท่านั้น

กฎที่เราใช้

  • ห้ามแก้ migration ที่ merge แล้ว เครื่องอื่นและ production รันไปแล้ว จะไม่มีวันเห็นการแก้ไขของคุณ ให้เขียน migration ใหม่
  • commit schema.rb พร้อมกับ migration คนรีวิวจะอ่าน diff ของ schema ไม่ใช่แค่ไฟล์ migration
  • หนึ่งการเปลี่ยนแปลงต่อหนึ่ง migration และตั้งชื่อตามสิ่งที่มันทำ
  • รัน db:migrate:redo ก่อน push เพื่อพิสูจน์ว่า rollback ได้
  • อย่าใช้ model ของแอปใน migration model อาจเปลี่ยนภายหลังแล้วทำให้ migration เก่าพัง ให้ใช้ SQL หรือ update_all กับ class เล็กๆ ที่นิยามในไฟล์นั้น
  • ใส่ index ให้ foreign key และคอลัมน์ที่ใช้กรอง (status, deleted_at)
  • หลัง migrate คอมเมนต์ == Schema Information ที่หัว model จะถูกอัปเดตโดย gem annotaterb ให้ commit การเปลี่ยนแปลงนั้นด้วย

ลองเช็กความเข้าใจ

ชื่อคอลัมน์ใน migration เมื่อเดือนที่แล้วสะกดผิด และ migration นั้นรันบน production ไปแล้ว ต้องทำอย่างไร?

production จะไม่รันไฟล์เก่าซ้ำ และ schema.rb ถูกสร้างอัตโนมัติ migration ใหม่เป็นทางเดียวที่จะไปถึงทุกฐานข้อมูล

ทำไม remove_column :users, :legacy_code ถึง rollback ไม่ได้?

ใส่ type ด้วย (remove_column :users, :legacy_code, :text) ก็จะย้อนกลับได้