Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix parsing schemeless connection URLs #2287

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/Doctrine/DBAL/DBALException.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,22 @@ public static function invalidPdoInstance()
}

/**
* @param bool|null $url The URL that was provided in the connection parameters (if any).
*
* @return \Doctrine\DBAL\DBALException
*/
public static function driverRequired()
public static function driverRequired($url = null)
{
if ($url) {
return new self(
sprintf(
"The options 'driver' or 'driverClass' are mandatory if a connection URL without scheme " .
"is given to DriverManager::getConnection(). Given URL: %s",
$url
)
);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd put this into a separate static method. To me only looking at this code it is not clear, that when $url is given here, it misses one special part. Maybe missingSchemeRequiredDriver() or something like that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also no strong opinion here. @Ocramius @zeroedin-bill thoughts?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would have done a separate method as well, yep.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Errata: seen now that 'url' may be passed in from multiple contexts. It is indeed better to let the exception class decide here.


return new self("The options 'driver' or 'driverClass' are mandatory if no PDO ".
"instance is given to DriverManager::getConnection().");
}
Expand Down
152 changes: 128 additions & 24 deletions lib/Doctrine/DBAL/DriverManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ private static function _checkParams(array $params)
}
}

/**
* Normalizes the given connection URL path.
*
* @param string $urlPath
*
* @return string The normalized connection URL path
*/
private static function normalizeDatabaseUrlPath($urlPath)
{
// Trim leading slash from URL path.
return substr($urlPath, 1);
}

