Skip to content

Commit

Permalink
Merge pull request #2 from volnix/master
Browse files Browse the repository at this point in the history
Adding in a query preview for seeing query before actually running it.
  • Loading branch information
joshmoody committed Oct 8, 2014
2 parents 70319d7 + 1d93ba7 commit d639312
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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') {
Expand All @@ -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;
Expand All @@ -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 = "";
Expand Down
12 changes: 12 additions & 0 deletions tests/DatabaseTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down

0 comments on commit d639312

Please sign in to comment.