From 0c04fc1d1e95645ca927b91d5c88211ccc602ab8 Mon Sep 17 00:00:00 2001
From: Jack Wink <57678801+mothershipper@users.noreply.github.com>
Date: Wed, 12 Apr 2023 12:59:01 -0700
Subject: [PATCH] Supports alternate postgres:// prefix in URLs

Adds support for the alternate postgres:// prefix in URLs. It's maybe
not the cleanest approach, but works.  Hoping I can either get some
pointers on a more appropriate patch, or that we could use this in the
interim to unblock this use-case.

Signed-off-by: Jack Wink <57678801+mothershipper@users.noreply.github.com>
---
 cmd/postgres_exporter/datasource.go |  2 +-
 config/dsn.go                       |  2 +-
 config/dsn_test.go                  | 13 +++++++++++++
 3 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/cmd/postgres_exporter/datasource.go b/cmd/postgres_exporter/datasource.go
index feaae6b6..0b8cef04 100644
--- a/cmd/postgres_exporter/datasource.go
+++ b/cmd/postgres_exporter/datasource.go
@@ -35,7 +35,7 @@ func (e *Exporter) discoverDatabaseDSNs() []string {
 		var dsnURI *url.URL
 		var dsnConnstring string
 
-		if strings.HasPrefix(dsn, "postgresql://") {
+		if strings.HasPrefix(dsn, "postgresql://") || strings.HasPrefix(dsn, "postgres://") {
 			var err error
 			dsnURI, err = url.Parse(dsn)
 			if err != nil {
diff --git a/config/dsn.go b/config/dsn.go
index 78d798d5..168d00d6 100644
--- a/config/dsn.go
+++ b/config/dsn.go
@@ -65,7 +65,7 @@ func (d DSN) GetConnectionString() string {
 // dsnFromString parses a connection string into a dsn. It will attempt to parse the string as
 // a URL and as a set of key=value pairs. If both attempts fail, dsnFromString will return an error.
 func dsnFromString(in string) (DSN, error) {
-	if strings.HasPrefix(in, "postgresql://") {
+	if strings.HasPrefix(in, "postgresql://") || strings.HasPrefix(in, "postgres://") {
 		return dsnFromURL(in)
 	}
 
diff --git a/config/dsn_test.go b/config/dsn_test.go
index 637a3568..68340cd0 100644
--- a/config/dsn_test.go
+++ b/config/dsn_test.go
@@ -186,6 +186,19 @@ func Test_dsnFromString(t *testing.T) {
 			},
 			wantErr: false,
 		},
+		{
+			name:  "Alternative URL prefix",
+			input: "postgres://user:s3cret@host.example.com:5432/tsdb?user=postgres",
+			want: DSN{
+				scheme:   "postgres",
+				host:     "host.example.com:5432",
+				path:     "/tsdb",
+				query:    url.Values{},
+				username: "user",
+				password: "s3cret",
+			},
+			wantErr: false,
+		},
 		{
 			name:  "URL with user and password in query string",
 			input: "postgresql://host.example.com:5432/tsdb?user=postgres&password=s3cr3t",