forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPreparedQueryTest.php
More file actions
415 lines (320 loc) · 15.2 KB
/
PreparedQueryTest.php
File metadata and controls
415 lines (320 loc) · 15.2 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\Live;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Query;
use CodeIgniter\Database\ResultInterface;
use CodeIgniter\Exceptions\BadMethodCallException;
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();
if (! $this->query instanceof BasePreparedQuery) {
return;
}
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' => 'b@example.com',
'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): Query {
$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 testPrepareAndExecuteManualQueryWithNamedPlaceholdersKeepsTimeLiteral(): void
{
// Quote alias to keep a consistent property name across drivers (OCI8 uppercases unquoted aliases)
$timeValue = $this->db->protectIdentifiers('time_value');
$this->query = $this->db->prepare(static function ($db) use ($timeValue): Query {
$sql = 'SELECT '
. $db->protectIdentifiers('name') . ', '
. $db->protectIdentifiers('email')
. ", '12:34' AS " . $timeValue . ' '
. 'FROM ' . $db->protectIdentifiers($db->DBPrefix . 'user')
. ' WHERE '
. $db->protectIdentifiers('name') . ' = :name:'
. ' AND ' . $db->protectIdentifiers('email') . ' = :email';
return (new Query($db))->setQuery($sql);
});
$preparedSql = $this->query->getQueryString();
$this->assertStringContainsString("'12:34' AS " . $timeValue, $preparedSql);
if ($this->db->DBDriver === 'Postgre') {
$this->assertStringContainsString(' = $1', $preparedSql);
$this->assertStringContainsString(' = $2', $preparedSql);
} else {
$this->assertStringContainsString(' = ?', $preparedSql);
}
$result = $this->query->execute('Derek Jones', 'derek@world.com');
$this->assertInstanceOf(ResultInterface::class, $result);
$this->assertSame('Derek Jones', $result->getRow()->name);
$this->assertSame('derek@world.com', $result->getRow()->email);
$this->assertSame('12:34', $result->getRow()->time_value);
}
public function testPrepareAndExecuteManualQueryWithPostgreCastKeepsDoubleColonSyntax(): void
{
if ($this->db->DBDriver !== 'Postgre') {
$this->markTestSkipped('PostgreSQL-specific cast syntax test.');
}
$this->query = $this->db->prepare(static function ($db): Query {
$sql = 'SELECT '
. ':value: AS value, now()::timestamp AS created_at'
. ' FROM ' . $db->protectIdentifiers($db->DBPrefix . 'user')
. ' WHERE ' . $db->protectIdentifiers('name') . ' = :name:';
return (new Query($db))->setQuery($sql);
});
$preparedSql = $this->query->getQueryString();
$this->assertStringContainsString('$1 AS value', $preparedSql);
$this->assertStringContainsString('now()::timestamp AS created_at', $preparedSql);
$result = $this->query->execute('ci4', 'Derek Jones');
$this->assertInstanceOf(ResultInterface::class, $result);
$this->assertSame('ci4', $result->getRow()->value);
$this->assertNotEmpty($result->getRow()->created_at);
$this->assertNotSame('now()::timestamp', $result->getRow()->created_at);
}
public function testExecuteRunsQueryAndReturnsTrue(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => 'b@example.com',
'country' => 'x',
]));
$this->assertTrue($this->query->execute('foo', 'foo@example.com', 'US'));
$this->assertTrue($this->query->execute('bar', 'bar@example.com', 'GB'));
$this->dontSeeInDatabase($this->db->DBPrefix . 'user', ['name' => 'a', 'email' => 'b@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']);
}
public function testExecuteRunsQueryManualAndReturnsTrue(): void
{
$this->query = $this->db->prepare(static function ($db): Query {
$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', 'foo@example.com', 'US'));
$this->assertTrue($this->query->execute('bar', 'bar@example.com', 'GB'));
$this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'foo', 'email' => 'foo@example.com']);
$this->seeInDatabase($this->db->DBPrefix . 'user', ['name' => 'bar', 'email' => 'bar@example.com']);
}
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): Query {
$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' => 'derek@world.com', 'country' => 'US'];
$this->assertSame($expectedRow, $result->getRowArray());
}
public function testExecuteSelectQueryManualAndCheckTypeAndResult(): void
{
$this->query = $this->db->prepare(static function ($db): Query {
$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' => 'derek@world.com', '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' => 'b@example.com',
]));
$this->query->execute('foo', 'foo@example.com', 'US');
}
public function testDeallocatePreparedQueryThenTryToExecute(): void
{
$this->query = $this->db->prepare(static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => 'b@example.com',
'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', 'bar@example.com', 'GB');
}
public function testDeallocatePreparedQueryThenTryToClose(): void
{
$this->query = $this->db->prepare(
static fn ($db) => $db->table('user')->insert([
'name' => 'a',
'email' => 'b@example.com',
'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));
}
public function testHandleTransStatusMarksTransactionFailedDuringTransaction(): void
{
$this->db->transStart();
// Verify we're in a transaction
$this->assertSame(1, $this->db->transDepth);
// Prepare a query that will fail (duplicate key)
$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('test_key', 'test_value'));
$this->assertTrue($this->db->transStatus());
$this->seeInDatabase($this->db->DBPrefix . 'without_auto_increment', [
'key' => 'test_key',
'value' => 'test_value',
]);
$this->assertFalse($this->query->execute('test_key', 'different_value'));
$this->assertFalse($this->db->transStatus());
$this->enableDBDebug();
// Complete the transaction - should rollback due to failed status
$this->assertFalse($this->db->transComplete());
// Verify the first insert was rolled back
$this->dontSeeInDatabase($this->db->DBPrefix . 'without_auto_increment', [
'key' => 'test_key',
'value' => 'test_value',
]);
$this->db->resetTransStatus();
}
}