DriverManager.php 14.5 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 21 22 23 24 25 26 27 28 29
use function array_keys;
use function array_map;
use function array_merge;
use function class_implements;
use function in_array;
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
30 31

/**
32
 * Factory for creating Doctrine\DBAL\Connection instances.
romanb's avatar
romanb committed
33
 */
34
final class DriverManager
romanb's avatar
romanb committed
35 36
{
    /**
37
     * List of supported drivers and their mappings to the driver classes.
romanb's avatar
romanb committed
38
     *
39 40 41
     * To add your own driver use the 'driverClass' parameter to
     * {@link DriverManager::getConnection()}.
     *
42
     * @var string[]
romanb's avatar
romanb committed
43
     */
44
    private static $_driverMap = [
45 46 47 48 49 50 51 52 53 54 55
        '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,
56
    ];
57

58 59
    /**
     * List of URL schemes from a database URL and their mappings to driver.
60 61
     *
     * @var string[]
62
     */
63
    private static $driverSchemeAliases = [
64 65 66 67 68 69 70 71 72
        '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',
73
    ];
74

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

romanb's avatar
romanb committed
82
    /**
83
     * Creates a connection object based on the specified parameters.
84
     * This method returns a Doctrine\DBAL\Connection which wraps the underlying
85
     * driver connection.
romanb's avatar
romanb committed
86
     *
87
     * $params must contain at least one of the following.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
88
     *
89
     * Either 'driver' with one of the following values:
90
     *
91 92 93
     *     pdo_mysql
     *     pdo_sqlite
     *     pdo_pgsql
94 95
     *     pdo_oci (unstable)
     *     pdo_sqlsrv
96
     *     pdo_sqlsrv
97
     *     mysqli
98
     *     sqlanywhere
99 100 101
     *     sqlsrv
     *     ibm_db2 (unstable)
     *     drizzle_pdo_mysql
Benjamin Eberlei's avatar
Benjamin Eberlei committed
102
     *
103 104
     * OR 'driverClass' that contains the full class name (with namespace) of the
     * driver class to instantiate.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
105
     *
106
     * Other (optional) parameters:
Benjamin Eberlei's avatar
Benjamin Eberlei committed
107
     *
108
     * <b>user (string)</b>:
Benjamin Eberlei's avatar
Benjamin Eberlei committed
109 110
     * The username to use when connecting.
     *
111 112
     * <b>password (string)</b>:
     * The password to use when connecting.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
113
     *
114 115 116
     * <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
117
     *
118 119
     * <b>pdo</b>:
     * You can pass an existing PDO instance through this parameter. The PDO
120
     * instance will be wrapped in a Doctrine\DBAL\Connection.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
121
     *
122 123
     * <b>wrapperClass</b>:
     * You may specify a custom wrapper class through the 'wrapperClass'
124
     * parameter but this class MUST inherit from Doctrine\DBAL\Connection.
Benjamin Eberlei's avatar
Benjamin Eberlei committed
125
     *
126 127 128
     * <b>driverClass</b>:
     * The driver class to use.
     *
129
     * @param mixed[]            $params       The parameters.
130 131
     * @param Configuration|null $config       The configuration to use.
     * @param EventManager|null  $eventManager The event manager to use.
Benjamin Morel's avatar
Benjamin Morel committed
132
     *
133
     * @throws DBALException
romanb's avatar
romanb committed
134
     */
135
    public static function getConnection(
136 137 138 139
        array $params,
        ?Configuration $config = null,
        ?EventManager $eventManager = null
    ) : Connection {
romanb's avatar
romanb committed
140
        // create default config and event manager, if not set
141
        if (! $config) {
142
            $config = new Configuration();
romanb's avatar
romanb committed
143
        }
144
        if (! $eventManager) {
145
            $eventManager = new EventManager();
romanb's avatar
romanb committed
146
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
147

David Zuelke's avatar
David Zuelke committed
148
        $params = self::parseDatabaseUrl($params);
149

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        // 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
172
        // check for existing pdo object
173
        if (isset($params['pdo']) && ! $params['pdo'] instanceof PDO) {
174
            throw DBALException::invalidPdoInstance();
Steve Müller's avatar
Steve Müller committed
175
        } elseif (isset($params['pdo'])) {
176 177
            $params['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(PDO::ATTR_DRIVER_NAME);
romanb's avatar
romanb committed
178
        } else {
179
            self::_checkParams($params);
romanb's avatar
romanb committed
180
        }
181

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

romanb's avatar
romanb committed
184
        $driver = new $className();
Benjamin Eberlei's avatar
Benjamin Eberlei committed
185

186
        $wrapperClass = Connection::class;
187
        if (isset($params['wrapperClass'])) {
188
            if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
189 190
                throw DBALException::invalidWrapperClass($params['wrapperClass']);
            }
191 192

            $wrapperClass = $params['wrapperClass'];
romanb's avatar
romanb committed
193
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
194

romanb's avatar
romanb committed
195 196
        return new $wrapperClass($params, $driver, $config, $eventManager);
    }
197

198
    /**
199
     * Returns the list of supported drivers.
200
     *
201
     * @return string[]
202
     */
203
    public static function getAvailableDrivers() : array
204
    {
205
        return array_keys(self::$_driverMap);
206 207
    }

romanb's avatar
romanb committed
208 209 210
    /**
     * Checks the list of parameters.
     *
211
     * @param mixed[] $params The list of parameters.
Benjamin Morel's avatar
Benjamin Morel committed
212
     *
213
     * @throws DBALException
romanb's avatar
romanb committed
214
     */
215
    private static function _checkParams(array $params) : void
Benjamin Eberlei's avatar
Benjamin Eberlei committed
216
    {
Pascal Borreli's avatar
Pascal Borreli committed
217
        // check existence of mandatory parameters
Benjamin Eberlei's avatar
Benjamin Eberlei committed
218

romanb's avatar
romanb committed
219
        // driver
220
        if (! isset($params['driver']) && ! isset($params['driverClass'])) {
221
            throw DBALException::driverRequired();
romanb's avatar
romanb committed
222
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
223

romanb's avatar
romanb committed
224
        // check validity of parameters
Benjamin Eberlei's avatar
Benjamin Eberlei committed
225

romanb's avatar
romanb committed
226
        // driver
227
        if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
228
            throw DBALException::unknownDriver($params['driver'], array_keys(self::$_driverMap));
romanb's avatar
romanb committed
229
        }
230

231
        if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) {
232 233
            throw DBALException::invalidDriverClass($params['driverClass']);
        }
romanb's avatar
romanb committed
234
    }
235

236 237 238 239 240
    /**
     * Normalizes the given connection URL path.
     *
     * @return string The normalized connection URL path
     */
241
    private static function normalizeDatabaseUrlPath(string $urlPath) : string
242 243 244 245 246
    {
        // Trim leading slash from URL path.
        return substr($urlPath, 1);
    }

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

264
        // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
David Zuelke's avatar
David Zuelke committed
265
        $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
266
        $url = parse_url($url);
267

David Zuelke's avatar
David Zuelke committed
268
        if ($url === false) {
269 270
            throw new DBALException('Malformed parameter "url".');
        }
271

272 273
        $url = array_map('rawurldecode', $url);

274 275 276 277 278
        // 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);
279

280 281 282 283 284 285 286 287 288 289 290 291
        if (isset($url['host'])) {
            $params['host'] = $url['host'];
        }
        if (isset($url['port'])) {
            $params['port'] = $url['port'];
        }
        if (isset($url['user'])) {
            $params['user'] = $url['user'];
        }
        if (isset($url['pass'])) {
            $params['password'] = $url['pass'];
        }
292

293 294
        $params = self::parseDatabaseUrlPath($url, $params);
        $params = self::parseDatabaseUrlQuery($url, $params);
295 296 297 298 299

        return $params;
    }

    /**
300 301 302 303
     * 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}.
304
     *
305 306
     * @see parseDatabaseUrlScheme
     *
307 308
     * @param mixed[] $url    The URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
309
     *
310
     * @return mixed[] The resolved connection parameters.
311
     */
312
    private static function parseDatabaseUrlPath(array $url, array $params) : array
313
    {
314
        if (! isset($url['path'])) {
315 316 317
            return $params;
        }

318
        $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
319

320 321 322 323 324 325 326
        // 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) {
327 328 329
            return self::parseSqliteDatabaseUrlPath($url, $params);
        }

330 331 332 333 334 335
        return self::parseRegularDatabaseUrlPath($url, $params);
    }

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

