From 1d93ba703f63c0423c36bf42bc8dd66b35a25dbb Mon Sep 17 00:00:00 2001 From: Nick Volgas Date: Tue, 7 Oct 2014 11:36:36 -0500 Subject: [PATCH] Adding in a query preview for seeing query before actually running it. --- src/Database.php | 39 +++++++++++++++++++++++++++++++++++++++ tests/DatabaseTests.php | 12 ++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/Database.php b/src/Database.php index 8ce14ec..740ddde 100644 --- a/src/Database.php +++ b/src/Database.php @@ -3,6 +3,7 @@ namespace werx\Core; use Illuminate\Database\Capsule\Manager as Capsule; +use Illuminate\Database\Eloquent\Builder as QueryBuilder; use Prelude\Dsn\DsnParser; class Database @@ -66,6 +67,12 @@ public static function init($config = null) $capsule->bootEloquent(); } + /** + * Return the name of the random function based on the SQL dialect being used. + * + * @param string $connection_name + * @return string + */ public static function random($connection_name = 'default') { if (self::$driver[$connection_name] == 'sqlite') { @@ -75,6 +82,12 @@ public static function random($connection_name = 'default') } } + /** + * Take a string DSN and parse it into an array of its pieces + * + * @param null $string + * @return array|null + */ public static function parseDsn($string = null) { $opts = null; @@ -94,6 +107,32 @@ public static function parseDsn($string = null) return $opts; } + /** + * Get a preview of what query will be run from a query builder. + * + * This DOES NOT run the query so it can be used for debugging potentially memory-intensive queries. + * + * @param QueryBuilder $query + * @return string + */ + public static function getQueryPreview(QueryBuilder $query = null) + { + if (empty($query)) { + return ""; + } + + $sql = str_replace('?', "'%s'", $query->toSql()); + $bindings = $query->getBindings(); + + return vsprintf($sql, $bindings); + } + + /** + * Get the last query that was run with data that was used bound to it. + * + * @param string $connection + * @return string + */ public static function getLastQuery($connection = "") { $last_query = ""; diff --git a/tests/DatabaseTests.php b/tests/DatabaseTests.php index 05804dd..28120d5 100644 --- a/tests/DatabaseTests.php +++ b/tests/DatabaseTests.php @@ -183,6 +183,18 @@ public function testGetLastQueryNoQueryRun() $this->assertEquals($expected, $query); } + public function testPreviewQuery() + { + $this->databaseInitSimple(); + + $query = \werx\Core\Tests\App\Models\Captain::where('first_name', 'James'); + + $sql = Database::getQueryPreview($query); + $expected = 'select * from "captains" where "first_name" = \'James\''; + + $this->assertEquals($expected, $sql); + } + protected function getTestDsnSimple() { return ['driver' => 'sqlite','database' => __DIR__ . '/resources/storage/example.sqlite'];