Merge pull request #22732 from braders/ui-45-contrib-participant-links
[civicrm-core.git] / Civi / Core / SqlTriggers.php
index 6fdc3336b78ec8c03709cb2acfcf8f1eca792743..b1ac987d532fe8bcc811ebe444dd6cd88d4d058c 100644 (file)
@@ -24,7 +24,14 @@ class SqlTriggers {
    *
    * @var string|null
    */
-  private $file = NULL;
+  private $file;
+
+  /**
+   * Queries written to file when the class is destructed.
+   *
+   * @var array
+   */
+  private $enqueuedQueries = [];
 
   /**
    * Build a list of triggers via hook and add them to (err, reconcile them
@@ -52,6 +59,7 @@ class SqlTriggers {
 
     // now create the set of new triggers
     $this->createTriggers($info, $tableName);
+    $this->writeEnqueuedQueriesToFile();
   }
 
   /**
@@ -138,6 +146,10 @@ class SqlTriggers {
       }
     }
 
+    // Sort tables alphabetically in order to output in a consistent order
+    // for sites that like to diff this output over time
+    // (ie. with the logging_no_trigger_permission setting in place).
+    ksort($triggers);
     // now spit out the sql
     foreach ($triggers as $tableName => $tables) {
       if ($onlyTableName != NULL && $onlyTableName != $tableName) {
@@ -198,12 +210,8 @@ class SqlTriggers {
           ['expires' => 0]
         );
       }
-
-      $buf = "\n";
-      $buf .= "DELIMITER //\n";
-      $buf .= \CRM_Core_DAO::composeQuery($triggerSQL, $params) . " //\n";
-      $buf .= "DELIMITER ;\n";
-      file_put_contents($this->getFile(), $buf, FILE_APPEND);
+      $query = \CRM_Core_DAO::composeQuery($triggerSQL, $params);
+      $this->enqueuedQueries[$query] = $query;
     }
     else {
       \CRM_Core_DAO::executeQuery($triggerSQL, $params, TRUE, NULL, FALSE, FALSE);
@@ -222,4 +230,35 @@ class SqlTriggers {
     return $this->file;
   }
 
+  /**
+   * Write queries to file when the class is destructed.
+   *
+   * Note this is already written out for a full rebuild but it is
+   * possible (at least in terms of what is public) to call drop & create
+   * separately so this ensures they are output.
+   */
+  public function __destruct() {
+    $this->writeEnqueuedQueriesToFile();
+  }
+
+  /**
+   * Write queries queued for write-to-file.
+   */
+  protected function writeEnqueuedQueriesToFile(): void {
+    if (!empty($this->enqueuedQueries) && $this->getFile()) {
+      $buf = "DELIMITER //\n";
+      foreach ($this->enqueuedQueries as $query) {
+        if (strpos($query, 'CREATE TRIGGER') === 0) {
+          // The create triggers are long so put spaces between them. For the drops
+          // condensed is more readable.
+          $buf .= "\n";
+        }
+        $buf .= $query . " //\n";
+      }
+      $buf .= "DELIMITER ;\n";
+      file_put_contents($this->getFile(), $buf, FILE_APPEND);
+      $this->enqueuedQueries = [];
+    }
+  }
+
 }