From b5343b93b7b526e6b040a80c9078f102c8df9195 Mon Sep 17 00:00:00 2001
From: catch <catch@35733.no-reply.drupal.org>
Date: Tue, 11 Aug 2020 12:03:26 +0100
Subject: [PATCH] Issue #3120892 by Kumar Kundan, ravi.shankar, julienjoye,
 daffie: Replicate SQL LEAST() in SQLite

---
 .../Database/Driver/sqlite/Connection.php     | 11 +++++++
 .../Core/Database/SelectLeastTest.php         | 32 +++++++++++++++++++
 2 files changed, 43 insertions(+)
 create mode 100644 core/tests/Drupal/KernelTests/Core/Database/SelectLeastTest.php

diff --git a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
index c1f3961f3f6d..817cebd05581 100644
--- a/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
+++ b/core/lib/Drupal/Core/Database/Driver/sqlite/Connection.php
@@ -133,6 +133,7 @@ public static function open(array &$connection_options = []) {
     // Create functions needed by SQLite.
     $pdo->sqliteCreateFunction('if', [__CLASS__, 'sqlFunctionIf']);
     $pdo->sqliteCreateFunction('greatest', [__CLASS__, 'sqlFunctionGreatest']);
+    $pdo->sqliteCreateFunction('least', [__CLASS__, 'sqlFunctionLeast']);
     $pdo->sqliteCreateFunction('pow', 'pow', 2);
     $pdo->sqliteCreateFunction('exp', 'exp', 1);
     $pdo->sqliteCreateFunction('length', 'strlen', 1);
@@ -239,6 +240,16 @@ public static function sqlFunctionGreatest() {
     }
   }
 
+  /**
+   * SQLite compatibility implementation for the LEAST() SQL function.
+   */
+  public static function sqlFunctionLeast() {
+    // Remove all NULL, FALSE and empty strings values but leaves 0 (zero) values.
+    $values = array_filter(func_get_args(), 'strlen');
+
+    return count($values) < 1 ? NULL : min($values);
+  }
+
   /**
    * SQLite compatibility implementation for the CONCAT() SQL function.
    */
diff --git a/core/tests/Drupal/KernelTests/Core/Database/SelectLeastTest.php b/core/tests/Drupal/KernelTests/Core/Database/SelectLeastTest.php
new file mode 100644
index 000000000000..7db76d03c568
--- /dev/null
+++ b/core/tests/Drupal/KernelTests/Core/Database/SelectLeastTest.php
@@ -0,0 +1,32 @@
+<?php
+
+namespace Drupal\KernelTests\Core\Database;
+
+/**
+ * Tests the SQL LEAST operator.
+ *
+ * @group Database
+ */
+class SelectLeastTest extends DatabaseTestBase {
+
+  /**
+   * Tests the SQL LEAST operator.
+   *
+   * @dataProvider selectLeastProvider
+   */
+  public function testSelectLeast($values, $expected) {
+    $least = $this->connection->query("SELECT LEAST(:values[])", [':values[]' => $values])->fetchField();
+    $this->assertEquals($expected, $least);
+  }
+
+  public function selectLeastProvider() {
+    return [
+      [[1, 2, 3, 4, 5, 6], 1],
+      [['A', 'B', 'C', 'NULL', 'F'], 'A'],
+      [['NULL', 'NULL'], 'NULL'],
+      [['TRUE', 'FALSE'], 'FALSE'],
+      [['A', 'B', 'C', 'NULL'], 'A'],
+    ];
+  }
+
+}
-- 
GitLab