347
        $query = [];
348 349 350 351 352 353 354 355 356 357 358

        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}.
     *
359 360
     * @see normalizeDatabaseUrlPath
     *
361 362
     * @param mixed[] $url    The regular connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
363
     *
364
     * @return mixed[] The resolved connection parameters.
365
     */
366
    private static function parseRegularDatabaseUrlPath(array $url, array $params) : array
367
    {
368 369 370 371 372 373
        $params['dbname'] = $url['path'];

        return $params;
    }

    /**
374
     * Parses the given SQLite connection URL and resolves the given connection parameters.
375
     *
376 377
     * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
     *
378 379
     * @see normalizeDatabaseUrlPath
     *
380 381
     * @param mixed[] $url    The SQLite connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
382
     *
383
     * @return mixed[] The resolved connection parameters.
384
     */
385
    private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array
386 387 388 389 390 391 392 393 394
    {
        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
395
        return $params;
396
    }
397 398 399 400

    /**
     * Parses the scheme part from given connection URL and resolves the given connection parameters.
     *
401 402
     * @param mixed[] $url    The connection URL parts to evaluate.
     * @param mixed[] $params The connection parameters to resolve.
403
     *
404
     * @return mixed[] The resolved connection parameters.
405
     *
406
     * @throws DBALException If parsing failed or resolution is not possible.
407
     */
408
    private static function parseDatabaseUrlScheme(array $url, array $params) : array
409 410 411 412 413 414 415 416 417
    {
        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']);

418 419 420 421
            // 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.
422
            $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
423 424 425 426 427 428 429 430 431 432 433 434

            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
435
}