Skip to content

Commit 809b73b

Browse files
boydbloemsmabrendt
andauthored
feat(database): support creating database configs from a URL (#2315)
Co-authored-by: Brent Roose <brent.roose@gmail.com>
1 parent 86b06a9 commit 809b73b

8 files changed

Lines changed: 537 additions & 3 deletions

File tree

‎docs/1-essentials/03-database.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,40 @@ return new PostgresConfig(
3636
);
3737
```
3838

39+
### Connecting with a connection string
40+
41+
Some hosting providers, such as Laravel Cloud, inject the connection details as a single `DATABASE_URL` environment variable. Each configuration class provides a `fromConnectionString()` method that builds the configuration from such a connection string:
42+
43+
```php app/Config/database.config.php
44+
use Tempest\Database\Config\MysqlConfig;
45+
use function Tempest\env;
46+
47+
return MysqlConfig::fromConnectionString(env('DATABASE_URL'));
48+
```
49+
50+
Components missing from the connection string fall back to their defaults. Any other constructor argument may be passed by name, and takes precedence over the values parsed from the connection string:
51+
52+
```php app/Config/database.config.php
53+
return PostgresConfig::fromConnectionString(env('DATABASE_URL'), persistent: true);
54+
```
55+
56+
Query parameters are appended to the DSN, which allows passing driver-specific options such as `sslmode` or `connect_timeout`:
57+
58+
```
59+
postgres://user:secret@db.example.com:5432/app?sslmode=require&connect_timeout=10
60+
```
61+
62+
To connect through a Unix socket, pass its path as a percent-encoded host, or as the `host` query parameter for PostgreSQL and the `unix_socket` query parameter for MySQL:
63+
64+
```
65+
postgres://user:secret@%2Fvar%2Frun%2Fpostgresql/app
66+
mysql://user:secret@localhost/app?unix_socket=/var/run/mysqld/mysqld.sock
67+
```
68+
69+
{b`Tempest\Database\Config\MysqlConfig`} accepts the `mysql` and `mariadb` schemes, {b`Tempest\Database\Config\PostgresConfig`} accepts `postgres`, `postgresql` and `pgsql`, and {b`Tempest\Database\Config\SQLiteConfig`} accepts connection strings such as `sqlite:///path/to/database.sqlite` and `sqlite::memory:`. Credentials containing special characters must be percent-encoded.
70+
71+
The parsed components are also available through the {b`Tempest\Database\Config\DatabaseConnectionString`} value object, using `DatabaseConnectionString::from()`.
72+
3973
## Querying the database
4074

4175
Multiple approaches exist for querying the database, all of which execute a {b`Tempest\Database\Query`} on the {b`Tempest\Database\Database`} class. The most straightforward approach is to inject {b`Tempest\Database\Database`}:
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Database\Config;
6+
7+
use SensitiveParameter;
8+
use Tempest\Database\Exceptions\DatabaseConnectionStringWasInvalid;
9+
use Uri\Rfc3986\Uri;
10+
11+
final class DatabaseConnectionString
12+
{
13+
/**
14+
* The path without its leading slash.
15+
*/
16+
public ?string $database {
17+
get => ltrim($this->path ?? '', '/') ?: null;
18+
}
19+
20+
/**
21+
* @param string $scheme The scheme, such as `mysql` or `postgres`.
22+
* @param null|string $host The host, or the path to a Unix socket.
23+
* @param null|int $port The port.
24+
* @param null|string $username The username.
25+
* @param null|string $password The password.
26+
* @param null|string $path The path following the authority, such as `/database` or `/path/to/database.sqlite`.
27+
* @param array<string,string> $parameters The query parameters, such as `sslmode` or `connect_timeout`.
28+
*/
29+
public function __construct(
30+
public readonly string $scheme,
31+
public readonly ?string $host = null,
32+
public readonly ?int $port = null,
33+
public readonly ?string $username = null,
34+
#[SensitiveParameter]
35+
public readonly ?string $password = null,
36+
public readonly ?string $path = null,
37+
public readonly array $parameters = [],
38+
) {}
39+
40+
/**
41+
* Creates a DatabaseConnectionString instance from a connection string, such as `postgres://user:password@host:5432/database?sslmode=require`. Components are percent-decoded, so a Unix socket may be given as a percent-encoded host.
42+
*/
43+
public static function from(#[SensitiveParameter] string $connectionString): self
44+
{
45+
$uri = Uri::parse($connectionString);
46+
47+
if ($uri?->getScheme() === null) {
48+
throw DatabaseConnectionStringWasInvalid::couldNotBeParsed();
49+
}
50+
51+
parse_str($uri->getQuery() ?? '', $parameters);
52+
53+
return new self(
54+
scheme: $uri->getScheme(),
55+
host: self::decode($uri->getHost()),
56+
port: $uri->getPort(),
57+
username: self::decode($uri->getUsername()),
58+
password: self::decode($uri->getPassword()),
59+
path: self::decode($uri->getPath()),
60+
parameters: array_filter($parameters, is_string(...)),
61+
);
62+
}
63+
64+
private static function decode(?string $component): ?string
65+
{
66+
if ($component === null || $component === '') {
67+
return null;
68+
}
69+
70+
return rawurldecode($component);
71+
}
72+
}

‎packages/database/src/Config/MysqlConfig.php‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PDO;
88
use Pdo\Mysql;
99
use SensitiveParameter;
10+
use Tempest\Database\Exceptions\DatabaseConnectionStringWasInvalid;
1011
use Tempest\Database\Migrations\DatePrefixStrategy;
1112
use Tempest\Database\Migrations\MigrationNamingStrategy;
1213
use Tempest\Database\Tables\NamingStrategy;
@@ -17,10 +18,15 @@ final class MysqlConfig implements DatabaseConfig
1718
{
1819
public string $dsn {
1920
get => sprintf(
20-
'mysql:host=%s:%s;dbname=%s',
21+
'mysql:host=%s:%s;dbname=%s%s',
2122
$this->host,
2223
$this->port,
2324
$this->database,
25+
implode('', array_map(
26+
fn (string $key, string $value) => ";{$key}={$value}",
27+
array_keys($this->parameters),
28+
$this->parameters,
29+
)),
2430
);
2531
}
2632

@@ -78,6 +84,7 @@ final class MysqlConfig implements DatabaseConfig
7884
* @param NamingStrategy $namingStrategy The naming strategy for database tables and columns.
7985
* @param MigrationNamingStrategy $migrationNaming The naming strategy for migration file prefixes.
8086
* @param string|UnitEnum|null $tag An optional tag to identify this database configuration.
87+
* @param array<string,string> $parameters Additional parameters appended to the DSN, such as `unix_socket` or `charset`.
8188
*/
8289
public function __construct(
8390
#[SensitiveParameter]
@@ -98,5 +105,47 @@ public function __construct(
98105
public NamingStrategy $namingStrategy = new PluralizedSnakeCaseStrategy(),
99106
public MigrationNamingStrategy $migrationNaming = new DatePrefixStrategy(),
100107
public string|UnitEnum|null $tag = null,
108+
public array $parameters = [],
101109
) {}
110+
111+
/**
112+
* Creates a MySQL configuration from a connection string, such as `mysql://user:password@host:3306/database?charset=utf8mb4`. Components missing from the connection string fall back to their defaults, and query parameters are appended to the DSN. A Unix socket may be given as a percent-encoded host or as the `unix_socket` query parameter.
113+
*
114+
* @param string $connectionString The connection string. Supported schemes are `mysql` and `mariadb`.
115+
* @param mixed ...$options Named constructor arguments, which take precedence over the values parsed from the connection string.
116+
*/
117+
public static function fromConnectionString(#[SensitiveParameter] string $connectionString, mixed ...$options): self
118+
{
119+
$parsed = DatabaseConnectionString::from($connectionString);
120+
121+
if (! in_array($parsed->scheme, ['mysql', 'mariadb'], strict: true)) {
122+
throw DatabaseConnectionStringWasInvalid::schemeWasNotSupported($parsed->scheme, ['mysql', 'mariadb']);
123+
}
124+
125+
$host = $parsed->host;
126+
$parameters = $parsed->parameters;
127+
128+
if ($host !== null && str_starts_with($host, '/')) {
129+
$parameters['unix_socket'] ??= $host;
130+
$host = null;
131+
}
132+
133+
if ($host === null && ! isset($parameters['unix_socket'])) {
134+
throw DatabaseConnectionStringWasInvalid::hostWasMissing();
135+
}
136+
137+
$arguments = array_filter(
138+
[
139+
'host' => $host,
140+
'port' => $parsed->port !== null ? (string) $parsed->port : null,
141+
'username' => $parsed->username,
142+
'password' => $parsed->password,
143+
'database' => $parsed->database,
144+
'parameters' => $parameters,
145+
],
146+
fn (mixed $value) => $value !== null,
147+
);
148+
149+
return new self(...[...$arguments, ...$options]);
150+
}
102151
}

‎packages/database/src/Config/PostgresConfig.php‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PDO;
88
use SensitiveParameter;
9+
use Tempest\Database\Exceptions\DatabaseConnectionStringWasInvalid;
910
use Tempest\Database\Migrations\DatePrefixStrategy;
1011
use Tempest\Database\Migrations\MigrationNamingStrategy;
1112
use Tempest\Database\Tables\NamingStrategy;
@@ -16,12 +17,17 @@ final class PostgresConfig implements DatabaseConfig
1617
{
1718
public string $dsn {
1819
get => sprintf(
19-
'pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s',
20+
'pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s%s',
2021
$this->host,
2122
$this->port,
2223
$this->database,
2324
$this->username,
2425
$this->password,
26+
implode('', array_map(
27+
fn (string $key, string $value) => ";{$key}={$value}",
28+
array_keys($this->parameters),
29+
$this->parameters,
30+
)),
2531
);
2632
}
2733

@@ -50,7 +56,7 @@ final class PostgresConfig implements DatabaseConfig
5056
}
5157

5258
/**
53-
* @param string $host The PostgreSQL server hostname or IP address.
59+
* @param string $host The PostgreSQL server hostname or IP address, or the directory containing its Unix socket.
5460
* @param string $port The PostgreSQL server port number.
5561
* @param string $username The PostgreSQL username for authentication.
5662
* @param string $password The PostgreSQL password for authentication.
@@ -59,6 +65,7 @@ final class PostgresConfig implements DatabaseConfig
5965
* @param NamingStrategy $namingStrategy The naming strategy for database tables and columns.
6066
* @param MigrationNamingStrategy $migrationNaming The naming strategy for migration file prefixes.
6167
* @param string|UnitEnum|null $tag An optional tag to identify this database configuration.
68+
* @param array<string,string> $parameters Additional parameters appended to the DSN, such as `sslmode`, `connect_timeout` or `keepalives`.
6269
*/
6370
public function __construct(
6471
#[SensitiveParameter]
@@ -75,5 +82,41 @@ public function __construct(
7582
public NamingStrategy $namingStrategy = new PluralizedSnakeCaseStrategy(),
7683
public MigrationNamingStrategy $migrationNaming = new DatePrefixStrategy(),
7784
public string|UnitEnum|null $tag = null,
85+
public array $parameters = [],
7886
) {}
87+
88+
/**
89+
* Creates a PostgreSQL configuration from a connection string, such as `postgres://user:password@host:5432/database?sslmode=require`. Components missing from the connection string fall back to their defaults, and query parameters are appended to the DSN. As with libpq, the `host`, `port`, `user`, `password` and `dbname` query parameters take precedence over the other components, so a Unix socket may be given as `postgres:///database?host=/var/run/postgresql` or as a percent-encoded host.
90+
*
91+
* @param string $connectionString The connection string. Supported schemes are `postgres`, `postgresql` and `pgsql`.
92+
* @param mixed ...$options Named constructor arguments, which take precedence over the values parsed from the connection string.
93+
*/
94+
public static function fromConnectionString(#[SensitiveParameter] string $connectionString, mixed ...$options): self
95+
{
96+
$parsed = DatabaseConnectionString::from($connectionString);
97+
98+
if (! in_array($parsed->scheme, ['postgres', 'postgresql', 'pgsql'], strict: true)) {
99+
throw DatabaseConnectionStringWasInvalid::schemeWasNotSupported($parsed->scheme, ['postgres', 'postgresql', 'pgsql']);
100+
}
101+
102+
$parameters = $parsed->parameters;
103+
104+
$arguments = [
105+
'host' => $parameters['host'] ?? $parsed->host,
106+
'port' => $parameters['port'] ?? ($parsed->port !== null ? (string) $parsed->port : null),
107+
'username' => $parameters['user'] ?? $parsed->username,
108+
'password' => $parameters['password'] ?? $parsed->password,
109+
'database' => $parameters['dbname'] ?? $parsed->database,
110+
'parameters' => array_diff_key($parameters, array_flip(['host', 'port', 'user', 'password', 'dbname'])),
111+
];
112+
113+
if ($arguments['host'] === null) {
114+
throw DatabaseConnectionStringWasInvalid::hostWasMissing();
115+
}
116+
117+
return new self(...[
118+
...array_filter($arguments, fn (mixed $value) => $value !== null),
119+
...$options,
120+
]);
121+
}
79122
}

‎packages/database/src/Config/SQLiteConfig.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PDO;
88
use SensitiveParameter;
9+
use Tempest\Database\Exceptions\DatabaseConnectionStringWasInvalid;
910
use Tempest\Database\Migrations\DatePrefixStrategy;
1011
use Tempest\Database\Migrations\MigrationNamingStrategy;
1112
use Tempest\Database\Tables\NamingStrategy;
@@ -68,4 +69,28 @@ public function __construct(
6869
public MigrationNamingStrategy $migrationNaming = new DatePrefixStrategy(),
6970
public string|UnitEnum|null $tag = null,
7071
) {}
72+
73+
/**
74+
* Creates a SQLite configuration from a connection string, such as `sqlite:///path/to/database.sqlite` or `sqlite::memory:`.
75+
*
76+
* @param string $connectionString The connection string, using the `sqlite` scheme.
77+
* @param mixed ...$options Named constructor arguments, which take precedence over the values parsed from the connection string.
78+
*/
79+
public static function fromConnectionString(#[SensitiveParameter] string $connectionString, mixed ...$options): self
80+
{
81+
$parsed = DatabaseConnectionString::from($connectionString);
82+
83+
if ($parsed->scheme !== 'sqlite') {
84+
throw DatabaseConnectionStringWasInvalid::schemeWasNotSupported($parsed->scheme, ['sqlite']);
85+
}
86+
87+
if ($parsed->path === null) {
88+
throw DatabaseConnectionStringWasInvalid::couldNotBeParsed();
89+
}
90+
91+
return new self(...[
92+
'path' => $parsed->path,
93+
...$options,
94+
]);
95+
}
7196
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Database\Exceptions;
6+
7+
use Exception;
8+
9+
final class DatabaseConnectionStringWasInvalid extends Exception implements DatabaseException
10+
{
11+
public static function couldNotBeParsed(): self
12+
{
13+
return new self('The database connection string could not be parsed. Make sure it is a valid URI with a scheme, e.g. `mysql://user:password@host:3306/database`.');
14+
}
15+
16+
public static function hostWasMissing(): self
17+
{
18+
return new self('The database connection string must contain a host, or a Unix socket in its query parameters.');
19+
}
20+
21+
public static function schemeWasNotSupported(string $scheme, array $supported): self
22+
{
23+
return new self(sprintf(
24+
'The database connection string scheme `%s` is not supported by this configuration. Supported schemes are: `%s`.',
25+
$scheme,
26+
implode('`, `', $supported),
27+
));
28+
}
29+
}

0 commit comments

Comments
 (0)