-- =====================================================================
-- 38_complaintosupplier.sql
-- Complaint Handling
--
-- GENERATED by _gen/pack.py from ../step/. DO NOT EDIT -- edit the source
-- there and re-pack, or the sha256 in MANIFEST.md stops matching.
--
-- 4 table(s), 16 ledger step(s).
--
-- ⚠ IMPORT ORDER: 01_system.sql, then all seven 1x masters, then this file. Order among
--    transactions does not matter. Re-importing costs nothing.
--
-- ⚠ STOP ON THE FIRST ERROR. Do not use `mysql --force`, and do not tick any
--    "continue on error" box. Each step records itself in `_migration_ledger`
--    immediately after its statement runs, WITHOUT checking that the statement
--    succeeded -- that is inherited from step/, where run.sh guarantees a stop by
--    running mysql without --force. Continue past an error here and a step that
--    failed is marked applied: 99_finalize.sql will then seed `migrations`, and
--    `php artisan migrate` will skip the work still owed. Both default clients
--    stop on error; the danger is turning that off.
--
-- ⚠ phpMyAdmin: UNTICK "Allow the interruption of an import".
--    If it fires, the import resumes on a NEW CONNECTION: SQL_MODE reverts to the server
--    default and every @variable dies, mid-file. Two things then break. NO_ZERO_DATE is
--    back, so any ALTER that rebuilds a table holding '0000-00-00' fails with ERROR 1292.
--    And @step / @todo / @sql are NULL, so the guard around the next payload stops meaning
--    anything. The SET SQL_MODE before every unit below limits the damage when someone
--    forgets the checkbox; it does not replace unticking it.
--
--    (STRICT_TRANS_TABLES is forced for a third case -- a value too big for its new column
--    is CLAMPED silently rather than refused. Measured on the tree as it stands, no column
--    narrows: all 674 MODIFY COLUMNs widen or are no-ops. It stays forced because the next
--    regeneration is under no obligation to keep that true.)
--
-- ⚠ Take a full backup first. The `20_cleanup` steps change data and nothing here
--    reverses them. `../audit_bukanmain_before_migrate.sql` only reads.
-- =====================================================================

-- Menus this file serves (20 links):
--   /complaint-handling/approval-ceo
--   /complaint-handling/close
--   /complaint-handling/complete/accounting
--   /complaint-handling/complete/finance
--   /complaint-handling/complete/logistic
--   /complaint-handling/complete/mm
--   /complaint-handling/complete/pm
--   /complaint-handling/complete/purchasing
--   /complaint-handling/create-logistic
--   /complaint-handling/create-pm
--   /complaint-handling/read-only
--   /complaint-handling/review/accounting
--   /complaint-handling/review/finance
--   /complaint-handling/review/logistic
--   /complaint-handling/review/mm
--   /complaint-handling/review/pm
--   /complaint-handling/review/purchasing
--   /complaint-handling/view
--   /complaint-handling/view-all
--   /complaint-handling/view-pm

-- --------------------------------------------------------------- prologue
-- run.sh sources step/_lib/session.sql for you. phpMyAdmin will not, so it is inlined.
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- Assert all four, not just the first. STRICT_TRANS_TABLES missing means out-of-range
-- values are clamped silently; NO_ZERO_DATE still present means any ALTER that rebuilds a
-- legacy table re-validates its '0000-00-00' rows and dies with ERROR 1292. The second is
-- the one that actually stops the migration, and it was not being checked.
SELECT IF(@@SQL_MODE LIKE '%STRICT_TRANS_TABLES%'
      AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
          'sql_mode OK - proceeding',
          (SELECT 'ABORT: sql_mode is wrong. Wanted STRICT_TRANS_TABLES + NO_AUTO_VALUE_ON_ZERO,'
           UNION ALL
           SELECT 'and NO_ZERO_DATE / NO_ZERO_IN_DATE OFF. The SET above should have done it.')
       ) AS preflight_sql_mode;

SET SESSION lock_wait_timeout = 60;
SET SESSION innodb_lock_wait_timeout = 60;

