| | | 1 | | using System.Collections.Specialized; |
| | | 2 | | using System.Web; |
| | | 3 | | using Npgsql; |
| | | 4 | | |
| | | 5 | | namespace ClutterStock.Infrastructure; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Converts a PostgreSQL URI (<c>postgres[ql]://[user[:password]@]host[:port][/database][?options]</c>) |
| | | 9 | | /// to an ADO.NET connection string accepted by Npgsql. Falls back to the input value when it is |
| | | 10 | | /// already in native key=value form. |
| | | 11 | | /// </summary> |
| | | 12 | | public static class PostgresUrlParser |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Parses <paramref name="value" /> into an Npgsql ADO.NET connection string. |
| | | 16 | | /// </summary> |
| | | 17 | | public static string Parse(string value) |
| | | 18 | | { |
| | 3 | 19 | | if (!value.StartsWith("postgres://", StringComparison.OrdinalIgnoreCase) && |
| | 3 | 20 | | !value.StartsWith("postgresql://", StringComparison.OrdinalIgnoreCase)) |
| | 3 | 21 | | return value; |
| | | 22 | | |
| | 0 | 23 | | var uri = new Uri(value); |
| | 0 | 24 | | var builder = new NpgsqlConnectionStringBuilder |
| | 0 | 25 | | { |
| | 0 | 26 | | Host = uri.Host, |
| | 0 | 27 | | Port = uri.IsDefaultPort ? 5432 : uri.Port, |
| | 0 | 28 | | }; |
| | | 29 | | |
| | 0 | 30 | | var database = uri.AbsolutePath.TrimStart('/'); |
| | 0 | 31 | | if (!string.IsNullOrEmpty(database)) |
| | 0 | 32 | | builder.Database = Uri.UnescapeDataString(database); |
| | | 33 | | |
| | 0 | 34 | | if (!string.IsNullOrEmpty(uri.UserInfo)) |
| | | 35 | | { |
| | 0 | 36 | | var colon = uri.UserInfo.IndexOf(':'); |
| | 0 | 37 | | if (colon >= 0) |
| | | 38 | | { |
| | 0 | 39 | | builder.Username = Uri.UnescapeDataString(uri.UserInfo[..colon]); |
| | 0 | 40 | | builder.Password = Uri.UnescapeDataString(uri.UserInfo[(colon + 1)..]); |
| | | 41 | | } |
| | | 42 | | else |
| | | 43 | | { |
| | 0 | 44 | | builder.Username = Uri.UnescapeDataString(uri.UserInfo); |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | |
| | 0 | 48 | | if (!string.IsNullOrEmpty(uri.Query)) |
| | | 49 | | { |
| | 0 | 50 | | NameValueCollection query = HttpUtility.ParseQueryString(uri.Query); |
| | 0 | 51 | | foreach (var key in query.AllKeys) |
| | | 52 | | { |
| | 0 | 53 | | if (string.IsNullOrEmpty(key)) continue; |
| | 0 | 54 | | var v = query[key]; |
| | 0 | 55 | | if (v is not null) builder[key] = v; |
| | | 56 | | } |
| | | 57 | | } |
| | | 58 | | |
| | 0 | 59 | | return builder.ConnectionString; |
| | | 60 | | } |
| | | 61 | | } |