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

Michael Moravec's avatar
Michael Moravec committed
3 4
declare(strict_types=1);

5 6 7
namespace Doctrine\DBAL;

use Doctrine\Common\EventManager;
8 9 10 11 12 13 14 15 16 17
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;
18 19 20 21
use Doctrine\DBAL\Exception\DriverRequired;
use Doctrine\DBAL\Exception\InvalidDriverClass;
use Doctrine\DBAL\Exception\InvalidWrapperClass;
use Doctrine\DBAL\Exception\UnknownDriver;
22 23 24
use function array_keys;
use function array_map;
use function array_merge;
Sergei Morozov's avatar
Sergei Morozov committed
25
use function assert;
26 27
use function class_implements;
use function in_array;
Sergei Morozov's avatar
Sergei Morozov committed
28
use function is_string;
29 30 31 32 33 34 35
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
36 37

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

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

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

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

David Zuelke's avatar
David Zuelke committed
152
        $params = self::parseDatabaseUrl($params);
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        // 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);
            }
        }

176
        self::_checkParams($params);
177

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

romanb's avatar
romanb committed
180
        $driver = new $className();
Benjamin Eberlei's avatar
Benjamin Eberlei committed
181

182
        $wrapperClass = Connection::class;
183
        if (isset($params['wrapperClass'])) {
184
            if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
185
                throw InvalidWrapperClass::new($params['wrapperClass']);
186
            }
187 188

            $wrapperClass = $params['wrapperClass'];
romanb's avatar
romanb committed
189
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
190

romanb's avatar
romanb committed
191 192
        return new $wrapperClass($params, $driver, $config, $eventManager);
    }
193

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

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

romanb's avatar
romanb committed
215
        // driver
216
        if (! isset($params['driver']) && ! isset($params['driverClass'])) {
217
            throw DriverRequired::new();
romanb's avatar
romanb committed
218
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
219

romanb's avatar
romanb committed
220
        // check validity of parameters
Benjamin Eberlei's avatar
Benjamin Eberlei committed
221

romanb's avatar
romanb committed
222
        // driver
223
        if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
224
            throw UnknownDriver::new($params['driver'], array_keys(self::$_driverMap));
romanb's avatar
romanb committed
225
        }
226

227
        if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) {
228
            throw InvalidDriverClass::new($params['driverClass']);
229
        }
romanb's avatar
romanb committed
230
    }
231

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

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

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

264
        $url = parse_url($url);
265

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

270 271
        $url = array_map('rawurldecode', $url);

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

274 275 276 277 278 279 280 281 282 283 284 285
        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'];
        }
286

287 288
        $params = self::parseDatabaseUrlPath($url, $params);
        $params = self::parseDatabaseUrlQuery($url, $params);
289 290 291 292 293

        return $params;
    }

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

312
        $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
313

314 315 316 317 318 319 320
        // 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) {
321 322 323
            return self::parseSqliteDatabaseUrlPath($url, $params);
        }

324 325 326 327 328 329
        return self::parseRegularDatabaseUrlPath($url, $params);
    }

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

341
        $query = [];
342 343 344 345 346 347 348 349 350 351 352

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

        return $params;
    }

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

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

413 414 415 416
            // 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.
417
            $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
418 419 420 421 422 423 424

            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'])) {
425
            throw DriverRequired::new($params['url']);
426 427 428 429
        }

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