DriverManager.php 14.4 KB
Newer Older
romanb's avatar
romanb committed
1 2
<?php

3 4 5
namespace Doctrine\DBAL;

use Doctrine\Common\EventManager;
6 7 8 9 10 11 12 13 14 15 16
use Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver as DrizzlePDOMySQLDriver;
use Doctrine\DBAL\Driver\IBMDB2\DB2Driver;
use Doctrine\DBAL\Driver\Mysqli\Driver as MySQLiDriver;
use Doctrine\DBAL\Driver\OCI8\Driver as OCI8Driver;
use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySQLDriver;
use Doctrine\DBAL\Driver\PDOOracle\Driver as PDOOCIDriver;
use Doctrine\DBAL\Driver\PDOPgSql\Driver as PDOPgSQLDriver;
use Doctrine\DBAL\Driver\PDOSqlite\Driver as PDOSQLiteDriver;
use Doctrine\DBAL\Driver\PDOSqlsrv\Driver as PDOSQLSrvDriver;
use Doctrine\DBAL\Driver\SQLAnywhere\Driver as SQLAnywhereDriver;
use Doctrine\DBAL\Driver\SQLSrv\Driver as SQLSrvDriver;
17
use PDO;
18 19 20
use function array_keys;
use function array_map;
use function array_merge;
Sergei Morozov's avatar
Sergei Morozov committed
21
use function assert;
22 23
use function class_implements;
use function in_array;
Sergei Morozov's avatar
Sergei Morozov committed
24
use function is_string;
25 26 27 28 29 30 31
use function is_subclass_of;
use function parse_str;
use function parse_url;
use function preg_replace;
use function str_replace;
use function strpos;
use function substr;
romanb's avatar
romanb committed
32 33

/**
34
 * Factory for creating Doctrine\DBAL\Connection instances.
romanb's avatar
romanb committed
35
 */
