-- =====================================================================
-- 10_masterdata.sql
-- shared lookups and the NetSuite product master
--
-- 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.
--
-- 15 table(s), 54 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 (6 links):
--   /bank-divisions
--   /banks
--   /branches
--   /company-categories
--   /divisions
--   /group-divisions

-- --------------------------------------------------------------- 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 ('application/10_alter', 'application/20_cleanup', 'application/30_assert', 'application/40_fk', 'bank/10_alter', 'bank/20_cleanup', 'bank/30_assert', 'bank/40_fk', 'bankdivision/10_alter', 'bankdivision/20_cleanup', 'bankdivision/30_assert', 'bankdivision/40_fk', 'branch/10_alter', 'companycategory/10_alter', 'companycategory/20_cleanup', 'companycategory/30_assert', 'companycategory/40_fk', 'companycategorylist/10_alter', 'companycategorylist/20_cleanup', 'companycategorylist/30_assert', 'companycategorylist/40_fk', 'country/10_alter', 'division/10_alter', 'division/20_cleanup', 'division/30_assert', 'division/40_fk', 'izintypestatus/10_alter', 'izintypestatus/20_cleanup', 'izintypestatus/30_assert', 'izintypestatus/40_fk', 'packing/10_alter', 'packing/20_cleanup', 'packing/30_assert', 'packing/40_fk', 'product/10_alter', 'product/20_cleanup', 'product/30_assert', 'product/40_fk', 'productapplication/10_alter', 'productapplication/20_cleanup', 'productapplication/30_assert', 'productapplication/40_fk', 'productcategory/10_alter', 'productcategory/20_cleanup', 'productcategory/30_assert', 'productcategory/40_fk', 'vehiclebrandtype/10_alter', 'vehiclebrandtype/20_cleanup', 'vehiclebrandtype/30_assert', 'vehiclebrandtype/40_fk', 'warehouse/10_alter', 'warehouse/20_cleanup', 'warehouse/30_assert', 'warehouse/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('application/10_alter:eac6e4697281fa38d5e08f7b0d4ebadb42607f1ac76aa32e6430e5cc882c1d54', 'application/20_cleanup:86844168866f497687d3a4296d42d51f2c4f83f1f9cd79eb13bbcd14b1ba8ffc', 'application/30_assert:559c7a9b0c8319c1baacb2f380270dec07912c107ea5741c820439f1bf91ea78', 'application/40_fk:7f4a1934d8fa93433a7f426d17bba705d09bbd3de7f9c351ac057eefb25aa92e', 'bank/10_alter:61d6c7e5be020f2c217f7e0aa57fc4946ee0dfa1e8498eac2c140308d7b6a401', 'bank/20_cleanup:cd92be699a50038e58136bbf54e010b556c8df545cd2495483ee438e76415977', 'bank/30_assert:f5d86d7fddc8c64f7cd6ab37792056be02c3c6af4c8575905a7f45e60d1e26b0', 'bank/40_fk:e4ced238ca07a95b52ba2af0993e7687127947e2054610a9d5e0bc2240c5a27a', 'bankdivision/10_alter:f2743c98009ba592ea40800c3dfa7007e67da3ba954433f415274f221f9e47be', 'bankdivision/20_cleanup:bb2f31e8bfa090a56664943d2b277f910820847c66d375beff4608930fec2ea6', 'bankdivision/30_assert:327e541e46e14180f2b8b7c2a5803e2dd8e2f671fac956b083d182c17c9e0b8d', 'bankdivision/40_fk:2f5ee05481c5d392d27d8dc1c768da6bd677cca8c58afeddfc0156f5373ccb19', 'branch/10_alter:fabc8dd23fbf74f2a92377691fd87dac1cc7eec57a9baf1346c2f68005d999e8', 'companycategory/10_alter:c91463641164f9d0fc4d99f279b9fc1de985e83744c93b242f3ec1c08c96175b', 'companycategory/20_cleanup:1488f1fcf0d4d52d1d3c840a1fa049dec28c18216f785cf4a8a45da10afe044d', 'companycategory/30_assert:91748ec58205a31a74b71380a9453e1af3ede564a048d3ffbf04adb923e903b8', 'companycategory/40_fk:6b80f0b732212e9db54867405dfdf069e20d2bc0fe2442610dd73c466b8f1541', 'companycategorylist/10_alter:71fcb14235a8275b1354624ce29791e2049669643853f800e19ddcd8ed968726', 'companycategorylist/20_cleanup:08be7f4ab3015aeaaf01733c4fcc82061aed033f2fdbe1ab62100fe58853a0fb', 'companycategorylist/30_assert:7e4878f8f6d5a0c724ddc74156b67db894e2921cb303a87b98e9e63f256b9e49', 'companycategorylist/40_fk:bbbbd8fc15036f78d5684f177bf86bcf66c1c834e94f1476d134e3b9feec95af', 'country/10_alter:a6cfab1eb8c16f7a47bd610be83f83a02a59668d02b9503686bca7081e66e951', 'division/10_alter:7ed7b90f3925cd0b4f093941d102477d6e918e8624f692ed0496607cc2273499', 'division/20_cleanup:308630c93f7a28d0da29c25c444a73b4ae90cb696e868532f428eac7403402e0', 'division/30_assert:eb3904a9a2e444a43eb245a38371aee9849be3058737d9baec426d85b33e41e0', 'division/40_fk:a43d37b59b92cab44f6f5adf476730011121ae6e0c64a0592d1b052dbdd1f211', 'izintypestatus/10_alter:ef943679b65ad1e8eebf307f1043d814428c3ba4992330726855ac1afc55b3af', 'izintypestatus/20_cleanup:a39366b94a3d9458ef2479e00d7f6a14735eddc5151a57ea04a69d6cdb42f48a', 'izintypestatus/30_assert:a73b63a0c2d0ec11bc8e314522eb2b0266ce39c7390fd6763653a5b8830c6343', 'izintypestatus/40_fk:ee61373dd3c7875d2ac3d2ee00855413f90262daf0dc65ddc55b5ce366258d7c', 'packing/10_alter:c5552835b6054b09d7ec385731ffe9c920ce5d07a9b8b1e6b652fd535d1d14ce', 'packing/20_cleanup:e89707b415f659b62030d9a3488efd0c084e1ecfed5095825519cd582fe8179b', 'packing/30_assert:1b49fc2dd248aea710d117a336b99c957e1bbf200b921268ce78ca2bcc190c76', 'packing/40_fk:7414b5692130770d33891f819b766881d2b4109e2e2437f5174804ac9cdc0807', 'product/10_alter:2448ee0c359a7cea614f3872da06eb194f7f5208303dfb9a595a44a5d86ce220', 'product/20_cleanup:e20c1f8530f57258fa3316202e4e847ca05bdc066972c22b8aa3554912f0dc63', 'product/30_assert:e61306069e99a3b950eb70a6d5dfd80d1338825049ec76596cc4dc9485da709a', 'product/40_fk:982403b709f0bd4fe73fa6b0a00e66bfd9eebcc5cde5bac3a79551b804dde3d8', 'productapplication/10_alter:0a6d08911987782115f85c2951b52ac16f89f705f8da1223088c6efab32cc6ca', 'productapplication/20_cleanup:2c83c674e36c7024ec1137906ba2ac1292684ce4b228be01c7b9718411511451', 'productapplication/30_assert:27f1e78c73d54073901527d3085e67f21c4a19be754f8f541e84e1b9601b2154', 'productapplication/40_fk:35d4e546927ef99b7aecb8267503148f817696d5aac234fecf689e8236ae2e34', 'productcategory/10_alter:8501d6dd0ffa1134aa4a2cde90deae5561089e0c687600ce61919268034deb78', 'productcategory/20_cleanup:fbc79456d25aad50a475009108791ffc091134ede1849374d4b8ab6e1b3470bd', 'productcategory/30_assert:b9dd587f875f230e84caa15c34a9aa5bda3a39af789a1ecbfe6e2470d54c6cae', 'productcategory/40_fk:d7dd4389a7eb1d0ccd50988176a16070a6696e8dc8567a9d7ee2e7e544b76ef0', 'vehiclebrandtype/10_alter:0da35a2e2569e4ff23880a6a558718eaee885f0221035e888444bfb797413714', 'vehiclebrandtype/20_cleanup:05ed77aa23c5ee7cc0826e1df00320f7978fba6bfa95a941078381b082d2fe53', 'vehiclebrandtype/30_assert:774b34659436085672c96734edea2e46cbda5d8171f537a6b16bbb279b9fad9c', 'vehiclebrandtype/40_fk:fc241890a5becc6661a752361793b45ed8d116ff20b2539e5030dc22112e4e32', 'warehouse/10_alter:cc46056c0559e65befd7c2c2b841d15b935477b672612ef5fbed701bc5575895', 'warehouse/20_cleanup:efefc1b8ebfab710249da96d5c3d8514b1c57ccee009bc96ce1bde442ec77165', 'warehouse/30_assert:0c2adc4ba76b369f501785fa6ce276d85a5e9cc776d9bbd3d58bf09ae8e72e87', 'warehouse/40_fk:04cefa36429b6e37c87cb35d57f121e88cff0d2a743ed0a8267430816500a17d');
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: application    (lookup)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- application/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 = 'application/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `application`
  MODIFY COLUMN `GroupDivisionID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  ADD INDEX `application_DivisionID` (`DivisionID`),
  ADD INDEX `GroupDivisionID` (`GroupDivisionID`,`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(), 'eac6e4697281fa38d5e08f7b0d4ebadb42607f1ac76aa32e6430e5cc882c1d54', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- application/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 = 'application/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `application` c
  LEFT JOIN `division` p0 ON c.`DivisionID` = p0.`ID`
  LEFT JOIN `groupdivision` p1 ON c.`GroupDivisionID` = p1.`ID`
   SET
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p0.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`GroupDivisionID` = IF((c.`GroupDivisionID` IS NOT NULL AND (c.`GroupDivisionID` = 0 OR p1.`ID` IS NULL)), NULL, c.`GroupDivisionID`)
 WHERE  (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p0.`ID` IS NULL))
    OR (c.`GroupDivisionID` IS NOT NULL AND (c.`GroupDivisionID` = 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(), '86844168866f497687d3a4296d42d51f2c4f83f1f9cd79eb13bbcd14b1ba8ffc', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- application/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 = 'application/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `application` c
  LEFT JOIN `division` p0 ON c.`DivisionID` = p0.`ID`
  LEFT JOIN `groupdivision` p1 ON c.`GroupDivisionID` = p1.`ID`
 WHERE  (c.`DivisionID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`GroupDivisionID` 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,
          'application: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `application` 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(), '559c7a9b0c8319c1baacb2f380270dec07912c107ea5741c820439f1bf91ea78', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- application/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 = 'application/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `application`
  ADD CONSTRAINT `application_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `application_GroupDivisionID` FOREIGN KEY (`GroupDivisionID`) REFERENCES `groupdivision` (`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(), '7f4a1934d8fa93433a7f426d17bba705d09bbd3de7f9c351ac057eefb25aa92e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- bank/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 = 'bank/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `bank` c
  LEFT JOIN `quotationpricedesc` p0 ON c.`QuotationPriceDescID` = p0.`ID`
 WHERE  (c.`QuotationPriceDescID` 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,
          'bank: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `bank` 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(), 'f5d86d7fddc8c64f7cd6ab37792056be02c3c6af4c8575905a7f45e60d1e26b0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- bank/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 = 'bank/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `bank` ADD CONSTRAINT `bank_QuotationPriceDescID` FOREIGN KEY (`QuotationPriceDescID`) REFERENCES `quotationpricedesc` (`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(), 'e4ced238ca07a95b52ba2af0993e7687127947e2054610a9d5e0bc2240c5a27a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- bankdivision/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 = 'bankdivision/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `bankdivision` c
  LEFT JOIN `bank` p0 ON c.`BankID` = p0.`ID`
  LEFT JOIN `division` p1 ON c.`DivisionID` = p1.`ID`
 WHERE  (c.`BankID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DivisionID` 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,
          'bankdivision: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `bankdivision` 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(), '327e541e46e14180f2b8b7c2a5803e2dd8e2f671fac956b083d182c17c9e0b8d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- bankdivision/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 = 'bankdivision/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `bankdivision`
  ADD CONSTRAINT `bankdivision_BankID` FOREIGN KEY (`BankID`) REFERENCES `bank` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `bankdivision_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(), '2f5ee05481c5d392d27d8dc1c768da6bd677cca8c58afeddfc0156f5373ccb19', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: branch    (lookup)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- branch/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 = 'branch/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `branch`
  ADD COLUMN `KodeKecamatan` varchar(200) NOT NULL AFTER `Kecamatan`,
  ADD COLUMN `Kota` varchar(200) NOT NULL AFTER `KodeKecamatan`,
  ADD COLUMN `KodeKota` varchar(200) NOT NULL AFTER `Kota`,
  ADD COLUMN `KodeProvinsi` varchar(200) NOT NULL AFTER `KodeKota`', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'fabc8dd23fbf74f2a92377691fd87dac1cc7eec57a9baf1346c2f68005d999e8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

COMMIT;
-- ---------------------------------------------------------------------
-- companycategory/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 = 'companycategory/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companycategory` c
  LEFT JOIN `groupdivision` p0 ON c.`GroupDivID` = p0.`ID`
 WHERE  (c.`GroupDivID` 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,
          'companycategory: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companycategory` 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(), '91748ec58205a31a74b71380a9453e1af3ede564a048d3ffbf04adb923e903b8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companycategory/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 = 'companycategory/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companycategory` ADD CONSTRAINT `companycategory_GroupDivID` FOREIGN KEY (`GroupDivID`) REFERENCES `groupdivision` (`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(), '6b80f0b732212e9db54867405dfdf069e20d2bc0fe2442610dd73c466b8f1541', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- companycategorylist/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 = 'companycategorylist/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `companycategorylist` c
  LEFT JOIN `companycategory` p0 ON c.`CompanyCategoryID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
 WHERE  (c.`CompanyCategoryID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` 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,
          'companycategorylist: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `companycategorylist` 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(), '7e4878f8f6d5a0c724ddc74156b67db894e2921cb303a87b98e9e63f256b9e49', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- companycategorylist/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 = 'companycategorylist/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `companycategorylist`
  ADD CONSTRAINT `companycategorylist_CompanyCategoryID` FOREIGN KEY (`CompanyCategoryID`) REFERENCES `companycategory` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `companycategorylist_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`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(), 'bbbbd8fc15036f78d5684f177bf86bcf66c1c834e94f1476d134e3b9feec95af', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: country    (lookup)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- country/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 = 'country/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `country` ADD COLUMN `country_code` char(2) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL AFTER `country_name`', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a6cfab1eb8c16f7a47bd610be83f83a02a59668d02b9503686bca7081e66e951', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

COMMIT;
-- ---------------------------------------------------------------------
-- division/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 = 'division/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `division` c
  LEFT JOIN `groupdivision` p0 ON c.`GroupDivisionID` = p0.`ID`
 WHERE  (c.`GroupDivisionID` 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,
          'division: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `division` 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(), 'eb3904a9a2e444a43eb245a38371aee9849be3058737d9baec426d85b33e41e0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- division/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 = 'division/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `division` ADD CONSTRAINT `division_GroupDivisionID` FOREIGN KEY (`GroupDivisionID`) REFERENCES `groupdivision` (`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(), 'a43d37b59b92cab44f6f5adf476730011121ae6e0c64a0592d1b052dbdd1f211', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- izintypestatus/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 = 'izintypestatus/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `izintypestatus` c
  LEFT JOIN `izintype` p0 ON c.`IzinTypeID` = p0.`ID`
 WHERE  (c.`IzinTypeID` 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,
          'izintypestatus: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `izintypestatus` 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(), 'a73b63a0c2d0ec11bc8e314522eb2b0266ce39c7390fd6763653a5b8830c6343', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- izintypestatus/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 = 'izintypestatus/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `izintypestatus` ADD CONSTRAINT `izintypestatus_IzinTypeID` FOREIGN KEY (`IzinTypeID`) REFERENCES `izintype` (`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(), 'ee61373dd3c7875d2ac3d2ee00855413f90262daf0dc65ddc55b5ce366258d7c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: packing    (lookup)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- packing/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 = 'packing/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `packing`
  MODIFY COLUMN `SatuanID` int DEFAULT NULL,
  ADD INDEX `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(), 'c5552835b6054b09d7ec385731ffe9c920ce5d07a9b8b1e6b652fd535d1d14ce', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- packing/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 = 'packing/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `packing` c
  LEFT JOIN `satuan` p0 ON c.`SatuanID` = p0.`ID`
   SET
       c.`SatuanID` = IF((c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p0.`ID` IS NULL)), NULL, c.`SatuanID`)
 WHERE  (c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 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(), 'e89707b415f659b62030d9a3488efd0c084e1ecfed5095825519cd582fe8179b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- packing/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 = 'packing/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `packing` c
  LEFT JOIN `satuan` p0 ON c.`SatuanID` = p0.`ID`
 WHERE  (c.`SatuanID` 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,
          'packing: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `packing` 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(), '1b49fc2dd248aea710d117a336b99c957e1bbf200b921268ce78ca2bcc190c76', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- packing/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 = 'packing/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `packing` ADD CONSTRAINT `packing_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(), '7414b5692130770d33891f819b766881d2b4109e2e2437f5174804ac9cdc0807', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: product    (master, packed here: NetSuite product master -- in 3 group closures)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- product/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 = 'product/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `product`
  MODIFY COLUMN `ClassID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `PackingID` int DEFAULT NULL,
  ADD INDEX `ClassID` (`ClassID`,`PrincipalID`,`PackingID`),
  ADD INDEX `product_PackingID` (`PackingID`),
  ADD INDEX `product_PrincipalID` (`PrincipalID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '2448ee0c359a7cea614f3872da06eb194f7f5208303dfb9a595a44a5d86ce220', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- product/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 = 'product/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `product` c
  LEFT JOIN `class` p0 ON c.`ClassID` = p0.`ID`
  LEFT JOIN `packing` p1 ON c.`PackingID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`PrincipalID` = p2.`ID`
   SET
       c.`ClassID` = IF((c.`ClassID` IS NOT NULL AND (c.`ClassID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ClassID`),
       c.`PackingID` = IF((c.`PackingID` IS NOT NULL AND (c.`PackingID` = 0 OR p1.`ID` IS NULL)), NULL, c.`PackingID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p2.`ID` IS NULL)), NULL, c.`PrincipalID`)
 WHERE  (c.`ClassID` IS NOT NULL AND (c.`ClassID` = 0 OR p0.`ID` IS NULL))
    OR (c.`PackingID` IS NOT NULL AND (c.`PackingID` = 0 OR p1.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p2.`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(), 'e20c1f8530f57258fa3316202e4e847ca05bdc066972c22b8aa3554912f0dc63', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- product/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 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 = 'product/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `product` c
  LEFT JOIN `class` p0 ON c.`ClassID` = p0.`ID`
  LEFT JOIN `packing` p1 ON c.`PackingID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`PrincipalID` = p2.`ID`
 WHERE  (c.`ClassID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`PackingID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p2.`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,
          'product: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `product` 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(), 'e61306069e99a3b950eb70a6d5dfd80d1338825049ec76596cc4dc9485da709a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- product/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 = 'product/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `product`
  ADD CONSTRAINT `product_ClassID` FOREIGN KEY (`ClassID`) REFERENCES `class` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `product_PackingID` FOREIGN KEY (`PackingID`) REFERENCES `packing` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `product_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`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(), '982403b709f0bd4fe73fa6b0a00e66bfd9eebcc5cde5bac3a79551b804dde3d8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: productapplication    (detail, packed here: follows its owner `product`)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- productapplication/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 = 'productapplication/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `productapplication`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `ProductID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  ADD INDEX `productapplication_ApplicationID` (`ApplicationID`),
  ADD INDEX `productapplication_ProductID` (`ProductID`),
  ADD INDEX `UserIDInput` (`UserIDInput`,`ProductID`,`ApplicationID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0a6d08911987782115f85c2951b52ac16f89f705f8da1223088c6efab32cc6ca', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- productapplication/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 = 'productapplication/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `productapplication` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`ProductID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`ProductID` = IF((c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ProductID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`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(), '2c83c674e36c7024ec1137906ba2ac1292684ce4b228be01c7b9718411511451', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- productapplication/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 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 = 'productapplication/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `productapplication` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`ProductID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ProductID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`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,
          'productapplication: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `productapplication` 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(), '27f1e78c73d54073901527d3085e67f21c4a19be754f8f541e84e1b9601b2154', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- productapplication/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 = 'productapplication/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `productapplication`
  ADD CONSTRAINT `productapplication_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `productapplication_ProductID` FOREIGN KEY (`ProductID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `productapplication_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(), '35d4e546927ef99b7aecb8267503148f817696d5aac234fecf689e8236ae2e34', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: productcategory    (detail, packed here: follows its owner `product`)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- productcategory/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 = 'productcategory/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `productcategory`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `CategoryID` int DEFAULT NULL,
  MODIFY COLUMN `ProductID` int DEFAULT NULL,
  ADD INDEX `productcategory_CategoryID` (`CategoryID`),
  ADD INDEX `productcategory_ProductID` (`ProductID`),
  ADD INDEX `UserIDInput` (`UserIDInput`,`CategoryID`,`ProductID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '8501d6dd0ffa1134aa4a2cde90deae5561089e0c687600ce61919268034deb78', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- productcategory/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 = 'productcategory/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `productcategory` c
  LEFT JOIN `category` p0 ON c.`CategoryID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`ProductID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`CategoryID` = IF((c.`CategoryID` IS NOT NULL AND (c.`CategoryID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CategoryID`),
       c.`ProductID` = IF((c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p1.`ID` IS NULL)), NULL, c.`ProductID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`CategoryID` IS NOT NULL AND (c.`CategoryID` = 0 OR p0.`ID` IS NULL))
    OR (c.`ProductID` IS NOT NULL AND (c.`ProductID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`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(), 'fbc79456d25aad50a475009108791ffc091134ede1849374d4b8ab6e1b3470bd', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- productcategory/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 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 = 'productcategory/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `productcategory` c
  LEFT JOIN `category` p0 ON c.`CategoryID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`ProductID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`CategoryID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`ProductID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`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,
          'productcategory: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `productcategory` 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(), 'b9dd587f875f230e84caa15c34a9aa5bda3a39af789a1ecbfe6e2470d54c6cae', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- productcategory/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 = 'productcategory/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `productcategory`
  ADD CONSTRAINT `productcategory_CategoryID` FOREIGN KEY (`CategoryID`) REFERENCES `category` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `productcategory_ProductID` FOREIGN KEY (`ProductID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `productcategory_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(), 'd7dd4389a7eb1d0ccd50988176a16070a6696e8dc8567a9d7ee2e7e544b76ef0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- vehiclebrandtype/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 = 'vehiclebrandtype/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `vehiclebrandtype` c
  LEFT JOIN `vehiclebrand` p0 ON c.`VehicleBrandID` = p0.`ID`
 WHERE  (c.`VehicleBrandID` 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,
          'vehiclebrandtype: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `vehiclebrandtype` 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(), '774b34659436085672c96734edea2e46cbda5d8171f537a6b16bbb279b9fad9c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- vehiclebrandtype/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 = 'vehiclebrandtype/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `vehiclebrandtype` ADD CONSTRAINT `vehiclebrandtype_VehicleBrandID` FOREIGN KEY (`VehicleBrandID`) REFERENCES `vehiclebrand` (`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(), 'fc241890a5becc6661a752361793b45ed8d116ff20b2539e5030dc22112e4e32', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- warehouse/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 = 'warehouse/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `warehouse` c
  LEFT JOIN `warehouse` p0 ON c.`ParentID` = p0.`ID`
 WHERE  (c.`ParentID` 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,
          'warehouse: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `warehouse` 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(), '0c2adc4ba76b369f501785fa6ce276d85a5e9cc776d9bbd3d58bf09ae8e72e87', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- warehouse/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 = 'warehouse/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `warehouse` ADD CONSTRAINT `warehouse_ParentID` FOREIGN KEY (`ParentID`) REFERENCES `warehouse` (`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(), '04cefa36429b6e37c87cb35d57f121e88cff0d2a743ed0a8267430816500a17d', 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 = 22;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'application.application_DivisionID' AS n UNION ALL SELECT 'application.application_GroupDivisionID' UNION ALL SELECT 'bank.bank_QuotationPriceDescID' UNION ALL SELECT 'bankdivision.bankdivision_BankID' UNION ALL SELECT 'bankdivision.bankdivision_DivisionID' UNION ALL SELECT 'companycategory.companycategory_GroupDivID' UNION ALL SELECT 'companycategorylist.companycategorylist_CompanyCategoryID' UNION ALL SELECT 'companycategorylist.companycategorylist_CompanyID' UNION ALL SELECT 'division.division_GroupDivisionID' UNION ALL SELECT 'izintypestatus.izintypestatus_IzinTypeID' UNION ALL SELECT 'packing.packing_SatuanID' UNION ALL SELECT 'product.product_ClassID' UNION ALL SELECT 'product.product_PackingID' UNION ALL SELECT 'product.product_PrincipalID' UNION ALL SELECT 'productapplication.productapplication_ApplicationID' UNION ALL SELECT 'productapplication.productapplication_ProductID' UNION ALL SELECT 'productapplication.productapplication_UserIDInput' UNION ALL SELECT 'productcategory.productcategory_CategoryID' UNION ALL SELECT 'productcategory.productcategory_ProductID' UNION ALL SELECT 'productcategory.productcategory_UserIDInput' UNION ALL SELECT 'vehiclebrandtype.vehiclebrandtype_VehicleBrandID' UNION ALL SELECT 'warehouse.warehouse_ParentID') _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 = 5;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_col, @miss_col
  FROM (SELECT 'branch.KodeKecamatan' AS n UNION ALL SELECT 'branch.KodeKota' UNION ALL SELECT 'branch.KodeProvinsi' UNION ALL SELECT 'branch.Kota' UNION ALL SELECT 'country.country_code') _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 = 23;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'application.GroupDivisionID' AS n UNION ALL SELECT 'application.application_DivisionID' UNION ALL SELECT 'bank.bank_QuotationPriceDescID' UNION ALL SELECT 'bankdivision.DivisionID' UNION ALL SELECT 'bankdivision.DivisionID_2' UNION ALL SELECT 'bankdivision.bankdivision_BankID' UNION ALL SELECT 'companycategory.companycategory_GroupDivID' UNION ALL SELECT 'companycategorylist.companycategorylist_CompanyCategoryID' UNION ALL SELECT 'companycategorylist.companycategorylist_CompanyID' UNION ALL SELECT 'division.GroupDivisionID' UNION ALL SELECT 'izintypestatus.IzinTypeID' UNION ALL SELECT 'packing.SatuanID' UNION ALL SELECT 'product.ClassID' UNION ALL SELECT 'product.product_PackingID' UNION ALL SELECT 'product.product_PrincipalID' UNION ALL SELECT 'productapplication.UserIDInput' UNION ALL SELECT 'productapplication.productapplication_ApplicationID' UNION ALL SELECT 'productapplication.productapplication_ProductID' UNION ALL SELECT 'productcategory.UserIDInput' UNION ALL SELECT 'productcategory.productcategory_CategoryID' UNION ALL SELECT 'productcategory.productcategory_ProductID' UNION ALL SELECT 'vehiclebrandtype.VehicleBrandID' UNION ALL SELECT 'warehouse.warehouse_ParentID') _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 = 22;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'application.DivisionID.int' AS n UNION ALL SELECT 'application.GroupDivisionID.int' UNION ALL SELECT 'bank.QuotationPriceDescID.int' UNION ALL SELECT 'bankdivision.BankID.int' UNION ALL SELECT 'bankdivision.DivisionID.int' UNION ALL SELECT 'companycategory.GroupDivID.int' UNION ALL SELECT 'companycategorylist.CompanyCategoryID.int' UNION ALL SELECT 'companycategorylist.CompanyID.int' UNION ALL SELECT 'division.GroupDivisionID.int' UNION ALL SELECT 'izintypestatus.IzinTypeID.int' UNION ALL SELECT 'packing.SatuanID.int' UNION ALL SELECT 'product.ClassID.int' UNION ALL SELECT 'product.PackingID.int' UNION ALL SELECT 'product.PrincipalID.int' UNION ALL SELECT 'productapplication.ApplicationID.int' UNION ALL SELECT 'productapplication.ProductID.int' UNION ALL SELECT 'productapplication.UserIDInput.int' UNION ALL SELECT 'productcategory.CategoryID.int' UNION ALL SELECT 'productcategory.ProductID.int' UNION ALL SELECT 'productcategory.UserIDInput.int' UNION ALL SELECT 'vehiclebrandtype.VehicleBrandID.int' UNION ALL SELECT 'warehouse.ParentID.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);
