Passed
Pull Request — master (#380)
by Wilmer
02:51
created

DbHelper::getCommmentsFromColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 3
dl 0
loc 20
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Tests\Support;
6
7
use Yiisoft\Db\Driver\PDO\ConnectionPDOInterface;
8
9
final class DbHelper
10
{
11
    public static function getCommmentsFromColumn(
12
        string $table,
13
        string $column,
14
        ConnectionPDOInterface $db
15
    ): array|string {
16
        $result = match ($db->getName()) {
17
            'sqlsrv' => $db->createCommand(
18
                <<<SQL
19
                SELECT *
20
                FROM fn_listextendedproperty (
21
                    N'MS_description',
22
                    'SCHEMA', N'dbo',
23
                    'TABLE', N{$db->getQuoter()->quoteValue($table)},
24
                    'COLUMN', N{$db->getQuoter()->quoteValue($column)}
25
                )
26
                SQL
27
            )->queryAll(),
28
        };
29
30
        return $result[0]['value'] ?? [];
31
    }
32
33
    public static function getCommmentsFromTable(
34
        string $table,
35
        ConnectionPDOInterface $db
36
    ): array|string {
37
        $result = match ($db->getName()) {
38
            'sqlsrv' => $db->createCommand(
39
                <<<SQL
40
                SELECT *
41
                FROM fn_listextendedproperty (
42
                    N'MS_description',
43
                    'SCHEMA', N'dbo',
44
                    'TABLE', N{$db->getQuoter()->quoteValue($table)},
45
                    DEFAULT, DEFAULT
46
                )
47
                SQL
48
            )->queryAll(),
49
        };
50
51
        return $result[0]['value'] ?? [];
52
    }
53
54
    /**
55
     * Adjust dbms specific escaping.
56
     *
57
     * @param string $sql string SQL statement to adjust.
58
     * @param string $drivername string DBMS name.
59
     *
60
     * @return mixed
61
     */
62
    public static function replaceQuotes(string $sql, string $drivername): string
63
    {
64
        return match ($drivername) {
65
            'mysql', 'sqlite' => str_replace(['[[', ']]'], '`', $sql),
66
            'oci' => str_replace(['[[', ']]'], '"', $sql),
67
            'pgsql' => str_replace(['\\[', '\\]'], ['[', ']'], preg_replace('/(\[\[)|((?<!(\[))]])/', '"', $sql)),
68
            'sqlsrv' => str_replace(['[[', ']]'], ['[', ']'], $sql),
69
            default => $sql,
70
        };
71
    }
72
}
73