-- The ledger, copied verbatim from step/_lib/ledger.sql -- not restated, so the two
-- paths cannot disagree about its definition.
-- ---------------------------------------------------------------------
-- _lib/ledger.sql  --  the only thing here that is not in the source file
-- One row per applied step. This is the record that decides what a re-run skips,
-- what --status reports, and -- through the app-side gate -- which modules the
-- application will serve. It lives in the database on purpose: a file on one
-- operator's laptop drifts the moment someone runs a step from another machine.
--
-- Deliberately NOT in the project's PascalCase convention. It is an ops table, never
-- touched by Eloquent, and it should be visibly not-an-app-table.
--
-- `checksum` is the SHA-256 of the step's SQL payload -- the verbatim statements,
-- not the file -- so it cannot change when a comment above them is reworded.
-- _lib/steps.tsv carries the whole-file hashes for tamper detection.
--
-- ⚠ `step` IS ascii, AND THAT IS LOAD-BEARING. Every guard compares it against a
-- user variable, and a user variable carries the CONNECTION collation. Give this
-- column utf8mb4_unicode_ci and the very first step dies with ERROR 1267,
-- "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and
-- (utf8mb4_0900_ai_ci,IMPLICIT) for operation '='" -- measured, that is exactly
-- how the first end-to-end run failed. ascii is a repertoire subset of latin1 and
-- of utf8mb4, so the server coerces it to whatever the connection is using,
-- whatever that turns out to be on the day. Step names are [a-z0-9_/] by
-- construction, so nothing is lost.
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `_migration_ledger` (
  `step`        varchar(191) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
  `applied_at`  datetime     NOT NULL,
  `checksum`    char(64)     NOT NULL,
  `duration_ms` int          NOT NULL,
  PRIMARY KEY (`step`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- --------------------------------------------------------------- preflight
-- 00_system/01_system.sql MUST already be applied. Every doc says so; until now nothing
-- enforced it, and the violation was silent for most of the tree: only three files break
-- without it (30_quotation and 40_budgetandtarget hit ERROR 1146 on a table 01_system
-- creates, and 99_finalize needs `migrations`). The other twenty import cleanly, record
-- their ledger rows, and leave a database that is half-migrated with nothing to say so.
--
-- 13 steps: the ALTER DATABASE plus the 12 CREATE TABLEs.
SET @sys_done = (SELECT COUNT(*) FROM `_migration_ledger` WHERE `step` LIKE '\_system/%');
SET @pf_sys = IF(@sys_done >= 13,
    'SELECT ''preflight: 00_system is applied'' AS preflight_system',
    'SELECT `ABORT: import 00_system/01_system.sql first. It runs the ALTER DATABASE and creates the 12 new tables that everything here assumes exist.`');
PREPARE _pf FROM @pf_sys; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- preflight
-- WAS THIS DATABASE MIGRATED FROM A DIFFERENT VERSION OF THIS FILE?
--
-- `_migration_ledger.checksum` is the SHA-256 of each step's payload. It is written 632
-- times across the tree and, until this block existed, read never -- so a corrected payload
-- re-issued under the same step name was skipped forever on any database that had recorded
-- the old one, silently and permanently.
SELECT COUNT(*) INTO @ck_bad FROM `_migration_ledger`
 WHERE `step` IN ('complaintosupplier/10_alter', 'complaintosupplier/20_cleanup', 'complaintosupplier/30_assert', 'complaintosupplier/40_fk', 'complaintosupplierassignment/10_alter', 'complaintosupplierassignment/20_cleanup', 'complaintosupplierassignment/30_assert', 'complaintosupplierassignment/40_fk', 'complaintosupplierdetailsaction/10_alter', 'complaintosupplierdetailsaction/20_cleanup', 'complaintosupplierdetailsaction/30_assert', 'complaintosupplierdetailsaction/40_fk', 'complaintosupplierdetailsactionassignment/10_alter', 'complaintosupplierdetailsactionassignment/20_cleanup', 'complaintosupplierdetailsactionassignment/30_assert', 'complaintosupplierdetailsactionassignment/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('complaintosupplier/10_alter:7c1492157e2624814219fad6f84ed650d000cd0376bff246bf57ec320ec19ba7', 'complaintosupplier/20_cleanup:eccda0a5febe4eb220b3eb5ca2116f637c57b916d28f7108922e6ed669d341f0', 'complaintosupplier/30_assert:6be275ae9e3cd970bcc6a478533623c5749134bf08c1085a52990302bc5ddfc5', 'complaintosupplier/40_fk:f5d2407202497d9cd452bf0ae6e2e33046575fb1c5067eb8c8a036bfa5389c82', 'complaintosupplierassignment/10_alter:3b00e8e0314dc06cfe0579b11213a2f9e3951a9dffa761e94007c1b240cb37e6', 'complaintosupplierassignment/20_cleanup:4356a7a36246c33844de1a1c4f3eff3c7f80ad41564a2e19faa83d73655d3b0e', 'complaintosupplierassignment/30_assert:88599469c266fcfaa2c17a56ed32393e488b7c74be59e28c7a2eaf1b1f0937ae', 'complaintosupplierassignment/40_fk:80c007b65e8da79031835ee4692bc22d6668d9ca793c064c09f751b413f77782', 'complaintosupplierdetailsaction/10_alter:bd44c8d38fd77072d4c97de90fd0ce68a320c9ac5942b5d059f07db5615e6a57', 'complaintosupplierdetailsaction/20_cleanup:3afc9ffcedd3ba2827bb2a5c2fbbd1108394461e592ac6822479778fa356cc4d', 'complaintosupplierdetailsaction/30_assert:709fe5d7341e5f4a36da868691da5868eaae599635fdb1bfa87336aa2568af2f', 'complaintosupplierdetailsaction/40_fk:7154a91e72b59cca9117c0e6a145963d7909c323d4c44666320e4e88211a9ce3', 'complaintosupplierdetailsactionassignment/10_alter:c99e378f62c5051c685a344691e7fdaa3e44aeb60eab04bc15550ed14b4b5e02', 'complaintosupplierdetailsactionassignment/20_cleanup:f102c09ef32a7f19a2f6252d7ac999afb50be9b7e2e4883db2d8240041513091', 'complaintosupplierdetailsactionassignment/30_assert:cbd2a92569236e85a8654340359b7f08bef265e645295f873a3ba479ff7ac5d5', 'complaintosupplierdetailsactionassignment/40_fk:ca4b452dae4a78db9d7b2f7931d025679c73d2cfb8c12b7e20f9924caf4b7e56');
SET @pf_ck = IF(@ck_bad = 0,
    'SELECT ''preflight: ledger matches this file'' AS preflight_checksum',
    CONCAT('SELECT `ABORT: ', @ck_bad, ' step(s) here were applied from a DIFFERENT version of this file. Their payloads changed. Compare before re-importing; do not delete ledger rows blindly.`'));
PREPARE _pf FROM @pf_ck; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- ---------------------------------------------------------------------
-- unit: complaintosupplier    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaintosupplier/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplier/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplier`
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainTypeID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `IndustryID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainItemTypeID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `ProductID` int DEFAULT NULL,
  MODIFY COLUMN `PackingMonth` int DEFAULT NULL,
  MODIFY COLUMN `PackingYear` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  ADD INDEX `complaintosupplier_ApplicationID` (`ApplicationID`),
  ADD INDEX `complaintosupplier_CompanyID` (`CompanyID`),
  ADD INDEX `complaintosupplier_ComplainItemTypeID` (`ComplainItemTypeID`),
  ADD INDEX `complaintosupplier_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complaintosupplier_ComplainTypeID` (`ComplainTypeID`),
  ADD INDEX `complaintosupplier_DivisionID` (`DivisionID`),
  ADD INDEX `complaintosupplier_IndustryID` (`IndustryID`),
  ADD INDEX `complaintosupplier_PackingMonth` (`PackingMonth`),
  ADD INDEX `complaintosupplier_PackingYear` (`PackingYear`),
  ADD INDEX `complaintosupplier_PrincipalID` (`PrincipalID`),
  ADD INDEX `complaintosupplier_ProductID` (`ProductID`),
  ADD INDEX `complaintosupplier_UserIDInput` (`UserIDInput`),
  ADD INDEX `complaintosupplier_UserIDSales` (`UserIDSales`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '7c1492157e2624814219fad6f84ed650d000cd0376bff246bf57ec320ec19ba7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplier/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaintosupplier/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaintosupplier` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `complaintosuppliertype` p2 ON c.`ComplainItemTypeID` = p2.`ID`
  LEFT JOIN `complaintosupplierstatus` p3 ON c.`ComplainStatusID` = p3.`ID`
  LEFT JOIN `complaintype` p4 ON c.`ComplainTypeID` = p4.`ID`
  LEFT JOIN `division` p5 ON c.`DivisionID` = p5.`ID`
  LEFT JOIN `industry` p6 ON c.`IndustryID` = p6.`ID`
  LEFT JOIN `packing` p7 ON c.`PackingMonth` = p7.`ID`
  LEFT JOIN `packing` p8 ON c.`PackingYear` = p8.`ID`
  LEFT JOIN `principal` p9 ON c.`PrincipalID` = p9.`ID`
  LEFT JOIN `product` p10 ON c.`ProductID` = p10.`ID`
  LEFT JOIN `users` p11 ON c.`UserIDInput` = p11.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`ComplainItemTypeID` = IF((c.`ComplainItemTypeID` IS NOT NULL AND (c.`ComplainItemTypeID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ComplainItemTypeID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`ComplainTypeID` = IF((c.`ComplainTypeID` IS NOT NULL AND (c.`ComplainTypeID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ComplainTypeID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p5.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p6.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`PackingMonth` = IF((c.`PackingMonth` IS NOT NULL AND (c.`PackingMonth` = 0 OR p7.`ID` IS NULL)), NULL, c.`PackingMonth`),
       c.`PackingYear` = IF((c.`PackingYear` IS NOT NULL AND (c.`PackingYear` = 0 OR p8.`ID` IS NULL)), NULL, c.`PackingYear`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p9.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`ProductID` = IF((c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p10.`ID` IS NULL)), NULL, c.`ProductID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p11.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ComplainItemTypeID` IS NOT NULL AND (c.`ComplainItemTypeID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ComplainTypeID` IS NOT NULL AND (c.`ComplainTypeID` = 0 OR p4.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p5.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p6.`ID` IS NULL))
    OR (c.`PackingMonth` IS NOT NULL AND (c.`PackingMonth` = 0 OR p7.`ID` IS NULL))
    OR (c.`PackingYear` IS NOT NULL AND (c.`PackingYear` = 0 OR p8.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p9.`ID` IS NULL))
    OR (c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p10.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p11.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
SET @sql = IF(@todo, 'UPDATE `complaintosupplier` c
  LEFT JOIN `users` p0 ON c.`UserIDSales` = p0.`ID`
   SET
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p0.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p0.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'eccda0a5febe4eb220b3eb5ca2116f637c57b916d28f7108922e6ed669d341f0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaintosupplier/30_assert  --  source section 7b
-- Orphan assertion over this table's 13 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplier/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaintosupplier` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `complaintosuppliertype` p2 ON c.`ComplainItemTypeID` = p2.`ID`
  LEFT JOIN `complaintosupplierstatus` p3 ON c.`ComplainStatusID` = p3.`ID`
  LEFT JOIN `complaintype` p4 ON c.`ComplainTypeID` = p4.`ID`
  LEFT JOIN `division` p5 ON c.`DivisionID` = p5.`ID`
  LEFT JOIN `industry` p6 ON c.`IndustryID` = p6.`ID`
  LEFT JOIN `packing` p7 ON c.`PackingMonth` = p7.`ID`
  LEFT JOIN `packing` p8 ON c.`PackingYear` = p8.`ID`
  LEFT JOIN `principal` p9 ON c.`PrincipalID` = p9.`ID`
  LEFT JOIN `product` p10 ON c.`ProductID` = p10.`ID`
  LEFT JOIN `users` p11 ON c.`UserIDInput` = p11.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ComplainItemTypeID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ComplainTypeID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`PackingMonth` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`PackingYear` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p9.`ID` IS NULL)
    OR (c.`ProductID` IS NOT NULL AND p10.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p11.`ID` IS NULL);
SET @orphans = @orphans + @n;
SELECT COUNT(*) INTO @n FROM `complaintosupplier` c
  LEFT JOIN `users` p0 ON c.`UserIDSales` = p0.`ID`
 WHERE  (c.`UserIDSales` IS NOT NULL AND p0.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaintosupplier: orphan check OK - 0 rows across 13 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaintosupplier` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6be275ae9e3cd970bcc6a478533623c5749134bf08c1085a52990302bc5ddfc5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplier/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaintosupplier/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplier`
  ADD CONSTRAINT `complaintosupplier_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_ComplainItemTypeID` FOREIGN KEY (`ComplainItemTypeID`) REFERENCES `complaintosuppliertype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complaintosupplierstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_ComplainTypeID` FOREIGN KEY (`ComplainTypeID`) REFERENCES `complaintype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_PackingMonth` FOREIGN KEY (`PackingMonth`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_PackingYear` FOREIGN KEY (`PackingYear`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_ProductID` FOREIGN KEY (`ProductID`) REFERENCES `product` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplier_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f5d2407202497d9cd452bf0ae6e2e33046575fb1c5067eb8c8a036bfa5389c82', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaintosupplierassignment    (detail, owned by complaintosupplier)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaintosupplierassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplierassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplierassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  ADD INDEX `complaintosupplierassignment_ComplainID` (`ComplainID`),
  ADD INDEX `complaintosupplierassignment_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complaintosupplierassignment_DepartmentID` (`DepartmentID`),
  ADD INDEX `complaintosupplierassignment_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '3b00e8e0314dc06cfe0579b11213a2f9e3951a9dffa761e94007c1b240cb37e6', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplierassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaintosupplierassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaintosupplierassignment` c
  LEFT JOIN `complaintosupplier` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complaintosupplierstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `department` p2 ON c.`DepartmentID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
   SET
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`DepartmentID` = IF((c.`DepartmentID` IS NOT NULL AND (c.`DepartmentID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DepartmentID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DepartmentID` IS NOT NULL AND (c.`DepartmentID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4356a7a36246c33844de1a1c4f3eff3c7f80ad41564a2e19faa83d73655d3b0e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaintosupplierassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplierassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaintosupplierassignment` c
  LEFT JOIN `complaintosupplier` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complaintosupplierstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `department` p2 ON c.`DepartmentID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
 WHERE  (c.`ComplainID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DepartmentID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaintosupplierassignment: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaintosupplierassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '88599469c266fcfaa2c17a56ed32393e488b7c74be59e28c7a2eaf1b1f0937ae', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplierassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaintosupplierassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplierassignment`
  ADD CONSTRAINT `complaintosupplierassignment_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complaintosupplier` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierassignment_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complaintosupplierstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierassignment_DepartmentID` FOREIGN KEY (`DepartmentID`) REFERENCES `department` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '80c007b65e8da79031835ee4692bc22d6668d9ca793c064c09f751b413f77782', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaintosupplierdetailsaction    (detail, owned by complaintosupplier)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsaction/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplierdetailsaction/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplierdetailsaction`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartementID` int DEFAULT NULL,
  ADD INDEX `complaintosupplierdetailsaction_ComplainID` (`ComplainID`),
  ADD INDEX `complaintosupplierdetailsaction_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complaintosupplierdetailsaction_DepartementID` (`DepartementID`),
  ADD INDEX `complaintosupplierdetailsaction_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'bd44c8d38fd77072d4c97de90fd0ce68a320c9ac5942b5d059f07db5615e6a57', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsaction/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaintosupplierdetailsaction/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaintosupplierdetailsaction` c
  LEFT JOIN `complaintosupplier` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complaintosupplierstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `department` p2 ON c.`DepartementID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
   SET
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`DepartementID` = IF((c.`DepartementID` IS NOT NULL AND (c.`DepartementID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DepartementID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DepartementID` IS NOT NULL AND (c.`DepartementID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '3afc9ffcedd3ba2827bb2a5c2fbbd1108394461e592ac6822479778fa356cc4d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsaction/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplierdetailsaction/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaintosupplierdetailsaction` c
  LEFT JOIN `complaintosupplier` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complaintosupplierstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `department` p2 ON c.`DepartementID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
 WHERE  (c.`ComplainID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DepartementID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaintosupplierdetailsaction: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaintosupplierdetailsaction` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '709fe5d7341e5f4a36da868691da5868eaae599635fdb1bfa87336aa2568af2f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsaction/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaintosupplierdetailsaction/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplierdetailsaction`
  ADD CONSTRAINT `complaintosupplierdetailsaction_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complaintosupplier` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierdetailsaction_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complaintosupplierstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierdetailsaction_DepartementID` FOREIGN KEY (`DepartementID`) REFERENCES `department` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierdetailsaction_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '7154a91e72b59cca9117c0e6a145963d7909c323d4c44666320e4e88211a9ce3', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: complaintosupplierdetailsactionassignment    (detail, owned by complaintosupplier)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsactionassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplierdetailsactionassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplierdetailsactionassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ComplainID` int DEFAULT NULL,
  MODIFY COLUMN `ComplainStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DepartmentID` int DEFAULT NULL,
  ADD INDEX `complaintosupplierdetailsactionassignment_ComplainID` (`ComplainID`),
  ADD INDEX `complaintosupplierdetailsactionassignment_ComplainStatusID` (`ComplainStatusID`),
  ADD INDEX `complaintosupplierdetailsactionassignment_DepartmentID` (`DepartmentID`),
  ADD INDEX `complaintosupplierdetailsactionassignment_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'c99e378f62c5051c685a344691e7fdaa3e44aeb60eab04bc15550ed14b4b5e02', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsactionassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'complaintosupplierdetailsactionassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `complaintosupplierdetailsactionassignment` c
  LEFT JOIN `complaintosupplier` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complaintosupplierstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `department` p2 ON c.`DepartmentID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
   SET
       c.`ComplainID` = IF((c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ComplainID`),
       c.`ComplainStatusID` = IF((c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ComplainStatusID`),
       c.`DepartmentID` = IF((c.`DepartmentID` IS NOT NULL AND (c.`DepartmentID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DepartmentID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ComplainID` IS NOT NULL AND (c.`ComplainID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ComplainStatusID` IS NOT NULL AND (c.`ComplainStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DepartmentID` IS NOT NULL AND (c.`DepartmentID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f102c09ef32a7f19a2f6252d7ac999afb50be9b7e2e4883db2d8240041513091', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsactionassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'complaintosupplierdetailsactionassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `complaintosupplierdetailsactionassignment` c
  LEFT JOIN `complaintosupplier` p0 ON c.`ComplainID` = p0.`ID`
  LEFT JOIN `complaintosupplierstatus` p1 ON c.`ComplainStatusID` = p1.`ID`
  LEFT JOIN `department` p2 ON c.`DepartmentID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
 WHERE  (c.`ComplainID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ComplainStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DepartmentID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'complaintosupplierdetailsactionassignment: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `complaintosupplierdetailsactionassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'cbd2a92569236e85a8654340359b7f08bef265e645295f873a3ba479ff7ac5d5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- complaintosupplierdetailsactionassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'complaintosupplierdetailsactionassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `complaintosupplierdetailsactionassignment`
  ADD CONSTRAINT `complaintosupplierdetailsactionassignment_ComplainID` FOREIGN KEY (`ComplainID`) REFERENCES `complaintosupplier` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierdetailsactionassignment_ComplainStatusID` FOREIGN KEY (`ComplainStatusID`) REFERENCES `complaintosupplierstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierdetailsactionassignment_DepartmentID` FOREIGN KEY (`DepartmentID`) REFERENCES `department` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `complaintosupplierdetailsactionassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'ca4b452dae4a78db9d7b2f7931d025679c73d2cfb8c12b7e20f9924caf4b7e56', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- --------------------------------------------------------------- postflight
-- DID THE WORK ACTUALLY LAND?
--
-- Every step records itself in `_migration_ledger` immediately after its statement runs,
-- WITHOUT checking that the statement succeeded. That is inherited from step/ unchanged,
-- and there it is safe because run.sh runs mysql without --force, so the first error stops
-- everything. Imported by hand, the client decides -- and "continue on error" would leave
-- failed steps marked applied.
--
-- So this file checks its own work against information_schema before it finishes. It is
-- the only thing here that is NOT copied from step/. It reads; it changes nothing.

-- postflight-set: fk
SET @want_fk = 25;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'complaintosupplier.complaintosupplier_ApplicationID' AS n UNION ALL SELECT 'complaintosupplier.complaintosupplier_CompanyID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ComplainItemTypeID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ComplainStatusID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ComplainTypeID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_DivisionID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_IndustryID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_PackingMonth' UNION ALL SELECT 'complaintosupplier.complaintosupplier_PackingYear' UNION ALL SELECT 'complaintosupplier.complaintosupplier_PrincipalID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ProductID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_UserIDInput' UNION ALL SELECT 'complaintosupplier.complaintosupplier_UserIDSales' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_ComplainID' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_ComplainStatusID' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_DepartmentID' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_UserIDInput' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_ComplainID' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_ComplainStatusID' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_DepartementID' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_UserIDInput' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_ComplainID' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_ComplainStatusID' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_DepartmentID' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_UserIDInput') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 25;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'complaintosupplier.complaintosupplier_ApplicationID' AS n UNION ALL SELECT 'complaintosupplier.complaintosupplier_CompanyID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ComplainItemTypeID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ComplainStatusID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ComplainTypeID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_DivisionID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_IndustryID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_PackingMonth' UNION ALL SELECT 'complaintosupplier.complaintosupplier_PackingYear' UNION ALL SELECT 'complaintosupplier.complaintosupplier_PrincipalID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_ProductID' UNION ALL SELECT 'complaintosupplier.complaintosupplier_UserIDInput' UNION ALL SELECT 'complaintosupplier.complaintosupplier_UserIDSales' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_ComplainID' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_ComplainStatusID' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_DepartmentID' UNION ALL SELECT 'complaintosupplierassignment.complaintosupplierassignment_UserIDInput' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_ComplainID' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_ComplainStatusID' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_DepartementID' UNION ALL SELECT 'complaintosupplierdetailsaction.complaintosupplierdetailsaction_UserIDInput' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_ComplainID' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_ComplainStatusID' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_DepartmentID' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.complaintosupplierdetailsactionassignment_UserIDInput') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', INDEX_NAME) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE());
SET @have_idx = @want_idx - @missn_idx;
SET @pf_idx = IF(@missn_idx = 0,
    CONCAT('SELECT ''postflight indexes: ', @have_idx, '/', @want_idx, ' present'' AS postflight_idx'),
    CONCAT('SELECT `ABORT postflight: MISSING indexes: ', @miss_idx,
           ' -- ', @missn_idx, ' of ', @want_idx, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_idx; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: typ
SET @want_typ = 25;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'complaintosupplier.ApplicationID.int' AS n UNION ALL SELECT 'complaintosupplier.CompanyID.int' UNION ALL SELECT 'complaintosupplier.ComplainItemTypeID.int' UNION ALL SELECT 'complaintosupplier.ComplainStatusID.int' UNION ALL SELECT 'complaintosupplier.ComplainTypeID.int' UNION ALL SELECT 'complaintosupplier.DivisionID.int' UNION ALL SELECT 'complaintosupplier.IndustryID.int' UNION ALL SELECT 'complaintosupplier.PackingMonth.int' UNION ALL SELECT 'complaintosupplier.PackingYear.int' UNION ALL SELECT 'complaintosupplier.PrincipalID.int' UNION ALL SELECT 'complaintosupplier.ProductID.int' UNION ALL SELECT 'complaintosupplier.UserIDInput.int' UNION ALL SELECT 'complaintosupplier.UserIDSales.int' UNION ALL SELECT 'complaintosupplierassignment.ComplainID.int' UNION ALL SELECT 'complaintosupplierassignment.ComplainStatusID.int' UNION ALL SELECT 'complaintosupplierassignment.DepartmentID.int' UNION ALL SELECT 'complaintosupplierassignment.UserIDInput.int' UNION ALL SELECT 'complaintosupplierdetailsaction.ComplainID.int' UNION ALL SELECT 'complaintosupplierdetailsaction.ComplainStatusID.int' UNION ALL SELECT 'complaintosupplierdetailsaction.DepartementID.int' UNION ALL SELECT 'complaintosupplierdetailsaction.UserIDInput.int' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.ComplainID.int' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.ComplainStatusID.int' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.DepartmentID.int' UNION ALL SELECT 'complaintosupplierdetailsactionassignment.UserIDInput.int') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', COLUMN_NAME, '.', DATA_TYPE) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE());
SET @have_typ = @want_typ - @missn_typ;
SET @pf_typ = IF(@missn_typ = 0,
    CONCAT('SELECT ''postflight retyped columns: ', @have_typ, '/', @want_typ, ' present'' AS postflight_typ'),
    CONCAT('SELECT `ABORT postflight: MISSING retyped columns: ', @miss_typ,
           ' -- ', @missn_typ, ' of ', @want_typ, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_typ; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- restore
-- IFNULL on all four: if phpMyAdmin resumed this import on a fresh connection the
-- @OLD_ variables are gone, and a bare SET from NULL is ERROR 1231.
--
-- The CAST is on the two timeouts and NOWHERE ELSE, on purpose. An INTEGER system
-- variable rejects IFNULL()'s result type outright (ERROR 1232, every time, not only
-- when NULL). FOREIGN_KEY_CHECKS is a boolean and SQL_MODE is a set; both accept a
-- string result, so they need no CAST. Do not "fix" the asymmetry, and do not copy
-- line 3's shape onto a new integer variable.
SET SESSION lock_wait_timeout = CAST(IFNULL(@OLD_LOCK_WAIT, 86400) AS UNSIGNED);
SET SESSION innodb_lock_wait_timeout = CAST(IFNULL(@OLD_INNODB_LOCK_WAIT, 50) AS UNSIGNED);
