-- liquibase formatted sql
-- changeset 2fi:20260430_04_truck_lane_version_snapshot_patch
-- preconditions onFail:MARK_RAN
-- precondition-sql-check expectedResult:0 SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'truck_lane_version_line' AND column_name = 'truckLanceCode'

ALTER TABLE `truck_lane_version`
    MODIFY COLUMN `truckLanceCode` VARCHAR(100) NULL;

SET @col_tlvl_storeId := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'truck_lane_version_line'
      AND column_name = 'storeId'
);
SET @col_tlvl_tlc := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'truck_lane_version_line'
      AND column_name = 'truckLanceCode'
);
SET @sql_add_tlc := IF(
    @col_tlvl_tlc = 0,
    'ALTER TABLE `truck_lane_version_line` ADD COLUMN `truckLanceCode` VARCHAR(100) NULL DEFAULT NULL AFTER `truckRowId`',
    'SELECT 1'
);
PREPARE stmt_add_tlc FROM @sql_add_tlc;
EXECUTE stmt_add_tlc;
DEALLOCATE PREPARE stmt_add_tlc;

SET @idx_tlvl_lane := (
    SELECT COUNT(*)
    FROM information_schema.statistics
    WHERE table_schema = DATABASE()
      AND table_name = 'truck_lane_version_line'
      AND index_name = 'idx_tlvl_lane'
);
SET @sql_tlvl_lane := IF(
    @idx_tlvl_lane = 0 AND @col_tlvl_storeId > 0 AND @col_tlvl_tlc > 0,
    'CREATE INDEX idx_tlvl_lane ON `truck_lane_version_line` (`storeId`, `truckLanceCode`)',
    'SELECT 1'
);
PREPARE stmt_tlvl_lane FROM @sql_tlvl_lane;
EXECUTE stmt_tlvl_lane;
DEALLOCATE PREPARE stmt_tlvl_lane;
