New method that will ignore duplicate key errors while inserting rows into the database
authorMarcel Werk <burntime@woltlab.com>
Thu, 30 Jul 2020 16:03:14 +0000 (18:03 +0200)
committerMarcel Werk <burntime@woltlab.com>
Thu, 30 Jul 2020 16:03:14 +0000 (18:03 +0200)
wcfsetup/install/files/lib/data/DatabaseObjectEditor.class.php

index 19cea93519119114ee2363d7b242f70d38e37cd8..1126fae67daf53468c0032cd889edf265a9195c0 100644 (file)
@@ -1,5 +1,6 @@
 <?php
 namespace wcf\data;
+use wcf\system\database\exception\DatabaseQueryExecutionException;
 use wcf\system\database\util\PreparedStatementConditionBuilder;
 use wcf\system\WCF;
 
@@ -123,4 +124,25 @@ abstract class DatabaseObjectEditor extends DatabaseObjectDecorator implements I
                
                return $affectedCount;
        }
+       
+       /**
+        * Creates a new object, returns null if the row already exists.
+        *
+        * @param       array   $parameters
+        * @return      IStorableObject|null
+        * @since       5.3
+        */
+       public static function createOrIgnore(array $parameters = []) {
+               try {
+                       return static::create($parameters);
+               }
+               catch (DatabaseQueryExecutionException $e) {
+                       // Error code 23000 = duplicate key
+                       if ($e->getCode() == '23000') {
+                               return null;
+                       }
+                       
+                       throw $e;
+               }
+       }
 }