forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPreparedQueryTest.php
307 lines (238 loc) · 10.9 KB
/
PreparedQueryTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\Live;
use BadMethodCallException;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Query;
use CodeIgniter\Database\ResultInterface;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use PHPUnit\Framework\Attributes\Group;
use Tests\Support\Database\Seeds\CITestSeeder;
/**
* @internal
*/
#[Group('DatabaseLive')]
final class PreparedQueryTest extends CIUnitTestCase
{
use DatabaseTestTrait;
protected $seed = CITestSeeder::class;
private ?BasePreparedQuery $query = null;
protected function setUp(): void
{
parent::setUp();
$this->query = null;
}
protected function tearDown(): void
{
parent::tearDown();
try {
$this->query->close();
} catch (BadMethodCallException) {
$this->query = null;
}
}
public function testPrepareReturnsPreparedQuery(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => '[email protected]',
'country' => 'JP',
]));
$this->assertInstanceOf(BasePreparedQuery::class, $this->query);
$ec = $this->db->escapeChar;
$pre = $this->db->DBPrefix;
$placeholders = '?, ?, ?';
if ($this->db->DBDriver === 'Postgre') {
$placeholders = '$1, $2, $3';
}
if ($this->db->DBDriver === 'SQLSRV') {
$database = $this->db->getDatabase();
$expected = "INSERT INTO {$ec}{$database}{$ec}.{$ec}{$this->db->schema}{$ec}.{$ec}{$pre}user{$ec} ({$ec}name{$ec},{$ec}email{$ec},{$ec}country{$ec}) VALUES ({$placeholders})";
} else {
$expected = "INSERT INTO {$ec}{$pre}user{$ec} ({$ec}name{$ec}, {$ec}email{$ec}, {$ec}country{$ec}) VALUES ({$placeholders})";
}
$this->assertSame($expected, $this->query->getQueryString());
}
public function testPrepareReturnsManualPreparedQuery(): void
{
$this->query = $this->db->prepare(static function ($db) {
$sql = "INSERT INTO {$db->protectIdentifiers($db->DBPrefix . 'user')} ("
. $db->protectIdentifiers('name') . ', '
. $db->protectIdentifiers('email') . ', '
. $db->protectIdentifiers('country')
. ') VALUES (?, ?, ?)';
return (new Query($db))->setQuery($sql);
});
$this->assertInstanceOf(BasePreparedQuery::class, $this->query);
$ec = $this->db->escapeChar;
$pre = $this->db->DBPrefix;
$placeholders = '?, ?, ?';
if ($this->db->DBDriver === 'Postgre') {
$placeholders = '$1, $2, $3';
}
$expected = "INSERT INTO {$ec}{$pre}user{$ec} ({$ec}name{$ec}, {$ec}email{$ec}, {$ec}country{$ec}) VALUES ({$placeholders})";
$this->assertSame($expected, $this->query->getQueryString());
}
public function testExecuteRunsQueryAndReturnsTrue(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => '[email protected]',
'country' => 'x',
]));
$this->assertTrue($this->query->execute('foo', '[email protected]', 'US'));
$this->assertTrue($this->query->execute('bar', '[email protected]', 'GB'));
$this->dontSeeInDatabase($this->db->DBPrefix . 'user', ['name' => 'a', 'email' => '[email protected]']);
$this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'foo', 'email' => '[email protected]']);
$this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'bar', 'email' => '[email protected]']);
}
public function testExecuteRunsQueryManualAndReturnsTrue(): void
{
$this->query = $this->db->prepare(static function ($db) {
$sql = "INSERT INTO {$db->protectIdentifiers($db->DBPrefix . 'user')} ("
. $db->protectIdentifiers('name') . ', '
. $db->protectIdentifiers('email') . ', '
. $db->protectIdentifiers('country')
. ') VALUES (?, ?, ?)';
return (new Query($db))->setQuery($sql);
});
$this->assertTrue($this->query->execute('foo', '[email protected]', 'US'));
$this->assertTrue($this->query->execute('bar', '[email protected]', 'GB'));
$this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'foo', 'email' => '[email protected]']);
$this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'bar', 'email' => '[email protected]']);
}
public function testExecuteRunsQueryAndReturnsFalse(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('without_auto_increment')->insert([
'key' => 'a',
'value' => 'b',
]));
$this->disableDBDebug();
$this->assertTrue($this->query->execute('foo1', 'bar'));
$this->assertFalse($this->query->execute('foo1', 'baz'));
$this->enableDBDebug();
$this->seeInDatabase($this->db->DBPrefix . 'without_auto_increment', ['key' => 'foo1', 'value' => 'bar']);
$this->dontSeeInDatabase($this->db->DBPrefix . 'without_auto_increment', ['key' => 'foo1', 'value' => 'baz']);
}
public function testExecuteRunsQueryManualAndReturnsFalse(): void
{
$this->query = $this->db->prepare(static function ($db) {
$sql = "INSERT INTO {$db->protectIdentifiers($db->DBPrefix . 'without_auto_increment')} ("
. $db->protectIdentifiers('key') . ', '
. $db->protectIdentifiers('value')
. ') VALUES (?, ?)';
return (new Query($db))->setQuery($sql);
});
$this->disableDBDebug();
$this->assertTrue($this->query->execute('foo1', 'bar'));
$this->assertFalse($this->query->execute('foo1', 'baz'));
$this->enableDBDebug();
$this->seeInDatabase($this->db->DBPrefix . 'without_auto_increment', ['key' => 'foo1', 'value' => 'bar']);
$this->dontSeeInDatabase($this->db->DBPrefix . 'without_auto_increment', ['key' => 'foo1', 'value' => 'baz']);
}
public function testExecuteSelectQueryAndCheckTypeAndResult(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->select('name, email, country')->where([
'name' => 'foo',
])->get());
$result = $this->query->execute('Derek Jones');
$this->assertInstanceOf(ResultInterface::class, $result);
$expectedRow = ['name' => 'Derek Jones', 'email' => '[email protected]', 'country' => 'US'];
$this->assertSame($expectedRow, $result->getRowArray());
}
public function testExecuteSelectQueryManualAndCheckTypeAndResult(): void
{
$this->query = $this->db->prepare(static function ($db) {
$sql = 'SELECT '
. $db->protectIdentifiers('name') . ', '
. $db->protectIdentifiers('email') . ', '
. $db->protectIdentifiers('country') . ' '
. "FROM {$db->protectIdentifiers($db->DBPrefix . 'user')}"
. "WHERE {$db->protectIdentifiers('name')} = ?";
return (new Query($db))->setQuery($sql);
});
$result = $this->query->execute('Derek Jones');
$this->assertInstanceOf(ResultInterface::class, $result);
$expectedRow = ['name' => 'Derek Jones', 'email' => '[email protected]', 'country' => 'US'];
$this->assertSame($expectedRow, $result->getRowArray());
}
public function testExecuteRunsInvalidQuery(): void
{
$this->expectException(DatabaseException::class);
// Not null `country` is missing
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => '[email protected]',
]));
$this->query->execute('foo', '[email protected]', 'US');
}
public function testDeallocatePreparedQueryThenTryToExecute(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => '[email protected]',
'country' => 'x',
]));
$this->query->close();
// Try to execute a non-existing prepared statement
$this->expectException(BadMethodCallException::class);
$this->expectExceptionMessage('You must call prepare before trying to execute a prepared statement.');
$this->query->execute('bar', '[email protected]', 'GB');
}
public function testDeallocatePreparedQueryThenTryToClose(): void
{
$this->query = $this->db->prepare(
static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => '[email protected]',
'country' => 'x',
])
);
$this->query->close();
// Try to close a non-existing prepared statement
$this->expectException(BadMethodCallException::class);
$this->expectExceptionMessage(
'Cannot call close on a non-existing prepared statement.'
);
$this->query->close();
}
public function testInsertBinaryData(): void
{
$params = [];
if ($this->db->DBDriver === 'SQLSRV') {
$params = [0 => SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY)];
}
$this->query = $this->db->prepare(static fn ($db) => $db->table('type_test')->insert([
'type_blob' => 'binary',
]), $params);
$fileContent = file_get_contents(TESTPATH . '_support/Images/EXIFsamples/landscape_0.jpg');
$this->assertTrue($this->query->execute($fileContent));
$id = $this->db->DBDriver === 'SQLSRV'
// It seems like INSERT for a prepared statement is run in the
// separate execution context even though it's part of the same session
? (int) ($this->db->query('SELECT @@IDENTITY AS insert_id')->getRow()->insert_id ?? 0)
: $this->db->insertID();
$builder = $this->db->table('type_test');
if ($this->db->DBDriver === 'Postgre') {
$file = $builder->select("ENCODE(type_blob, 'base64') AS type_blob")->where('id', $id)->get()->getRow();
$file = base64_decode($file->type_blob, true);
} elseif ($this->db->DBDriver === 'OCI8') {
$file = $builder->select('type_blob')->where('id', $id)->get()->getRow();
$file = $file->type_blob->load();
} else {
$file = $builder->select('type_blob')->where('id', $id)->get()->getRow();
$file = $file->type_blob;
}
$this->assertSame(strlen($fileContent), strlen($file));
}
}