/**
* Extracts parts from a database URL, if present, and returns an
* updated list of parameters.
Expand All @@ -232,18 +245,25 @@ private static function parseDatabaseUrl(array $params)
// (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
$url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);

$url = parse_url($url);
// PHP < 5.4.8 doesn't parse schemeless urls properly.
// See: https://php.net/parse-url#refsect1-function.parse-url-changelog
if (PHP_VERSION_ID < 50408 && strpos($url, '//') === 0) {
$url = parse_url('fake:' . $url);

unset($url['scheme']);
} else {
$url = parse_url($url);
}

if ($url === false) {
throw new DBALException('Malformed parameter "url".');
}

if (isset($url['scheme'])) {
$params['driver'] = str_replace('-', '_', $url['scheme']); // URL schemes must not contain underscores, but dashes are ok
if (isset(self::$driverSchemeAliases[$params['driver']])) {
$params['driver'] = self::$driverSchemeAliases[$params['driver']]; // use alias like "postgres", else we just let checkParams decide later if the driver exists (for literal "pdo-pgsql" etc)
}
}
// 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']);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My 2 cent: When I pass a concrete connection instance, I'd expect, that this instance is used. So either the connection url should be dropped, instead of the connection instance, or an error should occur. Else a new connection will be made, even if I already pass one. That may be unexpected. What do you think?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kingcrunch yeah I get what you mean. TBH it also took me some time to gather what actually the expected behaviour is/should be. The thing is (and after thinking a little bit about it also makes a lot of sense) the documentation propagates that if a URL is specified, it's information takes precedence over "default" value being set already in the connection parameters. This makes sense because as a service provider you could for example provide connection details for a default connection while the client can fully or partially ovewrite those settings. I think this was also part of the idea of your original PR. Telling that, a "default" PDO makes no differences in semantics towards providing a driver or driverClass because all of those end up in a connection instance using default values. So IMO making an exception for PDO here is rather confusing and defeats the original message of an URL taking precedence. Also silently discarding a connection URL may be dangerous to the client as he might expect to be connected to somewhere else than the default PDO connection. So IMO when providing a URL we have to error as soon as we have connection parameter conflicts.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah so since I originally wrote this URL stuff... the idea is definitely that a URL can override any individual defaults that are set. The reason is that were it the other way round, you'd have to repeat all individual args to unset the URL instructions. Also, the idea is kind of to have a few defaults for e.g. all dev envs set individually through a framework or whatever, and then a URL can "fill" or "override" those. Think charset, server version and SSL mode set "globally" through individual parameters, and then each developer/environment just has a single mysql://user:pass@host:port/dbname URL parameter set, but they could always attach ?sslmode=none to that URL for testing to override the default.


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

if (isset($url['host'])) {
$params['host'] = $url['host'];
Expand All @@ -258,53 +278,97 @@ private static function parseDatabaseUrl(array $params)
$params['password'] = $url['pass'];
}

if (isset($url['path'])) {
$params = self::parseDatabaseUrlPath($url, $params);
}

if (isset($url['query'])) {
$query = array();
parse_str($url['query'], $query); // simply ingest query as extra params, e.g. charset or sslmode
$params = array_merge($params, $query); // parse_str wipes existing array elements
}
$params = self::parseDatabaseUrlPath($url, $params);
$params = self::parseDatabaseUrlQuery($url, $params);

return $params;
}

/**
* Parses the given URL and resolves the given connection parameters.
* 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}.
*
* @param array $url The URL parts to evaluate.
* @param array $params The connection parameters to resolve.
*
* @return array The resolved connection parameters.
*
* @see parseDatabaseUrlScheme
*/
private static function parseDatabaseUrlPath(array $url, array $params)
{
if (!isset($url['scheme'])) {
$params['dbname'] = $url['path'];

if (! isset($url['path'])) {
return $params;
}

$url['path'] = substr($url['path'], 1);
$url['path'] = self::normalizeDatabaseUrlPath($url['path']);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is only used here. It doesn't look like a benefit to extract this substr() call

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True that. I don't have a strong opinion about that, my preference was to make things clear by defining each step that is part of the parsing process as individual method.


if (strpos($url['scheme'], 'sqlite') !== false) {
// 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) {
return self::parseSqliteDatabaseUrlPath($url, $params);
}

return self::parseRegularDatabaseUrlPath($url, $params);
}

/**
* Parses the query part of the given connection URL and resolves the given connection parameters.
*
* @param array $url The connection URL parts to evaluate.
* @param array $params The connection parameters to resolve.
*
* @return array The resolved connection parameters.
*/
private static function parseDatabaseUrlQuery(array $url, array $params)
{
if (! isset($url['query'])) {
return $params;
}

$query = array();

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}.
*
* @param array $url The regular connection URL parts to evaluate.
* @param array $params The connection parameters to resolve.
*
* @return array The resolved connection parameters.
*
* @see normalizeDatabaseUrlPath
*/
private static function parseRegularDatabaseUrlPath(array $url, array $params)
{
$params['dbname'] = $url['path'];

return $params;
}

/**
* Parses the given SQLite URL and resolves the given connection parameters.
* Parses the given SQLite connection URL and resolves the given connection parameters.
*
* Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
*
* @param array $url The SQLite URL parts to evaluate.
* @param array $url The SQLite connection URL parts to evaluate.
* @param array $params The connection parameters to resolve.
*
* @return array The resolved connection parameters.
*
* @see normalizeDatabaseUrlPath
*/
private static function parseSqliteDatabaseUrlPath(array $url, array $params)
{
Expand All @@ -318,4 +382,44 @@ private static function parseSqliteDatabaseUrlPath(array $url, array $params)

return $params;
}

/**
* Parses the scheme part from given connection URL and resolves the given connection parameters.
*
* @param array $url The connection URL parts to evaluate.
* @param array $params The connection parameters to resolve.
*
* @return array The resolved connection parameters.
*
* @throws DBALException if parsing failed or resolution is not possible.
*/
private static function parseDatabaseUrlScheme(array $url, array $params)
{
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']);

// The requested driver from the URL scheme takes precedence
// over the default driver from the connection parameters (if any).
$params['driver'] = isset(self::$driverSchemeAliases[$driver])
// use alias like "postgres", else we just let checkParams decide later
// if the driver exists (for literal "pdo-pgsql" etc)
? self::$driverSchemeAliases[$driver]
: $driver;

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;
}
}
16 changes: 16 additions & 0 deletions tests/Doctrine/Tests/DBAL/DBALExceptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,20 @@ public function testAvoidOverWrappingOnDriverException()
$e = DBALException::driverExceptionDuringQuery($driver, $ex, '');
$this->assertSame($ex, $e);
}

