From 13cbca25e09a0956fe0e8fcecdb89810fa52ab82 Mon Sep 17 00:00:00 2001 From: Venus Lumanglas Date: Sun, 26 Jan 2025 11:58:32 +0800 Subject: [PATCH] Add check constraints to order_items, products, and stocks for data integrity --- db/migrate/20250126034803_add_check_constraints.rb | 10 ++++++++++ db/schema.rb | 6 +++++- 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20250126034803_add_check_constraints.rb diff --git a/db/migrate/20250126034803_add_check_constraints.rb b/db/migrate/20250126034803_add_check_constraints.rb new file mode 100644 index 0000000..e7267fc --- /dev/null +++ b/db/migrate/20250126034803_add_check_constraints.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +class AddCheckConstraints < ActiveRecord::Migration[7.2] + def change + add_check_constraint :order_items, "product_price >= 0", name: "product_price_non_negative" + add_check_constraint :order_items, "quantity > 0", name: "quantity_positive" + add_check_constraint :products, "price >= 0", name: "price_non_negative" + add_check_constraint :stocks, "quantity >= 0", name: "quantity_non_negative" + end +end diff --git a/db/schema.rb b/db/schema.rb index e7fa053..ec738f0 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.2].define(version: 2025_01_26_012130) do +ActiveRecord::Schema[7.2].define(version: 2025_01_26_034803) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -88,6 +88,8 @@ t.index ["order_id"], name: "index_order_items_on_order_id" t.index ["product_id"], name: "index_order_items_on_product_id" t.index ["stock_id"], name: "index_order_items_on_stock_id" + t.check_constraint "product_price >= 0::numeric", name: "product_price_non_negative" + t.check_constraint "quantity > 0", name: "quantity_positive" end create_table "orders", force: :cascade do |t| @@ -119,6 +121,7 @@ t.index ["category_id"], name: "index_products_on_category_id" t.index ["name"], name: "index_products_on_name", unique: true t.index ["slug"], name: "index_products_on_slug", unique: true + t.check_constraint "price >= 0::numeric", name: "price_non_negative" end create_table "roles", force: :cascade do |t| @@ -138,6 +141,7 @@ t.datetime "updated_at", null: false t.index ["product_id", "size"], name: "index_stocks_on_product_id_and_size", unique: true t.index ["product_id"], name: "index_stocks_on_product_id" + t.check_constraint "quantity >= 0", name: "quantity_non_negative" end create_table "subscribers", force: :cascade do |t|