-- prc_quote: customer_code required + included in unique business key -- Idempotent; safe after quote_customer_code_alter.sql SET NAMES utf8mb4; SET @db := DATABASE(); -- Ensure column exists SET @has := ( SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'prc_quote' AND COLUMN_NAME = 'customer_code' ); SET @sql := IF(@has = 0, 'ALTER TABLE prc_quote ADD COLUMN customer_code VARCHAR(50) DEFAULT NULL COMMENT ''customer code'' AFTER customer_id', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; -- Backfill from bms_customer UPDATE prc_quote q INNER JOIN bms_customer c ON c.customer_id = q.customer_id SET q.customer_code = c.customer_code WHERE q.customer_id IS NOT NULL AND q.customer_id <> 0 AND (q.customer_code IS NULL OR q.customer_code = ''); -- Remove rows that still have no customer_code (cannot join unique NOT NULL) DELETE FROM prc_quote WHERE customer_code IS NULL OR customer_code = ''; -- NOT NULL ALTER TABLE prc_quote MODIFY COLUMN customer_code VARCHAR(50) NOT NULL COMMENT 'customer code'; -- Drop old non-unique index if present SET @hasIdx := ( SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'prc_quote' AND INDEX_NAME = 'idx_quote_customer_code' ); SET @sql := IF(@hasIdx > 0, 'ALTER TABLE prc_quote DROP INDEX idx_quote_customer_code', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; -- Normalized postcode for unique (NULL -> '') SET @hasGen := ( SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'prc_quote' AND COLUMN_NAME = 'quote_postcode_key' ); SET @sql := IF(@hasGen = 0, 'ALTER TABLE prc_quote ADD COLUMN quote_postcode_key VARCHAR(20) AS (IFNULL(dest_postcode, '''')) STORED COMMENT ''dest_postcode for unique key'' AFTER dest_postcode', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; -- Unique: customer_code + product + country + postcode + weight + biz_date SET @hasUk := ( SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'prc_quote' AND INDEX_NAME = 'uk_quote_cust_biz' ); SET @sql := IF(@hasUk = 0, 'ALTER TABLE prc_quote ADD UNIQUE KEY uk_quote_cust_biz (customer_code, product_code, country_code, quote_postcode_key, weight, biz_date)', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;