From 4768f16754694d91f9221f7d8b69de836577d887 Mon Sep 17 00:00:00 2001
From: Jan Wennrich <jan.wennrich@pcsg.de>
Date: Tue, 17 Mar 2020 14:14:10 +0100
Subject: [PATCH] fix: corrects falsy DROP PRIMARY KEY statement in setup
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

There where syntax errors in the SQL statement.
Furthermore the primary keys are only dropped if they exist.
This prevents unnecessary errors/messages in the logs.

Co-authored-by: Adrian Müller <adrian@pcsg.de>
---
 src/QUI/Bricks/Events.php | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/src/QUI/Bricks/Events.php b/src/QUI/Bricks/Events.php
index b3c124e..9e9425f 100644
--- a/src/QUI/Bricks/Events.php
+++ b/src/QUI/Bricks/Events.php
@@ -225,6 +225,8 @@ public static function onPackageSetup(QUI\Package\Package $Package)
         // unique bricks cache patch
         $projects = QUI::getProjectManager()->getProjectList();
 
+        $databaseName = QUI::getDataBase()->getAttribute('dbname');
+
         foreach ($projects as $Project) {
             $projectCacheTable = QUI::getDBProjectTableName(
                 Manager::TABLE_CACHE,
@@ -232,9 +234,19 @@ public static function onPackageSetup(QUI\Package\Package $Package)
             );
 
             try {
-                QUI::getDataBase()->fetchSQL(
-                    "`ALTER TABLE ``{$projectCacheTable}`` DROP PRIMARY KEY;`"
-                );
+                $primaryExists = QUI::getDataBase()->fetchSQL("
+                    SELECT COUNT(constraint_type) AS primary_key_count FROM information_schema.table_constraints
+                    WHERE constraint_type = 'PRIMARY KEY' 
+                    AND table_name = '{$projectCacheTable}'
+                    AND TABLE_SCHEMA = '{$databaseName}'
+                ");
+
+                $isPrimaryKeyExisting = \boolval($primaryExists[0]['primary_key_count']);
+
+                // Primary key should only be dropped if it exists
+                if ($isPrimaryKeyExisting) {
+                    QUI::getDataBase()->fetchSQL("ALTER TABLE `{$projectCacheTable}` DROP PRIMARY KEY;");
+                }
             } catch (QUI\Exception $Exception) {
                 QUI\System\Log::addInfo($Exception->getMessage());
             }
-- 
GitLab