-- =====================================================================
-- 16_companyproject.sql
-- company projects and their detail tiers
--
-- 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.
--
-- 11 table(s), 44 ledger step(s).
--
-- ⚠ IMPORT ORDER: 01_system.sql, then all seven 1x masters including this one, before
--    any transaction file. Order among the masters does not matter.
--
-- ⚠ 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 (9 links):
--   /company-projects
--   /company-projects/all
--   /company-projects/approval-pm
--   /company-projects/approval-sm
--   /company-projects/create
--   /company-projects/head
--   /company-projects/mm
--   /company-projects/pm
--   /company-projects/sm

-- --------------------------------------------------------------- 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 ('companyproject/10_alter', 'companyproject/20_cleanup', 'companyproject/30_assert', 'companyproject/40_fk', 'companyprojectassignment/10_alter', 'companyprojectassignment/20_cleanup', 'companyprojectassignment/30_assert', 'companyprojectassignment/40_fk', 'companyprojectdetailcc/10_alter', 'companyprojectdetailcc/20_cleanup', 'companyprojectdetailcc/30_assert', 'companyprojectdetailcc/40_fk', 'companyprojectdetailccassignment/10_alter', 'companyprojectdetailccassignment/20_cleanup', 'companyprojectdetailccassignment/30_assert', 'companyprojectdetailccassignment/40_fk', 'companyprojectdetailcomp/10_alter', 'companyprojectdetailcomp/20_cleanup', 'companyprojectdetailcomp/30_assert', 'companyprojectdetailcomp/40_fk', 'companyprojectdetailcompassignment/10_alter', 'companyprojectdetailcompassignment/20_cleanup', 'companyprojectdetailcompassignment/30_assert', 'companyprojectdetailcompassignment/40_fk', 'companyprojectdetails/10_alter', 'companyprojectdetails/20_cleanup', 'companyprojectdetails/30_assert', 'companyprojectdetails/40_fk', 'companyprojectdetailsassignment/10_alter', 'companyprojectdetailsassignment/20_cleanup', 'companyprojectdetailsassignment/30_assert', 'companyprojectdetailsassignment/40_fk', 'companyprojectdetailstatusassignment/10_alter', 'companyprojectdetailstatusassignment/20_cleanup', 'companyprojectdetailstatusassignment/30_assert', 'companyprojectdetailstatusassignment/40_fk', 'companyprojectdetailstatusreason/10_alter', 'companyprojectdetailstatusreason/20_cleanup', 'companyprojectdetailstatusreason/30_assert', 'companyprojectdetailstatusreason/40_fk', 'companyprojectheaderassignment/10_alter', 'companyprojectheaderassignment/20_cleanup', 'companyprojectheaderassignment/30_assert', 'companyprojectheaderassignment/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('companyproject/10_alter:23ed8e598107ba559e108871a86f37b98dbf2b680ba58bcbb969347c0e195ac9', 'companyproject/20_cleanup:da3a97a7b2eb9ea5879c4896e7cc57bac0d8e5732f4b849fe4224ec05027c734', 'companyproject/30_assert:c4eedd15645b8b8638eb9d806da7630595495b4d89d1a20815d3a4c9847a39c4', 'companyproject/40_fk:5b01502375a1736c8d326a33162d4f60514e5f081d436e71a0065322ff2f3483', 'companyprojectassignment/10_alter:2c78796a3157b84e655df470569961084a1a15bf8b3f8db2b6e5bbfe1bb1fd5c', 'companyprojectassignment/20_cleanup:1a0b19704d5a728fa0f03e96c9e5f1ff142177dd7df2fc3aff9a0730e10c5429', 'companyprojectassignment/30_assert:54b8157093e647d8bf2e389a6427bec04f5572546da2513505af7aea4ece3f1b', 'companyprojectassignment/40_fk:bc024daac708e657e0ddbf79f0921f69607fc052458ed5011a2bfa2ba5e5d380', 'companyprojectdetailcc/10_alter:1e5023a9759664579235a93d814a5b428553747175368acaba124d8db39d5ef8', 'companyprojectdetailcc/20_cleanup:b748ec9f57704cb21e8eb862f4c26086027d1c468bca213966a02dc65c9fd50a', 'companyprojectdetailcc/30_assert:62b8ab1dbea675c383f8fbc879f66d50484a6e3e20f44bc9aa1693fbe3b48e3f', 'companyprojectdetailcc/40_fk:402804b5970abd0f3a32f093780ad3500a84d54a35859bf36f8166cf149a5269', 'companyprojectdetailccassignment/10_alter:d6576ada7a1d30cfd59859673c2f7cca76449912fb38fb769184bd67ca3bced6', 'companyprojectdetailccassignment/20_cleanup:fa9389275068b9cd219b4ed2909cb77369aeed1dd3f35ed473517f21d89c9bbc', 'companyprojectdetailccassignment/30_assert:a65b7624c4ea484fe030c7a9783590f89b72fb47dd71d4ff59819beb9f31b2d9', 'companyprojectdetailccassignment/40_fk:ca4f4ceeb73e75b694ef7cddea19e4e81c0210fbcd4448ae265242c53a9b80ff', 'companyprojectdetailcomp/10_alter:7e14faf116fdf17e79132f5ece296adc50d32020e8064dbf5bd2d7e65fd88f43', 'companyprojectdetailcomp/20_cleanup:0514ae04c60bc5ccca85793e678163568fe4fb926ce443ff2e19a7a3527044a3', 'companyprojectdetailcomp/30_assert:e42ae917d0e8f1470a490ece20322d12ebec96009adea2628ee2acb7c2940303', 'companyprojectdetailcomp/40_fk:b285ec085e22c3d55d7e5ea435cded8b14a97986df290d75ff9fd868c4292c4e', 'companyprojectdetailcompassignment/10_alter:c28dd4c5422d1837cda709c39d3c177ec260f93815810299eb39fe939b46f441', 'companyprojectdetailcompassignment/20_cleanup:a54c23a9602d2066caabd4571b883683dffaca0620b300be04a8a9282a52f71d', 'companyprojectdetailcompassignment/30_assert:c84610b3a7bd7b8678a39339c8606bf257f8ae499474b64392f8eb52074957b5', 'companyprojectdetailcompassignment/40_fk:2bce5fd2b193a39677459fdb452d6b05af14dfd5f921bfc50c24ccfd00669ecd', 'companyprojectdetails/10_alter:d42cf36e19f4ebe75537cad79d6fac37593f0166c5137ba8918ce5b3ba0955e2', 'companyprojectdetails/20_cleanup:b7d8d61e2345babb1afdd567373b1319bbadab67aa33c542a59f366dba2392e1', 'companyprojectdetails/30_assert:ae5f246f011476a3c60663b2c9786e5692d8aac6cb5a8186b5635228bb92d8e9', 'companyprojectdetails/40_fk:4876527b3d3de07cff29f6c86c73d7b5b55a3e9a7efec6fc7a3c761d9022ff5e', 'companyprojectdetailsassignment/10_alter:06621fafed046ef5f696c56eb0b62bd60463e8bef601b6e1d7cb61641a62d89a', 'companyprojectdetailsassignment/20_cleanup:701dd2d3d287f7e690b94df5ba8b4fad9f7f5c1accd6d8034ba640990a7ae947', 'companyprojectdetailsassignment/30_assert:a7e75c6b100c3d63226965f2a0e0cdaf2ed960217a43e1ec4a2f0bd7f909779d', 'companyprojectdetailsassignment/40_fk:bf82200e4a85422b1a3e596a68425c8ec0be800a9f9cf6dcd7f7ac451dec4d95', 'companyprojectdetailstatusassignment/10_alter:256264a881739474d1c8b6a8f9baa87d598c669a6b1d0fef3b0e8e61eef8df17', 'companyprojectdetailstatusassignment/20_cleanup:8fcc1d62f31fa78ca40f877d9c497789b999fc4c13b67d9bf55aff41c4b457fa', 'companyprojectdetailstatusassignment/30_assert:53083b20eccbabb96419b1fe3fc494437da871e5ba401a51988c3420f7e9bc2e', 'companyprojectdetailstatusassignment/40_fk:63ac7d628feb22eb423095a8e960c1592bc75d7649da34c83514d97931295ea4', 'companyprojectdetailstatusreason/10_alter:2ef0acfd5befa2b040fbe4f8f0c1b64efe7338ed335788dcf790bcb860e71cf5', 'companyprojectdetailstatusreason/20_cleanup:b1eba54aa9556d03f13da91935fdcdf911bc07f73b543fd7a46d20bb852f9784', 'companyprojectdetailstatusreason/30_assert:b7f13792f3eb15f32ad6bc202b11f75f1f70b21970b19161147f40823f0725f8', 'companyprojectdetailstatusreason/40_fk:e2e33e6f2dbcbcb2acf79ba1feaf4b7d3072105951d430d64bfa5b7245172829', 'companyprojectheaderassignment/10_alter:f6731bc3e25d0b70202b9bc28a3a0c0173271719b8970c005507baaace2e9a3c', 'companyprojectheaderassignment/20_cleanup:bcb74c5e0214bf4c2d841b01842f479b98eaa03d75e6d8b8fd09d7a56e8d0fb5', 'companyprojectheaderassignment/30_assert:3df48d85f47272aa61cfdc19913d98e653a83f75424a866cb7eba049f5dbf1f9', 'companyprojectheaderassignment/40_fk:5f5b07b695b3e9addf54a58f2ac970f54880591973fdf34fd3391ac1a1d11d3f');
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: companyproject    (master)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyproject/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 = 'companyproject/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproject`
  ADD COLUMN `RemarkSM` varchar(255) NOT NULL AFTER `CommentProject`,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectStatusID` 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 `CompanyCP` int DEFAULT NULL,
  MODIFY COLUMN `ProjectPriority` int DEFAULT NULL,
  ADD INDEX `companyproject_CompanyCP` (`CompanyCP`),
  ADD INDEX `companyproject_CompanyID` (`CompanyID`),
  ADD INDEX `companyproject_DivisionID` (`DivisionID`),
  ADD INDEX `companyproject_IndustryID` (`IndustryID`),
  ADD INDEX `companyproject_ProjectID` (`ProjectID`),
  ADD INDEX `companyproject_ProjectPriority` (`ProjectPriority`),
  ADD INDEX `companyproject_ProjectStatusID` (`ProjectStatusID`),
  ADD INDEX `companyproject_UserIDInput` (`UserIDInput`),
  ADD INDEX `companyproject_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(), '23ed8e598107ba559e108871a86f37b98dbf2b680ba58bcbb969347c0e195ac9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproject/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 = 'companyproject/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproject` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCP` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `industry` p3 ON c.`IndustryID` = p3.`ID`
  LEFT JOIN `companyproject` p4 ON c.`ProjectID` = p4.`ID`
  LEFT JOIN `companyprojectpriority` p5 ON c.`ProjectPriority` = p5.`ID`
  LEFT JOIN `companyprojectstatus` p6 ON c.`ProjectStatusID` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDInput` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDSales` = p8.`ID`
   SET
       c.`CompanyCP` = IF((c.`CompanyCP` IS NOT NULL AND (c.`CompanyCP` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCP`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p3.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`ProjectPriority` = IF((c.`ProjectPriority` IS NOT NULL AND (c.`ProjectPriority` = 0 OR p5.`ID` IS NULL)), NULL, c.`ProjectPriority`),
       c.`ProjectStatusID` = IF((c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p6.`ID` IS NULL)), NULL, c.`ProjectStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p7.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p8.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`CompanyCP` IS NOT NULL AND (c.`CompanyCP` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p4.`ID` IS NULL))
    OR (c.`ProjectPriority` IS NOT NULL AND (c.`ProjectPriority` = 0 OR p5.`ID` IS NULL))
    OR (c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p6.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p7.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p8.`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(), 'da3a97a7b2eb9ea5879c4896e7cc57bac0d8e5732f4b849fe4224ec05027c734', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyproject/30_assert  --  source section 7b
-- Orphan assertion over this table's 9 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 = 'companyproject/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproject` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCP` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `industry` p3 ON c.`IndustryID` = p3.`ID`
  LEFT JOIN `companyproject` p4 ON c.`ProjectID` = p4.`ID`
  LEFT JOIN `companyprojectpriority` p5 ON c.`ProjectPriority` = p5.`ID`
  LEFT JOIN `companyprojectstatus` p6 ON c.`ProjectStatusID` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDInput` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDSales` = p8.`ID`
 WHERE  (c.`CompanyCP` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`ProjectPriority` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`ProjectStatusID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p8.`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,
          'companyproject: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproject` 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(), 'c4eedd15645b8b8638eb9d806da7630595495b4d89d1a20815d3a4c9847a39c4', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproject/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 = 'companyproject/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproject`
  ADD CONSTRAINT `companyproject_CompanyCP` FOREIGN KEY (`CompanyCP`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_ProjectPriority` FOREIGN KEY (`ProjectPriority`) REFERENCES `companyprojectpriority` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_ProjectStatusID` FOREIGN KEY (`ProjectStatusID`) REFERENCES `companyprojectstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproject_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(), '5b01502375a1736c8d326a33162d4f60514e5f081d436e71a0065322ff2f3483', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectassignment    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectassignment/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 = 'companyprojectassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyProjectDetailID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyProjectDetailCCID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectStatusID` int DEFAULT NULL,
  ADD INDEX `companyprojectassignment_CompanyProjectDetailCCID` (`CompanyProjectDetailCCID`),
  ADD INDEX `companyprojectassignment_CompanyProjectDetailID` (`CompanyProjectDetailID`),
  ADD INDEX `companyprojectassignment_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectassignment_ProjectStatusID` (`ProjectStatusID`),
  ADD INDEX `companyprojectassignment_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(), '2c78796a3157b84e655df470569961084a1a15bf8b3f8db2b6e5bbfe1bb1fd5c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectassignment/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 = 'companyprojectassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectassignment` c
  LEFT JOIN `companyprojectdetailcc` p0 ON c.`CompanyProjectDetailCCID` = p0.`ID`
  LEFT JOIN `companyprojectdetails` p1 ON c.`CompanyProjectDetailID` = p1.`ID`
  LEFT JOIN `companyproject` p2 ON c.`CompanyProjectID` = p2.`ID`
  LEFT JOIN `companyprojectstatus` p3 ON c.`ProjectStatusID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDInput` = p4.`ID`
   SET
       c.`CompanyProjectDetailCCID` = IF((c.`CompanyProjectDetailCCID` IS NOT NULL AND (c.`CompanyProjectDetailCCID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyProjectDetailCCID`),
       c.`CompanyProjectDetailID` = IF((c.`CompanyProjectDetailID` IS NOT NULL AND (c.`CompanyProjectDetailID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyProjectDetailID`),
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p2.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`ProjectStatusID` = IF((c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ProjectStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p4.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`CompanyProjectDetailCCID` IS NOT NULL AND (c.`CompanyProjectDetailCCID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyProjectDetailID` IS NOT NULL AND (c.`CompanyProjectDetailID` = 0 OR p1.`ID` IS NULL))
    OR (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p3.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p4.`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(), '1a0b19704d5a728fa0f03e96c9e5f1ff142177dd7df2fc3aff9a0730e10c5429', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 5 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 = 'companyprojectassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectassignment` c
  LEFT JOIN `companyprojectdetailcc` p0 ON c.`CompanyProjectDetailCCID` = p0.`ID`
  LEFT JOIN `companyprojectdetails` p1 ON c.`CompanyProjectDetailID` = p1.`ID`
  LEFT JOIN `companyproject` p2 ON c.`CompanyProjectID` = p2.`ID`
  LEFT JOIN `companyprojectstatus` p3 ON c.`ProjectStatusID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDInput` = p4.`ID`
 WHERE  (c.`CompanyProjectDetailCCID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyProjectDetailID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`CompanyProjectID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ProjectStatusID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p4.`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,
          'companyprojectassignment: orphan check OK - 0 rows across 5 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectassignment` 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(), '54b8157093e647d8bf2e389a6427bec04f5572546da2513505af7aea4ece3f1b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectassignment/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 = 'companyprojectassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectassignment`
  ADD CONSTRAINT `companyprojectassignment_CompanyProjectDetailCCID` FOREIGN KEY (`CompanyProjectDetailCCID`) REFERENCES `companyprojectdetailcc` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectassignment_CompanyProjectDetailID` FOREIGN KEY (`CompanyProjectDetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectassignment_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectassignment_ProjectStatusID` FOREIGN KEY (`ProjectStatusID`) REFERENCES `companyprojectstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectassignment_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(), 'bc024daac708e657e0ddbf79f0921f69607fc052458ed5011a2bfa2ba5e5d380', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailccassignment    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailccassignment/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 = 'companyprojectdetailccassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailccassignment`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DetailID` int DEFAULT NULL,
  MODIFY COLUMN `DetailCCID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `ProductID` int DEFAULT NULL,
  MODIFY COLUMN `PriceTypeID` int DEFAULT NULL,
  MODIFY COLUMN `QtTypeID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanID` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailccassignment_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetailccassignment_DetailCCID` (`DetailCCID`),
  ADD INDEX `companyprojectdetailccassignment_DetailID` (`DetailID`),
  ADD INDEX `companyprojectdetailccassignment_PriceTypeID` (`PriceTypeID`),
  ADD INDEX `companyprojectdetailccassignment_PrincipalID` (`PrincipalID`),
  ADD INDEX `companyprojectdetailccassignment_ProductID` (`ProductID`),
  ADD INDEX `companyprojectdetailccassignment_QtTypeID` (`QtTypeID`),
  ADD INDEX `companyprojectdetailccassignment_SatuanID` (`SatuanID`),
  ADD INDEX `companyprojectdetailccassignment_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(), 'd6576ada7a1d30cfd59859673c2f7cca76449912fb38fb769184bd67ca3bced6', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailccassignment/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 = 'companyprojectdetailccassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailccassignment` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetailcc` p1 ON c.`DetailCCID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `pricetype` p3 ON c.`PriceTypeID` = p3.`ID`
  LEFT JOIN `principal` p4 ON c.`PrincipalID` = p4.`ID`
  LEFT JOIN `barang` p5 ON c.`ProductID` = p5.`ID`
  LEFT JOIN `quantitytype` p6 ON c.`QtTypeID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanID` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDInput` = p8.`ID`
   SET
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DetailCCID` = IF((c.`DetailCCID` IS NOT NULL AND (c.`DetailCCID` = 0 OR p1.`ID` IS NULL)), NULL, c.`DetailCCID`),
       c.`DetailID` = IF((c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DetailID`),
       c.`PriceTypeID` = IF((c.`PriceTypeID` IS NOT NULL AND (c.`PriceTypeID` = 0 OR p3.`ID` IS NULL)), NULL, c.`PriceTypeID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p4.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`ProductID` = IF((c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p5.`ID` IS NULL)), NULL, c.`ProductID`),
       c.`QtTypeID` = IF((c.`QtTypeID` IS NOT NULL AND (c.`QtTypeID` = 0 OR p6.`ID` IS NULL)), NULL, c.`QtTypeID`),
       c.`SatuanID` = IF((c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p7.`ID` IS NULL)), NULL, c.`SatuanID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p8.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL))
    OR (c.`DetailCCID` IS NOT NULL AND (c.`DetailCCID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL))
    OR (c.`PriceTypeID` IS NOT NULL AND (c.`PriceTypeID` = 0 OR p3.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p4.`ID` IS NULL))
    OR (c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p5.`ID` IS NULL))
    OR (c.`QtTypeID` IS NOT NULL AND (c.`QtTypeID` = 0 OR p6.`ID` IS NULL))
    OR (c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p7.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p8.`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(), 'fa9389275068b9cd219b4ed2909cb77369aeed1dd3f35ed473517f21d89c9bbc', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailccassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 9 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 = 'companyprojectdetailccassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailccassignment` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetailcc` p1 ON c.`DetailCCID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `pricetype` p3 ON c.`PriceTypeID` = p3.`ID`
  LEFT JOIN `principal` p4 ON c.`PrincipalID` = p4.`ID`
  LEFT JOIN `barang` p5 ON c.`ProductID` = p5.`ID`
  LEFT JOIN `quantitytype` p6 ON c.`QtTypeID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanID` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDInput` = p8.`ID`
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DetailCCID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DetailID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`PriceTypeID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`ProductID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`QtTypeID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`SatuanID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p8.`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,
          'companyprojectdetailccassignment: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailccassignment` 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(), 'a65b7624c4ea484fe030c7a9783590f89b72fb47dd71d4ff59819beb9f31b2d9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailccassignment/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 = 'companyprojectdetailccassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailccassignment`
  ADD CONSTRAINT `companyprojectdetailccassignment_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_DetailCCID` FOREIGN KEY (`DetailCCID`) REFERENCES `companyprojectdetailcc` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_DetailID` FOREIGN KEY (`DetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_PriceTypeID` FOREIGN KEY (`PriceTypeID`) REFERENCES `pricetype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_ProductID` FOREIGN KEY (`ProductID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_QtTypeID` FOREIGN KEY (`QtTypeID`) REFERENCES `quantitytype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_SatuanID` FOREIGN KEY (`SatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailccassignment_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(), 'ca4f4ceeb73e75b694ef7cddea19e4e81c0210fbcd4448ae265242c53a9b80ff', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailcomp    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailcomp/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 = 'companyprojectdetailcomp/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailcomp`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DetailID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalIDComp` int DEFAULT NULL,
  MODIFY COLUMN `ProductIDComp` int DEFAULT NULL,
  MODIFY COLUMN `PriceTypeIDComp` int DEFAULT NULL,
  MODIFY COLUMN `QtTypeIDComp` int DEFAULT NULL,
  MODIFY COLUMN `SatuanIDComp` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailcomp_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetailcomp_DetailID` (`DetailID`),
  ADD INDEX `companyprojectdetailcomp_PriceTypeIDComp` (`PriceTypeIDComp`),
  ADD INDEX `companyprojectdetailcomp_PrincipalIDComp` (`PrincipalIDComp`),
  ADD INDEX `companyprojectdetailcomp_ProductIDComp` (`ProductIDComp`),
  ADD INDEX `companyprojectdetailcomp_QtTypeIDComp` (`QtTypeIDComp`),
  ADD INDEX `companyprojectdetailcomp_SatuanIDComp` (`SatuanIDComp`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '7e14faf116fdf17e79132f5ece296adc50d32020e8064dbf5bd2d7e65fd88f43', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailcomp/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 = 'companyprojectdetailcomp/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailcomp` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetails` p1 ON c.`DetailID` = p1.`ID`
  LEFT JOIN `pricetype` p2 ON c.`PriceTypeIDComp` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`PrincipalIDComp` = p3.`ID`
  LEFT JOIN `barang` p4 ON c.`ProductIDComp` = p4.`ID`
  LEFT JOIN `quantitytype` p5 ON c.`QtTypeIDComp` = p5.`ID`
  LEFT JOIN `satuan` p6 ON c.`SatuanIDComp` = p6.`ID`
   SET
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DetailID` = IF((c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p1.`ID` IS NULL)), NULL, c.`DetailID`),
       c.`PriceTypeIDComp` = IF((c.`PriceTypeIDComp` IS NOT NULL AND (c.`PriceTypeIDComp` = 0 OR p2.`ID` IS NULL)), NULL, c.`PriceTypeIDComp`),
       c.`PrincipalIDComp` = IF((c.`PrincipalIDComp` IS NOT NULL AND (c.`PrincipalIDComp` = 0 OR p3.`ID` IS NULL)), NULL, c.`PrincipalIDComp`),
       c.`ProductIDComp` = IF((c.`ProductIDComp` IS NOT NULL AND (c.`ProductIDComp` = 0 OR p4.`ID` IS NULL)), NULL, c.`ProductIDComp`),
       c.`QtTypeIDComp` = IF((c.`QtTypeIDComp` IS NOT NULL AND (c.`QtTypeIDComp` = 0 OR p5.`ID` IS NULL)), NULL, c.`QtTypeIDComp`),
       c.`SatuanIDComp` = IF((c.`SatuanIDComp` IS NOT NULL AND (c.`SatuanIDComp` = 0 OR p6.`ID` IS NULL)), NULL, c.`SatuanIDComp`)
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL))
    OR (c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p1.`ID` IS NULL))
    OR (c.`PriceTypeIDComp` IS NOT NULL AND (c.`PriceTypeIDComp` = 0 OR p2.`ID` IS NULL))
    OR (c.`PrincipalIDComp` IS NOT NULL AND (c.`PrincipalIDComp` = 0 OR p3.`ID` IS NULL))
    OR (c.`ProductIDComp` IS NOT NULL AND (c.`ProductIDComp` = 0 OR p4.`ID` IS NULL))
    OR (c.`QtTypeIDComp` IS NOT NULL AND (c.`QtTypeIDComp` = 0 OR p5.`ID` IS NULL))
    OR (c.`SatuanIDComp` IS NOT NULL AND (c.`SatuanIDComp` = 0 OR p6.`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(), '0514ae04c60bc5ccca85793e678163568fe4fb926ce443ff2e19a7a3527044a3', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailcomp/30_assert  --  source section 7b
-- Orphan assertion over this table's 7 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 = 'companyprojectdetailcomp/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailcomp` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetails` p1 ON c.`DetailID` = p1.`ID`
  LEFT JOIN `pricetype` p2 ON c.`PriceTypeIDComp` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`PrincipalIDComp` = p3.`ID`
  LEFT JOIN `barang` p4 ON c.`ProductIDComp` = p4.`ID`
  LEFT JOIN `quantitytype` p5 ON c.`QtTypeIDComp` = p5.`ID`
  LEFT JOIN `satuan` p6 ON c.`SatuanIDComp` = p6.`ID`
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DetailID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`PriceTypeIDComp` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`PrincipalIDComp` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ProductIDComp` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`QtTypeIDComp` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`SatuanIDComp` IS NOT NULL AND p6.`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,
          'companyprojectdetailcomp: orphan check OK - 0 rows across 7 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailcomp` 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(), 'e42ae917d0e8f1470a490ece20322d12ebec96009adea2628ee2acb7c2940303', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailcomp/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 = 'companyprojectdetailcomp/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailcomp`
  ADD CONSTRAINT `companyprojectdetailcomp_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcomp_DetailID` FOREIGN KEY (`DetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcomp_PriceTypeIDComp` FOREIGN KEY (`PriceTypeIDComp`) REFERENCES `pricetype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcomp_PrincipalIDComp` FOREIGN KEY (`PrincipalIDComp`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcomp_ProductIDComp` FOREIGN KEY (`ProductIDComp`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcomp_QtTypeIDComp` FOREIGN KEY (`QtTypeIDComp`) REFERENCES `quantitytype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcomp_SatuanIDComp` FOREIGN KEY (`SatuanIDComp`) REFERENCES `satuan` (`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(), 'b285ec085e22c3d55d7e5ea435cded8b14a97986df290d75ff9fd868c4292c4e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailcompassignment    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailcompassignment/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 = 'companyprojectdetailcompassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailcompassignment`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DetailID` int DEFAULT NULL,
  MODIFY COLUMN `DetailCompID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalIDComp` int DEFAULT NULL,
  MODIFY COLUMN `ProductIDComp` int DEFAULT NULL,
  MODIFY COLUMN `PriceTypeIDComp` int DEFAULT NULL,
  MODIFY COLUMN `QtTypeIDComp` int DEFAULT NULL,
  MODIFY COLUMN `SatuanIDComp` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailcompassignment_CompanyProjectIDID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetailcompassignment_DetailCompID` (`DetailCompID`),
  ADD INDEX `companyprojectdetailcompassignment_DetailID` (`DetailID`),
  ADD INDEX `companyprojectdetailcompassignment_PriceTypeIDComp` (`PriceTypeIDComp`),
  ADD INDEX `companyprojectdetailcompassignment_PrincipalIDComp` (`PrincipalIDComp`),
  ADD INDEX `companyprojectdetailcompassignment_ProductIDComp` (`ProductIDComp`),
  ADD INDEX `companyprojectdetailcompassignment_QtTypeIDComp` (`QtTypeIDComp`),
  ADD INDEX `companyprojectdetailcompassignment_SatuanIDComp` (`SatuanIDComp`),
  ADD INDEX `companyprojectdetailcompassignment_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(), 'c28dd4c5422d1837cda709c39d3c177ec260f93815810299eb39fe939b46f441', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailcompassignment/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 = 'companyprojectdetailcompassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailcompassignment` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetailcomp` p1 ON c.`DetailCompID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `pricetype` p3 ON c.`PriceTypeIDComp` = p3.`ID`
  LEFT JOIN `principal` p4 ON c.`PrincipalIDComp` = p4.`ID`
  LEFT JOIN `barang` p5 ON c.`ProductIDComp` = p5.`ID`
  LEFT JOIN `quantitytype` p6 ON c.`QtTypeIDComp` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanIDComp` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDInput` = p8.`ID`
   SET
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DetailCompID` = IF((c.`DetailCompID` IS NOT NULL AND (c.`DetailCompID` = 0 OR p1.`ID` IS NULL)), NULL, c.`DetailCompID`),
       c.`DetailID` = IF((c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DetailID`),
       c.`PriceTypeIDComp` = IF((c.`PriceTypeIDComp` IS NOT NULL AND (c.`PriceTypeIDComp` = 0 OR p3.`ID` IS NULL)), NULL, c.`PriceTypeIDComp`),
       c.`PrincipalIDComp` = IF((c.`PrincipalIDComp` IS NOT NULL AND (c.`PrincipalIDComp` = 0 OR p4.`ID` IS NULL)), NULL, c.`PrincipalIDComp`),
       c.`ProductIDComp` = IF((c.`ProductIDComp` IS NOT NULL AND (c.`ProductIDComp` = 0 OR p5.`ID` IS NULL)), NULL, c.`ProductIDComp`),
       c.`QtTypeIDComp` = IF((c.`QtTypeIDComp` IS NOT NULL AND (c.`QtTypeIDComp` = 0 OR p6.`ID` IS NULL)), NULL, c.`QtTypeIDComp`),
       c.`SatuanIDComp` = IF((c.`SatuanIDComp` IS NOT NULL AND (c.`SatuanIDComp` = 0 OR p7.`ID` IS NULL)), NULL, c.`SatuanIDComp`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p8.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL))
    OR (c.`DetailCompID` IS NOT NULL AND (c.`DetailCompID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL))
    OR (c.`PriceTypeIDComp` IS NOT NULL AND (c.`PriceTypeIDComp` = 0 OR p3.`ID` IS NULL))
    OR (c.`PrincipalIDComp` IS NOT NULL AND (c.`PrincipalIDComp` = 0 OR p4.`ID` IS NULL))
    OR (c.`ProductIDComp` IS NOT NULL AND (c.`ProductIDComp` = 0 OR p5.`ID` IS NULL))
    OR (c.`QtTypeIDComp` IS NOT NULL AND (c.`QtTypeIDComp` = 0 OR p6.`ID` IS NULL))
    OR (c.`SatuanIDComp` IS NOT NULL AND (c.`SatuanIDComp` = 0 OR p7.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p8.`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(), 'a54c23a9602d2066caabd4571b883683dffaca0620b300be04a8a9282a52f71d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailcompassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 9 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 = 'companyprojectdetailcompassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailcompassignment` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetailcomp` p1 ON c.`DetailCompID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `pricetype` p3 ON c.`PriceTypeIDComp` = p3.`ID`
  LEFT JOIN `principal` p4 ON c.`PrincipalIDComp` = p4.`ID`
  LEFT JOIN `barang` p5 ON c.`ProductIDComp` = p5.`ID`
  LEFT JOIN `quantitytype` p6 ON c.`QtTypeIDComp` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanIDComp` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDInput` = p8.`ID`
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DetailCompID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DetailID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`PriceTypeIDComp` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`PrincipalIDComp` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`ProductIDComp` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`QtTypeIDComp` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`SatuanIDComp` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p8.`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,
          'companyprojectdetailcompassignment: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailcompassignment` 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(), 'c84610b3a7bd7b8678a39339c8606bf257f8ae499474b64392f8eb52074957b5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailcompassignment/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 = 'companyprojectdetailcompassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailcompassignment`
  ADD CONSTRAINT `companyprojectdetailcompassignment_CompanyProjectIDID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_DetailCompID` FOREIGN KEY (`DetailCompID`) REFERENCES `companyprojectdetailcomp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_DetailID` FOREIGN KEY (`DetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_PriceTypeIDComp` FOREIGN KEY (`PriceTypeIDComp`) REFERENCES `pricetype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_PrincipalIDComp` FOREIGN KEY (`PrincipalIDComp`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_ProductIDComp` FOREIGN KEY (`ProductIDComp`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_QtTypeIDComp` FOREIGN KEY (`QtTypeIDComp`) REFERENCES `quantitytype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_SatuanIDComp` FOREIGN KEY (`SatuanIDComp`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcompassignment_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(), '2bce5fd2b193a39677459fdb452d6b05af14dfd5f921bfc50c24ccfd00669ecd', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailsassignment    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailsassignment/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 = 'companyprojectdetailsassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailsassignment`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DetailID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `OpportunityGroupID` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailsassignment_ApplicationID` (`ApplicationID`),
  ADD INDEX `companyprojectdetailsassignment_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetailsassignment_DetailID` (`DetailID`),
  ADD INDEX `companyprojectdetailsassignment_OpportunityGroupID` (`OpportunityGroupID`),
  ADD INDEX `companyprojectdetailsassignment_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(), '06621fafed046ef5f696c56eb0b62bd60463e8bef601b6e1d7cb61641a62d89a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailsassignment/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 = 'companyprojectdetailsassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailsassignment` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `companyproject` p1 ON c.`CompanyProjectID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `companyprojectopportunitygroup` p3 ON c.`OpportunityGroupID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDInput` = p4.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DetailID` = IF((c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DetailID`),
       c.`OpportunityGroupID` = IF((c.`OpportunityGroupID` IS NOT NULL AND (c.`OpportunityGroupID` = 0 OR p3.`ID` IS NULL)), NULL, c.`OpportunityGroupID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p4.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL))
    OR (c.`OpportunityGroupID` IS NOT NULL AND (c.`OpportunityGroupID` = 0 OR p3.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p4.`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(), '701dd2d3d287f7e690b94df5ba8b4fad9f7f5c1accd6d8034ba640990a7ae947', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailsassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 5 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 = 'companyprojectdetailsassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailsassignment` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `companyproject` p1 ON c.`CompanyProjectID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `companyprojectopportunitygroup` p3 ON c.`OpportunityGroupID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDInput` = p4.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyProjectID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DetailID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`OpportunityGroupID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p4.`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,
          'companyprojectdetailsassignment: orphan check OK - 0 rows across 5 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailsassignment` 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(), 'a7e75c6b100c3d63226965f2a0e0cdaf2ed960217a43e1ec4a2f0bd7f909779d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailsassignment/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 = 'companyprojectdetailsassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailsassignment`
  ADD CONSTRAINT `companyprojectdetailsassignment_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailsassignment_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailsassignment_DetailID` FOREIGN KEY (`DetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailsassignment_OpportunityGroupID` FOREIGN KEY (`OpportunityGroupID`) REFERENCES `companyprojectopportunitygroup` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailsassignment_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(), 'bf82200e4a85422b1a3e596a68425c8ec0be800a9f9cf6dcd7f7ac451dec4d95', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailstatusassignment    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusassignment/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 = 'companyprojectdetailstatusassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailstatusassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DetailID` int DEFAULT NULL,
  MODIFY COLUMN `DetailCCID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ItemStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ItemReasonID` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailstatusassignment_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetailstatusassignment_DetailCCID` (`DetailCCID`),
  ADD INDEX `companyprojectdetailstatusassignment_DetailID` (`DetailID`),
  ADD INDEX `companyprojectdetailstatusassignment_ItemReasonID` (`ItemReasonID`),
  ADD INDEX `companyprojectdetailstatusassignment_ItemStatusID` (`ItemStatusID`),
  ADD INDEX `companyprojectdetailstatusassignment_ProjectStatusID` (`ProjectStatusID`),
  ADD INDEX `companyprojectdetailstatusassignment_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(), '256264a881739474d1c8b6a8f9baa87d598c669a6b1d0fef3b0e8e61eef8df17', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusassignment/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 = 'companyprojectdetailstatusassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailstatusassignment` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetailcc` p1 ON c.`DetailCCID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `companyprojectdetailstatusreason` p3 ON c.`ItemReasonID` = p3.`ID`
  LEFT JOIN `companyprojectdetailstatus` p4 ON c.`ItemStatusID` = p4.`ID`
  LEFT JOIN `companyprojectstatus` p5 ON c.`ProjectStatusID` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDInput` = p6.`ID`
   SET
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DetailCCID` = IF((c.`DetailCCID` IS NOT NULL AND (c.`DetailCCID` = 0 OR p1.`ID` IS NULL)), NULL, c.`DetailCCID`),
       c.`DetailID` = IF((c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DetailID`),
       c.`ItemReasonID` = IF((c.`ItemReasonID` IS NOT NULL AND (c.`ItemReasonID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ItemReasonID`),
       c.`ItemStatusID` = IF((c.`ItemStatusID` IS NOT NULL AND (c.`ItemStatusID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ItemStatusID`),
       c.`ProjectStatusID` = IF((c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p5.`ID` IS NULL)), NULL, c.`ProjectStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p6.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL))
    OR (c.`DetailCCID` IS NOT NULL AND (c.`DetailCCID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ItemReasonID` IS NOT NULL AND (c.`ItemReasonID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ItemStatusID` IS NOT NULL AND (c.`ItemStatusID` = 0 OR p4.`ID` IS NULL))
    OR (c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p5.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p6.`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(), '8fcc1d62f31fa78ca40f877d9c497789b999fc4c13b67d9bf55aff41c4b457fa', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 7 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 = 'companyprojectdetailstatusassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailstatusassignment` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetailcc` p1 ON c.`DetailCCID` = p1.`ID`
  LEFT JOIN `companyprojectdetails` p2 ON c.`DetailID` = p2.`ID`
  LEFT JOIN `companyprojectdetailstatusreason` p3 ON c.`ItemReasonID` = p3.`ID`
  LEFT JOIN `companyprojectdetailstatus` p4 ON c.`ItemStatusID` = p4.`ID`
  LEFT JOIN `companyprojectstatus` p5 ON c.`ProjectStatusID` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDInput` = p6.`ID`
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DetailCCID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DetailID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ItemReasonID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ItemStatusID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`ProjectStatusID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p6.`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,
          'companyprojectdetailstatusassignment: orphan check OK - 0 rows across 7 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailstatusassignment` 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(), '53083b20eccbabb96419b1fe3fc494437da871e5ba401a51988c3420f7e9bc2e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusassignment/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 = 'companyprojectdetailstatusassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailstatusassignment`
  ADD CONSTRAINT `companyprojectdetailstatusassignment_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailstatusassignment_DetailCCID` FOREIGN KEY (`DetailCCID`) REFERENCES `companyprojectdetailcc` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailstatusassignment_DetailID` FOREIGN KEY (`DetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailstatusassignment_ItemReasonID` FOREIGN KEY (`ItemReasonID`) REFERENCES `companyprojectdetailstatusreason` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailstatusassignment_ItemStatusID` FOREIGN KEY (`ItemStatusID`) REFERENCES `companyprojectdetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailstatusassignment_ProjectStatusID` FOREIGN KEY (`ProjectStatusID`) REFERENCES `companyprojectstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailstatusassignment_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(), '63ac7d628feb22eb423095a8e960c1592bc75d7649da34c83514d97931295ea4', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectheaderassignment    (detail, owned by companyproject)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectheaderassignment/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 = 'companyprojectheaderassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectheaderassignment`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` 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 `CompanyCP` int DEFAULT NULL,
  MODIFY COLUMN `ProjectPriority` int DEFAULT NULL,
  ADD INDEX `companyprojectheaderassignment_CompanyCP` (`CompanyCP`),
  ADD INDEX `companyprojectheaderassignment_CompanyID` (`CompanyID`),
  ADD INDEX `companyprojectheaderassignment_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectheaderassignment_DivisionID` (`DivisionID`),
  ADD INDEX `companyprojectheaderassignment_IndustryID` (`IndustryID`),
  ADD INDEX `companyprojectheaderassignment_ProjectID` (`ProjectID`),
  ADD INDEX `companyprojectheaderassignment_ProjectPriority` (`ProjectPriority`),
  ADD INDEX `companyprojectheaderassignment_UserIDInput` (`UserIDInput`),
  ADD INDEX `companyprojectheaderassignment_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(), 'f6731bc3e25d0b70202b9bc28a3a0c0173271719b8970c005507baaace2e9a3c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectheaderassignment/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 = 'companyprojectheaderassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectheaderassignment` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCP` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `companyproject` p2 ON c.`CompanyProjectID` = p2.`ID`
  LEFT JOIN `division` p3 ON c.`DivisionID` = p3.`ID`
  LEFT JOIN `industry` p4 ON c.`IndustryID` = p4.`ID`
  LEFT JOIN `companyproject` p5 ON c.`ProjectID` = p5.`ID`
  LEFT JOIN `companyprojectpriority` p6 ON c.`ProjectPriority` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDInput` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDSales` = p8.`ID`
   SET
       c.`CompanyCP` = IF((c.`CompanyCP` IS NOT NULL AND (c.`CompanyCP` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCP`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p2.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p3.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p4.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p5.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`ProjectPriority` = IF((c.`ProjectPriority` IS NOT NULL AND (c.`ProjectPriority` = 0 OR p6.`ID` IS NULL)), NULL, c.`ProjectPriority`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p7.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p8.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`CompanyCP` IS NOT NULL AND (c.`CompanyCP` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p2.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p3.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p4.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p5.`ID` IS NULL))
    OR (c.`ProjectPriority` IS NOT NULL AND (c.`ProjectPriority` = 0 OR p6.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p7.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p8.`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(), 'bcb74c5e0214bf4c2d841b01842f479b98eaa03d75e6d8b8fd09d7a56e8d0fb5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectheaderassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 9 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 = 'companyprojectheaderassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectheaderassignment` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCP` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `companyproject` p2 ON c.`CompanyProjectID` = p2.`ID`
  LEFT JOIN `division` p3 ON c.`DivisionID` = p3.`ID`
  LEFT JOIN `industry` p4 ON c.`IndustryID` = p4.`ID`
  LEFT JOIN `companyproject` p5 ON c.`ProjectID` = p5.`ID`
  LEFT JOIN `companyprojectpriority` p6 ON c.`ProjectPriority` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDInput` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDSales` = p8.`ID`
 WHERE  (c.`CompanyCP` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`CompanyProjectID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`ProjectPriority` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p8.`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,
          'companyprojectheaderassignment: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectheaderassignment` 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(), '3df48d85f47272aa61cfdc19913d98e653a83f75424a866cb7eba049f5dbf1f9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectheaderassignment/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 = 'companyprojectheaderassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectheaderassignment`
  ADD CONSTRAINT `companyprojectheaderassignment_CompanyCP` FOREIGN KEY (`CompanyCP`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_ProjectPriority` FOREIGN KEY (`ProjectPriority`) REFERENCES `companyprojectpriority` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectheaderassignment_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(), '5f5b07b695b3e9addf54a58f2ac970f54880591973fdf34fd3391ac1a1d11d3f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailcc    (master)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailcc/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 = 'companyprojectdetailcc/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailcc`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DetailID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ItemStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ItemReasonID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `ProductID` int DEFAULT NULL,
  MODIFY COLUMN `PriceTypeID` int DEFAULT NULL,
  MODIFY COLUMN `QtTypeID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanID` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailcc_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetailcc_DetailID` (`DetailID`),
  ADD INDEX `companyprojectdetailcc_ItemReasonID` (`ItemReasonID`),
  ADD INDEX `companyprojectdetailcc_ItemStatusID` (`ItemStatusID`),
  ADD INDEX `companyprojectdetailcc_PriceTypeID` (`PriceTypeID`),
  ADD INDEX `companyprojectdetailcc_PrincipalID` (`PrincipalID`),
  ADD INDEX `companyprojectdetailcc_ProductID` (`ProductID`),
  ADD INDEX `companyprojectdetailcc_ProjectStatusID` (`ProjectStatusID`),
  ADD INDEX `companyprojectdetailcc_QtTypeID` (`QtTypeID`),
  ADD INDEX `companyprojectdetailcc_SatuanID` (`SatuanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '1e5023a9759664579235a93d814a5b428553747175368acaba124d8db39d5ef8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailcc/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 = 'companyprojectdetailcc/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailcc` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetails` p1 ON c.`DetailID` = p1.`ID`
  LEFT JOIN `companyprojectdetailstatusreason` p2 ON c.`ItemReasonID` = p2.`ID`
  LEFT JOIN `companyprojectdetailstatus` p3 ON c.`ItemStatusID` = p3.`ID`
  LEFT JOIN `pricetype` p4 ON c.`PriceTypeID` = p4.`ID`
  LEFT JOIN `principal` p5 ON c.`PrincipalID` = p5.`ID`
  LEFT JOIN `barang` p6 ON c.`ProductID` = p6.`ID`
  LEFT JOIN `companyprojectstatus` p7 ON c.`ProjectStatusID` = p7.`ID`
  LEFT JOIN `quantitytype` p8 ON c.`QtTypeID` = p8.`ID`
  LEFT JOIN `satuan` p9 ON c.`SatuanID` = p9.`ID`
   SET
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`DetailID` = IF((c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p1.`ID` IS NULL)), NULL, c.`DetailID`),
       c.`ItemReasonID` = IF((c.`ItemReasonID` IS NOT NULL AND (c.`ItemReasonID` = 0 OR p2.`ID` IS NULL)), NULL, c.`ItemReasonID`),
       c.`ItemStatusID` = IF((c.`ItemStatusID` IS NOT NULL AND (c.`ItemStatusID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ItemStatusID`),
       c.`PriceTypeID` = IF((c.`PriceTypeID` IS NOT NULL AND (c.`PriceTypeID` = 0 OR p4.`ID` IS NULL)), NULL, c.`PriceTypeID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p5.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`ProductID` = IF((c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p6.`ID` IS NULL)), NULL, c.`ProductID`),
       c.`ProjectStatusID` = IF((c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p7.`ID` IS NULL)), NULL, c.`ProjectStatusID`),
       c.`QtTypeID` = IF((c.`QtTypeID` IS NOT NULL AND (c.`QtTypeID` = 0 OR p8.`ID` IS NULL)), NULL, c.`QtTypeID`),
       c.`SatuanID` = IF((c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p9.`ID` IS NULL)), NULL, c.`SatuanID`)
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p0.`ID` IS NULL))
    OR (c.`DetailID` IS NOT NULL AND (c.`DetailID` = 0 OR p1.`ID` IS NULL))
    OR (c.`ItemReasonID` IS NOT NULL AND (c.`ItemReasonID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ItemStatusID` IS NOT NULL AND (c.`ItemStatusID` = 0 OR p3.`ID` IS NULL))
    OR (c.`PriceTypeID` IS NOT NULL AND (c.`PriceTypeID` = 0 OR p4.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p5.`ID` IS NULL))
    OR (c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p6.`ID` IS NULL))
    OR (c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p7.`ID` IS NULL))
    OR (c.`QtTypeID` IS NOT NULL AND (c.`QtTypeID` = 0 OR p8.`ID` IS NULL))
    OR (c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p9.`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(), 'b748ec9f57704cb21e8eb862f4c26086027d1c468bca213966a02dc65c9fd50a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailcc/30_assert  --  source section 7b
-- Orphan assertion over this table's 10 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 = 'companyprojectdetailcc/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailcc` c
  LEFT JOIN `companyproject` p0 ON c.`CompanyProjectID` = p0.`ID`
  LEFT JOIN `companyprojectdetails` p1 ON c.`DetailID` = p1.`ID`
  LEFT JOIN `companyprojectdetailstatusreason` p2 ON c.`ItemReasonID` = p2.`ID`
  LEFT JOIN `companyprojectdetailstatus` p3 ON c.`ItemStatusID` = p3.`ID`
  LEFT JOIN `pricetype` p4 ON c.`PriceTypeID` = p4.`ID`
  LEFT JOIN `principal` p5 ON c.`PrincipalID` = p5.`ID`
  LEFT JOIN `barang` p6 ON c.`ProductID` = p6.`ID`
  LEFT JOIN `companyprojectstatus` p7 ON c.`ProjectStatusID` = p7.`ID`
  LEFT JOIN `quantitytype` p8 ON c.`QtTypeID` = p8.`ID`
  LEFT JOIN `satuan` p9 ON c.`SatuanID` = p9.`ID`
 WHERE  (c.`CompanyProjectID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DetailID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`ItemReasonID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ItemStatusID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`PriceTypeID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`ProductID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`ProjectStatusID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`QtTypeID` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`SatuanID` IS NOT NULL AND p9.`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,
          'companyprojectdetailcc: orphan check OK - 0 rows across 10 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailcc` 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(), '62b8ab1dbea675c383f8fbc879f66d50484a6e3e20f44bc9aa1693fbe3b48e3f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailcc/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 = 'companyprojectdetailcc/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailcc`
  ADD CONSTRAINT `companyprojectdetailcc_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_DetailID` FOREIGN KEY (`DetailID`) REFERENCES `companyprojectdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_ItemReasonID` FOREIGN KEY (`ItemReasonID`) REFERENCES `companyprojectdetailstatusreason` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_ItemStatusID` FOREIGN KEY (`ItemStatusID`) REFERENCES `companyprojectdetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_PriceTypeID` FOREIGN KEY (`PriceTypeID`) REFERENCES `pricetype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_ProductID` FOREIGN KEY (`ProductID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_ProjectStatusID` FOREIGN KEY (`ProjectStatusID`) REFERENCES `companyprojectstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_QtTypeID` FOREIGN KEY (`QtTypeID`) REFERENCES `quantitytype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetailcc_SatuanID` FOREIGN KEY (`SatuanID`) REFERENCES `satuan` (`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(), '402804b5970abd0f3a32f093780ad3500a84d54a35859bf36f8166cf149a5269', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetails    (master)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetails/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 = 'companyprojectdetails/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetails`
  MODIFY COLUMN `CompanyProjectID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `OpportunityGroupID` int DEFAULT NULL,
  ADD INDEX `companyprojectdetails_ApplicationID` (`ApplicationID`),
  ADD INDEX `companyprojectdetails_CompanyProjectID` (`CompanyProjectID`),
  ADD INDEX `companyprojectdetails_OpportunityGroupID` (`OpportunityGroupID`),
  ADD INDEX `companyprojectdetails_ProjectStatusID` (`ProjectStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'd42cf36e19f4ebe75537cad79d6fac37593f0166c5137ba8918ce5b3ba0955e2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetails/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 = 'companyprojectdetails/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `companyproject` p1 ON c.`CompanyProjectID` = p1.`ID`
  LEFT JOIN `companyprojectopportunitygroup` p2 ON c.`OpportunityGroupID` = p2.`ID`
  LEFT JOIN `companyprojectstatus` p3 ON c.`ProjectStatusID` = p3.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CompanyProjectID` = IF((c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyProjectID`),
       c.`OpportunityGroupID` = IF((c.`OpportunityGroupID` IS NOT NULL AND (c.`OpportunityGroupID` = 0 OR p2.`ID` IS NULL)), NULL, c.`OpportunityGroupID`),
       c.`ProjectStatusID` = IF((c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ProjectStatusID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyProjectID` IS NOT NULL AND (c.`CompanyProjectID` = 0 OR p1.`ID` IS NULL))
    OR (c.`OpportunityGroupID` IS NOT NULL AND (c.`OpportunityGroupID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ProjectStatusID` IS NOT NULL AND (c.`ProjectStatusID` = 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(), 'b7d8d61e2345babb1afdd567373b1319bbadab67aa33c542a59f366dba2392e1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetails/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 = 'companyprojectdetails/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `companyproject` p1 ON c.`CompanyProjectID` = p1.`ID`
  LEFT JOIN `companyprojectopportunitygroup` p2 ON c.`OpportunityGroupID` = p2.`ID`
  LEFT JOIN `companyprojectstatus` p3 ON c.`ProjectStatusID` = p3.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyProjectID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`OpportunityGroupID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ProjectStatusID` 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,
          'companyprojectdetails: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetails` 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(), 'ae5f246f011476a3c60663b2c9786e5692d8aac6cb5a8186b5635228bb92d8e9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetails/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 = 'companyprojectdetails/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetails`
  ADD CONSTRAINT `companyprojectdetails_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetails_CompanyProjectID` FOREIGN KEY (`CompanyProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetails_OpportunityGroupID` FOREIGN KEY (`OpportunityGroupID`) REFERENCES `companyprojectopportunitygroup` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyprojectdetails_ProjectStatusID` FOREIGN KEY (`ProjectStatusID`) REFERENCES `companyprojectstatus` (`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(), '4876527b3d3de07cff29f6c86c73d7b5b55a3e9a7efec6fc7a3c761d9022ff5e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyprojectdetailstatusreason    (detail, owned by companyprojectdetails)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusreason/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 = 'companyprojectdetailstatusreason/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailstatusreason`
  MODIFY COLUMN `StatusID` int DEFAULT NULL,
  ADD INDEX `companyprojectdetailstatusreason_StatusID` (`StatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '2ef0acfd5befa2b040fbe4f8f0c1b64efe7338ed335788dcf790bcb860e71cf5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusreason/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 = 'companyprojectdetailstatusreason/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyprojectdetailstatusreason` c
  LEFT JOIN `companyprojectdetailstatus` p0 ON c.`StatusID` = p0.`ID`
   SET
       c.`StatusID` = IF((c.`StatusID` IS NOT NULL AND (c.`StatusID` = 0 OR p0.`ID` IS NULL)), NULL, c.`StatusID`)
 WHERE  (c.`StatusID` IS NOT NULL AND (c.`StatusID` = 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(), 'b1eba54aa9556d03f13da91935fdcdf911bc07f73b543fd7a46d20bb852f9784', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusreason/30_assert  --  source section 7b
-- Orphan assertion over this table's 1 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 = 'companyprojectdetailstatusreason/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyprojectdetailstatusreason` c
  LEFT JOIN `companyprojectdetailstatus` p0 ON c.`StatusID` = p0.`ID`
 WHERE  (c.`StatusID` 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,
          'companyprojectdetailstatusreason: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyprojectdetailstatusreason` 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(), 'b7f13792f3eb15f32ad6bc202b11f75f1f70b21970b19161147f40823f0725f8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyprojectdetailstatusreason/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 = 'companyprojectdetailstatusreason/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyprojectdetailstatusreason` ADD CONSTRAINT `companyprojectdetailstatusreason_StatusID` FOREIGN KEY (`StatusID`) REFERENCES `companyprojectdetailstatus` (`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(), 'e2e33e6f2dbcbcb2acf79ba1feaf4b7d3072105951d430d64bfa5b7245172829', 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 = 75;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'companyproject.companyproject_CompanyCP' AS n UNION ALL SELECT 'companyproject.companyproject_CompanyID' UNION ALL SELECT 'companyproject.companyproject_DivisionID' UNION ALL SELECT 'companyproject.companyproject_IndustryID' UNION ALL SELECT 'companyproject.companyproject_ProjectID' UNION ALL SELECT 'companyproject.companyproject_ProjectPriority' UNION ALL SELECT 'companyproject.companyproject_ProjectStatusID' UNION ALL SELECT 'companyproject.companyproject_UserIDInput' UNION ALL SELECT 'companyproject.companyproject_UserIDSales' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_CompanyProjectDetailCCID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_CompanyProjectDetailID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_ProjectStatusID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_DetailID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ItemReasonID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ItemStatusID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_PriceTypeID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_PrincipalID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ProductID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ProjectStatusID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_QtTypeID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_SatuanID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_DetailCCID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_DetailID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_PriceTypeID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_PrincipalID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_ProductID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_QtTypeID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_SatuanID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_DetailID' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_PriceTypeIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_PrincipalIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_ProductIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_QtTypeIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_SatuanIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_CompanyProjectIDID' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_DetailCompID' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_DetailID' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_PriceTypeIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_PrincipalIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_ProductIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_QtTypeIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_SatuanIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_ApplicationID' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_CompanyProjectID' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_OpportunityGroupID' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_ProjectStatusID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_ApplicationID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_DetailID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_OpportunityGroupID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_DetailCCID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_DetailID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_ItemReasonID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_ItemStatusID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_ProjectStatusID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailstatusreason.companyprojectdetailstatusreason_StatusID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_CompanyCP' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_CompanyID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_DivisionID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_IndustryID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_ProjectID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_ProjectPriority' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_UserIDInput' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_UserIDSales') _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: col
SET @want_col = 1;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_col, @miss_col
  FROM (SELECT 'companyproject.RemarkSM' AS n) _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', COLUMN_NAME) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE());
SET @have_col = @want_col - @missn_col;
SET @pf_col = IF(@missn_col = 0,
    CONCAT('SELECT ''postflight new columns: ', @have_col, '/', @want_col, ' present'' AS postflight_col'),
    CONCAT('SELECT `ABORT postflight: MISSING new columns: ', @miss_col,
           ' -- ', @missn_col, ' of ', @want_col, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_col; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 75;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'companyproject.companyproject_CompanyCP' AS n UNION ALL SELECT 'companyproject.companyproject_CompanyID' UNION ALL SELECT 'companyproject.companyproject_DivisionID' UNION ALL SELECT 'companyproject.companyproject_IndustryID' UNION ALL SELECT 'companyproject.companyproject_ProjectID' UNION ALL SELECT 'companyproject.companyproject_ProjectPriority' UNION ALL SELECT 'companyproject.companyproject_ProjectStatusID' UNION ALL SELECT 'companyproject.companyproject_UserIDInput' UNION ALL SELECT 'companyproject.companyproject_UserIDSales' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_CompanyProjectDetailCCID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_CompanyProjectDetailID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_ProjectStatusID' UNION ALL SELECT 'companyprojectassignment.companyprojectassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_DetailID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ItemReasonID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ItemStatusID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_PriceTypeID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_PrincipalID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ProductID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_ProjectStatusID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_QtTypeID' UNION ALL SELECT 'companyprojectdetailcc.companyprojectdetailcc_SatuanID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_DetailCCID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_DetailID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_PriceTypeID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_PrincipalID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_ProductID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_QtTypeID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_SatuanID' UNION ALL SELECT 'companyprojectdetailccassignment.companyprojectdetailccassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_DetailID' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_PriceTypeIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_PrincipalIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_ProductIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_QtTypeIDComp' UNION ALL SELECT 'companyprojectdetailcomp.companyprojectdetailcomp_SatuanIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_CompanyProjectIDID' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_DetailCompID' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_DetailID' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_PriceTypeIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_PrincipalIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_ProductIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_QtTypeIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_SatuanIDComp' UNION ALL SELECT 'companyprojectdetailcompassignment.companyprojectdetailcompassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_ApplicationID' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_CompanyProjectID' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_OpportunityGroupID' UNION ALL SELECT 'companyprojectdetails.companyprojectdetails_ProjectStatusID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_ApplicationID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_DetailID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_OpportunityGroupID' UNION ALL SELECT 'companyprojectdetailsassignment.companyprojectdetailsassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_DetailCCID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_DetailID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_ItemReasonID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_ItemStatusID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_ProjectStatusID' UNION ALL SELECT 'companyprojectdetailstatusassignment.companyprojectdetailstatusassignment_UserIDInput' UNION ALL SELECT 'companyprojectdetailstatusreason.companyprojectdetailstatusreason_StatusID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_CompanyCP' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_CompanyID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_CompanyProjectID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_DivisionID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_IndustryID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_ProjectID' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_ProjectPriority' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_UserIDInput' UNION ALL SELECT 'companyprojectheaderassignment.companyprojectheaderassignment_UserIDSales') _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 = 75;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'companyproject.CompanyCP.int' AS n UNION ALL SELECT 'companyproject.CompanyID.int' UNION ALL SELECT 'companyproject.DivisionID.int' UNION ALL SELECT 'companyproject.IndustryID.int' UNION ALL SELECT 'companyproject.ProjectID.int' UNION ALL SELECT 'companyproject.ProjectPriority.int' UNION ALL SELECT 'companyproject.ProjectStatusID.int' UNION ALL SELECT 'companyproject.UserIDInput.int' UNION ALL SELECT 'companyproject.UserIDSales.int' UNION ALL SELECT 'companyprojectassignment.CompanyProjectDetailCCID.int' UNION ALL SELECT 'companyprojectassignment.CompanyProjectDetailID.int' UNION ALL SELECT 'companyprojectassignment.CompanyProjectID.int' UNION ALL SELECT 'companyprojectassignment.ProjectStatusID.int' UNION ALL SELECT 'companyprojectassignment.UserIDInput.int' UNION ALL SELECT 'companyprojectdetailcc.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetailcc.DetailID.int' UNION ALL SELECT 'companyprojectdetailcc.ItemReasonID.int' UNION ALL SELECT 'companyprojectdetailcc.ItemStatusID.int' UNION ALL SELECT 'companyprojectdetailcc.PriceTypeID.int' UNION ALL SELECT 'companyprojectdetailcc.PrincipalID.int' UNION ALL SELECT 'companyprojectdetailcc.ProductID.int' UNION ALL SELECT 'companyprojectdetailcc.ProjectStatusID.int' UNION ALL SELECT 'companyprojectdetailcc.QtTypeID.int' UNION ALL SELECT 'companyprojectdetailcc.SatuanID.int' UNION ALL SELECT 'companyprojectdetailccassignment.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetailccassignment.DetailCCID.int' UNION ALL SELECT 'companyprojectdetailccassignment.DetailID.int' UNION ALL SELECT 'companyprojectdetailccassignment.PriceTypeID.int' UNION ALL SELECT 'companyprojectdetailccassignment.PrincipalID.int' UNION ALL SELECT 'companyprojectdetailccassignment.ProductID.int' UNION ALL SELECT 'companyprojectdetailccassignment.QtTypeID.int' UNION ALL SELECT 'companyprojectdetailccassignment.SatuanID.int' UNION ALL SELECT 'companyprojectdetailccassignment.UserIDInput.int' UNION ALL SELECT 'companyprojectdetailcomp.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetailcomp.DetailID.int' UNION ALL SELECT 'companyprojectdetailcomp.PriceTypeIDComp.int' UNION ALL SELECT 'companyprojectdetailcomp.PrincipalIDComp.int' UNION ALL SELECT 'companyprojectdetailcomp.ProductIDComp.int' UNION ALL SELECT 'companyprojectdetailcomp.QtTypeIDComp.int' UNION ALL SELECT 'companyprojectdetailcomp.SatuanIDComp.int' UNION ALL SELECT 'companyprojectdetailcompassignment.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetailcompassignment.DetailCompID.int' UNION ALL SELECT 'companyprojectdetailcompassignment.DetailID.int' UNION ALL SELECT 'companyprojectdetailcompassignment.PriceTypeIDComp.int' UNION ALL SELECT 'companyprojectdetailcompassignment.PrincipalIDComp.int' UNION ALL SELECT 'companyprojectdetailcompassignment.ProductIDComp.int' UNION ALL SELECT 'companyprojectdetailcompassignment.QtTypeIDComp.int' UNION ALL SELECT 'companyprojectdetailcompassignment.SatuanIDComp.int' UNION ALL SELECT 'companyprojectdetailcompassignment.UserIDInput.int' UNION ALL SELECT 'companyprojectdetails.ApplicationID.int' UNION ALL SELECT 'companyprojectdetails.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetails.OpportunityGroupID.int' UNION ALL SELECT 'companyprojectdetails.ProjectStatusID.int' UNION ALL SELECT 'companyprojectdetailsassignment.ApplicationID.int' UNION ALL SELECT 'companyprojectdetailsassignment.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetailsassignment.DetailID.int' UNION ALL SELECT 'companyprojectdetailsassignment.OpportunityGroupID.int' UNION ALL SELECT 'companyprojectdetailsassignment.UserIDInput.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.CompanyProjectID.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.DetailCCID.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.DetailID.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.ItemReasonID.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.ItemStatusID.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.ProjectStatusID.int' UNION ALL SELECT 'companyprojectdetailstatusassignment.UserIDInput.int' UNION ALL SELECT 'companyprojectdetailstatusreason.StatusID.int' UNION ALL SELECT 'companyprojectheaderassignment.CompanyCP.int' UNION ALL SELECT 'companyprojectheaderassignment.CompanyID.int' UNION ALL SELECT 'companyprojectheaderassignment.CompanyProjectID.int' UNION ALL SELECT 'companyprojectheaderassignment.DivisionID.int' UNION ALL SELECT 'companyprojectheaderassignment.IndustryID.int' UNION ALL SELECT 'companyprojectheaderassignment.ProjectID.int' UNION ALL SELECT 'companyprojectheaderassignment.ProjectPriority.int' UNION ALL SELECT 'companyprojectheaderassignment.UserIDInput.int' UNION ALL SELECT 'companyprojectheaderassignment.UserIDSales.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);