36
final class DriverManager
romanb's avatar
romanb committed
37 38
{
    /**
39
     * List of supported drivers and their mappings to the driver classes.
romanb's avatar
romanb committed
40
     *
41 42 43
     * To add your own driver use the 'driverClass' parameter to
     * {@link DriverManager::getConnection()}.
     *
44
     * @var string[]
romanb's avatar
romanb committed
45
     */
46
    private static $_driverMap = [
47 48 49 50 51 52 53 54 55 56 57
        'pdo_mysql'          => PDOMySQLDriver::class,
        'pdo_sqlite'         => PDOSQLiteDriver::class,
        'pdo_pgsql'          => PDOPgSQLDriver::class,
        'pdo_oci'            => PDOOCIDriver::class,
        'oci8'               => OCI8Driver::class,
        'ibm_db2'            => DB2Driver::class,
        'pdo_sqlsrv'         => PDOSQLSrvDriver::class,
        'mysqli'             => MySQLiDriver::class,
        'drizzle_pdo_mysql'  => DrizzlePDOMySQLDriver::class,
        'sqlanywhere'        => SQLAnywhereDriver::class,
        'sqlsrv'             => SQLSrvDriver::class,
58
    ];
59

60 61
    /**
     * List of URL schemes from a database URL and their mappings to driver.
62 63
     *
     * @var string[]
64
     */
65
    private static $driverSchemeAliases = [
66 67 68 69 70 71 72 73 74
        'db2'        => 'ibm_db2',
        'mssql'      => 'pdo_sqlsrv',
        'mysql'      => 'pdo_mysql',
        'mysql2'     => 'pdo_mysql', // Amazon RDS, for some weird reason
        'postgres'   => 'pdo_pgsql',
        'postgresql' => 'pdo_pgsql',
        'pgsql'      => 'pdo_pgsql',
        'sqlite'     => 'pdo_sqlite',
        'sqlite3'    => 'pdo_sqlite',
75
    ];
76

Benjamin Morel's avatar
Benjamin Morel committed
77 78 79 80 81 82
    /**
     * Private constructor. This class cannot be instantiated.
     */
    private function __construct()
    {
    }
83

romanb's avatar
romanb committed
84
    /**
85
     * Creates a connection object based on the specified parameters.
86
     * This method returns a Doctrine\DBAL\Connection which wraps the underlying
87
     * driver connection.
romanb's avatar
romanb committed
88
     *
89
     * $params must contain at least one of the following.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
90
     *
91
     * Either 'driver' with one of the array keys of {@link $_driverMap},
92 93
     * OR 'driverClass' that contains the full class name (with namespace) of the
     * driver class to instantiate.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
94
     *
95
     * Other (optional) parameters:
Benjamin Eberlei's avatar
Benjamin Eberlei committed
96
     *
97
     * <b>user (string)</b>:
Benjamin Eberlei's avatar
Benjamin Eberlei committed
98 99
     * The username to use when connecting.
     *
100 101
     * <b>password (string)</b>:
     * The password to use when connecting.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
102
     *
103 104 105
     * <b>driverOptions (array)</b>:
     * Any additional driver-specific options for the driver. These are just passed
     * through to the driver.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
106
     *
107 108
     * <b>pdo</b>:
     * You can pass an existing PDO instance through this parameter. The PDO
109
     * instance will be wrapped in a Doctrine\DBAL\Connection.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
110
     *
111 112
     * <b>wrapperClass</b>:
     * You may specify a custom wrapper class through the 'wrapperClass'
113
     * parameter but this class MUST inherit from Doctrine\DBAL\Connection.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
114
     *
115 116 117
     * <b>driverClass</b>:
     * The driver class to use.
     *
118
     * @param mixed[]            $params       The parameters.
119 120
     * @param Configuration|null $config       The configuration to use.
     * @param EventManager|null  $eventManager The event manager to use.
Benjamin Morel's avatar
Benjamin Morel committed
121
     *
122
     * @throws DBALException
romanb's avatar
romanb committed
123
     */
124
    public static function getConnection(
125 126 127 128
        array $params,
        ?Configuration $config = null,
        ?EventManager $eventManager = null
    ) : Connection {
romanb's avatar
romanb committed
129
        // create default config and event manager, if not set
130
        if (! $config) {
131
            $config = new Configuration();
romanb's avatar
romanb committed
132
        }
Grégoire Paris's avatar
Grégoire Paris committed
133

134
        if (! $eventManager) {
135
            $eventManager = new EventManager();
romanb's avatar
romanb committed
136
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
137

David Zuelke's avatar
David Zuelke committed
138
        $params = self::parseDatabaseUrl($params);
139

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        // URL support for MasterSlaveConnection
        if (isset($params['master'])) {
            $params['master'] = self::parseDatabaseUrl($params['master']);
        }

        if (isset($params['slaves'])) {
            foreach ($params['slaves'] as $key => $slaveParams) {
                $params['slaves'][$key] = self::parseDatabaseUrl($slaveParams);
            }
        }

        // URL support for PoolingShardConnection
        if (isset($params['global'])) {
            $params['global'] = self::parseDatabaseUrl($params['global']);
        }

        if (isset($params['shards'])) {
            foreach ($params['shards'] as $key => $shardParams) {
                $params['shards'][$key] = self::parseDatabaseUrl($shardParams);
            }
        }

romanb's avatar
romanb committed
162
        // check for existing pdo object
163
        if (isset($params['pdo']) && ! $params['pdo'] instanceof PDO) {
164
            throw DBALException::invalidPdoInstance();
165 166 167
        }

        if (isset($params['pdo'])) {
168 169
            $params['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(PDO::ATTR_DRIVER_NAME);
romanb's avatar
romanb committed
170
        } else {
171
            self::_checkParams($params);
romanb's avatar
romanb committed
172
        }
173

174
        $className = $params['driverClass'] ?? self::$_driverMap[$params['driver']];
Benjamin Eberlei's avatar
Benjamin Eberlei committed
175

romanb's avatar
romanb committed
176
        $driver = new $className();
Benjamin Eberlei's avatar
Benjamin Eberlei committed
177

178
        $wrapperClass = Connection::class;
179
        if (isset($params['wrapperClass'])) {
180
            if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
181 182
                throw DBALException::invalidWrapperClass($params['wrapperClass']);
            }
183 184

            $wrapperClass = $params['wrapperClass'];
romanb's avatar
romanb committed
185
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
186

romanb's avatar
romanb committed
187 188
        return new $wrapperClass($params, $driver, $config, $eventManager);
    }
189

190
    /**
191
     * Returns the list of supported drivers.
192
     *
193
     * @return string[]
194
     */
195
    public static function getAvailableDrivers() : array
196
    {
197
        return array_keys(self::$_driverMap);
198 199
    }

romanb's avatar
romanb committed
200 201 202
    /**
     * Checks the list of parameters.
     *
203
     * @param mixed[] $params The list of parameters.
Benjamin Morel's avatar
Benjamin Morel committed
204
     *
205
     * @throws DBALException
romanb's avatar
romanb committed
206
     */
207
    private static function _checkParams(array $params) : void
Benjamin Eberlei's avatar
Benjamin Eberlei committed
208
    {
Pascal Borreli's avatar
Pascal Borreli committed
209
        // check existence of mandatory parameters
Benjamin Eberlei's avatar
Benjamin Eberlei committed
210

romanb's avatar
romanb committed
211
        // driver
212
        if (! isset($params['driver']) && ! isset($params['driverClass'])) {
213
            throw DBALException::driverRequired();
romanb's avatar
romanb committed
214
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
215

romanb's avatar
romanb committed
216
        // check validity of parameters
Benjamin Eberlei's avatar
Benjamin Eberlei committed
217

romanb's avatar
romanb committed
218
        // driver
219
        if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
220
            throw DBALException::unknownDriver($params['driver'], array_keys(self::$_driverMap));
romanb's avatar
romanb committed
221
        }
222

223
        if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) {
224 225
            throw DBALException::invalidDriverClass($params['driverClass']);
        }
romanb's avatar
romanb committed
226
    }
227

228 229 230 231 232
    /**
     * Normalizes the given connection URL path.
     *
     * @return string The normalized connection URL path
     */
233
    private static function normalizeDatabaseUrlPath(string $urlPath) : string
234 235 236 237 238
    {
        // Trim leading slash from URL path.
        return substr($urlPath, 1);
    }

239 240 241 242
    /**
     * Extracts parts from a database URL, if present, and returns an
     * updated list of parameters.
     *
243
     * @param mixed[] $params The list of parameters.
244
     *
245 246
     * @return mixed[] A modified list of parameters with info from a database
     *                 URL extracted into indidivual parameter parts.
247
     *
248
     * @throws DBALException
249
     */
250
    private static function parseDatabaseUrl(array $params) : array
251
    {
252
        if (! isset($params['url'])) {
David Zuelke's avatar
David Zuelke committed
253
            return $params;
254
        }
255

256
        // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
David Zuelke's avatar
David Zuelke committed
257
        $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
Sergei Morozov's avatar
Sergei Morozov committed
258 259
        assert(is_string($url));

260
        $url = parse_url($url);
261

David Zuelke's avatar
David Zuelke committed
262
        if ($url === false) {
263 264
            throw new DBALException('Malformed parameter "url".');
        }
265

266 267
        $url = array_map('rawurldecode', $url);

268 269 270 271 272
        // If we have a connection URL, we have to unset the default PDO instance connection parameter (if any)
        // as we cannot merge connection details from the URL into the PDO instance (URL takes precedence).
        unset($params['pdo']);

        $params = self::parseDatabaseUrlScheme($url, $params);
273

274 275 276
        if (isset($url['host'])) {
            $params['host'] = $url['host'];
        }
Grégoire Paris's avatar
Grégoire Paris committed
277

278 279 280
        if (isset($url['port'])) {
            $params['port'] = $url['port'];
        }
Grégoire Paris's avatar
Grégoire Paris committed
281

282 283 284
        if (isset($url['user'])) {
            $params['user'] = $url['user'];
        }
Grégoire Paris's avatar
Grégoire Paris committed
285

286 287 288
        if (isset($url['pass'])) {
            $params['password'] = $url['pass'];
        }
289

290 291
        $params = self::parseDatabaseUrlPath($url, $params);
        $params = self::parseDatabaseUrlQuery($url, $params);
292 293 294 295 296

        return $params;
    }

    /**
297 298 299 300
     * Parses the given connection URL and resolves the given connection parameters.
     *
     * Assumes that the connection URL scheme is already parsed and resolved into the given connection parameters
     * via {@link parseDatabaseUrlScheme}.
301
     *
302 303
     * @see parseDatabaseUrlScheme
     *
304 305
     * @param mixed[] $url    The URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
306
     *
307
     * @return mixed[] The resolved connection parameters.
308
     */
309
    private static function parseDatabaseUrlPath(array $url, array $params) : array
310
    {
311
        if (! isset($url['path'])) {
312 313 314
            return $params;
        }

315
        $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
316

317 318 319 320 321 322 323
        // If we do not have a known DBAL driver, we do not know any connection URL path semantics to evaluate
        // and therefore treat the path as regular DBAL connection URL path.
        if (! isset($params['driver'])) {
            return self::parseRegularDatabaseUrlPath($url, $params);
        }

        if (strpos($params['driver'], 'sqlite') !== false) {
324 325 326
            return self::parseSqliteDatabaseUrlPath($url, $params);
        }

327 328 329 330 331 332
        return self::parseRegularDatabaseUrlPath($url, $params);
    }

    /**
     * Parses the query part of the given connection URL and resolves the given connection parameters.
     *
333 334
     * @param mixed[] $url    The connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
335
     *
336
     * @return mixed[] The resolved connection parameters.
337
     */
338
    private static function parseDatabaseUrlQuery(array $url, array $params) : array
339 340 341 342 343
    {
        if (! isset($url['query'])) {
            return $params;
        }

344
        $query = [];
345 346 347 348 349 350 351 352 353 354 355

        parse_str($url['query'], $query); // simply ingest query as extra params, e.g. charset or sslmode

        return array_merge($params, $query); // parse_str wipes existing array elements
    }

    /**
     * Parses the given regular connection URL and resolves the given connection parameters.
     *
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
     *
356 357
     * @see normalizeDatabaseUrlPath
     *
358 359
     * @param mixed[] $url    The regular connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
360
     *
361
     * @return mixed[] The resolved connection parameters.
362
     */
363
    private static function parseRegularDatabaseUrlPath(array $url, array $params) : array
364
    {
365 366 367 368 369 370
        $params['dbname'] = $url['path'];

        return $params;
    }

    /**
371
     * Parses the given SQLite connection URL and resolves the given connection parameters.
372
     *
373 374
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
     *
375 376
     * @see normalizeDatabaseUrlPath
     *
377 378
     * @param mixed[] $url    The SQLite connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
379
     *
380
     * @return mixed[] The resolved connection parameters.
381
     */
382
    private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array
383 384 385 386 387 388 389 390 391
    {
        if ($url['path'] === ':memory:') {
            $params['memory'] = true;

            return $params;
        }

        $params['path'] = $url['path']; // pdo_sqlite driver uses 'path' instead of 'dbname' key

David Zuelke's avatar
David Zuelke committed
392
        return $params;
393
    }
394 395 396 397

    /**
     * Parses the scheme part from given connection URL and resolves the given connection parameters.
     *
398 399
     * @param mixed[] $url    The connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
400
     *
401
     * @return mixed[] The resolved connection parameters.
402
     *
403
     * @throws DBALException If parsing failed or resolution is not possible.
404
     */
405
    private static function parseDatabaseUrlScheme(array $url, array $params) : array
406 407 408 409 410 411 412 413
    {
        if (isset($url['scheme'])) {
            // The requested driver from the URL scheme takes precedence
            // over the default custom driver from the connection parameters (if any).
            unset($params['driverClass']);

            // URL schemes must not contain underscores, but dashes are ok
            $driver = str_replace('-', '_', $url['scheme']);
Sergei Morozov's avatar
Sergei Morozov committed
414
            assert(is_string($driver));
415

416 417 418 419
            // The requested driver from the URL scheme takes precedence over the
            // default driver from the connection parameters. If the driver is
            // an alias (e.g. "postgres"), map it to the actual name ("pdo-pgsql").
            // Otherwise, let checkParams decide later if the driver exists.
420
            $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
421 422 423 424 425 426 427 428 429 430 431 432

            return $params;
        }

        // If a schemeless connection URL is given, we require a default driver or default custom driver
        // as connection parameter.
        if (! isset($params['driverClass']) && ! isset($params['driver'])) {
            throw DBALException::driverRequired($params['url']);
        }

        return $params;
    }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
433
}