From 9a2dea974a6f115ae4e3c53b7c20b67055867efe Mon Sep 17 00:00:00 2001
From: Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
Date: Fri, 2 Jul 2021 15:11:06 +0200
Subject: [PATCH] =?UTF-8?q?Corrections=20autour=20du=20type=20bool=C3=A9en?=
 =?UTF-8?q?=20de=20postgres?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../CodeGenerator/CodeGenerator.php           | 19 +++++++++-------
 src/UnicaenDbImport/CodeGenerator/Helper.php  | 10 +++++++++
 .../CodeGenerator/Helper/LogTableHelper.php   |  3 +++
 .../CodeGenerator/Helper/TableHelper.php      |  4 +++-
 .../Helper/TableValidationHelper.php          |  5 +++++
 .../Domain/Exception/NotFoundException.php    |  2 +-
 src/UnicaenDbImport/QueryExecutor.php         | 16 +++++++-------
 .../Service/DatabaseService.php               | 22 ++++++++++++-------
 src/UnicaenDbImport/Service/FacadeService.php | 11 +++++++++-
 9 files changed, 65 insertions(+), 27 deletions(-)

diff --git a/src/UnicaenDbImport/CodeGenerator/CodeGenerator.php b/src/UnicaenDbImport/CodeGenerator/CodeGenerator.php
index 719fad0..229cb7b 100644
--- a/src/UnicaenDbImport/CodeGenerator/CodeGenerator.php
+++ b/src/UnicaenDbImport/CodeGenerator/CodeGenerator.php
@@ -375,8 +375,10 @@ abstract class CodeGenerator implements CodeGeneratorInterface
     /**
      * @return string
      */
-    public function generateSQLForSelectingInImportObservTable()
+    public function generateSQLForSelectingInImportObservTable(string $table): string
     {
+        $requiredValueForEnabled = $this->tableHelper->platformSupportsBooleanType() ? 'true' : 1;
+
         return <<<EOS
 select
     id,
@@ -388,7 +390,8 @@ select
     to_value,
     filter
 from import_observ io 
-where io.operation = 'UPDATE' and io.enabled = 1
+where io.operation = 'UPDATE' and io.enabled = $requiredValueForEnabled
+and table_name = '$table'
 order by operation, table_name, column_name
 EOS;
     }
@@ -398,13 +401,13 @@ EOS;
      * @param string $where
      * @return string
      */
