1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Db\Tests\Support; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Cache\ArrayCache; |
8
|
|
|
use Yiisoft\Cache\Cache; |
9
|
|
|
use Yiisoft\Cache\CacheInterface; |
10
|
|
|
use Yiisoft\Db\Cache\QueryCache; |
11
|
|
|
use Yiisoft\Db\Cache\SchemaCache; |
12
|
|
|
use Yiisoft\Db\Driver\PDO\ConnectionPDOInterface; |
13
|
|
|
use Yiisoft\Db\Exception\Exception; |
14
|
|
|
use Yiisoft\Db\Exception\InvalidConfigException; |
15
|
|
|
|
16
|
|
|
use function explode; |
17
|
|
|
use function file_get_contents; |
18
|
|
|
use function preg_replace; |
19
|
|
|
use function str_replace; |
20
|
|
|
use function trim; |
21
|
|
|
|
22
|
|
|
final class DbHelper |
23
|
|
|
{ |
24
|
|
|
public static function getCache(): CacheInterface |
25
|
|
|
{ |
26
|
|
|
return new Cache(new ArrayCache()); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public static function getQueryCache(): QueryCache |
30
|
|
|
{ |
31
|
|
|
return new QueryCache(self::getCache()); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public static function getSchemaCache(): SchemaCache |
35
|
|
|
{ |
36
|
|
|
return new SchemaCache(self::getCache()); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Loads the fixture into the database. |
41
|
|
|
* |
42
|
|
|
* @throws Exception |
43
|
|
|
* @throws InvalidConfigException |
44
|
|
|
*/ |
45
|
|
|
public static function loadFixture(ConnectionPDOInterface $db, string $fixture): void |
46
|
|
|
{ |
47
|
|
|
$db->open(); |
48
|
|
|
$lines = explode(';', file_get_contents($fixture)); |
49
|
|
|
|
50
|
|
|
foreach ($lines as $line) { |
51
|
|
|
if (trim($line) !== '') { |
52
|
|
|
$db->getPDO()?->exec($line); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Adjust dbms specific escaping. |
59
|
|
|
* |
60
|
|
|
* @param string $sql string SQL statement to adjust. |
61
|
|
|
* @param string $driverName string DBMS name. |
62
|
|
|
* |
63
|
|
|
* @return mixed |
64
|
|
|
*/ |
65
|
|
|
public static function replaceQuotes(string $sql, string $driverName): string |
66
|
|
|
{ |
67
|
|
|
return match ($driverName) { |
68
|
|
|
'mysql', 'sqlite' => str_replace(['[[', ']]'], '`', $sql), |
69
|
|
|
'oci' => str_replace(['[[', ']]'], '"', $sql), |
70
|
|
|
'pgsql' => str_replace(['\\[', '\\]'], ['[', ']'], preg_replace('/(\[\[)|((?<!(\[))]])/', '"', $sql)), |
71
|
|
|
'db', 'sqlsrv' => str_replace(['[[', ']]'], ['[', ']'], $sql), |
72
|
|
|
default => $sql, |
73
|
|
|
}; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|