TestUtil.php 6.65 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2

3
namespace Doctrine\DBAL\Tests;
romanb's avatar
romanb committed
4

5
use Doctrine\DBAL\Connection;
6
use Doctrine\DBAL\DriverManager;
7
use Doctrine\DBAL\Platforms\AbstractPlatform;
8
use Doctrine\DBAL\Platforms\OraclePlatform;
9
use PHPUnit\Framework\Assert;
10

11 12 13
use function array_keys;
use function array_map;
use function array_values;
14 15
use function explode;
use function extension_loaded;
16 17
use function implode;
use function is_string;
18
use function unlink;
19

romanb's avatar
romanb committed
20 21 22
/**
 * TestUtil is a class with static utility methods used during tests.
 */
23
class TestUtil
24
{
Sergei Morozov's avatar
Sergei Morozov committed
25
    /** @var bool Whether the database schema is initialized. */
26 27
    private static $initialized = false;

romanb's avatar
romanb committed
28
    /**
29
     * Creates a new <b>test</b> database connection using the following parameters
romanb's avatar
romanb committed
30
     * of the $GLOBALS array:
31
     *
32 33 34 35 36 37 38 39
     * 'db_driver':   The name of the Doctrine DBAL database driver to use.
     * 'db_user':     The username to use for connecting.
     * 'db_password': The password to use for connecting.
     * 'db_host':     The hostname of the database to connect to.
     * 'db_server':   The server name of the database to connect to
     *                (optional, some vendors allow multiple server instances with different names on the same host).
     * 'db_dbname':   The name of the database to connect to.
     * 'db_port':     The port of the database to connect to.
40
     *
romanb's avatar
romanb committed
41 42 43
     * Usually these variables of the $GLOBALS array are filled by PHPUnit based
     * on an XML configuration file. If no such parameters exist, an SQLite
     * in-memory database is used.
44
     *
45
     * @return Connection The database connection instance.
romanb's avatar
romanb committed
46
     */
47
    public static function getConnection(): Connection
romanb's avatar
romanb committed
48
    {
49 50 51 52 53
        if (self::hasRequiredConnectionParams() && ! self::$initialized) {
            self::initializeDatabase();
            self::$initialized = true;
        }

54
        $conn = DriverManager::getConnection(self::getConnectionParams());
55

56
        self::addDbEventSubscribers($conn);
57

58 59
        return $conn;
    }
60

61 62 63
    /**
     * @return mixed[]
     */
64
    public static function getConnectionParams(): array
Sergei Morozov's avatar
Sergei Morozov committed
65
    {
66
        if (self::hasRequiredConnectionParams()) {
67
            return self::getTestConnectionParameters();
68 69
        }

70
        return self::getFallbackConnectionParams();
romanb's avatar
romanb committed
71
    }
72

73
    private static function hasRequiredConnectionParams(): bool
74
    {
75
        return isset($GLOBALS['db_driver']);
76 77
    }

78
    private static function initializeDatabase(): void
Sergei Morozov's avatar
Sergei Morozov committed
79
    {
80 81
        $testConnParams = self::getTestConnectionParameters();
        $privConnParams = self::getPrivilegedConnectionParameters();
82

83
        $testConn = DriverManager::getConnection($testConnParams);
84

85 86
        // Connect as a privileged user to create and drop the test database.
        $privConn = DriverManager::getConnection($privConnParams);
87

88
        $platform = $privConn->getDatabasePlatform();
89

90
        if ($platform->supportsCreateDropDatabase()) {
91 92 93 94 95 96
            if (! $platform instanceof OraclePlatform) {
                $dbname = $testConnParams['dbname'];
            } else {
                $dbname = $testConnParams['user'];
            }

97
            $testConn->close();
98

99
            $privConn->getSchemaManager()->dropAndCreateDatabase($dbname);
100

101
            $privConn->close();
102
        } else {
103
            $sm = $testConn->getSchemaManager();
104

105
            $schema = $sm->createSchema();
106
            $stmts  = $schema->toDropSql($testConn->getDatabasePlatform());
107

108
            foreach ($stmts as $stmt) {
109
                $testConn->exec($stmt);
110 111 112 113
            }
        }
    }

114 115 116
    /**
     * @return mixed[]
     */
117
    private static function getFallbackConnectionParams(): array
118
    {
Sergei Morozov's avatar
Sergei Morozov committed
119
        if (! extension_loaded('pdo_sqlite')) {
120 121 122
            Assert::markTestSkipped('PDO SQLite extension is not loaded');
        }

Sergei Morozov's avatar
Sergei Morozov committed
123
        $params = [
124
            'driver' => 'pdo_sqlite',
Sergei Morozov's avatar
Sergei Morozov committed
125 126
            'memory' => true,
        ];
127 128 129 130 131 132 133 134 135

        if (isset($GLOBALS['db_path'])) {
            $params['path'] = $GLOBALS['db_path'];
            unlink($GLOBALS['db_path']);
        }

        return $params;
    }

136
    private static function addDbEventSubscribers(Connection $conn): void
Sergei Morozov's avatar
Sergei Morozov committed
137 138 139 140 141 142 143 144 145
    {
        if (! isset($GLOBALS['db_event_subscribers'])) {
            return;
        }

        $evm = $conn->getEventManager();
        foreach (explode(',', $GLOBALS['db_event_subscribers']) as $subscriberClass) {
            $subscriberInstance = new $subscriberClass();
            $evm->addEventSubscriber($subscriberInstance);
146 147 148
        }
    }

149 150 151
    /**
     * @return mixed[]
     */
152
    private static function getPrivilegedConnectionParameters(): array
153
    {
154 155
        if (isset($GLOBALS['tmpdb_driver'])) {
            return self::mapConnectionParameters($GLOBALS, 'tmpdb_');
156 157
        }

158 159
        $parameters = self::mapConnectionParameters($GLOBALS, 'db_');
        unset($parameters['dbname']);
160

161
        return $parameters;
162 163
    }

164 165 166
    /**
     * @return mixed[]
     */
167
    private static function getTestConnectionParameters(): array
168
    {
169 170
        return self::mapConnectionParameters($GLOBALS, 'db_');
    }
171

172 173 174 175 176
    /**
     * @param array<string,mixed> $configuration
     *
     * @return array<string,mixed>
     */
177
    private static function mapConnectionParameters(array $configuration, string $prefix): array
178 179 180
    {
        $parameters = [];

181 182 183 184 185 186 187 188 189 190 191 192
        foreach (
            [
                'driver',
                'user',
                'password',
                'host',
                'dbname',
                'port',
                'server',
                'unix_socket',
            ] as $parameter
        ) {
193 194 195
            if (! isset($configuration[$prefix . $parameter])) {
                continue;
            }
196

197
            $parameters[$parameter] = $configuration[$prefix . $parameter];
198 199
        }

200
        return $parameters;
201 202
    }

203
    public static function getPrivilegedConnection(): Connection
204
    {
205
        return DriverManager::getConnection(self::getPrivilegedConnectionParameters());
206
    }
207 208 209 210 211 212

    /**
     * Generates a query that will return the given rows without the need to create a temporary table.
     *
     * @param array<int,array<string,mixed>> $rows
     */
213
    public static function generateResultSetQuery(array $rows, AbstractPlatform $platform): string
214
    {
215
        return implode(' UNION ALL ', array_map(static function (array $row) use ($platform): string {
216
            return $platform->getDummySelectSQL(
217
                implode(', ', array_map(static function (string $column, $value) use ($platform): string {
218 219 220 221 222 223 224 225 226
                    if (is_string($value)) {
                        $value = $platform->quoteStringLiteral($value);
                    }

                    return $value . ' ' . $platform->quoteIdentifier($column);
                }, array_keys($row), array_values($row)))
            );
        }, $rows));
    }
227
}