public function testDriverRequiredWithUrl()
{
$url = 'mysql://localhost';
$exception = DBALException::driverRequired($url);

$this->assertInstanceOf('Doctrine\DBAL\DBALException', $exception);
$this->assertSame(
sprintf(
"The options 'driver' or 'driverClass' are mandatory if a connection URL without scheme " .
"is given to DriverManager::getConnection(). Given URL: %s",
$url
),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be a constant string. Test should contain as less logic as possible :)

"The options 'driver' or 'driverClass' are mandatory if a connection URL without scheme is given to DriverManager::getConnection(). Given URL: mysql://localhost"

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arguable ;) But as we didn't practice something like that in the testsuite I'll not start here. Also the test case is quite simple so it should be understandable enough.

$exception->getMessage()
);
}
}
54 changes: 53 additions & 1 deletion tests/Doctrine/Tests/DBAL/DriverManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public function testDatabaseUrl($url, $expected)

$params = $conn->getParams();
foreach ($expected as $key => $value) {
if ($key == 'driver') {
if (in_array($key, array('pdo', 'driver', 'driverClass'), true)) {
$this->assertInstanceOf($value, $conn->getDriver());
} else {
$this->assertEquals($value, $params[$key]);
Expand All @@ -140,6 +140,8 @@ public function testDatabaseUrl($url, $expected)

public function databaseUrls()
{
$pdoMock = $this->getMock('Doctrine\Tests\Mocks\PDOMock');

return array(
'simple URL' => array(
'mysql://foo:bar@localhost/baz',
Expand Down Expand Up @@ -197,6 +199,56 @@ public function databaseUrls()
'drizzle-pdo-mysql://foo:bar@localhost/baz',
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver'),
),

// DBAL-1234
'URL without scheme and without any driver information' => array(
array('url' => '//foo:bar@localhost/baz'),
false,
),
'URL without scheme but default PDO driver' => array(
array('url' => '//foo:bar@localhost/baz', 'pdo' => $pdoMock),
false,
),
'URL without scheme but default driver' => array(
array('url' => '//foo:bar@localhost/baz', 'driver' => 'pdo_mysql'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL without scheme but custom driver' => array(
array('url' => '//foo:bar@localhost/baz', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
),
'URL without scheme but default PDO driver and default driver' => array(
array('url' => '//foo:bar@localhost/baz', 'pdo' => $pdoMock, 'driver' => 'pdo_mysql'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL without scheme but driver and custom driver' => array(
array('url' => '//foo:bar@localhost/baz', 'driver' => 'pdo_mysql', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
),
'URL with default PDO driver' => array(
array('url' => 'mysql://foo:bar@localhost/baz', 'pdo' => $pdoMock),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL with default driver' => array(
array('url' => 'mysql://foo:bar@localhost/baz', 'driver' => 'sqlite'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL with default custom driver' => array(
array('url' => 'mysql://foo:bar@localhost/baz', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL with default PDO driver and default driver' => array(
array('url' => 'mysql://foo:bar@localhost/baz', 'pdo' => $pdoMock, 'driver' => 'sqlite'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL with default driver and default custom driver' => array(
array('url' => 'mysql://foo:bar@localhost/baz', 'driver' => 'sqlite', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
'URL with default PDO driver and default driver and default custom driver' => array(
array('url' => 'mysql://foo:bar@localhost/baz', 'pdo' => $pdoMock, 'driver' => 'sqlite', 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock'),
array('user' => 'foo', 'password' => 'bar', 'host' => 'localhost', 'dbname' => 'baz', 'driver' => 'Doctrine\DBAL\Driver\PDOMySQL\Driver'),
),
);
}
}
10 changes: 10 additions & 0 deletions tests/Doctrine/Tests/Mocks/PDOMock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Doctrine\Tests\Mocks;

class PDOMock extends \PDO
{
public function __construct()
{
}
}