Browse Source

Translating IS operator to the best possible operator depending on value

Jose Lorenzo Rodriguez 11 years ago
parent
commit
f15a6f58d5
2 changed files with 33 additions and 1 deletions
  1. 10 1
      src/Database/Expression/QueryExpression.php
  2. 23 0
      tests/TestCase/Database/QueryTest.php

+ 10 - 1
src/Database/Expression/QueryExpression.php

@@ -488,9 +488,10 @@ class QueryExpression implements ExpressionInterface, Countable {
 
 		$type = $this->typeMap()->type($expression);
 		$multi = false;
+		$operator = strtolower(trim($operator));
 
 		$typeMultiple = strpos($type, '[]') !== false;
-		if (in_array(strtolower(trim($operator)), ['in', 'not in']) || $typeMultiple) {
+		if (in_array($operator, ['in', 'not in']) || $typeMultiple) {
 			$type = $type ?: 'string';
 			$type .= $typeMultiple ? null : '[]';
 			$operator = $operator === '=' ? 'IN' : $operator;
@@ -502,6 +503,14 @@ class QueryExpression implements ExpressionInterface, Countable {
 			$value = $value instanceof ExpressionInterface ? $value : (array)$value;
 		}
 
+		if ($operator === 'is' && $value === null) {
+			return new UnaryExpression('IS NULL', $expression, UnaryExpression::POSTFIX);
+		}
+
+		if ($operator === 'is' && $value !== null) {
+			$operator = '=';
+		}
+
 		return new Comparison($expression, $value, $type, $operator);
 	}
 

+ 23 - 0
tests/TestCase/Database/QueryTest.php

@@ -2694,6 +2694,29 @@ class QueryTest extends TestCase {
 	}
 
 /**
+ * Tests that using the IS operator will automatically translate to the best
+ * possible operator depending on the passed value
+ *
+ * @return void
+ */
+	public function testDirectIsNull() {
+		$sql = (new Query($this->connection))
+			->select(['name'])
+			->from(['authors'])
+			->where(['name IS' => null])
+			->sql();
+		$this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, true);
+
+		$results = (new Query($this->connection))
+			->select(['name'])
+			->from(['authors'])
+			->where(['name IS' => 'larry'])
+			->execute();
+		$this->assertCount(1, $results);
+		$this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
+	}
+
+/**
  * Assertion for comparing a table's contents with what is in it.
  *
  * @param string $table