From 560e04817dca062fb21ecf3c1a165c4fbccb995f Mon Sep 17 00:00:00 2001 From: michalsn Date: Tue, 1 Sep 2020 21:03:45 +0200 Subject: [PATCH] Fix for setBinds() method to sets the proper format of array --- system/Database/Query.php | 15 ++++++- .../Database/Live/PreparedQueryTest.php | 43 +++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/system/Database/Query.php b/system/Database/Query.php index f0b44c514d37..5cdf7fe0c1d9 100644 --- a/system/Database/Query.php +++ b/system/Database/Query.php @@ -168,12 +168,23 @@ public function setQuery(string $sql, $binds = null, bool $setEscape = true) /** * Will store the variables to bind into the query later. * - * @param array $binds + * @param array $binds + * @param boolean $setEscape * * @return $this */ - public function setBinds(array $binds) + public function setBinds(array $binds, bool $setEscape = true) { + if ($setEscape) + { + array_walk($binds, function (&$item) { + $item = [ + $item, + true, + ]; + }); + } + $this->binds = $binds; return $this; diff --git a/tests/system/Database/Live/PreparedQueryTest.php b/tests/system/Database/Live/PreparedQueryTest.php index da72b7459b1a..003662526cb7 100644 --- a/tests/system/Database/Live/PreparedQueryTest.php +++ b/tests/system/Database/Live/PreparedQueryTest.php @@ -1,6 +1,7 @@ close(); } + public function testPrepareReturnsManualPreparedQuery() + { + $query = $this->db->prepare(function ($db) { + $sql = "INSERT INTO {$db->DBPrefix}user (name, email, country) VALUES (?, ?, ?)"; + + return (new Query($db))->setQuery($sql); + }); + + $this->assertInstanceOf(BasePreparedQuery::class, $query); + + $pre = $this->db->DBPrefix; + + $placeholders = '?, ?, ?'; + + if ($this->db->DBDriver === 'Postgre') + { + $placeholders = '$1, $2, $3'; + } + + $expected = "INSERT INTO {$pre}user (name, email, country) VALUES ({$placeholders})"; + $this->assertEquals($expected, $query->getQueryString()); + + $query->close(); + } + //-------------------------------------------------------------------- public function testExecuteRunsQueryAndReturnsResultObject() @@ -62,6 +88,23 @@ public function testExecuteRunsQueryAndReturnsResultObject() $query->close(); } + public function testExecuteRunsQueryAndReturnsManualResultObject() + { + $query = $this->db->prepare(function ($db) { + $sql = "INSERT INTO {$db->DBPrefix}user (name, email, country) VALUES (?, ?, ?)"; + + return (new Query($db))->setQuery($sql); + }); + + $query->execute('foo', 'foo@example.com', ''); + $query->execute('bar', 'bar@example.com', ''); + + $this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'foo', 'email' => 'foo@example.com']); + $this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'bar', 'email' => 'bar@example.com']); + + $query->close(); + } + //-------------------------------------------------------------------- }