Skip to content

Commit

Permalink
Made scout search fixed ordering optional & enabled sqlite/mssql inte…
Browse files Browse the repository at this point in the history
…gration
  • Loading branch information
frknakk committed Nov 3, 2023
1 parent 7eb12ab commit 5b0563f
Showing 1 changed file with 26 additions and 28 deletions.
54 changes: 26 additions & 28 deletions src/QueryDataTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -1001,11 +1001,9 @@ protected function applyScoutSearch(string $search_keyword): bool
$this->query->whereIn($this->scoutKey, $search_results);
});

// Order by scout search results & disable user ordering
if (count($search_results) > 0) {
$this->applyFixedOrderingToQuery($this->scoutKey, $search_results);

// Disable user ordering because we already order by search relevancy
// Order by scout search results & disable user ordering (if db driver is supported)
if (count($search_results) > 0 && $this->applyFixedOrderingToQuery($this->scoutKey, $search_results)) {
// Disable user ordering because we already ordered by search relevancy
$this->disableUserOrdering = true;
}

Expand All @@ -1025,16 +1023,15 @@ protected function applyScoutSearch(string $search_keyword): bool
*
* @param string $keyName
* @param array $orderedKeys
* @return void
*
* @throws \Exception If the database driver is unsupported.
* @return bool
*/
protected function applyFixedOrderingToQuery(string $keyName, array $orderedKeys)
{
$connection = $this->getConnection();
$driver_name = $connection->getDriverName();

// Escape keyName and orderedKeys
$rawKeyName = $keyName;
$keyName = $connection->escape($keyName);
$orderedKeys = collect($orderedKeys)
->map(function ($value) use ($connection) {
Expand All @@ -1043,36 +1040,37 @@ protected function applyFixedOrderingToQuery(string $keyName, array $orderedKeys

switch ($driver_name) {
case 'mysql':
// MySQL
// MySQL / MariaDB
$this->query->orderByRaw("FIELD($keyName, ".$orderedKeys->implode(',').')');
break;
return true;

/*
TODO: test implementations, fix if necessary and uncomment
case 'pgsql':
// PostgreSQL
$this->query->orderByRaw("array_position(ARRAY[" . $orderedKeys->implode(',') . "], $keyName)");
break;
case 'sqlite':
case 'sqlsrv':
// SQLite & Microsoft SQL Server
// should be generally compatible with all drivers using SQL syntax (but ugly solution)
$this->query->orderByRaw(
"CASE $keyName "
.
$orderedKeys
->map(fn($value, $index) => "WHEN $keyName = $value THEN $index")
->implode(' ')
.
" END"
);
break;
return true;
*/

case 'sqlite':
case 'sqlsrv':
// SQLite & Microsoft SQL Server
// Compatible with all SQL drivers (but ugly solution)

$this->query->orderByRaw(
"CASE `$rawKeyName` "
.
$orderedKeys
->map(fn($value, $index) => "WHEN $value THEN $index")
->implode(' ')
.
" END"
);
return true;

default:
throw new \Exception("Unsupported database driver: $driver_name");
return false;
}
}

Expand Down

0 comments on commit 5b0563f

Please sign in to comment.