-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathDsnParser.php
More file actions
232 lines (205 loc) · 8.73 KB
/
DsnParser.php
File metadata and controls
232 lines (205 loc) · 8.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<?php namespace DBDiff\Migration\Config;
/**
* DsnParser — parse a database connection URL into its component parts.
*
* Supported URL schemes:
* mysql://user:pass@host:3306/dbname
* pgsql://user:pass@host:5432/dbname
* postgres://user:pass@host:5432/dbname (alias for pgsql)
* postgresql://user:pass@host:5432/dbname (alias for pgsql)
* sqlite:///absolute/path/to/db.sqlite
* sqlite://./relative/path/to/db.sqlite
*
* Query-string parameters are parsed for extras:
* ?sslmode=require
* ?pgbouncer=true (Supabase session-mode pooler)
*
* Supabase URL formats supported:
* Direct connection : postgres://postgres.PROJREF:[email protected]:5432/postgres
* Session pooler : postgres://postgres.PROJREF:[email protected]:6543/postgres
* Legacy direct : postgres://postgres:[email protected]:5432/postgres
*
* Returns an associative array with keys:
* driver, host, port, name (db), path (SQLite only), user, password, sslmode, pgbouncer
*/
class DsnParser
{
private static array $schemeMap = [
'mysql' => 'mysql',
'pgsql' => 'pgsql',
'postgres' => 'pgsql',
'postgresql' => 'pgsql',
'sqlite' => 'sqlite',
];
/**
* Parse a database URL into a flat configuration array.
*
* @param string $url Full connection URL.
* @return array{driver:string, host:string, port:int, name:string, path:string, user:string, password:string, sslmode:string, pgbouncer:bool}
* @throws \InvalidArgumentException on unsupported scheme or malformed URL.
*/
public static function parse(string $url): array
{
// Illuminate accepts DATABASE_URL env vars with the full URL form;
// strip a leading "env(" wrapper if someone passes the literal config value.
$url = trim($url);
// Proactively normalise credentials before parse_url() sees the URL.
// This encode → decode round-trip handles raw passwords that contain
// '@', '#', '?', '/', and other URL-special characters without the user
// having to pre-encode them. See DsnPasswordEncoder for details and
// the known limitation around literal '%' + two hex digits.
$url = DsnPasswordEncoder::normalizeUrl($url);
// ── SQLite early-exit ─────────────────────────────────────────────────
// PHP's parse_url() returns false for sqlite:///absolute/path because
// the empty authority (the third slash) is treated as a malformed URL.
// Handle SQLite ourselves to avoid that bug entirely.
if (preg_match('/^sqlite:(\/\/)?(.*)$/i', $url, $m)) {
return [
'driver' => 'sqlite',
'host' => '',
'port' => 0,
'name' => '',
'path' => self::resolveSqlitePath($m[2]),
'user' => '',
'password' => '',
'sslmode' => '',
'pgbouncer' => false,
];
}
$parsed = parse_url($url);
// If parse_url fails (commonly because credentials contain unencoded
// characters such as '@'), attempt a best-effort fix by percent-encoding
// the userinfo (user:pass) portion and re-parse.
if ($parsed === false || empty($parsed['scheme'])) {
$parsed = self::retryWithEncodedUserinfo($url);
}
if ($parsed === false || empty($parsed['scheme'])) {
throw new \InvalidArgumentException("Cannot parse database URL: {$url}");
}
$scheme = strtolower($parsed['scheme']);
if (!isset(self::$schemeMap[$scheme])) {
throw new \InvalidArgumentException(
"Unsupported scheme '{$scheme}'. Supported: " . implode(', ', array_keys(self::$schemeMap))
);
}
$driver = self::$schemeMap[$scheme];
// ── MySQL / Postgres ──────────────────────────────────────────────────
$host = $parsed['host'] ?? 'localhost';
$user = isset($parsed['user']) ? rawurldecode($parsed['user']) : '';
$password = isset($parsed['pass']) ? rawurldecode($parsed['pass']) : '';
$dbName = ltrim($parsed['path'] ?? '', '/');
// Default ports
$defaultPort = $driver === 'mysql' ? 3306 : 5432;
$port = isset($parsed['port']) ? (int) $parsed['port'] : $defaultPort;
// Query-string extras (?sslmode=require&pgbouncer=true)
$query = [];
if (!empty($parsed['query'])) {
parse_str($parsed['query'], $query);
}
$sslMode = $query['sslmode'] ?? '';
$pgbouncer = filter_var($query['pgbouncer'] ?? false, FILTER_VALIDATE_BOOLEAN);
// Supabase heuristics — apply sensible defaults when we detect a Supabase host
self::applySupabaseHeuristics($host, $port, $sslMode, $pgbouncer);
return [
'driver' => $driver,
'host' => $host,
'port' => $port,
'name' => $dbName,
'path' => '',
'user' => $user,
'password' => $password,
'sslmode' => $sslMode,
'pgbouncer' => $pgbouncer,
];
}
/**
* Resolve the file path from the path component of a sqlite:// URL.
*
* sqlite:///abs/path → /abs/path (absolute — starts with /)
* sqlite://./rel/path → ./rel/path (relative — starts with .)
* sqlite://rel/path → /rel/path (treat as absolute for consistency)
*/
private static function resolveSqlitePath(string $rawPath): string
{
if (str_starts_with($rawPath, '/') || str_starts_with($rawPath, '.')) {
return $rawPath;
}
return '/' . $rawPath;
}
/**
* Attempt to fix a URL that parse_url() couldn't handle by
* percent-encoding the userinfo portion (user:pass).
*
* @return array|false The parsed URL components, or false on failure.
*/
private static function retryWithEncodedUserinfo(string $url): array|false
{
if (!preg_match('#^([a-z0-9+.-]+)://([^@/]+)@([^/]+)(/.*)?$#i', $url, $m)) {
return false;
}
$scheme = $m[1];
$hostpart = $m[3];
$rest = $m[4] ?? '';
$userpass = explode(':', $m[2], 2);
$user = rawurlencode($userpass[0]);
$pass = isset($userpass[1]) ? rawurlencode($userpass[1]) : '';
$encodedUserinfo = $user . ($pass !== '' ? ":$pass" : '');
return parse_url("$scheme://$encodedUserinfo@$hostpart$rest");
}
/**
* Apply Supabase-specific connection defaults when a Supabase host is
* detected. Mutates $sslMode and $pgbouncer in place.
*
* - Forces sslmode=require when not already set.
* - Enables pgbouncer mode when the pooler port (6543) is used.
*/
private static function applySupabaseHeuristics(
string $host,
int $port,
string &$sslMode,
bool &$pgbouncer
): void {
if (!self::isSupabaseHost($host)) {
return;
}
if (empty($sslMode)) {
$sslMode = 'require';
}
// Port 6543 is the session-mode connection pooler (pgbouncer)
if ($port === 6543) {
$pgbouncer = true;
}
}
/**
* Detect whether a host looks like a Supabase-managed endpoint.
* Covers both the legacy `db.PROJ.supabase.co` and the newer
* `aws-0-REGION.pooler.supabase.com` formats.
*/
public static function isSupabaseHost(string $host): bool
{
return str_contains($host, '.supabase.co')
|| str_contains($host, '.supabase.com');
}
/**
* Convert a DsnParser result array into a CLIGetter-style server array
* (keys: user, password, host, port) and a database name.
*
* Useful for bridging DsnParser output into the existing diff pipeline.
*
* @return array{server: array, db: string, driver: string, sslmode: string}
*/
public static function toServerAndDb(array $parsed): array
{
return [
'driver' => $parsed['driver'],
'sslmode' => $parsed['sslmode'],
'db' => $parsed['driver'] === 'sqlite' ? $parsed['path'] : $parsed['name'],
'server' => [
'user' => $parsed['user'],
'password' => $parsed['password'],
'host' => $parsed['host'],
'port' => (string) $parsed['port'],
],
];
}
}