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

-- Menus this file serves (21 links):
--   /lwr-feedback-statuses
--   /lwrs
--   /lwrs/approval-pm
--   /lwrs/approval-sm
--   /lwrs/cancel
--   /lwrs/change-status
--   /lwrs/create
--   /lwrs/create-for-others
--   /lwrs/create-for-others-pm
--   /lwrs/feedback
--   /lwrs/pengerjaan-lab
--   /lwrs/view-all
--   /lwrs/view-all-lab
--   /lwrs/view-all-lab-div
--   /lwrs/view-details
--   /lwrs/view-details-head-dept
--   /lwrs/view-details-mm
--   /lwrs/view-details-pm
--   /lwrs/view-details-sm
--   /lwrs/view-head-dept
--   /lwrs/view-pengerjaan-lab

-- --------------------------------------------------------------- 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 ('labworkrequest/10_alter', 'labworkrequest/20_cleanup', 'labworkrequest/30_assert', 'labworkrequest/40_fk', 'labworkrequestassignment/10_alter', 'labworkrequestassignment/20_cleanup', 'labworkrequestassignment/30_assert', 'labworkrequestassignment/40_fk', 'labworkrequestdetails/10_alter', 'labworkrequestdetails/20_cleanup', 'labworkrequestdetails/30_assert', 'labworkrequestdetails/40_fk', 'labworkrequestdetailsassignment/10_alter', 'labworkrequestdetailsassignment/20_cleanup', 'labworkrequestdetailsassignment/30_assert', 'labworkrequestdetailsassignment/40_fk', 'labworkrequestlink/10_alter', 'labworkrequestlink/20_cleanup', 'labworkrequestlink/30_assert', 'labworkrequestlink/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('labworkrequest/10_alter:403cc78ac9452c4c2b12c9503e6fcad38db8ca129fc8d81e15a0f54f3a5ed430', 'labworkrequest/20_cleanup:f474cdaec4c343c2116fbcb4facab7848cbe8fc7564a96b7c35ef03a74555e75', 'labworkrequest/30_assert:693defeb2500d15fb3628e9b13fba7270f42f3019c220e974fdbfd034e9b17c9', 'labworkrequest/40_fk:fd5d3594508466d9632e074a1d571ebcc2bdd11bb442890136d764210ef8cffb', 'labworkrequestassignment/10_alter:8fd723d6eabf6ed56124fedbc0cc41acb391d8139d8294b0114d66d6deeacfee', 'labworkrequestassignment/20_cleanup:ea170bca3f092e0a948d11b01b8122e1207305e87cff389417084758db216a1e', 'labworkrequestassignment/30_assert:263c514406f5973422801586b8940a27197b8fd97041d5d55a81a435e472fbd1', 'labworkrequestassignment/40_fk:4fbcd1f4124915a7713b8269accbb7cb16d6d5b0e9343f4c5c62577923ca8e9c', 'labworkrequestdetails/10_alter:826450595943a4efd2be44765466932b21e74b2798f4112a5a90c5fd09a49e38', 'labworkrequestdetails/20_cleanup:8c7d39e680005e03f4306357949ac1594b189a0c1ec680dabca7fe71d95d984d', 'labworkrequestdetails/30_assert:6d70b8938d0ff16d88cebdfae6fb6169d1b00e192def4887a23ea79ac8fac405', 'labworkrequestdetails/40_fk:d65875705e324398840df8ed5e88cf03c073700e44b822c84a6b9bee85b67f49', 'labworkrequestdetailsassignment/10_alter:cce22867d6d9568769ea68c15081a02235c783417c4e2c33a55b842dcd91dae3', 'labworkrequestdetailsassignment/20_cleanup:604703989a6f503d9b59d4c632b49b557f6f470064c8a1fd0419604e970e7ab0', 'labworkrequestdetailsassignment/30_assert:fd73676687003c88708ebc826a7c2469a1abb06f6bddb36db7c21a97df483c7c', 'labworkrequestdetailsassignment/40_fk:5f03174bf54cf5af8ab6ef684f9366fa1e418ee427f38fd448f0cff52549ba0d', 'labworkrequestlink/10_alter:166d8a3f1f284e731aad51c911509b4dbeadfb4af16b341ec5d9a6285f27552c', 'labworkrequestlink/20_cleanup:eedacc8ca1d2edb5db6c8202481b4ae88130c6116e15a15821b759ec3df162fb', 'labworkrequestlink/30_assert:5089a1c4968dc0a288ae822dbb6977a217c188500eb4e438385fb6df13eceb78', 'labworkrequestlink/40_fk:62e43a227784cf417a74622beb2b59afe1a4629ccd21331f697a086509c8e035');
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: labworkrequest    (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'));
-- ---------------------------------------------------------------------
-- labworkrequest/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 = 'labworkrequest/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequest`
  MODIFY COLUMN `LabWorkRequestStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `IndustryID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDProjectInitiator` int DEFAULT NULL,
  MODIFY COLUMN `LabWorkRequestFeedbackStatusID` int DEFAULT NULL,
  ADD INDEX `labworkrequest_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `labworkrequest_CompanyID` (`CompanyID`),
  ADD INDEX `labworkrequest_DivisionID` (`DivisionID`),
  ADD INDEX `labworkrequest_IndustryID` (`IndustryID`),
  ADD INDEX `labworkrequest_LabWorkRequestFeedbackStatusID` (`LabWorkRequestFeedbackStatusID`),
  ADD INDEX `labworkrequest_ProjectID` (`ProjectID`),
  ADD INDEX `labworkrequest_UserIDInput` (`UserIDInput`),
  ADD INDEX `labworkrequest_UserIDProjectInitiator` (`UserIDProjectInitiator`),
  ADD INDEX `labworkrequest_UserIDSales` (`UserIDSales`),
  ADD INDEX `LabWorkRequestStatusID` (`LabWorkRequestStatusID`,`UserIDInput`,`UserIDSales`,`DivisionID`,`CompanyID`,`CompanyCPID`,`LabWorkRequestFeedbackStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '403cc78ac9452c4c2b12c9503e6fcad38db8ca129fc8d81e15a0f54f3a5ed430', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequest/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 = 'labworkrequest/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `labworkrequest` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `industry` p3 ON c.`IndustryID` = p3.`ID`
  LEFT JOIN `labworkrequestfeedbackstatus` p4 ON c.`LabWorkRequestFeedbackStatusID` = p4.`ID`
  LEFT JOIN `labworkrequeststatus` p5 ON c.`LabWorkRequestStatusID` = p5.`ID`
  LEFT JOIN `companyproject` p6 ON c.`ProjectID` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDInput` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDProjectInitiator` = p8.`ID`
  LEFT JOIN `users` p9 ON c.`UserIDSales` = p9.`ID`
   SET
       c.`CompanyCPID` = IF((c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCPID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p3.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`LabWorkRequestFeedbackStatusID` = IF((c.`LabWorkRequestFeedbackStatusID` IS NOT NULL AND (c.`LabWorkRequestFeedbackStatusID` = 0 OR p4.`ID` IS NULL)), NULL, c.`LabWorkRequestFeedbackStatusID`),
       c.`LabWorkRequestStatusID` = IF((c.`LabWorkRequestStatusID` IS NOT NULL AND (c.`LabWorkRequestStatusID` = 0 OR p5.`ID` IS NULL)), NULL, c.`LabWorkRequestStatusID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p6.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p7.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDProjectInitiator` = IF((c.`UserIDProjectInitiator` IS NOT NULL AND (c.`UserIDProjectInitiator` = 0 OR p8.`ID` IS NULL)), NULL, c.`UserIDProjectInitiator`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p9.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p3.`ID` IS NULL))
    OR (c.`LabWorkRequestFeedbackStatusID` IS NOT NULL AND (c.`LabWorkRequestFeedbackStatusID` = 0 OR p4.`ID` IS NULL))
    OR (c.`LabWorkRequestStatusID` IS NOT NULL AND (c.`LabWorkRequestStatusID` = 0 OR p5.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p6.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p7.`ID` IS NULL))
    OR (c.`UserIDProjectInitiator` IS NOT NULL AND (c.`UserIDProjectInitiator` = 0 OR p8.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p9.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f474cdaec4c343c2116fbcb4facab7848cbe8fc7564a96b7c35ef03a74555e75', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'labworkrequest/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `labworkrequest` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `industry` p3 ON c.`IndustryID` = p3.`ID`
  LEFT JOIN `labworkrequestfeedbackstatus` p4 ON c.`LabWorkRequestFeedbackStatusID` = p4.`ID`
  LEFT JOIN `labworkrequeststatus` p5 ON c.`LabWorkRequestStatusID` = p5.`ID`
  LEFT JOIN `companyproject` p6 ON c.`ProjectID` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDInput` = p7.`ID`
  LEFT JOIN `users` p8 ON c.`UserIDProjectInitiator` = p8.`ID`
  LEFT JOIN `users` p9 ON c.`UserIDSales` = p9.`ID`
 WHERE  (c.`CompanyCPID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`LabWorkRequestFeedbackStatusID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`LabWorkRequestStatusID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`UserIDProjectInitiator` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p9.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'labworkrequest: orphan check OK - 0 rows across 10 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `labworkrequest` 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(), '693defeb2500d15fb3628e9b13fba7270f42f3019c220e974fdbfd034e9b17c9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequest/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 = 'labworkrequest/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequest`
  ADD CONSTRAINT `labworkrequest_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_LabWorkRequestFeedbackStatusID` FOREIGN KEY (`LabWorkRequestFeedbackStatusID`) REFERENCES `labworkrequestfeedbackstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_LabWorkRequestStatusID` FOREIGN KEY (`LabWorkRequestStatusID`) REFERENCES `labworkrequeststatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_UserIDProjectInitiator` FOREIGN KEY (`UserIDProjectInitiator`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequest_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(), 'fd5d3594508466d9632e074a1d571ebcc2bdd11bb442890136d764210ef8cffb', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: labworkrequestassignment    (detail, owned by labworkrequest)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- labworkrequestassignment/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 = 'labworkrequestassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestassignment`
  MODIFY COLUMN `LabWorkRequestID` int DEFAULT NULL,
  MODIFY COLUMN `LabWorkRequestStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `labworkrequestassignment_LabWorkRequestStatusID` (`LabWorkRequestStatusID`),
  ADD INDEX `LabWorkRequestID` (`LabWorkRequestID`,`LabWorkRequestStatusID`),
  ADD INDEX `UserID` (`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(), '8fd723d6eabf6ed56124fedbc0cc41acb391d8139d8294b0114d66d6deeacfee', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestassignment/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 = 'labworkrequestassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `labworkrequestassignment` c
  LEFT JOIN `labworkrequest` p0 ON c.`LabWorkRequestID` = p0.`ID`
  LEFT JOIN `labworkrequeststatus` p1 ON c.`LabWorkRequestStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
   SET
       c.`LabWorkRequestID` = IF((c.`LabWorkRequestID` IS NOT NULL AND (c.`LabWorkRequestID` = 0 OR p0.`ID` IS NULL)), NULL, c.`LabWorkRequestID`),
       c.`LabWorkRequestStatusID` = IF((c.`LabWorkRequestStatusID` IS NOT NULL AND (c.`LabWorkRequestStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`LabWorkRequestStatusID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`LabWorkRequestID` IS NOT NULL AND (c.`LabWorkRequestID` = 0 OR p0.`ID` IS NULL))
    OR (c.`LabWorkRequestStatusID` IS NOT NULL AND (c.`LabWorkRequestStatusID` = 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(), 'ea170bca3f092e0a948d11b01b8122e1207305e87cff389417084758db216a1e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- labworkrequestassignment/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 = 'labworkrequestassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `labworkrequestassignment` c
  LEFT JOIN `labworkrequest` p0 ON c.`LabWorkRequestID` = p0.`ID`
  LEFT JOIN `labworkrequeststatus` p1 ON c.`LabWorkRequestStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
 WHERE  (c.`LabWorkRequestID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`LabWorkRequestStatusID` 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,
          'labworkrequestassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `labworkrequestassignment` 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(), '263c514406f5973422801586b8940a27197b8fd97041d5d55a81a435e472fbd1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestassignment/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 = 'labworkrequestassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestassignment`
  ADD CONSTRAINT `labworkrequestassignment_LabWorkRequestID` FOREIGN KEY (`LabWorkRequestID`) REFERENCES `labworkrequest` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestassignment_LabWorkRequestStatusID` FOREIGN KEY (`LabWorkRequestStatusID`) REFERENCES `labworkrequeststatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestassignment_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(), '4fbcd1f4124915a7713b8269accbb7cb16d6d5b0e9343f4c5c62577923ca8e9c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: labworkrequestdetails    (detail, owned by labworkrequest)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- labworkrequestdetails/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 = 'labworkrequestdetails/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestdetails`
  MODIFY COLUMN `LabWorkRequestDetailStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectIDComp` int DEFAULT NULL,
  MODIFY COLUMN `LabWorkRequestID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `TypeID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanIDVolume` int DEFAULT NULL,
  MODIFY COLUMN `SatuanIDUnitPrice` int DEFAULT NULL,
  ADD INDEX `labworkrequestdetails_BarangID` (`BarangID`),
  ADD INDEX `labworkrequestdetails_LabWorkRequestID` (`LabWorkRequestID`),
  ADD INDEX `labworkrequestdetails_PrincipalID` (`PrincipalID`),
  ADD INDEX `labworkrequestdetails_ProjectID` (`ProjectID`),
  ADD INDEX `labworkrequestdetails_ProjectIDComp` (`ProjectIDComp`),
  ADD INDEX `labworkrequestdetails_SatuanIDUnitPrice` (`SatuanIDUnitPrice`),
  ADD INDEX `labworkrequestdetails_SatuanIDVolume` (`SatuanIDVolume`),
  ADD INDEX `labworkrequestdetails_TypeID` (`TypeID`),
  ADD INDEX `LabWorkRequestDetailStatusID` (`LabWorkRequestDetailStatusID`,`LabWorkRequestID`,`ProductCategory`,`PrincipalID`,`BarangID`,`TypeID`,`SatuanIDVolume`,`SatuanIDUnitPrice`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '826450595943a4efd2be44765466932b21e74b2798f4112a5a90c5fd09a49e38', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestdetails/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 = 'labworkrequestdetails/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `labworkrequestdetails` c
  LEFT JOIN `barang` p0 ON c.`BarangID` = p0.`ID`
  LEFT JOIN `labworkrequestdetailstatus` p1 ON c.`LabWorkRequestDetailStatusID` = p1.`ID`
  LEFT JOIN `labworkrequest` p2 ON c.`LabWorkRequestID` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`PrincipalID` = p3.`ID`
  LEFT JOIN `companyprojectdetailcc` p4 ON c.`ProjectID` = p4.`ID`
  LEFT JOIN `companyprojectdetailcomp` p5 ON c.`ProjectIDComp` = p5.`ID`
  LEFT JOIN `satuan` p6 ON c.`SatuanIDUnitPrice` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanIDVolume` = p7.`ID`
  LEFT JOIN `type` p8 ON c.`TypeID` = p8.`ID`
   SET
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p0.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`LabWorkRequestDetailStatusID` = IF((c.`LabWorkRequestDetailStatusID` IS NOT NULL AND (c.`LabWorkRequestDetailStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`LabWorkRequestDetailStatusID`),
       c.`LabWorkRequestID` = IF((c.`LabWorkRequestID` IS NOT NULL AND (c.`LabWorkRequestID` = 0 OR p2.`ID` IS NULL)), NULL, c.`LabWorkRequestID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p3.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`ProjectIDComp` = IF((c.`ProjectIDComp` IS NOT NULL AND (c.`ProjectIDComp` = 0 OR p5.`ID` IS NULL)), NULL, c.`ProjectIDComp`),
       c.`SatuanIDUnitPrice` = IF((c.`SatuanIDUnitPrice` IS NOT NULL AND (c.`SatuanIDUnitPrice` = 0 OR p6.`ID` IS NULL)), NULL, c.`SatuanIDUnitPrice`),
       c.`SatuanIDVolume` = IF((c.`SatuanIDVolume` IS NOT NULL AND (c.`SatuanIDVolume` = 0 OR p7.`ID` IS NULL)), NULL, c.`SatuanIDVolume`),
       c.`TypeID` = IF((c.`TypeID` IS NOT NULL AND (c.`TypeID` = 0 OR p8.`ID` IS NULL)), NULL, c.`TypeID`)
 WHERE  (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p0.`ID` IS NULL))
    OR (c.`LabWorkRequestDetailStatusID` IS NOT NULL AND (c.`LabWorkRequestDetailStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`LabWorkRequestID` IS NOT NULL AND (c.`LabWorkRequestID` = 0 OR p2.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p4.`ID` IS NULL))
    OR (c.`ProjectIDComp` IS NOT NULL AND (c.`ProjectIDComp` = 0 OR p5.`ID` IS NULL))
    OR (c.`SatuanIDUnitPrice` IS NOT NULL AND (c.`SatuanIDUnitPrice` = 0 OR p6.`ID` IS NULL))
    OR (c.`SatuanIDVolume` IS NOT NULL AND (c.`SatuanIDVolume` = 0 OR p7.`ID` IS NULL))
    OR (c.`TypeID` IS NOT NULL AND (c.`TypeID` = 0 OR p8.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '8c7d39e680005e03f4306357949ac1594b189a0c1ec680dabca7fe71d95d984d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'labworkrequestdetails/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `labworkrequestdetails` c
  LEFT JOIN `barang` p0 ON c.`BarangID` = p0.`ID`
  LEFT JOIN `labworkrequestdetailstatus` p1 ON c.`LabWorkRequestDetailStatusID` = p1.`ID`
  LEFT JOIN `labworkrequest` p2 ON c.`LabWorkRequestID` = p2.`ID`
  LEFT JOIN `principal` p3 ON c.`PrincipalID` = p3.`ID`
  LEFT JOIN `companyprojectdetailcc` p4 ON c.`ProjectID` = p4.`ID`
  LEFT JOIN `companyprojectdetailcomp` p5 ON c.`ProjectIDComp` = p5.`ID`
  LEFT JOIN `satuan` p6 ON c.`SatuanIDUnitPrice` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanIDVolume` = p7.`ID`
  LEFT JOIN `type` p8 ON c.`TypeID` = p8.`ID`
 WHERE  (c.`BarangID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`LabWorkRequestDetailStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`LabWorkRequestID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`ProjectIDComp` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`SatuanIDUnitPrice` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`SatuanIDVolume` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`TypeID` IS NOT NULL AND p8.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'labworkrequestdetails: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `labworkrequestdetails` 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(), '6d70b8938d0ff16d88cebdfae6fb6169d1b00e192def4887a23ea79ac8fac405', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestdetails/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 = 'labworkrequestdetails/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestdetails`
  ADD CONSTRAINT `labworkrequestdetails_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_LabWorkRequestDetailStatusID` FOREIGN KEY (`LabWorkRequestDetailStatusID`) REFERENCES `labworkrequestdetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_LabWorkRequestID` FOREIGN KEY (`LabWorkRequestID`) REFERENCES `labworkrequest` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyprojectdetailcc` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_ProjectIDComp` FOREIGN KEY (`ProjectIDComp`) REFERENCES `companyprojectdetailcomp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_SatuanIDUnitPrice` FOREIGN KEY (`SatuanIDUnitPrice`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_SatuanIDVolume` FOREIGN KEY (`SatuanIDVolume`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetails_TypeID` FOREIGN KEY (`TypeID`) REFERENCES `type` (`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(), 'd65875705e324398840df8ed5e88cf03c073700e44b822c84a6b9bee85b67f49', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: labworkrequestdetailsassignment    (detail, owned by labworkrequest)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- labworkrequestdetailsassignment/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 = 'labworkrequestdetailsassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestdetailsassignment`
  MODIFY COLUMN `LabWorkRequestID` int DEFAULT NULL,
  MODIFY COLUMN `LabWorkRequestDetailID` int DEFAULT NULL,
  MODIFY COLUMN `LabWorkRequestDetailStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `labworkrequestdetailsassignment_LabWorkRequestDetailID` (`LabWorkRequestDetailID`),
  ADD INDEX `labworkrequestdetailsassignment_LabWorkRequestDetailStatusID` (`LabWorkRequestDetailStatusID`),
  ADD INDEX `labworkrequestdetailsassignment_UserID` (`UserID`),
  ADD INDEX `LabWorkRequestID` (`LabWorkRequestID`,`LabWorkRequestDetailID`,`LabWorkRequestDetailStatusID`,`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(), 'cce22867d6d9568769ea68c15081a02235c783417c4e2c33a55b842dcd91dae3', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestdetailsassignment/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 = 'labworkrequestdetailsassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `labworkrequestdetailsassignment` c
  LEFT JOIN `labworkrequestdetails` p0 ON c.`LabWorkRequestDetailID` = p0.`ID`
  LEFT JOIN `labworkrequestdetailstatus` p1 ON c.`LabWorkRequestDetailStatusID` = p1.`ID`
  LEFT JOIN `labworkrequest` p2 ON c.`LabWorkRequestID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
   SET
       c.`LabWorkRequestDetailID` = IF((c.`LabWorkRequestDetailID` IS NOT NULL AND (c.`LabWorkRequestDetailID` = 0 OR p0.`ID` IS NULL)), NULL, c.`LabWorkRequestDetailID`),
       c.`LabWorkRequestDetailStatusID` = IF((c.`LabWorkRequestDetailStatusID` IS NOT NULL AND (c.`LabWorkRequestDetailStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`LabWorkRequestDetailStatusID`),
       c.`LabWorkRequestID` = IF((c.`LabWorkRequestID` IS NOT NULL AND (c.`LabWorkRequestID` = 0 OR p2.`ID` IS NULL)), NULL, c.`LabWorkRequestID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`LabWorkRequestDetailID` IS NOT NULL AND (c.`LabWorkRequestDetailID` = 0 OR p0.`ID` IS NULL))
    OR (c.`LabWorkRequestDetailStatusID` IS NOT NULL AND (c.`LabWorkRequestDetailStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`LabWorkRequestID` IS NOT NULL AND (c.`LabWorkRequestID` = 0 OR p2.`ID` IS NULL))
    OR (c.`UserID` IS NOT NULL AND (c.`UserID` = 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(), '604703989a6f503d9b59d4c632b49b557f6f470064c8a1fd0419604e970e7ab0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- labworkrequestdetailsassignment/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 = 'labworkrequestdetailsassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `labworkrequestdetailsassignment` c
  LEFT JOIN `labworkrequestdetails` p0 ON c.`LabWorkRequestDetailID` = p0.`ID`
  LEFT JOIN `labworkrequestdetailstatus` p1 ON c.`LabWorkRequestDetailStatusID` = p1.`ID`
  LEFT JOIN `labworkrequest` p2 ON c.`LabWorkRequestID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
 WHERE  (c.`LabWorkRequestDetailID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`LabWorkRequestDetailStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`LabWorkRequestID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`UserID` 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,
          'labworkrequestdetailsassignment: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `labworkrequestdetailsassignment` 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(), 'fd73676687003c88708ebc826a7c2469a1abb06f6bddb36db7c21a97df483c7c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestdetailsassignment/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 = 'labworkrequestdetailsassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestdetailsassignment`
  ADD CONSTRAINT `labworkrequestdetailsassignment_LabWorkRequestDetailID` FOREIGN KEY (`LabWorkRequestDetailID`) REFERENCES `labworkrequestdetails` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetailsassignment_LabWorkRequestDetailStatusID` FOREIGN KEY (`LabWorkRequestDetailStatusID`) REFERENCES `labworkrequestdetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetailsassignment_LabWorkRequestID` FOREIGN KEY (`LabWorkRequestID`) REFERENCES `labworkrequest` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `labworkrequestdetailsassignment_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(), '5f03174bf54cf5af8ab6ef684f9366fa1e418ee427f38fd448f0cff52549ba0d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

COMMIT;
-- ---------------------------------------------------------------------
-- labworkrequestlink/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 = 'labworkrequestlink/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `labworkrequestlink` c
  LEFT JOIN `labworkrequest` p0 ON c.`LabWorkRequestID` = p0.`ID`
 WHERE  (c.`LabWorkRequestID` 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,
          'labworkrequestlink: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `labworkrequestlink` 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(), '5089a1c4968dc0a288ae822dbb6977a217c188500eb4e438385fb6df13eceb78', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- labworkrequestlink/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 = 'labworkrequestlink/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `labworkrequestlink` ADD CONSTRAINT `labworkrequestlink_LabWorkRequestID` FOREIGN KEY (`LabWorkRequestID`) REFERENCES `labworkrequest` (`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(), '62e43a227784cf417a74622beb2b59afe1a4629ccd21331f697a086509c8e035', 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 = 27;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'labworkrequest.labworkrequest_CompanyCPID' AS n UNION ALL SELECT 'labworkrequest.labworkrequest_CompanyID' UNION ALL SELECT 'labworkrequest.labworkrequest_DivisionID' UNION ALL SELECT 'labworkrequest.labworkrequest_IndustryID' UNION ALL SELECT 'labworkrequest.labworkrequest_LabWorkRequestFeedbackStatusID' UNION ALL SELECT 'labworkrequest.labworkrequest_LabWorkRequestStatusID' UNION ALL SELECT 'labworkrequest.labworkrequest_ProjectID' UNION ALL SELECT 'labworkrequest.labworkrequest_UserIDInput' UNION ALL SELECT 'labworkrequest.labworkrequest_UserIDProjectInitiator' UNION ALL SELECT 'labworkrequest.labworkrequest_UserIDSales' UNION ALL SELECT 'labworkrequestassignment.labworkrequestassignment_LabWorkRequestID' UNION ALL SELECT 'labworkrequestassignment.labworkrequestassignment_LabWorkRequestStatusID' UNION ALL SELECT 'labworkrequestassignment.labworkrequestassignment_UserID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_BarangID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_LabWorkRequestDetailStatusID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_LabWorkRequestID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_PrincipalID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_ProjectID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_ProjectIDComp' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_SatuanIDUnitPrice' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_SatuanIDVolume' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_TypeID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_LabWorkRequestDetailID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_LabWorkRequestDetailStatusID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_LabWorkRequestID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_UserID' UNION ALL SELECT 'labworkrequestlink.labworkrequestlink_LabWorkRequestID') _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 = 27;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'labworkrequest.LabWorkRequestStatusID' AS n UNION ALL SELECT 'labworkrequest.labworkrequest_CompanyCPID' UNION ALL SELECT 'labworkrequest.labworkrequest_CompanyID' UNION ALL SELECT 'labworkrequest.labworkrequest_DivisionID' UNION ALL SELECT 'labworkrequest.labworkrequest_IndustryID' UNION ALL SELECT 'labworkrequest.labworkrequest_LabWorkRequestFeedbackStatusID' UNION ALL SELECT 'labworkrequest.labworkrequest_ProjectID' UNION ALL SELECT 'labworkrequest.labworkrequest_UserIDInput' UNION ALL SELECT 'labworkrequest.labworkrequest_UserIDProjectInitiator' UNION ALL SELECT 'labworkrequest.labworkrequest_UserIDSales' UNION ALL SELECT 'labworkrequestassignment.LabWorkRequestID' UNION ALL SELECT 'labworkrequestassignment.UserID' UNION ALL SELECT 'labworkrequestassignment.labworkrequestassignment_LabWorkRequestStatusID' UNION ALL SELECT 'labworkrequestdetails.LabWorkRequestDetailStatusID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_BarangID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_LabWorkRequestID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_PrincipalID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_ProjectID' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_ProjectIDComp' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_SatuanIDUnitPrice' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_SatuanIDVolume' UNION ALL SELECT 'labworkrequestdetails.labworkrequestdetails_TypeID' UNION ALL SELECT 'labworkrequestdetailsassignment.LabWorkRequestID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_LabWorkRequestDetailID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_LabWorkRequestDetailStatusID' UNION ALL SELECT 'labworkrequestdetailsassignment.labworkrequestdetailsassignment_UserID' UNION ALL SELECT 'labworkrequestlink.labworkrequestlink_LabWorkRequestID') _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 = 27;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'labworkrequest.CompanyCPID.int' AS n UNION ALL SELECT 'labworkrequest.CompanyID.int' UNION ALL SELECT 'labworkrequest.DivisionID.int' UNION ALL SELECT 'labworkrequest.IndustryID.int' UNION ALL SELECT 'labworkrequest.LabWorkRequestFeedbackStatusID.int' UNION ALL SELECT 'labworkrequest.LabWorkRequestStatusID.int' UNION ALL SELECT 'labworkrequest.ProjectID.int' UNION ALL SELECT 'labworkrequest.UserIDInput.int' UNION ALL SELECT 'labworkrequest.UserIDProjectInitiator.int' UNION ALL SELECT 'labworkrequest.UserIDSales.int' UNION ALL SELECT 'labworkrequestassignment.LabWorkRequestID.int' UNION ALL SELECT 'labworkrequestassignment.LabWorkRequestStatusID.int' UNION ALL SELECT 'labworkrequestassignment.UserID.int' UNION ALL SELECT 'labworkrequestdetails.BarangID.int' UNION ALL SELECT 'labworkrequestdetails.LabWorkRequestDetailStatusID.int' UNION ALL SELECT 'labworkrequestdetails.LabWorkRequestID.int' UNION ALL SELECT 'labworkrequestdetails.PrincipalID.int' UNION ALL SELECT 'labworkrequestdetails.ProjectID.int' UNION ALL SELECT 'labworkrequestdetails.ProjectIDComp.int' UNION ALL SELECT 'labworkrequestdetails.SatuanIDUnitPrice.int' UNION ALL SELECT 'labworkrequestdetails.SatuanIDVolume.int' UNION ALL SELECT 'labworkrequestdetails.TypeID.int' UNION ALL SELECT 'labworkrequestdetailsassignment.LabWorkRequestDetailID.int' UNION ALL SELECT 'labworkrequestdetailsassignment.LabWorkRequestDetailStatusID.int' UNION ALL SELECT 'labworkrequestdetailsassignment.LabWorkRequestID.int' UNION ALL SELECT 'labworkrequestdetailsassignment.UserID.int' UNION ALL SELECT 'labworkrequestlink.LabWorkRequestID.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);
