-- =====================================================================
-- 31_sampleorder.sql
-- Sample Order and Surat Jalan
--
-- 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, 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 (20 links):
--   /sample-orders
--   /sample-orders/approval-pm
--   /sample-orders/approval-sm
--   /sample-orders/create
--   /sample-orders/create-sales-admin
--   /sample-orders/feedback
--   /sample-orders/good-issue
--   /sample-orders/packing
--   /sample-orders/request-vs-stock
--   /sample-orders/surat-jalan
--   /sample-orders/view-all-readonly
--   /sample-orders/view-details
--   /sample-orders/view-details-head-dept
--   /sample-orders/view-details-mm
--   /sample-orders/view-details-pm
--   /sample-orders/view-details-sm
--   /sample-orders/view-head
--   /sample-orders/view-request
--   /sample-orders/view-sm
--   /sample-orders/view-surat-jalan

-- --------------------------------------------------------------- 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 ('baranglist/10_alter', 'baranglist/20_cleanup', 'baranglist/30_assert', 'baranglist/40_fk', 'sampleorder/10_alter', 'sampleorder/20_cleanup', 'sampleorder/30_assert', 'sampleorder/40_fk', 'sampleorderassignment/10_alter', 'sampleorderassignment/20_cleanup', 'sampleorderassignment/30_assert', 'sampleorderassignment/40_fk', 'sampleorderdetail/10_alter', 'sampleorderdetail/20_cleanup', 'sampleorderdetail/30_assert', 'sampleorderdetail/40_fk', 'sampleorderdetailassignment/10_alter', 'sampleorderdetailassignment/20_cleanup', 'sampleorderdetailassignment/30_assert', 'sampleorderdetailassignment/40_fk', 'sampleorderlink/10_alter', 'sampleorderlink/20_cleanup', 'sampleorderlink/30_assert', 'sampleorderlink/40_fk', 'suratjalan/10_alter', 'suratjalan/20_cleanup', 'suratjalan/30_assert', 'suratjalan/40_fk', 'suratjalandetails/10_alter', 'suratjalandetails/20_cleanup', 'suratjalandetails/30_assert', 'suratjalandetails/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('baranglist/10_alter:2df11bb412dd905cdd9faf7783021ff9643538db7e4dc2e24da08b6674575fbc', 'baranglist/20_cleanup:fedb48a22d9dc58d244e353509be01ec46cc9332f683ad96f6d05bc4656bfbd2', 'baranglist/30_assert:9d9ecd3e7e6b34749c96fccb025ca873d59bacec4ef31c586adecdbf364a533e', 'baranglist/40_fk:77afb3307e425bbe8c645b43fd958881ade3e9cdc47a68e26debd147c28500a0', 'sampleorder/10_alter:9659348095e65779f48f65d37664c56d362e754ace5d235e188cd8e471b7a8f6', 'sampleorder/20_cleanup:8ae47ee4a2bf478261f75e6e4aeda51579183adc7cc381a01ae6487255c84648', 'sampleorder/30_assert:7953dddfb72da8de975ea69055d327e3015131c89ccc51cdee02071edfa33a59', 'sampleorder/40_fk:f4b1d300eb2a70fe2abd882c04541d4a6fe9d1e82f9888d50292d01fc2ef11ef', 'sampleorderassignment/10_alter:499bc2567e1bb7ffdeea362c822c0aecf1b4e2cbf2a067f3704d08b0e58d59d7', 'sampleorderassignment/20_cleanup:cb224d1c8a53c18357d97c81befd9abee4ab42aaa2b1c83b825e7a4b5d322d74', 'sampleorderassignment/30_assert:a8dcc9dfa3ca3c93567c8f53906e3040353b318ebeb89daae900bcb2952ee466', 'sampleorderassignment/40_fk:afba8015a7dcae91cf119d8f96f039bfc045d1d65e79d84d6deb79c40b77a9b5', 'sampleorderdetail/10_alter:93a6a1984ad5c32789d89eb298a1236d654f9dec3a20639328bb3244b991e2ec', 'sampleorderdetail/20_cleanup:7e5b97c4d08299dafe5380b7993b4a8fa27e3e4cac74d412853dfda2a0e192a7', 'sampleorderdetail/30_assert:f392742667c2b7a707cd00d108c254ab33ed7f55885ea05a5c9be21e56c5dc8d', 'sampleorderdetail/40_fk:53a945258c4c70b2762f196d153dd4d8e04905b45c9abc45e2bbf6b64283b070', 'sampleorderdetailassignment/10_alter:c7be3c6aa676e03afe79a7cd2b3668352e40bf5155878ba8ef3d73a6fe5ea8ec', 'sampleorderdetailassignment/20_cleanup:ea1003817a2c46cb263014ceecac460534676133d63f7fc38f3f66f9ccca4394', 'sampleorderdetailassignment/30_assert:b4f6c985d7df8c0b6edf013880cd231cd06a5b24bddbe0fde83c4df57d73a282', 'sampleorderdetailassignment/40_fk:b3ef521057dc804cefc7aead07f1733bc5b1f92c9221c03d4dce07d1a3178867', 'sampleorderlink/10_alter:4e933859e3d88d00df24bf71ee9897558577cf00949a14ad24a609d17609d348', 'sampleorderlink/20_cleanup:b4eb1e5040c485ea76ce397e8e9e916ee09ffd10a27128783a1ead616eed7f12', 'sampleorderlink/30_assert:1353f64b8e1b1b403e512c11604e49143b7a67776fd6a172aa11f9331b2892eb', 'sampleorderlink/40_fk:c934db4d0ba2d66815d8111f7e9a07ba4c5c0d0c88239a6f692359942f30930d', 'suratjalan/10_alter:03a316eef8138ec73bdfbaa8f7b19d272a4244c95952107a6d171df261a4f82c', 'suratjalan/20_cleanup:08e0ac7ad0d177d384dc9f9ef8036d5875cdb1d122fa97e2230d521d90de6802', 'suratjalan/30_assert:f79fcf483adc1724f61b6bdcea6e434f5c7516124fa167cad460361eaa0d828e', 'suratjalan/40_fk:7aea226cc6ebf08f049b39e83e6f3e616697c71e95c63955b9411e85e3d28d10', 'suratjalandetails/10_alter:55ebb37a8b789e12134576698ee8c0016055509e8444aee495150f6d109a50b3', 'suratjalandetails/20_cleanup:ec8d8785c5331191e76553c0e3c8098f20907f3477b7b447b222b356a48e73f4', 'suratjalandetails/30_assert:6fb8e0942c5d81f558d381cfa9782ceefc1861970cfdb561282862506d1b0151', 'suratjalandetails/40_fk:f88c450985e50fa29d834d1cd498d6f3a8848d01670eb07d6be1f99d61e92ac8');
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: sampleorder    (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'));
-- ---------------------------------------------------------------------
-- sampleorder/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 = 'sampleorder/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorder`
  MODIFY COLUMN `SampleOrderStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ReferenceSOID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `DeliveryID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  MODIFY COLUMN `LocationID` 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 `PriorityID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderFeedbackStatusID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderByID` int DEFAULT NULL,
  ADD INDEX `sampleorder_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `sampleorder_CompanyID` (`CompanyID`),
  ADD INDEX `sampleorder_DeliveryID` (`DeliveryID`),
  ADD INDEX `sampleorder_DivisionID` (`DivisionID`),
  ADD INDEX `sampleorder_IndustryID` (`IndustryID`),
  ADD INDEX `sampleorder_LocationID` (`LocationID`),
  ADD INDEX `sampleorder_PriorityID` (`PriorityID`),
  ADD INDEX `sampleorder_ProjectID` (`ProjectID`),
  ADD INDEX `sampleorder_ReferenceSOID` (`ReferenceSOID`),
  ADD INDEX `sampleorder_SampleOrderByID` (`SampleOrderByID`),
  ADD INDEX `sampleorder_SampleOrderFeedbackStatusID` (`SampleOrderFeedbackStatusID`),
  ADD INDEX `sampleorder_UserIDInput` (`UserIDInput`),
  ADD INDEX `sampleorder_UserIDSales` (`UserIDSales`),
  ADD INDEX `SampleOrderStatusID` (`SampleOrderStatusID`,`ReferenceSOID`,`DeliveryID`,`CompanyID`,`CompanyCPID`,`LocationID`,`DivisionID`,`PriorityID`,`SampleOrderFeedbackStatusID`,`SampleOrderByID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '9659348095e65779f48f65d37664c56d362e754ace5d235e188cd8e471b7a8f6', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorder/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 = 'sampleorder/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `sampleorder` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `delivery` p2 ON c.`DeliveryID` = p2.`ID`
  LEFT JOIN `division` p3 ON c.`DivisionID` = p3.`ID`
  LEFT JOIN `industry` p4 ON c.`IndustryID` = p4.`ID`
  LEFT JOIN `location` p5 ON c.`LocationID` = p5.`ID`
  LEFT JOIN `priority` p6 ON c.`PriorityID` = p6.`ID`
  LEFT JOIN `companyproject` p7 ON c.`ProjectID` = p7.`ID`
  LEFT JOIN `sampleorder` p8 ON c.`ReferenceSOID` = p8.`ID`
  LEFT JOIN `sampleorderby` p9 ON c.`SampleOrderByID` = p9.`ID`
  LEFT JOIN `sampleorderfeedbackstatus` p10 ON c.`SampleOrderFeedbackStatusID` = p10.`ID`
  LEFT JOIN `sampleorderstatus` p11 ON c.`SampleOrderStatusID` = p11.`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.`DeliveryID` = IF((c.`DeliveryID` IS NOT NULL AND (c.`DeliveryID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DeliveryID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p3.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p4.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`LocationID` = IF((c.`LocationID` IS NOT NULL AND (c.`LocationID` = 0 OR p5.`ID` IS NULL)), NULL, c.`LocationID`),
       c.`PriorityID` = IF((c.`PriorityID` IS NOT NULL AND (c.`PriorityID` = 0 OR p6.`ID` IS NULL)), NULL, c.`PriorityID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p7.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`ReferenceSOID` = IF((c.`ReferenceSOID` IS NOT NULL AND (c.`ReferenceSOID` = 0 OR p8.`ID` IS NULL)), NULL, c.`ReferenceSOID`),
       c.`SampleOrderByID` = IF((c.`SampleOrderByID` IS NOT NULL AND (c.`SampleOrderByID` = 0 OR p9.`ID` IS NULL)), NULL, c.`SampleOrderByID`),
       c.`SampleOrderFeedbackStatusID` = IF((c.`SampleOrderFeedbackStatusID` IS NOT NULL AND (c.`SampleOrderFeedbackStatusID` = 0 OR p10.`ID` IS NULL)), NULL, c.`SampleOrderFeedbackStatusID`),
       c.`SampleOrderStatusID` = IF((c.`SampleOrderStatusID` IS NOT NULL AND (c.`SampleOrderStatusID` = 0 OR p11.`ID` IS NULL)), NULL, c.`SampleOrderStatusID`)
 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.`DeliveryID` IS NOT NULL AND (c.`DeliveryID` = 0 OR p2.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p3.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p4.`ID` IS NULL))
    OR (c.`LocationID` IS NOT NULL AND (c.`LocationID` = 0 OR p5.`ID` IS NULL))
    OR (c.`PriorityID` IS NOT NULL AND (c.`PriorityID` = 0 OR p6.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p7.`ID` IS NULL))
    OR (c.`ReferenceSOID` IS NOT NULL AND (c.`ReferenceSOID` = 0 OR p8.`ID` IS NULL))
    OR (c.`SampleOrderByID` IS NOT NULL AND (c.`SampleOrderByID` = 0 OR p9.`ID` IS NULL))
    OR (c.`SampleOrderFeedbackStatusID` IS NOT NULL AND (c.`SampleOrderFeedbackStatusID` = 0 OR p10.`ID` IS NULL))
    OR (c.`SampleOrderStatusID` IS NOT NULL AND (c.`SampleOrderStatusID` = 0 OR p11.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
SET @sql = IF(@todo, 'UPDATE `sampleorder` c
  LEFT JOIN `users` p0 ON c.`UserIDInput` = p0.`ID`
  LEFT JOIN `users` p1 ON c.`UserIDSales` = p1.`ID`
   SET
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p0.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p1.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p0.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 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(), '8ae47ee4a2bf478261f75e6e4aeda51579183adc7cc381a01ae6487255c84648', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- sampleorder/30_assert  --  source section 7b
-- Orphan assertion over this table's 14 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 = 'sampleorder/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `sampleorder` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `delivery` p2 ON c.`DeliveryID` = p2.`ID`
  LEFT JOIN `division` p3 ON c.`DivisionID` = p3.`ID`
  LEFT JOIN `industry` p4 ON c.`IndustryID` = p4.`ID`
  LEFT JOIN `location` p5 ON c.`LocationID` = p5.`ID`
  LEFT JOIN `priority` p6 ON c.`PriorityID` = p6.`ID`
  LEFT JOIN `companyproject` p7 ON c.`ProjectID` = p7.`ID`
  LEFT JOIN `sampleorder` p8 ON c.`ReferenceSOID` = p8.`ID`
  LEFT JOIN `sampleorderby` p9 ON c.`SampleOrderByID` = p9.`ID`
  LEFT JOIN `sampleorderfeedbackstatus` p10 ON c.`SampleOrderFeedbackStatusID` = p10.`ID`
  LEFT JOIN `sampleorderstatus` p11 ON c.`SampleOrderStatusID` = p11.`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.`DeliveryID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`LocationID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`PriorityID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`ReferenceSOID` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`SampleOrderByID` IS NOT NULL AND p9.`ID` IS NULL)
    OR (c.`SampleOrderFeedbackStatusID` IS NOT NULL AND p10.`ID` IS NULL)
    OR (c.`SampleOrderStatusID` IS NOT NULL AND p11.`ID` IS NULL);
SET @orphans = @orphans + @n;
SELECT COUNT(*) INTO @n FROM `sampleorder` c
  LEFT JOIN `users` p0 ON c.`UserIDInput` = p0.`ID`
  LEFT JOIN `users` p1 ON c.`UserIDSales` = p1.`ID`
 WHERE  (c.`UserIDInput` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`UserIDSales` 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,
          'sampleorder: orphan check OK - 0 rows across 14 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `sampleorder` 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(), '7953dddfb72da8de975ea69055d327e3015131c89ccc51cdee02071edfa33a59', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorder/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 = 'sampleorder/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorder`
  ADD CONSTRAINT `sampleorder_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_DeliveryID` FOREIGN KEY (`DeliveryID`) REFERENCES `delivery` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_LocationID` FOREIGN KEY (`LocationID`) REFERENCES `location` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_PriorityID` FOREIGN KEY (`PriorityID`) REFERENCES `priority` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_ReferenceSOID` FOREIGN KEY (`ReferenceSOID`) REFERENCES `sampleorder` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_SampleOrderByID` FOREIGN KEY (`SampleOrderByID`) REFERENCES `sampleorderby` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_SampleOrderFeedbackStatusID` FOREIGN KEY (`SampleOrderFeedbackStatusID`) REFERENCES `sampleorderfeedbackstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_SampleOrderStatusID` FOREIGN KEY (`SampleOrderStatusID`) REFERENCES `sampleorderstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorder_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(), 'f4b1d300eb2a70fe2abd882c04541d4a6fe9d1e82f9888d50292d01fc2ef11ef', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: baranglist    (detail, owned by sampleorder)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- baranglist/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 = 'baranglist/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `baranglist`
  MODIFY COLUMN `BarangListStatusID` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderDetailID` int DEFAULT NULL,
  ADD INDEX `baranglist_BarangID` (`BarangID`),
  ADD INDEX `baranglist_SampleOrderDetailID` (`SampleOrderDetailID`),
  ADD INDEX `baranglist_SatuanID` (`SatuanID`),
  ADD INDEX `BarangListStatusID` (`BarangListStatusID`,`BarangID`,`SatuanID`,`SampleOrderDetailID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '2df11bb412dd905cdd9faf7783021ff9643538db7e4dc2e24da08b6674575fbc', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- baranglist/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 = 'baranglist/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `baranglist` c
  LEFT JOIN `barang` p0 ON c.`BarangID` = p0.`ID`
  LEFT JOIN `barangliststatus` p1 ON c.`BarangListStatusID` = p1.`ID`
  LEFT JOIN `sampleorderdetail` p2 ON c.`SampleOrderDetailID` = p2.`ID`
  LEFT JOIN `satuan` p3 ON c.`SatuanID` = p3.`ID`
   SET
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p0.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`BarangListStatusID` = IF((c.`BarangListStatusID` IS NOT NULL AND (c.`BarangListStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`BarangListStatusID`),
       c.`SampleOrderDetailID` = IF((c.`SampleOrderDetailID` IS NOT NULL AND (c.`SampleOrderDetailID` = 0 OR p2.`ID` IS NULL)), NULL, c.`SampleOrderDetailID`),
       c.`SatuanID` = IF((c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p3.`ID` IS NULL)), NULL, c.`SatuanID`)
 WHERE  (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p0.`ID` IS NULL))
    OR (c.`BarangListStatusID` IS NOT NULL AND (c.`BarangListStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`SampleOrderDetailID` IS NOT NULL AND (c.`SampleOrderDetailID` = 0 OR p2.`ID` IS NULL))
    OR (c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 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(), 'fedb48a22d9dc58d244e353509be01ec46cc9332f683ad96f6d05bc4656bfbd2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- baranglist/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 = 'baranglist/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `baranglist` c
  LEFT JOIN `barang` p0 ON c.`BarangID` = p0.`ID`
  LEFT JOIN `barangliststatus` p1 ON c.`BarangListStatusID` = p1.`ID`
  LEFT JOIN `sampleorderdetail` p2 ON c.`SampleOrderDetailID` = p2.`ID`
  LEFT JOIN `satuan` p3 ON c.`SatuanID` = p3.`ID`
 WHERE  (c.`BarangID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`BarangListStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`SampleOrderDetailID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`SatuanID` 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,
          'baranglist: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `baranglist` 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(), '9d9ecd3e7e6b34749c96fccb025ca873d59bacec4ef31c586adecdbf364a533e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- baranglist/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 = 'baranglist/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `baranglist`
  ADD CONSTRAINT `baranglist_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `baranglist_BarangListStatusID` FOREIGN KEY (`BarangListStatusID`) REFERENCES `barangliststatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `baranglist_SampleOrderDetailID` FOREIGN KEY (`SampleOrderDetailID`) REFERENCES `sampleorderdetail` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `baranglist_SatuanID` FOREIGN KEY (`SatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '77afb3307e425bbe8c645b43fd958881ade3e9cdc47a68e26debd147c28500a0', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: sampleorderassignment    (detail, owned by sampleorder)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- sampleorderassignment/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 = 'sampleorderassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorderassignment`
  MODIFY COLUMN `SampleOrderID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `sampleorderassignment_SampleOrderStatusID` (`SampleOrderStatusID`),
  ADD INDEX `sampleorderassignment_UserID` (`UserID`),
  ADD INDEX `SampleOrderID` (`SampleOrderID`,`SampleOrderStatusID`,`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(), '499bc2567e1bb7ffdeea362c822c0aecf1b4e2cbf2a067f3704d08b0e58d59d7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorderassignment/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 = 'sampleorderassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `sampleorderassignment` c
  LEFT JOIN `sampleorder` p0 ON c.`SampleOrderID` = p0.`ID`
  LEFT JOIN `sampleorderstatus` p1 ON c.`SampleOrderStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserID` = p2.`ID`
   SET
       c.`SampleOrderID` = IF((c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p0.`ID` IS NULL)), NULL, c.`SampleOrderID`),
       c.`SampleOrderStatusID` = IF((c.`SampleOrderStatusID` IS NOT NULL AND (c.`SampleOrderStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`SampleOrderStatusID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p0.`ID` IS NULL))
    OR (c.`SampleOrderStatusID` IS NOT NULL AND (c.`SampleOrderStatusID` = 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(), 'cb224d1c8a53c18357d97c81befd9abee4ab42aaa2b1c83b825e7a4b5d322d74', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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


-- ---------------------------------------------------------------------
-- unit: sampleorderdetail    (detail, owned by sampleorder)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- sampleorderdetail/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 = 'sampleorderdetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorderdetail`
  ADD COLUMN `IsStockReturnable` int NOT NULL DEFAULT ''0'' AFTER `SuratJalanDetailID`,
  MODIFY COLUMN `SampleOrderID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderDetailStatusID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectIDDetails` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `BarangListID` int DEFAULT NULL,
  MODIFY COLUMN `BarangListIDRequest` int DEFAULT NULL,
  MODIFY COLUMN `SuratJalanDetailID` int DEFAULT NULL,
  ADD INDEX `sampleorderdetail_ApplicationID` (`ApplicationID`),
  ADD INDEX `sampleorderdetail_BarangID` (`BarangID`),
  ADD INDEX `sampleorderdetail_BarangListID` (`BarangListID`),
  ADD INDEX `sampleorderdetail_BarangListIDRequest` (`BarangListIDRequest`),
  ADD INDEX `sampleorderdetail_ProjectID` (`ProjectID`),
  ADD INDEX `sampleorderdetail_ProjectIDDetails` (`ProjectIDDetails`),
  ADD INDEX `sampleorderdetail_SampleOrderDetailStatusID` (`SampleOrderDetailStatusID`),
  ADD INDEX `sampleorderdetail_SatuanID` (`SatuanID`),
  ADD INDEX `sampleorderdetail_SuratJalanDetailID` (`SuratJalanDetailID`),
  ADD INDEX `SampleOrderID` (`SampleOrderID`,`SampleOrderDetailStatusID`,`BarangID`,`SatuanID`,`ApplicationID`,`BarangListID`,`SuratJalanDetailID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '93a6a1984ad5c32789d89eb298a1236d654f9dec3a20639328bb3244b991e2ec', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorderdetail/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 = 'sampleorderdetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `sampleorderdetail` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `baranglists` p2 ON c.`BarangListID` = p2.`ID`
  LEFT JOIN `baranglists` p3 ON c.`BarangListIDRequest` = p3.`ID`
  LEFT JOIN `companyprojectdetailcc` p4 ON c.`ProjectID` = p4.`ID`
  LEFT JOIN `sampleorderdetailstatus` p5 ON c.`SampleOrderDetailStatusID` = p5.`ID`
  LEFT JOIN `sampleorder` p6 ON c.`SampleOrderID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanID` = p7.`ID`
  LEFT JOIN `suratjalandetails` p8 ON c.`SuratJalanDetailID` = p8.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`BarangListID` = IF((c.`BarangListID` IS NOT NULL AND (c.`BarangListID` = 0 OR p2.`ID` IS NULL)), NULL, c.`BarangListID`),
       c.`BarangListIDRequest` = IF((c.`BarangListIDRequest` IS NOT NULL AND (c.`BarangListIDRequest` = 0 OR p3.`ID` IS NULL)), NULL, c.`BarangListIDRequest`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`SampleOrderDetailStatusID` = IF((c.`SampleOrderDetailStatusID` IS NOT NULL AND (c.`SampleOrderDetailStatusID` = 0 OR p5.`ID` IS NULL)), NULL, c.`SampleOrderDetailStatusID`),
       c.`SampleOrderID` = IF((c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p6.`ID` IS NULL)), NULL, c.`SampleOrderID`),
       c.`SatuanID` = IF((c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p7.`ID` IS NULL)), NULL, c.`SatuanID`),
       c.`SuratJalanDetailID` = IF((c.`SuratJalanDetailID` IS NOT NULL AND (c.`SuratJalanDetailID` = 0 OR p8.`ID` IS NULL)), NULL, c.`SuratJalanDetailID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`BarangListID` IS NOT NULL AND (c.`BarangListID` = 0 OR p2.`ID` IS NULL))
    OR (c.`BarangListIDRequest` IS NOT NULL AND (c.`BarangListIDRequest` = 0 OR p3.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p4.`ID` IS NULL))
    OR (c.`SampleOrderDetailStatusID` IS NOT NULL AND (c.`SampleOrderDetailStatusID` = 0 OR p5.`ID` IS NULL))
    OR (c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p6.`ID` IS NULL))
    OR (c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p7.`ID` IS NULL))
    OR (c.`SuratJalanDetailID` IS NOT NULL AND (c.`SuratJalanDetailID` = 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(), '7e5b97c4d08299dafe5380b7993b4a8fa27e3e4cac74d412853dfda2a0e192a7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- sampleorderdetail/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 = 'sampleorderdetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `sampleorderdetail` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `baranglists` p2 ON c.`BarangListID` = p2.`ID`
  LEFT JOIN `baranglists` p3 ON c.`BarangListIDRequest` = p3.`ID`
  LEFT JOIN `companyprojectdetailcc` p4 ON c.`ProjectID` = p4.`ID`
  LEFT JOIN `sampleorderdetailstatus` p5 ON c.`SampleOrderDetailStatusID` = p5.`ID`
  LEFT JOIN `sampleorder` p6 ON c.`SampleOrderID` = p6.`ID`
  LEFT JOIN `satuan` p7 ON c.`SatuanID` = p7.`ID`
  LEFT JOIN `suratjalandetails` p8 ON c.`SuratJalanDetailID` = p8.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`BarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`BarangListID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`BarangListIDRequest` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`SampleOrderDetailStatusID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`SampleOrderID` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`SatuanID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`SuratJalanDetailID` 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,
          'sampleorderdetail: orphan check OK - 0 rows across 9 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `sampleorderdetail` 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(), 'f392742667c2b7a707cd00d108c254ab33ed7f55885ea05a5c9be21e56c5dc8d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorderdetail/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 = 'sampleorderdetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorderdetail`
  ADD CONSTRAINT `sampleorderdetail_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_BarangListID` FOREIGN KEY (`BarangListID`) REFERENCES `baranglists` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_BarangListIDRequest` FOREIGN KEY (`BarangListIDRequest`) REFERENCES `baranglists` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyprojectdetailcc` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_SampleOrderDetailStatusID` FOREIGN KEY (`SampleOrderDetailStatusID`) REFERENCES `sampleorderdetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_SampleOrderID` FOREIGN KEY (`SampleOrderID`) REFERENCES `sampleorder` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_SatuanID` FOREIGN KEY (`SatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetail_SuratJalanDetailID` FOREIGN KEY (`SuratJalanDetailID`) REFERENCES `suratjalandetails` (`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(), '53a945258c4c70b2762f196d153dd4d8e04905b45c9abc45e2bbf6b64283b070', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: sampleorderdetailassignment    (detail, owned by sampleorder)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- sampleorderdetailassignment/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 = 'sampleorderdetailassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorderdetailassignment`
  MODIFY COLUMN `SampleOrderID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderDetailID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderDetailStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  ADD INDEX `sampleorderdetailassignment_SampleOrderDetailID` (`SampleOrderDetailID`),
  ADD INDEX `sampleorderdetailassignment_SampleOrderDetailStatusID` (`SampleOrderDetailStatusID`),
  ADD INDEX `sampleorderdetailassignment_UserID` (`UserID`),
  ADD INDEX `SampleOrderID` (`SampleOrderID`,`SampleOrderDetailID`,`SampleOrderDetailStatusID`,`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(), 'c7be3c6aa676e03afe79a7cd2b3668352e40bf5155878ba8ef3d73a6fe5ea8ec', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorderdetailassignment/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 = 'sampleorderdetailassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `sampleorderdetailassignment` c
  LEFT JOIN `sampleorderdetail` p0 ON c.`SampleOrderDetailID` = p0.`ID`
  LEFT JOIN `sampleorderdetailstatus` p1 ON c.`SampleOrderDetailStatusID` = p1.`ID`
  LEFT JOIN `sampleorder` p2 ON c.`SampleOrderID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
   SET
       c.`SampleOrderDetailID` = IF((c.`SampleOrderDetailID` IS NOT NULL AND (c.`SampleOrderDetailID` = 0 OR p0.`ID` IS NULL)), NULL, c.`SampleOrderDetailID`),
       c.`SampleOrderDetailStatusID` = IF((c.`SampleOrderDetailStatusID` IS NOT NULL AND (c.`SampleOrderDetailStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`SampleOrderDetailStatusID`),
       c.`SampleOrderID` = IF((c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p2.`ID` IS NULL)), NULL, c.`SampleOrderID`),
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p3.`ID` IS NULL)), NULL, c.`UserID`)
 WHERE  (c.`SampleOrderDetailID` IS NOT NULL AND (c.`SampleOrderDetailID` = 0 OR p0.`ID` IS NULL))
    OR (c.`SampleOrderDetailStatusID` IS NOT NULL AND (c.`SampleOrderDetailStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 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(), 'ea1003817a2c46cb263014ceecac460534676133d63f7fc38f3f66f9ccca4394', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- sampleorderdetailassignment/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 = 'sampleorderdetailassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `sampleorderdetailassignment` c
  LEFT JOIN `sampleorderdetail` p0 ON c.`SampleOrderDetailID` = p0.`ID`
  LEFT JOIN `sampleorderdetailstatus` p1 ON c.`SampleOrderDetailStatusID` = p1.`ID`
  LEFT JOIN `sampleorder` p2 ON c.`SampleOrderID` = p2.`ID`
  LEFT JOIN `users` p3 ON c.`UserID` = p3.`ID`
 WHERE  (c.`SampleOrderDetailID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`SampleOrderDetailStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`SampleOrderID` 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,
          'sampleorderdetailassignment: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `sampleorderdetailassignment` 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(), 'b4f6c985d7df8c0b6edf013880cd231cd06a5b24bddbe0fde83c4df57d73a282', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- sampleorderdetailassignment/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 = 'sampleorderdetailassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `sampleorderdetailassignment`
  ADD CONSTRAINT `sampleorderdetailassignment_SampleOrderDetailID` FOREIGN KEY (`SampleOrderDetailID`) REFERENCES `sampleorderdetail` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetailassignment_SampleOrderDetailStatusID` FOREIGN KEY (`SampleOrderDetailStatusID`) REFERENCES `sampleorderdetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetailassignment_SampleOrderID` FOREIGN KEY (`SampleOrderID`) REFERENCES `sampleorder` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `sampleorderdetailassignment_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(), 'b3ef521057dc804cefc7aead07f1733bc5b1f92c9221c03d4dce07d1a3178867', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


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

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


-- ---------------------------------------------------------------------
-- unit: suratjalan    (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'));
-- ---------------------------------------------------------------------
-- suratjalan/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 = 'suratjalan/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `suratjalan`
  MODIFY COLUMN `Vendor` varchar(200) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
  MODIFY COLUMN `SampleOrderID` int DEFAULT NULL,
  MODIFY COLUMN `DeliveryID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  MODIFY COLUMN `LocationID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDsales` int DEFAULT NULL,
  MODIFY COLUMN `UserIDCreatorSJ` int DEFAULT NULL,
  ADD INDEX `SampleOrderID` (`SampleOrderID`,`DeliveryID`,`CompanyID`,`CompanyCPID`,`LocationID`,`UserIDsales`,`UserIDCreatorSJ`),
  ADD INDEX `suratjalan_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `suratjalan_CompanyID` (`CompanyID`),
  ADD INDEX `suratjalan_DeliveryID` (`DeliveryID`),
  ADD INDEX `suratjalan_LocationID` (`LocationID`),
  ADD INDEX `suratjalan_UserIDCreatorSJ` (`UserIDCreatorSJ`),
  ADD INDEX `suratjalan_UserIDsales` (`UserIDsales`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '03a316eef8138ec73bdfbaa8f7b19d272a4244c95952107a6d171df261a4f82c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- suratjalan/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 = 'suratjalan/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `suratjalan` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `delivery` p2 ON c.`DeliveryID` = p2.`ID`
  LEFT JOIN `location` p3 ON c.`LocationID` = p3.`ID`
  LEFT JOIN `sampleorder` p4 ON c.`SampleOrderID` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserIDCreatorSJ` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDsales` = p6.`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.`DeliveryID` = IF((c.`DeliveryID` IS NOT NULL AND (c.`DeliveryID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DeliveryID`),
       c.`LocationID` = IF((c.`LocationID` IS NOT NULL AND (c.`LocationID` = 0 OR p3.`ID` IS NULL)), NULL, c.`LocationID`),
       c.`SampleOrderID` = IF((c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p4.`ID` IS NULL)), NULL, c.`SampleOrderID`),
       c.`UserIDCreatorSJ` = IF((c.`UserIDCreatorSJ` IS NOT NULL AND (c.`UserIDCreatorSJ` = 0 OR p5.`ID` IS NULL)), NULL, c.`UserIDCreatorSJ`),
       c.`UserIDsales` = IF((c.`UserIDsales` IS NOT NULL AND (c.`UserIDsales` = 0 OR p6.`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.`DeliveryID` IS NOT NULL AND (c.`DeliveryID` = 0 OR p2.`ID` IS NULL))
    OR (c.`LocationID` IS NOT NULL AND (c.`LocationID` = 0 OR p3.`ID` IS NULL))
    OR (c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p4.`ID` IS NULL))
    OR (c.`UserIDCreatorSJ` IS NOT NULL AND (c.`UserIDCreatorSJ` = 0 OR p5.`ID` IS NULL))
    OR (c.`UserIDsales` IS NOT NULL AND (c.`UserIDsales` = 0 OR p6.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '08e0ac7ad0d177d384dc9f9ef8036d5875cdb1d122fa97e2230d521d90de6802', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

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

SET @step = 'suratjalan/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `suratjalan` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `delivery` p2 ON c.`DeliveryID` = p2.`ID`
  LEFT JOIN `location` p3 ON c.`LocationID` = p3.`ID`
  LEFT JOIN `sampleorder` p4 ON c.`SampleOrderID` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserIDCreatorSJ` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDsales` = p6.`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.`DeliveryID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`LocationID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`SampleOrderID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`UserIDCreatorSJ` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`UserIDsales` IS NOT NULL AND p6.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'suratjalan: orphan check OK - 0 rows across 7 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `suratjalan` 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(), 'f79fcf483adc1724f61b6bdcea6e434f5c7516124fa167cad460361eaa0d828e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- suratjalan/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 = 'suratjalan/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `suratjalan`
  ADD CONSTRAINT `suratjalan_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalan_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalan_DeliveryID` FOREIGN KEY (`DeliveryID`) REFERENCES `delivery` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalan_LocationID` FOREIGN KEY (`LocationID`) REFERENCES `location` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalan_SampleOrderID` FOREIGN KEY (`SampleOrderID`) REFERENCES `sampleorder` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalan_UserIDCreatorSJ` FOREIGN KEY (`UserIDCreatorSJ`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalan_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(), '7aea226cc6ebf08f049b39e83e6f3e616697c71e95c63955b9411e85e3d28d10', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: suratjalandetails    (detail, owned by suratjalan)
-- ---------------------------------------------------------------------
             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'));
-- ---------------------------------------------------------------------
-- suratjalandetails/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 = 'suratjalandetails/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `suratjalandetails`
  MODIFY COLUMN `SuratJalanID` int DEFAULT NULL,
  MODIFY COLUMN `SampleOrderID` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `SatuanID` int DEFAULT NULL,
  MODIFY COLUMN `ApplicationID` int DEFAULT NULL,
  MODIFY COLUMN `BarangListID` int DEFAULT NULL,
  ADD INDEX `suratjalandetails_ApplicationID` (`ApplicationID`),
  ADD INDEX `suratjalandetails_BarangID` (`BarangID`),
  ADD INDEX `suratjalandetails_BarangListID` (`BarangListID`),
  ADD INDEX `suratjalandetails_SampleOrderID` (`SampleOrderID`),
  ADD INDEX `suratjalandetails_SatuanID` (`SatuanID`),
  ADD INDEX `SuratJalanID` (`SuratJalanID`,`SampleOrderID`,`BarangID`,`SatuanID`,`ApplicationID`,`BarangListID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '55ebb37a8b789e12134576698ee8c0016055509e8444aee495150f6d109a50b3', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- suratjalandetails/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 = 'suratjalandetails/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `suratjalandetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `baranglists` p2 ON c.`BarangListID` = p2.`ID`
  LEFT JOIN `sampleorder` p3 ON c.`SampleOrderID` = p3.`ID`
  LEFT JOIN `satuan` p4 ON c.`SatuanID` = p4.`ID`
  LEFT JOIN `suratjalan` p5 ON c.`SuratJalanID` = p5.`ID`
   SET
       c.`ApplicationID` = IF((c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ApplicationID`),
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`BarangListID` = IF((c.`BarangListID` IS NOT NULL AND (c.`BarangListID` = 0 OR p2.`ID` IS NULL)), NULL, c.`BarangListID`),
       c.`SampleOrderID` = IF((c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p3.`ID` IS NULL)), NULL, c.`SampleOrderID`),
       c.`SatuanID` = IF((c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p4.`ID` IS NULL)), NULL, c.`SatuanID`),
       c.`SuratJalanID` = IF((c.`SuratJalanID` IS NOT NULL AND (c.`SuratJalanID` = 0 OR p5.`ID` IS NULL)), NULL, c.`SuratJalanID`)
 WHERE  (c.`ApplicationID` IS NOT NULL AND (c.`ApplicationID` = 0 OR p0.`ID` IS NULL))
    OR (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`BarangListID` IS NOT NULL AND (c.`BarangListID` = 0 OR p2.`ID` IS NULL))
    OR (c.`SampleOrderID` IS NOT NULL AND (c.`SampleOrderID` = 0 OR p3.`ID` IS NULL))
    OR (c.`SatuanID` IS NOT NULL AND (c.`SatuanID` = 0 OR p4.`ID` IS NULL))
    OR (c.`SuratJalanID` IS NOT NULL AND (c.`SuratJalanID` = 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(), 'ec8d8785c5331191e76553c0e3c8098f20907f3477b7b447b222b356a48e73f4', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- suratjalandetails/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 = 'suratjalandetails/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `suratjalandetails` c
  LEFT JOIN `application` p0 ON c.`ApplicationID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `baranglists` p2 ON c.`BarangListID` = p2.`ID`
  LEFT JOIN `sampleorder` p3 ON c.`SampleOrderID` = p3.`ID`
  LEFT JOIN `satuan` p4 ON c.`SatuanID` = p4.`ID`
  LEFT JOIN `suratjalan` p5 ON c.`SuratJalanID` = p5.`ID`
 WHERE  (c.`ApplicationID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`BarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`BarangListID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`SampleOrderID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`SatuanID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`SuratJalanID` 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,
          'suratjalandetails: orphan check OK - 0 rows across 6 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `suratjalandetails` 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(), '6fb8e0942c5d81f558d381cfa9782ceefc1861970cfdb561282862506d1b0151', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- suratjalandetails/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 = 'suratjalandetails/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `suratjalandetails`
  ADD CONSTRAINT `suratjalandetails_ApplicationID` FOREIGN KEY (`ApplicationID`) REFERENCES `application` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalandetails_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalandetails_BarangListID` FOREIGN KEY (`BarangListID`) REFERENCES `baranglists` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalandetails_SampleOrderID` FOREIGN KEY (`SampleOrderID`) REFERENCES `sampleorder` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalandetails_SatuanID` FOREIGN KEY (`SatuanID`) REFERENCES `satuan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `suratjalandetails_SuratJalanID` FOREIGN KEY (`SuratJalanID`) REFERENCES `suratjalan` (`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(), 'f88c450985e50fa29d834d1cd498d6f3a8848d01670eb07d6be1f99d61e92ac8', 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 = 48;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'baranglist.baranglist_BarangID' AS n UNION ALL SELECT 'baranglist.baranglist_BarangListStatusID' UNION ALL SELECT 'baranglist.baranglist_SampleOrderDetailID' UNION ALL SELECT 'baranglist.baranglist_SatuanID' UNION ALL SELECT 'sampleorder.sampleorder_CompanyCPID' UNION ALL SELECT 'sampleorder.sampleorder_CompanyID' UNION ALL SELECT 'sampleorder.sampleorder_DeliveryID' UNION ALL SELECT 'sampleorder.sampleorder_DivisionID' UNION ALL SELECT 'sampleorder.sampleorder_IndustryID' UNION ALL SELECT 'sampleorder.sampleorder_LocationID' UNION ALL SELECT 'sampleorder.sampleorder_PriorityID' UNION ALL SELECT 'sampleorder.sampleorder_ProjectID' UNION ALL SELECT 'sampleorder.sampleorder_ReferenceSOID' UNION ALL SELECT 'sampleorder.sampleorder_SampleOrderByID' UNION ALL SELECT 'sampleorder.sampleorder_SampleOrderFeedbackStatusID' UNION ALL SELECT 'sampleorder.sampleorder_SampleOrderStatusID' UNION ALL SELECT 'sampleorder.sampleorder_UserIDInput' UNION ALL SELECT 'sampleorder.sampleorder_UserIDSales' UNION ALL SELECT 'sampleorderassignment.sampleorderassignment_SampleOrderID' UNION ALL SELECT 'sampleorderassignment.sampleorderassignment_SampleOrderStatusID' UNION ALL SELECT 'sampleorderassignment.sampleorderassignment_UserID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_ApplicationID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_BarangID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_BarangListID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_BarangListIDRequest' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_ProjectID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SampleOrderDetailStatusID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SampleOrderID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SatuanID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SuratJalanDetailID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_SampleOrderDetailID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_SampleOrderDetailStatusID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_SampleOrderID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_UserID' UNION ALL SELECT 'sampleorderlink.sampleorderlink_SampleOrderID' UNION ALL SELECT 'suratjalan.suratjalan_CompanyCPID' UNION ALL SELECT 'suratjalan.suratjalan_CompanyID' UNION ALL SELECT 'suratjalan.suratjalan_DeliveryID' UNION ALL SELECT 'suratjalan.suratjalan_LocationID' UNION ALL SELECT 'suratjalan.suratjalan_SampleOrderID' UNION ALL SELECT 'suratjalan.suratjalan_UserIDCreatorSJ' UNION ALL SELECT 'suratjalan.suratjalan_UserIDsales' UNION ALL SELECT 'suratjalandetails.suratjalandetails_ApplicationID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_BarangID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_BarangListID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_SampleOrderID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_SatuanID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_SuratJalanID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: col
SET @want_col = 1;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_col, @miss_col
  FROM (SELECT 'sampleorderdetail.IsStockReturnable' AS n) _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', COLUMN_NAME) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE());
SET @have_col = @want_col - @missn_col;
SET @pf_col = IF(@missn_col = 0,
    CONCAT('SELECT ''postflight new columns: ', @have_col, '/', @want_col, ' present'' AS postflight_col'),
    CONCAT('SELECT `ABORT postflight: MISSING new columns: ', @miss_col,
           ' -- ', @missn_col, ' of ', @want_col, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_col; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 49;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'baranglist.BarangListStatusID' AS n UNION ALL SELECT 'baranglist.baranglist_BarangID' UNION ALL SELECT 'baranglist.baranglist_SampleOrderDetailID' UNION ALL SELECT 'baranglist.baranglist_SatuanID' UNION ALL SELECT 'sampleorder.SampleOrderStatusID' UNION ALL SELECT 'sampleorder.sampleorder_CompanyCPID' UNION ALL SELECT 'sampleorder.sampleorder_CompanyID' UNION ALL SELECT 'sampleorder.sampleorder_DeliveryID' UNION ALL SELECT 'sampleorder.sampleorder_DivisionID' UNION ALL SELECT 'sampleorder.sampleorder_IndustryID' UNION ALL SELECT 'sampleorder.sampleorder_LocationID' UNION ALL SELECT 'sampleorder.sampleorder_PriorityID' UNION ALL SELECT 'sampleorder.sampleorder_ProjectID' UNION ALL SELECT 'sampleorder.sampleorder_ReferenceSOID' UNION ALL SELECT 'sampleorder.sampleorder_SampleOrderByID' UNION ALL SELECT 'sampleorder.sampleorder_SampleOrderFeedbackStatusID' UNION ALL SELECT 'sampleorder.sampleorder_UserIDInput' UNION ALL SELECT 'sampleorder.sampleorder_UserIDSales' UNION ALL SELECT 'sampleorderassignment.SampleOrderID' UNION ALL SELECT 'sampleorderassignment.sampleorderassignment_SampleOrderStatusID' UNION ALL SELECT 'sampleorderassignment.sampleorderassignment_UserID' UNION ALL SELECT 'sampleorderdetail.SampleOrderID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_ApplicationID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_BarangID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_BarangListID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_BarangListIDRequest' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_ProjectID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_ProjectIDDetails' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SampleOrderDetailStatusID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SatuanID' UNION ALL SELECT 'sampleorderdetail.sampleorderdetail_SuratJalanDetailID' UNION ALL SELECT 'sampleorderdetailassignment.SampleOrderID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_SampleOrderDetailID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_SampleOrderDetailStatusID' UNION ALL SELECT 'sampleorderdetailassignment.sampleorderdetailassignment_UserID' UNION ALL SELECT 'sampleorderlink.sampleorderlink_SampleOrderID' UNION ALL SELECT 'suratjalan.SampleOrderID' UNION ALL SELECT 'suratjalan.suratjalan_CompanyCPID' UNION ALL SELECT 'suratjalan.suratjalan_CompanyID' UNION ALL SELECT 'suratjalan.suratjalan_DeliveryID' UNION ALL SELECT 'suratjalan.suratjalan_LocationID' UNION ALL SELECT 'suratjalan.suratjalan_UserIDCreatorSJ' UNION ALL SELECT 'suratjalan.suratjalan_UserIDsales' UNION ALL SELECT 'suratjalandetails.SuratJalanID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_ApplicationID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_BarangID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_BarangListID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_SampleOrderID' UNION ALL SELECT 'suratjalandetails.suratjalandetails_SatuanID') _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 = 50;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'baranglist.BarangID.int' AS n UNION ALL SELECT 'baranglist.BarangListStatusID.int' UNION ALL SELECT 'baranglist.SampleOrderDetailID.int' UNION ALL SELECT 'baranglist.SatuanID.int' UNION ALL SELECT 'sampleorder.CompanyCPID.int' UNION ALL SELECT 'sampleorder.CompanyID.int' UNION ALL SELECT 'sampleorder.DeliveryID.int' UNION ALL SELECT 'sampleorder.DivisionID.int' UNION ALL SELECT 'sampleorder.IndustryID.int' UNION ALL SELECT 'sampleorder.LocationID.int' UNION ALL SELECT 'sampleorder.PriorityID.int' UNION ALL SELECT 'sampleorder.ProjectID.int' UNION ALL SELECT 'sampleorder.ReferenceSOID.int' UNION ALL SELECT 'sampleorder.SampleOrderByID.int' UNION ALL SELECT 'sampleorder.SampleOrderFeedbackStatusID.int' UNION ALL SELECT 'sampleorder.SampleOrderStatusID.int' UNION ALL SELECT 'sampleorder.UserIDInput.int' UNION ALL SELECT 'sampleorder.UserIDSales.int' UNION ALL SELECT 'sampleorderassignment.SampleOrderID.int' UNION ALL SELECT 'sampleorderassignment.SampleOrderStatusID.int' UNION ALL SELECT 'sampleorderassignment.UserID.int' UNION ALL SELECT 'sampleorderdetail.ApplicationID.int' UNION ALL SELECT 'sampleorderdetail.BarangID.int' UNION ALL SELECT 'sampleorderdetail.BarangListID.int' UNION ALL SELECT 'sampleorderdetail.BarangListIDRequest.int' UNION ALL SELECT 'sampleorderdetail.ProjectID.int' UNION ALL SELECT 'sampleorderdetail.ProjectIDDetails.int' UNION ALL SELECT 'sampleorderdetail.SampleOrderDetailStatusID.int' UNION ALL SELECT 'sampleorderdetail.SampleOrderID.int' UNION ALL SELECT 'sampleorderdetail.SatuanID.int' UNION ALL SELECT 'sampleorderdetail.SuratJalanDetailID.int' UNION ALL SELECT 'sampleorderdetailassignment.SampleOrderDetailID.int' UNION ALL SELECT 'sampleorderdetailassignment.SampleOrderDetailStatusID.int' UNION ALL SELECT 'sampleorderdetailassignment.SampleOrderID.int' UNION ALL SELECT 'sampleorderdetailassignment.UserID.int' UNION ALL SELECT 'sampleorderlink.SampleOrderID.int' UNION ALL SELECT 'suratjalan.CompanyCPID.int' UNION ALL SELECT 'suratjalan.CompanyID.int' UNION ALL SELECT 'suratjalan.DeliveryID.int' UNION ALL SELECT 'suratjalan.LocationID.int' UNION ALL SELECT 'suratjalan.SampleOrderID.int' UNION ALL SELECT 'suratjalan.UserIDCreatorSJ.int' UNION ALL SELECT 'suratjalan.UserIDsales.int' UNION ALL SELECT 'suratjalan.Vendor.varchar' UNION ALL SELECT 'suratjalandetails.ApplicationID.int' UNION ALL SELECT 'suratjalandetails.BarangID.int' UNION ALL SELECT 'suratjalandetails.BarangListID.int' UNION ALL SELECT 'suratjalandetails.SampleOrderID.int' UNION ALL SELECT 'suratjalandetails.SatuanID.int' UNION ALL SELECT 'suratjalandetails.SuratJalanID.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);
