Permalink
Browse files

Improving TupleComparison

  • Loading branch information...
lorenzo committed Jan 11, 2014
1 parent 923cf27 commit 2585a8f97bc0c9af8e74502ad4dfed03c6f5a290
@@ -14,7 +14,8 @@
*/
namespace Cake\Database\Expression;
-use Cake\Database\Expression\Compariso;
+use Cake\Database\Expression\Comparison;
+use Cake\Database\ExpressionInterface;
use Cake\Database\ValueBinder;
/**
@@ -44,15 +45,25 @@ public function __construct($field, $value, $type = [], $conjuntion = '=') {
*/
public function sql(ValueBinder $generator) {
$template = '(%s) %s (%s)';
- $values = [];
+ $values = $fields = [];
+
+ foreach ((array)$this->getField() as $field) {
+ $fields[] = $field instanceof ExpressionInterface ? $field->sql($generator) : $field;
+ }
+
foreach ($this->getValue() as $i => $value) {
+ if ($value instanceof ExpressionInterface) {
+ $values[] = $value->sql($generator);
+ continue;
+ }
$values[] = $this->_bindValue(
$generator,
$value,
isset($this->_type[$i]) ? $this->_type[$i] : null
);
}
- $field = implode(', ', (array)$this->getField());
+
+ $field = implode(', ', $fields);
return sprintf($template, $field, $this->_conjunction, implode(', ', $values));
}
@@ -15,6 +15,7 @@
namespace Cake\Test\TestCase\Database\Expression;
use Cake\Database\Expression\TupleComparison;
+use Cake\Database\Expression\QueryExpression;
use Cake\Database\ValueBinder;
use Cake\TestSuite\TestCase;
@@ -39,4 +40,34 @@ public function testsSimpleTuple() {
$this->assertSame('integer', $binder->bindings()[':c1']['type']);
}
+/**
+ * Tests generating tuples in the fields side containing expressions
+ *
+ * @return void
+ */
+ public function testTupleWithExpressionFields() {
+ $field1 = new QueryExpression(['a' => 1]);
+ $f = new TupleComparison([$field1, 'field2'], [4, 5], ['integer', 'integer'], '>');
+ $binder = new ValueBinder;
+ $this->assertEquals('(a = :c0, field2) > (:c1, :c2)', $f->sql($binder));
+ $this->assertSame(1, $binder->bindings()[':c0']['value']);
+ $this->assertSame(4, $binder->bindings()[':c1']['value']);
+ $this->assertSame(5, $binder->bindings()[':c2']['value']);
+ }
+
+/**
+ * Tests generating tuples in the values side containing expressions
+ *
+ * @return void
+ */
+ public function testTupleWithExpressionValues() {
+ $value1 = new QueryExpression(['a' => 1]);
+ $f = new TupleComparison(['field1', 'field2'], [$value1, 2], ['integer', 'integer'], '=');
+ $binder = new ValueBinder;
+ $this->assertEquals('(field1, field2) = (a = :c0, :c1)', $f->sql($binder));
+ $this->assertSame(1, $binder->bindings()[':c0']['value']);
+ $this->assertSame(2, $binder->bindings()[':c1']['value']);
+ }
+
+
}

0 comments on commit 2585a8f

Please sign in to comment.