Skip to content

Commit 18b9848

Browse files
authored
Merge pull request #44 from moufmouf/cache_build
Improving performance
2 parents a6efcac + f41860a commit 18b9848

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-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
/**

tests/Mouf/Database/MagicQueryTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ public function testStandardSelect()
2020

2121
$sql = 'SELECT id FROM users WHERE name LIKE :name LIMIT 2, :limit';
2222
$this->assertEquals("SELECT id FROM users WHERE name LIKE 'foo' LIMIT 2, 10", self::simplifySql($magicQuery->build($sql, ['name' => 'foo', 'limit' => 10])));
23+
// Test cache
24+
$this->assertEquals("SELECT id FROM users WHERE name LIKE 'bar' LIMIT 2, 10", self::simplifySql($magicQuery->build($sql, ['name' => 'bar', 'limit' => 10])));
2325

2426
try {
2527
$exceptionOccurred = false;

0 commit comments

Comments
 (0)