From 585768bc30d330ac80a678cf7daec44d524fb585 Mon Sep 17 00:00:00 2001
From: s j <sj@1729.be>
Date: Tue, 29 Mar 2022 20:38:07 +0200
Subject: [PATCH] imp: post_update performance

---
 shareholder_register.post_update.php | 37 +++++++++++++++++-----------
 1 file changed, 22 insertions(+), 15 deletions(-)

diff --git a/shareholder_register.post_update.php b/shareholder_register.post_update.php
index 7e0b0ec3..6fd15113 100644
--- a/shareholder_register.post_update.php
+++ b/shareholder_register.post_update.php
@@ -119,11 +119,15 @@ function shareholder_register_post_update_indexes(&$sandbox) {
  * Update current holder for shares.
  */
 function shareholder_register_post_update_current_holder(&$sandbox) {
-  $share_ids = \Drupal::entityQuery('share')->execute();
-  foreach (array_chunk($share_ids, 250) as $current_share_ids_chunk) {
-    foreach (Share::loadMultiple($current_share_ids_chunk) as $share) {
-      $share->save();
-    }
+  \Drupal::database()->query(
+      "update {share} " .
+      "inner join {share__share_transaction_ids} on {share}.id = {share__share_transaction_ids}.entity_id " .
+      "inner join {share_transaction} on share_transaction_ids_target_id = {share_transaction}.id " .
+      "set {share}.shareholder_id = {share_transaction}.shareholder_id ".
+      "where {share_transaction}.state = 'valid' and {share}.state in ('issued', 'redeemed');"
+  );
+  foreach (\Drupal::database()->query("select entity_id from share__share_transaction_ids group by entity_id having count(*) > 1") as $row) {
+    Share::load($row->entity_id)->save();
   }
 }
 
@@ -131,16 +135,19 @@ function shareholder_register_post_update_current_holder(&$sandbox) {
  * Update share issue for shares.
  */
 function shareholder_register_post_update_share_issue(&$sandbox) {
-  $share_ids = \Drupal::entityQuery('share')
-    ->condition('state', ['issued', 'redeemed'], 'IN')
-    ->execute();
-  foreach (array_chunk($share_ids, 250) as $current_share_ids_chunk) {
-    foreach (Share::loadMultiple($current_share_ids_chunk) as $share) {
-      $share->set(
-        'share_issue_id',
-        $share->getIssuingTransaction()->getShareIssue()->id()
-      )->save();
-    }
+  \Drupal::database()->query(
+      "update {share} " .
+      "inner join {share__share_transaction_ids} on {share}.id = {share__share_transaction_ids}.entity_id " .
+      "inner join {share_transaction} on share_transaction_ids_target_id = {share_transaction}.id " .
+      "set {share}.share_issue_id = {share_transaction}.share_issue_id ".
+      "where {share_transaction}.state = 'valid' and {share}.state in ('issued', 'redeemed');"
+  );
+  foreach (\Drupal::database()->query("select entity_id from share__share_transaction_ids group by entity_id having count(*) > 1") as $row) {
+    $share = Share::load($row->entity_id);
+    $share->set(
+      'share_issue_id',
+      $share->getIssuingTransaction()->getShareIssue()->id()
+    )->save();
   }
 }
 
-- 
GitLab