-- Run in phpMyAdmin on database immapwjv_hrm (or your HRM database)
-- Fixes #1452 when adding activity_logs foreign keys after a partial import

UPDATE activity_logs AS t
LEFT JOIN users AS u ON t.user_id = u.id
SET t.user_id = NULL
WHERE t.user_id IS NOT NULL AND u.id IS NULL;

UPDATE activity_logs AS t
LEFT JOIN users AS u ON t.created_by = u.id
SET t.created_by = NULL
WHERE t.created_by IS NOT NULL AND u.id IS NULL;

-- Drop existing FKs if re-import failed halfway (ignore errors if missing)
-- ALTER TABLE activity_logs DROP FOREIGN KEY activity_logs_user_id_foreign;
-- ALTER TABLE activity_logs DROP FOREIGN KEY activity_logs_created_by_foreign;

ALTER TABLE activity_logs
  ADD CONSTRAINT activity_logs_user_id_foreign
    FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL,
  ADD CONSTRAINT activity_logs_created_by_foreign
    FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL;
