-- =====================================================================
-- 91_hr.sql
-- izin, lembur, onleave
--
-- 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.
--
-- 8 table(s), 32 ledger step(s).
--
-- ⚠ IMPORT ORDER: 01_system.sql, the seven 1x masters, then this file. No page needs it,
--    but 99_finalize.sql will not run until it is applied.
--
-- ⚠ 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.
-- =====================================================================

-- No menu.LinkLaravel points here yet. Nothing in the sidebar can reach
-- these tables -- but 99_finalize.sql still refuses to run until they are
-- applied, so this file is not optional for a completed migration.

-- --------------------------------------------------------------- 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 ('izin/10_alter', 'izin/20_cleanup', 'izin/30_assert', 'izin/40_fk', 'izinassignment/10_alter', 'izinassignment/20_cleanup', 'izinassignment/30_assert', 'izinassignment/40_fk', 'lembur/10_alter', 'lembur/20_cleanup', 'lembur/30_assert', 'lembur/40_fk', 'lemburassignment/10_alter', 'lemburassignment/20_cleanup', 'lemburassignment/30_assert', 'lemburassignment/40_fk', 'onleave/10_alter', 'onleave/20_cleanup', 'onleave/30_assert', 'onleave/40_fk', 'onleaveadditional/10_alter', 'onleaveadditional/20_cleanup', 'onleaveadditional/30_assert', 'onleaveadditional/40_fk', 'onleaveadditionalassignment/10_alter', 'onleaveadditionalassignment/20_cleanup', 'onleaveadditionalassignment/30_assert', 'onleaveadditionalassignment/40_fk', 'onleaveassignment/10_alter', 'onleaveassignment/20_cleanup', 'onleaveassignment/30_assert', 'onleaveassignment/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('izin/10_alter:a757e9d8cc3541bdc0d56e348d0c68878c6813154a74f603175904aa43e68c25', 'izin/20_cleanup:f4b1ae23b9b469e122599de2091c8364573022da751e837c38910f74f828eba5', 'izin/30_assert:ba02ec8f0d69cd1da7a18837ad95f4ab71543e2c2e31dee94a10a9b03844d6ee', 'izin/40_fk:2a1fd664c94e832f79a5401512e4bdca6f94c7fadb2eb3b512fe4f1e77f2f748', 'izinassignment/10_alter:41580e988d168c1ed678c4a67b047d1fa304c770693f96564371a4995d38b5bf', 'izinassignment/20_cleanup:ab07c9d43eb7b9c3d8e94f95720e42746937bb8e96cb88a24667fdab38ff0685', 'izinassignment/30_assert:16d0013f93a79afa5fc90ac8db06c9a89fca29730b253eb06b9fc2264c48b39c', 'izinassignment/40_fk:2dec1a6976f26cbec264da48e5ea0eaec73b65706f47036c9455b999138a5850', 'lembur/10_alter:96f3f0c809c77ce1f98fbbe7fa9e5f708dd4d08bda2c9973bdb4b85f1028f3cf', 'lembur/20_cleanup:b6dedaea0bc32d0078053d39ca1509a2a5d4f15c23403d363c600ec2c9361554', 'lembur/30_assert:36a6f203fb6ec50bb8f3e4e29302d0bdd26ff484bc50b1fa8ab8a7c44b72d1ea', 'lembur/40_fk:9e5680438d51db9af2b88924bc0627265b677fb07648325560f2172de4355a17', 'lemburassignment/10_alter:ee490b77bc816120111020cf19279c00a8cf75ad1cd768a8b1f5c0f37a227998', 'lemburassignment/20_cleanup:1305bf0f1e243c4142c1f1fccd3a9097737340a10d0df22ad0eb626acfabd445', 'lemburassignment/30_assert:442475d85f951e634dd674553140127423e10618fe520404f3c82050385bc548', 'lemburassignment/40_fk:f36a9010e66411adb57d7226222134899e45fa061d0441b83d0dd00396e00493', 'onleave/10_alter:62061a7194bdd301b1323611010f3c94c69694cc58b77dd7b40d9b1911e9ff4d', 'onleave/20_cleanup:e4b06d03e4470b7e1ebafe471055758aee541d27e5cf172c99c7c08f7d98ddb8', 'onleave/30_assert:b81d1462d7c40a6947839c1aac63eeb123190f0c23534ebb3382afccd8037da6', 'onleave/40_fk:1a5a5b44f9e2aeb92156f4e6f7579ae1d34f1fbd01f170e7333612fac065d3bf', 'onleaveadditional/10_alter:17e7a6a2b47c18e9e14dda947e646984a44b5e73f21089954a4ee1c160c99db7', 'onleaveadditional/20_cleanup:95339ece160db45c9ce826d4bfe9c881f168272b1536f1a580e5679a0c31b11a', 'onleaveadditional/30_assert:0884edf11e922e2adb60d92c9e63d78c79129e07a4c098d79a2f654a8be01cf0', 'onleaveadditional/40_fk:2c0da438f12c0848471d153aedef43562269a769f1ef6cc6692f3a30bd01ec74', 'onleaveadditionalassignment/10_alter:00ee9afca490844d7e1f2c37009c07f871c4a26af56ac41c060be08020fe572d', 'onleaveadditionalassignment/20_cleanup:162f2dfb690d978210a7bbdb599f5b8290efbc1e11215589365abec086fcf842', 'onleaveadditionalassignment/30_assert:c3c37ca9d475b1162d70565cb06ff063234b2e81534b0c1ff287bbd08e049404', 'onleaveadditionalassignment/40_fk:fbb9c9efeb170a5450a77770eb3b3a36357531ee9a4c0c9cb4448b83cb7dc0bd', 'onleaveassignment/10_alter:3610d59f2aad41bf6adad36f8766b4db0e5879a11414304caed0e920ad67e23f', 'onleaveassignment/20_cleanup:ec6244532bc13aa77d400de473b609a8f2182ad93454916f606228f67e3b7ffa', 'onleaveassignment/30_assert:96b47d015f3db9b0c1d7ee8a02b665e9a30917c3c38dcc0bc495690586086b66', 'onleaveassignment/40_fk:c8f330e2fdc46630461252d6d54fdab12542aa79798072621dbf10bbfeaece4b');
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: izin    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- izin/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 = 'izin/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `izin`
  MODIFY COLUMN `IzinTypeID` int DEFAULT NULL,
  MODIFY COLUMN `IzinTypeStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  MODIFY COLUMN `IzinStatusID` int DEFAULT NULL,
  ADD INDEX `izin_IzinStatusID` (`IzinStatusID`),
  ADD INDEX `izin_IzinTypeStatusID` (`IzinTypeStatusID`),
  ADD INDEX `izin_UserIDInput` (`UserIDInput`),
  ADD INDEX `izin_UserIDSales` (`UserIDSales`),
  ADD INDEX `IzinTypeID` (`IzinTypeID`,`IzinTypeStatusID`,`UserIDInput`,`UserIDSales`,`IzinStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a757e9d8cc3541bdc0d56e348d0c68878c6813154a74f603175904aa43e68c25', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- izin/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 = 'izin/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `izin` c
  LEFT JOIN `izinstatus` p0 ON c.`IzinStatusID` = p0.`ID`
  LEFT JOIN `izintype` p1 ON c.`IzinTypeID` = p1.`ID`
  LEFT JOIN `izintypestatus` p2 ON c.`IzinTypeStatusID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDSales` = p4.`ID`
   SET
       c.`IzinStatusID` = IF((c.`IzinStatusID` IS NOT NULL AND (c.`IzinStatusID` = 0 OR p0.`ID` IS NULL)), NULL, c.`IzinStatusID`),
       c.`IzinTypeID` = IF((c.`IzinTypeID` IS NOT NULL AND (c.`IzinTypeID` = 0 OR p1.`ID` IS NULL)), NULL, c.`IzinTypeID`),
       c.`IzinTypeStatusID` = IF((c.`IzinTypeStatusID` IS NOT NULL AND (c.`IzinTypeStatusID` = 0 OR p2.`ID` IS NULL)), NULL, c.`IzinTypeStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p4.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`IzinStatusID` IS NOT NULL AND (c.`IzinStatusID` = 0 OR p0.`ID` IS NULL))
    OR (c.`IzinTypeID` IS NOT NULL AND (c.`IzinTypeID` = 0 OR p1.`ID` IS NULL))
    OR (c.`IzinTypeStatusID` IS NOT NULL AND (c.`IzinTypeStatusID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p3.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p4.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f4b1ae23b9b469e122599de2091c8364573022da751e837c38910f74f828eba5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'izin/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `izin` c
  LEFT JOIN `izinstatus` p0 ON c.`IzinStatusID` = p0.`ID`
  LEFT JOIN `izintype` p1 ON c.`IzinTypeID` = p1.`ID`
  LEFT JOIN `izintypestatus` p2 ON c.`IzinTypeStatusID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDInput` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDSales` = p4.`ID`
 WHERE  (c.`IzinStatusID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`IzinTypeID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`IzinTypeStatusID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p4.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'izin: orphan check OK - 0 rows across 5 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `izin` 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(), 'ba02ec8f0d69cd1da7a18837ad95f4ab71543e2c2e31dee94a10a9b03844d6ee', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- izin/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 = 'izin/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `izin`
  ADD CONSTRAINT `izin_IzinStatusID` FOREIGN KEY (`IzinStatusID`) REFERENCES `izinstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `izin_IzinTypeID` FOREIGN KEY (`IzinTypeID`) REFERENCES `izintype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `izin_IzinTypeStatusID` FOREIGN KEY (`IzinTypeStatusID`) REFERENCES `izintypestatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `izin_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `izin_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '2a1fd664c94e832f79a5401512e4bdca6f94c7fadb2eb3b512fe4f1e77f2f748', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: izinassignment    (detail, owned by izin)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- izinassignment/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 = 'izinassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `izinassignment`
  MODIFY COLUMN `IzinID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  MODIFY COLUMN `IzinStatusID` int DEFAULT NULL,
  ADD INDEX `izinassignment_IzinStatusID` (`IzinStatusID`),
  ADD INDEX `izinassignment_UserID` (`UserID`),
  ADD INDEX `IzinID` (`IzinID`,`UserID`,`IzinStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '41580e988d168c1ed678c4a67b047d1fa304c770693f96564371a4995d38b5bf', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- izinassignment/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 = 'izinassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `izinassignment` c
  LEFT JOIN `izin` p0 ON c.`IzinID` = p0.`ID`
  LEFT JOIN `izinstatus` p1 ON c.`IzinStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
   SET
       c.`IzinID` = IF((c.`IzinID` IS NOT NULL AND (c.`IzinID` = 0 OR p0.`ID` IS NULL)), NULL, c.`IzinID`),
       c.`IzinStatusID` = IF((c.`IzinStatusID` IS NOT NULL AND (c.`IzinStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`IzinStatusID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`IzinID` IS NOT NULL AND (c.`IzinID` = 0 OR p0.`ID` IS NULL))
    OR (c.`IzinStatusID` IS NOT NULL AND (c.`IzinStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 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(), 'ab07c9d43eb7b9c3d8e94f95720e42746937bb8e96cb88a24667fdab38ff0685', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- izinassignment/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 = 'izinassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `izinassignment` c
  LEFT JOIN `izin` p0 ON c.`IzinID` = p0.`ID`
  LEFT JOIN `izinstatus` p1 ON c.`IzinStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
 WHERE  (c.`IzinID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`IzinStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserID` 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,
          'izinassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `izinassignment` 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(), '16d0013f93a79afa5fc90ac8db06c9a89fca29730b253eb06b9fc2264c48b39c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- izinassignment/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 = 'izinassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `izinassignment`
  ADD CONSTRAINT `izinassignment_IzinID` FOREIGN KEY (`IzinID`) REFERENCES `izin` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `izinassignment_IzinStatusID` FOREIGN KEY (`IzinStatusID`) REFERENCES `izinstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `izinassignment_UserID` FOREIGN KEY (`UserID`) 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(), '2dec1a6976f26cbec264da48e5ea0eaec73b65706f47036c9455b999138a5850', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: lembur    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- lembur/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 = 'lembur/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `lembur`
  MODIFY COLUMN `LemburTypeID` int DEFAULT NULL,
  MODIFY COLUMN `LemburStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  ADD INDEX `lembur_LemburStatusID` (`LemburStatusID`),
  ADD INDEX `lembur_UserIDInput` (`UserIDInput`),
  ADD INDEX `lembur_UserIDSales` (`UserIDSales`),
  ADD INDEX `LemburTypeID` (`LemburTypeID`,`LemburStatusID`,`UserIDInput`,`UserIDSales`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '96f3f0c809c77ce1f98fbbe7fa9e5f708dd4d08bda2c9973bdb4b85f1028f3cf', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- lembur/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 = 'lembur/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `lembur` c
  LEFT JOIN `lemburstatus` p0 ON c.`LemburStatusID` = p0.`ID`
  LEFT JOIN `lemburtype` p1 ON c.`LemburTypeID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDSales` = p3.`ID`
   SET
       c.`LemburStatusID` = IF((c.`LemburStatusID` IS NOT NULL AND (c.`LemburStatusID` = 0 OR p0.`ID` IS NULL)), NULL, c.`LemburStatusID`),
       c.`LemburTypeID` = IF((c.`LemburTypeID` IS NOT NULL AND (c.`LemburTypeID` = 0 OR p1.`ID` IS NULL)), NULL, c.`LemburTypeID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`LemburStatusID` IS NOT NULL AND (c.`LemburStatusID` = 0 OR p0.`ID` IS NULL))
    OR (c.`LemburTypeID` IS NOT NULL AND (c.`LemburTypeID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'b6dedaea0bc32d0078053d39ca1509a2a5d4f15c23403d363c600ec2c9361554', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'lembur/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `lembur` c
  LEFT JOIN `lemburstatus` p0 ON c.`LemburStatusID` = p0.`ID`
  LEFT JOIN `lemburtype` p1 ON c.`LemburTypeID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDSales` = p3.`ID`
 WHERE  (c.`LemburStatusID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`LemburTypeID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'lembur: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `lembur` 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(), '36a6f203fb6ec50bb8f3e4e29302d0bdd26ff484bc50b1fa8ab8a7c44b72d1ea', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- lembur/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 = 'lembur/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `lembur`
  ADD CONSTRAINT `lembur_LemburStatusID` FOREIGN KEY (`LemburStatusID`) REFERENCES `lemburstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `lembur_LemburTypeID` FOREIGN KEY (`LemburTypeID`) REFERENCES `lemburtype` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `lembur_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `lembur_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '9e5680438d51db9af2b88924bc0627265b677fb07648325560f2172de4355a17', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: lemburassignment    (detail, owned by lembur)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- lemburassignment/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 = 'lemburassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `lemburassignment`
  MODIFY COLUMN `LemburID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  MODIFY COLUMN `LemburStatusID` int DEFAULT NULL,
  ADD INDEX `lemburassignment_LemburStatusID` (`LemburStatusID`),
  ADD INDEX `lemburassignment_UserID` (`UserID`),
  ADD INDEX `LemburID` (`LemburID`,`UserID`,`LemburStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'ee490b77bc816120111020cf19279c00a8cf75ad1cd768a8b1f5c0f37a227998', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- lemburassignment/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 = 'lemburassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `lemburassignment` c
  LEFT JOIN `lembur` p0 ON c.`LemburID` = p0.`ID`
  LEFT JOIN `lemburstatus` p1 ON c.`LemburStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
   SET
       c.`LemburID` = IF((c.`LemburID` IS NOT NULL AND (c.`LemburID` = 0 OR p0.`ID` IS NULL)), NULL, c.`LemburID`),
       c.`LemburStatusID` = IF((c.`LemburStatusID` IS NOT NULL AND (c.`LemburStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`LemburStatusID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`LemburID` IS NOT NULL AND (c.`LemburID` = 0 OR p0.`ID` IS NULL))
    OR (c.`LemburStatusID` IS NOT NULL AND (c.`LemburStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 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(), '1305bf0f1e243c4142c1f1fccd3a9097737340a10d0df22ad0eb626acfabd445', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- lemburassignment/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 = 'lemburassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `lemburassignment` c
  LEFT JOIN `lembur` p0 ON c.`LemburID` = p0.`ID`
  LEFT JOIN `lemburstatus` p1 ON c.`LemburStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
 WHERE  (c.`LemburID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`LemburStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserID` 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,
          'lemburassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `lemburassignment` 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(), '442475d85f951e634dd674553140127423e10618fe520404f3c82050385bc548', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- lemburassignment/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 = 'lemburassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `lemburassignment`
  ADD CONSTRAINT `lemburassignment_LemburID` FOREIGN KEY (`LemburID`) REFERENCES `lembur` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `lemburassignment_LemburStatusID` FOREIGN KEY (`LemburStatusID`) REFERENCES `lemburstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `lemburassignment_UserID` FOREIGN KEY (`UserID`) 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(), 'f36a9010e66411adb57d7226222134899e45fa061d0441b83d0dd00396e00493', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: onleave    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- onleave/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 = 'onleave/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `onleave`
  MODIFY COLUMN `OnLeaveStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  MODIFY COLUMN `UserPengganti1` int DEFAULT NULL,
  MODIFY COLUMN `UserPengganti2` int DEFAULT NULL,
  MODIFY COLUMN `OnLeaveLimitID` int DEFAULT NULL,
  ADD INDEX `onleave_OnLeaveLimitID` (`OnLeaveLimitID`),
  ADD INDEX `onleave_UserIDInput` (`UserIDInput`),
  ADD INDEX `onleave_UserIDSales` (`UserIDSales`),
  ADD INDEX `onleave_UserPengganti1` (`UserPengganti1`),
  ADD INDEX `onleave_UserPengganti2` (`UserPengganti2`),
  ADD INDEX `OnLeaveStatusID` (`OnLeaveStatusID`,`UserIDInput`,`UserIDSales`,`UserPengganti1`,`UserPengganti2`,`OnLeaveLimitID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '62061a7194bdd301b1323611010f3c94c69694cc58b77dd7b40d9b1911e9ff4d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- onleave/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 = 'onleave/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `onleave` c
  LEFT JOIN `onleavelimit` p0 ON c.`OnLeaveLimitID` = p0.`ID`
  LEFT JOIN `onleavestatus` p1 ON c.`OnLeaveStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDSales` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserPengganti1` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserPengganti2` = p5.`ID`
   SET
       c.`OnLeaveLimitID` = IF((c.`OnLeaveLimitID` IS NOT NULL AND (c.`OnLeaveLimitID` = 0 OR p0.`ID` IS NULL)), NULL, c.`OnLeaveLimitID`),
       c.`OnLeaveStatusID` = IF((c.`OnLeaveStatusID` IS NOT NULL AND (c.`OnLeaveStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`OnLeaveStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserIDSales`),
       c.`UserPengganti1` = IF((c.`UserPengganti1` IS NOT NULL AND (c.`UserPengganti1` = 0 OR p4.`ID` IS NULL)), NULL, c.`UserPengganti1`),
       c.`UserPengganti2` = IF((c.`UserPengganti2` IS NOT NULL AND (c.`UserPengganti2` = 0 OR p5.`ID` IS NULL)), NULL, c.`UserPengganti2`)
 WHERE  (c.`OnLeaveLimitID` IS NOT NULL AND (c.`OnLeaveLimitID` = 0 OR p0.`ID` IS NULL))
    OR (c.`OnLeaveStatusID` IS NOT NULL AND (c.`OnLeaveStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p3.`ID` IS NULL))
    OR (c.`UserPengganti1` IS NOT NULL AND (c.`UserPengganti1` = 0 OR p4.`ID` IS NULL))
    OR (c.`UserPengganti2` IS NOT NULL AND (c.`UserPengganti2` = 0 OR p5.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'e4b06d03e4470b7e1ebafe471055758aee541d27e5cf172c99c7c08f7d98ddb8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'onleave/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `onleave` c
  LEFT JOIN `onleavelimit` p0 ON c.`OnLeaveLimitID` = p0.`ID`
  LEFT JOIN `onleavestatus` p1 ON c.`OnLeaveStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserIDSales` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserPengganti1` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserPengganti2` = p5.`ID`
 WHERE  (c.`OnLeaveLimitID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`OnLeaveStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UserPengganti1` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`UserPengganti2` IS NOT NULL AND p5.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'onleave: orphan check OK - 0 rows across 6 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `onleave` 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(), 'b81d1462d7c40a6947839c1aac63eeb123190f0c23534ebb3382afccd8037da6', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- onleave/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 = 'onleave/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `onleave`
  ADD CONSTRAINT `onleave_OnLeaveLimitID` FOREIGN KEY (`OnLeaveLimitID`) REFERENCES `onleavelimit` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleave_OnLeaveStatusID` FOREIGN KEY (`OnLeaveStatusID`) REFERENCES `onleavestatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleave_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleave_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleave_UserPengganti1` FOREIGN KEY (`UserPengganti1`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleave_UserPengganti2` FOREIGN KEY (`UserPengganti2`) 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(), '1a5a5b44f9e2aeb92156f4e6f7579ae1d34f1fbd01f170e7333612fac065d3bf', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: onleaveadditional    (detail, owned by onleave)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- onleaveadditional/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 = 'onleaveadditional/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `onleaveadditional`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  MODIFY COLUMN `OnLeaveLimitID` int DEFAULT NULL,
  ADD INDEX `onleaveadditional_OnLeaveLimitID` (`OnLeaveLimitID`),
  ADD INDEX `onleaveadditional_UserID` (`UserID`),
  ADD INDEX `UserIDInput` (`UserIDInput`,`UserID`,`OnLeaveLimitID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '17e7a6a2b47c18e9e14dda947e646984a44b5e73f21089954a4ee1c160c99db7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- onleaveadditional/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 = 'onleaveadditional/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `onleaveadditional` c
  LEFT JOIN `onleavelimit` p0 ON c.`OnLeaveLimitID` = p0.`ID`
  LEFT JOIN `users` p1 ON c.`UserID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`OnLeaveLimitID` = IF((c.`OnLeaveLimitID` IS NOT NULL AND (c.`OnLeaveLimitID` = 0 OR p0.`ID` IS NULL)), NULL, c.`OnLeaveLimitID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p1.`ID` IS NULL)), NULL, c.`UserID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`OnLeaveLimitID` IS NOT NULL AND (c.`OnLeaveLimitID` = 0 OR p0.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 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(), '95339ece160db45c9ce826d4bfe9c881f168272b1536f1a580e5679a0c31b11a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- onleaveadditional/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 = 'onleaveadditional/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `onleaveadditional` c
  LEFT JOIN `onleavelimit` p0 ON c.`OnLeaveLimitID` = p0.`ID`
  LEFT JOIN `users` p1 ON c.`UserID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`OnLeaveLimitID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`UserID` 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,
          'onleaveadditional: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `onleaveadditional` 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(), '0884edf11e922e2adb60d92c9e63d78c79129e07a4c098d79a2f654a8be01cf0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- onleaveadditional/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 = 'onleaveadditional/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `onleaveadditional`
  ADD CONSTRAINT `onleaveadditional_OnLeaveLimitID` FOREIGN KEY (`OnLeaveLimitID`) REFERENCES `onleavelimit` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleaveadditional_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleaveadditional_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(), '2c0da438f12c0848471d153aedef43562269a769f1ef6cc6692f3a30bd01ec74', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

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


-- ---------------------------------------------------------------------
-- unit: onleaveassignment    (detail, owned by onleave)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- onleaveassignment/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 = 'onleaveassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `onleaveassignment`
  MODIFY COLUMN `OnLeaveID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  MODIFY COLUMN `OnLeaveStatusID` int DEFAULT NULL,
  ADD INDEX `onleaveassignment_OnLeaveStatusID` (`OnLeaveStatusID`),
  ADD INDEX `onleaveassignment_UserID` (`UserID`),
  ADD INDEX `OnLeaveID` (`OnLeaveID`,`UserID`,`OnLeaveStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '3610d59f2aad41bf6adad36f8766b4db0e5879a11414304caed0e920ad67e23f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- onleaveassignment/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 = 'onleaveassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `onleaveassignment` c
  LEFT JOIN `onleave` p0 ON c.`OnLeaveID` = p0.`ID`
  LEFT JOIN `onleavestatus` p1 ON c.`OnLeaveStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
   SET
       c.`OnLeaveID` = IF((c.`OnLeaveID` IS NOT NULL AND (c.`OnLeaveID` = 0 OR p0.`ID` IS NULL)), NULL, c.`OnLeaveID`),
       c.`OnLeaveStatusID` = IF((c.`OnLeaveStatusID` IS NOT NULL AND (c.`OnLeaveStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`OnLeaveStatusID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`OnLeaveID` IS NOT NULL AND (c.`OnLeaveID` = 0 OR p0.`ID` IS NULL))
    OR (c.`OnLeaveStatusID` IS NOT NULL AND (c.`OnLeaveStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 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(), 'ec6244532bc13aa77d400de473b609a8f2182ad93454916f606228f67e3b7ffa', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- onleaveassignment/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 = 'onleaveassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `onleaveassignment` c
  LEFT JOIN `onleave` p0 ON c.`OnLeaveID` = p0.`ID`
  LEFT JOIN `onleavestatus` p1 ON c.`OnLeaveStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
 WHERE  (c.`OnLeaveID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`OnLeaveStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserID` 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,
          'onleaveassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `onleaveassignment` 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(), '96b47d015f3db9b0c1d7ee8a02b665e9a30917c3c38dcc0bc495690586086b66', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- onleaveassignment/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 = 'onleaveassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `onleaveassignment`
  ADD CONSTRAINT `onleaveassignment_OnLeaveID` FOREIGN KEY (`OnLeaveID`) REFERENCES `onleave` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleaveassignment_OnLeaveStatusID` FOREIGN KEY (`OnLeaveStatusID`) REFERENCES `onleavestatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `onleaveassignment_UserID` FOREIGN KEY (`UserID`) 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(), 'c8f330e2fdc46630461252d6d54fdab12542aa79798072621dbf10bbfeaece4b', 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 = 29;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'izin.izin_IzinStatusID' AS n UNION ALL SELECT 'izin.izin_IzinTypeID' UNION ALL SELECT 'izin.izin_IzinTypeStatusID' UNION ALL SELECT 'izin.izin_UserIDInput' UNION ALL SELECT 'izin.izin_UserIDSales' UNION ALL SELECT 'izinassignment.izinassignment_IzinID' UNION ALL SELECT 'izinassignment.izinassignment_IzinStatusID' UNION ALL SELECT 'izinassignment.izinassignment_UserID' UNION ALL SELECT 'lembur.lembur_LemburStatusID' UNION ALL SELECT 'lembur.lembur_LemburTypeID' UNION ALL SELECT 'lembur.lembur_UserIDInput' UNION ALL SELECT 'lembur.lembur_UserIDSales' UNION ALL SELECT 'lemburassignment.lemburassignment_LemburID' UNION ALL SELECT 'lemburassignment.lemburassignment_LemburStatusID' UNION ALL SELECT 'lemburassignment.lemburassignment_UserID' UNION ALL SELECT 'onleave.onleave_OnLeaveLimitID' UNION ALL SELECT 'onleave.onleave_OnLeaveStatusID' UNION ALL SELECT 'onleave.onleave_UserIDInput' UNION ALL SELECT 'onleave.onleave_UserIDSales' UNION ALL SELECT 'onleave.onleave_UserPengganti1' UNION ALL SELECT 'onleave.onleave_UserPengganti2' UNION ALL SELECT 'onleaveadditional.onleaveadditional_OnLeaveLimitID' UNION ALL SELECT 'onleaveadditional.onleaveadditional_UserID' UNION ALL SELECT 'onleaveadditional.onleaveadditional_UserIDInput' UNION ALL SELECT 'onleaveadditionalassignment.onleaveadditionalassignment_OnLeaveAdditionalID' UNION ALL SELECT 'onleaveadditionalassignment.onleaveadditionalassignment_UserID' UNION ALL SELECT 'onleaveassignment.onleaveassignment_OnLeaveID' UNION ALL SELECT 'onleaveassignment.onleaveassignment_OnLeaveStatusID' UNION ALL SELECT 'onleaveassignment.onleaveassignment_UserID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 29;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'izin.IzinTypeID' AS n UNION ALL SELECT 'izin.izin_IzinStatusID' UNION ALL SELECT 'izin.izin_IzinTypeStatusID' UNION ALL SELECT 'izin.izin_UserIDInput' UNION ALL SELECT 'izin.izin_UserIDSales' UNION ALL SELECT 'izinassignment.IzinID' UNION ALL SELECT 'izinassignment.izinassignment_IzinStatusID' UNION ALL SELECT 'izinassignment.izinassignment_UserID' UNION ALL SELECT 'lembur.LemburTypeID' UNION ALL SELECT 'lembur.lembur_LemburStatusID' UNION ALL SELECT 'lembur.lembur_UserIDInput' UNION ALL SELECT 'lembur.lembur_UserIDSales' UNION ALL SELECT 'lemburassignment.LemburID' UNION ALL SELECT 'lemburassignment.lemburassignment_LemburStatusID' UNION ALL SELECT 'lemburassignment.lemburassignment_UserID' UNION ALL SELECT 'onleave.OnLeaveStatusID' UNION ALL SELECT 'onleave.onleave_OnLeaveLimitID' UNION ALL SELECT 'onleave.onleave_UserIDInput' UNION ALL SELECT 'onleave.onleave_UserIDSales' UNION ALL SELECT 'onleave.onleave_UserPengganti1' UNION ALL SELECT 'onleave.onleave_UserPengganti2' UNION ALL SELECT 'onleaveadditional.UserIDInput' UNION ALL SELECT 'onleaveadditional.onleaveadditional_OnLeaveLimitID' UNION ALL SELECT 'onleaveadditional.onleaveadditional_UserID' UNION ALL SELECT 'onleaveadditionalassignment.OnLeaveAdditionalID' UNION ALL SELECT 'onleaveadditionalassignment.onleaveadditionalassignment_UserID' UNION ALL SELECT 'onleaveassignment.OnLeaveID' UNION ALL SELECT 'onleaveassignment.onleaveassignment_OnLeaveStatusID' UNION ALL SELECT 'onleaveassignment.onleaveassignment_UserID') _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 = 29;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'izin.IzinStatusID.int' AS n UNION ALL SELECT 'izin.IzinTypeID.int' UNION ALL SELECT 'izin.IzinTypeStatusID.int' UNION ALL SELECT 'izin.UserIDInput.int' UNION ALL SELECT 'izin.UserIDSales.int' UNION ALL SELECT 'izinassignment.IzinID.int' UNION ALL SELECT 'izinassignment.IzinStatusID.int' UNION ALL SELECT 'izinassignment.UserID.int' UNION ALL SELECT 'lembur.LemburStatusID.int' UNION ALL SELECT 'lembur.LemburTypeID.int' UNION ALL SELECT 'lembur.UserIDInput.int' UNION ALL SELECT 'lembur.UserIDSales.int' UNION ALL SELECT 'lemburassignment.LemburID.int' UNION ALL SELECT 'lemburassignment.LemburStatusID.int' UNION ALL SELECT 'lemburassignment.UserID.int' UNION ALL SELECT 'onleave.OnLeaveLimitID.int' UNION ALL SELECT 'onleave.OnLeaveStatusID.int' UNION ALL SELECT 'onleave.UserIDInput.int' UNION ALL SELECT 'onleave.UserIDSales.int' UNION ALL SELECT 'onleave.UserPengganti1.int' UNION ALL SELECT 'onleave.UserPengganti2.int' UNION ALL SELECT 'onleaveadditional.OnLeaveLimitID.int' UNION ALL SELECT 'onleaveadditional.UserID.int' UNION ALL SELECT 'onleaveadditional.UserIDInput.int' UNION ALL SELECT 'onleaveadditionalassignment.OnLeaveAdditionalID.int' UNION ALL SELECT 'onleaveadditionalassignment.UserID.int' UNION ALL SELECT 'onleaveassignment.OnLeaveID.int' UNION ALL SELECT 'onleaveassignment.OnLeaveStatusID.int' UNION ALL SELECT 'onleaveassignment.UserID.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);
