Skip to content

Commit 51e35d9

Browse files
committed
Improving performance
Adding a cache layer on build. The cache will serve the same SQL if a SQL string with the same parameters set is passed (value of parameters is ignored, only availability is checked)
1 parent a6efcac commit 51e35d9

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/Mouf/Database/MagicQuery.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Mouf\Database;
44

55
use Doctrine\Common\Cache\VoidCache;
6+
use function hash;
67
use Mouf\Database\MagicQuery\Twig\SqlTwigEnvironmentFactory;
78
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
89
use PHPSQLParser\PHPSQLParser;
@@ -83,9 +84,19 @@ public function build($sql, array $parameters = array())
8384
if ($this->enableTwig) {
8485
$sql = $this->getTwigEnvironment()->render($sql, $parameters);
8586
}
86-
$select = $this->parse($sql);
8787

88-
return $this->toSql($select, $parameters);
88+
$availableParameterKeys = array_keys(array_filter($parameters, static function($param) { return $param !== null;}));
89+
// We choose md4 because it is fast.
90+
$cacheKey = 'request_build_'.hash('md4', $sql.'__'.implode('_/_', $availableParameterKeys));
91+
$newSql = $this->cache->fetch($cacheKey);
92+
if ($newSql === false) {
93+
$select = $this->parse($sql);
94+
$newSql = $this->toSql($select, $parameters);
95+
96+
$this->cache->save($cacheKey, $newSql);
97+
}
98+
99+
return $newSql;
89100
}
90101

91102
/**

0 commit comments

Comments
 (0)