From faf67c824bdfd458e0b120bf978564a650317fa1 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Sun, 16 Feb 2014 14:56:22 +0100 Subject: [PATCH] Fixed Query::set() to apply field types when an array is passed, closes #2836 --- src/Database/Query.php | 18 ++++++++++------- tests/TestCase/Database/QueryTest.php | 29 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/Database/Query.php b/src/Database/Query.php index 5cfdf40e79d..9c860efef6b 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -1424,14 +1424,18 @@ public function set($key, $value = null, $types = []) { if (empty($this->_parts['set'])) { $this->_parts['set'] = $this->newExpr()->type(','); } - if (is_array($key) || $key instanceof QueryExpression) { - $this->_parts['set']->add($key, (array)$value); - } else { - if (is_string($types)) { - $types = [$key => $types]; - } - $this->_parts['set']->add([$key => $value], $types + $this->defaultTypes()); + + if (is_array($key) || $key instanceof ExpressionInterface) { + $types = (array)$value; + $this->_parts['set']->add($key, $types + $this->defaultTypes()); + return $this; } + + if (is_string($types) && is_string($key)) { + $types = [$key => $types]; + } + $this->_parts['set']->eq($key, $value, $types + $this->defaultTypes()); + return $this; } diff --git a/tests/TestCase/Database/QueryTest.php b/tests/TestCase/Database/QueryTest.php index 9f61d34438f..502dbd615cb 100644 --- a/tests/TestCase/Database/QueryTest.php +++ b/tests/TestCase/Database/QueryTest.php @@ -1817,6 +1817,35 @@ public function testUpdateWithExpression() { $this->assertCount(1, $result); } +/** + * Test update with array fields and types. + * + * @return void + */ + public function testUpdateArrayFields() { + $query = new Query($this->connection); + $date = new \DateTime; + $query->update('comments') + ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date']) + ->where(['id' => 1]); + $result = $query->sql(); + + $this->assertQuotedQuery( + 'UPDATE SET = :c0 , = :c1', + $result, + true + ); + + $this->assertQuotedQuery(' WHERE = :c2$', $result, true); + $result = $query->execute(); + $this->assertCount(1, $result); + + $query = new Query($this->connection); + $result = $query->select('created')->from('comments')->where(['id' => 1])->execute(); + $result = $result->fetchAll('assoc')[0]['created']; + $this->assertEquals($date->format('Y-m-d'), $result); + } + /** * You cannot call values() before insert() it causes all sorts of pain. *