-    protected function generateSQLForSelectingDiffViewFromImportObservRow(array $importObservRow, $where = null)
+    protected function generateSQLForSelectingDiffViewFromImportObservRow(array $importObservRow, $where = null): string
     {
-        $id = $importObservRow['id'];
-        $tableName = $importObservRow['tableName'];
-        $columnName = $importObservRow['columnName'];
-        $toValue = $importObservRow['toValue'];
-        $filter = $importObservRow['filter'];
+        $id = $importObservRow['id'] ?? $importObservRow['ID'];
+        $tableName = $importObservRow['table_name'] ?? $importObservRow['TABLE_NAME'];
+        $columnName = $importObservRow['column_name'] ?? $importObservRow['COLUMN_NAME'];
+        $toValue = $importObservRow['to_value'] ?? $importObservRow['TO_VALUE'];
+        $filter = $importObservRow['filter'] ?? $importObservRow['FILTER'];
 
         // Construction du nom de la colonne de la vue V_DIFF_X indiquant un changement de valeur dans la table X.
         // Ex: 'U_RESULTAT' (dans la vue V_DIFF_THESE, indiquant que la colonne THESE.RESULTAT a changé).
diff --git a/src/UnicaenDbImport/CodeGenerator/Helper.php b/src/UnicaenDbImport/CodeGenerator/Helper.php
index a02b46f..ed628e2 100644
--- a/src/UnicaenDbImport/CodeGenerator/Helper.php
+++ b/src/UnicaenDbImport/CodeGenerator/Helper.php
@@ -20,6 +20,16 @@ abstract class Helper
      */
     protected $platform;
 
+    /**
+     * @return bool
+     */
+    public function platformSupportsBooleanType(): bool
+    {
+        return
+            $this->platform->getBooleanTypeDeclarationSQL([]) === 'BOOLEAN' ||
+            $this->platform->getBooleanTypeDeclarationSQL([]) === 'boolean';
+    }
+
     /**
      * @param string $argument
      * @return string
diff --git a/src/UnicaenDbImport/CodeGenerator/Helper/LogTableHelper.php b/src/UnicaenDbImport/CodeGenerator/Helper/LogTableHelper.php
index bef564b..6e233eb 100644
--- a/src/UnicaenDbImport/CodeGenerator/Helper/LogTableHelper.php
+++ b/src/UnicaenDbImport/CodeGenerator/Helper/LogTableHelper.php
@@ -66,6 +66,9 @@ EOT;
                 break;
         }
         $success = $result->getFailure() ? 0 : 1;
+        if ($this->platformSupportsBooleanType()) {
+            $success = $success ? 'true' : 'false';
+        }
         $startDate = $result->getStartDate()->format("Y-m-d H:i:s");
         $endDate = $result->getEndDate()->format("Y-m-d H:i:s");
 
diff --git a/src/UnicaenDbImport/CodeGenerator/Helper/TableHelper.php b/src/UnicaenDbImport/CodeGenerator/Helper/TableHelper.php
index 7948f7e..553c600 100644
--- a/src/UnicaenDbImport/CodeGenerator/Helper/TableHelper.php
+++ b/src/UnicaenDbImport/CodeGenerator/Helper/TableHelper.php
@@ -217,6 +217,8 @@ EOT;
 
         $deletedOnColumn = $this->config->getHistoColumnAliasForDeletedOn();
 
+        $requiredValueForImportable = $this->platformSupportsBooleanType() ? 'true' : 0;
+
         return <<<EOT
 with diff as (
     SELECT
@@ -236,7 +238,7 @@ with diff as (
         $destColumsSql
 
     FROM $destinationTable d
-    JOIN source src ON src.id = d.source_id AND src.importable = 1
+    JOIN source src ON src.id = d.source_id AND src.importable = $requiredValueForImportable
     FULL OUTER JOIN $diffSourceTableName s ON s.source_id = d.source_id AND s.$sourceCodeColumn = d.$sourceCodeColumn
 )
 select * from diff
diff --git a/src/UnicaenDbImport/CodeGenerator/Helper/TableValidationHelper.php b/src/UnicaenDbImport/CodeGenerator/Helper/TableValidationHelper.php
index 6f26e23..c4e94be 100644
--- a/src/UnicaenDbImport/CodeGenerator/Helper/TableValidationHelper.php
+++ b/src/UnicaenDbImport/CodeGenerator/Helper/TableValidationHelper.php
@@ -3,6 +3,7 @@
 namespace UnicaenDbImport\CodeGenerator\Helper;
 
 use Doctrine\DBAL\DBALException;
+use InvalidArgumentException;
 use UnicaenApp\Exception\RuntimeException;
 use UnicaenDbImport\CodeGenerator\Helper;
 
@@ -33,6 +34,10 @@ abstract class TableValidationHelper extends Helper
      */
     public function convertTableExistenceCheckResultToBoolean(array $result)
     {
+        if (! isset($result[0])) {
+            throw new InvalidArgumentException("Données fournies non exploitables");
+        }
+
         $value = array_pop($result[0]); // NB: on ignore le nom de la colonne car la casse est incertaine
 
         return intval($value) === 1;
diff --git a/src/UnicaenDbImport/Domain/Exception/NotFoundException.php b/src/UnicaenDbImport/Domain/Exception/NotFoundException.php
index 66b8db1..2ac214d 100644
--- a/src/UnicaenDbImport/Domain/Exception/NotFoundException.php
+++ b/src/UnicaenDbImport/Domain/Exception/NotFoundException.php
@@ -13,6 +13,6 @@ class NotFoundException extends RuntimeException
 
     public static function synchroByName($name)
     {
-        return new static("Import introuvable avec ce nom : " . $name);
+        return new static("Synchro introuvable avec ce nom : " . $name);
     }
 }
\ No newline at end of file
diff --git a/src/UnicaenDbImport/QueryExecutor.php b/src/UnicaenDbImport/QueryExecutor.php
index 55f2fc0..0a2ea17 100644
--- a/src/UnicaenDbImport/QueryExecutor.php
+++ b/src/UnicaenDbImport/QueryExecutor.php
@@ -55,7 +55,7 @@ class QueryExecutor
      * @param Connection $connection
      * @return array
      */
-    public function fetchAllAsGenerator($sql, Connection $connection)
+    public function fetchAllAsGenerator(string $sql, Connection $connection)
     {
         $statement = $this->executeQuery($sql, $connection);
 
@@ -73,23 +73,23 @@ class QueryExecutor
      * @param Connection $connection
      * @return array
      */
-    public function fetchAll($sql, Connection $connection)
+    public function fetchAll(string $sql, Connection $connection): array
     {
         $statement = $this->executeQuery($sql, $connection);
 
-        return $statement->fetchAll(\PDO::FETCH_ASSOC);
+        return $statement->fetchAllAssociative();
     }
 
     /**
-     * @param string     $sql
+     * @param string $sql
      * @param Connection $connection
      * @return array|null
      */
-    public function fetch($sql, Connection $connection)
+    public function fetch(string $sql, Connection $connection): ?array
     {
         $statement = $this->executeQuery($sql, $connection);
 
-        return $statement->fetch(\PDO::FETCH_ASSOC) ?: null;
+        return $statement->fetchAssociative() ?: null;
     }
 
     /**
@@ -98,8 +98,8 @@ class QueryExecutor
      * @return int
      * @throws DBALException
      */
-    public function exec($sql, Connection $connection)
+    public function exec(string $sql, Connection $connection): int
     {
-        return $connection->exec($sql);
+        return $connection->executeStatement($sql);
     }
 }
\ No newline at end of file
diff --git a/src/UnicaenDbImport/Service/DatabaseService.php b/src/UnicaenDbImport/Service/DatabaseService.php
index 2e0b75d..373fa72 100644
--- a/src/UnicaenDbImport/Service/DatabaseService.php
+++ b/src/UnicaenDbImport/Service/DatabaseService.php
@@ -263,7 +263,7 @@ class DatabaseService
     public function checkIntermediateTableNotExists($intermediateTable)
     {
         $sql = $this->codeGenerator->generateSQLForTableExistenceCheck($intermediateTable);
-        $result = $this->queryExecutor->fetchAll($sql, $this->destination->getConnection());
+        $result = $this->queryExecutor->fetch($sql, $this->destination->getConnection());
         $exists = $this->codeGenerator->convertTableExistenceCheckResultToBoolean($result);
         if ($exists) {
             throw new RuntimeException(
@@ -392,18 +392,24 @@ class DatabaseService
      */
     public function populateImportObservResultTable()
     {
-        $qb = $this->importObservService->getRepository()->createQueryBuilder('io')
-            ->andWhere("upper(io.tableName) = upper(:table)")->setParameter('table', $this->destination->getTable())
-            ->andWhere("io.operation = 'UPDATE'")
-            ->andWhere("io.enabled = 1")
-            ->addOrderBy('io.operation, io.tableName, io.columnName');
-        $importObservRows = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);
+//        $qb = $this->importObservService->getRepository()->createQueryBuilder('io')
+//            ->andWhere("upper(io.tableName) = upper(:table)")->setParameter('table', $this->destination->getTable())
+//            ->andWhere("io.operation = 'UPDATE'")
+//            ->andWhere("io.enabled = 1")
+//            ->addOrderBy('io.operation, io.tableName, io.columnName');
+//        $importObservRows = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);
+        $sql = $this->codeGenerator->generateSQLForSelectingInImportObservTable($this->destination->getTable());
+        try {
+            $importObservRows = $this->queryExecutor->fetchAll($sql, $this->destination->getConnection());
+        } catch (Exception $e) {
+            throw new RuntimeException("Erreur rencontrée lors de l'écriture dans la table IMPORT_OBSERV_RESULT", null, $e);
+        }
 
         if (!empty($importObservRows)) {
             $sql = $this->codeGenerator->generateSQLForInsertionIntoImportObservResult($this->destination, $importObservRows);
             try {
                 $this->queryExecutor->exec($sql, $this->destination->getConnection());
-            } catch (DBALException $e) {
+            } catch (Exception $e) {
                 throw new RuntimeException("Erreur rencontrée lors de l'écriture dans la table IMPORT_OBSERV_RESULT", null, $e);
             }
         }
diff --git a/src/UnicaenDbImport/Service/FacadeService.php b/src/UnicaenDbImport/Service/FacadeService.php
index 645c2b3..be2d618 100644
--- a/src/UnicaenDbImport/Service/FacadeService.php
+++ b/src/UnicaenDbImport/Service/FacadeService.php
@@ -43,6 +43,11 @@ class FacadeService
      */
     protected $useImportObserv = false;
 
+    /**
+     * @var bool
+     */
+    protected $importLogTableCreated = false;
+
     /**
      * FacadeService constructor.
      *
@@ -119,15 +124,19 @@ class FacadeService
 
     public function createImportLog()
     {
+        if ($this->importLogTableCreated) {
+            return;
+        }
+
         $connection = $this->destination->getConnection();
 
         switch (true) {
             case $connection instanceof DbConnection:
                 $this->databaseService->createImportLogTableIfNotExists();
+                $this->importLogTableCreated = true;
                 break;
             default:
                 throw ConnectionException::unexpected($connection);
-                break;
         }
     }
 
-- 
GitLab