Skip to content

Commit

Permalink
Use Natural_SORT_KEY for natural sorting on MariaDB database which su…
Browse files Browse the repository at this point in the history
…pport that

This resolves issue #243 and #402
  • Loading branch information
jbtronics committed Jun 17, 2024
1 parent 0a482da commit 289c912
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/Doctrine/Functions/Natsort.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

namespace App\Doctrine\Functions;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\AbstractPostgreSQLDriver;
use Doctrine\DBAL\Platforms\MariaDBPlatform;
use Doctrine\DBAL\Platforms\PostgreSQLPlatform;
Expand All @@ -36,6 +37,29 @@ class Natsort extends FunctionNode
{
private ?Node $field = null;

private static ?bool $supportsNaturalSort = null;

/**
* Check if the MariaDB version which is connected to supports the natural sort (meaning it has a version of 10.7.0 or higher)
* The result is cached in memory.
* @param Connection $connection
* @return bool
* @throws \Doctrine\DBAL\Exception
*/
private static function mariaDBSupportsNaturalSort(Connection $connection): bool
{
if (self::$supportsNaturalSort !== null) {
return self::$supportsNaturalSort;
}

$version = $connection->getServerVersion();
//Remove the -MariaDB suffix
$version = str_replace('-MariaDB', '', $version);
//We need at least MariaDB 10.7.0 to support the natural sort
self::$supportsNaturalSort = version_compare($version, '10.7.0', '>=');
return self::$supportsNaturalSort;
}

public function parse(Parser $parser): void
{
$parser->match(TokenType::T_IDENTIFIER);
Expand All @@ -56,9 +80,9 @@ public function getSql(SqlWalker $sqlWalker): string
return $this->field->dispatch($sqlWalker) . ' COLLATE numeric';
}

/*if ($platform instanceof MariaDBPlatform && $sqlWalker->getConnection()->getServerVersion()) {
}*/
if ($platform instanceof MariaDBPlatform && self::mariaDBSupportsNaturalSort($sqlWalker->getConnection())) {
return 'NATURAL_SORT_KEY(' . $this->field->dispatch($sqlWalker) . ')';
}

//For every other platform, return the field as is
return $this->field->dispatch($sqlWalker);
Expand Down

0 comments on commit 289c912

Please sign in to comment.