diff --git a/.travis.yml b/.travis.yml index 084da3e..92dd802 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,12 +2,12 @@ language: php sudo: false php: - - 5.5 - - 5.6 + - 7.0 + - 7.1 before_script: - - composer install --dev + - composer install script: - mkdir -p build/logs diff --git a/composer.json b/composer.json index 0255dd8..465872b 100644 --- a/composer.json +++ b/composer.json @@ -9,18 +9,21 @@ "email": "joe.green0991@gmail.com" } ], + "scripts" : { + "test": "./vendor/bin/phpunit" + }, "require": { "php": ">=5.4.0", "psr/log": "~1.0" }, - "require-dev": { - "mockery/mockery": "*", - "satooshi/php-coveralls": "dev-master", - "phpunit/phpunit": "*" - }, "autoload": { "psr-4": { "Database\\": "src" } + }, + "require-dev": { + "mockery/mockery": "^0.9.9", + "satooshi/php-coveralls": "^1.0", + "phpunit/phpunit": "^6.1" } } diff --git a/phpunit.xml b/phpunit.xml index 62710cf..d7abd8d 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -7,7 +7,7 @@ convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" - stopOnFailure="true" + stopOnFailure="false" syntaxCheck="false" > diff --git a/src/Connection.php b/src/Connection.php index 979b93e..7da8bb0 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -339,7 +339,9 @@ protected function run($query, $bindings, $useReadPdo = false) */ private function execute($query, $bindings, $useReadPdo) { - if ($this->pretending()) return new \PDOStatement(); + if ($this->pretending()) { + return new \PDOStatement(); + } $pdo = $useReadPdo ? $this->getReadPdo() : $this->getPdo(); @@ -354,9 +356,7 @@ private function execute($query, $bindings, $useReadPdo) // If an exception occurs when attempting to run a query, we'll call the exception handler // if there is one, or throw the exception if not catch (\Exception $e) { - - if($this->exceptionHandler) - { + if ($this->exceptionHandler) { $this->exceptionHandler->handle($query, $this->prepareBindings($bindings), $e); } @@ -499,13 +499,9 @@ public function connect() public function reconnect() { if (is_callable($this->reconnector)) { - - try - { + try { return call_user_func($this->reconnector, $this); - } - catch(\PDOException $e) - { + } catch (\PDOException $e) { $this->exceptionHandler->handle("Connection attempt", array(), $e); } } @@ -535,7 +531,9 @@ protected function reconnectIfMissingConnection() */ protected function logQuery($query, $bindings, $start = null) { - if (!$this->loggingQueries || !$this->logger) return; + if (!$this->loggingQueries || !$this->logger) { + return; + } $time = $start ? round((microtime(true) - $start) * 1000, 2) : null; @@ -562,8 +560,7 @@ public function getPdo() */ public function getReadPdo() { - if (!$this->readPdo || $this->pdo->inTransaction()) - { + if (!$this->readPdo || $this->pdo->inTransaction()) { return $this->getPdo(); } @@ -684,8 +681,7 @@ public function enableQueryLog() { $this->loggingQueries = true; - if(!$this->logger) - { + if (!$this->logger) { $this->logger = new QueryLogger(); } diff --git a/src/ConnectionInterface.php b/src/ConnectionInterface.php index 225fd91..c386315 100644 --- a/src/ConnectionInterface.php +++ b/src/ConnectionInterface.php @@ -118,5 +118,4 @@ public function inTransaction(); * @return array */ public function pretend(Closure $callback); - } diff --git a/src/ConnectionResolver.php b/src/ConnectionResolver.php index f75e5b8..646d5e6 100644 --- a/src/ConnectionResolver.php +++ b/src/ConnectionResolver.php @@ -55,10 +55,11 @@ public function __construct(array $connections = array(), ConnectionFactoryInter */ public function connection($name = null) { - if (is_null($name)) $name = $this->getDefaultConnection(); + if (is_null($name)) { + $name = $this->getDefaultConnection(); + } - if (!isset($this->connectionCache[$name])) - { + if (!isset($this->connectionCache[$name])) { $this->connectionCache[$name] = $this->newConnection($name); } @@ -73,7 +74,9 @@ public function connection($name = null) */ public function newConnection($name = null) { - if (is_null($name)) $name = $this->getDefaultConnection(); + if (is_null($name)) { + $name = $this->getDefaultConnection(); + } return $this->connectionFactory->make($this->connectionConfig($name)); } @@ -86,7 +89,9 @@ public function newConnection($name = null) */ public function connectionConfig($name = null) { - if (is_null($name)) $name = $this->getDefaultConnection(); + if (is_null($name)) { + $name = $this->getDefaultConnection(); + } return $this->value($this->connections[$name]); } diff --git a/src/ConnectionResolverInterface.php b/src/ConnectionResolverInterface.php index 8870a4d..8861d4d 100644 --- a/src/ConnectionResolverInterface.php +++ b/src/ConnectionResolverInterface.php @@ -25,5 +25,4 @@ public function getDefaultConnection(); * @return void */ public function setDefaultConnection($name); - } diff --git a/src/Connectors/ConnectionFactory.php b/src/Connectors/ConnectionFactory.php index a86f038..19b579a 100644 --- a/src/Connectors/ConnectionFactory.php +++ b/src/Connectors/ConnectionFactory.php @@ -114,8 +114,7 @@ protected function createSingleConnection(array $config, $lazy) ->setTablePrefix(isset($config['prefix']) ? $config['prefix'] : '') ->setLogger($this->logger); - if(!$lazy) - { + if (!$lazy) { $connection->setPdo($this->createConnector($config['driver'])->connect($config)); } @@ -141,8 +140,7 @@ protected function createReadWriteConnection(array $config, $lazy) { $connection = $this->createSingleConnection($this->getWriteConfig($config), $lazy); - if(!$lazy) - { + if (!$lazy) { $connection->setReadPdo($this->createReadPdo($config)); } diff --git a/src/Connectors/Connector.php b/src/Connectors/Connector.php index 6cdcc32..fa715a9 100644 --- a/src/Connectors/Connector.php +++ b/src/Connectors/Connector.php @@ -46,14 +46,11 @@ public function createConnection($dsn, array $config, array $options) $password = isset($config['password']) ? $config['password'] : null; - try - { + try { return new PDO($dsn, $username, $password, $options); - }catch (\PDOException $e) - { + } catch (\PDOException $e) { throw new ConnectionException("Connection to '$dsn' failed: " . $e->getMessage(), $e); } - } /** @@ -76,5 +73,4 @@ public function setDefaultOptions(array $options) { $this->options = $options; } - } diff --git a/src/Connectors/ConnectorInterface.php b/src/Connectors/ConnectorInterface.php index 253f5d8..fe1d72c 100644 --- a/src/Connectors/ConnectorInterface.php +++ b/src/Connectors/ConnectorInterface.php @@ -10,5 +10,4 @@ interface ConnectorInterface * @return \PDO */ public function connect(array $config); - } diff --git a/src/Connectors/MySqlConnector.php b/src/Connectors/MySqlConnector.php index d661c11..8f6f47c 100644 --- a/src/Connectors/MySqlConnector.php +++ b/src/Connectors/MySqlConnector.php @@ -98,5 +98,4 @@ protected function getHostDsn(array $config) return $dsn; } - } diff --git a/src/Connectors/PostgresConnector.php b/src/Connectors/PostgresConnector.php index 65510a7..4e4187e 100644 --- a/src/Connectors/PostgresConnector.php +++ b/src/Connectors/PostgresConnector.php @@ -83,5 +83,4 @@ protected function getDsn(array $config) return $dsn; } - } diff --git a/src/Connectors/SQLiteConnector.php b/src/Connectors/SQLiteConnector.php index fb21dd4..ff5c24b 100644 --- a/src/Connectors/SQLiteConnector.php +++ b/src/Connectors/SQLiteConnector.php @@ -33,5 +33,4 @@ public function connect(array $config) return $this->createConnection("sqlite:{$path}", $config, $options); } - } diff --git a/src/Connectors/SqlServerConnector.php b/src/Connectors/SqlServerConnector.php index 6c27233..df97e8a 100644 --- a/src/Connectors/SqlServerConnector.php +++ b/src/Connectors/SqlServerConnector.php @@ -63,5 +63,4 @@ protected function getAvailableDrivers() { return PDO::getAvailableDrivers(); } - } diff --git a/src/Exception/ExceptionHandler.php b/src/Exception/ExceptionHandler.php index 44b32d8..c72fce5 100644 --- a/src/Exception/ExceptionHandler.php +++ b/src/Exception/ExceptionHandler.php @@ -34,10 +34,10 @@ public function handle($query = '', array $bindings = array(), \Exception $previ { $parameters = $this->parameters; - if($query){ + if ($query) { $sql = $this->replaceArray('\?', $bindings, $query); - if($this->maxQueryLength && strlen($sql) > $this->maxQueryLength){ + if ($this->maxQueryLength && strlen($sql) > $this->maxQueryLength) { $sql = substr($sql, 0, $this->maxQueryLength); } @@ -57,8 +57,7 @@ private function formatArrayParameters(array $parameters) { $parameters = $this->flattenArray($parameters); - foreach($parameters as $name => $value) - { + foreach ($parameters as $name => $value) { $parameters[$name] = $name . ': ' . $value; } diff --git a/src/Query/Builder.php b/src/Query/Builder.php index be27f60..615a2dc 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -1038,7 +1038,9 @@ public function offset($value) */ public function limit($value) { - if ($value > 0) $this->limit = $value; + if ($value > 0) { + $this->limit = $value; + } return $this; } @@ -1173,7 +1175,9 @@ public function first($columns = array('*')) */ public function get($columns = array('*')) { - if (is_null($this->columns)) $this->columns = $columns; + if (is_null($this->columns)) { + $this->columns = $columns; + } return $this->connection->fetchAll($this->toSql(), $this->getBindings()); } @@ -1188,8 +1192,7 @@ public function infile($file, $columns, Closure $builder = null) { $clause = new InfileClause($file, $columns); - if($builder) - { + if ($builder) { $builder($clause); } @@ -1228,8 +1231,7 @@ private function outfile($type, $file, $builder) { $this->outfile = $clause = new OutfileClause($file, $type); - if($builder) - { + if ($builder) { $builder($clause); } @@ -1244,7 +1246,9 @@ private function outfile($type, $file, $builder) */ public function query($columns = array('*')) { - if (is_null($this->columns)) $this->columns = $columns; + if (is_null($this->columns)) { + $this->columns = $columns; + } return $this->connection->query($this->toSql(), $this->getBindings()); } @@ -1313,7 +1317,9 @@ protected function getListSelect($column, $key) */ public function implode($column, $glue = null) { - if (is_null($glue)) return implode($this->lists($column)); + if (is_null($glue)) { + return implode($this->lists($column)); + } return implode($glue, $this->lists($column)); } @@ -1349,7 +1355,6 @@ protected function backupFieldsForCount() $this->{$field} = null; } - } /** @@ -1480,8 +1485,7 @@ public function setDefaultChunkSize($chunkSize) */ public function buffer($chunkSize = null) { - if(is_null($chunkSize)) - { + if (is_null($chunkSize)) { $chunkSize = $this->defaultChunkSize; } @@ -1565,8 +1569,7 @@ protected function doInsertSelect($select, array $columns, $type) */ private function prepareInsertSelect($select) { - if($select instanceof Closure) - { + if ($select instanceof Closure) { $callback = $select; $select = $this->newQuery(); @@ -1574,8 +1577,7 @@ private function prepareInsertSelect($select) call_user_func($callback, $select); } - if(!$select instanceof Builder) - { + if (!$select instanceof Builder) { throw new \Exception("Argument 1 must be a closure or an instance of Database\\Query\\Builder"); } @@ -1632,9 +1634,10 @@ public function insertSelectUpdate($select, array $columns, array $updateValues) $bindings = $select->getBindings(); - foreach($updateValues as $value) - { - if(!$value instanceof Expression) $bindings[] = $value; + foreach ($updateValues as $value) { + if (!$value instanceof Expression) { + $bindings[] = $value; + } } return $this->connection->query($sql, $bindings); @@ -1671,9 +1674,10 @@ public function insertUpdate(array $values, array $updateValues) $bindings = $this->buildBulkInsertBindings($values); - foreach($updateValues as $value) - { - if(!$value instanceof Expression) $bindings[] = $value; + foreach ($updateValues as $value) { + if (!$value instanceof Expression) { + $bindings[] = $value; + } } $sql = $this->grammar->compileInsertOnDuplicateKeyUpdate($this, $values, $updateValues); @@ -1706,7 +1710,9 @@ private function buildBulkInsertBindings($values) foreach ($values as $record) { foreach ($record as $value) { - if(!$value instanceof Expression) $bindings[] = $value; + if (!$value instanceof Expression) { + $bindings[] = $value; + } } } @@ -1793,7 +1799,9 @@ public function delete($id = null) // If an ID is passed to the method, we will set the where clause to check // the ID to allow developers to simply and quickly remove a single row // from their database without manually specifying the where clauses. - if (!is_null($id)) $this->where('id', '=', $id); + if (!is_null($id)) { + $this->where('id', '=', $id); + } $sql = $this->grammar->compileDelete($this); diff --git a/src/Query/Expression.php b/src/Query/Expression.php index 05de986..5e14679 100644 --- a/src/Query/Expression.php +++ b/src/Query/Expression.php @@ -40,5 +40,4 @@ public function __toString() { return (string)$this->getValue(); } - } diff --git a/src/Query/Grammars/Grammar.php b/src/Query/Grammars/Grammar.php index 765d72a..f9ef71a 100644 --- a/src/Query/Grammars/Grammar.php +++ b/src/Query/Grammars/Grammar.php @@ -5,7 +5,6 @@ class Grammar { - const DATE_SQL = 'Y-m-d H:i:s'; /** * The components that make up a select clause. @@ -53,7 +52,9 @@ public function wrapArray(array $values) */ public function wrapTable($table) { - if ($this->isExpression($table)) return $this->getValue($table); + if ($this->isExpression($table)) { + return $this->getValue($table); + } return $this->wrap($this->tablePrefix . $table); } @@ -66,7 +67,9 @@ public function wrapTable($table) */ public function wrap($value) { - if ($this->isExpression($value)) return $this->getValue($value); + if ($this->isExpression($value)) { + return $this->getValue($value); + } // If the value being wrapped has a column alias we will need to separate out // the pieces so we can wrap each of the segments of the expression on it @@ -103,7 +106,9 @@ public function wrap($value) */ protected function wrapValue($value) { - if ($value === '*') return $value; + if ($value === '*') { + return $value; + } return '"' . str_replace('"', '""', $value) . '"'; } @@ -204,7 +209,9 @@ public function setTablePrefix($prefix) */ public function compileSelect(Builder $query) { - if (is_null($query->columns)) $query->columns = array('*'); + if (is_null($query->columns)) { + $query->columns = array('*'); + } return trim($this->concatenate($this->compileComponents($query))); } @@ -266,7 +273,9 @@ protected function compileColumns(Builder $query, $columns) // If the query is actually performing an aggregating select, we will let that // compiler handle the building of the select clauses, as it will need some // more syntax that is best handled by that function to keep things neat. - if (!is_null($query->aggregate)) return; + if (!is_null($query->aggregate)) { + return; + } $select = $query->distinct ? 'select distinct ' : 'select '; @@ -355,7 +364,9 @@ protected function compileWheres(Builder $query) { $sql = array(); - if (is_null($query->wheres)) return ''; + if (is_null($query->wheres)) { + return ''; + } // Each type of where clauses has its own compiler function which is responsible // for actually creating the where clauses SQL. This helps keep the code nice @@ -670,11 +681,12 @@ protected function compileBasicHaving($having) protected function compileOrders(Builder $query, $orders) { return 'order by ' . implode(', ', array_map(function ($order) { - if (isset($order['sql'])) return $order['sql']; - - return $this->wrap($order['column']) . ' ' . $order['direction']; + if (isset($order['sql'])) { + return $order['sql']; } - , $orders)); + + return $this->wrap($order['column']) . ' ' . $order['direction']; + }, $orders)); } /** @@ -1009,5 +1021,4 @@ private function throwUnsupportedGrammarException($grammarDescription) { throw new UnsupportedGrammarException("$grammarDescription is not supported by the " . get_called_class() . " grammar driver"); } - } diff --git a/src/Query/Grammars/MySqlGrammar.php b/src/Query/Grammars/MySqlGrammar.php index e9f052c..8f6ee6a 100644 --- a/src/Query/Grammars/MySqlGrammar.php +++ b/src/Query/Grammars/MySqlGrammar.php @@ -66,7 +66,9 @@ protected function compileUnion(array $union) */ protected function compileLock(Builder $query, $value) { - if (is_string($value)) return $value; + if (is_string($value)) { + return $value; + } return $value ? 'for update' : 'lock in share mode'; } @@ -215,7 +217,9 @@ public function compileDelete(Builder $query) */ protected function wrapValue($value) { - if ($value === '*') return $value; + if ($value === '*') { + return $value; + } return '`' . str_replace('`', '``', $value) . '`'; } @@ -229,8 +233,7 @@ protected function compileOutfile(Builder $query, OutfileClause $outfileClause) { $sqlParts = array("into $outfileClause->type '$outfileClause->file'"); - if($options = $this->buildInfileOutfileOptions($outfileClause)) - { + if ($options = $this->buildInfileOutfileOptions($outfileClause)) { $sqlParts[] = $options; } @@ -250,20 +253,17 @@ public function compileInfile(Builder $query, InfileClause $infile) $sqlParts = array("load data {$local}infile '$infile->file' {$type}into table " . $this->wrapTable($query->from)); - if($options = $this->buildInfileOutfileOptions($infile)) - { + if ($options = $this->buildInfileOutfileOptions($infile)) { $sqlParts[] = $options; } - if($infile->ignoreLines) - { + if ($infile->ignoreLines) { $sqlParts[] = "ignore $infile->ignoreLines lines"; } $sqlParts[] = '(' . $this->columnize($infile->columns) . ')'; - if($infile->rules) - { + if ($infile->rules) { $sqlParts[] = 'set ' . $this->getUpdateColumns($infile->rules); } @@ -280,8 +280,7 @@ private function buildInfileOutfileOptions($infile) $optionally = $infile->optionallyEnclosedBy ? 'optionally ' : ''; - if(isset($infile->characterSet)) - { + if (isset($infile->characterSet)) { $sqlParts[] = "character set $infile->characterSet"; } @@ -297,12 +296,9 @@ private function buildInfileOutfileOptions($infile) ) ); - foreach ($parts as $type => $components) - { - foreach($components as $property => $sql) - { - if(isset($infile->$property)) - { + foreach ($parts as $type => $components) { + foreach ($components as $property => $sql) { + if (isset($infile->$property)) { $sqlParts[] = trim("$type $sql '{$infile->$property}'"); $type = ''; diff --git a/src/Query/Grammars/PostgresGrammar.php b/src/Query/Grammars/PostgresGrammar.php index 3940be9..32c0161 100644 --- a/src/Query/Grammars/PostgresGrammar.php +++ b/src/Query/Grammars/PostgresGrammar.php @@ -25,7 +25,9 @@ class PostgresGrammar extends Grammar */ protected function compileLock(Builder $query, $value) { - if (is_string($value)) return $value; + if (is_string($value)) { + return $value; + } return $value ? 'for update' : 'for share'; } @@ -81,7 +83,9 @@ protected function compileUpdateColumns($values) */ protected function compileUpdateFrom(Builder $query) { - if (!isset($query->joins)) return ''; + if (!isset($query->joins)) { + return ''; + } $froms = array(); @@ -92,7 +96,9 @@ protected function compileUpdateFrom(Builder $query) $froms[] = $this->wrapTable($join->table); } - if (count($froms) > 0) return ' from ' . implode(', ', $froms); + if (count($froms) > 0) { + return ' from ' . implode(', ', $froms); + } } /** @@ -105,7 +111,9 @@ protected function compileUpdateWheres(Builder $query) { $baseWhere = $this->compileWheres($query); - if (!isset($query->joins)) return $baseWhere; + if (!isset($query->joins)) { + return $baseWhere; + } // Once we compile the join constraints, we will either use them as the where // clause or append them to the existing base where clauses. If we need to @@ -151,7 +159,9 @@ protected function compileUpdateJoinWheres(Builder $query) */ public function compileInsertGetId(Builder $query, $values, $sequence) { - if (is_null($sequence)) $sequence = 'id'; + if (is_null($sequence)) { + $sequence = 'id'; + } return $this->compileInsert($query, $values) . ' returning ' . $this->wrap($sequence); } @@ -166,5 +176,4 @@ public function compileTruncate(Builder $query) { return array('truncate ' . $this->wrapTable($query->from) . ' restart identity' => array()); } - } diff --git a/src/Query/Grammars/SQLiteGrammar.php b/src/Query/Grammars/SQLiteGrammar.php index 7908969..11898ab 100644 --- a/src/Query/Grammars/SQLiteGrammar.php +++ b/src/Query/Grammars/SQLiteGrammar.php @@ -148,5 +148,4 @@ protected function dateBasedWhere($type, Builder $query, $where) return 'strftime(\'' . $type . '\', ' . $this->wrap($where['column']) . ') ' . $where['operator'] . ' ' . $value; } - } diff --git a/src/Query/Grammars/SqlServerGrammar.php b/src/Query/Grammars/SqlServerGrammar.php index 779f076..702637c 100644 --- a/src/Query/Grammars/SqlServerGrammar.php +++ b/src/Query/Grammars/SqlServerGrammar.php @@ -45,7 +45,9 @@ public function compileSelect(Builder $query) */ protected function compileColumns(Builder $query, $columns) { - if (!is_null($query->aggregate)) return; + if (!is_null($query->aggregate)) { + return; + } $select = $query->distinct ? 'select distinct ' : 'select '; @@ -70,7 +72,9 @@ protected function compileFrom(Builder $query, $table) { $from = parent::compileFrom($query, $table); - if (is_string($query->lock)) return $from . ' ' . $query->lock; + if (is_string($query->lock)) { + return $from . ' ' . $query->lock; + } if (!is_null($query->lock)) { return $from . ' with(rowlock,' . ($query->lock ? 'updlock,' : '') . 'holdlock)'; @@ -212,9 +216,10 @@ public function getDateFormat() */ protected function wrapValue($value) { - if ($value === '*') return $value; + if ($value === '*') { + return $value; + } return '[' . str_replace(']', ']]', $value) . ']'; } - } diff --git a/src/Query/Grammars/UnsupportedGrammarException.php b/src/Query/Grammars/UnsupportedGrammarException.php index 7250550..702abb9 100644 --- a/src/Query/Grammars/UnsupportedGrammarException.php +++ b/src/Query/Grammars/UnsupportedGrammarException.php @@ -2,5 +2,4 @@ class UnsupportedGrammarException extends \Exception { - } diff --git a/src/Query/InfileClause.php b/src/Query/InfileClause.php index 9190551..eca0db3 100644 --- a/src/Query/InfileClause.php +++ b/src/Query/InfileClause.php @@ -75,8 +75,7 @@ class InfileClause */ public function __construct($file, array $columns) { - if($file instanceof \SplFileInfo) - { + if ($file instanceof \SplFileInfo) { $file = $file->getPathname(); } @@ -160,8 +159,7 @@ public function linesTerminatedBy($character) */ public function ignoreLines($lineCount) { - if(!is_integer($lineCount) || $lineCount < 1) - { + if (!is_integer($lineCount) || $lineCount < 1) { throw new \InvalidArgumentException("Line count must be a positive, non-zero integer."); } diff --git a/src/Query/InsertBuffer.php b/src/Query/InsertBuffer.php index 90d01f3..16dc189 100644 --- a/src/Query/InsertBuffer.php +++ b/src/Query/InsertBuffer.php @@ -71,7 +71,7 @@ protected function doInsert(Traversable $values, $type) { $inserts = 0; - $this->buffer($values, function(array $buffer) use($type, &$inserts){ + $this->buffer($values, function (array $buffer) use ($type, &$inserts) { $inserts += $this->builder->doInsert($buffer, $type)->rowCount(); }); @@ -89,7 +89,7 @@ public function insertUpdate(Traversable $values, array $updateValues) { $upserts = 0; - $this->buffer($values, function(array $buffer) use($updateValues, &$upserts){ + $this->buffer($values, function (array $buffer) use ($updateValues, &$upserts) { $upserts += $this->builder->insertUpdate($buffer, $updateValues)->rowCount(); }); @@ -120,12 +120,10 @@ private function buffer(Traversable $values, Closure $callback) $size = 0; $buffer = array(); - foreach($values as $row) - { + foreach ($values as $row) { $buffer[] = $row; - if(++$size >= $this->chunkSize) - { + if (++$size >= $this->chunkSize) { $callback($buffer); $buffer = array(); @@ -134,8 +132,7 @@ private function buffer(Traversable $values, Closure $callback) } // Insert the remainder - if($size) - { + if ($size) { $callback($buffer); } } diff --git a/src/Query/JoinClause.php b/src/Query/JoinClause.php index 1edcef2..497b4c7 100644 --- a/src/Query/JoinClause.php +++ b/src/Query/JoinClause.php @@ -57,7 +57,9 @@ public function on($first, $operator, $second, $boolean = 'and', $where = false) { $this->clauses[] = compact('first', 'operator', 'second', 'boolean', 'where'); - if ($where) $this->bindings[] = $second; + if ($where) { + $this->bindings[] = $second; + } return $this; } @@ -113,5 +115,4 @@ public function whereNull($column, $boolean = 'and') { return $this->on($column, 'is', new Expression('null'), $boolean, false); } - } diff --git a/src/Query/OutfileClause.php b/src/Query/OutfileClause.php index bf37572..db211e0 100644 --- a/src/Query/OutfileClause.php +++ b/src/Query/OutfileClause.php @@ -49,8 +49,7 @@ class OutfileClause */ public function __construct($file, $type) { - if($file instanceof \SplFileInfo) - { + if ($file instanceof \SplFileInfo) { $file = $file->getPathname(); } @@ -116,5 +115,4 @@ public function linesTerminatedBy($character) return $this; } - } diff --git a/tests/integration/AbstractDatabaseIntegrationTest.php b/tests/integration/AbstractDatabaseIntegrationTest.php index aa6ecae..94280a6 100644 --- a/tests/integration/AbstractDatabaseIntegrationTest.php +++ b/tests/integration/AbstractDatabaseIntegrationTest.php @@ -1,6 +1,6 @@ connection = $factory->make($config); $this->createTable(); return; + } catch (\PDOException $e) { } - catch(\PDOException $e) {} } throw $e; @@ -39,4 +37,4 @@ private function createTable() $this->connection->query("TRUNCATE TABLE $this->tableName"); } -} \ No newline at end of file +} diff --git a/tests/integration/DatabaseConnectionIntegrationTest.php b/tests/integration/DatabaseConnectionIntegrationTest.php index b20d443..9727f3a 100644 --- a/tests/integration/DatabaseConnectionIntegrationTest.php +++ b/tests/integration/DatabaseConnectionIntegrationTest.php @@ -16,7 +16,7 @@ public function testItReturnsCorrectValuesForUtilityFunctions() public function testItPerformsTransactions() { - $this->connection->transaction(function($connection){ + $this->connection->transaction(function ($connection) { $connection->query("INSERT INTO $this->tableName (name, value) VALUES (?,?)", array('joe', 1)); }); @@ -25,16 +25,17 @@ public function testItPerformsTransactions() $this->assertCount(1, $rows); $this->assertEquals(array('name' => 'joe', 'value' => 1), $rows[0]); - try{ - $this->connection->transaction(function($connection){ + try { + $this->connection->transaction(function ($connection) { $connection->query("INSERT INTO $this->tableName (name, value) VALUES (?,?)", array('joseph', 2)); throw new \Exception("rollback"); }); - }catch (\Exception $e){} + } catch (\Exception $e) { + } $rows = $this->connection->fetchAll("SELECT * FROM $this->tableName"); $this->assertCount(1, $rows); } -} \ No newline at end of file +} diff --git a/tests/integration/DatabaseQueryBuilderIntegrationTest.php b/tests/integration/DatabaseQueryBuilderIntegrationTest.php index 89176ef..501d7b7 100644 --- a/tests/integration/DatabaseQueryBuilderIntegrationTest.php +++ b/tests/integration/DatabaseQueryBuilderIntegrationTest.php @@ -41,7 +41,6 @@ public function testInsertUpdateDelete() ->exists(); $this->assertFalse($exists); - } public function testOutfile() @@ -64,7 +63,7 @@ public function testOutfileWithTerminators() $this->connection ->table($this->tableName) ->where('name', '=', 'joe') - ->intoOutfile($file, function(\Database\Query\OutfileClause $outfile){ + ->intoOutfile($file, function (\Database\Query\OutfileClause $outfile) { $outfile ->linesTerminatedBy("\n") ->fieldsTerminatedBy("\t"); @@ -73,4 +72,4 @@ public function testOutfileWithTerminators() @unlink($file); } -} \ No newline at end of file +} diff --git a/tests/integration/config.php b/tests/integration/config.php index 6abeb32..4abeab6 100644 --- a/tests/integration/config.php +++ b/tests/integration/config.php @@ -13,7 +13,7 @@ ) ), array( - 'host' => 'localhost', + 'host' => '127.0.0.1', 'driver' => 'mysql', 'username' => 'root', 'password' => 'password', diff --git a/tests/unit/Database/DatabaseConnectionFactoryTest.php b/tests/unit/Database/DatabaseConnectionFactoryTest.php index f283bf1..31df02f 100755 --- a/tests/unit/Database/DatabaseConnectionFactoryTest.php +++ b/tests/unit/Database/DatabaseConnectionFactoryTest.php @@ -2,123 +2,133 @@ use Mockery as m; -class DatabaseConnectionFactoryPDOStub extends PDO { - public function __construct() {} +class DatabaseConnectionFactoryPDOStub extends PDO +{ + public function __construct() + { + } } -class DatabaseConnectionFactoryTest extends PHPUnit_Framework_TestCase { - - public function tearDown() - { - m::close(); - } +class DatabaseConnectionFactoryTest extends \PHPUnit\Framework\TestCase +{ + public function tearDown() + { + m::close(); + } - public function testMakeCallsCreateConnection() - { - $factory = $this->getMock('Database\Connectors\ConnectionFactory', array('createConnector', 'createConnection', 'createQueryGrammar', 'createExceptionHandler')); + public function testMakeCallsCreateConnection() + { + $factory = $this + ->getMockBuilder('Database\Connectors\ConnectionFactory') + ->setMethods(array('createConnector', 'createConnection', 'createQueryGrammar', 'createExceptionHandler')) + ->getMock(); - $config = array('driver' => 'mysql', 'prefix' => 'prefix', 'database' => 'database'); + $config = array('driver' => 'mysql', 'prefix' => 'prefix', 'database' => 'database'); - $pdo = new DatabaseConnectionFactoryPDOStub; + $pdo = new DatabaseConnectionFactoryPDOStub; $connector = m::mock('stdClass'); - $connector->shouldReceive('connect')->once()->with($config)->andReturn($pdo); + $connector->shouldReceive('connect')->once()->with($config)->andReturn($pdo); - $mockGrammar = $this->getMock('Database\Query\Grammars\MysqlGrammar'); - $mockExceptionHandler = $this->getMock('Database\Exception\ExceptionHandlerInterface'); + $mockGrammar = $this->createMock('Database\Query\Grammars\MysqlGrammar'); + $mockExceptionHandler = $this->createMock('Database\Exception\ExceptionHandlerInterface'); - $mockConnection = $this->getMockConnectionWithExpectations($pdo, $mockGrammar); + $mockConnection = $this->getMockConnectionWithExpectations($pdo, $mockGrammar); - $factory->expects($this->once())->method('createConnector')->with($config['driver'])->will($this->returnValue($connector)); - $factory->expects($this->once())->method('createQueryGrammar')->with('mysql')->will($this->returnValue($mockGrammar)); - $factory->expects($this->once())->method('createConnection')->will($this->returnValue($mockConnection)); - $factory->expects($this->once())->method('createExceptionHandler')->with($config)->will($this->returnValue($mockExceptionHandler)); + $factory->expects($this->once())->method('createConnector')->with($config['driver'])->willReturn($connector); + $factory->expects($this->once())->method('createQueryGrammar')->with('mysql')->willReturn($mockGrammar); + $factory->expects($this->once())->method('createConnection')->willReturn($mockConnection); + $factory->expects($this->once())->method('createExceptionHandler')->with($config)->willReturn($mockExceptionHandler); $connection = $factory->make($config); - $this->assertSame($mockConnection, $connection); - } + $this->assertSame($mockConnection, $connection); + } - public function testMakeCallsCreateConnectionForReadWrite() - { - $factory = $this->getMock('Database\Connectors\ConnectionFactory', array('createConnector', 'createConnection', 'createQueryGrammar')); - $connector = m::mock('stdClass'); - $config = array( - 'read' => array('database' => 'database'), - 'write' => array('database' => 'database'), - 'driver' => 'mysql', 'prefix' => 'prefix', 'name' => 'foo' - ); - $expect = $config; - unset($expect['read']); - unset($expect['write']); - $expect['database'] = 'database'; - $pdo = new DatabaseConnectionFactoryPDOStub; - $connector->shouldReceive('connect')->twice()->with($expect)->andReturn($pdo); + public function testMakeCallsCreateConnectionForReadWrite() + { + $factory = $this->getMockBuilder('Database\Connectors\ConnectionFactory') + ->setMethods(array('createConnector', 'createConnection', 'createQueryGrammar')) + ->getMock(); + $connector = m::mock('stdClass'); + $config = array( + 'read' => array('database' => 'database'), + 'write' => array('database' => 'database'), + 'driver' => 'mysql', 'prefix' => 'prefix', 'name' => 'foo' + ); + $expect = $config; + unset($expect['read']); + unset($expect['write']); + $expect['database'] = 'database'; + $pdo = new DatabaseConnectionFactoryPDOStub; + $connector->shouldReceive('connect')->twice()->with($expect)->andReturn($pdo); - $mockGrammar = $this->getMock('Database\Query\Grammars\MysqlGrammar'); + $mockGrammar = $this->createMock('Database\Query\Grammars\MysqlGrammar'); $mockConnection = $this->getMockConnectionWithExpectations($pdo, $mockGrammar); - $factory->expects($this->exactly(2))->method('createConnector')->with($expect['driver'])->will($this->returnValue($connector)); - $factory->expects($this->once())->method('createQueryGrammar')->with('mysql')->will($this->returnValue($mockGrammar)); - $factory->expects($this->once())->method('createConnection')->will($this->returnValue($mockConnection)); - - $connection = $factory->make($config, 'foo'); + $factory->expects($this->exactly(2))->method('createConnector')->with($expect['driver'])->willReturn($connector); + $factory->expects($this->once())->method('createQueryGrammar')->with('mysql')->willReturn($mockGrammar); + $factory->expects($this->once())->method('createConnection')->willReturn($mockConnection); - $this->assertSame($mockConnection, $connection); - } + $connection = $factory->make($config, 'foo'); - private function getMockConnectionWithExpectations($pdo, $grammar) - { - $mockConnection = $this->getMock('Database\Connection', array('setPdo','setReconnector', 'setQueryGrammar', 'setExceptionHandler'), array($pdo)); - $mockConnection->expects($this->once())->method('setReconnector')->will($this->returnSelf()); - $mockConnection->expects($this->once())->method('setQueryGrammar')->with($grammar)->will($this->returnSelf()); - $mockConnection->expects($this->once())->method('setExceptionHandler')->will($this->returnSelf()); - - $mockConnection->expects($this->once())->method('setPdo')->with($pdo)->will($this->returnValue($mockConnection)); + $this->assertSame($mockConnection, $connection); + } - return $mockConnection; - } + private function getMockConnectionWithExpectations($pdo, $grammar) + { + $mockConnection = $this->getMockBuilder('Database\Connection') + ->setConstructorArgs(array($pdo)) + ->getMock(); + //->setMethods(array('setPdo','setReconnector', 'setQueryGrammar', 'setExceptionHandler')); + $mockConnection->expects($this->once())->method('setReconnector')->will($this->returnSelf()); + $mockConnection->expects($this->once())->method('setQueryGrammar')->with($grammar)->will($this->returnSelf()); + $mockConnection->expects($this->once())->method('setExceptionHandler')->will($this->returnSelf()); + $mockConnection->expects($this->once())->method('setTablePrefix')->will($this->returnSelf()); + + $mockConnection->expects($this->once())->method('setPdo')->with($pdo)->willReturn($mockConnection); + + return $mockConnection; + } - public function testProperInstancesAreReturnedForProperDrivers() - { - $factory = new Database\Connectors\ConnectionFactory(); - $this->assertInstanceOf('Database\Connectors\MySqlConnector', $factory->createConnector('mysql')); - $this->assertInstanceOf('Database\Connectors\PostgresConnector', $factory->createConnector('pgsql')); - $this->assertInstanceOf('Database\Connectors\SQLiteConnector', $factory->createConnector('sqlite')); - $this->assertInstanceOf('Database\Connectors\SqlServerConnector', $factory->createConnector('sqlsrv')); - } + public function testProperInstancesAreReturnedForProperDrivers() + { + $factory = new Database\Connectors\ConnectionFactory(); + $this->assertInstanceOf('Database\Connectors\MySqlConnector', $factory->createConnector('mysql')); + $this->assertInstanceOf('Database\Connectors\PostgresConnector', $factory->createConnector('pgsql')); + $this->assertInstanceOf('Database\Connectors\SQLiteConnector', $factory->createConnector('sqlite')); + $this->assertInstanceOf('Database\Connectors\SqlServerConnector', $factory->createConnector('sqlsrv')); + } /** * @dataProvider driversGrammarProvider */ - public function testProperGrammarInstancesAreReturnedForProperDrivers($driver, $instance) - { - $factory = $this->getMock('Database\Connectors\ConnectionFactory', array('createConnector'), array()); + public function testProperGrammarInstancesAreReturnedForProperDrivers($driver, $instance) + { + $factory = $this->getMockBuilder('Database\Connectors\ConnectionFactory') + ->setMethods(array('createConnector')) + ->getMock(); - if(is_null($instance)) - { + if (is_null($instance)) { $this->setExpectedException('InvalidArgumentException'); - } - else - { - $mock = m::mock('stdClass'); - $mock->shouldReceive('connect')->andReturn(m::mock('PDO')); + } else { + $mock = m::mock('stdClass'); + $mock->shouldReceive('connect')->andReturn(m::mock('PDO')); - $factory->expects($this->once())->method('createConnector')->willReturn($mock); - } + $factory->expects($this->once())->method('createConnector')->willReturn($mock); + } $connection = $factory->make(array( 'driver' => $driver )); - if(!is_null($instance)) - { + if (!is_null($instance)) { $this->assertInstanceOf($instance, $connection->getQueryGrammar()); } - } + } public function driversGrammarProvider() { @@ -132,23 +142,22 @@ public function driversGrammarProvider() } - /** - * @expectedException InvalidArgumentException - */ - public function testIfDriverIsntSetExceptionIsThrown() - { - $factory = new Database\Connectors\ConnectionFactory(); - $factory->make(array('foo')); - } - + /** + * @expectedException InvalidArgumentException + */ + public function testIfDriverIsntSetExceptionIsThrown() + { + $factory = new Database\Connectors\ConnectionFactory(); + $factory->make(array('foo')); + } - /** - * @expectedException InvalidArgumentException - */ - public function testExceptionIsThrownOnUnsupportedDriver() - { - $factory = new Database\Connectors\ConnectionFactory(); - $factory->make(array('driver' => 'foo')); - } + /** + * @expectedException InvalidArgumentException + */ + public function testExceptionIsThrownOnUnsupportedDriver() + { + $factory = new Database\Connectors\ConnectionFactory(); + $factory->make(array('driver' => 'foo')); + } } diff --git a/tests/unit/Database/DatabaseConnectionResolverTest.php b/tests/unit/Database/DatabaseConnectionResolverTest.php index e4b72bc..3cdf237 100755 --- a/tests/unit/Database/DatabaseConnectionResolverTest.php +++ b/tests/unit/Database/DatabaseConnectionResolverTest.php @@ -2,21 +2,21 @@ use Mockery as m; -class DatabaseConnectionResolverTest extends PHPUnit_Framework_TestCase { - - public function tearDown() - { - m::close(); - } +class DatabaseConnectionResolverTest extends \PHPUnit\Framework\TestCase +{ + public function tearDown() + { + m::close(); + } - public function testConnectionsCanBeAddedAtConstruction() - { + public function testConnectionsCanBeAddedAtConstruction() + { $configs = array( - 'test1' => array( - 'foo' => 'bar' - ), - ); + 'test1' => array( + 'foo' => 'bar' + ), + ); $factory = m::mock('Database\Connectors\ConnectionFactory'); @@ -24,14 +24,14 @@ public function testConnectionsCanBeAddedAtConstruction() $factory->shouldReceive('make')->once()->with($configs['test1'])->andReturn($connectionMock); - $resolver = $this->getMock('Database\ConnectionResolver', null, array($configs, $factory)); + $resolver = new \Database\ConnectionResolver($configs, $factory); - $this->assertTrue($resolver->hasConnection('test1')); + $this->assertTrue($resolver->hasConnection('test1')); $connection = $resolver->connection('test1'); $this->assertSame($connectionMock, $connection); - } + } public function testItReturnsADefaultConnection() { @@ -47,7 +47,7 @@ public function testItReturnsADefaultConnection() $factory->shouldReceive('make')->once()->with($configs['test'])->andReturn($connectionMock); - $resolver = $this->getMock('Database\ConnectionResolver', null, array($configs, $factory)); + $resolver = new \Database\ConnectionResolver($configs, $factory); $resolver->setDefaultConnection('test'); diff --git a/tests/unit/Database/DatabaseConnectionTest.php b/tests/unit/Database/DatabaseConnectionTest.php index 833c1d6..2c7e44b 100755 --- a/tests/unit/Database/DatabaseConnectionTest.php +++ b/tests/unit/Database/DatabaseConnectionTest.php @@ -2,130 +2,130 @@ use Mockery as m; -class DatabaseConnectionTest extends PHPUnit_Framework_TestCase { - - public function tearDown() - { - m::close(); - } - - - public function testFetchOneCallsSelectAndReturnsSingleResult() - { - $connection = $this->getMockConnection(array('run')); - - $statement = $this->getMock('PDOStatement', array('fetchColumn')); - $connection->expects($this->once())->method('run')->with('foo', array('bar' => 'baz'))->will($this->returnValue($statement)); - $statement->expects($this->once())->method('fetchColumn')->will($this->returnValue('boom')); - - $result = $connection->fetchOne('foo', array('bar' => 'baz')); - $this->assertEquals('boom', $result); - } - - - public function testFetchProperlyCallsPDO() - { - $pdo = $this->getMock('DatabaseConnectionTestMockPDO', array('prepare')); - $writePdo = $this->getMock('DatabaseConnectionTestMockPDO', array('prepare', 'inTransaction')); - $writePdo->expects($this->never())->method('prepare'); - $writePdo->expects($this->exactly(2))->method('inTransaction')->willReturn(false); - $statement = $this->getMock('PDOStatement', array('execute', 'fetch')); - $statement->expects($this->once())->method('execute')->with($this->equalTo(array('foo' => 'bar'))); - $statement->expects($this->once())->method('fetch')->will($this->returnValue(array('boom'))); - $pdo->expects($this->once())->method('prepare')->with('foo')->will($this->returnValue($statement)); - $mock = $this->getMockConnection(array('prepareBindings', 'query'), $writePdo); - $mock->setReadPdo($pdo); - $mock->setPdo($writePdo); - $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(array('foo' => 'bar')))->will($this->returnValue(array('foo' => 'bar'))); - $results = $mock->fetch('foo', array('foo' => 'bar')); - $this->assertEquals(array('boom'), $results); - } - - public function testQueryCallsTheRunMethod() - { - $connection = $this->getMockConnection(array('run')); - $connection->expects($this->once())->method('run')->with($this->equalTo('foo'), $this->equalTo(array('bar')))->will($this->returnValue('baz')); - $results = $connection->query('foo', array('bar')); - $this->assertEquals('baz', $results); - } - - public function testQueryProperlyCallsPDO() - { - $pdo = $this->getMock('DatabaseConnectionTestMockPDO', array('prepare')); - $statement = $this->getMock('PDOStatement', array('execute')); - $statement->expects($this->once())->method('execute')->with($this->equalTo(array('bar')))->will($this->returnValue('foo')); - $pdo->expects($this->once())->method('prepare')->with($this->equalTo('foo'))->will($this->returnValue($statement)); - $mock = $this->getMockConnection(array('prepareBindings'), $pdo); - $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(array('bar')))->will($this->returnValue(array('bar'))); - $results = $mock->query('foo', array('bar')); - $this->assertInstanceOf('PDOStatement', $results); - } - - - public function testTransactionMethodRunsSuccessfully() - { - $pdo = $this->getMock('DatabaseConnectionTestMockPDO', array('beginTransaction', 'commit')); - $mock = $this->getMockConnection(array(), $pdo); - $pdo->expects($this->once())->method('beginTransaction'); - $pdo->expects($this->once())->method('commit'); - $result = $mock->transaction(function($db) { return $db; }); - $this->assertEquals($mock, $result); - } - - - public function testTransactionMethodRollsbackAndThrows() - { - $pdo = $this->getMock('DatabaseConnectionTestMockPDO', array('beginTransaction', 'commit', 'rollBack')); - $mock = $this->getMockConnection(array(), $pdo); - $pdo->expects($this->once())->method('beginTransaction'); - $pdo->expects($this->once())->method('rollBack'); - $pdo->expects($this->never())->method('commit'); - try - { - $mock->transaction(function() { throw new Exception('foo'); }); - } - catch (Exception $e) - { - $this->assertEquals('foo', $e->getMessage()); - } - } - - - public function testFromCreatesNewQueryBuilder() - { - $conn = $this->getMockConnection(); - $builder = $conn->table('users'); - $this->assertInstanceOf('Database\Query\Builder', $builder); - $this->assertEquals('users', $builder->from); - } - - - public function testPrepareBindings() - { - $date = m::mock('DateTime'); - $date->shouldReceive('format')->once()->with('foo')->andReturn('bar'); - $bindings = array('test' => $date); - $conn = $this->getMockConnection(); - $grammar = m::mock('Database\Query\Grammars\Grammar'); - $grammar->shouldReceive('getDateFormat')->once()->andReturn('foo'); - $conn->setQueryGrammar($grammar); - $result = $conn->prepareBindings($bindings); - $this->assertEquals(array('test' => 'bar'), $result); - } - - - public function testPretendOnlyLogsQueries() - { - $connection = $this->getMockConnection(); +class DatabaseConnectionTest extends \PHPUnit\Framework\TestCase +{ + public function tearDown() + { + m::close(); + } + + + public function testFetchOneCallsSelectAndReturnsSingleResult() + { + $connection = $this->getMockConnection(array('run')); + + $statement = $this->createMock('PDOStatement', array('fetchColumn')); + $connection->expects($this->once())->method('run')->with('foo', array('bar' => 'baz'))->will($this->returnValue($statement)); + $statement->expects($this->once())->method('fetchColumn')->will($this->returnValue('boom')); + + $result = $connection->fetchOne('foo', array('bar' => 'baz')); + $this->assertEquals('boom', $result); + } + + + public function testFetchProperlyCallsPDO() + { + $pdo = $this->getMockBuilder('DatabaseConnectionTestMockPDO')->setMethods(array('prepare'))->getMock(); + $writePdo = $this->getMockBuilder('DatabaseConnectionTestMockPDO')->setMethods(array('prepare', 'inTransaction'))->getMock(); + $writePdo->expects($this->never())->method('prepare'); + $writePdo->expects($this->exactly(2))->method('inTransaction')->willReturn(false); + $statement = $this->getMockBuilder('PDOStatement')->setMethods(array('execute', 'fetch'))->getMock(); + $statement->expects($this->once())->method('execute')->with($this->equalTo(array('foo' => 'bar'))); + $statement->expects($this->once())->method('fetch')->will($this->returnValue(array('boom'))); + $pdo->expects($this->once())->method('prepare')->with('foo')->will($this->returnValue($statement)); + $mock = $this->getMockConnection(array('prepareBindings', 'query'), $writePdo); + $mock->setReadPdo($pdo); + $mock->setPdo($writePdo); + $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(array('foo' => 'bar')))->will($this->returnValue(array('foo' => 'bar'))); + $results = $mock->fetch('foo', array('foo' => 'bar')); + $this->assertEquals(array('boom'), $results); + } + + public function testQueryCallsTheRunMethod() + { + $connection = $this->getMockConnection(array('run')); + $connection->expects($this->once())->method('run')->with($this->equalTo('foo'), $this->equalTo(array('bar')))->will($this->returnValue('baz')); + $results = $connection->query('foo', array('bar')); + $this->assertEquals('baz', $results); + } + + public function testQueryProperlyCallsPDO() + { + $pdo = $this->createMock('DatabaseConnectionTestMockPDO'); + $statement = $this->createMock('PDOStatement'); + $statement->expects($this->once())->method('execute')->with($this->equalTo(array('bar')))->will($this->returnValue('foo')); + $pdo->expects($this->once())->method('prepare')->with($this->equalTo('foo'))->will($this->returnValue($statement)); + $mock = $this->getMockConnection(array('prepareBindings'), $pdo); + $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(array('bar')))->will($this->returnValue(array('bar'))); + $results = $mock->query('foo', array('bar')); + $this->assertInstanceOf('PDOStatement', $results); + } + + + public function testTransactionMethodRunsSuccessfully() + { + $pdo = $this->getMockBuilder('DatabaseConnectionTestMockPDO')->setMethods(array('beginTransaction', 'commit'))->getMock(); + $connection = new \Database\Connection($pdo); + $pdo->expects($this->once())->method('beginTransaction'); + $pdo->expects($this->once())->method('commit'); + $result = $connection->transaction(function ($db) { + return $db; + }); + $this->assertEquals($connection, $result); + } + + + public function testTransactionMethodRollsbackAndThrows() + { + $pdo = $this->getMockBuilder('DatabaseConnectionTestMockPDO')->setMethods(array('beginTransaction', 'commit', 'rollBack'))->getMock(); + $connection = new \Database\Connection($pdo); + $pdo->expects($this->once())->method('beginTransaction'); + $pdo->expects($this->once())->method('rollBack'); + $pdo->expects($this->never())->method('commit'); + try { + $connection->transaction(function () { + throw new Exception('foo'); + }); + } catch (Exception $e) { + $this->assertEquals('foo', $e->getMessage()); + } + } + + + public function testFromCreatesNewQueryBuilder() + { + $conn = new \Database\Connection(new DatabaseConnectionTestMockPDO); + $builder = $conn->table('users'); + $this->assertInstanceOf('Database\Query\Builder', $builder); + $this->assertEquals('users', $builder->from); + } + + + public function testPrepareBindings() + { + $date = m::mock('DateTime'); + $date->shouldReceive('format')->once()->with('foo')->andReturn('bar'); + $bindings = array('test' => $date); + $conn = new \Database\Connection(new DatabaseConnectionTestMockPDO); + $grammar = m::mock('Database\Query\Grammars\Grammar'); + $grammar->shouldReceive('getDateFormat')->once()->andReturn('foo'); + $conn->setQueryGrammar($grammar); + $result = $conn->prepareBindings($bindings); + $this->assertEquals(array('test' => 'bar'), $result); + } + + + public function testPretendOnlyLogsQueries() + { + $connection = $this->getMockConnection(); $connection->expects($this->never())->method('getReadPdo'); $connection->expects($this->never())->method('getPdo'); - $connection->pretend(function($connection) - { - $connection->fetchAll('foo bar', array('baz')); - }); - } + $connection->pretend(function ($connection) { + $connection->fetchAll('foo bar', array('baz')); + }); + } public function testItProxiesInsertToBuilder() { @@ -190,7 +190,7 @@ public function testItProxiesInsertUpdateToBuilder() ->with('testTable') ->willReturn($mock); - $this->assertEquals('baz',$connection->insertUpdate('testTable', array('foo'), array('bar'))); + $this->assertEquals('baz', $connection->insertUpdate('testTable', array('foo'), array('bar'))); } private function doInsertTypeProxyCallsToBuilder($type) @@ -205,15 +205,16 @@ private function doInsertTypeProxyCallsToBuilder($type) ->with('testTable') ->willReturn($mock); - $this->assertEquals('baz',$connection->{$type}('testTable', array('foo'))); + $this->assertEquals('baz', $connection->{$type}('testTable', array('foo'))); } public function testQuoteInto() { - $connection = $this->getMockConnection(array('quote')); + $pdo = $this->createMock('DatabaseConnectionTestMockPDO', array('quote')); + $connection = new \Database\Connection($pdo); - $connection->expects($this->at(0))->method('quote')->with('foo')->willReturn('`foo`'); - $connection->expects($this->at(1))->method('quote')->with('bar')->willReturn('`bar`'); + $pdo->expects($this->at(0))->method('quote')->with('foo')->willReturn('`foo`'); + $pdo->expects($this->at(1))->method('quote')->with('bar')->willReturn('`bar`'); $string = $connection->quoteInto('col1 = ? AND col2 = ?', array('foo', 'bar')); @@ -222,8 +223,8 @@ public function testQuoteInto() public function testQuote() { - $pdo = $this->getMock('DatabaseConnectionTestMockPDO', array('quote')); - $connection = $this->getMockConnection(array(), $pdo); + $pdo = $this->createMock('DatabaseConnectionTestMockPDO', array('quote')); + $connection = new \Database\Connection($pdo); $pdo->expects($this->once())->method('quote')->with('foo')->willReturn('`foo`'); @@ -234,8 +235,8 @@ public function testQuote() public function testQuoteArray() { - $pdo = $this->getMock('DatabaseConnectionTestMockPDO', array('quote')); - $connection = $this->getMockConnection(array(), $pdo); + $pdo = $this->createMock('DatabaseConnectionTestMockPDO', array('quote')); + $connection = new \Database\Connection($pdo); $pdo->expects($this->at(0))->method('quote')->with('foo')->willReturn('`foo`'); $pdo->expects($this->at(1))->method('quote')->with('bar')->willReturn('`bar`'); @@ -247,7 +248,7 @@ public function testQuoteArray() public function testSetAndGetPrefix() { - $connection = $this->getMockConnection(array()); + $connection = new \Database\Connection(new DatabaseConnectionTestMockPDO); $connection->setTablePrefix('foo'); $this->assertEquals('foo', $connection->getTablePrefix()); @@ -258,7 +259,7 @@ public function testSetAndGetPrefix() public function testItCorrectlyEnablesAndDisablesLogging() { - $connection = $this->getMockConnection(array()); + $connection = new \Database\Connection(new DatabaseConnectionTestMockPDO); $connection->enableQueryLog(); $this->assertEquals(true, $connection->logging()); @@ -269,7 +270,7 @@ public function testItCorrectlyEnablesAndDisablesLogging() public function testItCorrectlySetsTheFetchMode() { - $connection = $this->getMockConnection(array()); + $connection = new \Database\Connection(new DatabaseConnectionTestMockPDO); $connection->setFetchMode(10); $this->assertEquals(10, $connection->getFetchMode()); @@ -283,11 +284,22 @@ public function testItCorrectlySetsTheFetchMode() * @param null $pdo * @return Database\Connection */ - protected function getMockConnection($methods = array(), $pdo = null) - { - $pdo = $pdo ?: new DatabaseConnectionTestMockPDO; - return $this->getMock('Database\Connection', $methods ?: null, array($pdo)); - } + protected function getMockConnection($methods = array(), $pdo = null) + { + $pdo = $pdo ?: new DatabaseConnectionTestMockPDO; + $builder = $this->getMockBuilder('Database\Connection')->setConstructorArgs(array($pdo)); + + if ($methods) { + $builder->setMethods($methods); + } + + return $builder->getMock(); + } } -class DatabaseConnectionTestMockPDO extends PDO { public function __construct() {} } +class DatabaseConnectionTestMockPDO extends PDO +{ + public function __construct() + { + } +} diff --git a/tests/unit/Database/DatabaseConnectorTest.php b/tests/unit/Database/DatabaseConnectorTest.php index 8f561d3..b527a99 100755 --- a/tests/unit/Database/DatabaseConnectorTest.php +++ b/tests/unit/Database/DatabaseConnectorTest.php @@ -2,147 +2,145 @@ use Mockery as m; -class DatabaseConnectorTest extends PHPUnit_Framework_TestCase { - - public function tearDown() - { - m::close(); - } - - - public function testOptionResolution() - { - $connector = new Database\Connectors\Connector; - $connector->setDefaultOptions(array(0 => 'foo', 1 => 'bar')); - $this->assertEquals(array(0 => 'baz', 1 => 'bar', 2 => 'boom'), $connector->getOptions(array('options' => array(0 => 'baz', 2 => 'boom')))); - } - - - /** - * @dataProvider mySqlConnectProvider - */ - public function testMySqlConnectCallsCreateConnectionWithProperArguments($dsn, $config) - { - $connector = $this->getMock('Database\Connectors\MySqlConnector', array('createConnection', 'getOptions')); - $connection = m::mock('stdClass'); - $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); - $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); - $connection->shouldReceive('prepare')->once()->with('set names \'utf8\' collate \'utf8_unicode_ci\'')->andReturn($connection); - $connection->shouldReceive('execute')->once(); - $connection->shouldReceive('exec')->zeroOrMoreTimes(); - $result = $connector->connect($config); - - $this->assertSame($result, $connection); - } - - - public function mySqlConnectProvider() - { - return array( - array('mysql:host=foo;dbname=bar', array('host' => 'foo', 'database' => 'bar', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8')), - array('mysql:host=foo;port=111;dbname=bar', array('host' => 'foo', 'database' => 'bar', 'port' => 111, 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8')), - array('mysql:unix_socket=baz;dbname=bar', array('host' => 'foo', 'database' => 'bar', 'port' => 111, 'unix_socket' => 'baz', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8')), - ); - } - - - public function testPostgresConnectCallsCreateConnectionWithProperArguments() - { - $dsn = 'pgsql:host=foo;dbname=bar;port=111'; - $config = array('host' => 'foo', 'database' => 'bar', 'port' => 111, 'charset' => 'utf8'); - $connector = $this->getMock('Database\Connectors\PostgresConnector', array('createConnection', 'getOptions')); - $connection = m::mock('stdClass'); - $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); - $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); - $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection); - $connection->shouldReceive('execute')->once(); - $result = $connector->connect($config); - - $this->assertSame($result, $connection); - } - - - public function testPostgresSearchPathIsSet() - { - $dsn = 'pgsql:host=foo;dbname=bar'; - $config = array('host' => 'foo', 'database' => 'bar', 'schema' => 'public', 'charset' => 'utf8'); - $connector = $this->getMock('Database\Connectors\PostgresConnector', array('createConnection', 'getOptions')); - $connection = m::mock('stdClass'); - $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); - $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); - $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection); - $connection->shouldReceive('prepare')->once()->with("set search_path to public")->andReturn($connection); - $connection->shouldReceive('execute')->twice(); - $result = $connector->connect($config); - - $this->assertSame($result, $connection); - } - - - public function testSQLiteMemoryDatabasesMayBeConnectedTo() - { - $dsn = 'sqlite::memory:'; - $config = array('database' => ':memory:'); - $connector = $this->getMock('Database\Connectors\SQLiteConnector', array('createConnection', 'getOptions')); - $connection = m::mock('stdClass'); - $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); - $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); - $result = $connector->connect($config); - - $this->assertSame($result, $connection); - } - - - public function testSQLiteFileDatabasesMayBeConnectedTo() - { - $dsn = 'sqlite:'.__DIR__; - $config = array('database' => __DIR__); - $connector = $this->getMock('Database\Connectors\SQLiteConnector', array('createConnection', 'getOptions')); - $connection = m::mock('stdClass'); - $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); - $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); - $result = $connector->connect($config); - - $this->assertSame($result, $connection); - } - - - public function testSqlServerConnectCallsCreateConnectionWithProperArguments() - { - $config = array('host' => 'foo', 'database' => 'bar', 'port' => 111); - $dsn = $this->getDsn($config); - $connector = $this->getMock('Database\Connectors\SqlServerConnector', array('createConnection', 'getOptions')); - $connection = m::mock('stdClass'); - $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); - $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); - $result = $connector->connect($config); - - $this->assertSame($result, $connection); - } - - public function testItThrowsExceptionOnFailedConnection() - { - $this->setExpectedException('Database\Exception\ConnectionException', "Connection to 'dsn' failed: invalid data source name"); - - $connector = new \Database\Connectors\MySqlConnector(); - - $connector->createConnection("dsn", array(), array()); - } - - protected function getDsn(array $config) - { - extract($config); - - $port = isset($config['port']) ? ','.$port : ''; - - if (in_array('dblib', PDO::getAvailableDrivers())) - { - return "dblib:host={$host}{$port};dbname={$database}"; - } - else - { - return "sqlsrv:Server={$host}{$port};Database={$database}"; - } - } - +class DatabaseConnectorTest extends \PHPUnit\Framework\TestCase +{ + public function tearDown() + { + m::close(); + } + + + public function testOptionResolution() + { + $connector = new Database\Connectors\Connector; + $connector->setDefaultOptions(array(0 => 'foo', 1 => 'bar')); + $this->assertEquals(array(0 => 'baz', 1 => 'bar', 2 => 'boom'), $connector->getOptions(array('options' => array(0 => 'baz', 2 => 'boom')))); + } + + + /** + * @dataProvider mySqlConnectProvider + */ + public function testMySqlConnectCallsCreateConnectionWithProperArguments($dsn, $config) + { + $connector = $this->getMockBuilder('Database\Connectors\MySqlConnector')->setMethods(array('createConnection', 'getOptions'))->getMock(); + $connection = m::mock('stdClass'); + $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); + $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); + $connection->shouldReceive('prepare')->once()->with('set names \'utf8\' collate \'utf8_unicode_ci\'')->andReturn($connection); + $connection->shouldReceive('execute')->once(); + $connection->shouldReceive('exec')->zeroOrMoreTimes(); + $result = $connector->connect($config); + + $this->assertSame($result, $connection); + } + + + public function mySqlConnectProvider() + { + return array( + array('mysql:host=foo;dbname=bar', array('host' => 'foo', 'database' => 'bar', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8')), + array('mysql:host=foo;port=111;dbname=bar', array('host' => 'foo', 'database' => 'bar', 'port' => 111, 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8')), + array('mysql:unix_socket=baz;dbname=bar', array('host' => 'foo', 'database' => 'bar', 'port' => 111, 'unix_socket' => 'baz', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8')), + ); + } + + + public function testPostgresConnectCallsCreateConnectionWithProperArguments() + { + $dsn = 'pgsql:host=foo;dbname=bar;port=111'; + $config = array('host' => 'foo', 'database' => 'bar', 'port' => 111, 'charset' => 'utf8'); + $connector = $this->getMockBuilder('Database\Connectors\PostgresConnector')->setMethods(array('createConnection', 'getOptions'))->getMock(); + $connection = m::mock('stdClass'); + $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); + $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); + $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection); + $connection->shouldReceive('execute')->once(); + $result = $connector->connect($config); + + $this->assertSame($result, $connection); + } + + + public function testPostgresSearchPathIsSet() + { + $dsn = 'pgsql:host=foo;dbname=bar'; + $config = array('host' => 'foo', 'database' => 'bar', 'schema' => 'public', 'charset' => 'utf8'); + $connector = $this->getMockBuilder('Database\Connectors\PostgresConnector')->setMethods(array('createConnection', 'getOptions'))->getMock(); + $connection = m::mock('stdClass'); + $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); + $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); + $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection); + $connection->shouldReceive('prepare')->once()->with("set search_path to public")->andReturn($connection); + $connection->shouldReceive('execute')->twice(); + $result = $connector->connect($config); + + $this->assertSame($result, $connection); + } + + + public function testSQLiteMemoryDatabasesMayBeConnectedTo() + { + $dsn = 'sqlite::memory:'; + $config = array('database' => ':memory:'); + $connector = $this->getMockBuilder('Database\Connectors\SQLiteConnector')->setMethods(array('createConnection', 'getOptions'))->getMock(); + $connection = m::mock('stdClass'); + $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); + $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); + $result = $connector->connect($config); + + $this->assertSame($result, $connection); + } + + + public function testSQLiteFileDatabasesMayBeConnectedTo() + { + $dsn = 'sqlite:'.__DIR__; + $config = array('database' => __DIR__); + $connector = $this->getMockBuilder('Database\Connectors\SQLiteConnector')->setMethods(array('createConnection', 'getOptions'))->getMock(); + $connection = m::mock('stdClass'); + $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); + $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); + $result = $connector->connect($config); + + $this->assertSame($result, $connection); + } + + + public function testSqlServerConnectCallsCreateConnectionWithProperArguments() + { + $config = array('host' => 'foo', 'database' => 'bar', 'port' => 111); + $dsn = $this->getDsn($config); + $connector = $this->getMockBuilder('Database\Connectors\SqlServerConnector')->setMethods(array('createConnection', 'getOptions'))->getMock(); + + $connection = m::mock('stdClass'); + $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(array('options'))); + $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(array('options')))->will($this->returnValue($connection)); + $result = $connector->connect($config); + + $this->assertSame($result, $connection); + } + + public function testItThrowsExceptionOnFailedConnection() + { + $this->expectException('Database\Exception\ConnectionException'); + $this->expectExceptionMessage("Connection to 'dsn' failed: invalid data source name"); + + $connector = new \Database\Connectors\MySqlConnector(); + + $connector->createConnection("dsn", array(), array()); + } + + protected function getDsn(array $config) + { + extract($config); + + $port = isset($config['port']) ? ','.$port : ''; + + if (in_array('dblib', PDO::getAvailableDrivers())) { + return "dblib:host={$host}{$port};dbname={$database}"; + } else { + return "sqlsrv:Server={$host}{$port};Database={$database}"; + } + } } diff --git a/tests/unit/Database/DatabaseJoinMemoryLeakTest.php b/tests/unit/Database/DatabaseJoinMemoryLeakTest.php index ce51da4..c8739e3 100755 --- a/tests/unit/Database/DatabaseJoinMemoryLeakTest.php +++ b/tests/unit/Database/DatabaseJoinMemoryLeakTest.php @@ -3,8 +3,8 @@ use Mockery as m; use Database\Query\Builder; -class DatabaseJoinMemoryLeakTest extends PHPUnit_Framework_TestCase { - +class DatabaseJoinMemoryLeakTest extends \PHPUnit\Framework\TestCase +{ public function tearDown() { m::close(); @@ -14,10 +14,9 @@ public function testItDoesNotLeakMemoryOnNewQuery() { $builderMain = $this->getBuilder(); - $this->runMemoryTest(function() use($builderMain){ + $this->runMemoryTest(function () use ($builderMain) { $builder = $builderMain->newQuery(); $builder->select('*')->from('users'); - }); } @@ -25,10 +24,9 @@ public function testItDoesNotLeakMemoryOnNewQueryWithJoin() { $builderMain = $this->getBuilder(); - $this->runMemoryTest(function() use($builderMain){ + $this->runMemoryTest(function () use ($builderMain) { $builder = $builderMain->newQuery(); $builder->select('*')->join('new', 'col', '=', 'col2')->from('users'); - }); } @@ -38,8 +36,7 @@ protected function runMemoryTest(\Closure $callback) $last = null; - while($i--) - { + while ($i--) { $callback(); $prev = $last; @@ -55,6 +52,4 @@ protected function getBuilder() $grammar = new Database\Query\Grammars\Grammar; return new Builder(m::mock('Database\ConnectionInterface'), $grammar); } - - } diff --git a/tests/unit/Database/DatabaseQueryBuilderTest.php b/tests/unit/Database/DatabaseQueryBuilderTest.php index 5a5c2fc..0eb164e 100755 --- a/tests/unit/Database/DatabaseQueryBuilderTest.php +++ b/tests/unit/Database/DatabaseQueryBuilderTest.php @@ -4,743 +4,730 @@ use Database\Query\Builder; use Database\Query\Expression as Raw; -class DatabaseQueryBuilderTest extends PHPUnit_Framework_TestCase { +class DatabaseQueryBuilderTest extends \PHPUnit\Framework\TestCase +{ + public function tearDown() + { + m::close(); + } + + + public function testBasicSelect() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users'); + $this->assertEquals('select * from "users"', $builder->toSql()); + } + + + public function testBasicTableWrappingProtectsQuotationMarks() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('some"table'); + $this->assertEquals('select * from "some""table"', $builder->toSql()); + } + + + public function testAddingSelects() + { + $builder = $this->getBuilder(); + $builder->select('foo')->addSelect('bar')->addSelect(array('baz', 'boom'))->from('users'); + $this->assertEquals('select "foo", "bar", "baz", "boom" from "users"', $builder->toSql()); + } + + + public function testBasicSelectWithPrefix() + { + $builder = $this->getBuilder(); + $builder->getGrammar()->setTablePrefix('prefix_'); + $builder->select('*')->from('users'); + $this->assertEquals('select * from "prefix_users"', $builder->toSql()); + } + + + public function testBasicSelectDistinct() + { + $builder = $this->getBuilder(); + $builder->distinct()->select('foo', 'bar')->from('users'); + $this->assertEquals('select distinct "foo", "bar" from "users"', $builder->toSql()); + } + + public function testSubSelectRawString() + { + $builder = $this->getBuilder(); + $builder->selectSub('select * from test', 'tmp')->from('users'); + $this->assertEquals('select (select * from test) as "tmp" from "users"', $builder->toSql()); + } + + public function testSubSelectClosure() + { + $builder = $this->getBuilder(); + + $builder->selectSub(function ($build) { + $build->select('foo')->where('bar', '=', 'baz')->from('test'); + }, 'tmp')->from('users'); + + $this->assertEquals('select (select "foo" from "test" where "bar" = ?) as "tmp" from "users"', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testSubSelectThrowsInvalidArgument() + { + $builder = $this->getBuilder(); + + $builder->selectSub(array('test'), 'tmp')->from('users'); + } + + public function testBasicAlias() + { + $builder = $this->getBuilder(); + $builder->select('foo as bar')->from('users'); + $this->assertEquals('select "foo" as "bar" from "users"', $builder->toSql()); + } + + + public function testBasicTableWrapping() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('public.users'); + $this->assertEquals('select * from "public"."users"', $builder->toSql()); + } + + + public function testBasicWheres() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1); + $this->assertEquals('select * from "users" where "id" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + public function testArrayWheres() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where(array('id' => 1, 'name' => 2)); + $this->assertEquals('select * from "users" where ("id" = ? and "name" = ?)', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + } + + public function testMySqlWrappingProtectsQuotationMarks() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->From('some`table'); + $this->assertEquals('select * from `some``table`', $builder->toSql()); + } + - public function tearDown() - { - m::close(); - } + public function testWhereDayMySql() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->whereDay('created_at', '=', 1); + $this->assertEquals('select * from `users` where day(`created_at`) = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + + public function testWhereMonthMySql() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); + $this->assertEquals('select * from `users` where month(`created_at`) = ?', $builder->toSql()); + $this->assertEquals(array(0 => 5), $builder->getBindings()); + } + + + public function testWhereYearMySql() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); + $this->assertEquals('select * from `users` where year(`created_at`) = ?', $builder->toSql()); + $this->assertEquals(array(0 => 2014), $builder->getBindings()); + } + + + public function testWhereDayPostgres() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('users')->whereDay('created_at', '=', 1); + $this->assertEquals('select * from "users" where day("created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + + public function testWhereMonthPostgres() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); + $this->assertEquals('select * from "users" where month("created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 5), $builder->getBindings()); + } - public function testBasicSelect() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users'); - $this->assertEquals('select * from "users"', $builder->toSql()); - } + public function testWhereYearPostgres() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); + $this->assertEquals('select * from "users" where year("created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 2014), $builder->getBindings()); + } + + + public function testWhereDaySqlite() + { + $builder = $this->getSQLiteBuilder(); + $builder->select('*')->from('users')->whereDay('created_at', '=', 1); + $this->assertEquals('select * from "users" where strftime(\'%d\', "created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + + public function testWhereMonthSqlite() + { + $builder = $this->getSQLiteBuilder(); + $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); + $this->assertEquals('select * from "users" where strftime(\'%m\', "created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 5), $builder->getBindings()); + } + + + public function testWhereYearSqlite() + { + $builder = $this->getSQLiteBuilder(); + $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); + $this->assertEquals('select * from "users" where strftime(\'%Y\', "created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 2014), $builder->getBindings()); + } + + + public function testWhereDaySqlServer() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('users')->whereDay('created_at', '=', 1); + $this->assertEquals('select * from "users" where day("created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + + public function testWhereMonthSqlServer() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); + $this->assertEquals('select * from "users" where month("created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 5), $builder->getBindings()); + } + + + public function testWhereYearSqlServer() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); + $this->assertEquals('select * from "users" where year("created_at") = ?', $builder->toSql()); + $this->assertEquals(array(0 => 2014), $builder->getBindings()); + } + + + public function testWhereBetweens() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereBetween('id', array(1, 2)); + $this->assertEquals('select * from "users" where "id" between ? and ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereNotBetween('id', array(1, 2)); + $this->assertEquals('select * from "users" where "id" not between ? and ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + } + + + public function testBasicOrWheres() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1)->orWhere('email', '=', 'foo'); + $this->assertEquals('select * from "users" where "id" = ? or "email" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); + } + + + public function testRawWheres() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereRaw('id = ? or email = ?', array(1, 'foo')); + $this->assertEquals('select * from "users" where id = ? or email = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); + } + + + public function testRawOrWheres() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1)->orWhereRaw('email = ?', array('foo')); + $this->assertEquals('select * from "users" where "id" = ? or email = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); + } + + + public function testBasicWhereIns() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereIn('id', array(1, 2, 3)); + $this->assertEquals('select * from "users" where "id" in (?, ?, ?)', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1)->orWhereIn('id', array(1, 2, 3)); + $this->assertEquals('select * from "users" where "id" = ? or "id" in (?, ?, ?)', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 1, 2 => 2, 3 => 3), $builder->getBindings()); + } - public function testBasicTableWrappingProtectsQuotationMarks() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('some"table'); - $this->assertEquals('select * from "some""table"', $builder->toSql()); - } + public function testBasicWhereNotIns() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereNotIn('id', array(1, 2, 3)); + $this->assertEquals('select * from "users" where "id" not in (?, ?, ?)', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNotIn('id', array(1, 2, 3)); + $this->assertEquals('select * from "users" where "id" = ? or "id" not in (?, ?, ?)', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 1, 2 => 2, 3 => 3), $builder->getBindings()); + } + + + public function testUnions() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1); + $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); + $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1); + $builder->union($this->getMySqlBuilder()->select('*')->from('users')->where('id', '=', 2)); + $this->assertEquals('(select * from `users` where `id` = ?) union (select * from `users` where `id` = ?)', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + } + + + public function testUnionAlls() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1); + $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); + $this->assertEquals('select * from "users" where "id" = ? union all select * from "users" where "id" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + } + + + public function testMultipleUnions() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1); + $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); + $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 3)); + $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ? union select * from "users" where "id" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); + } + + + public function testMultipleUnionAlls() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1); + $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); + $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 3)); + $this->assertEquals('select * from "users" where "id" = ? union all select * from "users" where "id" = ? union all select * from "users" where "id" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); + } + + + public function testSubSelectWhereIns() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereIn('id', function ($q) { + $q->select('id')->from('users')->where('age', '>', 25)->limit(3); + }); + $this->assertEquals('select * from "users" where "id" in (select "id" from "users" where "age" > ? limit 3)', $builder->toSql()); + $this->assertEquals(array(25), $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereNotIn('id', function ($q) { + $q->select('id')->from('users')->where('age', '>', 25)->limit(3); + }); + $this->assertEquals('select * from "users" where "id" not in (select "id" from "users" where "age" > ? limit 3)', $builder->toSql()); + $this->assertEquals(array(25), $builder->getBindings()); + } + + + public function testBasicWhereNulls() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereNull('id'); + $this->assertEquals('select * from "users" where "id" is null', $builder->toSql()); + $this->assertEquals(array(), $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNull('id'); + $this->assertEquals('select * from "users" where "id" = ? or "id" is null', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + + public function testBasicWhereNotNulls() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereNotNull('id'); + $this->assertEquals('select * from "users" where "id" is not null', $builder->toSql()); + $this->assertEquals(array(), $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', '>', 1)->orWhereNotNull('id'); + $this->assertEquals('select * from "users" where "id" > ? or "id" is not null', $builder->toSql()); + $this->assertEquals(array(0 => 1), $builder->getBindings()); + } + + + public function testGroupBys() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->groupBy('id', 'email'); + $this->assertEquals('select * from "users" group by "id", "email"', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->groupBy(['id', 'email']); + $this->assertEquals('select * from "users" group by "id", "email"', $builder->toSql()); + } + + + public function testOrderBys() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->orderBy('email')->orderBy('age', 'desc'); + $this->assertEquals('select * from "users" order by "email" asc, "age" desc', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->orderBy('email')->orderByRaw('"age" ? desc', array('foo')); + $this->assertEquals('select * from "users" order by "email" asc, "age" ? desc', $builder->toSql()); + $this->assertEquals(array('foo'), $builder->getBindings()); + } + + + public function testHavings() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->having('email', '>', 1); + $this->assertEquals('select * from "users" having "email" > ?', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->groupBy('email')->having('email', '>', 1); + $this->assertEquals('select * from "users" group by "email" having "email" > ?', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('email as foo_email')->from('users')->having('foo_email', '>', 1); + $this->assertEquals('select "email" as "foo_email" from "users" having "foo_email" > ?', $builder->toSql()); + } + + + public function testRawHavings() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->havingRaw('user_foo < user_bar'); + $this->assertEquals('select * from "users" having user_foo < user_bar', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->having('baz', '=', 1)->orHavingRaw('user_foo < user_bar'); + $this->assertEquals('select * from "users" having "baz" = ? or user_foo < user_bar', $builder->toSql()); + } + + + public function testLimitsAndOffsets() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->offset(5)->limit(10); + $this->assertEquals('select * from "users" limit 10 offset 5', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->offset(5)->limit(10); + $this->assertEquals('select * from "users" limit 10 offset 5', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->offset(-5)->limit(10); + $this->assertEquals('select * from "users" limit 10 offset 0', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->forPage(2, 15); + $this->assertEquals('select * from "users" limit 15 offset 15', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->forPage(-2, 15); + $this->assertEquals('select * from "users" limit 15 offset 0', $builder->toSql()); + } + + + public function testWhereShortcut() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('id', 1)->orWhere('name', 'foo'); + $this->assertEquals('select * from "users" where "id" = ? or "name" = ?', $builder->toSql()); + $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); + } + + + public function testNestedWheres() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere(function ($q) { + $q->where('name', '=', 'bar')->where('age', '=', 25); + }); + $this->assertEquals('select * from "users" where "email" = ? or ("name" = ? and "age" = ?)', $builder->toSql()); + $this->assertEquals(array(0 => 'foo', 1 => 'bar', 2 => 25), $builder->getBindings()); + } + + + public function testFullSubSelects() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere('id', '=', function ($q) { + $q->select(new Raw('max(id)'))->from('users')->where('email', '=', 'bar'); + }); + + $this->assertEquals('select * from "users" where "email" = ? or "id" = (select max(id) from "users" where "email" = ?)', $builder->toSql()); + $this->assertEquals(array(0 => 'foo', 1 => 'bar'), $builder->getBindings()); + } + + + public function testWhereExists() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('orders')->whereExists(function ($q) { + $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); + }); + $this->assertEquals('select * from "orders" where exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('orders')->whereNotExists(function ($q) { + $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); + }); + $this->assertEquals('select * from "orders" where not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('orders')->where('id', '=', 1)->orWhereExists(function ($q) { + $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); + }); + $this->assertEquals('select * from "orders" where "id" = ? or exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('orders')->where('id', '=', 1)->orWhereNotExists(function ($q) { + $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); + }); + $this->assertEquals('select * from "orders" where "id" = ? or not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); + } + + + public function testBasicJoins() + { + foreach (array('left join' => 'leftJoin', 'right join' => 'rightJoin') as $joinQuery => $joinType) { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->$joinType('photos', 'users.id', '=', 'photos.id'); + $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" '.$joinQuery.' "photos" on "users"."id" = "photos"."id"', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->{$joinType . 'Where'}('photos', 'users.id', '=', 'bar')->joinWhere('photos', 'users.id', '=', 'foo'); + $this->assertEquals('select * from "users" '.$joinQuery.' "photos" on "users"."id" = ? inner join "photos" on "users"."id" = ?', $builder->toSql()); + $this->assertEquals(array('bar', 'foo'), $builder->getBindings()); + } + } + + + + + public function testComplexJoin() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->join('contacts', function ($j) { + $j->on('users.id', '=', 'contacts.id')->orOn('users.name', '=', 'contacts.name'); + }); + $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" or "users"."name" = "contacts"."name"', $builder->toSql()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->join('contacts', function ($j) { + $j->where('users.id', '=', 'foo')->orWhere('users.name', '=', 'bar'); + }); + $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = ? or "users"."name" = ?', $builder->toSql()); + $this->assertEquals(array('foo', 'bar'), $builder->getBindings()); + } + + public function testJoinWhereNull() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->join('contacts', function ($j) { + $j->on('users.id', '=', 'contacts.id')->whereNull('contacts.deleted_at'); + }); + $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" and "contacts"."deleted_at" is null', $builder->toSql()); + } + + public function testRawExpressionsInSelect() + { + $builder = $this->getBuilder(); + $builder->select(new Raw('substr(foo, 6)'))->from('users'); + $this->assertEquals('select substr(foo, 6) from "users"', $builder->toSql()); + } + + + public function testFindReturnsFirstResultByID() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select * from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar'))); + $results = $builder->from('users')->find(1); + $this->assertEquals(array('foo' => 'bar'), $results); + } + + + public function testFirstMethodReturnsFirstResult() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select * from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar'))); + $results = $builder->from('users')->where('id', '=', 1)->first(); + $this->assertEquals(array('foo' => 'bar'), $results); + } - public function testAddingSelects() - { - $builder = $this->getBuilder(); - $builder->select('foo')->addSelect('bar')->addSelect(array('baz', 'boom'))->from('users'); - $this->assertEquals('select "foo", "bar", "baz", "boom" from "users"', $builder->toSql()); - } + public function testListMethodsGetsArrayOfColumnValues() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('foo' => 'bar'), array('foo' => 'baz'))); + $results = $builder->from('users')->where('id', '=', 1)->lists('foo'); + $this->assertEquals(array('bar', 'baz'), $results); + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('id' => 1, 'foo' => 'bar'), array('id' => 10, 'foo' => 'baz'))); + $results = $builder->from('users')->where('id', '=', 1)->lists('foo', 'id'); + $this->assertEquals(array(1 => 'bar', 10 => 'baz'), $results); + } - public function testBasicSelectWithPrefix() - { - $builder = $this->getBuilder(); - $builder->getGrammar()->setTablePrefix('prefix_'); - $builder->select('*')->from('users'); - $this->assertEquals('select * from "prefix_users"', $builder->toSql()); - } + public function testImplode() + { + // Test without glue. + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('foo' => 'bar'), array('foo' => 'baz'))); + $results = $builder->from('users')->where('id', '=', 1)->implode('foo'); + $this->assertEquals('barbaz', $results); - public function testBasicSelectDistinct() - { - $builder = $this->getBuilder(); - $builder->distinct()->select('foo', 'bar')->from('users'); - $this->assertEquals('select distinct "foo", "bar" from "users"', $builder->toSql()); - } + // Test with glue. + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('foo' => 'bar'), array('foo' => 'baz'))); + $results = $builder->from('users')->where('id', '=', 1)->implode('foo', ','); + $this->assertEquals('bar,baz', $results); + } - public function testSubSelectRawString() + public function testPluckMethodReturnsSingleColumn() { $builder = $this->getBuilder(); - $builder->selectSub('select * from test', 'tmp')->from('users'); - $this->assertEquals('select (select * from test) as "tmp" from "users"', $builder->toSql()); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "foo" from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar'))); + $results = $builder->from('users')->where('id', '=', 1)->pluck('foo'); + $this->assertEquals('bar', $results); } - public function testSubSelectClosure() + + public function testAggregateFunctions() { $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $results = $builder->from('users')->count(); + $this->assertEquals(1, $results); - $builder->selectSub(function($build){ - $build->select('foo')->where('bar','=','baz')->from('test'); - }, 'tmp')->from('users'); + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $results = $builder->from('users')->exists(); + $this->assertTrue($results); - $this->assertEquals('select (select "foo" from "test" where "bar" = ?) as "tmp" from "users"', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - } + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select max("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $results = $builder->from('users')->max('id'); + $this->assertEquals(1, $results); - /** - * @expectedException InvalidArgumentException - */ - public function testSubSelectThrowsInvalidArgument() - { $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select min("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $results = $builder->from('users')->min('id'); + $this->assertEquals(1, $results); - $builder->selectSub(array('test'), 'tmp')->from('users'); + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select sum("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $results = $builder->from('users')->sum('id'); + $this->assertEquals(1, $results); } - public function testBasicAlias() - { - $builder = $this->getBuilder(); - $builder->select('foo as bar')->from('users'); - $this->assertEquals('select "foo" as "bar" from "users"', $builder->toSql()); - } + public function testAggregateResetFollowedByGet() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select sum("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 2))); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "column1", "column2" from "users"', array())->andReturn(array(array('column1' => 'foo', 'column2' => 'bar'))); + $builder->from('users')->select('column1', 'column2'); + $count = $builder->count(); + $this->assertEquals(1, $count); + $sum = $builder->sum('id'); + $this->assertEquals(2, $sum); + $result = $builder->get(); + $this->assertEquals(array(array('column1' => 'foo', 'column2' => 'bar')), $result); + } - public function testBasicTableWrapping() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('public.users'); - $this->assertEquals('select * from "public"."users"', $builder->toSql()); - } + public function testAggregateResetFollowedBySelectGet() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count("column1") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "column2", "column3" from "users"', array())->andReturn(array(array('column2' => 'foo', 'column3' => 'bar'))); + $builder->from('users'); + $count = $builder->count('column1'); + $this->assertEquals(1, $count); + $result = $builder->select('column2', 'column3')->get(); + $this->assertEquals(array(array('column2' => 'foo', 'column3' => 'bar')), $result); + } - public function testBasicWheres() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1); - $this->assertEquals('select * from "users" where "id" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - public function testArrayWheres() + public function testAggregateResetFollowedByGetWithColumns() { $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where(array('id' => 1, 'name' => 2)); - $this->assertEquals('select * from "users" where ("id" = ? and "name" = ?)', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count("column1") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "column2", "column3" from "users"', array())->andReturn(array(array('column2' => 'foo', 'column3' => 'bar'))); + $builder->from('users'); + $count = $builder->count('column1'); + $this->assertEquals(1, $count); + $result = $builder->get(array('column2', 'column3')); + $this->assertEquals(array(array('column2' => 'foo', 'column3' => 'bar')), $result); } - public function testMySqlWrappingProtectsQuotationMarks() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->From('some`table'); - $this->assertEquals('select * from `some``table`', $builder->toSql()); - } - - - public function testWhereDayMySql() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('users')->whereDay('created_at', '=', 1); - $this->assertEquals('select * from `users` where day(`created_at`) = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - - - public function testWhereMonthMySql() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); - $this->assertEquals('select * from `users` where month(`created_at`) = ?', $builder->toSql()); - $this->assertEquals(array(0 => 5), $builder->getBindings()); - } - - - public function testWhereYearMySql() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); - $this->assertEquals('select * from `users` where year(`created_at`) = ?', $builder->toSql()); - $this->assertEquals(array(0 => 2014), $builder->getBindings()); - } - - - public function testWhereDayPostgres() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('users')->whereDay('created_at', '=', 1); - $this->assertEquals('select * from "users" where day("created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - - - public function testWhereMonthPostgres() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); - $this->assertEquals('select * from "users" where month("created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 5), $builder->getBindings()); - } - - - public function testWhereYearPostgres() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); - $this->assertEquals('select * from "users" where year("created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 2014), $builder->getBindings()); - } - - - public function testWhereDaySqlite() - { - $builder = $this->getSQLiteBuilder(); - $builder->select('*')->from('users')->whereDay('created_at', '=', 1); - $this->assertEquals('select * from "users" where strftime(\'%d\', "created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - - - public function testWhereMonthSqlite() - { - $builder = $this->getSQLiteBuilder(); - $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); - $this->assertEquals('select * from "users" where strftime(\'%m\', "created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 5), $builder->getBindings()); - } - - - public function testWhereYearSqlite() - { - $builder = $this->getSQLiteBuilder(); - $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); - $this->assertEquals('select * from "users" where strftime(\'%Y\', "created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 2014), $builder->getBindings()); - } - - - public function testWhereDaySqlServer() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('users')->whereDay('created_at', '=', 1); - $this->assertEquals('select * from "users" where day("created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - - - public function testWhereMonthSqlServer() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('users')->whereMonth('created_at', '=', 5); - $this->assertEquals('select * from "users" where month("created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 5), $builder->getBindings()); - } - - - public function testWhereYearSqlServer() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('users')->whereYear('created_at', '=', 2014); - $this->assertEquals('select * from "users" where year("created_at") = ?', $builder->toSql()); - $this->assertEquals(array(0 => 2014), $builder->getBindings()); - } - - - public function testWhereBetweens() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereBetween('id', array(1, 2)); - $this->assertEquals('select * from "users" where "id" between ? and ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereNotBetween('id', array(1, 2)); - $this->assertEquals('select * from "users" where "id" not between ? and ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); - } - - - public function testBasicOrWheres() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1)->orWhere('email', '=', 'foo'); - $this->assertEquals('select * from "users" where "id" = ? or "email" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); - } - - - public function testRawWheres() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereRaw('id = ? or email = ?', array(1, 'foo')); - $this->assertEquals('select * from "users" where id = ? or email = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); - } - - - public function testRawOrWheres() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1)->orWhereRaw('email = ?', array('foo')); - $this->assertEquals('select * from "users" where "id" = ? or email = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); - } - - - public function testBasicWhereIns() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereIn('id', array(1, 2, 3)); - $this->assertEquals('select * from "users" where "id" in (?, ?, ?)', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1)->orWhereIn('id', array(1, 2, 3)); - $this->assertEquals('select * from "users" where "id" = ? or "id" in (?, ?, ?)', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 1, 2 => 2, 3 => 3), $builder->getBindings()); - } - - - public function testBasicWhereNotIns() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereNotIn('id', array(1, 2, 3)); - $this->assertEquals('select * from "users" where "id" not in (?, ?, ?)', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNotIn('id', array(1, 2, 3)); - $this->assertEquals('select * from "users" where "id" = ? or "id" not in (?, ?, ?)', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 1, 2 => 2, 3 => 3), $builder->getBindings()); - } - - - public function testUnions() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1); - $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); - $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); - - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1); - $builder->union($this->getMySqlBuilder()->select('*')->from('users')->where('id', '=', 2)); - $this->assertEquals('(select * from `users` where `id` = ?) union (select * from `users` where `id` = ?)', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); - } - - - public function testUnionAlls() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1); - $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); - $this->assertEquals('select * from "users" where "id" = ? union all select * from "users" where "id" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2), $builder->getBindings()); - } - - - public function testMultipleUnions() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1); - $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); - $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 3)); - $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ? union select * from "users" where "id" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); - } - - - public function testMultipleUnionAlls() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1); - $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 2)); - $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 3)); - $this->assertEquals('select * from "users" where "id" = ? union all select * from "users" where "id" = ? union all select * from "users" where "id" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 2, 2 => 3), $builder->getBindings()); - } - - - public function testSubSelectWhereIns() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereIn('id', function($q) - { - $q->select('id')->from('users')->where('age', '>', 25)->limit(3); - }); - $this->assertEquals('select * from "users" where "id" in (select "id" from "users" where "age" > ? limit 3)', $builder->toSql()); - $this->assertEquals(array(25), $builder->getBindings()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereNotIn('id', function($q) - { - $q->select('id')->from('users')->where('age', '>', 25)->limit(3); - }); - $this->assertEquals('select * from "users" where "id" not in (select "id" from "users" where "age" > ? limit 3)', $builder->toSql()); - $this->assertEquals(array(25), $builder->getBindings()); - } - - - public function testBasicWhereNulls() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereNull('id'); - $this->assertEquals('select * from "users" where "id" is null', $builder->toSql()); - $this->assertEquals(array(), $builder->getBindings()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNull('id'); - $this->assertEquals('select * from "users" where "id" = ? or "id" is null', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - - - public function testBasicWhereNotNulls() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->whereNotNull('id'); - $this->assertEquals('select * from "users" where "id" is not null', $builder->toSql()); - $this->assertEquals(array(), $builder->getBindings()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', '>', 1)->orWhereNotNull('id'); - $this->assertEquals('select * from "users" where "id" > ? or "id" is not null', $builder->toSql()); - $this->assertEquals(array(0 => 1), $builder->getBindings()); - } - - - public function testGroupBys() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->groupBy('id', 'email'); - $this->assertEquals('select * from "users" group by "id", "email"', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->groupBy(['id', 'email']); - $this->assertEquals('select * from "users" group by "id", "email"', $builder->toSql()); - } - - - public function testOrderBys() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->orderBy('email')->orderBy('age', 'desc'); - $this->assertEquals('select * from "users" order by "email" asc, "age" desc', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->orderBy('email')->orderByRaw('"age" ? desc', array('foo')); - $this->assertEquals('select * from "users" order by "email" asc, "age" ? desc', $builder->toSql()); - $this->assertEquals(array('foo'), $builder->getBindings()); - } - - - public function testHavings() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->having('email', '>', 1); - $this->assertEquals('select * from "users" having "email" > ?', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->groupBy('email')->having('email', '>', 1); - $this->assertEquals('select * from "users" group by "email" having "email" > ?', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('email as foo_email')->from('users')->having('foo_email', '>', 1); - $this->assertEquals('select "email" as "foo_email" from "users" having "foo_email" > ?', $builder->toSql()); - } - - - public function testRawHavings() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->havingRaw('user_foo < user_bar'); - $this->assertEquals('select * from "users" having user_foo < user_bar', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->having('baz', '=', 1)->orHavingRaw('user_foo < user_bar'); - $this->assertEquals('select * from "users" having "baz" = ? or user_foo < user_bar', $builder->toSql()); - } - - - public function testLimitsAndOffsets() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->offset(5)->limit(10); - $this->assertEquals('select * from "users" limit 10 offset 5', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->offset(5)->limit(10); - $this->assertEquals('select * from "users" limit 10 offset 5', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->offset(-5)->limit(10); - $this->assertEquals('select * from "users" limit 10 offset 0', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->forPage(2, 15); - $this->assertEquals('select * from "users" limit 15 offset 15', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->forPage(-2, 15); - $this->assertEquals('select * from "users" limit 15 offset 0', $builder->toSql()); - } - - - public function testWhereShortcut() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('id', 1)->orWhere('name', 'foo'); - $this->assertEquals('select * from "users" where "id" = ? or "name" = ?', $builder->toSql()); - $this->assertEquals(array(0 => 1, 1 => 'foo'), $builder->getBindings()); - } - - - public function testNestedWheres() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere(function($q) - { - $q->where('name', '=', 'bar')->where('age', '=', 25); - }); - $this->assertEquals('select * from "users" where "email" = ? or ("name" = ? and "age" = ?)', $builder->toSql()); - $this->assertEquals(array(0 => 'foo', 1 => 'bar', 2 => 25), $builder->getBindings()); - } - - - public function testFullSubSelects() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere('id', '=', function($q) - { - $q->select(new Raw('max(id)'))->from('users')->where('email', '=', 'bar'); - }); - - $this->assertEquals('select * from "users" where "email" = ? or "id" = (select max(id) from "users" where "email" = ?)', $builder->toSql()); - $this->assertEquals(array(0 => 'foo', 1 => 'bar'), $builder->getBindings()); - } - - - public function testWhereExists() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('orders')->whereExists(function($q) - { - $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); - }); - $this->assertEquals('select * from "orders" where exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('orders')->whereNotExists(function($q) - { - $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); - }); - $this->assertEquals('select * from "orders" where not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('orders')->where('id', '=', 1)->orWhereExists(function($q) - { - $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); - }); - $this->assertEquals('select * from "orders" where "id" = ? or exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('orders')->where('id', '=', 1)->orWhereNotExists(function($q) - { - $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"')); - }); - $this->assertEquals('select * from "orders" where "id" = ? or not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql()); - } - - - public function testBasicJoins() - { - foreach(array('left join' => 'leftJoin', 'right join' => 'rightJoin') as $joinQuery => $joinType) - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->$joinType('photos', 'users.id', '=', 'photos.id'); - $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" '.$joinQuery.' "photos" on "users"."id" = "photos"."id"', $builder->toSql()); + public function testInsertSelectOnDuplicateKeyRawMethod() + { + $builder = $this->getMySqlBuilder(); - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->{$joinType . 'Where'}('photos', 'users.id', '=', 'bar')->joinWhere('photos', 'users.id', '=', 'foo'); - $this->assertEquals('select * from "users" '.$joinQuery.' "photos" on "users"."id" = ? inner join "photos" on "users"."id" = ?', $builder->toSql()); - $this->assertEquals(array('bar', 'foo'), $builder->getBindings()); - } + $builder->getConnection()->shouldReceive('query')->once() + ->with('insert into `users` (`email`, `name`) select `email`, `name` from `admin` where `name` = ? on duplicate key update `total` = ?, `email` = VALUES(email)', array('John', 1)) + ->andReturn(true); - } - - - - - public function testComplexJoin() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->join('contacts', function($j) - { - $j->on('users.id', '=', 'contacts.id')->orOn('users.name', '=', 'contacts.name'); - }); - $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" or "users"."name" = "contacts"."name"', $builder->toSql()); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->join('contacts', function($j) - { - $j->where('users.id', '=', 'foo')->orWhere('users.name', '=', 'bar'); - }); - $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = ? or "users"."name" = ?', $builder->toSql()); - $this->assertEquals(array('foo', 'bar'), $builder->getBindings()); - } - - public function testJoinWhereNull() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->join('contacts', function($j) - { - $j->on('users.id', '=', 'contacts.id')->whereNull('contacts.deleted_at'); - }); - $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" and "contacts"."deleted_at" is null', $builder->toSql()); - } - - public function testRawExpressionsInSelect() - { - $builder = $this->getBuilder(); - $builder->select(new Raw('substr(foo, 6)'))->from('users'); - $this->assertEquals('select substr(foo, 6) from "users"', $builder->toSql()); - } - - - public function testFindReturnsFirstResultByID() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select * from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar'))); - $results = $builder->from('users')->find(1); - $this->assertEquals(array('foo' => 'bar'), $results); - } - - - public function testFirstMethodReturnsFirstResult() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select * from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar'))); - $results = $builder->from('users')->where('id', '=', 1)->first(); - $this->assertEquals(array('foo' => 'bar'), $results); - } - - - public function testListMethodsGetsArrayOfColumnValues() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('foo' => 'bar'), array('foo' => 'baz'))); - $results = $builder->from('users')->where('id', '=', 1)->lists('foo'); - $this->assertEquals(array('bar', 'baz'), $results); - - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('id' => 1, 'foo' => 'bar'), array('id' => 10, 'foo' => 'baz'))); - $results = $builder->from('users')->where('id', '=', 1)->lists('foo', 'id'); - $this->assertEquals(array(1 => 'bar', 10 => 'baz'), $results); - } - - - public function testImplode() - { - // Test without glue. - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('foo' => 'bar'), array('foo' => 'baz'))); - $results = $builder->from('users')->where('id', '=', 1)->implode('foo'); - $this->assertEquals('barbaz', $results); - - // Test with glue. - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->andReturn(array(array('foo' => 'bar'), array('foo' => 'baz'))); - $results = $builder->from('users')->where('id', '=', 1)->implode('foo', ','); - $this->assertEquals('bar,baz', $results); - } - - public function testPluckMethodReturnsSingleColumn() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "foo" from "users" where "id" = ? limit 1', array(1))->andReturn(array(array('foo' => 'bar'))); - $results = $builder->from('users')->where('id', '=', 1)->pluck('foo'); - $this->assertEquals('bar', $results); - } - - - public function testAggregateFunctions() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $results = $builder->from('users')->count(); - $this->assertEquals(1, $results); - - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $results = $builder->from('users')->exists(); - $this->assertTrue($results); - - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select max("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $results = $builder->from('users')->max('id'); - $this->assertEquals(1, $results); - - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select min("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $results = $builder->from('users')->min('id'); - $this->assertEquals(1, $results); - - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select sum("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $results = $builder->from('users')->sum('id'); - $this->assertEquals(1, $results); - } - - - public function testAggregateResetFollowedByGet() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select sum("id") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 2))); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "column1", "column2" from "users"', array())->andReturn(array(array('column1' => 'foo', 'column2' => 'bar'))); - $builder->from('users')->select('column1', 'column2'); - $count = $builder->count(); - $this->assertEquals(1, $count); - $sum = $builder->sum('id'); - $this->assertEquals(2, $sum); - $result = $builder->get(); - $this->assertEquals(array(array('column1' => 'foo', 'column2' => 'bar')), $result); - } - - - public function testAggregateResetFollowedBySelectGet() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count("column1") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "column2", "column3" from "users"', array())->andReturn(array(array('column2' => 'foo', 'column3' => 'bar'))); - $builder->from('users'); - $count = $builder->count('column1'); - $this->assertEquals(1, $count); - $result = $builder->select('column2', 'column3')->get(); - $this->assertEquals(array(array('column2' => 'foo', 'column3' => 'bar')), $result); - } - - - public function testAggregateResetFollowedByGetWithColumns() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count("column1") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1))); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select "column2", "column3" from "users"', array())->andReturn(array(array('column2' => 'foo', 'column3' => 'bar'))); - $builder->from('users'); - $count = $builder->count('column1'); - $this->assertEquals(1, $count); - $result = $builder->get(array('column2', 'column3')); - $this->assertEquals(array(array('column2' => 'foo', 'column3' => 'bar')), $result); - } - - public function testInsertSelectOnDuplicateKeyRawMethod() - { - $builder = $this->getMySqlBuilder(); - - $builder->getConnection()->shouldReceive('query')->once() - ->with('insert into `users` (`email`, `name`) select `email`, `name` from `admin` where `name` = ? on duplicate key update `total` = ?, `email` = VALUES(email)', array('John', 1)) - ->andReturn(true); - - $select = $builder->newQuery() - ->from('admin') - ->select('email', 'name') - ->where('name','John'); - - $result = $builder - ->from('users') - ->insertSelectOnDuplicateKeyUpdate( - $select, - array('email', 'name'), - array('total' => 1, 'email' => new \Database\Query\Expression('VALUES(email)')) - ); - - $this->assertTrue($result); - } + $select = $builder->newQuery() + ->from('admin') + ->select('email', 'name') + ->where('name', 'John'); + + $result = $builder + ->from('users') + ->insertSelectOnDuplicateKeyUpdate( + $select, + array('email', 'name'), + array('total' => 1, 'email' => new \Database\Query\Expression('VALUES(email)')) + ); + + $this->assertTrue($result); + } public function doTestInsertSelectMethod($query, $method) { @@ -752,7 +739,7 @@ public function doTestInsertSelectMethod($query, $method) $select = $builder->newQuery() ->from('admin') ->select('email') - ->where('name','foo'); + ->where('name', 'foo'); $result = $builder ->from('users') @@ -770,10 +757,10 @@ public function testInsertSelectMethodClosure() $result = $builder ->from('users') - ->insertSelect(function($select){ + ->insertSelect(function ($select) { $select->from('admin') ->select('email') - ->where('name','foo'); + ->where('name', 'foo'); }, array('email')); $this->assertTrue($result); @@ -794,13 +781,13 @@ public function testReplaceSelectMethod() $this->doTestInsertSelectMethod("replace", "replaceSelect"); } - public function testInsertMethod() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email") values (?)', array('foo'))->andReturn(true); - $result = $builder->from('users')->insert(array('email' => 'foo')); - $this->assertTrue($result); - } + public function testInsertMethod() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email") values (?)', array('foo'))->andReturn(true); + $result = $builder->from('users')->insert(array('email' => 'foo')); + $this->assertTrue($result); + } public function testReplaceMethod() { @@ -826,81 +813,81 @@ public function testInsertIgnoreMethodSqlite() $this->assertTrue($result); } - public function testSQLiteMultipleInserts() - { - $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email", "name") select ? as "email", ? as "name" union select ? as "email", ? as "name"', array('foo', 'taylor', 'bar', 'dayle'))->andReturn(true); - $result = $builder->from('users')->insert(array(array('email' => 'foo', 'name' => 'taylor'), array('email' => 'bar', 'name' => 'dayle'))); - $this->assertTrue($result); - } + public function testSQLiteMultipleInserts() + { + $builder = $this->getSQLiteBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email", "name") select ? as "email", ? as "name" union select ? as "email", ? as "name"', array('foo', 'taylor', 'bar', 'dayle'))->andReturn(true); + $result = $builder->from('users')->insert(array(array('email' => 'foo', 'name' => 'taylor'), array('email' => 'bar', 'name' => 'dayle'))); + $this->assertTrue($result); + } - public function testInsertGetIdMethod() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email") values (?)', array('foo')); + public function testInsertGetIdMethod() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email") values (?)', array('foo')); $builder->getConnection()->shouldReceive('lastInsertId')->once()->andReturn(1); - $result = $builder->from('users')->insertGetId(array('email' => 'foo')); - $this->assertEquals(1, $result); - } - - public function testInsertMethodRespectsRawBindings() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email") values (CURRENT TIMESTAMP)', array())->andReturn(true); - $result = $builder->from('users')->insert(array('email' => new Raw('CURRENT TIMESTAMP'))); - $this->assertTrue($result); - } - - - public function testUpdateMethod() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = ?, "name" = ? where "id" = ?', array('foo', 'bar', 1))->andReturn(1); - $result = $builder->from('users')->where('id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); - $this->assertEquals(1, $result); - - $builder = $this->getMySqlBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('update `users` set `email` = ?, `name` = ? where `id` = ? order by `foo` desc limit 5', array('foo', 'bar', 1))->andReturn(1); - $result = $builder->from('users')->where('id', '=', 1)->orderBy('foo', 'desc')->limit(5)->update(array('email' => 'foo', 'name' => 'bar')); - $this->assertEquals(1, $result); - } - - - public function testUpdateMethodWithJoins() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" set "email" = ?, "name" = ? where "users"."id" = ?', array('foo', 'bar', 1))->andReturn(1); - $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); - $this->assertEquals(1, $result); - } - - - public function testUpdateMethodWithoutJoinsOnPostgres() - { - $builder = $this->getPostgresBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = ?, "name" = ? where "id" = ?', array('foo', 'bar', 1))->andReturn(1); - $result = $builder->from('users')->where('id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); - $this->assertEquals(1, $result); - } - - - public function testUpdateMethodWithJoinsOnPostgres() - { - $builder = $this->getPostgresBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = ? and "users"."id" = "orders"."user_id"', array('foo', 'bar', 1))->andReturn(1); - $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); - $this->assertEquals(1, $result); - } - - - public function testUpdateMethodRespectsRaw() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = foo, "name" = ? where "id" = ?', array('bar', 1))->andReturn(1); - $result = $builder->from('users')->where('id', '=', 1)->update(array('email' => new Raw('foo'), 'name' => 'bar')); - $this->assertEquals(1, $result); - } + $result = $builder->from('users')->insertGetId(array('email' => 'foo')); + $this->assertEquals(1, $result); + } + + public function testInsertMethodRespectsRawBindings() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('insert into "users" ("email") values (CURRENT TIMESTAMP)', array())->andReturn(true); + $result = $builder->from('users')->insert(array('email' => new Raw('CURRENT TIMESTAMP'))); + $this->assertTrue($result); + } + + + public function testUpdateMethod() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = ?, "name" = ? where "id" = ?', array('foo', 'bar', 1))->andReturn(1); + $result = $builder->from('users')->where('id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); + $this->assertEquals(1, $result); + + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('update `users` set `email` = ?, `name` = ? where `id` = ? order by `foo` desc limit 5', array('foo', 'bar', 1))->andReturn(1); + $result = $builder->from('users')->where('id', '=', 1)->orderBy('foo', 'desc')->limit(5)->update(array('email' => 'foo', 'name' => 'bar')); + $this->assertEquals(1, $result); + } + + + public function testUpdateMethodWithJoins() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" set "email" = ?, "name" = ? where "users"."id" = ?', array('foo', 'bar', 1))->andReturn(1); + $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); + $this->assertEquals(1, $result); + } + + + public function testUpdateMethodWithoutJoinsOnPostgres() + { + $builder = $this->getPostgresBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = ?, "name" = ? where "id" = ?', array('foo', 'bar', 1))->andReturn(1); + $result = $builder->from('users')->where('id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); + $this->assertEquals(1, $result); + } + + + public function testUpdateMethodWithJoinsOnPostgres() + { + $builder = $this->getPostgresBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = ? and "users"."id" = "orders"."user_id"', array('foo', 'bar', 1))->andReturn(1); + $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(array('email' => 'foo', 'name' => 'bar')); + $this->assertEquals(1, $result); + } + + + public function testUpdateMethodRespectsRaw() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('update "users" set "email" = foo, "name" = ? where "id" = ?', array('bar', 1))->andReturn(1); + $result = $builder->from('users')->where('id', '=', 1)->update(array('email' => new Raw('foo'), 'name' => 'bar')); + $this->assertEquals(1, $result); + } public function testInsertOnDuplicateKeyMethod() { @@ -932,7 +919,7 @@ public function testInsertOnDuplicateKeyRawMethod() public function testBufferedInsert() { - $statement = $this->getMock('PDOStatement', array('rowCount')); + $statement = $this->createMock('PDOStatement', array('rowCount')); $statement->expects($this->exactly(2)) ->method('rowCount') @@ -959,326 +946,330 @@ public function testBufferedInsert() $this->assertEquals(4, $result); } - public function testDeleteMethod() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('delete from "users" where "email" = ?', array('foo'))->andReturn(1); - $result = $builder->from('users')->where('email', '=', 'foo')->delete(); - $this->assertEquals(1, $result); - - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('delete from "users" where "id" = ?', array(1))->andReturn(1); - $result = $builder->from('users')->delete(1); - $this->assertEquals(1, $result); - } - - - public function testDeleteWithJoinMethod() - { - $builder = $this->getMySqlBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', array('foo'))->andReturn(1); - $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->delete(); - $this->assertEquals(1, $result); - - $builder = $this->getMySqlBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `id` = ?', array(1))->andReturn(1); - $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(1); - $this->assertEquals(1, $result); - } - - - public function testTruncateMethod() - { - $builder = $this->getBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with('truncate "users"', array()); - $builder->from('users')->truncate(); - - $sqlite = new Database\Query\Grammars\SQLiteGrammar; - $builder = $this->getBuilder(); - $builder->from('users'); - $this->assertEquals(array( - 'delete from sqlite_sequence where name = ?' => array('users'), - 'delete from "users"' => array(), - ), $sqlite->compileTruncate($builder)); - } - - public function testMySqlWrapping() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('users'); - $this->assertEquals('select * from `users`', $builder->toSql()); - } - - - public function testSQLiteOrderBy() - { - $builder = $this->getSQLiteBuilder(); - $builder->select('*')->from('users')->orderBy('email', 'desc'); - $this->assertEquals('select * from "users" order by "email" desc', $builder->toSql()); - } - - - public function testSqlServerLimitsAndOffsets() - { - $builder = $this->getSqlServerBuilder(); - $builder->select('*')->from('users')->limit(10); - $this->assertEquals('select top 10 * from [users]', $builder->toSql()); - - $builder = $this->getSqlServerBuilder(); - $builder->select('*')->from('users')->offset(10); - $this->assertEquals('select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num >= 11', $builder->toSql()); - - $builder = $this->getSqlServerBuilder(); - $builder->select('*')->from('users')->offset(10)->limit(10); - $this->assertEquals('select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num between 11 and 20', $builder->toSql()); - - $builder = $this->getSqlServerBuilder(); - $builder->select('*')->from('users')->offset(10)->limit(10)->orderBy('email', 'desc'); - $this->assertEquals('select * from (select *, row_number() over (order by [email] desc) as row_num from [users]) as temp_table where row_num between 11 and 20', $builder->toSql()); - } - - - public function testMergeWheresCanMergeWheresAndBindings() - { - $builder = $this->getBuilder(); - $builder->wheres = array('foo'); - $builder->mergeWheres(array('wheres'), array(12 => 'foo', 13 => 'bar')); - $this->assertEquals(array('foo', 'wheres'), $builder->wheres); - $this->assertEquals(array('foo', 'bar'), $builder->getBindings()); - } - - - public function testProvidingNullOrFalseAsSecondParameterBuildsCorrectly() - { - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->where('foo', null); - $this->assertEquals('select * from "users" where "foo" is null', $builder->toSql()); - } - - - /** - * @expectedException BadMethodCallException - */ - public function testBuilderThrowsExpectedExceptionWithUndefinedMethod() - { - $builder = $this->getBuilder(); - - $builder->noValidMethodHere(); - } - - - public function setupCacheTestQuery($cache, $driver) - { - $connection = m::mock('Database\ConnectionInterface'); - $connection->shouldReceive('getName')->andReturn('connection_name'); - $connection->shouldReceive('getCacheManager')->once()->andReturn($cache); - $cache->shouldReceive('driver')->once()->andReturn($driver); - $grammar = new Database\Query\Grammars\Grammar; - $processor = m::mock('Database\Query\Processors\Processor'); - - $builder = $this->getMock('Database\Query\Builder', array('getFresh'), array($connection, $grammar, $processor)); - $builder->expects($this->once())->method('getFresh')->with($this->equalTo(array('*')))->will($this->returnValue(array('results'))); - return $builder->select('*')->from('users')->where('email', 'foo@bar.com'); - } - - public function testMySqlRollup() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->groupBy('foo', 'bar')->withRollUp(); - $this->assertEquals('select * from `foo` where `bar` = ? group by `foo`, `bar` with rollup', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - } - - public function testMySqlRollupIsIgnoredWithoutGroupBy() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->withRollUp(); - $this->assertEquals('select * from `foo` where `bar` = ?', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - } - - public function testMySqlLock() - { - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(); - $this->assertEquals('select * from `foo` where `bar` = ? for update', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - - $builder = $this->getMySqlBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false); - $this->assertEquals('select * from `foo` where `bar` = ? lock in share mode', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - } - - public function testMySqlOutfile() - { - $builder = $this->getMySqlBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with( - 'select * into outfile \'filename\' from `foo` where `bar` = ?', - array('baz') - ); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->intoOutfile('filename')->query(); - } - - public function testMySqlOutfileWithParams() - { - $builder = $this->getMySqlBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with( - "select * into outfile 'filename' character set binary fields terminated by ',' optionally enclosed by '.' escaped by '\' lines terminated by '\n\r' from `foo` where `bar` = ?", - array('baz') - ); - - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->intoOutfile('filename', function(\Database\Query\OutfileClause $of){ - $of->enclosedBy(".", true) - ->escapedBy("\\") - ->characterSet('binary') - ->linesTerminatedBy("\n\r") - ->fieldsTerminatedBy(','); - })->query(); - } - - public function testMySqlDumpfile() - { - $builder = $this->getMySqlBuilder(); - $builder->getConnection()->shouldReceive('query')->once()->with( - "select * into dumpfile 'filename' from `foo` where `bar` = ?", - array('baz') - ); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->intoDumpfile('filename')->query(); - } - - public function testBasicInfile() - { - $builder = $this->getMySqlBuilder(); - - $filepath = 'bizbazbar'; - $tablename = 'foo'; - - $builder->getConnection()->shouldReceive('query')->once()->with( - "load data infile '$filepath' into table `$tablename` (`col1`, col2, `col3`)", - array()); - - $builder - ->from($tablename) - ->infile($filepath, array('col1', new \Database\Query\Expression('col2'), 'col3')); - } - - public function testInfile() - { - $builder = $this->getMySqlBuilder(); - - $filepath = 'bizbazbar'; - $tablename = 'foo'; - - $builder->getConnection()->shouldReceive('query')->once()->with( - "load data infile '$filepath' ignore into table `$tablename` character set utf8 fields terminated by ',' enclosed by '.' escaped by '\' lines starting by '$' terminated by '\n\r' ignore 4 lines (`col1`, col2, `col3`) set `fizz` = baz + 1, `buzz` = ?", - array('bar') - ); - - $builder - ->from($tablename) - ->infile($filepath, array('col1', new \Database\Query\Expression('col2'), 'col3'), function(\Database\Query\InfileClause $if){ - $if - ->ignore() - ->rules(array( - 'fizz' => new \Database\Query\Expression('baz + 1'), - 'buzz' => 'bar', - )) - ->characterSet('utf8') - ->enclosedBy(".") - ->escapedBy("\\") - ->linesStartingBy('$') - ->linesTerminatedBy("\n\r") - ->ignoreLines(4) - ->fieldsTerminatedBy(','); - }); - } - - public function testPostgresLock() - { - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(); - $this->assertEquals('select * from "foo" where "bar" = ? for update', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - - $builder = $this->getPostgresBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false); - $this->assertEquals('select * from "foo" where "bar" = ? for share', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - } - - - public function testSqlServerLock() - { - $builder = $this->getSqlServerBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(); - $this->assertEquals('select * from [foo] with(rowlock,updlock,holdlock) where [bar] = ?', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - - $builder = $this->getSqlServerBuilder(); - $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false); - $this->assertEquals('select * from [foo] with(rowlock,holdlock) where [bar] = ?', $builder->toSql()); - $this->assertEquals(array('baz'), $builder->getBindings()); - } - - - public function testBindingOrder() - { - $expectedSql = 'select * from "users" inner join "othertable" on "bar" = ? where "registered" = ? group by "city" having "population" > ? order by match ("foo") against(?)'; - $expectedBindings = array('foo', 1, 3, 'bar'); - - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->join('othertable', function($join) { $join->where('bar', '=', 'foo'); })->where('registered', 1)->groupBy('city')->having('population', '>', 3)->orderByRaw('match ("foo") against(?)', array('bar')); - $this->assertEquals($expectedSql, $builder->toSql()); - $this->assertEquals($expectedBindings, $builder->getBindings()); - - // order of statements reversed - $builder = $this->getBuilder(); - $builder->select('*')->from('users')->orderByRaw('match ("foo") against(?)', array('bar'))->having('population', '>', 3)->groupBy('city')->where('registered', 1)->join('othertable', function($join) { $join->where('bar', '=', 'foo'); }); - $this->assertEquals($expectedSql, $builder->toSql()); - $this->assertEquals($expectedBindings, $builder->getBindings()); - } - - - public function testAddBindingWithArrayMergesBindings() - { - $builder = $this->getBuilder(); - $builder->addBinding(array('foo', 'bar')); - $builder->addBinding(array('baz')); - $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); - } - - - public function testAddBindingWithArrayMergesBindingsInCorrectOrder() - { - $builder = $this->getBuilder(); - $builder->addBinding(array('bar', 'baz'), 'having'); - $builder->addBinding(array('foo'), 'where'); - $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); - } - - - public function testMergeBuilders() - { - $builder = $this->getBuilder(); - $builder->addBinding(array('foo', 'bar')); - $otherBuilder = $this->getBuilder(); - $otherBuilder->addBinding(array('baz')); - $builder->mergeBindings($otherBuilder); - $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); - } - - - public function testMergeBuildersBindingOrder() - { - $builder = $this->getBuilder(); - $builder->addBinding('foo', 'where'); - $builder->addBinding('baz', 'having'); - $otherBuilder = $this->getBuilder(); - $otherBuilder->addBinding('bar', 'where'); - $builder->mergeBindings($otherBuilder); - $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); - } + public function testDeleteMethod() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('delete from "users" where "email" = ?', array('foo'))->andReturn(1); + $result = $builder->from('users')->where('email', '=', 'foo')->delete(); + $this->assertEquals(1, $result); + + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('delete from "users" where "id" = ?', array(1))->andReturn(1); + $result = $builder->from('users')->delete(1); + $this->assertEquals(1, $result); + } + + + public function testDeleteWithJoinMethod() + { + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', array('foo'))->andReturn(1); + $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->delete(); + $this->assertEquals(1, $result); + + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `id` = ?', array(1))->andReturn(1); + $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(1); + $this->assertEquals(1, $result); + } + + + public function testTruncateMethod() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with('truncate "users"', array()); + $builder->from('users')->truncate(); + + $sqlite = new Database\Query\Grammars\SQLiteGrammar; + $builder = $this->getBuilder(); + $builder->from('users'); + $this->assertEquals(array( + 'delete from sqlite_sequence where name = ?' => array('users'), + 'delete from "users"' => array(), + ), $sqlite->compileTruncate($builder)); + } + + public function testMySqlWrapping() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users'); + $this->assertEquals('select * from `users`', $builder->toSql()); + } + + + public function testSQLiteOrderBy() + { + $builder = $this->getSQLiteBuilder(); + $builder->select('*')->from('users')->orderBy('email', 'desc'); + $this->assertEquals('select * from "users" order by "email" desc', $builder->toSql()); + } + + + public function testSqlServerLimitsAndOffsets() + { + $builder = $this->getSqlServerBuilder(); + $builder->select('*')->from('users')->limit(10); + $this->assertEquals('select top 10 * from [users]', $builder->toSql()); + + $builder = $this->getSqlServerBuilder(); + $builder->select('*')->from('users')->offset(10); + $this->assertEquals('select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num >= 11', $builder->toSql()); + + $builder = $this->getSqlServerBuilder(); + $builder->select('*')->from('users')->offset(10)->limit(10); + $this->assertEquals('select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num between 11 and 20', $builder->toSql()); + + $builder = $this->getSqlServerBuilder(); + $builder->select('*')->from('users')->offset(10)->limit(10)->orderBy('email', 'desc'); + $this->assertEquals('select * from (select *, row_number() over (order by [email] desc) as row_num from [users]) as temp_table where row_num between 11 and 20', $builder->toSql()); + } + + + public function testMergeWheresCanMergeWheresAndBindings() + { + $builder = $this->getBuilder(); + $builder->wheres = array('foo'); + $builder->mergeWheres(array('wheres'), array(12 => 'foo', 13 => 'bar')); + $this->assertEquals(array('foo', 'wheres'), $builder->wheres); + $this->assertEquals(array('foo', 'bar'), $builder->getBindings()); + } + + + public function testProvidingNullOrFalseAsSecondParameterBuildsCorrectly() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->where('foo', null); + $this->assertEquals('select * from "users" where "foo" is null', $builder->toSql()); + } + + + /** + * @expectedException BadMethodCallException + */ + public function testBuilderThrowsExpectedExceptionWithUndefinedMethod() + { + $builder = $this->getBuilder(); + + $builder->noValidMethodHere(); + } + + + public function setupCacheTestQuery($cache, $driver) + { + $connection = m::mock('Database\ConnectionInterface'); + $connection->shouldReceive('getName')->andReturn('connection_name'); + $connection->shouldReceive('getCacheManager')->once()->andReturn($cache); + $cache->shouldReceive('driver')->once()->andReturn($driver); + $grammar = new Database\Query\Grammars\Grammar; + $processor = m::mock('Database\Query\Processors\Processor'); + + $builder = $this->createMock('Database\Query\Builder', array('getFresh'), array($connection, $grammar, $processor)); + $builder->expects($this->once())->method('getFresh')->with($this->equalTo(array('*')))->will($this->returnValue(array('results'))); + return $builder->select('*')->from('users')->where('email', 'foo@bar.com'); + } + + public function testMySqlRollup() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->groupBy('foo', 'bar')->withRollUp(); + $this->assertEquals('select * from `foo` where `bar` = ? group by `foo`, `bar` with rollup', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + } + + public function testMySqlRollupIsIgnoredWithoutGroupBy() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->withRollUp(); + $this->assertEquals('select * from `foo` where `bar` = ?', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + } + + public function testMySqlLock() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(); + $this->assertEquals('select * from `foo` where `bar` = ? for update', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false); + $this->assertEquals('select * from `foo` where `bar` = ? lock in share mode', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + } + + public function testMySqlOutfile() + { + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with( + 'select * into outfile \'filename\' from `foo` where `bar` = ?', + array('baz') + ); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->intoOutfile('filename')->query(); + } + + public function testMySqlOutfileWithParams() + { + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with( + "select * into outfile 'filename' character set binary fields terminated by ',' optionally enclosed by '.' escaped by '\' lines terminated by '\n\r' from `foo` where `bar` = ?", + array('baz') + ); + + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->intoOutfile('filename', function (\Database\Query\OutfileClause $of) { + $of->enclosedBy(".", true) + ->escapedBy("\\") + ->characterSet('binary') + ->linesTerminatedBy("\n\r") + ->fieldsTerminatedBy(','); + })->query(); + } + + public function testMySqlDumpfile() + { + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('query')->once()->with( + "select * into dumpfile 'filename' from `foo` where `bar` = ?", + array('baz') + ); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->intoDumpfile('filename')->query(); + } + + public function testBasicInfile() + { + $builder = $this->getMySqlBuilder(); + + $filepath = 'bizbazbar'; + $tablename = 'foo'; + + $builder->getConnection()->shouldReceive('query')->once()->with( + "load data infile '$filepath' into table `$tablename` (`col1`, col2, `col3`)", + array()); + + $builder + ->from($tablename) + ->infile($filepath, array('col1', new \Database\Query\Expression('col2'), 'col3')); + } + + public function testInfile() + { + $builder = $this->getMySqlBuilder(); + + $filepath = 'bizbazbar'; + $tablename = 'foo'; + + $builder->getConnection()->shouldReceive('query')->once()->with( + "load data infile '$filepath' ignore into table `$tablename` character set utf8 fields terminated by ',' enclosed by '.' escaped by '\' lines starting by '$' terminated by '\n\r' ignore 4 lines (`col1`, col2, `col3`) set `fizz` = baz + 1, `buzz` = ?", + array('bar') + ); + + $builder + ->from($tablename) + ->infile($filepath, array('col1', new \Database\Query\Expression('col2'), 'col3'), function (\Database\Query\InfileClause $if) { + $if + ->ignore() + ->rules(array( + 'fizz' => new \Database\Query\Expression('baz + 1'), + 'buzz' => 'bar', + )) + ->characterSet('utf8') + ->enclosedBy(".") + ->escapedBy("\\") + ->linesStartingBy('$') + ->linesTerminatedBy("\n\r") + ->ignoreLines(4) + ->fieldsTerminatedBy(','); + }); + } + + public function testPostgresLock() + { + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(); + $this->assertEquals('select * from "foo" where "bar" = ? for update', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + + $builder = $this->getPostgresBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false); + $this->assertEquals('select * from "foo" where "bar" = ? for share', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + } + + + public function testSqlServerLock() + { + $builder = $this->getSqlServerBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(); + $this->assertEquals('select * from [foo] with(rowlock,updlock,holdlock) where [bar] = ?', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + + $builder = $this->getSqlServerBuilder(); + $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false); + $this->assertEquals('select * from [foo] with(rowlock,holdlock) where [bar] = ?', $builder->toSql()); + $this->assertEquals(array('baz'), $builder->getBindings()); + } + + + public function testBindingOrder() + { + $expectedSql = 'select * from "users" inner join "othertable" on "bar" = ? where "registered" = ? group by "city" having "population" > ? order by match ("foo") against(?)'; + $expectedBindings = array('foo', 1, 3, 'bar'); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->join('othertable', function ($join) { + $join->where('bar', '=', 'foo'); + })->where('registered', 1)->groupBy('city')->having('population', '>', 3)->orderByRaw('match ("foo") against(?)', array('bar')); + $this->assertEquals($expectedSql, $builder->toSql()); + $this->assertEquals($expectedBindings, $builder->getBindings()); + + // order of statements reversed + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->orderByRaw('match ("foo") against(?)', array('bar'))->having('population', '>', 3)->groupBy('city')->where('registered', 1)->join('othertable', function ($join) { + $join->where('bar', '=', 'foo'); + }); + $this->assertEquals($expectedSql, $builder->toSql()); + $this->assertEquals($expectedBindings, $builder->getBindings()); + } + + + public function testAddBindingWithArrayMergesBindings() + { + $builder = $this->getBuilder(); + $builder->addBinding(array('foo', 'bar')); + $builder->addBinding(array('baz')); + $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); + } + + + public function testAddBindingWithArrayMergesBindingsInCorrectOrder() + { + $builder = $this->getBuilder(); + $builder->addBinding(array('bar', 'baz'), 'having'); + $builder->addBinding(array('foo'), 'where'); + $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); + } + + + public function testMergeBuilders() + { + $builder = $this->getBuilder(); + $builder->addBinding(array('foo', 'bar')); + $otherBuilder = $this->getBuilder(); + $otherBuilder->addBinding(array('baz')); + $builder->mergeBindings($otherBuilder); + $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); + } + + + public function testMergeBuildersBindingOrder() + { + $builder = $this->getBuilder(); + $builder->addBinding('foo', 'where'); + $builder->addBinding('baz', 'having'); + $otherBuilder = $this->getBuilder(); + $otherBuilder->addBinding('bar', 'where'); + $builder->mergeBindings($otherBuilder); + $this->assertEquals(array('foo', 'bar', 'baz'), $builder->getBindings()); + } public function testCountAllRowsBacksUpLimitsOffsetsAndOrders() { @@ -1286,7 +1277,7 @@ public function testCountAllRowsBacksUpLimitsOffsetsAndOrders() $builder->from('users')->orderBy('baz')->offset(5)->limit(1); - $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"',array()) + $builder->getConnection()->shouldReceive('fetchAll')->once()->with('select count(*) as aggregate from "users"', array()) ->andReturn(array(array('aggregate' => 10))); $this->assertEquals(10, $builder->getTotalRowCount()); @@ -1334,38 +1325,37 @@ public function testSettingInvalidBindingThrowsException() $builder->setBindings(array(1), 'non-existent'); } - protected function getBuilder() - { - $grammar = new Database\Query\Grammars\Grammar; - return new Builder(m::mock('Database\ConnectionInterface'), $grammar); - } - + protected function getBuilder() + { + $grammar = new Database\Query\Grammars\Grammar; + return new Builder(m::mock('Database\ConnectionInterface'), $grammar); + } - protected function getPostgresBuilder() - { - $grammar = new Database\Query\Grammars\PostgresGrammar; - return new Builder(m::mock('Database\ConnectionInterface'), $grammar); - } + protected function getPostgresBuilder() + { + $grammar = new Database\Query\Grammars\PostgresGrammar; + return new Builder(m::mock('Database\ConnectionInterface'), $grammar); + } - protected function getMySqlBuilder() - { - $grammar = new Database\Query\Grammars\MySqlGrammar; - return new Builder(m::mock('Database\ConnectionInterface'), $grammar); - } + protected function getMySqlBuilder() + { + $grammar = new Database\Query\Grammars\MySqlGrammar; + return new Builder(m::mock('Database\ConnectionInterface'), $grammar); + } - protected function getSQLiteBuilder() - { - $grammar = new Database\Query\Grammars\SQLiteGrammar; - return new Builder(m::mock('Database\ConnectionInterface'), $grammar); - } + protected function getSQLiteBuilder() + { + $grammar = new Database\Query\Grammars\SQLiteGrammar; + return new Builder(m::mock('Database\ConnectionInterface'), $grammar); + } - protected function getSqlServerBuilder() - { - $grammar = new Database\Query\Grammars\SqlServerGrammar; - return new Builder(m::mock('Database\ConnectionInterface'), $grammar); - } + protected function getSqlServerBuilder() + { + $grammar = new Database\Query\Grammars\SqlServerGrammar; + return new Builder(m::mock('Database\ConnectionInterface'), $grammar); + } } diff --git a/tests/unit/Database/ExpressionTest.php b/tests/unit/Database/ExpressionTest.php index 579bf39..8d3d995 100755 --- a/tests/unit/Database/ExpressionTest.php +++ b/tests/unit/Database/ExpressionTest.php @@ -1,9 +1,9 @@ 'bar')), array('message2', array('bar' => 'foo')), ); - public function testItStoresAndLogsQueries() - { - $log = new \Database\QueryLogger(); + public function testItStoresAndLogsQueries() + { + $log = new \Database\QueryLogger(); - foreach($this->logMessages as $messages) - { + foreach ($this->logMessages as $messages) { $log->debug($messages[0], $messages[1]); } @@ -20,17 +19,16 @@ public function testItStoresAndLogsQueries() // Should be able to fetch the messages more than once $this->assertEquals($this->logMessages, $log->getQueryLog()); - } + } public function testItFlushesQueries() - { - $log = new \Database\QueryLogger(); + { + $log = new \Database\QueryLogger(); - foreach($this->logMessages as $messages) - { + foreach ($this->logMessages as $messages) { $log->debug($messages[0], $messages[1]); } $this->assertEquals(array(), $log->flushQueryLog()->getQueryLog()); - } + } }