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

-- Menus this file serves (3 links):
--   /market-surveys
--   /market-surveys/pm
--   /market-surveys/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 ('companyproduct/10_alter', 'companyproduct/20_cleanup', 'companyproduct/30_assert', 'companyproduct/40_fk', 'companyproductapplication/10_alter', 'companyproductapplication/20_cleanup', 'companyproductapplication/30_assert', 'companyproductapplication/40_fk', 'companyproductassignment/10_alter', 'companyproductassignment/20_cleanup', 'companyproductassignment/30_assert', 'companyproductassignment/40_fk', 'companyproductcategory/10_alter', 'companyproductcategory/20_cleanup', 'companyproductcategory/30_assert', 'companyproductcategory/40_fk', 'companyproduction/10_alter', 'companyproduction/20_cleanup', 'companyproduction/30_assert', 'companyproduction/40_fk', 'companyproductionassignment/10_alter', 'companyproductionassignment/20_cleanup', 'companyproductionassignment/30_assert', 'companyproductionassignment/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('companyproduct/10_alter:8378ca149e7515a2418544ddba9296a953feb37f79900ad7e7d69cb0de4d9e9c', 'companyproduct/20_cleanup:044faf7b64f3491148aff161eb89d380f762098f63cf108bf9941ec18bef2f87', 'companyproduct/30_assert:835b875d1406affd4fc202ed271d60e07198115870a0d00953cfc5f5c57a00d1', 'companyproduct/40_fk:de6f58a2d022ad77d9573002cb988a9acc88d9fdbb63d2581a5002f003985ad9', 'companyproductapplication/10_alter:5395e9de0a21afe3cabaf358247c8c6009bad23da96fe934ae036513df5c65eb', 'companyproductapplication/20_cleanup:2462d563de362bda82c610c86b1c431f25501920cb26ee7d2e4a1f4b3ca07078', 'companyproductapplication/30_assert:6596d13c039beae5f57b0f10c4667df54573311ad676ba149f5bef927c70db83', 'companyproductapplication/40_fk:9d703036fa01aac320b67ce309202c6a9d5e777ad1754d8501d67e59e531bc33', 'companyproductassignment/10_alter:cbc618f13c8da64046783ed4b33c12cdbeb59e58e09d0d1358839c3bf06264be', 'companyproductassignment/20_cleanup:9c01b61deba99e0ffb8d657905de5d233573918a837be924faf1e4a97e1eef32', 'companyproductassignment/30_assert:bb5a301840b22c84a6cd64593c60561035c8cb2ae94fd0a8b6cce27ecb2b09e2', 'companyproductassignment/40_fk:49d3890b889b9f07bff6266e753e38a43ba73ad6739f11d486a44519ce307743', 'companyproductcategory/10_alter:24fdd6d5ce1d1864d74f1cb0d92ad72add50c2d574393263cadb273abf30bca5', 'companyproductcategory/20_cleanup:e7db59bad59432833c6b82072a7cf9e5351baf4567badbc1926645c5d3ebfb7b', 'companyproductcategory/30_assert:68afc21842690192cdb34f097c607557fa2f6ad970e5358023db02be8ede55b0', 'companyproductcategory/40_fk:1ba3d1bf3169a94fa64f24b8da4ce6aa61698961abe6beea6396cc5ad2da2fe2', 'companyproduction/10_alter:a7c5b21ddc554569413dc7bdf6761e15a5c262060b8887f1d526ab3090498ef4', 'companyproduction/20_cleanup:84e0391734dd4efd45e52640ffe36d6ec6f7612041d2f8b0db173b5b7bd7e20f', 'companyproduction/30_assert:29f2cb0f31bcc7741922d49b226c92b73141c668740ade5d567909199a7945be', 'companyproduction/40_fk:74ab23c15872f0e0d0ec92d1a7a3cc7c4dd164f6c7fde621aec2d371ef1bb583', 'companyproductionassignment/10_alter:39ef77b811003b945f708cd3b087c5ea97a56e2a400df437770fc90dc8f0fd86', 'companyproductionassignment/20_cleanup:f97d61d658e5a43c41ae2ede912b3d22bc136eca637ee6f77c822fa7dbfe00bc', 'companyproductionassignment/30_assert:bced31bc9cab0c5dda2f7de2d328b143ba771559966dc323e78ba24cb8ce388f', 'companyproductionassignment/40_fk:350d71df8497e0dd489ae35f328713f691d7ea31a0dc2cf8f223ec73ede7d570');
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: companyproduct    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- companyproduct/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 = 'companyproduct/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproduct`
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `CCPrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `CCBarangID` int DEFAULT NULL,
  MODIFY COLUMN `CCVolumeSatuanID` int DEFAULT NULL,
  MODIFY COLUMN `CCPriceSatuanID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorPrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorBarangID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorVolumeSatuanID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorPriceSatuanID` int DEFAULT NULL,
  ADD INDEX `CompanyID` (`CompanyID`,`DivisionID`,`ApplicationID`,`CCPrincipalID`,`CCBarangID`,`CCVolumeSatuanID`,`CCPriceSatuanID`,`CompetitorPrincipalID`,`CompetitorBarangID`,`CompetitorVolumeSatuanID`,`CompetitorPriceSatuanID`),
  ADD INDEX `companyproduct_ApplicationID` (`ApplicationID`),
  ADD INDEX `companyproduct_CCBarangID` (`CCBarangID`),
  ADD INDEX `companyproduct_CCPriceSatuanID` (`CCPriceSatuanID`),
  ADD INDEX `companyproduct_CCPrincipalID` (`CCPrincipalID`),
  ADD INDEX `companyproduct_CCVolumeSatuanID` (`CCVolumeSatuanID`),
  ADD INDEX `companyproduct_CompetitorBarangID` (`CompetitorBarangID`),
  ADD INDEX `companyproduct_CompetitorPriceSatuanID` (`CompetitorPriceSatuanID`),
  ADD INDEX `companyproduct_CompetitorPrincipalID` (`CompetitorPrincipalID`),
  ADD INDEX `companyproduct_CompetitorVolumeSatuanID` (`CompetitorVolumeSatuanID`),
  ADD INDEX `companyproduct_DivisionID` (`DivisionID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '8378ca149e7515a2418544ddba9296a953feb37f79900ad7e7d69cb0de4d9e9c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproduct/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 = 'companyproduct/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproduct` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`CCBarangID` = p1.`ID`
  LEFT JOIN `satuan` p2 ON c.`CCPriceSatuanID` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`CCPrincipalID` = p3.`ID`
  LEFT JOIN `satuan` p4 ON c.`CCVolumeSatuanID` = p4.`ID`
  LEFT JOIN `company` p5 ON c.`CompanyID` = p5.`ID`
  LEFT JOIN `barang` p6 ON c.`CompetitorBarangID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`CompetitorPriceSatuanID` = p7.`ID`
  LEFT JOIN `principal` p8 ON c.`CompetitorPrincipalID` = p8.`ID`
  LEFT JOIN `satuan` p9 ON c.`CompetitorVolumeSatuanID` = p9.`ID`
  LEFT JOIN `division` p10 ON c.`DivisionID` = p10.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CCBarangID` = IF((c.`CCBarangID` IS NOT NULL AND (c.`CCBarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CCBarangID`),
       c.`CCPriceSatuanID` = IF((c.`CCPriceSatuanID` IS NOT NULL AND (c.`CCPriceSatuanID` = 0 OR p2.`ID` IS NULL)), NULL, c.`CCPriceSatuanID`),
       c.`CCPrincipalID` = IF((c.`CCPrincipalID` IS NOT NULL AND (c.`CCPrincipalID` = 0 OR p3.`ID` IS NULL)), NULL, c.`CCPrincipalID`),
       c.`CCVolumeSatuanID` = IF((c.`CCVolumeSatuanID` IS NOT NULL AND (c.`CCVolumeSatuanID` = 0 OR p4.`ID` IS NULL)), NULL, c.`CCVolumeSatuanID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p5.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`CompetitorBarangID` = IF((c.`CompetitorBarangID` IS NOT NULL AND (c.`CompetitorBarangID` = 0 OR p6.`ID` IS NULL)), NULL, c.`CompetitorBarangID`),
       c.`CompetitorPriceSatuanID` = IF((c.`CompetitorPriceSatuanID` IS NOT NULL AND (c.`CompetitorPriceSatuanID` = 0 OR p7.`ID` IS NULL)), NULL, c.`CompetitorPriceSatuanID`),
       c.`CompetitorPrincipalID` = IF((c.`CompetitorPrincipalID` IS NOT NULL AND (c.`CompetitorPrincipalID` = 0 OR p8.`ID` IS NULL)), NULL, c.`CompetitorPrincipalID`),
       c.`CompetitorVolumeSatuanID` = IF((c.`CompetitorVolumeSatuanID` IS NOT NULL AND (c.`CompetitorVolumeSatuanID` = 0 OR p9.`ID` IS NULL)), NULL, c.`CompetitorVolumeSatuanID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p10.`ID` IS NULL)), NULL, c.`DivisionID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CCBarangID` IS NOT NULL AND (c.`CCBarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`CCPriceSatuanID` IS NOT NULL AND (c.`CCPriceSatuanID` = 0 OR p2.`ID` IS NULL))
    OR (c.`CCPrincipalID` IS NOT NULL AND (c.`CCPrincipalID` = 0 OR p3.`ID` IS NULL))
    OR (c.`CCVolumeSatuanID` IS NOT NULL AND (c.`CCVolumeSatuanID` = 0 OR p4.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p5.`ID` IS NULL))
    OR (c.`CompetitorBarangID` IS NOT NULL AND (c.`CompetitorBarangID` = 0 OR p6.`ID` IS NULL))
    OR (c.`CompetitorPriceSatuanID` IS NOT NULL AND (c.`CompetitorPriceSatuanID` = 0 OR p7.`ID` IS NULL))
    OR (c.`CompetitorPrincipalID` IS NOT NULL AND (c.`CompetitorPrincipalID` = 0 OR p8.`ID` IS NULL))
    OR (c.`CompetitorVolumeSatuanID` IS NOT NULL AND (c.`CompetitorVolumeSatuanID` = 0 OR p9.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p10.`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(), '044faf7b64f3491148aff161eb89d380f762098f63cf108bf9941ec18bef2f87', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyproduct/30_assert  --  source section 7b
-- Orphan assertion over this table's 11 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 = 'companyproduct/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproduct` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`CCBarangID` = p1.`ID`
  LEFT JOIN `satuan` p2 ON c.`CCPriceSatuanID` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`CCPrincipalID` = p3.`ID`
  LEFT JOIN `satuan` p4 ON c.`CCVolumeSatuanID` = p4.`ID`
  LEFT JOIN `company` p5 ON c.`CompanyID` = p5.`ID`
  LEFT JOIN `barang` p6 ON c.`CompetitorBarangID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`CompetitorPriceSatuanID` = p7.`ID`
  LEFT JOIN `principal` p8 ON c.`CompetitorPrincipalID` = p8.`ID`
  LEFT JOIN `satuan` p9 ON c.`CompetitorVolumeSatuanID` = p9.`ID`
  LEFT JOIN `division` p10 ON c.`DivisionID` = p10.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CCBarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`CCPriceSatuanID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`CCPrincipalID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`CCVolumeSatuanID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`CompetitorBarangID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`CompetitorPriceSatuanID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`CompetitorPrincipalID` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`CompetitorVolumeSatuanID` IS NOT NULL AND p9.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p10.`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,
          'companyproduct: orphan check OK - 0 rows across 11 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproduct` 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(), '835b875d1406affd4fc202ed271d60e07198115870a0d00953cfc5f5c57a00d1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproduct/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 = 'companyproduct/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproduct`
  ADD CONSTRAINT `companyproduct_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CCBarangID` FOREIGN KEY (`CCBarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CCPriceSatuanID` FOREIGN KEY (`CCPriceSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CCPrincipalID` FOREIGN KEY (`CCPrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CCVolumeSatuanID` FOREIGN KEY (`CCVolumeSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CompetitorBarangID` FOREIGN KEY (`CompetitorBarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CompetitorPriceSatuanID` FOREIGN KEY (`CompetitorPriceSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CompetitorPrincipalID` FOREIGN KEY (`CompetitorPrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_CompetitorVolumeSatuanID` FOREIGN KEY (`CompetitorVolumeSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduct_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`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(), 'de6f58a2d022ad77d9573002cb988a9acc88d9fdbb63d2581a5002f003985ad9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyproductapplication    (detail, owned by companyproduct)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyproductapplication/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 = 'companyproductapplication/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductapplication`
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `ProductApplicationID` int DEFAULT NULL,
  ADD INDEX `companyproductapplication_CompanyID` (`CompanyID`),
  ADD INDEX `companyproductapplication_ProductApplicationID` (`ProductApplicationID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '5395e9de0a21afe3cabaf358247c8c6009bad23da96fe934ae036513df5c65eb', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductapplication/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 = 'companyproductapplication/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproductapplication` c
  LEFT JOIN `company` p0 ON c.`CompanyID` = p0.`ID`
  LEFT JOIN `application` p1 ON c.`ProductApplicationID` = p1.`ID`
   SET
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`ProductApplicationID` = IF((c.`ProductApplicationID` IS NOT NULL AND (c.`ProductApplicationID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ProductApplicationID`)
 WHERE  (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ProductApplicationID` IS NOT NULL AND (c.`ProductApplicationID` = 0 OR p1.`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(), '2462d563de362bda82c610c86b1c431f25501920cb26ee7d2e4a1f4b3ca07078', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyproductapplication/30_assert  --  source section 7b
-- Orphan assertion over this table's 2 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 = 'companyproductapplication/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproductapplication` c
  LEFT JOIN `company` p0 ON c.`CompanyID` = p0.`ID`
  LEFT JOIN `application` p1 ON c.`ProductApplicationID` = p1.`ID`
 WHERE  (c.`CompanyID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ProductApplicationID` IS NOT NULL AND p1.`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,
          'companyproductapplication: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproductapplication` 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(), '6596d13c039beae5f57b0f10c4667df54573311ad676ba149f5bef927c70db83', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductapplication/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 = 'companyproductapplication/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductapplication`
  ADD CONSTRAINT `companyproductapplication_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductapplication_ProductApplicationID` FOREIGN KEY (`ProductApplicationID`) REFERENCES `application` (`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(), '9d703036fa01aac320b67ce309202c6a9d5e777ad1754d8501d67e59e531bc33', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyproductassignment    (detail, owned by companyproduct)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyproductassignment/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 = 'companyproductassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductassignment`
  MODIFY COLUMN `UsersID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyProductID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `CCPrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `CCBarangID` int DEFAULT NULL,
  MODIFY COLUMN `CCVolumeSatuanID` int DEFAULT NULL,
  MODIFY COLUMN `CCPriceSatuanID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorPrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorBarangID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorVolumeSatuanID` int DEFAULT NULL,
  MODIFY COLUMN `CompetitorPriceSatuanID` int DEFAULT NULL,
  ADD INDEX `companyproductassignment_ApplicationID` (`ApplicationID`),
  ADD INDEX `companyproductassignment_CCBarangID` (`CCBarangID`),
  ADD INDEX `companyproductassignment_CCPriceSatuanID` (`CCPriceSatuanID`),
  ADD INDEX `companyproductassignment_CCPrincipalID` (`CCPrincipalID`),
  ADD INDEX `companyproductassignment_CCVolumeSatuanID` (`CCVolumeSatuanID`),
  ADD INDEX `companyproductassignment_CompanyID` (`CompanyID`),
  ADD INDEX `companyproductassignment_CompanyProductID` (`CompanyProductID`),
  ADD INDEX `companyproductassignment_CompetitorBarangID` (`CompetitorBarangID`),
  ADD INDEX `companyproductassignment_CompetitorPriceSatuanID` (`CompetitorPriceSatuanID`),
  ADD INDEX `companyproductassignment_CompetitorPrincipalID` (`CompetitorPrincipalID`),
  ADD INDEX `companyproductassignment_CompetitorVolumeSatuanID` (`CompetitorVolumeSatuanID`),
  ADD INDEX `companyproductassignment_DivisionID` (`DivisionID`),
  ADD INDEX `UsersID` (`UsersID`,`CompanyProductID`,`CompanyID`,`DivisionID`,`ApplicationID`,`CCPrincipalID`,`CCBarangID`,`CCVolumeSatuanID`,`CCPriceSatuanID`,`CompetitorPrincipalID`,`CompetitorBarangID`,`CompetitorVolumeSatuanID`,`CompetitorPriceSatuanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'cbc618f13c8da64046783ed4b33c12cdbeb59e58e09d0d1358839c3bf06264be', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductassignment/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 = 'companyproductassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproductassignment` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`CCBarangID` = p1.`ID`
  LEFT JOIN `satuan` p2 ON c.`CCPriceSatuanID` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`CCPrincipalID` = p3.`ID`
  LEFT JOIN `satuan` p4 ON c.`CCVolumeSatuanID` = p4.`ID`
  LEFT JOIN `company` p5 ON c.`CompanyID` = p5.`ID`
  LEFT JOIN `companyproduct` p6 ON c.`CompanyProductID` = p6.`ID`
  LEFT JOIN `barang` p7 ON c.`CompetitorBarangID` = p7.`ID`
  LEFT JOIN `satuan` p8 ON c.`CompetitorPriceSatuanID` = p8.`ID`
  LEFT JOIN `principal` p9 ON c.`CompetitorPrincipalID` = p9.`ID`
  LEFT JOIN `satuan` p10 ON c.`CompetitorVolumeSatuanID` = p10.`ID`
  LEFT JOIN `division` p11 ON c.`DivisionID` = p11.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CCBarangID` = IF((c.`CCBarangID` IS NOT NULL AND (c.`CCBarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CCBarangID`),
       c.`CCPriceSatuanID` = IF((c.`CCPriceSatuanID` IS NOT NULL AND (c.`CCPriceSatuanID` = 0 OR p2.`ID` IS NULL)), NULL, c.`CCPriceSatuanID`),
       c.`CCPrincipalID` = IF((c.`CCPrincipalID` IS NOT NULL AND (c.`CCPrincipalID` = 0 OR p3.`ID` IS NULL)), NULL, c.`CCPrincipalID`),
       c.`CCVolumeSatuanID` = IF((c.`CCVolumeSatuanID` IS NOT NULL AND (c.`CCVolumeSatuanID` = 0 OR p4.`ID` IS NULL)), NULL, c.`CCVolumeSatuanID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p5.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`CompanyProductID` = IF((c.`CompanyProductID` IS NOT NULL AND (c.`CompanyProductID` = 0 OR p6.`ID` IS NULL)), NULL, c.`CompanyProductID`),
       c.`CompetitorBarangID` = IF((c.`CompetitorBarangID` IS NOT NULL AND (c.`CompetitorBarangID` = 0 OR p7.`ID` IS NULL)), NULL, c.`CompetitorBarangID`),
       c.`CompetitorPriceSatuanID` = IF((c.`CompetitorPriceSatuanID` IS NOT NULL AND (c.`CompetitorPriceSatuanID` = 0 OR p8.`ID` IS NULL)), NULL, c.`CompetitorPriceSatuanID`),
       c.`CompetitorPrincipalID` = IF((c.`CompetitorPrincipalID` IS NOT NULL AND (c.`CompetitorPrincipalID` = 0 OR p9.`ID` IS NULL)), NULL, c.`CompetitorPrincipalID`),
       c.`CompetitorVolumeSatuanID` = IF((c.`CompetitorVolumeSatuanID` IS NOT NULL AND (c.`CompetitorVolumeSatuanID` = 0 OR p10.`ID` IS NULL)), NULL, c.`CompetitorVolumeSatuanID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p11.`ID` IS NULL)), NULL, c.`DivisionID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CCBarangID` IS NOT NULL AND (c.`CCBarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`CCPriceSatuanID` IS NOT NULL AND (c.`CCPriceSatuanID` = 0 OR p2.`ID` IS NULL))
    OR (c.`CCPrincipalID` IS NOT NULL AND (c.`CCPrincipalID` = 0 OR p3.`ID` IS NULL))
    OR (c.`CCVolumeSatuanID` IS NOT NULL AND (c.`CCVolumeSatuanID` = 0 OR p4.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p5.`ID` IS NULL))
    OR (c.`CompanyProductID` IS NOT NULL AND (c.`CompanyProductID` = 0 OR p6.`ID` IS NULL))
    OR (c.`CompetitorBarangID` IS NOT NULL AND (c.`CompetitorBarangID` = 0 OR p7.`ID` IS NULL))
    OR (c.`CompetitorPriceSatuanID` IS NOT NULL AND (c.`CompetitorPriceSatuanID` = 0 OR p8.`ID` IS NULL))
    OR (c.`CompetitorPrincipalID` IS NOT NULL AND (c.`CompetitorPrincipalID` = 0 OR p9.`ID` IS NULL))
    OR (c.`CompetitorVolumeSatuanID` IS NOT NULL AND (c.`CompetitorVolumeSatuanID` = 0 OR p10.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p11.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
SET @sql = IF(@todo, 'UPDATE `companyproductassignment` c
  LEFT JOIN `users` p0 ON c.`UsersID` = p0.`ID`
   SET
       c.`UsersID` = IF((c.`UsersID` IS NOT NULL AND (c.`UsersID` = 0 OR p0.`ID` IS NULL)), NULL, c.`UsersID`)
 WHERE  (c.`UsersID` IS NOT NULL AND (c.`UsersID` = 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(), '9c01b61deba99e0ffb8d657905de5d233573918a837be924faf1e4a97e1eef32', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'companyproductassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproductassignment` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`CCBarangID` = p1.`ID`
  LEFT JOIN `satuan` p2 ON c.`CCPriceSatuanID` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`CCPrincipalID` = p3.`ID`
  LEFT JOIN `satuan` p4 ON c.`CCVolumeSatuanID` = p4.`ID`
  LEFT JOIN `company` p5 ON c.`CompanyID` = p5.`ID`
  LEFT JOIN `companyproduct` p6 ON c.`CompanyProductID` = p6.`ID`
  LEFT JOIN `barang` p7 ON c.`CompetitorBarangID` = p7.`ID`
  LEFT JOIN `satuan` p8 ON c.`CompetitorPriceSatuanID` = p8.`ID`
  LEFT JOIN `principal` p9 ON c.`CompetitorPrincipalID` = p9.`ID`
  LEFT JOIN `satuan` p10 ON c.`CompetitorVolumeSatuanID` = p10.`ID`
  LEFT JOIN `division` p11 ON c.`DivisionID` = p11.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CCBarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`CCPriceSatuanID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`CCPrincipalID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`CCVolumeSatuanID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`CompanyProductID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`CompetitorBarangID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`CompetitorPriceSatuanID` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`CompetitorPrincipalID` IS NOT NULL AND p9.`ID` IS NULL)
    OR (c.`CompetitorVolumeSatuanID` IS NOT NULL AND p10.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p11.`ID` IS NULL);
SET @orphans = @orphans + @n;
SELECT COUNT(*) INTO @n FROM `companyproductassignment` c
  LEFT JOIN `users` p0 ON c.`UsersID` = p0.`ID`
 WHERE  (c.`UsersID` 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,
          'companyproductassignment: orphan check OK - 0 rows across 13 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproductassignment` 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(), 'bb5a301840b22c84a6cd64593c60561035c8cb2ae94fd0a8b6cce27ecb2b09e2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductassignment/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 = 'companyproductassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductassignment`
  ADD CONSTRAINT `companyproductassignment_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CCBarangID` FOREIGN KEY (`CCBarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CCPriceSatuanID` FOREIGN KEY (`CCPriceSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CCPrincipalID` FOREIGN KEY (`CCPrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CCVolumeSatuanID` FOREIGN KEY (`CCVolumeSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CompanyProductID` FOREIGN KEY (`CompanyProductID`) REFERENCES `companyproduct` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CompetitorBarangID` FOREIGN KEY (`CompetitorBarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CompetitorPriceSatuanID` FOREIGN KEY (`CompetitorPriceSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CompetitorPrincipalID` FOREIGN KEY (`CompetitorPrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_CompetitorVolumeSatuanID` FOREIGN KEY (`CompetitorVolumeSatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductassignment_UsersID` FOREIGN KEY (`UsersID`) 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(), '49d3890b889b9f07bff6266e753e38a43ba73ad6739f11d486a44519ce307743', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyproductcategory    (detail, owned by companyproduct)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyproductcategory/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 = 'companyproductcategory/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductcategory`
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `ProductCategoryID` int DEFAULT NULL,
  ADD INDEX `companyproductcategory_CompanyID` (`CompanyID`),
  ADD INDEX `companyproductcategory_ProductCategoryID` (`ProductCategoryID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '24fdd6d5ce1d1864d74f1cb0d92ad72add50c2d574393263cadb273abf30bca5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductcategory/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 = 'companyproductcategory/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproductcategory` c
  LEFT JOIN `company` p0 ON c.`CompanyID` = p0.`ID`
  LEFT JOIN `category` p1 ON c.`ProductCategoryID` = p1.`ID`
   SET
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`ProductCategoryID` = IF((c.`ProductCategoryID` IS NOT NULL AND (c.`ProductCategoryID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ProductCategoryID`)
 WHERE  (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ProductCategoryID` IS NOT NULL AND (c.`ProductCategoryID` = 0 OR p1.`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(), 'e7db59bad59432833c6b82072a7cf9e5351baf4567badbc1926645c5d3ebfb7b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyproductcategory/30_assert  --  source section 7b
-- Orphan assertion over this table's 2 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 = 'companyproductcategory/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproductcategory` c
  LEFT JOIN `company` p0 ON c.`CompanyID` = p0.`ID`
  LEFT JOIN `category` p1 ON c.`ProductCategoryID` = p1.`ID`
 WHERE  (c.`CompanyID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ProductCategoryID` IS NOT NULL AND p1.`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,
          'companyproductcategory: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproductcategory` 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(), '68afc21842690192cdb34f097c607557fa2f6ad970e5358023db02be8ede55b0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductcategory/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 = 'companyproductcategory/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductcategory`
  ADD CONSTRAINT `companyproductcategory_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductcategory_ProductCategoryID` FOREIGN KEY (`ProductCategoryID`) REFERENCES `category` (`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(), '1ba3d1bf3169a94fa64f24b8da4ce6aa61698961abe6beea6396cc5ad2da2fe2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyproduction    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- companyproduction/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 = 'companyproduction/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproduction`
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `VolumeSatuanID` int DEFAULT NULL,
  ADD INDEX `CompanyID` (`CompanyID`,`DivisionID`,`ApplicationID`,`VolumeSatuanID`),
  ADD INDEX `companyproduction_ApplicationID` (`ApplicationID`),
  ADD INDEX `companyproduction_DivisionID` (`DivisionID`),
  ADD INDEX `companyproduction_VolumeSatuanID` (`VolumeSatuanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a7c5b21ddc554569413dc7bdf6761e15a5c262060b8887f1d526ab3090498ef4', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproduction/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 = 'companyproduction/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproduction` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `satuan` p3 ON c.`VolumeSatuanID` = p3.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`VolumeSatuanID` = IF((c.`VolumeSatuanID` IS NOT NULL AND (c.`VolumeSatuanID` = 0 OR p3.`ID` IS NULL)), NULL, c.`VolumeSatuanID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL))
    OR (c.`VolumeSatuanID` IS NOT NULL AND (c.`VolumeSatuanID` = 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(), '84e0391734dd4efd45e52640ffe36d6ec6f7612041d2f8b0db173b5b7bd7e20f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyproduction/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 = 'companyproduction/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproduction` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `satuan` p3 ON c.`VolumeSatuanID` = p3.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`VolumeSatuanID` 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,
          'companyproduction: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproduction` 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(), '29f2cb0f31bcc7741922d49b226c92b73141c668740ade5d567909199a7945be', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproduction/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 = 'companyproduction/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproduction`
  ADD CONSTRAINT `companyproduction_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduction_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduction_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproduction_VolumeSatuanID` FOREIGN KEY (`VolumeSatuanID`) 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(), '74ab23c15872f0e0d0ec92d1a7a3cc7c4dd164f6c7fde621aec2d371ef1bb583', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: companyproductionassignment    (detail, owned by companyproduction)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- companyproductionassignment/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 = 'companyproductionassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductionassignment`
  MODIFY COLUMN `UsersID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyProductionID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `VolumeSatuanID` int DEFAULT NULL,
  ADD INDEX `companyproductionassignment_ApplicationID` (`ApplicationID`),
  ADD INDEX `companyproductionassignment_CompanyID` (`CompanyID`),
  ADD INDEX `companyproductionassignment_CompanyProductionID` (`CompanyProductionID`),
  ADD INDEX `companyproductionassignment_DivisionID` (`DivisionID`),
  ADD INDEX `companyproductionassignment_VolumeSatuanID` (`VolumeSatuanID`),
  ADD INDEX `UsersID` (`UsersID`,`CompanyProductionID`,`CompanyID`,`DivisionID`,`ApplicationID`,`VolumeSatuanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '39ef77b811003b945f708cd3b087c5ea97a56e2a400df437770fc90dc8f0fd86', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductionassignment/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 = 'companyproductionassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `companyproductionassignment` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `companyproduction` p2 ON c.`CompanyProductionID` = p2.`ID`
  LEFT JOIN `division` p3 ON c.`DivisionID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UsersID` = p4.`ID`
  LEFT JOIN `satuan` p5 ON c.`VolumeSatuanID` = p5.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`CompanyProductionID` = IF((c.`CompanyProductionID` IS NOT NULL AND (c.`CompanyProductionID` = 0 OR p2.`ID` IS NULL)), NULL, c.`CompanyProductionID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p3.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`UsersID` = IF((c.`UsersID` IS NOT NULL AND (c.`UsersID` = 0 OR p4.`ID` IS NULL)), NULL, c.`UsersID`),
       c.`VolumeSatuanID` = IF((c.`VolumeSatuanID` IS NOT NULL AND (c.`VolumeSatuanID` = 0 OR p5.`ID` IS NULL)), NULL, c.`VolumeSatuanID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`CompanyProductionID` IS NOT NULL AND (c.`CompanyProductionID` = 0 OR p2.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p3.`ID` IS NULL))
    OR (c.`UsersID` IS NOT NULL AND (c.`UsersID` = 0 OR p4.`ID` IS NULL))
    OR (c.`VolumeSatuanID` IS NOT NULL AND (c.`VolumeSatuanID` = 0 OR p5.`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(), 'f97d61d658e5a43c41ae2ede912b3d22bc136eca637ee6f77c822fa7dbfe00bc', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- companyproductionassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 6 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 = 'companyproductionassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companyproductionassignment` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `companyproduction` p2 ON c.`CompanyProductionID` = p2.`ID`
  LEFT JOIN `division` p3 ON c.`DivisionID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UsersID` = p4.`ID`
  LEFT JOIN `satuan` p5 ON c.`VolumeSatuanID` = p5.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`CompanyProductionID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UsersID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`VolumeSatuanID` IS NOT NULL AND p5.`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,
          'companyproductionassignment: orphan check OK - 0 rows across 6 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companyproductionassignment` 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(), 'bced31bc9cab0c5dda2f7de2d328b143ba771559966dc323e78ba24cb8ce388f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companyproductionassignment/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 = 'companyproductionassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companyproductionassignment`
  ADD CONSTRAINT `companyproductionassignment_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductionassignment_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductionassignment_CompanyProductionID` FOREIGN KEY (`CompanyProductionID`) REFERENCES `companyproduction` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductionassignment_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductionassignment_UsersID` FOREIGN KEY (`UsersID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companyproductionassignment_VolumeSatuanID` FOREIGN KEY (`VolumeSatuanID`) 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(), '350d71df8497e0dd489ae35f328713f691d7ea31a0dc2cf8f223ec73ede7d570', 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 = 38;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'companyproduct.companyproduct_ApplicationID' AS n UNION ALL SELECT 'companyproduct.companyproduct_CCBarangID' UNION ALL SELECT 'companyproduct.companyproduct_CCPriceSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_CCPrincipalID' UNION ALL SELECT 'companyproduct.companyproduct_CCVolumeSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_CompanyID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorBarangID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorPriceSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorPrincipalID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorVolumeSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_DivisionID' UNION ALL SELECT 'companyproductapplication.companyproductapplication_CompanyID' UNION ALL SELECT 'companyproductapplication.companyproductapplication_ProductApplicationID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_ApplicationID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCBarangID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCPriceSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCPrincipalID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCVolumeSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompanyID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompanyProductID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorBarangID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorPriceSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorPrincipalID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorVolumeSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_DivisionID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_UsersID' UNION ALL SELECT 'companyproductcategory.companyproductcategory_CompanyID' UNION ALL SELECT 'companyproductcategory.companyproductcategory_ProductCategoryID' UNION ALL SELECT 'companyproduction.companyproduction_ApplicationID' UNION ALL SELECT 'companyproduction.companyproduction_CompanyID' UNION ALL SELECT 'companyproduction.companyproduction_DivisionID' UNION ALL SELECT 'companyproduction.companyproduction_VolumeSatuanID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_ApplicationID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_CompanyID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_CompanyProductionID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_DivisionID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_UsersID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_VolumeSatuanID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 38;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'companyproduct.CompanyID' AS n UNION ALL SELECT 'companyproduct.companyproduct_ApplicationID' UNION ALL SELECT 'companyproduct.companyproduct_CCBarangID' UNION ALL SELECT 'companyproduct.companyproduct_CCPriceSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_CCPrincipalID' UNION ALL SELECT 'companyproduct.companyproduct_CCVolumeSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorBarangID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorPriceSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorPrincipalID' UNION ALL SELECT 'companyproduct.companyproduct_CompetitorVolumeSatuanID' UNION ALL SELECT 'companyproduct.companyproduct_DivisionID' UNION ALL SELECT 'companyproductapplication.companyproductapplication_CompanyID' UNION ALL SELECT 'companyproductapplication.companyproductapplication_ProductApplicationID' UNION ALL SELECT 'companyproductassignment.UsersID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_ApplicationID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCBarangID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCPriceSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCPrincipalID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CCVolumeSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompanyID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompanyProductID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorBarangID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorPriceSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorPrincipalID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_CompetitorVolumeSatuanID' UNION ALL SELECT 'companyproductassignment.companyproductassignment_DivisionID' UNION ALL SELECT 'companyproductcategory.companyproductcategory_CompanyID' UNION ALL SELECT 'companyproductcategory.companyproductcategory_ProductCategoryID' UNION ALL SELECT 'companyproduction.CompanyID' UNION ALL SELECT 'companyproduction.companyproduction_ApplicationID' UNION ALL SELECT 'companyproduction.companyproduction_DivisionID' UNION ALL SELECT 'companyproduction.companyproduction_VolumeSatuanID' UNION ALL SELECT 'companyproductionassignment.UsersID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_ApplicationID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_CompanyID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_CompanyProductionID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_DivisionID' UNION ALL SELECT 'companyproductionassignment.companyproductionassignment_VolumeSatuanID') _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 = 38;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'companyproduct.ApplicationID.int' AS n UNION ALL SELECT 'companyproduct.CCBarangID.int' UNION ALL SELECT 'companyproduct.CCPriceSatuanID.int' UNION ALL SELECT 'companyproduct.CCPrincipalID.int' UNION ALL SELECT 'companyproduct.CCVolumeSatuanID.int' UNION ALL SELECT 'companyproduct.CompanyID.int' UNION ALL SELECT 'companyproduct.CompetitorBarangID.int' UNION ALL SELECT 'companyproduct.CompetitorPriceSatuanID.int' UNION ALL SELECT 'companyproduct.CompetitorPrincipalID.int' UNION ALL SELECT 'companyproduct.CompetitorVolumeSatuanID.int' UNION ALL SELECT 'companyproduct.DivisionID.int' UNION ALL SELECT 'companyproductapplication.CompanyID.int' UNION ALL SELECT 'companyproductapplication.ProductApplicationID.int' UNION ALL SELECT 'companyproductassignment.ApplicationID.int' UNION ALL SELECT 'companyproductassignment.CCBarangID.int' UNION ALL SELECT 'companyproductassignment.CCPriceSatuanID.int' UNION ALL SELECT 'companyproductassignment.CCPrincipalID.int' UNION ALL SELECT 'companyproductassignment.CCVolumeSatuanID.int' UNION ALL SELECT 'companyproductassignment.CompanyID.int' UNION ALL SELECT 'companyproductassignment.CompanyProductID.int' UNION ALL SELECT 'companyproductassignment.CompetitorBarangID.int' UNION ALL SELECT 'companyproductassignment.CompetitorPriceSatuanID.int' UNION ALL SELECT 'companyproductassignment.CompetitorPrincipalID.int' UNION ALL SELECT 'companyproductassignment.CompetitorVolumeSatuanID.int' UNION ALL SELECT 'companyproductassignment.DivisionID.int' UNION ALL SELECT 'companyproductassignment.UsersID.int' UNION ALL SELECT 'companyproductcategory.CompanyID.int' UNION ALL SELECT 'companyproductcategory.ProductCategoryID.int' UNION ALL SELECT 'companyproduction.ApplicationID.int' UNION ALL SELECT 'companyproduction.CompanyID.int' UNION ALL SELECT 'companyproduction.DivisionID.int' UNION ALL SELECT 'companyproduction.VolumeSatuanID.int' UNION ALL SELECT 'companyproductionassignment.ApplicationID.int' UNION ALL SELECT 'companyproductionassignment.CompanyID.int' UNION ALL SELECT 'companyproductionassignment.CompanyProductionID.int' UNION ALL SELECT 'companyproductionassignment.DivisionID.int' UNION ALL SELECT 'companyproductionassignment.UsersID.int' UNION ALL SELECT 'companyproductionassignment.VolumeSatuanID.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);
